ymake_conf.py 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658
  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. from __future__ import print_function
  4. import base64
  5. import itertools
  6. import json
  7. import logging
  8. import ntpath
  9. import optparse
  10. import os
  11. import posixpath
  12. import re
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import six
  17. from functools import total_ordering
  18. logger = logging.getLogger(__name__ if __name__ != '__main__' else 'ymake_conf.py')
  19. class WindowsVersion(object):
  20. """
  21. Predefined values for _WIN32_WINNT macro.
  22. This macro specifies minimal Windows version required by the binary being build.
  23. A complete list of the values supported by the Windows SDK can be found at
  24. https://docs.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt
  25. """
  26. Windows07 = '0x0601'
  27. Windows08 = '0x0602'
  28. Windows10 = '0x0A00'
  29. # This is default Android API level unless `-DANDROID_API` is specified in cmdline
  30. # Android api level can be resolved to Android version using
  31. # https://android.googlesource.com/platform/bionic/+/master/docs/status.md
  32. ANDROID_API_DEFAULT = 21
  33. # This is default Linux SDK unless `-DOS_SDK` is specified in cmdline
  34. LINUX_SDK_DEFAULT = "ubuntu-14"
  35. MACOS_VERSION_MIN = "11.0"
  36. MACOS_VERSION_MIN_AS_INT = "110000"
  37. IOS_VERSION_MIN = "13.0"
  38. WINDOWS_VERSION_MIN = WindowsVersion.Windows07
  39. def init_logger(verbose):
  40. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
  41. def find_conf(conf_file):
  42. script_dir = os.path.dirname(__file__)
  43. full_path = os.path.join(script_dir, conf_file)
  44. if os.path.exists(full_path):
  45. return full_path
  46. return None
  47. # All paths in build graph shall be in posix format.
  48. # This ensures that UIDs of cross and native builds won't diverge
  49. # due to paths difference. This function is to be used to fix paths produced
  50. # by os.path.join on Windows.
  51. #
  52. # FIXME: upon complete switch to Python3 os.path.join may be replaced by posixpath.join
  53. # and this function will become unnecessary
  54. def win_path_fix(path):
  55. return path if sys.platform != 'win32' else path.replace('\\', '/')
  56. class DebugString(object):
  57. def __init__(self, get_string_func):
  58. self.get_string_func = get_string_func
  59. def __str__(self):
  60. return self.get_string_func()
  61. class ConfigureError(Exception):
  62. pass
  63. @total_ordering
  64. class Platform(object):
  65. def __init__(self, name, os, arch):
  66. """
  67. :type name: str
  68. :type os: str
  69. :type arch: str
  70. """
  71. self.name = name
  72. self.os = self._parse_os(os)
  73. self.arch = arch.lower()
  74. self.is_i386 = self.arch in ('i386', 'x86')
  75. self.is_i686 = self.arch == 'i686'
  76. self.is_x86 = self.is_i386 or self.is_i686
  77. self.is_x86_64 = self.arch in ('x86_64', 'amd64')
  78. self.is_intel = self.is_x86 or self.is_x86_64
  79. self.is_armv7 = self.arch in ('armv7', 'armv7a', 'armv7ahf', 'armv7a_neon', 'arm', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  80. self.is_armv8 = self.arch in ('armv8', 'armv8a', 'arm64', 'aarch64', 'armv8a_cortex_a35', 'armv8a_cortex_a53')
  81. self.is_armv8m = self.arch in ('armv8m_cortex_m33', 'armv8m_cortex_m23')
  82. self.is_armv7em = self.arch in ('armv7em_cortex_m4', 'armv7em_cortex_m7')
  83. self.is_arm64 = self.arch in ('arm64',)
  84. self.is_arm = self.is_armv7 or self.is_armv8 or self.is_armv8m or self.is_armv7em
  85. self.is_armv7_neon = self.arch in ('armv7a_neon', 'armv7ahf', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  86. self.is_armv7hf = self.arch in ('armv7ahf', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  87. self.is_armv5te = self.arch in ('armv5te_arm968e_s')
  88. self.is_rv32imc = self.arch in ('riscv32_esp',)
  89. self.is_riscv32 = self.is_rv32imc
  90. self.is_nds32 = self.arch in ('nds32le_elf_mculib_v5f',)
  91. self.is_tc32 = self.arch in ('tc32_elf',)
  92. self.is_xtensa = self.arch in ('xtensa_hifi5',)
  93. self.armv7_float_abi = None
  94. if self.is_armv7:
  95. if self.is_armv7hf:
  96. self.armv7_float_abi = 'hard'
  97. else:
  98. self.armv7_float_abi = 'softfp'
  99. self.is_cortex_a9 = self.arch in ('armv7a_cortex_a9',)
  100. self.is_cortex_a35 = self.arch in ('armv7ahf_cortex_a35', 'armv8a_cortex_a35')
  101. self.is_cortex_a53 = self.arch in ('armv7ahf_cortex_a53', 'armv8a_cortex_a53')
  102. self.is_cortex_m33 = self.arch in ('armv8m_cortex_m33',)
  103. self.is_cortex_m23 = self.arch in ('armv8m_cortex_m23',)
  104. self.is_cortex_m4 = self.arch in ('armv7em_cortex_m4',)
  105. self.is_cortex_m7 = self.arch in ('armv7em_cortex_m7')
  106. self.is_arm968e_s = self.arch in ('armv5te_arm968e_s')
  107. self.is_power8le = self.arch == 'ppc64le'
  108. self.is_power9le = self.arch == 'power9le'
  109. self.is_powerpc = self.is_power8le or self.is_power9le
  110. self.is_wasm64 = self.arch == 'wasm64'
  111. self.is_wasm = self.is_wasm64
  112. self.is_32_bit = self.is_x86 or self.is_armv5te or self.is_armv7 or self.is_armv8m or self.is_riscv32 or self.is_nds32 or self.is_armv7em or self.is_xtensa or self.is_tc32
  113. self.is_64_bit = self.is_x86_64 or self.is_armv8 or self.is_powerpc or self.is_wasm64
  114. assert self.is_32_bit or self.is_64_bit
  115. assert not (self.is_32_bit and self.is_64_bit)
  116. self.is_linux = self.os == 'linux' or 'yocto' in self.os
  117. self.is_linux_x86_64 = self.is_linux and self.is_x86_64
  118. self.is_linux_armv8 = self.is_linux and self.is_armv8
  119. self.is_linux_armv7 = self.is_linux and self.is_armv7
  120. self.is_linux_power8le = self.is_linux and self.is_power8le
  121. self.is_linux_power9le = self.is_linux and self.is_power9le
  122. self.is_linux_powerpc = self.is_linux_power8le or self.is_linux_power9le
  123. self.is_macos = self.os == 'macos'
  124. self.is_macos_x86_64 = self.is_macos and self.is_x86_64
  125. self.is_macos_arm64 = self.is_macos and self.is_arm64
  126. self.is_iossim = self.os == 'iossim' or (self.os == 'ios' and self.is_intel)
  127. self.is_ios = self.os == 'ios' or self.is_iossim
  128. self.is_apple = self.is_macos or self.is_ios
  129. self.is_windows = self.os == 'windows'
  130. self.is_windows_x86_64 = self.is_windows and self.is_x86_64
  131. self.is_android = self.os == 'android'
  132. if self.is_android:
  133. self.android_api = int(preset('ANDROID_API', ANDROID_API_DEFAULT))
  134. self.is_cygwin = self.os == 'cygwin'
  135. self.is_yocto = self.os == 'yocto'
  136. self.is_emscripten = self.os == 'emscripten'
  137. self.is_none = self.os == 'none'
  138. self.is_posix = self.is_linux or self.is_apple or self.is_android or self.is_cygwin or self.is_yocto
  139. @staticmethod
  140. def from_json(data):
  141. name = data.get('visible_name', data['toolchain'])
  142. return Platform(name, os=data['os'], arch=data['arch'])
  143. @property
  144. def os_variables(self):
  145. # 'LINUX' variable, for backward compatibility
  146. yield self.os.upper()
  147. # 'OS_LINUX' variable
  148. yield 'OS_{}'.format(self.os.upper())
  149. # yocto is linux
  150. if 'yocto' in self.os:
  151. yield 'LINUX'
  152. yield 'OS_LINUX'
  153. if self.is_macos:
  154. yield 'DARWIN'
  155. yield 'OS_DARWIN'
  156. if self.is_iossim:
  157. yield 'IOS'
  158. yield 'OS_IOS'
  159. yield 'OS_IOSSIM'
  160. @property
  161. def arch_variables(self):
  162. return select_multiple((
  163. (self.is_i386 or self.is_i686, 'ARCH_I386'),
  164. (self.is_i686, 'ARCH_I686'),
  165. (self.is_x86_64, 'ARCH_X86_64'),
  166. (self.is_armv7, 'ARCH_ARM7'),
  167. (self.is_armv7_neon, 'ARCH_ARM7_NEON'),
  168. (self.is_armv8, 'ARCH_ARM64'),
  169. (self.is_armv8m, 'ARCH_ARM8M'),
  170. (self.is_armv7em, 'ARCH_ARM7EM'),
  171. (self.is_armv5te, 'ARCH_ARM5TE'),
  172. (self.is_arm, 'ARCH_ARM'),
  173. (self.is_linux_armv8 or self.is_macos_arm64, 'ARCH_AARCH64'),
  174. (self.is_powerpc, 'ARCH_PPC64LE'),
  175. (self.is_power8le, 'ARCH_POWER8LE'),
  176. (self.is_power9le, 'ARCH_POWER9LE'),
  177. (self.is_riscv32, 'ARCH_RISCV32'),
  178. (self.is_xtensa, 'ARCH_XTENSA'),
  179. (self.is_nds32, 'ARCH_NDS32'),
  180. (self.is_tc32, 'ARCH_TC32'),
  181. (self.is_wasm64, 'ARCH_WASM64'),
  182. (self.is_32_bit, 'ARCH_TYPE_32'),
  183. (self.is_64_bit, 'ARCH_TYPE_64'),
  184. ))
  185. @property
  186. def library_path_variables(self):
  187. return ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
  188. def find_in_dict(self, dict_, default=None):
  189. if dict_ is None:
  190. return default
  191. for key in six.iterkeys(dict_):
  192. if self._parse_os(key) == self.os:
  193. return dict_[key]
  194. return default
  195. @property
  196. def os_compat(self):
  197. if self.is_macos:
  198. return 'DARWIN'
  199. else:
  200. return self.os.upper()
  201. @property
  202. def canonized_platform(self):
  203. os = None
  204. if self.os == 'macos':
  205. os = 'darwin'
  206. elif self.os == 'windows':
  207. os = 'win32'
  208. else:
  209. os = self.os
  210. if self.arch != 'x86_64':
  211. return '-'.join([os, self.arch])
  212. else:
  213. return os
  214. def exe(self, *paths):
  215. if self.is_windows:
  216. return ntpath.join(*itertools.chain(paths[:-1], (paths[-1] + '.exe',)))
  217. else:
  218. return posixpath.join(*paths)
  219. def __str__(self):
  220. return '{name}-{os}-{arch}'.format(name=self.name, os=self.os, arch=self.arch)
  221. def __eq__(self, other):
  222. return (self.name, self.os, self.arch) == (other.name, other.os, other.arch)
  223. def __lt__(self, other):
  224. return (self.name, self.os, self.arch) < (other.name, other.os, other.arch)
  225. def __hash__(self):
  226. return hash((self.name, self.os, self.arch))
  227. @staticmethod
  228. def _parse_os(os):
  229. os = os.lower()
  230. if os == 'darwin':
  231. return 'macos'
  232. if os in ('win', 'win32', 'win64'):
  233. return 'windows'
  234. if os.startswith('cygwin'):
  235. return 'cygwin'
  236. return os
  237. def which(prog):
  238. if os.path.exists(prog) and os.access(prog, os.X_OK):
  239. return prog
  240. # Ищем в $PATH только простые команды, без путей.
  241. if os.path.dirname(prog) != '':
  242. return None
  243. path = os.getenv('PATH', '')
  244. pathext = os.environ.get('PATHEXT')
  245. # На Windows %PATHEXT% указывает на список расширений, которые нужно проверять
  246. # при поиске команды в пути. Точное совпадение без расширения имеет приоритет.
  247. pathext = [''] if pathext is None else [''] + pathext.lower().split(os.pathsep)
  248. for dir_ in path.split(os.path.pathsep):
  249. for ext in pathext:
  250. p = os.path.join(dir_, prog + ext)
  251. if os.path.exists(p) and os.path.isfile(p) and os.access(p, os.X_OK):
  252. return win_path_fix(p)
  253. return None
  254. def get_stdout(command):
  255. stdout, code = get_stdout_and_code(command)
  256. return stdout if code == 0 else None
  257. def get_stdout_and_code(command):
  258. # noinspection PyBroadException
  259. try:
  260. process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  261. stdout, _ = process.communicate()
  262. return six.ensure_str(stdout), process.returncode
  263. except Exception as e:
  264. logger.info("While run: `%s`", e)
  265. return None, None
  266. def to_strings(o):
  267. if isinstance(o, (list, tuple)):
  268. for s in o:
  269. for ss in to_strings(s):
  270. yield ss
  271. else:
  272. if o is not None:
  273. if isinstance(o, bool):
  274. yield 'yes' if o else 'no'
  275. elif isinstance(o, (str, int)):
  276. yield str(o)
  277. else:
  278. raise ConfigureError('Unexpected value {} {}'.format(type(o), o))
  279. def emit(key, *value):
  280. print('{0}={1}'.format(key, ' '.join(to_strings(value))))
  281. def emit_with_comment(comment, key, *value):
  282. print('# {}'.format(comment))
  283. emit(key, *value)
  284. def emit_with_ignore_comment(key, *value):
  285. emit_with_comment('IGNORE YMAKE CONF CONTEXT', key, *value)
  286. def append(key, *value):
  287. print('{0}+={1}'.format(key, ' '.join(to_strings(value))))
  288. def emit_big(text):
  289. prefix = None
  290. first = True
  291. for line in text.split('\n'):
  292. if prefix is None:
  293. if not line:
  294. continue
  295. prefix = 0
  296. while prefix < len(line) and line[prefix] == ' ':
  297. prefix += 1
  298. if first: # Be pretty, prepend an empty line before the output
  299. print()
  300. first = False
  301. print(line[prefix:])
  302. class Variables(dict):
  303. def emit(self, with_ignore_comment=[]):
  304. with_ignore_comment_set = set(with_ignore_comment)
  305. for k in sorted(self.keys()):
  306. if k in with_ignore_comment_set:
  307. emit_with_ignore_comment(k, self[k])
  308. else:
  309. emit(k, self[k])
  310. def update_from_presets(self):
  311. for k in six.iterkeys(self):
  312. v = preset(k)
  313. if v is not None:
  314. self[k] = v
  315. def reset_if_any(self, value_check=None, reset_value=None):
  316. if value_check is None:
  317. def value_check(v_):
  318. return v_ is None
  319. if any(map(value_check, six.itervalues(self))):
  320. for k in six.iterkeys(self):
  321. self[k] = reset_value
  322. def format_env(env, list_separator=':'):
  323. def format_value(value):
  324. return value if isinstance(value, str) else ('\\' + list_separator).join(value)
  325. def format(kv):
  326. return '${env:"%s=%s"}' % (kv[0], format_value(kv[1]))
  327. return ' '.join(map(format, sorted(six.iteritems(env))))
  328. # TODO(somov): Проверить, используется ли это. Может быть, выпилить.
  329. def userify_presets(presets, keys):
  330. for key in keys:
  331. user_key = 'USER_{}'.format(key)
  332. values = [presets.pop(key, None), presets.get(user_key)]
  333. presets[user_key] = ' '.join(filter(None, values))
  334. def preset(key, default=None):
  335. return opts().presets.get(key, default)
  336. def is_positive(key):
  337. return is_positive_str(preset(key, ''))
  338. def is_positive_str(s):
  339. return s.lower() in ('yes', 'true', 'on', '1')
  340. def is_negative(key):
  341. return is_negative_str(preset(key, ''))
  342. def is_negative_str(s):
  343. return s.lower() in ('no', 'false', 'off', '0')
  344. def to_bool(s, default=None):
  345. if isinstance(s, six.string_types):
  346. if is_positive_str(s):
  347. return True
  348. if is_negative_str(s):
  349. return False
  350. if default is None:
  351. raise ConfigureError('{} is not a bool value'.format(s))
  352. return default
  353. def select(selectors, default=None, no_default=False):
  354. for enabled, value in selectors:
  355. if enabled:
  356. return value
  357. if no_default:
  358. raise ConfigureError()
  359. return default
  360. def select_multiple(selectors):
  361. for enabled, value in selectors:
  362. if enabled:
  363. yield value
  364. def unique(it):
  365. known = set()
  366. for i in it:
  367. if i not in known:
  368. known.add(i)
  369. yield i
  370. class Options(object):
  371. def __init__(self, argv):
  372. def parse_presets(raw_presets):
  373. presets = {}
  374. for p in raw_presets:
  375. toks = p.split('=', 1)
  376. name = toks[0]
  377. value = toks[1] if len(toks) >= 2 else ''
  378. presets[name] = value
  379. return presets
  380. parser = optparse.OptionParser(add_help_option=False)
  381. opt_group = optparse.OptionGroup(parser, 'Conf script options')
  382. opt_group.add_option('--toolchain-params', dest='toolchain_params', action='store', help='Set toolchain params via file')
  383. opt_group.add_option('-D', '--preset', dest='presets', action='append', default=[], help='set or override presets')
  384. opt_group.add_option('-l', '--local-distbuild', dest='local_distbuild', action='store_true', default=False, help='conf for local distbuild')
  385. parser.add_option_group(opt_group)
  386. self.options, self.arguments = parser.parse_args(argv)
  387. argv = self.arguments
  388. if len(argv) < 4:
  389. print('Usage: ArcRoot, --BuildType--, Verbosity, [Path to local.ymake]', file=sys.stderr)
  390. sys.exit(1)
  391. self.arcadia_root = argv[1]
  392. init_logger(argv[3] == 'verbose')
  393. # Эти переменные не надо использоваться напрямую. Их значения уже разбираются в других местах.
  394. self.build_type = argv[2].lower()
  395. self.local_distbuild = self.options.local_distbuild
  396. self.toolchain_params = self.options.toolchain_params
  397. self.presets = parse_presets(self.options.presets)
  398. userify_presets(self.presets, ('CFLAGS', 'CXXFLAGS', 'CONLYFLAGS', 'LDFLAGS', 'GO_COMPILE_FLAGS', 'GO_LINK_FLAGS', 'STD_CXX_VERSION'))
  399. Instance = None
  400. def opts():
  401. if Options.Instance is None:
  402. Options.Instance = Options(sys.argv)
  403. return Options.Instance
  404. class Profiler(object):
  405. Generic = 'generic'
  406. GProf = 'gprof'
  407. class Arcadia(object):
  408. def __init__(self, root):
  409. self.root = root
  410. class Build(object):
  411. def __init__(self, arcadia, build_type, toolchain_params, force_ignore_local_files=False):
  412. self.arcadia = arcadia
  413. self.params = self._load_json_from_base64(toolchain_params)
  414. self.build_type = build_type
  415. platform = self.params['platform']
  416. self.host = Platform.from_json(platform['host'])
  417. self.target = Platform.from_json(platform['target'])
  418. self.tc = self._get_toolchain_options()
  419. # TODO(somov): Удалить, когда перестанет использоваться.
  420. self.build_system = 'ymake'
  421. self.ignore_local_files = False
  422. dist_prefix = 'dist-'
  423. if self.build_type.startswith(dist_prefix):
  424. self.build_system = 'distbuild'
  425. self.build_type = self.build_type[len(dist_prefix):]
  426. if force_ignore_local_files:
  427. self.ignore_local_files = True
  428. if self.is_ide_build_type(self.build_type):
  429. self.ignore_local_files = True
  430. self.pic = not is_positive('FORCE_NO_PIC')
  431. @property
  432. def host_target(self):
  433. return self.host, self.target
  434. def print_build(self):
  435. self._print_build_settings()
  436. host_os = System(self.host)
  437. host_os.print_host_settings()
  438. target_os = System(self.target)
  439. target_os.print_target_settings()
  440. if self.pic:
  441. emit('PIC', 'yes')
  442. emit('COMPILER_ID', self.tc.type.upper())
  443. if self.is_valgrind:
  444. emit('WITH_VALGRIND', 'yes')
  445. if self.is_coverage:
  446. emit('_BUILD_COVERAGE', 'yes')
  447. if self.is_debug:
  448. emit('_BUILD_DEBUG', 'yes')
  449. if self.is_fast_debug:
  450. emit('_BUILD_FAST_DEBUG', 'yes')
  451. if self.is_release:
  452. emit('_BUILD_RELEASE', 'yes')
  453. if self.is_sanitized:
  454. emit('_BUILD_SANITIZED', 'yes')
  455. if self.is_size_optimized:
  456. emit('_BUILD_SIZE_OPTIMIZED', 'yes')
  457. if self.with_ndebug:
  458. emit('_BUILD_WITH_NDEBUG', 'yes')
  459. toolchain_type, compiler_type, linker_type = Compilers[self.tc.type]
  460. toolchain = toolchain_type(self.tc, self)
  461. compiler = compiler_type(self.tc, self)
  462. linker = linker_type(self.tc, self)
  463. toolchain.print_toolchain()
  464. compiler.print_compiler()
  465. linker.print_linker()
  466. self._print_other_settings(compiler)
  467. def _print_build_settings(self):
  468. emit('BUILD_TYPE', self.build_type.upper())
  469. emit('BT_' + self.build_type.upper().replace('-', '_'), 'yes')
  470. if self.build_system == 'distbuild':
  471. emit('DISTBUILD', 'yes')
  472. elif self.build_system != 'ymake':
  473. raise ConfigureError()
  474. python_bin = preset('BUILD_PYTHON_BIN', '$(PYTHON)/python')
  475. emit('YMAKE_PYTHON', python_bin)
  476. emit('YMAKE_UNPICKLER', python_bin, '$ARCADIA_ROOT/build/plugins/_unpickler.py')
  477. @property
  478. def is_release(self):
  479. # TODO(somov): Проверить, бывают ли тут суффиксы на самом деле
  480. return self.build_type in ('release', 'relwithdebinfo', 'minsizerel', 'profile', 'gprof') or self.build_type.endswith('-release')
  481. @property
  482. def is_debug(self):
  483. return self.build_type in ('debug', 'debugnoasserts', 'fastdebug') or self.build_type.endswith('-debug')
  484. @property
  485. def is_fast_debug(self):
  486. return self.build_type == 'fastdebug'
  487. @property
  488. def is_size_optimized(self):
  489. return self.build_type == 'minsizerel'
  490. @property
  491. def is_coverage(self):
  492. return self.build_type == 'coverage'
  493. @property
  494. def is_sanitized(self):
  495. sanitizer = preset('SANITIZER_TYPE')
  496. return bool(sanitizer) and not is_negative_str(sanitizer)
  497. @property
  498. def with_ndebug(self):
  499. return self.build_type in ('release', 'minsizerel', 'valgrind-release', 'profile', 'gprof', 'debugnoasserts')
  500. @property
  501. def is_valgrind(self):
  502. return self.build_type == 'valgrind' or self.build_type == 'valgrind-release'
  503. @property
  504. def is_ide(self):
  505. return self.is_ide_build_type(self.build_type)
  506. @property
  507. def profiler_type(self):
  508. if self.build_type == 'profile':
  509. return Profiler.Generic
  510. elif self.build_type == 'gprof':
  511. return Profiler.GProf
  512. else:
  513. return None
  514. @staticmethod
  515. def is_ide_build_type(build_type):
  516. return build_type == 'nobuild'
  517. def _configure_runtime_versions(self):
  518. try:
  519. res = subprocess.check_output(['xcrun', 'simctl', 'list', '--json', 'runtimes'])
  520. except subprocess.CalledProcessError as exc:
  521. logger.warning(exc)
  522. return
  523. raw_object = json.loads(res)
  524. raw_object = raw_object['runtimes']
  525. for runtime in raw_object:
  526. if runtime['isAvailable']:
  527. if "iOS" in runtime['identifier']:
  528. emit('DEFAULT_IOS_RUNTIME', '{}'.format(runtime['identifier']))
  529. def _get_toolchain_options(self):
  530. type_ = self.params['params']['type']
  531. if self.params['params'].get('local') and type_ == 'xcode':
  532. detector = CompilerDetector()
  533. detector.detect(self.params['params']['c_compiler'], self.params['params']['cxx_compiler'])
  534. emit('LOCAL_XCODE_TOOLS', 'yes')
  535. emit('XCODE', 'yes')
  536. emit('ACTOOL_PATH', self.params['params']['actool'])
  537. emit('IBTOOL_PATH', self.params['params']['ibtool'])
  538. self._configure_runtime_versions()
  539. elif type_ == 'system_cxx':
  540. c_compiler = self.params['params'].get('c_compiler')
  541. cxx_compiler = self.params['params'].get('cxx_compiler')
  542. if is_positive('USE_CLANG_CL'):
  543. c_compiler = 'clang-cl.exe' if c_compiler == 'cl.exe' else c_compiler
  544. cxx_compiler = 'clang-cl.exe' if cxx_compiler == 'cl.exe' else cxx_compiler
  545. detector = CompilerDetector()
  546. detector.detect(c_compiler, cxx_compiler)
  547. type_ = detector.type
  548. else:
  549. detector = None
  550. if type_ == 'msvc':
  551. return MSVCToolchainOptions(self, detector)
  552. else:
  553. return GnuToolchainOptions(self, detector)
  554. def _print_other_settings(self, compiler):
  555. host = self.host
  556. emit('USE_LOCAL_TOOLS', 'no' if self.ignore_local_files else 'yes')
  557. ragel = Ragel()
  558. ragel.configure_toolchain(self, compiler)
  559. ragel.print_variables()
  560. swiftc = SwiftCompiler(self)
  561. swiftc.configure()
  562. swiftc.print_compiler()
  563. if host.is_linux or host.is_macos or host.is_cygwin:
  564. if is_negative('USE_ARCADIA_PYTHON'):
  565. python = Python(self.tc)
  566. python.configure_posix()
  567. python.print_variables()
  568. cuda = Cuda(self)
  569. cuda.print_()
  570. CuDNN(cuda).print_()
  571. if self.ignore_local_files or host.is_windows or is_positive('NO_SVN_DEPENDS'):
  572. emit_with_ignore_comment('SVN_DEPENDS_CACHE__NO_UID__')
  573. else:
  574. emit_with_ignore_comment('SVN_DEPENDS_CACHE__NO_UID__', '${hide;kv:"disable_cache"}')
  575. @staticmethod
  576. def _load_json_from_base64(base64str):
  577. """
  578. :rtype: dict[str, Any]
  579. """
  580. def un_unicode(o):
  581. if isinstance(o, six.text_type):
  582. return six.ensure_str(o)
  583. if isinstance(o, list):
  584. return [un_unicode(oo) for oo in o]
  585. if isinstance(o, dict):
  586. return {un_unicode(k): un_unicode(v) for k, v in six.iteritems(o)}
  587. return o
  588. return un_unicode(json.loads(base64.b64decode(base64str)))
  589. class YMake(object):
  590. def __init__(self, arcadia):
  591. self.arcadia = arcadia
  592. def print_presets(self):
  593. presets = opts().presets
  594. if is_positive_str(presets.get('EXPORT_GRADLE', 'no')):
  595. print('@import "${CONF_ROOT}/conf/export_gradle.yes.conf"')
  596. else:
  597. print('@import "${CONF_ROOT}/conf/export_gradle.no.conf"')
  598. if presets.get('CLANG_COVERAGE', None) is None:
  599. print('@import "${CONF_ROOT}/conf/coverage_full_instrumentation.conf"')
  600. else:
  601. print('@import "${CONF_ROOT}/conf/coverage_selective_instrumentation.conf"')
  602. if presets:
  603. print('# Variables set from command line by -D options')
  604. for key in sorted(presets):
  605. emit(key, opts().presets[key])
  606. @staticmethod
  607. def _print_conf_content(path):
  608. with open(path, 'r') as fin:
  609. print(fin.read())
  610. def print_core_conf(self):
  611. print('@import "${CONF_ROOT}/ymake.core.conf"')
  612. def print_settings(self):
  613. pass
  614. class System(object):
  615. def __init__(self, platform):
  616. """
  617. :type platform: Platform
  618. """
  619. self.platform = platform
  620. def print_windows_target_const(self):
  621. # TODO(somov): Remove this variables, use generic OS/arch variables in makelists.
  622. emit('WINDOWS', 'yes')
  623. emit('WIN32', 'yes')
  624. if self.platform.is_64_bit == 64:
  625. emit('WIN64', 'yes')
  626. def print_nix_target_const(self):
  627. emit('JAVA_INCLUDE', '-I{0}/include -I{0}/include/{1}'.format('/usr/lib/jvm/default-java', self.platform.os_compat))
  628. emit('UNIX', 'yes')
  629. emit('REALPRJNAME')
  630. emit('SONAME')
  631. def print_target_settings(self):
  632. emit('TARGET_PLATFORM', self.platform.os_compat)
  633. emit('CANONIZED_TARGET_PLATFORM', self.platform.canonized_platform)
  634. emit('HARDWARE_ARCH', '32' if self.platform.is_32_bit else '64')
  635. emit('HARDWARE_TYPE', self.platform.arch)
  636. for variable in self.platform.arch_variables:
  637. emit(variable, 'yes')
  638. for variable in self.platform.os_variables:
  639. emit(variable, 'yes')
  640. if self.platform.is_armv7:
  641. emit('ARM7_FLOAT_ABI', self.platform.armv7_float_abi)
  642. if self.platform.is_android:
  643. emit('ANDROID_API', str(self.platform.android_api))
  644. if self.platform.is_posix:
  645. self.print_nix_target_const()
  646. elif self.platform.is_windows:
  647. self.print_windows_target_const()
  648. def print_host_settings(self):
  649. emit('HOST_PLATFORM', self.platform.os_compat)
  650. emit('CANONIZED_HOST_PLATFORM', self.platform.canonized_platform)
  651. for variable in itertools.chain(self.platform.os_variables, self.platform.arch_variables):
  652. emit('HOST_{var}'.format(var=variable), 'yes')
  653. class CompilerDetector(object):
  654. def __init__(self):
  655. self.type = None
  656. self.c_compiler = None
  657. self.cxx_compiler = None
  658. self.version_list = None
  659. @staticmethod
  660. def preprocess_source(compiler, source):
  661. # noinspection PyBroadException
  662. try:
  663. fd, path = tempfile.mkstemp(suffix='.cpp')
  664. try:
  665. with os.fdopen(fd, 'w') as output:
  666. output.write(source)
  667. stdout, code = get_stdout_and_code([compiler, '-E', path])
  668. except Exception as e:
  669. logger.info("While writing: `%s`", e)
  670. finally:
  671. os.remove(path)
  672. return stdout, code
  673. except Exception as e:
  674. logger.debug('Preprocessing failed: %s', e)
  675. return None, None
  676. @staticmethod
  677. def get_compiler_vars(compiler, names):
  678. prefix = '____YA_VAR_'
  679. source = '\n'.join(['{prefix}{name}={name}\n'.format(prefix=prefix, name=n) for n in names])
  680. # Некоторые препроцессоры возвращают ненулевой код возврата. Поэтому его проверять нельзя.
  681. # Мы можем только удостовериться после разбора stdout, что в нём
  682. # присутствовала хотя бы одна подставленная переменная.
  683. # TODO(somov): Исследовать, можно ли проверять ограниченный набор кодов возврата.
  684. # TODO(v-korovin): Нормально прокидывать Exception-ы, оно и так упадёт
  685. stdout, _ = CompilerDetector.preprocess_source(compiler, source)
  686. if stdout is None:
  687. return None
  688. vars_ = {}
  689. for line in six.ensure_str(stdout).split('\n'):
  690. parts = line.split('=', 1)
  691. if len(parts) == 2 and parts[0].startswith(prefix):
  692. name, value = parts[0][len(prefix):], parts[1]
  693. if value == name:
  694. continue # Preprocessor variable was not substituted
  695. vars_[name] = value
  696. return vars_
  697. def detect(self, c_compiler=None, cxx_compiler=None):
  698. c_compiler = c_compiler or os.environ.get('CC')
  699. cxx_compiler = cxx_compiler or os.environ.get('CXX') or c_compiler
  700. c_compiler = c_compiler or cxx_compiler
  701. logger.debug('e=%s', os.environ)
  702. if c_compiler is None:
  703. raise ConfigureError('Custom compiler was requested but not specified')
  704. c_compiler_path = which(c_compiler)
  705. clang_vars = ['__clang_major__', '__clang_minor__', '__clang_patchlevel__']
  706. gcc_vars = ['__GNUC__', '__GNUC_MINOR__', '__GNUC_PATCHLEVEL__']
  707. msvc_vars = ['_MSC_VER']
  708. apple_var = '__apple_build_version__'
  709. compiler_vars = self.get_compiler_vars(c_compiler_path, clang_vars + [apple_var] + gcc_vars + msvc_vars)
  710. if not compiler_vars:
  711. raise ConfigureError('Could not determine custom compiler version: {}'.format(c_compiler))
  712. def version(version_names):
  713. def iter_version():
  714. for name in version_names:
  715. yield int(compiler_vars[name])
  716. # noinspection PyBroadException
  717. try:
  718. return list(iter_version())
  719. except Exception:
  720. return None
  721. clang_version = version(clang_vars)
  722. apple_build = apple_var in compiler_vars
  723. # TODO(somov): Учитывать номера версий сборки Apple компилятора Clang.
  724. _ = apple_build
  725. gcc_version = version(gcc_vars)
  726. msvc_version = version(msvc_vars)
  727. if msvc_version:
  728. logger.debug('Detected MSVC version %s', msvc_version)
  729. self.type = 'msvc'
  730. elif clang_version:
  731. logger.debug('Detected Clang version %s', clang_version)
  732. self.type = 'clang'
  733. elif gcc_version:
  734. logger.debug('Detected GCC version %s', gcc_version)
  735. # TODO(somov): Переименовать в gcc.
  736. self.type = 'gnu'
  737. else:
  738. raise ConfigureError('Could not determine custom compiler type: {}'.format(c_compiler))
  739. self.version_list = clang_version or gcc_version or msvc_version
  740. self.c_compiler = c_compiler_path
  741. self.cxx_compiler = cxx_compiler and which(cxx_compiler) or c_compiler_path
  742. class ToolchainOptions(object):
  743. def __init__(self, build, detector):
  744. """
  745. :type build: Build
  746. """
  747. self.host = build.host
  748. self.target = build.target
  749. tc_json = build.params
  750. logger.debug('Toolchain host %s', self.host)
  751. logger.debug('Toolchain target %s', self.target)
  752. logger.debug('Toolchain json %s', DebugString(lambda: json.dumps(tc_json, indent=4, sort_keys=True)))
  753. self.params = tc_json['params']
  754. self._name = tc_json.get('name', 'theyknow')
  755. if detector:
  756. self.type = detector.type
  757. self.from_arcadia = False
  758. self.c_compiler = detector.c_compiler
  759. self.cxx_compiler = detector.cxx_compiler
  760. self.compiler_version_list = detector.version_list
  761. self.compiler_version = '.'.join(map(lambda part: six.ensure_str(str(part)), self.compiler_version_list))
  762. else:
  763. self.type = self.params['type']
  764. self.from_arcadia = True
  765. self.c_compiler = self.params['c_compiler']
  766. self.cxx_compiler = self.params['cxx_compiler']
  767. # TODO(somov): Требовать номер версии всегда.
  768. self.compiler_version = self.params.get('gcc_version') or self.params.get('version') or '0'
  769. self.compiler_version_list = list(map(int, self.compiler_version.split('.')))
  770. # 'match_root' at this point contains real name for references via toolchain
  771. self.name_marker = '$(%s)' % self.params.get('match_root', self._name.upper())
  772. self.arch_opt = self.params.get('arch_opt', [])
  773. self.triplet_opt = self.params.get('triplet_opt', {})
  774. self.target_opt = self.params.get('target_opt', [])
  775. # TODO(somov): Убрать чтение настройки из os.environ.
  776. self.werror_mode = preset('WERROR_MODE') or os.environ.get('WERROR_MODE') or self.params.get('werror_mode') or 'compiler_specific'
  777. # default C++ standard is set here, some older toolchains might need to redefine it in ya.conf.json
  778. self.cxx_std = self.params.get('cxx_std', 'c++20')
  779. self._env = tc_json.get('env', {})
  780. self.android_ndk_version = self.params.get('android_ndk_version', None)
  781. logger.debug('c_compiler=%s', self.c_compiler)
  782. logger.debug('cxx_compiler=%s', self.cxx_compiler)
  783. self.compiler_platform_projects = self.target.find_in_dict(self.params.get('platform'), [])
  784. def version_at_least(self, *args):
  785. return args <= tuple(self.compiler_version_list)
  786. def version_below(self, *args):
  787. return args > tuple(self.compiler_version_list)
  788. def version_exactly(self, *args):
  789. if not args or len(args) > len(self.compiler_version_list):
  790. return False
  791. for left, right in zip(args, list(self.compiler_version_list)[:len(args)]):
  792. if left != right:
  793. return False
  794. return True
  795. @property
  796. def is_gcc(self):
  797. return self.type == 'gnu'
  798. @property
  799. def is_clang(self):
  800. return self.type in ('clang', 'xcode')
  801. @property
  802. def is_xcode(self):
  803. return self.type == 'xcode'
  804. @property
  805. def is_from_arcadia(self):
  806. return self.from_arcadia
  807. @property
  808. def is_system_cxx(self):
  809. return self._name == "system_cxx"
  810. def get_env(self, convert_list=None):
  811. convert_list = convert_list or (lambda x: x)
  812. r = {}
  813. for k, v in six.iteritems(self._env):
  814. if isinstance(v, str):
  815. r[k] = v
  816. elif isinstance(v, list):
  817. r[k] = convert_list(v)
  818. else:
  819. logger.debug('Unexpected values in environment: %s', self._env)
  820. raise ConfigureError('Internal error')
  821. return r
  822. class GnuToolchainOptions(ToolchainOptions):
  823. def __init__(self, build, detector):
  824. super(GnuToolchainOptions, self).__init__(build, detector)
  825. self.ar = self.params.get('ar')
  826. self.ar_plugin = self.params.get('ar_plugin')
  827. self.strip = self.params.get('strip')
  828. self.objcopy = self.params.get('objcopy')
  829. self.objdump = self.params.get('objdump')
  830. self.isystem = self.params.get('isystem')
  831. self.dwarf_tool = self.target.find_in_dict(self.params.get('dwarf_tool'))
  832. # TODO(somov): Унифицировать формат sys_lib
  833. self.sys_lib = self.params.get('sys_lib', {})
  834. if isinstance(self.sys_lib, dict):
  835. self.sys_lib = self.target.find_in_dict(self.sys_lib, [])
  836. self.os_sdk = preset('OS_SDK') or self._default_os_sdk()
  837. self.os_sdk_local = False
  838. if build.host.is_apple and build.target.is_apple and to_bool(preset('APPLE_SDK_LOCAL'), default=False):
  839. self.os_sdk_local = True
  840. if build.host.is_apple and build.target.is_ios and to_bool(preset('MAPSMOBI_BUILD_TARGET'), default=False):
  841. self.os_sdk_local = True
  842. if self.os_sdk == 'local':
  843. self.os_sdk_local = True
  844. def _default_os_sdk(self):
  845. if self.target.is_linux:
  846. if self.target.is_armv8:
  847. return 'ubuntu-16'
  848. if self.target.is_armv7 and self.target.armv7_float_abi == 'hard':
  849. return 'ubuntu-16'
  850. if self.target.is_armv7 and self.target.armv7_float_abi == 'softfp':
  851. return 'ubuntu-18'
  852. # Default OS SDK for Linux builds
  853. return LINUX_SDK_DEFAULT
  854. class Toolchain(object):
  855. def __init__(self, tc, build):
  856. """
  857. :type tc: ToolchainOptions
  858. :type build: Build
  859. """
  860. self.tc = tc
  861. self.build = build
  862. self.platform_projects = self.tc.compiler_platform_projects
  863. def print_toolchain(self):
  864. if self.platform_projects:
  865. emit('COMPILER_PLATFORM', list(unique(self.platform_projects)))
  866. class Compiler(object):
  867. def __init__(self, tc, compiler_variable):
  868. self.compiler_variable = compiler_variable
  869. self.tc = tc
  870. def print_compiler(self):
  871. # CLANG and CLANG_VER variables
  872. emit(self.compiler_variable, 'yes')
  873. cv = self.tc.compiler_version
  874. if '.' in cv:
  875. cv = cv[:cv.index('.')]
  876. emit('{}_VER'.format(self.compiler_variable), cv)
  877. if self.tc.is_xcode:
  878. emit('XCODE', 'yes')
  879. class GnuToolchain(Toolchain):
  880. def __init__(self, tc, build):
  881. """
  882. :type tc: GnuToolchainOptions
  883. :type build: Build
  884. """
  885. def get_os_sdk(target):
  886. sdk_native_version = 10.11 if not preset('EXPERIMENTAL_MACOS_M1_SUPPORT') else '11.1'
  887. if target.is_macos:
  888. return '$MACOS_SDK_RESOURCE_GLOBAL/MacOSX{}.sdk'.format(sdk_native_version)
  889. elif target.is_yocto:
  890. return '$YOCTO_SDK_RESOURCE_GLOBAL'
  891. return '$OS_SDK_ROOT_RESOURCE_GLOBAL'
  892. super(GnuToolchain, self).__init__(tc, build)
  893. self.tc = tc
  894. host = build.host
  895. target = build.target
  896. self.c_flags_platform = list(tc.target_opt)
  897. self.default_os_sdk_root = get_os_sdk(target)
  898. self.env = self.tc.get_env()
  899. self.env_go = {}
  900. if self.tc.is_clang and not self.tc.is_system_cxx:
  901. self.env_go = {'PATH': ['{}/bin'.format(self.tc.name_marker)]}
  902. if self.tc.is_gcc:
  903. self.env_go = {'PATH': ['{}/gcc/bin'.format(self.tc.name_marker)]}
  904. if 'PATH' in self.env_go:
  905. if target.is_linux:
  906. self.env_go['PATH'].append('$OS_SDK_ROOT_RESOURCE_GLOBAL/usr/bin')
  907. elif target.is_macos:
  908. self.env_go['PATH'].extend([
  909. '$MACOS_SDK_RESOURCE_GLOBAL/usr/bin',
  910. '$GO_FAKE_XCRUN_RESOURCE_GLOBAL',
  911. ])
  912. self.swift_flags_platform = []
  913. self.swift_lib_path = None
  914. if self.tc.is_from_arcadia:
  915. for lib_path in build.host.library_path_variables:
  916. self.env.setdefault(lib_path, []).append('{}/lib'.format(self.tc.name_marker))
  917. swift_target = select(default=None, selectors=[
  918. (target.is_iossim and target.is_x86_64, 'x86_64-apple-ios{}-simulator'.format(IOS_VERSION_MIN)),
  919. (target.is_iossim and target.is_x86, 'i386-apple-ios{}-simulator'.format(IOS_VERSION_MIN)),
  920. (target.is_iossim and target.is_armv8, 'arm64-apple-ios{}-simulator'.format(IOS_VERSION_MIN)),
  921. (not target.is_iossim and target.is_ios and target.is_armv8, 'arm64-apple-ios9'),
  922. (not target.is_iossim and target.is_ios and target.is_armv7, 'armv7-apple-ios9'),
  923. ])
  924. if swift_target:
  925. self.swift_flags_platform += ['-target', swift_target]
  926. if self.tc.is_from_arcadia:
  927. self.swift_lib_path = select(default=None, selectors=[
  928. (host.is_macos and target.is_iossim, '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/lib/swift/iphonesimulator'),
  929. (host.is_macos and not target.is_iossim and target.is_ios and (target.is_armv8 or target.is_armv7), '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/lib/swift/iphoneos'),
  930. ])
  931. if self.tc.is_clang:
  932. target_triple = self.tc.triplet_opt.get(target.arch, None)
  933. if not target_triple:
  934. target_triple = select(default=None, selectors=[
  935. (target.is_linux and target.is_x86_64, 'x86_64-linux-gnu'),
  936. (target.is_linux and target.is_armv8, 'aarch64-linux-gnu'),
  937. (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'hard', 'armv7-linux-gnueabihf'),
  938. (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'softfp', 'armv7-linux-gnueabi'),
  939. (target.is_linux and target.is_powerpc, 'powerpc64le-linux-gnu'),
  940. (target.is_iossim and target.is_x86_64, 'x86_64-apple-ios{}-simulator'.format(IOS_VERSION_MIN)),
  941. (target.is_iossim and target.is_x86, 'i386-apple-ios{}-simulator'.format(IOS_VERSION_MIN)),
  942. (target.is_iossim and target.is_armv8, 'arm64-apple-ios{}-simulator'.format(IOS_VERSION_MIN)),
  943. (not target.is_iossim and target.is_ios and target.is_armv8, 'arm64-apple-ios{}'.format(IOS_VERSION_MIN)),
  944. (not target.is_iossim and target.is_ios and target.is_armv7, 'armv7-apple-ios{}'.format(IOS_VERSION_MIN)),
  945. (target.is_apple and target.is_x86, 'i386-apple-darwin14'),
  946. (target.is_apple and target.is_x86_64, 'x86_64-apple-darwin14'),
  947. (target.is_apple and target.is_macos_arm64, 'arm64-apple-macos11'),
  948. (target.is_apple and target.is_armv7, 'armv7-apple-darwin14'),
  949. (target.is_apple and target.is_armv8, 'arm64-apple-darwin14'),
  950. (target.is_yocto and target.is_armv7, 'arm-poky-linux-gnueabi'),
  951. (target.is_android and target.is_x86, 'i686-linux-android'),
  952. (target.is_android and target.is_x86_64, 'x86_64-linux-android'),
  953. (target.is_android and target.is_armv7, 'armv7a-linux-androideabi'),
  954. (target.is_android and target.is_armv8, 'aarch64-linux-android'),
  955. (target.is_emscripten and target.is_wasm64, 'wasm64-unknown-emscripten'),
  956. ])
  957. if target.is_android:
  958. # Android NDK allows specification of API level in target triple, e.g.:
  959. # armv7a-linux-androideabi16, aarch64-linux-android21
  960. target_triple += str(target.android_api)
  961. if target_triple:
  962. self.c_flags_platform.append('--target={}'.format(target_triple))
  963. if self.tc.isystem:
  964. for root in list(self.tc.isystem):
  965. self.c_flags_platform.extend(['-isystem', root])
  966. if target.is_android:
  967. self.c_flags_platform.extend(['-isystem', '{}/sources/cxx-stl/llvm-libc++abi/include'.format(self.tc.name_marker)])
  968. if target.is_cortex_a9:
  969. self.c_flags_platform.append('-mcpu=cortex-a9')
  970. if target.is_cortex_a35:
  971. self.c_flags_platform.append('-mcpu=cortex-a35')
  972. elif target.is_cortex_a53:
  973. self.c_flags_platform.append('-mcpu=cortex-a53')
  974. elif target.is_cortex_m4:
  975. self.c_flags_platform.append('-mcpu=cortex-m4 -mfpu=fpv4-sp-d16')
  976. elif target.is_cortex_m7:
  977. self.c_flags_platform.append('-mcpu=cortex-m7 -mfpu=fpv5-sp-d16')
  978. elif target.is_cortex_m23:
  979. self.c_flags_platform.append('-mcpu=cortex-m23')
  980. elif target.is_cortex_m33:
  981. self.c_flags_platform.append('-mcpu=cortex-m33 -mfpu=fpv5-sp-d16')
  982. elif target.is_armv7_neon:
  983. self.c_flags_platform.append('-mfpu=neon')
  984. elif target.is_arm968e_s:
  985. self.c_flags_platform.append('-march=armv5te -mcpu=arm968e-s -mthumb-interwork -mlittle-endian')
  986. if (target.is_armv7 or target.is_armv8m or target.is_armv7em or target.is_armv5te) and build.is_size_optimized:
  987. # Enable ARM Thumb2 variable-length instruction encoding
  988. # to reduce code size
  989. self.c_flags_platform.append('-mthumb')
  990. if target.is_arm or target.is_powerpc:
  991. # On linux, ARM and PPC default to unsigned char
  992. # However, Arcadia requires char to be signed
  993. self.c_flags_platform.append('-fsigned-char')
  994. if target.is_rv32imc:
  995. self.c_flags_platform.append('-march=rv32imc')
  996. if self.tc.is_clang or self.tc.is_gcc and self.tc.version_at_least(8, 2):
  997. target_flags = select(default=[], selectors=[
  998. (target.is_linux and target.is_power8le, ['-mcpu=power8', '-mtune=power8', '-maltivec']),
  999. (target.is_linux and target.is_power9le, ['-mcpu=power9', '-mtune=power9', '-maltivec']),
  1000. (target.is_linux and target.is_armv8, ['-march=armv8a']),
  1001. (target.is_macos, ['-mmacosx-version-min={}'.format(MACOS_VERSION_MIN)]),
  1002. (target.is_ios and not target.is_iossim, ['-mios-version-min={}'.format(IOS_VERSION_MIN)]),
  1003. (target.is_iossim, ['-mios-simulator-version-min={}'.format(IOS_VERSION_MIN)]),
  1004. (target.is_android and target.is_armv7, ['-march=armv7-a', '-mfloat-abi=softfp']),
  1005. (target.is_android and target.is_armv8, ['-march=armv8-a']),
  1006. (target.is_yocto and target.is_armv7, ['-march=armv7-a', '-mfpu=neon', '-mfloat-abi=hard', '-mcpu=cortex-a9', '-O1'])
  1007. ])
  1008. if target_flags:
  1009. self.c_flags_platform.extend(target_flags)
  1010. if target.is_ios:
  1011. self.c_flags_platform.append('-D__IOS__=1')
  1012. if target.is_apple:
  1013. self.setup_apple_sdk(target)
  1014. if self.tc.is_from_arcadia or self.tc.is_system_cxx:
  1015. if target.is_linux:
  1016. if not tc.os_sdk_local:
  1017. self.setup_sdk(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL')
  1018. if target.is_x86_64:
  1019. if host.is_linux and not self.tc.is_gcc:
  1020. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/lib/x86_64-linux-gnu')
  1021. elif host.is_macos:
  1022. self.setup_tools(project='build/platform/binutils', var='$BINUTILS_ROOT_RESOURCE_GLOBAL', bin='x86_64-linux-gnu/bin', ldlibs=None)
  1023. elif target.is_powerpc:
  1024. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/x86_64-linux-gnu/powerpc64le-linux-gnu/lib')
  1025. elif target.is_armv8:
  1026. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/lib/x86_64-linux-gnu')
  1027. if target.is_yocto:
  1028. self.setup_sdk(project='build/platform/yocto_sdk/yocto_sdk', var='${YOCTO_SDK_ROOT_RESOURCE_GLOBAL}')
  1029. def setup_apple_sdk(self, target):
  1030. if not self.tc.os_sdk_local:
  1031. self.setup_apple_arcadia_sdk(target)
  1032. else:
  1033. self.setup_apple_local_sdk(target)
  1034. def setup_apple_arcadia_sdk(self, target):
  1035. if target.is_ios:
  1036. self.setup_xcode_sdk(project='build/internal/platform/ios_sdk', var='${IOS_SDK_ROOT_RESOURCE_GLOBAL}')
  1037. self.platform_projects.append('build/internal/platform/macos_system_stl')
  1038. if target.is_macos:
  1039. self.setup_xcode_sdk(project='build/internal/platform/macos_sdk', var='${MACOS_SDK_RESOURCE_GLOBAL}')
  1040. def setup_apple_local_sdk(self, target):
  1041. def get_output(*args):
  1042. return six.ensure_str(subprocess.check_output(tuple(args))).strip()
  1043. def get_sdk_root(sdk):
  1044. root = self.env.get('SDKROOT')
  1045. if root not in (None, '', ['']):
  1046. return root
  1047. root = os.environ.get('SDKROOT')
  1048. if root:
  1049. return root
  1050. return get_output('xcrun', '-sdk', sdk, '--show-sdk-path')
  1051. if target.is_iossim:
  1052. self.env['SDKROOT'] = get_sdk_root('iphonesimulator')
  1053. elif target.is_ios:
  1054. self.env['SDKROOT'] = get_sdk_root('iphoneos')
  1055. elif target.is_macos:
  1056. self.env['SDKROOT'] = get_sdk_root('macosx')
  1057. def setup_sdk(self, project, var):
  1058. self.platform_projects.append(project)
  1059. self.c_flags_platform.append('--sysroot={}'.format(var))
  1060. self.swift_flags_platform += ['-sdk', var]
  1061. def setup_xcode_sdk(self, project, var):
  1062. self.platform_projects.append(project)
  1063. self.c_flags_platform.append('-isysroot')
  1064. self.c_flags_platform.append(var)
  1065. self.swift_flags_platform += ['-sdk', var]
  1066. # noinspection PyShadowingBuiltins
  1067. def setup_tools(self, project, var, bin, ldlibs):
  1068. self.platform_projects.append(project)
  1069. self.c_flags_platform.append('-B{}/{}'.format(var, bin))
  1070. if ldlibs:
  1071. for lib_path in self.build.host.library_path_variables:
  1072. self.env.setdefault(lib_path, []).append('{}/{}'.format(var, ldlibs))
  1073. def print_toolchain(self):
  1074. super(GnuToolchain, self).print_toolchain()
  1075. emit('TOOLCHAIN_ENV', format_env(self.env, list_separator=':'))
  1076. emit('_GO_TOOLCHAIN_ENV_PATH', format_env(self.env_go, list_separator=':'))
  1077. emit('C_FLAGS_PLATFORM', self.c_flags_platform)
  1078. emit('SWIFT_FLAGS_PLATFORM', self.swift_flags_platform)
  1079. emit('SWIFT_LD_FLAGS', '-L{}'.format(self.swift_lib_path) if self.swift_lib_path else '')
  1080. emit('PERL_SDK', preset('OS_SDK') or self.tc.os_sdk)
  1081. if preset('OS_SDK') is None:
  1082. emit('OS_SDK', self.tc.os_sdk)
  1083. emit('OS_SDK_ROOT', None if self.tc.os_sdk_local else self.default_os_sdk_root)
  1084. class GnuCompiler(Compiler):
  1085. def __init__(self, tc, build):
  1086. """
  1087. :type tc: GnuToolchainOptions
  1088. :type build: Build
  1089. """
  1090. compiler_variable = 'CLANG' if tc.is_clang else 'GCC'
  1091. super(GnuCompiler, self).__init__(tc, compiler_variable)
  1092. self.build = build
  1093. self.host = self.build.host
  1094. self.target = self.build.target
  1095. self.tc = tc
  1096. self.c_foptions = [
  1097. # Enable C++ exceptions (and allow them to be throw through pure C code)
  1098. '-fexceptions',
  1099. # Enable standard-conforming behavior and generate duplicate symbol error in case of duplicated global constants.
  1100. # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85678#c0
  1101. '-fno-common',
  1102. # Split all functions and data into separate sections for DCE and ICF linker passes
  1103. '-ffunction-sections',
  1104. '-fdata-sections'
  1105. ]
  1106. if self.tc.is_clang and self.target.is_linux:
  1107. # Use .init_array instead of .ctors (default for old clang versions)
  1108. # See: https://maskray.me/blog/2021-11-07-init-ctors-init-array
  1109. self.c_foptions.append('-fuse-init-array')
  1110. if self.target.is_xtensa:
  1111. self.c_foptions.append('-mlongcalls')
  1112. if self.tc.is_clang:
  1113. self.c_foptions += [
  1114. # Set up output colorization
  1115. '-fcolor-diagnostics',
  1116. # Enable aligned allocation
  1117. '-faligned-allocation',
  1118. '-fdebug-default-version=4',
  1119. ]
  1120. elif self.tc.is_gcc:
  1121. if self.target.is_xtensa or self.target.is_tc32:
  1122. # Xtensa and tc32 toolchains does not support this flag
  1123. pass
  1124. else:
  1125. self.c_foptions += [
  1126. # Set up output colorization
  1127. '-fdiagnostics-color=always',
  1128. # It looks like there is no way to enable aligned allocation in gcc
  1129. ]
  1130. self.c_warnings = [
  1131. # Enable default warnings subset
  1132. '-Wall',
  1133. '-Wextra',
  1134. ]
  1135. self.cxx_warnings = [
  1136. # Issue a warning if certain overload is hidden due to inheritance
  1137. '-Woverloaded-virtual',
  1138. ]
  1139. # Disable some warnings which will fail compilation at the time
  1140. self.c_warnings += [
  1141. '-Wno-parentheses',
  1142. ]
  1143. self.c_defines = ['${hide:CPP_FAKEID}']
  1144. if self.target.is_android:
  1145. self.c_defines.append('${hide:ANDROID_FAKEID}')
  1146. self.c_defines.extend([
  1147. '-DARCADIA_ROOT=${ARCADIA_ROOT}',
  1148. '-DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
  1149. ])
  1150. self.c_defines.extend([
  1151. '-D_THREAD_SAFE', '-D_PTHREADS', '-D_REENTRANT',
  1152. '-D_LARGEFILE_SOURCE', '-D__STDC_CONSTANT_MACROS', '-D__STDC_FORMAT_MACROS',
  1153. ])
  1154. if self.target.is_macos and self.tc.version_below(17):
  1155. # OS-versioning macros for Darwin-based OSes were generalized in
  1156. # https://github.com/llvm/llvm-project/commit/c8e2dd8c6f490b68e41fe663b44535a8a21dfeab
  1157. #
  1158. # This PR was released in llvm-17. Provide similar behaviour manually.
  1159. self.c_defines.append("-D__ENVIRONMENT_OS_VERSION_MIN_REQUIRED__=" + MACOS_VERSION_MIN_AS_INT)
  1160. if not self.target.is_android:
  1161. # There is no usable _FILE_OFFSET_BITS=64 support in Androids until API 21. And it's incomplete until at least API 24.
  1162. # https://android.googlesource.com/platform/bionic/+/master/docs/32-bit-abi.md
  1163. # Arcadia have API 16 for 32-bit Androids.
  1164. self.c_defines.append('-D_FILE_OFFSET_BITS=64')
  1165. if self.target.is_linux or self.target.is_android or self.target.is_cygwin or self.target.is_none:
  1166. self.c_defines.append('-D_GNU_SOURCE')
  1167. if self.tc.is_clang and self.target.is_linux and self.target.is_x86_64:
  1168. self.c_defines.append('-D_YNDX_LIBUNWIND_ENABLE_EXCEPTION_BACKTRACE')
  1169. self.c_flags = ['$CL_DEBUG_INFO', '$CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__']
  1170. self.c_flags += self.tc.arch_opt + ['-pipe']
  1171. self.sfdl_flags = ['-E', '-C', '-x', 'c++']
  1172. if self.target.is_x86:
  1173. self.c_flags.append('-m32')
  1174. if self.target.is_x86_64:
  1175. self.c_flags.append('-m64')
  1176. if self.target.is_wasm64:
  1177. # WebAssembly-specific exception handling flags
  1178. self.c_foptions += [
  1179. '-fwasm-exceptions',
  1180. ]
  1181. self.debug_info_flags = ['-g']
  1182. if self.target.is_linux:
  1183. self.debug_info_flags.append('-ggnu-pubnames')
  1184. self.cross_suffix = '' if is_positive('FORCE_NO_PIC') else '.pic'
  1185. self.optimize = None
  1186. self.configure_build_type()
  1187. if self.tc.is_clang:
  1188. self.sfdl_flags.append('-Qunused-arguments')
  1189. self.c_warnings += [
  1190. '-Wno-implicit-const-int-float-conversion',
  1191. # For nvcc to accept the above.
  1192. '-Wno-unknown-warning-option',
  1193. ]
  1194. self.cxx_warnings += [
  1195. '-Wimport-preprocessor-directive-pedantic',
  1196. '-Wno-ambiguous-reversed-operator',
  1197. '-Wno-defaulted-function-deleted',
  1198. '-Wno-deprecated-anon-enum-enum-conversion',
  1199. '-Wno-deprecated-enum-enum-conversion',
  1200. '-Wno-deprecated-enum-float-conversion',
  1201. '-Wno-deprecated-volatile',
  1202. '-Wno-pessimizing-move',
  1203. '-Wno-return-std-move',
  1204. '-Wno-undefined-var-template',
  1205. ]
  1206. elif self.tc.is_gcc:
  1207. if self.target.is_xtensa:
  1208. # Xtensa toolchain does not support this flags
  1209. pass
  1210. else:
  1211. self.c_foptions.append('-fno-delete-null-pointer-checks')
  1212. self.c_foptions.append('-fabi-version=8')
  1213. def configure_build_type(self):
  1214. if self.build.is_valgrind:
  1215. self.c_defines.append('-DWITH_VALGRIND=1')
  1216. if self.build.is_debug:
  1217. self.c_foptions.append('$FSTACK')
  1218. if self.build.is_fast_debug:
  1219. self.c_flags.append('-Og')
  1220. if self.build.is_release:
  1221. self.c_flags.append('$OPTIMIZE')
  1222. if self.build.is_size_optimized:
  1223. # -Oz is clang's more size-aggressive version of -Os
  1224. # For ARM specifically, clang -Oz is on par with gcc -Os:
  1225. # https://github.com/android/ndk/issues/133#issuecomment-365763507
  1226. if self.tc.is_clang:
  1227. self.optimize = '-Oz'
  1228. else:
  1229. self.optimize = '-Os'
  1230. # Generate sections with address significance tables for ICF linker pass
  1231. if self.tc.is_clang:
  1232. self.c_foptions.extend(['-faddrsig'])
  1233. else:
  1234. self.optimize = '-O3'
  1235. if self.build.with_ndebug:
  1236. self.c_defines.append('-DNDEBUG')
  1237. else:
  1238. self.c_defines.append('-UNDEBUG')
  1239. if self.build.profiler_type in (Profiler.Generic, Profiler.GProf):
  1240. self.c_foptions.append('-fno-omit-frame-pointer')
  1241. if self.build.profiler_type == Profiler.GProf:
  1242. self.c_flags.append('-pg')
  1243. def print_compiler(self):
  1244. super(GnuCompiler, self).print_compiler()
  1245. emit('C_COMPILER', '"{}"'.format(self.tc.c_compiler))
  1246. emit('C_COMPILER_OLD_UNQUOTED', self.tc.c_compiler)
  1247. emit('C_COMPILER_OLD', '${quo:C_COMPILER_OLD_UNQUOTED}')
  1248. emit('OPTIMIZE', self.optimize)
  1249. emit('WERROR_MODE', self.tc.werror_mode)
  1250. emit('_C_FLAGS', self.c_flags)
  1251. emit('_C_FOPTIONS', self.c_foptions)
  1252. emit('_STD_CXX_VERSION', preset('USER_STD_CXX_VERSION') or self.tc.cxx_std)
  1253. append('C_DEFINES', self.c_defines)
  1254. append('C_WARNING_OPTS', self.c_warnings)
  1255. append('CXX_WARNING_OPTS', self.cxx_warnings)
  1256. emit('CXX_COMPILER', '"{}"'.format(self.tc.cxx_compiler))
  1257. emit('CXX_COMPILER_OLD_UNQUOTED', format(self.tc.cxx_compiler))
  1258. emit('CXX_COMPILER_OLD', '${quo:CXX_COMPILER_OLD_UNQUOTED}')
  1259. # TODO(somov): Убрать чтение настройки из os.environ
  1260. emit('USE_ARC_PROFILE', 'yes' if preset('USE_ARC_PROFILE') or os.environ.get('USE_ARC_PROFILE') else 'no')
  1261. emit('DEBUG_INFO_FLAGS', self.debug_info_flags)
  1262. if self.build.is_coverage:
  1263. emit('_IS_COVERAGE', 'yes')
  1264. if self.tc.is_clang and self.tc.version_at_least(9):
  1265. emit('_HAS_TIME_TRACE', 'yes')
  1266. print('@import "${CONF_ROOT}/conf/compilers/gnu_compiler.conf"')
  1267. class SwiftCompiler(object):
  1268. def __init__(self, build):
  1269. self.host = build.host
  1270. self.compiler = None
  1271. def configure(self):
  1272. if self.host.is_macos:
  1273. self.compiler = '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/bin/swiftc'
  1274. def print_compiler(self):
  1275. emit('SWIFT_COMPILER', self.compiler or '')
  1276. class Linker(object):
  1277. BFD = 'bfd'
  1278. LLD = 'lld'
  1279. GOLD = 'gold'
  1280. def __init__(self, tc, build):
  1281. """
  1282. :type tc: ToolchainOptions
  1283. :type build: Build
  1284. """
  1285. self.tc = tc
  1286. self.build = build
  1287. self.type = self._get_default_linker_type()
  1288. def _get_default_linker_type(self):
  1289. if not self.tc.is_from_arcadia or is_positive('EXPORT_CMAKE'):
  1290. # External (e.g. system) toolchain: disable linker selection logic
  1291. return None
  1292. if self.build.target.is_android:
  1293. # Android toolchain is NDK, LLD works on all supported platforms
  1294. return Linker.LLD
  1295. elif self.build.target.is_linux or self.build.target.is_macos or self.build.target.is_ios or self.build.target.is_wasm:
  1296. return Linker.LLD
  1297. # There is no linker choice on Windows (link.exe)
  1298. return None
  1299. def print_linker(self):
  1300. self._print_linker_selector()
  1301. def _print_linker_selector(self):
  1302. # if self.type is None then _DEFAULT_LINKER is set to empty string value
  1303. emit('_DEFAULT_LINKER_ID', self.type)
  1304. class LD(Linker):
  1305. def __init__(self, tc, build):
  1306. """
  1307. :type tc: GnuToolchainOptions
  1308. :type build: Build
  1309. """
  1310. super(LD, self).__init__(tc, build)
  1311. self.build = build
  1312. self.host = self.build.host
  1313. self.target = self.build.target
  1314. self.tc = tc
  1315. target = self.target
  1316. self.ar = preset('AR') or self.tc.ar
  1317. self.ar_plugin = self.tc.ar_plugin
  1318. self.strip = self.tc.strip
  1319. self.objcopy = self.tc.objcopy
  1320. self.objdump = self.tc.objdump
  1321. self.musl = Setting('MUSL', convert=to_bool)
  1322. if self.ar is None:
  1323. if self.tc.is_from_arcadia:
  1324. if self.tc.is_clang:
  1325. self.ar = '{}/bin/llvm-ar'.format(self.tc.name_marker)
  1326. if self.tc.is_gcc:
  1327. self.ar = '{}/gcc/bin/gcc-ar'.format(self.tc.name_marker)
  1328. else:
  1329. self.ar = 'ar'
  1330. self.ar_type = 'GNU_AR'
  1331. self.llvm_ar_format = 'None'
  1332. if 'libtool' in self.ar:
  1333. self.ar_type = 'LIBTOOL'
  1334. elif 'llvm-ar' in self.ar:
  1335. self.ar_type = 'LLVM_AR'
  1336. if target.is_apple:
  1337. self.llvm_ar_format = "darwin"
  1338. else:
  1339. self.llvm_ar_format = "gnu"
  1340. self.ld_flags = []
  1341. if self.musl.value:
  1342. self.ld_flags.extend(['-Wl,--no-as-needed'])
  1343. elif target.is_linux:
  1344. self.ld_flags.extend(['-ldl', '-lrt', '-Wl,--no-as-needed'])
  1345. if self.tc.is_gcc:
  1346. self.ld_flags.extend(('-Wl,-Bstatic', '-latomic', '-Wl,-Bdynamic'))
  1347. elif target.is_android:
  1348. self.ld_flags.extend(['-ldl', '-Wl,--no-as-needed'])
  1349. self.ld_sdk = select(default=None, selectors=[
  1350. # -platform_version <platform> <min_version> <sdk_version>
  1351. (target.is_macos, '-Wl,-platform_version,macos,{MACOS_VERSION_MIN},11.0'.format(MACOS_VERSION_MIN=MACOS_VERSION_MIN)),
  1352. (not target.is_iossim and target.is_ios, '-Wl,-platform_version,ios,{IOS_VERSION_MIN},13.1'.format(IOS_VERSION_MIN=IOS_VERSION_MIN)),
  1353. (target.is_iossim, '-Wl,-platform_version,ios-simulator,{IOS_VERSION_MIN},14.5'.format(IOS_VERSION_MIN=IOS_VERSION_MIN)),
  1354. ])
  1355. if self.build.profiler_type == Profiler.GProf:
  1356. self.ld_flags.append('-pg')
  1357. if self.ld_sdk:
  1358. self.ld_flags.append(self.ld_sdk)
  1359. self.sys_lib = self.tc.sys_lib
  1360. if target.is_android:
  1361. # Use toolchain defaults to link with libunwind/clang_rt.builtins
  1362. self.use_stdlib = '-nostdlib++'
  1363. def print_linker(self):
  1364. super(LD, self).print_linker()
  1365. emit('AR_TOOL', self.ar)
  1366. emit('AR_TYPE', self.ar_type)
  1367. emit('_LD_LLVM_AR_FORMAT', self.llvm_ar_format)
  1368. emit('_LD_AR_PLUGIN', self.ar_plugin or 'None')
  1369. emit('STRIP_TOOL_VENDOR', self.strip)
  1370. emit('OBJCOPY_TOOL_VENDOR', self.objcopy)
  1371. emit('OBJDUMP_TOOL_VENDOR', self.objdump)
  1372. emit('_LD_FLAGS', self.ld_flags)
  1373. emit('_LD_SYS_LIB', self.sys_lib)
  1374. emit('LD_SDK_VERSION', self.ld_sdk)
  1375. dwarf_tool = self.tc.dwarf_tool
  1376. if dwarf_tool is None and self.tc.is_clang and (self.target.is_macos or self.target.is_ios):
  1377. dsymutil = '{}/bin/{}dsymutil'.format(self.tc.name_marker, '' if self.tc.version_at_least(7) else 'llvm-')
  1378. dwarf_tool = '${YMAKE_PYTHON} ${input:"build/scripts/run_llvm_dsymutil.py"} ' + dsymutil
  1379. if self.tc.version_at_least(5, 0):
  1380. dwarf_tool += ' -flat'
  1381. if dwarf_tool is not None:
  1382. emit('DWARF_TOOL', dwarf_tool)
  1383. arch_flag = '--arch={arch}'.format(arch=self.target.os_compat)
  1384. emit('_LD_ARCH_FLAG', arch_flag)
  1385. print('@import "${CONF_ROOT}/conf/linkers/ld.conf"')
  1386. class MSVCToolchainOptions(ToolchainOptions):
  1387. def __init__(self, build, detector):
  1388. super(MSVCToolchainOptions, self).__init__(build, detector)
  1389. # C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428
  1390. self.vc_root = None
  1391. # C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0
  1392. self.kit_includes = None
  1393. # C:\Program Files (x86)\Windows Kits\10\Lib\10.0.14393.0
  1394. self.kit_libs = None
  1395. self.under_wine_compiler = self.params.get('wine', False)
  1396. self.under_wine_tools = not build.host.is_windows
  1397. self.under_wine_link = self.under_wine_tools
  1398. self.under_wine_lib = self.under_wine_tools
  1399. self.system_msvc = self.params.get('system_msvc', False)
  1400. self.ide_msvs = self.params.get('ide_msvs', False)
  1401. self.use_clang = self.params.get('use_clang', False)
  1402. self.use_msvc_linker = is_positive('USE_MSVC_LINKER')
  1403. self.use_arcadia_toolchain = self.params.get('use_arcadia_toolchain', False)
  1404. self.sdk_version = None
  1405. if self.ide_msvs:
  1406. bindir = '$(VC_ExecutablePath_x64_x64)\\'
  1407. self.c_compiler = bindir + 'cl.exe'
  1408. self.cxx_compiler = self.c_compiler
  1409. self.link = bindir + 'link.exe'
  1410. self.lib = bindir + 'lib.exe'
  1411. self.masm_compiler = bindir + 'ml64.exe'
  1412. self.vc_root = None
  1413. sdk_dir = '$(WindowsSdkDir)'
  1414. self.sdk_version = '$(WindowsTargetPlatformVersion)'
  1415. self.kit_includes = win_path_fix(os.path.join(sdk_dir, 'Include', self.sdk_version))
  1416. self.kit_libs = win_path_fix(os.path.join(sdk_dir, 'Lib', self.sdk_version))
  1417. elif detector:
  1418. self.use_clang = is_positive('USE_CLANG_CL')
  1419. self.masm_compiler = which('ml64.exe')
  1420. self.link = which('link.exe')
  1421. self.lib = which('lib.exe')
  1422. sdk_dir = os.environ.get('WindowsSdkDir')
  1423. self.sdk_version = os.environ.get('WindowsSDKVersion').replace('\\', '')
  1424. vc_install_dir = os.environ.get('VCToolsInstallDir')
  1425. if any([x is None for x in (sdk_dir, self.sdk_version, vc_install_dir)]):
  1426. raise ConfigureError('No %WindowsSdkDir%, %WindowsSDKVersion% or %VCINSTALLDIR% present. Please, run vcvars64.bat to setup preferred environment.')
  1427. self.vc_root = os.path.normpath(vc_install_dir)
  1428. self.kit_includes = win_path_fix(os.path.normpath(os.path.join(sdk_dir, 'Include', self.sdk_version)))
  1429. self.kit_libs = win_path_fix(os.path.normpath(os.path.join(sdk_dir, 'Lib', self.sdk_version)))
  1430. # TODO(somov): Определять автоматически self.version в этом случае
  1431. else:
  1432. if self.version_at_least(2019):
  1433. self.sdk_version = '10.0.18362.0'
  1434. if is_positive('MSVC20'): # XXX: temporary flag, remove after DTCC-123 is completed
  1435. self.cxx_std = 'c++latest'
  1436. else:
  1437. self.sdk_version = '10.0.16299.0'
  1438. sdk_dir = '$WINDOWS_KITS_RESOURCE_GLOBAL'
  1439. self.vc_root = self.name_marker if not self.use_clang else '$MSVC_FOR_CLANG_RESOURCE_GLOBAL'
  1440. self.kit_includes = win_path_fix(os.path.join(sdk_dir, 'Include', self.sdk_version))
  1441. self.kit_libs = win_path_fix(os.path.join(sdk_dir, 'Lib', self.sdk_version))
  1442. bindir = win_path_fix(os.path.join(self.vc_root, 'bin', 'Hostx64'))
  1443. tools_name = select(selectors=[
  1444. (build.target.is_x86, 'x86'),
  1445. (build.target.is_x86_64, 'x64'),
  1446. (build.target.is_armv7, 'arm'),
  1447. ])
  1448. asm_name = select(selectors=[
  1449. (build.target.is_x86, 'ml.exe'),
  1450. (build.target.is_x86_64, 'ml64.exe'),
  1451. (build.target.is_armv7, 'armasm.exe'),
  1452. ])
  1453. self.masm_compiler = win_path_fix(os.path.join(bindir, tools_name, asm_name))
  1454. if self.use_clang and not self.use_msvc_linker:
  1455. self.link = self.host.exe(self.name_marker, "bin", "lld-link")
  1456. self.under_wine_link = False
  1457. else:
  1458. self.link = win_path_fix(os.path.join(bindir, tools_name, 'link.exe'))
  1459. self.under_wine_link = self.under_wine_tools
  1460. if self.use_clang:
  1461. self.lib = self.host.exe(self.name_marker, "bin", "llvm-lib")
  1462. self.under_wine_lib = False
  1463. else:
  1464. self.lib = win_path_fix(os.path.join(bindir, tools_name, 'lib.exe'))
  1465. self.under_wine_lib = self.under_wine_tools
  1466. logger.debug("link {}; lib {}".format(self.link, self.lib))
  1467. class MSVC(object):
  1468. def __init__(self, tc, build):
  1469. """
  1470. :type tc: MSVCToolchainOptions
  1471. :type build: Build
  1472. """
  1473. if not isinstance(tc, MSVCToolchainOptions):
  1474. raise TypeError('Got {} ({}) instead of an MSVCToolchainOptions'.format(tc, type(tc)))
  1475. self.build = build
  1476. self.tc = tc
  1477. class MSVCToolchain(MSVC, Toolchain):
  1478. def __init__(self, tc, build):
  1479. """
  1480. :type tc: MSVCToolchainOptions
  1481. :param build: Build
  1482. """
  1483. Toolchain.__init__(self, tc, build)
  1484. MSVC.__init__(self, tc, build)
  1485. if self.tc.from_arcadia and not self.tc.ide_msvs:
  1486. self.platform_projects.append('build/internal/platform/msvc')
  1487. if tc.under_wine_compiler or tc.under_wine_tools:
  1488. self.platform_projects.append('build/platform/wine')
  1489. def print_toolchain(self):
  1490. super(MSVCToolchain, self).print_toolchain()
  1491. emit('TOOLCHAIN_ENV', format_env(self.tc.get_env(), list_separator=';'))
  1492. if self.tc.sdk_version:
  1493. emit('WINDOWS_KITS_VERSION', self.tc.sdk_version)
  1494. if self.tc.under_wine_tools:
  1495. emit('_UNDER_WINE_TOOLS', 'yes')
  1496. if self.tc.under_wine_link:
  1497. emit('_UNDER_WINE_LINK', 'yes')
  1498. if self.tc.under_wine_lib:
  1499. emit('_UNDER_WINE_LIB', 'yes')
  1500. if self.tc.under_wine_compiler:
  1501. emit('_UNDER_WINE_COMPILER', 'yes')
  1502. if self.tc.use_clang:
  1503. emit('CLANG_CL', 'yes')
  1504. if self.tc.ide_msvs:
  1505. emit('IDE_MSVS', 'yes')
  1506. if self.tc.use_arcadia_toolchain:
  1507. emit('USE_ARCADIA_TOOLCHAIN', 'yes')
  1508. emit('_MSVC_TC_KIT_LIBS', self.tc.kit_libs)
  1509. emit('_MSVC_TC_VC_ROOT', self.tc.vc_root)
  1510. print('@import "${CONF_ROOT}/conf/toolchains/msvc_toolchain.conf"')
  1511. class MSVCCompiler(MSVC, Compiler):
  1512. def __init__(self, tc, build):
  1513. Compiler.__init__(self, tc, 'MSVC')
  1514. MSVC.__init__(self, tc, build)
  1515. def print_compiler(self):
  1516. super(MSVCCompiler, self).print_compiler()
  1517. target = self.build.target
  1518. warns_enabled = [
  1519. 4018, # 'expression' : signed/unsigned mismatch
  1520. 4265, # 'class' : class has virtual functions, but destructor is not virtual
  1521. 4296, # 'operator' : expression is always false
  1522. 4431, # missing type specifier - int assumed
  1523. ]
  1524. warns_as_error = [
  1525. 4013, # 'function' undefined; assuming extern returning int
  1526. ]
  1527. warns_disabled = [
  1528. # While this warning corresponds to enabled-by-default -Wmacro-redefinition,
  1529. # it floods clog with abundant amount of log lines,
  1530. # as yvals_core.h from Windows SDK redefines certain
  1531. # which macros logically belong to libcxx
  1532. 4005, # '__cpp_lib_*': macro redefinition.
  1533. # Ne need to recheck this, but it looks like _CRT_USE_BUILTIN_OFFSETOF still makes sense
  1534. 4117, # macro name '_CRT_USE_BUILTIN_OFFSETOF' is reserved, '#define' ignored
  1535. 4127, # conditional expression is constant
  1536. 4200, # nonstandard extension used : zero-sized array in struct/union
  1537. 4201, # nonstandard extension used : nameless struct/union
  1538. 4351, # elements of array will be default initialized
  1539. 4355, # 'this' : used in base member initializer list
  1540. 4503, # decorated name length exceeded, name was truncated
  1541. 4510, # default constructor could not be generated
  1542. 4511, # copy constructor could not be generated
  1543. 4512, # assignment operator could not be generated
  1544. 4554, # check operator precedence for possible error; use parentheses to clarify precedence
  1545. 4610, # 'object' can never be instantiated - user defined constructor required
  1546. 4706, # assignment within conditional expression
  1547. 4800, # forcing value to bool 'true' or 'false' (performance warning)
  1548. 4996, # The POSIX name for this item is deprecated
  1549. 4714, # function marked as __forceinline not inlined
  1550. 4197, # 'TAtomic' : top-level volatile in cast is ignored
  1551. 4245, # 'initializing' : conversion from 'int' to 'ui32', signed/unsigned mismatch
  1552. 4324, # 'ystd::function<void (uint8_t *)>': structure was padded due to alignment specifier
  1553. 5033, # 'register' is no longer a supported storage class
  1554. ]
  1555. defines = [
  1556. '${hide:CPP_FAKEID}',
  1557. # FIXME: This is quick fix to let catboost build from MSVS IDE
  1558. # This place is questionable overall, see YMAKE-437
  1559. '/DARCADIA_ROOT=' + ('${ARCADIA_ROOT}' if not self.tc.ide_msvs else '.'),
  1560. '/DARCADIA_BUILD_ROOT=' + ('${ARCADIA_BUILD_ROOT}' if not self.tc.ide_msvs else '.'),
  1561. '/DWIN32',
  1562. '/D_WIN32',
  1563. '/D_WINDOWS',
  1564. # Define _CRT_*_NO_WARNINGS macros to prevent ucrt from issuing a warning whenever
  1565. # a POSIX-style function is used instead of the alternative Microsoft suggests as a secure / standard replacement
  1566. # (e. g. `strncpy()` instead of `strncpy_s()`, `access()` instead of `_access()`)
  1567. # For details see:
  1568. # https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt
  1569. '/D_CRT_SECURE_NO_WARNINGS',
  1570. '/D_CRT_NONSTDC_NO_WARNINGS',
  1571. # Math constants (such as M_PI, M_E, M_SQRT2) are not defined in standard C / C++
  1572. # In order to get them defined by Windows ucrt library,
  1573. # you must first define _USE_MATH_DEFINES before #including <cmath> or math.h>.
  1574. # (NB: glibc defines these macros whenever _XOPEN_SOURCE is defined)
  1575. '/D_USE_MATH_DEFINES',
  1576. '/D__STDC_CONSTANT_MACROS',
  1577. '/D__STDC_FORMAT_MACROS',
  1578. '/D_USING_V110_SDK71_',
  1579. # Below defines are covered at
  1580. # https://docs.microsoft.com/en-us/windows/win32/winprog/using-the-windows-headers#faster-builds-with-smaller-header-files
  1581. # Exclude APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets (while including <windows.h>)
  1582. '/DWIN32_LEAN_AND_MEAN',
  1583. # Define NOMINMAX to avoid min() and max() macros definition (while including <windows.h>)
  1584. '/DNOMINMAX',
  1585. ]
  1586. cxx_defines = [
  1587. # Use builtin offsetof implementation
  1588. # instead of a crutcy macro defined in ucrt/stddef.h.
  1589. # The latter can not be used in constexpr statements.
  1590. '/D_CRT_USE_BUILTIN_OFFSETOF',
  1591. ]
  1592. if target.is_x86_64:
  1593. defines.extend(('/D_WIN64', '/DWIN64'))
  1594. if target.is_armv7:
  1595. defines.extend(('/D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE', '/D__arm__'))
  1596. winapi_unicode = False
  1597. flags = [
  1598. '/nologo', '/Zm500', '/GR', '/bigobj', '/FC', '/EHs', '/errorReport:prompt', '$MSVC_INLINE_FLAG', '/utf-8',
  1599. # enable standard conforming mode
  1600. '/permissive-'
  1601. ]
  1602. flags += self.tc.arch_opt
  1603. c_warnings = ['/we{}'.format(code) for code in warns_as_error]
  1604. c_warnings += ['/w1{}'.format(code) for code in warns_enabled]
  1605. c_warnings += ['/wd{}'.format(code) for code in warns_disabled]
  1606. cxx_warnings = []
  1607. if self.tc.use_clang:
  1608. if not self.tc.is_system_cxx:
  1609. flags += [
  1610. # Allow <windows.h> to be included via <Windows.h> in case-sensitive file-systems.
  1611. '-fcase-insensitive-paths',
  1612. ]
  1613. flags += [
  1614. # At the time clang-cl identifies itself as MSVC 19.11:
  1615. # (actual value can be found in clang/lib/Driver/ToolChains/MSVC.cpp, the syntax would be like
  1616. # ```
  1617. # MSVT = VersionTuple(19, 11);
  1618. # ```
  1619. #
  1620. # We override this value to match current value of the actual MSVC being used.
  1621. '-fms-compatibility-version=19.21',
  1622. # for msvc compatibility
  1623. # https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
  1624. '-fdelayed-template-parsing',
  1625. ]
  1626. if target.is_x86:
  1627. flags.append('-m32')
  1628. elif target.is_x86_64:
  1629. flags.append('-m64')
  1630. c_warnings.extend((
  1631. '-Wno-format',
  1632. '-Wno-parentheses',
  1633. '-Wno-unknown-warning-option',
  1634. ))
  1635. cxx_warnings += [
  1636. '-Wimport-preprocessor-directive-pedantic',
  1637. '-Woverloaded-virtual',
  1638. '-Wno-ambiguous-reversed-operator',
  1639. '-Wno-defaulted-function-deleted',
  1640. '-Wno-deprecated-anon-enum-enum-conversion',
  1641. '-Wno-deprecated-enum-enum-conversion',
  1642. '-Wno-deprecated-enum-float-conversion',
  1643. '-Wno-deprecated-volatile',
  1644. '-Wno-undefined-var-template',
  1645. ]
  1646. if self.tc.ide_msvs:
  1647. cxx_warnings += [
  1648. '-Wno-unused-command-line-argument',
  1649. ]
  1650. defines.append('/D_WIN32_WINNT={0}'.format(WINDOWS_VERSION_MIN))
  1651. if winapi_unicode:
  1652. defines += ['/DUNICODE', '/D_UNICODE']
  1653. else:
  1654. defines += ['/D_MBCS']
  1655. vc_include = win_path_fix(os.path.join(self.tc.vc_root, 'include')) if not self.tc.ide_msvs else "$(VC_VC_IncludePath.Split(';')[0].Replace('\\','/'))"
  1656. if not self.tc.ide_msvs:
  1657. def include_flag(path):
  1658. return '{flag}"{path}"'.format(path=path, flag='/I ' if not self.tc.use_clang else '-imsvc')
  1659. for name in ('shared', 'ucrt', 'um', 'winrt'):
  1660. flags.append(include_flag(win_path_fix(os.path.join(self.tc.kit_includes, name))))
  1661. flags.append(include_flag(vc_include))
  1662. if self.tc.use_clang:
  1663. emit('CLANG_CL', 'yes')
  1664. if self.tc.ide_msvs:
  1665. emit('IDE_MSVS', 'yes')
  1666. if self.tc.use_arcadia_toolchain:
  1667. emit('USE_ARCADIA_TOOLCHAIN', 'yes')
  1668. emit('CXX_COMPILER_UNQUOTED', '"{}"'.format(self.tc.cxx_compiler))
  1669. emit('CXX_COMPILER_OLD_UNQUOTED', self.tc.cxx_compiler)
  1670. emit('C_COMPILER_UNQUOTED', '"{}"'.format(self.tc.c_compiler))
  1671. emit('C_COMPILER_OLD_UNQUOTED', self.tc.c_compiler)
  1672. emit('MASM_COMPILER_UNQUOTED', '"{}"'.format(self.tc.masm_compiler))
  1673. emit('MASM_COMPILER_OLD_UNQUOTED', self.tc.masm_compiler)
  1674. append('C_DEFINES', defines)
  1675. append('C_WARNING_OPTS', c_warnings)
  1676. emit('_CXX_DEFINES', cxx_defines)
  1677. append('CXX_WARNING_OPTS', cxx_warnings)
  1678. if self.build.is_release:
  1679. emit('CFLAGS_PER_TYPE', '$CFLAGS_RELEASE')
  1680. if self.build.is_debug:
  1681. emit('CFLAGS_PER_TYPE', '$CFLAGS_DEBUG')
  1682. if self.build.is_ide:
  1683. emit('CFLAGS_PER_TYPE', '@[debug|$CFLAGS_DEBUG]@[release|$CFLAGS_RELEASE]')
  1684. emit('_STD_CXX_VERSION', preset('USER_STD_CXX_VERSION') or self.tc.cxx_std)
  1685. emit('_MSVC_FLAGS', flags)
  1686. ucrt_include = win_path_fix(os.path.join(self.tc.kit_includes, 'ucrt')) if not self.tc.ide_msvs else "$(UniversalCRT_IncludePath.Split(';')[0].Replace('\\','/'))"
  1687. # clang-cl has '#include_next', and MSVC hasn't. It needs separately specified CRT and VC include directories for libc++ to include second in order standard C and C++ headers.
  1688. if not self.tc.use_clang:
  1689. emit('_CFLAGS_UCRT_VC_INCLUDES', '/DY_UCRT_INCLUDE="%s"' % ucrt_include, '/DY_MSVC_INCLUDE="%s"' % vc_include)
  1690. else:
  1691. emit('_CFLAGS_UCRT_VC_INCLUDES')
  1692. emit('WERROR_MODE', self.tc.werror_mode)
  1693. print('@import "${CONF_ROOT}/conf/compilers/msvc_compiler.conf"')
  1694. class MSVCLinker(MSVC, Linker):
  1695. def __init__(self, tc, build):
  1696. MSVC.__init__(self, tc, build)
  1697. Linker.__init__(self, tc, build)
  1698. def print_linker(self):
  1699. super(MSVCLinker, self).print_linker()
  1700. linker = self.tc.link
  1701. linker_lib = self.tc.lib
  1702. emit('_MSVC_LIB', '"{}"'.format(linker_lib))
  1703. emit('_MSVC_LIB_OLD_UNQUOTED', linker_lib)
  1704. emit('_MSVC_LIB_OLD', '${quo:_MSVC_LIB_OLD_UNQUOTED}')
  1705. emit('_MSVC_LINK', '"{}"'.format(linker))
  1706. emit('_MSVC_LINK_OLD_UNQUOTED', linker)
  1707. emit('_MSVC_LINK_OLD', '${quo:_MSVC_LINK_OLD_UNQUOTED}')
  1708. if self.build.is_release:
  1709. emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_RELEASE')
  1710. if self.build.is_debug:
  1711. emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_DEBUG')
  1712. if self.build.is_ide and self.tc.ide_msvs:
  1713. emit('LINK_EXE_FLAGS_PER_TYPE', '@[debug|$LINK_EXE_FLAGS_DEBUG]@[release|$LINK_EXE_FLAGS_RELEASE]')
  1714. print('@import "${CONF_ROOT}/conf/linkers/msvc_linker.conf"')
  1715. # TODO(somov): Rename!
  1716. Compilers = {
  1717. 'gnu': (GnuToolchain, GnuCompiler, LD),
  1718. 'clang': (GnuToolchain, GnuCompiler, LD),
  1719. 'xcode': (GnuToolchain, GnuCompiler, LD),
  1720. 'msvc': (MSVCToolchain, MSVCCompiler, MSVCLinker),
  1721. }
  1722. class Ragel(object):
  1723. def __init__(self):
  1724. self.rlgen_flags = []
  1725. self.ragel_flags = []
  1726. self.ragel6_flags = []
  1727. def configure_toolchain(self, build, compiler):
  1728. if isinstance(compiler, MSVCCompiler):
  1729. self.set_default_flags(optimized=False)
  1730. elif isinstance(compiler, GnuCompiler):
  1731. self.set_default_flags(optimized=build.is_release and not build.is_sanitized)
  1732. else:
  1733. raise ConfigureError('Unexpected compiler {}'.format(compiler))
  1734. def set_default_flags(self, optimized):
  1735. if optimized:
  1736. self.rlgen_flags.append('-G2')
  1737. self.ragel6_flags.append('-CG2')
  1738. else:
  1739. self.rlgen_flags.append('-T0')
  1740. self.ragel6_flags.append('-CT0')
  1741. def print_variables(self):
  1742. emit('RLGEN_FLAGS', self.rlgen_flags)
  1743. emit('RAGEL_FLAGS', self.ragel_flags)
  1744. emit('RAGEL6_FLAGS', self.ragel6_flags)
  1745. class Python(object):
  1746. def __init__(self, tc):
  1747. self.python = None
  1748. self.flags = None
  1749. self.ldflags = None
  1750. self.libraries = None
  1751. self.includes = None
  1752. self.tc = tc
  1753. def configure_posix(self, python=None, python_config=None):
  1754. self.check_configuration()
  1755. python = python or preset('PYTHON_BIN') or which('python')
  1756. python_config = python_config or preset('PYTHON_CONFIG') or which('python-config')
  1757. if python is None or python_config is None:
  1758. return
  1759. # python-config dumps each option on one line in the specified order
  1760. config = get_stdout([python_config, '--cflags', '--ldflags', '--includes']) or ''
  1761. config = config.split('\n')
  1762. if len(config) < 3:
  1763. return
  1764. self.python = python
  1765. self.flags = config[0]
  1766. self.ldflags = config[1]
  1767. self.includes = config[2]
  1768. # Do not split libraries from ldflags.
  1769. # They are not used separately and get overriden together, so it is safe.
  1770. # TODO(somov): Удалить эту переменную и PYTHON_LIBRARIES из makelist-ов.
  1771. self.libraries = ''
  1772. def check_configuration(self):
  1773. if preset('USE_ARCADIA_PYTHON') == 'no':
  1774. # Set USE_LOCAL_PYTHON to enable configuration
  1775. # when we still using fixed OS SDK,
  1776. # but at the same time using Python from the local system.
  1777. #
  1778. # This configuration is not guaranteed to work,
  1779. # for example, if local and fixed OS SDKs differ much.
  1780. if preset('USE_LOCAL_PYTHON') == 'yes':
  1781. return
  1782. if not preset('USE_SYSTEM_PYTHON') and not self.tc.os_sdk_local:
  1783. raise Exception("Use fixed python (see https://clubs.at.yandex-team.ru/arcadia/15392) or set OS_SDK=local flag")
  1784. def print_variables(self):
  1785. variables = Variables({
  1786. 'PYTHON_BIN': self.python,
  1787. 'PYTHON_FLAGS': self.flags,
  1788. 'PYTHON_LDFLAGS': self.ldflags,
  1789. 'PYTHON_LIBRARIES': self.libraries,
  1790. 'PYTHON_INCLUDE': self.includes
  1791. })
  1792. variables.update_from_presets()
  1793. variables.reset_if_any(reset_value='PYTHON-NOT-FOUND')
  1794. variables.emit()
  1795. class Setting(object):
  1796. def __init__(self, key, auto=None, convert=None, rewrite=False):
  1797. self.key = key
  1798. self.auto = auto
  1799. self.convert = convert
  1800. self.preset = preset(key)
  1801. self.from_user = self.preset is not None
  1802. self.rewrite = rewrite
  1803. self._value = Setting.no_value
  1804. @property
  1805. def value(self):
  1806. if self._value is Setting.no_value:
  1807. self._value = self.calculate_value()
  1808. return self._value
  1809. def calculate_value(self):
  1810. if not self.from_user:
  1811. return self.auto if not callable(self.auto) else self.auto()
  1812. else:
  1813. return self.preset if not self.convert else self.convert(self.preset)
  1814. @value.setter
  1815. def value(self, value):
  1816. if self.from_user:
  1817. raise ConfigureError("Variable {key} already set by user to {old}. Can not change it's value to {new}".format(key=self.key, old=self._value, new=value))
  1818. self._value = value
  1819. def emit(self):
  1820. if not self.from_user or self.rewrite:
  1821. emit(self.key, self.value)
  1822. no_value = object()
  1823. class Cuda(object):
  1824. def __init__(self, build):
  1825. """
  1826. :type build: Build
  1827. """
  1828. self.build = build
  1829. self.have_cuda = Setting('HAVE_CUDA', auto=self.auto_have_cuda, convert=to_bool)
  1830. self.cuda_root = Setting('CUDA_ROOT')
  1831. self.cuda_target_root = Setting('CUDA_TARGET_ROOT')
  1832. self.cuda_version = Setting('CUDA_VERSION', auto=self.auto_cuda_version, convert=self.convert_major_version, rewrite=True)
  1833. self.cuda_architectures = Setting('CUDA_ARCHITECTURES', auto=self.auto_cuda_architectures, rewrite=True)
  1834. self.use_arcadia_cuda = Setting('USE_ARCADIA_CUDA', auto=self.auto_use_arcadia_cuda, convert=to_bool)
  1835. self.use_arcadia_cuda_host_compiler = Setting('USE_ARCADIA_CUDA_HOST_COMPILER', auto=self.auto_use_arcadia_cuda_host_compiler, convert=to_bool)
  1836. self.cuda_use_clang = Setting('CUDA_USE_CLANG', auto=False, convert=to_bool)
  1837. self.cuda_host_compiler = Setting('CUDA_HOST_COMPILER', auto=self.auto_cuda_host_compiler)
  1838. self.cuda_host_compiler_env = Setting('CUDA_HOST_COMPILER_ENV')
  1839. self.cuda_host_msvc_version = Setting('CUDA_HOST_MSVC_VERSION')
  1840. self.cuda_nvcc_flags = Setting('CUDA_NVCC_FLAGS', auto=[])
  1841. self.peerdirs = ['build/platform/cuda']
  1842. self.nvcc_flags = [
  1843. # Compress fatbinary to reduce size of .nv_fatbin and prevent problems with linking
  1844. #
  1845. # Idea comes from many resources, one of them is https://discourse.llvm.org/t/lld-relocation-overflows-and-nv-fatbin/58889/6
  1846. # Some sources suggest using `-Xfatbin=-compress-all`, other suggest using `-Xcuda-fatbinary --compress-all`
  1847. # We will use the same flag as in nixpkgs
  1848. # (https://github.com/NixOS/nixpkgs/pull/220402/files#diff-a38e6c4e8421c03dc6c2a60c9a172ceb4059048b65798e5d4a400a7a4a5720ffR167)
  1849. "-Xfatbin=-compress-all",
  1850. # Allow __host__, __device__ annotations in lambda declaration.
  1851. "--expt-extended-lambda",
  1852. # Allow host code to invoke __device__ constexpr functions and vice versa
  1853. "--expt-relaxed-constexpr",
  1854. # Allow to use newer compilers than CUDA Toolkit officially supports
  1855. "--allow-unsupported-compiler",
  1856. # Set paths explicitly
  1857. "--dont-use-profile",
  1858. "--libdevice-directory=$CUDA_ROOT/nvvm/libdevice",
  1859. ]
  1860. if not self.have_cuda.value:
  1861. return
  1862. if self.cuda_host_compiler.value:
  1863. self.nvcc_flags.append('--compiler-bindir=$CUDA_HOST_COMPILER')
  1864. if self.use_arcadia_cuda.value:
  1865. self.cuda_root.value = '$CUDA_RESOURCE_GLOBAL'
  1866. host, target = self.build.host_target
  1867. if host == target:
  1868. self.cuda_target_root.value = '$CUDA_RESOURCE_GLOBAL'
  1869. else:
  1870. self.cuda_target_root.value = '$CUDA_TARGET_RESOURCE_GLOBAL'
  1871. if self.build.target.is_linux_x86_64 and self.build.tc.is_clang:
  1872. # TODO(somov): Эта настройка должна приезжать сюда автоматически из другого места
  1873. self.nvcc_flags.append('-I$OS_SDK_ROOT/usr/include/x86_64-linux-gnu')
  1874. def print_(self):
  1875. self.print_variables()
  1876. self.print_macros()
  1877. print('@import "${CONF_ROOT}/conf/compilers/nvcc.conf"')
  1878. def print_variables(self):
  1879. self.have_cuda.emit()
  1880. if not self.have_cuda.value:
  1881. return
  1882. if self.use_arcadia_cuda.value and self.cuda_host_compiler.value is None:
  1883. logger.warning('$USE_ARCADIA_CUDA is set, but no $CUDA_HOST_COMPILER')
  1884. self.setup_vc_root()
  1885. self.cuda_root.emit()
  1886. self.cuda_target_root.emit()
  1887. self.cuda_version.emit()
  1888. self.cuda_architectures.emit()
  1889. self.use_arcadia_cuda.emit()
  1890. self.use_arcadia_cuda_host_compiler.emit()
  1891. self.cuda_use_clang.emit()
  1892. self.cuda_host_compiler.emit()
  1893. self.cuda_host_compiler_env.emit()
  1894. self.cuda_host_msvc_version.emit()
  1895. self.cuda_nvcc_flags.emit()
  1896. emit('NVCC', '"{}"'.format(self.build.host.exe('$CUDA_ROOT', 'bin', 'nvcc')))
  1897. emit('NVCC_OLD_UNQUOTED', self.build.host.exe('$CUDA_ROOT', 'bin', 'nvcc'))
  1898. emit('NVCC_OLD', '${quo:NVCC_OLD_UNQUOTED}')
  1899. emit('NVCC_FLAGS', self.nvcc_flags, '$CUDA_NVCC_FLAGS')
  1900. emit('NVCC_OBJ_EXT', '.o' if not self.build.target.is_windows else '.obj')
  1901. emit('NVCC_ENV', format_env({'PATH': '$CUDA_ROOT/nvvm/bin:$CUDA_ROOT/bin'}))
  1902. def print_macros(self):
  1903. mtime = ' '
  1904. if self.build.host_target[1].is_linux:
  1905. mtime = ' --mtime ${tool:"tools/mtime0"} '
  1906. if not self.cuda_use_clang.value:
  1907. cmd = '$YMAKE_PYTHON ${input:"build/scripts/compile_cuda.py"}' + mtime + '$NVCC_OLD $NVCC_STD $NVCC_FLAGS -c ${input:SRC} -o ${output;suf=${OBJ_SUF}${NVCC_OBJ_EXT}:SRC} ${pre=-I:_C__INCLUDE} --cflags $C_FLAGS_PLATFORM $CXXFLAGS $NVCC_STD $NVCC_CFLAGS $SRCFLAGS ${input;hide:"build/platform/cuda/cuda_runtime_include.h"} $NVCC_ENV $CUDA_HOST_COMPILER_ENV ${kv;hide:"p CC"} ${kv;hide:"pc light-green"}' # noqa E501
  1908. else:
  1909. cmd = '$CXX_COMPILER_OLD --cuda-path=$CUDA_ROOT $C_FLAGS_PLATFORM -c ${input:SRC} -o ${output;suf=${OBJ_SUF}${NVCC_OBJ_EXT}:SRC} ${pre=-I:_C__INCLUDE} $CXXFLAGS $SRCFLAGS $TOOLCHAIN_ENV ${kv;hide:"p CU"} ${kv;hide:"pc green"}' # noqa E501
  1910. emit('_SRC_CU_CMD', cmd)
  1911. emit('_SRC_CU_PEERDIR', ' '.join(sorted(self.peerdirs)))
  1912. # This method is only used to set HAVE_CUDA=no automatically during ymake initialization
  1913. # (i.e. is used only in `auto_have_cuda` invocation)
  1914. def have_cuda_in_arcadia(self):
  1915. host, target = self.build.host_target
  1916. if not any((host.is_linux_x86_64, host.is_windows_x86_64)):
  1917. return False
  1918. if host != target:
  1919. if not (host.is_linux_x86_64 and target.is_linux_armv8):
  1920. return False
  1921. if not self.cuda_version.from_user:
  1922. return False
  1923. if self.cuda_version.value in ('11.4', '11.8', '12.1', '12.2'):
  1924. return True
  1925. elif self.cuda_version.value in ('10.2',) and target.is_linux_armv8:
  1926. return True
  1927. else:
  1928. raise ConfigureError('CUDA version {} is not supported in Arcadia'.format(self.cuda_version.value))
  1929. def auto_have_cuda(self):
  1930. if is_positive('MUSL'):
  1931. return False
  1932. if self.build.is_sanitized:
  1933. return False
  1934. return self.cuda_root.from_user or self.use_arcadia_cuda.value and self.have_cuda_in_arcadia()
  1935. def auto_cuda_version(self):
  1936. if self.use_arcadia_cuda.value:
  1937. return '11.4'
  1938. if not self.have_cuda.value:
  1939. return None
  1940. nvcc_exe = self.build.host.exe(os.path.expanduser(self.cuda_root.value), 'bin', 'nvcc')
  1941. def error():
  1942. raise ConfigureError('Failed to get CUDA version from {}'.format(nvcc_exe))
  1943. version_output = get_stdout([nvcc_exe, '--version']) or error()
  1944. match = re.search(r'^Cuda compilation tools, release (\d+)\.\d+,', version_output, re.MULTILINE) or error()
  1945. return match.group(1)
  1946. def convert_major_version(self, value):
  1947. if value == '11':
  1948. return '11.4'
  1949. else:
  1950. return value
  1951. def auto_cuda_architectures(self):
  1952. # empty list does not mean "no architectures"
  1953. # it means "no restriction -- any available architecture"
  1954. host, target = self.build.host_target
  1955. if not target.is_linux_x86_64:
  1956. # do not impose any restrictions, when build not for "linux 64-bit"
  1957. return ''
  1958. # Equality to CUDA 11.4 is rather strict comparison
  1959. # TODO: find out how we can relax check (e.g. to include more version of CUDA toolkit)
  1960. if self.cuda_version.value == '11.4':
  1961. # * use output of CUDA 11.4 `nvcc --help`
  1962. # * drop support for '53', '62', '72' and '87'
  1963. # (these devices run only on arm64)
  1964. # * drop support for '37'
  1965. # the single place it's used in Arcadia is https://a.yandex-team.ru/arcadia/sdg/sdc/third_party/cub/common.mk?rev=r13268523#L69
  1966. return ':'.join(
  1967. ['sm_35',
  1968. 'sm_50', 'sm_52',
  1969. 'sm_60', 'sm_61',
  1970. 'sm_70', 'sm_75',
  1971. 'sm_80', 'sm_86',
  1972. 'compute_86'])
  1973. else:
  1974. return ''
  1975. def auto_use_arcadia_cuda(self):
  1976. return not self.cuda_root.from_user
  1977. def auto_use_arcadia_cuda_host_compiler(self):
  1978. return not self.cuda_host_compiler.from_user and not self.cuda_use_clang.value
  1979. def auto_cuda_host_compiler(self):
  1980. if not self.use_arcadia_cuda_host_compiler.value:
  1981. return None
  1982. host, target = self.build.host_target
  1983. if host.is_windows_x86_64 and target.is_windows_x86_64:
  1984. return self.cuda_windows_host_compiler()
  1985. return select((
  1986. (host.is_linux_x86_64 and target.is_linux_x86_64, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  1987. (host.is_linux_x86_64 and target.is_linux_armv8, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  1988. ))
  1989. def cuda_windows_host_compiler(self):
  1990. vc_version = '14.28.29910'
  1991. env = {
  1992. 'Y_VC_Version': vc_version,
  1993. 'Y_VC_Root': '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/VC/Tools/MSVC/{}'.format(vc_version),
  1994. 'Y_SDK_Version': self.build.tc.sdk_version,
  1995. 'Y_SDK_Root': '$WINDOWS_KITS_RESOURCE_GLOBAL',
  1996. }
  1997. if not self.build.tc.ide_msvs:
  1998. self.peerdirs.append('build/internal/platform/msvc')
  1999. self.cuda_host_compiler_env.value = format_env(env)
  2000. self.cuda_host_msvc_version.value = vc_version
  2001. return '%(Y_VC_Root)s/bin/HostX64/x64/cl.exe' % env
  2002. def setup_vc_root(self):
  2003. if not self.cuda_host_compiler.from_user:
  2004. return # Already set in cuda_windows_host_compiler()
  2005. if self.cuda_host_compiler_env.from_user:
  2006. return # We won't override user setting
  2007. def is_root(dir):
  2008. return all(os.path.isdir(os.path.join(dir, name)) for name in ('bin', 'include', 'lib'))
  2009. def get_root():
  2010. path, old_path = os.path.normpath(self.cuda_host_compiler.value), None
  2011. while path != old_path:
  2012. if is_root(path):
  2013. return path
  2014. path, old_path = os.path.dirname(path), path
  2015. vc_root = get_root()
  2016. if vc_root:
  2017. self.cuda_host_compiler_env.value = format_env({'Y_VC_Root': vc_root})
  2018. class CuDNN(object):
  2019. def __init__(self, cuda):
  2020. """
  2021. :type cuda: Cuda
  2022. """
  2023. self.cuda = cuda
  2024. self.cudnn_version = Setting('CUDNN_VERSION', auto=self.auto_cudnn_version)
  2025. def have_cudnn(self):
  2026. return self.cudnn_version.value in ('7.6.5', '8.0.5')
  2027. def auto_cudnn_version(self):
  2028. return '8.0.5'
  2029. def print_(self):
  2030. if self.cuda.have_cuda.value and self.have_cudnn():
  2031. self.cudnn_version.emit()
  2032. def customization():
  2033. if not is_positive('DISABLE_YMAKE_CONF_CUSTOMIZATION'):
  2034. try:
  2035. sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'internal'))
  2036. from custom_conf import CustomConf
  2037. logger.debug('Customization extension was successfully loaded')
  2038. return CustomConf
  2039. except Exception as e:
  2040. logger.debug('Customization extension was not found; [{}]'.format(str(e)))
  2041. else:
  2042. logger.debug('Customization extension was disabled')
  2043. class DummyConf:
  2044. def __init__(self, options):
  2045. pass
  2046. def print_prologue(self):
  2047. pass
  2048. def print_epilogue(self):
  2049. pass
  2050. return DummyConf
  2051. def main():
  2052. options = opts()
  2053. CustomConfig = customization()
  2054. custom_conf = CustomConfig(options)
  2055. arcadia = Arcadia(options.arcadia_root)
  2056. ymake = YMake(arcadia)
  2057. ymake.print_core_conf()
  2058. _INTERNAL_CONF = 'internal/conf/internal.conf'
  2059. internal_conf_full_path = find_conf(_INTERNAL_CONF)
  2060. if internal_conf_full_path and not is_positive('DISABLE_YMAKE_CONF_CUSTOMIZATION'):
  2061. print('@import "${{CONF_ROOT}}/{}"'.format(_INTERNAL_CONF))
  2062. custom_conf.print_prologue()
  2063. ymake.print_presets()
  2064. ymake.print_settings()
  2065. build = Build(arcadia, options.build_type, options.toolchain_params, force_ignore_local_files=not options.local_distbuild)
  2066. build.print_build()
  2067. custom_conf.print_epilogue()
  2068. if __name__ == '__main__':
  2069. main()