genboardscfg.py 14 KB

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