@@ -196,6 +196,7 @@ static bool fileGetFromVar(JsFile *file, JsVar *parent) {
196196 if (fHandle && jsvIsFlatString (fHandle )) {
197197 file -> data = (JsFileData * )jsvGetFlatStringPointer (fHandle );
198198 file -> fileVar = parent ;
199+ file -> dataVar = fHandle ;
199200 if (file -> data -> state == FS_OPEN ) {// return false if the file has been closed.
200201 ret = true;
201202 }
@@ -254,22 +255,22 @@ void jswrap_E_unmountSD() {
254255 jswrap_file_kill ();
255256}
256257
257- static bool allocateJsFile (JsFile * file ,FileMode mode , FileType type ) {
258+ static bool allocateJsFile (JsFile * file , FileMode mode , FileType type ) {
258259 JsVar * parent = jspNewObject (0 , "File" );
259260 if (!parent ) return false; // low memory
260261
261- JsVar * data = jsvNewFlatStringOfLength (sizeof (JsFileData ));
262- if (!data ) { // out of memory for flat string
262+ file -> dataVar = jsvNewFlatStringOfLength (sizeof (JsFileData ));
263+ if (!file -> dataVar ) { // out of memory for flat string
263264 jsvDefragment (); // defrag and try again in case it was a memory fragmentation issue
264- data = jsvNewFlatStringOfLength (sizeof (JsFileData ));
265+ file -> dataVar = jsvNewFlatStringOfLength (sizeof (JsFileData ));
265266 }
266- if (!data ) { // out of memory for flat string
267+ if (!file -> dataVar ) { // out of memory for flat string
267268 jsErrorFlags |= JSERR_LOW_MEMORY ; // flag this up as an issue
268269 jsvUnLock (parent );
269270 return false;
270271 }
271- file -> data = (JsFileData * )jsvGetFlatStringPointer (data );
272- jsvObjectSetChildAndUnLock (parent , JS_FS_DATA_NAME , data );
272+ file -> data = (JsFileData * )jsvGetFlatStringPointer (file -> dataVar );
273+ jsvObjectSetChild (parent , JS_FS_DATA_NAME , file -> dataVar ); // intentionally leave dataVar locked so it can't be moved by defrag
273274 file -> fileVar = parent ;
274275 assert (file -> data );
275276 file -> data -> mode = mode ;
@@ -359,8 +360,9 @@ JsVar *jswrap_E_openFile(JsVar* path, JsVar* mode) {
359360 jsvArrayPush (arr , file .fileVar );
360361 } else {
361362 // File open failed
362- jsvUnLock (file .fileVar );
363+ jsvUnLock2 (file .fileVar , file . dataVar );
363364 file .fileVar = 0 ;
365+ file .dataVar = 0 ;
364366 }
365367
366368 if (res != FR_OK )
@@ -402,8 +404,10 @@ void jswrap_file_close(JsVar* parent) {
402404 JsVar * arr = fsGetArray (false);
403405 if (arr ) {
404406 JsVar * idx = jsvGetIndexOf (arr , file .fileVar , true);
405- if (idx )
407+ if (idx ) {
408+ jsvUnLock (file .dataVar );
406409 jsvRemoveChildAndUnLock (arr , idx );
410+ }
407411 jsvUnLock (arr );
408412 }
409413 }
0 commit comments