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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. '-Werror=declaration-after-statement',
  355. '-Wall',
  356. '-Wmissing-prototypes',
  357. '-Wmissing-field-initializers',
  358. '-Wpointer-arith',
  359. '-Wno-long-long',
  360. '-ffast-math',
  361. '-std=gnu99',
  362. '-fmessage-length=0', # be nice to Eclipse
  363. ]
  364. if msvc:
  365. # See also:
  366. # - http://msdn.microsoft.com/en-us/library/19z1t1wy.aspx
  367. # - cl /?
  368. if debug:
  369. ccflags += [
  370. '/Od', # disable optimizations
  371. '/Oi', # enable intrinsic functions
  372. '/Oy-', # disable frame pointer omission
  373. '/GL-', # disable whole program optimization
  374. ]
  375. else:
  376. ccflags += [
  377. '/Ox', # maximum optimizations
  378. '/Oi', # enable intrinsic functions
  379. '/Ot', # favor code speed
  380. #'/fp:fast', # fast floating point
  381. ]
  382. if env['profile']:
  383. ccflags += [
  384. '/Gh', # enable _penter hook function
  385. '/GH', # enable _pexit hook function
  386. ]
  387. ccflags += [
  388. '/W3', # warning level
  389. #'/Wp64', # enable 64 bit porting warnings
  390. ]
  391. if env['machine'] == 'x86':
  392. ccflags += [
  393. #'/QIfist', # Suppress _ftol
  394. #'/arch:SSE2', # use the SSE2 instructions
  395. ]
  396. if platform == 'windows':
  397. ccflags += [
  398. # TODO
  399. ]
  400. if platform == 'winddk':
  401. ccflags += [
  402. '/Zl', # omit default library name in .OBJ
  403. '/Zp8', # 8bytes struct member alignment
  404. '/Gy', # separate functions for linker
  405. '/Gm-', # disable minimal rebuild
  406. '/WX', # treat warnings as errors
  407. '/Gz', # __stdcall Calling convention
  408. '/GX-', # disable C++ EH
  409. '/GR-', # disable C++ RTTI
  410. '/GF', # enable read-only string pooling
  411. '/G6', # optimize for PPro, P-II, P-III
  412. '/Ze', # enable extensions
  413. '/Gi-', # disable incremental compilation
  414. '/QIfdiv-', # disable Pentium FDIV fix
  415. '/hotpatch', # prepares an image for hotpatching.
  416. #'/Z7', #enable old-style debug info
  417. ]
  418. if platform == 'wince':
  419. # See also C:\WINCE600\public\common\oak\misc\makefile.def
  420. ccflags += [
  421. '/Zl', # omit default library name in .OBJ
  422. '/GF', # enable read-only string pooling
  423. '/GR-', # disable C++ RTTI
  424. '/GS', # enable security checks
  425. # Allow disabling language conformance to maintain backward compat
  426. #'/Zc:wchar_t-', # don't force wchar_t as native type, instead of typedef
  427. #'/Zc:forScope-', # don't enforce Standard C++ for scoping rules
  428. #'/wd4867',
  429. #'/wd4430',
  430. #'/MT',
  431. #'/U_MT',
  432. ]
  433. # Automatic pdb generation
  434. # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
  435. env.EnsureSConsVersion(0, 98, 0)
  436. env['PDB'] = '${TARGET.base}.pdb'
  437. env.Append(CCFLAGS = ccflags)
  438. env.Append(CFLAGS = cflags)
  439. env.Append(CXXFLAGS = cxxflags)
  440. if env['platform'] == 'windows' and msvc:
  441. # Choose the appropriate MSVC CRT
  442. # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
  443. if env['debug']:
  444. env.Append(CCFLAGS = ['/MTd'])
  445. env.Append(SHCCFLAGS = ['/LDd'])
  446. else:
  447. env.Append(CCFLAGS = ['/MT'])
  448. env.Append(SHCCFLAGS = ['/LD'])
  449. # Assembler options
  450. if gcc:
  451. if env['machine'] == 'x86':
  452. env.Append(ASFLAGS = ['-m32'])
  453. if env['machine'] == 'x86_64':
  454. env.Append(ASFLAGS = ['-m64'])
  455. # Linker options
  456. linkflags = []
  457. if gcc:
  458. if env['machine'] == 'x86':
  459. linkflags += ['-m32']
  460. if env['machine'] == 'x86_64':
  461. linkflags += ['-m64']
  462. if platform == 'windows' and msvc:
  463. # See also:
  464. # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
  465. linkflags += [
  466. '/fixed:no',
  467. '/incremental:no',
  468. ]
  469. if platform == 'winddk':
  470. linkflags += [
  471. '/merge:_PAGE=PAGE',
  472. '/merge:_TEXT=.text',
  473. '/section:INIT,d',
  474. '/opt:ref',
  475. '/opt:icf',
  476. '/ignore:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221',
  477. '/incremental:no',
  478. '/fullbuild',
  479. '/release',
  480. '/nodefaultlib',
  481. '/wx',
  482. '/debug',
  483. '/debugtype:cv',
  484. '/version:5.1',
  485. '/osversion:5.1',
  486. '/functionpadmin:5',
  487. '/safeseh',
  488. '/pdbcompress',
  489. '/stack:0x40000,0x1000',
  490. '/driver',
  491. '/align:0x80',
  492. '/subsystem:native,5.01',
  493. '/base:0x10000',
  494. '/entry:DrvEnableDriver',
  495. ]
  496. if env['debug'] or env['profile']:
  497. linkflags += [
  498. '/MAP', # http://msdn.microsoft.com/en-us/library/k7xkk3e2.aspx
  499. ]
  500. if platform == 'wince':
  501. linkflags += [
  502. '/nodefaultlib',
  503. #'/incremental:no',
  504. #'/fullbuild',
  505. '/entry:_DllMainCRTStartup',
  506. ]
  507. env.Append(LINKFLAGS = linkflags)
  508. # Default libs
  509. env.Append(LIBS = [])
  510. # Custom builders and methods
  511. createConvenienceLibBuilder(env)
  512. createCodeGenerateMethod(env)
  513. createInstallMethods(env)
  514. # for debugging
  515. #print env.Dump()
  516. def exists(env):
  517. return 1