gen-postmortem-metadata.py 28.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#!/usr/bin/env python

#
# 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.
#

#
# Emits a C++ file to be compiled and linked into libv8 to support postmortem
# debugging tools.  Most importantly, this tool emits constants describing V8
# internals:
#
#    v8dbg_type_CLASS__TYPE = VALUE             Describes class type values
#    v8dbg_class_CLASS__FIELD__TYPE = OFFSET    Describes class fields
#    v8dbg_parent_CLASS__PARENT                 Describes class hierarchy
#    v8dbg_frametype_NAME = VALUE               Describes stack frame values
#    v8dbg_off_fp_NAME = OFFSET                 Frame pointer offsets
#    v8dbg_prop_NAME = OFFSET                   Object property offsets
#    v8dbg_NAME = VALUE                         Miscellaneous values
#
# These constants are declared as global integers so that they'll be present in
# the generated libv8 binary.
#

49 50 51
# for py2/py3 compatibility
from __future__ import print_function

52
import io
53 54 55 56
import re
import sys

#
57 58
# Miscellaneous constants such as tags and masks used for object identification,
# enumeration values used as indexes in internal tables, etc..
59 60 61
#
consts_misc = [
    { 'name': 'FirstNonstringType',     'value': 'FIRST_NONSTRING_TYPE' },
62 63
    { 'name': 'APIObjectType',          'value': 'JS_API_OBJECT_TYPE' },
    { 'name': 'SpecialAPIObjectType',   'value': 'JS_SPECIAL_API_OBJECT_TYPE' },
64

65 66 67
    { 'name': 'FirstContextType',     'value': 'FIRST_CONTEXT_TYPE' },
    { 'name': 'LastContextType',     'value': 'LAST_CONTEXT_TYPE' },

68 69 70 71 72
    { 'name': 'IsNotStringMask',        'value': 'kIsNotStringMask' },
    { 'name': 'StringTag',              'value': 'kStringTag' },

    { 'name': 'StringEncodingMask',     'value': 'kStringEncodingMask' },
    { 'name': 'TwoByteStringTag',       'value': 'kTwoByteStringTag' },
73
    { 'name': 'OneByteStringTag',       'value': 'kOneByteStringTag' },
74 75 76 77 78 79

    { 'name': 'StringRepresentationMask',
        'value': 'kStringRepresentationMask' },
    { 'name': 'SeqStringTag',           'value': 'kSeqStringTag' },
    { 'name': 'ConsStringTag',          'value': 'kConsStringTag' },
    { 'name': 'ExternalStringTag',      'value': 'kExternalStringTag' },
80
    { 'name': 'SlicedStringTag',        'value': 'kSlicedStringTag' },
81
    { 'name': 'ThinStringTag',          'value': 'kThinStringTag' },
82 83 84 85 86 87

    { 'name': 'HeapObjectTag',          'value': 'kHeapObjectTag' },
    { 'name': 'HeapObjectTagMask',      'value': 'kHeapObjectTagMask' },
    { 'name': 'SmiTag',                 'value': 'kSmiTag' },
    { 'name': 'SmiTagMask',             'value': 'kSmiTagMask' },
    { 'name': 'SmiValueShift',          'value': 'kSmiTagSize' },
88
    { 'name': 'SmiShiftSize',           'value': 'kSmiShiftSize' },
89 90 91 92
    { 'name': 'SystemPointerSize',      'value': 'kSystemPointerSize' },
    { 'name': 'SystemPointerSizeLog2',  'value': 'kSystemPointerSizeLog2' },
    { 'name': 'TaggedSize',             'value': 'kTaggedSize' },
    { 'name': 'TaggedSizeLog2',         'value': 'kTaggedSizeLog2' },
93

94 95 96 97
    { 'name': 'OddballFalse',           'value': 'Oddball::kFalse' },
    { 'name': 'OddballTrue',            'value': 'Oddball::kTrue' },
    { 'name': 'OddballTheHole',         'value': 'Oddball::kTheHole' },
    { 'name': 'OddballNull',            'value': 'Oddball::kNull' },
98
    { 'name': 'OddballArgumentsMarker', 'value': 'Oddball::kArgumentsMarker' },
99 100 101 102 103
    { 'name': 'OddballUndefined',       'value': 'Oddball::kUndefined' },
    { 'name': 'OddballUninitialized',   'value': 'Oddball::kUninitialized' },
    { 'name': 'OddballOther',           'value': 'Oddball::kOther' },
    { 'name': 'OddballException',       'value': 'Oddball::kException' },

104 105 106 107 108 109
    { 'name': 'prop_kind_Data',
        'value': 'kData' },
    { 'name': 'prop_kind_Accessor',
        'value': 'kAccessor' },
    { 'name': 'prop_kind_mask',
        'value': 'PropertyDetails::KindField::kMask' },
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    { 'name': 'prop_location_Descriptor',
        'value': 'kDescriptor' },
    { 'name': 'prop_location_Field',
        'value': 'kField' },
    { 'name': 'prop_location_mask',
        'value': 'PropertyDetails::LocationField::kMask' },
    { 'name': 'prop_location_shift',
        'value': 'PropertyDetails::LocationField::kShift' },
    { 'name': 'prop_attributes_NONE', 'value': 'NONE' },
    { 'name': 'prop_attributes_READ_ONLY', 'value': 'READ_ONLY' },
    { 'name': 'prop_attributes_DONT_ENUM', 'value': 'DONT_ENUM' },
    { 'name': 'prop_attributes_DONT_DELETE', 'value': 'DONT_DELETE' },
    { 'name': 'prop_attributes_mask',
        'value': 'PropertyDetails::AttributesField::kMask' },
    { 'name': 'prop_attributes_shift',
        'value': 'PropertyDetails::AttributesField::kShift' },
126 127 128 129
    { 'name': 'prop_index_mask',
        'value': 'PropertyDetails::FieldIndexField::kMask' },
    { 'name': 'prop_index_shift',
        'value': 'PropertyDetails::FieldIndexField::kShift' },
130 131 132 133 134 135 136 137 138 139 140 141
    { 'name': 'prop_representation_mask',
        'value': 'PropertyDetails::RepresentationField::kMask' },
    { 'name': 'prop_representation_shift',
        'value': 'PropertyDetails::RepresentationField::kShift' },
    { 'name': 'prop_representation_smi',
        'value': 'Representation::Kind::kSmi' },
    { 'name': 'prop_representation_double',
        'value': 'Representation::Kind::kDouble' },
    { 'name': 'prop_representation_heapobject',
        'value': 'Representation::Kind::kHeapObject' },
    { 'name': 'prop_representation_tagged',
        'value': 'Representation::Kind::kTagged' },
142

143
    { 'name': 'prop_desc_key',
144
        'value': 'DescriptorArray::kEntryKeyIndex' },
145
    { 'name': 'prop_desc_details',
146
        'value': 'DescriptorArray::kEntryDetailsIndex' },
147
    { 'name': 'prop_desc_value',
148
        'value': 'DescriptorArray::kEntryValueIndex' },
149
    { 'name': 'prop_desc_size',
150
        'value': 'DescriptorArray::kEntrySize' },
151

152
    { 'name': 'elements_fast_holey_elements',
153
        'value': 'HOLEY_ELEMENTS' },
154
    { 'name': 'elements_fast_elements',
155
        'value': 'PACKED_ELEMENTS' },
156 157 158 159
    { 'name': 'elements_dictionary_elements',
        'value': 'DICTIONARY_ELEMENTS' },

    { 'name': 'bit_field2_elements_kind_mask',
160
        'value': 'Map::Bits2::ElementsKindBits::kMask' },
161
    { 'name': 'bit_field2_elements_kind_shift',
162
        'value': 'Map::Bits2::ElementsKindBits::kShift' },
163
    { 'name': 'bit_field3_is_dictionary_map_shift',
164
        'value': 'Map::Bits3::IsDictionaryMapBit::kShift' },
165
    { 'name': 'bit_field3_number_of_own_descriptors_mask',
166
        'value': 'Map::Bits3::NumberOfOwnDescriptorsBits::kMask' },
167
    { 'name': 'bit_field3_number_of_own_descriptors_shift',
168
        'value': 'Map::Bits3::NumberOfOwnDescriptorsBits::kShift' },
169 170
    { 'name': 'class_Map__instance_descriptors_offset',
        'value': 'Map::kInstanceDescriptorsOffset' },
171

172 173
    { 'name': 'off_fp_context_or_frame_type',
        'value': 'CommonFrameConstants::kContextOrFrameTypeOffset'},
174 175
    { 'name': 'off_fp_context',
        'value': 'StandardFrameConstants::kContextOffset' },
176 177
    { 'name': 'off_fp_constant_pool',
        'value': 'StandardFrameConstants::kConstantPoolOffset' },
178
    { 'name': 'off_fp_function',
179
        'value': 'StandardFrameConstants::kFunctionOffset' },
180
    { 'name': 'off_fp_args',
181
        'value': 'StandardFrameConstants::kFixedFrameSizeAboveFp' },
182 183 184 185 186 187 188

    { 'name': 'scopeinfo_idx_nparams',
        'value': 'ScopeInfo::kParameterCount' },
    { 'name': 'scopeinfo_idx_ncontextlocals',
        'value': 'ScopeInfo::kContextLocalCount' },
    { 'name': 'scopeinfo_idx_first_vars',
        'value': 'ScopeInfo::kVariablePartIndex' },
189

190 191 192 193
    { 'name': 'jsarray_buffer_was_detached_mask',
        'value': 'JSArrayBuffer::WasDetachedBit::kMask' },
    { 'name': 'jsarray_buffer_was_detached_shift',
        'value': 'JSArrayBuffer::WasDetachedBit::kShift' },
194

195 196
    { 'name': 'context_idx_scope_info',
        'value': 'Context::SCOPE_INFO_INDEX' },
197 198 199 200
    { 'name': 'context_idx_prev',
        'value': 'Context::PREVIOUS_INDEX' },
    { 'name': 'context_min_slots',
        'value': 'Context::MIN_CONTEXT_SLOTS' },
201 202
    { 'name': 'native_context_embedder_data_offset',
        'value': 'Internals::kNativeContextEmbedderDataOffset' },
203

204 205 206 207 208

    { 'name': 'namedictionaryshape_prefix_size',
        'value': 'NameDictionaryShape::kPrefixSize' },
    { 'name': 'namedictionaryshape_entry_size',
        'value': 'NameDictionaryShape::kEntrySize' },
209 210
    { 'name': 'globaldictionaryshape_entry_size',
        'value': 'GlobalDictionaryShape::kEntrySize' },
211 212 213 214

    { 'name': 'namedictionary_prefix_start_index',
        'value': 'NameDictionary::kPrefixStartIndex' },

215 216 217 218
    { 'name': 'numberdictionaryshape_prefix_size',
        'value': 'NumberDictionaryShape::kPrefixSize' },
    { 'name': 'numberdictionaryshape_entry_size',
        'value': 'NumberDictionaryShape::kEntrySize' },
219 220 221 222 223

    { 'name': 'simplenumberdictionaryshape_prefix_size',
        'value': 'SimpleNumberDictionaryShape::kPrefixSize' },
    { 'name': 'simplenumberdictionaryshape_entry_size',
        'value': 'SimpleNumberDictionaryShape::kEntrySize' },
224 225

    { 'name': 'type_JSError__JS_ERROR_TYPE', 'value': 'JS_ERROR_TYPE' },
226 227 228 229
];

