Skip to content
Snippets Groups Projects
jsexec.c 36.6 KiB
Newer Older
/* Execute a Synchronet JavaScript module from the command-line */

/****************************************************************************
 * @format.tab-size 4		(Plain Text/Source Code File Header)			*
 * @format.use-tabs true	(see http://www.synchro.net/ptsc_hdr.html)		*
 *																			*
 * Copyright 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										*
 *																			*
 * For Synchronet coding style and modification guidelines, see				*
 * http://www.synchro.net/source.html										*
 *																			*
 * Note: If this box doesn't appear square, then you need to fix your tabs.	*
 ****************************************************************************/

rswindell's avatar
rswindell committed
#ifndef JAVASCRIPT
rswindell's avatar
rswindell committed
#endif
#ifdef __unix__
#define _WITH_GETLINE
#include <signal.h>
deuce's avatar
deuce committed
#include <termios.h>
#define STARTUP_INI_JSOPT_BITDESC_TABLE
#if defined(main) && !defined(JSDOOR)
 #undef main	// Don't be a Windows program, be a Console one
#endif
#include "jsdebug.h"
#include "git_branch.h"
#include "git_hash.h"
#define DEFAULT_LOG_LEVEL	LOG_INFO
#define DEFAULT_ERR_LOG_LVL	LOG_WARNING
static const char*	strJavaScriptMaxBytes		="JavaScriptMaxBytes";
static const char*	strJavaScriptTimeLimit		="JavaScriptTimeLimit";
static const char*	strJavaScriptGcInterval		="JavaScriptGcInterval";
static const char*	strJavaScriptYieldInterval	="JavaScriptYieldInterval";
static const char*	strJavaScriptOptions		="JavaScriptOptions";
JSRuntime*	js_runtime;
JSContext*	js_cx;
JSObject*	js_glob;
ulong		js_max_bytes=JAVASCRIPT_MAX_BYTES;
ulong		js_opts = JAVASCRIPT_OPTIONS;
ulong		js_opts = JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT | JSOPTION_COMPILE_N_GO | JSOPTION_PROFILING;
rswindell's avatar
rswindell committed
FILE*		confp;
FILE*		errfp;
FILE*		statfp;
char*		host_name=NULL;
char		host_name_buf[128];
char*		load_path_list=JAVASCRIPT_LOAD_PATH;
bool		pause_on_exit=false;
bool		pause_on_error=false;
bool		terminated=false;
bool		recycled;
bool		require_cfg=false;
int			log_level=DEFAULT_LOG_LEVEL;
#if defined(__unix__)
bool		daemonize=false;
bool		debugger=false;
#ifndef PROG_NAME
#define PROG_NAME "JSexec"
#endif
#ifndef PROG_NAME_LC
#define PROG_NAME_LC "jsexec"
#endif
void banner(FILE* fp)
{
	fprintf(fp,"\n" PROG_NAME " v%s%c-%s %s/%s%s - "
		"Execute Synchronet JavaScript Module\n"
		,VERSION,REVISION
		,PLATFORM_DESC
		,GIT_BRANCH, GIT_HASH

	fprintf(fp, "Compiled %s %s with %s\n"
		,__DATE__, __TIME__, compiler);
Rob Swindell's avatar
Rob Swindell committed
	banner(stdout);
	fprintf(stdout, "\nusage: " PROG_NAME_LC " [-opts] [[path/]module[.js] [args]\n"
		"   or: " PROG_NAME_LC " [-opts] -r js-expression [args]\n"
		"   or: " PROG_NAME_LC " -v\n"
		"\navailable opts:\n\n"
		"    -r<expression> run (compile and execute) JavaScript expression\n"
		"    -c<ctrl_dir>   specify path to CTRL directory\n"
		"    -c<ctrl_dir>   specify path to Synchronet CTRL directory\n"
		"    -R             require successful load of configuration files\n"
		"    -C             do not change the current working directory (to CTRL dir)\n"
#if defined(__unix__)
		"    -d             run in background (daemonize)\n"
		"    -m<bytes>      set maximum heap size (default=%u bytes)\n"
		"    -t<limit>      set time limit (default=%u, 0=unlimited)\n"
		"    -y<interval>   set yield interval (default=%u, 0=never)\n"
		"    -g<interval>   set garbage collection interval (default=%u, 0=never)\n"
		"    -h[hostname]   use local or specified host name\n"
		"    -h[hostname]   use local or specified host name (instead of SCFG value)\n"
		"    -u<mask>       set file creation permissions mask (in octal)\n"
		"    -L<level>      set output log level by number or name (default=%u)\n"
		"    -E<level>      set error log level threshold (default=%u)\n"
		"    -i<path_list>  set load() comma-sep search path list (default=\"%s\")\n"
		"    -f             use non-buffered stream for console messages\n"
		"    -a             append instead of overwriting message output files\n"
Rob Swindell's avatar
Rob Swindell committed
		"    -A             send all messages to stdout\n"
		"    -A<filename>   send all messages to file instead of stdout/stderr\n"
		"    -e<filename>   send error messages to file in addition to stderr\n"
		"    -o<filename>   send console messages to file instead of stdout\n"
		"    -S<filename>   send status messages to file instead of stderr\n"
		"    -S             send status messages to stdout\n"
		"    -n             send status messages to %s instead of stderr\n"
		"    -q             send console messages to %s instead of stdout\n"
		"    -v             display version details and exit\n"
		"    -x             disable auto-termination on local abort signal\n"
		"    -l             loop until intentionally terminated\n"
		"    -p             wait for keypress (pause) on exit\n"
		"    -!             wait for keypress (pause) on error\n"
		"    -D             load the script into an interactive debugger\n"
		,JAVASCRIPT_MAX_BYTES
		,JAVASCRIPT_YIELD_INTERVAL
		,JAVASCRIPT_GC_INTERVAL
		,load_path_list
		,_PATH_DEVNULL
static void
cooked_tty(void)
{
	if (isatty(fileno(stdin))) {
#ifdef __unix__
		tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
#elif defined _WIN32
		SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_ECHO_INPUT
		    | ENABLE_EXTENDED_FLAGS | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT
		    | ENABLE_MOUSE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_QUICK_EDIT_MODE);
		#warning "Can't cook the tty on this platform"
#endif
	}
}

#ifdef __unix__
static void raw_input(struct termios *t)
{
#ifdef JSDOOR
	t->c_iflag &= ~(IMAXBEL|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
	t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
#else
	t->c_iflag &= ~(IMAXBEL|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
	t->c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
#endif
}
#endif

static void
raw_tty(void)
{
	if (isatty(fileno(stdin))) {
#ifdef __unix__
		struct termios term = orig_term;

		raw_input(&term);
		tcsetattr(fileno(stdin), TCSANOW, &term);
#elif defined _WIN32
deuce's avatar
deuce committed
		SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), 0);
#else
		#warning "Can't set the tty as raw on this platform"
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);
}

int lprintf(int level, const char *fmt, ...)
deuce's avatar
deuce committed
	int ret=0;
    ret=vsnprintf(sbuf,sizeof(sbuf),fmt,argptr);
#if defined(__unix__)
	if(daemonize) {

	/* Mutex-protect stdout/stderr */
	pthread_mutex_lock(&output_mutex);

		ret=fprintf(errfp,"%s\n",sbuf);
	if(level>err_level)
		ret=fprintf(statfp,"%s\n",sbuf);
#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

#if defined(_WINSOCKAPI_)
#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);
#define winsock_startup()	(true)
static int do_bail(int code)
#if defined(_WINSOCKAPI_)
	if(WSAInitialized && WSACleanup()!=0)
		lprintf(LOG_ERR,"!WSACleanup ERROR %d",ERROR_VALUE);
	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));
js_log(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*logstr=NULL;
	size_t		logstr_sz=0;
	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);
deuce's avatar
deuce committed
		JSSTRING_TO_RASTRING(cx, str, logstr, &logstr_sz, NULL);
deuce's avatar
deuce committed
		if(logstr==NULL)
			return(JS_FALSE);
deuce's avatar
deuce committed
		lprintf(level,"%s",logstr);
		JS_SET_RVAL(cx, arglist, JSVAL_VOID);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
js_read(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	char*	buf;
	int		rd;
	int32	len=128;
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc) {
		if(!JS_ValueToInt32(cx,argv[0],&len))
			return JS_FALSE;
	}
deuce's avatar
deuce committed
	if((buf=malloc(len))==NULL)
	rd=fread(buf,sizeof(char),len,stdin);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyN(cx,buf,rd)));
