Newer
Older
/* jsexec.c */
/* Execute a Synchronet JavaScript module from the command-line */
/* $Id$ */
/****************************************************************************
* @format.tab-size 4 (Plain Text/Source Code File Header) *
* @format.use-tabs true (see http://www.synchro.net/ptsc_hdr.html) *
* *
* Copyright 2011 Rob Swindell - http://www.synchro.net/copyright.html *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* See the GNU General Public License for more details: gpl.txt or *
* http://www.fsf.org/copyleft/gpl.html *
* *
* Anonymous FTP access to the most recent released source is available at *
* ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net *
* *
* Anonymous CVS access to the development source and modification history *
* is available at cvs.synchro.net:/cvsroot/sbbs, example: *
* cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login *
* (just hit return, no password is necessary) *
* cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src *
* *
* For Synchronet coding style and modification guidelines, see *
* http://www.synchro.net/source.html *
* *
* You are encouraged to submit any modifications (preferably in Unix diff *
* format) via e-mail to mods@synchro.net *
* *
* Note: If this box doesn't appear square, then you need to fix your tabs. *
****************************************************************************/
#define JAVASCRIPT
#ifdef __unix__
#include <signal.h>
#endif
#include "sbbs.h"
#include "ciolib.h"
#include "ini_file.h"
#include "js_rtpool.h"
#include "js_request.h"
#define DEFAULT_LOG_LEVEL LOG_DEBUG /* Display all LOG levels */
#define DEFAULT_ERR_LOG_LVL LOG_WARNING
js_startup_t startup;
JSRuntime* js_runtime;
JSContext* js_cx;
JSObject* js_glob;
js_callback_t cb;
scfg_t scfg;
ulong js_max_bytes=JAVASCRIPT_MAX_BYTES;
ulong js_cx_stack=JAVASCRIPT_CONTEXT_STACK;
FILE* nulfp;
char compiler[32];
char* host_name=NULL;
char host_name_buf[128];
char* load_path_list=JAVASCRIPT_LOAD_PATH;
BOOL pause_on_exit=FALSE;
BOOL recycled;
int log_level=DEFAULT_LOG_LEVEL;
int err_level=DEFAULT_ERR_LOG_LVL;
pthread_mutex_t output_mutex;
#if defined(__unix__)
BOOL daemonize=FALSE;
#endif
char orig_cwd[MAX_PATH+1];
enum debug_action {
DEBUG_CONTINUE,
DEBUG_EXIT
};
static JSTrapStatus trap_handler(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, jsval closure);
static enum debug_action debug_prompt(JSScript *script);
void banner(FILE* fp)
{
fprintf(fp,"\nJSexec v%s%c-%s (rev %s)%s - "
"Execute Synchronet JavaScript Module\n"
,VERSION,REVISION
,PLATFORM_DESC
,revision
#ifdef _DEBUG
," Debug"
#else
,""
#endif
fprintf(fp, "Compiled %s %s with %s\n"
,__DATE__, __TIME__, compiler);
fprintf(fp,"\nusage: jsexec [-opts] [path]module[.js] [args]\n"
"\navailable opts:\n\n"
"\t-c<ctrl_dir> specify path to Synchronet CTRL directory\n"
#if defined(__unix__)
"\t-d run in background (daemonize)\n"
#endif
"\t-m<bytes> set maximum heap size (default=%u bytes)\n"
"\t-s<bytes> set context stack size (default=%u bytes)\n"
"\t-t<limit> set time limit (default=%u, 0=unlimited)\n"
"\t-y<interval> set yield interval (default=%u, 0=never)\n"
"\t-g<interval> set garbage collection interval (default=%u, 0=never)\n"
"\t-h[hostname] use local or specified host name (instead of SCFG value)\n"
"\t-u<mask> set file creation permissions mask (in octal)\n"
"\t-L<level> set log level (default=%u)\n"
"\t-E<level> set error log level threshold (default=%u)\n"
"\t-i<path_list> set load() comma-sep search path list (default=\"%s\")\n"
"\t-f use non-buffered stream for console messages\n"
"\t-a append instead of overwriting message output files\n"
"\t-e<filename> send error messages to file in addition to stderr\n"
"\t-o<filename> send console messages to file instead of stdout\n"
"\t-n send status messages to %s instead of stderr\n"
"\t-q send console messages to %s instead of stdout\n"
"\t-v display version details and exit\n"
"\t-x disable auto-termination on local abort signal\n"
"\t-l loop until intentionally terminated\n"
"\t-p wait for keypress (pause) on exit\n"
"\t-! wait for keypress (pause) on error\n"
,JAVASCRIPT_MAX_BYTES
,JAVASCRIPT_CONTEXT_STACK
,JAVASCRIPT_TIME_LIMIT
,JAVASCRIPT_YIELD_INTERVAL
,JAVASCRIPT_GC_INTERVAL
,DEFAULT_LOG_LEVEL
,DEFAULT_ERR_LOG_LVL
int mfprintf(FILE* fp, char *fmt, ...)
{
va_list argptr;
char sbuf[1024];
int ret=0;
va_start(argptr,fmt);
ret=vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
sbuf[sizeof(sbuf)-1]=0;
va_end(argptr);
/* Mutex-protect stdout/stderr */
pthread_mutex_lock(&output_mutex);
ret = fprintf(fp, "%s\n", sbuf);
pthread_mutex_unlock(&output_mutex);
return(ret);
}
/* Log printf */
int lprintf(int level, const char *fmt, ...)
{
va_list argptr;
char sbuf[1024];
if(level > log_level)
return(0);
va_start(argptr,fmt);
ret=vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
sbuf[sizeof(sbuf)-1]=0;
va_end(argptr);
#if defined(__unix__)
if(daemonize) {
syslog(level,"%s",sbuf);
/* Mutex-protect stdout/stderr */
pthread_mutex_lock(&output_mutex);
if(level<=err_level) {
ret=fprintf(errfp,"%s\n",sbuf);
if(errfp!=stderr && confp!=stdout)
ret=fprintf(statfp,"%s\n",sbuf);
}
if(level>err_level || errfp!=stderr)
ret=fprintf(confp,"%s\n",sbuf);
pthread_mutex_unlock(&output_mutex);
return(ret);
}
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
#if defined(__unix__) && defined(NEEDS_DAEMON)
/****************************************************************************/
/* Daemonizes the process */
/****************************************************************************/
int
daemon(int nochdir, int noclose)
{
int fd;
switch (fork()) {
case -1:
return (-1);
case 0:
break;
default:
_exit(0);
}
if (setsid() == -1)
return (-1);
if (!nochdir)
(void)chdir("/");
if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
(void)dup2(fd, STDIN_FILENO);
(void)dup2(fd, STDOUT_FILENO);
(void)dup2(fd, STDERR_FILENO);
if (fd > 2)
(void)close(fd);
}
return (0);
}
#endif
WSADATA WSAData;
#define SOCKLIB_DESC WSAData.szDescription
static BOOL WSAInitialized=FALSE;
static BOOL winsock_startup(void)
{
int status; /* Status Code */
if((status = WSAStartup(MAKEWORD(1,1), &WSAData))==0) {
/* fprintf(statfp,"%s %s\n",WSAData.szDescription, WSAData.szSystemStatus); */
WSAInitialized=TRUE;
return(TRUE);
}
lprintf(LOG_CRIT,"!WinSock startup ERROR %d", status);
return(FALSE);
}
#else /* No WINSOCK */
#define winsock_startup() (TRUE)
#define SOCKLIB_DESC NULL
#endif
if(WSAInitialized && WSACleanup()!=0)
lprintf(LOG_ERR,"!WSACleanup ERROR %d",ERROR_VALUE);
#endif
if(pause_on_exit || (code && pause_on_error)) {
fprintf(statfp,"\nHit enter to continue...");
if(code)
fprintf(statfp,"\nReturning error code: %d\n",code);
return(code);
}
void bail(int code)
{
exit(do_bail(code));
static JSBool
js_log(JSContext *cx, uintN argc, jsval *arglist)
{
jsval *argv=JS_ARGV(cx, arglist);
uintN i=0;
int32 level=LOG_INFO;
JSString* str=NULL;
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if(argc > 1 && JSVAL_IS_NUMBER(argv[i])) {
if(!JS_ValueToInt32(cx,argv[i++],&level))
return JS_FALSE;
}
for(; i<argc; i++) {
if((str=JS_ValueToString(cx, argv[i]))==NULL)
return(JS_FALSE);
JSSTRING_TO_STRING(cx, str, logstr, NULL);
rc=JS_SUSPENDREQUEST(cx);
JS_RESUMEREQUEST(cx, rc);
}
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
return(JS_TRUE);
}
js_read(JSContext *cx, uintN argc, jsval *arglist)
jsval *argv=JS_ARGV(cx, arglist);
char* buf;
int rd;
int32 len=128;
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if(argc) {
if(!JS_ValueToInt32(cx,argv[0],&len))
return JS_FALSE;
}
if((buf=alloca(len))==NULL)
rc=JS_SUSPENDREQUEST(cx);
rd=fread(buf,sizeof(char),len,stdin);
JS_RESUMEREQUEST(cx, rc);
JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyN(cx,buf,rd)));
return(JS_TRUE);
}
static JSBool
js_readln(JSContext *cx, uintN argc, jsval *arglist)
jsval *argv=JS_ARGV(cx, arglist);
char* buf;
char* p;
int32 len=128;
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if(argc) {
if(!JS_ValueToInt32(cx,argv[0],&len))
return JS_FALSE;
}
if((buf=alloca(len+1))==NULL)
rc=JS_SUSPENDREQUEST(cx);
p=fgets(buf,len+1,stdin);
JS_RESUMEREQUEST(cx, rc);
JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyZ(cx,truncnl(p))));
return(JS_TRUE);
}
static JSBool
js_write(JSContext *cx, uintN argc, jsval *arglist)
{
jsval *argv=JS_ARGV(cx, arglist);
uintN i;
JSString* str=NULL;
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
for (i = 0; i < argc; i++) {
return(JS_FALSE);
JSSTRING_TO_STRING(cx, str, line, NULL);
rc=JS_SUSPENDREQUEST(cx);
JS_RESUMEREQUEST(cx, rc);
}
if(str==NULL)
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
return(JS_TRUE);
}
static JSBool
js_writeln(JSContext *cx, uintN argc, jsval *arglist)
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
return(JS_FALSE);
rc=JS_SUSPENDREQUEST(cx);
fprintf(confp,"\n");
JS_RESUMEREQUEST(cx, rc);
return(JS_TRUE);
}
static JSBool
jse_printf(JSContext *cx, uintN argc, jsval *arglist)
{
jsval *argv=JS_ARGV(cx, arglist);
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if((p = js_sprintf(cx, 0, argc, argv))==NULL) {
JS_ReportError(cx,"js_sprintf failed");
return(JS_FALSE);
}
rc=JS_SUSPENDREQUEST(cx);
fprintf(confp,"%s",p);
JS_RESUMEREQUEST(cx, rc);
JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyZ(cx, p)));
js_sprintf_free(p);
return(JS_TRUE);
}
static JSBool
js_alert(JSContext *cx, uintN argc, jsval *arglist)
{
jsval *argv=JS_ARGV(cx, arglist);
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
JSVALUE_TO_STRING(cx, argv[0], line, NULL);
return(JS_FALSE);
rc=JS_SUSPENDREQUEST(cx);
JS_RESUMEREQUEST(cx, rc);
JS_SET_RVAL(cx, arglist, argv[0]);
return(JS_TRUE);
}
static JSBool
js_confirm(JSContext *cx, uintN argc, jsval *arglist)
{
jsval *argv=JS_ARGV(cx, arglist);
JSString * str;
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if((str=JS_ValueToString(cx, argv[0]))==NULL)
return(JS_FALSE);
JSSTRING_TO_STRING(cx, str, cstr, NULL);
printf("%s (Y/n)? ", cstr);
rc=JS_SUSPENDREQUEST(cx);
fgets(instr,sizeof(instr),stdin);
JS_RESUMEREQUEST(cx, rc);
p=instr;
SKIP_WHITESPACE(p);
JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(tolower(*p)!='n'));
return(JS_TRUE);
}
static JSBool
js_deny(JSContext *cx, uintN argc, jsval *arglist)
jsval *argv=JS_ARGV(cx, arglist);
JSString * str;
char * cstr;
char * p;
jsrefcount rc;
char instr[81];
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if((str=JS_ValueToString(cx, argv[0]))==NULL)
return(JS_FALSE);
JSSTRING_TO_STRING(cx, str, cstr, NULL);
printf("%s (N/y)? ", cstr);
rc=JS_SUSPENDREQUEST(cx);
fgets(instr,sizeof(instr),stdin);
JS_RESUMEREQUEST(cx, rc);
p=instr;
SKIP_WHITESPACE(p);
JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(tolower(*p)!='y'));
return(JS_TRUE);
}
static JSBool
js_prompt(JSContext *cx, uintN argc, jsval *arglist)
{
jsval *argv=JS_ARGV(cx, arglist);
char instr[81];
JSString * str;
JS_SET_RVAL(cx, arglist, JSVAL_VOID);
if(argc>0 && !JSVAL_IS_VOID(argv[0])) {
JSVALUE_TO_STRING(cx, argv[0], prstr, NULL);
rc=JS_SUSPENDREQUEST(cx);
JS_RESUMEREQUEST(cx, rc);
if(argc>1) {
JSVALUE_TO_STRING(cx, argv[1], prstr, NULL);
return(JS_FALSE);
} else
instr[0]=0;
rc=JS_SUSPENDREQUEST(cx);
if(!fgets(instr,sizeof(instr),stdin)) {
JS_RESUMEREQUEST(cx, rc);
return(JS_TRUE);
JS_RESUMEREQUEST(cx, rc);
if((str=JS_NewStringCopyZ(cx, truncnl(instr)))==NULL)
return(JS_FALSE);
JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
return(JS_TRUE);
}
js_chdir(JSContext *cx, uintN argc, jsval *arglist)
jsval *argv=JS_ARGV(cx, arglist);
JSVALUE_TO_STRING(cx, argv[0], p, NULL);
JS_SET_RVAL(cx, arglist, INT_TO_JSVAL(-1));
rc=JS_SUSPENDREQUEST(cx);
JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(chdir(p)==0));
JS_RESUMEREQUEST(cx, rc);
js_putenv(JSContext *cx, uintN argc, jsval *arglist)
jsval *argv=JS_ARGV(cx, arglist);
if(argc)
JSVALUE_TO_STRING(cx, argv[0], p, NULL);
JS_SET_RVAL(cx, arglist, INT_TO_JSVAL(-1));
JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(putenv(strdup(p))==0));
static jsSyncMethodSpec js_global_functions[] = {
{"log", js_log, 1},
{"readln", js_readln, 0, JSTYPE_STRING, JSDOCSTR("[count]")
,JSDOCSTR("read a single line, up to count characters, from input stream")
,311
},
{"write", js_write, 0},
{"writeln", js_writeln, 0},
{"print", js_writeln, 0},
{"alert", js_alert, 1},
{"prompt", js_prompt, 1},
{"confirm", js_confirm, 1},
{0}
};
static void
js_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
{
char line[64];
char file[MAX_PATH+1];
const char* warning;
int log_level;
rc=JS_SUSPENDREQUEST(cx);
if(report==NULL) {
lprintf(LOG_ERR,"!JavaScript: %s", message);
JS_RESUMEREQUEST(cx, rc);
return;
}
if(report->filename)
sprintf(file," %s",report->filename);
else
file[0]=0;
if(report->lineno)
sprintf(line," line %d",report->lineno);
else
line[0]=0;
if(JSREPORT_IS_WARNING(report->flags)) {
if(JSREPORT_IS_STRICT(report->flags))
warning="strict warning";
else
warning="warning";
log_level=LOG_WARNING;
} else {
log_level=LOG_ERR;
warning="";
lprintf(log_level,"!JavaScript %s%s%s: %s",warning,file,line,message);
JS_RESUMEREQUEST(cx, rc);
}
static JSBool
js_OperationCallback(JSContext *cx)
{
JSBool ret;
JS_SetOperationCallback(cx, NULL);
ret=js_CommonOperationCallback(cx, &cb);
JS_SetOperationCallback(cx, js_OperationCallback);
return ret;
}
static BOOL js_CreateEnvObject(JSContext* cx, JSObject* glob, char** env)
{
char name[256];
char* val;
uint i;
JSObject* js_env;
if((js_env=JS_NewObject(js_cx, NULL, NULL, glob))==NULL)
return(FALSE);
if(!JS_DefineProperty(cx, glob, "env", OBJECT_TO_JSVAL(js_env)
,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE))
return(FALSE);
for(i=0;env[i]!=NULL;i++) {
SAFECOPY(name,env[i]);
truncstr(name,"=");
val=strchr(env[i],'=');
if(val==NULL)
val="";
else
val++;
if(!JS_DefineProperty(cx, js_env, name, STRING_TO_JSVAL(JS_NewStringCopyZ(cx,val))
,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE))
return(FALSE);
}
return(TRUE);
}
{
memset(&startup,0,sizeof(startup));
SAFECOPY(startup.load_path, load_path_list);
fprintf(statfp,"%s\n",(char *)JS_GetImplementationVersion());
fprintf(statfp,"JavaScript: Creating runtime: %lu bytes\n"
,js_max_bytes);
if((js_runtime = jsrt_GetNew(js_max_bytes, 5000, __FILE__, __LINE__))==NULL)
return(FALSE);
fprintf(statfp,"JavaScript: Initializing context (stack: %lu bytes)\n"
,js_cx_stack);
if((js_cx = JS_NewContext(js_runtime, js_cx_stack))==NULL)
return(FALSE);
JS_BEGINREQUEST(js_cx);
JS_SetErrorReporter(js_cx, js_ErrorReporter);
/* Global Object */
if(!js_CreateCommonObjects(js_cx, &scfg, NULL, js_global_functions
,time(NULL), host_name, SOCKLIB_DESC /* system */
,&cb,&startup /* js */
,NULL,INVALID_SOCKET /* client */
,NULL /* server */
,&js_glob
)) {
JS_ENDREQUEST(js_cx);
return(FALSE);
/* Environment Object (associative array) */
if(!js_CreateEnvObject(js_cx, js_glob, environ)) {
JS_ENDREQUEST(js_cx);
if(js_CreateUifcObject(js_cx, js_glob)==NULL) {
JS_ENDREQUEST(js_cx);
return(FALSE);
if(js_CreateConioObject(js_cx, js_glob)==NULL) {
JS_ENDREQUEST(js_cx);
return(TRUE);
}
static const char* js_ext(const char* fname)
{
if(strchr(fname,'.')==NULL)
return(".js");
return("");
}
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
/*
* This doesn't belong here and is done wrong...
* mcmlxxix should love it.
*/
static enum debug_action debug_prompt(JSScript *script)
{
char line[1024];
while(1) {
if(JS_IsExceptionPending(js_cx))
fputs("!", stdout);
fputs("JS> ", stdout);
if(fgets(line, sizeof(line), stdin)==NULL) {
fputs("Error readin input\n",stderr);
continue;
}
if(strncmp(line, "break ", 6)==0) {
ulong linenum=strtoul(line+6, NULL, 10);
jsbytecode *pc;
if(linenum==ULONG_MAX) {
fputs("Unable to parse line number\n",stderr);
continue;
}
pc=JS_LineNumberToPC(js_cx, script, linenum);
if(pc==NULL) {
fprintf(stderr, "Unable to locate line %lu\n", linenum);
break;
}
if(!JS_SetTrap(js_cx, script, pc, trap_handler, JSVAL_VOID)) {
fprintf(stderr, "Unable to set breakpoint at line %lu\n",linenum);
}
continue;
}
if(strncmp(line, "r", 1)==0) {
return DEBUG_CONTINUE;
}
if(strncmp(line, "eval ", 5)==0 ||
strncmp(line, "e ", 2)==0
) {
jsval ret;
JSStackFrame *fp;
jsval oldexcept;
BOOL has_old=FALSE;
int cmdlen=5;
if(line[1]==' ')
cmdlen=2;
if(JS_IsExceptionPending(js_cx)) {
if(JS_GetPendingException(js_cx, &oldexcept))
has_old=TRUE;
JS_ClearPendingException(js_cx);
}
fp=JS_GetScriptedCaller(js_cx, NULL);
if(!fp) {
if(has_old)
JS_SetPendingException(js_cx, oldexcept);
fputs("Unable to get frame pointer\n", stderr);
continue;
}
if(!JS_EvaluateInStackFrame(js_cx, fp, line+cmdlen, strlen(line)-cmdlen, "eval-d statement", 1, &ret)) {
if(JS_IsExceptionPending(js_cx)) {
JS_SetErrorReporter(js_cx, js_ErrorReporter);
JS_ReportPendingException(js_cx);
JS_ClearPendingException(js_cx);
}
}
else {
// TODO: Check ret...
}
if(has_old)
JS_SetPendingException(js_cx, oldexcept);
continue;
}
if(strncmp(line, "clear", 5)==0) {
JS_ClearPendingException(js_cx);
continue;
}
fputs("Unrecognized command:\n"
"break #### - Sets a breakpoint\n"
"r - Runs the script\n"
"eval <statement> - eval() <statement> in the current frame\n"
"e <statement> - eval() <statement> in the current frame\n"
"clear - Clears pending exceptions (doesn't seem to help)\n"
"\n",stderr);
}
return DEBUG_CONTINUE;
}
static JSTrapStatus trap_handler(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, jsval closure)
{
JS_GC(cx);
fputs("Breakpoint reached\n",stdout);
switch(debug_prompt(script)) {
case DEBUG_CONTINUE:
return JSTRAP_CONTINUE;
case DEBUG_EXIT:
return JSTRAP_ERROR;
}
return JSTRAP_CONTINUE;
}
static JSTrapStatus throw_handler(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, void *closure)
{
JS_GC(cx);
fputs("Exception thrown\n",stdout);
switch(debug_prompt(script)) {
case DEBUG_CONTINUE:
return JSTRAP_CONTINUE;
case DEBUG_EXIT:
return JSTRAP_ERROR;
}
return JSTRAP_CONTINUE;
}
long js_exec(const char *fname, char** args)
{
int argc=0;

rswindell
committed
uint line_no;
char path[MAX_PATH+1];
char line[1024];
char rev_detail[256];
size_t len;
char* js_buf=NULL;
size_t js_buflen;
JSString* arg;
JSObject* argv;
FILE* fp=stdin;
jsval val;
jsval rval=JSVAL_VOID;
int32 result=0;
long double start;
long double diff;
if(fname!=NULL) {
if(isfullpath(fname)) {
SAFECOPY(path,fname);
}
else {
SAFEPRINTF3(path,"%s%s%s",orig_cwd,fname,js_ext(fname));
if(!fexistcase(path)) {
SAFEPRINTF3(path,"%s%s%s",scfg.mods_dir,fname,js_ext(fname));
if(scfg.mods_dir[0]==0 || !fexistcase(path))
SAFEPRINTF3(path,"%s%s%s",scfg.exec_dir,fname,js_ext(fname));
}
if(!fexistcase(path)) {
lprintf(LOG_ERR,"!Module file (%s) doesn't exist",path);
return(-1);
}
if((fp=fopen(path,"r"))==NULL) {
lprintf(LOG_ERR,"!Error %d (%s) opening %s",errno,STRERROR(errno),path);
return(-1);
}
}
JS_ClearPendingException(js_cx);
argv=JS_NewArrayObject(js_cx, 0, NULL);
JS_DefineProperty(js_cx, js_glob, "argv", OBJECT_TO_JSVAL(argv)
,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);
for(argc=0;args[argc];argc++) {
arg = JS_NewStringCopyZ(js_cx, args[argc]);
if(arg==NULL)
break;
val=STRING_TO_JSVAL(arg);
if(!JS_SetElement(js_cx, argv, argc, &val))
break;
}
JS_DefineProperty(js_cx, js_glob, "argc", INT_TO_JSVAL(argc)
,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);
JS_DefineProperty(js_cx, js_glob, "jsexec_revision"
,STRING_TO_JSVAL(JS_NewStringCopyZ(js_cx,revision))
,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);
sprintf(rev_detail,"JSexec %s%s "
"Compiled %s %s with %s"
,revision
#ifdef _DEBUG
," Debug"
#else
,""
#endif
,__DATE__, __TIME__, compiler
);
JS_DefineProperty(js_cx, js_glob, "jsexec_revision_detail"
,STRING_TO_JSVAL(JS_NewStringCopyZ(js_cx,rev_detail))
,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE);
cb.terminated=&terminated;
JS_SetOperationCallback(js_cx, js_OperationCallback);
if(fp==stdin) /* Using stdin for script source */

rswindell
committed
SAFECOPY(path,"stdin");

rswindell
committed
fprintf(statfp,"Reading script from %s\n",path);
line_no=0;
js_buflen=0;
while(!feof(fp)) {
if(!fgets(line,sizeof(line),fp))

rswindell
committed
break;
line_no++;
#if defined(__unix__) /* Support Unix Shell Scripts that start with #!/path/to/jsexec */
if(line_no==1 && strncmp(line,"#!",2)==0)
strcpy(line,"\n"); /* To keep line count correct */

rswindell
committed
#endif
len=strlen(line);
if((js_buf=realloc(js_buf,js_buflen+len))==NULL) {
lprintf(LOG_ERR,"!Error allocating %u bytes of memory"
,js_buflen+len);
return(-1);
}
memcpy(js_buf+js_buflen,line,len);
js_buflen+=len;