#
# The following useful fields are missing accessors, so we define fake ones.
230 231 232 233 234
# Please note that extra accessors should _only_ be added to expose offsets that
# can be used to access actual V8 objects' properties. They should not be added
# for exposing other values. For instance, enumeration values or class'
# constants should be exposed by adding an entry in the "consts_misc" table, not
# in this "extras_accessors" table.
235 236
#
extras_accessors = [
237
    'JSFunction, context, Context, kContextOffset',
238
    'JSFunction, shared, SharedFunctionInfo, kSharedFunctionInfoOffset',
239 240
    'HeapObject, map, Map, kMapOffset',
    'JSObject, elements, Object, kElementsOffset',
241
    'JSObject, internal_fields, uintptr_t, kHeaderSize',
242
    'FixedArray, data, uintptr_t, kHeaderSize',
243
    'JSArrayBuffer, backing_store, uintptr_t, kBackingStoreOffset',
244 245 246
    'JSArrayBuffer, byte_length, size_t, kByteLengthOffset',
    'JSArrayBufferView, byte_length, size_t, kByteLengthOffset',
    'JSArrayBufferView, byte_offset, size_t, kByteOffsetOffset',
247 248
    'JSDate, value, Object, kValueOffset',
    'JSRegExp, source, Object, kSourceOffset',
249
    'JSTypedArray, external_pointer, uintptr_t, kExternalPointerOffset',
250
    'JSTypedArray, length, Object, kLengthOffset',
251 252
    'Map, instance_size_in_words, char, kInstanceSizeInWordsOffset',
    'Map, inobject_properties_start_or_constructor_function_index, char, kInObjectPropertiesStartOrConstructorFunctionIndexOffset',
253
    'Map, instance_type, uint16_t, kInstanceTypeOffset',
254 255
    'Map, bit_field, char, kBitFieldOffset',
    'Map, bit_field2, char, kBitField2Offset',
256
    'Map, bit_field3, int, kBitField3Offset',
257 258
    'Map, prototype, Object, kPrototypeOffset',
    'Oddball, kind_offset, int, kKindOffset',
259 260
    'HeapNumber, value, double, kValueOffset',
    'ExternalString, resource, Object, kResourceOffset',
261
    'SeqOneByteString, chars, char, kHeaderSize',
262
    'SeqTwoByteString, chars, char, kHeaderSize',
263
    'UncompiledData, inferred_name, String, kInferredNameOffset',
264 265 266
    'UncompiledData, start_position, int32_t, kStartPositionOffset',
    'UncompiledData, end_position, int32_t, kEndPositionOffset',
    'SharedFunctionInfo, raw_function_token_offset, int16_t, kFunctionTokenOffsetOffset',
267
    'SharedFunctionInfo, internal_formal_parameter_count, uint16_t, kFormalParameterCountOffset',
268
    'SharedFunctionInfo, flags, int, kFlagsOffset',
269
    'SharedFunctionInfo, length, uint16_t, kLengthOffset',
270
    'SlicedString, parent, String, kParentOffset',
271 272
    'Code, instruction_start, uintptr_t, kHeaderSize',
    'Code, instruction_size, int, kInstructionSizeOffset',
273
    'String, length, int32_t, kLengthOffset',
274
    'DescriptorArray, header_size, uintptr_t, kHeaderSize',
275 276 277 278
    'ConsString, first, String, kFirstOffset',
    'ConsString, second, String, kSecondOffset',
    'SlicedString, offset, SMI, kOffsetOffset',
    'ThinString, actual, String, kActualOffset',
279
    'Symbol, name, Object, kDescriptionOffset',
280 281 282 283 284 285 286 287 288
];

