genboardscfg.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env python2
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Author: Masahiro Yamada <yamada.m@jp.panasonic.com>
  5. #
  6. """
  7. Converter from Kconfig and MAINTAINERS to a board database.
  8. Run 'tools/genboardscfg.py' to create a board database.
  9. Run 'tools/genboardscfg.py -h' for available options.
  10. Python 2.6 or later, but not Python 3.x is necessary to run this script.
  11. """
  12. import errno
  13. import fnmatch
  14. import glob
  15. import multiprocessing
  16. import optparse
  17. import os
  18. import sys
  19. import tempfile
  20. import time
  21. sys.path.append(os.path.join(os.path.dirname(__file__), 'buildman'))
  22. import kconfiglib
  23. ### constant variables ###
  24. OUTPUT_FILE = 'boards.cfg'
  25. CONFIG_DIR = 'configs'
  26. SLEEP_TIME = 0.03
  27. COMMENT_BLOCK = '''#
  28. # List of boards
  29. # Automatically generated by %s: don't edit
  30. #
  31. # Status, Arch, CPU, SoC, Vendor, Board, Target, Options, Maintainers
  32. ''' % __file__
  33. ### helper functions ###
  34. def try_remove(f):
  35. """Remove a file ignoring 'No such file or directory' error."""
  36. try:
  37. os.remove(f)
  38. except OSError as exception:
  39. # Ignore 'No such file or directory' error
  40. if exception.errno != errno.ENOENT:
  41. raise
  42. def check_top_directory():
  43. """Exit if we are not at the top of source directory."""
  44. for f in ('README', 'Licenses'):
  45. if not os.path.exists(f):
  46. sys.exit('Please run at the top of source directory.')
  47. def output_is_new(output):
  48. """Check if the output file is up to date.
  49. Returns:
  50. True if the given output file exists and is newer than any of
  51. *_defconfig, MAINTAINERS and Kconfig*. False otherwise.
  52. """
  53. try:
  54. ctime = os.path.getctime(output)
  55. except OSError as exception:
  56. if exception.errno == errno.ENOENT:
  57. # return False on 'No such file or directory' error
  58. return False
  59. else:
  60. raise
  61. for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR):
  62. for filename in fnmatch.filter(filenames, '*_defconfig'):
  63. if fnmatch.fnmatch(filename, '.*'):
  64. continue
  65. filepath = os.path.join(dirpath, filename)
  66. if ctime < os.path.getctime(filepath):
  67. return False
  68. for (dirpath, dirnames, filenames) in os.walk('.'):
  69. for filename in filenames:
  70. if (fnmatch.fnmatch(filename, '*~') or
  71. not fnmatch.fnmatch(filename, 'Kconfig*') and
  72. not filename == 'MAINTAINERS'):
  73. continue
  74. filepath = os.path.join(dirpath, filename)
  75. if ctime < os.path.getctime(filepath):
  76. return False
  77. # Detect a board that has been removed since the current board database
  78. # was generated
  79. with open(output) as f:
  80. for line in f:
  81. if line[0] == '#' or line == '\n':
  82. continue
  83. defconfig = line.split()[6] + '_defconfig'
  84. if not os.path.exists(os.path.join(CONFIG_DIR, defconfig)):
  85. return False
  86. return True
  87. ### classes ###
  88. class KconfigScanner:
  89. """Kconfig scanner."""
  90. ### constant variable only used in this class ###
  91. _SYMBOL_TABLE = {
  92. 'arch' : 'SYS_ARCH',
  93. 'cpu' : 'SYS_CPU',
  94. 'soc' : 'SYS_SOC',
  95. 'vendor' : 'SYS_VENDOR',
  96. 'board' : 'SYS_BOARD',
  97. 'config' : 'SYS_CONFIG_NAME',
  98. 'options' : 'SYS_EXTRA_OPTIONS'
  99. }
  100. def __init__(self):
  101. """Scan all the Kconfig files and create a Config object."""
  102. # Define environment variables referenced from Kconfig
  103. os.environ['srctree'] = os.getcwd()
  104. os.environ['UBOOTVERSION'] = 'dummy'
  105. os.environ['KCONFIG_OBJDIR'] = ''
  106. self._conf = kconfiglib.Config(print_warnings=False)
  107. def __del__(self):
  108. """Delete a leftover temporary file before exit.
  109. The scan() method of this class creates a temporay file and deletes
  110. it on success. If scan() method throws an exception on the way,
  111. the temporary file might be left over. In that case, it should be
  112. deleted in this destructor.
  113. """
  114. if hasattr(self, '_tmpfile') and self._tmpfile:
  115. try_remove(self._tmpfile)
  116. def scan(self, defconfig):
  117. """Load a defconfig file to obtain board parameters.
  118. Arguments:
  119. defconfig: path to the defconfig file to be processed
  120. Returns:
  121. A dictionary of board parameters. It has a form of:
  122. {
  123. 'arch': <arch_name>,
  124. 'cpu': <cpu_name>,
  125. 'soc': <soc_name>,
  126. 'vendor': <vendor_name>,
  127. 'board': <board_name>,
  128. 'target': <target_name>,
  129. 'config': <config_header_name>,
  130. 'options': <extra_options>
  131. }
  132. """
  133. # strip special prefixes and save it in a temporary file
  134. fd, self._tmpfile = tempfile.mkstemp()
  135. with os.fdopen(fd, 'w') as f:
  136. for line in open(defconfig):
  137. colon = line.find(':CONFIG_')
  138. if colon == -1:
  139. f.write(line)
  140. else:
  141. f.write(line[colon + 1:])
  142. warnings = self._conf.load_config(self._tmpfile)
  143. if warnings:
  144. for warning in warnings:
  145. print '%s: %s' % (defconfig, warning)
  146. try_remove(self._tmpfile)
  147. self._tmpfile = None
  148. params = {}
  149. # Get the value of CONFIG_SYS_ARCH, CONFIG_SYS_CPU, ... etc.
  150. # Set '-' if the value is empty.
  151. for key, symbol in self._SYMBOL_TABLE.items():
  152. value = self._conf.get_symbol(symbol).get_value()
  153. if value:
  154. params[key] = value
  155. else:
  156. params[key] = '-'
  157. defconfig = os.path.basename(defconfig)
  158. params['target'], match, rear = defconfig.partition('_defconfig')
  159. assert match and not rear, '%s : invalid defconfig' % defconfig
  160. # fix-up for aarch64
  161. if params['arch'] == 'arm' and params['cpu'] == 'armv8':
  162. params['arch'] = 'aarch64'
  163. # fix-up options field. It should have the form:
  164. # <config name>[:comma separated config options]
  165. if params['options'] != '-':
  166. params['options'] = params['config'] + ':' + \
  167. params['options'].replace(r'\"', '"')
  168. elif params['config'] != params['target']:
  169. params['options'] = params['config']
  170. return params
  171. def scan_defconfigs_for_multiprocess(queue, defconfigs):
  172. """Scan defconfig files and queue their board parameters
  173. This function is intended to be passed to
  174. multiprocessing.Process() constructor.
  175. Arguments:
  176. queue: An instance of multiprocessing.Queue().
  177. The resulting board parameters are written into it.
  178. defconfigs: A sequence of defconfig files to be scanned.
  179. """
  180. kconf_scanner = KconfigScanner()
  181. for defconfig in defconfigs:
  182. queue.put(kconf_scanner.scan(defconfig))
  183. def read_queues(queues, params_list):
  184. """Read the queues and append the data to the paramers list"""
  185. for q in queues:
  186. while not q.empty():
  187. params_list.append(q.get())
  188. def scan_defconfigs(jobs=1):
  189. """Collect board parameters for all defconfig files.
  190. This function invokes multiple processes for faster processing.
  191. Arguments:
  192. jobs: The number of jobs to run simultaneously
  193. """
  194. all_defconfigs = []
  195. for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR):
  196. for filename in fnmatch.filter(filenames, '*_defconfig'):
  197. if fnmatch.fnmatch(filename, '.*'):
  198. continue
  199. all_defconfigs.append(os.path.join(dirpath, filename))
  200. total_boards = len(all_defconfigs)
  201. processes = []
  202. queues = []
  203. for i in range(jobs):
  204. defconfigs = all_defconfigs[total_boards * i / jobs :
  205. total_boards * (i + 1) / jobs]
  206. q = multiprocessing.Queue(maxsize=-1)
  207. p = multiprocessing.Process(target=scan_defconfigs_for_multiprocess,
  208. args=(q, defconfigs))
  209. p.start()
  210. processes.append(p)
  211. queues.append(q)
  212. # The resulting data should be accumulated to this list
  213. params_list = []
  214. # Data in the queues should be retrieved preriodically.
  215. # Otherwise, the queues would become full and subprocesses would get stuck.
  216. while any([p.is_alive() for p in processes]):
  217. read_queues(queues, params_list)
  218. # sleep for a while until the queues are filled
  219. time.sleep(SLEEP_TIME)
  220. # Joining subprocesses just in case
  221. # (All subprocesses should already have been finished)
  222. for p in processes:
  223. p.join()
  224. # retrieve leftover data
  225. read_queues(queues, params_list)
  226. return params_list
  227. class MaintainersDatabase:
  228. """The database of board status and maintainers."""
  229. def __init__(self):
  230. """Create an empty database."""
  231. self.database = {}
  232. def get_status(self, target):
  233. """Return the status of the given board.
  234. The board status is generally either 'Active' or 'Orphan'.
  235. Display a warning message and return '-' if status information
  236. is not found.
  237. Returns:
  238. 'Active', 'Orphan' or '-'.
  239. """
  240. if not target in self.database:
  241. print >> sys.stderr, "WARNING: no status info for '%s'" % target
  242. return '-'
  243. tmp = self.database[target][0]
  244. if tmp.startswith('Maintained'):
  245. return 'Active'
  246. elif tmp.startswith('Supported'):
  247. return 'Active'
  248. elif tmp.startswith('Orphan'):
  249. return 'Orphan'
  250. else:
  251. print >> sys.stderr, ("WARNING: %s: unknown status for '%s'" %
  252. (tmp, target))
  253. return '-'
  254. def get_maintainers(self, target):
  255. """Return the maintainers of the given board.
  256. Returns:
  257. Maintainers of the board. If the board has two or more maintainers,
  258. they are separated with colons.
  259. """
  260. if not target in self.database:
  261. print >> sys.stderr, "WARNING: no maintainers for '%s'" % target
  262. return ''
  263. return ':'.join(self.database[target][1])
  264. def parse_file(self, file):
  265. """Parse a MAINTAINERS file.
  266. Parse a MAINTAINERS file and accumulates board status and
  267. maintainers information.
  268. Arguments:
  269. file: MAINTAINERS file to be parsed
  270. """
  271. targets = []
  272. maintainers = []
  273. status = '-'
  274. for line in open(file):
  275. # Check also commented maintainers
  276. if line[:3] == '#M:':
  277. line = line[1:]
  278. tag, rest = line[:2], line[2:].strip()
  279. if tag == 'M:':
  280. maintainers.append(rest)
  281. elif tag == 'F:':
  282. # expand wildcard and filter by 'configs/*_defconfig'
  283. for f in glob.glob(rest):
  284. front, match, rear = f.partition('configs/')
  285. if not front and match:
  286. front, match, rear = rear.rpartition('_defconfig')
  287. if match and not rear:
  288. targets.append(front)
  289. elif tag == 'S:':
  290. status = rest
  291. elif line == '\n':
  292. for target in targets:
  293. self.database[target] = (status, maintainers)
  294. targets = []
  295. maintainers = []
  296. status = '-'
  297. if targets:
  298. for target in targets:
  299. self.database[target] = (status, maintainers)
  300. def insert_maintainers_info(params_list):
  301. """Add Status and Maintainers information to the board parameters list.
  302. Arguments:
  303. params_list: A list of the board parameters
  304. """
  305. database = MaintainersDatabase()
  306. for (dirpath, dirnames, filenames) in os.walk('.'):
  307. if 'MAINTAINERS' in filenames:
  308. database.parse_file(os.path.join(dirpath, 'MAINTAINERS'))
  309. for i, params in enumerate(params_list):
  310. target = params['target']
  311. params['status'] = database.get_status(target)
  312. params['maintainers'] = database.get_maintainers(target)
  313. params_list[i] = params
  314. def format_and_output(params_list, output):
  315. """Write board parameters into a file.
  316. Columnate the board parameters, sort lines alphabetically,
  317. and then write them to a file.
  318. Arguments:
  319. params_list: The list of board parameters
  320. output: The path to the output file
  321. """
  322. FIELDS = ('status', 'arch', 'cpu', 'soc', 'vendor', 'board', 'target',
  323. 'options', 'maintainers')
  324. # First, decide the width of each column
  325. max_length = dict([ (f, 0) for f in FIELDS])
  326. for params in params_list:
  327. for f in FIELDS:
  328. max_length[f] = max(max_length[f], len(params[f]))
  329. output_lines = []
  330. for params in params_list:
  331. line = ''
  332. for f in FIELDS:
  333. # insert two spaces between fields like column -t would
  334. line += ' ' + params[f].ljust(max_length[f])
  335. output_lines.append(line.strip())
  336. # ignore case when sorting
  337. output_lines.sort(key=str.lower)
  338. with open(output, 'w') as f:
  339. f.write(COMMENT_BLOCK + '\n'.join(output_lines) + '\n')
  340. def gen_boards_cfg(output, jobs=1, force=False):
  341. """Generate a board database file.
  342. Arguments:
  343. output: The name of the output file
  344. jobs: The number of jobs to run simultaneously
  345. force: Force to generate the output even if it is new
  346. """
  347. check_top_directory()
  348. if not force and output_is_new(output):
  349. print "%s is up to date. Nothing to do." % output
  350. sys.exit(0)
  351. params_list = scan_defconfigs(jobs)
  352. insert_maintainers_info(params_list)
  353. format_and_output(params_list, output)
  354. def main():
  355. try:
  356. cpu_count = multiprocessing.cpu_count()
  357. except NotImplementedError:
  358. cpu_count = 1
  359. parser = optparse.OptionParser()
  360. # Add options here
  361. parser.add_option('-f', '--force', action="store_true", default=False,
  362. help='regenerate the output even if it is new')
  363. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  364. help='the number of jobs to run simultaneously')
  365. parser.add_option('-o', '--output', default=OUTPUT_FILE,
  366. help='output file [default=%s]' % OUTPUT_FILE)
  367. (options, args) = parser.parse_args()
  368. gen_boards_cfg(options.output, jobs=options.jobs, force=options.force)
  369. if __name__ == '__main__':
  370. main()