SConstruct 32.1 KB
Newer Older
1
# Copyright 2008 the V8 project authors. All rights reserved.
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
# 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.

import platform
29
import re
30
import sys
31
import os
32
from os.path import join, dirname, abspath
33
from types import DictType, StringTypes
34 35
root_dir = dirname(File('SConstruct').rfile().abspath)
sys.path.append(join(root_dir, 'tools'))
36
import js2c, utils
37

38 39 40 41 42 43 44
# ANDROID_TOP is the top of the Android checkout, fetched from the environment
# variable 'TOP'.   You will also need to set the CXX, CC, AR and RANLIB
# environment variables to the cross-compiling tools.
ANDROID_TOP = os.environ.get('TOP')
if ANDROID_TOP is None:
  ANDROID_TOP=""

45
# TODO: Sort these issues out properly but as a temporary solution for gcc 4.4
46 47
# on linux we need these compiler flags to avoid crashes in the v8 test suite
# and avoid dtoa.c strict aliasing issues
48
if os.environ.get('GCC_VERSION') == '44':
49 50
    GCC_EXTRA_CCFLAGS = ['-fno-tree-vrp', '-fno-strict-aliasing']
    GCC_DTOA_EXTRA_CCFLAGS = []
51 52 53 54
else:
    GCC_EXTRA_CCFLAGS = []
    GCC_DTOA_EXTRA_CCFLAGS = []

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
ANDROID_FLAGS = ['-march=armv5te',
                 '-mtune=xscale',
                 '-msoft-float',
                 '-fpic',
                 '-mthumb-interwork',
                 '-funwind-tables',
                 '-fstack-protector',
                 '-fno-short-enums',
                 '-fmessage-length=0',
                 '-finline-functions',
                 '-fno-inline-functions-called-once',
                 '-fgcse-after-reload',
                 '-frerun-cse-after-loop',
                 '-frename-registers',
                 '-fomit-frame-pointer',
                 '-fno-strict-aliasing',
                 '-finline-limit=64',
                 '-MD']

ANDROID_INCLUDES = [ANDROID_TOP + '/bionic/libc/arch-arm/include',
                    ANDROID_TOP + '/bionic/libc/include',
                    ANDROID_TOP + '/bionic/libstdc++/include',
                    ANDROID_TOP + '/bionic/libc/kernel/common',
                    ANDROID_TOP + '/bionic/libc/kernel/arch-arm',
                    ANDROID_TOP + '/bionic/libm/include',
                    ANDROID_TOP + '/bionic/libm/include/arch/arm',
81 82 83
                    ANDROID_TOP + '/bionic/libthread_db/include',
                    ANDROID_TOP + '/frameworks/base/include',
                    ANDROID_TOP + '/system/core/include']
84

85 86 87 88 89 90 91 92
ANDROID_LINKFLAGS = ['-nostdlib',
                     '-Bdynamic',
                     '-Wl,-T,' + ANDROID_TOP + '/build/core/armelf.x',
                     '-Wl,-dynamic-linker,/system/bin/linker',
                     '-Wl,--gc-sections',
                     '-Wl,-z,nocopyreloc',
                     '-Wl,-rpath-link=' + ANDROID_TOP + '/out/target/product/generic/obj/lib',
                     ANDROID_TOP + '/out/target/product/generic/obj/lib/crtbegin_dynamic.o',
93
                     ANDROID_TOP + '/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0/interwork/libgcc.a',
94 95
                     ANDROID_TOP + '/out/target/product/generic/obj/lib/crtend_android.o'];

