genboardscfg.py 14 KB

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