process.cc 23.6 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
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
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

28 29 30
#include <include/v8.h>

#include <include/libplatform/libplatform.h>
31

32
#include <stdlib.h>
33 34
#include <string.h>

35
#include <map>
36
#include <string>
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

using namespace std;
using namespace v8;

// These interfaces represent an existing request processing interface.
// The idea is to imagine a real application that uses these interfaces
// and then add scripting capabilities that allow you to interact with
// the objects through JavaScript.

/**
 * A simplified http request.
 */
class HttpRequest {
 public:
  virtual ~HttpRequest() { }
  virtual const string& Path() = 0;
  virtual const string& Referrer() = 0;
  virtual const string& Host() = 0;
  virtual const string& UserAgent() = 0;
};

58

59 60 61 62 63 64 65 66 67 68
/**
 * The abstract superclass of http request processors.
 */
class HttpRequestProcessor {
 public:
  virtual ~HttpRequestProcessor() { }

  // Initialize this processor.  The map contains options that control
  // how requests should be processed.
  virtual bool Initialize(map<string, string>* options,
69
                          map<string, string>* output) = 0;
70 71 72 73 74 75 76

  // Process a single request.
  virtual bool Process(HttpRequest* req) = 0;

  static void Log(const char* event);
};

77

78 79 80 81 82 83 84
/**
 * An http request processor that is scriptable using JavaScript.
 */
class JsHttpRequestProcessor : public HttpRequestProcessor {
 public:
  // Creates a new processor that processes requests by invoking the
  // Process function of the JavaScript script given as an argument.
85 86
  JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
      : isolate_(isolate), script_(script) {}
87 88 89
  virtual ~JsHttpRequestProcessor();

  virtual bool Initialize(map<string, string>* opts,
90
                          map<string, string>* output);
91 92 93
  virtual bool Process(HttpRequest* req);

 private:
94 95
  // Execute the script associated with this processor and extract the
  // Process function.  Returns true if this succeeded, otherwise false.
96
  bool ExecuteScript(Local<String> script);
97 98 99 100 101 102 103

  // Wrap the options and output map in a JavaScript objects and
  // install it in the global namespace as 'options' and 'output'.
  bool InstallMaps(map<string, string>* opts, map<string, string>* output);

  // Constructs the template that describes the JavaScript wrapper
  // type for requests.
104 105
  static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
  static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
106 107

  // Callbacks that access the individual fields of request objects.
108 109 110 111 112 113 114 115
  static void GetPath(Local<String> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetReferrer(Local<String> name,
                          const PropertyCallbackInfo<Value>& info);
  static void GetHost(Local<String> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetUserAgent(Local<String> name,
                           const PropertyCallbackInfo<Value>& info);
116 117

  // Callbacks that access maps
118 119
  static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
  static void MapSet(Local<Name> name, Local<Value> value,
120
                     const PropertyCallbackInfo<Value>& info);
121 122 123

  // Utility methods for wrapping C++ objects as JavaScript objects,
  // and going back again.
124 125 126 127
  Local<Object> WrapMap(map<string, string>* obj);
  static map<string, string>* UnwrapMap(Local<Object> obj);
  Local<Object> WrapRequest(HttpRequest* obj);
  static HttpRequest* UnwrapRequest(Local<Object> obj);
128

129
  Isolate* GetIsolate() { return isolate_; }
130

131
  Isolate* isolate_;
132 133 134 135 136
  Local<String> script_;
  Global<Context> context_;
  Global<Function> process_;
  static Global<ObjectTemplate> request_template_;
  static Global<ObjectTemplate> map_template_;
137 138
};

139

140 141 142 143 144
// -------------------------
// --- P r o c e s s o r ---
// -------------------------


145 146
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() < 1) return;
147
  HandleScope scope(args.GetIsolate());
148
  Local<Value> arg = args[0];
149
  String::Utf8Value value(arg);
150 151 152 153 154 155
  HttpRequestProcessor::Log(*value);
}


