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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. '_USE_MATH_DEFINES',
  276. '_CRT_SECURE_NO_WARNINGS',
  277. '_CRT_SECURE_NO_DEPRECATE',
  278. '_SCL_SECURE_NO_WARNINGS',
  279. '_SCL_SECURE_NO_DEPRECATE',
  280. ]
  281. if debug:
  282. cppdefines += ['_DEBUG']
  283. if platform == 'winddk':
  284. # Mimic WINDDK's builtin flags. See also:
  285. # - WINDDK's bin/makefile.new i386mk.inc for more info.
  286. # - buildchk_wxp_x86.log files, generated by the WINDDK's build
  287. # - http://alter.org.ua/docs/nt_kernel/vc8_proj/
  288. cppdefines += [
  289. ('_X86_', '1'),
  290. ('i386', '1'),
  291. 'STD_CALL',
  292. ('CONDITION_HANDLING', '1'),
  293. ('NT_INST', '0'),
  294. ('WIN32', '100'),
  295. ('_NT1X_', '100'),
  296. ('WINNT', '1'),
  297. ('_WIN32_WINNT', '0x0501'), # minimum required OS version
  298. ('WINVER', '0x0501'),
  299. ('_WIN32_IE', '0x0603'),
  300. ('WIN32_LEAN_AND_MEAN', '1'),
  301. ('DEVL', '1'),
  302. ('__BUILDMACHINE__', 'WinDDK'),
  303. ('FPO', '0'),
  304. ]
  305. if debug:
  306. cppdefines += [('DBG', 1)]
  307. if platform == 'wince':
  308. cppdefines += [
  309. '_CRT_SECURE_NO_DEPRECATE',
  310. '_USE_32BIT_TIME_T',
  311. 'UNICODE',
  312. '_UNICODE',
  313. ('UNDER_CE', '600'),
  314. ('_WIN32_WCE', '0x600'),
  315. 'WINCEOEM',
  316. 'WINCEINTERNAL',
  317. 'WIN32',
  318. 'STRICT',
  319. 'x86',
  320. '_X86_',
  321. 'INTERNATIONAL',
  322. ('INTLMSG_CODEPAGE', '1252'),
  323. ]
  324. env.Append(CPPDEFINES = cppdefines)
  325. # C preprocessor includes
  326. if platform == 'winddk':
  327. env.Append(CPPPATH = [
  328. env['SDK_INC_PATH'],
  329. env['DDK_INC_PATH'],
  330. env['WDM_INC_PATH'],
  331. env['CRT_INC_PATH'],
  332. ])
  333. # C compiler options
  334. cflags = [] # C
  335. cxxflags = [] # C++
  336. ccflags = [] # C & C++
  337. if gcc:
  338. if debug:
  339. ccflags += ['-O0', '-g3']
  340. elif env['toolchain'] == 'crossmingw':
  341. ccflags += ['-O0', '-g3'] # mingw 4.2.1 optimizer is broken
  342. else:
  343. ccflags += ['-O3', '-g0']
  344. if env['machine'] == 'x86':
  345. ccflags += [
  346. '-m32',
  347. #'-march=pentium4',
  348. '-mmmx', '-msse', '-msse2', # enable SIMD intrinsics
  349. #'-mfpmath=sse',
  350. ]
  351. if env['machine'] == 'x86_64':
  352. ccflags += ['-m64']
  353. # See also:
  354. # - http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
  355. ccflags += [
  356. '-Wall',
  357. '-Wmissing-field-initializers',
  358. '-Wpointer-arith',
  359. '-Wno-long-long',
  360. '-ffast-math',
  361. '-fmessage-length=0', # be nice to Eclipse
  362. ]
  363. cflags += [
  364. '-Werror=declaration-after-statement',
  365. '-Wmissing-prototypes',
  366. '-std=gnu99',
  367. ]
  368. if msvc:
  369. # See also:
  370. # - http://msdn.microsoft.com/en-us/library/19z1t1wy.aspx
  371. # - cl /?
  372. if debug:
  373. ccflags += [
  374. '/Od', # disable optimizations
  375. '/Oi', # enable intrinsic functions
  376. '/Oy-', # disable frame pointer omission
  377. '/GL-', # disable whole program optimization
  378. ]
  379. else:
  380. ccflags += [
  381. '/Ox', # maximum optimizations
  382. '/Oi', # enable intrinsic functions
  383. '/Ot', # favor code speed
  384. #'/fp:fast', # fast floating point
  385. ]
  386. ccflags += [
  387. '/W3', # warning level
  388. #'/Wp64', # enable 64 bit porting warnings
  389. ]
  390. if env['machine'] == 'x86':
  391. ccflags += [
  392. #'/QIfist', # Suppress _ftol
  393. #'/arch:SSE2', # use the SSE2 instructions
  394. ]
  395. if platform == 'windows':
  396. ccflags += [
  397. # TODO
  398. ]
  399. if platform == 'winddk':
  400. ccflags += [
  401. '/Zl', # omit default library name in .OBJ
  402. '/Zp8', # 8bytes struct member alignment
  403. '/Gy', # separate functions for linker
  404. '/Gm-', # disable minimal rebuild
  405. '/WX', # treat warnings as errors
  406. '/Gz', # __stdcall Calling convention
  407. '/GX-', # disable C++ EH
  408. '/GR-', # disable C++ RTTI
  409. '/GF', # enable read-only string pooling
  410. '/G6', # optimize for PPro, P-II, P-III
  411. '/Ze', # enable extensions
  412. '/Gi-', # disable incremental compilation
  413. '/QIfdiv-', # disable Pentium FDIV fix
  414. '/hotpatch', # prepares an image for hotpatching.
  415. #'/Z7', #enable old-style debug info
  416. ]
  417. if platform == 'wince':
  418. # See also C:\WINCE600\public\common\oak\misc\makefile.def
  419. ccflags += [
  420. '/Zl', # omit default library name in .OBJ
  421. '/GF', # enable read-only string pooling
  422. '/GR-', # disable C++ RTTI
  423. '/GS', # enable security checks
  424. # Allow disabling language conformance to maintain backward compat
  425. #'/Zc:wchar_t-', # don't force wchar_t as native type, instead of typedef
  426. #'/Zc:forScope-', # don't enforce Standard C++ for scoping rules
  427. #'/wd4867',
  428. #'/wd4430',
  429. #'/MT',
  430. #'/U_MT',
  431. ]
  432. # Automatic pdb generation
  433. # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
  434. env.EnsureSConsVersion(0, 98, 0)
  435. env['PDB'] = '${TARGET.base}.pdb'
  436. env.Append(CCFLAGS = ccflags)
  437. env.Append(CFLAGS = cflags)
  438. env.Append(CXXFLAGS = cxxflags)
  439. if env['platform'] == 'windows' and msvc:
  440. # Choose the appropriate MSVC CRT
  441. # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
  442. if env['debug']:
  443. env.Append(CCFLAGS = ['/MTd'])
  444. env.Append(SHCCFLAGS = ['/LDd'])
  445. else:
  446. env.Append(CCFLAGS = ['/MT'])
  447. env.Append(SHCCFLAGS = ['/LD'])
  448. # Assembler options
  449. if gcc:
  450. if env['machine'] == 'x86':
  451. env.Append(ASFLAGS = ['-m32'])
  452. if env['machine'] == 'x86_64':
  453. env.Append(ASFLAGS = ['-m64'])
  454. # Linker options
  455. linkflags = []
  456. if gcc:
  457. if env['machine'] == 'x86':
  458. linkflags += ['-m32']
  459. if env['machine'] == 'x86_64':
  460. linkflags += ['-m64']
  461. if platform == 'windows' and msvc:
  462. # See also:
  463. # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
  464. linkflags += [
  465. '/fixed:no',
  466. '/incremental:no',
  467. ]
  468. if platform == 'winddk':
  469. linkflags += [
  470. '/merge:_PAGE=PAGE',
  471. '/merge:_TEXT=.text',
  472. '/section:INIT,d',
  473. '/opt:ref',
  474. '/opt:icf',
  475. '/ignore:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221',
  476. '/incremental:no',
  477. '/fullbuild',
  478. '/release',
  479. '/nodefaultlib',
  480. '/wx',
  481. '/debug',
  482. '/debugtype:cv',
  483. '/version:5.1',
  484. '/osversion:5.1',
  485. '/functionpadmin:5',
  486. '/safeseh',
  487. '/pdbcompress',
  488. '/stack:0x40000,0x1000',
  489. '/driver',
  490. '/align:0x80',
  491. '/subsystem:native,5.01',
  492. '/base:0x10000',
  493. '/entry:DrvEnableDriver',
  494. ]
  495. if env['debug'] or env['profile']:
  496. linkflags += [
  497. '/MAP', # http://msdn.microsoft.com/en-us/library/k7xkk3e2.aspx
  498. ]
  499. if platform == 'wince':
  500. linkflags += [
  501. '/nodefaultlib',
  502. #'/incremental:no',
  503. #'/fullbuild',
  504. '/entry:_DllMainCRTStartup',
  505. ]
  506. env.Append(LINKFLAGS = linkflags)
  507. # Default libs
  508. env.Append(LIBS = [])
  509. # Custom builders and methods
  510. createConvenienceLibBuilder(env)
  511. createCodeGenerateMethod(env)
  512. createInstallMethods(env)
  513. # for debugging
  514. #print env.Dump()
  515. def exists(env):
  516. return 1