#
# The following is a whitelist of classes we expect to find when scanning the
# source code. This list is not exhaustive, but it's still useful to identify
# when this script gets out of sync with the source. See load_objects().
#
expected_classes = [
    'ConsString', 'FixedArray', 'HeapNumber', 'JSArray', 'JSFunction',
289
    'JSObject', 'JSRegExp', 'JSPrimitiveWrapper', 'Map', 'Oddball', 'Script',
290 291
    'SeqOneByteString', 'SharedFunctionInfo', 'ScopeInfo', 'JSPromise',
    'DescriptorArray'
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
];


#
# The following structures store high-level representations of the structures
# for which we're going to emit descriptive constants.
#
types = {};             # set of all type names
typeclasses = {};       # maps type names to corresponding class names
klasses = {};           # known classes, including parents
fields = [];            # field declarations

header = '''
/*
 * This file is generated by %s.  Do not edit directly.
 */

309
#include "src/init/v8.h"
310 311
#include "src/execution/frames.h"
#include "src/execution/frames-inl.h" /* for architecture-specific frame constants */
312 313
#include "src/objects/contexts.h"
#include "src/objects/objects.h"
314
#include "src/objects/data-handler.h"
315
#include "src/objects/js-promise.h"
316
#include "src/objects/js-regexp-string-iterator.h"
317

318 319
namespace v8 {
namespace internal {
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

extern "C" {

/* stack frame constants */
#define FRAME_CONST(value, klass)       \
    int v8dbg_frametype_##klass = StackFrame::value;

STACK_FRAME_TYPE_LIST(FRAME_CONST)

#undef FRAME_CONST

''' % sys.argv[0];

