genboardscfg.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. if not target in self.database:
  87. print >> sys.stderr, "WARNING: no status info for '%s'" % target
  88. return '-'
  89. tmp = self.database[target][0]
  90. if tmp.startswith('Maintained'):
  91. return 'Active'
  92. elif tmp.startswith('Orphan'):
  93. return 'Orphan'
  94. else:
  95. print >> sys.stderr, ("WARNING: %s: unknown status for '%s'" %
  96. (tmp, target))
  97. return '-'
  98. def get_maintainers(self, target):
  99. """Return the maintainers of the given board.
  100. If the board has two or more maintainers, they are separated
  101. with colons.
  102. """
  103. if not target in self.database:
  104. print >> sys.stderr, "WARNING: no maintainers for '%s'" % target
  105. return ''
  106. return ':'.join(self.database[target][1])
  107. def parse_file(self, file):
  108. """Parse the given MAINTAINERS file.
  109. This method parses MAINTAINERS and add board status and
  110. maintainers information to the database.
  111. Arguments:
  112. file: MAINTAINERS file to be parsed
  113. """
  114. targets = []
  115. maintainers = []
  116. status = '-'
  117. for line in open(file):
  118. tag, rest = line[:2], line[2:].strip()
  119. if tag == 'M:':
  120. maintainers.append(rest)
  121. elif tag == 'F:':
  122. # expand wildcard and filter by 'configs/*_defconfig'
  123. for f in glob.glob(rest):
  124. front, match, rear = f.partition('configs/')
  125. if not front and match:
  126. front, match, rear = rear.rpartition('_defconfig')
  127. if match and not rear:
  128. targets.append(front)
  129. elif tag == 'S:':
  130. status = rest
  131. elif line == '\n':
  132. for target in targets:
  133. self.database[target] = (status, maintainers)
  134. targets = []
  135. maintainers = []
  136. status = '-'
  137. if targets:
  138. for target in targets:
  139. self.database[target] = (status, maintainers)
  140. class DotConfigParser:
  141. """A parser of .config file.
  142. Each line of the output should have the form of:
  143. Status, Arch, CPU, SoC, Vendor, Board, Target, Options, Maintainers
  144. Most of them are extracted from .config file.
  145. MAINTAINERS files are also consulted for Status and Maintainers fields.
  146. """
  147. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  148. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  149. re_soc = re.compile(r'CONFIG_SYS_SOC="(.*)"')
  150. re_vendor = re.compile(r'CONFIG_SYS_VENDOR="(.*)"')
  151. re_board = re.compile(r'CONFIG_SYS_BOARD="(.*)"')
  152. re_config = re.compile(r'CONFIG_SYS_CONFIG_NAME="(.*)"')
  153. re_options = re.compile(r'CONFIG_SYS_EXTRA_OPTIONS="(.*)"')
  154. re_list = (('arch', re_arch), ('cpu', re_cpu), ('soc', re_soc),
  155. ('vendor', re_vendor), ('board', re_board),
  156. ('config', re_config), ('options', re_options))
  157. must_fields = ('arch', 'config')
  158. def __init__(self, build_dir, output, maintainers_database):
  159. """Create a new .config perser.
  160. Arguments:
  161. build_dir: Build directory where .config is located
  162. output: File object which the result is written to
  163. maintainers_database: An instance of class MaintainersDatabase
  164. """
  165. self.dotconfig = os.path.join(build_dir, '.config')
  166. self.output = output
  167. self.database = maintainers_database
  168. def parse(self, defconfig):
  169. """Parse .config file and output one-line database for the given board.
  170. Arguments:
  171. defconfig: Board (defconfig) name
  172. """
  173. fields = {}
  174. for line in open(self.dotconfig):
  175. if not line.startswith('CONFIG_SYS_'):
  176. continue
  177. for (key, pattern) in self.re_list:
  178. m = pattern.match(line)
  179. if m and m.group(1):
  180. fields[key] = m.group(1)
  181. break
  182. # sanity check of '.config' file
  183. for field in self.must_fields:
  184. if not field in fields:
  185. print >> sys.stderr, (
  186. "WARNING: '%s' is not defined in '%s'. Skip." %
  187. (field, defconfig))
  188. return
  189. # fix-up for aarch64
  190. if fields['arch'] == 'arm' and 'cpu' in fields:
  191. if fields['cpu'] == 'armv8':
  192. fields['arch'] = 'aarch64'
  193. target, match, rear = defconfig.partition('_defconfig')
  194. assert match and not rear, \
  195. '%s : invalid defconfig file name' % defconfig
  196. fields['status'] = self.database.get_status(target)
  197. fields['maintainers'] = self.database.get_maintainers(target)
  198. if 'options' in fields:
  199. options = fields['config'] + ':' + \
  200. fields['options'].replace(r'\"', '"')
  201. elif fields['config'] != target:
  202. options = fields['config']
  203. else:
  204. options = '-'
  205. self.output.write((' '.join(['%s'] * 9) + '\n') %
  206. (fields['status'],
  207. fields['arch'],
  208. fields.get('cpu', '-'),
  209. fields.get('soc', '-'),
  210. fields.get('vendor', '-'),
  211. fields.get('board', '-'),
  212. target,
  213. options,
  214. fields['maintainers']))
  215. class Slot:
  216. """A slot to store a subprocess.
  217. Each instance of this class handles one subprocess.
  218. This class is useful to control multiple processes
  219. for faster processing.
  220. """
  221. def __init__(self, output, maintainers_database, devnull, make_cmd):
  222. """Create a new slot.
  223. Arguments:
  224. output: File object which the result is written to
  225. maintainers_database: An instance of class MaintainersDatabase
  226. """
  227. self.occupied = False
  228. self.build_dir = tempfile.mkdtemp()
  229. self.devnull = devnull
  230. self.make_cmd = make_cmd
  231. self.parser = DotConfigParser(self.build_dir, output,
  232. maintainers_database)
  233. def __del__(self):
  234. """Delete the working directory"""
  235. if not self.occupied:
  236. while self.ps.poll() == None:
  237. pass
  238. shutil.rmtree(self.build_dir)
  239. def add(self, defconfig):
  240. """Add a new subprocess to the slot.
  241. Fails if the slot is occupied, that is, the current subprocess
  242. is still running.
  243. Arguments:
  244. defconfig: Board (defconfig) name
  245. Returns:
  246. Return True on success or False on fail
  247. """
  248. if self.occupied:
  249. return False
  250. o = 'O=' + self.build_dir
  251. self.ps = subprocess.Popen([self.make_cmd, o, defconfig],
  252. stdout=self.devnull)
  253. self.defconfig = defconfig
  254. self.occupied = True
  255. return True
  256. def poll(self):
  257. """Check if the subprocess is running and invoke the .config
  258. parser if the subprocess is terminated.
  259. Returns:
  260. Return True if the subprocess is terminated, False otherwise
  261. """
  262. if not self.occupied:
  263. return True
  264. if self.ps.poll() == None:
  265. return False
  266. if self.ps.poll() == 0:
  267. self.parser.parse(self.defconfig)
  268. else:
  269. print >> sys.stderr, ("WARNING: failed to process '%s'. skip." %
  270. self.defconfig)
  271. self.occupied = False
  272. return True
  273. class Slots:
  274. """Controller of the array of subprocess slots."""
  275. def __init__(self, jobs, output, maintainers_database):
  276. """Create a new slots controller.
  277. Arguments:
  278. jobs: A number of slots to instantiate
  279. output: File object which the result is written to
  280. maintainers_database: An instance of class MaintainersDatabase
  281. """
  282. self.slots = []
  283. devnull = get_devnull()
  284. make_cmd = get_make_cmd()
  285. for i in range(jobs):
  286. self.slots.append(Slot(output, maintainers_database,
  287. devnull, make_cmd))
  288. def add(self, defconfig):
  289. """Add a new subprocess if a vacant slot is available.
  290. Arguments:
  291. defconfig: Board (defconfig) name
  292. Returns:
  293. Return True on success or False on fail
  294. """
  295. for slot in self.slots:
  296. if slot.add(defconfig):
  297. return True
  298. return False
  299. def available(self):
  300. """Check if there is a vacant slot.
  301. Returns:
  302. Return True if a vacant slot is found, False if all slots are full
  303. """
  304. for slot in self.slots:
  305. if slot.poll():
  306. return True
  307. return False
  308. def empty(self):
  309. """Check if all slots are vacant.
  310. Returns:
  311. Return True if all slots are vacant, False if at least one slot
  312. is running
  313. """
  314. ret = True
  315. for slot in self.slots:
  316. if not slot.poll():
  317. ret = False
  318. return ret
  319. class Indicator:
  320. """A class to control the progress indicator."""
  321. MIN_WIDTH = 15
  322. MAX_WIDTH = 70
  323. def __init__(self, total):
  324. """Create an instance.
  325. Arguments:
  326. total: A number of boards
  327. """
  328. self.total = total
  329. self.cur = 0
  330. width = get_terminal_columns()
  331. width = min(width, self.MAX_WIDTH)
  332. width -= self.MIN_WIDTH
  333. if width > 0:
  334. self.enabled = True
  335. else:
  336. self.enabled = False
  337. self.width = width
  338. def inc(self):
  339. """Increment the counter and show the progress bar."""
  340. if not self.enabled:
  341. return
  342. self.cur += 1
  343. arrow_len = self.width * self.cur // self.total
  344. msg = '%4d/%d [' % (self.cur, self.total)
  345. msg += '=' * arrow_len + '>' + ' ' * (self.width - arrow_len) + ']'
  346. sys.stdout.write('\r' + msg)
  347. sys.stdout.flush()
  348. def __gen_boards_cfg(jobs):
  349. """Generate boards.cfg file.
  350. Arguments:
  351. jobs: The number of jobs to run simultaneously
  352. Note:
  353. The incomplete boards.cfg is left over when an error (including
  354. the termination by the keyboard interrupt) occurs on the halfway.
  355. """
  356. check_top_directory()
  357. print 'Generating %s ... (jobs: %d)' % (BOARD_FILE, jobs)
  358. # All the defconfig files to be processed
  359. defconfigs = []
  360. for (dirpath, dirnames, filenames) in os.walk(CONFIG_DIR):
  361. dirpath = dirpath[len(CONFIG_DIR) + 1:]
  362. for filename in fnmatch.filter(filenames, '*_defconfig'):
  363. if fnmatch.fnmatch(filename, '.*'):
  364. continue
  365. defconfigs.append(os.path.join(dirpath, filename))
  366. # Parse all the MAINTAINERS files
  367. maintainers_database = MaintainersDatabase()
  368. for (dirpath, dirnames, filenames) in os.walk('.'):
  369. if 'MAINTAINERS' in filenames:
  370. maintainers_database.parse_file(os.path.join(dirpath,
  371. 'MAINTAINERS'))
  372. # Output lines should be piped into the reformat tool
  373. reformat_process = subprocess.Popen(REFORMAT_CMD, stdin=subprocess.PIPE,
  374. stdout=open(BOARD_FILE, 'w'))
  375. pipe = reformat_process.stdin
  376. pipe.write(COMMENT_BLOCK)
  377. indicator = Indicator(len(defconfigs))
  378. slots = Slots(jobs, pipe, maintainers_database)
  379. # Main loop to process defconfig files:
  380. # Add a new subprocess into a vacant slot.
  381. # Sleep if there is no available slot.
  382. for defconfig in defconfigs:
  383. while not slots.add(defconfig):
  384. while not slots.available():
  385. # No available slot: sleep for a while
  386. time.sleep(SLEEP_TIME)
  387. indicator.inc()
  388. # wait until all the subprocesses finish
  389. while not slots.empty():
  390. time.sleep(SLEEP_TIME)
  391. print ''
  392. # wait until the reformat tool finishes
  393. reformat_process.communicate()
  394. if reformat_process.returncode != 0:
  395. sys.exit('"%s" failed' % REFORMAT_CMD[0])
  396. def gen_boards_cfg(jobs):
  397. """Generate boards.cfg file.
  398. The incomplete boards.cfg is deleted if an error (including
  399. the termination by the keyboard interrupt) occurs on the halfway.
  400. Arguments:
  401. jobs: The number of jobs to run simultaneously
  402. """
  403. try:
  404. __gen_boards_cfg(jobs)
  405. except:
  406. # We should remove incomplete boards.cfg
  407. try:
  408. os.remove(BOARD_FILE)
  409. except OSError as exception:
  410. # Ignore 'No such file or directory' error
  411. if exception.errno != errno.ENOENT:
  412. raise
  413. raise
  414. def main():
  415. parser = optparse.OptionParser()
  416. # Add options here
  417. parser.add_option('-j', '--jobs',
  418. help='the number of jobs to run simultaneously')
  419. (options, args) = parser.parse_args()
  420. if options.jobs:
  421. try:
  422. jobs = int(options.jobs)
  423. except ValueError:
  424. sys.exit('Option -j (--jobs) takes a number')
  425. else:
  426. try:
  427. jobs = int(subprocess.Popen(['getconf', '_NPROCESSORS_ONLN'],
  428. stdout=subprocess.PIPE).communicate()[0])
  429. except (OSError, ValueError):
  430. print 'info: failed to get the number of CPUs. Set jobs to 1'
  431. jobs = 1
  432. gen_boards_cfg(jobs)
  433. if __name__ == '__main__':
  434. main()