process.cc 24.1 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 58 59 60 61
using std::map;
using std::pair;
using std::string;

using v8::Context;
using v8::EscapableHandleScope;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Global;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Name;
using v8::NamedPropertyHandlerConfiguration;
using v8::NewStringType;
using v8::Object;
using v8::ObjectTemplate;
using v8::PropertyCallbackInfo;
using v8::Script;
using v8::String;
using v8::TryCatch;
using v8::Value;
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

// 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;
};

80

81 82 83 84 85 86 87 88 89 90
/**
 * 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,
91
                          map<string, string>* output) = 0;
92 93 94 95 96 97 98

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

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

99

100 101 102 103 104 105 106
/**
 * 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.
107 108
  JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
      : isolate_(isolate), script_(script) {}
109 110 111
  virtual ~JsHttpRequestProcessor();

  virtual bool Initialize(map<string, string>* opts,
112
                          map<string, string>* output);
113 114 115
  virtual bool Process(HttpRequest* req);

 private:
116 117
  // Execute the script associated with this processor and extract the
  // Process function.  Returns true if this succeeded, otherwise false.
118
  bool ExecuteScript(Local<String> script);
119 120 121 122 123 124 125

  // 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.
126 127
  static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
  static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
128 129

  // Callbacks that access the individual fields of request objects.
130 131 132 133 134 135 136 137
  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);
138 139

  // Callbacks that access maps
140 141
  static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
  static void MapSet(Local<Name> name, Local<Value> value,
142
                     const PropertyCallbackInfo<Value>& info);
143 144 145

  // Utility methods for wrapping C++ objects as JavaScript objects,
  // and going back again.
146 147 148 149
  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);
150

151
  Isolate* GetIsolate() { return isolate_; }
152

153
  Isolate* isolate_;
154 155 156 157 158
  Local<String> script_;
  Global<Context> context_;
  Global<Function> process_;
  static Global<ObjectTemplate> request_template_;
  static Global<ObjectTemplate> map_template_;
159 160
};

161

162 163 164 165 166
// -------------------------
// --- P r o c e s s o r ---
// -------------------------


167 168
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() < 1) return;
169 170
  Isolate* isolate = args.GetIsolate();
  HandleScope scope(isolate);
171
  Local<Value> arg = args[0];
172
  String::Utf8Value value(isolate, arg);
173 174 175 176 177 178
  HttpRequestProcessor::Log(*value);
}


// Execute the script and fetch the Process method.
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
179
                                        map<string, string>* output) {
180
  // Create a handle scope to hold the temporary references.
181
  HandleScope handle_scope(GetIsolate());
182 183 184

  // Create a template for the global object where we set the
  // built-in global functions.
185
  Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
186
  global->Set(String::NewFromUtf8Literal(GetIsolate(), "log"),
187
              FunctionTemplate::New(GetIsolate(), LogCallback));
188

189 190 191 192 193
  // 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.
194
  v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
195
  context_.Reset(GetIsolate(), context);
196 197 198

  // Enter the new context so all the following operations take place
  // within it.
199
  Context::Scope context_scope(context);
200 201 202 203 204 205 206 207 208 209 210

  // 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.
211
  Local<String> process_name =
212
      String::NewFromUtf8Literal(GetIsolate(), "Process");
213
  Local<Value> process_val;
214 215
  // If there is no Process function, or if it is not a function,
  // bail out
216 217 218 219
  if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
      !process_val->IsFunction()) {
    return false;
  }
220 221

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

224
  // Store the function in a Global handle, since we also want
225
  // that to remain after this call returns
226
  process_.Reset(GetIsolate(), process_fun);
227 228 229 230 231 232

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


233
bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
234
  HandleScope handle_scope(GetIsolate());
235 236 237

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

240 241
  Local<Context> context(GetIsolate()->GetCurrentContext());

242
  // Compile the script and check for errors.
243 244
  Local<Script> compiled_script;
  if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
245
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
246 247 248 249 250 251
    Log(*error);
    // The script failed to compile; bail out.
    return false;
  }

  // Run the script!
252 253
  Local<Value> result;
  if (!compiled_script->Run(context).ToLocal(&result)) {
254
    // The TryCatch above is still in effect and will have caught the error.
255
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
256 257 258 259
    Log(*error);
    // Running the script failed; bail out.
    return false;
  }
260

261 262 263 264 265
  return true;
}


bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
266
                                         map<string, string>* output) {
267
  HandleScope handle_scope(GetIsolate());
268 269

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

272 273 274
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

275
  // Set the options object as a property on the global object.
276
  context->Global()
277
      ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "options"),
278 279 280 281 282
            opts_obj)
      .FromJust();

  Local<Object> output_obj = WrapMap(output);
  context->Global()
283
      ->Set(context, String::NewFromUtf8Literal(GetIsolate(), "output"),
284 285
            output_obj)
      .FromJust();
286 287 288 289 290 291 292

  return true;
}


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

295 296 297
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

298 299
  // Enter this processor's context so all the remaining operations
  // take place there
300
  Context::Scope context_scope(context);
301 302

  // Wrap the C++ request object in a JavaScript wrapper
303
  Local<Object> request_obj = WrapRequest(request);
304 305

  // Set up an exception handler before calling the Process function
306
  TryCatch try_catch(GetIsolate());
307 308 309 310

  // Invoke the process function, giving the global object as 'this'
  // and one argument, the request.
  const int argc = 1;
311
  Local<Value> argv[argc] = {request_obj};
312 313
  v8::Local<v8::Function> process =
      v8::Local<v8::Function>::New(GetIsolate(), process_);
314 315
  Local<Value> result;
  if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
316
    String::Utf8Value error(GetIsolate(), try_catch.Exception());
317 318 319
    Log(*error);
    return false;
  }
320
  return true;
321 322 323 324
}


JsHttpRequestProcessor::~JsHttpRequestProcessor() {
325
  // Dispose the persistent handles.  When no one else has any
326 327
  // references to the objects stored in the handles they will be
  // automatically reclaimed.
328 329
  context_.Reset();
  process_.Reset();
330 331 332
}


333 334
Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
335 336 337 338 339 340 341 342


// -----------------------------------
// --- 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.
343 344
Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
  // Local scope for temporary handles.
345
  EscapableHandleScope handle_scope(GetIsolate());
346 347 348

  // Fetch the template for creating JavaScript map wrappers.
  // It only has to be created once, which we do on demand.
349
  if (map_template_.IsEmpty()) {
350
    Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
351
    map_template_.Reset(GetIsolate(), raw_template);
352
  }
353
  Local<ObjectTemplate> templ =
354
      Local<ObjectTemplate>::New(GetIsolate(), map_template_);
355 356

  // Create an empty map wrapper.
357 358
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
359 360 361

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
362
  Local<External> map_ptr = External::New(GetIsolate(), obj);
363 364 365 366 367 368 369 370

  // 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.
371
  return handle_scope.Escape(result);
372 373 374 375 376
}


// Utility function that extracts the C++ map pointer from a wrapper
// object.
377 378
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
  Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
379 380 381 382 383 384 385
  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.
386 387
string ObjectToString(v8::Isolate* isolate, Local<Value> value) {
  String::Utf8Value utf8_value(isolate, value);
388
  return string(*utf8_value);
389 390 391
}


392
void JsHttpRequestProcessor::MapGet(Local<Name> name,
393
                                    const PropertyCallbackInfo<Value>& info) {
394 395
  if (name->IsSymbol()) return;

396 397 398 399
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the JavaScript string to a std::string.
400
  string key = ObjectToString(info.GetIsolate(), Local<String>::Cast(name));
401 402 403 404 405

  // 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
406
  if (iter == obj->end()) return;
407 408 409

  // Otherwise fetch the value and wrap it in a JavaScript string
  const string& value = (*iter).second;
410 411 412 413
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), value.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(value.length())).ToLocalChecked());
414 415 416
}


417
void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
418
                                    const PropertyCallbackInfo<Value>& info) {
419 420
  if (name->IsSymbol()) return;

421 422 423 424
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the key and value to std::strings.
425 426
  string key = ObjectToString(info.GetIsolate(), Local<String>::Cast(name));
  string value = ObjectToString(info.GetIsolate(), value_obj);
427 428 429 430 431

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

  // Return the value; any non-empty handle will work.
432
  info.GetReturnValue().Set(value_obj);
433 434 435
}


436
Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
437
    Isolate* isolate) {
438
  EscapableHandleScope handle_scope(isolate);
439

440
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
441
  result->SetInternalFieldCount(1);
442
  result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
443 444

  // Again, return the result through the current handle scope.
445
  return handle_scope.Escape(result);
446 447 448 449 450 451 452 453 454 455 456
}


// -------------------------------------------
// --- 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.
 */