footer = '''
}
335 336 337

}
}
338 339
'''

340 341 342 343 344 345 346 347 348 349 350 351 352 353
#
# Get the base class
#
def get_base_class(klass):
        if (klass == 'Object'):
                return klass;

        if (not (klass in klasses)):
                return None;

        k = klasses[klass];

        return get_base_class(k['parent']);

354
#
355
# Loads class hierarchy and type information from "objects.h" etc.
356 357 358 359 360 361 362 363 364
#
def load_objects():
        #
        # Construct a dictionary for the classes we're sure should be present.
        #
        checktypes = {};
        for klass in expected_classes:
                checktypes[klass] = True;

365 366 367 368 369 370 371 372 373 374 375 376 377

        for filename in sys.argv[2:]:
                if not filename.endswith("-inl.h"):
                        load_objects_from_file(filename, checktypes)

        if (len(checktypes) > 0):
                for klass in checktypes:
                        print('error: expected class \"%s\" not found' % klass);

                sys.exit(1);


def load_objects_from_file(objfilename, checktypes):
378
        objfile = io.open(objfilename, 'r', encoding='utf-8');
379
        in_insttype = False;
380
        in_torque_insttype = False
381
        in_torque_fulldef = False
382 383

        typestr = '';
384
        torque_typestr = ''
