// Copyright 2006-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. #include "v8.h" #include "accessors.h" #include "api.h" #include "bootstrapper.h" #include "compiler.h" #include "debug.h" #include "execution.h" #include "global-handles.h" #include "macro-assembler.h" #include "natives.h" #include "snapshot.h" namespace v8 { namespace internal { // A SourceCodeCache uses a FixedArray to store pairs of // (AsciiString*, JSFunction*), mapping names of native code files // (runtime.js, etc.) to precompiled functions. Instead of mapping // names to functions it might make sense to let the JS2C tool // generate an index for each native JS file. class SourceCodeCache BASE_EMBEDDED { public: explicit SourceCodeCache(Script::Type type): type_(type), cache_(NULL) { } void Initialize(bool create_heap_objects) { cache_ = create_heap_objects ? Heap::empty_fixed_array() : NULL; } void Iterate(ObjectVisitor* v) { v->VisitPointer(BitCast(&cache_)); } bool Lookup(Vector name, Handle* handle) { for (int i = 0; i < cache_->length(); i+=2) { SeqAsciiString* str = SeqAsciiString::cast(cache_->get(i)); if (str->IsEqualTo(name)) { *handle = Handle( SharedFunctionInfo::cast(cache_->get(i + 1))); return true; } } return false; } void Add(Vector name, Handle shared) { HandleScope scope; int length = cache_->length(); Handle new_array = Factory::NewFixedArray(length + 2, TENURED); cache_->CopyTo(0, *new_array, 0, cache_->length()); cache_ = *new_array; Handle str = Factory::NewStringFromAscii(name, TENURED); cache_->set(length, *str); cache_->set(length + 1, *shared); Script::cast(shared->script())->set_type(Smi::FromInt(type_)); } private: Script::Type type_; FixedArray* cache_; DISALLOW_COPY_AND_ASSIGN(SourceCodeCache); }; static SourceCodeCache extensions_cache(Script::TYPE_EXTENSION); // This is for delete, not delete[]. static List* delete_these_non_arrays_on_tear_down = NULL; // This is for delete[] static List* delete_these_arrays_on_tear_down = NULL; NativesExternalStringResource::NativesExternalStringResource(const char* source) : data_(source), length_(StrLength(source)) { if (delete_these_non_arrays_on_tear_down == NULL) { delete_these_non_arrays_on_tear_down = new List(2); } // The resources are small objects and we only make a fixed number of // them, but let's clean them up on exit for neatness. delete_these_non_arrays_on_tear_down-> Add(reinterpret_cast(this)); } Handle Bootstrapper::NativesSourceLookup(int index) { ASSERT(0 <= index && index < Natives::GetBuiltinsCount()); if (Heap::natives_source_cache()->get(index)->IsUndefined()) { if (!Snapshot::IsEnabled() || FLAG_new_snapshot) { // We can use external strings for the natives. NativesExternalStringResource* resource = new NativesExternalStringResource( Natives::GetScriptSource(index).start()); Handle source_code = Factory::NewExternalStringFromAscii(resource); Heap::natives_source_cache()->set(index, *source_code); } else { // Old snapshot code can't cope with external strings at all. Handle source_code = Factory::NewStringFromAscii(Natives::GetScriptSource(index)); Heap::natives_source_cache()->set(index, *source_code); } } Handle cached_source(Heap::natives_source_cache()->get(index)); return Handle::cast(cached_source); } void Bootstrapper::Initialize(bool create_heap_objects) { extensions_cache.Initialize(create_heap_objects); } char* Bootstrapper::AllocateAutoDeletedArray(int bytes) { char* memory = new char[bytes]; if (memory != NULL) { if (delete_these_arrays_on_tear_down == NULL) { delete_these_arrays_on_tear_down = new List(2); } delete_these_arrays_on_tear_down->Add(memory); } return memory; } void Bootstrapper::TearDown() { if (delete_these_non_arrays_on_tear_down != NULL) { int len = delete_these_non_arrays_on_tear_down->length(); ASSERT(len < 20); // Don't use this mechanism for unbounded allocations. for (int i = 0; i < len; i++) { delete delete_these_non_arrays_on_tear_down->at(i); delete_these_non_arrays_on_tear_down->at(i) = NULL; } delete delete_these_non_arrays_on_tear_down; delete_these_non_arrays_on_tear_down = NULL; } if (delete_these_arrays_on_tear_down != NULL) { int len = delete_these_arrays_on_tear_down->length(); ASSERT(len < 1000); // Don't use this mechanism for unbounded allocations. for (int i = 0; i < len; i++) { delete[] delete_these_arrays_on_tear_down->at(i); delete_these_arrays_on_tear_down->at(i) = NULL; } delete delete_these_arrays_on_tear_down; delete_these_arrays_on_tear_down = NULL; } extensions_cache.Initialize(false); // Yes, symmetrical } class Genesis BASE_EMBEDDED { public: Genesis(Handle global_object, v8::Handle global_template, v8::ExtensionConfiguration* extensions); ~Genesis() { } Handle result() { return result_; } Genesis* previous() { return previous_; } private: Handle global_context_; // There may be more than one active genesis object: When GC is // triggered during environment creation there may be weak handle // processing callbacks which may create new environments. Genesis* previous_; Handle global_context() { return global_context_; } // Creates some basic objects. Used for creating a context from scratch. void CreateRoots(); // Creates the empty function. Used for creating a context from scratch. Handle CreateEmptyFunction(); // Creates the global objects using the global and the template passed in // through the API. We call this regardless of whether we are building a // context from scratch or using a deserialized one from the partial snapshot // but in the latter case we don't use the objects it produces directly, as // we have to used the deserialized ones that are linked together with the // rest of the context snapshot. Handle CreateNewGlobals( v8::Handle global_template, Handle global_object, Handle* global_proxy_out); // Hooks the given global proxy into the context. If the context was created // by deserialization then this will unhook the global proxy that was // deserialized, leaving the GC to pick it up. void HookUpGlobalProxy(Handle inner_global, Handle global_proxy); // Similarly, we want to use the inner global that has been created by the // templates passed through the API. The inner global from the snapshot is // detached from the other objects in the snapshot. void HookUpInnerGlobal(Handle inner_global); // New context initialization. Used for creating a context from scratch. void InitializeGlobal(Handle inner_global, Handle empty_function); // Installs the contents of the native .js files on the global objects. // Used for creating a context from scratch. void InstallNativeFunctions(); bool InstallNatives(); // Used both for deserialized and from-scratch contexts to add the extensions // provided. static bool InstallExtensions(Handle global_context, v8::ExtensionConfiguration* extensions); static bool InstallExtension(const char* name); static bool InstallExtension(v8::RegisteredExtension* current); static void InstallSpecialObjects(Handle global_context); bool InstallJSBuiltins(Handle builtins); bool ConfigureApiObject(Handle object, Handle object_template); bool ConfigureGlobalObjects(v8::Handle global_template); // Migrates all properties from the 'from' object to the 'to' // object and overrides the prototype in 'to' with the one from // 'from'. void TransferObject(Handle from, Handle to); void TransferNamedProperties(Handle from, Handle to); void TransferIndexedProperties(Handle from, Handle to); Handle ComputeFunctionInstanceDescriptor( bool make_prototype_read_only, bool make_prototype_enumerable = false); void MakeFunctionInstancePrototypeWritable(); static bool CompileBuiltin(int index); static bool CompileNative(Vector name, Handle source); static bool CompileScriptCached(Vector name, Handle source, SourceCodeCache* cache, v8::Extension* extension, Handle top_context, bool use_runtime_context); Handle result_; Handle empty_function_; BootstrapperActive active_; friend class Bootstrapper; }; void Bootstrapper::Iterate(ObjectVisitor* v) { extensions_cache.Iterate(v); v->Synchronize("Extensions"); } Handle Bootstrapper::CreateEnvironment( Handle global_object, v8::Handle global_template, v8::ExtensionConfiguration* extensions) { HandleScope scope; Handle env; Genesis genesis(global_object, global_template, extensions); env = genesis.result(); if (!env.is_null()) { if (InstallExtensions(env, extensions)) { return env; } } return Handle(); } static void SetObjectPrototype(Handle object, Handle proto) { // object.__proto__ = proto; Handle old_to_map = Handle(object->map()); Handle new_to_map = Factory::CopyMapDropTransitions(old_to_map); new_to_map->set_prototype(*proto); object->set_map(*new_to_map); } void Bootstrapper::DetachGlobal(Handle env) { JSGlobalProxy::cast(env->global_proxy())->set_context(*Factory::null_value()); SetObjectPrototype(Handle(env->global_proxy()), Factory::null_value()); env->set_global_proxy(env->global()); env->global()->set_global_receiver(env->global()); } void Bootstrapper::ReattachGlobal(Handle env, Handle global_object) { ASSERT(global_object->IsJSGlobalProxy()); Handle global = Handle::cast(global_object); env->global()->set_global_receiver(*global); env->set_global_proxy(*global); SetObjectPrototype(global, Handle(env->global())); global->set_context(*env); } static Handle InstallFunction(Handle target, const char* name, InstanceType type, int instance_size, Handle prototype, Builtins::Name call, bool is_ecma_native) { Handle symbol = Factory::LookupAsciiSymbol(name); Handle call_code = Handle(Builtins::builtin(call)); Handle function = Factory::NewFunctionWithPrototype(symbol, type, instance_size, prototype, call_code, is_ecma_native); SetProperty(target, symbol, function, DONT_ENUM); if (is_ecma_native) { function->shared()->set_instance_class_name(*symbol); } return function; } Handle Genesis::ComputeFunctionInstanceDescriptor( bool make_prototype_read_only, bool make_prototype_enumerable) { Handle result = Factory::empty_descriptor_array(); // Add prototype. PropertyAttributes attributes = static_cast( (make_prototype_enumerable ? 0 : DONT_ENUM) | DONT_DELETE | (make_prototype_read_only ? READ_ONLY : 0)); result = Factory::CopyAppendProxyDescriptor( result, Factory::prototype_symbol(), Factory::NewProxy(&Accessors::FunctionPrototype), attributes); attributes = static_cast(DONT_ENUM | DONT_DELETE | READ_ONLY); // Add length. result = Factory::CopyAppendProxyDescriptor( result, Factory::length_symbol(), Factory::NewProxy(&Accessors::FunctionLength), attributes); // Add name. result = Factory::CopyAppendProxyDescriptor( result, Factory::name_symbol(), Factory::NewProxy(&Accessors::FunctionName), attributes); // Add arguments. result = Factory::CopyAppendProxyDescriptor( result, Factory::arguments_symbol(), Factory::NewProxy(&Accessors::FunctionArguments), attributes); // Add caller. result = Factory::CopyAppendProxyDescriptor( result, Factory::caller_symbol(), Factory::NewProxy(&Accessors::FunctionCaller), attributes); return result; } Handle Genesis::CreateEmptyFunction() { // Allocate the map for function instances. Handle fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize); global_context()->set_function_instance_map(*fm); // Please note that the prototype property for function instances must be // writable. Handle function_map_descriptors = ComputeFunctionInstanceDescriptor(false, false); fm->set_instance_descriptors(*function_map_descriptors); // Allocate the function map first and then patch the prototype later fm = Factory::NewMap(JS_FUNCTION_TYPE, JSFunction::kSize); global_context()->set_function_map(*fm); function_map_descriptors = ComputeFunctionInstanceDescriptor(true); fm->set_instance_descriptors(*function_map_descriptors); Handle object_name = Handle(Heap::Object_symbol()); { // --- O b j e c t --- Handle object_fun = Factory::NewFunction(object_name, Factory::null_value()); Handle object_function_map = Factory::NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize); object_fun->set_initial_map(*object_function_map); object_function_map->set_constructor(*object_fun); global_context()->set_object_function(*object_fun); // Allocate a new prototype for the object function. Handle prototype = Factory::NewJSObject(Top::object_function(), TENURED); global_context()->set_initial_object_prototype(*prototype); SetPrototype(object_fun, prototype); object_function_map-> set_instance_descriptors(Heap::empty_descriptor_array()); } // Allocate the empty function as the prototype for function ECMAScript // 262 15.3.4. Handle symbol = Factory::LookupAsciiSymbol("Empty"); Handle empty_function = Factory::NewFunction(symbol, Factory::null_value()); // --- E m p t y --- Handle code = Handle(Builtins::builtin(Builtins::EmptyFunction)); empty_function->set_code(*code); Handle source = Factory::NewStringFromAscii(CStrVector("() {}")); Handle