gobuild.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import base64
  2. import itertools
  3. from hashlib import md5
  4. import os
  5. import six
  6. from _common import rootrel_arc_src, tobuilddir
  7. import ymake
  8. runtime_cgo_path = os.path.join('runtime', 'cgo')
  9. runtime_msan_path = os.path.join('runtime', 'msan')
  10. runtime_race_path = os.path.join('runtime', 'race')
  11. arc_project_prefix = 'a.yandex-team.ru/'
  12. import_runtime_cgo_false = {
  13. 'norace': (runtime_cgo_path, runtime_msan_path, runtime_race_path),
  14. 'race': (runtime_cgo_path, runtime_msan_path),
  15. }
  16. import_syscall_false = {
  17. 'norace': (runtime_cgo_path),
  18. 'race': (runtime_cgo_path, runtime_race_path),
  19. }
  20. def get_import_path(unit):
  21. # std_lib_prefix = unit.get('GO_STD_LIB_PREFIX')
  22. # unit.get() doesn't evalutate the value of variable, so the line above doesn't really work
  23. std_lib_prefix = unit.get('GOSTD') + '/'
  24. arc_project_prefix = unit.get('GO_ARCADIA_PROJECT_PREFIX')
  25. vendor_prefix = unit.get('GO_CONTRIB_PROJECT_PREFIX')
  26. module_path = rootrel_arc_src(unit.path(), unit)
  27. assert len(module_path) > 0
  28. import_path = module_path.replace('\\', '/')
  29. if import_path.startswith(std_lib_prefix):
  30. import_path = import_path[len(std_lib_prefix) :]
  31. elif import_path.startswith(vendor_prefix):
  32. import_path = import_path[len(vendor_prefix) :]
  33. else:
  34. import_path = arc_project_prefix + import_path
  35. assert len(import_path) > 0
  36. return import_path
  37. def get_appended_values(unit, key):
  38. values = []
  39. raw_value = unit.get(key)
  40. if raw_value:
  41. values = [x for x in raw_value.split(' ') if x]
  42. if len(values) > 0 and values[0] == '$' + key:
  43. values.pop(0)
  44. return values
  45. def compare_versions(version1, version2):
  46. def last_index(version):
  47. index = version.find('beta')
  48. return len(version) if index < 0 else index
  49. v1 = tuple(x.zfill(8) for x in version1[: last_index(version1)].split('.'))
  50. v2 = tuple(x.zfill(8) for x in version2[: last_index(version2)].split('.'))
  51. if v1 == v2:
  52. return 0
  53. return 1 if v1 < v2 else -1
  54. def need_compiling_runtime(import_path, gostd_version):
  55. return (
  56. import_path in ('runtime', 'reflect', 'syscall')
  57. or import_path.startswith('runtime/internal/')
  58. or compare_versions('1.17', gostd_version) >= 0
  59. and import_path == 'internal/bytealg'
  60. )
  61. def go_package_name(unit):
  62. name = unit.get('GO_PACKAGE_VALUE')
  63. if not name:
  64. name = unit.get('GO_TEST_IMPORT_PATH')
  65. if name:
  66. name = os.path.basename(os.path.normpath(name))
  67. elif unit.get('MODULE_TYPE') == 'PROGRAM':
  68. name = 'main'
  69. else:
  70. name = unit.get('REALPRJNAME')
  71. return name
  72. def need_lint(path):
  73. return not path.startswith('$S/vendor/') and not path.startswith('$S/contrib/')
  74. def on_go_process_srcs(unit):
  75. """
  76. _GO_PROCESS_SRCS() macro processes only 'CGO' files. All remaining *.go files
  77. and other input files are currently processed by a link command of the
  78. GO module (GO_LIBRARY, GO_PROGRAM)
  79. """
  80. srcs_files = get_appended_values(unit, '_GO_SRCS_VALUE')
  81. asm_files = []
  82. c_files = []
  83. cxx_files = []
  84. ev_files = []
  85. fbs_files = []
  86. go_files = []
  87. in_files = []
  88. proto_files = []
  89. s_files = []
  90. syso_files = []
  91. classified_files = {
  92. '.c': c_files,
  93. '.cc': cxx_files,
  94. '.cpp': cxx_files,
  95. '.cxx': cxx_files,
  96. '.ev': ev_files,
  97. '.fbs': fbs_files,
  98. '.go': go_files,
  99. '.in': in_files,
  100. '.proto': proto_files,
  101. '.s': asm_files,
  102. '.syso': syso_files,
  103. '.C': cxx_files,
  104. '.S': s_files,
  105. }
  106. # Classify files specifed in _GO_SRCS() macro by extension and process CGO_EXPORT keyword
  107. # which can preceed C/C++ files only
  108. is_cgo_export = False
  109. for f in srcs_files:
  110. _, ext = os.path.splitext(f)
  111. ext_files = classified_files.get(ext)
  112. if ext_files is not None:
  113. if is_cgo_export:
  114. is_cgo_export = False
  115. if ext in ('.c', '.cc', '.cpp', '.cxx', '.C'):
  116. unit.oncopy_file_with_context([f, f, 'OUTPUT_INCLUDES', '${BINDIR}/_cgo_export.h'])
  117. f = '${BINDIR}/' + f
  118. else:
  119. ymake.report_configure_error('Unmatched CGO_EXPORT keyword in SRCS() macro')
  120. ext_files.append(f)
  121. elif f == 'CGO_EXPORT':
  122. is_cgo_export = True
  123. else:
  124. # FIXME(snermolaev): We can report an unsupported files for _GO_SRCS here
  125. pass
  126. if is_cgo_export:
  127. ymake.report_configure_error('Unmatched CGO_EXPORT keyword in SRCS() macro')
  128. for f in go_files:
  129. if f.endswith('_test.go'):
  130. ymake.report_configure_error('file {} must be listed in GO_TEST_SRCS() or GO_XTEST_SRCS() macros'.format(f))
  131. go_test_files = get_appended_values(unit, '_GO_TEST_SRCS_VALUE')
  132. go_xtest_files = get_appended_values(unit, '_GO_XTEST_SRCS_VALUE')
  133. for f in go_test_files + go_xtest_files:
  134. if not f.endswith('_test.go'):
  135. ymake.report_configure_error(
  136. 'file {} should not be listed in GO_TEST_SRCS() or GO_XTEST_SRCS() macros'.format(f)
  137. )
  138. is_test_module = unit.enabled('GO_TEST_MODULE')
  139. # Add gofmt style checks
  140. if unit.enabled('_GO_FMT_ADD_CHECK'):
  141. resolved_go_files = []
  142. go_source_files = [] if is_test_module and unit.get(['GO_TEST_FOR_DIR']) else go_files
  143. for path in itertools.chain(go_source_files, go_test_files, go_xtest_files):
  144. if path.endswith('.go'):
  145. resolved = unit.resolve_arc_path([path])
  146. if resolved != path and need_lint(resolved):
  147. resolved_go_files.append(resolved)
  148. if resolved_go_files:
  149. basedirs = {}
  150. for f in resolved_go_files:
  151. basedir = os.path.dirname(f)
  152. if basedir not in basedirs:
  153. basedirs[basedir] = []
  154. basedirs[basedir].append(f)
  155. for basedir in basedirs:
  156. unit.onadd_check(['gofmt'] + basedirs[basedir])
  157. unit_path = unit.path()
  158. # Go coverage instrumentation (NOTE! go_files list is modified here)
  159. if is_test_module and unit.enabled('GO_TEST_COVER'):
  160. cover_info = []
  161. for f in go_files:
  162. if f.endswith('_test.go'):
  163. continue
  164. cover_var = 'GoCover' + six.ensure_str(base64.b32encode(six.ensure_binary(f))).rstrip('=')
  165. cover_file = unit.resolve_arc_path(f)
  166. cover_file_output = '{}/{}'.format(unit_path, os.path.basename(f))
  167. unit.on_go_gen_cover_go([cover_file, cover_file_output, cover_var])
  168. if cover_file.startswith('$S/'):
  169. cover_file = arc_project_prefix + cover_file[3:]
  170. cover_info.append('{}:{}'.format(cover_var, cover_file))
  171. # go_files should be empty now since the initial list shouldn't contain
  172. # any non-go or go test file. The value of go_files list will be used later
  173. # to update the value of _GO_SRCS_VALUE
  174. go_files = []
  175. unit.set(['GO_COVER_INFO_VALUE', ' '.join(cover_info)])
  176. # We have cleaned up the list of files from _GO_SRCS_VALUE var and we have to update
  177. # the value since it is used in module command line
  178. unit.set(['_GO_SRCS_VALUE', ' '.join(itertools.chain(go_files, asm_files, syso_files))])
  179. # Add go vet check
  180. if unit.enabled('_GO_VET_ADD_CHECK') and need_lint(unit_path):
  181. vet_report_file_name = os.path.join(unit_path, '{}{}'.format(unit.filename(), unit.get('GO_VET_REPORT_EXT')))
  182. unit.onadd_check(["govet", '$(BUILD_ROOT)/' + tobuilddir(vet_report_file_name)[3:]])
  183. for f in ev_files:
  184. ev_proto_file = '{}.proto'.format(f)
  185. unit.oncopy_file_with_context([f, ev_proto_file])
  186. proto_files.append(ev_proto_file)
  187. # Process .proto files
  188. for f in proto_files:
  189. unit.on_go_proto_cmd(f)
  190. # Process .fbs files
  191. for f in fbs_files:
  192. unit.on_go_flatc_cmd([f, go_package_name(unit)])
  193. # Process .in files
  194. for f in in_files:
  195. unit.onsrc(f)
  196. # Generate .symabis for .s files (starting from 1.12 version)
  197. if len(asm_files) > 0:
  198. symabis_flags = []
  199. gostd_version = unit.get('GOSTD_VERSION')
  200. if compare_versions('1.16', gostd_version) >= 0:
  201. import_path = get_import_path(unit)
  202. symabis_flags.extend(['FLAGS', '-p', import_path])
  203. if need_compiling_runtime(import_path, gostd_version):
  204. symabis_flags.append('-compiling-runtime')
  205. unit.on_go_compile_symabis(asm_files + symabis_flags)
  206. # Process cgo files
  207. cgo_files = get_appended_values(unit, '_CGO_SRCS_VALUE')
  208. cgo_cflags = []
  209. if len(c_files) + len(cxx_files) + len(s_files) + len(cgo_files) > 0:
  210. if is_test_module:
  211. go_test_for_dir = unit.get('GO_TEST_FOR_DIR')
  212. if go_test_for_dir and go_test_for_dir.startswith('$S/'):
  213. unit.onaddincl(['FOR', 'c', go_test_for_dir[3:]])
  214. unit.onaddincl(['FOR', 'c', unit.get('MODDIR')])
  215. cgo_cflags = get_appended_values(unit, 'CGO_CFLAGS_VALUE')
  216. for f in itertools.chain(c_files, cxx_files, s_files):
  217. unit.onsrc([f] + cgo_cflags)
  218. if len(cgo_files) > 0:
  219. if not unit.enabled('CGO_ENABLED'):
  220. ymake.report_configure_error('trying to build with CGO (CGO_SRCS is non-empty) when CGO is disabled')
  221. import_path = get_import_path(unit)
  222. if import_path != runtime_cgo_path:
  223. go_std_root = unit.get('GOSTD')
  224. unit.onpeerdir(os.path.join(go_std_root, runtime_cgo_path))
  225. race_mode = 'race' if unit.enabled('RACE') else 'norace'
  226. import_runtime_cgo = 'false' if import_path in import_runtime_cgo_false[race_mode] else 'true'
  227. import_syscall = 'false' if import_path in import_syscall_false[race_mode] else 'true'
  228. args = (
  229. [import_path]
  230. + cgo_files
  231. + ['FLAGS', '-import_runtime_cgo=' + import_runtime_cgo, '-import_syscall=' + import_syscall]
  232. )
  233. unit.on_go_compile_cgo1(args)
  234. cgo2_cflags = get_appended_values(unit, 'CGO2_CFLAGS_VALUE')
  235. for f in cgo_files:
  236. if f.endswith('.go'):
  237. unit.onsrc([f[:-2] + 'cgo2.c'] + cgo_cflags + cgo2_cflags)
  238. else:
  239. ymake.report_configure_error('file {} should not be listed in CGO_SRCS() macros'.format(f))
  240. args = [go_package_name(unit)] + cgo_files
  241. if len(c_files) > 0:
  242. args += ['C_FILES'] + c_files
  243. if len(s_files) > 0:
  244. args += ['S_FILES'] + s_files
  245. if len(syso_files) > 0:
  246. args += ['OBJ_FILES'] + syso_files
  247. unit.on_go_compile_cgo2(args)
  248. def on_go_resource(unit, *args):
  249. args = list(args)
  250. files = args[::2]
  251. keys = args[1::2]
  252. suffix_md5 = md5(six.ensure_binary('@'.join(args))).hexdigest()
  253. resource_go = os.path.join("resource.{}.res.go".format(suffix_md5))
  254. unit.onpeerdir(["library/go/core/resource"])
  255. if len(files) != len(keys):
  256. ymake.report_configure_error("last file {} is missing resource key".format(files[-1]))
  257. for i, (key, filename) in enumerate(zip(keys, files)):
  258. if not key:
  259. ymake.report_configure_error("file key must be non empty")
  260. return
  261. if filename == "-" and "=" not in key:
  262. ymake.report_configure_error("key \"{}\" must contain = sign".format(key))
  263. return
  264. # quote key, to avoid automatic substitution of filename by absolute
  265. # path in RUN_PROGRAM
  266. args[2 * i + 1] = "notafile" + args[2 * i + 1]
  267. files = [file for file in files if file != "-"]
  268. unit.onrun_program(
  269. ["library/go/core/resource/cc", "-package", go_package_name(unit), "-o", resource_go]
  270. + list(args)
  271. + ["IN"]
  272. + files
  273. + ["OUT", resource_go]
  274. )