mjSpec: deleting or renaming a default leaves a stale def_map entry (use-after-free in mjs_getDefault / mjs_addGeom / mj_saveXMLString)
Intro
Hi!
I build and edit models through the mjSpec C API, and I ran into this while deleting and renaming default classes.
My setup
- MuJoCo
mainat d10ff84 (3.14.1), built from source in Release mode - C API. The Python
MjSpec.delete(default)binding calls the samemjs_delete, but I have only run the C repro. - macOS 26 (Darwin 25.5), Apple M4 (arm64), Apple clang
What's happening? What did you expect?
mjCModel::def_map (class name -> mjCDef*) gets out of sync with defaults_ in two cases.
- Deleting a default.
mjs_delete(spec, def->element)callsmjCModel::operator-=(const mjCDef&)insrc/user/user_model.cc. That function callsRelease()on the removed defaults, which frees them, and erases them fromdefaults_, but it never erases them fromdef_map. Everything that readsdef_mapthen gets a dangling pointer:mjs_getDefault(elem)returns the freed default, whilemjs_findDefault(spec, "cls")returns NULL.mjs_addGeom(body, NULL)on a body whose childclass was the deleted default copies the new geom's values from freed memory (mjCBody::AddGeom->model->def_map[classname]). The same applies to AddJoint, AddSite, AddCamera and AddLight.mj_saveXMLStringlooks upmodel->def_map[...]inxml_native_writer.ccand reads the freed default.
- Renaming a default. The
mjOBJ_DEFAULTbranch ofmjs_setName(src/user/user_api.cc) assignsdef->namewithout rekeyingdef_map. After that:mjs_getDefaulton an element that uses the new name returns NULL.mj_saveXMLStringcrashes. The writer usesdef_map[...](operator[]), which inserts anullptrfor the unknown name, andmjXWriter::OneGeomthen dereferences it (EXC_BAD_ACCESSat0x888). This happens in a plain Release build, with no guard malloc.
Expected behaviour: once a default has been deleted, which is a supported operation (MujocoTest.DetachDefault, specs_test.py test_delete_default), no API should return or read the freed mjCDef. Once a default has been renamed through mjs_setName, which handles defaults as a special case, lookups by the new name should succeed. The API is also inconsistent with itself: after the delete, mjs_findDefault returns NULL but mjs_getDefault still returns the old pointer.
specs_test.py (test_delete_default, around line 718) deletes def1 while geom1 still uses it, but it only checks find_default. That is why the dangling entry goes unnoticed there.
Steps for reproduction
- Build the program below against
libmujoco. - Run
./repro 0(delete) and./repro 1(rename). Run each once normally and once withDYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib(on Linux, use an ASan build).
Results on d10ff84:
| case | plain Release | guard malloc |
|---|---|---|
repro 0 (delete) |
getDefault(geom) equals the deleted pointer; geom2 size[0] = 0.3 (copied from the deleted default; the global default is 0); then SIGSEGV in mj_saveXMLString (WriteAttr<double> <- mjXWriter::OneGeom <- mjXWriter::Body) |
SIGSEGV in mjs_addGeom (memmove <- mjCGeom::mjCGeom <- mjCBody::AddGeom), reading a freed page |
repro 1 (rename) |
findDefault(renamed) is non-null; getDefault(geom) = 0x0; then SIGSEGV at 0x888 in WriteAttr<double> <- mjXWriter::OneGeom <- mj_saveXMLString |
same SIGSEGV |
Minimal model for reproduction
No XML is needed. The model is built with mjSpec in the code below.
Code required for reproduction
#include <cstdio>
#include <mujoco/mujoco.h>
// usage: repro 0 (delete a default) | repro 1 (rename a default)
int main(int argc, char** argv) {
int mode = argc > 1 ? argv[1][0] - '0' : 0;
mjSpec* spec = mj_makeSpec();
mjsDefault* def = mjs_addDefault(spec, "cls", mjs_getSpecDefault(spec));
def->geom->size[0] = 0.3;
mjsBody* world = mjs_findBody(spec, "world");
mjsGeom* geom = mjs_addGeom(world, def);
geom->size[0] = 0.1;
if (mode == 0) {
mjsBody* body = mjs_addBody(world, nullptr);
mjs_setDefault(body->element, def); // childclass="cls"
mjs_delete(spec, def->element);
printf("findDefault(cls) = %p\n", (void*)mjs_findDefault(spec, "cls"));
printf("getDefault(geom) = %p (deleted default was %p)\n",
(void*)mjs_getDefault(geom->element), (void*)def);
mjsGeom* geom2 = mjs_addGeom(body, nullptr); // copies from the deleted default
printf("geom2 size[0] = %g (global default is %g)\n", geom2->size[0],
mjs_getSpecDefault(spec)->geom->size[0]);
geom2->size[0] = 0.2;
} else {
mjs_setName(def->element, "renamed");
printf("findDefault(renamed) = %p\n", (void*)mjs_findDefault(spec, "renamed"));
mjs_setDefault(geom->element, def); // classname = "renamed"
printf("getDefault(geom) = %p\n", (void*)mjs_getDefault(geom->element));
}
fflush(stdout);
mjModel* m = mj_compile(spec, nullptr);
printf("compile: %s\n", m ? "ok" : mjs_getError(spec));
fflush(stdout);
char xml[4096], err[1024];
int r = mj_saveXMLString(spec, xml, sizeof(xml), err, sizeof(err));
printf("save: %d\n", r);
mj_deleteModel(m);
mj_deleteSpec(spec);
return 0;
}Suggested fix
I have a small local patch with gtests and can open a PR if that is useful.
mjCModel::operator-=(const mjCDef&): for each removed default, erase itsdef_mapentry, if the entry still points to that default, before callingRelease().mjs_setNameon a default: return an error if another default already uses the new name, asAddDefaultdoes; otherwise erase the old key and insert the new one.mjs_getDefault: treat anullptrvalue as not found.def_map[...]inmjCBody::Add*can insert one.xml_native_writer.cc: replace the 11model->def_map[name]lookups with afindthat falls back to the global default, so a missing class can no longer produce a nullmjCDef*.
With these changes both cases above run cleanly, including under guard malloc. The existing user_api_test, user_model_test, user_objects_test, xml_native_reader_test and xml_native_writer_test also pass.
One question the patch does not answer: elements that still name a deleted default keep that classname. The saved XML therefore contains <geom class="cls" .../> with no matching <default class="cls">, and reloading it fails with unknown default class name 'cls'. Should mjs_delete on a default reset those elements to the parent class (or to main), or should it refuse to delete a default that is still in use?
Confirmations
- I searched the latest documentation thoroughly before posting.
- I searched previous Issues and Discussions, I am certain this has not been raised before. (#1798 and #1799 fixed
def_mapnot being copied in the copy constructor, which is a different defect. #3612 is aboutmjs_setDefaultcopying values.)
AI assistance: drafted with an AI coding assistant (Claude). The reproduction above was run locally against the current default branch.
Source: google-deepmind/mujoco