385
        torque_fulldefstr = ''
386
        uncommented_file = ''
387

388
        #
389 390 391 392
        # Iterate the header file line-by-line to collect type and class
        # information. For types, we accumulate a string representing the entire
        # InstanceType enum definition and parse it later because it's easier to
        # do so without the embedded newlines.
393 394
        #
        for line in objfile:
395
                if (line.startswith('enum InstanceType : uint16_t {')):
396 397 398
                        in_insttype = True;
                        continue;

399 400 401 402
                if (line.startswith('#define TORQUE_ASSIGNED_INSTANCE_TYPE_LIST')):
                        in_torque_insttype = True
                        continue

403 404 405 406
                if (line.startswith('#define TORQUE_INSTANCE_CHECKERS_SINGLE_FULLY_DEFINED')):
                        in_torque_fulldef = True
                        continue

407 408 409 410
                if (in_insttype and line.startswith('};')):
                        in_insttype = False;
                        continue;

411 412 413 414
                if (in_torque_insttype and (not line or line.isspace())):
                          in_torque_insttype = False
                          continue

415 416 417 418
                if (in_torque_fulldef and (not line or line.isspace())):
                          in_torque_fulldef = False
                          continue

419
                line = re.sub('//.*', '', line.strip());
420 421 422 423 424

                if (in_insttype):
                        typestr += line;
                        continue;

425 426 427 428
                if (in_torque_insttype):
                        torque_typestr += line
                        continue

429 430 431 432
                if (in_torque_fulldef):
                        torque_fulldefstr += line
                        continue

433 434 435 436
                uncommented_file += '\n' + line

        for match in re.finditer(r'\nclass(?:\s+V8_EXPORT(?:_PRIVATE)?)?'
                                 r'\s+(\w[^:;]*)'
437
                                 r'(?:: public (\w[^{]*))?\s*{\s*',
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
                                 uncommented_file):
                klass = match.group(1).strip();
                pklass = match.group(2);
                if (pklass):
                        # Check for generated Torque class.
                        gen_match = re.match(
                            r'TorqueGenerated\w+\s*<\s*\w+,\s*(\w+)\s*>',
                            pklass)
                        if (gen_match):
                                pklass = gen_match.group(1)
                        # Strip potential template arguments from parent
                        # class.
                        match = re.match(r'(\w+)(<.*>)?', pklass.strip());
                        pklass = match.group(1).strip();
                klasses[klass] = { 'parent': pklass };
453 454 455 456 457 458 459

        #
        # Process the instance type declaration.
        #
        entries = typestr.split(',');
        for entry in entries:
                types[re.sub('\s*=.*', '', entry).lstrip()] = True;
460 461 462
        entries = torque_typestr.split('\\')
        for entry in entries:
                types[re.sub(r' *V\(|\) *', '', entry)] = True
