genboardscfg.py 20 KB

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