aboutsummaryrefslogtreecommitdiff
path: root/samples
diff options
context:
space:
mode:
authorRubin Xu <rubinxu@google.com>2019-02-07 16:01:35 +0000
committerRubin Xu <rubinxu@google.com>2019-03-04 17:33:22 +0000
commit2894c6aa01bdd1c031c453cacab7b5fec4dc7809 (patch)
tree7b5ab135bd37b3f6661638231bb043f3c82328ec /samples
parent1a4b825c997dfe9ab3540da0b5e3693f9951af0c (diff)
downloadv8-2894c6aa01bdd1c031c453cacab7b5fec4dc7809.tar.gz
Upgrade V8 to 7.0.276.40
Bug: 117554758 Bug: 117555811 Bug: 117556606 Bug: 117556220 Bug: 117607414 Bug: 117606285 Test: atest com.google.android.gts.devicepolicy.DeviceOwnerTest#testProxyPacProxyTest Test: atest proxy_resolver_v8_unittest Change-Id: I2e02d994f107e64e4f465b4d8a02d4159a95240e
Diffstat (limited to 'samples')
-rw-r--r--samples/hello-world.cc94
-rw-r--r--samples/process.cc68
-rw-r--r--samples/samples.gyp84
-rw-r--r--samples/shell.cc28
4 files changed, 126 insertions, 148 deletions
diff --git a/samples/hello-world.cc b/samples/hello-world.cc
index 9e5188f4..d75dcb3c 100644
--- a/samples/hello-world.cc
+++ b/samples/hello-world.cc
@@ -9,54 +9,94 @@
#include "include/libplatform/libplatform.h"
#include "include/v8.h"
-using namespace v8;
-
int main(int argc, char* argv[]) {
// Initialize V8.
- V8::InitializeICUDefaultLocation(argv[0]);
- V8::InitializeExternalStartupData(argv[0]);
- Platform* platform = platform::CreateDefaultPlatform();
- V8::InitializePlatform(platform);
- V8::Initialize();
+ 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.
- Isolate::CreateParams create_params;
+ v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
- Isolate* isolate = Isolate::New(create_params);
+ v8::Isolate* isolate = v8::Isolate::New(create_params);
{
- Isolate::Scope isolate_scope(isolate);
+ v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
- HandleScope handle_scope(isolate);
+ v8::HandleScope handle_scope(isolate);
// Create a new context.
- Local<Context> context = Context::New(isolate);
+ v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
- Context::Scope context_scope(context);
+ v8::Context::Scope context_scope(context);
+
+ {
+ // Create a string containing the JavaScript source code.
+ v8::Local<v8::String> source =
+ v8::String::NewFromUtf8(isolate, "'Hello' + ', World!'",
+ v8::NewStringType::kNormal)
+ .ToLocalChecked();
+
+ // 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.
- Local<String> source =
- String::NewFromUtf8(isolate, "'Hello' + ', World!'",
- NewStringType::kNormal).ToLocalChecked();
+ // Create a string containing the JavaScript source code.
+ v8::Local<v8::String> source =
+ v8::String::NewFromUtf8(isolate, csource, v8::NewStringType::kNormal)
+ .ToLocalChecked();
- // Compile the source code.
- Local<Script> script = Script::Compile(context, source).ToLocalChecked();
+ // Compile the source code.
+ v8::Local<v8::Script> script =
+ v8::Script::Compile(context, source).ToLocalChecked();
- // Run the script to get the result.
- Local<Value> result = script->Run(context).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.
- String::Utf8Value utf8(result);
- printf("%s\n", *utf8);
+ // 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::Dispose();
- V8::ShutdownPlatform();
- delete platform;
+ v8::V8::Dispose();
+ v8::V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
return 0;
}
diff --git a/samples/process.cc b/samples/process.cc
index 29ddb5cf..9af1c0b2 100644
--- a/samples/process.cc
+++ b/samples/process.cc
@@ -35,8 +35,30 @@
#include <map>
#include <string>
-using namespace std;
-using namespace v8;
+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
@@ -144,9 +166,10 @@ class JsHttpRequestProcessor : public HttpRequestProcessor {
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() < 1) return;
- HandleScope scope(args.GetIsolate());
+ Isolate* isolate = args.GetIsolate();
+ HandleScope scope(isolate);
Local<Value> arg = args[0];
- String::Utf8Value value(arg);
+ String::Utf8Value value(isolate, arg);
HttpRequestProcessor::Log(*value);
}
@@ -221,7 +244,7 @@ bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
// Compile the script and check for errors.
Local<Script> compiled_script;
if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
- String::Utf8Value error(try_catch.Exception());
+ String::Utf8Value error(GetIsolate(), try_catch.Exception());
Log(*error);
// The script failed to compile; bail out.
return false;
@@ -231,11 +254,12 @@ bool JsHttpRequestProcessor::ExecuteScript(Local<String> 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(try_catch.Exception());
+ String::Utf8Value error(GetIsolate(), try_catch.Exception());
Log(*error);
// Running the script failed; bail out.
return false;
}
+
return true;
}
@@ -295,17 +319,16 @@ bool JsHttpRequestProcessor::Process(HttpRequest* request) {
v8::Local<v8::Function>::New(GetIsolate(), process_);
Local<Value> result;
if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
- String::Utf8Value error(try_catch.Exception());
+ String::Utf8Value error(GetIsolate(), try_catch.Exception());
Log(*error);
return false;
- } else {
- return true;
}
+ return true;
}
JsHttpRequestProcessor::~JsHttpRequestProcessor() {
- // Dispose the persistent handles. When noone else has any
+ // 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();
@@ -366,8 +389,8 @@ map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
// 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) {
- String::Utf8Value utf8_value(value);
+string ObjectToString(v8::Isolate* isolate, Local<Value> value) {
+ String::Utf8Value utf8_value(isolate, value);
return string(*utf8_value);
}
@@ -380,7 +403,7 @@ void JsHttpRequestProcessor::MapGet(Local<Name> name,
map<string, string>* obj = UnwrapMap(info.Holder());
// Convert the JavaScript string to a std::string.
- string key = ObjectToString(Local<String>::Cast(name));
+ string key = ObjectToString(info.GetIsolate(), Local<String>::Cast(name));
// Look up the value if it exists using the standard STL ideom.
map<string, string>::iterator iter = obj->find(key);
@@ -405,8 +428,8 @@ void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
map<string, string>* obj = UnwrapMap(info.Holder());
// Convert the key and value to std::strings.
- string key = ObjectToString(Local<String>::Cast(name));
- string value = ObjectToString(value_obj);
+ string key = ObjectToString(info.GetIsolate(), Local<String>::Cast(name));
+ string value = ObjectToString(info.GetIsolate(), value_obj);
// Update the map.
(*obj)[key] = value;
@@ -627,10 +650,10 @@ MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
size_t size = ftell(file);
rewind(file);
- char* chars = new char[size + 1];
- chars[size] = '\0';
+ std::unique_ptr<char> chars(new char[size + 1]);
+ chars.get()[size] = '\0';
for (size_t i = 0; i < size;) {
- i += fread(&chars[i], 1, size - i, file);
+ i += fread(&chars.get()[i], 1, size - i, file);
if (ferror(file)) {
fclose(file);
return MaybeLocal<String>();
@@ -638,8 +661,7 @@ MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
}
fclose(file);
MaybeLocal<String> result = String::NewFromUtf8(
- isolate, chars, NewStringType::kNormal, static_cast<int>(size));
- delete[] chars;
+ isolate, chars.get(), NewStringType::kNormal, static_cast<int>(size));
return result;
}
@@ -678,8 +700,8 @@ void PrintMap(map<string, string>* m) {
int main(int argc, char* argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
- v8::Platform* platform = v8::platform::CreateDefaultPlatform();
- v8::V8::InitializePlatform(platform);
+ std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
+ v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
map<string, string> options;
string file;
@@ -705,7 +727,7 @@ int main(int argc, char* argv[]) {
fprintf(stderr, "Error initializing processor.\n");
return 1;
}
- if (!ProcessEntries(platform, &processor, kSampleSize, kSampleRequests))
+ if (!ProcessEntries(platform.get(), &processor, kSampleSize, kSampleRequests))
return 1;
PrintMap(&output);
}
diff --git a/samples/samples.gyp b/samples/samples.gyp
deleted file mode 100644
index e7c26cf2..00000000
--- a/samples/samples.gyp
+++ /dev/null
@@ -1,84 +0,0 @@
-# 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.
-
-{
- 'variables': {
- 'v8_code': 1,
- 'v8_enable_i18n_support%': 1,
- 'v8_toolset_for_shell%': 'target',
- },
- 'includes': ['../gypfiles/toolchain.gypi', '../gypfiles/features.gypi'],
- 'target_defaults': {
- 'type': 'executable',
- 'dependencies': [
- '../src/v8.gyp:v8',
- '../src/v8.gyp:v8_libbase',
- '../src/v8.gyp:v8_libplatform',
- ],
- 'include_dirs': [
- '..',
- ],
- 'conditions': [
- ['v8_enable_i18n_support==1', {
- 'dependencies': [
- '<(icu_gyp_path):icui18n',
- '<(icu_gyp_path):icuuc',
- ],
- }],
- ['OS=="win" and v8_enable_i18n_support==1', {
- 'dependencies': [
- '<(icu_gyp_path):icudata',
- ],
- }],
- ],
- },
- 'targets': [
- {
- 'target_name': 'v8_shell',
- 'sources': [
- 'shell.cc',
- ],
- 'conditions': [
- [ 'want_separate_host_toolset==1', {
- 'toolsets': [ '<(v8_toolset_for_shell)', ],
- }],
- ],
- },
- {
- 'target_name': 'hello-world',
- 'sources': [
- 'hello-world.cc',
- ],
- },
- {
- 'target_name': 'process',
- 'sources': [
- 'process.cc',
- ],
- },
- ],
-}
diff --git a/samples/shell.cc b/samples/shell.cc
index e042815e..81b02872 100644
--- a/samples/shell.cc
+++ b/samples/shell.cc
@@ -66,8 +66,8 @@ static bool run_shell;
int main(int argc, char* argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
- v8::Platform* platform = v8::platform::CreateDefaultPlatform();
- v8::V8::InitializePlatform(platform);
+ std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
+ v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
v8::Isolate::CreateParams create_params;
@@ -85,13 +85,12 @@ int main(int argc, char* argv[]) {
return 1;
}
v8::Context::Scope context_scope(context);
- result = RunMain(isolate, platform, argc, argv);
- if (run_shell) RunShell(context, platform);
+ result = RunMain(isolate, platform.get(), argc, argv);
+ if (run_shell) RunShell(context, platform.get());
}
isolate->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
- delete platform;
delete create_params.array_buffer_allocator;
return result;
}
@@ -147,7 +146,7 @@ void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
} else {
printf(" ");
}
- v8::String::Utf8Value str(args[i]);
+ v8::String::Utf8Value str(args.GetIsolate(), args[i]);
const char* cstr = ToCString(str);
printf("%s", cstr);
}
@@ -166,7 +165,7 @@ void Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::NewStringType::kNormal).ToLocalChecked());
return;
}
- v8::String::Utf8Value file(args[0]);
+ v8::String::Utf8Value file(args.GetIsolate(), args[0]);
if (*file == NULL) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
@@ -180,17 +179,17 @@ void Read(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::NewStringType::kNormal).ToLocalChecked());
return;
}
+
args.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>& args) {
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope(args.GetIsolate());
- v8::String::Utf8Value file(args[i]);
+ v8::String::Utf8Value file(args.GetIsolate(), args[i]);
if (*file == NULL) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file",
@@ -361,7 +360,7 @@ bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
if (print_result && !result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
- v8::String::Utf8Value str(result);
+ v8::String::Utf8Value str(isolate, result);
const char* cstr = ToCString(str);
printf("%s\n", cstr);
}
@@ -373,7 +372,7 @@ bool ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
v8::HandleScope handle_scope(isolate);
- v8::String::Utf8Value exception(try_catch->Exception());
+ 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()) {
@@ -382,14 +381,15 @@ void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
fprintf(stderr, "%s\n", exception_string);
} else {
// Print (filename):(line number): (message).
- v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
+ 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(
- message->GetSourceLine(context).ToLocalChecked());
+ isolate, message->GetSourceLine(context).ToLocalChecked());
const char* sourceline_string = ToCString(sourceline);
fprintf(stderr, "%s\n", sourceline_string);
// Print wavy underline (GetUnderline is deprecated).
@@ -406,7 +406,7 @@ void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch) {
if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
stack_trace_string->IsString() &&
v8::Local<v8::String>::Cast(stack_trace_string)->Length() > 0) {
- v8::String::Utf8Value stack_trace(stack_trace_string);
+ v8::String::Utf8Value stack_trace(isolate, stack_trace_string);
const char* stack_trace_string = ToCString(stack_trace);
fprintf(stderr, "%s\n", stack_trace_string);
}