// Execute the script and fetch the Process method.
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
156
                                        map<string, string>* output) {
157
  // Create a handle scope to hold the temporary references.
158
  HandleScope handle_scope(GetIsolate());
159 160 161

  // Create a template for the global object where we set the
  // built-in global functions.
162 163 164
  Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
  global->Set(String::NewFromUtf8(GetIsolate(), "log", NewStringType::kNormal)
                  .ToLocalChecked(),
165
              FunctionTemplate::New(GetIsolate(), LogCallback));
166

167 168 169 170 171
  // Each processor gets its own context so different processors don't
  // affect each other. Context::New returns a persistent handle which
  // is what we need for the reference to remain after we return from
  // this method. That persistent handle has to be disposed in the
  // destructor.
172
  v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
173
  context_.Reset(GetIsolate(), context);
174 175 176

  // Enter the new context so all the following operations take place
  // within it.
177
  Context::Scope context_scope(context);
178 179 180 181 182 183 184 185 186 187 188

  // Make the options mapping available within the context
  if (!InstallMaps(opts, output))
    return false;

  // Compile and run the script
  if (!ExecuteScript(script_))
    return false;

  // The script compiled and ran correctly.  Now we fetch out the
  // Process function from the global object.
189 190 191 192
  Local<String> process_name =
      String::NewFromUtf8(GetIsolate(), "Process", NewStringType::kNormal)
          .ToLocalChecked();
  Local<Value> process_val;
193 194
  // If there is no Process function, or if it is not a function,
  // bail out
195 196 197 198
  if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
      !process_val->IsFunction()) {
    return false;
  }
199 200

  // It is a function; cast it to a Function
201
  Local<Function> process_fun = Local<Function>::Cast(process_val);
202

203
  // Store the function in a Global handle, since we also want
204
  // that to remain after this call returns
205
  process_.Reset(GetIsolate(), process_fun);
206 207 208 209 210 211

  // All done; all went well
  return true;
}


212
bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
213
  HandleScope handle_scope(GetIsolate());
214 215 216

  // We're just about to compile the script; set up an error handler to
  // catch any exceptions the script might throw.
217
  TryCatch try_catch(GetIsolate());
218

219 220
  Local<Context> context(GetIsolate()->GetCurrentContext());

221
  // Compile the script and check for errors.
222 223
  Local<Script> compiled_script;
  if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
224
    String::Utf8Value error(try_catch.Exception());
225 226 227 228 229 230
    Log(*error);
    // The script failed to compile; bail out.
    return false;
  }

  // Run the script!
231 232
  Local<Value> result;
  if (!compiled_script->Run(context).ToLocal(&result)) {
233
    // The TryCatch above is still in effect and will have caught the error.
234
    String::Utf8Value error(try_catch.Exception());
235 236 237 238 239 240 241 242 243
    Log(*error);
    // Running the script failed; bail out.
    return false;
  }
  return true;
}


bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
244
                                         map<string, string>* output) {
245
  HandleScope handle_scope(GetIsolate());
246 247

  // Wrap the map object in a JavaScript wrapper
248
  Local<Object> opts_obj = WrapMap(opts);
249

250 251 252
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

253
  // Set the options object as a property on the global object.
254 255 256 257 258 259 260 261 262 263 264 265 266 267
  context->Global()
      ->Set(context,
            String::NewFromUtf8(GetIsolate(), "options", NewStringType::kNormal)
                .ToLocalChecked(),
            opts_obj)
      .FromJust();

  Local<Object> output_obj = WrapMap(output);
  context->Global()
      ->Set(context,
            String::NewFromUtf8(GetIsolate(), "output", NewStringType::kNormal)
                .ToLocalChecked(),
            output_obj)
      .FromJust();
268 269 270 271 272 273 274

  return true;
}