96 97
LIBRARY_FLAGS = {
  'all': {
98 99 100
    'CPPPATH': [join(root_dir, 'src')],
    'regexp:native': {
        'CPPDEFINES': ['V8_NATIVE_REGEXP']
101 102 103
    },
    'mode:debug': {
      'CPPDEFINES': ['V8_ENABLE_CHECKS']
104 105 106 107 108 109
    },
    'profilingsupport:on': {
      'CPPDEFINES':   ['ENABLE_LOGGING_AND_PROFILING'],
    },
    'debuggersupport:on': {
      'CPPDEFINES':   ['ENABLE_DEBUGGER_SUPPORT'],
110
    }
111 112 113
  },
  'gcc': {
    'all': {
114
      'CCFLAGS':      ['$DIALECTFLAGS', '$WARNINGFLAGS'],
115
      'CXXFLAGS':     ['$CCFLAGS', '-fno-rtti', '-fno-exceptions'],
116
    },
117 118 119 120
    'visibility:hidden': {
      # Use visibility=default to disable this.
      'CXXFLAGS':     ['-fvisibility=hidden']
    },
121 122
    'mode:debug': {
      'CCFLAGS':      ['-g', '-O0'],
123 124 125 126
      'CPPDEFINES':   ['ENABLE_DISASSEMBLER', 'DEBUG'],
      'os:android': {
        'CCFLAGS':    ['-mthumb']
      }
127 128
    },
    'mode:release': {
129 130 131
      'CCFLAGS':      ['-O3', '-fomit-frame-pointer', '-fdata-sections',
                       '-ffunction-sections'],
      'os:android': {
132
        'CCFLAGS':    ['-mthumb', '-Os'],
133
        'CPPDEFINES': ['SK_RELEASE', 'NDEBUG']
134
      }
135
    },
136
    'os:linux': {
137
      'CCFLAGS':      ['-ansi'] + GCC_EXTRA_CCFLAGS,
138
      'library:shared': {
139
        'CPPDEFINES': ['V8_SHARED'],
140
        'LIBS': ['pthread']
141
      }
142 143
    },
    'os:macos': {
144
      'CCFLAGS':      ['-ansi', '-mmacosx-version-min=10.4'],
145 146 147
      'library:shared': {
        'CPPDEFINES': ['V8_SHARED']
      }
148
    },
149
    'os:freebsd': {
150 151
      'CPPPATH' : ['/usr/local/include'],
      'LIBPATH' : ['/usr/local/lib'],
152 153
      'CCFLAGS':      ['-ansi'],
    },
154 155 156 157 158
    'os:openbsd': {
      'CPPPATH' : ['/usr/local/include'],
      'LIBPATH' : ['/usr/local/lib'],
      'CCFLAGS':      ['-ansi'],
    },
159 160 161 162 163
    'os:solaris': {
      'CPPPATH' : ['/usr/local/include'],
      'LIBPATH' : ['/usr/local/lib'],
      'CCFLAGS':      ['-ansi'],
    },
164 165 166
    'os:win32': {
      'CCFLAGS':      ['-DWIN32'],
      'CXXFLAGS':     ['-DWIN32'],
167
    },
168 169 170 171 172 173 174 175
    'os:android': {
      'CPPDEFINES':   ['ANDROID', '__ARM_ARCH_5__', '__ARM_ARCH_5T__',
                       '__ARM_ARCH_5E__', '__ARM_ARCH_5TE__'],
      'CCFLAGS':      ANDROID_FLAGS,
      'WARNINGFLAGS': ['-Wall', '-Wno-unused', '-Werror=return-type',
                       '-Wstrict-aliasing=2'],
      'CPPPATH':      ANDROID_INCLUDES,
    },
176
    'arch:ia32': {
177 178 179
      'CPPDEFINES':   ['V8_TARGET_ARCH_IA32'],
      'CCFLAGS':      ['-m32'],
      'LINKFLAGS':    ['-m32']
180 181
    },
    'arch:arm': {
182
      'CPPDEFINES':   ['V8_TARGET_ARCH_ARM']
183
    },
184 185 186 187
    'simulator:arm': {
      'CCFLAGS':      ['-m32'],
      'LINKFLAGS':    ['-m32']
    },
188 189 190 191 192 193
    'armvariant:thumb2': {
      'CPPDEFINES':   ['V8_ARM_VARIANT_THUMB']
    },
    'armvariant:arm': {
      'CPPDEFINES':   ['V8_ARM_VARIANT_ARM']
    },
194 195 196 197 198 199 200 201 202 203 204
    'arch:mips': {
      'CPPDEFINES':   ['V8_TARGET_ARCH_MIPS'],
      'simulator:none': {
        'CCFLAGS':      ['-EL', '-mips32r2', '-Wa,-mips32r2', '-fno-inline'],
        'LDFLAGS':      ['-EL']
      }
    },
    'simulator:mips': {
      'CCFLAGS':      ['-m32'],
      'LINKFLAGS':    ['-m32']
    },
205
    'arch:x64': {
lrn@chromium.org's avatar
lrn@chromium.org committed
206
      'CPPDEFINES':   ['V8_TARGET_ARCH_X64'],
207
      'CCFLAGS':      ['-m64'],
208
      'LINKFLAGS':    ['-m64'],
209
    },
210 211
    'prof:oprofile': {
      'CPPDEFINES':   ['ENABLE_OPROFILE_AGENT']
212
    }
213 214 215 216
  },
  'msvc': {
    'all': {
      'CCFLAGS':      ['$DIALECTFLAGS', '$WARNINGFLAGS'],
217
      'CXXFLAGS':     ['$CCFLAGS', '/GR-', '/Gy'],
218 219
      'CPPDEFINES':   ['WIN32'],
      'LINKFLAGS':    ['/INCREMENTAL:NO', '/NXCOMPAT', '/IGNORE:4221'],
220 221
      'CCPDBFLAGS':   ['/Zi']
    },
222 223 224 225
    'verbose:off': {
      'DIALECTFLAGS': ['/nologo'],
      'ARFLAGS':      ['/NOLOGO']
    },
226
    'arch:ia32': {
227 228 229 230 231
      'CPPDEFINES':   ['V8_TARGET_ARCH_IA32', '_USE_32BIT_TIME_T'],
      'LINKFLAGS':    ['/MACHINE:X86'],
      'ARFLAGS':      ['/MACHINE:X86']
    },
    'arch:x64': {
lrn@chromium.org's avatar
lrn@chromium.org committed
232
      'CPPDEFINES':   ['V8_TARGET_ARCH_X64'],
233 234
      'LINKFLAGS':    ['/MACHINE:X64'],
      'ARFLAGS':      ['/MACHINE:X64']
235
    },
236
    'mode:debug': {
237
      'CCFLAGS':      ['/Od', '/Gm'],
238
      'CPPDEFINES':   ['_DEBUG', 'ENABLE_DISASSEMBLER', 'DEBUG'],
239 240 241 242 243 244 245
      'LINKFLAGS':    ['/DEBUG'],
      'msvcrt:static': {
        'CCFLAGS': ['/MTd']
      },
      'msvcrt:shared': {
        'CCFLAGS': ['/MDd']
      }
246 247
    },
    'mode:release': {
248 249
      'CCFLAGS':      ['/O2'],
      'LINKFLAGS':    ['/OPT:REF', '/OPT:ICF'],
250 251 252 253 254
      'msvcrt:static': {
        'CCFLAGS': ['/MT']
      },
      'msvcrt:shared': {
        'CCFLAGS': ['/MD']
255 256 257 258
      },
      'msvcltcg:on': {
        'CCFLAGS':      ['/GL'],
        'ARFLAGS':      ['/LTCG'],
259 260 261 262 263 264 265 266 267
        'pgo:off': {
          'LINKFLAGS':    ['/LTCG'],
        },
        'pgo:instrument': {
          'LINKFLAGS':    ['/LTCG:PGI']
        },
        'pgo:optimize': {
          'LINKFLAGS':    ['/LTCG:PGO']
        }
268
      }
269
    }
270 271 272 273 274 275 276
  }
}