463 464 465 466 467 468 469 470 471 472 473 474
        entries = torque_fulldefstr.split('\\')
        for entry in entries:
                entry = entry.strip()
                if not entry:
                    continue
                idx = entry.find('(');
                rest = entry[idx + 1: len(entry) - 1];
                args = re.split('\s*,\s*', rest);
                typename = args[0]
                typeconst = args[1]
                types[typeconst] = True
                typeclasses[typeconst] = typename
475 476 477 478 479 480 481 482
        #
        # Infer class names for each type based on a systematic transformation.
        # For example, "JS_FUNCTION_TYPE" becomes "JSFunction".  We find the
        # class for each type rather than the other way around because there are
        # fewer cases where one type maps to more than one class than the other
        # way around.
        #
        for type in types:
483
                usetype = type
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

                #
                # Remove the "_TYPE" suffix and then convert to camel case,
                # except that a "JS" prefix remains uppercase (as in
                # "JS_FUNCTION_TYPE" => "JSFunction").
                #
                if (not usetype.endswith('_TYPE')):
                        continue;

                usetype = usetype[0:len(usetype) - len('_TYPE')];
                parts = usetype.split('_');
                cctype = '';

                if (parts[0] == 'JS'):
                        cctype = 'JS';
                        start = 1;
                else:
                        cctype = '';
                        start = 0;

                for ii in range(start, len(parts)):
                        part = parts[ii];
                        cctype += part[0].upper() + part[1:].lower();

                #
                # Mapping string types is more complicated.  Both types and
                # class names for Strings specify a representation (e.g., Seq,
511
                # Cons, External, or Sliced) and an encoding (TwoByte/OneByte),
512 513 514
                # In the simplest case, both of these are explicit in both
                # names, as in:
                #
515
                #       EXTERNAL_ONE_BYTE_STRING_TYPE => ExternalOneByteString
516 517 518 519 520 521 522 523 524 525
                #
                # However, either the representation or encoding can be omitted
                # from the type name, in which case "Seq" and "TwoByte" are
                # assumed, as in:
                #
                #       STRING_TYPE => SeqTwoByteString
                #
                # Additionally, sometimes the type name has more information
                # than the class, as in:
                #
526
                #       CONS_ONE_BYTE_STRING_TYPE => ConsString
527 528 529 530 531 532 533 534 535 536
                #
                # To figure this out dynamically, we first check for a
                # representation and encoding and add them if they're not
                # present.  If that doesn't yield a valid class name, then we
                # strip out the representation.
                #
                if (cctype.endswith('String')):
                        if (cctype.find('Cons') == -1 and
                            cctype.find('External') == -1 and
                            cctype.find('Sliced') == -1):
537 538
                                if (cctype.find('OneByte') != -1):
                                        cctype = re.sub('OneByteString$',
539
                                            'SeqOneByteString', cctype);
540 541 542 543
                                else:
                                        cctype = re.sub('String$',
                                            'SeqString', cctype);

544
                        if (cctype.find('OneByte') == -1):
545 546 547 548
                                cctype = re.sub('String$', 'TwoByteString',
                                    cctype);

                        if (not (cctype in klasses)):
549
                                cctype = re.sub('OneByte', '', cctype);
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
                                cctype = re.sub('TwoByte', '', cctype);

                #
                # Despite all that, some types have no corresponding class.
                #
                if (cctype in klasses):
                        typeclasses[type] = cctype;
                        if (cctype in checktypes):
                                del checktypes[cctype];

#
# For a given macro call, pick apart the arguments and return an object
# describing the corresponding output constant.  See load_fields().
#
def parse_field(call):
        # Replace newlines with spaces.
        for ii in range(0, len(call)):
                if (call[ii] == '\n'):
                        call[ii] == ' ';

        idx = call.find('(');
        kind = call[0:idx];
        rest = call[idx + 1: len(call) - 1];
        args = re.split('\s*,\s*', rest);

        consts = [];

577 578 579 580 581 582 583 584
        klass = args[0];
        field = args[1];
        dtype = None
        offset = None
        if kind.startswith('WEAK_ACCESSORS'):
                dtype = 'weak'
                offset = args[2];
        elif not (kind.startswith('SMI_ACCESSORS') or kind.startswith('ACCESSORS_TO_SMI')):
585
                dtype = args[2].replace('<', '_').replace('>', '_')
586
                offset = args[3];
587 588 589
        else:
                offset = args[2];
                dtype = 'SMI'