bool JsHttpRequestProcessor::Process(HttpRequest* request) {
  // Create a handle scope to keep the temporary object references.
275
  HandleScope handle_scope(GetIsolate());
276

277 278 279
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

280 281
  // Enter this processor's context so all the remaining operations
  // take place there
282
  Context::Scope context_scope(context);
283 284

  // Wrap the C++ request object in a JavaScript wrapper
285
  Local<Object> request_obj = WrapRequest(request);
286 287

  // Set up an exception handler before calling the Process function
288
  TryCatch try_catch(GetIsolate());
289 290 291 292

  // Invoke the process function, giving the global object as 'this'
  // and one argument, the request.
  const int argc = 1;
293
  Local<Value> argv[argc] = {request_obj};
294 295
  v8::Local<v8::Function> process =
      v8::Local<v8::Function>::New(GetIsolate(), process_);
296 297
  Local<Value> result;
  if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
298
    String::Utf8Value error(try_catch.Exception());
299 300 301 302 303 304 305 306 307 308 309 310
    Log(*error);
    return false;
  } else {
    return true;
  }
}


JsHttpRequestProcessor::~JsHttpRequestProcessor() {
  // Dispose the persistent handles.  When noone else has any
  // references to the objects stored in the handles they will be
  // automatically reclaimed.
311 312
  context_.Reset();
  process_.Reset();
313 314 315
}


316 317
Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
318 319 320 321 322 323 324 325


// -----------------------------------
// --- A c c e s s i n g   M a p s ---
// -----------------------------------

// Utility function that wraps a C++ http request object in a
// JavaScript object.
326 327
Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
  // Local scope for temporary handles.
328
  EscapableHandleScope handle_scope(GetIsolate());
329 330 331

  // Fetch the template for creating JavaScript map wrappers.
  // It only has to be created once, which we do on demand.
332
  if (map_template_.IsEmpty()) {
333
    Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
334
    map_template_.Reset(GetIsolate(), raw_template);
335
  }
336
  Local<ObjectTemplate> templ =
337
      Local<ObjectTemplate>::New(GetIsolate(), map_template_);
338 339

  // Create an empty map wrapper.
340 341
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
342 343 344

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
345
  Local<External> map_ptr = External::New(GetIsolate(), obj);
346 347 348 349 350 351 352 353

  // Store the map pointer in the JavaScript wrapper.
  result->SetInternalField(0, map_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
354
  return handle_scope.Escape(result);
355 356 357 358 359
}


// Utility function that extracts the C++ map pointer from a wrapper
// object.
360 361
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
  Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
362 363 364 365 366 367 368 369
  void* ptr = field->Value();
  return static_cast<map<string, string>*>(ptr);
}


// Convert a JavaScript string to a std::string.  To not bother too
// much with string encodings we just use ascii.
string ObjectToString(Local<Value> value) {
370 371
  String::Utf8Value utf8_value(value);
  return string(*utf8_value);
372 373 374
}


375
void JsHttpRequestProcessor::MapGet(Local<Name> name,
376
                                    const PropertyCallbackInfo<Value>& info) {
377 378
  if (name->IsSymbol()) return;

379 380 381 382
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the JavaScript string to a std::string.
383
  string key = ObjectToString(Local<String>::Cast(name));
384 385 386 387 388

  // Look up the value if it exists using the standard STL ideom.
  map<string, string>::iterator iter = obj->find(key);

  // If the key is not present return an empty handle as signal
389
  if (iter == obj->end()) return;
390 391 392

  // Otherwise fetch the value and wrap it in a JavaScript string
  const string& value = (*iter).second;
393 394 395 396
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), value.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(value.length())).ToLocalChecked());
397 398 399
}


400
void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
401
                                    const PropertyCallbackInfo<Value>& info) {
402 403
  if (name->IsSymbol()) return;

404 405 406 407
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the key and value to std::strings.
408
  string key = ObjectToString(Local<String>::Cast(name));
409 410 411 412 413 414
  string value = ObjectToString(value_obj);

  // Update the map.
  (*obj)[key] = value;

  // Return the value; any non-empty handle will work.
415
  info.GetReturnValue().Set(value_obj);
416 417 418
}


419
Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
420
    Isolate* isolate) {
421
  EscapableHandleScope handle_scope(isolate);
422

423
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
424
  result->SetInternalFieldCount(1);
425
  result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
426 427

  // Again, return the result through the current handle scope.
428
  return handle_scope.Escape(result);
429 430 431 432 433 434 435 436 437 438 439
}


