ymake_conf.py 96 KB

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