Clone of mesa.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generic.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. """generic
  2. Generic tool that provides a commmon ground for all platforms.
  3. """
  4. #
  5. # Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
  6. # All Rights Reserved.
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a
  9. # copy of this software and associated documentation files (the
  10. # "Software"), to deal in the Software without restriction, including
  11. # without limitation the rights to use, copy, modify, merge, publish,
  12. # distribute, sub license, and/or sell copies of the Software, and to
  13. # permit persons to whom the Software is furnished to do so, subject to
  14. # the following conditions:
  15. #
  16. # The above copyright notice and this permission notice (including the
  17. # next paragraph) shall be included in all copies or substantial portions
  18. # of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  21. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
  23. # IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
  24. # ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  25. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  26. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. #
  28. import os
  29. import os.path
  30. import re
  31. import platform as _platform
  32. import sys
  33. import SCons.Action
  34. import SCons.Builder
  35. import SCons.Scanner
  36. def quietCommandLines(env):
  37. # Quiet command lines
  38. # See also http://www.scons.org/wiki/HidingCommandLinesInOutput
  39. env['CCCOMSTR'] = "Compiling $SOURCE ..."
  40. env['CXXCOMSTR'] = "Compiling $SOURCE ..."
  41. env['ARCOMSTR'] = "Archiving $TARGET ..."
  42. env['RANLIBCOMSTR'] = ""
  43. env['LINKCOMSTR'] = "Linking $TARGET ..."
  44. def createConvenienceLibBuilder(env):
  45. """This is a utility function that creates the ConvenienceLibrary
  46. Builder in an Environment if it is not there already.
  47. If it is already there, we return the existing one.
  48. Based on the stock StaticLibrary and SharedLibrary builders.
  49. """
  50. try:
  51. convenience_lib = env['BUILDERS']['ConvenienceLibrary']
  52. except KeyError:
  53. action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ]
  54. if env.Detect('ranlib'):
  55. ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR")
  56. action_list.append(ranlib_action)
  57. convenience_lib = SCons.Builder.Builder(action = action_list,
  58. emitter = '$LIBEMITTER',
  59. prefix = '$LIBPREFIX',
  60. suffix = '$LIBSUFFIX',
  61. src_suffix = '$SHOBJSUFFIX',
  62. src_builder = 'SharedObject')
  63. env['BUILDERS']['ConvenienceLibrary'] = convenience_lib
  64. return convenience_lib
  65. # TODO: handle import statements with multiple modules
  66. # TODO: handle from import statements
  67. import_re = re.compile(r'^import\s+(\S+)$', re.M)
  68. def python_scan(node, env, path):
  69. # http://www.scons.org/doc/0.98.5/HTML/scons-user/c2781.html#AEN2789
  70. contents = node.get_contents()
  71. source_dir = node.get_dir()
  72. imports = import_re.findall(contents)
  73. results = []
  74. for imp in imports:
  75. for dir in path:
  76. file = os.path.join(str(dir), imp.replace('.', os.sep) + '.py')
  77. if os.path.exists(file):
  78. results.append(env.File(file))
  79. break
  80. file = os.path.join(str(dir), imp.replace('.', os.sep), '__init__.py')
  81. if os.path.exists(file):
  82. results.append(env.File(file))
  83. break
  84. return results
  85. python_scanner = SCons.Scanner.Scanner(function = python_scan, skeys = ['.py'])
  86. def code_generate(env, script, target, source, command):
  87. """Method to simplify code generation via python scripts.
  88. http://www.scons.org/wiki/UsingCodeGenerators
  89. http://www.scons.org/doc/0.98.5/HTML/scons-user/c2768.html
  90. """
  91. # We're generating code using Python scripts, so we have to be
  92. # careful with our scons elements. This entry represents
  93. # the generator file *in the source directory*.
  94. script_src = env.File(script).srcnode()
  95. # This command creates generated code *in the build directory*.
  96. command = command.replace('$SCRIPT', script_src.path)
  97. code = env.Command(target, source, command)
  98. # Explicitly mark that the generated code depends on the generator,
  99. # and on implicitly imported python modules
  100. path = (script_src.get_dir(),)
  101. deps = [script_src]
  102. deps += script_src.get_implicit_deps(env, python_scanner, path)
  103. env.Depends(code, deps)
  104. # Running the Python script causes .pyc files to be generated in the
  105. # source directory. When we clean up, they should go too. So add side
  106. # effects for .pyc files
  107. for dep in deps:
  108. pyc = env.File(str(dep) + 'c')
  109. env.SideEffect(pyc, code)
  110. return code
  111. def createCodeGenerateMethod(env):
  112. env.Append(SCANNERS = python_scanner)
  113. env.AddMethod(code_generate, 'CodeGenerate')
  114. def symlink(target, source, env):
  115. target = str(target[0])
  116. source = str(source[0])
  117. if os.path.islink(target) or os.path.exists(target):
  118. os.remove(target)
  119. os.symlink(os.path.basename(source), target)
  120. def install_shared_library(env, source, version = ()):
  121. source = str(source[0])
  122. version = tuple(map(str, version))
  123. target_dir = os.path.join(env.Dir('#.').srcnode().abspath, env['build'], 'lib')
  124. target_name = '.'.join((str(source),) + version)
  125. last = env.InstallAs(os.path.join(target_dir, target_name), source)
  126. while len(version):
  127. version = version[:-1]
  128. target_name = '.'.join((str(source),) + version)
  129. action = SCons.Action.Action(symlink, "$TARGET -> $SOURCE")
  130. last = env.Command(os.path.join(target_dir, target_name), last, action)
  131. def createInstallMethods(env):
  132. env.AddMethod(install_shared_library, 'InstallSharedLibrary')
  133. _platform_map = {
  134. 'linux2': 'linux',
  135. 'win32': 'windows',
  136. }
  137. _machine_map = {
  138. 'x86': 'x86',
  139. 'i386': 'x86',
  140. 'i486': 'x86',
  141. 'i586': 'x86',
  142. 'i686': 'x86',
  143. 'ppc': 'ppc',
  144. 'x86_64': 'x86_64',
  145. }
  146. _toolchain_map = {
  147. 'winddk': 'winddk',
  148. 'wince': 'wcesdk',
  149. }
  150. _bool_map = {
  151. 'y': 1,
  152. 'yes': 1,
  153. 't': 1,
  154. 'true': 1,
  155. '1': 1,
  156. 'on': 1,
  157. 'all': 1,
  158. 'n': 0,
  159. 'no': 0,
  160. 'f': 0,
  161. 'false': 0,
  162. '0': 0,
  163. 'off': 0,
  164. 'none': 0,
  165. }
  166. def num_jobs():
  167. try:
  168. return int(os.environ['NUMBER_OF_PROCESSORS'])
  169. except (ValueError, KeyError):
  170. pass
  171. try:
  172. return os.sysconf('SC_NPROCESSORS_ONLN')
  173. except (ValueError, OSError, AttributeError):
  174. pass
  175. try:
  176. return int(os.popen2("sysctl -n hw.ncpu")[1].read())
  177. except ValueError:
  178. pass
  179. return 1
  180. def generate(env):
  181. """Common environment generation code"""
  182. from SCons.Script import ARGUMENTS
  183. # FIXME: this is already too late
  184. #if env.get('quiet', False):
  185. # quietCommandLines(env)
  186. # Platform
  187. try:
  188. env['platform'] = ARGUMENTS['platform']
  189. except KeyError:
  190. env['platform'] = _platform_map.get(sys.platform, sys.platform)
  191. # Machine
  192. try:
  193. env['machine'] = ARGUMENTS['machine']
  194. except KeyError:
  195. env['machine'] = _machine_map.get(os.environ.get('PROCESSOR_ARCHITECTURE', _platform.machine()), 'generic')
  196. # Toolchain
  197. try:
  198. env['toolchain'] = ARGUMENTS['toolchain']
  199. except KeyError:
  200. if env['platform'] in ('windows', 'winddk', 'wince') and sys.platform != 'win32':
  201. env['toolchain'] = 'crossmingw'
  202. else:
  203. env['toolchain'] = _toolchain_map.get(env['platform'], 'default')
  204. if env['toolchain'] == 'crossmingw' and env['machine'] not in ('generic', 'x86'):
  205. env['machine'] = 'x86'
  206. try:
  207. env['MSVS_VERSION'] = ARGUMENTS['MSVS_VERSION']
  208. except KeyError:
  209. pass
  210. # Build type
  211. env['debug'] = _bool_map[ARGUMENTS.get('debug', 'no')]
  212. env['profile'] = _bool_map[ARGUMENTS.get('profile', 'no')]
  213. # Put build output in a separate dir, which depends on the current
  214. # configuration. See also http://www.scons.org/wiki/AdvancedBuildExample
  215. try:
  216. env['build'] = ARGUMENTS['build']
  217. except KeyError:
  218. build_topdir = 'build'
  219. build_subdir = env['platform']
  220. if env['machine'] != 'generic':
  221. build_subdir += '-' + env['machine']
  222. if env['debug']:
  223. build_subdir += "-debug"
  224. if env['profile']:
  225. build_subdir += "-profile"
  226. env['build'] = os.path.join(build_topdir, build_subdir)
  227. # Place the .sconsign file in the build dir too, to avoid issues with
  228. # different scons versions building the same source file
  229. env.SConsignFile(os.path.join(env['build'], '.sconsign'))
  230. # Parallel build
  231. if env.GetOption('num_jobs') <= 1:
  232. env.SetOption('num_jobs', num_jobs())
  233. # Summary
  234. print
  235. print ' platform=%s' % env['platform']
  236. print ' machine=%s' % env['machine']
  237. print ' toolchain=%s' % env['toolchain']
  238. print ' debug=%s' % ['no', 'yes'][env['debug']]
  239. print ' profile=%s' % ['no', 'yes'][env['profile']]
  240. print ' build=%s' % env['build']
  241. print ' %s jobs' % env.GetOption('num_jobs')
  242. print
  243. # Load tool chain
  244. env.Tool(env['toolchain'])
  245. env['gcc'] = 'gcc' in os.path.basename(env['CC']).split('-')
  246. env['msvc'] = env['CC'] == 'cl'
  247. # shortcuts
  248. debug = env['debug']
  249. machine = env['machine']
  250. platform = env['platform']
  251. x86 = env['machine'] == 'x86'
  252. ppc = env['machine'] == 'ppc'
  253. gcc = env['gcc']
  254. msvc = env['msvc']
  255. # C preprocessor options
  256. cppdefines = []
  257. if debug:
  258. cppdefines += ['DEBUG']
  259. else:
  260. cppdefines += ['NDEBUG']
  261. if env['profile']:
  262. cppdefines += ['PROFILE']
  263. if platform == 'windows':
  264. cppdefines += [
  265. 'WIN32',
  266. '_WINDOWS',
  267. #'_UNICODE',
  268. #'UNICODE',
  269. # http://msdn2.microsoft.com/en-us/library/6dwk3a1z.aspx,
  270. #'WIN32_LEAN_AND_MEAN',
  271. ]
  272. if msvc:
  273. cppdefines += [
  274. 'VC_EXTRALEAN',
  275. '_CRT_SECURE_NO_DEPRECATE',
  276. ]
  277. if debug:
  278. cppdefines += ['_DEBUG']
  279. if platform == 'winddk':
  280. # Mimic WINDDK's builtin flags. See also:
  281. # - WINDDK's bin/makefile.new i386mk.inc for more info.
  282. # - buildchk_wxp_x86.log files, generated by the WINDDK's build
  283. # - http://alter.org.ua/docs/nt_kernel/vc8_proj/
  284. cppdefines += [
  285. ('_X86_', '1'),
  286. ('i386', '1'),
  287. 'STD_CALL',
  288. ('CONDITION_HANDLING', '1'),
  289. ('NT_INST', '0'),
  290. ('WIN32', '100'),
  291. ('_NT1X_', '100'),
  292. ('WINNT', '1'),
  293. ('_WIN32_WINNT', '0x0501'), # minimum required OS version
  294. ('WINVER', '0x0501'),
  295. ('_WIN32_IE', '0x0603'),
  296. ('WIN32_LEAN_AND_MEAN', '1'),
  297. ('DEVL', '1'),
  298. ('__BUILDMACHINE__', 'WinDDK'),
  299. ('FPO', '0'),
  300. ]
  301. if debug:
  302. cppdefines += [('DBG', 1)]
  303. if platform == 'wince':
  304. cppdefines += [
  305. '_CRT_SECURE_NO_DEPRECATE',
  306. '_USE_32BIT_TIME_T',
  307. 'UNICODE',
  308. '_UNICODE',
  309. ('UNDER_CE', '600'),
  310. ('_WIN32_WCE', '0x600'),
  311. 'WINCEOEM',
  312. 'WINCEINTERNAL',
  313. 'WIN32',
  314. 'STRICT',
  315. 'x86',
  316. '_X86_',
  317. 'INTERNATIONAL',
  318. ('INTLMSG_CODEPAGE', '1252'),
  319. ]
  320. env.Append(CPPDEFINES = cppdefines)
  321. # C preprocessor includes
  322. if platform == 'winddk':
  323. env.Append(CPPPATH = [
  324. env['SDK_INC_PATH'],
  325. env['DDK_INC_PATH'],
  326. env['WDM_INC_PATH'],
  327. env['CRT_INC_PATH'],
  328. ])
  329. # C compiler options
  330. cflags = [] # C
  331. cxxflags = [] # C++
  332. ccflags = [] # C & C++
  333. if gcc:
  334. if debug:
  335. ccflags += ['-O0', '-g3']
  336. elif env['toolchain'] == 'crossmingw':
  337. ccflags += ['-O0', '-g3'] # mingw 4.2.1 optimizer is broken
  338. else:
  339. ccflags += ['-O3', '-g0']
  340. if env['profile']:
  341. ccflags += ['-pg']
  342. if env['machine'] == 'x86':
  343. ccflags += [
  344. '-m32',
  345. #'-march=pentium4',
  346. '-mmmx', '-msse', '-msse2', # enable SIMD intrinsics
  347. #'-mfpmath=sse',
  348. ]
  349. if env['machine'] == 'x86_64':
  350. ccflags += ['-m64']
  351. # See also:
  352. # - http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
  353. ccflags += [
  354. '-Wall',
  355. '-Wmissing-field-initializers',
  356. '-Wpointer-arith',
  357. '-Wno-long-long',
  358. '-ffast-math',
  359. '-fmessage-length=0', # be nice to Eclipse
  360. ]
  361. cflags += [
  362. '-Werror=declaration-after-statement',
  363. '-Wmissing-prototypes',
  364. '-std=gnu99',
  365. ]
  366. if msvc:
  367. # See also:
  368. # - http://msdn.microsoft.com/en-us/library/19z1t1wy.aspx
  369. # - cl /?
  370. if debug:
  371. ccflags += [
  372. '/Od', # disable optimizations
  373. '/Oi', # enable intrinsic functions
  374. '/Oy-', # disable frame pointer omission
  375. '/GL-', # disable whole program optimization
  376. ]
  377. else:
  378. ccflags += [
  379. '/Ox', # maximum optimizations
  380. '/Oi', # enable intrinsic functions
  381. '/Ot', # favor code speed
  382. #'/fp:fast', # fast floating point
  383. ]
  384. if env['profile']:
  385. ccflags += [
  386. '/Gh', # enable _penter hook function
  387. '/GH', # enable _pexit hook function
  388. ]
  389. ccflags += [
  390. '/W3', # warning level
  391. #'/Wp64', # enable 64 bit porting warnings
  392. ]
  393. if env['machine'] == 'x86':
  394. ccflags += [
  395. #'/QIfist', # Suppress _ftol
  396. #'/arch:SSE2', # use the SSE2 instructions
  397. ]
  398. if platform == 'windows':
  399. ccflags += [
  400. # TODO
  401. ]
  402. if platform == 'winddk':
  403. ccflags += [
  404. '/Zl', # omit default library name in .OBJ
  405. '/Zp8', # 8bytes struct member alignment
  406. '/Gy', # separate functions for linker
  407. '/Gm-', # disable minimal rebuild
  408. '/WX', # treat warnings as errors
  409. '/Gz', # __stdcall Calling convention
  410. '/GX-', # disable C++ EH
  411. '/GR-', # disable C++ RTTI
  412. '/GF', # enable read-only string pooling
  413. '/G6', # optimize for PPro, P-II, P-III
  414. '/Ze', # enable extensions
  415. '/Gi-', # disable incremental compilation
  416. '/QIfdiv-', # disable Pentium FDIV fix
  417. '/hotpatch', # prepares an image for hotpatching.
  418. #'/Z7', #enable old-style debug info
  419. ]
  420. if platform == 'wince':
  421. # See also C:\WINCE600\public\common\oak\misc\makefile.def
  422. ccflags += [
  423. '/Zl', # omit default library name in .OBJ
  424. '/GF', # enable read-only string pooling
  425. '/GR-', # disable C++ RTTI
  426. '/GS', # enable security checks
  427. # Allow disabling language conformance to maintain backward compat
  428. #'/Zc:wchar_t-', # don't force wchar_t as native type, instead of typedef
  429. #'/Zc:forScope-', # don't enforce Standard C++ for scoping rules
  430. #'/wd4867',
  431. #'/wd4430',
  432. #'/MT',
  433. #'/U_MT',
  434. ]
  435. # Automatic pdb generation
  436. # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
  437. env.EnsureSConsVersion(0, 98, 0)
  438. env['PDB'] = '${TARGET.base}.pdb'
  439. env.Append(CCFLAGS = ccflags)
  440. env.Append(CFLAGS = cflags)
  441. env.Append(CXXFLAGS = cxxflags)
  442. if env['platform'] == 'windows' and msvc:
  443. # Choose the appropriate MSVC CRT
  444. # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
  445. if env['debug']:
  446. env.Append(CCFLAGS = ['/MTd'])
  447. env.Append(SHCCFLAGS = ['/LDd'])
  448. else:
  449. env.Append(CCFLAGS = ['/MT'])
  450. env.Append(SHCCFLAGS = ['/LD'])
  451. # Assembler options
  452. if gcc:
  453. if env['machine'] == 'x86':
  454. env.Append(ASFLAGS = ['-m32'])
  455. if env['machine'] == 'x86_64':
  456. env.Append(ASFLAGS = ['-m64'])
  457. # Linker options
  458. linkflags = []
  459. if gcc:
  460. if env['machine'] == 'x86':
  461. linkflags += ['-m32']
  462. if env['machine'] == 'x86_64':
  463. linkflags += ['-m64']
  464. if platform == 'windows' and msvc:
  465. # See also:
  466. # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
  467. linkflags += [
  468. '/fixed:no',
  469. '/incremental:no',
  470. ]
  471. if platform == 'winddk':
  472. linkflags += [
  473. '/merge:_PAGE=PAGE',
  474. '/merge:_TEXT=.text',
  475. '/section:INIT,d',
  476. '/opt:ref',
  477. '/opt:icf',
  478. '/ignore:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221',
  479. '/incremental:no',
  480. '/fullbuild',
  481. '/release',
  482. '/nodefaultlib',
  483. '/wx',
  484. '/debug',
  485. '/debugtype:cv',
  486. '/version:5.1',
  487. '/osversion:5.1',
  488. '/functionpadmin:5',
  489. '/safeseh',
  490. '/pdbcompress',
  491. '/stack:0x40000,0x1000',
  492. '/driver',
  493. '/align:0x80',
  494. '/subsystem:native,5.01',
  495. '/base:0x10000',
  496. '/entry:DrvEnableDriver',
  497. ]
  498. if env['debug'] or env['profile']:
  499. linkflags += [
  500. '/MAP', # http://msdn.microsoft.com/en-us/library/k7xkk3e2.aspx
  501. ]
  502. if platform == 'wince':
  503. linkflags += [
  504. '/nodefaultlib',
  505. #'/incremental:no',
  506. #'/fullbuild',
  507. '/entry:_DllMainCRTStartup',
  508. ]
  509. env.Append(LINKFLAGS = linkflags)
  510. # Default libs
  511. env.Append(LIBS = [])
  512. # Custom builders and methods
  513. createConvenienceLibBuilder(env)
  514. createCodeGenerateMethod(env)
  515. createInstallMethods(env)
  516. # for debugging
  517. #print env.Dump()
  518. def exists(env):
  519. return 1