V8_EXTRA_FLAGS = {
  'gcc': {
    'all': {
277 278 279 280 281
      'WARNINGFLAGS': ['-Wall',
                       '-Werror',
                       '-W',
                       '-Wno-unused-parameter',
                       '-Wnon-virtual-dtor']
282
    },
283
    'os:win32': {
284 285 286
      'WARNINGFLAGS': ['-pedantic', '-Wno-long-long']
    },
    'os:linux': {
287 288 289 290 291 292
      'WARNINGFLAGS': ['-pedantic'],
      'library:shared': {
        'soname:on': {
          'LINKFLAGS': ['-Wl,-soname,${SONAME}']
        }
      }
293 294 295
    },
    'os:macos': {
      'WARNINGFLAGS': ['-pedantic']
296
    },
297 298 299
    'disassembler:on': {
      'CPPDEFINES':   ['ENABLE_DISASSEMBLER']
    }
300 301 302
  },
  'msvc': {
    'all': {
303
      'WARNINGFLAGS': ['/W3', '/WX', '/wd4355', '/wd4800']
304
    },
305 306 307 308
    'library:shared': {
      'CPPDEFINES': ['BUILDING_V8_SHARED'],
      'LIBS': ['winmm', 'ws2_32']
    },
309
    'arch:arm': {
310
      'CPPDEFINES':   ['V8_TARGET_ARCH_ARM'],
311 312 313
      # /wd4996 is to silence the warning about sscanf
      # used by the arm simulator.
      'WARNINGFLAGS': ['/wd4996']
314
    },
315 316 317
    'arch:mips': {
      'CPPDEFINES':   ['V8_TARGET_ARCH_MIPS'],
    },
318 319 320
    'disassembler:on': {
      'CPPDEFINES':   ['ENABLE_DISASSEMBLER']
    }
321 322 323 324
  }
}


325 326 327
MKSNAPSHOT_EXTRA_FLAGS = {
  'gcc': {
    'os:linux': {
328
      'LIBS': ['pthread'],
329 330 331 332 333
    },
    'os:macos': {
      'LIBS': ['pthread'],
    },
    'os:freebsd': {
334
      'LIBS': ['execinfo', 'pthread']
335
    },
336 337 338 339
    'os:solaris': {
      'LIBS': ['m', 'pthread', 'socket', 'nsl', 'rt'],
      'LINKFLAGS': ['-mt']
    },
340 341 342
    'os:openbsd': {
      'LIBS': ['execinfo', 'pthread']
    },
343
    'os:win32': {
344
      'LIBS': ['winmm', 'ws2_32'],
345 346 347 348
    },
  },
  'msvc': {
    'all': {
349
      'CPPDEFINES': ['_HAS_EXCEPTIONS=0'],
350
      'LIBS': ['winmm', 'ws2_32']
351 352 353 354 355
    }
  }
}


356 357 358
DTOA_EXTRA_FLAGS = {
  'gcc': {
    'all': {
359 360
      'WARNINGFLAGS': ['-Werror', '-Wno-uninitialized'],
      'CCFLAGS': GCC_DTOA_EXTRA_CCFLAGS
361
    }
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  },
  'msvc': {
    'all': {
      'WARNINGFLAGS': ['/WX', '/wd4018', '/wd4244']
    }
  }
}


CCTEST_EXTRA_FLAGS = {
  'all': {
    'CPPPATH': [join(root_dir, 'src')],
  },
  'gcc': {
    'all': {
      'LIBPATH': [abspath('.')]
378
    },
379
    'os:linux': {
380
      'LIBS':         ['pthread'],
381 382 383 384 385 386 387
    },
    'os:macos': {
      'LIBS':         ['pthread'],
    },
    'os:freebsd': {
      'LIBS':         ['execinfo', 'pthread']
    },
388 389 390 391
    'os:solaris': {
      'LIBS':         ['m', 'pthread', 'socket', 'nsl', 'rt'],
      'LINKFLAGS':    ['-mt']
    },
392 393 394
    'os:openbsd': {
      'LIBS':         ['execinfo', 'pthread']
    },
395
    'os:win32': {
396
      'LIBS': ['winmm', 'ws2_32']
397
    },
398 399 400 401 402
    'os:android': {
      'CPPDEFINES':   ['ANDROID', '__ARM_ARCH_5__', '__ARM_ARCH_5T__',
                       '__ARM_ARCH_5E__', '__ARM_ARCH_5TE__'],
      'CCFLAGS':      ANDROID_FLAGS,
      'CPPPATH':      ANDROID_INCLUDES,
403 404
      'LIBPATH':     [ANDROID_TOP + '/out/target/product/generic/obj/lib',
                      ANDROID_TOP + '/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0/interwork'],
405
      'LINKFLAGS':    ANDROID_LINKFLAGS,
406
      'LIBS':         ['log', 'c', 'stdc++', 'm', 'gcc'],
407 408 409 410
      'mode:release': {
        'CPPDEFINES': ['SK_RELEASE', 'NDEBUG']
      }
    },
411 412
  },
  'msvc': {
413
    'all': {
414
      'CPPDEFINES': ['_HAS_EXCEPTIONS=0'],
415
      'LIBS': ['winmm', 'ws2_32']
416
    },
417 418
    'library:shared': {
      'CPPDEFINES': ['USING_V8_SHARED']
419 420
    },
    'arch:ia32': {
421
      'CPPDEFINES': ['V8_TARGET_ARCH_IA32']
422 423
    },
    'arch:x64': {
424 425
      'CPPDEFINES':   ['V8_TARGET_ARCH_X64'],
      'LINKFLAGS': ['/STACK:2091752']
426
    },
427 428 429 430 431 432
  }
}


