Oolite
Loading...
Searching...
No Matches
OOJSScript.m
Go to the documentation of this file.
1/*
2
3OOJSScript.m (QuickJS-ng)
4
5JavaScript support for Oolite
6Copyright (C) 2007-2013 David Taylor and Jens Ayton.
7
8This program is free software; you can redistribute it and/or
9modify it under the terms of the GNU General Public License
10as published by the Free Software Foundation; either version 2
11of the License, or (at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21MA 02110-1301, USA.
22
23*/
24
25#ifndef OO_CACHE_JS_SCRIPTS
26#define OO_CACHE_JS_SCRIPTS 1
27#endif
28
29#import "OOJSScript.h"
32
33#import "Entity.h"
37#if OO_CACHE_JS_SCRIPTS
38#import "OOCacheManager.h"
39#endif
40#import "OOConstToJSString.h"
41#import "OOConstToString.h"
42#import "OODebugStandards.h"
43#import "OOLogging.h"
45#import "OOPListParsing.h"
46
47typedef struct RunningStack RunningStack;
48struct RunningStack {
51};
52
53static JSClassID sScriptClassID;
55
56static void AddStackToArrayReversed(NSMutableArray* array, RunningStack* stack);
57
58static BOOL RunScriptWithName(JSContext* context, NSString* path, JSValueConst object, NSString** outErrorMessage);
59
60static NSString* StrippedName(NSString* string);
61static NSString* RewriteLegacyConst(JSContext* context, NSString* source);
62static BOOL HasModernScopeDirective(NSString* source);
63
64#if OO_CACHE_JS_SCRIPTS
65static JSValue CachedCompiledScript(JSContext* context, NSString* path, NSData* source);
66static void CacheCompiledScript(JSContext* context, NSString* path, NSData* source, JSValueConst compiled);
67#endif
68
69static JSClassDef sScriptClass = {
70 .class_name = "Script",
71 .finalizer = OOJSObjectWrapperFinalize,
72};
73
74static const JSCFunctionListEntry sScriptMethods[] = {
75 // JS name, min args, function
76 JS_CFUNC_DEF("toString", 0, OOJSObjectWrapperToString),
77};
78
79@interface OOJSScript (OOPrivate)
80
81- (NSString*)scriptNameFromPath:(NSString*)path;
82- (NSDictionary*)defaultPropertiesFromPath:(NSString*)path;
83- (void)checkForTickle:(JSContext*)context;
84
85@end
86
87@implementation OOJSScript
88
89+ (id)scriptWithPath:(NSString*)path properties:(NSDictionary*)properties
90{
91 return [[[self alloc] initWithPath:path properties:properties] autorelease];
92}
93
94- (id)initWithPath:(NSString*)path properties:(NSDictionary*)properties
95{
96 JSContext* context = NULL;
97 NSString* problem = nil; // Acts as error flag.
98 NSString* key = nil;
99 id property = nil;
100
101 self = [super init];
102 if (self == nil)
103 problem = @"allocation failure";
104 else {
105 context = OOJSAcquireContext();
106
107 if (JS_HasException(context)) {
108 JS_FreeValue(context, JS_GetException(context));
109 OOLogERR(@"script.javaScript.load.waitingException", @"Prior to loading script %@, there was a pending JavaScript exception, which has been cleared. This is an internal error, please report it.", path);
110 }
111
112 // Set up JS object
113 if (!problem) {
114 _jsSelf = JS_NewObjectClass(context, (int)sScriptClassID);
115 if (JS_IsException(_jsSelf)) {
116 JS_FreeValue(context, JS_GetException(context));
117 _jsSelf = JS_UNDEFINED;
118 problem = @"allocation failure";
119 }
120 }
121
122 if (!problem) {
123 JS_SetOpaque(_jsSelf, OOConsumeReference([self weakRetain]));
124 }
125
126 // Push self on stack of running scripts.
127 RunningStack stackElement = {
128 .back = sRunningStack,
129 .current = self
130 };
131 sRunningStack = &stackElement;
132
133 filePath = [path retain];
134
135 // Set default properties from manifest.plist
136 NSDictionary* defaultProperties = [self defaultPropertiesFromPath:path];
137 foreachkey(key, defaultProperties)
138 {
139 if ([key isKindOfClass:[NSString class]]) {
140 property = [defaultProperties objectForKey:key];
141 if ([key isEqualToString:kLocalManifestProperty]) {
142 // this must not be editable
143 [self defineProperty:property named:key];
144 } else {
145 // can be overwritten by script itself
146 [self setProperty:property named:key];
147 }
148 }
149 }
150
151 // Set properties. (read-only)
152 if (!problem && properties != nil) {
153 foreachkey(key, properties)
154 {
155 if ([key isKindOfClass:[NSString class]]) {
156 property = [properties objectForKey:key];
157 [self defineProperty:property named:key];
158 }
159 }
160 }
161
162 /* Set initial name (in case of script error during initial run).
163 The "name" ivar is not set here, so the property can be fetched from JS
164 if we fail during setup. However, the "name" ivar is set later so that
165 the script object can't be renamed after the initial run. This could
166 probably also be achieved by fiddling with JS property attributes.
167 */
168 JSAtom nameID = OOJSID("name");
169 [self setProperty:[self scriptNameFromPath:path] withID:nameID inContext:context];
170
171 // Run the script (allowing it to set up the properties we need, as well as setting up those event handlers)
172 if (!problem) {
173 OOLog(@"script.javaScript.willLoad", @"About to load JavaScript %@", path);
174 OOLogIndentIf(@"script.javaScript.willLoad");
175
176 if (!RunScriptWithName(context, path, _jsSelf, &problem)) {
177 if (problem == nil)
178 problem = @"could not run script";
179 }
180 }
181
182 sRunningStack = stackElement.back;
183
184 if (!problem) {
185 [self checkForTickle:context];
186
187 // Get display attributes from script
188 DESTROY(name);
189 name = [StrippedName([[self propertyWithID:nameID inContext:context] description]) copy];
190 if (name == nil) {
191 name = [[self scriptNameFromPath:path] retain];
192 [self setProperty:name withID:nameID inContext:context];
193 }
194
195 version = [[[self propertyWithID:OOJSID("version") inContext:context] description] copy];
196 description = [[[self propertyWithID:OOJSID("description") inContext:context] description] copy];
197
198 OOLog(@"script.javaScript.load.success", @"Loaded JavaScript: %@ -- %@", [self displayName], description ? description : (NSString*)@"(no description)");
199 }
200
201 OOLogOutdentIf(@"script.javaScript.willLoad");
202
203 DESTROY(filePath); // Only used for error reporting during startup.
204 }
205
206 if (problem) {
207 OOLog(@"script.javaScript.load.failed", @"***** Error loading JavaScript script %@ -- %@", path, problem);
208 if (context != NULL && JS_HasException(context))
210 DESTROY(self);
211 }
212
213 OOJSRelinquishContext(context);
214
215 if (self != nil) {
216 [[NSNotificationCenter defaultCenter] addObserver:self
217 selector:@selector(javaScriptEngineWillReset:)
218 name:kOOJavaScriptEngineWillResetNotification
220 }
221
222 return self;
223}
224
225- (void)dealloc
226{
227 [[NSNotificationCenter defaultCenter] removeObserver:self
228 name:kOOJavaScriptEngineWillResetNotification
230
231 DESTROY(name);
232 DESTROY(description);
233 DESTROY(version);
234 DESTROY(filePath);
235
236 if (JS_IsObject(_jsSelf)) {
237 JSContext* context = OOJSAcquireContext();
238
239 // Release weakref to self, as the finalizer would; the JS object may outlive us.
240 JSClassID ignored;
241 [(id)JS_GetAnyOpaque(_jsSelf, &ignored) release];
242 JS_SetOpaque(_jsSelf, NULL);
243 JS_FreeValue(context, _jsSelf);
244 _jsSelf = JS_UNDEFINED;
245
246 OOJSRelinquishContext(context);
247 }
248
249 [weakSelf weakRefDrop];
250
251 [super dealloc];
252}
253
254- (NSString*)oo_jsClassName
255{
256 return @"Script";
257}
258
259- (NSString*)descriptionComponents
260{
261 if (JS_IsObject(_jsSelf))
262 return [super descriptionComponents];
263 else
264 return @"invalid script";
265}
266
267- (void)javaScriptEngineWillReset:(NSNotification*)notification
268{
269 // All scripts become invalid when the JS engine resets.
270 if (JS_IsObject(_jsSelf)) {
271 JS_FreeValue(OOJSAcquireContext(), _jsSelf);
272 _jsSelf = JS_UNDEFINED;
273 }
274}
275
276+ (OOJSScript*)currentlyRunningScript
277{
278 if (sRunningStack == NULL)
279 return NULL;
280 return sRunningStack->current;
281}
282
283+ (NSArray*)scriptStack
284{
285 NSMutableArray* result = nil;
286
287 result = [NSMutableArray array];
289 return result;
290}
291
292- (id)weakRetain
293{
294 if (weakSelf == nil)
295 weakSelf = [OOWeakReference weakRefWithObject:self];
296 return [weakSelf retain];
297}
298
299- (void)weakRefDied:(OOWeakReference*)weakRef
300{
301 if (weakRef == weakSelf)
302 weakSelf = nil;
303}
304
305- (NSString*)name
306{
307 if (name == nil)
308 name = [[self propertyNamed:@"name"] copy];
309 if (name == nil)
310 return [self scriptNameFromPath:filePath]; // Special case for parse errors during load.
311 return name;
312}
313
314- (NSString*)scriptDescription
315{
316 return description;
317}
318
319- (NSString*)version
320{
321 return version;
322}
323
324- (void)runWithTarget:(Entity*)target
325{
326}
327
328- (BOOL)callMethod:(JSAtom)methodID
329 inContext:(JSContext*)context
330 withArguments:(JSValueConst*)argv
331 count:(int)argc
332 result:(JSValue*)outResult
333{
334 NSParameterAssert(name != NULL && (argv != NULL || argc == 0) && context != NULL);
335 if (outResult != NULL)
336 *outResult = JS_UNDEFINED;
337 if (!JS_IsObject(_jsSelf))
338 return NO;
339
340 BOOL OK = NO;
341
342 JSValue method = JS_GetProperty(context, _jsSelf, methodID);
343 if (EXPECT_NOT(JS_IsException(method))) {
345 return NO;
346 }
347
348 if (EXPECT(!JS_IsUndefined(method))) {
349#ifndef NDEBUG
350 if (JS_HasException(context)) {
351 OOLog(@"script.internalBug", @"Exception pending on context before calling method in %s, clearing. This is an internal error, please report it.", __PRETTY_FUNCTION__);
352 JS_FreeValue(context, JS_GetException(context));
353 }
354
355 OOLog(@"script.javaScript.call", @"Calling [%@].%@()", [self name], OOStringFromJSID(methodID));
356 OOLogIndentIf(@"script.javaScript.call");
357#endif
358
359 // Push self on stack of running scripts.
360 RunningStack stackElement = {
361 .back = sRunningStack,
362 .current = self
363 };
364 sRunningStack = &stackElement;
365
366 // Call the method.
368 JSValue result = JS_Call(context, method, _jsSelf, argc, argv);
370
371 if (JS_IsException(result)) {
373 OK = NO;
374 } else {
375 OK = YES;
376 if (outResult != NULL)
377 *outResult = result;
378 else
379 JS_FreeValue(context, result);
380 }
381
382 // Pop running scripts stack
383 sRunningStack = stackElement.back;
384
385#ifndef NDEBUG
386 OOLogOutdentIf(@"script.javaScript.call");
387#endif
388 }
389
390 JS_FreeValue(context, method);
391 return OK;
392}
393
394- (id)propertyWithID:(JSAtom)propID inContext:(JSContext*)context
395{
396 NSParameterAssert(context != NULL);
397 if (!JS_IsObject(_jsSelf))
398 return nil;
399
400 JSValue jsValue = JS_GetProperty(context, _jsSelf, propID);
401 if (JS_IsException(jsValue)) {
402 JS_FreeValue(context, JS_GetException(context));
403 return nil;
404 }
405
406 id result = OOJSNativeObjectFromJSValue(context, jsValue);
407 JS_FreeValue(context, jsValue);
408 return result;
409}
410
411- (BOOL)setProperty:(id)value withID:(JSAtom)propID inContext:(JSContext*)context
412{
413 NSParameterAssert(context != NULL);
414 if (!JS_IsObject(_jsSelf))
415 return NO;
416
417 // JS_SetProperty() takes ownership of the value.
418 return JS_SetProperty(context, _jsSelf, propID, OOJSValueFromNativeObject(context, value)) >= 0;
419}
420
421- (BOOL)defineProperty:(id)value withID:(JSAtom)propID inContext:(JSContext*)context
422{
423 NSParameterAssert(context != NULL);
424 if (!JS_IsObject(_jsSelf))
425 return NO;
426
427 // JS_DefinePropertyValue() takes ownership of the value.
428 return JS_DefinePropertyValue(context, _jsSelf, propID, OOJSValueFromNativeObject(context, value), OOJS_PROP_READONLY) >= 0;
429}
430
431- (id)propertyNamed:(NSString*)propName
432{
433 if (propName == nil)
434 return nil;
435 if (!JS_IsObject(_jsSelf))
436 return nil;
437
438 JSContext* context = OOJSAcquireContext();
439 id result = [self propertyWithID:OOJSIDFromString(propName) inContext:context];
440 OOJSRelinquishContext(context);
441
442 return result;
443}
444
445- (BOOL)setProperty:(id)value named:(NSString*)propName
446{
447 if (value == nil || propName == nil)
448 return NO;
449 if (!JS_IsObject(_jsSelf))
450 return NO;
451
452 JSContext* context = OOJSAcquireContext();
453 BOOL result = [self setProperty:value withID:OOJSIDFromString(propName) inContext:context];
454 OOJSRelinquishContext(context);
455
456 return result;
457}
458
459- (BOOL)defineProperty:(id)value named:(NSString*)propName
460{
461 if (value == nil || propName == nil)
462 return NO;
463 if (!JS_IsObject(_jsSelf))
464 return NO;
465
466 JSContext* context = OOJSAcquireContext();
467 BOOL result = [self defineProperty:value withID:OOJSIDFromString(propName) inContext:context];
468 OOJSRelinquishContext(context);
469
470 return result;
471}
472
473- (JSValue)oo_jsValueInContext:(JSContext*)context
474{
475 if (!JS_IsObject(_jsSelf))
476 return JS_UNDEFINED;
477 return JS_DupValue(context, _jsSelf);
478}
479
480+ (void)pushScript:(OOJSScript*)script
481{
482 RunningStack* element = NULL;
483
484 element = malloc(sizeof *element);
485 if (element == NULL)
486 exit(EXIT_FAILURE);
487
488 element->back = sRunningStack;
489 element->current = script;
490 sRunningStack = element;
491}
492
493+ (void)popScript:(OOJSScript*)script
494{
495 RunningStack* element = NULL;
496
497 assert(sRunningStack->current == script);
498
499 element = sRunningStack;
501 free(element);
502}
503
504@end
505
506@implementation OOJSScript (OOPrivate)
507
508/* Generate default name for script which doesn't set its name property when
509 first run.
510
511 The generated name is <name>.anon-script, where <name> is selected as
512 follows:
513 * If path is nil (futureproofing), use the address of the script object.
514 * If the file's name is something other than script.*, use the file name.
515 * If the containing directory is something other than Config, use the
516 containing directory's name.
517 * Otherwise, use the containing directory's parent (which will generally
518 be an OXP root directory).
519 * If either of the two previous steps results in an empty string, fall
520 back on the full path.
521*/
522- (NSString*)scriptNameFromPath:(NSString*)path
523{
524 NSString* lastComponent = nil;
525 NSString* truncatedPath = nil;
526 NSString* theName = nil;
527
528 if (path == nil)
529 theName = [NSString stringWithFormat:@"%p", self];
530 else {
531 lastComponent = [path lastPathComponent];
532 if (![lastComponent hasPrefix:@"script."])
533 theName = lastComponent;
534 else {
535 truncatedPath = [path stringByDeletingLastPathComponent];
536 if (NSOrderedSame == [[truncatedPath lastPathComponent] caseInsensitiveCompare:@"Config"]) {
537 truncatedPath = [truncatedPath stringByDeletingLastPathComponent];
538 }
539 if (NSOrderedSame == [[truncatedPath pathExtension] caseInsensitiveCompare:@"oxp"]) {
540 truncatedPath = [truncatedPath stringByDeletingPathExtension];
541 }
542
543 lastComponent = [truncatedPath lastPathComponent];
544 theName = lastComponent;
545 }
546 }
547
548 if (0 == [theName length])
549 theName = path;
550
551 return StrippedName([theName stringByAppendingString:@".anon-script"]);
552}
553
554- (NSDictionary*)defaultPropertiesFromPath:(NSString*)path
555{
556 // remove file name, remove OXP subfolder, add manifest.plist
557 NSString* manifestPath = [[[path stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"manifest.plist"];
558 NSDictionary* manifest = OODictionaryFromFile(manifestPath);
559 NSMutableDictionary* properties = [NSMutableDictionary dictionaryWithCapacity:3];
560 /* __oolite.tmp.* is allocated for OXPs without manifests. Its
561 * values are meaningless and shouldn't be used here */
562 if (manifest != nil && ![[manifest oo_stringForKey:kOOManifestIdentifier] hasPrefix:@"__oolite.tmp."]) {
563 if ([manifest objectForKey:kOOManifestVersion] != nil) {
564 [properties setObject:[manifest oo_stringForKey:kOOManifestVersion] forKey:@"version"];
565 }
566 if ([manifest objectForKey:kOOManifestIdentifier] != nil) {
567 // used for system info
568 [properties setObject:[manifest oo_stringForKey:kOOManifestIdentifier] forKey:kLocalManifestProperty];
569 }
570 if ([manifest objectForKey:kOOManifestAuthor] != nil) {
571 [properties setObject:[manifest oo_stringForKey:kOOManifestAuthor] forKey:@"author"];
572 }
573 if ([manifest objectForKey:kOOManifestLicense] != nil) {
574 [properties setObject:[manifest oo_stringForKey:kOOManifestLicense] forKey:@"license"];
575 }
576 }
577 return properties;
578}
579
580/* Complain about scripts using the tickle event handler. SpiderMonkey
581 reported this from the class's addProperty hook; QuickJS has no such
582 hook, so check once the script's top level has run (which is where
583 handlers are normally defined).
584*/
585- (void)checkForTickle:(JSContext*)context
586{
587 JSValue tickle = JS_GetPropertyStr(context, _jsSelf, "tickle");
588 if (JS_IsException(tickle)) {
589 JS_FreeValue(context, JS_GetException(context));
590 } else if (!JS_IsUndefined(tickle)) {
591 OOJSReportWarning(context, @"Script %@ appears to use the tickle() event handler, which is no longer supported.", [self name]);
592 }
593 JS_FreeValue(context, tickle);
594}
595
596@end
597
598@implementation OOScript (JavaScriptEvents)
599
600- (BOOL)callMethod:(JSAtom)methodID
601 inContext:(JSContext*)context
602 withArguments:(JSValueConst*)argv
603 count:(int)argc
604 result:(JSValue*)outResult
605{
606 if (outResult != NULL)
607 *outResult = JS_UNDEFINED;
608 return NO;
609}
610
611@end
612
619
620static void AddStackToArrayReversed(NSMutableArray* array, RunningStack* stack)
621{
622 if (stack != NULL) {
623 AddStackToArrayReversed(array, stack->back);
624 [array addObject:stack->current];
625 }
626}
627
628/* Compiled scripts by path, kept for the session, so a script loaded for
629 every ship (ship scripts and AIs) is read and compiled only once, as
630 SpiderMonkey's compiled script cache did. Each load runs a new closure
631 of the shared bytecode, so script objects still don't share state.
632*/
633static NSMutableDictionary* sCompiledScripts = nil;
634
635static JSValue CompileScriptWithName(JSContext* context, NSString* path, NSString** outErrorMessage);
636
637void OOJSScriptDestroyCompiledScripts(JSContext* context)
638{
639 NSValue* held = nil;
640 foreach (held, [sCompiledScripts allValues]) {
641 JSValue compiled;
642 [held getValue:&compiled];
643 JS_FreeValue(context, compiled);
644 }
646}
647
648/* Compile (or reuse) and run a script file with object as its this and,
649 unless the script opts out with the "use oolite modern" directive, at the
650 head of its scope chain.
651*/
652static BOOL RunScriptWithName(JSContext* context, NSString* path, JSValueConst object, NSString** outErrorMessage)
653{
654 NSCParameterAssert(outErrorMessage != NULL);
655 *outErrorMessage = nil;
656
657 JSValue compiled;
658 NSValue* held = [sCompiledScripts objectForKey:path];
659 if (held != nil) {
660 [held getValue:&compiled];
661 compiled = JS_DupValue(context, compiled);
662 } else {
663 compiled = CompileScriptWithName(context, path, outErrorMessage);
664 if (JS_IsException(compiled))
665 return NO;
666
667 if (sCompiledScripts == nil)
668 sCompiledScripts = [[NSMutableDictionary alloc] init];
669 JSValue kept = JS_DupValue(context, compiled);
670 [sCompiledScripts setObject:[NSValue valueWithBytes:&kept objCType:@encode(JSValue)] forKey:path];
671 }
672
674 JSValue result;
675 JSValue function = JS_EvalFunction(context, compiled); // Takes ownership of compiled.
676 if (JS_IsException(function)) {
677 result = function;
678 } else {
679 result = JS_Call(context, function, object, 0, NULL);
680 JS_FreeValue(context, function);
681 }
683
684 if (JS_IsException(result)) {
686 *outErrorMessage = @"could not run script";
687 return NO;
688 }
689
690 JS_FreeValue(context, result);
691 return YES;
692}
693
694// Owned compiled script, or JS_EXCEPTION with *outErrorMessage set.
695static JSValue CompileScriptWithName(JSContext* context, NSString* path, NSString** outErrorMessage)
696{
697 NSString* fileContents = [NSString stringWithContentsOfUnicodeFile:path];
698 if (fileContents == nil) {
699 *outErrorMessage = @"could not load file";
700 return JS_EXCEPTION;
701 }
702
703#ifdef OO_DEBUG_MONITOR_ENABLED
704 /* FIXME: this isn't strictly the right test, since strict
705 * mode can be enabled with this string within a function
706 * definition, but it seems unlikely anyone is actually doing
707 * that here. */
708 if ([fileContents rangeOfString:@"\"use strict\";"].location == NSNotFound && [fileContents rangeOfString:@"'use strict';"].location == NSNotFound) {
709 OOStandardsDeprecated([NSString stringWithFormat:@"Script %@ does not \"use strict\";", path]);
710 if (OOEnforceStandards()) {
711 // prepend it anyway (before wrapping: see OOJSWrapScriptSource())
712 // TODO: some time after 1.82, make this required
713 fileContents = [@"\"use strict\";\n" stringByAppendingString:fileContents];
714 }
715 }
716#endif
717
718 /* Scripts marked with the "use oolite modern" directive (for example by
719 tools/oxp-upgrade) don't rely on SpiderMonkey 1.8.5 scoping, so they
720 run without its emulation: no with(this) and no const rewrite.
721 */
722 BOOL modern = HasModernScopeDirective(fileContents);
723 if (modern) {
724 OOLog(@"script.javaScript.load.modern", @"Script %@ uses modern scoping.", path);
725 NSString* lineEnd = [fileContents hasSuffix:@"\n"] ? @"" : @"\n";
726 fileContents = [NSString stringWithFormat:@"(function(){%@%@})", fileContents, lineEnd];
727 } else {
728 fileContents = [NSString stringWithFormat:@"(function(){%@})", OOJSWrapScriptSource(RewriteLegacyConst(context, fileContents))];
729 }
730
731 /* QuickJS runs compiled (and cached) code only with the global object as
732 its this (JS_EvalFunction()), so the wrapped script is compiled as a
733 function expression, which is then called with the script object as
734 this. The extra prefix is on the first line, so line numbers are
735 unchanged.
736 */
737 NSString* wrapped = fileContents;
738 NSData* source = [wrapped dataUsingEncoding:NSUTF8StringEncoding];
739
740 JSValue compiled = JS_UNDEFINED;
741#if OO_CACHE_JS_SCRIPTS
742 compiled = CachedCompiledScript(context, path, source);
743#endif
744
745 if (JS_IsUndefined(compiled)) {
746 NSMutableData* terminated = [NSMutableData dataWithData:source];
747 [terminated appendBytes:"" length:1]; // JS_Eval requires a terminating NUL.
748
749 compiled = JS_Eval(context, [terminated bytes], [source length], [path UTF8String], JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
750 if (JS_IsException(compiled)) {
752 *outErrorMessage = @"compilation failed";
753 return JS_EXCEPTION;
754 }
755#if OO_CACHE_JS_SCRIPTS
756 CacheCompiledScript(context, path, source, compiled);
757#endif
758 }
759
760 return compiled;
761}
762
763#if OO_CACHE_JS_SCRIPTS
764/* Compiled scripts are cached by path, like the SpiderMonkey version's XDR
765 data, but under a different cache name. Each entry also records a hash of
766 the exact text that was compiled (after the const rewrite and wrapping),
767 the QuickJS version and the entry format, and is only used if all three
768 match. As before, the whole cache is cleared when the Oolite version or
769 the search paths change (see OOCacheManager and ResourceManager).
770*/
771static NSString* const kCompiledScriptCache = @"compiled QuickJS scripts";
772static NSString* const kCompiledScriptKeyHash = @"source hash";
773static NSString* const kCompiledScriptKeyEngine = @"engine";
774static NSString* const kCompiledScriptKeyFormat = @"format";
775static NSString* const kCompiledScriptKeyBytecode = @"bytecode";
776enum {
777 kCompiledScriptFormat = 1 // Increment when the compiled text or the way it is run changes.
778};
779
780// 64-bit FNV-1a and length. Only needs to detect changed source, not resist tampering.
781static NSString* SourceHash(NSData* source)
782{
783 const uint8_t* bytes = [source bytes];
784 NSUInteger length = [source length];
785 uint64_t hash = 0xcbf29ce484222325ULL;
786 for (NSUInteger i = 0; i < length; i++) {
787 hash ^= bytes[i];
788 hash *= 0x100000001b3ULL;
789 }
790 return [NSString stringWithFormat:@"%016llx:%lu", (unsigned long long)hash, (unsigned long)length];
791}
792
793// Owned compiled script from the cache, or JS_UNDEFINED if there is no usable entry.
794static JSValue CachedCompiledScript(JSContext* context, NSString* path, NSData* source)
795{
796 NSDictionary* entry = [[OOCacheManager sharedCache] objectForKey:path inCache:kCompiledScriptCache];
797 if (![entry isKindOfClass:[NSDictionary class]])
798 return JS_UNDEFINED;
799
800 NSData* bytecode = [entry objectForKey:kCompiledScriptKeyBytecode];
801 if (![bytecode isKindOfClass:[NSData class]]
802 || [entry oo_unsignedIntForKey:kCompiledScriptKeyFormat] != kCompiledScriptFormat
803 || ![[entry oo_stringForKey:kCompiledScriptKeyEngine] isEqualToString:[NSString stringWithUTF8String:JS_GetVersion()]]
804 || ![[entry oo_stringForKey:kCompiledScriptKeyHash] isEqualToString:SourceHash(source)]) {
805 OOLog(@"script.javaScript.cache.stale", @"Compiled script cache entry for %@ is out of date.", path);
806 return JS_UNDEFINED;
807 }
808
809 // Trusted input: the cache is written only by CacheCompiledScript().
810 JSValue compiled = JS_ReadObject(context, [bytecode bytes], [bytecode length], JS_READ_OBJ_BYTECODE);
811 if (JS_IsException(compiled)) {
812 JS_FreeValue(context, JS_GetException(context));
813 OOLog(@"script.javaScript.cache.readFailed", @"Could not read compiled script cache entry for %@; compiling instead.", path);
814 return JS_UNDEFINED;
815 }
816
817 OOLog(@"script.javaScript.cache.load", @"Loaded compiled script %@ from cache.", path);
818 return compiled;
819}
820
821static void CacheCompiledScript(JSContext* context, NSString* path, NSData* source, JSValueConst compiled)
822{
823 size_t length = 0;
824 uint8_t* bytes = JS_WriteObject(context, &length, compiled, JS_WRITE_OBJ_BYTECODE);
825 if (bytes == NULL) {
826 if (JS_HasException(context))
827 JS_FreeValue(context, JS_GetException(context));
828 return;
829 }
830
831 NSData* bytecode = [NSData dataWithBytes:bytes length:length];
832 js_free(context, bytes);
833
834 NSDictionary* entry = [NSDictionary dictionaryWithObjectsAndKeys:
835 bytecode, kCompiledScriptKeyBytecode,
836 SourceHash(source), kCompiledScriptKeyHash,
837 [NSString stringWithUTF8String:JS_GetVersion()], kCompiledScriptKeyEngine,
838 [NSNumber numberWithUnsignedInt:kCompiledScriptFormat], kCompiledScriptKeyFormat,
839 nil];
840
841 [[OOCacheManager sharedCache] setObject:entry forKey:path inCache:kCompiledScriptCache];
842 OOLog(@"script.javaScript.cache.store", @"Cached compiled script %@.", path);
843}
844#endif
845
846/* Whether the script's directive prologue (the string literal statements
847 at its start, like "use strict") includes "use oolite modern".
848*/
849static BOOL HasModernScopeDirective(NSString* source)
850{
851 NSUInteger length = [source length];
852 NSUInteger i = 0;
853 if (length > 0 && [source characterAtIndex:0] == 0xFEFF)
854 i = 1;
855
856 for (;;) {
857 // Skip white space and comments.
858 BOOL skipped = YES;
859 while (skipped && i < length) {
860 skipped = NO;
861 unichar c = [source characterAtIndex:i];
862 if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0xA0 || c == 0xFEFF) {
863 i++;
864 skipped = YES;
865 } else if (c == '/' && i + 1 < length && [source characterAtIndex:i + 1] == '/') {
866 while (i < length && [source characterAtIndex:i] != '\n')
867 i++;
868 skipped = YES;
869 } else if (c == '/' && i + 1 < length && [source characterAtIndex:i + 1] == '*') {
870 NSRange end = [source rangeOfString:@"*/" options:0 range:NSMakeRange(i + 2, length - i - 2)];
871 if (end.location == NSNotFound)
872 return NO;
873 i = end.location + 2;
874 skipped = YES;
875 }
876 }
877 if (i >= length)
878 return NO;
879
880 // A directive: a string literal, followed by ; or a line break.
881 unichar quote = [source characterAtIndex:i];
882 if (quote != '"' && quote != '\'')
883 return NO;
884 NSUInteger start = ++i;
885 BOOL escaped = NO;
886 while (i < length && [source characterAtIndex:i] != quote) {
887 unichar c = [source characterAtIndex:i];
888 if (c == '\\') {
889 escaped = YES;
890 i++;
891 }
892 if (c == '\n')
893 return NO;
894 i++;
895 }
896 if (i >= length)
897 return NO;
898 NSString* directive = [source substringWithRange:NSMakeRange(start, i - start)];
899 i++;
900
901 BOOL lineBreak = NO;
902 while (i < length) {
903 unichar c = [source characterAtIndex:i];
904 if (c == '\n') {
905 lineBreak = YES;
906 } else if (c == '/' && i + 1 < length && [source characterAtIndex:i + 1] == '/') {
907 while (i < length && [source characterAtIndex:i] != '\n')
908 i++;
909 continue;
910 } else if (c != ' ' && c != '\t' && c != '\r') {
911 break;
912 }
913 i++;
914 }
915 if (i < length && [source characterAtIndex:i] == ';')
916 i++;
917 else if (!lineBreak && i < length && [source characterAtIndex:i] != '}')
918 return NO; // Part of a larger expression, so not a directive.
919
920 if (!escaped && [directive isEqualToString:@"use oolite modern"])
921 return YES;
922 }
923}
924
925/* In SpiderMonkey 1.8.5, const declarations were function-scoped and usable
926 before the declaration, like var; under ES2015 rules they are
927 block-scoped with a temporal dead zone, which breaks some OXPs. The
928 compatibility script's const rewriter (OOJSLegacyConstRewriter()) replaces the const
929 keyword with var (keeping line and column positions).
930
931 The rewriter is interpreted JavaScript, and a ship script is loaded again
932 for every ship that uses it, so results are kept for the rest of the
933 session, keyed by the source text.
934*/
935static NSString* RewriteLegacyConst(JSContext* context, NSString* source)
936{
937 static NSMutableDictionary* sRewritten = nil;
938
939 if ([source rangeOfString:@"const"].location == NSNotFound)
940 return source;
941
942 NSString* cached = [sRewritten objectForKey:source];
943 if (cached != nil)
944 return cached;
945
946 JSValueConst rewriter = OOJSLegacyConstRewriter();
947 NSString* result = source;
948
949 if (JS_IsFunction(context, rewriter)) {
950 JSValue argument = OOJSValueFromNativeObject(context, source);
951 JSValue rewritten = JS_Call(context, rewriter, JS_UNDEFINED, 1, (JSValueConst*)&argument);
952 if (JS_IsException(rewritten)) {
954 } else {
955 result = OOStringFromJSValue(context, rewritten) ?: source;
956 if (sRewritten == nil)
957 sRewritten = [[NSMutableDictionary alloc] init];
958 [sRewritten setObject:result forKey:source];
959 }
960 JS_FreeValue(context, rewritten);
961 JS_FreeValue(context, argument);
962 }
963
964 return result;
965}
966
967static NSString* StrippedName(NSString* string)
968{
969 static NSCharacterSet* invalidSet = nil;
970 if (invalidSet == nil)
971 invalidSet = [[NSCharacterSet characterSetWithCharactersInString:@"_ \t\n\r\v"] retain];
972
973 return [string stringByTrimmingCharactersInSet:invalidSet];
974}
void OOStandardsDeprecated(NSString *message)
BOOL OOEnforceStandards(void)
#define DESTROY(x)
#define foreachkey(VAR, DICT)
id OOConsumeReference(id OO_NS_CONSUMED value)
#define EXPECT_NOT(x)
#define EXPECT(x)
#define OOJSStopTimeLimiter()
#define OOJSStartTimeLimiter()
#define kOOJSLongTimeLimit
#define OOJSStartTimeLimiterWithTimeLimit(limit)
#define OOJSID(str)
Definition OOJSPropID.h:42
void InitOOJSScript(JSContext *context, JSObject *global)
Definition OOJSScript.m:614
static NSString *const kLocalManifestProperty
Definition OOJSScript.h:28
static NSString * StrippedName(NSString *string)
Definition OOJSScript.m:754
static RunningStack * sRunningStack
Definition OOJSScript.m:56
static JSFunctionSpec sScriptMethods[]
Definition OOJSScript.m:85
static JSClass sScriptClass
Definition OOJSScript.m:71
static void AddStackToArrayReversed(NSMutableArray *array, RunningStack *stack)
Definition OOJSScript.m:635
id OOJSNativeObjectFromJSValue(JSContext *context, jsval value)
void OOJSReportWarning(JSContext *context, NSString *format,...)
JSBool OOJSObjectWrapperToString(JSContext *context, uintN argc, jsval *vp)
NSString * OOStringFromJSID(jsid propID)
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
#define OOJS_PROP_READONLY
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSReportPendingException(JSContext *context)
OOINLINE void OOJSRelinquishContext(JSContext *context)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
#define OOLogOutdentIf(class)
Definition OOLogging.h:112
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define OOLogIndentIf(class)
Definition OOLogging.h:107
static NSString *const kOOManifestLicense
static NSString *const kOOManifestIdentifier
static NSString *const kOOManifestVersion
static NSString *const kOOManifestAuthor
NSDictionary * OODictionaryFromFile(NSString *path)
return nil
void OOJSScriptDestroyCompiledScripts(JSContext *context)
Definition OOJSScript.m:637
static NSMutableDictionary * sCompiledScripts
Definition OOJSScript.m:633
static void CacheCompiledScript(JSContext *context, NSString *path, NSData *source, JSValueConst compiled)
Definition OOJSScript.m:821
static NSString * StrippedName(NSString *string)
Definition OOJSScript.m:967
static BOOL RunScriptWithName(JSContext *context, NSString *path, JSValueConst object, NSString **outErrorMessage)
Definition OOJSScript.m:652
static NSString *const kCompiledScriptKeyHash
Definition OOJSScript.m:772
@ kCompiledScriptFormat
Definition OOJSScript.m:777
static NSString *const kCompiledScriptCache
Definition OOJSScript.m:771
static NSString * SourceHash(NSData *source)
Definition OOJSScript.m:781
static NSString *const kCompiledScriptKeyEngine
Definition OOJSScript.m:773
static JSValue CachedCompiledScript(JSContext *context, NSString *path, NSData *source)
Definition OOJSScript.m:794
static BOOL HasModernScopeDirective(NSString *source)
Definition OOJSScript.m:849
static JSValue CompileScriptWithName(JSContext *context, NSString *path, NSString **outErrorMessage)
Definition OOJSScript.m:695
static NSString * RewriteLegacyConst(JSContext *context, NSString *source)
Definition OOJSScript.m:935
static NSString *const kCompiledScriptKeyFormat
Definition OOJSScript.m:774
static JSClassID sScriptClassID
Definition OOJSScript.m:53
static NSString *const kCompiledScriptKeyBytecode
Definition OOJSScript.m:775
JSValueConst OOJSLegacyConstRewriter(void)
JSClassID OOJSRegisterClass(JSClassID *ioClassID, const JSClassDef *classDef)
Definition OOJSClasses.m:61
JSValueConst OOJSInitClass(JSContext *context, JSValueConst global, JSClassID classID, JSValueConst parentPrototype, JSCFunction *constructor, int constructorArgCount, const JSCFunctionListEntry *properties, size_t propertyCount, const JSCFunctionListEntry *methods, size_t methodCount, const JSCFunctionListEntry *staticMethods, size_t staticMethodCount)
#define OOJS_COUNT(array)
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)
OOCacheManager * sharedCache()
BOOL defineProperty:named:(id value,[named] NSString *name)
Definition OOJSScript.m:459
NSString * version
Definition OOJSScript.m:113
NSString * displayName()
Definition OOJSScript.m:118
BOOL setProperty:named:(id value,[named] NSString *name)
Definition OOJSScript.m:445
BOOL defineProperty:withID:inContext:(id value,[withID] jsid propID,[inContext] JSContext *context)
Definition OOJSScript.m:421
NSString * filePath
Definition OOJSScript.h:37
NSArray * scriptStack()
Definition OOJSScript.m:283
id propertyWithID:inContext:(jsid propID,[inContext] JSContext *context)
Definition OOJSScript.m:394
NSString * description
Definition OOJSScript.h:35
NSString * scriptNameFromPath:(NSString *path)
Definition OOJSScript.m:522
JSObject * _jsSelf
Definition OOJSScript.h:32
BOOL setProperty:withID:inContext:(id value,[withID] jsid propID,[inContext] JSContext *context)
Definition OOJSScript.m:411
NSString * name
Definition OOJSScript.m:108
void checkForTickle:(JSContext *context)
Definition OOJSScript.m:585
NSDictionary * defaultPropertiesFromPath:(NSString *path)
Definition OOJSScript.m:554
OOJavaScriptEngine * sharedEngine()
id weakRefWithObject:(id< OOWeakReferenceSupport > object)
OOJSScript * current
Definition OOJSScript.m:52
RunningStack * back
Definition OOJSScript.m:51