// 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(bit_cast(&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(JSFunction::cast(cache_->get(i + 1))); return true; } } return false; } void Add(Vector name, Handle fun) { ASSERT(fun->IsBoilerplate()); 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, *fun); Script::cast(fun->shared()->script())->set_type(Smi::FromInt(type_)); } private: Script::Type type_; FixedArray* cache_; DISALLOW_COPY_AND_ASSIGN(SourceCodeCache); }; static SourceCodeCache natives_cache(Script::TYPE_NATIVE); 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); } bool Bootstrapper::NativesCacheLookup(Vector name, Handle* handle) { return natives_cache.Lookup(name, handle); } void Bootstrapper::NativesCacheAdd(Vector name, Handle fun) { natives_cache.Add(name, fun); } void Bootstrapper::Initialize(bool create_heap_objects) { natives_cache.Initialize(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; } natives_cache.Initialize(false); // Yes, symmetrical extensions_cache.Initialize(false); } // Pending fixups are code positions that refer to builtin code // objects that were not available at the time the code was generated. // The pending list is processed whenever an environment has been // created. class PendingFixups : public AllStatic { public: static void Add(Code* code, MacroAssembler* masm); static bool Process(Handle builtins); static void Iterate(ObjectVisitor* v); private: static List code_; static List name_; static List pc_; static List flags_; static void Clear(); }; List PendingFixups::code_(0); List PendingFixups::name_(0); List PendingFixups::pc_(0); List PendingFixups::flags_(0); void PendingFixups::Add(Code* code, MacroAssembler* masm) { // Note this code is not only called during bootstrapping. List* unresolved = masm->unresolved(); int n = unresolved->length(); for (int i = 0; i < n; i++) { const char* name = unresolved->at(i).name; code_.Add(code); name_.Add(name); pc_.Add(unresolved->at(i).pc); flags_.Add(unresolved->at(i).flags); LOG(StringEvent("unresolved", name)); } } bool PendingFixups::Process(Handle builtins) { HandleScope scope; // NOTE: Extra fixups may be added to the list during the iteration // due to lazy compilation of functions during the processing. Do not // cache the result of getting the length of the code list. for (int i = 0; i < code_.length(); i++) { const char* name = name_[i]; uint32_t flags = flags_[i]; Handle symbol = Factory::LookupAsciiSymbol(name); Object* o = builtins->GetProperty(*symbol); #ifdef DEBUG if (!o->IsJSFunction()) { V8_Fatal(__FILE__, __LINE__, "Cannot resolve call to builtin %s", name); } #endif Handle f = Handle(JSFunction::cast(o)); // Make sure the number of parameters match the formal parameter count. int argc = Bootstrapper::FixupFlagsArgumentsCount::decode(flags); USE(argc); ASSERT(f->shared()->formal_parameter_count() == argc); if (!f->is_compiled()) { // Do lazy compilation and check for stack overflows. if (!CompileLazy(f, CLEAR_EXCEPTION)) { Clear(); return false; } } Code* code = Code::cast(code_[i]); Address pc = code->instruction_start() + pc_[i]; RelocInfo target(pc, RelocInfo::CODE_TARGET, 0); bool use_code_object = Bootstrapper::FixupFlagsUseCodeObject::decode(flags); if (use_code_object) { target.set_target_object(f->code()); } else { target.set_target_address(f->code()->instruction_start()); } LOG(StringEvent("resolved", name)); } Clear(); // TODO(1240818): We should probably try to avoid doing this for all // the V8 builtin JS files. It should only happen after running // runtime.js - just like there shouldn't be any fixups left after // that. for (int i = 0; i < Builtins::NumberOfJavaScriptBuiltins(); i++) { Builtins::JavaScript id = static_cast(i); Handle name = Factory::LookupAsciiSymbol(Builtins::GetName(id)); JSFunction* function = JSFunction::cast(builtins->GetProperty(*name)); builtins->set_javascript_builtin(id, function); } return true; } void PendingFixups::Clear() { code_.Clear(); name_.Clear(); pc_.Clear(); flags_.Clear(); } void PendingFixups::Iterate(ObjectVisitor* v) { if (!code_.is_empty()) { v->VisitPointers(&code_[0], &code_[0] + code_.length()); } } 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_; } static Genesis* current() { return current_; } // Support for thread preemption. static int ArchiveSpacePerThread(); static char* ArchiveState(char* to); static char* RestoreState(char* from); 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_; static Genesis* current_; Handle global_context() { return global_context_; } void CreateRoots(v8::Handle global_template, Handle global_object); void InstallNativeFunctions(); bool InstallNatives(); bool InstallExtensions(v8::ExtensionConfiguration* extensions); bool InstallExtension(const char* name); bool InstallExtension(v8::RegisteredExtension* current); bool InstallSpecialObjects(); 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(); void AddSpecialFunction(Handle prototype, const char* name, Handle code); void BuildSpecialFunctionTable(); static bool CompileBuiltin(int index); static bool CompileNative(Vector name, Handle source); static bool CompileScriptCached(Vector name, Handle source, SourceCodeCache* cache, v8::Extension* extension, bool use_runtime_context); Handle result_; }; Genesis* Genesis::current_ = NULL; void Bootstrapper::Iterate(ObjectVisitor* v) { natives_cache.Iterate(v); v->Synchronize("NativesCache"); extensions_cache.Iterate(v); v->Synchronize("Extensions"); PendingFixups::Iterate(v); v->Synchronize("PendingFixups"); } // While setting up the environment, we collect code positions that // need to be patched before we can run any code in the environment. void Bootstrapper::AddFixup(Code* code, MacroAssembler* masm) { PendingFixups::Add(code, masm); } bool Bootstrapper::IsActive() { return Genesis::current() != NULL; } Handle Bootstrapper::CreateEnvironment( Handle global_object, v8::Handle global_template, v8::ExtensionConfiguration* extensions) { Genesis genesis(global_object, global_template, extensions); return genesis.result(); } 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()); } Genesis::~Genesis() { ASSERT(current_ == this); current_ = previous_; } 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; } void Genesis::CreateRoots(v8::Handle global_template, Handle global_object) { HandleScope scope; // Allocate the global context FixedArray first and then patch the // closure and extension object later (we need the empty function // and the global object, but in order to create those, we need the // global context). global_context_ = Handle::cast( GlobalHandles::Create(*Factory::NewGlobalContext())); Top::set_context(*global_context()); // Allocate the message listeners object. v8::NeanderArray listeners; global_context()->set_message_listeners(*listeners.value()); // 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