590 591


592
        assert(offset is not None and dtype is not None);
593
        return ({
594
            'name': 'class_%s__%s__%s' % (klass, field, dtype),
595 596 597 598
            'value': '%s::%s' % (klass, offset)
        });

#
599
# Load field offset information from objects-inl.h etc.
600 601
#
def load_fields():
602 603 604 605 606 607 608 609 610
        for filename in sys.argv[2:]:
                if filename.endswith("-inl.h"):
                        load_fields_from_file(filename)

        for body in extras_accessors:
                fields.append(parse_field('ACCESSORS(%s)' % body));


def load_fields_from_file(filename):
611
        inlfile = io.open(filename, 'r', encoding='utf-8');
612 613 614 615 616 617 618 619

        #
        # Each class's fields and the corresponding offsets are described in the
        # source by calls to macros like "ACCESSORS" (and friends).  All we do
        # here is extract these macro invocations, taking into account that they
        # may span multiple lines and may contain nested parentheses.  We also
        # call parse_field() to pick apart the invocation.
        #
620
        prefixes = [ 'ACCESSORS', 'ACCESSORS2', 'ACCESSORS_GCSAFE',
621 622 623 624
                     'SMI_ACCESSORS', 'ACCESSORS_TO_SMI',
                     'SYNCHRONIZED_ACCESSORS', 'WEAK_ACCESSORS' ];
        prefixes += ([ prefix + "_CHECKED" for prefix in prefixes ] +
                     [ prefix + "_CHECKED2" for prefix in prefixes ])
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        current = '';
        opens = 0;

        for line in inlfile:
                if (opens > 0):
                        # Continuation line
                        for ii in range(0, len(line)):
                                if (line[ii] == '('):
                                        opens += 1;
                                elif (line[ii] == ')'):
                                        opens -= 1;

                                if (opens == 0):
                                        break;

                        current += line[0:ii + 1];
                        continue;

                for prefix in prefixes:
                        if (not line.startswith(prefix + '(')):
                                continue;

                        if (len(current) > 0):
                                fields.append(parse_field(current));
                                current = '';

                        for ii in range(len(prefix), len(line)):
                                if (line[ii] == '('):
                                        opens += 1;
                                elif (line[ii] == ')'):
                                        opens -= 1;

                                if (opens == 0):
                                        break;

                        current += line[0:ii + 1];

        if (len(current) > 0):
                fields.append(parse_field(current));
                current = '';

#
# Emit a block of constants.
#
def emit_set(out, consts):
670 671 672 673 674 675 676
        # Fix up overzealous parses.  This could be done inside the
        # parsers but as there are several, it's easiest to do it here.
        ws = re.compile('\s+')
        for const in consts:
                name = ws.sub('', const['name'])
                value = ws.sub('', str(const['value']))  # Can be a number.
                out.write('int v8dbg_%s = %s;\n' % (name, value))
677 678 679 680 681 682
        out.write('\n');

#
# Emit the whole output file.
#
def emit_config():
683
        out = open(sys.argv[1], 'w');
684 685 686 687 688 689 690 691

        out.write(header);

        out.write('/* miscellaneous constants */\n');
        emit_set(out, consts_misc);

        out.write('/* class type information */\n');
        consts = [];
692
        for typename in sorted(typeclasses):
693 694 695 696 697 698 699 700 701 702
                klass = typeclasses[typename];
                consts.append({
                    'name': 'type_%s__%s' % (klass, typename),
                    'value': typename
                });

        emit_set(out, consts);

        out.write('/* class hierarchy information */\n');
        consts = [];
703
        for klassname in sorted(klasses):
704
                pklass = klasses[klassname]['parent'];
705 706 707
                bklass = get_base_class(klassname);
                if (bklass != 'Object'):
                        continue;
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
                if (pklass == None):
                        continue;

                consts.append({
                    'name': 'parent_%s__%s' % (klassname, pklass),
                    'value': 0
                });

        emit_set(out, consts);

        out.write('/* field information */\n');
        emit_set(out, fields);

        out.write(footer);

if (len(sys.argv) < 4):
        print('usage: %s output.cc objects.h objects-inl.h' % sys.argv[0]);
        sys.exit(2);

load_objects();
load_fields();
emit_config();