javaw.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2006-2018 (ita)
  4. """
  5. Java support
  6. Javac is one of the few compilers that behaves very badly:
  7. #. it outputs files where it wants to (-d is only for the package root)
  8. #. it recompiles files silently behind your back
  9. #. it outputs an undefined amount of files (inner classes)
  10. Remember that the compilation can be performed using Jython[1] rather than regular Python. Instead of
  11. running one of the following commands::
  12. ./waf configure
  13. python waf configure
  14. You would have to run::
  15. java -jar /path/to/jython.jar waf configure
  16. [1] http://www.jython.org/
  17. Usage
  18. =====
  19. Load the "java" tool.
  20. def configure(conf):
  21. conf.load('java')
  22. Java tools will be autodetected and eventually, if present, the quite
  23. standard JAVA_HOME environment variable will be used. The also standard
  24. CLASSPATH variable is used for library searching.
  25. In configuration phase checks can be done on the system environment, for
  26. example to check if a class is known in the classpath::
  27. conf.check_java_class('java.io.FileOutputStream')
  28. or if the system supports JNI applications building::
  29. conf.check_jni_headers()
  30. The java tool supports compiling java code, creating jar files and
  31. creating javadoc documentation. This can be either done separately or
  32. together in a single definition. For example to manage them separately::
  33. bld(features = 'javac',
  34. srcdir = 'src',
  35. compat = '1.7',
  36. use = 'animals',
  37. name = 'cats-src',
  38. )
  39. bld(features = 'jar',
  40. basedir = '.',
  41. destfile = '../cats.jar',
  42. name = 'cats',
  43. use = 'cats-src'
  44. )
  45. Or together by defining all the needed attributes::
  46. bld(features = 'javac jar javadoc',
  47. srcdir = 'src/', # folder containing the sources to compile
  48. outdir = 'src', # folder where to output the classes (in the build directory)
  49. compat = '1.6', # java compatibility version number
  50. classpath = ['.', '..'],
  51. # jar
  52. basedir = 'src', # folder containing the classes and other files to package (must match outdir)
  53. destfile = 'foo.jar', # do not put the destfile in the folder of the java classes!
  54. use = 'NNN',
  55. jaropts = ['-C', 'default/src/', '.'], # can be used to give files
  56. manifest = 'src/Manifest.mf', # Manifest file to include
  57. # javadoc
  58. javadoc_package = ['com.meow' , 'com.meow.truc.bar', 'com.meow.truc.foo'],
  59. javadoc_output = 'javadoc',
  60. )
  61. External jar dependencies can be mapped to a standard waf "use" dependency by
  62. setting an environment variable with a CLASSPATH prefix in the configuration,
  63. for example::
  64. conf.env.CLASSPATH_NNN = ['aaaa.jar', 'bbbb.jar']
  65. and then NNN can be freely used in rules as::
  66. use = 'NNN',
  67. In the java tool the dependencies via use are not transitive by default, as
  68. this necessity depends on the code. To enable recursive dependency scanning
  69. use on a specific rule:
  70. recurse_use = True
  71. Or build-wise by setting RECURSE_JAVA:
  72. bld.env.RECURSE_JAVA = True
  73. Unit tests can be integrated in the waf unit test environment using the javatest extra.
  74. """
  75. import os, shutil
  76. from waflib import Task, Utils, Errors, Node
  77. from waflib.Configure import conf
  78. from waflib.TaskGen import feature, before_method, after_method, taskgen_method
  79. from waflib.Tools import ccroot
  80. ccroot.USELIB_VARS['javac'] = set(['CLASSPATH', 'JAVACFLAGS'])
  81. SOURCE_RE = '**/*.java'
  82. JAR_RE = '**/*'
  83. class_check_source = '''
  84. public class Test {
  85. public static void main(String[] argv) {
  86. Class lib;
  87. if (argv.length < 1) {
  88. System.err.println("Missing argument");
  89. System.exit(77);
  90. }
  91. try {
  92. lib = Class.forName(argv[0]);
  93. } catch (ClassNotFoundException e) {
  94. System.err.println("ClassNotFoundException");
  95. System.exit(1);
  96. }
  97. lib = null;
  98. System.exit(0);
  99. }
  100. }
  101. '''
  102. @feature('javac')
  103. @before_method('process_source')
  104. def apply_java(self):
  105. """
  106. Create a javac task for compiling *.java files*. There can be
  107. only one javac task by task generator.
  108. """
  109. Utils.def_attrs(self, jarname='', classpath='',
  110. sourcepath='.', srcdir='.',
  111. jar_mf_attributes={}, jar_mf_classpath=[])
  112. outdir = getattr(self, 'outdir', None)
  113. if outdir:
  114. if not isinstance(outdir, Node.Node):
  115. outdir = self.path.get_bld().make_node(self.outdir)
  116. else:
  117. outdir = self.path.get_bld()
  118. outdir.mkdir()
  119. self.outdir = outdir
  120. self.env.OUTDIR = outdir.abspath()
  121. self.javac_task = tsk = self.create_task('javac')
  122. tmp = []
  123. srcdir = getattr(self, 'srcdir', '')
  124. if isinstance(srcdir, Node.Node):
  125. srcdir = [srcdir]
  126. for x in Utils.to_list(srcdir):
  127. if isinstance(x, Node.Node):
  128. y = x
  129. else:
  130. y = self.path.find_dir(x)
  131. if not y:
  132. self.bld.fatal('Could not find the folder %s from %s' % (x, self.path))
  133. tmp.append(y)
  134. tsk.srcdir = tmp
  135. if getattr(self, 'compat', None):
  136. tsk.env.append_value('JAVACFLAGS', ['-source', str(self.compat)])
  137. if hasattr(self, 'sourcepath'):
  138. fold = [isinstance(x, Node.Node) and x or self.path.find_dir(x) for x in self.to_list(self.sourcepath)]
  139. names = os.pathsep.join([x.srcpath() for x in fold])
  140. else:
  141. names = [x.srcpath() for x in tsk.srcdir]
  142. if names:
  143. tsk.env.append_value('JAVACFLAGS', ['-sourcepath', names])
  144. @taskgen_method
  145. def java_use_rec(self, name, **kw):
  146. """
  147. Processes recursively the *use* attribute for each referred java compilation
  148. """
  149. if name in self.tmp_use_seen:
  150. return
  151. self.tmp_use_seen.append(name)
  152. try:
  153. y = self.bld.get_tgen_by_name(name)
  154. except Errors.WafError:
  155. self.uselib.append(name)
  156. return
  157. else:
  158. y.post()
  159. # Add generated JAR name for CLASSPATH. Task ordering (set_run_after)
  160. # is already guaranteed by ordering done between the single tasks
  161. if hasattr(y, 'jar_task'):
  162. self.use_lst.append(y.jar_task.outputs[0].abspath())
  163. else:
  164. if hasattr(y,'outdir'):
  165. self.use_lst.append(y.outdir.abspath())
  166. else:
  167. self.use_lst.append(y.path.get_bld().abspath())
  168. for x in self.to_list(getattr(y, 'use', [])):
  169. self.java_use_rec(x)
  170. @feature('javac')
  171. @before_method('propagate_uselib_vars')
  172. @after_method('apply_java')
  173. def use_javac_files(self):
  174. """
  175. Processes the *use* attribute referring to other java compilations
  176. """
  177. self.use_lst = []
  178. self.tmp_use_seen = []
  179. self.uselib = self.to_list(getattr(self, 'uselib', []))
  180. names = self.to_list(getattr(self, 'use', []))
  181. get = self.bld.get_tgen_by_name
  182. for x in names:
  183. try:
  184. tg = get(x)
  185. except Errors.WafError:
  186. self.uselib.append(x)
  187. else:
  188. tg.post()
  189. if hasattr(tg, 'jar_task'):
  190. self.use_lst.append(tg.jar_task.outputs[0].abspath())
  191. self.javac_task.set_run_after(tg.jar_task)
  192. self.javac_task.dep_nodes.extend(tg.jar_task.outputs)
  193. else:
  194. if hasattr(tg, 'outdir'):
  195. base_node = tg.outdir
  196. else:
  197. base_node = tg.path.get_bld()
  198. self.use_lst.append(base_node.abspath())
  199. self.javac_task.dep_nodes.extend([dx for dx in base_node.ant_glob(JAR_RE, remove=False, quiet=True)])
  200. for tsk in tg.tasks:
  201. self.javac_task.set_run_after(tsk)
  202. # If recurse use scan is enabled recursively add use attribute for each used one
  203. if getattr(self, 'recurse_use', False) or self.bld.env.RECURSE_JAVA:
  204. self.java_use_rec(x)
  205. self.env.prepend_value('CLASSPATH', self.use_lst)
  206. @feature('javac')
  207. @after_method('apply_java', 'propagate_uselib_vars', 'use_javac_files')
  208. def set_classpath(self):
  209. """
  210. Sets the CLASSPATH value on the *javac* task previously created.
  211. """
  212. if getattr(self, 'classpath', None):
  213. self.env.append_unique('CLASSPATH', getattr(self, 'classpath', []))
  214. for x in self.tasks:
  215. x.env.CLASSPATH = os.pathsep.join(self.env.CLASSPATH) + os.pathsep
  216. @feature('jar')
  217. @after_method('apply_java', 'use_javac_files')
  218. @before_method('process_source')
  219. def jar_files(self):
  220. """
  221. Creates a jar task (one maximum per task generator)
  222. """
  223. destfile = getattr(self, 'destfile', 'test.jar')
  224. jaropts = getattr(self, 'jaropts', [])
  225. manifest = getattr(self, 'manifest', None)
  226. basedir = getattr(self, 'basedir', None)
  227. if basedir:
  228. if not isinstance(self.basedir, Node.Node):
  229. basedir = self.path.get_bld().make_node(basedir)
  230. else:
  231. basedir = self.path.get_bld()
  232. if not basedir:
  233. self.bld.fatal('Could not find the basedir %r for %r' % (self.basedir, self))
  234. self.jar_task = tsk = self.create_task('jar_create')
  235. if manifest:
  236. jarcreate = getattr(self, 'jarcreate', 'cfm')
  237. if not isinstance(manifest,Node.Node):
  238. node = self.path.find_resource(manifest)
  239. else:
  240. node = manifest
  241. if not node:
  242. self.bld.fatal('invalid manifest file %r for %r' % (manifest, self))
  243. tsk.dep_nodes.append(node)
  244. jaropts.insert(0, node.abspath())
  245. else:
  246. jarcreate = getattr(self, 'jarcreate', 'cf')
  247. if not isinstance(destfile, Node.Node):
  248. destfile = self.path.find_or_declare(destfile)
  249. if not destfile:
  250. self.bld.fatal('invalid destfile %r for %r' % (destfile, self))
  251. tsk.set_outputs(destfile)
  252. tsk.basedir = basedir
  253. jaropts.append('-C')
  254. jaropts.append(basedir.bldpath())
  255. jaropts.append('.')
  256. tsk.env.JAROPTS = jaropts
  257. tsk.env.JARCREATE = jarcreate
  258. if getattr(self, 'javac_task', None):
  259. tsk.set_run_after(self.javac_task)
  260. @feature('jar')
  261. @after_method('jar_files')
  262. def use_jar_files(self):
  263. """
  264. Processes the *use* attribute to set the build order on the
  265. tasks created by another task generator.
  266. """
  267. self.uselib = self.to_list(getattr(self, 'uselib', []))
  268. names = self.to_list(getattr(self, 'use', []))
  269. get = self.bld.get_tgen_by_name
  270. for x in names:
  271. try:
  272. y = get(x)
  273. except Errors.WafError:
  274. self.uselib.append(x)
  275. else:
  276. y.post()
  277. self.jar_task.run_after.update(y.tasks)
  278. class JTask(Task.Task):
  279. """
  280. Base class for java and jar tasks; provides functionality to run long commands
  281. """
  282. def split_argfile(self, cmd):
  283. inline = [cmd[0]]
  284. infile = []
  285. for x in cmd[1:]:
  286. # jar and javac do not want -J flags in @file
  287. if x.startswith('-J'):
  288. inline.append(x)
  289. else:
  290. infile.append(self.quote_flag(x))
  291. return (inline, infile)
  292. class jar_create(JTask):
  293. """
  294. Creates a jar file
  295. """
  296. color = 'GREEN'
  297. run_str = '${JAR} ${JARCREATE} ${TGT} ${JAROPTS}'
  298. def runnable_status(self):
  299. """
  300. Wait for dependent tasks to be executed, then read the
  301. files to update the list of inputs.
  302. """
  303. for t in self.run_after:
  304. if not t.hasrun:
  305. return Task.ASK_LATER
  306. if not self.inputs:
  307. try:
  308. self.inputs = [x for x in self.basedir.ant_glob(JAR_RE, remove=False, quiet=True) if id(x) != id(self.outputs[0])]
  309. except Exception:
  310. raise Errors.WafError('Could not find the basedir %r for %r' % (self.basedir, self))
  311. return super(jar_create, self).runnable_status()
  312. class javac(JTask):
  313. """
  314. Compiles java files
  315. """
  316. color = 'BLUE'
  317. run_str = '${JAVAC} -classpath ${CLASSPATH} -d ${OUTDIR} ${JAVACFLAGS} ${SRC}'
  318. vars = ['CLASSPATH', 'JAVACFLAGS', 'JAVAC', 'OUTDIR']
  319. """
  320. The javac task will be executed again if the variables CLASSPATH, JAVACFLAGS, JAVAC or OUTDIR change.
  321. """
  322. def uid(self):
  323. """Identify java tasks by input&output folder"""
  324. lst = [self.__class__.__name__, self.generator.outdir.abspath()]
  325. for x in self.srcdir:
  326. lst.append(x.abspath())
  327. return Utils.h_list(lst)
  328. def runnable_status(self):
  329. """
  330. Waits for dependent tasks to be complete, then read the file system to find the input nodes.
  331. """
  332. for t in self.run_after:
  333. if not t.hasrun:
  334. return Task.ASK_LATER
  335. if not self.inputs:
  336. self.inputs = []
  337. for x in self.srcdir:
  338. if x.exists():
  339. self.inputs.extend(x.ant_glob(SOURCE_RE, remove=False, quiet=True))
  340. return super(javac, self).runnable_status()
  341. def post_run(self):
  342. """
  343. List class files created
  344. """
  345. for node in self.generator.outdir.ant_glob('**/*.class', quiet=True):
  346. self.generator.bld.node_sigs[node] = self.uid()
  347. self.generator.bld.task_sigs[self.uid()] = self.cache_sig
  348. @feature('javadoc')
  349. @after_method('process_rule')
  350. def create_javadoc(self):
  351. """
  352. Creates a javadoc task (feature 'javadoc')
  353. """
  354. tsk = self.create_task('javadoc')
  355. tsk.classpath = getattr(self, 'classpath', [])
  356. self.javadoc_package = Utils.to_list(self.javadoc_package)
  357. if not isinstance(self.javadoc_output, Node.Node):
  358. self.javadoc_output = self.bld.path.find_or_declare(self.javadoc_output)
  359. class javadoc(Task.Task):
  360. """
  361. Builds java documentation
  362. """
  363. color = 'BLUE'
  364. def __str__(self):
  365. return '%s: %s -> %s\n' % (self.__class__.__name__, self.generator.srcdir, self.generator.javadoc_output)
  366. def run(self):
  367. env = self.env
  368. bld = self.generator.bld
  369. wd = bld.bldnode
  370. #add src node + bld node (for generated java code)
  371. srcpath = self.generator.path.abspath() + os.sep + self.generator.srcdir
  372. srcpath += os.pathsep
  373. srcpath += self.generator.path.get_bld().abspath() + os.sep + self.generator.srcdir
  374. classpath = env.CLASSPATH
  375. classpath += os.pathsep
  376. classpath += os.pathsep.join(self.classpath)
  377. classpath = "".join(classpath)
  378. self.last_cmd = lst = []
  379. lst.extend(Utils.to_list(env.JAVADOC))
  380. lst.extend(['-d', self.generator.javadoc_output.abspath()])
  381. lst.extend(['-sourcepath', srcpath])
  382. lst.extend(['-classpath', classpath])
  383. lst.extend(['-subpackages'])
  384. lst.extend(self.generator.javadoc_package)
  385. lst = [x for x in lst if x]
  386. self.generator.bld.cmd_and_log(lst, cwd=wd, env=env.env or None, quiet=0)
  387. def post_run(self):
  388. nodes = self.generator.javadoc_output.ant_glob('**', quiet=True)
  389. for node in nodes:
  390. self.generator.bld.node_sigs[node] = self.uid()
  391. self.generator.bld.task_sigs[self.uid()] = self.cache_sig
  392. def configure(self):
  393. """
  394. Detects the javac, java and jar programs
  395. """
  396. # If JAVA_PATH is set, we prepend it to the path list
  397. java_path = self.environ['PATH'].split(os.pathsep)
  398. v = self.env
  399. if 'JAVA_HOME' in self.environ:
  400. java_path = [os.path.join(self.environ['JAVA_HOME'], 'bin')] + java_path
  401. self.env.JAVA_HOME = [self.environ['JAVA_HOME']]
  402. for x in 'javac java jar javadoc'.split():
  403. self.find_program(x, var=x.upper(), path_list=java_path, mandatory=(x not in ('javadoc')))
  404. if not self.env.JAVA_HOME:
  405. # needed for jni
  406. if self.env.JAVAC and len(Utils.to_list(self.env.JAVAC)) == 1:
  407. # heuristic to find the correct JAVA_HOME
  408. javac_path = Utils.to_list(self.env.JAVAC)[0]
  409. java_dir = os.path.dirname(os.path.dirname(os.path.realpath(javac_path)))
  410. if os.path.exists(os.path.join(java_dir, 'lib')):
  411. self.env.JAVA_HOME = [java_dir]
  412. if 'CLASSPATH' in self.environ:
  413. v.CLASSPATH = self.environ['CLASSPATH']
  414. if not v.JAR:
  415. self.fatal('jar is required for making java packages')
  416. if not v.JAVAC:
  417. self.fatal('javac is required for compiling java classes')
  418. v.JARCREATE = 'cf' # can use cvf
  419. v.JAVACFLAGS = []
  420. @conf
  421. def check_java_class(self, classname, with_classpath=None):
  422. """
  423. Checks if the specified java class exists
  424. :param classname: class to check, like java.util.HashMap
  425. :type classname: string
  426. :param with_classpath: additional classpath to give
  427. :type with_classpath: string
  428. """
  429. javatestdir = '.waf-javatest'
  430. classpath = javatestdir
  431. if self.env.CLASSPATH:
  432. classpath += os.pathsep + self.env.CLASSPATH
  433. if isinstance(with_classpath, str):
  434. classpath += os.pathsep + with_classpath
  435. shutil.rmtree(javatestdir, True)
  436. os.mkdir(javatestdir)
  437. Utils.writef(os.path.join(javatestdir, 'Test.java'), class_check_source)
  438. # Compile the source
  439. self.exec_command(self.env.JAVAC + [os.path.join(javatestdir, 'Test.java')], shell=False)
  440. # Try to run the app
  441. cmd = self.env.JAVA + ['-cp', classpath, 'Test', classname]
  442. self.to_log("%s\n" % str(cmd))
  443. found = self.exec_command(cmd, shell=False)
  444. self.msg('Checking for java class %s' % classname, not found)
  445. shutil.rmtree(javatestdir, True)
  446. return found
  447. @conf
  448. def check_jni_headers(conf):
  449. """
  450. Checks for jni headers and libraries. On success the conf.env variables xxx_JAVA are added for use in C/C++ targets::
  451. def options(opt):
  452. opt.load('compiler_c')
  453. def configure(conf):
  454. conf.load('compiler_c java')
  455. conf.check_jni_headers()
  456. def build(bld):
  457. bld.shlib(source='a.c', target='app', use='JAVA')
  458. """
  459. if not conf.env.CC_NAME and not conf.env.CXX_NAME:
  460. conf.fatal('load a compiler first (gcc, g++, ..)')
  461. if not conf.env.JAVA_HOME:
  462. conf.fatal('set JAVA_HOME in the system environment')
  463. # jni requires the jvm
  464. javaHome = conf.env.JAVA_HOME[0]
  465. dir = conf.root.find_dir(conf.env.JAVA_HOME[0] + '/include')
  466. if dir is None:
  467. dir = conf.root.find_dir(conf.env.JAVA_HOME[0] + '/../Headers') # think different?!
  468. if dir is None:
  469. conf.fatal('JAVA_HOME does not seem to be set properly')
  470. f = dir.ant_glob('**/(jni|jni_md).h')
  471. incDirs = [x.parent.abspath() for x in f]
  472. dir = conf.root.find_dir(conf.env.JAVA_HOME[0])
  473. f = dir.ant_glob('**/*jvm.(so|dll|dylib)')
  474. libDirs = [x.parent.abspath() for x in f] or [javaHome]
  475. # On windows, we need both the .dll and .lib to link. On my JDK, they are
  476. # in different directories...
  477. f = dir.ant_glob('**/*jvm.(lib)')
  478. if f:
  479. libDirs = [[x, y.parent.abspath()] for x in libDirs for y in f]
  480. if conf.env.DEST_OS == 'freebsd':
  481. conf.env.append_unique('LINKFLAGS_JAVA', '-pthread')
  482. for d in libDirs:
  483. try:
  484. conf.check(header_name='jni.h', define_name='HAVE_JNI_H', lib='jvm',
  485. libpath=d, includes=incDirs, uselib_store='JAVA', uselib='JAVA')
  486. except Exception:
  487. pass
  488. else:
  489. break
  490. else:
  491. conf.fatal('could not find lib jvm in %r (see config.log)' % libDirs)