Coverage Report

Created: 2026-12-01 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/moddable/xs/tools/xst.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2016-2026  Moddable Tech, Inc.
3
 *
4
 *   This file is part of the Moddable SDK Tools.
5
 * 
6
 *   The Moddable SDK Tools is free software: you can redistribute it and/or modify
7
 *   it under the terms of the GNU General Public License as published by
8
 *   the Free Software Foundation, either version 3 of the License, or
9
 *   (at your option) any later version.
10
 * 
11
 *   The Moddable SDK Tools is distributed in the hope that it will be useful,
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 *   GNU General Public License for more details.
15
 * 
16
 *   You should have received a copy of the GNU General Public License
17
 *   along with the Moddable SDK Tools.  If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 */
20
21
#include "xsAll.h"
22
#include "xsScript.h"
23
#include "xs.h"
24
25
extern int fuzz(int argc, char* argv[]);
26
extern void fx_print(xsMachine* the);
27
extern void fxBuildAgent(xsMachine* the);
28
extern void fxBuildFuzz(xsMachine* the);
29
extern txScript* fxLoadScript(txMachine* the, txString path, txUnsigned flags);
30
extern void fxFulfillModuleFile(txMachine* the);
31
extern void fxRejectModuleFile(txMachine* the);
32
extern void fxRunLoop(txMachine* the);
33
extern void fxRunModuleFile(txMachine* the, txString path);
34
extern void fxRunProgramFile(txMachine* the, txString path, txUnsigned flags);
35
extern int fxBundleIs(const char *buffer, size_t size);
36
extern int fxBundleLoad(txMachine *the, txSlot *module, txID moduleID);
37
extern void fxBundleMapReset(void);
38
extern void fxBundleRun(txMachine *the, char *buffer, size_t size);
39
extern int main262(int argc, char* argv[]);
40
41
struct sxJob {
42
  txMachine* the;
43
  txSlot self;
44
  txSlot function;
45
  txSlot argument;
46
};
47
48
struct sxSharedTimer {
49
  txSharedTimer* next;
50
  txThread thread;
51
  txNumber when;
52
  txNumber interval;
53
  txSharedTimerCallback callback;
54
  txInteger refconSize;
55
  char refcon[1];
56
};
57
58
static void fxPrintUsage();
59
static int fxRunBundle(const char* path);
60
61
static void fx_agent_broadcast(xsMachine* the);
62
static void fx_agent_getReport(xsMachine* the);
63
static void fx_agent_leaving(xsMachine* the);
64
static void fx_agent_monotonicNow(xsMachine* the);
65
static void fx_agent_receiveBroadcast(xsMachine* the);
66
static void fx_agent_report(xsMachine* the);
67
static void fx_agent_sleep(xsMachine* the);
68
static void fx_agent_start(xsMachine* the);
69
#if mxWindows
70
static unsigned int __stdcall fx_agent_start_aux(void* it);
71
#else
72
static void* fx_agent_start_aux(void* it);
73
#endif
74
static void fx_createRealm(xsMachine* the);
75
void fx_detachArrayBuffer(xsMachine* the);
76
static void fx_evalScript(xsMachine* the);
77
static void fx_gc(xsMachine* the);
78
static void fx_isLockedDown(xsMachine* the);
79
static void fx_metering(xsMachine* the);
80
static void fx_runScript(xsMachine* the);
81
82
extern void fx_clearTimer(txMachine* the);
83
static void fx_destroyTimer(void* data);
84
static void fx_markTimer(txMachine* the, void* it, txMarkRoot markRoot);
85
static void fx_setInterval(txMachine* the);
86
static void fx_setTimeout(txMachine* the);
87
static void fx_setTimer(txMachine* the, txNumber interval, txBoolean repeat);
88
89
txAgentCluster gxAgentCluster;
90
91
#if OSSFUZZ
92
int omain(int argc, char* argv[]) 
93
#else
94
int main(int argc, char* argv[]) 
95
#endif
96
0
{
97
0
  txAgentCluster* agentCluster = &gxAgentCluster;
98
0
  int argi;
99
0
  int option = 0;
100
0
  int profiling = 0;
101
0
  int bundle = 0;
102
0
  char path[C_PATH_MAX];
103
0
  char* dot;
104
#if mxWindows
105
    char* harnessPath = "..\\harness";
106
#else
107
0
    char* harnessPath = "../harness";
108
0
#endif
109
0
  int error = 0;
110
  
111
0
  c_memset(agentCluster, 0, sizeof(txAgentCluster));
112
0
  fxCreateMutex(&(agentCluster->mainMutex));
113
0
  fxCreateCondition(&(agentCluster->countCondition));
114
0
  fxCreateMutex(&(agentCluster->countMutex));
115
0
  fxCreateCondition(&(agentCluster->dataCondition));
116
0
  fxCreateMutex(&(agentCluster->dataMutex));
117
0
  fxCreateMutex(&(agentCluster->reportMutex));
118
119
0
  if (argc == 1) {
120
0
    fxPrintUsage();
121
0
    return 1;
122
0
  }
123
0
  for (argi = 1; argi < argc; argi++) {
124
0
    if (argv[argi][0] != '-')
125
0
      continue;
126
  
127
0
    if (!strcmp(argv[argi], "-c"))
128
0
      option = 4;
129
0
    else if (!strcmp(argv[argi], "-i")) {
130
0
      argi++;
131
0
      option = 4;
132
0
    }
133
0
    else if (!strcmp(argv[argi], "-l"))
134
0
      option = 4;
135
0
    else if (!strcmp(argv[argi], "-lc"))
136
0
      option = 4;
137
0
    else if (!strcmp(argv[argi], "-o")) {
138
0
      argi++;
139
0
      option = 4;
140
0
    }
141
0
    else if (!strcmp(argv[argi], "-t"))
142
0
      option = 4;
143
144
0
    else if (!strcmp(argv[argi], "-h"))
145
0
      fxPrintUsage();
146
0
    else if (!strcmp(argv[argi], "-b"))
147
0
      option = 7;
148
0
    else if (!strcmp(argv[argi], "-e"))
149
0
      option = 1;
150
0
    else if (!strcmp(argv[argi], "-f"))
151
0
      option = 5;
152
0
    else if (!strcmp(argv[argi], "-j"))
153
0
      option = 6;
154
0
    else if (!strcmp(argv[argi], "-m"))
155
0
      option = 2;
156
0
    else if (!strcmp(argv[argi], "-p"))
157
0
      profiling = 1;
158
0
    else if (!strcmp(argv[argi], "-s"))
159
0
      option = 3;
160
0
    else if (!strcmp(argv[argi], "-v"))
161
0
      printf("XS %d.%d.%d, slot %zu bytes, ID %zu bytes\n", XS_MAJOR_VERSION, XS_MINOR_VERSION, XS_PATCH_VERSION, sizeof(txSlot), sizeof(txID));
162
0
    else if (!strcmp(argv[argi], "--bundle"))
163
0
      bundle = 1;
164
0
    else {
165
0
      fxPrintUsage();
166
0
      return 1;
167
0
    }
168
0
  }
169
0
  if (bundle && (option != 5)) {
170
0
    for (argi = 1; argi < argc; argi++) {
171
0
      if (argv[argi][0] == '-') {
172
        // consume flags that take a following value
173
0
        if (!strcmp(argv[argi], "-i") || !strcmp(argv[argi], "-o"))
174
0
          argi++;
175
0
        continue;
176
0
      }
177
0
      int r = fxRunBundle(argv[argi]);
178
0
      if (r) error = r;
179
0
    }
180
0
    return error;
181
0
  }
182
0
  if (option == 0) {
183
0
    if (c_realpath(harnessPath, path))
184
0
      option  = 4;
185
0
  }
186
0
  if (option == 4) {
187
0
    error = main262(argc, argv);
188
0
  }
189
0
  else if (option == 5) {
190
0
    error = fuzz(argc, argv);
191
0
  }
192
0
  else {
193
0
    xsCreation _creation = {
194
0
      16 * 1024 * 1024,   /* initialChunkSize */
195
0
      16 * 1024 * 1024,   /* incrementalChunkSize */
196
0
      1 * 1024 * 1024,  /* initialHeapCount */
197
0
      1 * 1024 * 1024,  /* incrementalHeapCount */
198
0
      256 * 1024,     /* stackCount */
199
0
      1024,         /* initialKeyCount */
200
0
      1024,       /* incrementalKeyCount */
201
0
      1993,         /* nameModulo */
202
0
      127,        /* symbolModulo */
203
0
      64 * 1024,      /* parserBufferSize */
204
0
      1993,       /* parserTableModulo */
205
0
    };
206
0
    xsCreation* creation = &_creation;
207
0
    xsMachine* machine;
208
0
        machine = xsCreateMachine(creation, "xst", NULL);
209
0
    xsBeginMetering(machine, NULL, 0);
210
0
    {
211
0
    if (profiling)
212
0
      fxStartProfiling(machine);
213
214
0
    xsBeginHost(machine);
215
0
    {
216
0
      xsVars(2);
217
0
      xsTry {
218
0
        fxBuildAgent(machine);
219
0
        fxBuildFuzz(machine);
220
221
0
        xsVar(0) = xsUndefined;
222
0
        the->rejection = &xsVar(0);
223
0
        for (argi = 1; argi < argc; argi++) {
224
0
          if (argv[argi][0] == '-')
225
0
            continue;
226
0
          if (option == 1) {
227
0
            xsVar(1) = xsGet(xsGlobal, xsID("$262"));
228
0
            xsResult = xsString(argv[argi]);
229
0
            xsCall1(xsVar(1), xsID("evalScript"), xsResult);
230
0
          }
231
0
          else {
232
0
            if (!c_realpath(argv[argi], path))
233
0
              xsURIError("file not found: %s", argv[argi]);
234
0
            dot = strrchr(path, '.');
235
0
            if ((option == 6) || (option == 7)) {
236
0
              FILE* file = C_NULL;
237
0
              char *buffer = C_NULL;
238
0
              xsTry {
239
0
                file = fopen(path, "r");
240
0
                if (!file)
241
0
                  xsUnknownError("can't open file");
242
0
                fseek(file, 0, SEEK_END);
243
0
                size_t size = ftell(file);
244
0
                fseek(file, 0, SEEK_SET);
245
0
                buffer = c_malloc(size + 1);
246
0
                if (!buffer)
247
0
                  xsUnknownError("not enough memory");
248
0
                if (size != fread(buffer, 1, size, file)) 
249
0
                  xsUnknownError("can't read file");
250
0
                buffer[size] = 0;
251
0
                fclose(file);
252
0
                file = C_NULL;
253
0
                xsResult = xsArrayBuffer(buffer, (txInteger)size);
254
0
                c_free(buffer);
255
0
                buffer = C_NULL;
256
0
                xsVar(1) = xsNew0(xsGlobal, xsID("TextDecoder"));
257
0
                xsResult = xsCall1(xsVar(1), xsID("decode"), xsResult);
258
0
                if (option == 6) {
259
0
                  xsVar(1) = xsGet(xsGlobal, xsID("JSON"));
260
0
                  xsResult = xsCall1(xsVar(1), xsID("parse"), xsResult);
261
0
                }
262
0
                else {
263
0
                  xsResult = xsCall1(xsGlobal, xsID("eval"), xsResult);
264
0
                }
265
0
              }
266
0
              xsCatch {
267
0
                if (buffer)
268
0
                  c_free(buffer);
269
0
                if (file)
270
0
                  fclose(file);
271
0
              }
272
0
            }
273
0
            else
274
0
            if (((option == 0) && dot && !c_strcmp(dot, ".mjs")) || (option == 2))
275
0
              fxRunModuleFile(the, path);
276
0
            else
277
0
              fxRunProgramFile(the, path, mxProgramFlag | mxDebugFlag);
278
0
          }
279
0
        }
280
0
        fxRunLoop(the);
281
0
        if (xsTest(xsVar(0))) 
282
0
          xsThrow(xsVar(0));
283
0
      }
284
0
      xsCatch {
285
0
        fprintf(stderr, "%s\n", xsToString(xsException));
286
0
        error = 1;
287
0
      }
288
0
    }
289
0
    fxCheckUnhandledRejections(machine, 1);
290
0
    xsEndHost(machine);
291
0
    if (profiling)
292
0
      fxStopProfiling(machine, C_NULL);
293
0
    }
294
0
    xsEndMetering(machine);
295
0
    if (machine->exitStatus) {
296
0
      fprintf(stderr, "Error: %s\n", fxAbortString(machine->exitStatus));
297
0
      error = 1;
298
0
    }
299
0
    xsDeleteMachine(machine);
300
0
  }
301
0
  return error;
302
0
}
303
304
int fxRunBundle(const char* path)
305
0
{
306
0
  int error = 0;
307
0
  FILE* file = C_NULL;
308
0
  char* buffer = C_NULL;
309
0
  size_t size = 0;
310
0
  char resolved[C_PATH_MAX];
311
312
0
  if (!c_realpath(path, resolved)) {
313
0
    fprintf(stderr, "file not found: %s\n", path);
314
0
    return 1;
315
0
  }
316
0
  file = fopen(resolved, "r");
317
0
  if (!file) {
318
0
    fprintf(stderr, "can't open file: %s\n", resolved);
319
0
    return 1;
320
0
  }
321
0
  fseek(file, 0, SEEK_END);
322
0
  size = ftell(file);
323
0
  fseek(file, 0, SEEK_SET);
324
0
  buffer = c_malloc(size + 1);
325
0
  if (!buffer) {
326
0
    fclose(file);
327
0
    fprintf(stderr, "not enough memory\n");
328
0
    return 1;
329
0
  }
330
0
  if (size != fread(buffer, 1, size, file)) {
331
0
    fclose(file);
332
0
    c_free(buffer);
333
0
    fprintf(stderr, "can't read file: %s\n", resolved);
334
0
    return 1;
335
0
  }
336
0
  buffer[size] = 0;
337
0
  fclose(file);
338
339
0
  xsCreation _creation = {
340
0
    16 * 1024 * 1024,   /* initialChunkSize */
341
0
    16 * 1024 * 1024,   /* incrementalChunkSize */
342
0
    1 * 1024 * 1024,  /* initialHeapCount */
343
0
    1 * 1024 * 1024,  /* incrementalHeapCount */
344
0
    256 * 1024,     /* stackCount */
345
0
    1024,         /* initialKeyCount */
346
0
    1024,       /* incrementalKeyCount */
347
0
    1993,         /* nameModulo */
348
0
    127,        /* symbolModulo */
349
0
    64 * 1024,      /* parserBufferSize */
350
0
    1993,       /* parserTableModulo */
351
0
  };
352
0
  xsMachine* machine = xsCreateMachine(&_creation, "xst", NULL);
353
0
  xsBeginMetering(machine, NULL, 0);
354
0
  {
355
0
  xsBeginHost(machine);
356
0
  {
357
0
    xsVars(1);
358
0
    xsTry {
359
0
      fxBuildAgent(machine);
360
0
      fxBuildFuzz(machine);
361
0
      xsVar(0) = xsUndefined;
362
0
      the->rejection = &xsVar(0);
363
0
      fxBundleRun(the, buffer, size);
364
0
      fxRunLoop(the);
365
0
      if (xsTest(xsVar(0)))
366
0
        xsThrow(xsVar(0));
367
0
    }
368
0
    xsCatch {
369
0
      fprintf(stderr, "%s\n", xsToString(xsException));
370
0
      error = 1;
371
0
    }
372
0
  }
373
0
  fxCheckUnhandledRejections(machine, 1);
374
0
  xsEndHost(machine);
375
0
  }
376
0
  xsEndMetering(machine);
377
0
  fxBundleMapReset();
378
0
  if (machine->exitStatus) {
379
0
    fprintf(stderr, "Error: %s\n", fxAbortString(machine->exitStatus));
380
0
    error = 1;
381
0
  }
382
0
  xsDeleteMachine(machine);
383
0
  c_free(buffer);
384
0
  return error;
385
0
}
386
387
extern void modInstallTextDecoder(xsMachine *the);
388
extern void modInstallTextEncoder(xsMachine *the);
389
extern void modInstallBase64(xsMachine *the);
390
391
void fxBuildAgent(xsMachine* the) 
392
0
{
393
0
  txSlot* slot;
394
0
  txSlot* agent;
395
0
  txSlot* global;
396
397
0
  slot = fxLastProperty(the, fxNewHostObject(the, NULL));
398
0
  slot = fxNextHostFunctionProperty(the, slot, fx_agent_broadcast, 2, xsID("broadcast"), XS_DONT_ENUM_FLAG); 
399
0
  slot = fxNextHostFunctionProperty(the, slot, fx_agent_getReport, 0, xsID("getReport"), XS_DONT_ENUM_FLAG); 
400
0
  slot = fxNextHostFunctionProperty(the, slot, fx_agent_monotonicNow, 0, xsID("monotonicNow"), XS_DONT_ENUM_FLAG); 
401
0
  slot = fxNextHostFunctionProperty(the, slot, fx_agent_sleep, 1, xsID("sleep"), XS_DONT_ENUM_FLAG); 
402
0
  slot = fxNextHostFunctionProperty(the, slot, fx_agent_start, 1, xsID("start"), XS_DONT_ENUM_FLAG); 
403
0
  agent = the->stack;
404
405
0
  mxPush(mxGlobal);
406
0
  global = the->stack;
407
408
0
  mxPush(mxObjectPrototype);
409
0
  slot = fxLastProperty(the, fxNewObjectInstance(the));
410
0
  slot = fxNextSlotProperty(the, slot, agent, xsID("agent"), XS_GET_ONLY);
411
0
  slot = fxNextHostFunctionProperty(the, slot, fx_createRealm, 0, xsID("createRealm"), XS_DONT_ENUM_FLAG); 
412
0
  slot = fxNextHostFunctionProperty(the, slot, fx_detachArrayBuffer, 1, xsID("detachArrayBuffer"), XS_DONT_ENUM_FLAG); 
413
0
  slot = fxNextHostFunctionProperty(the, slot, fx_gc, 1, xsID("gc"), XS_DONT_ENUM_FLAG); 
414
0
  slot = fxNextHostFunctionProperty(the, slot, fx_evalScript, 1, xsID("evalScript"), XS_DONT_ENUM_FLAG); 
415
0
  slot = fxNextHostFunctionProperty(the, slot, fx_isLockedDown, 1, xsID("isLockedDown"), XS_DONT_ENUM_FLAG); 
416
0
  slot = fxNextHostFunctionProperty(the, slot, fx_metering, 1, xsID("metering"), XS_DONT_ENUM_FLAG); 
417
0
  slot = fxNextSlotProperty(the, slot, global, xsID("global"), XS_GET_ONLY);
418
419
0
  slot = fxLastProperty(the, fxToInstance(the, global));
420
0
  slot = fxNextSlotProperty(the, slot, the->stack, xsID("$262"), XS_DONT_ENUM_FLAG);
421
0
  slot = fxNextHostFunctionProperty(the, slot, fx_print, 1, xsID("print"), XS_DONT_ENUM_FLAG);
422
0
  slot = fxNextHostFunctionProperty(the, slot, fx_runScript, 1, xsID("runScript"), XS_DONT_ENUM_FLAG);
423
0
  slot = fxNextHostFunctionProperty(the, slot, fx_clearTimer, 1, xsID("clearInterval"), XS_DONT_ENUM_FLAG);
424
0
  slot = fxNextHostFunctionProperty(the, slot, fx_clearTimer, 1, xsID("clearTimeout"), XS_DONT_ENUM_FLAG);
425
0
  slot = fxNextHostFunctionProperty(the, slot, fx_setInterval, 1, xsID("setInterval"), XS_DONT_ENUM_FLAG);
426
0
  slot = fxNextHostFunctionProperty(the, slot, fx_setTimeout, 1, xsID("setTimeout"), XS_DONT_ENUM_FLAG);
427
  
428
0
  slot = fxNextHostFunctionProperty(the, slot, fx_harden, 1, xsID("harden"), XS_DONT_ENUM_FLAG);
429
0
  slot = fxNextHostFunctionProperty(the, slot, fx_lockdown, 0, xsID("lockdown"), XS_DONT_ENUM_FLAG);
430
  
431
0
  slot = fxNextHostFunctionProperty(the, slot, fx_unicodeCompare, 2, xsID("unicodeCompare"), XS_DONT_ENUM_FLAG);
432
0
  slot = fxNextHostFunctionProperty(the, slot, fx_detachArrayBuffer, 1, xsID("detachArrayBuffer"), XS_DONT_ENUM_FLAG);
433
434
0
  mxPop();
435
0
  mxPop();
436
  
437
0
  modInstallTextDecoder(the);
438
0
  modInstallTextEncoder(the);
439
0
  modInstallBase64(the);
440
0
}
441
442
void fxPrintUsage()
443
0
{
444
0
  printf("xst [-h] [-e] [-f] [-j] [-m] [-p] [-s] [-t] [-v] strings...\n");
445
0
  printf("\t-b: strings are paths to script buffers\n");
446
0
  printf("\t-e: eval strings\n");
447
0
  printf("\t-f: fuzz with REPRL harness\n");
448
0
  printf("\t-h: print this help message\n");
449
0
  printf("\t-j: strings are paths to JSON buffers\n");
450
0
  printf("\t-m: strings are paths to modules\n");
451
0
  printf("\t-p: profile\n");
452
0
  printf("\t-s: strings are paths to scripts\n");
453
0
  printf("\t-t: strings are paths to test262 cases or directories\n");
454
0
  printf("\t-v: print XS version\n");
455
0
  printf("without -b, -e, -f, -j, -m, -s, or -t:\n");
456
0
  printf("\tif ../harness exists, strings are paths to test262 cases or directories\n");
457
0
  printf("\telse if the extension is .mjs, strings are paths to modules\n");
458
0
  printf("\telse strings are paths to scripts\n");
459
0
}
460
461
void fx_evalScript(xsMachine* the)
462
0
{
463
0
  txSlot* realm;
464
0
  txSlot* module = mxFunctionInstanceHome(mxFunction->value.reference)->value.home.module;
465
0
  if (!module) module = mxProgram.value.reference;
466
0
  realm = mxModuleInstanceInternal(module)->value.module.realm;
467
0
  txStringStream aStream;
468
0
  aStream.slot = mxArgv(0);
469
0
  aStream.offset = 0;
470
0
  aStream.size = mxStringLength(fxToString(the, mxArgv(0)));
471
0
  fxRunScript(the, fxParseScript(the, &aStream, fxStringGetter, mxProgramFlag | mxDebugFlag), mxRealmGlobal(realm), C_NULL, mxRealmClosures(realm)->value.reference, C_NULL, module);
472
0
  mxPullSlot(mxResult);
473
0
}
474
475
void fx_gc(xsMachine* the)
476
0
{
477
0
  xsCollectGarbage();
478
0
}
479
480
void fx_isLockedDown(xsMachine* the)
481
0
{
482
0
  xsResult = (mxProgram.value.reference->flag & XS_DONT_MARSHALL_FLAG) ? xsTrue : xsFalse;
483
0
}
484
485
void fx_metering(xsMachine* the)
486
0
{
487
0
#ifdef mxMetering
488
0
  xsResult = xsNumber(the->meterIndex);
489
0
#endif  
490
0
}
491
492
void fx_print(xsMachine* the)
493
11.4k
{
494
11.4k
  xsIntegerValue c = xsToInteger(xsArgc), i;
495
11.4k
  xsStringValue string, p, q;
496
11.4k
  xsVars(1);
497
11.4k
  xsVar(0) = xsGet(xsGlobal, xsID("String"));
498
20.2k
  for (i = 0; i < c; i++) {
499
8.86k
    if (i)
500
621
      fprintf(stdout, " ");
501
8.86k
    xsArg(i) = xsCallFunction1(xsVar(0), xsUndefined, xsArg(i));
502
8.86k
    p = string = xsToString(xsArg(i));
503
8.86k
  #if mxCESU8
504
306k
    for (;;) {
505
306k
      xsIntegerValue character;
506
306k
      q = fxUTF8Decode(p, &character);
507
308k
    again:
508
308k
      if (character == C_EOF)
509
8.86k
        break;
510
299k
      if (character == 0) {
511
55.7k
        if (p > string) {
512
21.7k
          char c = *p;
513
21.7k
          *p = 0;
514
21.7k
          fprintf(stdout, "%s", string);
515
21.7k
          *p = c;
516
21.7k
        }
517
55.7k
        string = q;
518
55.7k
      }
519
243k
      else if ((0x0000D800 <= character) && (character <= 0x0000DBFF)) {
520
2.23k
        xsStringValue r = q;
521
2.23k
        xsIntegerValue surrogate;
522
2.23k
        q = fxUTF8Decode(r, &surrogate);
523
2.23k
        if ((0x0000DC00 <= surrogate) && (surrogate <= 0x0000DFFF)) {
524
953
          char buffer[5];
525
953
          character = (txInteger)(0x00010000 + ((character & 0x03FF) << 10) + (surrogate & 0x03FF));
526
953
          if (p > string) {
527
874
            char c = *p;
528
874
            *p = 0;
529
874
            fprintf(stdout, "%s", string);
530
874
            *p = c;
531
874
          }
532
953
          p = fxUTF8Encode(buffer, character);
533
953
          *p = 0;
534
953
          fprintf(stdout, "%s", buffer);
535
953
          string = q;
536
953
        }
537
1.28k
        else {
538
1.28k
          p = r;
539
1.28k
          character = surrogate;
540
1.28k
          goto again;
541
1.28k
        }
542
2.23k
      }
543
298k
      p = q;
544
298k
    }
545
8.86k
  #endif  
546
8.86k
    fprintf(stdout, "%s", string);
547
8.86k
  }
548
11.4k
  fprintf(stdout, "\n");
549
11.4k
}
550
551
void fx_runScript(xsMachine* the)
552
0
{
553
0
  txSlot* realm = mxProgram.value.reference->next->value.module.realm;
554
0
  char path[C_PATH_MAX];
555
0
  txUnsigned flags = mxProgramFlag | mxDebugFlag;
556
0
  if (!c_realpath(fxToString(the, mxArgv(0)), path))
557
0
    xsURIError("file not found");
558
0
  txScript* script = fxLoadScript(the, path, flags);
559
0
  mxModuleInstanceInternal(mxProgram.value.reference)->value.module.id = fxID(the, path);
560
0
  fxRunScript(the, script, mxRealmGlobal(realm), C_NULL, mxRealmClosures(realm)->value.reference, C_NULL, mxProgram.value.reference);
561
0
  mxPullSlot(mxResult);
562
0
}
563
564
/* $262 */
565
566
void fx_agent_broadcast(xsMachine* the)
567
0
{
568
0
  txAgentCluster* agentCluster = &gxAgentCluster;
569
0
  if (xsIsInstanceOf(xsArg(0), xsTypedArrayPrototype)) {
570
0
    xsArg(0) = xsGet(xsArg(0), xsID("buffer"));
571
0
  }
572
0
    fxLockMutex(&(agentCluster->dataMutex));
573
0
  agentCluster->dataBuffer = xsMarshallAlien(xsArg(0));
574
0
  if (mxArgc > 1)
575
0
    agentCluster->dataValue = xsToInteger(xsArg(1));
576
0
  fxWakeAllCondition(&(agentCluster->dataCondition));
577
0
    fxUnlockMutex(&(agentCluster->dataMutex));
578
    
579
0
    fxLockMutex(&(agentCluster->countMutex));
580
0
    while (agentCluster->count > 0)
581
0
    fxSleepCondition(&(agentCluster->countCondition), &(agentCluster->countMutex));
582
0
    fxUnlockMutex(&(agentCluster->countMutex));
583
0
}
584
585
void fx_agent_getReport(xsMachine* the)
586
0
{
587
0
  txAgentCluster* agentCluster = &gxAgentCluster;
588
0
  txAgentReport* report = C_NULL;
589
0
    fxLockMutex(&(agentCluster->reportMutex));
590
0
  report = agentCluster->firstReport;
591
0
  if (report)
592
0
    agentCluster->firstReport = report->next;
593
0
    fxUnlockMutex(&(agentCluster->reportMutex));
594
0
    if (report) {
595
0
      xsResult = xsString(report->message);
596
0
      c_free(report);
597
0
    }
598
0
    else
599
0
      xsResult = xsNull;
600
0
}
601
602
void fx_agent_leaving(xsMachine* the)
603
0
{
604
0
}
605
606
void fx_agent_monotonicNow(xsMachine* the)
607
0
{
608
0
  xsResult = xsNumber(mxMonotonicNow());
609
0
}
610
611
void fx_agent_receiveBroadcast(xsMachine* the)
612
0
{
613
0
  txAgentCluster* agentCluster = &gxAgentCluster;
614
0
   fxLockMutex(&(agentCluster->dataMutex));
615
0
  while (agentCluster->dataBuffer == NULL)
616
0
    fxSleepCondition(&(agentCluster->dataCondition), &(agentCluster->dataMutex));
617
0
  xsResult = xsDemarshallAlien(agentCluster->dataBuffer);
618
0
    fxUnlockMutex(&(agentCluster->dataMutex));
619
  
620
0
    fxLockMutex(&(agentCluster->countMutex));
621
0
    agentCluster->count--;
622
0
    fxWakeCondition(&(agentCluster->countCondition));
623
0
    fxUnlockMutex(&(agentCluster->countMutex));
624
    
625
0
  xsCallFunction2(xsArg(0), xsGlobal, xsResult, xsInteger(agentCluster->dataValue));
626
0
}
627
628
void fx_agent_report(xsMachine* the)
629
0
{
630
0
  txAgentCluster* agentCluster = &gxAgentCluster;
631
0
  xsStringValue message = xsToString(xsArg(0));
632
0
  xsIntegerValue messageLength = mxStringLength(message);
633
0
  txAgentReport* report = c_malloc(sizeof(txAgentReport) + messageLength);
634
0
  if (!report) xsUnknownError("not enough memory");
635
0
    report->next = C_NULL;
636
0
  c_memcpy(&(report->message[0]), message, messageLength + 1);
637
0
    fxLockMutex(&(agentCluster->reportMutex));
638
0
    if (agentCluster->firstReport)
639
0
    agentCluster->lastReport->next = report;
640
0
    else
641
0
    agentCluster->firstReport = report;
642
0
  agentCluster->lastReport = report;
643
0
    fxUnlockMutex(&(agentCluster->reportMutex));
644
0
}
645
646
void fx_agent_sleep(xsMachine* the)
647
0
{
648
0
  xsIntegerValue delay = xsToInteger(xsArg(0));
649
#if mxWindows
650
  Sleep(delay);
651
#else 
652
0
  usleep(delay * 1000);
653
0
#endif
654
0
}
655
656
void fx_agent_start(xsMachine* the)
657
0
{
658
0
  xsStringValue script = xsToString(xsArg(0));
659
0
  xsIntegerValue scriptLength = mxStringLength(script);
660
0
  txAgentCluster* agentCluster = &gxAgentCluster;
661
0
  txAgent* agent = c_malloc(sizeof(txAgent) + scriptLength);
662
0
  if (!agent) xsUnknownError("not enough memory");
663
0
  c_memset(agent, 0, sizeof(txAgent));
664
0
  if (agentCluster->firstAgent)
665
0
    agentCluster->lastAgent->next = agent;
666
0
  else
667
0
    agentCluster->firstAgent = agent;
668
0
  agentCluster->lastAgent = agent;
669
0
  agentCluster->count++;
670
0
  agent->scriptLength = scriptLength;
671
0
  c_memcpy(&(agent->script[0]), script, scriptLength + 1);
672
#if mxWindows
673
  agent->thread = (HANDLE)_beginthreadex(NULL, 0, fx_agent_start_aux, agent, 0, NULL);
674
#elif mxMacOSX
675
  pthread_attr_t attr; 
676
  pthread_t self = pthread_self();
677
  size_t size = pthread_get_stacksize_np(self);
678
  pthread_attr_init(&attr);
679
  pthread_attr_setstacksize(&attr, size);
680
    pthread_create(&(agent->thread), &attr, &fx_agent_start_aux, agent);
681
#else 
682
0
    pthread_create(&(agent->thread), NULL, &fx_agent_start_aux, agent);
683
0
#endif
684
0
}
685
686
#if mxWindows
687
unsigned int __stdcall fx_agent_start_aux(void* it)
688
#else
689
void* fx_agent_start_aux(void* it)
690
#endif
691
0
{
692
0
  xsCreation creation = {
693
0
    16 * 1024 * 1024,   /* initialChunkSize */
694
0
    16 * 1024 * 1024,   /* incrementalChunkSize */
695
0
    1 * 1024 * 1024,  /* initialHeapCount */
696
0
    1 * 1024 * 1024,  /* incrementalHeapCount */
697
0
    4096,         /* stackCount */
698
0
    1024,         /* initialKeyCount */
699
0
    1024,       /* incrementalKeyCount */
700
0
    1993,         /* nameModulo */
701
0
    127,        /* symbolModulo */
702
0
    64 * 1024,      /* parserBufferSize */
703
0
    1993,       /* parserTableModulo */
704
0
  };
705
0
  txAgent* agent = it;
706
0
  xsMachine* machine = xsCreateMachine(&creation, "xst-agent", NULL);
707
0
  xsBeginHost(machine);
708
0
  {
709
0
    xsTry {
710
0
      txSlot* slot;
711
0
      txSlot* global;
712
0
      txStringCStream stream;
713
      
714
0
      mxPush(mxGlobal);
715
0
      global = the->stack;
716
      
717
0
      slot = fxLastProperty(the, fxNewHostObject(the, NULL));
718
0
      slot = fxNextHostFunctionProperty(the, slot, fx_agent_leaving, 0, xsID("leaving"), XS_DONT_ENUM_FLAG); 
719
0
      slot = fxNextHostFunctionProperty(the, slot, fx_agent_monotonicNow, 0, xsID("monotonicNow"), XS_DONT_ENUM_FLAG); 
720
0
      slot = fxNextHostFunctionProperty(the, slot, fx_agent_receiveBroadcast, 1, xsID("receiveBroadcast"), XS_DONT_ENUM_FLAG); 
721
0
      slot = fxNextHostFunctionProperty(the, slot, fx_agent_report, 1, xsID("report"), XS_DONT_ENUM_FLAG); 
722
0
      slot = fxNextHostFunctionProperty(the, slot, fx_agent_sleep, 1, xsID("sleep"), XS_DONT_ENUM_FLAG); 
723
0
      fxSetHostData(the, the->stack, agent);
724
      
725
0
      mxPush(mxObjectPrototype);
726
0
      slot = fxLastProperty(the, fxNewObjectInstance(the));
727
0
      slot = fxNextSlotProperty(the, slot, the->stack + 1, xsID("agent"), XS_GET_ONLY);
728
      
729
0
      slot = fxLastProperty(the, fxToInstance(the, global));
730
0
      slot = fxNextSlotProperty(the, slot, the->stack, xsID("$262"), XS_GET_ONLY);
731
      
732
0
      mxPop();
733
0
      mxPop();
734
0
      mxPop();
735
      
736
0
      stream.buffer = agent->script;
737
0
      stream.offset = 0;
738
0
      stream.size = agent->scriptLength;
739
0
      fxRunScript(the, fxParseScript(the, &stream, fxStringCGetter, mxProgramFlag), mxThis, C_NULL, C_NULL, C_NULL, mxProgram.value.reference);
740
0
      fxRunLoop(the);
741
0
    }
742
0
    xsCatch {
743
0
    }
744
0
  }
745
0
  xsEndHost(the);
746
0
  xsDeleteMachine(machine);
747
#if mxWindows
748
  return 0;
749
#else
750
0
  return NULL;
751
0
#endif
752
0
}
753
754
void fx_createRealm(xsMachine* the)
755
0
{
756
0
  xsResult = xsThis;
757
0
}
758
759
void fx_detachArrayBuffer(xsMachine* the)
760
0
{
761
0
  txSlot* slot = mxArgv(0);
762
0
  if (slot->kind == XS_REFERENCE_KIND) {
763
0
    txSlot* instance = slot->value.reference;
764
0
    if (((slot = instance->next)) && (slot->flag & XS_INTERNAL_FLAG) && (slot->kind == XS_ARRAY_BUFFER_KIND) && (instance != mxArrayBufferPrototype.value.reference)) {
765
0
      slot->value.arrayBuffer.address = C_NULL;
766
0
      slot->next->value.bufferInfo.length = 0;
767
0
      return;
768
0
    }
769
0
  }
770
0
  mxTypeError("this is no ArrayBuffer instance");
771
0
}
772
773
/* TIMER */
774
775
static txHostHooks gxTimerHooks = {
776
  fx_destroyTimer,
777
  fx_markTimer
778
};
779
780
void fx_callbackTimer(txSharedTimer* timer, void* refcon, txInteger refconSize)
781
0
{
782
0
  txJob* job = (txJob*)refcon;
783
0
  txMachine* the = job->the;
784
0
  if (the) {
785
0
    fxBeginHost(the);
786
0
    mxTry(the) {
787
0
      mxPushUndefined();
788
0
      mxPush(job->function);
789
0
      mxCall();
790
0
      mxPush(job->argument);
791
0
      mxRunCount(1);
792
0
      mxPop();
793
0
    }
794
0
    mxCatch(the) {
795
0
      *((txSlot*)the->rejection) = mxException;
796
0
      timer->interval = 0;
797
0
    }
798
0
    if (job->the) {
799
0
      if (timer->interval == 0) {
800
0
        fxAccess(the, &job->self);
801
0
        *mxResult = the->scratch;
802
0
        fxForget(the, &job->self);
803
0
        fxSetHostData(the, mxResult, NULL);
804
0
        job->the = NULL;
805
0
      }
806
0
    }
807
0
    else
808
0
      timer->interval = 0;
809
0
    fxEndHost(the);
810
0
  }
811
0
  else
812
0
    timer->interval = 0;
813
0
}
814
815
void fx_clearTimer(txMachine* the)
816
0
{
817
0
  if ((0 == mxArgc) || (XS_REFERENCE_KIND != mxArgv(0)->kind) || (C_NULL == fxGetHostDataIf(the, mxArgv(0))))
818
0
    return;
819
0
  txHostHooks* hooks = fxGetHostHooks(the, mxArgv(0));
820
0
  if (hooks == &gxTimerHooks) {
821
0
    txJob* job = fxGetHostData(the, mxArgv(0));
822
0
    if (job) {
823
0
      fxForget(the, &job->self);
824
0
      fxSetHostData(the, mxArgv(0), NULL);
825
0
      job->the = NULL;
826
0
      txSharedTimer* timer = (txSharedTimer*)(((txByte*)job) - offsetof(txSharedTimer, refcon));
827
0
      fxRescheduleSharedTimer(timer, 0, 0);
828
0
    }
829
0
  }
830
0
}
831
832
void fx_destroyTimer(void* data)
833
0
{
834
0
}
835
836
void fx_markTimer(txMachine* the, void* it, txMarkRoot markRoot)
837
0
{
838
0
  txJob* job = it;
839
0
  if (job) {
840
0
    (*markRoot)(the, &job->function);
841
0
    (*markRoot)(the, &job->argument);
842
0
  }
843
0
}
844
845
void fx_setInterval(txMachine* the)
846
0
{
847
0
  fx_setTimer(the, fxToNumber(the, mxArgv(1)), 1);
848
0
}
849
850
void fx_setTimeout(txMachine* the)
851
0
{
852
0
  fx_setTimer(the, fxToNumber(the, mxArgv(1)), 0);
853
0
}
854
855
void fx_setTimer(txMachine* the, txNumber interval, txBoolean repeat)
856
0
{
857
0
  txJob _job;
858
0
  txJob* job;
859
0
  txSharedTimer* timer;
860
0
  if (c_isnan(interval) || (interval < 0))
861
0
    interval = 0;
862
0
  c_memset(&_job, 0, sizeof(txJob));
863
0
  timer = fxScheduleSharedTimer(interval, (repeat) ? interval : 0, fx_callbackTimer, &_job, sizeof(txJob));  
864
0
  if (!timer)
865
0
    fxAbort(the, XS_NOT_ENOUGH_MEMORY_EXIT);
866
0
  job = (txJob*)&(timer->refcon[0]);
867
0
  job->the = the;
868
0
  fxNewHostObject(the, NULL);
869
0
    mxPull(job->self);
870
0
  job->function = *mxArgv(0);
871
0
  if (mxArgc > 2)
872
0
    job->argument = *mxArgv(2);
873
0
  else
874
0
    job->argument = mxUndefined;
875
0
  fxSetHostData(the, &job->self, job);
876
0
  fxSetHostHooks(the, &job->self, &gxTimerHooks);
877
0
  fxRemember(the, &job->self);
878
0
  fxAccess(the, &job->self);
879
0
  *mxResult = the->scratch;
880
0
}
881
882
/* PLATFORM */
883
884
void fxCreateMachinePlatform(txMachine* the)
885
27.2k
{
886
27.2k
#ifdef mxDebug
887
27.2k
  the->connection = mxNoSocket;
888
27.2k
#endif
889
27.2k
}
890
891
void fxDeleteMachinePlatform(txMachine* the)
892
27.2k
{
893
27.2k
}
894
895
void fxQueuePromiseJobs(txMachine* the)
896
134k
{
897
134k
  the->promiseJobs = 1;
898
134k
}
899
900
/* SHARED TIMERS */
901
902
typedef struct sxSharedTimers txSharedTimers;
903
struct sxSharedTimers {
904
  txSharedTimer* first;
905
  txMutex mutex;
906
};
907
static txSharedTimers gxSharedTimers;
908
909
void fxInitializeSharedTimers()
910
27.2k
{
911
27.2k
  c_memset(&gxSharedTimers, 0, sizeof(txSharedTimers));
912
27.2k
  fxCreateMutex(&(gxSharedTimers.mutex));
913
27.2k
}
914
915
void fxTerminateSharedTimers()
916
27.2k
{
917
27.2k
  fxDeleteMutex(&(gxSharedTimers.mutex));
918
27.2k
  if (gxSharedTimers.first != C_NULL) {
919
0
    fprintf(stderr, "# shared timers mismatch!\n");
920
0
    exit(1);
921
0
  }
922
27.2k
}
923
924
void fxRescheduleSharedTimer(txSharedTimer* timer, txNumber timeout, txNumber interval)
925
0
{
926
0
    fxLockMutex(&(gxSharedTimers.mutex));
927
0
  timer->when = mxMonotonicNow() + timeout;
928
0
  timer->interval = interval;
929
0
    fxUnlockMutex(&(gxSharedTimers.mutex));
930
0
}
931
932
void* fxScheduleSharedTimer(txNumber timeout, txNumber interval, txSharedTimerCallback callback, void* refcon, txInteger refconSize)
933
2
{
934
2
  txSharedTimer* timer;
935
2
  txSharedTimer** address;
936
2
  txSharedTimer* link;
937
2
  timer = c_calloc(1, sizeof(txSharedTimer) + refconSize - 1);
938
2
  if (timer) {
939
2
    timer->thread = mxCurrentThread();
940
2
    timer->when = mxMonotonicNow() + timeout;
941
2
    timer->interval = interval;
942
2
    timer->callback = callback;
943
2
    timer->refconSize = refconSize;
944
2
    c_memcpy(timer->refcon, refcon, refconSize);
945
    
946
2
    fxLockMutex(&(gxSharedTimers.mutex));
947
2
    address = (txSharedTimer**)&(gxSharedTimers.first);
948
2
    while ((link = *address))
949
0
      address = &(link->next);
950
2
    *address = timer;
951
2
    fxUnlockMutex(&(gxSharedTimers.mutex));
952
2
    }
953
2
    return timer;
954
2
}
955
956
void fxUnscheduleSharedTimer(txSharedTimer* timer)
957
2
{
958
2
  txSharedTimer** address;
959
2
  txSharedTimer* link;
960
2
    fxLockMutex(&(gxSharedTimers.mutex));
961
2
    address = (txSharedTimer**)&(gxSharedTimers.first);
962
2
  while ((link = *address)) {
963
2
    if (link == timer) {
964
2
      *address = link->next;
965
2
      c_free(timer);
966
2
      break;
967
2
    }
968
0
    address = &(link->next);
969
0
  }
970
2
    fxUnlockMutex(&(gxSharedTimers.mutex));
971
2
}
972
973
void fxRunLoop(txMachine* the)
974
15.1k
{
975
15.1k
  txThread thread = mxCurrentThread();
976
15.1k
  txNumber when;
977
15.1k
  txInteger count;
978
15.1k
  txSharedTimer* timer;
979
  
980
171k
  for (;;) {
981
171k
    fxEndJob(the);
982
172k
    while (the->promiseJobs) {
983
135k
      while (the->promiseJobs) {
984
134k
        the->promiseJobs = 0;
985
134k
        fxRunPromiseJobs(the);
986
134k
      }
987
287
      fxEndJob(the);
988
287
    }
989
171k
    when = mxMonotonicNow();
990
171k
    fxLockMutex(&(gxSharedTimers.mutex));
991
171k
    count = 0;
992
171k
    timer = gxSharedTimers.first;
993
328k
    while (timer) {
994
156k
      if (timer->thread == thread) {
995
156k
        count++;
996
156k
        if (timer->when <= when)
997
2
          break; // one timer at time to run promise jobs queued by the timer in the same "tick"
998
156k
      }
999
156k
      timer = timer->next;
1000
156k
    }
1001
171k
    fxUnlockMutex(&(gxSharedTimers.mutex));
1002
171k
    if (timer) {
1003
2
      (timer->callback)(timer, timer->refcon, timer->refconSize);
1004
2
      if (timer->interval == 0)
1005
2
        fxUnscheduleSharedTimer(timer);
1006
0
      else
1007
0
        timer->when += timer->interval;
1008
2
      continue;
1009
2
    }
1010
171k
    if (count == 0)
1011
15.0k
      break;
1012
171k
  }
1013
15.1k
}
1014
1015
void fxFulfillModuleFile(txMachine* the)
1016
0
{
1017
0
}
1018
1019
void fxRejectModuleFile(txMachine* the)
1020
0
{
1021
0
  *((txSlot*)the->rejection) = xsArg(0);
1022
0
}
1023
1024
void fxRunModuleFile(txMachine* the, txString path)
1025
0
{
1026
0
  txSlot* realm = mxProgram.value.reference->next->value.module.realm;
1027
0
  mxPushStringC(path);
1028
0
  mxPushUndefined();
1029
0
  fxRunImport(the, realm, C_NULL);
1030
0
  mxDub();
1031
0
  fxGetID(the, mxID(_then));
1032
0
  mxCall();
1033
0
  fxNewHostFunction(the, fxFulfillModuleFile, 1, XS_NO_ID, XS_NO_ID);
1034
0
  fxNewHostFunction(the, fxRejectModuleFile, 1, XS_NO_ID, XS_NO_ID);
1035
0
  mxRunCount(2);
1036
0
  mxPop();
1037
0
}
1038
1039
void fxRunProgramFile(txMachine* the, txString path, txUnsigned flags)
1040
0
{
1041
0
  txSlot* realm = mxProgram.value.reference->next->value.module.realm;
1042
0
  txScript* script = fxLoadScript(the, path, flags);
1043
0
  mxModuleInstanceInternal(mxProgram.value.reference)->value.module.id = fxID(the, path);
1044
0
  fxRunScript(the, script, mxRealmGlobal(realm), C_NULL, mxRealmClosures(realm)->value.reference, C_NULL, mxProgram.value.reference);
1045
0
  mxPullSlot(mxResult);
1046
0
}
1047
1048
void fxAbort(txMachine* the, int status)
1049
1.17k
{
1050
1.17k
  if (XS_DEBUGGER_EXIT == status)
1051
0
    c_exit(1);
1052
1.17k
  if (the->exitStatus) // xsEndHost calls fxAbort!
1053
0
    return;
1054
1.17k
  the->exitStatus = status;
1055
1.17k
  fxExitToHost(the);
1056
1.17k
}
1057
1058
txID fxFindModule(txMachine* the, txSlot* realm, txID moduleID, txSlot* slot)
1059
54.3k
{
1060
54.3k
  char name[C_PATH_MAX];
1061
54.3k
  char path[C_PATH_MAX];
1062
54.3k
  txInteger dot = 0;
1063
54.3k
  txString slash;
1064
54.3k
  fxToStringBuffer(the, slot, name, sizeof(name));
1065
54.3k
  if (name[0] == '.') {
1066
864
    if (name[1] == '/') {
1067
1
      dot = 1;
1068
1
    }
1069
863
    else if ((name[1] == '.') && (name[2] == '/')) {
1070
0
      dot = 2;
1071
0
    }
1072
864
  }
1073
54.3k
  if (dot) {
1074
1
    if (moduleID == XS_NO_ID)
1075
0
      return XS_NO_ID;
1076
1
    c_strncpy(path, fxGetKeyName(the, moduleID), C_PATH_MAX - 1);
1077
1
    path[C_PATH_MAX - 1] = 0;
1078
1
    slash = c_strrchr(path, mxSeparator);
1079
1
    if (!slash)
1080
1
      return XS_NO_ID;
1081
0
    if (dot == 2) {
1082
0
      *slash = 0;
1083
0
      slash = c_strrchr(path, mxSeparator);
1084
0
      if (!slash)
1085
0
        return XS_NO_ID;
1086
0
    }
1087
#if mxWindows
1088
    {
1089
      char c;
1090
      char* s = name;
1091
      while ((c = *s)) {
1092
        if (c == '/')
1093
          *s = '\\';
1094
        s++;
1095
      }
1096
    }
1097
#endif
1098
0
  }
1099
54.3k
  else
1100
54.3k
    slash = path;
1101
54.3k
  *slash = 0;
1102
54.3k
  if ((c_strlen(path) + c_strlen(name + dot)) >= sizeof(path))
1103
0
    xsRangeError("path too long");
1104
54.3k
  c_strcat(path, name + dot);
1105
54.3k
  return fxNewNameC(the, path);
1106
54.3k
}
1107
1108
void fxLoadModule(txMachine* the, txSlot* module, txID moduleID)
1109
515
{
1110
515
  char path[C_PATH_MAX];
1111
515
  char real[C_PATH_MAX];
1112
515
  txString dot;
1113
515
  txScript* script;
1114
515
#ifdef mxDebug
1115
515
  txUnsigned flags = mxDebugFlag;
1116
#else
1117
  txUnsigned flags = 0;
1118
#endif
1119
515
  if (fxBundleLoad(the, module, moduleID))
1120
0
    return;
1121
515
  c_strncpy(path, fxGetKeyName(the, moduleID), C_PATH_MAX - 1);
1122
515
  path[C_PATH_MAX - 1] = 0;
1123
515
  if (c_realpath(path, real)) {
1124
#if mxWindows
1125
    DWORD attributes;
1126
    attributes = GetFileAttributes(path);
1127
    if (attributes != 0xFFFFFFFF) {
1128
      if (attributes & FILE_ATTRIBUTE_DIRECTORY)
1129
        return;
1130
    }
1131
#else
1132
0
    struct stat a_stat;
1133
0
    if (stat(path, &a_stat) == 0) {
1134
0
      if (S_ISDIR(a_stat.st_mode)) 
1135
0
        return;
1136
0
    }
1137
0
#endif  
1138
0
    dot = c_strrchr(real, '.');
1139
0
    if (dot && !c_strcmp(dot, ".json"))
1140
0
      flags |= mxJSONModuleFlag;
1141
0
    script = fxLoadScript(the, real, flags);
1142
0
    if (script)
1143
0
      fxResolveModule(the, module, moduleID, script, C_NULL, C_NULL);
1144
0
  }
1145
515
}
1146
1147
txScript* fxLoadScript(txMachine* the, txString path, txUnsigned flags)
1148
0
{
1149
0
  txParser _parser;
1150
0
  txParser* parser = &_parser;
1151
0
  txParserJump jump;
1152
0
  FILE* file = NULL;
1153
0
  txString name = NULL;
1154
0
  char map[C_PATH_MAX];
1155
0
  txScript* script = NULL;
1156
0
  fxInitializeParser(parser, the, the->parserBufferSize, the->parserTableModulo);
1157
0
  parser->firstJump = &jump;
1158
0
  file = fopen(path, "r");
1159
0
  if (c_setjmp(jump.jmp_buf) == 0) {
1160
0
    mxParserThrowElse(file);
1161
0
    parser->path = fxNewParserSymbol(parser, path);
1162
0
    fxParserTree(parser, file, (txGetter)fgetc, flags, &name);
1163
0
    fclose(file);
1164
0
    file = NULL;
1165
0
    if (name) {
1166
0
      mxParserThrowElse(c_realpath(fxCombinePath(parser, path, name), map));
1167
0
      parser->path = fxNewParserSymbol(parser, map);
1168
0
      file = fopen(map, "r");
1169
0
      mxParserThrowElse(file);
1170
0
      fxParserSourceMap(parser, file, (txGetter)fgetc, flags, &name);
1171
0
      fclose(file);
1172
0
      file = NULL;
1173
0
      if ((parser->errorCount == 0) && name) {
1174
0
        mxParserThrowElse(c_realpath(fxCombinePath(parser, map, name), map));
1175
0
        parser->path = fxNewParserSymbol(parser, map);
1176
0
      }
1177
0
    }
1178
0
    fxParserHoist(parser);
1179
0
    fxParserBind(parser);
1180
0
    script = fxParserCode(parser);
1181
0
  }
1182
0
  if (file)
1183
0
    fclose(file);
1184
#ifdef mxInstrument
1185
  if (the->peakParserSize < parser->total)
1186
    the->peakParserSize = parser->total;
1187
#endif
1188
0
  fxTerminateParser(parser);
1189
0
  return script;
1190
0
}
1191
1192
/* DEBUG */
1193
1194
#ifdef mxDebug
1195
1196
void fxConnect(txMachine* the)
1197
27.2k
{
1198
27.2k
  if (!c_strcmp(the->name, "xst_fuzz"))
1199
0
    return;
1200
27.2k
  if (!c_strcmp(the->name, "xst_fuzz_oss"))
1201
27.2k
    return;
1202
#ifdef mxMultipleThreads
1203
  if (!c_strcmp(the->name, "xst262"))
1204
    return;
1205
  if (!c_strcmp(the->name, "xst-agent"))
1206
    return;
1207
#endif    
1208
0
  char name[256];
1209
0
  char* colon;
1210
0
  int port;
1211
#if mxWindows
1212
  if (GetEnvironmentVariable("XSBUG_HOST", name, sizeof(name))) {
1213
#else
1214
0
  colon = getenv("XSBUG_HOST");
1215
0
  if ((colon) && (c_strlen(colon) + 1 < sizeof(name))) {
1216
0
    c_strcpy(name, colon);
1217
0
#endif    
1218
0
    colon = strchr(name, ':');
1219
0
    if (colon == NULL)
1220
0
      port = 5002;
1221
0
    else {
1222
0
      *colon = 0;
1223
0
      colon++;
1224
0
      port = strtol(colon, NULL, 10);
1225
0
    }
1226
0
  }
1227
0
  else {
1228
0
    strcpy(name, "localhost");
1229
0
    port = 5002;
1230
0
  }
1231
#if mxWindows
1232
{   
1233
  WSADATA wsaData;
1234
  struct hostent *host;
1235
  struct sockaddr_in address;
1236
  unsigned long flag;
1237
  if (WSAStartup(0x202, &wsaData) == SOCKET_ERROR)
1238
    return;
1239
  host = gethostbyname(name);
1240
  if (!host)
1241
    goto bail;
1242
  memset(&address, 0, sizeof(address));
1243
  address.sin_family = AF_INET;
1244
  memcpy(&(address.sin_addr), host->h_addr, host->h_length);
1245
    address.sin_port = htons(port);
1246
  the->connection = socket(AF_INET, SOCK_STREAM, 0);
1247
  if (the->connection == INVALID_SOCKET)
1248
    return;
1249
    flag = 1;
1250
    ioctlsocket(the->connection, FIONBIO, &flag);
1251
  if (connect(the->connection, (struct sockaddr*)&address, sizeof(address)) == SOCKET_ERROR) {
1252
    if (WSAEWOULDBLOCK == WSAGetLastError()) {
1253
      fd_set fds;
1254
      struct timeval timeout = { 2, 0 }; // 2 seconds, 0 micro-seconds
1255
      FD_ZERO(&fds);
1256
      FD_SET(the->connection, &fds);
1257
      if (select(0, NULL, &fds, NULL, &timeout) == 0)
1258
        goto bail;
1259
      if (!FD_ISSET(the->connection, &fds))
1260
        goto bail;
1261
    }
1262
    else
1263
      goto bail;
1264
  }
1265
  flag = 0;
1266
  ioctlsocket(the->connection, FIONBIO, &flag);
1267
}
1268
#else
1269
0
{   
1270
0
  struct sockaddr_in address;
1271
0
  int flag;
1272
0
  memset(&address, 0, sizeof(address));
1273
0
    address.sin_family = AF_INET;
1274
0
  address.sin_addr.s_addr = inet_addr(name);
1275
0
  if (address.sin_addr.s_addr == INADDR_NONE) {
1276
0
    struct hostent *host = gethostbyname(name);
1277
0
    if (!host)
1278
0
      return;
1279
0
    memcpy(&(address.sin_addr), host->h_addr, host->h_length);
1280
0
  }
1281
0
    address.sin_port = htons(port);
1282
0
  the->connection = socket(AF_INET, SOCK_STREAM, 0);
1283
0
  if (the->connection <= 0)
1284
0
    goto bail;
1285
0
  c_signal(SIGPIPE, SIG_IGN);
1286
#if mxMacOSX
1287
  {
1288
    int set = 1;
1289
    setsockopt(the->connection, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
1290
  }
1291
#endif
1292
0
  flag = fcntl(the->connection, F_GETFL, 0);
1293
0
  fcntl(the->connection, F_SETFL, flag | O_NONBLOCK);
1294
0
  if (connect(the->connection, (struct sockaddr*)&address, sizeof(address)) < 0) {
1295
0
       if (errno == EINPROGRESS) { 
1296
0
      fd_set fds;
1297
0
      struct timeval timeout = { 2, 0 }; // 2 seconds, 0 micro-seconds
1298
0
      int error = 0;
1299
0
      unsigned int length = sizeof(error);
1300
0
      FD_ZERO(&fds);
1301
0
      FD_SET(the->connection, &fds);
1302
0
      if (select(the->connection + 1, NULL, &fds, NULL, &timeout) == 0)
1303
0
        goto bail;
1304
0
      if (!FD_ISSET(the->connection, &fds))
1305
0
        goto bail;
1306
0
      if (getsockopt(the->connection, SOL_SOCKET, SO_ERROR, &error, &length) < 0)
1307
0
        goto bail;
1308
0
      if (error)
1309
0
        goto bail;
1310
0
    }
1311
0
    else
1312
0
      goto bail;
1313
0
  }
1314
0
  fcntl(the->connection, F_SETFL, flag);
1315
0
  c_signal(SIGPIPE, SIG_DFL);
1316
0
}
1317
0
#endif
1318
0
  return;
1319
0
bail:
1320
0
  fxDisconnect(the);
1321
0
}
1322
1323
void fxDisconnect(txMachine* the)
1324
0
{
1325
#if mxWindows
1326
  if (the->connection != INVALID_SOCKET) {
1327
    closesocket(the->connection);
1328
    the->connection = INVALID_SOCKET;
1329
  }
1330
  WSACleanup();
1331
#else
1332
0
  if (the->connection >= 0) {
1333
0
    close(the->connection);
1334
0
    the->connection = -1;
1335
0
  }
1336
0
#endif
1337
0
}
1338
1339
txBoolean fxIsConnected(txMachine* the)
1340
9.94M
{
1341
9.94M
  return (the->connection != mxNoSocket) ? 1 : 0;
1342
9.94M
}
1343
1344
txBoolean fxIsReadable(txMachine* the)
1345
105M
{
1346
105M
  return 0;
1347
105M
}
1348
1349
void fxReceive(txMachine* the)
1350
0
{
1351
0
  int count;
1352
0
  if (the->connection != mxNoSocket) {
1353
#if mxWindows
1354
    count = recv(the->connection, the->debugBuffer, sizeof(the->debugBuffer) - 1, 0);
1355
    if (count < 0)
1356
      fxDisconnect(the);
1357
    else
1358
      the->debugOffset = count;
1359
#else
1360
0
  again:
1361
0
    count = read(the->connection, the->debugBuffer, sizeof(the->debugBuffer) - 1);
1362
0
    if (count < 0) {
1363
0
      if (errno == EINTR)
1364
0
        goto again;
1365
0
      else
1366
0
        fxDisconnect(the);
1367
0
    }
1368
0
    else
1369
0
      the->debugOffset = count;
1370
0
#endif
1371
0
  }
1372
0
  the->debugBuffer[the->debugOffset] = 0;
1373
0
}
1374
1375
void fxSend(txMachine* the, txBoolean more)
1376
0
{
1377
0
  if (the->connection != mxNoSocket) {
1378
#if mxWindows
1379
    if (send(the->connection, the->echoBuffer, the->echoOffset, 0) <= 0)
1380
      fxDisconnect(the);
1381
#else
1382
0
  again:
1383
0
    if (write(the->connection, the->echoBuffer, the->echoOffset) <= 0) {
1384
0
      if (errno == EINTR)
1385
0
        goto again;
1386
0
      else
1387
0
        fxDisconnect(the);
1388
0
    }
1389
0
#endif
1390
0
  }
1391
0
}
1392
1393
#endif /* mxDebug */
1394
1395
1396
1397
1398