SAMPLE_FLAGS = {
  'all': {
433
    'CPPPATH': [join(abspath('.'), 'include')],
434 435 436
  },
  'gcc': {
    'all': {
437 438
      'LIBPATH': ['.'],
      'CCFLAGS': ['-fno-rtti', '-fno-exceptions']
439
    },
440
    'os:linux': {
441
      'LIBS':         ['pthread'],
442 443 444 445
    },
    'os:macos': {
      'LIBS':         ['pthread'],
    },
446
    'os:freebsd': {
447
      'LIBPATH' : ['/usr/local/lib'],
448 449
      'LIBS':     ['execinfo', 'pthread']
    },
450 451 452 453 454
    'os:solaris': {
      'LIBPATH' : ['/usr/local/lib'],
      'LIBS':     ['m', 'pthread', 'socket', 'nsl', 'rt'],
      'LINKFLAGS': ['-mt']
    },
455 456 457
    'os:openbsd': {
      'LIBPATH' : ['/usr/local/lib'],
      'LIBS':     ['execinfo', 'pthread']
458 459
    },
    'os:win32': {
460
      'LIBS':         ['winmm', 'ws2_32']
461
    },
462 463 464 465 466
    'os:android': {
      'CPPDEFINES':   ['ANDROID', '__ARM_ARCH_5__', '__ARM_ARCH_5T__',
                       '__ARM_ARCH_5E__', '__ARM_ARCH_5TE__'],
      'CCFLAGS':      ANDROID_FLAGS,
      'CPPPATH':      ANDROID_INCLUDES,
467 468
      'LIBPATH':     [ANDROID_TOP + '/out/target/product/generic/obj/lib',
                      ANDROID_TOP + '/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0/interwork'],
469
      'LINKFLAGS':    ANDROID_LINKFLAGS,
470
      'LIBS':         ['log', 'c', 'stdc++', 'm', 'gcc'],
471 472 473 474
      'mode:release': {
        'CPPDEFINES': ['SK_RELEASE', 'NDEBUG']
      }
    },
475 476 477
    'arch:ia32': {
      'CCFLAGS':      ['-m32'],
      'LINKFLAGS':    ['-m32']
478
    },
479 480 481 482
    'arch:x64': {
      'CCFLAGS':      ['-m64'],
      'LINKFLAGS':    ['-m64']
    },
483 484 485 486 487 488 489 490
    'arch:mips': {
      'CPPDEFINES':   ['V8_TARGET_ARCH_MIPS'],
      'simulator:none': {
        'CCFLAGS':      ['-EL', '-mips32r2', '-Wa,-mips32r2', '-fno-inline'],
        'LINKFLAGS':    ['-EL'],
        'LDFLAGS':      ['-EL']
      }
    },
491 492 493
    'simulator:arm': {
      'CCFLAGS':      ['-m32'],
      'LINKFLAGS':    ['-m32']
494
    },
495 496 497 498
    'simulator:mips': {
      'CCFLAGS':      ['-m32'],
      'LINKFLAGS':    ['-m32']
    },
499
    'mode:release': {
500
      'CCFLAGS':      ['-O2']
501
    },
502 503
    'mode:debug': {
      'CCFLAGS':      ['-g', '-O0']
504 505 506 507
    },
    'prof:oprofile': {
      'LIBPATH': ['/usr/lib32', '/usr/lib32/oprofile'],
      'LIBS': ['opagent']
508
    }
509 510 511
  },
  'msvc': {
    'all': {
512
      'LIBS': ['winmm', 'ws2_32']
513
    },
514 515 516 517 518 519 520
    'verbose:off': {
      'CCFLAGS': ['/nologo'],
      'LINKFLAGS': ['/NOLOGO']
    },
    'verbose:on': {
      'LINKFLAGS': ['/VERBOSE']
    },
521 522 523
    'library:shared': {
      'CPPDEFINES': ['USING_V8_SHARED']
    },
524 525 526
    'prof:on': {
      'LINKFLAGS': ['/MAP']
    },
527
    'mode:release': {
528
      'CCFLAGS':   ['/O2'],
529
      'LINKFLAGS': ['/OPT:REF', '/OPT:ICF'],
530 531 532 533 534
      'msvcrt:static': {
        'CCFLAGS': ['/MT']
      },
      'msvcrt:shared': {
        'CCFLAGS': ['/MD']
535 536 537
      },
      'msvcltcg:on': {
        'CCFLAGS':      ['/GL'],
538 539 540 541 542 543 544 545 546
        'pgo:off': {
          'LINKFLAGS':    ['/LTCG'],
        },
      },
      'pgo:instrument': {
        'LINKFLAGS':    ['/LTCG:PGI']
      },
      'pgo:optimize': {
        'LINKFLAGS':    ['/LTCG:PGO']
547
      }
548
    },
549
    'arch:ia32': {
550 551 552 553 554
      'CPPDEFINES': ['V8_TARGET_ARCH_IA32'],
      'LINKFLAGS': ['/MACHINE:X86']
    },
    'arch:x64': {
      'CPPDEFINES': ['V8_TARGET_ARCH_X64'],
555
      'LINKFLAGS': ['/MACHINE:X64', '/STACK:2091752']
556
    },
557
    'mode:debug': {
558 559 560 561 562 563 564 565
      'CCFLAGS':   ['/Od'],
      'LINKFLAGS': ['/DEBUG'],
      'msvcrt:static': {
        'CCFLAGS': ['/MTd']
      },
      'msvcrt:shared': {
        'CCFLAGS': ['/MDd']
      }
566 567 568 569 570
    }
  }
}


