Oolite
Loading...
Searching...
No Matches
OOJSScript.m File Reference
Include dependency graph for OOJSScript.m:

Go to the source code of this file.

Classes

struct  RunningStack
category  OOJSScript(OOPrivate)

Macros

#define OO_CACHE_JS_SCRIPTS   1

Enumerations

enum  { kCompiledScriptFormat = 1 }

Functions

static void AddStackToArrayReversed (NSMutableArray *array, RunningStack *stack)
static BOOL RunScriptWithName (JSContext *context, NSString *path, JSValueConst object, NSString **outErrorMessage)
static NSString * StrippedName (NSString *string)
static NSString * RewriteLegacyConst (JSContext *context, NSString *source)
static BOOL HasModernScopeDirective (NSString *source)
static JSValue CachedCompiledScript (JSContext *context, NSString *path, NSData *source)
static void CacheCompiledScript (JSContext *context, NSString *path, NSData *source, JSValueConst compiled)
void InitOOJSScript (JSContext *context, JSValueConst global)
static JSValue CompileScriptWithName (JSContext *context, NSString *path, NSString **outErrorMessage)
void OOJSScriptDestroyCompiledScripts (JSContext *context)
static NSString * SourceHash (NSData *source)

Variables

static JSClassID sScriptClassID
static RunningStack * sRunningStack = NULL
static JSClassDef sScriptClass
static const JSCFunctionListEntry sScriptMethods []
static NSMutableDictionary * sCompiledScripts = nil
static NSString *const kCompiledScriptCache = @"@"compiled QuickJS scripts"
static NSString *const kCompiledScriptKeyHash = @"@"source hash"
static NSString *const kCompiledScriptKeyEngine = @"@"engine"
static NSString *const kCompiledScriptKeyFormat = @"@"format"
static NSString *const kCompiledScriptKeyBytecode = @"@"bytecode"

Macro Definition Documentation

◆ OO_CACHE_JS_SCRIPTS

#define OO_CACHE_JS_SCRIPTS   1

Definition at line 26 of file OOJSScript.m.

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
kCompiledScriptFormat 

Definition at line 776 of file OOJSScript.m.

776 {
777 kCompiledScriptFormat = 1 // Increment when the compiled text or the way it is run changes.
778};
@ kCompiledScriptFormat
Definition OOJSScript.m:777

Function Documentation

◆ AddStackToArrayReversed()

void AddStackToArrayReversed ( NSMutableArray * array,
RunningStack * stack )
static

Definition at line 620 of file OOJSScript.m.

621{
622 if (stack != NULL) {
623 AddStackToArrayReversed(array, stack->back);
624 [array addObject:stack->current];
625 }
626}
static void AddStackToArrayReversed(NSMutableArray *array, RunningStack *stack)
Definition OOJSScript.m:635
RunningStack * back
Definition OOJSScript.m:51

References AddStackToArrayReversed(), and RunningStack::back.

Here is the call graph for this function:

◆ CacheCompiledScript()

void CacheCompiledScript ( JSContext * context,
NSString * path,
NSData * source,
JSValueConst compiled )
static

Definition at line 821 of file OOJSScript.m.

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}
#define OOLog(class, format,...)
Definition OOLogging.h:84
void setObject:forKey:inCache:(id inElement,[forKey] NSString *inKey,[inCache] NSString *inCacheKey)
OOCacheManager * sharedCache()

References OOLog, OOCacheManager::setObject:forKey:inCache:, and OOCacheManager::sharedCache.

Referenced by CompileScriptWithName().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CachedCompiledScript()

JSValue CachedCompiledScript ( JSContext * context,
NSString * path,
NSData * source )
static

Definition at line 794 of file OOJSScript.m.

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}
static NSString *const kCompiledScriptKeyHash
Definition OOJSScript.m:772
static NSString * SourceHash(NSData *source)
Definition OOJSScript.m:781
static NSString *const kCompiledScriptKeyEngine
Definition OOJSScript.m:773
static NSString *const kCompiledScriptKeyFormat
Definition OOJSScript.m:774
id objectForKey:inCache:(NSString *inKey,[inCache] NSString *inCacheKey)

References kCompiledScriptFormat, kCompiledScriptKeyEngine, kCompiledScriptKeyFormat, kCompiledScriptKeyHash, OOCacheManager::objectForKey:inCache:, OOLog, OOCacheManager::sharedCache, and SourceHash().

Referenced by CompileScriptWithName().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CompileScriptWithName()

JSValue CompileScriptWithName ( JSContext * context,
NSString * path,
NSString ** outErrorMessage )
static

Definition at line 695 of file OOJSScript.m.

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}
void OOStandardsDeprecated(NSString *message)
BOOL OOEnforceStandards(void)
OOINLINE void OOJSReportPendingException(JSContext *context)
return nil
static void CacheCompiledScript(JSContext *context, NSString *path, NSData *source, JSValueConst compiled)
Definition OOJSScript.m:821
static JSValue CachedCompiledScript(JSContext *context, NSString *path, NSData *source)
Definition OOJSScript.m:794
static BOOL HasModernScopeDirective(NSString *source)
Definition OOJSScript.m:849
static NSString * RewriteLegacyConst(JSContext *context, NSString *source)
Definition OOJSScript.m:935
NSString * OOJSWrapScriptSource(NSString *source)

References CacheCompiledScript(), CachedCompiledScript(), HasModernScopeDirective(), nil, OOEnforceStandards(), OOJSReportPendingException(), OOLog, and OOStandardsDeprecated().

