summaryrefslogtreecommitdiff
path: root/shell/igt-shell.cc
blob: 5ebb30bc6531f260e843572b4045d3ef8dbaf13c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <unistd.h>

#include <iostream>
#include <fstream>
#include <sstream>

#include "v8.h"
#include "libplatform/libplatform.h"

#include "igt-shell.h"
#include "v8-helpers.h"

#include "../lib/version.h"
#include "../config.h"

using namespace v8;

static const char* ToCString(const String::Utf8Value& value) {
  return *value ? *value : "<invalid string>";
}

static void ReportException(Isolate* iso, TryCatch* try_catch)
{
  HandleScope handle_scope(iso);
  String::Utf8Value exception(iso, try_catch->Exception());
  const char* exception_string = ToCString(exception);

  Local<Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    fprintf(stderr, "%s\n", exception_string);
  } else {
    String::Utf8Value filename(iso,
                               message->GetScriptOrigin().ResourceName());
    Local<Context> ctx(iso->GetCurrentContext());
    fprintf(stderr, "%s:%i: %s\n",
            ToCString(filename),
            message->GetLineNumber(ctx).FromJust(),
            exception_string);

    String::Utf8Value sourceline(iso,
                                 message->GetSourceLine(ctx).ToLocalChecked());
    fprintf(stderr, "%s\n", ToCString(sourceline));

    int start = message->GetStartColumn(ctx).FromJust();
    for (int i = 0; i < start; i++)
      fprintf(stderr, " ");
    int end = message->GetEndColumn(ctx).FromJust();
    for (int i = start; i < end; i++)
      fprintf(stderr, "^");
    fprintf(stderr, "\n");

    Local<Value> stack_trace_string;
    if (try_catch->StackTrace(ctx).ToLocal(&stack_trace_string) &&
        stack_trace_string->IsString() &&
        Local<String>::Cast(stack_trace_string)->Length() > 0) {
      String::Utf8Value stack_trace(iso, stack_trace_string);
      fprintf(stderr, "%s\n", ToCString(stack_trace));
    }
  }
}

static bool ExecuteString(Isolate* iso, Local<String> source,
                          Local<Value> name, bool print_result,
                          bool report_exceptions)
{
  HandleScope handle_scope(iso);
  TryCatch try_catch(iso);

  ScriptOrigin origin(name);
  Local<Context> ctx(iso->GetCurrentContext());
  Local<Script> script;
  if (!Script::Compile(ctx, source, &origin).ToLocal(&script)) {
    if (report_exceptions)
      ReportException(iso, &try_catch);
    return false;
  }

  Local<Value> result;
  if (!script->Run(ctx).ToLocal(&result)) {
    if (report_exceptions)
      ReportException(iso, &try_catch);
    return false;
  }

  if (print_result && !result->IsUndefined()) {
    String::Utf8Value str(iso, result);
    printf("%s\n", ToCString(str));
  }

  return true;
}

static void Print(const FunctionCallbackInfo<Value>& args)
{
  auto iso = args.GetIsolate();
  HandleScope handle_scope(iso);

  for (int i = 0; i < args.Length(); i++) {
    String::Utf8Value str(iso, args[i]);
    printf("%s%s", i ? " " : "", ToCString(str));
  }
  printf("\n");
  fflush(stdout);
}

static MaybeLocal<String> ReadStream(Isolate* iso, std::istream &in)
{
  std::stringstream out;
  out << in.rdbuf();
  std::string str = out.str();
  return String::NewFromUtf8(iso, str.c_str(), NewStringType::kNormal,
                             str.length());
}


MaybeLocal<String> ReadFile(Isolate* iso, const char* filename)
{
  std::ifstream stream(filename);
  if (!stream)
    iso->ThrowException(AsString(iso, "Error opening file").ToLocalChecked());

  return ReadStream(iso, stream);
}

static void Read(const FunctionCallbackInfo<Value>& args)
{
  auto iso = args.GetIsolate();

  if (args.Length() != 1) {
    iso->ThrowException(AsString(iso, "Bad parameters").ToLocalChecked());
    return;
  }

  String::Utf8Value filename(iso, args[0]);
  if (*filename == NULL) {
    iso->ThrowException(AsString(iso, "Bad parameters").ToLocalChecked());
    return;
  }

  Local<String> source;
  if (!ReadFile(iso, *filename).ToLocal(&source)) {
    iso->ThrowException(AsString(iso, "Error reading file").ToLocalChecked());
    return;
  }

  args.GetReturnValue().Set(source);
}

static void Load(const FunctionCallbackInfo<Value>& args)
{
  auto iso = args.GetIsolate();

  for (int i = 0; i < args.Length(); i++) {
    HandleScope handle_scope(iso);
    String::Utf8Value filename(iso, args[i]);
    if (*filename == NULL) {
      iso->ThrowException(AsString(iso, "Bad parameters").ToLocalChecked());
      return;
    }

    Local<String> source;
    if (!ReadFile(iso, *filename).ToLocal(&source)) {
      iso->ThrowException(AsString(iso, "Error loading file").ToLocalChecked());
      return;
    }

    if (!ExecuteString(iso, source, args[i], false, false)) {
      iso->ThrowException(AsString(iso, "Error executing file").ToLocalChecked());
      return;
    }
  }
}

