Upload Kmake

This commit is contained in:
Gorochu
2026-05-26 23:36:42 -07:00
parent ba051b2f74
commit 555ec72358
41615 changed files with 13344630 additions and 1 deletions

2
deps/v8/samples/OWNERS vendored Normal file
View File

@ -0,0 +1,2 @@
ahaas@chromium.org
cbruni@chromium.org

42
deps/v8/samples/count-hosts.js vendored Normal file
View File

@ -0,0 +1,42 @@
// Copyright 2008 the V8 project authors. All rights reserved.
// 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.
function Initialize() { }
function Process(request) {
if (options.verbose) {
log("Processing " + request.host + request.path +
" from " + request.referrer + "@" + request.userAgent);
}
if (!output[request.host]) {
output[request.host] = 1;
} else {
output[request.host]++
}
}
Initialize();

3
deps/v8/samples/cppgc/OWNERS vendored Normal file
View File

@ -0,0 +1,3 @@
bikineev@chromium.org
mlippautz@chromium.org
omerkatz@chromium.org

77
deps/v8/samples/cppgc/hello-world.cc vendored Normal file
View File

@ -0,0 +1,77 @@
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <iostream>
#include <memory>
#include <string>
#include "include/cppgc/allocation.h"
#include "include/cppgc/default-platform.h"
#include "include/cppgc/garbage-collected.h"
#include "include/cppgc/heap.h"
#include "include/cppgc/member.h"
#include "include/cppgc/visitor.h"
#if !CPPGC_IS_STANDALONE
#include "include/v8-initialization.h"
#endif // !CPPGC_IS_STANDALONE
/**
* This sample program shows how to set up a stand-alone cppgc heap.
*/
/**
* Simple string rope to illustrate allocation and garbage collection below.
* The rope keeps the next parts alive via regular managed reference.
*/
class Rope final : public cppgc::GarbageCollected<Rope> {
public:
explicit Rope(std::string part, Rope* next = nullptr)
: part_(std::move(part)), next_(next) {}
void Trace(cppgc::Visitor* visitor) const { visitor->Trace(next_); }
private:
const std::string part_;
const cppgc::Member<Rope> next_;
friend std::ostream& operator<<(std::ostream& os, const Rope& rope) {
os << rope.part_;
if (rope.next_) {
os << *rope.next_;
}
return os;
}
};
int main(int argc, char* argv[]) {
// Create a default platform that is used by cppgc::Heap for execution and
// backend allocation.
auto cppgc_platform = std::make_shared<cppgc::DefaultPlatform>();
#if !CPPGC_IS_STANDALONE
// When initializing a stand-alone cppgc heap in a regular V8 build, the
// internal V8 platform will be reused. Reusing the V8 platform requires
// initializing it properly.
v8::V8::InitializePlatform(cppgc_platform->GetV8Platform());
#endif // !CPPGC_IS_STANDALONE
// Initialize the process. This must happen before any cppgc::Heap::Create()
// calls.
cppgc::InitializeProcess(cppgc_platform->GetPageAllocator());
{
// Create a managed heap.
std::unique_ptr<cppgc::Heap> heap = cppgc::Heap::Create(cppgc_platform);
// Allocate a string rope on the managed heap.
Rope* greeting = cppgc::MakeGarbageCollected<Rope>(
heap->GetAllocationHandle(), "Hello ",
cppgc::MakeGarbageCollected<Rope>(heap->GetAllocationHandle(),
"World!"));
// Manually trigger garbage collection. The object greeting is held alive
// through conservative stack scanning.
heap->ForceGarbageCollectionSlow("CppGC example", "Testing");
std::cout << *greeting << std::endl;
}
// Gracefully shutdown the process.
cppgc::ShutdownProcess();
return 0;
}

104
deps/v8/samples/hello-world.cc vendored Normal file
View File

