Oolite
Loading...
Searching...
No Matches
OOJSConsole.m
Go to the documentation of this file.
1/*
2
3OOJSConsole.m
4
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9Permission is hereby granted, free of charge, to any person obtaining a copy
10of this software and associated documentation files (the "Software"), to deal
11in the Software without restriction, including without limitation the rights
12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13copies of the Software, and to permit persons to whom the Software is
14furnished to do so, subject to the following conditions:
15
16The above copyright notice and this permission notice shall be included in all
17copies or substantial portions of the Software.
18
19THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25SOFTWARE.
26
27*/
28
29#ifdef OO_DEBUG_MONITOR_ENABLED
30
31#import "OOJSConsole.h"
32#import "OODebugMonitor.h"
33#include <stdint.h>
34
35#import "OOConstToString.h"
36#import "OODebugFlags.h"
37#import "OODebugMonitor.h"
38#import "OOJSCall.h"
39#import "OOJSEngineTimeManagement.h"
40#import "OOJSEntity.h"
41#import "OOJSScript.h"
42#import "OOJSVector.h"
43#import "OOLoggingExtended.h"
46#import "ResourceManager.h"
47
48@interface Entity (OODebugInspector)
49
50// Method added by inspector in Debug OXP under OS X only.
51- (void)inspect;
52
53@end
54
55NSString* OOPlatformDescription(void);
56
57static JSObject* sConsolePrototype = NULL;
58static JSObject* sConsoleSettingsPrototype = NULL;
59
60static JSBool ConsoleGetProperty(JSContext* context, JSObject* this, jsid propID, jsval* value);
61static JSBool ConsoleSetProperty(JSContext* context, JSObject* this, jsid propID, JSBool strict, jsval* value);
62static void ConsoleFinalize(JSContext* context, JSObject* this);
63
64// Methods
65static JSBool ConsoleConsoleMessage(JSContext* context, uintN argc, jsval* vp);
66static JSBool ConsoleClearConsole(JSContext* context, uintN argc, jsval* vp);
67static JSBool ConsoleScriptStack(JSContext* context, uintN argc, jsval* vp);
68static JSBool ConsoleInspectEntity(JSContext* context, uintN argc, jsval* vp);
69#if OO_DEBUG
70static JSBool ConsoleCallObjCMethod(JSContext* context, uintN argc, jsval* vp);
71static JSBool ConsoleSetUpCallObjC(JSContext* context, uintN argc, jsval* vp);
72#endif
73static JSBool ConsoleIsExecutableJavaScript(JSContext* context, uintN argc, jsval* vp);
74static JSBool ConsoleDisplayMessagesInClass(JSContext* context, uintN argc, jsval* vp);
75static JSBool ConsoleSetDisplayMessagesInClass(JSContext* context, uintN argc, jsval* vp);
76static JSBool ConsoleWriteLogMarker(JSContext* context, uintN argc, jsval* vp);
77static JSBool ConsoleWriteMemoryStats(JSContext* context, uintN argc, jsval* vp);
78static JSBool ConsoleWriteJSMemoryStats(JSContext* context, uintN argc, jsval* vp);
79static JSBool ConsoleGarbageCollect(JSContext* context, uintN argc, jsval* vp);
80#if DEBUG
81static JSBool ConsoleDumpNamedRoots(JSContext* context, uintN argc, jsval* vp);
82static JSBool ConsoleDumpHeap(JSContext* context, uintN argc, jsval* vp);
83#endif
84#if OOJS_PROFILE
85static JSBool ConsoleProfile(JSContext* context, uintN argc, jsval* vp);
86static JSBool ConsoleGetProfile(JSContext* context, uintN argc, jsval* vp);
87static JSBool ConsoleTrace(JSContext* context, uintN argc, jsval* vp);
88#endif
89
90static JSBool ConsoleSettingsDeleteProperty(JSContext* context, JSObject* this, jsid propID, jsval* value);
91static JSBool ConsoleSettingsGetProperty(JSContext* context, JSObject* this, jsid propID, jsval* value);
92static JSBool ConsoleSettingsSetProperty(JSContext* context, JSObject* this, jsid propID, JSBool strict, jsval* value);
93
94#if OOJS_PROFILE
95static JSBool PerformProfiling(JSContext* context, NSString* nominalFunction, uintN argc, jsval* argv, jsval* rval, BOOL trace, OOTimeProfile** profile);
96#endif
97
98static JSClass sConsoleClass = {
99 "Console",
100 JSCLASS_HAS_PRIVATE,
101
102 JS_PropertyStub, // addProperty
103 JS_PropertyStub, // delProperty
104 ConsoleGetProperty, // getProperty
105 ConsoleSetProperty, // setProperty
106 JS_EnumerateStub, // enumerate
107 JS_ResolveStub, // resolve
108 JS_ConvertStub, // convert
109 ConsoleFinalize, // finalize
110 JSCLASS_NO_OPTIONAL_MEMBERS
111};
112
113enum {
114 // Property IDs
115 kConsole_debugFlags, // debug flags, integer, read/write
116 kConsole_detailLevel, // graphics detail level, symbolic string, read/write
117 kConsole_maximumDetailLevel, // maximum graphics detail level, symbolic string, read-only
118 kConsole_displayFPS, // display FPS (and related info), boolean, read/write
119 kConsole_platformDescription, // Information about system we're running on in unspecified format, string, read-only
120 kConsole_ignoreDroppedPackets, // boolean (default false), read/write
121 kConsole_pedanticMode, // JS pedantic mode (JS_STRICT flag, not the same as "use strict"), boolean (default true), read/write
122 kConsole_showErrorLocations, // Show error/warning source locations, boolean (default true), read/write
123 kConsole_dumpStackForErrors, // Write stack dump when reporting error/exception, boolean (default false), read/write
124 kConsole_dumpStackForWarnings, // Write stack dump when reporting warning, boolean (default false), read/write
125
126 kConsole_glVendorString, // OpenGL GL_VENDOR string, string, read-only
127 kConsole_glRendererString, // OpenGL GL_RENDERER string, string, read-only
128 kConsole_glFixedFunctionTextureUnitCount, // GL_MAX_TEXTURE_UNITS_ARB, integer, read-only
129 kConsole_glFragmentShaderTextureUnitCount, // GL_MAX_TEXTURE_IMAGE_UNITS_ARB, integer, read-only
130
131 // Symbolic constants for debug flags:
132 kConsole_DEBUG_LINKED_LISTS,
133 kConsole_DEBUG_COLLISIONS,
134 kConsole_DEBUG_DOCKING,
135 kConsole_DEBUG_OCTREE_LOGGING,
136 kConsole_DEBUG_BOUNDING_BOXES,
137 kConsole_DEBUG_OCTREE_DRAW,
138 kConsole_DEBUG_DRAW_NORMALS,
139 kConsole_DEBUG_NO_DUST,
140 kConsole_DEBUG_NO_SHADER_FALLBACK,
141 kConsole_DEBUG_SHADER_VALIDATION,
142
143 kConsole_DEBUG_MISC
144};
145
146static JSPropertySpec sConsoleProperties[] = {
147 // JS name ID flags
148 { "debugFlags", kConsole_debugFlags, OOJS_PROP_READWRITE_CB },
149 { "detailLevel", kConsole_detailLevel, OOJS_PROP_READWRITE_CB },
150 { "maximumDetailLevel", kConsole_maximumDetailLevel, OOJS_PROP_READONLY_CB },
151 { "displayFPS", kConsole_displayFPS, OOJS_PROP_READWRITE_CB },
152 { "platformDescription", kConsole_platformDescription, OOJS_PROP_READONLY_CB },
153 { "pedanticMode", kConsole_pedanticMode, OOJS_PROP_READWRITE_CB },
154 { "ignoreDroppedPackets", kConsole_ignoreDroppedPackets, OOJS_PROP_READWRITE_CB },
155 { "__showErrorLocations", kConsole_showErrorLocations, OOJS_PROP_HIDDEN_READWRITE_CB },
156 { "__dumpStackForErrors", kConsole_dumpStackForErrors, OOJS_PROP_HIDDEN_READWRITE_CB },
157 { "__dumpStackForWarnings", kConsole_dumpStackForWarnings, OOJS_PROP_HIDDEN_READWRITE_CB },
158 { "glVendorString", kConsole_glVendorString, OOJS_PROP_READONLY_CB },
159 { "glRendererString", kConsole_glRendererString, OOJS_PROP_READONLY_CB },
160 { "glFixedFunctionTextureUnitCount", kConsole_glFixedFunctionTextureUnitCount, OOJS_PROP_READONLY_CB },
161 { "glFragmentShaderTextureUnitCount", kConsole_glFragmentShaderTextureUnitCount, OOJS_PROP_READONLY_CB },
162
163#define DEBUG_FLAG_DECL(x) { #x, kConsole_##x, OOJS_PROP_READONLY_CB }
164 DEBUG_FLAG_DECL(DEBUG_LINKED_LISTS),
165 DEBUG_FLAG_DECL(DEBUG_COLLISIONS),
166 DEBUG_FLAG_DECL(DEBUG_DOCKING),
167 DEBUG_FLAG_DECL(DEBUG_OCTREE_LOGGING),
168 DEBUG_FLAG_DECL(DEBUG_BOUNDING_BOXES),
169 DEBUG_FLAG_DECL(DEBUG_OCTREE_DRAW),
170 DEBUG_FLAG_DECL(DEBUG_DRAW_NORMALS),
171 DEBUG_FLAG_DECL(DEBUG_NO_DUST),
172 DEBUG_FLAG_DECL(DEBUG_NO_SHADER_FALLBACK),
173 DEBUG_FLAG_DECL(DEBUG_SHADER_VALIDATION),
174
175 DEBUG_FLAG_DECL(DEBUG_MISC),
176#undef DEBUG_FLAG_DECL
177
178 { 0 }
179};
180
181static JSFunctionSpec sConsoleMethods[] = {
182 // JS name Function min args
183 { "consoleMessage", ConsoleConsoleMessage, 2 },
184 { "clearConsole", ConsoleClearConsole, 0 },
185 { "scriptStack", ConsoleScriptStack, 0 },
186 { "inspectEntity", ConsoleInspectEntity, 1 },
187#if OO_DEBUG
188 { "__setUpCallObjC", ConsoleSetUpCallObjC, 1 },
189#endif
190 { "isExecutableJavaScript", ConsoleIsExecutableJavaScript, 2 },
191 { "displayMessagesInClass", ConsoleDisplayMessagesInClass, 1 },
192 { "setDisplayMessagesInClass", ConsoleSetDisplayMessagesInClass, 2 },
193 { "writeLogMarker", ConsoleWriteLogMarker, 0 },
194 { "writeMemoryStats", ConsoleWriteMemoryStats, 0 },
195 { "writeJSMemoryStats", ConsoleWriteJSMemoryStats, 0 },
196 { "garbageCollect", ConsoleGarbageCollect, 0 },
197#if DEBUG
198 { "dumpNamedRoots", ConsoleDumpNamedRoots, 0 },
199 { "dumpHeap", ConsoleDumpHeap, 0 },
200#endif
201#if OOJS_PROFILE
202 { "profile", ConsoleProfile, 1 },
203 { "getProfile", ConsoleGetProfile, 1 },
204 { "trace", ConsoleTrace, 1 },
205#endif
206 { 0 }
207};
208
209static JSClass sConsoleSettingsClass = {
210 "ConsoleSettings",
211 JSCLASS_HAS_PRIVATE,
212
213 JS_PropertyStub, // addProperty
214 ConsoleSettingsDeleteProperty, // delProperty
215 ConsoleSettingsGetProperty, // getProperty
216 ConsoleSettingsSetProperty, // setProperty
217 JS_EnumerateStub, // enumerate. FIXME: this should work.
218 JS_ResolveStub, // resolve
219 JS_ConvertStub, // convert
220 ConsoleFinalize, // finalize (same as Console)
221 JSCLASS_NO_OPTIONAL_MEMBERS
222};
223
224static void InitOOJSConsole(JSContext* context, JSObject* global)
225{
226 sConsolePrototype = JS_InitClass(context, global, NULL, &sConsoleClass, OOJSUnconstructableConstruct, 0, sConsoleProperties, sConsoleMethods, NULL, NULL);
228
229 sConsoleSettingsPrototype = JS_InitClass(context, global, NULL, &sConsoleSettingsClass, OOJSUnconstructableConstruct, 0, NULL, NULL, NULL, NULL);
231}
232
233void OOJSConsoleDestroy(void)
234{
235 sConsolePrototype = NULL;
236}
237
238JSObject* DebugMonitorToJSConsole(JSContext* context, OODebugMonitor* monitor)
239{
241
242 OOJavaScriptEngine* engine = nil;
243 JSObject* object = NULL;
244 JSObject* settingsObject = NULL;
245 jsval value;
246
247 NSCAssert(JS_EnterLocalRootScope(context), @"Failed to create JS GC root scope");
249
250 if (sConsolePrototype == NULL) {
251 InitOOJSConsole(context, [engine globalObject]);
252 }
253
254 // Create Console object
255 object = JS_NewObject(context, &sConsoleClass, sConsolePrototype, NULL);
256 if (object != NULL) {
257 if (!JS_SetPrivate(context, object, [monitor weakRetain]))
258 object = NULL;
259 }
260
261 if (object != NULL) {
262 // Create ConsoleSettings object
263 settingsObject = JS_NewObject(context, &sConsoleSettingsClass, sConsoleSettingsPrototype, NULL);
264 if (settingsObject != NULL) {
265 if (!JS_SetPrivate(context, settingsObject, [monitor weakRetain]))
266 settingsObject = NULL;
267 }
268 if (settingsObject != NULL) {
269 value = OBJECT_TO_JSVAL(settingsObject);
270 if (!JS_SetProperty(context, object, "settings", &value)) {
271 settingsObject = NULL;
272 }
273 }
274
275 if (settingsObject == NULL)
276 object = NULL;
277 }
278
279 JS_LeaveLocalRootScope(context);
280
281 return object;
282 // Analyzer: object leaked. (x2) [Expected, objects are retained by JS object.]
283
285}
286
287static JSBool ConsoleGetProperty(JSContext* context, JSObject* this, jsid propID, jsval* value)
288{
289 if (!JSID_IS_INT(propID))
290 return YES;
291
292 OOJS_NATIVE_ENTER(context)
293
294 switch (JSID_TO_INT(propID)) {
295#ifdef OO_DEBUG_MONITOR_ENABLED
296 case kConsole_debugFlags:
297 *value = INT_TO_JSVAL((uint32_t)gDebugFlags);
298 break;
299#endif
300
301 case kConsole_detailLevel:
302 *value = [OOStringFromGraphicsDetail([UNIVERSE detailLevel]) oo_jsValueInContext:context];
303 break;
304
305 case kConsole_maximumDetailLevel:
306 *value = [OOStringFromGraphicsDetail([[OOOpenGLExtensionManager sharedManager] maximumDetailLevel]) oo_jsValueInContext:context];
307 break;
308
309 case kConsole_displayFPS:
310 *value = OOJSValueFromBOOL([UNIVERSE displayFPS]);
311 break;
312
313 case kConsole_platformDescription:
315 break;
316
317 case kConsole_pedanticMode: {
318 uint32_t options = JS_GetOptions(context);
319 *value = OOJSValueFromBOOL(options & JSOPTION_STRICT);
320 } break;
321
322 case kConsole_ignoreDroppedPackets:
323 *value = OOJSValueFromBOOL([[OODebugMonitor sharedDebugMonitor] TCPIgnoresDroppedPackets]);
324 break;
325
326 case kConsole_showErrorLocations:
327 *value = OOJSValueFromBOOL([[OOJavaScriptEngine sharedEngine] showErrorLocations]);
328 break;
329
330 case kConsole_dumpStackForErrors:
331 *value = OOJSValueFromBOOL([[OOJavaScriptEngine sharedEngine] dumpStackForErrors]);
332 break;
333
334 case kConsole_dumpStackForWarnings:
335 *value = OOJSValueFromBOOL([[OOJavaScriptEngine sharedEngine] dumpStackForWarnings]);
336 break;
337
338 case kConsole_glVendorString:
339 *value = OOJSValueFromNativeObject(context, [[OOOpenGLExtensionManager sharedManager] vendorString]);
340 break;
341
342 case kConsole_glRendererString:
343 *value = OOJSValueFromNativeObject(context, [[OOOpenGLExtensionManager sharedManager] rendererString]);
344 break;
345
346 case kConsole_glFixedFunctionTextureUnitCount:
347 *value = INT_TO_JSVAL([[OOOpenGLExtensionManager sharedManager] textureUnitCount]);
348 break;
349
350 case kConsole_glFragmentShaderTextureUnitCount:
351 *value = INT_TO_JSVAL([[OOOpenGLExtensionManager sharedManager] textureImageUnitCount]);
352 break;
353
354#define DEBUG_FLAG_CASE(x) \
355 case kConsole_##x: \
356 *value = INT_TO_JSVAL(x); \
357 break;
358 DEBUG_FLAG_CASE(DEBUG_LINKED_LISTS);
359 DEBUG_FLAG_CASE(DEBUG_COLLISIONS);
360 DEBUG_FLAG_CASE(DEBUG_DOCKING);
361 DEBUG_FLAG_CASE(DEBUG_OCTREE_LOGGING);
362 DEBUG_FLAG_CASE(DEBUG_BOUNDING_BOXES);
363 DEBUG_FLAG_CASE(DEBUG_OCTREE_DRAW);
364 DEBUG_FLAG_CASE(DEBUG_DRAW_NORMALS);
365 DEBUG_FLAG_CASE(DEBUG_NO_DUST);
366 DEBUG_FLAG_CASE(DEBUG_NO_SHADER_FALLBACK);
367 DEBUG_FLAG_CASE(DEBUG_SHADER_VALIDATION);
368
369 DEBUG_FLAG_CASE(DEBUG_MISC);
370#undef DEBUG_FLAG_CASE
371
372 default:
373 OOJSReportBadPropertySelector(context, this, propID, sConsoleProperties);
374 return NO;
375 }
376
377 return YES;
378
380}
381
382static JSBool ConsoleSetProperty(JSContext* context, JSObject* this, jsid propID, JSBool strict, jsval* value)
383{
384 if (!JSID_IS_INT(propID))
385 return YES;
386
387 OOJS_NATIVE_ENTER(context)
388
389 int32 iValue;
390 JSBool bValue = NO;
391 NSString* sValue;
392
393 switch (JSID_TO_INT(propID)) {
394#ifdef OO_DEBUG_MONITOR_ENABLED
395 case kConsole_debugFlags:
396 if (JS_ValueToInt32(context, *value, &iValue)) {
397 gDebugFlags = iValue;
398 }
399 break;
400#endif
401 case kConsole_detailLevel:
402 sValue = OOStringFromJSValue(context, *value);
404 [UNIVERSE setDetailLevel:OOGraphicsDetailFromString(sValue)];
406 break;
407
408 case kConsole_displayFPS:
409 if (JS_ValueToBoolean(context, *value, &bValue)) {
410 [UNIVERSE setDisplayFPS:bValue];
411 }
412 break;
413
414 case kConsole_pedanticMode:
415 if (JS_ValueToBoolean(context, *value, &bValue)) {
416 uint32_t options = JS_GetOptions(context);
417 if (bValue)
418 options |= JSOPTION_STRICT;
419 else
420 options &= ~JSOPTION_STRICT;
421
422 JS_SetOptions(context, options);
423 }
424 break;
425
426 case kConsole_ignoreDroppedPackets:
427 if (JS_ValueToBoolean(context, *value, &bValue)) {
429 }
430 break;
431
432 case kConsole_showErrorLocations:
433 if (JS_ValueToBoolean(context, *value, &bValue)) {
435 }
436 break;
437
438 case kConsole_dumpStackForErrors:
439 if (JS_ValueToBoolean(context, *value, &bValue)) {
440 [[OOJavaScriptEngine sharedEngine] setDumpStackForErrors:bValue];
441 }
442 break;
443
444 case kConsole_dumpStackForWarnings:
445 if (JS_ValueToBoolean(context, *value, &bValue)) {
446 [[OOJavaScriptEngine sharedEngine] setDumpStackForWarnings:bValue];
447 }
448 break;
449
450 default:
451 OOJSReportBadPropertySelector(context, this, propID, sConsoleProperties);
452 return NO;
453 }
454
455 return YES;
456
458}
459
460static BOOL DoWeDefineAllDebugFlags(enum OODebugFlags flags) GCC_ATTR((unused));
461static BOOL DoWeDefineAllDebugFlags(enum OODebugFlags flags)
462{
463 /* This function doesn't do anything, but will generate a warning
464 (Enumeration value 'DEBUG_FOO' not handled in switch) if a debug flag
465 is added without updating it. The point is that if you get such a
466 warning, you should first add a JS symbolic constant for the flag,
467 then add it to the switch to suppress the warning.
468 NOTE: don't add a default: to this switch, or I will have to hurt you.
469 -- Ahruman 2010-04-11
470 */
471 switch (flags) {
473 case DEBUG_COLLISIONS:
474 case DEBUG_DOCKING:
479 case DEBUG_NO_DUST:
482 case DEBUG_MISC:
483 return YES;
484 }
485
486 return NO;
487}
488
489static void ConsoleFinalize(JSContext* context, JSObject* this)
490{
492
493 [(id)JS_GetPrivate(context, this) release];
494 JS_SetPrivate(context, this, nil);
495
497}
498
499static JSBool ConsoleSettingsDeleteProperty(JSContext* context, JSObject* this, jsid propID, jsval* value)
500{
501 OOJS_NATIVE_ENTER(context)
502
503 NSString* key = nil;
504 id monitor = nil;
505
506 if (!JSID_IS_STRING(propID))
507 return NO;
508 key = OOStringFromJSString(context, JSID_TO_STRING(propID));
509
510 monitor = OOJSNativeObjectFromJSObject(context, this);
511 if (![monitor isKindOfClass:[OODebugMonitor class]]) {
512 OOJSReportError(context, @"Expected OODebugMonitor, got %@ in %s. %@", [monitor class], __PRETTY_FUNCTION__, @"This is an internal error, please report it.");
513 return NO;
514 }
515
516 [monitor setConfigurationValue:nil forKey:key];
517 *value = JSVAL_TRUE;
518 return YES;
519
521}
522
523static JSBool ConsoleSettingsGetProperty(JSContext* context, JSObject* this, jsid propID, jsval* value)
524{
525 if (!JSID_IS_STRING(propID))
526 return YES;
527
528 OOJS_NATIVE_ENTER(context)
529
530 NSString* key = nil;
531 id settingValue = nil;
532 id monitor = nil;
533
534 key = OOStringFromJSString(context, JSID_TO_STRING(propID));
535
536 monitor = OOJSNativeObjectFromJSObject(context, this);
537 if (![monitor isKindOfClass:[OODebugMonitor class]]) {
538 OOJSReportError(context, @"Expected OODebugMonitor, got %@ in %s. %@", [monitor class], __PRETTY_FUNCTION__, @"This is an internal error, please report it.");
539 return NO;
540 }
541
542 settingValue = [monitor configurationValueForKey:key];
543 if (settingValue != NULL)
544 *value = [settingValue oo_jsValueInContext:context];
545 else
546 *value = JSVAL_VOID;
547
548 return YES;
549
551}
552
553static JSBool ConsoleSettingsSetProperty(JSContext* context, JSObject* this, jsid propID, JSBool strict, jsval* value)
554{
555 if (!JSID_IS_STRING(propID))
556 return YES;
557
558 OOJS_NATIVE_ENTER(context)
559
560 NSString* key = nil;
561 id settingValue = nil;
562 id monitor = nil;
563
564 key = OOStringFromJSString(context, JSID_TO_STRING(propID));
565
566 monitor = OOJSNativeObjectFromJSObject(context, this);
567 if (![monitor isKindOfClass:[OODebugMonitor class]]) {
568 OOJSReportError(context, @"Expected OODebugMonitor, got %@ in %s. %@", [monitor class], __PRETTY_FUNCTION__, @"This is an internal error, please report it.");
569 return NO;
570 }
571
572 // Not OOJS_BEGIN_FULL_NATIVE() - we use JSAPI while paused.
574 if (JSVAL_IS_NULL(*value) || JSVAL_IS_VOID(*value)) {
575 [monitor setConfigurationValue:nil forKey:key];
576 } else {
577 settingValue = OOJSNativeObjectFromJSValue(context, *value);
578 if (settingValue != nil) {
579 [monitor setConfigurationValue:settingValue forKey:key];
580 } else {
581 OOJSReportWarning(context, @"debugConsole.settings: could not convert %@ to native object.", OOStringFromJSValue(context, *value));
582 }
583 }
585
586 return YES;
587
589}
590
591// *** Methods ***
592
593// function consoleMessage(colorCode : String, message : String [, emphasisStart : Number, emphasisLength : Number]) : void
594static JSBool ConsoleConsoleMessage(JSContext* context, uintN argc, jsval* vp)
595{
596 NSRange emphasisRange = { 0, 0 };
597
598 OOJS_NATIVE_ENTER(context)
599
600 id monitor = nil;
601 NSString *colorKey = nil,
602 *message = nil;
603 jsdouble location, length;
604
605 // Not OOJS_BEGIN_FULL_NATIVE() - we use JSAPI while paused.
607 monitor = OOJSNativeObjectOfClassFromJSObject(context, OOJS_THIS, [OODebugMonitor class]);
608 if (monitor == nil) {
609 OOJSReportError(context, @"Expected OODebugMonitor, got %@ in %s. %@", [monitor class], __PRETTY_FUNCTION__, @"This is an internal error, please report it.");
611 return NO;
612 }
613
614 if (argc > 0)
615 colorKey = OOStringFromJSValue(context, OOJS_ARGV[0]);
616 if (argc > 1)
617 message = OOStringFromJSValue(context, OOJS_ARGV[1]);
618
619 if (argc > 3) {
620 // Attempt to get two numbers, specifying an emphasis range.
621 if (JS_ValueToNumber(context, OOJS_ARGV[2], &location) && JS_ValueToNumber(context, OOJS_ARGV[3], &length)) {
622 emphasisRange = (NSRange) { location, length };
623 }
624 }
625
626 if (message == nil) {
627 if (colorKey == nil) {
628 OOJSReportWarning(context, @"Console.consoleMessage() called with no parameters.");
629 } else {
630 message = colorKey;
631 colorKey = @"command-result";
632 }
633 }
634
635 if (message != nil) {
636 [monitor appendJSConsoleLine:message
637 colorKey:colorKey
638 emphasisRange:emphasisRange];
639 }
641
643
645}
646
647// function clearConsole() : void
648static JSBool ConsoleClearConsole(JSContext* context, uintN argc, jsval* vp)
649{
650 OOJS_NATIVE_ENTER(context)
651
652 id monitor = nil;
653
654 monitor = OOJSNativeObjectFromJSObject(context, OOJS_THIS);
655 if (![monitor isKindOfClass:[OODebugMonitor class]]) {
656 OOJSReportError(context, @"Expected OODebugMonitor, got %@ in %s. %@", [monitor class], __PRETTY_FUNCTION__, @"This is an internal error, please report it.");
657 return NO;
658 }
659
660 [monitor clearJSConsole];
662
664}
665
666// function scriptStack() : Array
667static JSBool ConsoleScriptStack(JSContext* context, uintN argc, jsval* vp)
668{
669 OOJS_NATIVE_ENTER(context)
670
671 OOJS_RETURN_OBJECT([OOJSScript scriptStack]);
672
674}
675
676// function inspectEntity(entity : Entity) : void
677static JSBool ConsoleInspectEntity(JSContext* context, uintN argc, jsval* vp)
678{
679 OOJS_NATIVE_ENTER(context)
680
681 Entity* entity = nil;
682
683 if (JSValueToEntity(context, OOJS_ARGV[0], &entity)) {
685 if ([entity respondsToSelector:@selector(inspect)]) {
686 [entity inspect];
687 }
689 }
690
692
694}
695
696#if OO_DEBUG
697// function callObjC(selector : String [, ...]) : Object
698static JSBool ConsoleCallObjCMethod(JSContext* context, uintN argc, jsval* vp)
699{
700 OOJS_NATIVE_ENTER(context)
701
702 id object = nil;
703 jsval result;
704 BOOL OK;
705
706 object = OOJSNativeObjectFromJSObject(context, OOJS_THIS);
707 if (object == nil) {
708 OOJSReportError(context, @"Attempt to call __callObjCMethod() for non-Objective-C object %@.", OOStringFromJSValueEvenIfNull(context, JS_THIS(context, vp)));
709 return NO;
710 }
711
713 result = JSVAL_VOID;
714 OK = OOJSCallObjCObjectMethod(context, object, [object oo_jsClassName], argc, OOJS_ARGV, &result);
716
717 OOJS_SET_RVAL(result);
718 return OK;
719
721}
722
723// function __setUpCallObjC(object) -- object is expected to be Object.prototye.
724static JSBool ConsoleSetUpCallObjC(JSContext* context, uintN argc, jsval* vp)
725{
726 OOJS_NATIVE_ENTER(context)
727
728 if (EXPECT_NOT(!JSVAL_IS_OBJECT(OOJS_ARGV[0]))) {
729 OOJSReportBadArguments(context, @"Console", @"__setUpCallObjC", argc, OOJS_ARGV, nil, @"Object.prototype");
730 return NO;
731 }
732
733 JSObject* obj = JSVAL_TO_OBJECT(OOJS_ARGV[0]);
734 JS_DefineFunction(context, obj, "callObjC", ConsoleCallObjCMethod, 1, OOJS_METHOD_READONLY);
736
738}
739#endif
740
741// function isExecutableJavaScript(this : Object, string : String) : Boolean
742static JSBool ConsoleIsExecutableJavaScript(JSContext* context, uintN argc, jsval* vp)
743{
744 OOJS_NATIVE_ENTER(context)
745
746 BOOL result = NO;
747 JSObject* target = NULL;
748
749 if (argc < 2 || !JS_ValueToObject(context, OOJS_ARGV[0], &target) || !JSVAL_IS_STRING(OOJS_ARGV[1])) {
750 OOJS_RETURN_BOOL(NO); // Fail silently
751 }
752
753 // Not OOJS_BEGIN_FULL_NATIVE() - we use JSAPI while paused.
755
756 // FIXME: this must be possible using just JSAPI functions.
757 NSString* string = OOStringFromJSValue(context, OOJS_ARGV[1]);
758 NSData* stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
759 result = JS_BufferIsCompilableUnit(context, target, [stringData bytes], [stringData length]);
760
762
763 OOJS_RETURN_BOOL(result);
764
766}
767
768// function displayMessagesInClass(class : String) : Boolean
769static JSBool ConsoleDisplayMessagesInClass(JSContext* context, uintN argc, jsval* vp)
770{
771 OOJS_NATIVE_ENTER(context)
772
773 NSString* messageClass = nil;
774
775 messageClass = OOStringFromJSValue(context, OOJS_ARGV[0]);
776 OOJS_RETURN_BOOL(messageClass != nil && OOLogWillDisplayMessagesInClass(messageClass));
777
779}
780
781// function setDisplayMessagesInClass(class : String, flag : Boolean) : void
782static JSBool ConsoleSetDisplayMessagesInClass(JSContext* context, uintN argc, jsval* vp)
783{
784 OOJS_NATIVE_ENTER(context)
785
786 NSString* messageClass = nil;
787 JSBool flag;
788
789 messageClass = OOStringFromJSValue(context, OOJS_ARGV[0]);
790 if (messageClass != nil && JS_ValueToBoolean(context, OOJS_ARGV[1], &flag)) {
791 OOLogSetDisplayMessagesInClass(messageClass, flag);
792 }
794
796}
797
798// function writeLogMarker() : void
799static JSBool ConsoleWriteLogMarker(JSContext* context, uintN argc, jsval* vp)
800{
801 OOJS_NATIVE_ENTER(context)
802
805
807}
808
809// function writeMemoryStats() : void
810static JSBool ConsoleWriteMemoryStats(JSContext* context, uintN argc, jsval* vp)
811{
812 OOJS_NATIVE_ENTER(context)
813
817
819
821}
822
823// function writeJSMemoryStats() : void
824static JSBool ConsoleWriteJSMemoryStats(JSContext* context, uintN argc, jsval* vp)
825{
826 OOJS_NATIVE_ENTER(context)
827
831
833
835}
836
837// function garbageCollect() : string
838static JSBool ConsoleGarbageCollect(JSContext* context, uintN argc, jsval* vp)
839{
840 OOJS_NATIVE_ENTER(context)
841
842 uint32_t bytesBefore = JS_GetGCParameter(JS_GetRuntime(context), JSGC_BYTES);
843 JS_GC(context);
844 uint32_t bytesAfter = JS_GetGCParameter(JS_GetRuntime(context), JSGC_BYTES);
845
846 OOJS_RETURN_OBJECT(([NSString stringWithFormat:@"Bytes before: %u Bytes after: %u", bytesBefore, bytesAfter]));
847
849}
850
851#if DEBUG
852typedef struct
853{
854 JSContext* context;
855 FILE* file;
856} DumpCallbackData;
857
858static void DumpCallback(const char* name, void* rp, JSGCRootType type, void* datap)
859{
860 assert(type == JS_GC_ROOT_VALUE_PTR || type == JS_GC_ROOT_GCTHING_PTR);
861
862 DumpCallbackData* data = datap;
863
864 const char* typeString = "unknown type";
865 jsval value;
866 switch (type) {
867 case JS_GC_ROOT_VALUE_PTR:
868 typeString = "value";
869 value = *(jsval*)rp;
870 break;
871
872 case JS_GC_ROOT_GCTHING_PTR:
873 typeString = "gc-thing";
874 value = OBJECT_TO_JSVAL(*(JSObject**)rp);
875 }
876
877 fprintf(data->file, "%s @ %p (%s): %s\n", name, rp, typeString, [OOJSDescribeValue(data->context, value, NO) UTF8String]);
878}
879
880static JSBool ConsoleDumpNamedRoots(JSContext* context, uintN argc, jsval* vp)
881{
882 OOJS_NATIVE_ENTER(context)
883
884 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
885
886 BOOL OK = NO;
887 NSString* path = [[ResourceManager diagnosticFileLocation] stringByAppendingPathComponent:@"js-roots.txt"];
888 FILE* file = fopen([path UTF8String], "w");
889 if (file != NULL) {
890 DumpCallbackData data = {
891 .context = context,
892 .file = file
893 };
894 JS_DumpNamedRoots(JS_GetRuntime(context), DumpCallback, &data);
895 fclose(file);
896 OK = YES;
897 }
898
899 [pool release];
901
903}
904
905static JSBool ConsoleDumpHeap(JSContext* context, uintN argc, jsval* vp)
906{
907 OOJS_NATIVE_ENTER(context)
908
909 BOOL OK = NO;
910 NSString* path = [[ResourceManager diagnosticFileLocation] stringByAppendingPathComponent:@"js-heaps.txt"];
911 FILE* file = fopen([path UTF8String], "w");
912 if (file != NULL) {
913 OK = JS_DumpHeap(context, file, NULL, 0, NULL, SIZE_MAX, NULL);
914 fclose(file);
915 }
916
918
920}
921#endif
922
923#if OOJS_PROFILE
924
925// function profile(func : function [, Object this = debugConsole.script]) : String
926static JSBool ConsoleProfile(JSContext* context, uintN argc, jsval* vp)
927{
928 OOJS_NATIVE_ENTER(context)
929
930 if (EXPECT_NOT(OOJSIsProfiling())) {
931 OOJSReportError(context, @"Profiling functions may not be called while already profiling.");
932 return NO;
933 }
934
935 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
936 OOTimeProfile* profile = nil;
937
938 JSBool result = PerformProfiling(context, @"profile", argc, OOJS_ARGV, NULL, NO, &profile);
939 if (result) {
940 OOJS_SET_RVAL(OOJSValueFromNativeObject(context, [profile description]));
941 }
942
943 [pool release];
944 return result;
945
947}
948
949// function getProfile(func : function [, Object this = debugConsole.script]) : Object { totalTime : Number, jsTime : Number, extensionTime : Number }
950static JSBool ConsoleGetProfile(JSContext* context, uintN argc, jsval* vp)
951{
952 OOJS_NATIVE_ENTER(context)
953
954 if (EXPECT_NOT(OOJSIsProfiling())) {
955 OOJSReportError(context, @"Profiling functions may not be called while already profiling.");
956 return NO;
957 }
958
959 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
960 OOTimeProfile* profile = nil;
961
962 JSBool result = PerformProfiling(context, @"getProfile", argc, OOJS_ARGV, NULL, NO, &profile);
963 if (result) {
964 OOJS_SET_RVAL(OOJSValueFromNativeObject(context, profile));
965 }
966
967 [pool release];
968 return result;
969
971}
972
973// function trace(func : function [, Object this = debugConsole.script]) : [return type of func]
974static JSBool ConsoleTrace(JSContext* context, uintN argc, jsval* vp)
975{
976 OOJS_NATIVE_ENTER(context)
977
978 if (EXPECT_NOT(OOJSIsProfiling())) {
979 OOJSReportError(context, @"Profiling functions may not be called while already profiling.");
980 return NO;
981 }
982
983 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
984 jsval rval;
985
986 JSBool result = PerformProfiling(context, @"trace", argc, OOJS_ARGV, &rval, YES, NULL);
987 if (result) {
988 OOJS_SET_RVAL(rval);
989 }
990
991 [pool release];
992 return result;
993
995}
996
997static JSBool PerformProfiling(JSContext* context, NSString* nominalFunction, uintN argc, jsval* argv, jsval* outRval, BOOL trace, OOTimeProfile** outProfile)
998{
999 // Get function.
1000 jsval function = argv[0];
1001 if (!OOJSValueIsFunction(context, function)) {
1002 OOJSReportBadArguments(context, @"Console", nominalFunction, 1, argv, nil, @"function");
1003 return NO;
1004 }
1005
1006 // Get "this" object.
1007 jsval this;
1008 if (argc > 1)
1009 this = argv[1];
1010 else {
1011 jsval debugConsole = OOJSValueFromNativeObject(context, [OODebugMonitor sharedDebugMonitor]);
1012 assert(JSVAL_IS_OBJECT(debugConsole) && !JSVAL_IS_NULL(debugConsole));
1013 JS_GetProperty(context, JSVAL_TO_OBJECT(debugConsole), "script", &this);
1014 }
1015
1016 JSObject* thisObj;
1017 if (!JS_ValueToObject(context, this, &thisObj))
1018 thisObj = NULL;
1019
1020 jsval ignored;
1021 if (outRval == NULL)
1022 outRval = &ignored;
1023
1024 // Fiddle with time limiter.
1025 // We want to save the current limit, reset the limiter, and set the time limit to a long time.
1026#define LONG_TIME (1e7) // A long time - 115.7 days - but, crucially, finite.
1027
1028 OOTimeDelta originalLimit = OOJSGetTimeLimiterLimit();
1029 OOJSSetTimeLimiterLimit(LONG_TIME);
1031
1032 OOJSBeginProfiling(trace);
1033
1034 // Call the function.
1035 BOOL result = JS_CallFunctionValue(context, thisObj, function, 0, NULL, outRval);
1036
1037 // Get results.
1038 OOTimeProfile* profile = OOJSEndProfiling();
1039 if (outProfile != NULL)
1040 *outProfile = profile;
1041
1042 // Restore original timer state.
1043 OOJSSetTimeLimiterLimit(originalLimit);
1045
1046 JS_ReportPendingException(context);
1047
1048 return result;
1049}
1050
1051#endif // OOJS_PROFILE
1052
1053#endif /* OO_DEBUG_MONITOR_ENABLED */
#define gDebugFlags
OODebugFlags
Definition OODebugFlags.h:3
@ DEBUG_COLLISIONS
Definition OODebugFlags.h:6
@ DEBUG_NO_DUST
@ DEBUG_DOCKING
Definition OODebugFlags.h:7
@ DEBUG_SHADER_VALIDATION
@ DEBUG_MISC
@ DEBUG_OCTREE_LOGGING
Definition OODebugFlags.h:8
@ DEBUG_OCTREE_DRAW
@ DEBUG_NO_SHADER_FALLBACK
@ DEBUG_DRAW_NORMALS
@ DEBUG_LINKED_LISTS
Definition OODebugFlags.h:4
@ DEBUG_BOUNDING_BOXES
#define EXPECT_NOT(x)
#define GCC_ATTR(x)
JSObject * DebugMonitorToJSConsole(JSContext *context, OODebugMonitor *monitor)
void OOJSConsoleDestroy(void)
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_END_FULL_NATIVE
#define OOJS_BEGIN_FULL_NATIVE(context)
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_NATIVE_EXIT
#define OOJS_PROFILE_ENTER
void OOJSResetTimeLimiter(void)
OOTimeDelta OOJSGetTimeLimiterLimit(void)
void OOJSSetTimeLimiterLimit(OOTimeDelta limit)
BOOL JSValueToEntity(JSContext *context, jsval value, Entity **outEntity)
Definition OOJSEntity.m:133
void OOJSPauseTimeLimiter(void)
id OOJSNativeObjectFromJSValue(JSContext *context, jsval value)
void OOJSReportWarning(JSContext *context, NSString *format,...)
#define OOJS_THIS
#define OOJS_SET_RVAL(v)
#define OOJS_PROP_READWRITE_CB
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
id OOJSNativeObjectFromJSObject(JSContext *context, JSObject *object)
#define OOJS_RETURN_OBJECT(o)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
#define OOJS_RETURN_BOOL(v)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
NSString * OOJSDescribeValue(JSContext *context, jsval value, BOOL abbreviateObjects)
void OOJSReportError(JSContext *context, NSString *format,...)
#define OOJS_ARGV
OOINLINE jsval OOJSValueFromBOOL(int b) INLINE_CONST_FUNC
NSString * OOStringFromJSValueEvenIfNull(JSContext *context, jsval value)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, NSString *message, NSString *expectedArgsDescription)
#define OOJS_PROP_READONLY_CB
void OOJSResumeTimeLimiter(void)
#define OOJS_PROP_HIDDEN_READWRITE_CB
#define OOJS_RETURN_VOID
NSString * OOStringFromJSString(JSContext *context, JSString *string)
#define OOJS_METHOD_READONLY
id OOJSNativeObjectOfClassFromJSObject(JSContext *context, JSObject *object, Class requiredClass)
NSString * OOPlatformDescription(void)
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
void OOLogSetDisplayMessagesInClass(NSString *inClass, BOOL inFlag)
Definition OOLogging.m:172
void OOLogInsertMarker(void)
Definition OOLogging.m:581
return nil
double OOTimeDelta
Definition OOTypes.h:193
#define UNIVERSE
Definition Universe.h:827
void dumpMemoryStatistics()
void setTCPIgnoresDroppedPackets:(BOOL flag)
size_t dumpJSMemoryStatistics()
OODebugMonitor * sharedDebugMonitor()
void setShowErrorLocations:(BOOL value)
OOJavaScriptEngine * sharedEngine()
OOOpenGLExtensionManager * sharedManager()
NSString * diagnosticFileLocation()