// -------------------------------------------
// --- A c c e s s i n g   R e q u e s t s ---
// -------------------------------------------

/**
 * Utility function that wraps a C++ http request object in a
 * JavaScript object.
 */
440 441
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  // Local scope for temporary handles.
442
  EscapableHandleScope handle_scope(GetIsolate());
443 444 445 446

  // Fetch the template for creating JavaScript http request wrappers.
  // It only has to be created once, which we do on demand.
  if (request_template_.IsEmpty()) {
447
    Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
448
    request_template_.Reset(GetIsolate(), raw_template);
449
  }
450
  Local<ObjectTemplate> templ =
451
      Local<ObjectTemplate>::New(GetIsolate(), request_template_);
452 453

  // Create an empty http request wrapper.
454 455
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
456 457 458

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
459
  Local<External> request_ptr = External::New(GetIsolate(), request);
460 461 462 463 464 465 466 467

  // Store the request pointer in the JavaScript wrapper.
  result->SetInternalField(0, request_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
468
  return handle_scope.Escape(result);
469 470 471 472 473 474 475
}


/**
 * Utility function that extracts the C++ http request object from a
 * wrapper object.
 */
476 477
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
  Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
478 479 480 481 482
  void* ptr = field->Value();
  return static_cast<HttpRequest*>(ptr);
}


483 484
void JsHttpRequestProcessor::GetPath(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
485 486 487 488 489 490 491
  // Extract the C++ request object from the JavaScript wrapper.
  HttpRequest* request = UnwrapRequest(info.Holder());

  // Fetch the path.
  const string& path = request->Path();

  // Wrap the result in a JavaScript string and return it.
492 493 494 495
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
496 497 498
}


499 500 501
void JsHttpRequestProcessor::GetReferrer(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
502 503
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Referrer();
504 505 506 507
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
508 509 510
}


511 512
void JsHttpRequestProcessor::GetHost(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
513 514
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Host();
515 516 517 518
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
519 520 521
}


522 523 524
void JsHttpRequestProcessor::GetUserAgent(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
525 526
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->UserAgent();
527 528 529 530
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
531 532 533
}


534
Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
535
    Isolate* isolate) {
536
  EscapableHandleScope handle_scope(isolate);
537

538
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
539 540 541
  result->SetInternalFieldCount(1);

  // Add accessors for each of the fields of the request.
542
  result->SetAccessor(
543 544
      String::NewFromUtf8(isolate, "path", NewStringType::kInternalized)
          .ToLocalChecked(),
545 546
      GetPath);
  result->SetAccessor(
547 548
      String::NewFromUtf8(isolate, "referrer", NewStringType::kInternalized)
          .ToLocalChecked(),
549 550
      GetReferrer);
  result->SetAccessor(
551 552
      String::NewFromUtf8(isolate, "host", NewStringType::kInternalized)
          .ToLocalChecked(),
553 554
      GetHost);
  result->SetAccessor(
555 556
      String::NewFromUtf8(isolate, "userAgent", NewStringType::kInternalized)
          .ToLocalChecked(),
557
      GetUserAgent);
558 559

  // Again, return the result through the current handle scope.
560
  return handle_scope.Escape(result);
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
}


// --- Test ---


void HttpRequestProcessor::Log(const char* event) {
  printf("Logged: %s\n", event);
}


/**
 * A simplified http request.
 */
class StringHttpRequest : public HttpRequest {
 public:
577 578 579 580
  StringHttpRequest(const string& path,
                    const string& referrer,
                    const string& host,
                    const string& user_agent);
581 582 583 584 585 586 587 588 589 590 591 592 593
  virtual const string& Path() { return path_; }
  virtual const string& Referrer() { return referrer_; }
  virtual const string& Host() { return host_; }
  virtual const string& UserAgent() { return user_agent_; }
 private:
  string path_;
  string referrer_;
  string host_;
  string user_agent_;
};


