common.h
1 #include <stdlib.h>
2 #include <kuroko/kuroko.h>
3 #include <kuroko/vm.h>
4 
5 /* Copied from src/kuroko.c */
6 static void findInterpreter(char * argv[]) {
7 #ifdef _WIN32
8  vm.binpath = strdup(_pgmptr);
9 #else
10  /* Try asking /proc */
11  char tmp[4096];
12  char * binpath = realpath("/proc/self/exe", NULL);
13  if (!binpath || (access(binpath, X_OK) != 0)) {
14  if (binpath) {
15  free(binpath);
16  binpath = NULL;
17  }
18  if (strchr(argv[0], '/')) {
19  binpath = realpath(argv[0], NULL);
20  } else {
21  /* Search PATH for argv[0] */
22  char * p = getenv("PATH");
23  if (!p) return;
24  char * _path = strdup(p);
25  char * path = _path;
26  while (path) {
27  char * next = strchr(path,':');
28  if (next) *next++ = '\0';
29 
30  snprintf(tmp, 4096, "%s/%s", path, argv[0]);
31  if (access(tmp, X_OK) == 0) {
32  binpath = strdup(tmp);
33  break;
34  }
35  path = next;
36  }
37  free(_path);
38  }
39  }
40  if (binpath) {
41  vm.binpath = binpath;
42  } /* Else, give up at this point and just don't attach it at all. */
43 #endif
44 }
45 
46 /* Collect arguments for script, also copied from src/kuroko.c */
47 static KrkValue addArgs(int argc, char * argv[]) {
48  for (int arg = optind; arg < argc; ++arg) {
49  krk_push(OBJECT_VAL(krk_copyString(argv[arg],strlen(argv[arg]))));
50  }
51  KrkValue argList = krk_callNativeOnStack(argc - optind + (optind == argc), &krk_currentThread.stackTop[-(argc - optind + (optind == argc))], 0, krk_list_of);
52  krk_push(argList);
53  krk_attachNamedValue(&vm.system->fields, "argv", argList);
54  krk_pop();
55  for (int arg = optind; arg < argc + (optind == argc); ++arg) krk_pop();
56  return argList;
57 }
58 
Top-level header with configuration macros.
KrkValue krk_list_of(int argc, const KrkValue argv[], int hasKw)
Create a list object.
Definition: obj_list.c:30
KrkString * krk_copyString(const char *chars, size_t length)
Obtain a string object representation of the given C string.
Definition: object.c:224
void krk_attachNamedValue(KrkTable *table, const char name[], KrkValue obj)
Attach a value to an attribute table.
Definition: vm.c:794
KrkValue * stackTop
Definition: vm.h:159
Stack reference or primative value.
Core API for the bytecode virtual machine.
krk_threadLocal KrkThreadState krk_currentThread
Thread-local VM state.
#define vm
Convenience macro for namespacing.
Definition: vm.h:257
KrkValue krk_callNativeOnStack(size_t argCount, const KrkValue *stackArgs, int hasKw, NativeFn native)
Call a native function using a reference to stack arguments safely.
Definition: vm.c:601
KrkValue krk_pop(void)
Pop the top of the stack.
Definition: vm.c:131
void krk_push(KrkValue value)
Push a stack value.
Definition: vm.c:118