VFS relies on mjVFS not being moved, resulting in segmentation faults
Intro
Hi!
I am a researcher at University of Ljubljana, I use MuJoCo for my various things.
My setup
MuJoCo 3.5.0, C API, x86_64, Fedora Linux 43, clang version 21.1.8 (optimizations disabled).
What's happening? What did you expect?
When initializing the mjVFS struct (with mj_defaultVFS) on a different memory location than the location at which mj_loadXML is called, the program crashes (segmentation fault).
This is because the new implementation relies on mjVFS not being moved to a different memory location. This did not happen on 3.3.7, from which I'm migrating, because then it did not store and use a pointer to the C mjVFS struct in its C++ impl_ attribute (i.e., the vfs variable in below permalink renders).
3.3.7: https://github.com/google-deepmind/mujoco/blob/f1d45bd5422c74beddfb0d1deb590a02583d21de/src/user/user_vfs.cc#L214
3.5.0: https://github.com/google-deepmind/mujoco/blob/881544c0c58dc2e95fbd132a5ec90b99e012b6f7/src/user/user_vfs.cc#L337
I solved this by allocating mjVFS on the heap instead of the stack.
If this implementation intentionally breaks moves of mjVFS, it would beneficial to document this.
Steps for reproduction
- Run the code below, with the given model saved in a file (
model.xml).
Minimal model for reproduction
If you encountered the issue in a complex model, please simplify it as much as possible (while still reproducing the issue).
minimal XML
<mujoco>
<worldbody>
<light pos="0 0 1"/>
<geom type="sphere" size="1" rgba="1 0 0 1"/>
</worldbody>
</mujoco>
Code required for reproduction
The following example demonstrates the use in C. I am however using this in Rust, hence I wrapped mjVFS into a fake wrapper to simulate my exact (wrapped) usage.
To reproduce results, compile with clang-21 vfs_bug.c -o vfs_bug -L mujoco-3.5.0/lib/ -lmujoco -I mujoco-3.5.0/include/. Make sure OPTIMIZATIONS are DISABLED, otherwise they hide the bug by optimizing everything out.
#include "mujoco/mujoco.h"
#include <stdio.h>
typedef struct {
mjVFS inner;
}WrapperVfs;
WrapperVfs initialize() {
WrapperVfs wrapper;
mj_defaultVFS(&wrapper.inner);
return wrapper;
}
int main() {
WrapperVfs wrapper_vfs = initialize();
if (mj_addFileVFS(&wrapper_vfs.inner, NULL, "model.xml") != 0) {
printf("Exiting: failed to load\n");
return 1;
}
char error[100] = {};
mjModel* model = mj_loadXML("model.xml", &wrapper_vfs.inner, error, sizeof(error) / sizeof(error[0]));
printf("Exiting ok\n");
mj_deleteVFS(&wrapper_vfs.inner);
if (model) {
mj_deleteModel(model);
}
return 0;
}
Confirmations
- [x] I searched the latest documentation thoroughly before posting.
- [x] I searched previous Issues and Discussions, I am certain this has not been raised before.
@haroonq can you take a look?
Thanks for the report. This was indeed an oversight on my end. I believe https://github.com/google-deepmind/mujoco/pull/3105 should fix this issue.