@ -0,0 +1,104 @@
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "include/libplatform/libplatform.h"
#include "include/v8-context.h"
#include "include/v8-initialization.h"
#include "include/v8-isolate.h"
#include "include/v8-local-handle.h"
#include "include/v8-primitive.h"
#include "include/v8-script.h"
int main(int argc, char* argv[]) {
// Initialize V8.
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
// Create a new Isolate and make it the current one.
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
{
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8Literal(isolate, "'Hello' + ', World!'");
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
}
{
// Use the JavaScript API to generate a WebAssembly module.
//
// |bytes| contains the binary format for the following module:
//
// (func (export "add") (param i32 i32) (result i32)
// get_local 0
// get_local 1
// i32.add)
//
const char csource[] = R"(
let bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01,
0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07,
0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, 0x01,
0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b
]);
let module = new WebAssembly.Module(bytes);
let instance = new WebAssembly.Instance(module);
instance.exports.add(3, 4);
)";
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8Literal(isolate, csource);
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to a uint32 and print it.
uint32_t number = result->Uint32Value(context).ToChecked();
printf("3 + 4 = %u\n", number);
}
}
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
v8::V8::DisposePlatform();
delete create_params.array_buffer_allocator;
return 0;
}

727
deps/v8/samples/process.cc vendored Normal file
View File

