go_tool.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. import argparse
  2. import copy
  3. import json
  4. import os
  5. import re
  6. import shutil
  7. import subprocess
  8. import sys
  9. import tarfile
  10. import tempfile
  11. import threading
  12. import traceback
  13. from contextlib import contextmanager
  14. from functools import reduce
  15. import process_command_files as pcf
  16. import process_whole_archive_option as pwa
  17. arc_project_prefix = 'a.yandex-team.ru/'
  18. # FIXME: make version-independent
  19. std_lib_prefix = 'contrib/go/_std_1.22/src/'
  20. vendor_prefix = 'vendor/'
  21. vet_info_ext = '.vet.out'
  22. vet_report_ext = '.vet.txt'
  23. FIXED_CGO1_SUFFIX = '.fixed.cgo1.go'
  24. COMPILE_OPTIMIZATION_FLAGS = ('-N',)
  25. IGNORED_FLAGS = ['-fprofile-instr-generate', '-fcoverage-mapping']
  26. def get_trimpath_args(args):
  27. return ['-trimpath', args.trimpath] if args.trimpath else []
  28. def preprocess_cgo1(src_path, dst_path, source_root):
  29. with open(src_path, 'r') as f:
  30. content = f.read()
  31. content = content.replace('__ARCADIA_SOURCE_ROOT_PREFIX__', source_root)
  32. with open(dst_path, 'w') as f:
  33. f.write(content)
  34. def preprocess_args(args):
  35. # Temporary work around for noauto
  36. if args.cgo_srcs and len(args.cgo_srcs) > 0:
  37. cgo_srcs_set = set(args.cgo_srcs)
  38. args.srcs = [x for x in args.srcs if x not in cgo_srcs_set]
  39. args.pkg_root = os.path.join(args.toolchain_root, 'pkg')
  40. toolchain_tool_root = os.path.join(args.pkg_root, 'tool', '{}_{}'.format(args.host_os, args.host_arch))
  41. args.go_compile = os.path.join(toolchain_tool_root, 'compile')
  42. args.go_cgo = os.path.join(toolchain_tool_root, 'cgo')
  43. args.go_link = os.path.join(toolchain_tool_root, 'link')
  44. args.go_asm = os.path.join(toolchain_tool_root, 'asm')
  45. args.go_pack = os.path.join(toolchain_tool_root, 'pack')
  46. args.go_vet = os.path.join(toolchain_tool_root, 'vet') if args.vet is True else args.vet
  47. args.output = os.path.normpath(args.output)
  48. args.vet_report_output = vet_report_output_name(args.output, args.vet_report_ext)
  49. args.trimpath = None
  50. if args.debug_root_map:
  51. roots = {'build': args.build_root, 'source': args.source_root, 'tools': args.tools_root}
  52. replaces = []
  53. for root in args.debug_root_map.split(';'):
  54. src, dst = root.split('=', 1)
  55. assert src in roots
  56. replaces.append('{}=>{}'.format(roots[src], dst))
  57. del roots[src]
  58. assert len(replaces) > 0
  59. args.trimpath = ';'.join(replaces)
  60. args.build_root = os.path.normpath(args.build_root)
  61. args.build_root_dir = args.build_root + os.path.sep
  62. args.source_root = os.path.normpath(args.source_root)
  63. args.source_root_dir = args.source_root + os.path.sep
  64. args.output_root = os.path.normpath(args.output_root)
  65. args.import_map = {}
  66. args.module_map = {}
  67. def is_valid_cgo_peer(peer):
  68. if peer.endswith('.fake.pkg') or peer.endswith('.fake'):
  69. return False
  70. return True
  71. if args.cgo_peers:
  72. args.cgo_peers = list(filter(is_valid_cgo_peer, args.cgo_peers))
  73. srcs = []
  74. for f in args.srcs:
  75. if f.endswith('.gosrc'):
  76. with tarfile.open(f, 'r') as tar:
  77. srcs.extend(os.path.join(args.output_root, src) for src in tar.getnames())
  78. if sys.version_info >= (3, 12):
  79. tar.extractall(path=args.output_root, filter='data')
  80. else:
  81. tar.extractall(path=args.output_root)
  82. else:
  83. srcs.append(f)
  84. args.srcs = srcs
  85. assert args.mode == 'test' or args.test_srcs is None and args.xtest_srcs is None
  86. # add lexical oreder by basename for go sources
  87. args.srcs.sort(key=lambda x: os.path.basename(x))
  88. if args.test_srcs:
  89. args.srcs += sorted(args.test_srcs, key=lambda x: os.path.basename(x))
  90. del args.test_srcs
  91. if args.xtest_srcs:
  92. args.xtest_srcs.sort(key=lambda x: os.path.basename(x))
  93. # compute root relative module dir path
  94. assert args.output is None or args.output_root == os.path.dirname(args.output)
  95. assert args.output_root.startswith(args.build_root_dir)
  96. args.module_path = args.output_root[len(args.build_root_dir) :]
  97. args.source_module_dir = os.path.join(args.source_root, args.test_import_path or args.module_path) + os.path.sep
  98. assert len(args.module_path) > 0
  99. args.import_path, args.is_std = get_import_path(args.module_path)
  100. assert args.asmhdr is None or args.word == 'go'
  101. srcs = []
  102. for f in args.srcs:
  103. if f.endswith(FIXED_CGO1_SUFFIX) and f.startswith(args.build_root_dir):
  104. path = os.path.join(args.output_root, '{}.cgo1.go'.format(os.path.basename(f[: -len(FIXED_CGO1_SUFFIX)])))
  105. srcs.append(path)
  106. preprocess_cgo1(f, path, args.source_root)
  107. else:
  108. srcs.append(f)
  109. args.srcs = srcs
  110. if args.extldflags:
  111. tmp = [flag for flag in args.extldflags if flag not in IGNORED_FLAGS]
  112. args.extldflags = pwa.ProcessWholeArchiveOption(args.targ_os).construct_cmd(tmp)
  113. classify_srcs(args.srcs, args)
  114. def compare_versions(version1, version2):
  115. def last_index(version):
  116. index = version.find('beta')
  117. return len(version) if index < 0 else index
  118. v1 = tuple(x.zfill(8) for x in version1[: last_index(version1)].split('.'))
  119. v2 = tuple(x.zfill(8) for x in version2[: last_index(version2)].split('.'))
  120. if v1 == v2:
  121. return 0
  122. return 1 if v1 < v2 else -1
  123. def get_symlink_or_copyfile():
  124. os_symlink = getattr(os, 'symlink', None)
  125. if os_symlink is None or os.name == 'nt':
  126. os_symlink = shutil.copyfile
  127. return os_symlink
  128. def copy_args(args):
  129. return copy.copy(args)
  130. def get_vendor_index(import_path):
  131. index = import_path.rfind('/' + vendor_prefix)
  132. if index < 0:
  133. index = 0 if import_path.startswith(vendor_prefix) else index
  134. else:
  135. index = index + 1
  136. return index
  137. def get_import_path(module_path):
  138. assert len(module_path) > 0
  139. import_path = module_path.replace('\\', '/')
  140. is_std_module = import_path.startswith(std_lib_prefix)
  141. if is_std_module:
  142. import_path = import_path[len(std_lib_prefix) :]
  143. elif import_path.startswith(vendor_prefix):
  144. import_path = import_path[len(vendor_prefix) :]
  145. else:
  146. import_path = arc_project_prefix + import_path
  147. assert len(import_path) > 0
  148. return import_path, is_std_module
  149. def call(cmd, cwd, env=None):
  150. # sys.stderr.write('{}\n'.format(' '.join(cmd)))
  151. return subprocess.check_output(cmd, stdin=None, stderr=subprocess.STDOUT, cwd=cwd, env=env, text=True)
  152. def classify_srcs(srcs, args):
  153. args.go_srcs = [x for x in srcs if x.endswith('.go')]
  154. args.asm_srcs = [x for x in srcs if x.endswith('.s')]
  155. args.objects = [x for x in srcs if x.endswith('.o') or x.endswith('.obj')]
  156. args.symabis = [x for x in srcs if x.endswith('.symabis')]
  157. args.sysos = [x for x in srcs if x.endswith('.syso')]
  158. def get_import_config_info(peers, gen_importmap, import_map={}, module_map={}):
  159. info = {'importmap': [], 'packagefile': [], 'standard': {}}
  160. if gen_importmap:
  161. for key, value in import_map.items():
  162. info['importmap'].append((key, value))
  163. for peer in peers:
  164. peer_import_path, is_std = get_import_path(os.path.dirname(peer))
  165. if gen_importmap:
  166. index = get_vendor_index(peer_import_path)
  167. if index >= 0:
  168. index += len(vendor_prefix)
  169. info['importmap'].append((peer_import_path[index:], peer_import_path))
  170. info['packagefile'].append((peer_import_path, os.path.join(args.build_root, peer)))
  171. if is_std:
  172. info['standard'][peer_import_path] = True
  173. for key, value in module_map.items():
  174. info['packagefile'].append((key, value))
  175. return info
  176. def create_import_config(peers, gen_importmap, import_map={}, module_map={}):
  177. lines = []
  178. info = get_import_config_info(peers, gen_importmap, import_map, module_map)
  179. for key in ('importmap', 'packagefile'):
  180. for item in info[key]:
  181. lines.append('{} {}={}'.format(key, *item))
  182. if len(lines) > 0:
  183. lines.append('')
  184. content = '\n'.join(lines)
  185. # sys.stderr.writelines('{}\n'.format(l) for l in lines)
  186. with tempfile.NamedTemporaryFile(delete=False) as f:
  187. f.write(content.encode('UTF-8'))
  188. return f.name
  189. return None
  190. def create_embed_config(args):
  191. data = {
  192. 'Patterns': {},
  193. 'Files': {},
  194. }
  195. for info in args.embed:
  196. embed_dir = os.path.normpath(info[0])
  197. assert embed_dir == args.source_module_dir[:-1] or embed_dir.startswith(
  198. (args.source_module_dir, args.build_root)
  199. )
  200. pattern = info[1]
  201. if pattern.endswith('/**/*'):
  202. pattern = pattern[:-3]
  203. files = {os.path.relpath(f, embed_dir).replace('\\', '/'): f for f in info[2:]}
  204. data['Patterns'][pattern] = list(files.keys())
  205. data['Files'].update(files)
  206. # sys.stderr.write('{}\n'.format(json.dumps(data, indent=4)))
  207. with tempfile.NamedTemporaryFile(delete=False, suffix='.embedcfg') as f:
  208. f.write(json.dumps(data).encode('UTF-8'))
  209. return f.name
  210. def vet_info_output_name(path, ext=None):
  211. return '{}{}'.format(path, ext or vet_info_ext)
  212. def vet_report_output_name(path, ext=None):
  213. return '{}{}'.format(path, ext or vet_report_ext)
  214. def get_source_path(args):
  215. return args.test_import_path or args.module_path
  216. def gen_vet_info(args):
  217. import_path = args.real_import_path if hasattr(args, 'real_import_path') else args.import_path
  218. info = get_import_config_info(args.peers, True, args.import_map, args.module_map)
  219. import_map = dict(info['importmap'])
  220. # FIXME(snermolaev): it seems that adding import map for 'fake' package
  221. # does't make any harm (it needs to be revised later)
  222. import_map['unsafe'] = 'unsafe'
  223. for key, _ in info['packagefile']:
  224. if key not in import_map:
  225. import_map[key] = key
  226. data = {
  227. 'ID': import_path,
  228. 'Compiler': 'gc',
  229. 'Dir': os.path.join(args.source_root, get_source_path(args)),
  230. 'ImportPath': import_path,
  231. 'GoFiles': [x for x in args.go_srcs if x.endswith('.go')],
  232. 'NonGoFiles': [x for x in args.go_srcs if not x.endswith('.go')],
  233. 'ImportMap': import_map,
  234. 'PackageFile': dict(info['packagefile']),
  235. 'Standard': dict(info['standard']),
  236. 'PackageVetx': dict((key, vet_info_output_name(value)) for key, value in info['packagefile']),
  237. 'VetxOnly': False,
  238. 'VetxOutput': vet_info_output_name(args.output),
  239. 'SucceedOnTypecheckFailure': False,
  240. }
  241. # sys.stderr.write('{}\n'.format(json.dumps(data, indent=4)))
  242. return data
  243. def create_vet_config(args, info):
  244. with tempfile.NamedTemporaryFile(delete=False, suffix='.cfg') as f:
  245. f.write(json.dumps(info).encode('UTF-8'))
  246. return f.name
  247. def decode_vet_report(json_report):
  248. report = ''
  249. if json_report:
  250. json_report = json_report.decode('UTF-8')
  251. try:
  252. full_diags = json.JSONDecoder().decode(json_report)
  253. except ValueError:
  254. report = json_report
  255. else:
  256. messages = []
  257. for _, module_diags in full_diags.items():
  258. for _, type_diags in module_diags.items():
  259. for diag in type_diags:
  260. messages.append('{}: {}'.format(diag['posn'], json.dumps(diag['message'])))
  261. report = '\n'.join(messages)
  262. return report
  263. def dump_vet_report(args, report):
  264. if report:
  265. report = report.replace(args.build_root, '$B')
  266. report = report.replace(args.source_root, '$S')
  267. with open(args.vet_report_output, 'w') as f:
  268. f.write(report)
  269. def read_vet_report(args):
  270. assert args
  271. report = ''
  272. if os.path.exists(args.vet_report_output):
  273. with open(args.vet_report_output, 'r') as f:
  274. report += f.read()
  275. return report
  276. def dump_vet_report_for_tests(args, *test_args_list):
  277. dump_vet_report(args, reduce(lambda x, y: x + read_vet_report(y), [_f for _f in test_args_list if _f], ''))
  278. def do_vet(args):
  279. assert args.vet
  280. info = gen_vet_info(args)
  281. vet_config = create_vet_config(args, info)
  282. cmd = [args.go_vet, '-json']
  283. if args.vet_flags:
  284. cmd.extend(args.vet_flags)
  285. cmd.append(vet_config)
  286. # sys.stderr.write('>>>> [{}]\n'.format(' '.join(cmd)))
  287. p_vet = subprocess.Popen(cmd, stdin=None, stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=args.source_root)
  288. vet_out, vet_err = p_vet.communicate()
  289. report = decode_vet_report(vet_out) if vet_out else ''
  290. dump_vet_report(args, report)
  291. if p_vet.returncode:
  292. raise subprocess.CalledProcessError(returncode=p_vet.returncode, cmd=cmd, output=vet_err)
  293. def _do_compile_go(args):
  294. import_path, is_std_module = args.import_path, args.is_std
  295. cmd = [
  296. args.go_compile,
  297. '-o',
  298. args.output,
  299. '-p',
  300. import_path if import_path != "unsafe" else "",
  301. '-D',
  302. '""',
  303. ]
  304. if args.lang:
  305. cmd.append('-lang=go{}'.format(args.lang))
  306. cmd.extend(get_trimpath_args(args))
  307. compiling_runtime = False
  308. if is_std_module:
  309. cmd.append('-std')
  310. if import_path in ('runtime', 'internal/abi', 'internal/bytealg', 'internal/cpu') or import_path.startswith(
  311. 'runtime/internal/'
  312. ):
  313. cmd.append('-+')
  314. compiling_runtime = True
  315. import_config_name = create_import_config(args.peers, True, args.import_map, args.module_map)
  316. if import_config_name:
  317. cmd += ['-importcfg', import_config_name]
  318. else:
  319. if import_path == 'unsafe' or len(args.objects) > 0 or args.asmhdr:
  320. pass
  321. else:
  322. cmd.append('-complete')
  323. # if compare_versions('1.16', args.goversion) >= 0:
  324. if args.embed:
  325. embed_config_name = create_embed_config(args)
  326. cmd.extend(['-embedcfg', embed_config_name])
  327. if args.asmhdr:
  328. cmd += ['-asmhdr', args.asmhdr]
  329. # Use .symabis (starting from 1.12 version)
  330. if args.symabis:
  331. cmd += ['-symabis'] + args.symabis
  332. # If 1.12 <= version < 1.13 we have to pass -allabis for 'runtime' and 'runtime/internal/atomic'
  333. # if compare_versions('1.13', args.goversion) >= 0:
  334. # pass
  335. # elif import_path in ('runtime', 'runtime/internal/atomic'):
  336. # cmd.append('-allabis')
  337. compile_workers = '4'
  338. if args.compile_flags:
  339. if compiling_runtime:
  340. cmd.extend(x for x in args.compile_flags if x not in COMPILE_OPTIMIZATION_FLAGS)
  341. else:
  342. cmd.extend(args.compile_flags)
  343. if any([x in ('-race', '-shared') for x in args.compile_flags]):
  344. compile_workers = '1'
  345. cmd += ['-pack', '-c={}'.format(compile_workers)]
  346. cmd += args.go_srcs
  347. call(cmd, args.build_root)
  348. class VetThread(threading.Thread):
  349. def __init__(self, target, args):
  350. super(VetThread, self).__init__(target=target, args=args)
  351. self.exc_info = None
  352. def run(self):
  353. try:
  354. super(VetThread, self).run()
  355. except:
  356. self.exc_info = sys.exc_info()
  357. def join_with_exception(self, reraise_exception):
  358. self.join()
  359. if reraise_exception and self.exc_info:
  360. raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2])
  361. def do_compile_go(args):
  362. raise_exception_from_vet = False
  363. if args.vet:
  364. run_vet = VetThread(target=do_vet, args=(args,))
  365. run_vet.start()
  366. try:
  367. _do_compile_go(args)
  368. raise_exception_from_vet = True
  369. finally:
  370. if args.vet:
  371. run_vet.join_with_exception(raise_exception_from_vet)
  372. def do_compile_asm(args):
  373. assert len(args.srcs) == 1 and len(args.asm_srcs) == 1
  374. cmd = [args.go_asm]
  375. cmd += get_trimpath_args(args)
  376. cmd += ['-I', args.output_root, '-I', os.path.join(args.pkg_root, 'include')]
  377. cmd += ['-D', 'GOOS_' + args.targ_os, '-D', 'GOARCH_' + args.targ_arch, '-o', args.output]
  378. # if compare_versions('1.16', args.goversion) >= 0:
  379. cmd += ['-p', args.import_path]
  380. if args.asm_flags:
  381. cmd += args.asm_flags
  382. cmd += args.asm_srcs
  383. call(cmd, args.build_root)
  384. def do_link_lib(args):
  385. if len(args.asm_srcs) > 0:
  386. asmargs = copy_args(args)
  387. asmargs.asmhdr = os.path.join(asmargs.output_root, 'go_asm.h')
  388. do_compile_go(asmargs)
  389. for src in asmargs.asm_srcs:
  390. asmargs.srcs = [src]
  391. asmargs.asm_srcs = [src]
  392. asmargs.output = os.path.join(asmargs.output_root, os.path.basename(src) + '.o')
  393. do_compile_asm(asmargs)
  394. args.objects.append(asmargs.output)
  395. else:
  396. do_compile_go(args)
  397. if args.objects or args.sysos:
  398. cmd = [args.go_pack, 'r', args.output] + args.objects + args.sysos
  399. call(cmd, args.build_root)
  400. def do_link_exe(args):
  401. assert args.extld is not None
  402. assert args.non_local_peers is not None
  403. compile_args = copy_args(args)
  404. compile_args.output = os.path.join(args.output_root, 'main.a')
  405. compile_args.real_import_path = compile_args.import_path
  406. compile_args.import_path = 'main'
  407. if args.vcs and os.path.isfile(compile_args.vcs):
  408. build_info = os.path.join('library', 'go', 'core', 'buildinfo')
  409. if any([x.startswith(build_info) for x in compile_args.peers]):
  410. compile_args.go_srcs.append(compile_args.vcs)
  411. do_link_lib(compile_args)
  412. cmd = [args.go_link, '-o', args.output]
  413. import_config_name = create_import_config(
  414. args.peers + args.non_local_peers, False, args.import_map, args.module_map
  415. )
  416. if import_config_name:
  417. cmd += ['-importcfg', import_config_name]
  418. if args.link_flags:
  419. cmd += args.link_flags
  420. extldflags = []
  421. if args.buildmode:
  422. cmd.append('-buildmode={}'.format(args.buildmode))
  423. elif args.mode in ('exe', 'test'):
  424. mode = '-buildmode=exe'
  425. if 'ld.lld' in str(args):
  426. if '-fPIE' in str(args) or '-fPIC' in str(args):
  427. # support explicit PIE
  428. mode = '-buildmode=pie'
  429. else:
  430. extldflags.append('-Wl,-no-pie')
  431. cmd.append(mode)
  432. elif args.mode == 'dll':
  433. cmd.append('-buildmode=c-shared')
  434. else:
  435. assert False, 'Unexpected mode: {}'.format(args.mode)
  436. cmd.append('-extld={}'.format(args.extld))
  437. if args.extldflags is not None:
  438. filter_musl = bool
  439. if args.musl:
  440. cmd.append('-linkmode=external')
  441. extldflags.append('-static')
  442. filter_musl = lambda x: x not in ('-lc', '-ldl', '-lm', '-lpthread', '-lrt')
  443. extldflags += [x for x in args.extldflags if filter_musl(x)]
  444. cgo_peers = []
  445. if args.cgo_peers is not None and len(args.cgo_peers) > 0:
  446. is_group = args.targ_os == 'linux'
  447. if is_group:
  448. cgo_peers.append('-Wl,--start-group')
  449. cgo_peers.extend(args.cgo_peers)
  450. if is_group:
  451. cgo_peers.append('-Wl,--end-group')
  452. try:
  453. index = extldflags.index('--cgo-peers')
  454. extldflags = extldflags[:index] + cgo_peers + extldflags[index + 1 :]
  455. except ValueError:
  456. extldflags.extend(cgo_peers)
  457. if len(extldflags) > 0:
  458. cmd.append('-extldflags={}'.format(' '.join(extldflags)))
  459. cmd.append(compile_args.output)
  460. call(cmd, args.build_root)
  461. def gen_cover_info(args):
  462. lines = []
  463. lines.extend(
  464. [
  465. """
  466. var (
  467. coverCounters = make(map[string][]uint32)
  468. coverBlocks = make(map[string][]testing.CoverBlock)
  469. )
  470. """,
  471. 'func init() {',
  472. ]
  473. )
  474. for var, file in (x.split(':') for x in args.cover_info):
  475. lines.append(
  476. ' coverRegisterFile("{file}", _cover0.{var}.Count[:], _cover0.{var}.Pos[:], _cover0.{var}.NumStmt[:])'.format(
  477. file=file, var=var
  478. )
  479. )
  480. lines.extend(
  481. [
  482. '}',
  483. """
  484. func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
  485. if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
  486. panic("coverage: mismatched sizes")
  487. }
  488. if coverCounters[fileName] != nil {
  489. // Already registered.
  490. return
  491. }
  492. coverCounters[fileName] = counter
  493. block := make([]testing.CoverBlock, len(counter))
  494. for i := range counter {
  495. block[i] = testing.CoverBlock{
  496. Line0: pos[3*i+0],
  497. Col0: uint16(pos[3*i+2]),
  498. Line1: pos[3*i+1],
  499. Col1: uint16(pos[3*i+2]>>16),
  500. Stmts: numStmts[i],
  501. }
  502. }
  503. coverBlocks[fileName] = block
  504. }
  505. """,
  506. ]
  507. )
  508. return lines
  509. def filter_out_skip_tests(tests, skip_tests):
  510. skip_set = set()
  511. star_skip_set = set()
  512. for t in skip_tests:
  513. work_set = star_skip_set if '*' in t else skip_set
  514. work_set.add(t)
  515. re_star_tests = None
  516. if len(star_skip_set) > 0:
  517. re_star_tests = re.compile(re.sub(r'(\*)+', r'.\1', '^({})$'.format('|'.join(star_skip_set))))
  518. return [x for x in tests if not (x in skip_tests or re_star_tests and re_star_tests.match(x))]
  519. @contextmanager
  520. def create_strip_symlink():
  521. # This function creates symlink of llvm-strip as strip for golink needs.
  522. # We believe that cc-binaries path is a first element in PATH enviroment variable.
  523. tmpdir = None
  524. if os.getenv("CC") == "clang":
  525. tmpdir = tempfile.mkdtemp()
  526. cc_path = os.getenv("PATH").split(os.pathsep)[0]
  527. os.environ["PATH"] += os.pathsep + tmpdir
  528. src_strip_path = os.path.join(cc_path, 'llvm-strip')
  529. dst_strip_path = os.path.join(tmpdir, 'strip')
  530. os.symlink(src_strip_path, dst_strip_path)
  531. try:
  532. yield
  533. finally:
  534. if tmpdir:
  535. shutil.rmtree(tmpdir)
  536. def gen_test_main(args, test_lib_args, xtest_lib_args):
  537. assert args and (test_lib_args or xtest_lib_args)
  538. test_miner = args.test_miner
  539. test_module_path = test_lib_args.import_path if test_lib_args else xtest_lib_args.import_path
  540. is_cover = args.cover_info and len(args.cover_info) > 0
  541. # Prepare GOPATH
  542. # $BINDIR
  543. # |- __go__
  544. # |- src
  545. # |- pkg
  546. # |- ${TARGET_OS}_${TARGET_ARCH}
  547. go_path_root = os.path.join(args.output_root, '__go__')
  548. test_src_dir = os.path.join(go_path_root, 'src')
  549. target_os_arch = '_'.join([args.targ_os, args.targ_arch])
  550. test_pkg_dir = os.path.join(go_path_root, 'pkg', target_os_arch, os.path.dirname(test_module_path))
  551. os.makedirs(test_pkg_dir)
  552. my_env = os.environ.copy()
  553. my_env['GOROOT'] = ''
  554. my_env['GOPATH'] = go_path_root
  555. my_env['GOARCH'] = args.targ_arch
  556. my_env['GOOS'] = args.targ_os
  557. tests = []
  558. xtests = []
  559. os_symlink = get_symlink_or_copyfile()
  560. # Get the list of "internal" tests
  561. if test_lib_args:
  562. os.makedirs(os.path.join(test_src_dir, test_module_path))
  563. os_symlink(test_lib_args.output, os.path.join(test_pkg_dir, os.path.basename(test_module_path) + '.a'))
  564. cmd = [test_miner, '-benchmarks', '-tests', test_module_path]
  565. tests = [x for x in (call(cmd, test_lib_args.output_root, my_env) or '').strip().split('\n') if len(x) > 0]
  566. if args.skip_tests:
  567. tests = filter_out_skip_tests(tests, args.skip_tests)
  568. test_main_found = '#TestMain' in tests
  569. # Get the list of "external" tests
  570. if xtest_lib_args:
  571. xtest_module_path = xtest_lib_args.import_path
  572. os.makedirs(os.path.join(test_src_dir, xtest_module_path))
  573. os_symlink(xtest_lib_args.output, os.path.join(test_pkg_dir, os.path.basename(xtest_module_path) + '.a'))
  574. cmd = [test_miner, '-benchmarks', '-tests', xtest_module_path]
  575. xtests = [x for x in (call(cmd, xtest_lib_args.output_root, my_env) or '').strip().split('\n') if len(x) > 0]
  576. if args.skip_tests:
  577. xtests = filter_out_skip_tests(xtests, args.skip_tests)
  578. xtest_main_found = '#TestMain' in xtests
  579. test_main_package = None
  580. if test_main_found and xtest_main_found:
  581. assert False, 'multiple definition of TestMain'
  582. elif test_main_found:
  583. test_main_package = '_test'
  584. elif xtest_main_found:
  585. test_main_package = '_xtest'
  586. shutil.rmtree(go_path_root)
  587. lines = ['package main', '', 'import (']
  588. if test_main_package is None:
  589. lines.append(' "os"')
  590. lines.extend([' "testing"', ' "testing/internal/testdeps"'])
  591. lines.extend([' _ "{}library/go/test/yatest"'.format(args.arc_project_prefix)])
  592. if len(tests) > 0:
  593. lines.append(' _test "{}"'.format(test_module_path))
  594. elif test_lib_args:
  595. lines.append(' _ "{}"'.format(test_module_path))
  596. if len(xtests) > 0:
  597. lines.append(' _xtest "{}"'.format(xtest_module_path))
  598. elif xtest_lib_args:
  599. lines.append(' _ "{}"'.format(xtest_module_path))
  600. if is_cover:
  601. lines.append(' _cover0 "{}"'.format(test_module_path))
  602. lines.extend([')', ''])
  603. if compare_versions('1.18', args.goversion) < 0:
  604. kinds = ['Test', 'Benchmark', 'Example']
  605. else:
  606. kinds = ['Test', 'Benchmark', 'FuzzTarget', 'Example']
  607. var_names = []
  608. for kind in kinds:
  609. var_name = '{}s'.format(kind.lower())
  610. var_names.append(var_name)
  611. lines.append('var {} = []testing.Internal{}{{'.format(var_name, kind))
  612. for test in [x for x in tests if x.startswith(kind)]:
  613. lines.append(' {{"{test}", _test.{test}}},'.format(test=test))
  614. for test in [x for x in xtests if x.startswith(kind)]:
  615. lines.append(' {{"{test}", _xtest.{test}}},'.format(test=test))
  616. lines.extend(['}', ''])
  617. if is_cover:
  618. lines.extend(gen_cover_info(args))
  619. lines.append('func main() {')
  620. if is_cover:
  621. lines.extend(
  622. [
  623. ' testing.RegisterCover(testing.Cover{',
  624. ' Mode: "set",',
  625. ' Counters: coverCounters,',
  626. ' Blocks: coverBlocks,',
  627. ' CoveredPackages: "",',
  628. ' })',
  629. ]
  630. )
  631. lines.extend(
  632. [
  633. ' m := testing.MainStart(testdeps.TestDeps{{}}, {})'.format(', '.join(var_names)),
  634. '',
  635. ]
  636. )
  637. if test_main_package:
  638. lines.append(' {}.TestMain(m)'.format(test_main_package))
  639. else:
  640. lines.append(' os.Exit(m.Run())')
  641. lines.extend(['}', ''])
  642. content = '\n'.join(lines)
  643. # sys.stderr.write('{}\n'.format(content))
  644. return content
  645. def do_link_test(args):
  646. assert args.srcs or args.xtest_srcs
  647. assert args.test_miner is not None
  648. test_module_path = get_source_path(args)
  649. test_import_path, _ = get_import_path(test_module_path)
  650. test_lib_args = copy_args(args) if args.srcs else None
  651. xtest_lib_args = copy_args(args) if args.xtest_srcs else None
  652. if xtest_lib_args is not None:
  653. xtest_lib_args.embed = args.embed_xtest if args.embed_xtest else None
  654. ydx_file_name = None
  655. xtest_ydx_file_name = None
  656. need_append_ydx = test_lib_args and xtest_lib_args and args.ydx_file and args.vet_flags
  657. if need_append_ydx:
  658. def find_ydx_file_name(name, flags):
  659. for i, elem in enumerate(flags):
  660. if elem.endswith(name):
  661. return (i, elem)
  662. assert False, 'Unreachable code'
  663. idx, ydx_file_name = find_ydx_file_name(xtest_lib_args.ydx_file, xtest_lib_args.vet_flags)
  664. xtest_ydx_file_name = '{}_xtest'.format(ydx_file_name)
  665. xtest_lib_args.vet_flags = copy.copy(xtest_lib_args.vet_flags)
  666. xtest_lib_args.vet_flags[idx] = xtest_ydx_file_name
  667. if test_lib_args:
  668. test_lib_args.output = os.path.join(args.output_root, 'test.a')
  669. test_lib_args.vet_report_output = vet_report_output_name(test_lib_args.output)
  670. test_lib_args.module_path = test_module_path
  671. test_lib_args.import_path = test_import_path
  672. do_link_lib(test_lib_args)
  673. if xtest_lib_args:
  674. xtest_lib_args.srcs = xtest_lib_args.xtest_srcs
  675. classify_srcs(xtest_lib_args.srcs, xtest_lib_args)
  676. xtest_lib_args.output = os.path.join(args.output_root, 'xtest.a')
  677. xtest_lib_args.vet_report_output = vet_report_output_name(xtest_lib_args.output)
  678. xtest_lib_args.module_path = test_module_path + '_test'
  679. xtest_lib_args.import_path = test_import_path + '_test'
  680. if test_lib_args:
  681. xtest_lib_args.module_map[test_import_path] = test_lib_args.output
  682. need_append_ydx = args.ydx_file and args.srcs and args.vet_flags
  683. do_link_lib(xtest_lib_args)
  684. if need_append_ydx:
  685. with open(os.path.join(args.build_root, ydx_file_name), 'ab') as dst_file:
  686. with open(os.path.join(args.build_root, xtest_ydx_file_name), 'rb') as src_file:
  687. dst_file.write(src_file.read())
  688. test_main_content = gen_test_main(args, test_lib_args, xtest_lib_args)
  689. test_main_name = os.path.join(args.output_root, '_test_main.go')
  690. with open(test_main_name, "w") as f:
  691. f.write(test_main_content)
  692. test_args = copy_args(args)
  693. test_args.embed = None
  694. test_args.srcs = [test_main_name]
  695. if test_args.test_import_path is None:
  696. # it seems that we can do it unconditionally, but this kind
  697. # of mangling doesn't really looks good to me and we leave it
  698. # for pure GO_TEST module
  699. test_args.module_path = test_args.module_path + '___test_main__'
  700. test_args.import_path = test_args.import_path + '___test_main__'
  701. classify_srcs(test_args.srcs, test_args)
  702. if test_lib_args:
  703. test_args.module_map[test_lib_args.import_path] = test_lib_args.output
  704. if xtest_lib_args:
  705. test_args.module_map[xtest_lib_args.import_path] = xtest_lib_args.output
  706. if args.vet:
  707. dump_vet_report_for_tests(test_args, test_lib_args, xtest_lib_args)
  708. test_args.vet = False
  709. do_link_exe(test_args)
  710. if __name__ == '__main__':
  711. args = pcf.get_args(sys.argv[1:])
  712. parser = argparse.ArgumentParser(prefix_chars='+')
  713. parser.add_argument('++mode', choices=['dll', 'exe', 'lib', 'test'], required=True)
  714. parser.add_argument('++buildmode', choices=['c-shared', 'exe', 'pie'])
  715. parser.add_argument('++srcs', nargs='*', required=True)
  716. parser.add_argument('++cgo-srcs', nargs='*')
  717. parser.add_argument('++test_srcs', nargs='*')
  718. parser.add_argument('++xtest_srcs', nargs='*')
  719. parser.add_argument('++cover_info', nargs='*')
  720. parser.add_argument('++output', nargs='?', default=None)
  721. parser.add_argument('++source-root', default=None)
  722. parser.add_argument('++build-root', required=True)
  723. parser.add_argument('++tools-root', default=None)
  724. parser.add_argument('++output-root', required=True)
  725. parser.add_argument('++toolchain-root', required=True)
  726. parser.add_argument('++host-os', choices=['linux', 'darwin', 'windows'], required=True)
  727. parser.add_argument('++host-arch', choices=['amd64', 'arm64'], required=True)
  728. parser.add_argument('++targ-os', choices=['linux', 'darwin', 'windows'], required=True)
  729. parser.add_argument('++targ-arch', choices=['amd64', 'x86', 'arm64'], required=True)
  730. parser.add_argument('++peers', nargs='*')
  731. parser.add_argument('++non-local-peers', nargs='*')
  732. parser.add_argument('++cgo-peers', nargs='*')
  733. parser.add_argument('++asmhdr', nargs='?', default=None)
  734. parser.add_argument('++test-import-path', nargs='?')
  735. parser.add_argument('++test-miner', nargs='?')
  736. parser.add_argument('++arc-project-prefix', nargs='?', default=arc_project_prefix)
  737. parser.add_argument('++std-lib-prefix', nargs='?', default=std_lib_prefix)
  738. parser.add_argument('++vendor-prefix', nargs='?', default=vendor_prefix)
  739. parser.add_argument('++extld', nargs='?', default=None)
  740. parser.add_argument('++extldflags', nargs='+', default=None)
  741. parser.add_argument('++goversion', required=True)
  742. parser.add_argument('++lang', nargs='?', default=None)
  743. parser.add_argument('++asm-flags', nargs='*')
  744. parser.add_argument('++compile-flags', nargs='*')
  745. parser.add_argument('++link-flags', nargs='*')
  746. parser.add_argument('++vcs', nargs='?', default=None)
  747. parser.add_argument('++vet', nargs='?', const=True, default=False)
  748. parser.add_argument('++vet-flags', nargs='*', default=None)
  749. parser.add_argument('++vet-info-ext', default=vet_info_ext)
  750. parser.add_argument('++vet-report-ext', default=vet_report_ext)
  751. parser.add_argument('++musl', action='store_true')
  752. parser.add_argument('++skip-tests', nargs='*', default=None)
  753. parser.add_argument('++ydx-file', default='')
  754. parser.add_argument('++debug-root-map', default=None)
  755. parser.add_argument('++embed', action='append', nargs='*')
  756. parser.add_argument('++embed_xtest', action='append', nargs='*')
  757. args = parser.parse_args(args)
  758. arc_project_prefix = args.arc_project_prefix
  759. std_lib_prefix = args.std_lib_prefix
  760. vendor_prefix = args.vendor_prefix
  761. vet_info_ext = args.vet_info_ext
  762. vet_report_ext = args.vet_report_ext
  763. preprocess_args(args)
  764. try:
  765. os.unlink(args.output)
  766. except OSError:
  767. pass
  768. # We are going to support only 'lib', 'exe' and 'cgo' build modes currently
  769. # and as a result we are going to generate only one build node per module
  770. # (or program)
  771. dispatch = {'exe': do_link_exe, 'dll': do_link_exe, 'lib': do_link_lib, 'test': do_link_test}
  772. exit_code = 1
  773. try:
  774. with create_strip_symlink():
  775. dispatch[args.mode](args)
  776. exit_code = 0
  777. except subprocess.CalledProcessError as e:
  778. sys.stderr.write('{} returned non-zero exit code {}.\n{}\n'.format(' '.join(e.cmd), e.returncode, e.output))
  779. exit_code = e.returncode
  780. sys.exit(exit_code)