ymake_conf.py 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247
  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_arm64 = self.arch in ('arm64',)
  46. self.is_arm = self.is_armv7 or self.is_armv8 or self.is_armv8m
  47. self.is_armv7_neon = self.arch in ('armv7a_neon', 'armv7ahf', 'armv7a_cortex_a9', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  48. self.is_armv7hf = self.arch in ('armv7ahf', 'armv7ahf_cortex_a35', 'armv7ahf_cortex_a53')
  49. self.is_nds32 = self.arch in ('nds32le_elf_mculib_v5f',)
  50. self.armv7_float_abi = None
  51. if self.is_armv7:
  52. if self.is_armv7hf:
  53. self.armv7_float_abi = 'hard'
  54. else:
  55. self.armv7_float_abi = 'softfp'
  56. self.is_cortex_a9 = self.arch in ('armv7a_cortex_a9',)
  57. self.is_cortex_a35 = self.arch in ('armv7ahf_cortex_a35', 'armv8a_cortex_a35')
  58. self.is_cortex_a53 = self.arch in ('armv7ahf_cortex_a53', 'armv8a_cortex_a53')
  59. self.is_cortex_m33 = self.arch in ('armv8m_cortex_m33',)
  60. self.is_power8le = self.arch == 'ppc64le'
  61. self.is_power9le = self.arch == 'power9le'
  62. self.is_powerpc = self.is_power8le or self.is_power9le
  63. self.is_32_bit = self.is_x86 or self.is_armv7 or self.is_armv8m or self.is_nds32
  64. self.is_64_bit = self.is_x86_64 or self.is_armv8 or self.is_powerpc
  65. assert self.is_32_bit or self.is_64_bit
  66. assert not (self.is_32_bit and self.is_64_bit)
  67. self.is_linux = self.os == 'linux' or 'yocto' in self.os
  68. self.is_linux_x86_64 = self.is_linux and self.is_x86_64
  69. self.is_linux_armv8 = self.is_linux and self.is_armv8
  70. self.is_linux_armv7 = self.is_linux and self.is_armv7
  71. self.is_linux_power8le = self.is_linux and self.is_power8le
  72. self.is_linux_power9le = self.is_linux and self.is_power9le
  73. self.is_linux_powerpc = self.is_linux_power8le or self.is_linux_power9le
  74. self.is_macos = self.os == 'macos'
  75. self.is_macos_x86_64 = self.is_macos and self.is_x86_64
  76. self.is_macos_arm64 = self.is_macos and self.is_arm64
  77. self.is_iossim = self.os == 'iossim' or (self.os == 'ios' and self.is_intel)
  78. self.is_ios = self.os == 'ios' or self.is_iossim
  79. self.is_apple = self.is_macos or self.is_ios
  80. self.is_windows = self.os == 'windows'
  81. self.is_windows_x86_64 = self.is_windows and self.is_x86_64
  82. self.is_android = self.os == 'android'
  83. if self.is_android:
  84. # This is default Android API level unless `ANDROID_API` is specified
  85. # 18 is the smallest level with OpenGL support
  86. # 21 is the smallest level for 64-bit platforms
  87. default_android_api = 21 if self.is_64_bit else 18
  88. self.android_api = int(preset('ANDROID_API', default_android_api))
  89. self.is_cygwin = self.os == 'cygwin'
  90. self.is_yocto = self.os == 'yocto'
  91. self.is_none = self.os == 'none'
  92. self.is_posix = self.is_linux or self.is_apple or self.is_android or self.is_cygwin or self.is_yocto
  93. @staticmethod
  94. def from_json(data):
  95. name = data.get('visible_name', data['toolchain'])
  96. return Platform(name, os=data['os'], arch=data['arch'])
  97. @property
  98. def os_variables(self):
  99. # 'LINUX' variable, for backward compatibility
  100. yield self.os.upper()
  101. # 'OS_LINUX' variable
  102. yield 'OS_{}'.format(self.os.upper())
  103. # yocto is linux
  104. if 'yocto' in self.os:
  105. yield 'LINUX'
  106. yield 'OS_LINUX'
  107. if self.is_macos:
  108. yield 'DARWIN'
  109. yield 'OS_DARWIN'
  110. if self.is_iossim:
  111. yield 'IOS'
  112. yield 'OS_IOS'
  113. yield 'OS_IOSSIM'
  114. @property
  115. def arch_variables(self):
  116. return select_multiple((
  117. (self.is_i386 or self.is_i686, 'ARCH_I386'),
  118. (self.is_i686, 'ARCH_I686'),
  119. (self.is_x86_64, 'ARCH_X86_64'),
  120. (self.is_armv7, 'ARCH_ARM7'),
  121. (self.is_armv7_neon, 'ARCH_ARM7_NEON'),
  122. (self.is_armv8, 'ARCH_ARM64'),
  123. (self.is_armv8m, 'ARCH_ARM8M'),
  124. (self.is_arm, 'ARCH_ARM'),
  125. (self.is_linux_armv8 or self.is_macos_arm64, 'ARCH_AARCH64'),
  126. (self.is_powerpc, 'ARCH_PPC64LE'),
  127. (self.is_power8le, 'ARCH_POWER8LE'),
  128. (self.is_power9le, 'ARCH_POWER9LE'),
  129. (self.is_nds32, 'ARCH_NDS32'),
  130. (self.is_32_bit, 'ARCH_TYPE_32'),
  131. (self.is_64_bit, 'ARCH_TYPE_64'),
  132. ))
  133. @property
  134. def library_path_variables(self):
  135. return ['LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH']
  136. def find_in_dict(self, dict_, default=None):
  137. if dict_ is None:
  138. return default
  139. for key in six.iterkeys(dict_):
  140. if self._parse_os(key) == self.os:
  141. return dict_[key]
  142. return default
  143. @property
  144. def os_compat(self):
  145. if self.is_macos:
  146. return 'DARWIN'
  147. else:
  148. return self.os.upper()
  149. def exe(self, *paths):
  150. if self.is_windows:
  151. return ntpath.join(*itertools.chain(paths[:-1], (paths[-1] + '.exe',)))
  152. else:
  153. return posixpath.join(*paths)
  154. def __str__(self):
  155. return '{name}-{os}-{arch}'.format(name=self.name, os=self.os, arch=self.arch)
  156. def __cmp__(self, other):
  157. return cmp((self.name, self.os, self.arch), (other.name, other.os, other.arch))
  158. def __hash__(self):
  159. return hash((self.name, self.os, self.arch))
  160. @staticmethod
  161. def _parse_os(os):
  162. os = os.lower()
  163. if os == 'darwin':
  164. return 'macos'
  165. if os in ('win', 'win32', 'win64'):
  166. return 'windows'
  167. if os.startswith('cygwin'):
  168. return 'cygwin'
  169. return os
  170. def which(prog):
  171. if os.path.exists(prog) and os.access(prog, os.X_OK):
  172. return prog
  173. # Ищем в $PATH только простые команды, без путей.
  174. if os.path.dirname(prog) != '':
  175. return None
  176. path = os.getenv('PATH', '')
  177. pathext = os.environ.get('PATHEXT')
  178. # На Windows %PATHEXT% указывает на список расширений, которые нужно проверять
  179. # при поиске команды в пути. Точное совпадение без расширения имеет приоритет.
  180. pathext = [''] if pathext is None else [''] + pathext.lower().split(os.pathsep)
  181. for dir_ in path.split(os.path.pathsep):
  182. for ext in pathext:
  183. p = os.path.join(dir_, prog + ext)
  184. if os.path.exists(p) and os.path.isfile(p) and os.access(p, os.X_OK):
  185. return p
  186. return None
  187. def get_stdout(command):
  188. stdout, code = get_stdout_and_code(command)
  189. return stdout if code == 0 else None
  190. def get_stdout_and_code(command):
  191. # noinspection PyBroadException
  192. try:
  193. process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  194. stdout, _ = process.communicate()
  195. return stdout, process.returncode
  196. except Exception:
  197. return None, None
  198. def to_strings(o):
  199. if isinstance(o, (list, tuple)):
  200. for s in o:
  201. for ss in to_strings(s):
  202. yield ss
  203. else:
  204. if o is not None:
  205. if isinstance(o, bool):
  206. yield 'yes' if o else 'no'
  207. elif isinstance(o, (str, int)):
  208. yield str(o)
  209. else:
  210. raise ConfigureError('Unexpected value {} {}'.format(type(o), o))
  211. def emit(key, *value):
  212. print('{0}={1}'.format(key, ' '.join(to_strings(value))))
  213. def emit_with_comment(comment, key, *value):
  214. print('# {}'.format(comment))
  215. emit(key, *value)
  216. def emit_with_ignore_comment(key, *value):
  217. emit_with_comment('IGNORE YMAKE CONF CONTEXT', key, *value)
  218. def append(key, *value):
  219. print('{0}+={1}'.format(key, ' '.join(to_strings(value))))
  220. def emit_big(text):
  221. prefix = None
  222. first = True
  223. for line in text.split('\n'):
  224. if prefix is None:
  225. if not line:
  226. continue
  227. prefix = 0
  228. while prefix < len(line) and line[prefix] == ' ':
  229. prefix += 1
  230. if first: # Be pretty, prepend an empty line before the output
  231. print()
  232. first = False
  233. print(line[prefix:])
  234. class Variables(dict):
  235. def emit(self, with_ignore_comment=[]):
  236. with_ignore_comment_set = set(with_ignore_comment)
  237. for k in sorted(self.keys()):
  238. if k in with_ignore_comment_set:
  239. emit_with_ignore_comment(k, self[k])
  240. else:
  241. emit(k, self[k])
  242. def update_from_presets(self):
  243. for k in six.iterkeys(self):
  244. v = preset(k)
  245. if v is not None:
  246. self[k] = v
  247. def reset_if_any(self, value_check=None, reset_value=None):
  248. if value_check is None:
  249. def value_check(v_):
  250. return v_ is None
  251. if any(map(value_check, six.itervalues(self))):
  252. for k in six.iterkeys(self):
  253. self[k] = reset_value
  254. def format_env(env, list_separator=':'):
  255. def format_value(value):
  256. return value if isinstance(value, str) else ('\\' + list_separator).join(value)
  257. def format(kv):
  258. return '${env:"%s=%s"}' % (kv[0], format_value(kv[1]))
  259. return ' '.join(map(format, sorted(six.iteritems(env))))
  260. # TODO(somov): Проверить, используется ли это. Может быть, выпилить.
  261. def userify_presets(presets, keys):
  262. for key in keys:
  263. user_key = 'USER_{}'.format(key)
  264. values = [presets.pop(key, None), presets.get(user_key)]
  265. presets[user_key] = ' '.join(filter(None, values))
  266. def preset(key, default=None):
  267. return opts().presets.get(key, default)
  268. def is_positive(key):
  269. return is_positive_str(preset(key, ''))
  270. def is_positive_str(s):
  271. return s.lower() in ('yes', 'true', 'on', '1')
  272. def is_negative(key):
  273. return is_negative_str(preset(key, ''))
  274. def is_negative_str(s):
  275. return s.lower() in ('no', 'false', 'off', '0')
  276. def to_bool(s, default=None):
  277. if isinstance(s, six.string_types):
  278. if is_positive_str(s):
  279. return True
  280. if is_negative_str(s):
  281. return False
  282. if default is None:
  283. raise ConfigureError('{} is not a bool value'.format(s))
  284. return default
  285. def select(selectors, default=None, no_default=False):
  286. for enabled, value in selectors:
  287. if enabled:
  288. return value
  289. if no_default:
  290. raise ConfigureError()
  291. return default
  292. def select_multiple(selectors):
  293. for enabled, value in selectors:
  294. if enabled:
  295. yield value
  296. def unique(it):
  297. known = set()
  298. for i in it:
  299. if i not in known:
  300. known.add(i)
  301. yield i
  302. class Options(object):
  303. def __init__(self, argv):
  304. def parse_presets(raw_presets):
  305. presets = {}
  306. for p in raw_presets:
  307. toks = p.split('=', 1)
  308. name = toks[0]
  309. value = toks[1] if len(toks) >= 2 else ''
  310. presets[name] = value
  311. return presets
  312. parser = optparse.OptionParser(add_help_option=False)
  313. opt_group = optparse.OptionGroup(parser, 'Conf script options')
  314. opt_group.add_option('--toolchain-params', dest='toolchain_params', action='store', help='Set toolchain params via file')
  315. opt_group.add_option('-D', '--preset', dest='presets', action='append', default=[], help='set or override presets')
  316. opt_group.add_option('-l', '--local-distbuild', dest='local_distbuild', action='store_true', default=False, help='conf for local distbuild')
  317. parser.add_option_group(opt_group)
  318. self.options, self.arguments = parser.parse_args(argv)
  319. argv = self.arguments
  320. if len(argv) < 4:
  321. print('Usage: ArcRoot, --BuildType--, Verbosity, [Path to local.ymake]', file=sys.stderr)
  322. sys.exit(1)
  323. self.arcadia_root = argv[1]
  324. init_logger(argv[3] == 'verbose')
  325. # Эти переменные не надо использоваться напрямую. Их значения уже разбираются в других местах.
  326. self.build_type = argv[2].lower()
  327. self.local_distbuild = self.options.local_distbuild
  328. self.toolchain_params = self.options.toolchain_params
  329. self.presets = parse_presets(self.options.presets)
  330. userify_presets(self.presets, ('CFLAGS', 'CXXFLAGS', 'CONLYFLAGS', 'LDFLAGS', 'GO_COMPILE_FLAGS', 'GO_LINK_FLAGS', 'USE_LOCAL_SWIG', 'SWIG_TOOL', 'SWIG_LIBRARY'))
  331. Instance = None
  332. def opts():
  333. if Options.Instance is None:
  334. Options.Instance = Options(sys.argv)
  335. return Options.Instance
  336. class Profiler(object):
  337. Generic = 'generic'
  338. GProf = 'gprof'
  339. class Arcadia(object):
  340. def __init__(self, root):
  341. self.root = root
  342. class Build(object):
  343. def __init__(self, arcadia, build_type, toolchain_params, force_ignore_local_files=False):
  344. self.arcadia = arcadia
  345. self.params = self._load_json_from_base64(toolchain_params)
  346. self.build_type = build_type
  347. platform = self.params['platform']
  348. self.host = Platform.from_json(platform['host'])
  349. self.target = Platform.from_json(platform['target'])
  350. self.tc = self._get_toolchain_options()
  351. # TODO(somov): Удалить, когда перестанет использоваться.
  352. self.build_system = 'ymake'
  353. self.ignore_local_files = False
  354. dist_prefix = 'dist-'
  355. if self.build_type.startswith(dist_prefix):
  356. self.build_system = 'distbuild'
  357. self.build_type = self.build_type[len(dist_prefix):]
  358. if force_ignore_local_files:
  359. self.ignore_local_files = True
  360. if self.is_ide_build_type(self.build_type):
  361. self.ignore_local_files = True
  362. self.pic = not is_positive('FORCE_NO_PIC')
  363. @property
  364. def host_target(self):
  365. return self.host, self.target
  366. def print_build(self):
  367. self._print_build_settings()
  368. host_os = System(self.host)
  369. host_os.print_host_settings()
  370. target_os = System(self.target)
  371. target_os.print_target_settings()
  372. if self.pic:
  373. emit('PIC', 'yes')
  374. emit('COMPILER_ID', self.tc.type.upper())
  375. if self.is_valgrind:
  376. emit('WITH_VALGRIND', 'yes')
  377. toolchain_type, compiler_type, linker_type = Compilers[self.tc.type]
  378. toolchain = toolchain_type(self.tc, self)
  379. compiler = compiler_type(self.tc, self)
  380. linker = linker_type(self.tc, self)
  381. toolchain.print_toolchain()
  382. compiler.print_compiler()
  383. linker.print_linker()
  384. self._print_other_settings(compiler)
  385. def _print_build_settings(self):
  386. emit('BUILD_TYPE', self.build_type.upper())
  387. emit('BT_' + self.build_type.upper().replace('-', '_'), 'yes')
  388. if self.build_system == 'distbuild':
  389. emit('DISTBUILD', 'yes')
  390. elif self.build_system != 'ymake':
  391. raise ConfigureError()
  392. python_bin = preset('BUILD_PYTHON_BIN', '$(PYTHON)/python')
  393. emit('YMAKE_PYTHON', python_bin)
  394. emit('YMAKE_UNPICKLER', python_bin, '$ARCADIA_ROOT/build/plugins/_unpickler.py')
  395. @property
  396. def is_release(self):
  397. # TODO(somov): Проверить, бывают ли тут суффиксы на самом деле
  398. return self.build_type in ('release', 'relwithdebinfo', 'minsizerel', 'profile', 'gprof') or self.build_type.endswith('-release')
  399. @property
  400. def is_debug(self):
  401. return self.build_type in ('debug', 'debugnoasserts', 'fastdebug') or self.build_type.endswith('-debug')
  402. @property
  403. def is_fast_debug(self):
  404. return self.build_type == 'fastdebug'
  405. @property
  406. def is_size_optimized(self):
  407. return self.build_type == 'minsizerel'
  408. @property
  409. def is_coverage(self):
  410. return self.build_type == 'coverage'
  411. @property
  412. def is_sanitized(self):
  413. sanitizer = preset('SANITIZER_TYPE')
  414. return bool(sanitizer) and not is_negative_str(sanitizer)
  415. @property
  416. def with_ndebug(self):
  417. return self.build_type in ('release', 'minsizerel', 'valgrind-release', 'profile', 'gprof', 'debugnoasserts')
  418. @property
  419. def is_valgrind(self):
  420. return self.build_type == 'valgrind' or self.build_type == 'valgrind-release'
  421. @property
  422. def is_ide(self):
  423. return self.is_ide_build_type(self.build_type)
  424. @property
  425. def profiler_type(self):
  426. if self.build_type == 'profile':
  427. return Profiler.Generic
  428. elif self.build_type == 'gprof':
  429. return Profiler.GProf
  430. else:
  431. return None
  432. @staticmethod
  433. def is_ide_build_type(build_type):
  434. return build_type == 'nobuild'
  435. def _configure_runtime_versions(self):
  436. res = subprocess.check_output(['xcrun', 'simctl', 'list', '--json', 'runtimes'])
  437. raw_object = json.loads(res)
  438. raw_object = raw_object['runtimes']
  439. for runtime in raw_object:
  440. if runtime['isAvailable']:
  441. if "iOS" in runtime['identifier']:
  442. emit('DEFAULT_IOS_RUNTIME', '{}'.format(runtime['identifier']))
  443. def _get_toolchain_options(self):
  444. type_ = self.params['params']['type']
  445. if self.params['params'].get('local') and type_ == 'xcode':
  446. detector = CompilerDetector()
  447. detector.detect(self.params['params']['c_compiler'], self.params['params']['cxx_compiler'])
  448. emit('LOCAL_XCODE_TOOLS', 'yes')
  449. emit('XCODE', 'yes')
  450. emit('ACTOOL_PATH', self.params['params']['actool'])
  451. emit('IBTOOL_PATH', self.params['params']['ibtool'])
  452. self._configure_runtime_versions()
  453. elif type_ == 'system_cxx':
  454. detector = CompilerDetector()
  455. detector.detect(self.params['params'].get('c_compiler'), self.params['params'].get('cxx_compiler'))
  456. type_ = detector.type
  457. else:
  458. detector = None
  459. if type_ == 'msvc':
  460. return MSVCToolchainOptions(self, detector)
  461. else:
  462. return GnuToolchainOptions(self, detector)
  463. def _print_other_settings(self, compiler):
  464. host = self.host
  465. emit('USE_LOCAL_TOOLS', 'no' if self.ignore_local_files else 'yes')
  466. ragel = Ragel()
  467. ragel.configure_toolchain(self, compiler)
  468. ragel.print_variables()
  469. perl = Perl()
  470. perl.configure_local()
  471. perl.print_variables('LOCAL_')
  472. swiftc = SwiftCompiler(self)
  473. swiftc.configure()
  474. swiftc.print_compiler()
  475. if host.is_linux or host.is_macos or host.is_cygwin:
  476. if is_negative('USE_ARCADIA_PYTHON'):
  477. python = Python(self.tc)
  478. python.configure_posix()
  479. python.print_variables()
  480. cuda = Cuda(self)
  481. cuda.print_()
  482. CuDNN(cuda).print_()
  483. print_swig_config()
  484. if self.ignore_local_files or host.is_windows or is_positive('NO_SVN_DEPENDS'):
  485. emit_with_ignore_comment('SVN_DEPENDS')
  486. emit_with_ignore_comment('SVN_DEPENDS_CACHE__NO_UID__')
  487. else:
  488. def find_svn():
  489. for i in range(0, 3):
  490. for path in (['.svn', 'wc.db'], ['.svn', 'entries'], ['.git', 'logs', 'HEAD']):
  491. path_parts = [os.pardir] * i + path
  492. full_path = os.path.join(self.arcadia.root, *path_parts)
  493. # HACK(somov): No "normpath" here. ymake fails with the "source file name is outside the build tree" error
  494. # when .svn/wc.db found in "trunk" instead of "arcadia". But $ARCADIA_ROOT/../.svn/wc.db is ok.
  495. if os.path.exists(full_path):
  496. out_path = os.path.join('${ARCADIA_ROOT}', *path_parts)
  497. return '${input;hide:"%s"}' % out_path
  498. # Special processing for arc repository since .arc may be a symlink.
  499. dot_arc = os.path.realpath(os.path.join(self.arcadia.root, '.arc'))
  500. full_path = os.path.join(dot_arc, 'TREE')
  501. if os.path.exists(full_path):
  502. out_path = os.path.join('${ARCADIA_ROOT}', os.path.relpath(full_path, self.arcadia.root))
  503. return '${input;hide:"%s"}' % out_path
  504. return ''
  505. emit_with_ignore_comment('SVN_DEPENDS', find_svn())
  506. emit_with_ignore_comment('SVN_DEPENDS_CACHE__NO_UID__', '${hide;kv:"disable_cache"}')
  507. @staticmethod
  508. def _load_json_from_base64(base64str):
  509. """
  510. :rtype: dict[str, Any]
  511. """
  512. def un_unicode(o):
  513. if isinstance(o, six.text_type):
  514. return six.ensure_str(o)
  515. if isinstance(o, list):
  516. return [un_unicode(oo) for oo in o]
  517. if isinstance(o, dict):
  518. return {un_unicode(k): un_unicode(v) for k, v in six.iteritems(o)}
  519. return o
  520. return un_unicode(json.loads(base64.b64decode(base64str)))
  521. class YMake(object):
  522. def __init__(self, arcadia):
  523. self.arcadia = arcadia
  524. def print_presets(self):
  525. presets = opts().presets
  526. if presets and 'YMAKE_JAVA_MODULES' not in presets:
  527. if 'YA_IDE_IDEA' in presets or 'MAVEN_EXPORT' in presets:
  528. presets['YMAKE_JAVA_MODULES'] = 'no'
  529. else:
  530. presets['YMAKE_JAVA_MODULES'] = 'yes'
  531. if presets and 'YMAKE_JAVA_MODULES' in presets and presets['YMAKE_JAVA_MODULES'] == "yes":
  532. print('@import "${CONF_ROOT}/conf/java.ymake.conf"')
  533. else:
  534. print('@import "${CONF_ROOT}/conf/jbuild.ymake.conf"')
  535. if presets:
  536. print('# Variables set from command line by -D options')
  537. for key in sorted(presets):
  538. if key in ('MY_YMAKE_BIN', 'REAL_YMAKE_BIN'):
  539. emit_with_ignore_comment(key, opts().presets[key])
  540. elif key == 'YMAKE_JAVA_MODULES':
  541. continue
  542. else:
  543. emit(key, opts().presets[key])
  544. @staticmethod
  545. def _print_conf_content(path):
  546. with open(path, 'r') as fin:
  547. print(fin.read())
  548. def print_core_conf(self):
  549. emit('YMAKE_YNDEXER_IGNORE_BUILD_ROOT', 'yes')
  550. print('@import "${CONF_ROOT}/ymake.core.conf"')
  551. def print_settings(self):
  552. emit_with_ignore_comment('ARCADIA_ROOT', self.arcadia.root)
  553. @staticmethod
  554. def _find_conf(conf_file):
  555. script_dir = os.path.dirname(__file__)
  556. full_path = os.path.join(script_dir, conf_file)
  557. if os.path.exists(full_path):
  558. return full_path
  559. return None
  560. def _find_core_conf(self):
  561. return self._find_conf('ymake.core.conf')
  562. class System(object):
  563. def __init__(self, platform):
  564. """
  565. :type platform: Platform
  566. """
  567. self.platform = platform
  568. def print_windows_target_const(self):
  569. # TODO(somov): Remove this variables, use generic OS/arch variables in makelists.
  570. emit('WINDOWS', 'yes')
  571. emit('WIN32', 'yes')
  572. if self.platform.is_64_bit == 64:
  573. emit('WIN64', 'yes')
  574. def print_nix_target_const(self):
  575. emit('JAVA_INCLUDE', '-I{0}/include -I{0}/include/{1}'.format('/usr/lib/jvm/default-java', self.platform.os_compat))
  576. emit('UNIX', 'yes')
  577. emit('REALPRJNAME')
  578. emit('SONAME')
  579. @staticmethod
  580. def print_nix_host_const():
  581. emit('WRITE_COMMAND', '/bin/echo', '-e')
  582. print('''
  583. when ($USE_PYTHON) {
  584. C_DEFINES+= -DUSE_PYTHON
  585. }''')
  586. @staticmethod
  587. def print_linux_const():
  588. print('''
  589. when (($USEMPROF == "yes") || ($USE_MPROF == "yes")) {
  590. C_SYSTEM_LIBRARIES_INTERCEPT+=-ldmalloc
  591. }
  592. ''')
  593. def print_target_settings(self):
  594. emit('TARGET_PLATFORM', self.platform.os_compat)
  595. emit('HARDWARE_ARCH', '32' if self.platform.is_32_bit else '64')
  596. emit('HARDWARE_TYPE', self.platform.arch)
  597. for variable in self.platform.arch_variables:
  598. emit(variable, 'yes')
  599. for variable in self.platform.os_variables:
  600. emit(variable, 'yes')
  601. if self.platform.is_armv7:
  602. emit('ARM7_FLOAT_ABI', self.platform.armv7_float_abi)
  603. if self.platform.is_android:
  604. emit('ANDROID_API', str(self.platform.android_api))
  605. if self.platform.is_posix:
  606. self.print_nix_target_const()
  607. if self.platform.is_linux:
  608. self.print_linux_const()
  609. elif self.platform.is_windows:
  610. self.print_windows_target_const()
  611. def print_host_settings(self):
  612. emit('HOST_PLATFORM', self.platform.os_compat)
  613. if not self.platform.is_windows:
  614. self.print_nix_host_const()
  615. for variable in itertools.chain(self.platform.os_variables, self.platform.arch_variables):
  616. emit('HOST_{var}'.format(var=variable), 'yes')
  617. class CompilerDetector(object):
  618. def __init__(self):
  619. self.type = None
  620. self.c_compiler = None
  621. self.cxx_compiler = None
  622. self.version_list = None
  623. @staticmethod
  624. def preprocess_source(compiler, source):
  625. # noinspection PyBroadException
  626. try:
  627. fd, path = tempfile.mkstemp(suffix='.cpp')
  628. try:
  629. with os.fdopen(fd, 'wb') as output:
  630. output.write(source)
  631. stdout, code = get_stdout_and_code([compiler, '-E', path])
  632. finally:
  633. os.remove(path)
  634. return stdout, code
  635. except Exception as e:
  636. logger.debug('Preprocessing failed: %s', e)
  637. return None, None
  638. @staticmethod
  639. def get_compiler_vars(compiler, names):
  640. prefix = '____YA_VAR_'
  641. source = '\n'.join(['{prefix}{name}={name}\n'.format(prefix=prefix, name=n) for n in names])
  642. # Некоторые препроцессоры возвращают ненулевой код возврата. Поэтому его проверять нельзя.
  643. # Мы можем только удостовериться после разбора stdout, что в нём
  644. # присутствовала хотя бы одна подставленная переменная.
  645. # TODO(somov): Исследовать, можно ли проверять ограниченный набор кодов возврата.
  646. stdout, _ = CompilerDetector.preprocess_source(compiler, source)
  647. if stdout is None:
  648. return None
  649. vars_ = {}
  650. for line in stdout.split('\n'):
  651. parts = line.split('=', 1)
  652. if len(parts) == 2 and parts[0].startswith(prefix):
  653. name, value = parts[0][len(prefix):], parts[1]
  654. if value == name:
  655. continue # Preprocessor variable was not substituted
  656. vars_[name] = value
  657. return vars_
  658. def detect(self, c_compiler=None, cxx_compiler=None):
  659. c_compiler = c_compiler or os.environ.get('CC')
  660. cxx_compiler = cxx_compiler or os.environ.get('CXX') or c_compiler
  661. c_compiler = c_compiler or cxx_compiler
  662. logger.debug('e=%s', os.environ)
  663. if c_compiler is None:
  664. raise ConfigureError('Custom compiler was requested but not specified')
  665. c_compiler_path = which(c_compiler)
  666. clang_vars = ['__clang_major__', '__clang_minor__', '__clang_patchlevel__']
  667. gcc_vars = ['__GNUC__', '__GNUC_MINOR__', '__GNUC_PATCHLEVEL__']
  668. msvc_vars = ['_MSC_VER']
  669. apple_var = '__apple_build_version__'
  670. compiler_vars = self.get_compiler_vars(c_compiler_path, clang_vars + [apple_var] + gcc_vars + msvc_vars)
  671. if not compiler_vars:
  672. raise ConfigureError('Could not determine custom compiler version: {}'.format(c_compiler))
  673. def version(version_names):
  674. def iter_version():
  675. for name in version_names:
  676. yield int(compiler_vars[name])
  677. # noinspection PyBroadException
  678. try:
  679. return list(iter_version())
  680. except Exception:
  681. return None
  682. clang_version = version(clang_vars)
  683. apple_build = apple_var in compiler_vars
  684. # TODO(somov): Учитывать номера версий сборки Apple компилятора Clang.
  685. _ = apple_build
  686. gcc_version = version(gcc_vars)
  687. msvc_version = version(msvc_vars)
  688. if clang_version:
  689. logger.debug('Detected Clang version %s', clang_version)
  690. self.type = 'clang'
  691. elif gcc_version:
  692. logger.debug('Detected GCC version %s', gcc_version)
  693. # TODO(somov): Переименовать в gcc.
  694. self.type = 'gnu'
  695. elif msvc_version:
  696. logger.debug('Detected MSVC version %s', msvc_version)
  697. self.type = 'msvc'
  698. else:
  699. raise ConfigureError('Could not determine custom compiler type: {}'.format(c_compiler))
  700. self.version_list = clang_version or gcc_version or msvc_version
  701. self.c_compiler = c_compiler_path
  702. self.cxx_compiler = cxx_compiler and which(cxx_compiler) or c_compiler_path
  703. class ToolchainOptions(object):
  704. def __init__(self, build, detector):
  705. """
  706. :type build: Build
  707. """
  708. self.host = build.host
  709. self.target = build.target
  710. tc_json = build.params
  711. logger.debug('Toolchain host %s', self.host)
  712. logger.debug('Toolchain target %s', self.target)
  713. logger.debug('Toolchain json %s', DebugString(lambda: json.dumps(tc_json, indent=4, sort_keys=True)))
  714. self.params = tc_json['params']
  715. self._name = tc_json.get('name', 'theyknow')
  716. if detector:
  717. self.type = detector.type
  718. self.from_arcadia = False
  719. self.c_compiler = detector.c_compiler
  720. self.cxx_compiler = detector.cxx_compiler
  721. self.compiler_version_list = detector.version_list
  722. self.compiler_version = '.'.join(map(lambda part: six.ensure_str(str(part)), self.compiler_version_list))
  723. else:
  724. self.type = self.params['type']
  725. self.from_arcadia = True
  726. self.c_compiler = self.params['c_compiler']
  727. self.cxx_compiler = self.params['cxx_compiler']
  728. # TODO(somov): Требовать номер версии всегда.
  729. self.compiler_version = self.params.get('gcc_version') or self.params.get('version') or '0'
  730. self.compiler_version_list = list(map(int, self.compiler_version.split('.')))
  731. # TODO(somov): Посмотреть, можно ли спрятать это поле.
  732. self.name_marker = '$(%s)' % self.params.get('match_root', self._name.upper())
  733. self.arch_opt = self.params.get('arch_opt', [])
  734. self.triplet_opt = self.params.get('triplet_opt', {})
  735. self.target_opt = self.params.get('target_opt', [])
  736. # TODO(somov): Убрать чтение настройки из os.environ.
  737. self.werror_mode = preset('WERROR_MODE') or os.environ.get('WERROR_MODE') or self.params.get('werror_mode') or 'compiler_specific'
  738. # default C++ standard is set here, some older toolchains might need to redefine it in ya.conf.json
  739. self.cxx_std = self.params.get('cxx_std', 'c++20')
  740. self._env = tc_json.get('env', {})
  741. self.android_ndk_version = self.params.get('android_ndk_version', None)
  742. logger.debug('c_compiler=%s', self.c_compiler)
  743. logger.debug('cxx_compiler=%s', self.cxx_compiler)
  744. self.compiler_platform_projects = self.target.find_in_dict(self.params.get('platform'), [])
  745. def version_at_least(self, *args):
  746. return args <= tuple(self.compiler_version_list)
  747. def version_exactly(self, *args):
  748. if not args or len(args) > len(self.compiler_version_list):
  749. return False
  750. for l, r in zip(args, list(self.compiler_version_list)[:len(args)]):
  751. if l != r:
  752. return False
  753. return True
  754. @property
  755. def is_gcc(self):
  756. return self.type == 'gnu'
  757. @property
  758. def is_clang(self):
  759. return self.type in ('clang', 'xcode')
  760. @property
  761. def is_xcode(self):
  762. return self.type == 'xcode'
  763. @property
  764. def is_from_arcadia(self):
  765. return self.from_arcadia
  766. @property
  767. def is_system_cxx(self):
  768. return self._name == "system_cxx"
  769. def get_env(self, convert_list=None):
  770. convert_list = convert_list or (lambda x: x)
  771. r = {}
  772. for k, v in six.iteritems(self._env):
  773. if isinstance(v, str):
  774. r[k] = v
  775. elif isinstance(v, list):
  776. r[k] = convert_list(v)
  777. else:
  778. logger.debug('Unexpected values in environment: %s', self._env)
  779. raise ConfigureError('Internal error')
  780. return r
  781. class GnuToolchainOptions(ToolchainOptions):
  782. def __init__(self, build, detector):
  783. super(GnuToolchainOptions, self).__init__(build, detector)
  784. self.ar = self.params.get('ar')
  785. self.ar_plugin = self.params.get('ar_plugin')
  786. self.inplace_tools = self.params.get('inplace_tools', False)
  787. self.strip = self.params.get('strip')
  788. self.objcopy = self.params.get('objcopy')
  789. self.isystem = self.params.get('isystem')
  790. self.dwarf_tool = self.target.find_in_dict(self.params.get('dwarf_tool'))
  791. # TODO(somov): Унифицировать формат sys_lib
  792. self.sys_lib = self.params.get('sys_lib', {})
  793. if isinstance(self.sys_lib, dict):
  794. self.sys_lib = self.target.find_in_dict(self.sys_lib, [])
  795. self.os_sdk = preset('OS_SDK') or self._default_os_sdk()
  796. self.os_sdk_local = self.os_sdk == 'local'
  797. def _default_os_sdk(self):
  798. if self.target.is_linux:
  799. if self.target.is_armv8:
  800. return 'ubuntu-16'
  801. if self.target.is_armv7 and self.target.armv7_float_abi == 'hard':
  802. return 'ubuntu-16'
  803. if self.target.is_armv7 and self.target.armv7_float_abi == 'softfp':
  804. return 'ubuntu-18'
  805. if self.target.is_powerpc:
  806. return 'ubuntu-14'
  807. # Default OS SDK for Linux builds
  808. return 'ubuntu-14'
  809. class Toolchain(object):
  810. def __init__(self, tc, build):
  811. """
  812. :type tc: ToolchainOptions
  813. :type build: Build
  814. """
  815. self.tc = tc
  816. self.build = build
  817. self.platform_projects = self.tc.compiler_platform_projects
  818. def print_toolchain(self):
  819. if self.platform_projects:
  820. emit('COMPILER_PLATFORM', list(unique(self.platform_projects)))
  821. class Compiler(object):
  822. def __init__(self, tc, compiler_variable):
  823. self.compiler_variable = compiler_variable
  824. self.tc = tc
  825. def print_compiler(self):
  826. # CLANG and CLANG_VER variables
  827. emit(self.compiler_variable, 'yes')
  828. emit('{}_VER'.format(self.compiler_variable), self.tc.compiler_version)
  829. if self.tc.is_xcode:
  830. emit('XCODE', 'yes')
  831. class GnuToolchain(Toolchain):
  832. def __init__(self, tc, build):
  833. """
  834. :type tc: GnuToolchainOptions
  835. :type build: Build
  836. """
  837. def get_os_sdk(target):
  838. sdk_native_version = 10.11 if not preset('EXPERIMENTAL_MACOS_M1_SUPPORT') else '11.1'
  839. if target.is_macos:
  840. return '$MACOS_SDK_RESOURCE_GLOBAL/MacOSX{}.sdk'.format(sdk_native_version)
  841. elif target.is_yocto:
  842. return '$YOCTO_SDK_RESOURCE_GLOBAL'
  843. return '$OS_SDK_ROOT_RESOURCE_GLOBAL'
  844. super(GnuToolchain, self).__init__(tc, build)
  845. self.tc = tc
  846. host = build.host
  847. target = build.target
  848. self.c_flags_platform = list(tc.target_opt)
  849. self.default_os_sdk_root = get_os_sdk(target)
  850. self.env = self.tc.get_env()
  851. self.env_go = {}
  852. if self.tc.is_clang and not self.tc.is_system_cxx:
  853. self.env_go = {'PATH': ['{}/bin'.format(self.tc.name_marker)]}
  854. if self.tc.is_gcc:
  855. self.env_go = {'PATH': ['{}/gcc/bin'.format(self.tc.name_marker)]}
  856. if 'PATH' in self.env_go:
  857. if target.is_linux:
  858. self.env_go['PATH'].append('$OS_SDK_ROOT_RESOURCE_GLOBAL/usr/bin')
  859. elif target.is_macos:
  860. self.env_go['PATH'].extend([
  861. '$MACOS_SDK_RESOURCE_GLOBAL/usr/bin',
  862. '$CCTOOLS_ROOT_RESOURCE_GLOBAL/bin',
  863. '$GO_FAKE_XCRUN_RESOURCE_GLOBAL',
  864. ])
  865. self.swift_flags_platform = []
  866. self.swift_lib_path = None
  867. if self.tc.is_from_arcadia:
  868. for lib_path in build.host.library_path_variables:
  869. self.env.setdefault(lib_path, []).append('{}/lib'.format(self.tc.name_marker))
  870. macos_version_min = '10.12'
  871. macos_arm64_version_min = '11.0'
  872. ios_version_min = '11.0'
  873. # min ios simulator version for Metal App is 13.0
  874. # https://developer.apple.com/documentation/metal/supporting_simulator_in_a_metal_app
  875. # Mapkit (MAPSMOBI_BUILD_TARGET) uses Metal Framework
  876. if preset('MAPSMOBI_BUILD_TARGET') and target.is_iossim and target.is_armv8:
  877. macos_version_min = '10.14'
  878. ios_version_min = '13.0'
  879. # Mapkit uses SecTrustEvaluateWithError function and these are min versions for it
  880. elif preset('MAPSMOBI_BUILD_TARGET'):
  881. macos_version_min = '10.14'
  882. ios_version_min = '12.0'
  883. swift_target = select(default=None, selectors=[
  884. (target.is_iossim and target.is_x86_64, 'x86_64-apple-ios{}-simulator'.format(ios_version_min)),
  885. (target.is_iossim and target.is_x86, 'i386-apple-ios{}-simulator'.format(ios_version_min)),
  886. (target.is_iossim and target.is_armv8, 'arm64-apple-ios{}-simulator'.format(ios_version_min)),
  887. (not target.is_iossim and target.is_ios and target.is_armv8, 'arm64-apple-ios9'),
  888. (not target.is_iossim and target.is_ios and target.is_armv7, 'armv7-apple-ios9'),
  889. ])
  890. if swift_target:
  891. self.swift_flags_platform += ['-target', swift_target]
  892. if self.tc.is_from_arcadia:
  893. self.swift_lib_path = select(default=None, selectors=[
  894. (host.is_macos and target.is_iossim, '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/lib/swift/iphonesimulator'),
  895. (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'),
  896. ])
  897. if self.tc.is_clang:
  898. target_triple = self.tc.triplet_opt.get(target.arch, None)
  899. if not target_triple:
  900. target_triple = select(default=None, selectors=[
  901. (target.is_linux and target.is_x86_64, 'x86_64-linux-gnu'),
  902. (target.is_linux and target.is_armv8, 'aarch64-linux-gnu'),
  903. (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'hard', 'armv7-linux-gnueabihf'),
  904. (target.is_linux and target.is_armv7 and target.armv7_float_abi == 'softfp', 'armv7-linux-gnueabi'),
  905. (target.is_linux and target.is_powerpc, 'powerpc64le-linux-gnu'),
  906. (target.is_iossim and target.is_arm64, 'arm64-apple-ios{}-simulator'.format(ios_version_min)),
  907. (target.is_apple and target.is_x86, 'i386-apple-darwin14'),
  908. (target.is_apple and target.is_x86_64, 'x86_64-apple-darwin14'),
  909. (target.is_apple and target.is_macos_arm64, 'arm64-apple-macos11'),
  910. (target.is_apple and target.is_armv7, 'armv7-apple-darwin14'),
  911. (target.is_apple and target.is_armv8, 'arm64-apple-darwin14'),
  912. (target.is_yocto and target.is_armv7, 'arm-poky-linux-gnueabi'),
  913. (target.is_android and target.is_x86, 'i686-linux-android'),
  914. (target.is_android and target.is_x86_64, 'x86_64-linux-android'),
  915. (target.is_android and target.is_armv7, 'armv7a-linux-androideabi'),
  916. (target.is_android and target.is_armv8, 'aarch64-linux-android'),
  917. ])
  918. if target.is_android:
  919. # Android NDK allows specification of API level in target triple, e.g.:
  920. # armv7a-linux-androideabi16, aarch64-linux-android21
  921. target_triple += str(target.android_api)
  922. if target_triple:
  923. self.c_flags_platform.append('--target={}'.format(target_triple))
  924. if self.tc.isystem:
  925. for root in list(self.tc.isystem):
  926. self.c_flags_platform.extend(['-isystem', root])
  927. if target.is_android:
  928. self.c_flags_platform.extend(['-isystem', '{}/sources/cxx-stl/llvm-libc++abi/include'.format(self.tc.name_marker)])
  929. if target.is_cortex_a9:
  930. self.c_flags_platform.append('-mcpu=cortex-a9')
  931. if target.is_cortex_a35:
  932. self.c_flags_platform.append('-mcpu=cortex-a35')
  933. elif target.is_cortex_a53:
  934. self.c_flags_platform.append('-mcpu=cortex-a53')
  935. elif target.is_cortex_m33:
  936. self.c_flags_platform.append('-mcpu=cortex-m33 -mfpu=fpv5-sp-d16')
  937. elif target.is_armv7_neon:
  938. self.c_flags_platform.append('-mfpu=neon')
  939. if (target.is_armv7 or target.is_armv8m) and build.is_size_optimized:
  940. # Enable ARM Thumb2 variable-length instruction encoding
  941. # to reduce code size
  942. self.c_flags_platform.append('-mthumb')
  943. if target.is_arm or target.is_powerpc:
  944. # On linux, ARM and PPC default to unsigned char
  945. # However, Arcadia requires char to be signed
  946. self.c_flags_platform.append('-fsigned-char')
  947. if self.tc.is_clang or self.tc.is_gcc and self.tc.version_at_least(8, 2):
  948. target_flags = select(default=[], selectors=[
  949. (target.is_linux and target.is_power8le, ['-mcpu=power8', '-mtune=power8', '-maltivec']),
  950. (target.is_linux and target.is_power9le, ['-mcpu=power9', '-mtune=power9', '-maltivec']),
  951. (target.is_linux and target.is_armv8, ['-march=armv8a']),
  952. (target.is_macos_arm64, ['-mmacosx-version-min={}'.format(macos_arm64_version_min)]),
  953. (target.is_macos, ['-mmacosx-version-min={}'.format(macos_version_min)]),
  954. (target.is_ios and not target.is_iossim, ['-mios-version-min={}'.format(ios_version_min)]),
  955. (target.is_iossim, ['-mios-simulator-version-min={}'.format(ios_version_min)]),
  956. (target.is_android and target.is_armv7, ['-march=armv7-a', '-mfloat-abi=softfp']),
  957. (target.is_android and target.is_armv8, ['-march=armv8-a']),
  958. (target.is_yocto and target.is_armv7, ['-march=armv7-a', '-mfpu=neon', '-mfloat-abi=hard', '-mcpu=cortex-a9', '-O1'])
  959. ])
  960. if target_flags:
  961. self.c_flags_platform.extend(target_flags)
  962. if target.is_ios:
  963. self.c_flags_platform.append('-D__IOS__=1')
  964. if self.tc.is_from_arcadia or self.tc.is_system_cxx:
  965. if target.is_apple:
  966. if target.is_ios:
  967. self.setup_sdk(project='build/platform/ios_sdk', var='${IOS_SDK_ROOT_RESOURCE_GLOBAL}')
  968. self.platform_projects.append('build/platform/macos_system_stl')
  969. if target.is_macos:
  970. self.setup_sdk(project='build/platform/macos_sdk', var='${MACOS_SDK_RESOURCE_GLOBAL}')
  971. self.platform_projects.append('build/platform/macos_system_stl')
  972. if not self.tc.inplace_tools:
  973. self.setup_tools(project='build/platform/cctools', var='${CCTOOLS_ROOT_RESOURCE_GLOBAL}', bin='bin', ldlibs=None)
  974. if target.is_linux:
  975. if not tc.os_sdk_local:
  976. self.setup_sdk(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL')
  977. if target.is_x86_64:
  978. if host.is_linux and not self.tc.is_gcc:
  979. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/lib/x86_64-linux-gnu')
  980. elif host.is_macos:
  981. self.setup_tools(project='build/platform/binutils', var='$BINUTILS_ROOT_RESOURCE_GLOBAL', bin='x86_64-linux-gnu/bin', ldlibs=None)
  982. elif target.is_powerpc:
  983. 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')
  984. elif target.is_armv8:
  985. self.setup_tools(project='build/platform/linux_sdk', var='$OS_SDK_ROOT_RESOURCE_GLOBAL', bin='usr/bin', ldlibs='usr/lib/x86_64-linux-gnu')
  986. if target.is_yocto:
  987. self.setup_sdk(project='build/platform/yocto_sdk/yocto_sdk', var='${YOCTO_SDK_ROOT_RESOURCE_GLOBAL}')
  988. elif self.tc.params.get('local'):
  989. if target.is_apple:
  990. if not tc.os_sdk_local:
  991. if target.is_ios:
  992. self.setup_sdk(project='build/platform/ios_sdk', var='${IOS_SDK_ROOT_RESOURCE_GLOBAL}')
  993. self.platform_projects.append('build/platform/macos_system_stl')
  994. if target.is_macos:
  995. self.setup_sdk(project='build/platform/macos_sdk', var='${MACOS_SDK_RESOURCE_GLOBAL}')
  996. self.platform_projects.append('build/platform/macos_system_stl')
  997. else:
  998. if target.is_iossim:
  999. self.env.setdefault('SDKROOT', subprocess.check_output(['xcrun', '-sdk', 'iphonesimulator', '--show-sdk-path']).strip())
  1000. elif target.is_ios:
  1001. self.env.setdefault('SDKROOT', subprocess.check_output(['xcrun', '-sdk', 'iphoneos', '--show-sdk-path']).strip())
  1002. elif target.is_macos:
  1003. self.env.setdefault('SDKROOT', subprocess.check_output(['xcrun', '-sdk', 'macosx', '--show-sdk-path']).strip())
  1004. def setup_sdk(self, project, var):
  1005. self.platform_projects.append(project)
  1006. self.c_flags_platform.append('--sysroot={}'.format(var))
  1007. self.swift_flags_platform += ['-sdk', var]
  1008. # noinspection PyShadowingBuiltins
  1009. def setup_tools(self, project, var, bin, ldlibs):
  1010. self.platform_projects.append(project)
  1011. self.c_flags_platform.append('-B{}/{}'.format(var, bin))
  1012. if ldlibs:
  1013. for lib_path in self.build.host.library_path_variables:
  1014. self.env.setdefault(lib_path, []).append('{}/{}'.format(var, ldlibs))
  1015. def print_toolchain(self):
  1016. super(GnuToolchain, self).print_toolchain()
  1017. emit('TOOLCHAIN_ENV', format_env(self.env, list_separator=':'))
  1018. emit('_GO_TOOLCHAIN_ENV_PATH', format_env(self.env_go, list_separator=':'))
  1019. emit('C_FLAGS_PLATFORM', self.c_flags_platform)
  1020. emit('SWIFT_FLAGS_PLATFORM', self.swift_flags_platform)
  1021. emit('SWIFT_LD_FLAGS', '-L{}'.format(self.swift_lib_path) if self.swift_lib_path else '')
  1022. emit('PERL_SDK', preset('OS_SDK') or self.tc.os_sdk)
  1023. if preset('OS_SDK') is None:
  1024. emit('OS_SDK', self.tc.os_sdk)
  1025. emit('OS_SDK_ROOT', None if self.tc.os_sdk_local else self.default_os_sdk_root)
  1026. class GnuCompiler(Compiler):
  1027. gcc_fstack = ['-fstack-protector']
  1028. def __init__(self, tc, build):
  1029. """
  1030. :type tc: GnuToolchainOptions
  1031. :type build: Build
  1032. """
  1033. compiler_variable = 'CLANG' if tc.is_clang else 'GCC'
  1034. super(GnuCompiler, self).__init__(tc, compiler_variable)
  1035. self.build = build
  1036. self.host = self.build.host
  1037. self.target = self.build.target
  1038. self.tc = tc
  1039. self.c_foptions = [
  1040. # Enable C++ exceptions (and allow them to be throw through pure C code)
  1041. '-fexceptions',
  1042. # Enable standard-conforming behavior and generate duplicate symbol error in case of duplicated global constants.
  1043. # See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85678#c0
  1044. '-fno-common',
  1045. ]
  1046. if self.tc.is_clang and self.target.is_linux:
  1047. # Use .init_array instead of .ctors (default for old clang versions)
  1048. # See: https://maskray.me/blog/2021-11-07-init-ctors-init-array
  1049. self.c_foptions.append('-fuse-init-array')
  1050. if self.tc.is_clang:
  1051. self.c_foptions += [
  1052. # Set up output colorization
  1053. '-fcolor-diagnostics',
  1054. # Enable aligned allocation
  1055. '-faligned-allocation',
  1056. ]
  1057. elif self.tc.is_gcc:
  1058. self.c_foptions += [
  1059. # Set up output colorization
  1060. '-fdiagnostics-color=always',
  1061. # It looks like there is no way to enable aligned allocation in gcc
  1062. ]
  1063. self.c_warnings = [
  1064. # Enable default warnings subset
  1065. '-Wall',
  1066. '-Wextra',
  1067. ]
  1068. self.cxx_warnings = [
  1069. # Issue a warning if certain overload is hidden due to inheritance
  1070. '-Woverloaded-virtual',
  1071. ]
  1072. # Disable some warnings which will fail compilation at the time
  1073. self.c_warnings += [
  1074. '-Wno-parentheses'
  1075. ]
  1076. self.c_defines = ['-DFAKEID=$CPP_FAKEID']
  1077. if self.target.is_android:
  1078. self.c_defines.append('-DANDROID_FAKEID=$ANDROID_FAKEID')
  1079. self.c_defines.extend([
  1080. '-DARCADIA_ROOT=${ARCADIA_ROOT}',
  1081. '-DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
  1082. ])
  1083. self.c_defines.extend([
  1084. '-D_THREAD_SAFE', '-D_PTHREADS', '-D_REENTRANT', '-D_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES',
  1085. '-D_LARGEFILE_SOURCE', '-D__STDC_CONSTANT_MACROS', '-D__STDC_FORMAT_MACROS',
  1086. ])
  1087. if not self.target.is_android:
  1088. # There is no usable _FILE_OFFSET_BITS=64 support in Androids until API 21. And it's incomplete until at least API 24.
  1089. # https://android.googlesource.com/platform/bionic/+/master/docs/32-bit-abi.md
  1090. # Arcadia have API 16 for 32-bit Androids.
  1091. self.c_defines.append('-D_FILE_OFFSET_BITS=64')
  1092. if self.target.is_linux or self.target.is_android or self.target.is_cygwin:
  1093. self.c_defines.append('-D_GNU_SOURCE')
  1094. if self.tc.is_clang and self.target.is_linux and self.target.is_x86_64:
  1095. self.c_defines.append('-D_YNDX_LIBUNWIND_ENABLE_EXCEPTION_BACKTRACE')
  1096. if self.target.is_ios:
  1097. self.c_defines.extend(['-D_XOPEN_SOURCE', '-D_DARWIN_C_SOURCE'])
  1098. if preset('MAPSMOBI_BUILD_TARGET') and self.target.is_arm:
  1099. self.c_foptions.append('-fembed-bitcode')
  1100. self.extra_compile_opts = []
  1101. self.c_flags = ['$CL_DEBUG_INFO', '$CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__']
  1102. self.c_flags += self.tc.arch_opt + ['-pipe']
  1103. self.sfdl_flags = ['-E', '-C', '-x', 'c++']
  1104. if self.target.is_x86:
  1105. self.c_flags.append('-m32')
  1106. if self.target.is_x86_64:
  1107. self.c_flags.append('-m64')
  1108. self.debug_info_flags = ['-g']
  1109. if self.target.is_linux:
  1110. self.debug_info_flags.append('-ggnu-pubnames')
  1111. self.cross_suffix = '' if is_positive('FORCE_NO_PIC') else '.pic'
  1112. self.optimize = None
  1113. self.configure_build_type()
  1114. if self.tc.is_clang:
  1115. self.sfdl_flags.append('-Qunused-arguments')
  1116. self.c_warnings += [
  1117. '-Wno-implicit-const-int-float-conversion',
  1118. # For nvcc to accept the above.
  1119. '-Wno-unknown-warning-option',
  1120. ]
  1121. self.cxx_warnings += [
  1122. '-Wimport-preprocessor-directive-pedantic',
  1123. '-Wno-ambiguous-reversed-operator',
  1124. '-Wno-defaulted-function-deleted',
  1125. '-Wno-deprecated-anon-enum-enum-conversion',
  1126. '-Wno-deprecated-enum-enum-conversion',
  1127. '-Wno-deprecated-enum-float-conversion',
  1128. '-Wno-deprecated-volatile',
  1129. '-Wno-pessimizing-move',
  1130. '-Wno-return-std-move',
  1131. '-Wno-undefined-var-template',
  1132. ]
  1133. elif self.tc.is_gcc:
  1134. self.c_foptions.append('-fno-delete-null-pointer-checks')
  1135. self.c_foptions.append('-fabi-version=8')
  1136. # Split all functions and data into separate sections for DCE and ICF linker passes
  1137. # NOTE: iOS build uses -fembed-bitcode which conflicts with -ffunction-sections (only relevant for ELF targets)
  1138. if not self.target.is_ios:
  1139. self.c_foptions.extend(['-ffunction-sections', '-fdata-sections'])
  1140. def configure_build_type(self):
  1141. if self.build.is_valgrind:
  1142. self.c_defines.append('-DWITH_VALGRIND=1')
  1143. if self.build.is_debug:
  1144. self.c_foptions.append('$FSTACK')
  1145. if self.build.is_fast_debug:
  1146. self.c_flags.append('-Og')
  1147. if self.build.is_release:
  1148. self.c_flags.append('$OPTIMIZE')
  1149. if self.build.is_size_optimized:
  1150. # -Oz is clang's more size-aggressive version of -Os
  1151. # For ARM specifically, clang -Oz is on par with gcc -Os:
  1152. # https://github.com/android/ndk/issues/133#issuecomment-365763507
  1153. if self.tc.is_clang:
  1154. self.optimize = '-Oz'
  1155. else:
  1156. self.optimize = '-Os'
  1157. # Generate sections with address significance tables for ICF linker pass
  1158. if self.tc.is_clang:
  1159. self.c_foptions.extend(['-faddrsig'])
  1160. else:
  1161. self.optimize = '-O3'
  1162. if self.build.with_ndebug:
  1163. self.c_defines.append('-DNDEBUG')
  1164. else:
  1165. self.c_defines.append('-UNDEBUG')
  1166. if self.build.profiler_type in (Profiler.Generic, Profiler.GProf):
  1167. self.c_foptions.append('-fno-omit-frame-pointer')
  1168. if self.build.profiler_type == Profiler.GProf:
  1169. self.c_flags.append('-pg')
  1170. def print_compiler(self):
  1171. super(GnuCompiler, self).print_compiler()
  1172. emit('C_COMPILER_UNQUOTED', self.tc.c_compiler)
  1173. emit('C_COMPILER', '${quo:C_COMPILER_UNQUOTED}')
  1174. emit('OPTIMIZE', self.optimize)
  1175. emit('WERROR_MODE', self.tc.werror_mode)
  1176. emit('FSTACK', self.gcc_fstack)
  1177. append('C_DEFINES', self.c_defines)
  1178. emit('DUMP_DEPS')
  1179. emit('GCC_PREPROCESSOR_OPTS', '$DUMP_DEPS', '$C_DEFINES')
  1180. append('C_WARNING_OPTS', self.c_warnings)
  1181. append('CXX_WARNING_OPTS', self.cxx_warnings)
  1182. # PIE is only valid for executables, while PIC implies a shared library
  1183. # `-pie` with a shared library is either ignored or fails to link
  1184. emit_big('''
  1185. when ($PIC == "yes") {
  1186. CFLAGS+=-fPIC
  1187. LDFLAGS+=-fPIC
  1188. }
  1189. elsewhen ($PIE == "yes") {
  1190. CFLAGS+=-fPIE
  1191. LDFLAGS+=-fPIE -pie
  1192. }''')
  1193. append('CFLAGS', self.c_flags, '$DEBUG_INFO_FLAGS', self.c_foptions, '$C_WARNING_OPTS', '$GCC_PREPROCESSOR_OPTS', '$USER_CFLAGS', '$USER_CFLAGS_GLOBAL')
  1194. append('CXXFLAGS', '$CFLAGS', '-std=' + self.tc.cxx_std, '$CXX_WARNING_OPTS', '$USER_CXXFLAGS', '$USER_CXXFLAGS_GLOBAL')
  1195. append('CONLYFLAGS', '$USER_CONLYFLAGS', '$USER_CONLYFLAGS_GLOBAL')
  1196. emit('CXX_COMPILER_UNQUOTED', self.tc.cxx_compiler)
  1197. emit('CXX_COMPILER', '${quo:CXX_COMPILER_UNQUOTED}')
  1198. emit('NOGCCSTACKCHECK', 'yes')
  1199. emit('SFDL_FLAG', self.sfdl_flags, '-o', '$SFDL_TMP_OUT')
  1200. emit('WERROR_FLAG', '-Werror')
  1201. # TODO(somov): Убрать чтение настройки из os.environ
  1202. emit('USE_ARC_PROFILE', 'yes' if preset('USE_ARC_PROFILE') or os.environ.get('USE_ARC_PROFILE') else 'no')
  1203. emit('DEBUG_INFO_FLAGS', self.debug_info_flags)
  1204. emit_big('''
  1205. when ($NO_WSHADOW == "yes") {
  1206. C_WARNING_OPTS += -Wno-shadow
  1207. }''')
  1208. # Though -w is intended to switch off all the warnings,
  1209. # it does not switch at least -Wregister and -Wreserved-user-defined-literal under clang.
  1210. #
  1211. # Use -Wno-everything to force warning suppression.
  1212. emit_big('''
  1213. when ($NO_COMPILER_WARNINGS == "yes") {
  1214. C_WARNING_OPTS = -w
  1215. CXX_WARNING_OPTS = -Wno-everything
  1216. }''')
  1217. emit_big('''
  1218. when ($NO_OPTIMIZE == "yes") {
  1219. OPTIMIZE = -O0
  1220. }
  1221. when ($SAVE_TEMPS == "yes") {
  1222. CXXFLAGS += -save-temps
  1223. }
  1224. when ($NOGCCSTACKCHECK != "yes") {
  1225. FSTACK += -fstack-check
  1226. }''')
  1227. c_builtins = [
  1228. "-Wno-builtin-macro-redefined",
  1229. '-D__DATE__=\\""Sep 31 2019\\""',
  1230. '-D__TIME__=\\"00:00:00\\"',
  1231. ]
  1232. compiler_supports_macro_prefix_map = (
  1233. self.tc.is_clang and self.tc.version_at_least(10) or
  1234. self.tc.is_gcc and self.tc.version_at_least(8)
  1235. )
  1236. if compiler_supports_macro_prefix_map:
  1237. c_builtins += [
  1238. # XXX does not support non-normalized paths
  1239. "-fmacro-prefix-map=${ARCADIA_BUILD_ROOT}/=",
  1240. "-fmacro-prefix-map=${ARCADIA_ROOT}/=",
  1241. "-fmacro-prefix-map=$(TOOL_ROOT)/=",
  1242. ]
  1243. else:
  1244. c_builtins += [
  1245. # XXX this macro substitution breaks __FILE__ in included sources
  1246. '-D__FILE__=\\""${input;qe;rootrel:SRC}\\""',
  1247. ]
  1248. c_debug_map = [
  1249. # XXX does not support non-normalized paths
  1250. "-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
  1251. "-fdebug-prefix-map=${ARCADIA_ROOT}=/-S",
  1252. "-fdebug-prefix-map=$(TOOL_ROOT)=/-T",
  1253. ]
  1254. c_debug_map_cl = c_debug_map + [
  1255. "-Xclang", "-fdebug-compilation-dir", "-Xclang", "/tmp",
  1256. ]
  1257. c_debug_map_light = [
  1258. # XXX does not support non-normalized paths
  1259. "-fdebug-prefix-map=${ARCADIA_BUILD_ROOT}=/-B",
  1260. ]
  1261. c_debug_map_light_cl = c_debug_map_light + [
  1262. "-Xclang", "-fdebug-compilation-dir", "-Xclang", "/tmp",
  1263. ]
  1264. yasm_debug_map = [
  1265. # XXX does not support non-normalized paths
  1266. "--replace=${ARCADIA_BUILD_ROOT}=/-B",
  1267. "--replace=${ARCADIA_ROOT}=/-S",
  1268. "--replace=$(TOOL_ROOT)=/-T"
  1269. ]
  1270. emit_big('''
  1271. when ($FORCE_CONSISTENT_DEBUG == "yes") {{
  1272. when ($CLANG == "yes") {{
  1273. CL_DEBUG_INFO={c_debug_cl}
  1274. }}
  1275. otherwise {{
  1276. CL_DEBUG_INFO={c_debug}
  1277. }}
  1278. YASM_DEBUG_INFO={yasm_debug}
  1279. }}
  1280. elsewhen ($CONSISTENT_DEBUG == "yes") {{
  1281. when ($CLANG == "yes") {{
  1282. CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_cl}
  1283. }}
  1284. otherwise {{
  1285. CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug}
  1286. }}
  1287. YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug}
  1288. }}
  1289. elsewhen ($CONSISTENT_DEBUG_LIGHT == "yes") {{
  1290. when ($CLANG == "yes") {{
  1291. CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_light_cl}
  1292. }}
  1293. otherwise {{
  1294. CL_DEBUG_INFO_DISABLE_CACHE__NO_UID__={c_debug_light}
  1295. }}
  1296. YASM_DEBUG_INFO_DISABLE_CACHE__NO_UID__={yasm_debug_light}
  1297. }}
  1298. when ($FORCE_CONSISTENT_BUILD == "yes") {{
  1299. CL_MACRO_INFO={macro}
  1300. }}
  1301. elsewhen ($CONSISTENT_BUILD == "yes") {{
  1302. CL_MACRO_INFO_DISABLE_CACHE__NO_UID__={macro}
  1303. }}
  1304. '''.format(c_debug=' '.join(c_debug_map),
  1305. c_debug_cl=' '.join(c_debug_map_cl),
  1306. yasm_debug=' '.join(yasm_debug_map),
  1307. c_debug_light=' '.join(c_debug_map_light), # build_root substitution only
  1308. c_debug_light_cl=' '.join(c_debug_map_light_cl), # build_root substitution only
  1309. yasm_debug_light=yasm_debug_map[0], # build_root substitution only
  1310. macro=' '.join(c_builtins)))
  1311. # TODO(somov): Check whether this specific architecture is needed.
  1312. if self.target.arch == 'i386':
  1313. append('CFLAGS', '-march=pentiumpro')
  1314. append('CFLAGS', '-mtune=pentiumpro')
  1315. append('BC_CFLAGS', '$CFLAGS')
  1316. append('BC_CXXFLAGS', '$CXXFLAGS')
  1317. append('C_DEFINES', '-D__LONG_LONG_SUPPORTED')
  1318. emit('OBJ_CROSS_SUF', '$OBJ_SUF%s' % self.cross_suffix)
  1319. emit('OBJECT_SUF', '$OBJ_SUF%s.o' % self.cross_suffix)
  1320. emit('GCC_COMPILE_FLAGS', '$EXTRA_C_FLAGS -c -o $_COMPILE_OUTPUTS', '${pre=-I:_C__INCLUDE}')
  1321. if is_positive('DUMP_COMPILER_DEPS'):
  1322. emit('DUMP_DEPS', '-MD', '${output;hide;noauto;suf=${OBJ_SUF}.o.d:SRC}')
  1323. elif is_positive('DUMP_COMPILER_DEPS_FAST'):
  1324. emit('DUMP_DEPS', '-E', '-M', '-MF', '${output;noauto;suf=${OBJ_SUF}.o.d:SRC}')
  1325. compiler_time_trace_requested = is_positive('TIME_TRACE') or is_positive('COMPILER_TIME_TRACE')
  1326. compiler_supports_time_trace = self.tc.is_clang and self.tc.version_at_least(9)
  1327. if compiler_time_trace_requested and compiler_supports_time_trace:
  1328. compiler_time_trace_granularity = preset('TIME_TRACE_GRANULARITY', '500')
  1329. emit('COMPILER_TIME_TRACE_FLAGS', '-ftime-trace -ftime-trace-granularity=' + compiler_time_trace_granularity)
  1330. emit('COMPILER_TIME_TRACE_POSTPROCESS', '${YMAKE_PYTHON}', '${input:"build/scripts/find_time_trace.py"}', '$_COMPILE_OUTPUTS', '$_COMPILE_TIME_TRACE_OUTPUTS')
  1331. else:
  1332. emit('COMPILER_TIME_TRACE_FLAGS')
  1333. emit('COMPILER_TIME_TRACE_POSTPROCESS')
  1334. append('EXTRA_OUTPUT')
  1335. style = ['${hide;kv:"p CC"} ${hide;kv:"pc green"}']
  1336. cxx_args = [
  1337. '$CLANG_TIDY_ARGS',
  1338. '$YNDEXER_ARGS',
  1339. '$CXX_COMPILER',
  1340. '$C_FLAGS_PLATFORM',
  1341. '$GCC_COMPILE_FLAGS',
  1342. '$CXXFLAGS',
  1343. '$CL_MACRO_INFO',
  1344. '$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
  1345. '$COMPILER_TIME_TRACE_FLAGS',
  1346. '$EXTRA_OUTPUT',
  1347. '$SRCFLAGS',
  1348. '$_LANG_CFLAGS_VALUE',
  1349. '${input:SRC}',
  1350. '$TOOLCHAIN_ENV',
  1351. '$YNDEXER_OUTPUT',
  1352. '&& $COMPILER_TIME_TRACE_POSTPROCESS',
  1353. ] + style
  1354. c_args = [
  1355. '$CLANG_TIDY_ARGS',
  1356. '$YNDEXER_ARGS',
  1357. '$C_COMPILER',
  1358. '$C_FLAGS_PLATFORM',
  1359. '$GCC_COMPILE_FLAGS',
  1360. '$CFLAGS',
  1361. '$CL_MACRO_INFO',
  1362. '$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
  1363. '$CONLYFLAGS',
  1364. '$COMPILER_TIME_TRACE_FLAGS',
  1365. '$EXTRA_OUTPUT',
  1366. '$SRCFLAGS',
  1367. '${input:SRC}',
  1368. '$TOOLCHAIN_ENV',
  1369. '$YNDEXER_OUTPUT',
  1370. '&& $COMPILER_TIME_TRACE_POSTPROCESS',
  1371. ] + style
  1372. ignore_c_args_no_deps = [
  1373. '${input:SRC}',
  1374. '$SRCFLAGS',
  1375. '$CLANG_TIDY_ARGS',
  1376. '$YNDEXER_ARGS',
  1377. '$YNDEXER_OUTPUT',
  1378. '$COMPILER_TIME_TRACE_FLAGS',
  1379. '$EXTRA_OUTPUT',
  1380. '$CL_MACRO_INFO',
  1381. '$CL_MACRO_INFO_DISABLE_CACHE__NO_UID__',
  1382. '&& $COMPILER_TIME_TRACE_POSTPROCESS',
  1383. ]
  1384. c_args_nodeps = [c if c != '$GCC_COMPILE_FLAGS' else '$EXTRA_C_FLAGS -c -o ${OUTFILE} ${SRC} ${pre=-I:INC}' for c in c_args if c not in ignore_c_args_no_deps]
  1385. emit('_SRC_C_NODEPS_CMD', ' '.join(c_args_nodeps))
  1386. emit('_SRC_CPP_CMD', ' '.join(cxx_args))
  1387. emit('_SRC_C_CMD', ' '.join(c_args))
  1388. emit('_SRC_M_CMD', '$SRC_c($SRC $SRCFLAGS)')
  1389. emit('_SRC_MASM_CMD', '$_EMPTY_CMD')
  1390. # fuzzing configuration
  1391. if self.tc.is_clang:
  1392. if self.tc.version_at_least(12):
  1393. emit('LIBFUZZER_PATH', 'contrib/libs/libfuzzer12')
  1394. class SwiftCompiler(object):
  1395. def __init__(self, build):
  1396. self.host = build.host
  1397. self.compiler = None
  1398. def configure(self):
  1399. if self.host.is_macos:
  1400. self.compiler = '$SWIFT_XCODE_TOOLCHAIN_ROOT_RESOURCE_GLOBAL/usr/bin/swiftc'
  1401. def print_compiler(self):
  1402. emit('SWIFT_COMPILER', self.compiler or '')
  1403. class Linker(object):
  1404. BFD = 'bfd'
  1405. LLD = 'lld'
  1406. GOLD = 'gold'
  1407. def __init__(self, tc, build):
  1408. """
  1409. :type tc: ToolchainOptions
  1410. :type build: Build
  1411. """
  1412. self.tc = tc
  1413. self.build = build
  1414. self.type = self._get_default_linker_type()
  1415. def _get_default_linker_type(self):
  1416. if not self.tc.is_from_arcadia or is_positive('EXPORT_CMAKE'):
  1417. # External (e.g. system) toolchain: disable linker selection logic
  1418. return None
  1419. if self.build.target.is_android:
  1420. # Android toolchain is NDK, LLD works on all supported platforms
  1421. return Linker.LLD
  1422. elif self.build.target.is_linux:
  1423. return Linker.LLD
  1424. # There is no linker choice on Darwin (ld64) or Windows (link.exe)
  1425. return None
  1426. def print_linker(self):
  1427. self._print_linker_selector()
  1428. def _print_linker_selector(self):
  1429. # if self.type is None then _DEFAULT_LINKER is set to empty string value
  1430. emit('_DEFAULT_LINKER_ID', self.type)
  1431. class LD(Linker):
  1432. def __init__(self, tc, build):
  1433. """
  1434. :type tc: GnuToolchainOptions
  1435. :type build: Build
  1436. """
  1437. super(LD, self).__init__(tc, build)
  1438. self.build = build
  1439. self.host = self.build.host
  1440. self.target = self.build.target
  1441. self.tc = tc
  1442. target = self.target
  1443. self.ar = preset('AR') or self.tc.ar
  1444. self.ar_plugin = self.tc.ar_plugin
  1445. self.strip = self.tc.strip
  1446. self.objcopy = self.tc.objcopy
  1447. self.musl = Setting('MUSL', convert=to_bool)
  1448. if self.ar is None:
  1449. if target.is_apple:
  1450. # Use libtool. cctools ar does not understand -M needed for archive merging
  1451. self.ar = '${CCTOOLS_ROOT_RESOURCE_GLOBAL}/bin/libtool'
  1452. elif self.tc.is_from_arcadia:
  1453. if self.tc.is_clang:
  1454. self.ar = '{}/bin/llvm-ar'.format(self.tc.name_marker)
  1455. if self.tc.is_gcc:
  1456. self.ar = '{}/gcc/bin/gcc-ar'.format(self.tc.name_marker)
  1457. else:
  1458. self.ar = 'ar'
  1459. self.ar_type = 'GNU_AR'
  1460. self.llvm_ar_format = 'None'
  1461. if 'libtool' in self.ar:
  1462. self.ar_type = 'LIBTOOL'
  1463. elif 'llvm-ar' in self.ar:
  1464. self.ar_type = 'LLVM_AR'
  1465. if target.is_apple:
  1466. self.llvm_ar_format="darwin"
  1467. else:
  1468. self.llvm_ar_format="gnu"
  1469. self.ld_flags = []
  1470. # Save linker's stdout to an additional .txt output file
  1471. # e.g. LLD writes `--print-gc-sections` or `--print-icf-sections` to stdout
  1472. self.save_linker_output = False
  1473. # Enable section-level DCE (dead code elimination):
  1474. # remove whole unused code and data sections
  1475. # (needs `-ffunction-sections` and `-fdata-sections` to be useful)
  1476. #
  1477. # NOTE: CGO linker doesn't seem to support DCE, but shares common LDFLAGS
  1478. if target.is_macos:
  1479. self.ld_dce_flag = '-Wl,-dead_strip'
  1480. elif target.is_linux or target.is_android:
  1481. self.ld_dce_flag = '-Wl,--gc-sections'
  1482. if preset('LINKER_DCE_PRINT_SECTIONS'):
  1483. self.save_linker_output = True
  1484. self.ld_dce_flag += ' -Wl,--print-gc-sections'
  1485. else:
  1486. self.ld_dce_flag = ''
  1487. if self.type == Linker.LLD:
  1488. # Enable ICF (identical code folding pass) in safe mode
  1489. # https://research.google/pubs/pub36912/
  1490. self.ld_icf_flag = '-Wl,-icf=safe'
  1491. if preset('LINKER_ICF_PRINT_SECTIONS'):
  1492. self.save_linker_output = True
  1493. self.ld_icf_flag += ' -Wl,--print-icf-sections'
  1494. else:
  1495. self.ld_icf_flag = ''
  1496. if self.musl.value:
  1497. self.ld_flags.extend(['-Wl,--no-as-needed'])
  1498. elif target.is_linux:
  1499. self.ld_flags.extend(['-ldl', '-lrt', '-Wl,--no-as-needed'])
  1500. if self.tc.is_gcc:
  1501. self.ld_flags.extend(('-Wl,-Bstatic', '-latomic', '-Wl,-Bdynamic'))
  1502. elif target.is_android:
  1503. self.ld_flags.extend(['-ldl', '-Wl,--no-as-needed'])
  1504. elif target.is_macos:
  1505. self.ld_flags.append('-Wl,-no_deduplicate')
  1506. if not self.tc.is_clang:
  1507. self.ld_flags.append('-Wl,-no_compact_unwind')
  1508. self.thread_library = select([
  1509. (target.is_linux or target.is_macos, '-lpthread'),
  1510. ])
  1511. self.ld_export_dynamic_flag = None
  1512. self.start_group = None
  1513. self.end_group = None
  1514. self.whole_archive = None
  1515. self.no_whole_archive = None
  1516. self.ld_stripflag = None
  1517. self.use_stdlib = None
  1518. self.soname_option = None
  1519. self.dwarf_command = None
  1520. self.libresolv = '-lresolv' if target.is_linux or target.is_macos or target.is_android else None
  1521. if target.is_linux or target.is_android:
  1522. self.ld_export_dynamic_flag = '-rdynamic'
  1523. self.use_stdlib = '-nodefaultlibs'
  1524. if target.is_linux or target.is_android or target.is_cygwin or target.is_none:
  1525. self.start_group = '-Wl,--start-group'
  1526. self.end_group = '-Wl,--end-group'
  1527. self.whole_archive = '-Wl,--whole-archive'
  1528. self.no_whole_archive = '-Wl,--no-whole-archive'
  1529. self.ld_stripflag = '-s'
  1530. self.soname_option = '-soname'
  1531. if target.is_macos or target.is_ios:
  1532. self.use_stdlib = '-nodefaultlibs'
  1533. self.soname_option = '-install_name'
  1534. if not preset('NO_DEBUGINFO'):
  1535. self.dwarf_command = '$DWARF_TOOL $TARGET -o ${output;pre=$MODULE_PREFIX$REALPRJNAME.dSYM/Contents/Resources/DWARF/$MODULE_PREFIX:REALPRJNAME}'
  1536. if self.target.is_ios and preset('MAPSMOBI_BUILD_TARGET') and self.target.is_arm:
  1537. self.ld_flags.extend(('-fembed-bitcode', '-Wl,-bitcode_verify'))
  1538. if self.build.profiler_type == Profiler.GProf:
  1539. self.ld_flags.append('-pg')
  1540. # TODO(somov): Единое условие на coverage.
  1541. if self.build.is_coverage or is_positive('GCOV_COVERAGE') or is_positive('CLANG_COVERAGE') or self.build.is_sanitized:
  1542. self.use_stdlib = None
  1543. self.ld_sdk = select(default=None, selectors=[
  1544. (target.is_macos_arm64, '-Wl,-sdk_version,11.0'),
  1545. (target.is_macos, '-Wl,-sdk_version,10.15'),
  1546. (not target.is_iossim and target.is_ios, '-Wl,-sdk_version,13.1'),
  1547. (target.is_iossim, '-Wl,-sdk_version,14.5'),
  1548. ])
  1549. if self.ld_sdk:
  1550. self.ld_flags.append(self.ld_sdk)
  1551. self.sys_lib = self.tc.sys_lib
  1552. if target.is_android:
  1553. if target.is_armv7 and self.type != Linker.LLD:
  1554. self.sys_lib.append('-Wl,--fix-cortex-a8')
  1555. # NDK r23 onwards has stopped using libgcc:
  1556. # - https://github.com/android/ndk/wiki/Changelog-r23#changes
  1557. # - https://github.com/android/ndk/issues/1230
  1558. # LLVM's libunwind is now used instead of libgcc for all architectures rather than just 32-bit Arm.
  1559. # - https://github.com/android/ndk/issues/1231
  1560. # LLVM's libclang_rt.builtins is now used instead of libgcc.
  1561. if self.tc.android_ndk_version >= 23:
  1562. # Use toolchain defaults to link with libunwind/clang_rt.builtins
  1563. self.use_stdlib = '-nostdlib++'
  1564. else:
  1565. # Preserve old behaviour: specify runtime libs manually
  1566. self.use_stdlib = '-nodefaultlibs'
  1567. if target.is_armv7:
  1568. self.sys_lib.append('-lunwind')
  1569. self.sys_lib.append('-lgcc')
  1570. if self.tc.is_clang and not self.tc.version_at_least(4, 0) and target.is_linux_x86_64:
  1571. self.sys_lib.append('-L/usr/lib/x86_64-linux-gnu')
  1572. def print_linker(self):
  1573. super(LD, self).print_linker()
  1574. emit('AR_TOOL', self.ar)
  1575. emit('AR_TYPE', self.ar_type)
  1576. emit('STRIP_TOOL_VENDOR', self.strip)
  1577. emit('OBJCOPY_TOOL_VENDOR', self.objcopy)
  1578. append('LDFLAGS', '$USER_LDFLAGS', self.ld_flags)
  1579. append('LDFLAGS_GLOBAL', '')
  1580. emit('LD_STRIP_FLAG', self.ld_stripflag)
  1581. emit('STRIP_FLAG')
  1582. emit('LD_DCE_FLAG', self.ld_dce_flag)
  1583. emit('DCE_FLAG')
  1584. emit('LD_ICF_FLAG', self.ld_icf_flag)
  1585. emit('ICF_FLAG')
  1586. emit('C_LIBRARY_PATH')
  1587. emit('C_SYSTEM_LIBRARIES_INTERCEPT')
  1588. if self.musl.value:
  1589. emit('C_SYSTEM_LIBRARIES', '-nostdlib')
  1590. else:
  1591. emit('C_SYSTEM_LIBRARIES', self.use_stdlib, self.thread_library, self.sys_lib, '-lc')
  1592. emit('START_WHOLE_ARCHIVE_VALUE', self.whole_archive)
  1593. emit('END_WHOLE_ARCHIVE_VALUE', self.no_whole_archive)
  1594. if self.ld_sdk:
  1595. emit('LD_SDK_VERSION', self.ld_sdk)
  1596. dwarf_tool = self.tc.dwarf_tool
  1597. if dwarf_tool is None and self.tc.is_clang and (self.target.is_macos or self.target.is_ios):
  1598. dsymutil = '{}/bin/{}dsymutil'.format(self.tc.name_marker, '' if self.tc.version_at_least(7) else 'llvm-')
  1599. dwarf_tool = '${YMAKE_PYTHON} ${input:"build/scripts/run_llvm_dsymutil.py"} ' + dsymutil
  1600. if self.tc.version_at_least(5, 0):
  1601. dwarf_tool += ' -flat'
  1602. if dwarf_tool is not None:
  1603. emit('DWARF_TOOL', dwarf_tool)
  1604. emit('OBJADDE')
  1605. emit('LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG', self.ld_export_dynamic_flag)
  1606. emit_big('''
  1607. NO_EXPORT_DYNAMIC_SYMBOLS=
  1608. EXPORTS_VALUE=$LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG
  1609. when ($EXPORTS_FILE) {
  1610. EXPORTS_VALUE=$LD_EXPORT_ALL_DYNAMIC_SYMBOLS_FLAG -Wl,--version-script=${input:EXPORTS_FILE}
  1611. }
  1612. when ($NO_EXPORT_DYNAMIC_SYMBOLS == "yes") {
  1613. EXPORTS_VALUE=
  1614. }''')
  1615. emit('LINKER_SCRIPT_VALUE', '${ext=.ld;pre=-T:SRCS_GLOBAL}')
  1616. linker_time_trace_requested = is_positive('TIME_TRACE') or is_positive('LINKER_TIME_TRACE')
  1617. linker_supports_time_trace = self.type == Linker.LLD # XXX: Should really check the linker version if we had one
  1618. if linker_time_trace_requested and linker_supports_time_trace:
  1619. linker_time_trace_granularity = preset('TIME_TRACE_GRANULARITY', '500')
  1620. emit('LINKER_TIME_TRACE_FLAG', ' '.join([
  1621. '-Wl,--time-trace',
  1622. '-Wl,--time-trace-granularity=' + linker_time_trace_granularity,
  1623. '-Wl,--time-trace-file=${output;rootrel;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.time_trace.json:REALPRJNAME}',
  1624. ]))
  1625. else:
  1626. emit('LINKER_TIME_TRACE_FLAG')
  1627. exe_flags = [
  1628. '$C_FLAGS_PLATFORM', '$BEFORE_PEERS', self.start_group, '${rootrel:PEERS}', self.end_group, '$AFTER_PEERS',
  1629. '$EXPORTS_VALUE $LINKER_SCRIPT_VALUE $LDFLAGS $LDFLAGS_GLOBAL $OBJADDE $OBJADDE_LIB',
  1630. '$C_LIBRARY_PATH $C_SYSTEM_LIBRARIES_INTERCEPT $C_SYSTEM_LIBRARIES $STRIP_FLAG $DCE_FLAG $ICF_FLAG $LINKER_TIME_TRACE_FLAG']
  1631. arch_flag = '--arch={arch}'.format(arch=self.target.os_compat)
  1632. soname_flag = '-Wl,{option},${{_SONAME}}'.format(option=self.soname_option)
  1633. shared_flag = '-shared'
  1634. exec_shared_flag = '-pie -fPIE -Wl,--unresolved-symbols=ignore-all -rdynamic' if self.target.is_linux else ''
  1635. if self.whole_archive:
  1636. srcs_globals = self.whole_archive + ' ${rootrel;ext=.a:SRCS_GLOBAL} ' + self.no_whole_archive \
  1637. + ' ${rootrel;ext=.o:SRCS_GLOBAL} ${rootrel;ext=.supp:SRCS_GLOBAL}'
  1638. else:
  1639. srcs_globals = '--start-wa ${rootrel;ext=.a:SRCS_GLOBAL} --end-wa ${rootrel;ext=.o:SRCS_GLOBAL} ${rootrel;ext=.supp:SRCS_GLOBAL}'
  1640. ld_env_style = '${cwd:ARCADIA_BUILD_ROOT} $TOOLCHAIN_ENV ${kv;hide:"p LD"} ${kv;hide:"pc light-blue"} ${kv;hide:"show_out"}'
  1641. # Program
  1642. emit(
  1643. "GENERATE_MF_CMD",
  1644. '$YMAKE_PYTHON', '${input:"build/scripts/generate_mf.py"}', '${input;hide:"build/scripts/process_command_files.py"}',
  1645. '--build-root $ARCADIA_BUILD_ROOT --module-name $REALPRJNAME -o ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.mf:REALPRJNAME}',
  1646. '-t $MODULE_TYPE --ya-start-command-file -Ya,lics $LICENSE_NAMES -Ya,peers ${rootrel:PEERS} -Ya,credits ${input:CREDITS_TEXTS_FILE} $CREDITS_FLAGS --ya-end-command-file',
  1647. )
  1648. if is_positive("TIDY"):
  1649. emit(
  1650. 'REAL_LINK_EXE',
  1651. '$YMAKE_PYTHON ${input:"build/scripts/clang_tidy_arch.py"}',
  1652. '--build-root $ARCADIA_BUILD_ROOT',
  1653. '--source-root $ARCADIA_ROOT',
  1654. '--output-file',
  1655. '$TARGET',
  1656. '$AUTO_INPUT',
  1657. ld_env_style
  1658. )
  1659. else:
  1660. emit('LINK_SCRIPT_EXE_FLAGS')
  1661. emit('REAL_LINK_EXE_CMDLINE',
  1662. '$YMAKE_PYTHON ${input:"build/scripts/link_exe.py"}',
  1663. '--source-root $ARCADIA_ROOT',
  1664. '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
  1665. '${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS}',
  1666. '${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}',
  1667. arch_flag,
  1668. '$LINK_SCRIPT_EXE_FLAGS',
  1669. '$CXX_COMPILER',
  1670. srcs_globals,
  1671. '$VCS_C_OBJ $AUTO_INPUT -o $TARGET',
  1672. exe_flags,
  1673. ld_env_style,
  1674. )
  1675. emit('REAL_LINK_EXE', '$REAL_LINK_EXE_IMPL($_WHOLE_ARCHIVE_PEERS_VALUE)')
  1676. # Executable Shared Library
  1677. emit('REAL_LINK_EXEC_DYN_LIB_CMDLINE',
  1678. '$YMAKE_PYTHON ${input:"build/scripts/link_dyn_lib.py"}',
  1679. '--target $TARGET',
  1680. '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
  1681. '${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS}',
  1682. '${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}',
  1683. arch_flag,
  1684. '$LINK_DYN_LIB_FLAGS',
  1685. '$CXX_COMPILER',
  1686. srcs_globals,
  1687. '$VCS_C_OBJ $AUTO_INPUT -o $TARGET',
  1688. exec_shared_flag,
  1689. soname_flag,
  1690. exe_flags,
  1691. ld_env_style,
  1692. )
  1693. emit('REAL_LINK_EXEC_DYN_LIB', '$REAL_LINK_EXEC_DYN_LIB_IMPL($_WHOLE_ARCHIVE_PEERS_VALUE)')
  1694. # Shared Library
  1695. emit('LINK_DYN_LIB_FLAGS')
  1696. emit('REAL_LINK_DYN_LIB_CMDLINE',
  1697. '$YMAKE_PYTHON ${input:"build/scripts/link_dyn_lib.py"}',
  1698. '--target $TARGET',
  1699. '--linker-output ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX$MODULE_VERSION.linker.txt:REALPRJNAME}' if self.save_linker_output else '',
  1700. '${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS}',
  1701. '${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}',
  1702. arch_flag,
  1703. '$LINK_DYN_LIB_FLAGS',
  1704. '$CXX_COMPILER',
  1705. srcs_globals,
  1706. '$VCS_C_OBJ $AUTO_INPUT -o $TARGET',
  1707. shared_flag,
  1708. soname_flag,
  1709. exe_flags,
  1710. ld_env_style)
  1711. emit('REAL_LINK_DYN_LIB', '$REAL_LINK_DYN_LIB_IMPL($_WHOLE_ARCHIVE_PEERS_VALUE)')
  1712. if self.dwarf_command is None or self.target.is_ios:
  1713. emit('DWARF_COMMAND')
  1714. else:
  1715. emit('DWARF_COMMAND', self.dwarf_command, ld_env_style)
  1716. if is_positive("TIDY"):
  1717. emit('LINK_EXE', '$REAL_LINK_EXE')
  1718. else:
  1719. emit('LINK_EXE', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_EXE && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND && $PACK_IOS_CMD')
  1720. if is_positive("TIDY"):
  1721. emit('LINK_DYN_LIB', "$REAL_LINK_EXE")
  1722. else:
  1723. emit('LINK_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
  1724. emit('LINK_EXEC_DYN_LIB', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_EXEC_DYN_LIB && $DWARF_COMMAND && $LINK_ADDITIONAL_SECTIONS_COMMAND')
  1725. emit('SWIG_DLL_JAR_CMD', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_SWIG_DLL_JAR_CMD && $DWARF_COMMAND')
  1726. tail_link_lib = '$AUTO_INPUT ${kv;hide:"p AR"} $TOOLCHAIN_ENV ${kv;hide:"pc light-red"} ${kv;hide:"show_out"}'
  1727. if is_positive("TIDY"):
  1728. archiver = '$YMAKE_PYTHON ${input:"build/scripts/clang_tidy_arch.py"} --source-root $ARCADIA_ROOT --build-root $ARCADIA_BUILD_ROOT --output-file'
  1729. emit('LINK_LIB', archiver, "$TARGET", tail_link_lib)
  1730. else:
  1731. archiver = '$YMAKE_PYTHON ${input:"build/scripts/link_lib.py"} ${quo:AR_TOOL} $AR_TYPE %s $ARCADIA_BUILD_ROOT %s' % (self.llvm_ar_format, self.ar_plugin or 'None')
  1732. # Static Library
  1733. emit('LINK_LIB', '$GENERATE_MF &&', archiver, '$TARGET', tail_link_lib)
  1734. emit('GLOBAL_LINK_LIB', archiver, '$GLOBAL_TARGET', tail_link_lib)
  1735. # "Fat Object" : pre-linked global objects and static library with all dependencies
  1736. def emit_link_fat_obj(cmd_name, need_wa_option, *extended_flags):
  1737. prefix = ['$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP &&',
  1738. '$YMAKE_PYTHON ${input:"build/scripts/link_fat_obj.py"} --build-root $ARCADIA_BUILD_ROOT']
  1739. globals_libs = srcs_globals if need_wa_option else '${rootrel;ext=.a:SRCS_GLOBAL} ${rootrel;ext=.o:SRCS_GLOBAL}'
  1740. suffix = [arch_flag,
  1741. '-Ya,input $AUTO_INPUT $VCS_C_OBJ -Ya,global_srcs', globals_libs, '-Ya,peers $PEERS',
  1742. '-Ya,linker $CXX_COMPILER $LDFLAGS_GLOBAL $C_FLAGS_PLATFORM', self.ld_sdk, '-Ya,archiver', archiver,
  1743. '$TOOLCHAIN_ENV ${kv;hide:"p LD"} ${kv;hide:"pc light-blue"} ${kv;hide:"show_out"}']
  1744. emit(cmd_name, *(prefix + list(extended_flags) + suffix))
  1745. # TODO(somov): Проверить, не нужны ли здесь все остальные флаги компоновки (LDFLAGS и т. д.).
  1746. emit_link_fat_obj('LINK_FAT_OBJECT', True, '--obj=$TARGET', '--lib=${output:REALPRJNAME.a}')
  1747. emit_link_fat_obj('LINK_RECURSIVE_LIBRARY', False, '--lib=$TARGET', '--with-own-obj', '--with-global-srcs')
  1748. emit_link_fat_obj('LINK_FAT_OBJECT_LIBRARY', False, '--lib=$TARGET', '$FAT_OBJECT_ARGS', '$FAT_OBJECT_OUTS')
  1749. emit('LIBRT', '-lrt')
  1750. emit('MD5LIB', '-lcrypt')
  1751. emit('LIBRESOLV', self.libresolv)
  1752. emit('PROFFLAG', '-pg')
  1753. class MSVCToolchainOptions(ToolchainOptions):
  1754. def __init__(self, build, detector):
  1755. super(MSVCToolchainOptions, self).__init__(build, detector)
  1756. # C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428
  1757. self.vc_root = None
  1758. # C:\Program Files (x86)\Windows Kits\10\Include\10.0.14393.0
  1759. self.kit_includes = None
  1760. # C:\Program Files (x86)\Windows Kits\10\Lib\10.0.14393.0
  1761. self.kit_libs = None
  1762. self.under_wine = 'wine' in self.params
  1763. self.system_msvc = 'system_msvc' in self.params
  1764. self.ide_msvs = 'ide_msvs' in self.params
  1765. self.use_clang = self.params.get('use_clang', False)
  1766. self.use_arcadia_toolchain = self.params.get('use_arcadia_toolchain', False)
  1767. self.sdk_version = None
  1768. if build.host.is_windows:
  1769. self.under_wine = False
  1770. if self.ide_msvs:
  1771. bindir = '$(VC_ExecutablePath_x64_x64)\\'
  1772. self.c_compiler = bindir + 'cl.exe'
  1773. self.cxx_compiler = self.c_compiler
  1774. self.link = bindir + 'link.exe'
  1775. self.lib = bindir + 'lib.exe'
  1776. self.masm_compiler = bindir + 'ml64.exe'
  1777. self.vc_root = None
  1778. sdk_dir = '$(WindowsSdkDir)'
  1779. self.sdk_version = '$(WindowsTargetPlatformVersion)'
  1780. self.kit_includes = os.path.join(sdk_dir, 'Include', self.sdk_version)
  1781. self.kit_libs = os.path.join(sdk_dir, 'Lib', self.sdk_version)
  1782. elif detector:
  1783. self.masm_compiler = which('ml64.exe')
  1784. self.link = which('link.exe')
  1785. self.lib = which('lib.exe')
  1786. sdk_dir = os.environ.get('WindowsSdkDir')
  1787. self.sdk_version = os.environ.get('WindowsSDKVersion').replace('\\', '')
  1788. vc_install_dir = os.environ.get('VCToolsInstallDir')
  1789. # fix for cxx_std detection problem introduced in r7740071 when running in native VS toolkit commandline:
  1790. # in that case ya make gets 'system_cxx' configuration name and cxx_std is obviously missing in that config
  1791. # so default 'c++20' is substituted and we need to hotfix it here
  1792. self.cxx_std = 'c++latest'
  1793. if any([x is None for x in (sdk_dir, self.sdk_version, vc_install_dir)]):
  1794. raise ConfigureError('No %WindowsSdkDir%, %WindowsSDKVersion% or %VCINSTALLDIR% present. Please, run vcvars64.bat to setup preferred environment.')
  1795. self.vc_root = os.path.normpath(vc_install_dir)
  1796. self.kit_includes = os.path.normpath(os.path.join(sdk_dir, 'Include', self.sdk_version))
  1797. self.kit_libs = os.path.normpath(os.path.join(sdk_dir, 'Lib', self.sdk_version))
  1798. # TODO(somov): Определять автоматически self.version в этом случае
  1799. else:
  1800. if self.version_at_least(2019):
  1801. self.sdk_version = '10.0.18362.0'
  1802. sdk_dir = '$(WINDOWS_KITS-sbr:1939557911)'
  1803. if is_positive('MSVC20'): # XXX: temporary flag, remove after DTCC-123 is completed
  1804. self.cxx_std = 'c++latest'
  1805. else:
  1806. self.sdk_version = '10.0.16299.0'
  1807. sdk_dir = '$(WINDOWS_KITS-sbr:1379398385)'
  1808. self.vc_root = self.name_marker if not self.use_clang else '$MSVC_FOR_CLANG_RESOURCE_GLOBAL'
  1809. self.kit_includes = os.path.join(sdk_dir, 'Include', self.sdk_version)
  1810. self.kit_libs = os.path.join(sdk_dir, 'Lib', self.sdk_version)
  1811. bindir = os.path.join(self.vc_root, 'bin', 'Hostx64')
  1812. tools_name = select(selectors=[
  1813. (build.target.is_x86, 'x86'),
  1814. (build.target.is_x86_64, 'x64'),
  1815. (build.target.is_armv7, 'arm'),
  1816. ])
  1817. asm_name = select(selectors=[
  1818. (build.target.is_x86, 'ml.exe'),
  1819. (build.target.is_x86_64, 'ml64.exe'),
  1820. (build.target.is_armv7, 'armasm.exe'),
  1821. ])
  1822. def prefix(_type, _path):
  1823. if not self.under_wine:
  1824. return _path
  1825. return '{wine} {type} $WINE_ENV ${{ARCADIA_ROOT}} ${{ARCADIA_BUILD_ROOT}} {path}'.format(
  1826. wine='${YMAKE_PYTHON} ${input:\"build/scripts/run_msvc_wine.py\"} $(WINE_TOOL-sbr:1093314933)/bin/wine64 -v140 ' +
  1827. '${input;hide:\"build/scripts/process_command_files.py\"} ${input;hide:\"build/scripts/process_whole_archive_option.py\"}',
  1828. type=_type,
  1829. path=_path
  1830. )
  1831. self.masm_compiler = prefix('masm', os.path.join(bindir, tools_name, asm_name))
  1832. self.link = prefix('link', os.path.join(bindir, tools_name, 'link.exe'))
  1833. self.lib = prefix('lib', os.path.join(bindir, tools_name, 'lib.exe'))
  1834. class MSVC(object):
  1835. # noinspection PyPep8Naming
  1836. class WindowsVersion(object):
  1837. """
  1838. Predefined values for _WIN32_WINNT macro.
  1839. This macro specifies minimal Windows version required by the binary being build.
  1840. A complete list of the values supported by the Windows SDK can be found at
  1841. https://docs.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt
  1842. """
  1843. Windows7 = '0x0601'
  1844. Windows8 = '0x0602'
  1845. def __init__(self, tc, build):
  1846. """
  1847. :type tc: MSVCToolchainOptions
  1848. :type build: Build
  1849. """
  1850. if not isinstance(tc, MSVCToolchainOptions):
  1851. raise TypeError('Got {} ({}) instead of an MSVCToolchainOptions'.format(tc, type(tc)))
  1852. self.build = build
  1853. self.tc = tc
  1854. class MSVCToolchain(MSVC, Toolchain):
  1855. def __init__(self, tc, build):
  1856. """
  1857. :type tc: MSVCToolchainOptions
  1858. :param build: Build
  1859. """
  1860. Toolchain.__init__(self, tc, build)
  1861. MSVC.__init__(self, tc, build)
  1862. if self.tc.from_arcadia and not self.tc.ide_msvs:
  1863. self.platform_projects.append('build/platform/msvc')
  1864. if tc.under_wine:
  1865. self.platform_projects.append('build/platform/wine')
  1866. def print_toolchain(self):
  1867. super(MSVCToolchain, self).print_toolchain()
  1868. emit('TOOLCHAIN_ENV', format_env(self.tc.get_env(), list_separator=';'))
  1869. if self.tc.sdk_version:
  1870. emit('WINDOWS_KITS_VERSION', self.tc.sdk_version)
  1871. # TODO(somov): Заглушка для тех мест, где C_FLAGS_PLATFORM используется
  1872. # для любых платформ. Нужно унифицировать с GnuToolchain.
  1873. emit('C_FLAGS_PLATFORM')
  1874. if self.tc.under_wine:
  1875. emit('WINE_ENV', format_env({'WINEPREFIX_SUFFIX': '4.0'}))
  1876. class MSVCCompiler(MSVC, Compiler):
  1877. def __init__(self, tc, build):
  1878. Compiler.__init__(self, tc, 'MSVC')
  1879. MSVC.__init__(self, tc, build)
  1880. def print_compiler(self):
  1881. super(MSVCCompiler, self).print_compiler()
  1882. target = self.build.target
  1883. warns_enabled = [
  1884. 4018, # 'expression' : signed/unsigned mismatch
  1885. 4265, # 'class' : class has virtual functions, but destructor is not virtual
  1886. 4296, # 'operator' : expression is always false
  1887. 4431, # missing type specifier - int assumed
  1888. ]
  1889. warns_as_error = [
  1890. 4013, # 'function' undefined; assuming extern returning int
  1891. ]
  1892. warns_disabled = [
  1893. 4127, # conditional expression is constant
  1894. 4200, # nonstandard extension used : zero-sized array in struct/union
  1895. 4201, # nonstandard extension used : nameless struct/union
  1896. 4351, # elements of array will be default initialized
  1897. 4355, # 'this' : used in base member initializer list
  1898. 4503, # decorated name length exceeded, name was truncated
  1899. 4510, # default constructor could not be generated
  1900. 4511, # copy constructor could not be generated
  1901. 4512, # assignment operator could not be generated
  1902. 4554, # check operator precedence for possible error; use parentheses to clarify precedence
  1903. 4610, # 'object' can never be instantiated - user defined constructor required
  1904. 4706, # assignment within conditional expression
  1905. 4800, # forcing value to bool 'true' or 'false' (performance warning)
  1906. 4996, # The POSIX name for this item is deprecated
  1907. 4714, # function marked as __forceinline not inlined
  1908. 4197, # 'TAtomic' : top-level volatile in cast is ignored
  1909. 4245, # 'initializing' : conversion from 'int' to 'ui32', signed/unsigned mismatch
  1910. 4324, # 'ystd::function<void (uint8_t *)>': structure was padded due to alignment specifier
  1911. 5033, # 'register' is no longer a supported storage class
  1912. ]
  1913. defines = [
  1914. '/DARCADIA_ROOT=${ARCADIA_ROOT}',
  1915. '/DARCADIA_BUILD_ROOT=${ARCADIA_BUILD_ROOT}',
  1916. '/DFAKEID=$CPP_FAKEID',
  1917. '/DWIN32',
  1918. '/D_WIN32',
  1919. '/D_WINDOWS',
  1920. # Define _CRT_*_NO_WARNINGS macros to prevent ucrt from issuing a warning whenever
  1921. # a POSIX-style function is used instead of the alternative Microsoft suggests as a secure / standard replacement
  1922. # (e. g. `strncpy()` instead of `strncpy_s()`, `access()` instead of `_access()`)
  1923. # For details see:
  1924. # https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt
  1925. '/D_CRT_SECURE_NO_WARNINGS',
  1926. '/D_CRT_NONSTDC_NO_WARNINGS',
  1927. # Math constants (such as M_PI, M_E, M_SQRT2) are not defined in standard C / C++
  1928. # In order to get them defined by Windows ucrt library,
  1929. # you must first define _USE_MATH_DEFINES before #including <cmath> or math.h>.
  1930. # (NB: glibc defines these macros whenever _XOPEN_SOURCE is defined)
  1931. '/D_USE_MATH_DEFINES',
  1932. '/D__STDC_CONSTANT_MACROS',
  1933. '/D__STDC_FORMAT_MACROS',
  1934. '/D_USING_V110_SDK71_',
  1935. '/D_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES',
  1936. # Below defines are covered at
  1937. # https://docs.microsoft.com/en-us/windows/win32/winprog/using-the-windows-headers#faster-builds-with-smaller-header-files
  1938. # Exclude APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets (while including <windows.h>)
  1939. '/DWIN32_LEAN_AND_MEAN',
  1940. # Define NOMINMAX to avoid min() and max() macros definition (while including <windows.h>)
  1941. '/DNOMINMAX',
  1942. ]
  1943. cxx_defines = [
  1944. # Use builtin offsetof implementation
  1945. # instead of a crutcy macro defined in ucrt/stddef.h.
  1946. # The latter can not be used in constexpr statements.
  1947. '/D_CRT_USE_BUILTIN_OFFSETOF',
  1948. ]
  1949. if target.is_x86_64:
  1950. defines.extend(('/D_WIN64', '/DWIN64'))
  1951. if target.is_armv7:
  1952. defines.extend(('/D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE', '/D__arm__'))
  1953. winapi_unicode = False
  1954. emit_big('''
  1955. MSVC_INLINE_OPTIMIZED=yes
  1956. when ($MSVC_INLINE_OPTIMIZED == "yes") {
  1957. MSVC_INLINE_FLAG=/Zc:inline
  1958. }
  1959. when ($MSVC_INLINE_OPTIMIZED == "no") {
  1960. MSVC_INLINE_FLAG=/Zc:inline-
  1961. }''')
  1962. flags = [
  1963. '/nologo', '/Zm500', '/GR', '/bigobj', '/FC', '/EHs', '/errorReport:prompt', '$MSVC_INLINE_FLAG', '/utf-8',
  1964. # enable standard conforming mode
  1965. '/permissive-'
  1966. ]
  1967. flags += self.tc.arch_opt
  1968. c_warnings = ['/we{}'.format(code) for code in warns_as_error]
  1969. c_warnings += ['/w1{}'.format(code) for code in warns_enabled]
  1970. c_warnings += ['/wd{}'.format(code) for code in warns_disabled]
  1971. cxx_warnings = []
  1972. flags_debug = ['/Ob0', '/Od', '/D_DEBUG']
  1973. flags_release = ['/Ox', '/Ob2', '/Oi', '/DNDEBUG']
  1974. flags_c_only = []
  1975. cxx_flags = [
  1976. # Provide proper __cplusplus value
  1977. # https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
  1978. "/Zc:__cplusplus"
  1979. ]
  1980. if self.tc.use_clang:
  1981. flags += [
  1982. # Allow <windows.h> to be included via <Windows.h> in case-sensitive file-systems.
  1983. '-fcase-insensitive-paths',
  1984. # At the time clang-cl identifies itself as MSVC 19.11:
  1985. # (actual value can be found in clang/lib/Driver/ToolChains/MSVC.cpp, the syntax would be like
  1986. # ```
  1987. # MSVT = VersionTuple(19, 11);
  1988. # ```
  1989. #
  1990. # We override this value to match current value of the actual MSVC being used.
  1991. '-fms-compatibility-version=19.21',
  1992. ]
  1993. if target.is_x86:
  1994. flags.append('-m32')
  1995. elif target.is_x86_64:
  1996. flags.append('-m64')
  1997. c_warnings.extend((
  1998. '-Wno-format',
  1999. '-Wno-parentheses',
  2000. '-Wno-unknown-warning-option',
  2001. ))
  2002. cxx_warnings += [
  2003. '-Wimport-preprocessor-directive-pedantic',
  2004. '-Woverloaded-virtual',
  2005. '-Wno-ambiguous-reversed-operator',
  2006. '-Wno-defaulted-function-deleted',
  2007. '-Wno-deprecated-anon-enum-enum-conversion',
  2008. '-Wno-deprecated-enum-enum-conversion',
  2009. '-Wno-deprecated-enum-float-conversion',
  2010. '-Wno-deprecated-volatile',
  2011. '-Wno-undefined-var-template',
  2012. ]
  2013. if self.tc.ide_msvs:
  2014. cxx_warnings += [
  2015. '-Wno-unused-command-line-argument',
  2016. ]
  2017. if target.is_armv7:
  2018. masm_io = '-o ${output;suf=${OBJECT_SUF}:SRC} ${input;msvs_source:SRC}'
  2019. else:
  2020. masm_io = '/nologo /c /Fo${output;suf=${OBJECT_SUF}:SRC} ${input;msvs_source:SRC}'
  2021. emit('OBJ_CROSS_SUF', '$OBJ_SUF')
  2022. emit('OBJECT_SUF', '$OBJ_SUF.obj')
  2023. win_version_min = self.WindowsVersion.Windows7
  2024. defines.append('/D_WIN32_WINNT={0}'.format(win_version_min))
  2025. if winapi_unicode:
  2026. defines += ['/DUNICODE', '/D_UNICODE']
  2027. else:
  2028. defines += ['/D_MBCS']
  2029. # https://msdn.microsoft.com/en-us/library/abx4dbyh.aspx
  2030. if is_positive('DLL_RUNTIME'): # XXX
  2031. flags_debug += ['/MDd']
  2032. flags_release += ['/MD']
  2033. else:
  2034. flags_debug += ['/MTd']
  2035. flags_release += ['/MT']
  2036. vc_include = os.path.join(self.tc.vc_root, 'include') if not self.tc.ide_msvs else "$(VC_VC_IncludePath.Split(';')[0].Replace('\\','/'))"
  2037. if not self.tc.ide_msvs:
  2038. def include_flag(path):
  2039. return '{flag}"{path}"'.format(path=path, flag='/I ' if not self.tc.use_clang else '-imsvc')
  2040. for name in ('shared', 'ucrt', 'um', 'winrt'):
  2041. flags.append(include_flag(os.path.join(self.tc.kit_includes, name)))
  2042. flags.append(include_flag(vc_include))
  2043. flags_msvs_only = []
  2044. if self.tc.ide_msvs:
  2045. if not self.tc.use_clang:
  2046. flags_msvs_only += ['/FD', '/MP']
  2047. debug_info_flags = '/Zi /FS'
  2048. else:
  2049. debug_info_flags = '/Z7'
  2050. if self.tc.use_clang:
  2051. emit('CLANG_CL', 'yes')
  2052. if self.tc.ide_msvs:
  2053. emit('IDE_MSVS', 'yes')
  2054. if self.tc.use_arcadia_toolchain:
  2055. emit('USE_ARCADIA_TOOLCHAIN', 'yes')
  2056. emit('CXX_COMPILER', self.tc.cxx_compiler)
  2057. emit('C_COMPILER', self.tc.c_compiler)
  2058. emit('MASM_COMPILER', self.tc.masm_compiler)
  2059. append('C_DEFINES', defines)
  2060. emit('CFLAGS_DEBUG', flags_debug)
  2061. emit('CFLAGS_RELEASE', flags_release)
  2062. emit('MASMFLAGS', '')
  2063. emit('DEBUG_INFO_FLAGS', debug_info_flags)
  2064. append('C_WARNING_OPTS', c_warnings)
  2065. append('CXX_WARNING_OPTS', cxx_warnings)
  2066. if self.build.is_release:
  2067. emit('CFLAGS_PER_TYPE', '$CFLAGS_RELEASE')
  2068. if self.build.is_debug:
  2069. emit('CFLAGS_PER_TYPE', '$CFLAGS_DEBUG')
  2070. if self.build.is_ide:
  2071. emit('CFLAGS_PER_TYPE', '@[debug|$CFLAGS_DEBUG]@[release|$CFLAGS_RELEASE]')
  2072. append('CFLAGS', flags, flags_msvs_only, '$CFLAGS_PER_TYPE', '$DEBUG_INFO_FLAGS', '$C_WARNING_OPTS', '$C_DEFINES', '$USER_CFLAGS', '$USER_CFLAGS_GLOBAL')
  2073. append('CXXFLAGS', '$CFLAGS', '/std:' + self.tc.cxx_std, cxx_flags, cxx_defines, '$CXX_WARNING_OPTS', '$USER_CXXFLAGS', '$USER_CXXFLAGS_GLOBAL')
  2074. append('CONLYFLAGS', flags_c_only, '$USER_CONLYFLAGS', '$USER_CONLYFLAGS_GLOBAL')
  2075. append('BC_CFLAGS', '$CFLAGS')
  2076. append('BC_CXXFLAGS', '$BC_CFLAGS', '$CXXFLAGS')
  2077. ucrt_include = os.path.join(self.tc.kit_includes, 'ucrt') if not self.tc.ide_msvs else "$(UniversalCRT_IncludePath.Split(';')[0].Replace('\\','/'))"
  2078. # 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.
  2079. if not self.tc.use_clang:
  2080. append('CFLAGS', '/DY_UCRT_INCLUDE="%s"' % ucrt_include)
  2081. append('CFLAGS', '/DY_MSVC_INCLUDE="%s"' % vc_include)
  2082. emit_big('''
  2083. when ($NO_WSHADOW == "yes") {
  2084. C_WARNING_OPTS += /wd4456 /wd4457
  2085. }''')
  2086. if self.tc.use_clang:
  2087. # Though /w is intended to switch off all the warnings,
  2088. # it does not switch at least -Wregister and -Wreserved-user-defined-literal under clang-cl.
  2089. #
  2090. # Use -Wno-everything to force warning suppression.
  2091. emit_big('''
  2092. when ($NO_COMPILER_WARNINGS == "yes") {
  2093. C_WARNING_OPTS = /w
  2094. CXX_WARNING_OPTS = -Wno-everything
  2095. }''')
  2096. else:
  2097. emit_big('''
  2098. when ($NO_COMPILER_WARNINGS == "yes") {
  2099. C_WARNING_OPTS = /w
  2100. CXX_WARNING_OPTS =
  2101. }''')
  2102. emit_big('''
  2103. when ($NO_OPTIMIZE == "yes") {
  2104. OPTIMIZE = /Od
  2105. }''')
  2106. emit('SFDL_FLAG', ['/E', '/C', '/P', '/TP', '/Fi$SFDL_TMP_OUT'])
  2107. emit('WERROR_FLAG', '/WX')
  2108. emit('WERROR_MODE', self.tc.werror_mode)
  2109. if not self.tc.under_wine:
  2110. emit('CL_WRAPPER', '${FIX_MSVC_OUTPUT}', 'cl')
  2111. emit('ML_WRAPPER', '${FIX_MSVC_OUTPUT}', 'ml')
  2112. else:
  2113. emit('CL_WRAPPER')
  2114. emit('ML_WRAPPER')
  2115. emit('_SRC_C_NODEPS_CMD',
  2116. '${TOOLCHAIN_ENV} ${CL_WRAPPER} ${C_COMPILER} /c /Fo${OUTFILE} ${SRC} ${EXTRA_C_FLAGS} ${pre=/I :INC} '
  2117. '${CFLAGS} ${hide;kv:"soe"} ${hide;kv:"p CC"} ${hide;kv:"pc yellow"}'
  2118. )
  2119. emit('_SRC_CPP_CMD',
  2120. '${TOOLCHAIN_ENV} ${CL_WRAPPER} ${CXX_COMPILER} /c /Fo$_COMPILE_OUTPUTS ${input;msvs_source:SRC} '
  2121. '${EXTRA_C_FLAGS} ${pre=/I :_C__INCLUDE} ${CXXFLAGS} ${SRCFLAGS} ${_LANG_CFLAGS_VALUE} '
  2122. '${hide;kv:"soe"} ${hide;kv:"p CC"} ${hide;kv:"pc yellow"}'
  2123. )
  2124. emit('_SRC_C_CMD',
  2125. '${TOOLCHAIN_ENV} ${CL_WRAPPER} ${C_COMPILER} /c /Fo$_COMPILE_OUTPUTS ${input;msvs_source:SRC} '
  2126. '${EXTRA_C_FLAGS} ${pre=/I :_C__INCLUDE} ${CFLAGS} ${CONLYFLAGS} ${SRCFLAGS} '
  2127. '${hide;kv:"soe"} ${hide;kv:"p CC"} ${hide;kv:"pc yellow"}'
  2128. )
  2129. emit('_SRC_M_CMD', '$_EMPTY_CMD')
  2130. emit('_SRC_MASM_CMD',
  2131. '${cwd:ARCADIA_BUILD_ROOT} ${TOOLCHAIN_ENV} ${ML_WRAPPER} ${MASM_COMPILER} ${MASMFLAGS} ${SRCFLAGS} ' +
  2132. masm_io + '${kv;hide:"p AS"} ${kv;hide:"pc yellow"}'
  2133. )
  2134. class MSVCLinker(MSVC, Linker):
  2135. def __init__(self, tc, build):
  2136. MSVC.__init__(self, tc, build)
  2137. Linker.__init__(self, tc, build)
  2138. def print_linker(self):
  2139. super(MSVCLinker, self).print_linker()
  2140. target = self.build.target
  2141. linker = self.tc.link
  2142. linker_lib = self.tc.lib
  2143. arch = select(no_default=True, selectors=(
  2144. (target.is_x86, 'x86'),
  2145. (target.is_x86_64, 'x64'),
  2146. (target.is_armv7, 'arm'),
  2147. ))
  2148. libpaths = []
  2149. if not self.tc.ide_msvs:
  2150. if self.tc.kit_libs:
  2151. libpaths.extend([os.path.join(self.tc.kit_libs, name, arch) for name in ('um', 'ucrt')])
  2152. libpaths.append(os.path.join(self.tc.vc_root, 'lib', arch))
  2153. ignored_errors = [
  2154. 4221
  2155. ]
  2156. flag_machine = '/MACHINE:{}'.format(arch.upper())
  2157. flags_ignore = ['/IGNORE:{}'.format(code) for code in ignored_errors]
  2158. flags_common = ['/NOLOGO', '/ERRORREPORT:PROMPT', '/SUBSYSTEM:CONSOLE', '/TLBID:1', '$MSVC_DYNAMICBASE', '/NXCOMPAT']
  2159. flags_common += flags_ignore
  2160. flags_common += [flag_machine]
  2161. flags_debug_only = []
  2162. flags_release_only = []
  2163. if self.tc.ide_msvs:
  2164. flags_common += ['/INCREMENTAL']
  2165. else:
  2166. flags_common += ['/INCREMENTAL:NO']
  2167. if self.tc.use_clang:
  2168. flags_debug_only.append('/STACK:4194304')
  2169. if is_negative_str(preset('NO_DEBUGINFO', 'no')):
  2170. if self.tc.ide_msvs:
  2171. flags_debug_only.append('/DEBUG:FASTLINK' if not self.tc.use_clang else '/DEBUG')
  2172. flags_release_only.append('/DEBUG')
  2173. else:
  2174. # No FASTLINK for ya make, because resulting PDB would require .obj files (build_root's) to persist
  2175. flags_common.append('/DEBUG')
  2176. if not self.tc.ide_msvs:
  2177. flags_common += ['/LIBPATH:"{}"'.format(path) for path in libpaths]
  2178. link_flags_debug = flags_common + flags_debug_only
  2179. link_flags_release = flags_common + flags_release_only
  2180. link_flags_lib = flags_ignore + [flag_machine]
  2181. stdlibs = [
  2182. 'advapi32.lib',
  2183. 'comdlg32.lib',
  2184. 'crypt32.lib',
  2185. 'dnsapi.lib',
  2186. 'gdi32.lib',
  2187. 'iphlpapi.lib',
  2188. 'kernel32.lib',
  2189. 'mswsock.lib',
  2190. 'ole32.lib',
  2191. 'oleaut32.lib',
  2192. 'psapi.lib',
  2193. 'rpcrt4.lib',
  2194. 'secur32.lib',
  2195. 'shell32.lib',
  2196. 'shlwapi.lib',
  2197. 'user32.lib',
  2198. 'userenv.lib',
  2199. 'uuid.lib',
  2200. 'version.lib',
  2201. 'winmm.lib',
  2202. 'winspool.lib',
  2203. 'ws2_32.lib',
  2204. ]
  2205. emit('LINK_LIB_CMD', linker_lib)
  2206. emit('LINK_EXE_CMD', linker)
  2207. emit('LINK_LIB_FLAGS', link_flags_lib)
  2208. emit('LINK_EXE_FLAGS_RELEASE', link_flags_release)
  2209. emit('LINK_EXE_FLAGS_DEBUG', link_flags_debug)
  2210. emit('LINK_STDLIBS', stdlibs)
  2211. emit('LDFLAGS_GLOBAL', '')
  2212. emit('LDFLAGS', '')
  2213. emit('OBJADDE', '')
  2214. if self.build.is_release:
  2215. emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_RELEASE')
  2216. if self.build.is_debug:
  2217. emit('LINK_EXE_FLAGS_PER_TYPE', '$LINK_EXE_FLAGS_DEBUG')
  2218. if self.build.is_ide and self.tc.ide_msvs:
  2219. emit('LINK_EXE_FLAGS_PER_TYPE', '@[debug|$LINK_EXE_FLAGS_DEBUG]@[release|$LINK_EXE_FLAGS_RELEASE]')
  2220. emit('LINK_EXE_FLAGS', '$LINK_EXE_FLAGS_PER_TYPE')
  2221. emit('LINK_IMPLIB_VALUE')
  2222. emit('LINK_IMPLIB', '/IMPLIB:${output;noext;rootrel;pre=$MODULE_PREFIX:REALPRJNAME.lib}')
  2223. if is_negative_str(preset('NO_DEBUGINFO', 'no')):
  2224. emit('LINK_EXTRA_OUTPUT', '/PDB:${output;noext;rootrel;pre=$MODULE_PREFIX:REALPRJNAME.pdb}')
  2225. else:
  2226. emit('LINK_EXTRA_OUTPUT')
  2227. if not self.tc.under_wine:
  2228. emit('LIB_WRAPPER', '${FIX_MSVC_OUTPUT}', 'lib')
  2229. emit('LINK_WRAPPER', '${FIX_MSVC_OUTPUT}', 'link')
  2230. else:
  2231. emit('LIB_WRAPPER')
  2232. emit('LINK_WRAPPER')
  2233. emit('LINK_WRAPPER_DYNLIB', '${YMAKE_PYTHON}', '${input:"build/scripts/link_dyn_lib.py"}', '--arch', 'WINDOWS', '--target', '$TARGET')
  2234. emit_big('''
  2235. EXPORTS_VALUE=
  2236. when ($EXPORTS_FILE) {
  2237. LINK_IMPLIB_VALUE=$LINK_IMPLIB
  2238. EXPORTS_VALUE=/DEF:${input:EXPORTS_FILE}
  2239. }''')
  2240. emit("GENERATE_MF_CMD", '$YMAKE_PYTHON ${input:"build/scripts/generate_mf.py"}', '${input;hide:"build/scripts/process_command_files.py"}',
  2241. '--build-root $ARCADIA_BUILD_ROOT --module-name $REALPRJNAME -o ${output;pre=$MODULE_PREFIX;suf=$MODULE_SUFFIX.mf:REALPRJNAME}',
  2242. '-t $MODULE_TYPE --ya-start-command-file -Ya,lics $LICENSE_NAMES -Ya,peers ${rootrel:PEERS} -Ya,credits ${input:CREDITS_TEXTS_FILE} $CREDITS_FLAGS --ya-end-command-file',
  2243. )
  2244. # we split srcs_global into two groups: libs and objs
  2245. # # each group can be in its own command file
  2246. # first group need /WHOLEARCHIVE: prefix which will be added in fix_msvc_output.py or run_msvc_wine.py
  2247. # the tail of link commands will be added in the third command file
  2248. srcs_globals = '--start-wa --ya-start-command-file ${qe;rootrel;ext=.lib:SRCS_GLOBAL} --ya-end-command-file --end-wa \
  2249. --ya-start-command-file ${qe;rootrel;ext=.obj:SRCS_GLOBAL} --ya-end-command-file'
  2250. emit('REAL_LINK_DYN_LIB_CMDLINE', '${TOOLCHAIN_ENV} ${cwd:ARCADIA_BUILD_ROOT} ${LINK_WRAPPER} ${LINK_WRAPPER_DYNLIB} ${LINK_EXE_CMD} \
  2251. ${LINK_IMPLIB_VALUE} /DLL /OUT:${qe;rootrel:TARGET} ${LINK_EXTRA_OUTPUT} ${EXPORTS_VALUE} \
  2252. ${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS} \
  2253. ${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}',
  2254. srcs_globals, '--ya-start-command-file ${VCS_C_OBJ_RR} ${qe;rootrel:AUTO_INPUT} ${qe;rootrel;ext=.lib:PEERS} ${qe;rootrel;ext=.dll;noext;suf=.lib:PEERS} \
  2255. $LINK_EXE_FLAGS $LINK_STDLIBS $LDFLAGS $LDFLAGS_GLOBAL $OBJADDE --ya-end-command-file')
  2256. emit('REAL_LINK_DYN_LIB', '$REAL_LINK_DYN_LIB_IMPL($_WHOLE_ARCHIVE_PEERS_VALUE)')
  2257. emit('SWIG_DLL_JAR_CMD', '$GENERATE_MF && $GENERATE_VCS_C_INFO_NODEP && $REAL_SWIG_DLL_JAR_CMD')
  2258. head_link_lib = '${TOOLCHAIN_ENV} ${cwd:ARCADIA_BUILD_ROOT} ${LIB_WRAPPER} ${LINK_LIB_CMD}'
  2259. tail_link_lib = '--ya-start-command-file ${qe;rootrel:AUTO_INPUT} $LINK_LIB_FLAGS --ya-end-command-file \
  2260. ${hide;kv:"soe"} ${hide;kv:"p AR"} ${hide;kv:"pc light-red"}'
  2261. emit('LINK_LIB', '${GENERATE_MF} &&', head_link_lib, '/OUT:${qe;rootrel:TARGET}', tail_link_lib)
  2262. emit('GLOBAL_LINK_LIB', head_link_lib, '/OUT:${qe;rootrel:GLOBAL_TARGET}', tail_link_lib)
  2263. emit('LINK_EXE_CMDLINE', '${GENERATE_MF} && $GENERATE_VCS_C_INFO_NODEP && ${TOOLCHAIN_ENV} ${cwd:ARCADIA_BUILD_ROOT} ${LINK_WRAPPER}',
  2264. '${LINK_EXE_CMD} /OUT:${qe;rootrel:TARGET} \
  2265. ${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS} \
  2266. ${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL} ',
  2267. '${LINK_EXTRA_OUTPUT}', srcs_globals, '--ya-start-command-file ${VCS_C_OBJ_RR} ${qe;rootrel:AUTO_INPUT} $LINK_EXE_FLAGS $LINK_STDLIBS $LDFLAGS $LDFLAGS_GLOBAL $OBJADDE \
  2268. ${qe;rootrel;ext=.lib:PEERS} ${qe;rootrel;ext=.dll;noext;suf=.lib:PEERS} --ya-end-command-file \
  2269. ${hide;kv:"soe"} ${hide;kv:"p LD"} ${hide;kv:"pc blue"}')
  2270. emit('LINK_EXE', '$LINK_EXE_IMPL($_WHOLE_ARCHIVE_PEERS_VALUE)')
  2271. emit('LINK_DYN_LIB', '${GENERATE_MF} && $GENERATE_VCS_C_INFO_NODEP && $REAL_LINK_DYN_LIB ${hide;kv:"soe"} ${hide;kv:"p LD"} ${hide;kv:"pc blue"}')
  2272. emit('LINK_EXEC_DYN_LIB_CMDLINE', '${GENERATE_MF} && $GENERATE_VCS_C_INFO_NODEP && ${TOOLCHAIN_ENV} ${cwd:ARCADIA_BUILD_ROOT} ${LINK_WRAPPER} ${LINK_WRAPPER_DYNLIB} ${LINK_EXE_CMD} \
  2273. /OUT:${qe;rootrel:TARGET} ${LINK_EXTRA_OUTPUT} ${EXPORTS_VALUE} \
  2274. ${pre=--whole-archive-peers :WHOLE_ARCHIVE_PEERS} \
  2275. ${pre=--whole-archive-libs :_WHOLE_ARCHIVE_LIBS_VALUE_GLOBAL}', srcs_globals,
  2276. '--ya-start-command-file ${VCS_C_OBJ_RR} ${qe;rootrel:AUTO_INPUT} ${qe;rootrel;ext=.lib:PEERS} ${qe;rootrel;ext=.dll;noext;suf=.lib:PEERS} \
  2277. $LINK_EXE_FLAGS $LINK_STDLIBS $LDFLAGS $LDFLAGS_GLOBAL $OBJADDE --ya-end-command-file \
  2278. ${hide;kv:"soe"} ${hide;kv:"p LD"} ${hide;kv:"pc blue"}')
  2279. emit('LINK_EXEC_DYN_LIB', '$LINK_EXEC_DYN_LIB_IMPL($_WHOLE_ARCHIVE_PEERS_VALUE)')
  2280. emit('LINK_GLOBAL_FAT_OBJECT', '${TOOLCHAIN_ENV} ${cwd:ARCADIA_BUILD_ROOT} ${LIB_WRAPPER} ${LINK_LIB_CMD} /OUT:${qe;rootrel:TARGET} \
  2281. --ya-start-command-file ${qe;rootrel;ext=.lib:SRCS_GLOBAL} ${qe;rootrel;ext=.obj:SRCS_GLOBAL} ${qe;rootrel:AUTO_INPUT} $LINK_LIB_FLAGS --ya-end-command-file')
  2282. emit('LINK_PEERS_FAT_OBJECT', '${TOOLCHAIN_ENV} ${cwd:ARCADIA_BUILD_ROOT} ${LIB_WRAPPER} ${LINK_LIB_CMD} /OUT:${qe;rootrel;output:REALPRJNAME.lib} \
  2283. --ya-start-command-file ${qe;rootrel:PEERS} $LINK_LIB_FLAGS --ya-end-command-file')
  2284. emit('LINK_FAT_OBJECT', '${GENERATE_MF} && $GENERATE_VCS_C_INFO_NODEP && $LINK_GLOBAL_FAT_OBJECT && $LINK_PEERS_FAT_OBJECT ${kv;hide:"p LD"} ${kv;hide:"pc light-blue"} ${kv;hide:"show_out"}') # noqa E501
  2285. # TODO(somov): Rename!
  2286. Compilers = {
  2287. 'gnu': (GnuToolchain, GnuCompiler, LD),
  2288. 'clang': (GnuToolchain, GnuCompiler, LD),
  2289. 'xcode': (GnuToolchain, GnuCompiler, LD),
  2290. 'msvc': (MSVCToolchain, MSVCCompiler, MSVCLinker),
  2291. }
  2292. class Ragel(object):
  2293. def __init__(self):
  2294. self.rlgen_flags = []
  2295. self.ragel_flags = []
  2296. self.ragel6_flags = []
  2297. def configure_toolchain(self, build, compiler):
  2298. if isinstance(compiler, MSVCCompiler):
  2299. self.set_default_flags(optimized=False)
  2300. elif isinstance(compiler, GnuCompiler):
  2301. self.set_default_flags(optimized=build.is_release and not build.is_sanitized)
  2302. else:
  2303. raise ConfigureError('Unexpected compiler {}'.format(compiler))
  2304. def set_default_flags(self, optimized):
  2305. if optimized:
  2306. self.rlgen_flags.append('-G2')
  2307. self.ragel6_flags.append('-CG2')
  2308. else:
  2309. self.rlgen_flags.append('-T0')
  2310. self.ragel6_flags.append('-CT0')
  2311. def print_variables(self):
  2312. emit('RLGEN_FLAGS', self.rlgen_flags)
  2313. emit('RAGEL_FLAGS', self.ragel_flags)
  2314. emit('RAGEL6_FLAGS', self.ragel6_flags)
  2315. class Python(object):
  2316. def __init__(self, tc):
  2317. self.python = None
  2318. self.flags = None
  2319. self.ldflags = None
  2320. self.libraries = None
  2321. self.includes = None
  2322. self.tc = tc
  2323. def configure_posix(self, python=None, python_config=None):
  2324. python = python or preset('PYTHON_BIN') or which('python')
  2325. python_config = python_config or preset('PYTHON_CONFIG') or which('python-config')
  2326. if python is None or python_config is None:
  2327. return
  2328. # python-config dumps each option on one line in the specified order
  2329. config = get_stdout([python_config, '--cflags', '--ldflags', '--includes']) or ''
  2330. config = config.split('\n')
  2331. if len(config) < 3:
  2332. return
  2333. self.python = python
  2334. self.flags = config[0]
  2335. self.ldflags = config[1]
  2336. self.includes = config[2]
  2337. # Do not split libraries from ldflags.
  2338. # They are not used separately and get overriden together, so it is safe.
  2339. # TODO(somov): Удалить эту переменную и PYTHON_LIBRARIES из makelist-ов.
  2340. self.libraries = ''
  2341. if preset('USE_ARCADIA_PYTHON') == 'no' and not preset('USE_SYSTEM_PYTHON') and not self.tc.os_sdk_local:
  2342. raise Exception("Use fixed python (see https://clubs.at.yandex-team.ru/arcadia/15392) or set OS_SDK=local flag")
  2343. def print_variables(self):
  2344. variables = Variables({
  2345. 'PYTHON_BIN': self.python,
  2346. 'PYTHON_FLAGS': self.flags,
  2347. 'PYTHON_LDFLAGS': self.ldflags,
  2348. 'PYTHON_LIBRARIES': self.libraries,
  2349. 'PYTHON_INCLUDE': self.includes
  2350. })
  2351. variables.update_from_presets()
  2352. variables.reset_if_any(reset_value='PYTHON-NOT-FOUND')
  2353. variables.emit()
  2354. class Perl(object):
  2355. # Parse (key, value) from "version='5.26.0';" lines
  2356. PERL_CONFIG_RE = re.compile(r"^(?P<key>\w+)='(?P<value>.*)';$", re.MULTILINE)
  2357. def __init__(self):
  2358. self.perl = None
  2359. self.version = None
  2360. self.privlib = None
  2361. self.archlib = None
  2362. def configure_local(self, perl=None):
  2363. self.perl = perl or preset('PERL') or which('perl')
  2364. if self.perl is None:
  2365. return
  2366. # noinspection PyTypeChecker
  2367. config = dict(self._iter_config(['version', 'privlibexp', 'archlibexp']))
  2368. self.version = config.get('version')
  2369. self.privlib = config.get('privlibexp')
  2370. self.archlib = config.get('archlibexp')
  2371. def print_variables(self, prefix=''):
  2372. variables = Variables({
  2373. prefix + 'PERL': self.perl,
  2374. prefix + 'PERL_VERSION': self.version,
  2375. prefix + 'PERL_PRIVLIB': self.privlib,
  2376. prefix + 'PERL_ARCHLIB': self.archlib,
  2377. })
  2378. variables.reset_if_any(reset_value='PERL-NOT-FOUND')
  2379. variables.emit(with_ignore_comment=variables.keys())
  2380. def _iter_config(self, config_keys):
  2381. # Run perl -V:version -V:etc...
  2382. perl_config = [self.perl] + ['-V:{}'.format(key) for key in config_keys]
  2383. config = six.ensure_str(get_stdout(perl_config) or '')
  2384. start = 0
  2385. while True:
  2386. match = Perl.PERL_CONFIG_RE.search(config, start)
  2387. if match is None:
  2388. break
  2389. yield match.group('key', 'value')
  2390. start = match.end()
  2391. class Setting(object):
  2392. def __init__(self, key, auto=None, convert=None, rewrite=False):
  2393. self.key = key
  2394. self.auto = auto
  2395. self.convert = convert
  2396. self.preset = preset(key)
  2397. self.from_user = self.preset is not None
  2398. self.rewrite = rewrite
  2399. self._value = Setting.no_value
  2400. @property
  2401. def value(self):
  2402. if self._value is Setting.no_value:
  2403. self._value = self.calculate_value()
  2404. return self._value
  2405. def calculate_value(self):
  2406. if not self.from_user:
  2407. return self.auto if not callable(self.auto) else self.auto()
  2408. else:
  2409. return self.preset if not self.convert else self.convert(self.preset)
  2410. @value.setter
  2411. def value(self, value):
  2412. if self.from_user:
  2413. 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))
  2414. self._value = value
  2415. def emit(self):
  2416. if not self.from_user or self.rewrite:
  2417. emit(self.key, self.value)
  2418. no_value = object()
  2419. class Cuda(object):
  2420. def __init__(self, build):
  2421. """
  2422. :type build: Build
  2423. """
  2424. self.build = build
  2425. self.have_cuda = Setting('HAVE_CUDA', auto=self.auto_have_cuda, convert=to_bool)
  2426. self.cuda_root = Setting('CUDA_ROOT')
  2427. self.cuda_version = Setting('CUDA_VERSION', auto=self.auto_cuda_version, convert=self.convert_major_version, rewrite=True)
  2428. self.use_arcadia_cuda = Setting('USE_ARCADIA_CUDA', auto=self.auto_use_arcadia_cuda, convert=to_bool)
  2429. self.use_arcadia_cuda_host_compiler = Setting('USE_ARCADIA_CUDA_HOST_COMPILER', auto=self.auto_use_arcadia_cuda_host_compiler, convert=to_bool)
  2430. self.cuda_use_clang = Setting('CUDA_USE_CLANG', auto=False, convert=to_bool)
  2431. self.cuda_host_compiler = Setting('CUDA_HOST_COMPILER', auto=self.auto_cuda_host_compiler)
  2432. self.cuda_host_compiler_env = Setting('CUDA_HOST_COMPILER_ENV')
  2433. self.cuda_host_msvc_version = Setting('CUDA_HOST_MSVC_VERSION')
  2434. self.cuda_nvcc_flags = Setting('CUDA_NVCC_FLAGS', auto=[])
  2435. self.peerdirs = ['build/platform/cuda']
  2436. self.nvcc_flags = []
  2437. if not self.have_cuda.value:
  2438. return
  2439. if self.cuda_host_compiler.value:
  2440. self.nvcc_flags.append('--compiler-bindir=$CUDA_HOST_COMPILER')
  2441. if self.use_arcadia_cuda.value:
  2442. self.cuda_root.value = '$CUDA_RESOURCE_GLOBAL'
  2443. if self.build.target.is_linux_x86_64 and self.build.tc.is_clang:
  2444. # TODO(somov): Эта настройка должна приезжать сюда автоматически из другого места
  2445. self.nvcc_flags.append('-I$OS_SDK_ROOT/usr/include/x86_64-linux-gnu')
  2446. def print_(self):
  2447. self.print_variables()
  2448. self.print_macros()
  2449. def print_variables(self):
  2450. self.have_cuda.emit()
  2451. if not self.have_cuda.value:
  2452. return
  2453. if self.use_arcadia_cuda.value and self.cuda_host_compiler.value is None:
  2454. logger.warning('$USE_ARCADIA_CUDA is set, but no $CUDA_HOST_COMPILER')
  2455. self.setup_vc_root()
  2456. self.cuda_root.emit()
  2457. self.cuda_version.emit()
  2458. self.use_arcadia_cuda.emit()
  2459. self.use_arcadia_cuda_host_compiler.emit()
  2460. self.cuda_use_clang.emit()
  2461. self.cuda_host_compiler.emit()
  2462. self.cuda_host_compiler_env.emit()
  2463. self.cuda_host_msvc_version.emit()
  2464. self.cuda_nvcc_flags.emit()
  2465. emit('NVCC_UNQUOTED', self.build.host.exe('$CUDA_ROOT', 'bin', 'nvcc'))
  2466. emit('NVCC', '${quo:NVCC_UNQUOTED}')
  2467. emit('NVCC_FLAGS', self.nvcc_flags, '$CUDA_NVCC_FLAGS')
  2468. emit('NVCC_OBJ_EXT', '.o' if not self.build.target.is_windows else '.obj')
  2469. def print_macros(self):
  2470. if not self.cuda_use_clang.value:
  2471. cmd = '$YMAKE_PYTHON ${input:"build/scripts/compile_cuda.py"} ${tool:"tools/mtime0"} $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 $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
  2472. else:
  2473. 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
  2474. emit('_SRC_CU_CMD', cmd)
  2475. emit('_SRC_CU_PEERDIR', ' '.join(sorted(self.peerdirs)))
  2476. def have_cuda_in_arcadia(self):
  2477. host, target = self.build.host_target
  2478. if not any((host.is_linux_x86_64, host.is_macos_x86_64, host.is_windows_x86_64, host.is_linux_powerpc)):
  2479. return False
  2480. if host != target:
  2481. if not(host.is_linux_x86_64 and target.is_linux_armv8):
  2482. return False
  2483. if not self.cuda_version.from_user:
  2484. return False
  2485. if self.cuda_version.value not in ('11.3',):
  2486. raise ConfigureError('Only CUDA 11.3 are available for cross compilation from linux-x86 to linux-aarch64.\nUse -DCUDA_VERSION=11.3 flag.')
  2487. if self.cuda_version.value in ('8.0', '9.0', '9.1', '9.2', '10.0'):
  2488. raise ConfigureError('CUDA versions 8.x, 9.x and 10.0 are no longer supported.\nSee DEVTOOLS-7108.')
  2489. if self.cuda_version.value in ('10.1', '11.0', '11.1', '11.3', '11.4'):
  2490. return True
  2491. return False
  2492. def auto_have_cuda(self):
  2493. if is_positive('MUSL'):
  2494. return False
  2495. if self.build.is_sanitized:
  2496. return False
  2497. if self.build.host_target[1].is_macos_x86_64 or self.build.host_target[1].is_macos_arm64:
  2498. # DEVTOOLSSUPPORT-19178 CUDA is rarely needed on Mac. Disable it by default but allow explicit builds with CUDA.
  2499. return False
  2500. return self.cuda_root.from_user or self.use_arcadia_cuda.value and self.have_cuda_in_arcadia()
  2501. def auto_cuda_version(self):
  2502. if self.use_arcadia_cuda.value:
  2503. return '10.1'
  2504. if not self.have_cuda.value:
  2505. return None
  2506. nvcc_exe = self.build.host.exe(os.path.expanduser(self.cuda_root.value), 'bin', 'nvcc')
  2507. def error():
  2508. raise ConfigureError('Failed to get CUDA version from {}'.format(nvcc_exe))
  2509. version_output = get_stdout([nvcc_exe, '--version']) or error()
  2510. match = re.search(r'^Cuda compilation tools, release (\d+)\.\d+,', version_output, re.MULTILINE) or error()
  2511. return match.group(1)
  2512. def convert_major_version(self, value):
  2513. if value == '10':
  2514. return '10.1'
  2515. elif value == '11':
  2516. return '11.3'
  2517. else:
  2518. return value
  2519. def auto_use_arcadia_cuda(self):
  2520. return not self.cuda_root.from_user
  2521. def auto_use_arcadia_cuda_host_compiler(self):
  2522. return not self.cuda_host_compiler.from_user and not self.cuda_use_clang.value
  2523. def auto_cuda_host_compiler(self):
  2524. if not self.use_arcadia_cuda_host_compiler.value:
  2525. return None
  2526. host, target = self.build.host_target
  2527. if host.is_windows_x86_64 and target.is_windows_x86_64:
  2528. return self.cuda_windows_host_compiler()
  2529. return select((
  2530. (host.is_linux_x86_64 and target.is_linux_x86_64, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  2531. (host.is_linux_x86_64 and target.is_linux_armv8, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  2532. (host.is_linux_powerpc and target.is_linux_powerpc, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/bin/clang'),
  2533. (host.is_macos_x86_64 and target.is_macos_x86_64, '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/usr/bin/clang'),
  2534. ))
  2535. def cuda_windows_host_compiler(self):
  2536. vc_version = '14.28.29910'
  2537. env = {
  2538. 'Y_VC_Version': vc_version,
  2539. 'Y_VC_Root': '$CUDA_HOST_TOOLCHAIN_RESOURCE_GLOBAL/VC/Tools/MSVC/{}'.format(vc_version),
  2540. 'Y_SDK_Version': self.build.tc.sdk_version,
  2541. 'Y_SDK_Root': '$WINDOWS_KITS_RESOURCE_GLOBAL',
  2542. }
  2543. if not self.build.tc.ide_msvs:
  2544. self.peerdirs.append('build/platform/msvc')
  2545. self.cuda_host_compiler_env.value = format_env(env)
  2546. self.cuda_host_msvc_version.value = vc_version
  2547. return '%(Y_VC_Root)s/bin/HostX64/x64/cl.exe' % env
  2548. def setup_vc_root(self):
  2549. if not self.cuda_host_compiler.from_user:
  2550. return # Already set in cuda_windows_host_compiler()
  2551. if self.cuda_host_compiler_env.from_user:
  2552. return # We won't override user setting
  2553. def is_root(dir):
  2554. return all(os.path.isdir(os.path.join(dir, name)) for name in ('bin', 'include', 'lib'))
  2555. def get_root():
  2556. path, old_path = os.path.normpath(self.cuda_host_compiler.value), None
  2557. while path != old_path:
  2558. if is_root(path):
  2559. return path
  2560. path, old_path = os.path.dirname(path), path
  2561. vc_root = get_root()
  2562. if vc_root:
  2563. self.cuda_host_compiler_env.value = format_env({'Y_VC_Root': vc_root})
  2564. class CuDNN(object):
  2565. def __init__(self, cuda):
  2566. """
  2567. :type cuda: Cuda
  2568. """
  2569. self.cuda = cuda
  2570. self.cudnn_version = Setting('CUDNN_VERSION', auto=self.auto_cudnn_version)
  2571. def have_cudnn(self):
  2572. return self.cudnn_version.value in ('7.6.5', '8.0.5')
  2573. def auto_cudnn_version(self):
  2574. return '7.6.5'
  2575. def print_(self):
  2576. if self.cuda.have_cuda.value and self.have_cudnn():
  2577. self.cudnn_version.emit()
  2578. def print_swig_config():
  2579. def get_swig_tool():
  2580. tool = preset('USER_SWIG_TOOL')
  2581. if not tool:
  2582. tool = which('swig')
  2583. if not tool:
  2584. raise ConfigureError('SWIG_TOOL is not specified and "swig" is not found in PATH')
  2585. return os.path.abspath(tool)
  2586. def get_swig_library(tool):
  2587. library = preset('USER_SWIG_LIBRARY')
  2588. if not library:
  2589. library, code = get_stdout_and_code((tool, '-swiglib'))
  2590. if code != 0:
  2591. raise ConfigureError('SWIG_LIBRARY is not specified and "{} -swiglib" failed'.format(tool))
  2592. library = library.split('\n')[0]
  2593. return os.path.abspath(library)
  2594. use_local_swig = to_bool(preset('USER_USE_LOCAL_SWIG'), False) or bool(preset('USER_SWIG_TOOL'))
  2595. if use_local_swig:
  2596. tool = get_swig_tool()
  2597. library = get_swig_library(tool)
  2598. emit('USE_LOCAL_SWIG', True)
  2599. emit('SWIG_TOOL', tool)
  2600. emit('SWIG_LIBRARY', library)
  2601. def main():
  2602. options = opts()
  2603. arcadia = Arcadia(options.arcadia_root)
  2604. ymake = YMake(arcadia)
  2605. ymake.print_core_conf()
  2606. ymake.print_presets()
  2607. ymake.print_settings()
  2608. build = Build(arcadia, options.build_type, options.toolchain_params, force_ignore_local_files=not options.local_distbuild)
  2609. build.print_build()
  2610. emit_with_ignore_comment('CONF_SCRIPT_DEPENDS', __file__)
  2611. if __name__ == '__main__':
  2612. main()