-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjscntxt.cpp
More file actions
2314 lines (2050 loc) · 65.4 KB
/
jscntxt.cpp
File metadata and controls
2314 lines (2050 loc) · 65.4 KB
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=80:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* JS execution context.
*/
#include <new>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#ifdef ANDROID
# include <android/log.h>
# include <fstream>
# include <string>
#endif // ANDROID
#include "jsstdint.h"
#include "jstypes.h"
#include "jsarena.h"
#include "jsutil.h"
#include "jsclist.h"
#include "jsprf.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jsversion.h"
#include "jsdbgapi.h"
#include "jsexn.h"
#include "jsfun.h"
#include "jsgc.h"
#include "jsiter.h"
#include "jslock.h"
#include "jsmath.h"
#include "jsnativestack.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jsopcode.h"
#include "jspubtd.h"
#include "jsscan.h"
#include "jsscope.h"
#include "jsscript.h"
#include "jsstaticcheck.h"
#include "jsstr.h"
#include "jstracer.h"
#ifdef JS_METHODJIT
# include "assembler/assembler/MacroAssembler.h"
#endif
#include "jscntxtinlines.h"
#include "jscompartment.h"
#include "jsinterpinlines.h"
#include "jsobjinlines.h"
#ifdef XP_WIN
# include "jswin.h"
#elif defined(XP_OS2)
# define INCL_DOSMEMMGR
# include <os2.h>
#else
# include <unistd.h>
# include <sys/mman.h>
# if !defined(MAP_ANONYMOUS)
# if defined(MAP_ANON)
# define MAP_ANONYMOUS MAP_ANON
# else
# define MAP_ANONYMOUS 0
# endif
# endif
#endif
using namespace js;
using namespace js::gc;
static const size_t ARENA_HEADER_SIZE_HACK = 40;
static const size_t TEMP_POOL_CHUNK_SIZE = 4096 - ARENA_HEADER_SIZE_HACK;
static void
FreeContext(JSContext *cx);
#ifdef DEBUG
JS_REQUIRES_STACK bool
StackSegment::contains(const JSStackFrame *fp) const
{
JS_ASSERT(inContext());
JSStackFrame *start;
JSStackFrame *stop;
if (isActive()) {
JS_ASSERT(cx->hasfp());
start = cx->fp();
stop = cx->activeSegment()->initialFrame->prev();
} else {
JS_ASSERT(suspendedRegs && suspendedRegs->fp);
start = suspendedRegs->fp;
stop = initialFrame->prev();
}
for (JSStackFrame *f = start; f != stop; f = f->prev()) {
if (f == fp)
return true;
}
return false;
}
#endif
bool
StackSpace::init()
{
void *p;
#ifdef XP_WIN
p = VirtualAlloc(NULL, CAPACITY_BYTES, MEM_RESERVE, PAGE_READWRITE);
if (!p)
return false;
void *check = VirtualAlloc(p, COMMIT_BYTES, MEM_COMMIT, PAGE_READWRITE);
if (p != check)
return false;
base = reinterpret_cast<Value *>(p);
commitEnd = base + COMMIT_VALS;
end = base + CAPACITY_VALS;
#elif defined(XP_OS2)
if (DosAllocMem(&p, CAPACITY_BYTES, PAG_COMMIT | PAG_READ | PAG_WRITE | OBJ_ANY) &&
DosAllocMem(&p, CAPACITY_BYTES, PAG_COMMIT | PAG_READ | PAG_WRITE))
return false;
base = reinterpret_cast<Value *>(p);
end = base + CAPACITY_VALS;
#else
JS_ASSERT(CAPACITY_BYTES % getpagesize() == 0);
p = mmap(NULL, CAPACITY_BYTES, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED)
return false;
base = reinterpret_cast<Value *>(p);
end = base + CAPACITY_VALS;
#endif
return true;
}
void
StackSpace::finish()
{
#ifdef XP_WIN
VirtualFree(base, (commitEnd - base) * sizeof(Value), MEM_DECOMMIT);
VirtualFree(base, 0, MEM_RELEASE);
#elif defined(XP_OS2)
DosFreeMem(base);
#else
#ifdef SOLARIS
munmap((caddr_t)base, CAPACITY_BYTES);
#else
munmap(base, CAPACITY_BYTES);
#endif
#endif
}
#ifdef XP_WIN
JS_FRIEND_API(bool)
StackSpace::bumpCommit(Value *from, ptrdiff_t nvals) const
{
JS_ASSERT(end - from >= nvals);
Value *newCommit = commitEnd;
Value *request = from + nvals;
/* Use a dumb loop; will probably execute once. */
JS_ASSERT((end - newCommit) % COMMIT_VALS == 0);
do {
newCommit += COMMIT_VALS;
JS_ASSERT((end - newCommit) >= 0);
} while (newCommit < request);
/* The cast is safe because CAPACITY_BYTES is small. */
int32 size = static_cast<int32>(newCommit - commitEnd) * sizeof(Value);
if (!VirtualAlloc(commitEnd, size, MEM_COMMIT, PAGE_READWRITE))
return false;
commitEnd = newCommit;
return true;
}
#endif
void
StackSpace::mark(JSTracer *trc)
{
/*
* The correctness/completeness of marking depends on the continuity
* invariants described by the StackSegment and StackSpace definitions.
*
* NB:
* Stack slots might be torn or uninitialized in the presence of method
* JIT'd code. Arguments are an exception and are always fully synced
* (so they can be read by functions).
*/
Value *end = firstUnused();
for (StackSegment *seg = currentSegment; seg; seg = seg->getPreviousInMemory()) {
STATIC_ASSERT(ubound(end) >= 0);
if (seg->inContext()) {
/* This may be the only pointer to the initialVarObj. */
if (seg->hasInitialVarObj())
MarkObject(trc, seg->getInitialVarObj(), "varobj");
/* Mark slots/args trailing off of the last stack frame. */
JSStackFrame *fp = seg->getCurrentFrame();
MarkStackRangeConservatively(trc, fp->slots(), end);
/* Mark stack frames and slots/args between stack frames. */
JSStackFrame *initial = seg->getInitialFrame();
for (JSStackFrame *f = fp; f != initial; f = f->prev()) {
js_TraceStackFrame(trc, f);
MarkStackRangeConservatively(trc, f->prev()->slots(), (Value *)f);
}
/* Mark initial stack frame and leading args. */
js_TraceStackFrame(trc, initial);
MarkStackRangeConservatively(trc, seg->valueRangeBegin(), (Value *)initial);
} else {
/* Mark slots/args trailing off segment. */
MarkValueRange(trc, seg->valueRangeBegin(), end, "stack");
}
end = (Value *)seg;
}
}
bool
StackSpace::pushSegmentForInvoke(JSContext *cx, uintN argc, InvokeArgsGuard *ag)
{
Value *start = firstUnused();
ptrdiff_t nvals = VALUES_PER_STACK_SEGMENT + 2 + argc;
if (!ensureSpace(cx, start, nvals))
return false;
StackSegment *seg = new(start) StackSegment;
seg->setPreviousInMemory(currentSegment);
currentSegment = seg;
ag->cx = cx;
ag->seg = seg;
ag->argv_ = seg->valueRangeBegin() + 2;
ag->argc_ = argc;
/* Use invokeArgEnd to root [vp, vpend) until the frame is pushed. */
#ifdef DEBUG
ag->prevInvokeSegment = invokeSegment;
invokeSegment = seg;
ag->prevInvokeFrame = invokeFrame;
invokeFrame = NULL;
#endif
ag->prevInvokeArgEnd = invokeArgEnd;
invokeArgEnd = ag->argv() + ag->argc();
return true;
}
void
StackSpace::popSegmentForInvoke(const InvokeArgsGuard &ag)
{
JS_ASSERT(!currentSegment->inContext());
JS_ASSERT(ag.seg == currentSegment);
JS_ASSERT(invokeSegment == currentSegment);
JS_ASSERT(invokeArgEnd == ag.argv() + ag.argc());
currentSegment = currentSegment->getPreviousInMemory();
#ifdef DEBUG
invokeSegment = ag.prevInvokeSegment;
invokeFrame = ag.prevInvokeFrame;
#endif
invokeArgEnd = ag.prevInvokeArgEnd;
}
bool
StackSpace::getSegmentAndFrame(JSContext *cx, uintN vplen, uintN nslots,
FrameGuard *fg) const
{
Value *start = firstUnused();
uintN nvals = VALUES_PER_STACK_SEGMENT + vplen + VALUES_PER_STACK_FRAME + nslots;
if (!ensureSpace(cx, start, nvals))
return false;
fg->seg_ = new(start) StackSegment;
fg->vp_ = start + VALUES_PER_STACK_SEGMENT;
fg->fp_ = reinterpret_cast<JSStackFrame *>(fg->vp() + vplen);
return true;
}
void
StackSpace::pushSegmentAndFrame(JSContext *cx, JSFrameRegs *regs, FrameGuard *fg)
{
/* Caller should have already initialized regs. */
JS_ASSERT(regs->fp == fg->fp());
StackSegment *seg = fg->segment();
/* Register new segment/frame with the context. */
cx->pushSegmentAndFrame(seg, *regs);
/* Officially push the segment/frame on the stack. */
seg->setPreviousInMemory(currentSegment);
currentSegment = seg;
/* Mark as 'pushed' in the guard. */
fg->cx_ = cx;
}
void
StackSpace::popSegmentAndFrame(JSContext *cx)
{
JS_ASSERT(isCurrentAndActive(cx));
JS_ASSERT(cx->hasActiveSegment());
/* Officially pop the segment/frame from the stack. */
currentSegment = currentSegment->getPreviousInMemory();
/* Unregister pushed segment/frame from the context. */
cx->popSegmentAndFrame();
/*
* N.B. This StackSpace should be GC-able without any operations after
* cx->popSegmentAndFrame executes since it can trigger GC.
*/
}
FrameGuard::~FrameGuard()
{
if (!pushed())
return;
JS_ASSERT(cx_->activeSegment() == segment());
JS_ASSERT(cx_->maybefp() == fp());
cx_->stack().popSegmentAndFrame(cx_);
}
bool
StackSpace::getExecuteFrame(JSContext *cx, JSScript *script, ExecuteFrameGuard *fg) const
{
return getSegmentAndFrame(cx, 2, script->nslots, fg);
}
void
StackSpace::pushExecuteFrame(JSContext *cx, JSObject *initialVarObj, ExecuteFrameGuard *fg)
{
JSStackFrame *fp = fg->fp();
JSScript *script = fp->script();
fg->regs_.pc = script->code;
fg->regs_.fp = fp;
fg->regs_.sp = fp->base();
pushSegmentAndFrame(cx, &fg->regs_, fg);
fg->seg_->setInitialVarObj(initialVarObj);
}
bool
StackSpace::pushDummyFrame(JSContext *cx, JSObject &scopeChain, DummyFrameGuard *fg)
{
if (!getSegmentAndFrame(cx, 0 /*vplen*/, 0 /*nslots*/, fg))
return false;
fg->fp()->initDummyFrame(cx, scopeChain);
fg->regs_.fp = fg->fp();
fg->regs_.pc = NULL;
fg->regs_.sp = fg->fp()->slots();
pushSegmentAndFrame(cx, &fg->regs_, fg);
return true;
}
bool
StackSpace::getGeneratorFrame(JSContext *cx, uintN vplen, uintN nslots, GeneratorFrameGuard *fg)
{
return getSegmentAndFrame(cx, vplen, nslots, fg);
}
void
StackSpace::pushGeneratorFrame(JSContext *cx, JSFrameRegs *regs, GeneratorFrameGuard *fg)
{
JS_ASSERT(regs->fp == fg->fp());
JS_ASSERT(regs->fp->prev() == cx->maybefp());
pushSegmentAndFrame(cx, regs, fg);
}
bool
StackSpace::bumpCommitAndLimit(JSStackFrame *base, Value *sp, uintN nvals, Value **limit) const
{
JS_ASSERT(sp >= firstUnused());
JS_ASSERT(sp + nvals >= *limit);
#ifdef XP_WIN
if (commitEnd <= *limit) {
Value *quotaEnd = (Value *)base + STACK_QUOTA;
if (sp + nvals < quotaEnd) {
if (!ensureSpace(NULL, sp, nvals))
return false;
*limit = Min(quotaEnd, commitEnd);
return true;
}
}
#endif
return false;
}
void
FrameRegsIter::initSlow()
{
if (!curseg) {
curfp = NULL;
cursp = NULL;
curpc = NULL;
return;
}
JS_ASSERT(curseg->isSuspended());
curfp = curseg->getSuspendedFrame();
cursp = curseg->getSuspendedRegs()->sp;
curpc = curseg->getSuspendedRegs()->pc;
}
/*
* Using the invariant described in the js::StackSegment comment, we know that,
* when a pair of prev-linked stack frames are in the same segment, the
* first frame's address is the top of the prev-frame's stack, modulo missing
* arguments.
*/
void
FrameRegsIter::incSlow(JSStackFrame *fp, JSStackFrame *prev)
{
JS_ASSERT(prev);
JS_ASSERT(curpc == curfp->pc(cx, fp));
JS_ASSERT(fp == curseg->getInitialFrame());
/*
* If fp is in cs and the prev-frame is in csprev, it is not necessarily
* the case that |cs->getPreviousInContext == csprev| or that
* |csprev->getSuspendedFrame == prev| (because of indirect eval and
* JS_EvaluateInStackFrame). To compute prev's sp, we need to do a linear
* scan, keeping track of what is immediately after prev in memory.
*/
curseg = curseg->getPreviousInContext();
cursp = curseg->getSuspendedRegs()->sp;
JSStackFrame *f = curseg->getSuspendedFrame();
while (f != prev) {
if (f == curseg->getInitialFrame()) {
curseg = curseg->getPreviousInContext();
cursp = curseg->getSuspendedRegs()->sp;
f = curseg->getSuspendedFrame();
} else {
cursp = f->formalArgsEnd();
f = f->prev();
}
}
}
AllFramesIter::AllFramesIter(JSContext *cx)
: curcs(cx->stack().getCurrentSegment()),
curfp(curcs ? curcs->getCurrentFrame() : NULL)
{
}
AllFramesIter&
AllFramesIter::operator++()
{
JS_ASSERT(!done());
if (curfp == curcs->getInitialFrame()) {
curcs = curcs->getPreviousInMemory();
curfp = curcs ? curcs->getCurrentFrame() : NULL;
} else {
curfp = curfp->prev();
}
return *this;
}
bool
JSThreadData::init()
{
#ifdef DEBUG
/* The data must be already zeroed. */
for (size_t i = 0; i != sizeof(*this); ++i)
JS_ASSERT(reinterpret_cast<uint8*>(this)[i] == 0);
#endif
if (!stackSpace.init())
return false;
dtoaState = js_NewDtoaState();
if (!dtoaState) {
finish();
return false;
}
nativeStackBase = GetNativeStackBase();
#ifdef JS_TRACER
/* Set the default size for the code cache to 16MB. */
maxCodeCacheBytes = 16 * 1024 * 1024;
#endif
return true;
}
void
JSThreadData::finish()
{
if (dtoaState)
js_DestroyDtoaState(dtoaState);
js_FinishGSNCache(&gsnCache);
propertyCache.~PropertyCache();
stackSpace.finish();
}
void
JSThreadData::mark(JSTracer *trc)
{
stackSpace.mark(trc);
}
void
JSThreadData::purge(JSContext *cx)
{
js_PurgeGSNCache(&gsnCache);
/* FIXME: bug 506341. */
propertyCache.purge(cx);
}
#ifdef JS_THREADSAFE
static JSThread *
NewThread(void *id)
{
JS_ASSERT(js_CurrentThreadId() == id);
JSThread *thread = (JSThread *) js_calloc(sizeof(JSThread));
if (!thread)
return NULL;
JS_INIT_CLIST(&thread->contextList);
thread->id = id;
if (!thread->data.init()) {
js_free(thread);
return NULL;
}
return thread;
}
static void
DestroyThread(JSThread *thread)
{
/* The thread must have zero contexts. */
JS_ASSERT(JS_CLIST_IS_EMPTY(&thread->contextList));
/*
* The conservative GC scanner should be disabled when the thread leaves
* the last request.
*/
JS_ASSERT(!thread->data.conservativeGC.hasStackToScan());
thread->data.finish();
js_free(thread);
}
JSThread *
js_CurrentThread(JSRuntime *rt)
{
void *id = js_CurrentThreadId();
JS_LOCK_GC(rt);
/*
* We must not race with a GC that accesses cx->thread for JSContext
* instances on all threads, see bug 476934.
*/
js_WaitForGC(rt);
JSThread *thread;
JSThread::Map::AddPtr p = rt->threads.lookupForAdd(id);
if (p) {
thread = p->value;
/*
* If thread has no contexts, it might be left over from a previous
* thread with the same id but a different stack address.
*/
if (JS_CLIST_IS_EMPTY(&thread->contextList))
thread->data.nativeStackBase = GetNativeStackBase();
} else {
JS_UNLOCK_GC(rt);
thread = NewThread(id);
if (!thread)
return NULL;
JS_LOCK_GC(rt);
js_WaitForGC(rt);
if (!rt->threads.relookupOrAdd(p, id, thread)) {
JS_UNLOCK_GC(rt);
DestroyThread(thread);
return NULL;
}
/* Another thread cannot add an entry for the current thread id. */
JS_ASSERT(p->value == thread);
}
JS_ASSERT(thread->id == id);
#ifdef DEBUG
char* gnsb = (char*) GetNativeStackBase();
JS_ASSERT(gnsb + 0 == (char*) thread->data.nativeStackBase ||
/* Work around apparent glibc bug; see bug 608526. */
gnsb + 0x1000 == (char*) thread->data.nativeStackBase ||
gnsb + 0x2000 == (char*) thread->data.nativeStackBase ||
gnsb + 0x3000 == (char*) thread->data.nativeStackBase);
#endif
return thread;
}
JSBool
js_InitContextThread(JSContext *cx)
{
JSThread *thread = js_CurrentThread(cx->runtime);
if (!thread)
return false;
JS_APPEND_LINK(&cx->threadLinks, &thread->contextList);
cx->thread = thread;
return true;
}
void
js_ClearContextThread(JSContext *cx)
{
JS_ASSERT(CURRENT_THREAD_IS_ME(cx->thread));
JS_REMOVE_AND_INIT_LINK(&cx->threadLinks);
cx->thread = NULL;
}
#endif /* JS_THREADSAFE */
JSThreadData *
js_CurrentThreadData(JSRuntime *rt)
{
#ifdef JS_THREADSAFE
JSThread *thread = js_CurrentThread(rt);
if (!thread)
return NULL;
return &thread->data;
#else
return &rt->threadData;
#endif
}
JSBool
js_InitThreads(JSRuntime *rt)
{
#ifdef JS_THREADSAFE
if (!rt->threads.init(4))
return false;
#else
if (!rt->threadData.init())
return false;
#endif
return true;
}
void
js_FinishThreads(JSRuntime *rt)
{
#ifdef JS_THREADSAFE
if (!rt->threads.initialized())
return;
for (JSThread::Map::Range r = rt->threads.all(); !r.empty(); r.popFront()) {
JSThread *thread = r.front().value;
JS_ASSERT(JS_CLIST_IS_EMPTY(&thread->contextList));
DestroyThread(thread);
}
rt->threads.clear();
#else
rt->threadData.finish();
#endif
}
void
js_PurgeThreads(JSContext *cx)
{
#ifdef JS_THREADSAFE
for (JSThread::Map::Enum e(cx->runtime->threads);
!e.empty();
e.popFront()) {
JSThread *thread = e.front().value;
if (JS_CLIST_IS_EMPTY(&thread->contextList)) {
JS_ASSERT(cx->thread != thread);
DestroyThread(thread);
e.removeFront();
} else {
thread->data.purge(cx);
}
}
#else
cx->runtime->threadData.purge(cx);
#endif
}
JSContext *
js_NewContext(JSRuntime *rt, size_t stackChunkSize)
{
JSContext *cx;
JSBool ok, first;
JSContextCallback cxCallback;
/*
* We need to initialize the new context fully before adding it to the
* runtime list. After that it can be accessed from another thread via
* js_ContextIterator.
*/
void *mem = js_calloc(sizeof *cx);
if (!mem)
return NULL;
cx = new (mem) JSContext(rt);
cx->debugHooks = &rt->globalDebugHooks;
#if JS_STACK_GROWTH_DIRECTION > 0
cx->stackLimit = (jsuword) -1;
#endif
cx->scriptStackQuota = JS_DEFAULT_SCRIPT_STACK_QUOTA;
JS_STATIC_ASSERT(JSVERSION_DEFAULT == 0);
JS_ASSERT(cx->findVersion() == JSVERSION_DEFAULT);
VOUCH_DOES_NOT_REQUIRE_STACK();
JS_InitArenaPool(&cx->tempPool, "temp", TEMP_POOL_CHUNK_SIZE, sizeof(jsdouble),
&cx->scriptStackQuota);
JS_InitArenaPool(&cx->regExpPool, "regExp", TEMP_POOL_CHUNK_SIZE, sizeof(int),
&cx->scriptStackQuota);
JS_ASSERT(cx->resolveFlags == 0);
if (!cx->busyArrays.init()) {
FreeContext(cx);
return NULL;
}
#ifdef JS_THREADSAFE
if (!js_InitContextThread(cx)) {
FreeContext(cx);
return NULL;
}
#endif
/*
* Here the GC lock is still held after js_InitContextThread took it and
* the GC is not running on another thread.
*/
for (;;) {
if (rt->state == JSRTS_UP) {
JS_ASSERT(!JS_CLIST_IS_EMPTY(&rt->contextList));
first = JS_FALSE;
break;
}
if (rt->state == JSRTS_DOWN) {
JS_ASSERT(JS_CLIST_IS_EMPTY(&rt->contextList));
first = JS_TRUE;
rt->state = JSRTS_LAUNCHING;
break;
}
JS_WAIT_CONDVAR(rt->stateChange, JS_NO_TIMEOUT);
/*
* During the above wait after we are notified about the state change
* but before we wake up, another thread could enter the GC from
* js_DestroyContext, bug 478336. So we must wait here to ensure that
* when we exit the loop with the first flag set to true, that GC is
* finished.
*/
js_WaitForGC(rt);
}
JS_APPEND_LINK(&cx->link, &rt->contextList);
JS_UNLOCK_GC(rt);
js_InitRandom(cx);
/*
* If cx is the first context on this runtime, initialize well-known atoms,
* keywords, numbers, and strings. If one of these steps should fail, the
* runtime will be left in a partially initialized state, with zeroes and
* nulls stored in the default-initialized remainder of the struct. We'll
* clean the runtime up under js_DestroyContext, because cx will be "last"
* as well as "first".
*/
if (first) {
#ifdef JS_THREADSAFE
JS_BeginRequest(cx);
#endif
ok = js_InitCommonAtoms(cx);
/*
* scriptFilenameTable may be left over from a previous episode of
* non-zero contexts alive in rt, so don't re-init the table if it's
* not necessary.
*/
if (ok && !rt->scriptFilenameTable)
ok = js_InitRuntimeScriptState(rt);
if (ok)
ok = js_InitRuntimeNumberState(cx);
#ifdef JS_THREADSAFE
JS_EndRequest(cx);
#endif
if (!ok) {
js_DestroyContext(cx, JSDCM_NEW_FAILED);
return NULL;
}
AutoLockGC lock(rt);
rt->state = JSRTS_UP;
JS_NOTIFY_ALL_CONDVAR(rt->stateChange);
}
cxCallback = rt->cxCallback;
if (cxCallback && !cxCallback(cx, JSCONTEXT_NEW)) {
js_DestroyContext(cx, JSDCM_NEW_FAILED);
return NULL;
}
return cx;
}
#if defined DEBUG && defined XP_UNIX
# include <stdio.h>
class JSAutoFile {
public:
JSAutoFile() : mFile(NULL) {}
~JSAutoFile() {
if (mFile)
fclose(mFile);
}
FILE *open(const char *fname, const char *mode) {
return mFile = fopen(fname, mode);
}
operator FILE *() {
return mFile;
}
private:
FILE *mFile;
};
static void
DumpEvalCacheMeter(JSContext *cx)
{
if (const char *filename = getenv("JS_EVALCACHE_STATFILE")) {
struct {
const char *name;
ptrdiff_t offset;
} table[] = {
#define frob(x) { #x, offsetof(JSEvalCacheMeter, x) }
EVAL_CACHE_METER_LIST(frob)
#undef frob
};
JSEvalCacheMeter *ecm = &cx->compartment->evalCacheMeter;
static JSAutoFile fp;
if (!fp && !fp.open(filename, "w"))
return;
fprintf(fp, "eval cache meter (%p):\n",
#ifdef JS_THREADSAFE
(void *) cx->thread
#else
(void *) cx->runtime
#endif
);
for (uintN i = 0; i < JS_ARRAY_LENGTH(table); ++i) {
fprintf(fp, "%-8.8s %llu\n",
table[i].name,
(unsigned long long int) *(uint64 *)((uint8 *)ecm + table[i].offset));
}
fprintf(fp, "hit ratio %g%%\n", ecm->hit * 100. / ecm->probe);
fprintf(fp, "avg steps %g\n", double(ecm->step) / ecm->probe);
fflush(fp);
}
}
# define DUMP_EVAL_CACHE_METER(cx) DumpEvalCacheMeter(cx)
static void
DumpFunctionCountMap(const char *title, JSRuntime::FunctionCountMap &map, FILE *fp)
{
fprintf(fp, "\n%s count map:\n", title);
for (JSRuntime::FunctionCountMap::Range r = map.all(); !r.empty(); r.popFront()) {
JSFunction *fun = r.front().key;
int32 count = r.front().value;
fprintf(fp, "%10d %s:%u\n", count, fun->u.i.script->filename, fun->u.i.script->lineno);
}
}
static void
DumpFunctionMeter(JSContext *cx)
{
if (const char *filename = cx->runtime->functionMeterFilename) {
struct {
const char *name;
ptrdiff_t offset;
} table[] = {
#define frob(x) { #x, offsetof(JSFunctionMeter, x) }
FUNCTION_KIND_METER_LIST(frob)
#undef frob
};
JSFunctionMeter *fm = &cx->runtime->functionMeter;
static JSAutoFile fp;
if (!fp && !fp.open(filename, "w"))
return;
fprintf(fp, "function meter (%s):\n", cx->runtime->lastScriptFilename);
for (uintN i = 0; i < JS_ARRAY_LENGTH(table); ++i)
fprintf(fp, "%-19.19s %d\n", table[i].name, *(int32 *)((uint8 *)fm + table[i].offset));
DumpFunctionCountMap("method read barrier", cx->runtime->methodReadBarrierCountMap, fp);
DumpFunctionCountMap("unjoined function", cx->runtime->unjoinedFunctionCountMap, fp);
putc('\n', fp);
fflush(fp);
}
}
# define DUMP_FUNCTION_METER(cx) DumpFunctionMeter(cx)
#endif /* DEBUG && XP_UNIX */
#ifndef DUMP_EVAL_CACHE_METER
# define DUMP_EVAL_CACHE_METER(cx) ((void) 0)
#endif
#ifndef DUMP_FUNCTION_METER
# define DUMP_FUNCTION_METER(cx) ((void) 0)
#endif
void
js_DestroyContext(JSContext *cx, JSDestroyContextMode mode)
{
JSRuntime *rt;
JSContextCallback cxCallback;
JSBool last;
JS_ASSERT(!cx->enumerators);
rt = cx->runtime;
#ifdef JS_THREADSAFE
/*
* For API compatibility we allow to destroy contexts without a thread in
* optimized builds. We assume that the embedding knows that an OOM error
* cannot happen in JS_SetContextThread.
*/
JS_ASSERT(cx->thread && CURRENT_THREAD_IS_ME(cx->thread));
if (!cx->thread)
JS_SetContextThread(cx);
/*
* For API compatibility we support destroying contexts with non-zero
* cx->outstandingRequests but we assume that all JS_BeginRequest calls
* on this cx contributes to cx->thread->data.requestDepth and there is no
* JS_SuspendRequest calls that set aside the counter.
*/
JS_ASSERT(cx->outstandingRequests <= cx->thread->data.requestDepth);
#endif
if (mode != JSDCM_NEW_FAILED) {
cxCallback = rt->cxCallback;
if (cxCallback) {
/*
* JSCONTEXT_DESTROY callback is not allowed to fail and must
* return true.
*/
#ifdef DEBUG
JSBool callbackStatus =
#endif