571 572 573 574
D8_FLAGS = {
  'gcc': {
    'console:readline': {
      'LIBS': ['readline']
575 576
    },
    'os:linux': {
577
      'LIBS': ['pthread'],
578 579 580 581 582 583 584
    },
    'os:macos': {
      'LIBS': ['pthread'],
    },
    'os:freebsd': {
      'LIBS': ['pthread'],
    },
585 586 587 588
    'os:solaris': {
      'LIBS': ['m', 'pthread', 'socket', 'nsl', 'rt'],
      'LINKFLAGS': ['-mt']
    },
589 590 591
    'os:openbsd': {
      'LIBS': ['pthread'],
    },
592
    'os:android': {
593 594
      'LIBPATH':     [ANDROID_TOP + '/out/target/product/generic/obj/lib',
                      ANDROID_TOP + '/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/lib/gcc/arm-eabi/4.4.0/interwork'],
595
      'LINKFLAGS':    ANDROID_LINKFLAGS,
596
      'LIBS':         ['log', 'c', 'stdc++', 'm', 'gcc'],
597
    },
598
    'os:win32': {
599
      'LIBS': ['winmm', 'ws2_32'],
600
    },
601
  },
602 603
  'msvc': {
    'all': {
604
      'LIBS': ['winmm', 'ws2_32']
605 606
    }
  }
607 608 609
}


610 611 612 613 614 615
SUFFIXES = {
  'release': '',
  'debug': '_g'
}


616 617 618 619 620 621 622 623
def Abort(message):
  print message
  sys.exit(1)


def GuessToolchain(os):
  tools = Environment()['TOOLS']
  if 'gcc' in tools:
624
    return 'gcc'
625 626 627
  elif 'msvc' in tools:
    return 'msvc'
  else:
628 629 630
    return None


631
OS_GUESS = utils.GuessOS()
632
TOOLCHAIN_GUESS = GuessToolchain(OS_GUESS)
633
ARCH_GUESS = utils.GuessArchitecture()
634 635 636 637 638 639


SIMPLE_OPTIONS = {
  'toolchain': {
    'values': ['gcc', 'msvc'],
    'default': TOOLCHAIN_GUESS,
640
    'help': 'the toolchain to use (' + TOOLCHAIN_GUESS + ')'
641 642
  },
  'os': {
643
    'values': ['freebsd', 'linux', 'macos', 'win32', 'android', 'openbsd', 'solaris'],
644
    'default': OS_GUESS,
645
    'help': 'the os to build for (' + OS_GUESS + ')'
646 647
  },
  'arch': {
648
    'values':['arm', 'ia32', 'x64', 'mips'],
649
    'default': ARCH_GUESS,
650
    'help': 'the architecture to build for (' + ARCH_GUESS + ')'
651
  },
652 653 654 655 656
  'regexp': {
    'values': ['native', 'interpreted'],
    'default': 'native',
    'help': 'Whether to use native or interpreted regexp implementation'
  },
657
  'snapshot': {
658
    'values': ['on', 'off', 'nobuild'],
659 660 661
    'default': 'off',
    'help': 'build using snapshots for faster start-up'
  },
662
  'prof': {
663
    'values': ['on', 'off', 'oprofile'],
664 665 666
    'default': 'off',
    'help': 'enable profiling of build target'
  },
667
  'library': {
668 669
    'values': ['static', 'shared'],
    'default': 'static',
670 671
    'help': 'the type of library to produce'
  },
672 673 674 675 676 677 678 679 680 681
  'profilingsupport': {
    'values': ['on', 'off'],
    'default': 'on',
    'help': 'enable profiling of JavaScript code'
  },
  'debuggersupport': {
    'values': ['on', 'off'],
    'default': 'on',
    'help': 'enable debugging of JavaScript code'
  },
682 683 684 685 686
  'soname': {
    'values': ['on', 'off'],
    'default': 'off',
    'help': 'turn on setting soname for Linux shared library'
  },
687 688 689
  'msvcrt': {
    'values': ['static', 'shared'],
    'default': 'static',
690 691 692 693 694 695
    'help': 'the type of Microsoft Visual C++ runtime library to use'
  },
  'msvcltcg': {
    'values': ['on', 'off'],
    'default': 'on',
    'help': 'use Microsoft Visual C++ link-time code generation'
696
  },
697
  'simulator': {
698
    'values': ['arm', 'mips', 'none'],
699 700
    'default': 'none',
    'help': 'build with simulator'
701 702 703 704 705
  },
  'disassembler': {
    'values': ['on', 'off'],
    'default': 'off',
    'help': 'enable the disassembler to inspect generated code'
706 707 708 709 710
  },
  'sourcesignatures': {
    'values': ['MD5', 'timestamp'],
    'default': 'MD5',
    'help': 'set how the build system detects file changes'
711 712 713 714 715
  },
  'console': {
    'values': ['dumb', 'readline'],
    'default': 'dumb',
    'help': 'the console to use for the d8 shell'
716 717 718 719 720
  },
  'verbose': {
    'values': ['on', 'off'],
    'default': 'off',
    'help': 'more output from compiler and linker'
721 722 723 724 725
  },
  'visibility': {
    'values': ['default', 'hidden'],
    'default': 'hidden',
    'help': 'shared library symbol visibility'
726 727 728 729 730
  },
  'armvariant': {
    'values': ['arm', 'thumb2', 'none'],
    'default': 'none',
    'help': 'generate thumb2 instructions instead of arm instructions (default)'
731 732 733 734 735
  },
  'pgo': {
    'values': ['off', 'instrument', 'optimize'],
    'default': 'off',
    'help': 'select profile guided optimization variant',
736 737
  }
}
738 739 740 741


