build-clang.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #!/usr/bin/python2.7
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. import os
  6. import os.path
  7. import shutil
  8. import subprocess
  9. import platform
  10. import json
  11. import argparse
  12. import tempfile
  13. import glob
  14. import errno
  15. import re
  16. from contextlib import contextmanager
  17. import sys
  18. import which
  19. DEBUG = os.getenv("DEBUG")
  20. def symlink(source, link_name):
  21. os_symlink = getattr(os, "symlink", None)
  22. if callable(os_symlink):
  23. os_symlink(source, link_name)
  24. else:
  25. if os.path.isdir(source):
  26. # Fall back to copying the directory :(
  27. copy_dir_contents(source, link_name)
  28. def check_run(args):
  29. global DEBUG
  30. if DEBUG:
  31. print >> sys.stderr, ' '.join(args)
  32. r = subprocess.call(args)
  33. assert r == 0
  34. def run_in(path, args):
  35. d = os.getcwd()
  36. global DEBUG
  37. if DEBUG:
  38. print >> sys.stderr, 'cd "%s"' % path
  39. os.chdir(path)
  40. check_run(args)
  41. if DEBUG:
  42. print >> sys.stderr, 'cd "%s"' % d
  43. os.chdir(d)
  44. def patch(patch, srcdir):
  45. patch = os.path.realpath(patch)
  46. check_run(['patch', '-d', srcdir, '-p1', '-i', patch, '--fuzz=0',
  47. '-s'])
  48. def build_package(package_build_dir, run_cmake, cmake_args):
  49. if not os.path.exists(package_build_dir):
  50. os.mkdir(package_build_dir)
  51. if run_cmake:
  52. run_in(package_build_dir, ["cmake"] + cmake_args)
  53. run_in(package_build_dir, ["ninja", "install"])
  54. @contextmanager
  55. def updated_env(env):
  56. old_env = os.environ.copy()
  57. os.environ.update(env)
  58. yield
  59. os.environ.clear()
  60. os.environ.update(old_env)
  61. def build_tar_package(tar, name, base, directory):
  62. name = os.path.realpath(name)
  63. # On Windows, we have to convert this into an msys path so that tar can
  64. # understand it.
  65. if is_windows():
  66. name = name.replace('\\', '/')
  67. def f(match):
  68. return '/' + match.group(1).lower()
  69. name = re.sub(r'^([A-Z]):', f, name)
  70. run_in(base, [tar,
  71. "-c",
  72. "-%s" % ("J" if ".xz" in name else "j"),
  73. "-f",
  74. name, directory])
  75. def copy_dir_contents(src, dest):
  76. for f in glob.glob("%s/*" % src):
  77. try:
  78. destname = "%s/%s" % (dest, os.path.basename(f))
  79. if os.path.isdir(f):
  80. shutil.copytree(f, destname)
  81. else:
  82. shutil.copy2(f, destname)
  83. except OSError as e:
  84. if e.errno == errno.ENOTDIR:
  85. shutil.copy2(f, destname)
  86. elif e.errno == errno.EEXIST:
  87. if os.path.isdir(f):
  88. copy_dir_contents(f, destname)
  89. else:
  90. os.remove(destname)
  91. shutil.copy2(f, destname)
  92. else:
  93. raise Exception('Directory not copied. Error: %s' % e)
  94. def mkdir_p(path):
  95. try:
  96. os.makedirs(path)
  97. except OSError as e:
  98. if e.errno != errno.EEXIST or not os.path.isdir(path):
  99. raise
  100. def install_libgcc(gcc_dir, clang_dir):
  101. out = subprocess.check_output([os.path.join(gcc_dir, "bin", "gcc"),
  102. '-print-libgcc-file-name'])
  103. libgcc_dir = os.path.dirname(out.rstrip())
  104. clang_lib_dir = os.path.join(clang_dir, "lib", "gcc",
  105. "x86_64-unknown-linux-gnu",
  106. os.path.basename(libgcc_dir))
  107. mkdir_p(clang_lib_dir)
  108. copy_dir_contents(libgcc_dir, clang_lib_dir)
  109. libgcc_dir = os.path.join(gcc_dir, "lib64")
  110. clang_lib_dir = os.path.join(clang_dir, "lib")
  111. copy_dir_contents(libgcc_dir, clang_lib_dir)
  112. include_dir = os.path.join(gcc_dir, "include")
  113. clang_include_dir = os.path.join(clang_dir, "include")
  114. copy_dir_contents(include_dir, clang_include_dir)
  115. def svn_co(source_dir, url, directory, revision):
  116. run_in(source_dir, ["svn", "co", "-q", "-r", revision, url, directory])
  117. def svn_update(directory, revision):
  118. run_in(directory, ["svn", "update", "-q", "-r", revision])
  119. def get_platform():
  120. p = platform.system()
  121. if p == "Darwin":
  122. return "macosx64"
  123. elif p == "Linux":
  124. if platform.architecture() == "AMD64":
  125. return "linux64"
  126. else:
  127. return "linux32"
  128. elif p == "Windows":
  129. if platform.architecture() == "AMD64":
  130. return "win64"
  131. else:
  132. return "win32"
  133. else:
  134. raise NotImplementedError("Not supported platform")
  135. def is_darwin():
  136. return platform.system() == "Darwin"
  137. def is_linux():
  138. return platform.system() == "Linux"
  139. def is_windows():
  140. return platform.system() == "Windows"
  141. def build_one_stage(cc, cxx, src_dir, stage_dir, build_libcxx,
  142. build_type, assertions, python_path, gcc_dir):
  143. if not os.path.exists(stage_dir):
  144. os.mkdir(stage_dir)
  145. build_dir = stage_dir + "/build"
  146. inst_dir = stage_dir + "/clang"
  147. run_cmake = True
  148. if os.path.exists(build_dir + "/build.ninja"):
  149. run_cmake = False
  150. # cmake doesn't deal well with backslashes in paths.
  151. def slashify_path(path):
  152. return path.replace('\\', '/')
  153. cmake_args = ["-GNinja",
  154. "-DCMAKE_C_COMPILER=%s" % slashify_path(cc[0]),
  155. "-DCMAKE_CXX_COMPILER=%s" % slashify_path(cxx[0]),
  156. "-DCMAKE_ASM_COMPILER=%s" % slashify_path(cc[0]),
  157. "-DCMAKE_C_FLAGS=%s" % ' '.join(cc[1:]),
  158. "-DCMAKE_CXX_FLAGS=%s" % ' '.join(cxx[1:]),
  159. "-DCMAKE_BUILD_TYPE=%s" % build_type,
  160. "-DLLVM_TARGETS_TO_BUILD=X86;ARM",
  161. "-DLLVM_ENABLE_ASSERTIONS=%s" % ("ON" if assertions else "OFF"),
  162. "-DPYTHON_EXECUTABLE=%s" % slashify_path(python_path),
  163. "-DCMAKE_INSTALL_PREFIX=%s" % inst_dir,
  164. "-DLLVM_TOOL_LIBCXX_BUILD=%s" % ("ON" if build_libcxx else "OFF"),
  165. "-DLIBCXX_LIBCPPABI_VERSION=\"\"",
  166. src_dir];
  167. build_package(build_dir, run_cmake, cmake_args)
  168. if is_linux():
  169. install_libgcc(gcc_dir, inst_dir)
  170. def get_compiler(config, key):
  171. if key not in config:
  172. raise ValueError("Config file needs to set %s" % key)
  173. f = config[key]
  174. if os.path.isabs(f):
  175. if not os.path.exists(f):
  176. raise ValueError("%s must point to an existing path" % key)
  177. return f
  178. # Assume that we have the name of some program that should be on PATH.
  179. try:
  180. return which.which(f)
  181. except which.WhichError:
  182. raise ValueError("%s not found on PATH" % f)
  183. if __name__ == "__main__":
  184. # The directories end up in the debug info, so the easy way of getting
  185. # a reproducible build is to run it in a know absolute directory.
  186. # We use a directory in /builds/slave because the mozilla infrastructure
  187. # cleans it up automatically.
  188. base_dir = "/builds/slave/moz-toolchain"
  189. if is_windows():
  190. # TODO: Because Windows taskcluster builds are run with distinct
  191. # user IDs for each job, we can't store things in some globally
  192. # accessible directory: one job will run, checkout LLVM to that
  193. # directory, and then if another job runs, the new user won't be
  194. # able to access the previously-checked out code--or be able to
  195. # delete it. So on Windows, we build in the task-specific home
  196. # directory; we will eventually add -fdebug-prefix-map options
  197. # to the LLVM build to bring back reproducibility.
  198. base_dir = os.path.join(os.getcwd(), 'llvm-sources')
  199. source_dir = base_dir + "/src"
  200. build_dir = base_dir + "/build"
  201. llvm_source_dir = source_dir + "/llvm"
  202. clang_source_dir = source_dir + "/clang"
  203. compiler_rt_source_dir = source_dir + "/compiler-rt"
  204. libcxx_source_dir = source_dir + "/libcxx"
  205. libcxxabi_source_dir = source_dir + "/libcxxabi"
  206. if is_darwin():
  207. os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.7'
  208. exe_ext = ""
  209. if is_windows():
  210. exe_ext = ".exe"
  211. cc_name = "clang"
  212. cxx_name = "clang++"
  213. if is_windows():
  214. cc_name = "clang-cl"
  215. cxx_name = "clang-cl"
  216. parser = argparse.ArgumentParser()
  217. parser.add_argument('-c', '--config', required=True,
  218. type=argparse.FileType('r'),
  219. help="Clang configuration file")
  220. parser.add_argument('--clean', required=False,
  221. action='store_true',
  222. help="Clean the build directory")
  223. args = parser.parse_args()
  224. config = json.load(args.config)
  225. if args.clean:
  226. shutil.rmtree(build_dir)
  227. os.sys.exit(0)
  228. llvm_revision = config["llvm_revision"]
  229. llvm_repo = config["llvm_repo"]
  230. clang_repo = config["clang_repo"]
  231. compiler_repo = config["compiler_repo"]
  232. libcxx_repo = config["libcxx_repo"]
  233. libcxxabi_repo = config.get("libcxxabi_repo")
  234. stages = 3
  235. if "stages" in config:
  236. stages = int(config["stages"])
  237. if stages not in (1, 2, 3):
  238. raise ValueError("We only know how to build 1, 2, or 3 stages")
  239. build_type = "Release"
  240. if "build_type" in config:
  241. build_type = config["build_type"]
  242. if build_type not in ("Release", "Debug", "RelWithDebInfo", "MinSizeRel"):
  243. raise ValueError("We only know how to do Release, Debug, RelWithDebInfo or MinSizeRel builds")
  244. build_libcxx = False
  245. if "build_libcxx" in config:
  246. build_libcxx = config["build_libcxx"]
  247. if build_libcxx not in (True, False):
  248. raise ValueError("Only boolean values are accepted for build_libcxx.")
  249. assertions = False
  250. if "assertions" in config:
  251. assertions = config["assertions"]
  252. if assertions not in (True, False):
  253. raise ValueError("Only boolean values are accepted for assertions.")
  254. python_path = None
  255. if "python_path" not in config:
  256. raise ValueError("Config file needs to set python_path")
  257. python_path = config["python_path"]
  258. gcc_dir = None
  259. if "gcc_dir" in config:
  260. gcc_dir = config["gcc_dir"]
  261. if not os.path.exists(gcc_dir):
  262. raise ValueError("gcc_dir must point to an existing path")
  263. if is_linux() and gcc_dir is None:
  264. raise ValueError("Config file needs to set gcc_dir")
  265. cc = get_compiler(config, "cc")
  266. cxx = get_compiler(config, "cxx")
  267. if not os.path.exists(source_dir):
  268. os.makedirs(source_dir)
  269. svn_co(source_dir, llvm_repo, llvm_source_dir, llvm_revision)
  270. svn_co(source_dir, clang_repo, clang_source_dir, llvm_revision)
  271. svn_co(source_dir, compiler_repo, compiler_rt_source_dir, llvm_revision)
  272. svn_co(source_dir, libcxx_repo, libcxx_source_dir, llvm_revision)
  273. if libcxxabi_repo:
  274. svn_co(source_dir, libcxxabi_repo, libcxxabi_source_dir, llvm_revision)
  275. for p in config.get("patches", {}).get(get_platform(), []):
  276. patch(p, source_dir)
  277. else:
  278. svn_update(llvm_source_dir, llvm_revision)
  279. svn_update(clang_source_dir, llvm_revision)
  280. svn_update(compiler_rt_source_dir, llvm_revision)
  281. svn_update(libcxx_source_dir, llvm_revision)
  282. if libcxxabi_repo:
  283. svn_update(libcxxabi_source_dir, llvm_revision)
  284. symlinks = [(source_dir + "/clang",
  285. llvm_source_dir + "/tools/clang"),
  286. (source_dir + "/compiler-rt",
  287. llvm_source_dir + "/projects/compiler-rt"),
  288. (source_dir + "/libcxx",
  289. llvm_source_dir + "/projects/libcxx"),
  290. (source_dir + "/libcxxabi",
  291. llvm_source_dir + "/projects/libcxxabi")]
  292. for l in symlinks:
  293. # On Windows, we have to re-copy the whole directory every time.
  294. if not is_windows() and os.path.islink(l[1]):
  295. continue
  296. if os.path.isdir(l[1]):
  297. shutil.rmtree(l[1])
  298. elif os.path.exists(l[1]):
  299. os.unlink(l[1])
  300. if os.path.exists(l[0]):
  301. symlink(l[0], l[1])
  302. if not os.path.exists(build_dir):
  303. os.makedirs(build_dir)
  304. stage1_dir = build_dir + '/stage1'
  305. stage1_inst_dir = stage1_dir + '/clang'
  306. final_stage_dir = stage1_dir
  307. if is_darwin():
  308. extra_cflags = []
  309. extra_cxxflags = ["-stdlib=libc++"]
  310. extra_cflags2 = []
  311. extra_cxxflags2 = ["-stdlib=libc++"]
  312. elif is_linux():
  313. extra_cflags = ["-static-libgcc"]
  314. extra_cxxflags = ["-static-libgcc", "-static-libstdc++"]
  315. extra_cflags2 = ["-fPIC"]
  316. extra_cxxflags2 = ["-fPIC", "-static-libstdc++"]
  317. if os.environ.has_key('LD_LIBRARY_PATH'):
  318. os.environ['LD_LIBRARY_PATH'] = '%s/lib64/:%s' % (gcc_dir, os.environ['LD_LIBRARY_PATH']);
  319. else:
  320. os.environ['LD_LIBRARY_PATH'] = '%s/lib64/' % gcc_dir
  321. elif is_windows():
  322. extra_cflags = []
  323. extra_cxxflags = []
  324. # clang-cl would like to figure out what it's supposed to be emulating
  325. # by looking at an MSVC install, but we don't really have that here.
  326. # Force things on.
  327. extra_cflags2 = []
  328. extra_cxxflags2 = ['-fms-compatibility-version=19.00.24213', '-Xclang', '-std=c++14']
  329. build_one_stage(
  330. [cc] + extra_cflags,
  331. [cxx] + extra_cxxflags,
  332. llvm_source_dir, stage1_dir, build_libcxx,
  333. build_type, assertions, python_path, gcc_dir)
  334. if stages > 1:
  335. stage2_dir = build_dir + '/stage2'
  336. stage2_inst_dir = stage2_dir + '/clang'
  337. final_stage_dir = stage2_dir
  338. build_one_stage(
  339. [stage1_inst_dir + "/bin/%s%s" %
  340. (cc_name, exe_ext)] + extra_cflags2,
  341. [stage1_inst_dir + "/bin/%s%s" %
  342. (cxx_name, exe_ext)] + extra_cxxflags2,
  343. llvm_source_dir, stage2_dir, build_libcxx,
  344. build_type, assertions, python_path, gcc_dir)
  345. if stages > 2:
  346. stage3_dir = build_dir + '/stage3'
  347. final_stage_dir = stage3_dir
  348. build_one_stage(
  349. [stage2_inst_dir + "/bin/%s%s" %
  350. (cc_name, exe_ext)] + extra_cflags2,
  351. [stage2_inst_dir + "/bin/%s%s" %
  352. (cxx_name, exe_ext)] + extra_cxxflags2,
  353. llvm_source_dir, stage3_dir, build_libcxx,
  354. build_type, assertions, python_path, gcc_dir)
  355. if is_darwin() or is_windows():
  356. build_tar_package("tar", "clang.tar.bz2", final_stage_dir, "clang")
  357. else:
  358. build_tar_package("tar", "clang.tar.xz", final_stage_dir, "clang")