@ -0,0 +1,727 @@
// Copyright 2012 the V8 project authors. All rights reserved.
// 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.
#include <stdlib.h>
#include <string.h>
#include <map>
#include <string>
#include "include/libplatform/libplatform.h"
#include "include/v8-array-buffer.h"
#include "include/v8-context.h"
#include "include/v8-exception.h"
#include "include/v8-external.h"
#include "include/v8-function.h"
#include "include/v8-initialization.h"
#include "include/v8-isolate.h"
#include "include/v8-local-handle.h"
#include "include/v8-object.h"
#include "include/v8-persistent-handle.h"
#include "include/v8-primitive.h"
#include "include/v8-script.h"
#include "include/v8-snapshot.h"
#include "include/v8-template.h"
#include "include/v8-value.h"
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;
// 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;
};
/**
* 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,
map<string, string>* output) = 0;
// Process a single request.
virtual bool Process(HttpRequest* req) = 0;
static void Log(const char* event);
};
/**
* 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.
JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
: isolate_(isolate), script_(script) {}
virtual ~JsHttpRequestProcessor();
virtual bool Initialize(map<string, string>* opts,
map<string, string>* output);
virtual bool Process(HttpRequest* req);
private:
// Execute the script associated with this processor and extract the
// Process function. Returns true if this succeeded, otherwise false.
bool ExecuteScript(Local<String> script);
// 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.
static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
// Callbacks that access the individual fields of request objects.
static void GetPath(Local<Name> name,
const PropertyCallbackInfo<Value>& info);
static void GetReferrer(Local<Name> name,
const PropertyCallbackInfo<Value>& info);
static void GetHost(Local<Name> name,
const PropertyCallbackInfo<Value>& info);
static void GetUserAgent(Local<Name> name,
const PropertyCallbackInfo<Value>& info);
// Callbacks that access maps
static v8::Intercepted MapGet(Local<Name> name,
const PropertyCallbackInfo<Value>& info);
static v8::Intercepted MapSet(Local<Name> name, Local<Value> value,
const PropertyCallbackInfo<void>& info);
// Utility methods for wrapping C++ objects as JavaScript objects,
// and going back again.
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);
Isolate* GetIsolate() { return isolate_; }
Isolate* isolate_;
Local<String> script_;
Global<Context> context_;
Global<Function> process_;
static Global<ObjectTemplate> request_template_;
static Global<ObjectTemplate> map_template_;
};
// -------------------------
// --- P r o c e s s o r ---
// -------------------------
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() < 1) return;
Isolate* isolate = info.GetIsolate();
HandleScope scope(isolate);
Local<Value> arg = info[0];
String::Utf8Value value(isolate, arg);
HttpRequestProcessor::Log(*value);
}
// Execute the script and fetch the Process method.
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
map<string, string>* output) {
// Create a handle scope to hold the temporary references.
HandleScope handle_scope(GetIsolate());
// Create a template for the global object where we set the
// built-in global functions.
Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
global->Set(GetIsolate(), "log",
FunctionTemplate::New(GetIsolate(), LogCallback));
// 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.
v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
context_.Reset(GetIsolate(), context);
// Enter the new context so all the following operations take place
// within it.
Context::Scope context_scope(context);
// 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.
Local<String> process_name =
String::NewFromUtf8Literal(GetIsolate(), "Process");
Local<Value> process_val;
// If there is no Process function, or if it is not a function,
// bail out
if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
!process_val->IsFunction()) {
return false;
}
// It is a function; cast it to a Function
Local<Function> process_fun = process_val.As<Function>();
// Store the function in a Global handle, since we also want
// that to remain after this call returns
process_.Reset(GetIsolate(), process_fun);
// All done; all went well
return true;
}
bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
HandleScope handle_scope(GetIsolate());
// We're just about to compile the script; set up an error handler to
// catch any exceptions the script might throw.
TryCatch try_catch(GetIsolate());
Local<Context> context(GetIsolate()->GetCurrentContext());
// Compile the script and check for errors.
Local<Script> compiled_script;
if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
String::Utf8Value error(GetIsolate(), try_catch.Exception());
Log(*error);
// The script failed to compile; bail out.
return false;
}
// Run the script!
Local<Value> result;
if (!compiled_script->Run(context).ToLocal(&result)) {
// The TryCatch above is still in effect and will have caught the error.
String::Utf8Value error(GetIsolate(), try_catch.Exception());
Log(*error);
// Running the script failed; bail out.
return false;
}
return true;
}
bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
map<string, string>* output) {
HandleScope handle_scope(GetIsolate());
// Wrap the map object in a JavaScript wrapper
Local<Object> opts_obj = WrapMap(opts);
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(GetIsolate(), context_);
// Set the options object as a property on the global object.
context->Global()
->Set(context, String::NewFromUtf8Literal(GetIsolate(), "options"),
opts_obj)
.FromJust();
Local<Object> output_obj = WrapMap(output);
context->Global()
->Set(context, String::NewFromUtf8Literal(GetIsolate(), "output"),
output_obj)
.FromJust();
return true;
}
bool JsHttpRequestProcessor::Process(HttpRequest* request) {
// Create a handle scope to keep the temporary object references.
HandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(GetIsolate(), context_);
// Enter this processor's context so all the remaining operations
// take place there
Context::Scope context_scope(context);
// Wrap the C++ request object in a JavaScript wrapper
Local<Object> request_obj = WrapRequest(request);
// Set up an exception handler before calling the Process function
TryCatch try_catch(GetIsolate());
// Invoke the process function, giving the global object as 'this'
// and one argument, the request.
const int argc = 1;
Local<Value> argv[argc] = {request_obj};
v8::Local<v8::Function> process =
v8::Local<v8::Function>::New(GetIsolate(), process_);
Local<Value> result;
if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
String::Utf8Value error(GetIsolate(), try_catch.Exception());
Log(*error);
return false;
}
return true;
}
JsHttpRequestProcessor::~JsHttpRequestProcessor() {
// Dispose the persistent handles. When no one else has any
// references to the objects stored in the handles they will be
// automatically reclaimed.
context_.Reset();
process_.Reset();
}
Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
// -----------------------------------
// --- 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.
Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
// Local scope for temporary handles.
EscapableHandleScope handle_scope(GetIsolate());
// Fetch the template for creating JavaScript map wrappers.
// It only has to be created once, which we do on demand.
if (map_template_.IsEmpty()) {
Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
map_template_.Reset(GetIsolate(), raw_template);
}
Local<ObjectTemplate> templ =
Local<ObjectTemplate>::New(GetIsolate(), map_template_);
// Create an empty map wrapper.
Local<Object> result =
templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
// Wrap the raw C++ pointer in an External so it can be referenced
// from within JavaScript.
Local<External> map_ptr = External::New(GetIsolate(), obj);
// 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.
return handle_scope.Escape(result);
}
// Utility function that extracts the C++ map pointer from a wrapper
// object.
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
Local<External> field = obj->GetInternalField(0).As<Value>().As<External>();
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(v8::Isolate* isolate, Local<Value> value) {
String::Utf8Value utf8_value(isolate, value);
return string(*utf8_value);
}
v8::Intercepted JsHttpRequestProcessor::MapGet(
Local<Name> name, const PropertyCallbackInfo<Value>& info) {
if (name->IsSymbol()) return v8::Intercepted::kNo;
// Fetch the map wrapped by this object.
map<string, string>* obj = UnwrapMap(info.HolderV2());
// Convert the JavaScript string to a std::string.
string key = ObjectToString(info.GetIsolate(), name.As<String>());
// 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
if (iter == obj->end()) return v8::Intercepted::kNo;
// Otherwise fetch the value and wrap it in a JavaScript string
const string& value = (*iter).second;
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), value.c_str(),
NewStringType::kNormal,
static_cast<int>(value.length())).ToLocalChecked());
return v8::Intercepted::kYes;
}
v8::Intercepted JsHttpRequestProcessor::MapSet(
Local<Name> name, Local<Value> value_obj,
const PropertyCallbackInfo<void>& info) {
if (name->IsSymbol()) return v8::Intercepted::kNo;
// Fetch the map wrapped by this object.
map<string, string>* obj = UnwrapMap(info.HolderV2());
// Convert the key and value to std::strings.
string key = ObjectToString(info.GetIsolate(), name.As<String>());
string value = ObjectToString(info.GetIsolate(), value_obj);
// Update the map.
(*obj)[key] = value;
return v8::Intercepted::kYes;
}
Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
Isolate* isolate) {
EscapableHandleScope handle_scope(isolate);
Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
result->SetInternalFieldCount(1);
result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
// Again, return the result through the current handle scope.
return handle_scope.Escape(result);
}
// -------------------------------------------
// --- 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.
*/
Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
// Local scope for temporary handles.
EscapableHandleScope handle_scope(GetIsolate());
// 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()) {
Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
request_template_.Reset(GetIsolate(), raw_template);
}
Local<ObjectTemplate> templ =
Local<ObjectTemplate>::New(GetIsolate(), request_template_);
// Create an empty http request wrapper.
Local<Object> result =
templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
// Wrap the raw C++ pointer in an External so it can be referenced
// from within JavaScript.
Local<External> request_ptr = External::New(GetIsolate(), request);
// 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.
return handle_scope.Escape(result);
}
/**
* Utility function that extracts the C++ http request object from a
* wrapper object.
*/
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
Local<External> field = obj->GetInternalField(0).As<Value>().As<External>();
void* ptr = field->Value();
return static_cast<HttpRequest*>(ptr);
}
void JsHttpRequestProcessor::GetPath(Local<Name> name,
const PropertyCallbackInfo<Value>& info) {
// Extract the C++ request object from the JavaScript wrapper.
HttpRequest* request = UnwrapRequest(info.HolderV2());
// Fetch the path.
const string& path = request->Path();
// Wrap the result in a JavaScript string and return it.
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), path.c_str(),
NewStringType::kNormal,
static_cast<int>(path.length())).ToLocalChecked());
}
void JsHttpRequestProcessor::GetReferrer(
Local<Name> name, const PropertyCallbackInfo<Value>& info) {
HttpRequest* request = UnwrapRequest(info.HolderV2());
const string& path = request->Referrer();
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), path.c_str(),
NewStringType::kNormal,
static_cast<int>(path.length())).ToLocalChecked());
}
void JsHttpRequestProcessor::GetHost(Local<Name> name,
const PropertyCallbackInfo<Value>& info) {
HttpRequest* request = UnwrapRequest(info.HolderV2());
const string& path = request->Host();
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), path.c_str(),
NewStringType::kNormal,
static_cast<int>(path.length())).ToLocalChecked());
}
void JsHttpRequestProcessor::GetUserAgent(
Local<Name> name, const PropertyCallbackInfo<Value>& info) {
HttpRequest* request = UnwrapRequest(info.HolderV2());
const string& path = request->UserAgent();
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), path.c_str(),
NewStringType::kNormal,
static_cast<int>(path.length())).ToLocalChecked());
}
Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
Isolate* isolate) {
EscapableHandleScope handle_scope(isolate);
Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
result->SetInternalFieldCount(1);
// Add accessors for each of the fields of the request.
result->SetNativeDataProperty(
String::NewFromUtf8Literal(isolate, "path", NewStringType::kInternalized),
GetPath);
result->SetNativeDataProperty(
String::NewFromUtf8Literal(isolate, "referrer",
NewStringType::kInternalized),
GetReferrer);
result->SetNativeDataProperty(
String::NewFromUtf8Literal(isolate, "host", NewStringType::kInternalized),
GetHost);
result->SetNativeDataProperty(
String::NewFromUtf8Literal(isolate, "userAgent",
NewStringType::kInternalized),
GetUserAgent);
// Again, return the result through the current handle scope.
return handle_scope.Escape(result);
}
// --- Test ---
void HttpRequestProcessor::Log(const char* event) {
printf("Logged: %s\n", event);
}
/**
* A simplified http request.
*/
class StringHttpRequest : public HttpRequest {
public:
StringHttpRequest(const string& path,
const string& referrer,
const string& host,
const string& user_agent);
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,
const string& referrer,
const string& host,
const string& user_agent)
: path_(path),
referrer_(referrer),
host_(host),
user_agent_(user_agent) { }
void ParseOptions(int argc,
char* argv[],
map<string, string>* options,
string* file) {
for (int i = 1; i < argc; i++) {
string arg = argv[i];
size_t index = arg.find('=', 0);
if (index == string::npos) {
*file = arg;
} else {
string key = arg.substr(0, index);
string value = arg.substr(index+1);
(*options)[key] = value;
}
}
}
// Reads a file into a v8 string.
MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
FILE* file = fopen(name.c_str(), "rb");
if (file == NULL) return MaybeLocal<String>();
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
std::unique_ptr<char[]> chars(new char[size + 1]);
chars.get()[size] = '\0';
for (size_t i = 0; i < size;) {
i += fread(&chars.get()[i], 1, size - i, file);
if (ferror(file)) {
fclose(file);
return MaybeLocal<String>();
}
}
fclose(file);
MaybeLocal<String> result = String::NewFromUtf8(
isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size));
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")
};
bool ProcessEntries(v8::Isolate* isolate, v8::Platform* platform,
HttpRequestProcessor* processor, int count,
StringHttpRequest* reqs) {
for (int i = 0; i < count; i++) {
bool result = processor->Process(&reqs[i]);
while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
if (!result) return false;
}
return true;
}
void PrintMap(map<string, string>* m) {
for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
pair<string, string> entry = *i;
printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
}
}
int main(int argc, char* argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
map<string, string> options;
string file;
ParseOptions(argc, argv, &options, &file);
if (file.empty()) {
fprintf(stderr, "No script was specified.\n");
return 1;
}
Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
Isolate* isolate = Isolate::New(create_params);
Isolate::Scope isolate_scope(isolate);
HandleScope scope(isolate);
Local<String> source;
if (!ReadFile(isolate, file).ToLocal(&source)) {
fprintf(stderr, "Error reading '%s'.\n", file.c_str());
return 1;
}
JsHttpRequestProcessor processor(isolate, source);
map<string, string> output;
if (!processor.Initialize(&options, &output)) {
fprintf(stderr, "Error initializing processor.\n");
return 1;
}
if (!ProcessEntries(isolate, platform.get(), &processor, kSampleSize,
kSampleRequests)) {
return 1;
}
PrintMap(&output);
}