def GetOptions():
  result = Options()
742
  result.Add('mode', 'compilation mode (debug, release)', 'release')
743
  result.Add('sample', 'build sample (shell, process, lineprocessor)', '')
744 745
  result.Add('env', 'override environment settings (NAME0:value0,NAME1:value1,...)', '')
  result.Add('importenv', 'import environment settings (NAME0,NAME1,...)', '')
746
  for (name, option) in SIMPLE_OPTIONS.iteritems():
747 748
    help = '%s (%s)' % (name, ", ".join(option['values']))
    result.Add(name, help, option.get('default'))
749 750 751
  return result


752 753 754 755 756 757 758 759 760 761 762
def GetVersionComponents():
  MAJOR_VERSION_PATTERN = re.compile(r"#define\s+MAJOR_VERSION\s+(.*)")
  MINOR_VERSION_PATTERN = re.compile(r"#define\s+MINOR_VERSION\s+(.*)")
  BUILD_NUMBER_PATTERN = re.compile(r"#define\s+BUILD_NUMBER\s+(.*)")
  PATCH_LEVEL_PATTERN = re.compile(r"#define\s+PATCH_LEVEL\s+(.*)")

  patterns = [MAJOR_VERSION_PATTERN,
              MINOR_VERSION_PATTERN,
              BUILD_NUMBER_PATTERN,
              PATCH_LEVEL_PATTERN]

763
  source = open(join(root_dir, 'src', 'version.cc')).read()
764 765 766 767 768 769 770 771 772 773 774 775 776
  version_components = []
  for pattern in patterns:
    match = pattern.search(source)
    if match:
      version_components.append(match.group(1).strip())
    else:
      version_components.append('0')

  return version_components


def GetVersion():
  version_components = GetVersionComponents()
777

778 779 780 781 782 783 784
  if version_components[len(version_components) - 1] == '0':
    version_components.pop()
  return '.'.join(version_components)


def GetSpecificSONAME():
  SONAME_PATTERN = re.compile(r"#define\s+SONAME\s+\"(.*)\"")
785

786
  source = open(join(root_dir, 'src', 'version.cc')).read()
787
  match = SONAME_PATTERN.search(source)
788

789 790 791 792 793 794
  if match:
    return match.group(1).strip()
  else:
    return ''


795 796 797 798 799 800 801 802 803 804 805 806 807
def SplitList(str):
  return [ s for s in str.split(",") if len(s) > 0 ]


def IsLegal(env, option, values):
  str = env[option]
  for s in SplitList(str):
    if not s in values:
      Abort("Illegal value for option %s '%s'." % (option, s))
      return False
  return True


808
def VerifyOptions(env):
809 810
  if not IsLegal(env, 'mode', ['debug', 'release']):
    return False
811
  if not IsLegal(env, 'sample', ["shell", "process", "lineprocessor"]):
812
    return False
813 814
  if not IsLegal(env, 'regexp', ["native", "interpreted"]):
    return False
815 816
  if env['os'] == 'win32' and env['library'] == 'shared' and env['prof'] == 'on':
    Abort("Profiling on windows only supported for static library.")
817 818
  if env['prof'] == 'oprofile' and env['os'] != 'linux':
    Abort("OProfile is only supported on Linux.")
819 820 821 822
  if env['os'] == 'win32' and env['soname'] == 'on':
    Abort("Shared Object soname not applicable for Windows.")
  if env['soname'] == 'on' and env['library'] == 'static':
    Abort("Shared Object soname not applicable for static library.")
823 824
  if env['os'] != 'win32' and env['pgo'] != 'off':
    Abort("Profile guided optimization only supported on Windows.")
825
  for (name, option) in SIMPLE_OPTIONS.iteritems():
826 827 828 829 830 831 832 833
    if (not option.get('default')) and (name not in ARGUMENTS):
      message = ("A value for option %s must be specified (%s)." %
          (name, ", ".join(option['values'])))
      Abort(message)
    if not env[name] in option['values']:
      message = ("Unknown %s value '%s'.  Possible values are (%s)." %
          (name, env[name], ", ".join(option['values'])))
      Abort(message)
834 835


