process.cc 23.9 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

using namespace std;
using namespace v8;

41 42 43 44 45 46 47 48 49 50 51
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
 public:
  virtual void* Allocate(size_t length) {
    void* data = AllocateUninitialized(length);
    return data == NULL ? data : memset(data, 0, length);
  }
  virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
  virtual void Free(void* data, size_t) { free(data); }
};


52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
// 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;
};

69

70 71 72 73 74 75 76 77 78 79
/**
 * 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,
80
                          map<string, string>* output) = 0;
81 82 83 84 85 86 87

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

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

88

89 90 91 92 93 94 95
/**
 * 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.
96 97
  JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
      : isolate_(isolate), script_(script) {}
98 99 100
  virtual ~JsHttpRequestProcessor();

  virtual bool Initialize(map<string, string>* opts,
101
                          map<string, string>* output);
102 103 104
  virtual bool Process(HttpRequest* req);

 private:
105 106
  // Execute the script associated with this processor and extract the
  // Process function.  Returns true if this succeeded, otherwise false.
107
  bool ExecuteScript(Local<String> script);
108 109 110 111 112 113 114

  // 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.
115 116
  static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
  static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
117 118

  // Callbacks that access the individual fields of request objects.
119 120 121 122 123 124 125 126
  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);
127 128

  // Callbacks that access maps
129 130
  static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
  static void MapSet(Local<Name> name, Local<Value> value,
131
                     const PropertyCallbackInfo<Value>& info);
132 133 134

  // Utility methods for wrapping C++ objects as JavaScript objects,
  // and going back again.
135 136 137 138
  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);
139

140
  Isolate* GetIsolate() { return isolate_; }
141

142
  Isolate* isolate_;
143 144 145 146 147
  Local<String> script_;
  Global<Context> context_;
  Global<Function> process_;
  static Global<ObjectTemplate> request_template_;
  static Global<ObjectTemplate> map_template_;
148 149
};

150

151 152 153 154 155
// -------------------------
// --- P r o c e s s o r ---
// -------------------------


156 157
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() < 1) return;
158
  HandleScope scope(args.GetIsolate());
159
  Local<Value> arg = args[0];
160
  String::Utf8Value value(arg);
161 162 163 164 165 166
  HttpRequestProcessor::Log(*value);
}


// Execute the script and fetch the Process method.
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
167
                                        map<string, string>* output) {
168
  // Create a handle scope to hold the temporary references.
169
  HandleScope handle_scope(GetIsolate());
170 171 172

  // Create a template for the global object where we set the
  // built-in global functions.
173 174 175
  Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
  global->Set(String::NewFromUtf8(GetIsolate(), "log", NewStringType::kNormal)
                  .ToLocalChecked(),
176
              FunctionTemplate::New(GetIsolate(), LogCallback));
177

178 179 180 181 182
  // 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.
183
  v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
184
  context_.Reset(GetIsolate(), context);
185 186 187

  // Enter the new context so all the following operations take place
  // within it.
188
  Context::Scope context_scope(context);
189 190 191 192 193 194 195 196 197 198 199

  // 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.
200 201 202 203
  Local<String> process_name =
      String::NewFromUtf8(GetIsolate(), "Process", NewStringType::kNormal)
          .ToLocalChecked();
  Local<Value> process_val;
204 205
  // If there is no Process function, or if it is not a function,
  // bail out
206 207 208 209
  if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
      !process_val->IsFunction()) {
    return false;
  }
210 211

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

214
  // Store the function in a Global handle, since we also want
215
  // that to remain after this call returns
216
  process_.Reset(GetIsolate(), process_fun);
217 218 219 220 221 222

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


223
bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
224
  HandleScope handle_scope(GetIsolate());
225 226 227

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

230 231
  Local<Context> context(GetIsolate()->GetCurrentContext());

232
  // Compile the script and check for errors.
233 234
  Local<Script> compiled_script;
  if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
235
    String::Utf8Value error(try_catch.Exception());
236 237 238 239 240 241
    Log(*error);
    // The script failed to compile; bail out.
    return false;
  }

  // Run the script!
242 243
  Local<Value> result;
  if (!compiled_script->Run(context).ToLocal(&result)) {
244
    // The TryCatch above is still in effect and will have caught the error.
245
    String::Utf8Value error(try_catch.Exception());
246 247 248 249 250 251 252 253 254
    Log(*error);
    // Running the script failed; bail out.
    return false;
  }
  return true;
}


bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
255
                                         map<string, string>* output) {
256
  HandleScope handle_scope(GetIsolate());
257 258

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

261 262 263
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

264
  // Set the options object as a property on the global object.
265 266 267 268 269 270 271 272 273 274 275 276 277 278
  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();
279 280 281 282 283 284 285

  return true;
}


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

288 289 290
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

291 292
  // Enter this processor's context so all the remaining operations
  // take place there
293
  Context::Scope context_scope(context);
294 295

  // Wrap the C++ request object in a JavaScript wrapper
296
  Local<Object> request_obj = WrapRequest(request);
297 298

  // Set up an exception handler before calling the Process function
299
  TryCatch try_catch(GetIsolate());
300 301 302 303

  // Invoke the process function, giving the global object as 'this'
  // and one argument, the request.
  const int argc = 1;
304
  Local<Value> argv[argc] = {request_obj};
305 306
  v8::Local<v8::Function> process =
      v8::Local<v8::Function>::New(GetIsolate(), process_);
307 308
  Local<Value> result;
  if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
309
    String::Utf8Value error(try_catch.Exception());
310 311 312 313 314 315 316 317 318 319 320 321
    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.
322 323
  context_.Reset();
  process_.Reset();
324 325 326
}


327 328
Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
329 330 331 332 333 334 335 336


// -----------------------------------
// --- 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.
337 338
Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
  // Local scope for temporary handles.
339
  EscapableHandleScope handle_scope(GetIsolate());
340 341 342

  // Fetch the template for creating JavaScript map wrappers.
  // It only has to be created once, which we do on demand.
343
  if (map_template_.IsEmpty()) {
344
    Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
345
    map_template_.Reset(GetIsolate(), raw_template);
346
  }
347
  Local<ObjectTemplate> templ =
348
      Local<ObjectTemplate>::New(GetIsolate(), map_template_);
349 350

  // Create an empty map wrapper.
351 352
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
353 354 355

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
356
  Local<External> map_ptr = External::New(GetIsolate(), obj);
357 358 359 360 361 362 363 364

  // 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.
365
  return handle_scope.Escape(result);
366 367 368 369 370
}


// Utility function that extracts the C++ map pointer from a wrapper
// object.
371 372
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
  Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
373 374 375 376 377 378 379 380
  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) {
381 382
  String::Utf8Value utf8_value(value);
  return string(*utf8_value);
383 384 385
}


386
void JsHttpRequestProcessor::MapGet(Local<Name> name,
387
                                    const PropertyCallbackInfo<Value>& info) {
388 389
  if (name->IsSymbol()) return;

390 391 392 393
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the JavaScript string to a std::string.
394
  string key = ObjectToString(Local<String>::Cast(name));
395 396 397 398 399

  // 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
400
  if (iter == obj->end()) return;
401 402 403

  // Otherwise fetch the value and wrap it in a JavaScript string
  const string& value = (*iter).second;
404 405 406 407
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), value.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(value.length())).ToLocalChecked());
408 409 410
}


411
void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
412
                                    const PropertyCallbackInfo<Value>& info) {
413 414
  if (name->IsSymbol()) return;

415 416 417 418
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the key and value to std::strings.
419
  string key = ObjectToString(Local<String>::Cast(name));
420 421 422 423 424 425
  string value = ObjectToString(value_obj);

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

  // Return the value; any non-empty handle will work.
426
  info.GetReturnValue().Set(value_obj);
427 428 429
}


430
Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
431
    Isolate* isolate) {
432
  EscapableHandleScope handle_scope(isolate);
433

434
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
435
  result->SetInternalFieldCount(1);
436
  result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
437 438

  // Again, return the result through the current handle scope.
439
  return handle_scope.Escape(result);
440 441 442 443 444 445 446 447 448 449 450
}


// -------------------------------------------
// --- 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.
 */
