// Copyright 2014 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. #ifndef V8_HEAP_FACTORY_H_ #define V8_HEAP_FACTORY_H_ // Clients of this interface shouldn't depend on lots of heap internals. // Do not include anything from src/heap here! #include "src/base/strings.h" #include "src/base/vector.h" #include "src/baseline/baseline.h" #include "src/builtins/builtins.h" #include "src/common/globals.h" #include "src/execution/messages.h" #include "src/handles/handles.h" #include "src/handles/maybe-handles.h" #include "src/heap/factory-base.h" #include "src/heap/heap.h" #include "src/objects/code.h" #include "src/objects/dictionary.h" #include "src/objects/js-array.h" #include "src/objects/js-regexp.h" #include "src/objects/shared-function-info.h" #include "src/objects/string.h" namespace v8 { namespace internal { // Forward declarations. class AliasedArgumentsEntry; class ObjectBoilerplateDescription; class BasicBlockProfilerData; class BreakPoint; class BreakPointInfo; class CallableTask; class CallbackTask; class CallHandlerInfo; class CallSiteInfo; class Expression; class EmbedderDataArray; class ArrayBoilerplateDescription; class CoverageInfo; class DebugInfo; class EnumCache; class FreshlyAllocatedBigInt; class Isolate; class JSArrayBufferView; class JSDataView; class JSGeneratorObject; class JSMap; class JSMapIterator; class JSModuleNamespace; class JSPromise; class JSProxy; class JSSet; class JSSetIterator; class JSTypedArray; class JSWeakMap; class LoadHandler; class NativeContext; class PromiseResolveThenableJobTask; class RegExpMatchInfo; class ScriptContextTable; class SourceTextModule; class StackFrameInfo; class StringSet; class StoreHandler; class SyntheticModule; class TemplateObjectDescription; class WasmCapiFunctionData; class WasmExportedFunctionData; class WasmJSFunctionData; class WeakCell; #if V8_ENABLE_WEBASSEMBLY namespace wasm { class ArrayType; class StructType; class WasmValue; } // namespace wasm #endif enum class SharedFlag : uint8_t; enum class InitializedFlag : uint8_t; enum FunctionMode { kWithNameBit = 1 << 0, kWithWritablePrototypeBit = 1 << 1, kWithReadonlyPrototypeBit = 1 << 2, kWithPrototypeBits = kWithWritablePrototypeBit | kWithReadonlyPrototypeBit, // Without prototype. FUNCTION_WITHOUT_PROTOTYPE = 0, METHOD_WITH_NAME = kWithNameBit, // With writable prototype. FUNCTION_WITH_WRITEABLE_PROTOTYPE = kWithWritablePrototypeBit, FUNCTION_WITH_NAME_AND_WRITEABLE_PROTOTYPE = kWithWritablePrototypeBit | kWithNameBit, // With readonly prototype. FUNCTION_WITH_READONLY_PROTOTYPE = kWithReadonlyPrototypeBit, FUNCTION_WITH_NAME_AND_READONLY_PROTOTYPE = kWithReadonlyPrototypeBit | kWithNameBit, }; enum class NumberCacheMode { kIgnore, kSetOnly, kBoth }; // Interface for handle based allocation. class V8_EXPORT_PRIVATE Factory : public FactoryBase { public: inline ReadOnlyRoots read_only_roots() const; Handle NewOddball(Handle map, const char* to_string, Handle to_number, const char* type_of, byte kind); // Marks self references within code generation. Handle NewSelfReferenceMarker(); // Marks references to a function's basic-block usage counters array during // code generation. Handle NewBasicBlockCountersMarker(); // Allocates a property array initialized with undefined values. Handle NewPropertyArray( int length, AllocationType allocation = AllocationType::kYoung); // Tries allocating a fixed array initialized with undefined values. // In case of an allocation failure (OOM) an empty handle is returned. // The caller has to manually signal an // v8::internal::Heap::FatalProcessOutOfMemory typically by calling // NewFixedArray as a fallback. V8_WARN_UNUSED_RESULT MaybeHandle TryNewFixedArray( int length, AllocationType allocation = AllocationType::kYoung); // Allocates a closure feedback cell array whose feedback cells are // initialized with undefined values. Handle NewClosureFeedbackCellArray(int num_slots); // Allocates a feedback vector whose slots are initialized with undefined // values. Handle NewFeedbackVector( Handle shared, Handle closure_feedback_cell_array); // Allocates a clean embedder data array with given capacity. Handle NewEmbedderDataArray(int length); // Allocate a new fixed double array with hole values. Handle NewFixedDoubleArrayWithHoles(int size); // Allocates a NameDictionary with an internal capacity calculated such that // |at_least_space_for| entries can be added without reallocating. Handle NewNameDictionary(int at_least_space_for); // Allocates an OrderedNameDictionary of the given capacity. This guarantees // that |capacity| entries can be added without reallocating. Handle NewOrderedNameDictionary( int capacity = OrderedNameDictionary::kInitialCapacity); Handle NewOrderedHashSet(); Handle NewOrderedHashMap(); Handle NewSmallOrderedHashSet( int capacity = kSmallOrderedHashSetMinCapacity, AllocationType allocation = AllocationType::kYoung); Handle NewSmallOrderedHashMap( int capacity = kSmallOrderedHashMapMinCapacity, AllocationType allocation = AllocationType::kYoung); Handle NewSmallOrderedNameDictionary( int capacity = kSmallOrderedHashMapMinCapacity, AllocationType allocation = AllocationType::kYoung); Handle CreateCanonicalEmptySwissNameDictionary(); // Create a new PrototypeInfo struct. Handle NewPrototypeInfo(); // Create a new EnumCache struct. Handle NewEnumCache(Handle keys, Handle indices); // Create a new Tuple2 struct. Handle NewTuple2(Handle value1, Handle value2, AllocationType allocation); // Create a new PropertyDescriptorObject struct. Handle NewPropertyDescriptorObject(); // Finds the internalized copy for string in the string table. // If not found, a new string is added to the table and returned. Handle InternalizeUtf8String(const base::Vector& str); Handle InternalizeUtf8String(const char* str) { return InternalizeUtf8String(base::CStrVector(str)); } // Import InternalizeString overloads from base class. using FactoryBase::InternalizeString; Handle InternalizeString(base::Vector str, bool convert_encoding = false) { return InternalizeString(base::Vector::cast(str)); } template Handle InternalizeString(Handle, int from, int length, bool convert_encoding = false); // Internalized strings are created in the old generation (data space). inline Handle InternalizeString(Handle string); inline Handle InternalizeName(Handle name); // String creation functions. Most of the string creation functions take // an AllocationType argument to optionally request that they be // allocated in the old generation. Otherwise the default is // AllocationType::kYoung. // // Creates a new String object. There are two String encodings: one-byte and // two-byte. One should choose between the three string factory functions // based on the encoding of the string buffer that the string is // initialized from. // - ...FromOneByte initializes the string from a buffer that is Latin1 // encoded (it does not check that the buffer is Latin1 encoded) and // the result will be Latin1 encoded. // - ...FromUtf8 initializes the string from a buffer that is UTF-8 // encoded. If the characters are all ASCII characters, the result // will be Latin1 encoded, otherwise it will converted to two-byte. // - ...FromTwoByte initializes the string from a buffer that is two-byte // encoded. If the characters are all Latin1 characters, the result // will be converted to Latin1, otherwise it will be left as two-byte. // // One-byte strings are pretenured when used as keys in the SourceCodeCache. V8_WARN_UNUSED_RESULT MaybeHandle NewStringFromOneByte( const base::Vector& str, AllocationType allocation = AllocationType::kYoung); template inline Handle NewStringFromStaticChars( const char (&str)[N], AllocationType allocation = AllocationType::kYoung) { DCHECK_EQ(N, strlen(str) + 1); return NewStringFromOneByte(base::StaticOneByteVector(str), allocation) .ToHandleChecked(); } inline Handle NewStringFromAsciiChecked( const char* str, AllocationType allocation = AllocationType::kYoung) { return NewStringFromOneByte(base::OneByteVector(str), allocation) .ToHandleChecked(); } // UTF8 strings are pretenured when used for regexp literal patterns and // flags in the parser. V8_WARN_UNUSED_RESULT MaybeHandle NewStringFromUtf8( const base::Vector& str, AllocationType allocation = AllocationType::kYoung); V8_WARN_UNUSED_RESULT MaybeHandle NewStringFromUtf8SubString( Handle str, int begin, int end, AllocationType allocation = AllocationType::kYoung); V8_WARN_UNUSED_RESULT MaybeHandle NewStringFromTwoByte( const base::Vector& str, AllocationType allocation = AllocationType::kYoung); V8_WARN_UNUSED_RESULT MaybeHandle NewStringFromTwoByte( const ZoneVector* str, AllocationType allocation = AllocationType::kYoung); Handle NewJSStringIterator(Handle string); Handle NewInternalizedStringImpl(Handle string, int chars, uint32_t hash_field); // Compute the internalization strategy for the input string. // // Old-generation sequential strings can be internalized by mutating their map // and return kInPlace, along with the matching internalized string map for // string stored in internalized_map. // // Internalized strings return kAlreadyTransitioned. // // All other strings are internalized by flattening and copying and return // kCopy. V8_WARN_UNUSED_RESULT StringTransitionStrategy ComputeInternalizationStrategyForString(Handle string, MaybeHandle* internalized_map); // Creates an internalized copy of an external string. |string| must be // of type StringClass. template Handle InternalizeExternalString(Handle string); // Compute the sharing strategy for the input string. // // Old-generation sequential and thin strings can be shared by mutating their // map and return kInPlace, along with the matching shared string map for the // string stored in shared_map. // // Already-shared strings return kAlreadyTransitioned. // // All other strings are shared by flattening and copying into a sequential // string then sharing that sequential string, and return kCopy. V8_WARN_UNUSED_RESULT StringTransitionStrategy ComputeSharingStrategyForString(Handle string, MaybeHandle* shared_map); // Creates a single character string where the character has given code. // A cache is used for Latin1 codes. Handle LookupSingleCharacterStringFromCode(uint16_t code); // Create or lookup a single characters tring made up of a utf16 surrogate // pair. Handle NewSurrogatePairString(uint16_t lead, uint16_t trail); // Create a new string object which holds a proper substring of a string. Handle NewProperSubString(Handle str, int begin, int end); // Create a new string object which holds a substring of a string. inline Handle NewSubString(Handle str, int begin, int end); // Creates a new external String object. There are two String encodings // in the system: one-byte and two-byte. Unlike other String types, it does // not make sense to have a UTF-8 factory function for external strings, // because we cannot change the underlying buffer. Note that these strings // are backed by a string resource that resides outside the V8 heap. V8_WARN_UNUSED_RESULT MaybeHandle NewExternalStringFromOneByte( const ExternalOneByteString::Resource* resource); V8_WARN_UNUSED_RESULT MaybeHandle NewExternalStringFromTwoByte( const ExternalTwoByteString::Resource* resource); // Create a symbol in old or read-only space. Handle NewSymbol(AllocationType allocation = AllocationType::kOld); Handle NewPrivateSymbol( AllocationType allocation = AllocationType::kOld); Handle NewPrivateNameSymbol(Handle name); // Create a global (but otherwise uninitialized) context. Handle NewNativeContext(); // Create a script context. Handle NewScriptContext(Handle outer, Handle scope_info); // Create an empty script context table. Handle NewScriptContextTable(); // Create a module context. Handle NewModuleContext(Handle module, Handle outer, Handle scope_info); // Create a function or eval context. Handle NewFunctionContext(Handle outer, Handle scope_info); // Create a catch context. Handle NewCatchContext(Handle previous, Handle scope_info, Handle thrown_object); // Create a 'with' context. Handle NewWithContext(Handle previous, Handle scope_info, Handle extension); Handle NewDebugEvaluateContext(Handle previous, Handle scope_info, Handle extension, Handle wrapped); // Create a block context. Handle NewBlockContext(Handle previous, Handle scope_info); // Create a context that's used by builtin functions. // // These are similar to function context but don't have a previous // context or any scope info. These are used to store spec defined // context values. Handle NewBuiltinContext(Handle native_context, int length); Handle NewAliasedArgumentsEntry( int aliased_context_slot); Handle NewAccessorInfo(); Handle NewErrorStackData( Handle call_site_infos_or_formatted_stack, Handle limit_or_stack_frame_infos); Handle