deuce's avatar
deuce committed
	free(buf);
js_readln(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	char*	buf;
	char*	p;
	int32	len=128;
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc) {
		if(!JS_ValueToInt32(cx,argv[0],&len))
			return JS_FALSE;
	}
deuce's avatar
deuce committed
	if((buf=malloc(len+1))==NULL)
	p=fgets(buf,len+1,stdin);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyZ(cx,truncnl(p))));
deuce's avatar
deuce committed
	free(buf);
js_write(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*line=NULL;
	size_t		line_sz=0;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

		if((str=JS_ValueToString(cx, argv[i]))==NULL)
deuce's avatar
deuce committed
		JSSTRING_TO_RASTRING(cx, str, line, &line_sz, NULL);
deuce's avatar
deuce committed
		if(line==NULL)
			return(JS_FALSE);
deuce's avatar
deuce committed
		fprintf(confp,"%s",line);
		JS_SET_RVAL(cx, arglist, JSVAL_VOID);
		JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
js_writeln(JSContext *cx, uintN argc, jsval *arglist)
deuce's avatar
deuce committed
	jsrefcount	rc;

	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

deuce's avatar
deuce committed
	if(!js_write(cx,argc,arglist))
jse_printf(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if((p = js_sprintf(cx, 0, argc, argv))==NULL) {
		JS_ReportError(cx,"js_sprintf failed");
	JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(JS_NewStringCopyZ(cx, p)));
js_alert(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	char		*line;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

deuce's avatar
deuce committed
	JSVALUE_TO_MSTRING(cx, argv[0], line, NULL);
deuce's avatar
deuce committed
	if(line==NULL)
deuce's avatar
deuce committed
	fprintf(confp,"!%s\n",line);
deuce's avatar
deuce committed
	free(line);
	JS_SET_RVAL(cx, arglist, argv[0]);
js_confirm(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
	char		instr[81]="y";
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if((str=JS_ValueToString(cx, argv[0]))==NULL)
	    return(JS_FALSE);

deuce's avatar
deuce committed
	JSSTRING_TO_MSTRING(cx, str, cstr, NULL);
	HANDLE_PENDING(cx, cstr);
deuce's avatar
deuce committed
	if(cstr==NULL)
		return JS_TRUE;
deuce's avatar
deuce committed
	printf("%s (Y/n)? ", cstr);
	free(cstr);
	p=fgets(instr,sizeof(instr),stdin);
	if(p != NULL) {
		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);
	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);

deuce's avatar
deuce committed
	JSSTRING_TO_MSTRING(cx, str, cstr, NULL);
	HANDLE_PENDING(cx, cstr);
deuce's avatar
deuce committed
	if(cstr==NULL)
		return JS_TRUE;
	rc=JS_SUSPENDREQUEST(cx);
deuce's avatar
deuce committed
	printf("%s (N/y)? ", cstr);
	free(cstr);
	p = fgets(instr,sizeof(instr),stdin);
	JS_RESUMEREQUEST(cx, rc);

	if(p != NULL) {
		SKIP_WHITESPACE(p);
		JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(tolower(*p)!='y'));
	}
js_prompt(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
	char		instr[256];
deuce's avatar
deuce committed
	jsrefcount	rc;
	JS_SET_RVAL(cx, arglist, JSVAL_VOID);

	if(argc>0 && !JSVAL_IS_VOID(argv[0])) {
deuce's avatar
deuce committed
		JSVALUE_TO_MSTRING(cx, argv[0], prstr, NULL);
		HANDLE_PENDING(cx, prstr);
deuce's avatar
deuce committed
		fprintf(confp,"%s: ",prstr);
deuce's avatar
deuce committed
		free(prstr);
deuce's avatar
deuce committed
		JSVALUE_TO_STRBUF(cx, argv[1], instr, sizeof(instr), NULL);
		HANDLE_PENDING(cx, NULL);
	if(!fgets(instr,sizeof(instr),stdin)) {
	if((str=JS_NewStringCopyZ(cx, truncnl(instr)))==NULL)
	JS_SET_RVAL(cx, arglist, STRING_TO_JSVAL(str));
static JSBool
js_chdir(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	JSVALUE_TO_MSTRING(cx, argv[0], p, NULL);
deuce's avatar
deuce committed
	if(p==NULL) {
		JS_SET_RVAL(cx, arglist, INT_TO_JSVAL(-1));
		return(JS_TRUE);
	}

deuce's avatar
deuce committed
	ret=chdir(p)==0;
	free(p);
deuce's avatar
deuce committed
	JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(ret));
	return(JS_TRUE);
}

static JSBool
js_putenv(JSContext *cx, uintN argc, jsval *arglist)
	jsval *argv=JS_ARGV(cx, arglist);
deuce's avatar
deuce committed
	jsrefcount	rc;
deuce's avatar
deuce committed
	if(argc) {
		JSVALUE_TO_MSTRING(cx, argv[0], p, NULL);
deuce's avatar
deuce committed
	if(p==NULL) {
		JS_SET_RVAL(cx, arglist, INT_TO_JSVAL(-1));
		return(JS_TRUE);
	}

deuce's avatar
deuce committed
	rc=JS_SUSPENDREQUEST(cx);
	ret=putenv(strdup(p))==0;
	free(p);
	JS_RESUMEREQUEST(cx, rc);
	JS_SET_RVAL(cx, arglist, BOOLEAN_TO_JSVAL(ret));
	return(JS_TRUE);
}

// Forked from mozilla/js/src/shell/js.cpp: AssertEq()
static JSBool
js_AssertEq(JSContext *cx, uintN argc, jsval *vp)
{
    if (!(argc == 2 || (argc == 3 && JSVAL_IS_STRING(JS_ARGV(cx, vp)[2])))) {
        JS_ReportError(cx, "assertEq: missing or invalid args");
        return JS_FALSE;
    }

    jsval *argv = JS_ARGV(cx, vp);
    JSBool same;
    if (!JS_SameValue(cx, argv[0], argv[1], &same))
        return JS_FALSE;
    if (!same) {
		JS_ReportError(cx, "not equal");
        return JS_FALSE;
    }
    JS_SET_RVAL(cx, vp, JSVAL_VOID);
    return JS_TRUE;
}


static jsSyncMethodSpec js_global_functions[] = {
	{"read",			js_read,            1},
deuce's avatar
deuce committed
	{"readln",			js_readln,			0,	JSTYPE_STRING,	JSDOCSTR("[count]")
Rob Swindell's avatar
Rob Swindell committed
	,JSDOCSTR("Read a single line, up to count characters, from input stream")
deuce's avatar
deuce committed
	,311
	},
    {"writeln",         js_writeln,         0},
    {"print",           js_writeln,         0},
	{"alert",			js_alert,			1},
	{"prompt",			js_prompt,			1},
	{"confirm",			js_confirm,			1},
	{"deny",			js_deny,			1},
	{"chdir",			js_chdir,			1},
	{"putenv",			js_putenv,			1},
    {0}
};

static void
js_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
{
	char	line[64];
	char	file[MAX_PATH+1];
	const char*	warning;
deuce's avatar
deuce committed
	jsrefcount	rc;
		lprintf(LOG_ERR,"!JavaScript: %s", message);
		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;
	lprintf(log_level,"!JavaScript %s%s%s: %s",warning,file,line,message);
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)
	if(!JS_DefineProperty(cx, glob, "env", OBJECT_TO_JSVAL(js_env)
		,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE))
	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))
static bool js_init(char** env)
	memset(&startup,0,sizeof(startup));
	SAFECOPY(startup.load_path, load_path_list);
    if((js_cx = JS_NewContext(js_runtime, JAVASCRIPT_CONTEXT_STACK))==NULL)

	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 */
		,NULL,INVALID_SOCKET,-1					/* client */
	/* Environment Object (associative array) */
	if(!js_CreateEnvObject(js_cx, js_glob, env)) {
	if(js_CreateUifcObject(js_cx, js_glob)==NULL) {
	if(js_CreateConioObject(js_cx, js_glob)==NULL) {
	if(!js_CreateFileObject(js_cx, js_glob, "stdout", STDOUT_FILENO, "w")) {
	if(!js_CreateFileObject(js_cx, js_glob, "stdin", STDIN_FILENO, "r")) {
	if(!js_CreateFileObject(js_cx, js_glob, "stderr", STDERR_FILENO, "w")) {
static const char* js_ext(const char* fname)
{
	if(strchr(fname,'.')==NULL)
		return(".js");
	return("");
}

void dbg_puts(const char *msg)
deuce's avatar
deuce committed
	fputs(msg, stderr);
char *dbg_getline(void)
#ifdef __unix__
	char	*line=NULL;
	size_t	linecap=0;

	cooked_tty();
	if(getline(&line, &linecap, stdin)>=0) {
		raw_tty();
	if(line)
		free(line);
	return NULL;
#else
	// I assume Windows sucks.
	char	buf[1025];
	cooked_tty();
	if(fgets(buf,sizeof(buf),stdin)) {
		raw_tty();
		return strdup(buf);
long js_exec(const char *fname, const char* buf, char** args)
	char*		js_buf=NULL;
	size_t		js_buflen;
	JSObject*	js_script=NULL;
	jsval		rval=JSVAL_VOID;
	int32		result=0;
	long double	start;
	long double	diff;
	bool		abort = false;
		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));
			}
			lprintf(LOG_ERR,"!Module file (%s) doesn't exist",path);
			lprintf(LOG_ERR,"!Error %d (%s) opening %s",errno,strerror(errno),path);
	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;