genboardscfg.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. 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.insert(1, 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, encoding="utf-8") 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 Kconfig 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.Kconfig(warn=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. self._conf.load_config(self._tmpfile)
  143. try_remove(self._tmpfile)
  144. self._tmpfile = None
  145. params = {}
  146. # Get the value of CONFIG_SYS_ARCH, CONFIG_SYS_CPU, ... etc.
  147. # Set '-' if the value is empty.
  148. for key, symbol in list(self._SYMBOL_TABLE.items()):
  149. value = self._conf.syms.get(symbol).str_value
  150. if value:
  151. params[key] = value
  152. else:
  153. params[key] = '-'
  154. defconfig = os.path.basename(defconfig)
  155. params['target'], match, rear = defconfig.partition('_defconfig')
  156. assert match and not rear, '%s : invalid defconfig' % defconfig
  157. # fix-up for aarch64
  158. if params['arch'] == 'arm' and params['cpu'] == 'armv8':
  159. params['arch'] = 'aarch64'
  160. # fix-up options field. It should have the form:
  161. # <config name>[:comma separated config options]
  162. if params['options'] != '-':
  163. params['options'] = params['config'] + ':' + \
  164. params['options'].replace(r'\"', '"')
  165. elif params['config'] != params['target']:
  166. params['options'] = params['config']
  167. return params
  168. def scan_defconfigs_for_multiprocess(queue, defconfigs):
  169. """Scan defconfig files and queue their board parameters
  170. This function is intended to be passed to
  171. multiprocessing.Process() constructor.
  172. Arguments:
  173. queue: An instance of multiprocessing.Queue().
  174. The resulting board parameters are written into it.
  175. defconfigs: A sequence of defconfig files to be scanned.
  176. """
  177. kconf_scanner = KconfigScanner()
  178. for defconfig in defconfigs:
  179. queue.put(kconf_scanner.scan(defconfig))
  180. def read_queues(queues, params_list):
  181. """Read the queues and append the data to the paramers list"""
  182. for q in queues:
  183. while not q.empty():
  184. params_list.append(q.get())
  185. def scan_defconfigs(jobs=1):
  186. """Collect board parameters for all defconfig files.
  187. This function invokes multiple processes for faster processing.
  188. Arguments:
  189. jobs: The number of jobs to run simultaneously
  190. """
  191. all_defconfigs = []
  192. for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR):
  193. for filename in fnmatch.filter(filenames, '*_defconfig'):
  194. if fnmatch.fnmatch(filename, '.*'):
  195. continue
  196. all_defconfigs.append(os.path.join(dirpath, filename))
  197. total_boards = len(all_defconfigs)
  198. processes = []
  199. queues = []
  200. for i in range(jobs):
  201. defconfigs = all_defconfigs[total_boards * i // jobs :
  202. total_boards * (i + 1) // jobs]
  203. q = multiprocessing.Queue(maxsize=-1)
  204. p = multiprocessing.Process(target=scan_defconfigs_for_multiprocess,
  205. args=(q, defconfigs))
  206. p.start()
  207. processes.append(p)
  208. queues.append(q)
  209. # The resulting data should be accumulated to this list
  210. params_list = []
  211. # Data in the queues should be retrieved preriodically.
  212. # Otherwise, the queues would become full and subprocesses would get stuck.
  213. while any([p.is_alive() for p in processes]):
  214. read_queues(queues, params_list)
  215. # sleep for a while until the queues are filled
  216. time.sleep(SLEEP_TIME)
  217. # Joining subprocesses just in case
  218. # (All subprocesses should already have been finished)
  219. for p in processes:
  220. p.join()
  221. # retrieve leftover data
  222. read_queues(queues, params_list)
  223. return params_list
  224. class MaintainersDatabase:
  225. """The database of board status and maintainers."""
  226. def __init__(self):
  227. """Create an empty database."""
  228. self.database = {}
  229. def get_status(self, target):
  230. """Return the status of the given board.
  231. The board status is generally either 'Active' or 'Orphan'.
  232. Display a warning message and return '-' if status information
  233. is not found.
  234. Returns:
  235. 'Active', 'Orphan' or '-'.
  236. """
  237. if not target in self.database:
  238. print("WARNING: no status info for '%s'" % target, file=sys.stderr)
  239. return '-'
  240. tmp = self.database[target][0]
  241. if tmp.startswith('Maintained'):
  242. return 'Active'
  243. elif tmp.startswith('Supported'):
  244. return 'Active'
  245. elif tmp.startswith('Orphan'):
  246. return 'Orphan'
  247. else:
  248. print(("WARNING: %s: unknown status for '%s'" %
  249. (tmp, target)), file=sys.stderr)
  250. return '-'
  251. def get_maintainers(self, target):
  252. """Return the maintainers of the given board.
  253. Returns:
  254. Maintainers of the board. If the board has two or more maintainers,
  255. they are separated with colons.
  256. """
  257. if not target in self.database:
  258. print("WARNING: no maintainers for '%s'" % target, file=sys.stderr)
  259. return ''
  260. return ':'.join(self.database[target][1])
  261. def parse_file(self, file):
  262. """Parse a MAINTAINERS file.
  263. Parse a MAINTAINERS file and accumulates board status and
  264. maintainers information.
  265. Arguments:
  266. file: MAINTAINERS file to be parsed
  267. """
  268. targets = []
  269. maintainers = []
  270. status = '-'
  271. for line in open(file, encoding="utf-8"):
  272. # Check also commented maintainers
  273. if line[:3] == '#M:':
  274. line = line[1:]
  275. tag, rest = line[:2], line[2:].strip()
  276. if tag == 'M:':
  277. maintainers.append(rest)
  278. elif tag == 'F:':
  279. # expand wildcard and filter by 'configs/*_defconfig'
  280. for f in glob.glob(rest):
  281. front, match, rear = f.partition('configs/')
  282. if not front and match:
  283. front, match, rear = rear.rpartition('_defconfig')
  284. if match and not rear:
  285. targets.append(front)
  286. elif tag == 'S:':
  287. status = rest
  288. elif line == '\n':
  289. for target in targets:
  290. self.database[target] = (status, maintainers)
  291. targets = []
  292. maintainers = []
  293. status = '-'
  294. if targets:
  295. for target in targets:
  296. self.database[target] = (status, maintainers)
  297. def insert_maintainers_info(params_list):
  298. """Add Status and Maintainers information to the board parameters list.
  299. Arguments:
  300. params_list: A list of the board parameters
  301. """
  302. database = MaintainersDatabase()
  303. for (dirpath, dirnames, filenames) in os.walk('.'):
  304. if 'MAINTAINERS' in filenames:
  305. database.parse_file(os.path.join(dirpath, 'MAINTAINERS'))
  306. for i, params in enumerate(params_list):
  307. target = params['target']
  308. params['status'] = database.get_status(target)
  309. params['maintainers'] = database.get_maintainers(target)
  310. params_list[i] = params
  311. def format_and_output(params_list, output):
  312. """Write board parameters into a file.
  313. Columnate the board parameters, sort lines alphabetically,
  314. and then write them to a file.
  315. Arguments:
  316. params_list: The list of board parameters
  317. output: The path to the output file
  318. """
  319. FIELDS = ('status', 'arch', 'cpu', 'soc', 'vendor', 'board', 'target',
  320. 'options', 'maintainers')
  321. # First, decide the width of each column
  322. max_length = dict([ (f, 0) for f in FIELDS])
  323. for params in params_list:
  324. for f in FIELDS:
  325. max_length[f] = max(max_length[f], len(params[f]))
  326. output_lines = []
  327. for params in params_list:
  328. line = ''
  329. for f in FIELDS:
  330. # insert two spaces between fields like column -t would
  331. line += ' ' + params[f].ljust(max_length[f])
  332. output_lines.append(line.strip())
  333. # ignore case when sorting
  334. output_lines.sort(key=str.lower)
  335. with open(output, 'w', encoding="utf-8") as f:
  336. f.write(COMMENT_BLOCK + '\n'.join(output_lines) + '\n')
  337. def gen_boards_cfg(output, jobs=1, force=False):
  338. """Generate a board database file.
  339. Arguments:
  340. output: The name of the output file
  341. jobs: The number of jobs to run simultaneously
  342. force: Force to generate the output even if it is new
  343. """
  344. check_top_directory()
  345. if not force and output_is_new(output):
  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. (options, args) = parser.parse_args()
  365. gen_boards_cfg(options.output, jobs=options.jobs, force=options.force)
  366. if __name__ == '__main__':
  367. main()