/
jsvar.c
4377 lines (4055 loc) · 149 KB
/
jsvar.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Variables
* ----------------------------------------------------------------------------
*/
#include "jsvar.h"
#include "jslex.h"
#include "jsparse.h"
#include "jswrap_json.h"
#include "jsinteractive.h"
#include "jswrapper.h"
#include "jswrap_math.h" // for jswrap_math_mod
#include "jswrap_object.h" // for jswrap_object_toString
#include "jswrap_arraybuffer.h" // for jsvNewTypedArray
#include "jswrap_dataview.h" // for jsvNewDataViewWithData
#if defined(ESPR_JIT) && defined(LINUX)
#include <sys/mman.h>
#endif
#ifdef DEBUG
/** When freeing, clear the references (nextChild/etc) in the JsVar.
* This means we can assert at the end of jsvFreePtr to make sure
* everything really is free. */
#define CLEAR_MEMORY_ON_FREE
#endif
/** Basically, JsVars are stored in one big array, so save the need for
* lots of memory allocation. On Linux, the arrays are in blocks, so that
* more blocks can be allocated. We can't use realloc on one big block as
* this may change the address of vars that are already locked!
*
*/
#ifdef RESIZABLE_JSVARS
JsVar **jsVarBlocks = 0;
unsigned int jsVarsSize = 0;
#define JSVAR_BLOCK_SIZE 4096
#define JSVAR_BLOCK_SHIFT 12
#else
#ifdef JSVAR_MALLOC
unsigned int jsVarsSize = 0;
JsVar *jsVars = NULL;
#else
JsVar jsVars[JSVAR_CACHE_SIZE] __attribute__((aligned(4)));
const unsigned int jsVarsSize = JSVAR_CACHE_SIZE;
#endif
#endif
typedef enum {
MEM_NOT_BUSY,
MEMBUSY_SYSTEM,
MEMBUSY_GC
} PACKED_FLAGS MemBusyType;
volatile bool touchedFreeList = false;
volatile JsVarRef jsVarFirstEmpty; ///< reference of first unused variable (variables are in a linked list)
volatile MemBusyType isMemoryBusy; ///< Are we doing garbage collection or similar, so can't access memory?
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
JsVarRef jsvGetFirstChild(const JsVar *v) { return v->varData.ref.firstChild; }
JsVarRefSigned jsvGetFirstChildSigned(const JsVar *v) {
if (v->varData.ref.firstChild > JSVARREF_MAX)
return ((JsVarRefSigned)v->varData.ref.firstChild) + JSVARREF_MIN*2;
return (JsVarRefSigned)v->varData.ref.firstChild;
}
JsVarRef jsvGetLastChild(const JsVar *v) { return v->varData.ref.lastChild; }
JsVarRef jsvGetNextSibling(const JsVar *v) { return v->varData.ref.nextSibling; }
JsVarRef jsvGetPrevSibling(const JsVar *v) { return v->varData.ref.prevSibling; }
void jsvSetFirstChild(JsVar *v, JsVarRef r) { v->varData.ref.firstChild = r; }
void jsvSetLastChild(JsVar *v, JsVarRef r) { v->varData.ref.lastChild = r; }
void jsvSetNextSibling(JsVar *v, JsVarRef r) { v->varData.ref.nextSibling = r; }
void jsvSetPrevSibling(JsVar *v, JsVarRef r) { v->varData.ref.prevSibling = r; }
JsVarRefCounter jsvGetRefs(JsVar *v) { return v->varData.ref.refs; }
void jsvSetRefs(JsVar *v, JsVarRefCounter refs) { v->varData.ref.refs = refs; }
unsigned char jsvGetLocks(JsVar *v) { return (unsigned char)((v->flags>>JSV_LOCK_SHIFT) & JSV_LOCK_MAX); }
// These defines take 'f' as 'v->flags&JSV_VARTYPEMASK
#define JSV_IS_ROOT(f) (f)==JSV_ROOT
#define JSV_IS_NULL(f) (f)==JSV_NULL
#define JSV_IS_BOOL(f) ((f)==JSV_BOOLEAN || (f)==JSV_NAME_INT_BOOL)
#ifndef ESPR_EMBED
#define JSV_IS_PIN(f) (f)==JSV_PIN
#else
#define JSV_IS_PIN(f) false
#endif
#define JSV_IS_INT(f) ((f)==JSV_INTEGER || JSV_IS_PIN(f) || (f)==JSV_NAME_INT || (f)==JSV_NAME_INT_INT || (f)==JSV_NAME_INT_BOOL)
#define JSV_IS_NUMERIC(f) ((f)>=_JSV_NUMERIC_START && (f)<=_JSV_NUMERIC_END)
#define JSV_IS_STRING(f) ((f)>=_JSV_STRING_START && (f)<=_JSV_STRING_END)
#define JSV_IS_STRING_EXT(f) ((f)>=JSV_STRING_EXT_0 && (f)<=JSV_STRING_EXT_MAX)
#define JSV_IS_FLAT_STRING(f) (f)==JSV_FLAT_STRING
#define JSV_IS_NATIVE_STRING(f) (f)==JSV_NATIVE_STRING
#define JSV_IS_ARRAY(f) (f)==JSV_ARRAY
#define JSV_IS_OBJECT(f) ((f)==JSV_OBJECT || (f)==JSV_ROOT)
#define JSV_IS_FUNCTION(f) ((f)==JSV_FUNCTION || (f)==JSV_FUNCTION_RETURN || (f)==JSV_NATIVE_FUNCTION)
#define JSV_IS_ARRAYBUFFER(f) (f)==JSV_ARRAYBUFFER
#define JSV_IS_NAME(f) ((f)>=_JSV_NAME_START && (f)<=_JSV_NAME_END)
#define JSV_IS_NAME_WITH_VALUE(f) ((f)>=_JSV_NAME_WITH_VALUE_START && (f)<=_JSV_NAME_WITH_VALUE_END)
#ifdef ESPR_NO_GET_SET
#define JSV_IS_GETTER_OR_SETTER(f) false
#else
#define JSV_IS_GETTER_OR_SETTER(f) (f)==JSV_GET_SET
#endif
#ifdef SPIFLASH_BASE
#define JSV_IS_FLASH_STRING(f) (f)==JSV_FLASH_STRING
#else
#define JSV_IS_FLASH_STRING(f) false
#endif
#define JSV_IS_NONAPPENDABLE_STRING(f) (JSV_IS_FLAT_STRING(f) || JSV_IS_NATIVE_STRING(f) || JSV_IS_FLASH_STRING(f))
bool jsvIsRoot(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_ROOT(f); }
bool jsvIsPin(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_PIN(f); }
bool jsvIsSimpleInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_INTEGER; } // is just a very basic integer value
bool jsvIsInt(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_INT(f); }
bool jsvIsFloat(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLOAT; }
bool jsvIsBoolean(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_BOOL(f); }
bool jsvIsString(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_STRING(f); } ///< String, or a NAME too
bool jsvIsBasicString(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return f>=JSV_STRING_0 && f<=JSV_STRING_MAX; } ///< Just a string (NOT a name/flatstr/nativestr or flashstr)
bool jsvIsStringExt(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_STRING_EXT(f); } ///< The extra bits dumped onto the end of a string to store more data
bool jsvIsFlatString(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_FLAT_STRING(f); }
bool jsvIsNativeString(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_NATIVE_STRING(f); }
bool jsvIsFlashString(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_FLASH_STRING(f); }
bool jsvIsConstant(const JsVar *v) { return v && (v->flags&JSV_CONSTANT)==JSV_CONSTANT; }
bool jsvIsNumeric(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return f>=_JSV_NUMERIC_START && f<=_JSV_NUMERIC_END; }
bool jsvIsFunction(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_FUNCTION(f); }
bool jsvIsFunctionReturn(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); } ///< Is this a function with an implicit 'return' at the start?
bool jsvIsFunctionParameter(const JsVar *v) { return v && (v->flags&JSV_NATIVE) && jsvIsString(v); }
bool jsvIsObject(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_OBJECT(f); }
bool jsvIsArray(const JsVar *v) { return v && JSV_IS_ARRAY(v->flags&JSV_VARTYPEMASK); }
bool jsvIsArrayBuffer(const JsVar *v) { return v && JSV_IS_ARRAYBUFFER(v->flags&JSV_VARTYPEMASK); }
bool jsvIsArrayBufferName(const JsVar *v) { return v && (v->flags&(JSV_VARTYPEMASK))==JSV_ARRAYBUFFERNAME; }
bool jsvIsNativeFunction(const JsVar *v) { return v && (v->flags&(JSV_VARTYPEMASK))==JSV_NATIVE_FUNCTION; }
bool jsvIsUndefined(const JsVar *v) { return v==0; }
bool jsvIsNull(const JsVar *v) { return v && JSV_IS_NULL(v->flags&JSV_VARTYPEMASK); }
bool jsvIsNullish(const JsVar *v) { return !v || JSV_IS_NULL(v->flags&JSV_VARTYPEMASK); } // jsvIsUndefined(v) || jsvIsNull(v);
bool jsvIsBasic(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_NUMERIC(f) || JSV_IS_STRING(f); } ///< Is this *not* an array/object/etc
bool jsvIsName(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_NAME(f); } ///< NAMEs are what's used to name a variable (it is not the data itself)
bool jsvIsBasicName(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return f>=JSV_NAME_STRING_0 && f<=JSV_NAME_STRING_MAX; } ///< Simple NAME that links to a variable via firstChild
/// Names with values have firstChild set to a value - AND NOT A REFERENCE
bool jsvIsNameWithValue(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_NAME_WITH_VALUE(f); }
bool jsvIsNameInt(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return f==JSV_NAME_INT_INT || (f>=JSV_NAME_STRING_INT_0 && f<=JSV_NAME_STRING_INT_MAX); } ///< Is this a NAME pointing to an Integer value
bool jsvIsNameIntInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT; }
bool jsvIsNameIntBool(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL; }
/// What happens when we access a variable that doesn't exist. We get a NAME where the next + previous siblings point to the object that may one day contain them
bool jsvIsNewChild(const JsVar *v) { return jsvIsName(v) && jsvGetNextSibling(v) && jsvGetNextSibling(v)==jsvGetPrevSibling(v); }
/// Returns true if v is a getter/setter
bool jsvIsGetterOrSetter(const JsVar *v) { if (!v) return false; char f = v->flags&JSV_VARTYPEMASK; return JSV_IS_GETTER_OR_SETTER(f); }
/// Are var.varData.ref.* (excl pad) used for data (so we expect them not to be empty)
bool jsvIsRefUsedForData(const JsVar *v) {
// Used for assert - no need to optimise
return jsvIsStringExt(v) || (jsvIsString(v)&&!jsvIsName(v)) || jsvIsFloat(v) ||
jsvIsNativeFunction(v) || jsvIsArrayBuffer(v) || jsvIsArrayBufferName(v);
}
/// Can the given variable be converted into an integer without loss of precision
bool jsvIsIntegerish(const JsVar *v) {
//return jsvIsInt(v) || jsvIsPin(v) || jsvIsBoolean(v) || jsvIsNull(v);
if (!v) return false;
char f = v->flags&JSV_VARTYPEMASK;
return JSV_IS_INT(f) || JSV_IS_PIN(f) || JSV_IS_BOOL(f) || JSV_IS_NULL(f);
}
bool jsvIsIterable(const JsVar *v) {
//return jsvIsArray(v) || jsvIsObject(v) || jsvIsFunction(v) || jsvIsString(v) || jsvIsArrayBuffer(v);
if (!v) return false;
char f = v->flags&JSV_VARTYPEMASK;
return
JSV_IS_ARRAY(f) || JSV_IS_OBJECT(f) || JSV_IS_FUNCTION(f) ||
JSV_IS_STRING(f) || JSV_IS_ARRAYBUFFER(f);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
bool jsvHasCharacterData(const JsVar *v) {
if (!v) return false;
char f = v->flags&JSV_VARTYPEMASK;
return JSV_IS_STRING(f) || JSV_IS_STRING_EXT(f);
}
bool jsvHasStringExt(const JsVar *v) {
if (!v) return false;
char f = v->flags&JSV_VARTYPEMASK;
return (JSV_IS_STRING(f) || JSV_IS_STRING_EXT(f)) && !JSV_IS_NONAPPENDABLE_STRING(f);
}
bool jsvHasChildren(const JsVar *v) {
if (!v) return false;
char f = v->flags&JSV_VARTYPEMASK;
return JSV_IS_FUNCTION(f) || JSV_IS_OBJECT(f) || JSV_IS_ARRAY(f) ||
JSV_IS_ROOT(f) || JSV_IS_GETTER_OR_SETTER(f);
}
/// Is this variable a type that uses firstChild to point to a single Variable (ie. it doesn't have multiple children)
bool jsvHasSingleChild(const JsVar *v) {
if (!v) return false;
char f = v->flags&JSV_VARTYPEMASK;
return JSV_IS_ARRAYBUFFER(f) ||
(JSV_IS_NAME(f) && !JSV_IS_NAME_WITH_VALUE(f));
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/** Return a pointer - UNSAFE for null refs.
* This is effectively a Lock without locking! */
static ALWAYS_INLINE JsVar *jsvGetAddressOf(JsVarRef ref) {
assert(ref);
#ifdef RESIZABLE_JSVARS
assert(ref <= jsVarsSize);
JsVarRef t = ref-1;
return &jsVarBlocks[t>>JSVAR_BLOCK_SHIFT][t&(JSVAR_BLOCK_SIZE-1)];
#elif defined(JSVAR_MALLOC)
assert(ref <= jsVarsSize);
return &jsVars[ref-1];
#else
assert(ref <= JSVAR_CACHE_SIZE);
return &jsVars[ref-1];
#endif
}
JsVar *_jsvGetAddressOf(JsVarRef ref) {
return jsvGetAddressOf(ref);
}
// For debugging/testing ONLY - maximum # of vars we are allowed to use
void jsvSetMaxVarsUsed(unsigned int size) {
#ifdef RESIZABLE_JSVARS
assert(size < JSVAR_BLOCK_SIZE); // remember - this is only for DEBUGGING - as such it doesn't use multiple blocks
jsVarsSize = size;
#else
#ifdef JSVAR_MALLOC
assert(size < JSVAR_CACHE_SIZE);
jsVarsSize = size;
#else
assert(0);
#endif
#endif
}
// maps the empty variables in...
void jsvCreateEmptyVarList() {
assert(!isMemoryBusy);
isMemoryBusy = MEMBUSY_SYSTEM;
jsVarFirstEmpty = 0;
JsVar firstVar; // temporary var to simplify code in the loop below
jsvSetNextSibling(&firstVar, 0);
JsVar *lastEmpty = &firstVar;
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) {
jsvSetNextSibling(lastEmpty, i);
lastEmpty = var;
} else if (jsvIsFlatString(var)) {
// skip over used blocks for flat strings
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
jsvSetNextSibling(lastEmpty, 0);
jsVarFirstEmpty = jsvGetNextSibling(&firstVar);
isMemoryBusy = MEM_NOT_BUSY;
}
/* Removes the empty variable counter, cleaving clear runs of 0s
where no data resides. This helps if compressing the variables
for storage. */
void jsvClearEmptyVarList() {
assert(!isMemoryBusy);
isMemoryBusy = MEMBUSY_SYSTEM;
jsVarFirstEmpty = 0;
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) {
// completely zero it (JSV_UNUSED==0, so it still stays the same)
memset((void*)var,0,sizeof(JsVar));
} else if (jsvIsFlatString(var)) {
// skip over used blocks for flat strings
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
isMemoryBusy = MEM_NOT_BUSY;
}
void jsvSoftInit() {
jsvCreateEmptyVarList();
}
void jsvSoftKill() {
jsvClearEmptyVarList();
}
/** This links all JsVars together, so we can have our nice
* linked list of free JsVars. It returns the ref of the first
* item - that we should set jsVarFirstEmpty to (if it is 0) */
static JsVarRef jsvInitJsVars(JsVarRef start, unsigned int count) {
JsVarRef i;
for (i=start;i<start+count;i++) {
JsVar *v = jsvGetAddressOf(i);
v->flags = JSV_UNUSED;
// v->locks = 0; // locks is 0 anyway because it is stored in flags
jsvSetNextSibling(v, (JsVarRef)(i+1)); // link to next
}
jsvSetNextSibling(jsvGetAddressOf((JsVarRef)(start+count-1)), (JsVarRef)0); // set the final one to 0
return start;
}
void jsvInit(unsigned int size) {
#ifdef RESIZABLE_JSVARS
assert(size==0);
jsVarsSize = JSVAR_BLOCK_SIZE;
jsVarBlocks = malloc(sizeof(JsVar*)); // just 1
#if defined(ESPR_JIT) && defined(LINUX)
jsVarBlocks[0] = (JsVar *)mmap(NULL, sizeof(JsVar) * JSVAR_BLOCK_SIZE, PROT_EXEC | PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
#else
jsVarBlocks[0] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE);
#endif
#elif defined(JSVAR_MALLOC)
if (size) jsVarsSize = size;
#if defined(ESPR_JIT) && defined(LINUX)
if (!jsVars)
jsVars = (JsVar *)mmap(NULL, sizeof(JsVar) * jsVarsSize, PROT_EXEC | PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
#else
if(!jsVars) jsVars = (JsVar *)malloc(sizeof(JsVar) * jsVarsSize);
#endif
#else
assert(size==0);
#endif
jsVarFirstEmpty = jsvInitJsVars(1/*first*/, jsVarsSize);
jsvSoftInit();
}
void jsvKill() {
#ifdef RESIZABLE_JSVARS
unsigned int i;
for (i=0;i<jsVarsSize>>JSVAR_BLOCK_SHIFT;i++) {
#if defined(ESPR_JIT) && defined(LINUX)
munmap(jsVarBlocks[i], sizeof(JsVar) * JSVAR_BLOCK_SIZE);
#else
free(jsVarBlocks[i]);
#endif
}
free(jsVarBlocks);
jsVarBlocks = 0;
jsVarsSize = 0;
#elif defined(JSVAR_MALLOC)
free(jsVars);
jsVars = NULL;
jsVarsSize = 0;
#endif
}
#ifndef EMBED
/** Find or create the ROOT variable item - used mainly
* if recovering from a saved state. */
JsVar *jsvFindOrCreateRoot() {
JsVarRef i;
for (i=1;i<=jsVarsSize;i++)
if (jsvIsRoot(jsvGetAddressOf(i)))
return jsvLock(i);
return jsvRef(jsvNewWithFlags(JSV_ROOT));
}
#endif
/// Get number of memory records (JsVars) used
unsigned int jsvGetMemoryUsage() {
unsigned int usage = 0;
for (unsigned int i=1;i<=jsVarsSize;i++) {
JsVar *v = jsvGetAddressOf((JsVarRef)i);
if ((v->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
usage++;
if (jsvIsFlatString(v)) {
unsigned int b = (unsigned int)jsvGetFlatStringBlocks(v);
i+=b;
usage+=b;
}
}
}
return usage;
}
/// Get total amount of memory records
unsigned int jsvGetMemoryTotal() {
return jsVarsSize;
}
/// Try and allocate more memory - only works if RESIZABLE_JSVARS is defined
void jsvSetMemoryTotal(unsigned int jsNewVarCount) {
#ifdef RESIZABLE_JSVARS
assert(!isMemoryBusy);
if (jsNewVarCount <= jsVarsSize) return; // never allow us to have less!
isMemoryBusy = MEMBUSY_SYSTEM;
// When resizing, we just allocate a bunch more
unsigned int oldSize = jsVarsSize;
unsigned int oldBlockCount = jsVarsSize >> JSVAR_BLOCK_SHIFT;
unsigned int newBlockCount = (jsNewVarCount+JSVAR_BLOCK_SIZE-1) >> JSVAR_BLOCK_SHIFT;
jsVarsSize = newBlockCount << JSVAR_BLOCK_SHIFT;
// resize block table
jsVarBlocks = realloc(jsVarBlocks, sizeof(JsVar*)*newBlockCount);
// allocate more blocks
unsigned int i;
for (i=oldBlockCount;i<newBlockCount;i++)
jsVarBlocks[i] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE);
/** and now reset all the newly allocated vars. We know jsVarFirstEmpty
* is 0 (because jsiFreeMoreMemory returned 0) so we can just assign it. */
assert(!jsVarFirstEmpty);
jsVarFirstEmpty = jsvInitJsVars(oldSize+1, jsVarsSize-oldSize);
// jsiConsolePrintf("Resized memory from %d blocks to %d\n", oldBlockCount, newBlockCount);
touchedFreeList = true;
isMemoryBusy = MEM_NOT_BUSY;
#else
NOT_USED(jsNewVarCount);
assert(0);
#endif
}
/// Scan memory to find any JsVar that references a specific memory range, and if so update what it points to to point to the new address
void jsvUpdateMemoryAddress(size_t oldAddr, size_t length, size_t newAddr) {
for (unsigned int i=1;i<=jsVarsSize;i++) {
JsVar *v = jsvGetAddressOf((JsVarRef)i);
if (jsvIsNativeString(v) || jsvIsFlashString(v)) {
size_t p = (size_t)v->varData.nativeStr.ptr;
if (p>=oldAddr && p<oldAddr+length)
v->varData.nativeStr.ptr = (char*)(p+newAddr-oldAddr);
} else if (jsvIsFlatString(v)) {
i += (unsigned int)jsvGetFlatStringBlocks(v);
}
}
}
bool jsvMoreFreeVariablesThan(unsigned int vars) {
if (!vars) return false;
JsVarRef r = jsVarFirstEmpty;
while (r) {
if (!vars--) return true;
r = jsvGetNextSibling(jsvGetAddressOf(r));
}
return false;
}
/// Get whether memory is full or not
bool jsvIsMemoryFull() {
return !jsVarFirstEmpty;
}
// Show what is still allocated, for debugging memory problems
void jsvShowAllocated() {
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
if ((jsvGetAddressOf(i)->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
jsiConsolePrintf("USED VAR #%d:",i);
jsvTrace(jsvGetAddressOf(i), 2);
}
}
}
/** Return the is the number of characters this one JsVar can contain, NOT string length (eg, a chain of JsVars)
* This will return an invalid length when applied to Flat Strings */
size_t jsvGetMaxCharactersInVar(const JsVar *v) {
// see jsvCopy - we need to know about this in there too
if (jsvIsStringExt(v)) return JSVAR_DATA_STRING_MAX_LEN;
assert(jsvHasCharacterData(v));
if (jsvIsName(v)) return JSVAR_DATA_STRING_NAME_LEN;
if (jsvIsFlatString(v) || jsvIsFlashString(v) || jsvIsNativeString(v)) return jsvGetCharactersInVar(v);
return JSVAR_DATA_STRING_LEN;
}
/// This is the number of characters a JsVar can contain, NOT string length
size_t jsvGetCharactersInVar(const JsVar *v) {
unsigned int f = v->flags&JSV_VARTYPEMASK;
if (f == JSV_FLAT_STRING)
return (size_t)v->varData.integer;
if ((f == JSV_NATIVE_STRING)
#ifdef SPIFLASH_BASE
|| (f == JSV_FLASH_STRING)
#endif
)
return (size_t)v->varData.nativeStr.len;
if (f < JSV_NAME_STRING_INT_0) jsiConsolePrintf("F %d\n", f);
assert(f >= JSV_NAME_STRING_INT_0);
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
if (f<=JSV_NAME_STRING_MAX) {
if (f<=JSV_NAME_STRING_INT_MAX)
return f-JSV_NAME_STRING_INT_0;
else
return f-JSV_NAME_STRING_0;
} else {
if (f<=JSV_STRING_MAX) return f-JSV_STRING_0;
assert(f <= JSV_STRING_EXT_MAX);
return f - JSV_STRING_EXT_0;
}
}
/// This is the number of characters a JsVar can contain, NOT string length
void jsvSetCharactersInVar(JsVar *v, size_t chars) {
unsigned int f = v->flags&JSV_VARTYPEMASK;
assert(!(jsvIsFlatString(v) || jsvIsNativeString(v) || jsvIsFlashString(v)));
JsVarFlags m = (JsVarFlags)(v->flags&~JSV_VARTYPEMASK);
assert(f >= JSV_NAME_STRING_INT_0);
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
if (f<=JSV_NAME_STRING_MAX) {
assert(chars <= JSVAR_DATA_STRING_NAME_LEN);
if (f<=JSV_NAME_STRING_INT_MAX)
v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_INT_0+chars));
else
v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_0+chars));
} else {
if (f<=JSV_STRING_MAX) {
assert(chars <= JSVAR_DATA_STRING_LEN);
v->flags = (JsVarFlags)(m | (JSV_STRING_0+chars));
} else {
assert(chars <= JSVAR_DATA_STRING_MAX_LEN);
assert(f <= JSV_STRING_EXT_MAX);
v->flags = (JsVarFlags)(m | (JSV_STRING_EXT_0+chars));
}
}
}
void jsvResetVariable(JsVar *v, JsVarFlags flags) {
assert((v->flags&JSV_VARTYPEMASK) == JSV_UNUSED);
// make sure we clear all data...
/* Force a proper zeroing of all data. We don't use
* memset because that'd create a function call. This
* should just generate a bunch of STR instructions */
// FIXME: this does not generate STR instructions - it's just a tight loop with STRB. We should be able to do better?
unsigned int i;
if ((sizeof(JsVar)&3) == 0) {
for (i=0;i<sizeof(JsVar)/sizeof(uint32_t);i++)
((uint32_t*)v)[i] = 0;
} else { // just fall back to bytes and hope it's smart enough
for (i=0;i<sizeof(JsVar);i++)
((uint8_t*)v)[i] = 0;
}
// set flags
assert(!(flags & JSV_LOCK_MASK));
v->flags = flags | JSV_LOCK_ONE;
}
JsVar *jsvNewWithFlags(JsVarFlags flags) {
if (isMemoryBusy) {
jsErrorFlags |= JSERR_MEMORY_BUSY;
return 0;
}
JsVar *v = 0;
jshInterruptOff(); // to allow this to be used from an IRQ
if (jsVarFirstEmpty!=0) {
v = jsvGetAddressOf(jsVarFirstEmpty); // jsvResetVariable will lock
jsVarFirstEmpty = jsvGetNextSibling(v); // move our reference to the next in the free list
touchedFreeList = true;
}
jshInterruptOn();
if (v) {
assert(v->flags == JSV_UNUSED);
// Cope with IRQs/multi-threading when getting a new free variable
/* JsVarRef empty;
JsVarRef next;
JsVar *v;
do {
empty = jsVarFirstEmpty;
v = jsvGetAddressOf(empty); // jsvResetVariable will lock
next = jsvGetNextSibling(v); // move our reference to the next in the free list
touchedFreeList = true;
} while (!__sync_bool_compare_and_swap(&jsVarFirstEmpty, empty, next));
assert(v->flags == JSV_UNUSED);*/
jsvResetVariable(v, flags); // setup variable, and add one lock
// return pointer
return v;
}
jsErrorFlags |= JSERR_LOW_MEMORY;
/* If we're calling from an IRQ, do NOT try and do fancy
* stuff to free memory */
if (jshIsInInterrupt()) {
return 0;
}
/* we don't have memory - second last hope - run garbage collector */
if (jsvGarbageCollect()) {
return jsvNewWithFlags(flags); // if it freed something, continue
}
/* we don't have memory - last hope - ask jsInteractive to try and free some it
may have kicking around */
if (jsiFreeMoreMemory()) {
return jsvNewWithFlags(flags);
}
/* We couldn't claim any more memory by Garbage collecting... */
#ifdef RESIZABLE_JSVARS
jsvSetMemoryTotal(jsVarsSize*2);
return jsvNewWithFlags(flags);
#else
// On a micro, we're screwed.
jsErrorFlags |= JSERR_MEMORY;
jspSetInterrupted(true);
return 0;
#endif
}
static void jsvFreePtrInternal(JsVar *var) {
assert(jsvGetLocks(var)==0);
var->flags = JSV_UNUSED;
// add this to our free list
jshInterruptOff(); // to allow this to be used from an IRQ
jsvSetNextSibling(var, jsVarFirstEmpty);
jsVarFirstEmpty = jsvGetRef(var);
touchedFreeList = true;
jshInterruptOn();
}
ALWAYS_INLINE void jsvFreePtr(JsVar *var) {
/* To be here, we're not supposed to be part of anything else. If
* we were, we'd have been freed by jsvGarbageCollect */
assert((!jsvGetNextSibling(var) && !jsvGetPrevSibling(var)) || // check that next/prevSibling are not set
jsvIsRefUsedForData(var) || // UNLESS we're part of a string and nextSibling/prevSibling are used for string data
(jsvIsName(var) && (jsvGetNextSibling(var)==jsvGetPrevSibling(var)))); // UNLESS we're signalling that we're jsvild
// Names that Link to other things
if (jsvIsNameWithValue(var)) {
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // it just contained random data - zero it
#endif // CLEAR_MEMORY_ON_FREE
} else if (jsvHasSingleChild(var)) {
if (jsvGetFirstChild(var)) {
if (jsuGetFreeStack() > 256) {
// we have to check stack here in case someone allocates some huge linked list.
// if we just unreference the rest hopefully it'll be cleaned on the next GC pass
// https://github.com/espruino/Espruino/issues/2136
JsVar *child = jsvLock(jsvGetFirstChild(var));
jsvUnRef(child);
jsvUnLock(child); // unlock should trigger a free
}
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // unlink the child
#endif // CLEAR_MEMORY_ON_FREE
}
}
/* No else, because a String Name may have a single child, but
* also StringExts */
/* Now, free children - see jsvar.h comments for how! */
if (jsvHasStringExt(var)) {
// Free the string without recursing
JsVarRef stringDataRef = jsvGetLastChild(var);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetLastChild(var, 0);
#endif // CLEAR_MEMORY_ON_FREE
while (stringDataRef) {
JsVar *child = jsvGetAddressOf(stringDataRef);
assert(jsvIsStringExt(child));
stringDataRef = jsvGetLastChild(child);
jsvFreePtrInternal(child);
}
if (jsvIsBasicString(var)) {
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // firstchild could have had string data in
#endif // CLEAR_MEMORY_ON_FREE
}
} else if (jsvIsFlatString(var)) { // We might be a flat string (we're not allowing strings to be added to flat strings yet)
// in which case we need to free all the blocks.
size_t count = jsvGetFlatStringBlocks(var);
JsVarRef i = (JsVarRef)(jsvGetRef(var)+count);
// Because this is a whole bunch of blocks, try
// and insert it in the right place in the free list
// So, iterate along free list to figure out where we
// need to insert the free items
jshInterruptOff(); // to allow this to be used from an IRQ
JsVarRef insertBefore = jsVarFirstEmpty;
JsVarRef insertAfter = 0;
while (insertBefore && insertBefore<i) {
insertAfter = insertBefore;
insertBefore = jsvGetNextSibling(jsvGetAddressOf(insertBefore));
}
// free in reverse, so the free list ends up in kind of the right order
while (count--) {
JsVar *p = jsvGetAddressOf(i--);
p->flags = JSV_UNUSED; // set locks to 0 so the assert in jsvFreePtrInternal doesn't get fed up
// add this to our free list
jsvSetNextSibling(p, insertBefore);
insertBefore = jsvGetRef(p);
}
// patch up jsVarFirstEmpty/rejoin the list
if (insertAfter)
jsvSetNextSibling(jsvGetAddressOf(insertAfter), insertBefore);
else
jsVarFirstEmpty = insertBefore;
touchedFreeList = true;
jshInterruptOn();
}
/* NO ELSE HERE - because jsvIsNewChild stuff can be for Names, which
can be ints or strings */
if (jsvHasChildren(var)) {
JsVarRef childref = jsvGetFirstChild(var);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0);
jsvSetLastChild(var, 0);
#endif // CLEAR_MEMORY_ON_FREE
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsName(child));
childref = jsvGetNextSibling(child);
jsvSetPrevSibling(child, 0);
jsvSetNextSibling(child, 0);
jsvUnRef(child);
jsvUnLock(child);
}
} else {
#ifdef CLEAR_MEMORY_ON_FREE
assert(jsvIsFloat(var) || !jsvGetFirstChild(var));
assert(jsvIsFloat(var) || !jsvGetLastChild(var));
#endif // CLEAR_MEMORY_ON_FREE
if (jsvIsName(var)) {
assert(jsvGetNextSibling(var)==jsvGetPrevSibling(var)); // the case for jsvIsNewChild
if (jsvGetNextSibling(var)) {
jsvUnRefRef(jsvGetNextSibling(var));
jsvUnRefRef(jsvGetPrevSibling(var));
}
}
}
// free!
jsvFreePtrInternal(var);
}
/// Get a reference from a var - SAFE for null vars
JsVarRef jsvGetRef(JsVar *var) {
if (!var) return 0;
#ifdef RESIZABLE_JSVARS
unsigned int i, c = jsVarsSize>>JSVAR_BLOCK_SHIFT;
for (i=0;i<c;i++) {
if (var>=jsVarBlocks[i] && var<&jsVarBlocks[i][JSVAR_BLOCK_SIZE]) {
JsVarRef r = (JsVarRef)(1 + (i<<JSVAR_BLOCK_SHIFT) + (var - jsVarBlocks[i]));
return r;
}
}
return 0;
#else
return (JsVarRef)(1 + (var - jsVars));
#endif
}
/// Lock this reference and return a pointer - UNSAFE for null refs
JsVar *jsvLock(JsVarRef ref) {
JsVar *var = jsvGetAddressOf(ref);
//var->locks++;
assert(jsvGetLocks(var) < JSV_LOCK_MAX);
var->flags += JSV_LOCK_ONE;
#ifdef DEBUG
if (jsvGetLocks(var)==0) {
jsError("Too many locks to Variable!");
//jsPrint("Var #");jsPrintInt(ref);jsPrint("\n");
}
#endif
return var;
}
/// Lock this reference and return a pointer - UNSAFE for null refs
JsVar *jsvLockSafe(JsVarRef ref) {
if (!ref) return 0;
return jsvLock(ref);
}
/// Lock this pointer and return a pointer - UNSAFE for null pointer
JsVar *jsvLockAgain(JsVar *var) {
assert(var);
assert(jsvGetLocks(var) < JSV_LOCK_MAX);
var->flags += JSV_LOCK_ONE;
return var;
}
/// Lock this pointer and return a pointer - UNSAFE for null pointer
JsVar *jsvLockAgainSafe(JsVar *var) {
return var ? jsvLockAgain(var) : 0;
}
// CALL ONLY FROM jsvUnlock
// jsvGetLocks(var) must == 0
static NO_INLINE void jsvUnLockFreeIfNeeded(JsVar *var) {
assert(jsvGetLocks(var) == 0);
/* if we know we're free, then we can just free this variable right now.
* Loops of variables are handled by the Garbage Collector.
* Note: we checked locks already in jsvUnLock as it is fastest to check */
if (jsvGetRefs(var) == 0 &&
jsvHasRef(var) &&
(var->flags&JSV_VARTYPEMASK)!=JSV_UNUSED) { // we might be in an IRQ now, with GC in the main thread. If so, don't free!
jsvFreePtr(var);
}
}
/** Unlock this variable - this is SAFE for null variables
* This version is used so we can ensure that the relatively
* simple code here gets inlined for jsvUnLock2/etc */
static ALWAYS_INLINE void jsvUnLockInline(JsVar *var) {
if (!var) return;
assert(jsvGetLocks(var)>0);
/* Reduce lock count. Since ->flags is volatile
* it helps to explicitly save it to a var to avoid a
* load-store-load */
JsVarFlags f = var->flags -= JSV_LOCK_ONE;
// Now see if we can properly free the data
// Note: we check locks first as they are already in a register
if ((f & JSV_LOCK_MASK) == 0) jsvUnLockFreeIfNeeded(var);
}
/// Unlock this variable - this is SAFE for null variables
void jsvUnLock(JsVar *var) {
jsvUnLockInline(var);
}
/// Unlock 2 variables in one go
void jsvUnLock2(JsVar *var1, JsVar *var2) {
jsvUnLockInline(var1);
jsvUnLockInline(var2);
}
/// Unlock 3 variables in one go
void jsvUnLock3(JsVar *var1, JsVar *var2, JsVar *var3) {
jsvUnLockInline(var1);
jsvUnLockInline(var2);
jsvUnLockInline(var3);
}
/// Unlock 4 variables in one go
void jsvUnLock4(JsVar *var1, JsVar *var2, JsVar *var3, JsVar *var4) {
jsvUnLockInline(var1);
jsvUnLockInline(var2);
jsvUnLockInline(var3);
jsvUnLockInline(var4);
}
/// Unlock an array of variables
NO_INLINE void jsvUnLockMany(unsigned int count, JsVar **vars) {
while (count) jsvUnLockInline(vars[--count]);
}
/// Reference - set this variable as used by something
JsVar *jsvRef(JsVar *var) {
assert(var && jsvHasRef(var));
if (jsvGetRefs(var) < JSVARREFCOUNT_MAX) // if we hit max refcounts, just keep them - GC will fix it later
jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)+1));
assert(jsvGetRefs(var));
return var;
}
/// Unreference - set this variable as not used by anything
void jsvUnRef(JsVar *var) {
assert(var && jsvGetRefs(var)>0 && jsvHasRef(var));
if (jsvGetRefs(var) < JSVARREFCOUNT_MAX) // if we hit max refcounts, just keep them - GC will fix it later
jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)-1));
}
/// Helper fn, Reference - set this variable as used by something
JsVarRef jsvRefRef(JsVarRef ref) {
JsVar *v;
assert(ref);
v = jsvLock(ref);
assert(!jsvIsStringExt(v));
jsvRef(v);
jsvUnLock(v);
return ref;
}
/// Helper fn, Unreference - set this variable as not used by anything
JsVarRef jsvUnRefRef(JsVarRef ref) {
JsVar *v;
assert(ref);
v = jsvLock(ref);
assert(!jsvIsStringExt(v));
jsvUnRef(v);
jsvUnLock(v);
return 0;
}
JsVar *jsvNewFlatStringOfLength(unsigned int byteLength) {
bool firstRun = true;
// Work out how many blocks we need. One for the header, plus some for the characters
size_t requiredBlocks = 1 + ((byteLength+sizeof(JsVar)-1) / sizeof(JsVar));
JsVar *flatString = 0;
if (isMemoryBusy) {
jsErrorFlags |= JSERR_MEMORY_BUSY;
return 0;
}
while (true) {
/* Now try and find a contiguous set of 'requiredBlocks' blocks by
searching the free list. This can be done as long as nobody's
messed with the free list in the mean time (which we check for with
touchedFreeList). If someone has messed with it, we restart.*/
bool memoryTouched = true;
while (memoryTouched) {
memoryTouched = false;
touchedFreeList = false;
JsVarRef beforeStartBlock = 0;
JsVarRef curr = jsVarFirstEmpty;
JsVarRef startBlock = curr;
unsigned int blockCount = 0;
while (curr && !touchedFreeList) {
JsVar *currVar = jsvGetAddressOf(curr);
JsVarRef next = jsvGetNextSibling(currVar);
#ifdef RESIZABLE_JSVARS
if (blockCount && next && (jsvGetAddressOf(next)==currVar+1)) {
#else
if (blockCount && (next == curr+1)) {
#endif
blockCount++;
if (blockCount>=requiredBlocks) {
JsVar *nextVar = jsvGetAddressOf(next);
JsVarRef nextFree = jsvGetNextSibling(nextVar);
jshInterruptOff();
if (!touchedFreeList) {
// we're there! Quickly re-link free list
if (beforeStartBlock) {
jsvSetNextSibling(jsvGetAddressOf(beforeStartBlock),nextFree);
} else {
jsVarFirstEmpty = nextFree;
}
flatString = jsvGetAddressOf(startBlock);
// Set up the header block (including one lock)
jsvResetVariable(flatString, JSV_FLAT_STRING);
flatString->varData.integer = (JsVarInt)byteLength;
}
jshInterruptOn();
// if success, break out!
if (flatString) break;
}
} else {
// this block is not immediately after the last - restart run
beforeStartBlock = curr;
startBlock = next;
// Check to see if the next block is aligned on a 4 byte boundary or not
if (startBlock==jsVarsSize || ((size_t)(jsvGetAddressOf(startBlock+1)))&3)
blockCount = 0; // this block is not aligned
else
blockCount = 1; // all ok - start block here
}
// move to next!
curr = next;
}
// memory list has been touched - restart!
if (touchedFreeList) {
memoryTouched = true;
}
}
// all good
if (flatString || !firstRun)
break;
/* Nope... we couldn't find a free string. It could be because
* the free list is fragmented, so GCing might well fix it - which
* we'll try - but only ONCE */
firstRun = false;
jsvGarbageCollect();
};
if (!flatString) return 0;
/* We now have the string! All that's left is to clear it */
// clear data
memset((char*)&flatString[1], 0, sizeof(JsVar)*(requiredBlocks-1));
/* We did mess with the free list - set it here in case we
are trying to create a flat string in an IRQ while trying to
make one outside the IRQ too */
touchedFreeList = true;
// and we're done
return flatString;
}
JsVar *jsvNewFromString(const char *str) {
// Create a var
JsVar *first = jsvNewWithFlags(JSV_STRING_0);
if (!first) return 0; // out of memory
// Now we copy the string, but keep creating new jsVars if we go
// over the end
JsVar *var = jsvLockAgain(first);
while (*str) {
// copy data in
size_t i, l = jsvGetMaxCharactersInVar(var);
for (i=0;i<l && *str;i++)
var->varData.str[i] = *(str++);
// we already set the variable data to 0, so no need for adding one