Clone of mesa.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

generic.py 18KB

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