-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsdb.cpp
1185 lines (1066 loc) · 29.7 KB
/
jsdb.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "jsdb.h"
#include "rslib.h"
//#include "jscpucfg.h" // file missing in tracemonkey
#include "rs/wrap_jsdb.h"
#include "jspubtd.h"
#ifdef XP_WIN
#include <conio.h>
#endif
#ifdef XP_UNIX
#include <sys/select.h>
extern "C" char * readline(char *prompt);
extern "C" void add_history(char *line);
#endif
//#include "jscntxt.h"
// needed for Coinitialize because of WIN32_LEAN_AND_MEAN=1 defined in tracemonkey
#ifdef XP_WIN
#include <Objbase.h>
#endif
class System
{
public:
TStr path;
TParameterList modules;
#ifndef JSDB_MINIMAL
ZipArchive* zip;
#endif
System()
{
#ifdef XP_WIN
modules.CaseSensitive = false;
#else
modules.CaseSensitive = true;
#endif
#ifndef JSDB_MINIMAL
zip = 0;
#endif
}
};
// wrap RS lib functions in JavaScript
TParameterList GlobalOptions;
void StartConsole(JSDBEnvironment*Env);
void ExecCommand(JSDBEnvironment* Env,const char * cmd,size_t len,uintN line);
void PrintDirectory(Stream& out, const char * filter = 0);
NATIVE(GarbageCollect)
{
JS_GC(cx);
RETBOOL(true);
}
//extern JSBool
//Readln(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
NATIVE(Readbytes)
{
if (argc == 0) ERR_COUNT(system,read);
GETARGS;
if (!ISINT(0)) ERR_TYPE(system,read,1,Integer);
GETENV;
if (Env->in)
{
int32 length;
TOINT(0,length);
int pos = 0;
if (length < 1) RETSTRW(L"");
TStr line(length);
#ifdef XP_WIN
DWORD mode;
FileStream* fs = TYPESAFE_DOWNCAST(Env->in,FileStream);
HANDLE h = fs ? fs->File : 0;
// if (!strcmp(Env->in->filename(),"stdin"))
// h = GetStdHandle(STD_INPUT_HANDLE);
if (h) if (!GetConsoleMode(h,&mode) || (GetFileType(h) != FILE_TYPE_CHAR)) h=0;
if (h) SetConsoleMode(h,mode & ~(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_OUTPUT));
#endif
while (pos < length)
{
pos += Env->in->read(line + pos,length - pos);
}
#ifdef XP_WIN
if (h) SetConsoleMode(h,mode);
#endif
RETSTRWC(line);
}
RETSTRW(L"");
}
//-------------------
NATIVE(Help)
{
GETENV;
WRITELN("JSDB " JSDB_VERSION " " JSDB_DATE "\n"
JSDB_COPYRIGHT " See http://www.jsdb.org/\n");
return JS_TRUE;
}
NATIVE(TestCompile)
{
if (argc == 0) ERR_COUNT(jsdb,testCompile);
GETARGS;
if (!ISSTR(0)) ERR_TYPE(jsdb,testCompile,1,String);
GETENV;
JSString* str = JSVAL_TO_STRING(argv[0]);
MemoryStream f;
Stream* oldout = Env->out;
Env->out = &f;
size_t length;
#if JS_VERSION > 180
const jschar* chars = JS_GetStringCharsAndLength(cx, str, &length);
#else
const jschar* chars = JS_GetStringChars(str);
length = JS_GetStringLength(str);
#endif
JSScript * script = JS_CompileUCScript( Env->cx,
Env->global,
chars,
length,
"",
1);
Env->out = oldout;
RETSTR((char*)f);
// garbage collection should take care of script
}
NATIVE(Mkdir)
{
if (argc > 0)
{
GETUTF8(0);
MakeDirectoryExist(u0);
}
RETBOOL(true);
}
NATIVE(Resource)
{
GETENV;
if (argc < 1) RETOBJ(0);
JSString *str;
Stream* dt = 0;
if (!ISSTR(0)) RETBOOL(false);
GETUTF8(0);
const char * filename = u0;
//look for the file in the EXE's ZIP archive
System* sys = (System*)Env->System;
if (sys)
{
#ifndef JSDB_MINIMAL
ZipArchive * zip = sys->zip;
size_t index = NOT_FOUND;
if (zip) index = zip->Find(filename);
if (index != NOT_FOUND)
{
dt = new MemoryStream;
if (zip->Extract(index,*dt))
{
dt->rewind();
}
} else
#endif
//look in the path (never the local directory)
if (!strchr(filename,'/') && !strchr(filename,'\\'))
{
TStr file(sys->path,filename);
FixFilename(file);
if (FileExists(file))
{
try
{
dt = new FileStream(file,Stream::OMBinary,Stream::ReadOnly);
}catch(...) {}
}
}
}
if (dt)
RETOBJ(Stream_Object(cx,dt,true,0));
RETOBJ(0);
}
JSBool DiskLoadProgram(JSContext* cx, JSObject* obj,JSDBEnvironment* Env, System* sys, const char* file, jsval *rval)
{
//then use the file name
if (FileExists(file))
{
int line = 1;
FileStream in(file,Stream::OMBinary,Stream::ReadOnly);
if (rval) *rval = BOOLEAN_TO_JSVAL(true);
return Env->ExecScript(cx,obj,in,in.filename(),line);
}
if (rval) *rval = BOOLEAN_TO_JSVAL(false);
return JS_TRUE;
}
#ifndef JSDB_MINIMAL
JSBool ZipLoadProgram(JSContext* cx, JSObject* obj,JSDBEnvironment* Env, System* sys, const char* file, jsval *rval)
{
if (sys)
{
//look for the file in the EXE's ZIP archive
ZipArchive * zip = sys->zip;
size_t index = NOT_FOUND;
if (zip) index = zip->Find(file);
if (index != NOT_FOUND)
{
int line = 1;
MemoryStream m;
if (zip->Extract(index,m))
{
m.rewind();
*rval = BOOLEAN_TO_JSVAL(Env->ExecScript(cx,obj,m,file,line));
return JS_TRUE;
}
}
}
*rval = BOOLEAN_TO_JSVAL(false);
return JS_FALSE;
}
#endif
/*
JSBool Run(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
GETENV;
*rval = OBJECT_TO_JSVAL(0);
if (Env->SafeMode) RETBOOL(false);
if (argc < 1) RETBOOL(false);
JSString *str;
Stream* data;
GETFILE(0,data);
try
{
if (data) //execute from a stream
{
const char* filename = (argc > 1 && ISSTR(1)) ? STR(1) : data->filename();
int line = (argc > 2 && ISINT(2)) ? INT(2) : 1;
*rval = BOOLEAN_TO_JSVAL(true);
return Env->ExecScript(*data,filename,line);
}
else //load a file
{
if (!ISSTR(0)) RETBOOL(false);
const char * filename = STR(0);
System* sys = (System*)Env->System;
return LoadProgram(Env,sys,filename,rval);
}
}
catch(xdb& x)
{
ERR_MSG(Load,"File open failure",TStr(x.why(), x.info()));
}
}
*/
NATIVE(Run)
{
GETENV;
GETTHIS;
if (Env->SafeMode) RETBOOL(false);
if (argc < 1) RETBOOL(false);
Stream* data;
GETFILE(0,data);
RETVAL(OBJECT_TO_JSVAL(0));
// JSObject* executionObject = JS_GetScopeChain(cx);
//if (argc > 1 && JSVAL_IS_OBJECT(ARGV(1)))
//executionObject= JSVAL_TO_OBJECT(ARGV(1)) ;
//if (executionObject && JS_IsArrayObject(cx,executionObject))
// executionObject = NULL;
try
{
if (data) //execute from a stream
{
GETUTF8(1);
const char* filename = (argc > 1 ? (const char*)u1 : data->filename());
int32 line = 1;
if (argc > 2 && ISINT(2))
TOINT(2,line);
RETVAL(BOOLEAN_TO_JSVAL(true));
return Env->ExecScript(cx,obj,*data,filename,line);
}
if (!ISSTR(0)) RETBOOL(false);
GETUTF8(0);
TStr name(u0); //use the original when looking up in a Zip archive
Replace(name, "\\", '/');
System* sys = (System*)Env->System;
#ifndef JSDB_MINIMAL
if (sys)
{
ZipArchive * zip = sys->zip;
if (zip)
{
if (zip->Find(u0) != NOT_FOUND)
return ZipLoadProgram(cx,obj,Env,sys,u0,RVAL);
}
}
#endif
/* The local directory overrides the system path */
FixFilename(name);
if (sys)
{
TStr othername(sys->path,name);
FixFilename(othername);
if (!FileExists(name) && FileExists(othername))
name = othername;
}
return DiskLoadProgram(cx,obj,Env,sys,name,RVAL);
}
catch(xdb& x)
{
ERR_MSG(Load,"File open failure",TStr(x.why(), x.info()));
}
}
NATIVE(Load)
{
GETENV;
RETVAL(OBJECT_TO_JSVAL(0));
if (Env->SafeMode) RETBOOL(false);
if (argc < 1) RETBOOL(false);
try
{
if (!ISSTR(0)) RETBOOL(false);
GETUTF8(0);
int filetime = 0;
TStr name(u0);
Replace(name, "\\", '/');
System* sys = (System*)Env->System;
#ifndef JSDB_MINIMAL
if (sys)
{
ZipArchive * zip = sys->zip;
if (zip)
{
if (zip->Find(u0) != NOT_FOUND)
{
if (sys->modules.Has(u0)) RETBOOL(true);
JSBool ret = ZipLoadProgram(cx,obj,Env,sys,u0,RVAL);
if (ret) sys->modules.Set(u0,1);
return ret;
}
}
}
#endif
/* The local directory overrides the system path */
FixFilename(name);
if (sys)
{
TStr othername(sys->path,name);
FixFilename(othername);
if (!FileExists(name) && FileExists(othername))
name = othername;
#ifdef XP_WIN
WIN32_FILE_ATTRIBUTE_DATA attr;
if (GetFileAttributesExW(WStr(name),GetFileExInfoStandard,&attr))
filetime = attr.ftLastWriteTime.dwLowDateTime;
#else
struct stat ms;
int x = stat(name,&ms);
if (x == 0) filetime = ms.st_mtime;
#endif
}
if (sys && filetime)
{
if (sys->modules.GetInt(name) == filetime)
RETBOOL(true);
}
JSBool ret = DiskLoadProgram(cx,obj,Env,sys,name,RVAL);
if (ret && sys) sys->modules.Set(name,filetime);
return ret;
}
catch(xdb& x)
{
ERR_MSG(Load,"File open failure",TStr(x.why(), x.info()));
}
}
/*
JSBool OldLoad(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
GETENV;
*rval = OBJECT_TO_JSVAL(0);
if (Env->SafeMode) RETBOOL(false);
if (argc < 1) RETBOOL(false);
try
{
if (!ISSTR(0)) RETBOOL(false);
System* sys = (System*)Env->System;
GETUTF8(0);
int filetime = 0;
#ifndef JSDB_MINIMAL
ZipArchive * zip = sys->zip;
if (zip)
{
if (zip->Find(s0) != NOT_FOUND)
filetime = 1;
JSBool ret = ZipLoadProgram(Env,sys,s0,rval);
if (ret && sys) sys->modules.Set(s0,filetime);
return ret;
}
else
#endif
{
TStr othername(sys->path,s0);
FixFilename(othername);
if (!FileExists(s0) && FileExists(othername))
s0 = othername;
#ifdef XP_WIN
WIN32_FILE_ATTRIBUTE_DATA attr;
if (GetFileAttributesExW(WStr(s0),GetFileExInfoStandard,&attr))
filetime = attr.ftLastWriteTime.dwLowDateTime;
#else
struct stat ms;
int x = stat(s0,&ms);
if (x > 0) filetime = ms.st_mtime;
#endif
}
if (sys && filetime)
{
if (sys->modules.GetInt(s0) == filetime)
RETBOOL(true);
}
JSBool ret = DiskLoadProgram(Env,sys,s0,rval);
if (ret && sys) sys->modules.Set(s0,filetime);
return ret;
}
catch(xdb& x)
{
ERR_MSG(Load,"File open failure",TStr(x.why(), x.info()));
}
}
*/
NATIVE(KBHit)
{
JS_MaybeGC(cx);
#ifdef XP_WIN
static INPUT_RECORD pinp[128];
DWORD nread, nevents, j;
HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
GetNumberOfConsoleInputEvents(hstdin, &nevents);
//printf("input %d\n",nevents);
if (nevents == 0)
RETBOOL(false);
if (nevents > 128) nevents = 128;
PeekConsoleInput(hstdin, pinp, nevents, &nread);
for (j = 0;j<nevents;j++)
if ((pinp[j].EventType & KEY_EVENT) != 0)
if (pinp[j].Event.KeyEvent.bKeyDown != 0)
{
if ((pinp[j].Event.KeyEvent.wVirtualKeyCode == VK_SHIFT) ||
(pinp[j].Event.KeyEvent.wVirtualKeyCode == VK_CONTROL) ||
(pinp[j].Event.KeyEvent.wVirtualKeyCode == VK_MENU))
continue;
else
RETBOOL(true);
}
//discard the events we just peeked
//ReadConsoleInput(hstdin,pinp,nread,&nread);
RETBOOL(false);
#else
struct timeval tv;
fd_set read_fd;
tv.tv_sec=0;
tv.tv_usec=0;
FD_ZERO(&read_fd);
FD_SET(0,&read_fd);
if (select(1, &read_fd, NULL, NULL, &tv) == -1)
RETBOOL(false);
if(FD_ISSET(0,&read_fd))
RETBOOL(true);
RETBOOL(false);
#endif
}
inline bool isCGI()
{
const char* c = getenv("GATEWAY_INTERFACE");
return c && (c[0] == 'C' && c[1] == 'G' && c[2] == 'I');
}
void CGIErrorMessage(Stream& out)
{
if (isCGI()) out << "Content-Type: text/plain\nWarn: 500 Script Error\n\n";
}
int main(int argc, char **argv)
{
//JS_SetCStringsAreUTF8(); //oops. broke binary in/out
/*set up global JS variables, including global and custom objects */
/* can't trust argv[0] on gcc. */
#ifdef _Windows
char argv0[MAXPATH+1];
argv0[MAXPATH]=0;
GetModuleFileName(0,argv0,MAXPATH);
#else
char* argv0 = argv[0];
#if defined(XP_MACOSX) || defined(__sun__)
char selfpath[PATH_MAX+1];
selfpath[PATH_MAX]=0;
if (realpath(argv[0],selfpath));
argv0 = selfpath;
#else
char selfpath[PATH_MAX+1];
selfpath[PATH_MAX]=0;
if (readlink( "/proc/self/exe", selfpath, PATH_MAX) > 0)
argv0 = selfpath;
#endif
#endif
int dummy = 0;
TBLEnv Tables;
TPointer<JSDBEnvironment> Env(new JSDBEnvironment(&Tables));
Env->reportWarnings = false;
Env->shouldStop = false;
/*
const int minbytes = 8L * 1024L * 1024L;
int maxbytes = minbytes;
char mbmul = 'B';
char *mbstr = NULL;
mbstr = getenv("JSDB_MAXBYTES");
if (mbstr != NULL) {
sscanf(mbstr,"%d%c",&maxbytes,mbmul);
if (maxbytes < 0)
maxbytes = 0;
if (mbmul = 'M')
maxbytes *= 1000000;
else
if (mbmul = 'K')
maxbytes *= 1000;
}
if (maxbytes < minbytes)
maxbytes = minbytes;
*/
Env->rt = JS_NewRuntime(200L * 1024L * 1024L/*maxbytes*/);
if (!Env->rt)
{
return 1;
}
Env->cx = JS_NewContext(Env->rt, 8192);
JS_SetVersion(Env->cx,JSVERSION_1_7);
if (!Env->cx)
{
JS_DestroyRuntime(Env->rt);
return 2;
}
#ifdef XP_WIN
CoInitialize(NULL);
#endif
Env->in = new FileStream("stdin",Stream::OMBinary);
Env->out = new FileStream("stdout",Stream::OMBinary);
Env->err = new FileStream("stderr",Stream::OMBinary);
JSFunctionSpec extra_functions[] = {
{"load", Load, 1},
{"run", Run, 1},
//{"loadResource", Resource, 1},
//{"help", Help, 0},
//{"jsTestCompile", TestCompile, 1},
//{"jsGC", GarbageCollect, 0},
{0}};
JSFunctionSpec extra_functions2[] = {
{"load", Load, 1},
{"run", Load, 1},
{"resource", Resource, 1},
{"help", Help, 0},
{"compile", TestCompile, 1},
{"gc", GarbageCollect, 0},
{"read", Readbytes, 1},
//{"readln", Readln, 1},
//{"readLine", Readln, 1},
{"mkdir", Mkdir, 1},
{"kbhit", KBHit, 1},
{0}};
jsval rval;
Env->InitGlobal(0);
Env->AllowExec = true;
JS_InitStandardClasses(Env->cx, Env->global);
Env->InitClasses();
Env->DefineProcessFunctions();
Env->DefineShellFunctions();
JSObject* sys = Env->DefineSystemObject(extra_functions2);
JS_DefineFunctions(Env->cx, Env->global, extra_functions);
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_VAROBJFIX);
#ifdef JSOPTION_XML
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_XML);
#endif
#ifdef JSOPTION_JIT // Default is nojit
// JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_JIT);
#endif
{
JSObject* ret = Stream_Object(Env->cx,Env->in,false,0);
jsval ptr = OBJECT_TO_JSVAL(ret);
JSBool foundp = 0;
JS_SetProperty(Env->cx, sys,"stdin",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"stdin",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
ret = Stream_Object(Env->cx,Env->out,false,0);
ptr = OBJECT_TO_JSVAL(ret);
JS_SetProperty(Env->cx, sys,"stdout",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"stdout",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
ret = Stream_Object(Env->cx,Env->out,false,0);
ptr = OBJECT_TO_JSVAL(ret);
JS_SetProperty(Env->cx, sys,"stderr",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"stderr",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,JSDB_VERSION));
JS_SetProperty(Env->cx, sys,"release",&ptr);
ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,argv0));
JS_SetProperty(Env->cx, sys,"program",&ptr);
ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,JSDB_PLATFORM));
JS_SetProperty(Env->cx, sys,"platform",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"platform",JSPROP_PERMANENT, &foundp);
#ifdef XP_WIN
char* hn = getenv("COMPUTERNAME");
#else
char hn[1024];
hn[0]=0;
gethostname(hn,1024);
#endif
ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,hn));
JS_SetProperty(Env->cx, sys,"name",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"name",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
ptr = OBJECT_TO_JSVAL(JS_NewArrayObject(Env->cx,0,0));
JS_SetProperty(Env->cx, sys,"arguments",&ptr);
}
System system;
#ifdef XP_WIN
GetDirectory(argv0,system.path);
#endif
#ifdef XP_UNIX
GetDirectory(argv0,system.path);
// system.path="/etc/jsdb/";
#endif
Env->System = &system;
/*
process flags
-load file
-strict
-werror
-debug server:port
*/
bool runFromZip = false;
bool runConsole = true;
const char* execCode = 0;
int error = 0;
#ifndef JSDB_MINIMAL
if (FileExists(argv0))
{
try {
FileStream * Program = new FileStream(argv0,Stream::OMBinary,Stream::ReadOnly);
ZipArchive * Archive = new ZipArchive(Program,true);
if (Archive->Count())
{
system.zip = Archive;
if (system.zip->Find("main.js")!=NOT_FOUND || system.zip->Find("run.js")!=NOT_FOUND )
runFromZip = true;
}
else delete Archive;
} catch(...) {system.zip = 0;}
} else system.zip = 0;
#endif
while (argc > 1)
{
char* c = argv[1];
if (!strcasecmp(c,"-help") || !strcasecmp(c,"/help") || !strcasecmp(c,"/?"))
{
runConsole = false;
argv ++;
argc --;
*Env->out << "JSDB " JSDB_VERSION " " JSDB_DATE "\n"
JSDB_COPYRIGHT " See http://www.jsdb.org/\n";
*Env->out << "\n"
"JSDB [-strict] [-werror] [-load file.js] [-debug server] [lib.zip] [program.js]\n"
" [-path directory] [-exec code]\n"
"\n"
" -strict Strict syntax mode\n"
" -werror Treat warnings as errors\n"
" -noxml Disable the ECMAScript For XML extensions\n"
#ifdef JSOPTION_JIT
" -jit Enable the JIT compiler (tracemonkey)\n"
" -nojit Disable the JIT compiler (tracemonkey)\n"
#endif
" -path directory Set the search path to directory\n"
" -load file.js Load and run file.js before program.js\n"
" -debug server:port Connect to a debugger server\n"
" -exec \"code\" Evaluates code and exits\n"
" lib.zip Set lib.zip as the default location for library files\n"
" Executes main.js if it exists in lib.zip\n"
" program.js Runs a JavaScript program\n"
" JSDB runs console mode if no program is specified\n"
"\n";
}
else if ((!strcasecmp(c,"-strict") || !strcasecmp(c,"/strict")))
{
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_STRICT);
argv ++;
argc --;
}
else if ((!strcasecmp(c,"-noxml") || !strcasecmp(c,"/noxml")))
{
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) & ~JSOPTION_XML);
argv ++;
argc --;
}
else if ((!strcasecmp(c,"-werror") || !strcasecmp(c,"/werror")))
{
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_WERROR);
argv ++;
argc --;
}
#ifdef JSOPTION_JIT
else if ((!strcasecmp(c,"-jit") || !strcasecmp(c,"/jit")))
{
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_JIT);
argv ++;
argc --;
}
else if ((!strcasecmp(c,"-nojit") || !strcasecmp(c,"/nojit")))
{
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) & ~JSOPTION_JIT);
argv ++;
argc --;
}
#endif
else if ((!strcasecmp(c,"-exec") || !strcasecmp(c,"/exec")))
{
argv ++;
argc --;
if (argc)
{
execCode = argv[1];
argv ++;
argc --;
}
}
else if ((!strcasecmp(c,"-path") || !strcasecmp(c,"/path")))
{
system.path = argv[2];
argv += 2;
argc -= 2;
AddBackslash(system.path);
FixFilename(system.path);
}
#ifndef JSDB_MINIMAL
else if ((!strcasecmp(c,"-debug") || !strcasecmp(c,"/debug")))
{
TStr address(argv[2]);
char* port = strchr(address,':');
if (port) *port++ = 0;
else port = (char*)"";
Env->Debugger = JSDB_StartDebug(Env->rt, address, atoi(port));
JS_SetOptions(Env->cx,JS_GetOptions(Env->cx) | JSOPTION_WERROR);
argv += 2;
argc -= 2;
}
#endif
else if (argc > 2 && (!strcasecmp(c,"-load") || !strcasecmp(c,"/load")))
{
TStr fn(argv[2]);
argv += 2;
argc -= 2;
FixFilename(fn);
if (!FileExists(fn)) fn = TStr(system.path,fn);
if (!FileExists(fn))
{
error = 1;
CGIErrorMessage(*Env->out);
*Env->out << "Error: Can not find " << fn << "\n";
}
else
{
try {
FileStream in(fn,Stream::OMBinary,Stream::ReadOnly);
Env->ExecScript(0,0,in,fn,1);
} catch(...)
{
error = 2;
CGIErrorMessage(*Env->out);
*Env->out << "Error: Unable to open " << fn << "\n";
break;
}
}
continue;
}
#ifndef JSDB_MINIMAL
else if (system.zip == 0 && (stristr(c,".zip")||stristr(c,".jar")))
{
try {
FileStream * Program = new FileStream(c,Stream::OMBinary,Stream::ReadOnly);
ZipArchive * Archive = new ZipArchive(Program,true);
system.zip = Archive;
if (system.zip->Find("main.js")!=NOT_FOUND || system.zip->Find("run.js")!=NOT_FOUND )
runFromZip = true;
argv ++;
argc --;
} catch(...) {system.zip=0;}
}
#endif
else break;
}
TStr filename;
if (runFromZip == false && argc > 1)
{
filename = argv[1];
FixFilename(filename);
argc --;
argv ++;
}
jsval * arr;
if (argc > 1)
{
arr = new jsval[argc-1];
for (int i=1; i< argc; i++)
{
arr[i-1] = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,argv[i]));
}
JSObject * ret = (JS_NewArrayObject(Env->cx,argc-1,arr));
jsval ptr = OBJECT_TO_JSVAL(ret);
JSBool foundp = 0;
JS_SetProperty(Env->cx, Env->global,"jsArguments",&ptr);
JS_SetPropertyAttributes(Env->cx, Env->global,"jsArguments",JSPROP_PERMANENT, &foundp);
JS_SetProperty(Env->cx, sys,"arguments",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"arguments",JSPROP_PERMANENT, &foundp);
if (arr) delete [] arr;
}
else
{
jsval ptr = OBJECT_TO_JSVAL(JS_NewArrayObject(Env->cx,0,0));
JS_SetProperty(Env->cx, Env->global,"jsArguments",&ptr);
JS_SetProperty(Env->cx, sys,"arguments",&ptr);
}
{
jsval ptr ; //= STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,""));
JSBool foundp = 0;
//JS_SetProperty(Env->cx, sys,"script",&ptr);
//JS_SetPropertyAttributes(Env->cx, sys,"script",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,system.path));
JS_SetProperty(Env->cx, sys,"path",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"path",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
}
if (execCode)
{
jsval ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,GetFilename(filename)));
JSBool foundp = 0;
JS_SetProperty(Env->cx, sys,"script",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"script",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
Env->ExecScript(0,0,execCode,"",1);
}
#ifndef JSDB_MINIMAL
else if (runFromZip)
{
MemoryStream in;
const char * name = "main.js";
if (!system.zip->Extract(system.zip->Find(name),in))
{
name = "run.js";
system.zip->Extract(system.zip->Find(name),in);
}
in.rewind();
jsval ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,GetFilename(name)));
JSBool foundp = 0;
JS_SetProperty(Env->cx, sys,"script",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"script",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
Env->ExecScript(0,0,in,name,1);
}
#endif
else if (*filename)
{
if (FileExists(filename))
{ // ExecScript skips the shebang #!
try {
FileStream in(filename,Stream::OMBinary,Stream::ReadOnly);
jsval ptr = STRING_TO_JSVAL(JS_NewStringCopyZ(Env->cx,GetFilename(filename)));
JSBool foundp = 0;
JS_SetProperty(Env->cx, sys,"script",&ptr);
JS_SetPropertyAttributes(Env->cx, sys,"script",JSPROP_PERMANENT|JSPROP_READONLY, &foundp);
Env->ExecScript(0,0,in,filename,1);
} catch(...)
{
error = 2;
CGIErrorMessage(*Env->out);
*Env->out << "Error: Unable to open " << filename << "\n";
}
}
else
{
error = 1;
CGIErrorMessage(*Env->out);
*Env->out << "Error: Can not find " << filename << "\n";
}
}
else if (!error && runConsole)
{
StartConsole(Env);
}
// Cleanup!
JS_GC(Env->cx);
JS_DestroyContext(Env->cx);
JS_DestroyRuntime(Env->rt);
if (Env->in != Env->out)
delete Env->in;
delete Env->out;
if (Env->ExitCode) error = Env->ExitCode;
Env = 0; //Env is a smart pointer, assigning NULL forces cleanup
#ifdef XP_WIN
CoFreeUnusedLibraries();
CoUninitialize();
#endif
JS_ShutDown();
return error;
}
//wrapper function macros
extern JSBool
Write(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *);
extern JSBool
Writeln(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *);
void ExecCommand(JSDBEnvironment* Env,const char * cmd,size_t len,uintN line)
{
#ifndef JSDB_MINIMAL
if (Env->Debugger)
DebugScriptSource(Env->Debugger,"console",line,cmd,len);
#endif
jsval result;
JSString* str;
JSBool ok = JS_EvaluateScript(Env->cx, Env->global, cmd, len, "console", line, &result);