go_tool.py 32 KB

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