-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpsee_modules.c
2123 lines (1811 loc) · 70 KB
/
gpsee_modules.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
/* ***** 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 Initial Developer of the Original Code is PageMail, Inc.
*
* Portions created by the Initial Developer are
* Copyright (c) 2007-2010, PageMail, Inc. 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 *****
*/
/**
* @author Wes Garland, PageMail, Inc., wes@page.ca
* @version $Id: gpsee_modules.c,v 1.37 2011/12/05 19:13:36 wes Exp $
* @date March 2009
* @file gpsee_modules.c GPSEE module load, unload, and management code
* for native, script, and blended modules.
*
* <b>C Module API</b>
*
* C modules are indistinguishable from JS modules from the POV of the module consumer, and follow
* the exact loading conventions, etc as CommonJS modules. If a native module and a script module
* both exist for the same require() argument, both will be loaded; the C module will be loaded first,
* and module object it decorates will be passed as the exports object to the script module. This is
* how we create blended modules. (Note that "internal" modules, i.e. those compiled directly into
* libgpsee, do not have a true path and as such cannot collide with script modules)
*
* When a C module is loaded, GPSEE invokes the ModuleName_InitModule function. When the module is unloaded,
* GPSEE invokes the optional ModuleName_FiniModule function. Modules which need to persist private C-visible
* data must use the realm-based storage facility, realm->moduleData, to prevent private data from leaking
* into other realms (e.g. when the module is used by more than one JS_Runtime, thread, sandbox, etc per UNIX
* process). If C private data is used by the module, it is the module's responsibility to clean it up before
* the module is unloaded. Modules which maintain references between JS objects and C private data must
* also tell the garbage collector about these references; this is best done by registering a GC callback
* during InitModule, and cleaning it up during FiniModule. GC callbacks should be registered with the GPSEE
* gpsee_addGCCallback() facility.
*
* Module unloading can be a very tricky operation when the module persists private data. GPSEE may ask to
* unload a module during GC, any time the module's exports or scoping object is not reachable from a GC root.
* The module unloader can run from a JSAPI Finalizer, which means it cannot call back into JS, allocate
* memory, etc. The GPSEE datastore functions are safe to run in a finalizer, as is gpsee_removeGCCallback().
*
* Modules which have JS- or JSAPI-accessible resources that GPSEE is not aware of via the JS object graph can
* return JS_FALSE from FiniModule when the force parameter is JS_TRUE, to indicate that GPSEE should keep the
* module alive, even though it believes the module should be colleted. When GPSEE is shutting down the realm,
* and able to guarantee that no more JS code will execute, it will pass force=JS_TRUE to the ModuleFini
* function. When this happens, the module MUST release all resources and return JS_TRUE.
*
* Examples of JS- or JSAPI-accessible resources that must be cleared by a forced-shutdown:
* - GC callback
* - Context callback
* - Async callback
* - JSObjects which hold pointers to functions inside the module in their private slot
*
***************
*
* <b>Design Notes</b>
*
* Module handles are a private (to this file) data structure which describe everything
* worth knowing about a module -- it's scope (var object), init and fini functions,
* exports object, etc.
*
* Module handles are stored in a splay tree, realm->modules. Splay trees are
* automatically balanced binary search trees that slightly re-balance on
* every read to improve to locality of reference, moving recent search results
* closer to the head.
*
* Extra GC roots, provided by moduleGCCallback(), are available in each
* module handle. They are:
* - exports: Marked during module initialization, afterwards rooted by scope or calling script
* - scrobj: Marked during module initialization, afterwards not needed
* - scope: Marked when object is NULL; otherwise by virtue of object.parent
*
**************
*
* Terminology
*
* moduleScope: Nearly equivalent to the var object of a closure which wraps the module
* parentModule: The module calling require(); usually this is the program module
* exports: An object which holds the return value of parentModule's require() call
* GPSEE module path: The first place non-(internal|relative) modules are searched for; libexec dir etc.
*/
static const char __attribute__((unused)) rcsid[]="$Id: gpsee_modules.c,v 1.37 2011/12/05 19:13:36 wes Exp $:";
#define _GPSEE_INTERNALS
#include "gpsee.h"
#include "gpsee_private.h"
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "./freebsd_tree.h"
#if defined(GPSEE_DEBUG_BUILD)
# define RTLD_mode RTLD_NOW
static int dpDepthSpaces=0;
static const char *spaces(void)
{
static char buf[1024];
memset(buf, 32, dpDepthSpaces * 2);
buf[dpDepthSpaces * 2] = (char)0;
return buf;
}
# define dpDepth(a) do { if (a > 0) dprintf("{\n"); dpDepthSpaces += a; if (a < 0) dprintf("}\n"); } while (0)
# define dprintf(a...) do { if (gpsee_verbosity(0) > GPSEE_MODULE_DEBUG_VERBOSITY) gpsee_printf(cx, "modules\t> %s", spaces()), gpsee_printf(cx, a); } while(0)
# define moduleShortName(a) strstr(a, gpsee_basename(getenv("PWD")?:"trunk")) ?: a
#else
# define RTLD_mode RTLD_LAZY
# define dprintf(a...) while(0) gpsee_printf(cx, a)
# define dpDepth(a) while(0)
# define moduleShortName(a) a
#endif
GPSEE_STATIC_ASSERT(sizeof(void *) >= sizeof(size_t));
extern cfgHnd cfg;
typedef const char * (* moduleInit_fn)(JSContext *, JSObject *); /**< Module initializer function type */
typedef JSBool (* moduleFini_fn)(JSContext *, gpsee_realm_t *, JSObject *, JSBool); /**< Module finisher function type */
typedef struct
{
moduleHandle_t *module;
gpsee_realm_t *realm;
} moduleScopeInfo_t;
/* Generate Init/Fini function prototypes for all internal modules */
#define InternalModule(a) const char *a ## _InitModule(JSContext *, JSObject *);\
JSBool a ## _FiniModule(JSContext *, gpsee_realm_t *, JSObject *, JSBool);
#include "modules.h"
#undef InternalModule
/** Entry in a module path linked list. Completes forward declaration
* found in gpsee.h
*/
struct modulePathEntry
{
const char *dir; /**< Directory to search for modules */
struct modulePathEntry *next; /**< Next element in the list, or NULL for the last */
};
/** Type describing a module loader function pointer. These functions can load and
* initialize a module during loadDiskModule.
*/
typedef JSBool(*moduleLoader_t)(JSContext *, moduleHandle_t *, const char *);
static void finalizeModuleScope(JSContext *cx, JSObject *exports);
static JSBool setModuleScopeInfo(JSContext *cx, gpsee_realm_t *realm, JSObject *moduleScope, moduleHandle_t *module);
static moduleScopeInfo_t *getModuleScopeInfo(JSContext *cx, JSObject *moduleScope);
static void markModuleUnused(JSContext *cx, gpsee_realm_t *realm, moduleHandle_t *module);
/** Module-scope getter which retrieves properties from the true global */
static JSBool getGlobalProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
gpsee_realm_t *realm = gpsee_getRealm(cx);
return realm ? JS_GetPropertyById(cx, realm->globalObject, id, vp) : JS_FALSE;
}
/** Module-scope setter which sets properties on the true global */
static JSBool setGlobalProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
gpsee_realm_t *realm = gpsee_getRealm(cx);
return realm ? JS_SetPropertyById(cx, realm->globalObject, id, vp) : JS_FALSE;
}
/** Module-scope resolver which resolves properties on the scope by looking them
* up on the true global. Any properties which are found are defined on the module
* scope with a setter and getter which look back to the true global.
*/
static JSBool resolveGlobalProperty(JSContext *cx, JSObject *obj, jsval id, uintN flags, JSObject **objp)
{
gpsee_realm_t *realm = gpsee_getRealm(cx);
jsval v;
if (flags & JSRESOLVE_DECLARING) /* Don't walk up scope to global when making new vars */
{
return JS_TRUE;
}
if (!realm || JS_GetPropertyById(cx, realm->globalObject, id, &v) == JS_FALSE)
return JS_FALSE;
if (v == JSVAL_VOID)
return JS_TRUE;
if (JS_DefinePropertyById(cx, obj, id, v, getGlobalProperty, setGlobalProperty, 0) == JS_FALSE)
return JS_FALSE;
/** @todo Add JS_GetPropertyAttributesById() and JS_SetPropertyAttributesById() to JSAPI,
* re-write this block to use them, and eliminate the JSVAL_IS_STRING(id) condition,
* which is actually semantically incorrect but reasonable in practice.
*/
if (JSVAL_IS_STRING(id))
{
char *s = JS_GetStringBytes(JSVAL_TO_STRING(id));
JSBool found;
uintN attrs;
if (JS_GetPropertyAttributes(cx, obj, s, &attrs, &found) == JS_FALSE)
return JS_FALSE;
if (found)
{
if (JS_SetPropertyAttributes(cx, obj, s, attrs, &found) == JS_FALSE)
return JS_FALSE;
GPSEE_ASSERT(found);
}
}
*objp = obj;
return JS_TRUE;
}
static JSClass module_scope_class = /* private member is reserved by gpsee - holds module handle */
{
GPSEE_GLOBAL_NAMESPACE_NAME ".module.Scope",
JSCLASS_HAS_PRIVATE | JSCLASS_GLOBAL_FLAGS | JSCLASS_NEW_RESOLVE,
JS_PropertyStub,
JS_PropertyStub,
JS_PropertyStub,
JS_PropertyStub,
JS_EnumerateStub,
(JSResolveOp)resolveGlobalProperty,
JS_ConvertStub,
finalizeModuleScope,
JSCLASS_NO_OPTIONAL_MEMBERS
};
static JSClass module_exports_class = /* private member - do not touch - for use by native module */
{
GPSEE_GLOBAL_NAMESPACE_NAME ".module.Exports",
JSCLASS_HAS_PRIVATE,
JS_PropertyStub,
JS_PropertyStub,
JS_PropertyStub,
JS_PropertyStub,
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
JS_FinalizeStub,
JSCLASS_NO_OPTIONAL_MEMBERS
};
typedef enum
{
mhf_loaded = 1 << 0, /**< Indicates that the module has been successfully loaded */
} moduleHandle_flags_t;
/** Structure describing a module. Completes forward declaration in gpsee.h */
struct moduleHandle
{
const char *cname; /**< Name of the module; canonical, unique */
void *DSOHnd; /**< Handle to dlopen() shared object for DSO modules */
moduleInit_fn init; /**< Function to run when module done loading */
moduleFini_fn fini; /**< Function to run just before module is unloaded */
JSObject *exports; /**< JavaScript object holding module contents (require/loadModule return).
Private slot reserved for module's use. */
JSObject *scope; /**< Scope object for JavaScript modules; preserved only from load->init */
JSScript *script; /**< Script object for JavaScript modules; preserved only from
load -> JS_ExecuteScript() */
JSObject *scrobj; /**< GC thing for script, used by GC callback */
moduleHandle_flags_t flags; /**< Special attributes of module; bit-field */
int released;
moduleHandle_t *next; /**< Used when treating as a linked list node, i.e. during DSO unload */
SPLAY_ENTRY(moduleHandle) entry; /**< Tree data */
};
/** Compare two module pointers to see if they have the same canonical name */
static int moduleCName_strcmp(struct moduleHandle *module1, struct moduleHandle *module2)
{
return strcmp(module1->cname, module2->cname);
}
/** Declare splay tree support functions for splay tree type moduleMemo */
SPLAY_HEAD(moduleMemo, moduleHandle);
SPLAY_PROTOTYPE(moduleMemo, moduleHandle, entry, moduleCName_strcmp)
SPLAY_GENERATE(moduleMemo, moduleHandle, entry, moduleCName_strcmp)
/**
* requireLock / requireUnlock form a simple re-entrant lockless "mutex", optimized for
* the case where there are no collisions. These locks are per-runtime.
*
* The requireLockThread holds the thread ID of the thread currrently holding this lock, or
* JSVAL_NULL (which is an invalid value for PRThread).
*
* requireLockThread is only read/written via CAS operations, forcing a full memory barrier
* at the start of a locking operation. requireLockDepth may only be read or written by a
* thread which holds the lock. When the lock is released, the cas memory barrier insures
* that the next lock-holder gets an initial depth of zero.
*/
static void requireLock(JSContext *cx)
{
dpDepth(+1);
#if defined(JS_THREADSAFE)
gpsee_runtime_t *grt = JS_GetRuntimePrivate(JS_GetRuntime(cx));
PRThread *thisThread = PR_GetCurrentThread();
if (jsval_CompareAndSwap((jsval *)&grt->requireLockThread, (jsval)thisThread, (jsval)thisThread) == JS_TRUE) /* membar */
goto haveLock;
do
{
jsrefcount depth;
if (jsval_CompareAndSwap((jsval *)&grt->requireLockThread, JSVAL_NULL, (jsval)thisThread) == JS_TRUE)
goto haveLock;
depth = JS_SuspendRequest(cx);
PR_Sleep(PR_INTERVAL_NO_WAIT);
JS_ResumeRequest(cx, depth);
} while(1);
haveLock:
grt->requireLockDepth++;
#endif
return;
}
/**
* @see requireLock()
*/
static void requireUnlock(JSContext *cx)
{
#if defined(JS_THREADSAFE)
gpsee_runtime_t *grt = JS_GetRuntimePrivate(JS_GetRuntime(cx));
PRThread *thisThread = PR_GetCurrentThread();
GPSEE_ASSERT(grt->requireLockDepth);
GPSEE_ASSERT(grt->requireLockThread == thisThread);
grt->requireLockDepth--;
if (grt->requireLockDepth == 0)
{
if (jsval_CompareAndSwap((jsval *)&grt->requireLockThread, (jsval)thisThread, JSVAL_NULL) != JS_TRUE) /* membar */
{
GPSEE_NOT_REACHED("bug in require-locking code");
}
}
#endif
dpDepth(-1);
return;
}
/**
* Create a new module object (exports)
*
* This object is effectively a container for the properties of the module,
* and is what require() returns to the JS programmer.
*
* The exports object will be created with an unused private slot.
* This slot is for use by the module's Fini code, based on data
* the module's Init code puts there.
*
* @param cx The JS context to use
* @param moduleScope The scope for the module we are creating the exports object for.
*
* @return A new, valid, module object or NULL if an exception has been
* thrown.
*
* @note Module object is unrooted, and thus should be assigned to a
* rooted address immediately.
*
*/
static JSObject *newModuleExports(JSContext *cx, JSObject *moduleScope)
{
JSObject *exports;
exports = JS_NewObject(cx, &module_exports_class, NULL, moduleScope);
dprintf("Created new exports at %p for module at scope %p\n", exports, moduleScope);
return exports;
}
/**
* Initialize a "fresh" module scope ("global") to have all the correct properties
* and methods. This includes a require function which "knows" its path information
* by virtue of the module handle stored in reserved slot 0.
*
* If the module global is not the realm's global ("super-global"), we also copy through
* the standard classes.
*
* @param cx Current JavaScript context
* @param module Module handle for the module whose scope we are initializing.
* Handle must remain valid for the lifetime of this scope. Only
* the cname member is used by this function.
* @param moduleScope Scope object to initialize
* @param isVolatileScope If isVolatileScope is JS_TRUE, this module scope will be created
* with "volatile" objects; that is, properties like require, exports,
* and so can be deleted or modified in ways they normally could not.
* This mode allows us to declare a special module scope before the
* program module loads that shares the global object with the program
* module, but has had its module-special properties (like require and
* exports) replaced by the time the program module runs.
*
* @note This function also sets module->exports
*
* @returns JS_TRUE or JS_FALSE if an exception was thrown
*/
static JSBool initializeModuleScope(JSContext *cx, gpsee_realm_t *realm, moduleHandle_t *module, JSObject *moduleScope, JSBool isVolatileScope)
{
JSFunction *require;
JSObject *modDotModObj;
JSString *moduleId;
int jsProp_permanentReadOnly;
int jsProp_permanent;
if (!realm)
return JS_FALSE;
if (isVolatileScope == JS_TRUE)
{
jsProp_permanent = 0;
jsProp_permanentReadOnly = 0;
GPSEE_ASSERT(module != realm->monitored.programModule);
}
else
{
jsProp_permanent = JSPROP_PERMANENT;
jsProp_permanentReadOnly = JSPROP_PERMANENT | JSPROP_READONLY;
}
dprintf("Initializing module scope for module %s at %p\n", moduleShortName(module->cname), module);
dpDepth(+1);
GPSEE_ASSERT(module->exports == NULL || isVolatileScope);
GPSEE_ASSERT(JS_GET_CLASS(cx, moduleScope)->flags & JSCLASS_IS_GLOBAL);
GPSEE_ASSERT(JS_GET_CLASS(cx, moduleScope)->flags & JSCLASS_HAS_PRIVATE);
if (setModuleScopeInfo(cx, realm, moduleScope, module) == JS_FALSE)
return JS_FALSE;
if (moduleScope != realm->globalObject)
{
JSProtoKey key;
/** Get the cached class prototypes sorted out in advance. Not guaranteed tracemonkey-future-proof.
* Almost certainly requires eager standard class initialization on the true global.
*/
for (key = 0; key < JSProto_LIMIT; key++)
{
jsval v;
if (JS_GetReservedSlot(cx, realm->globalObject, key, &v) == JS_FALSE)
return JS_FALSE;
if (JS_SetReservedSlot(cx, moduleScope, key, v) == JS_FALSE)
return JS_FALSE;
}
if (JS_DefineProperty(cx, moduleScope, "undefined", JSVAL_VOID, NULL, NULL,
JSPROP_ENUMERATE | jsProp_permanent) == JS_FALSE)
goto fail;
}
/* Define the basic requirements for what constitutes a CommonJS module:
* - require
* - require.paths
* - exports
* - module.id
*/
require = JS_DefineFunction(cx, moduleScope, "require", gpsee_loadModule, 1, JSPROP_ENUMERATE | jsProp_permanentReadOnly);
if (!require)
goto fail;
if (!realm->userModulePath)
{
/* This is the first module scope we've initialized; set up the storage
* required for the user module path (require.paths). This path is global
* across ALL contexts in the realm.
*/
JS_AddNamedObjectRoot(cx, &realm->userModulePath, "User Module Path");
realm->userModulePath = JS_NewArrayObject(cx, 0, NULL);
if (!realm->userModulePath)
goto fail;
}
if (JS_DefineProperty(cx, (JSObject *)require, "paths",
OBJECT_TO_JSVAL(realm->userModulePath), NULL, NULL,
JSPROP_ENUMERATE | jsProp_permanentReadOnly) != JS_TRUE)
goto fail;
if (JS_SetReservedSlot(cx, (JSObject *)require, 0, PRIVATE_TO_JSVAL(module)) == JS_FALSE)
goto fail;
module->exports = newModuleExports(cx, moduleScope);
if (JS_DefineProperty(cx, moduleScope, "exports",
OBJECT_TO_JSVAL(module->exports), NULL, NULL,
JSPROP_ENUMERATE | jsProp_permanentReadOnly) != JS_TRUE)
goto fail;
modDotModObj = JS_NewObject(cx, realm->moduleObjectClass, realm->moduleObjectProto, moduleScope);
if (!modDotModObj)
goto fail;
if (module == realm->monitored.programModule)
realm->requireDotMain = modDotModObj;
if (JS_DefineProperty(cx, (JSObject *)require, "main",
OBJECT_TO_JSVAL(realm->requireDotMain), NULL, NULL,
JSPROP_ENUMERATE | jsProp_permanentReadOnly) != JS_TRUE)
goto fail;
if (JS_DefineProperty(cx, moduleScope, "module", OBJECT_TO_JSVAL(modDotModObj), NULL, NULL,
JSPROP_ENUMERATE | jsProp_permanentReadOnly) == JS_FALSE)
goto fail;
/* Add 'id' property to 'module' property of module scope. */
moduleId = JS_NewStringCopyZ(cx, module->cname);
if (!moduleId)
goto fail;
if (JS_DefineProperty(cx, modDotModObj, "id", STRING_TO_JSVAL(moduleId), NULL, NULL,
JSPROP_ENUMERATE | jsProp_permanentReadOnly) == JS_FALSE)
goto fail;
dpDepth(-1);
return JS_TRUE;
fail:
dpDepth(-1);
return JS_FALSE;
}
/**
* Create an object to act as the global object for the module. The module's
* exports object will be a property of this object, along with
* module-scope variables.
*
* The private slot for this object is reserved for (and contains) the module handle.
*
* @param cx JavaScript context in the current realm
* @param realm The GPSEE Realm in which to create the module scope
* @param module The handle describing the module we are building
* @returns NULL on failure, or an object which is in unrooted
* but in the recently-created slot.
*/
static JSObject *newModuleScope(JSContext *cx, gpsee_realm_t *realm, moduleHandle_t *module)
{
JSObject *moduleScope;
GPSEE_ASSERT(module);
if (!realm || JS_EnterLocalRootScope(cx) != JS_TRUE)
return NULL;
dpDepth(+1);
moduleScope = JS_NewGlobalObject(cx, &module_scope_class);
if (!moduleScope)
goto fail;
if (JS_SetParent(cx, moduleScope, JS_GetParent(cx, realm->globalObject)) == JS_FALSE)
goto fail;
if (initializeModuleScope(cx, realm, module, moduleScope, JS_FALSE) == JS_FALSE)
goto fail;
JS_LeaveLocalRootScopeWithResult(cx, OBJECT_TO_JSVAL(moduleScope));
dpDepth(-1);
return moduleScope;
fail:
JS_LeaveLocalRootScope(cx);
dpDepth(-1);
return NULL;
}
static moduleHandle_t *findModuleHandle(gpsee_realm_t *realm, const char *cname)
{
moduleHandle_t tmp;
tmp.cname = cname;
return SPLAY_FIND(moduleMemo, realm->modules, &tmp);
}
/** Find existing or create new module handle.
*
* Module handles are used to
* - track shutdown requirements over the lifetime of the realm
* - track module objects so they don't get garbage collected
*
* Any module handle returned from this routine is guaranteed to have a cname, so that it
* can be identified.
*
* @param cx JavaScript context in the current realm
* @param realm The GPSEE realm in which to acquire the module handle
* @param cname Canonical name of the module we're interested in; may contain slashses, relative ..s etc,
* or name an internal module.
* @param moduleScope Scope object to be used instead of a brand-new one if we need to create a module handle.
* @returns A module handle, possibly one already initialized, or NULL if an exception has been thrown.
*/
static moduleHandle_t *acquireModuleHandle(JSContext *cx, gpsee_realm_t *realm, const char *cname, JSObject *moduleScope)
{
moduleHandle_t *module = NULL;
GPSEE_ASSERT(cname != NULL);
dprintf("Acquiring module handle for %s\n", cname);
dpDepth(+1);
if (!realm)
goto fail;
module = findModuleHandle(realm, cname);
if (module)
{
dprintf("Returning used module handle at %p with scope %p and exports %p\n", module, module->scope, module->exports);
goto success; /* seen this one already */
}
module = calloc(sizeof *module, 1);
if (!module)
{
JS_ReportOutOfMemory(cx);
goto fail;
}
dprintf("Allocated new module node for %s in memo tree at 0x%p\n",
cname ? moduleShortName(cname) : "program module", module);
module->cname = JS_strdup(cx, cname);
if (!moduleScope)
{
dprintf("Creating new module scope\n");
module->scope = newModuleScope(cx, realm, module);
if (!module->scope)
{
dprintf("Could not create new module scope\n");
goto fail;
}
}
else
{
dprintf("Using module scope at %p\n", moduleScope);
module->scope = moduleScope;
GPSEE_ASSERT(module->scope);
}
SPLAY_INSERT(moduleMemo, realm->modules, module); /* module->scope becomes a root here */
dprintf("Memoized module at %p with scope %p\n", module, module->scope);
success:
dpDepth(-1);
dprintf("Module handle is at %p\n", module);
return module;
fail:
dpDepth(-1);
if (module)
markModuleUnused(cx, realm, module);
return NULL;
}
/** Marking a module unused makes it eligible for immediate garbage
* collection. Safe to call from a finalizer.
*/
static void markModuleUnused(JSContext *cx, gpsee_realm_t *realm, moduleHandle_t *module)
{
dpDepth(+1);
dprintf("Marking module at %p (%s) as unused\n", module, module->cname?:"no name");
if (module->flags & mhf_loaded && module->exports && module->fini)
if (module->fini(cx, realm, module->exports, JS_TRUE) == JS_TRUE)
module->fini = NULL;
module->scope = NULL;
module->scrobj = NULL;
module->exports = NULL;
module->flags &= ~mhf_loaded;
dpDepth(-1);
}
/**
* Return resources used by a module handle to the OS or other
* underlying allocator.
*
* This routine is intended be called from the garbage collector
* callback after all finalizable JS gcthings have been finalized.
* This is because some of those gcthings might need C resources
* for finalization. The canonical example is that finalizing a
* prototype object for a class which has its clasp in a DSO. It
* is imperative that the DSO stay around until AFTER the prototype
* is finalized, but there is no direct way to know that since
* finalization order is random.
*
* @param cx JavaScript context
* @param module Module handle to destroy'
* @returns module->next
*/
static moduleHandle_t *destroyModuleHandle(JSContext *cx, moduleHandle_t *module)
{
moduleHandle_t *next = module->next;
dprintf("Destroyinging module handle at 0x%p (%s)\n", module, moduleShortName(module->cname));
if (module->cname)
{
#if defined(GPSEE_DEBUG_BUILD)
memset((char *)module->cname, 0xbb, strlen(module->cname));
#endif
JS_free(cx, (char *)module->cname);
}
if (module->DSOHnd)
{
dpDepth(+1);
dprintf("unloading DSO at 0x%p for module 0x%p\n", module->DSOHnd, module);
dpDepth(-1);
dlclose(module->DSOHnd);
}
#if defined(GPSEE_DEBUG_BUILD)
memset(module, 0xba, sizeof(*module));
#endif
free(module);
return next;
}
/**
* Release all resources allocated during the creation of the handle,
* including the handle itself.
*
* Note that "release" in this case means "schedule for finalization";
* the finalization actually returns the resources to the OS or other
* underlying resources allocators.
*
* This routine should only be called from the scope finalizer. Once
* a module has been 'released', it is removed from the realm->modules
* memo, meaning that reloading the same module will result in a new
* instance even if the module handle has not yet been finalized.
*
* Once the module is out of the realm->modules memo, it is inserted
* into the realm->unreachableModules_llist linked list. This list is
* traversed at the very end of the garbaged collector cycle,
* finalizing all modules handles in the list as it prunes the list.
* This two-phase garbage collection process is necessary because
* the code to finalize the module scope may in fact get dlclose()d
* during finalization of the module handle.
*
* @param cx JavaScript context handle
* @param module Handle to destroy
*/
static void releaseModuleHandle(JSContext *cx, gpsee_realm_t *realm, moduleHandle_t *module)
{
dprintf("Releasing module at 0x%p\n", module);
if (module->released)
return;
else
module->released = 1;
SPLAY_REMOVE(moduleMemo, realm->modules, module);
markModuleUnused(cx, realm, module);
/* Actually release OS resources after everything on JS
* side has been finalized. This is especially important
* for DSO modules, as dlclosing() before JS object finalizer
* has read clasp is disastrous
*/
module->next = realm->unreachableModule_llist;
realm->unreachableModule_llist = module;
}
/**
* Retrieve the module handle associated with the scope.
* Safe to run in a finalizer.
*/
static moduleScopeInfo_t *getModuleScopeInfo(JSContext *cx, JSObject *moduleScope)
{
dprintf("Retrieving info for module with scope 0x%p\n", moduleScope);
GPSEE_ASSERT(JS_GET_CLASS(cx, moduleScope) == &module_scope_class || JS_GET_CLASS(cx, moduleScope) == gpsee_getGlobalClass());
return JS_GetPrivate(cx, moduleScope);
}
/**
* Note the module handle associated with the scope.
* Safe to run in a finalizer.
*/
static JSBool setModuleScopeInfo(JSContext *cx, gpsee_realm_t *realm, JSObject *moduleScope, moduleHandle_t *module)
{
moduleScopeInfo_t *hnd;
dprintf("Noting module with scope 0x%p\n", moduleScope);
GPSEE_ASSERT(JS_GET_CLASS(cx, moduleScope) == &module_scope_class || JS_GET_CLASS(cx, moduleScope) == gpsee_getGlobalClass());
hnd = JS_malloc(cx, sizeof(*hnd));
if (!hnd)
return JS_FALSE;
memset(hnd, 0, sizeof(*hnd));
hnd->module = module;
hnd->realm = realm;
JS_SetPrivate(cx, moduleScope, hnd);
return JS_TRUE;
}
/**
* Attempt to extract the current GPSEE realm from the given moduleScope.
* Passing NULL for the moduleScope instructs this function to use
* the context's current global object. This function will not cause
* a JS exception to be thrown. The current global object is normally the module's
* scope during module load/initialization, and the program module's scope
* otherwise.
*
* @param cx The current JS context (belonging to the current realm)
* @param moduleScope The scope to search for the realm in, or NULL to select the global object.
* @returns The realm or NUL.
*
* @note This routine is called by gpsee_getRealm().
*/
gpsee_realm_t *gpsee_getModuleScopeRealm(JSContext *cx, JSObject *moduleScope)
{
moduleScopeInfo_t *hnd;
JSClass *class;
if (!moduleScope)
moduleScope = JS_GetGlobalObject(cx);
if (!moduleScope)
return NULL;
class = JS_GET_CLASS(cx, moduleScope);
if (class != &module_scope_class && class != gpsee_getGlobalClass())
return NULL;
hnd = JS_GetPrivate(cx, moduleScope);
if (!hnd)
return NULL;
return hnd->realm;
}
static void finalizeModuleScope(JSContext *cx, JSObject *moduleScope)
{
moduleScopeInfo_t *hnd;
dprintf("begin finalizing module scope\n");
dpDepth(+1);
hnd = getModuleScopeInfo(cx, moduleScope);
if (!hnd)
{
dpDepth(-1);
dprintf("scope is already final\n");
return;
}
GPSEE_ASSERT(hnd->module);
GPSEE_ASSERT(hnd->module->fini == NULL); /* Should not be finalizing if fini handler is unrun */
dprintf("module is %s, %p\n", moduleShortName(hnd->module->cname), hnd->module);
releaseModuleHandle(cx, hnd->realm, hnd->module);
#if defined(GPSEE_DEBUG_BUILD)
memset(hnd, 0xbc, sizeof(*hnd));
#endif
JS_free(cx, hnd);
dpDepth(-1);
dprintf("done finalizing module scope\n");
}
/**
* Load a JavaScript-language module. These modules conform to the ServerJS Securable Modules
* proposal at https://wiki.mozilla.org/ServerJS/Modules/SecurableModules.
*
* Namely,
* - JS is executed in a non-global scope
* - JS modifies "exports" object in that scope
* - Exports object is in fact module->exports
*
* @param cx JS Context
* @param module Pre-populated moduleHandle
* @param filename Fully-qualified path to the file to load
*
* @returns JSBool
*/
static JSBool loadJSModule(JSContext *cx, moduleHandle_t *module, const char *filename)
{
dprintf("loadJSModule(\"%s\")\n", filename);
dpDepth(+1);
if (!gpsee_compileScript(cx, filename, NULL, NULL, &module->script,
module->scope, &module->scrobj))
{
dprintf("module %s compilation failed\n", moduleShortName(filename));
dpDepth(-1);
return JS_FALSE;
}
dprintf("module %s compiled okay\n", moduleShortName(filename));
dpDepth(-1);
return JS_TRUE;
}
/**
* Load a DSO module. These modules are linked in at run-time, so we compute the
* addresses of the symbols with dlsym().
*
* @param cx JS Context
* @returns JSBool
*/
static JSBool loadDSOModule(JSContext *cx, moduleHandle_t *module, const char *filename)
{
jsrefcount depth;
depth = JS_SuspendRequest(cx);
module->DSOHnd = dlopen(filename, RTLD_mode);
JS_ResumeRequest(cx, depth);
if (!module->DSOHnd)
{
return gpsee_throw(cx, "dlopen() error: %s", dlerror());
}
else
{
char symbol[strlen(module->cname) + 11 + 1];
const char *bname = gpsee_basename(module->cname);
sprintf(symbol, "%s_InitModule", bname);
module->init = dlsym(module->DSOHnd, symbol);
sprintf(symbol, "%s_FiniModule", bname);
module->fini = dlsym(module->DSOHnd, symbol);
}
return JS_TRUE;
}
/** Check to insure a full path is a child of a jail path.
* @param fullPath The full path we're checking
* @param jailpath The jail path we're checking against, or NULL for "anything goes".
* @returns fullPath if the path is inside the jail; NULL otherwise.
*/
static const char *checkJail(const char *fullPath, const char *jailPath)
{
size_t jailLen = jailPath ? strlen(jailPath) : 0;
if (!jailPath)
return fullPath;
if ((strncmp(fullPath, jailPath, jailLen) != 0) || fullPath[jailLen] != '/')
return NULL;
return fullPath;
}
static int isRelativePath(const char *path)
{
if (path[0] != '.')
return 0;
if (path[1] == '/')
return 1;
if ((path[1] == '.') && (path[2] == '/'))
return 1;
return 0;
}
/**
* Turn a JavaScript array in a module path linked list.
*
* @param cx Current JavaScript context
* @param obj Scope-Object containing the array (e.g. global)