genboardscfg.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/env python
  2. #
  3. # Author: Masahiro Yamada <yamada.m@jp.panasonic.com>
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. """
  8. Converter from Kconfig and MAINTAINERS to boards.cfg
  9. Run 'tools/genboardscfg.py' to create boards.cfg file.
  10. Run 'tools/genboardscfg.py -h' for available options.
  11. """
  12. import errno
  13. import fnmatch
  14. import glob
  15. import optparse
  16. import os
  17. import re
  18. import shutil
  19. import subprocess
  20. import sys
  21. import tempfile
  22. import time
  23. BOARD_FILE = 'boards.cfg'
  24. CONFIG_DIR = 'configs'
  25. REFORMAT_CMD = [os.path.join('tools', 'reformat.py'),
  26. '-i', '-d', '-', '-s', '8']
  27. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  28. SLEEP_TIME=0.03
  29. COMMENT_BLOCK = '''#
  30. # List of boards
  31. # Automatically generated by %s: don't edit
  32. #
  33. # Status, Arch, CPU, SoC, Vendor, Board, Target, Options, Maintainers
  34. ''' % __file__
  35. ### helper functions ###
  36. def get_terminal_columns():
  37. """Get the width of the terminal.
  38. Returns:
  39. The width of the terminal, or zero if the stdout is not
  40. associated with tty.
  41. """
  42. try:
  43. return shutil.get_terminal_size().columns # Python 3.3~
  44. except AttributeError:
  45. import fcntl
  46. import termios
  47. import struct
  48. arg = struct.pack('hhhh', 0, 0, 0, 0)
  49. try:
  50. ret = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, arg)
  51. except IOError as exception:
  52. # If 'Inappropriate ioctl for device' error occurs,
  53. # stdout is probably redirected. Return 0.
  54. return 0
  55. return struct.unpack('hhhh', ret)[1]
  56. def get_devnull():
  57. """Get the file object of '/dev/null' device."""
  58. try:
  59. devnull = subprocess.DEVNULL # py3k
  60. except AttributeError:
  61. devnull = open(os.devnull, 'wb')
  62. return devnull
  63. def check_top_directory():
  64. """Exit if we are not at the top of source directory."""
  65. for f in ('README', 'Licenses'):
  66. if not os.path.exists(f):
  67. sys.exit('Please run at the top of source directory.')
  68. def get_make_cmd():
  69. """Get the command name of GNU Make."""
  70. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  71. ret = process.communicate()
  72. if process.returncode:
  73. sys.exit('GNU Make not found')
  74. return ret[0].rstrip()
  75. ### classes ###
  76. class MaintainersDatabase:
  77. """The database of board status and maintainers."""
  78. def __init__(self):
  79. """Create an empty database."""
  80. self.database = {}
  81. def get_status(self, target):
  82. """Return the status of the given board.
  83. Returns:
  84. Either 'Active' or 'Orphan'
  85. """
  86. tmp = self.database[target][0]
  87. if tmp.startswith('Maintained'):
  88. return 'Active'
  89. elif tmp.startswith('Orphan'):
  90. return 'Orphan'
  91. else:
  92. print >> sys.stderr, 'Error: %s: unknown status' % tmp
  93. def get_maintainers(self, target):
  94. """Return the maintainers of the given board.
  95. If the board has two or more maintainers, they are separated
  96. with colons.
  97. """
  98. return ':'.join(self.database[target][1])
  99. def parse_file(self, file):
  100. """Parse the given MAINTAINERS file.
  101. This method parses MAINTAINERS and add board status and
  102. maintainers information to the database.
  103. Arguments:
  104. file: MAINTAINERS file to be parsed
  105. """
  106. targets = []
  107. maintainers = []
  108. status = '-'
  109. for line in open(file):
  110. tag, rest = line[:2], line[2:].strip()
  111. if tag == 'M:':
  112. maintainers.append(rest)
  113. elif tag == 'F:':
  114. # expand wildcard and filter by 'configs/*_defconfig'
  115. for f in glob.glob(rest):
  116. front, match, rear = f.partition('configs/')
  117. if not front and match:
  118. front, match, rear = rear.rpartition('_defconfig')
  119. if match and not rear:
  120. targets.append(front)
  121. elif tag == 'S:':
  122. status = rest
  123. elif line == '\n':
  124. for target in targets:
  125. self.database[target] = (status, maintainers)
  126. targets = []
  127. maintainers = []
  128. status = '-'
  129. if targets:
  130. for target in targets:
  131. self.database[target] = (status, maintainers)
  132. class DotConfigParser:
  133. """A parser of .config file.
  134. Each line of the output should have the form of:
  135. Status, Arch, CPU, SoC, Vendor, Board, Target, Options, Maintainers
  136. Most of them are extracted from .config file.
  137. MAINTAINERS files are also consulted for Status and Maintainers fields.
  138. """
  139. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  140. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  141. re_soc = re.compile(r'CONFIG_SYS_SOC="(.*)"')
  142. re_vendor = re.compile(r'CONFIG_SYS_VENDOR="(.*)"')
  143. re_board = re.compile(r'CONFIG_SYS_BOARD="(.*)"')
  144. re_config = re.compile(r'CONFIG_SYS_CONFIG_NAME="(.*)"')
  145. re_options = re.compile(r'CONFIG_SYS_EXTRA_OPTIONS="(.*)"')
  146. re_list = (('arch', re_arch), ('cpu', re_cpu), ('soc', re_soc),
  147. ('vendor', re_vendor), ('board', re_board),
  148. ('config', re_config), ('options', re_options))
  149. must_fields = ('arch', 'config')
  150. def __init__(self, build_dir, output, maintainers_database):
  151. """Create a new .config perser.
  152. Arguments:
  153. build_dir: Build directory where .config is located
  154. output: File object which the result is written to
  155. maintainers_database: An instance of class MaintainersDatabase
  156. """
  157. self.dotconfig = os.path.join(build_dir, '.config')
  158. self.output = output
  159. self.database = maintainers_database
  160. def parse(self, defconfig):
  161. """Parse .config file and output one-line database for the given board.
  162. Arguments:
  163. defconfig: Board (defconfig) name
  164. """
  165. fields = {}
  166. for line in open(self.dotconfig):
  167. if not line.startswith('CONFIG_SYS_'):
  168. continue
  169. for (key, pattern) in self.re_list:
  170. m = pattern.match(line)
  171. if m and m.group(1):
  172. fields[key] = m.group(1)
  173. break
  174. # sanity check of '.config' file
  175. for field in self.must_fields:
  176. if not field in fields:
  177. sys.exit('Error: %s is not defined in %s' % (field, defconfig))
  178. # fix-up for aarch64
  179. if fields['arch'] == 'arm' and 'cpu' in fields:
  180. if fields['cpu'] == 'armv8':
  181. fields['arch'] = 'aarch64'
  182. target, match, rear = defconfig.partition('_defconfig')
  183. assert match and not rear, \
  184. '%s : invalid defconfig file name' % defconfig
  185. fields['status'] = self.database.get_status(target)
  186. fields['maintainers'] = self.database.get_maintainers(target)
  187. if 'options' in fields:
  188. options = fields['config'] + ':' + \
  189. fields['options'].replace(r'\"', '"')
  190. elif fields['config'] != target:
  191. options = fields['config']
  192. else:
  193. options = '-'
  194. self.output.write((' '.join(['%s'] * 9) + '\n') %
  195. (fields['status'],
  196. fields['arch'],
  197. fields.get('cpu', '-'),
  198. fields.get('soc', '-'),
  199. fields.get('vendor', '-'),
  200. fields.get('board', '-'),
  201. target,
  202. options,
  203. fields['maintainers']))
  204. class Slot:
  205. """A slot to store a subprocess.
  206. Each instance of this class handles one subprocess.
  207. This class is useful to control multiple processes
  208. for faster processing.
  209. """
  210. def __init__(self, output, maintainers_database, devnull, make_cmd):
  211. """Create a new slot.
  212. Arguments:
  213. output: File object which the result is written to
  214. maintainers_database: An instance of class MaintainersDatabase
  215. """
  216. self.occupied = False
  217. self.build_dir = tempfile.mkdtemp()
  218. self.devnull = devnull
  219. self.make_cmd = make_cmd
  220. self.parser = DotConfigParser(self.build_dir, output,
  221. maintainers_database)
  222. def __del__(self):
  223. """Delete the working directory"""
  224. shutil.rmtree(self.build_dir)
  225. def add(self, defconfig):
  226. """Add a new subprocess to the slot.
  227. Fails if the slot is occupied, that is, the current subprocess
  228. is still running.
  229. Arguments:
  230. defconfig: Board (defconfig) name
  231. Returns:
  232. Return True on success or False on fail
  233. """
  234. if self.occupied:
  235. return False
  236. o = 'O=' + self.build_dir
  237. self.ps = subprocess.Popen([self.make_cmd, o, defconfig],
  238. stdout=self.devnull)
  239. self.defconfig = defconfig
  240. self.occupied = True
  241. return True
  242. def poll(self):
  243. """Check if the subprocess is running and invoke the .config
  244. parser if the subprocess is terminated.
  245. Returns:
  246. Return True if the subprocess is terminated, False otherwise
  247. """
  248. if not self.occupied:
  249. return True
  250. if self.ps.poll() == None:
  251. return False
  252. self.parser.parse(self.defconfig)
  253. self.occupied = False
  254. return True
  255. class Slots:
  256. """Controller of the array of subprocess slots."""
  257. def __init__(self, jobs, output, maintainers_database):
  258. """Create a new slots controller.
  259. Arguments:
  260. jobs: A number of slots to instantiate
  261. output: File object which the result is written to
  262. maintainers_database: An instance of class MaintainersDatabase
  263. """
  264. self.slots = []
  265. devnull = get_devnull()
  266. make_cmd = get_make_cmd()
  267. for i in range(jobs):
  268. self.slots.append(Slot(output, maintainers_database,
  269. devnull, make_cmd))
  270. def add(self, defconfig):
  271. """Add a new subprocess if a vacant slot is available.
  272. Arguments:
  273. defconfig: Board (defconfig) name
  274. Returns:
  275. Return True on success or False on fail
  276. """
  277. for slot in self.slots:
  278. if slot.add(defconfig):
  279. return True
  280. return False
  281. def available(self):
  282. """Check if there is a vacant slot.
  283. Returns:
  284. Return True if a vacant slot is found, False if all slots are full
  285. """
  286. for slot in self.slots:
  287. if slot.poll():
  288. return True
  289. return False
  290. def empty(self):
  291. """Check if all slots are vacant.
  292. Returns:
  293. Return True if all slots are vacant, False if at least one slot
  294. is running
  295. """
  296. ret = True
  297. for slot in self.slots:
  298. if not slot.poll():
  299. ret = False
  300. return ret
  301. class Indicator:
  302. """A class to control the progress indicator."""
  303. MIN_WIDTH = 15
  304. MAX_WIDTH = 70
  305. def __init__(self, total):
  306. """Create an instance.
  307. Arguments:
  308. total: A number of boards
  309. """
  310. self.total = total
  311. self.cur = 0
  312. width = get_terminal_columns()
  313. width = min(width, self.MAX_WIDTH)
  314. width -= self.MIN_WIDTH
  315. if width > 0:
  316. self.enabled = True
  317. else:
  318. self.enabled = False
  319. self.width = width
  320. def inc(self):
  321. """Increment the counter and show the progress bar."""
  322. if not self.enabled:
  323. return
  324. self.cur += 1
  325. arrow_len = self.width * self.cur // self.total
  326. msg = '%4d/%d [' % (self.cur, self.total)
  327. msg += '=' * arrow_len + '>' + ' ' * (self.width - arrow_len) + ']'
  328. sys.stdout.write('\r' + msg)
  329. sys.stdout.flush()
  330. def __gen_boards_cfg(jobs):
  331. """Generate boards.cfg file.
  332. Arguments:
  333. jobs: The number of jobs to run simultaneously
  334. Note:
  335. The incomplete boards.cfg is left over when an error (including
  336. the termination by the keyboard interrupt) occurs on the halfway.
  337. """
  338. check_top_directory()
  339. print 'Generating %s ... (jobs: %d)' % (BOARD_FILE, jobs)
  340. # All the defconfig files to be processed
  341. defconfigs = []
  342. for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR):
  343. dirpath = dirpath[len(CONFIG_DIR) + 1:]
  344. for filename in fnmatch.filter(filenames, '*_defconfig'):
  345. defconfigs.append(os.path.join(dirpath, filename))
  346. # Parse all the MAINTAINERS files
  347. maintainers_database = MaintainersDatabase()
  348. for (dirpath, dirnames, filenames) in os.walk('.'):
  349. if 'MAINTAINERS' in filenames:
  350. maintainers_database.parse_file(os.path.join(dirpath,
  351. 'MAINTAINERS'))
  352. # Output lines should be piped into the reformat tool
  353. reformat_process = subprocess.Popen(REFORMAT_CMD, stdin=subprocess.PIPE,
  354. stdout=open(BOARD_FILE, 'w'))
  355. pipe = reformat_process.stdin
  356. pipe.write(COMMENT_BLOCK)
  357. indicator = Indicator(len(defconfigs))
  358. slots = Slots(jobs, pipe, maintainers_database)
  359. # Main loop to process defconfig files:
  360. # Add a new subprocess into a vacant slot.
  361. # Sleep if there is no available slot.
  362. for defconfig in defconfigs:
  363. while not slots.add(defconfig):
  364. while not slots.available():
  365. # No available slot: sleep for a while
  366. time.sleep(SLEEP_TIME)
  367. indicator.inc()
  368. # wait until all the subprocesses finish
  369. while not slots.empty():
  370. time.sleep(SLEEP_TIME)
  371. print ''
  372. # wait until the reformat tool finishes
  373. reformat_process.communicate()
  374. if reformat_process.returncode != 0:
  375. sys.exit('"%s" failed' % REFORMAT_CMD[0])
  376. def gen_boards_cfg(jobs):
  377. """Generate boards.cfg file.
  378. The incomplete boards.cfg is deleted if an error (including
  379. the termination by the keyboard interrupt) occurs on the halfway.
  380. Arguments:
  381. jobs: The number of jobs to run simultaneously
  382. """
  383. try:
  384. __gen_boards_cfg(jobs)
  385. except:
  386. # We should remove incomplete boards.cfg
  387. try:
  388. os.remove(BOARD_FILE)
  389. except OSError as exception:
  390. # Ignore 'No such file or directory' error
  391. if exception.errno != errno.ENOENT:
  392. raise
  393. raise
  394. def main():
  395. parser = optparse.OptionParser()
  396. # Add options here
  397. parser.add_option('-j', '--jobs',
  398. help='the number of jobs to run simultaneously')
  399. (options, args) = parser.parse_args()
  400. if options.jobs:
  401. try:
  402. jobs = int(options.jobs)
  403. except ValueError:
  404. sys.exit('Option -j (--jobs) takes a number')
  405. else:
  406. try:
  407. jobs = int(subprocess.Popen(['getconf', '_NPROCESSORS_ONLN'],
  408. stdout=subprocess.PIPE).communicate()[0])
  409. except (OSError, ValueError):
  410. print 'info: failed to get the number of CPUs. Set jobs to 1'
  411. jobs = 1
  412. gen_boards_cfg(jobs)
  413. if __name__ == '__main__':
  414. main()