836 837
class BuildContext(object):

838
  def __init__(self, options, env_overrides, samples):
839
    self.library_targets = []
840
    self.mksnapshot_targets = []
841 842
    self.cctest_targets = []
    self.sample_targets = []
843
    self.d8_targets = []
844
    self.options = options
845
    self.env_overrides = env_overrides
846
    self.samples = samples
847 848
    self.use_snapshot = (options['snapshot'] != 'off')
    self.build_snapshot = (options['snapshot'] == 'on')
849
    self.flags = None
850

851 852
  def AddRelevantFlags(self, initial, flags):
    result = initial.copy()
853
    toolchain = self.options['toolchain']
854 855 856 857 858
    if toolchain in flags:
      self.AppendFlags(result, flags[toolchain].get('all'))
      for option in sorted(self.options.keys()):
        value = self.options[option]
        self.AppendFlags(result, flags[toolchain].get(option + ':' + value))
859
    self.AppendFlags(result, flags.get('all'))
860 861 862 863
    return result

  def AddRelevantSubFlags(self, options, flags):
    self.AppendFlags(options, flags.get('all'))
864 865
    for option in sorted(self.options.keys()):
      value = self.options[option]
866
      self.AppendFlags(options, flags.get(option + ':' + value))
867

868 869 870
  def GetRelevantSources(self, source):
    result = []
    result += source.get('all', [])
871
    for (name, value) in self.options.iteritems():
872 873 874 875 876
      source_value = source.get(name + ':' + value, [])
      if type(source_value) == dict:
        result += self.GetRelevantSources(source_value)
      else:
        result += source_value
877
    return sorted(result)
878 879 880 881

  def AppendFlags(self, options, added):
    if not added:
      return
882
    for (key, value) in added.iteritems():
883 884
      if key.find(':') != -1:
        self.AddRelevantSubFlags(options, { key: value })
885
      else:
886 887 888 889 890 891
        if not key in options:
          options[key] = value
        else:
          prefix = options[key]
          if isinstance(prefix, StringTypes): prefix = prefix.split()
          options[key] = prefix + value
892

893
  def ConfigureObject(self, env, input, **kw):
894 895
    if (kw.has_key('CPPPATH') and env.has_key('CPPPATH')):
      kw['CPPPATH'] += env['CPPPATH']
896
    if self.options['library'] == 'static':
897 898
      return env.StaticObject(input, **kw)
    else:
899
      return env.SharedObject(input, **kw)
900

901 902 903 904 905 906 907 908
  def ApplyEnvOverrides(self, env):
    if not self.env_overrides:
      return
    if type(env['ENV']) == DictType:
      env['ENV'].update(**self.env_overrides)
    else:
      env['ENV'] = self.env_overrides

909

910
def PostprocessOptions(options, os):
911 912 913 914 915 916
  # Adjust architecture if the simulator option has been set
  if (options['simulator'] != 'none') and (options['arch'] != options['simulator']):
    if 'arch' in ARGUMENTS:
      # Print a warning if arch has explicitly been set
      print "Warning: forcing architecture to match simulator (%s)" % options['simulator']
    options['arch'] = options['simulator']
917 918 919 920
  if (options['prof'] != 'off') and (options['profilingsupport'] == 'off'):
    # Print a warning if profiling is enabled without profiling support
    print "Warning: forcing profilingsupport on when prof is on"
    options['profilingsupport'] = 'on'
921 922 923 924
  if os == 'win32' and options['pgo'] != 'off' and options['msvcltcg'] == 'off':
    if 'msvcltcg' in ARGUMENTS:
      print "Warning: forcing msvcltcg on as it is required for pgo (%s)" % options['pgo']
    options['msvcltcg'] = 'on'
925 926 927 928
  if (options['armvariant'] == 'none' and options['arch'] == 'arm'):
    options['armvariant'] = 'arm'
  if (options['armvariant'] != 'none' and options['arch'] != 'arm'):
    options['armvariant'] = 'none'
929 930 931 932 933
  if options['arch'] == 'mips':
    if ('regexp' in ARGUMENTS) and options['regexp'] == 'native':
      # Print a warning if native regexp is specified for mips
      print "Warning: forcing regexp to interpreted for mips"
    options['regexp'] = 'interpreted'
934 935


936 937 938
def ParseEnvOverrides(arg, imports):
  # The environment overrides are in the format NAME0:value0,NAME1:value1,...
  # The environment imports are in the format NAME0,NAME1,...
939
  overrides = {}
940 941 942
  for var in imports.split(','):
    if var in os.environ:
      overrides[var] = os.environ[var]
943 944 945 946 947 948 949 950 951
  for override in arg.split(','):
    pos = override.find(':')
    if pos == -1:
      continue
    overrides[override[:pos].strip()] = override[pos+1:].strip()
  return overrides


def BuildSpecific(env, mode, env_overrides):
952 953 954
  options = {'mode': mode}
  for option in SIMPLE_OPTIONS:
    options[option] = env[option]
955
  PostprocessOptions(options, env['os'])
956

957
  context = BuildContext(options, env_overrides, samples=SplitList(env['sample']))
958

959 960 961 962 963 964 965 966 967
  # Remove variables which can't be imported from the user's external
  # environment into a construction environment.
  user_environ = os.environ.copy()
  try:
    del user_environ['ENV']
  except KeyError:
    pass

  library_flags = context.AddRelevantFlags(user_environ, LIBRARY_FLAGS)