static void Quit(const FunctionCallbackInfo<Value>& args)
{
  int exit_code =
      args[0]->Int32Value(args.GetIsolate()->GetCurrentContext()).FromMaybe(0);
  fflush(stdout);
  fflush(stderr);
  exit(exit_code);
}

static struct igt_builtin *globals;

void igt_register_global(struct igt_builtin *b)
{
  b->next = globals;
  globals = b;
}

static void shell_template(Isolate *iso, Local<ObjectTemplate> global)
{
  static const v8_helper_fn funcs[] = {
    { "print", Print },
    { "read", Read },
    { "load", Load },
    { "quit", Quit },
    { },
  };
  v8_helper_funcs(iso, global, funcs);
}

static Local<Context> ShellContext(Isolate* iso)
{
  Local<ObjectTemplate> global = ObjectTemplate::New(iso);

  shell_template(iso, global); /* XXX defer to shell */
  for (auto *b = globals; b; b = b->next)
	  b->ctor(iso, global);

  return Context::New(iso, NULL, global);
}

static void print_welcome()
{
  struct utsname uts;

  uname(&uts);
  printf("IGT Version: %s-%s (%s) (%s: %s %s)\n",
         PACKAGE_VERSION, IGT_GIT_SHA1, TARGET_CPU_PLATFORM,
         uts.sysname, uts.release, uts.machine);
  printf("V8: %s\n", V8::GetVersion());
}

static int do_eval(Isolate *iso, Platform *p, const char *str)
{
  Handle<String> filename = AsString(iso, "eval").ToLocalChecked();
  Handle<String> source = AsString(iso, str).ToLocalChecked();

  bool success = ExecuteString(iso, source, filename, false, true);
  while (platform::PumpMessageLoop(p, iso))
          ;

  return !success;
}

static int run(Isolate *iso, Platform *p, int argc, char **argv)
{
  while (++optind < argc) {
    HandleScope handle_scope(iso);
    const char *str = argv[optind];

    Local<String> source;
    if (!strcmp(str, "-")) {
      if (!ReadStream(iso, std::cin).ToLocal(&source)) {
        fprintf(stderr, "Error reading '%s'\n", str);
        return 1;
      }
    } else {
      if (!ReadFile(iso, str).ToLocal(&source)) {
        fprintf(stderr, "Error reading '%s'\n", str);
        return 1;
      }
    }

    Local<String> filename = AsString(iso, str).ToLocalChecked();
    if (!ExecuteString(iso, source, filename, true, true))
      return 1;

    while (platform::PumpMessageLoop(p, iso))
      ;
  }

  return 0;
}

static int shell(Isolate *iso, Platform *p, int argc, char **argv)
{
  print_welcome();

  HandleScope outer(iso);
  Local<String> name(AsString(iso, "(shell)").ToLocalChecked());

  while (true) {
    char buf[256];

    printf("igt> ");
    char *str = fgets(buf, sizeof(buf), stdin);
    if (!str)
	    break;

    HandleScope inner(iso);
    ExecuteString(iso,
                  AsString(iso, str).ToLocalChecked(),
                  name, true, true);

    while (platform::PumpMessageLoop(p, iso))
      ;
  }
  printf("\n");

  return 0;
}

int main(int argc, char* argv[])
{
  V8::InitializeICUDefaultLocation(argv[0]);
  V8::InitializeExternalStartupData(argv[0]);

  std::unique_ptr<Platform> p = platform::NewDefaultPlatform();
  V8::InitializePlatform(p.get());

  V8::Initialize();
  V8::SetFlagsFromCommandLine(&argc, argv, true);

  Isolate::CreateParams create_params;
  create_params.array_buffer_allocator =
      ArrayBuffer::Allocator::NewDefaultAllocator();
  Isolate *iso = Isolate::New(create_params);

  int err, opt;

  {
    Isolate::Scope isolate_scope(iso);
    HandleScope handle_scope(iso);
    Local<Context> ctx = ShellContext(iso);
    if (ctx.IsEmpty()) {
      fprintf(stderr, "Error creating ctx\n");
      return 1;
    }

    Context::Scope context_scope(ctx);
    while ((opt = getopt(argc, argv, "e:")) != -1) {
      switch (opt) {
      case 'e':
        if (do_eval(iso, p.get(), optarg)) {
          err = 1;
          goto err;
        }
        break;
      }
    }
    if (optind < argc) {
      static const struct target {
        const char *name;
        int (*fn)(Isolate*, Platform*, int argc, char **argv);
      } targets[] = {
        { "shell", shell },
        { "run", run },
        { }
      };
      for (typeof(*targets) *t = targets; t->name; t++) {
        if (!strcmp(argv[optind], t->name)) {
          err = t->fn(iso, p.get(), argc, argv);
          goto err;
        }
      }
      fprintf(stderr, "Unrecognised command '%s'\n", argv[optind]);
    } else {
      err = shell(iso, p.get(), 0, NULL);
    }
  }

err:
  iso->Dispose();
  V8::Dispose();
  V8::ShutdownPlatform();
  delete create_params.array_buffer_allocator;

  return err;
}