genboardscfg.py 19 KB

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