457 458
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  // Local scope for temporary handles.
459
  EscapableHandleScope handle_scope(GetIsolate());
460 461 462 463

  // 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()) {
464
    Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
465
    request_template_.Reset(GetIsolate(), raw_template);
466
  }
467
  Local<ObjectTemplate> templ =
468
      Local<ObjectTemplate>::New(GetIsolate(), request_template_);
469 470

  // Create an empty http request wrapper.
471 472
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
473 474 475

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
476
  Local<External> request_ptr = External::New(GetIsolate(), request);
477 478 479 480 481 482 483 484

  // 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.
485
  return handle_scope.Escape(result);
486 487 488 489 490 491 492
}


/**
 * Utility function that extracts the C++ http request object from a
 * wrapper object.
 */
493 494
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
  Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
495 496 497 498 499
  void* ptr = field->Value();
  return static_cast<HttpRequest*>(ptr);
}


500 501
void JsHttpRequestProcessor::GetPath(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
502 503 504 505 506 507 508
  // 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.
509 510 511 512
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
513 514 515
}


516 517 518
void JsHttpRequestProcessor::GetReferrer(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
519 520
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Referrer();
521 522 523 524
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
525 526 527
}


528 529
void JsHttpRequestProcessor::GetHost(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
530 531
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Host();
532 533 534 535
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
536 537 538
}