397
deps/v8/samples/shell.cc vendored Normal file
View File

@ -0,0 +1,397 @@
// Copyright 2012 the V8 project authors. All rights reserved.
// 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.
#include <assert.h>
#include <fcntl.h>
#include <include/libplatform/libplatform.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "include/v8-context.h"
#include "include/v8-exception.h"
#include "include/v8-initialization.h"
#include "include/v8-isolate.h"
#include "include/v8-local-handle.h"
#include "include/v8-script.h"
#include "include/v8-template.h"
/**
* This sample program shows how to implement a simple javascript shell
* based on V8. This includes initializing V8 with command line options,
* creating global functions, compiling and executing strings.
*
* For a more sophisticated shell, consider using the debug shell D8.
*/
v8::Global<v8::Context> CreateShellContext(v8::Isolate* isolate);
void RunShell(v8::Isolate* isolate, const v8::Global<v8::Context>& context,
v8::Platform* platform);
int RunMain(v8::Isolate* isolate, const v8::Global<v8::Context>& context,
v8::Platform* platform, int argc, char* argv[]);
bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
v8::Local<v8::Value> name, bool print_result,
bool report_exceptions);
void Print(const v8::FunctionCallbackInfo<v8::Value>& info);
void Read(const v8::FunctionCallbackInfo<v8::Value>& info);
void Load(const v8::FunctionCallbackInfo<v8::Value>& info);
void Quit(const v8::FunctionCallbackInfo<v8::Value>& info);
void Version(const v8::FunctionCallbackInfo<v8::Value>& info);
v8::MaybeLocal<v8::String> ReadFile(v8::Isolate* isolate, const char* name);
void ReportException(v8::Isolate* isolate, v8::TryCatch* handler);
static bool run_shell;
int main(int argc, char* argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
v8::V8::Initialize();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
run_shell = (argc == 1);
int result;
{
v8::Isolate::Scope isolate_scope(isolate);
v8::Global<v8::Context> context = CreateShellContext(isolate);
if (context.IsEmpty()) {
fprintf(stderr, "Error creating context\n");
return 1;
}
result = RunMain(isolate, context, platform.get(), argc, argv);
if (run_shell) RunShell(isolate, context, platform.get());
}
isolate->Dispose();
v8::V8::Dispose();
v8::V8::DisposePlatform();
delete create_params.array_buffer_allocator;
return result;
}
// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}
// Creates a new execution environment containing the built-in
// functions.
v8::Global<v8::Context> CreateShellContext(v8::Isolate* isolate) {
v8::HandleScope handle_scope(isolate);
// Create a template for the global object.
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
// Bind the global 'print' function to the C++ Print callback.
global->Set(isolate, "print", v8::FunctionTemplate::New(isolate, Print));
// Bind the global 'read' function to the C++ Read callback.
global->Set(isolate, "read", v8::FunctionTemplate::New(isolate, Read));
// Bind the global 'load' function to the C++ Load callback.
global->Set(isolate, "load", v8::FunctionTemplate::New(isolate, Load));
// Bind the 'quit' function
global->Set(isolate, "quit", v8::FunctionTemplate::New(isolate, Quit));
// Bind the 'version' function
global->Set(isolate, "version", v8::FunctionTemplate::New(isolate, Version));
// Return the context.
v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
return v8::Global<v8::Context>(isolate, context);
}
// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called. Prints its arguments on stdout separated by
// spaces and ending with a newline.
void Print(const v8::FunctionCallbackInfo<v8::Value>& info) {
bool first = true;
for (int i = 0; i < info.Length(); i++) {
v8::HandleScope handle_scope(info.GetIsolate());
if (first) {
first = false;
} else {
printf(" ");
}
v8::String::Utf8Value str(info.GetIsolate(), info[i]);
const char* cstr = ToCString(str);
printf("%s", cstr);
}
printf("\n");
fflush(stdout);
}
// The callback that is invoked by v8 whenever the JavaScript 'read'
// function is called. This function loads the content of the file named in
// the argument into a JavaScript string.
void Read(const v8::FunctionCallbackInfo<v8::Value>& info) {
if (info.Length() != 1) {
info.GetIsolate()->ThrowError("Bad parameters");
return;
}
v8::String::Utf8Value file(info.GetIsolate(), info[0]);
if (*file == nullptr) {
info.GetIsolate()->ThrowError("Error loading file");
return;
}
v8::Local<v8::String> source;
if (!ReadFile(info.GetIsolate(), *file).ToLocal(&source)) {
info.GetIsolate()->ThrowError("Error loading file");
return;
}
info.GetReturnValue().Set(source);
}
// The callback that is invoked by v8 whenever the JavaScript 'load'
// function is called. Loads, compiles and executes its argument
// JavaScript file.
void Load(const v8::FunctionCallbackInfo<v8::Value>& info) {
for (int i = 0; i < info.Length(); i++) {
v8::HandleScope handle_scope(info.GetIsolate());
v8::String::Utf8Value file(info.GetIsolate(), info[i]);
if (*file == nullptr) {
info.GetIsolate()->ThrowError("Error loading file");
return;
}
v8::Local<v8::String> source;
if (!ReadFile(info.GetIsolate(), *file).ToLocal(&source)) {
info.GetIsolate()->ThrowError("Error loading file");
return;
}
if (!ExecuteString(info.GetIsolate(), source, info[i], false, false)) {
info.GetIsolate()->ThrowError("Error executing file");
return;
}
}
}
// The callback that is invoked by v8 whenever the JavaScript 'quit'
// function is called. Quits.
void Quit(const v8::FunctionCallbackInfo<v8::Value>& info) {
// If not arguments are given info[0] will yield undefined which
// converts to the integer value 0.
int exit_code =
info[0]->Int32Value(info.GetIsolate()->GetCurrentContext()).FromMaybe(0);
fflush(stdout);
fflush(stderr);
exit(exit_code);
}
// The callback that is invoked by v8 whenever the JavaScript 'version'
// function is called. Returns a string containing the current V8 version.
void Version(const v8::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(
v8::String::NewFromUtf8(info.GetIsolate(), v8::V8::GetVersion())
.ToLocalChecked());
}
// Reads a file into a v8 string.
v8::MaybeLocal<v8::String> ReadFile(v8::Isolate* isolate, const char* name) {
FILE* file = fopen(name, "rb");
if (file == nullptr) return {};
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (size_t i = 0; i < size;) {
i += fread(&chars[i], 1, size - i, file);
if (ferror(file)) {
fclose(file);
return {};
}
}
fclose(file);
v8::MaybeLocal<v8::String> result = v8::String::NewFromUtf8(
isolate, chars, v8::NewStringType::kNormal, static_cast<int>(size));
delete[] chars;
return result;
}
// Process remaining command line arguments and execute files
int RunMain(v8::Isolate* isolate, const v8::Global<v8::Context>& context,
v8::Platform* platform, int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
const char* str = argv[i];
if (strcmp(str, "--shell") == 0) {
run_shell = true;
} else if (strcmp(str, "-f") == 0) {
// Ignore any -f flags for compatibility with the other stand-
// alone JavaScript engines.
continue;
} else if (strncmp(str, "--", 2) == 0) {
fprintf(stderr,
"Warning: unknown flag %s.\nTry --help for options\n", str);
} else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
// Execute argument given to -e option directly.
bool success;
{
// Enter the execution environment before evaluating any code.
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context.Get(isolate));
v8::Local<v8::String> file_name =
v8::String::NewFromUtf8Literal(isolate, "unnamed");
v8::Local<v8::String> source;
if (!v8::String::NewFromUtf8(isolate, argv[++i]).ToLocal(&source)) {
return 1;
}
success = ExecuteString(isolate, source, file_name, false, true);
}
// It is important not to pump the message loop when there are v8::Local
// handles on the stack, as this may trigger a stackless GC.
while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
if (!success) return 1;
} else {
// Use all other arguments as names of files to load and run.
bool success;
{
// Enter the execution environment before evaluating any code.
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context.Get(isolate));
v8::Local<v8::String> file_name =
v8::String::NewFromUtf8(isolate, str).ToLocalChecked();
v8::Local<v8::String> source;
if (!ReadFile(isolate, str).ToLocal(&source)) {
fprintf(stderr, "Error reading '%s'\n", str);
continue;
}
success = ExecuteString(isolate, source, file_name, false, true);
}
// It is important not to pump the message loop when there are v8::Local
// handles on the stack, as this may trigger a stackless GC.
while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
if (!success) return 1;
}
}
return 0;
}
// The read-eval-execute loop of the shell.
void RunShell(v8::Isolate* isolate, const v8::Global<v8::Context>& context,
v8::Platform* platform) {
fprintf(stderr, "V8 version %s [sample shell]\n", v8::V8::GetVersion());
static const int kBufferSize = 256;
while (true) {
char buffer[kBufferSize];
fprintf(stderr, "> ");
char* str = fgets(buffer, kBufferSize, stdin);
if (str == nullptr) break;
{
// Enter the execution environment before evaluating any code.
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context.Get(isolate));
v8::Local<v8::String> name(
v8::String::NewFromUtf8Literal(isolate, "(shell)"));
ExecuteString(isolate,
v8::String::NewFromUtf8(isolate, str).ToLocalChecked(),
name, true, true);
}
// It is important not to pump the message loop when there are v8::Local
// handles on the stack, as this may trigger a stackless GC.
while (v8::platform::PumpMessageLoop(platform, isolate)) continue;
}
fprintf(stderr, "\n");
}
// Executes a string within the current v8 context.
bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
v8::Local<v8::Value> name, bool print_result,
bool report_exceptions) {
v8::HandleScope handle_scope(isolate);
v8::TryCatch try_catch(isolate);
v8::ScriptOrigin origin(name);
v8::Local<v8::Context> context(isolate->GetCurrentContext());
v8::Local<v8::Script> script;
if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) {
// Print errors that happened during compilation.
if (report_exceptions)
ReportException(isolate, &try_catch);
return false;
} else {
v8::Local<v8::Value> result;
if (!script->Run(context).ToLocal(&result)) {
assert(try_catch.HasCaught());
// Print errors that happened during execution.
if (report_exceptions)
ReportException(isolate, &try_catch);
return false;
} else {
assert(!try_catch.HasCaught());
if (print_result && !result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
v8::String::Utf8Value str(isolate, result);
const char* cstr = ToCString(str);
printf("%s\n", cstr);
}
return true;
}
}
}
void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
v8::HandleScope handle_scope(isolate);
v8::String::Utf8Value exception(isolate, try_catch->Exception());
const char* exception_string = ToCString(exception);
v8::Local<v8::Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
fprintf(stderr, "%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(isolate,
message->GetScriptOrigin().ResourceName());
v8::Local<v8::Context> context(isolate->GetCurrentContext());
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber(context).FromJust();
fprintf(stderr, "%s:%i: %s\n", filename_string, linenum, exception_string);
// Print line of source code.
v8::String::Utf8Value sourceline(
isolate, message->GetSourceLine(context).ToLocalChecked());
const char* sourceline_string = ToCString(sourceline);
fprintf(stderr, "%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn(context).FromJust();
for (int i = 0; i < start; i++) {
fprintf(stderr, " ");
}
int end = message->GetEndColumn(context).FromJust();
for (int i = start; i < end; i++) {
fprintf(stderr, "^");
}
fprintf(stderr, "\n");
v8::Local<v8::Value> stack_trace_string;
if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
stack_trace_string->IsString() &&
stack_trace_string.As<v8::String>()->Length() > 0) {
v8::String::Utf8Value stack_trace(isolate, stack_trace_string);
const char* err = ToCString(stack_trace);
fprintf(stderr, "%s\n", err);
}
}
}