451 452
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  // Local scope for temporary handles.
453
  EscapableHandleScope handle_scope(GetIsolate());
454 455 456 457

  // 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()) {
458
    Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
459
    request_template_.Reset(GetIsolate(), raw_template);
460
  }
461
  Local<ObjectTemplate> templ =
462
      Local<ObjectTemplate>::New(GetIsolate(), request_template_);
463 464

  // Create an empty http request wrapper.
465 466
  Local<Object> result =
      templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
467 468 469

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
470
  Local<External> request_ptr = External::New(GetIsolate(), request);
471 472 473 474 475 476 477 478

  // 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.
479
  return handle_scope.Escape(result);
480 481 482 483 484 485 486
}


/**
 * Utility function that extracts the C++ http request object from a
 * wrapper object.
 */
487 488
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
  Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
489 490 491 492 493
  void* ptr = field->Value();
  return static_cast<HttpRequest*>(ptr);
}


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


510 511 512
void JsHttpRequestProcessor::GetReferrer(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
513 514
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Referrer();
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
void JsHttpRequestProcessor::GetHost(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
524 525
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Host();
526 527 528 529
  info.GetReturnValue().Set(
      String::NewFromUtf8(info.GetIsolate(), path.c_str(),
                          NewStringType::kNormal,
                          static_cast<int>(path.length())).ToLocalChecked());
530 531 532
}


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


545
Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
546
    Isolate* isolate) {
547
  EscapableHandleScope handle_scope(isolate);
548

549
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
550 551 552
  result->SetInternalFieldCount(1);

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

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


// --- Test ---


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


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


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


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

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

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


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


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


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