539 540 541
void JsHttpRequestProcessor::GetUserAgent(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
542 543
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->UserAgent();
544 545 546 547
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
548 549 550
}


551
Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
552
    Isolate* isolate) {
553
  EscapableHandleScope handle_scope(isolate);
554

555
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
556 557 558
  result->SetInternalFieldCount(1);

  // Add accessors for each of the fields of the request.
559
  result->SetAccessor(
560
      String::NewFromUtf8Literal(isolate, "path", NewStringType::kInternalized),
561
      GetPath);
562 563 564
  result->SetAccessor(String::NewFromUtf8Literal(isolate, "referrer",
                                                 NewStringType::kInternalized),
                      GetReferrer);
565
  result->SetAccessor(
566
      String::NewFromUtf8Literal(isolate, "host", NewStringType::kInternalized),
567
      GetHost);
568 569 570
  result->SetAccessor(String::NewFromUtf8Literal(isolate, "userAgent",
                                                 NewStringType::kInternalized),
                      GetUserAgent);
571 572

  // Again, return the result through the current handle scope.
573
  return handle_scope.Escape(result);
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
}


// --- Test ---


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


/**
 * A simplified http request.
 */
class StringHttpRequest : public HttpRequest {
 public:
590 591 592 593
  StringHttpRequest(const string& path,
                    const string& referrer,
                    const string& host,
                    const string& user_agent);
594 595 596 597 598 599 600 601 602 603 604 605 606
  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,
607 608 609
                                     const string& referrer,
                                     const string& host,
                                     const string& user_agent)
610 611 612 613 614 615
    : path_(path),
      referrer_(referrer),
      host_(host),
      user_agent_(user_agent) { }


616 617
void ParseOptions(int argc,
                  char* argv[],
618
                  map<string, string>* options,
619
                  string* file) {
620 621
  for (int i = 1; i < argc; i++) {
    string arg = argv[i];
622
    size_t index = arg.find('=', 0);
623 624 625 626 627
    if (index == string::npos) {
      *file = arg;
    } else {
      string key = arg.substr(0, index);
      string value = arg.substr(index+1);
628
      (*options)[key] = value;
629 630 631 632 633 634
    }
  }
}


// Reads a file into a v8 string.
635
MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
636
  FILE* file = fopen(name.c_str(), "rb");
637
  if (file == NULL) return MaybeLocal<String>();
638 639

  fseek(file, 0, SEEK_END);
640
  size_t size = ftell(file);
641 642
  rewind(file);

643 644
  std::unique_ptr<char> chars(new char[size + 1]);
  chars.get()[size] = '\0';
645
  for (size_t i = 0; i < size;) {
646
    i += fread(&chars.get()[i], 1, size - i, file);
647 648
    if (ferror(file)) {
      fclose(file);
649
      return MaybeLocal<String>();
650
    }
651 652
  }
  fclose(file);
653
  MaybeLocal<String> result = String::NewFromUtf8(
654
      isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size));
655 656 657 658 659 660 661 662 663 664 665 666 667 668
  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")
};

669 670 671
bool ProcessEntries(v8::Isolate* isolate, v8::Platform* platform,
                    HttpRequestProcessor* processor, int count,
                    StringHttpRequest* reqs) {
672
  for (int i = 0; i < count; i++) {
673
    bool result = processor->Process(&reqs[i]);
674
    while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
675
    if (!result) return false;
676 677 678 679
  }
  return true;
}

680 681
void PrintMap(map<string, string>* m) {
  for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
682 683 684 685 686 687 688
    pair<string, string> entry = *i;
    printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
  }
}


int main(int argc, char* argv[]) {
689
  v8::V8::InitializeICUDefaultLocation(argv[0]);
vogelheim's avatar
vogelheim committed
690
  v8::V8::InitializeExternalStartupData(argv[0]);
691 692
  std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(platform.get());
693
  v8::V8::Initialize();
694 695
  map<string, string> options;
  string file;
696
  ParseOptions(argc, argv, &options, &file);
697 698 699 700
  if (file.empty()) {
    fprintf(stderr, "No script was specified.\n");
    return 1;
  }
701
  Isolate::CreateParams create_params;
702 703
  create_params.array_buffer_allocator =
      v8::ArrayBuffer::Allocator::NewDefaultAllocator();
704
  Isolate* isolate = Isolate::New(create_params);
705
  Isolate::Scope isolate_scope(isolate);
706
  HandleScope scope(isolate);
707 708
  Local<String> source;
  if (!ReadFile(isolate, file).ToLocal(&source)) {
709 710 711
    fprintf(stderr, "Error reading '%s'.\n", file.c_str());
    return 1;
  }
712
  JsHttpRequestProcessor processor(isolate, source);
713 714 715 716 717
  map<string, string> output;
  if (!processor.Initialize(&options, &output)) {
    fprintf(stderr, "Error initializing processor.\n");
    return 1;
  }
718 719
  if (!ProcessEntries(isolate, platform.get(), &processor, kSampleSize,
                      kSampleRequests)) {
720
    return 1;
721
  }
722
  PrintMap(&output);
723
}