StringHttpRequest::StringHttpRequest(const string& path,
594 595 596
                                     const string& referrer,
                                     const string& host,
                                     const string& user_agent)
597 598 599 600 601 602
    : path_(path),
      referrer_(referrer),
      host_(host),
      user_agent_(user_agent) { }


603 604
void ParseOptions(int argc,
                  char* argv[],
605
                  map<string, string>* options,
606
                  string* file) {
607 608
  for (int i = 1; i < argc; i++) {
    string arg = argv[i];
609
    size_t index = arg.find('=', 0);
610 611 612 613 614
    if (index == string::npos) {
      *file = arg;
    } else {
      string key = arg.substr(0, index);
      string value = arg.substr(index+1);
615
      (*options)[key] = value;
616 617 618 619 620 621
    }
  }
}


// Reads a file into a v8 string.
622
MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
623
  FILE* file = fopen(name.c_str(), "rb");
624
  if (file == NULL) return MaybeLocal<String>();
625 626

  fseek(file, 0, SEEK_END);
627
  size_t size = ftell(file);
628 629 630 631
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
632 633 634 635
  for (size_t i = 0; i < size;) {
    i += fread(&chars[i], 1, size - i, file);
    if (ferror(file)) {
      fclose(file);
636
      return MaybeLocal<String>();
637
    }
638 639
  }
  fclose(file);
640 641
  MaybeLocal<String> result = String::NewFromUtf8(
      isolate, chars, NewStringType::kNormal, static_cast<int>(size));
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
  delete[] chars;
  return result;
}


const int kSampleSize = 6;
StringHttpRequest kSampleRequests[kSampleSize] = {
  StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"),
  StringHttpRequest("/", "localhost", "google.net", "firefox"),
  StringHttpRequest("/", "localhost", "google.org", "safari"),
  StringHttpRequest("/", "localhost", "yahoo.com", "ie"),
  StringHttpRequest("/", "localhost", "yahoo.com", "safari"),
  StringHttpRequest("/", "localhost", "yahoo.com", "firefox")
};


658 659
bool ProcessEntries(v8::Platform* platform, HttpRequestProcessor* processor,
                    int count, StringHttpRequest* reqs) {
660
  for (int i = 0; i < count; i++) {
661 662 663 664
    bool result = processor->Process(&reqs[i]);
    while (v8::platform::PumpMessageLoop(platform, Isolate::GetCurrent()))
      continue;
    if (!result) return false;
665 666 667 668 669
  }
  return true;
}


670 671
void PrintMap(map<string, string>* m) {
  for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
672 673 674 675 676 677 678
    pair<string, string> entry = *i;
    printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
  }
}


int main(int argc, char* argv[]) {
679
  v8::V8::InitializeICUDefaultLocation(argv[0]);
vogelheim's avatar
vogelheim committed
680
  v8::V8::InitializeExternalStartupData(argv[0]);
681
  v8::Platform* platform = v8::platform::CreateDefaultPlatform();
682
  v8::V8::InitializePlatform(platform);
683
  v8::V8::Initialize();
684 685
  map<string, string> options;
  string file;
686
  ParseOptions(argc, argv, &options, &file);
687 688 689 690
  if (file.empty()) {
    fprintf(stderr, "No script was specified.\n");
    return 1;
  }
691
  Isolate::CreateParams create_params;
692 693
  create_params.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
694
  Isolate* isolate = Isolate::New(create_params);
695
  Isolate::Scope isolate_scope(isolate);
696
  HandleScope scope(isolate);
697 698
  Local<String> source;
  if (!ReadFile(isolate, file).ToLocal(&source)) {
699 700 701
    fprintf(stderr, "Error reading '%s'.\n", file.c_str());
    return 1;
  }
702
  JsHttpRequestProcessor processor(isolate, source);
703 704 705 706 707
  map<string, string> output;
  if (!processor.Initialize(&options, &output)) {
    fprintf(stderr, "Error initializing processor.\n");
    return 1;
  }
708
  if (!ProcessEntries(platform, &processor, kSampleSize, kSampleRequests))
709
    return 1;
710
  PrintMap(&output);
711
}