968
  v8_flags = context.AddRelevantFlags(library_flags, V8_EXTRA_FLAGS)
969
  mksnapshot_flags = context.AddRelevantFlags(library_flags, MKSNAPSHOT_EXTRA_FLAGS)
970
  dtoa_flags = context.AddRelevantFlags(library_flags, DTOA_EXTRA_FLAGS)
971
  cctest_flags = context.AddRelevantFlags(v8_flags, CCTEST_EXTRA_FLAGS)
972
  sample_flags = context.AddRelevantFlags(user_environ, SAMPLE_FLAGS)
973
  d8_flags = context.AddRelevantFlags(library_flags, D8_FLAGS)
974 975 976

  context.flags = {
    'v8': v8_flags,
977
    'mksnapshot': mksnapshot_flags,
978 979
    'dtoa': dtoa_flags,
    'cctest': cctest_flags,
980 981
    'sample': sample_flags,
    'd8': d8_flags
982
  }
983

984
  # Generate library base name.
985 986 987
  target_id = mode
  suffix = SUFFIXES[target_id]
  library_name = 'v8' + suffix
988 989 990 991
  version = GetVersion()
  if context.options['soname'] == 'on':
    # When building shared object with SONAME version the library name.
    library_name += '-' + version
992

993 994 995 996 997 998 999
  # Generate library SONAME if required by the build.
  if context.options['soname'] == 'on':
    soname = GetSpecificSONAME()
    if soname == '':
      soname = 'lib' + library_name + '.so'
    env['SONAME'] = soname

1000
  # Build the object files by invoking SCons recursively.
1001
  (object_files, shell_files, mksnapshot) = env.SConscript(
1002
    join('src', 'SConscript'),
1003 1004
    build_dir=join('obj', target_id),
    exports='context',
1005 1006
    duplicate=False
  )
1007

1008 1009
  context.mksnapshot_targets.append(mksnapshot)

1010
  # Link the object files into a library.
1011
  env.Replace(**context.flags['v8'])
1012
  env.Prepend(LIBS=[library_name])
1013

1014
  context.ApplyEnvOverrides(env)
1015
  if context.options['library'] == 'static':
1016
    library = env.StaticLibrary(library_name, object_files)
1017
  else:
1018 1019 1020
    # There seems to be a glitch in the way scons decides where to put
    # PDB files when compiling using MSVC so we specify it manually.
    # This should not affect any other platforms.
1021 1022 1023
    pdb_name = library_name + '.dll.pdb'
    library = env.SharedLibrary(library_name, object_files, PDB=pdb_name)
  context.library_targets.append(library)
1024

1025 1026
  d8_env = Environment()
  d8_env.Replace(**context.flags['d8'])
1027
  context.ApplyEnvOverrides(d8_env)
1028 1029 1030
  shell = d8_env.Program('d8' + suffix, object_files + shell_files)
  context.d8_targets.append(shell)

1031
  for sample in context.samples:
1032
    sample_env = Environment()
1033
    sample_env.Replace(**context.flags['sample'])
1034
    sample_env.Prepend(LIBS=[library_name])
1035
    context.ApplyEnvOverrides(sample_env)
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    sample_object = sample_env.SConscript(
      join('samples', 'SConscript'),
      build_dir=join('obj', 'sample', sample, target_id),
      exports='sample context',
      duplicate=False
    )
    sample_name = sample + suffix
    sample_program = sample_env.Program(sample_name, sample_object)
    sample_env.Depends(sample_program, library)
    context.sample_targets.append(sample_program)
1046

1047 1048 1049 1050 1051 1052 1053
  cctest_program = env.SConscript(
    join('test', 'cctest', 'SConscript'),
    build_dir=join('obj', 'test', target_id),
    exports='context object_files',
    duplicate=False
  )
  context.cctest_targets.append(cctest_program)
1054

1055 1056 1057 1058 1059 1060 1061 1062
  return context


def Build():
  opts = GetOptions()
  env = Environment(options=opts)
  Help(opts.GenerateHelpText(env))
  VerifyOptions(env)
1063
  env_overrides = ParseEnvOverrides(env['env'], env['importenv'])
1064

1065
  SourceSignatures(env['sourcesignatures'])
1066

1067
  libraries = []
1068
  mksnapshots = []
1069 1070
  cctests = []
  samples = []
1071
  d8s = []
1072 1073
  modes = SplitList(env['mode'])
  for mode in modes:
1074
    context = BuildSpecific(env.Copy(), mode, env_overrides)
1075
    libraries += context.library_targets
1076
    mksnapshots += context.mksnapshot_targets
1077 1078
    cctests += context.cctest_targets
    samples += context.sample_targets
1079
    d8s += context.d8_targets
1080 1081

  env.Alias('library', libraries)
1082
  env.Alias('mksnapshot', mksnapshots)
1083 1084
  env.Alias('cctests', cctests)
  env.Alias('sample', samples)
1085
  env.Alias('d8', d8s)
1086

1087 1088
  if env['sample']:
    env.Default('sample')
1089
  else:
1090
    env.Default('library')
1091

1092

1093 1094
# We disable deprecation warnings because we need to be able to use
# env.Copy without getting warnings for compatibility with older
1095 1096 1097 1098 1099 1100 1101
# version of scons.  Also, there's a bug in some revisions that
# doesn't allow this flag to be set, so we swallow any exceptions.
# Lovely.
try:
  SetOption('warn', 'no-deprecated')
except:
  pass
1102 1103


1104
Build()