Referenced by RunScriptWithName().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HasModernScopeDirective()

BOOL HasModernScopeDirective ( NSString * source)
static

Definition at line 849 of file OOJSScript.m.

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}

Referenced by CompileScriptWithName().

Here is the caller graph for this function:

◆ InitOOJSScript()

void InitOOJSScript ( JSContext * context,
JSValueConst global )

Definition at line 613 of file OOJSScript.m.

614{
616 OOJSInitClass(context, global, sScriptClassID, JS_UNDEFINED, OOJSUnconstructableConstruct, 0, NULL, 0, sScriptMethods, OOJS_COUNT(sScriptMethods), NULL, 0);
618}
static JSFunctionSpec sScriptMethods[]
Definition OOJSScript.m:85
static JSClass sScriptClass
Definition OOJSScript.m:71
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
static JSClassID sScriptClassID
Definition OOJSScript.m:53
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)

◆ OOJSScriptDestroyCompiledScripts()

void OOJSScriptDestroyCompiledScripts ( JSContext * context)

Definition at line 637 of file OOJSScript.m.

638{
639 NSValue* held = nil;
640 foreach (held, [sCompiledScripts allValues]) {
641 JSValue compiled;
642 [held getValue:&compiled];
643 JS_FreeValue(context, compiled);
644 }
646}
#define DESTROY(x)
static NSMutableDictionary * sCompiledScripts
Definition OOJSScript.m:633

References DESTROY, nil, and sCompiledScripts.

◆ RewriteLegacyConst()

NSString * RewriteLegacyConst ( JSContext * context,
NSString * source )
static

Definition at line 935 of file OOJSScript.m.

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}
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSValueConst OOJSLegacyConstRewriter(void)

References nil, OOJSLegacyConstRewriter(), OOJSReportPendingException(), OOJSValueFromNativeObject(), and OOStringFromJSValue().

Here is the call graph for this function:

◆ RunScriptWithName()

BOOL RunScriptWithName ( JSContext * context,
NSString * path,
JSValueConst object,
NSString ** outErrorMessage )
static

Definition at line 652 of file OOJSScript.m.

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}
#define OOJSStopTimeLimiter()
#define kOOJSLongTimeLimit
#define OOJSStartTimeLimiterWithTimeLimit(limit)
static JSValue CompileScriptWithName(JSContext *context, NSString *path, NSString **outErrorMessage)
Definition OOJSScript.m:695

References CompileScriptWithName(), kOOJSLongTimeLimit, nil, OOJSReportPendingException(), OOJSStartTimeLimiterWithTimeLimit, OOJSStopTimeLimiter, and sCompiledScripts.

Referenced by OOJSScript::initWithPath:properties:.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ SourceHash()

NSString * SourceHash ( NSData * source)
static

Definition at line 781 of file OOJSScript.m.

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}
typedef long(ZCALLBACK *tell_file_func) OF((voidpf opaque

Referenced by CachedCompiledScript().

Here is the caller graph for this function:

◆ StrippedName()

NSString * StrippedName ( NSString * string)
static

Definition at line 967 of file OOJSScript.m.

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}

References nil.

Referenced by OOJSScript(OOPrivate)::scriptNameFromPath:.

Here is the caller graph for this function:

Variable Documentation

◆ kCompiledScriptCache

NSString* const kCompiledScriptCache = @"@"compiled QuickJS scripts"
static

Definition at line 771 of file OOJSScript.m.

◆ kCompiledScriptKeyBytecode

NSString* const kCompiledScriptKeyBytecode = @"@"bytecode"
static

Definition at line 775 of file OOJSScript.m.

◆ kCompiledScriptKeyEngine

NSString* const kCompiledScriptKeyEngine = @"@"engine"
static

Definition at line 773 of file OOJSScript.m.

Referenced by CachedCompiledScript().

◆ kCompiledScriptKeyFormat

NSString* const kCompiledScriptKeyFormat = @"@"format"
static

Definition at line 774 of file OOJSScript.m.

Referenced by CachedCompiledScript().

◆ kCompiledScriptKeyHash

NSString* const kCompiledScriptKeyHash = @"@"source hash"
static

Definition at line 772 of file OOJSScript.m.

Referenced by CachedCompiledScript().

◆ sCompiledScripts

NSMutableDictionary* sCompiledScripts = nil
static

Definition at line 633 of file OOJSScript.m.

Referenced by OOJSScriptDestroyCompiledScripts(), and RunScriptWithName().

◆ sRunningStack

RunningStack* sRunningStack = NULL
static

Definition at line 54 of file OOJSScript.m.

◆ sScriptClass

JSClassDef sScriptClass
static
Initial value:
= {
.class_name = "Script",
}
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)

Definition at line 69 of file OOJSScript.m.

69 {
70 .class_name = "Script",
71 .finalizer = OOJSObjectWrapperFinalize,
72};

◆ sScriptClassID

JSClassID sScriptClassID
static

◆ sScriptMethods

const JSCFunctionListEntry sScriptMethods[]
static
Initial value:
= {
JS_CFUNC_DEF("toString", 0, OOJSObjectWrapperToString),
}
JSBool OOJSObjectWrapperToString(JSContext *context, uintN argc, jsval *vp)

Definition at line 74 of file OOJSScript.m.

74 {
75 // JS name, min args, function
76 JS_CFUNC_DEF("toString", 0, OOJSObjectWrapperToString),
77};