test_checkpatch.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. # -*- coding: utf-8 -*-
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Tests for U-Boot-specific checkpatch.pl features
  5. #
  6. # Copyright (c) 2011 The Chromium OS Authors.
  7. #
  8. import os
  9. import tempfile
  10. import unittest
  11. from patman import checkpatch
  12. from patman import gitutil
  13. from patman import patchstream
  14. from patman import series
  15. from patman import commit
  16. class Line:
  17. def __init__(self, fname, text):
  18. self.fname = fname
  19. self.text = text
  20. class PatchMaker:
  21. def __init__(self):
  22. self.lines = []
  23. def add_line(self, fname, text):
  24. self.lines.append(Line(fname, text))
  25. def get_patch_text(self):
  26. base = '''From 125b77450f4c66b8fd9654319520bbe795c9ef31 Mon Sep 17 00:00:00 2001
  27. From: Simon Glass <sjg@chromium.org>
  28. Date: Sun, 14 Jun 2020 09:45:14 -0600
  29. Subject: [PATCH] Test commit
  30. This is a test commit.
  31. Signed-off-by: Simon Glass <sjg@chromium.org>
  32. ---
  33. '''
  34. lines = base.splitlines()
  35. # Create the diffstat
  36. change = 0
  37. insert = 0
  38. for line in self.lines:
  39. lines.append(' %s | 1 +' % line.fname)
  40. change += 1
  41. insert += 1
  42. lines.append(' %d files changed, %d insertions(+)' % (change, insert))
  43. lines.append('')
  44. # Create the patch info for each file
  45. for line in self.lines:
  46. lines.append('diff --git a/%s b/%s' % (line.fname, line.fname))
  47. lines.append('index 7837d459f18..5ba7840f68e 100644')
  48. lines.append('--- a/%s' % line.fname)
  49. lines.append('+++ b/%s' % line.fname)
  50. lines += ('''@@ -121,6 +121,7 @@ enum uclass_id {
  51. UCLASS_W1, /* Dallas 1-Wire bus */
  52. UCLASS_W1_EEPROM, /* one-wire EEPROMs */
  53. UCLASS_WDT, /* Watchdog Timer driver */
  54. +%s
  55. UCLASS_COUNT,
  56. UCLASS_INVALID = -1,
  57. ''' % line.text).splitlines()
  58. lines.append('---')
  59. lines.append('2.17.1')
  60. return '\n'.join(lines)
  61. def get_patch(self):
  62. inhandle, inname = tempfile.mkstemp()
  63. infd = os.fdopen(inhandle, 'w')
  64. infd.write(self.get_patch_text())
  65. infd.close()
  66. return inname
  67. def run_checkpatch(self):
  68. return checkpatch.CheckPatch(self.get_patch(), show_types=True)
  69. class TestPatch(unittest.TestCase):
  70. """Test the u_boot_line() function in checkpatch.pl"""
  71. def testBasic(self):
  72. """Test basic filter operation"""
  73. data='''
  74. From 656c9a8c31fa65859d924cd21da920d6ba537fad Mon Sep 17 00:00:00 2001
  75. From: Simon Glass <sjg@chromium.org>
  76. Date: Thu, 28 Apr 2011 09:58:51 -0700
  77. Subject: [PATCH (resend) 3/7] Tegra2: Add more clock support
  78. This adds functions to enable/disable clocks and reset to on-chip peripherals.
  79. cmd/pci.c:152:11: warning: format ‘%llx’ expects argument of type
  80. ‘long long unsigned int’, but argument 3 has type
  81. ‘u64 {aka long unsigned int}’ [-Wformat=]
  82. BUG=chromium-os:13875
  83. TEST=build U-Boot for Seaboard, boot
  84. Change-Id: I80fe1d0c0b7dd10aa58ce5bb1d9290b6664d5413
  85. Review URL: http://codereview.chromium.org/6900006
  86. Signed-off-by: Simon Glass <sjg@chromium.org>
  87. ---
  88. arch/arm/cpu/armv7/tegra2/Makefile | 2 +-
  89. arch/arm/cpu/armv7/tegra2/ap20.c | 57 ++----
  90. arch/arm/cpu/armv7/tegra2/clock.c | 163 +++++++++++++++++
  91. '''
  92. expected='''Message-Id: <19991231235959.0.I80fe1d0c0b7dd10aa58ce5bb1d9290b6664d5413@changeid>
  93. From 656c9a8c31fa65859d924cd21da920d6ba537fad Mon Sep 17 00:00:00 2001
  94. From: Simon Glass <sjg@chromium.org>
  95. Date: Thu, 28 Apr 2011 09:58:51 -0700
  96. Subject: [PATCH (resend) 3/7] Tegra2: Add more clock support
  97. This adds functions to enable/disable clocks and reset to on-chip peripherals.
  98. cmd/pci.c:152:11: warning: format ‘%llx’ expects argument of type
  99. ‘long long unsigned int’, but argument 3 has type
  100. ‘u64 {aka long unsigned int}’ [-Wformat=]
  101. Signed-off-by: Simon Glass <sjg@chromium.org>
  102. ---
  103. arch/arm/cpu/armv7/tegra2/Makefile | 2 +-
  104. arch/arm/cpu/armv7/tegra2/ap20.c | 57 ++----
  105. arch/arm/cpu/armv7/tegra2/clock.c | 163 +++++++++++++++++
  106. '''
  107. out = ''
  108. inhandle, inname = tempfile.mkstemp()
  109. infd = os.fdopen(inhandle, 'w', encoding='utf-8')
  110. infd.write(data)
  111. infd.close()
  112. exphandle, expname = tempfile.mkstemp()
  113. expfd = os.fdopen(exphandle, 'w', encoding='utf-8')
  114. expfd.write(expected)
  115. expfd.close()
  116. # Normally by the time we call fix_patch we've already collected
  117. # metadata. Here, we haven't, but at least fake up something.
  118. # Set the "count" to -1 which tells fix_patch to use a bogus/fixed
  119. # time for generating the Message-Id.
  120. com = commit.Commit('')
  121. com.change_id = 'I80fe1d0c0b7dd10aa58ce5bb1d9290b6664d5413'
  122. com.count = -1
  123. patchstream.fix_patch(None, inname, series.Series(), com)
  124. rc = os.system('diff -u %s %s' % (inname, expname))
  125. self.assertEqual(rc, 0)
  126. os.remove(inname)
  127. os.remove(expname)
  128. def GetData(self, data_type):
  129. data='''From 4924887af52713cabea78420eff03badea8f0035 Mon Sep 17 00:00:00 2001
  130. From: Simon Glass <sjg@chromium.org>
  131. Date: Thu, 7 Apr 2011 10:14:41 -0700
  132. Subject: [PATCH 1/4] Add microsecond boot time measurement
  133. This defines the basics of a new boot time measurement feature. This allows
  134. logging of very accurate time measurements as the boot proceeds, by using
  135. an available microsecond counter.
  136. %s
  137. ---
  138. README | 11 ++++++++
  139. MAINTAINERS | 3 ++
  140. common/bootstage.c | 50 ++++++++++++++++++++++++++++++++++++
  141. include/bootstage.h | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++
  142. include/common.h | 8 ++++++
  143. 5 files changed, 141 insertions(+), 0 deletions(-)
  144. create mode 100644 common/bootstage.c
  145. create mode 100644 include/bootstage.h
  146. diff --git a/README b/README
  147. index 6f3748d..f9e4e65 100644
  148. --- a/README
  149. +++ b/README
  150. @@ -2026,6 +2026,17 @@ The following options need to be configured:
  151. example, some LED's) on your board. At the moment,
  152. the following checkpoints are implemented:
  153. +- Time boot progress
  154. + CONFIG_BOOTSTAGE
  155. +
  156. + Define this option to enable microsecond boot stage timing
  157. + on supported platforms. For this to work your platform
  158. + needs to define a function timer_get_us() which returns the
  159. + number of microseconds since reset. This would normally
  160. + be done in your SOC or board timer.c file.
  161. +
  162. + You can add calls to bootstage_mark() to set time markers.
  163. +
  164. - Standalone program support:
  165. CONFIG_STANDALONE_LOAD_ADDR
  166. diff --git a/MAINTAINERS b/MAINTAINERS
  167. index b167b028ec..beb7dc634f 100644
  168. --- a/MAINTAINERS
  169. +++ b/MAINTAINERS
  170. @@ -474,3 +474,8 @@ S: Maintained
  171. T: git git://git.denx.de/u-boot.git
  172. F: *
  173. F: */
  174. +
  175. +BOOTSTAGE
  176. +M: Simon Glass <sjg@chromium.org>
  177. +L: u-boot@lists.denx.de
  178. +F: common/bootstage.c
  179. diff --git a/common/bootstage.c b/common/bootstage.c
  180. new file mode 100644
  181. index 0000000..2234c87
  182. --- /dev/null
  183. +++ b/common/bootstage.c
  184. @@ -0,0 +1,37 @@
  185. +%s
  186. +/*
  187. + * Copyright (c) 2011, Google Inc. All rights reserved.
  188. + *
  189. + */
  190. +
  191. +/*
  192. + * This module records the progress of boot and arbitrary commands, and
  193. + * permits accurate timestamping of each. The records can optionally be
  194. + * passed to kernel in the ATAGs
  195. + */
  196. +
  197. +#include <common.h>
  198. +
  199. +struct bootstage_record {
  200. + u32 time_us;
  201. + const char *name;
  202. +};
  203. +
  204. +static struct bootstage_record record[BOOTSTAGE_COUNT];
  205. +
  206. +u32 bootstage_mark(enum bootstage_id id, const char *name)
  207. +{
  208. + struct bootstage_record *rec = &record[id];
  209. +
  210. + /* Only record the first event for each */
  211. +%sif (!rec->name) {
  212. + rec->time_us = (u32)timer_get_us();
  213. + rec->name = name;
  214. + }
  215. + if (!rec->name &&
  216. + %ssomething_else) {
  217. + rec->time_us = (u32)timer_get_us();
  218. + rec->name = name;
  219. + }
  220. +%sreturn rec->time_us;
  221. +}
  222. --
  223. 1.7.3.1
  224. '''
  225. signoff = 'Signed-off-by: Simon Glass <sjg@chromium.org>\n'
  226. license = '// SPDX-License-Identifier: GPL-2.0+'
  227. tab = ' '
  228. indent = ' '
  229. if data_type == 'good':
  230. pass
  231. elif data_type == 'no-signoff':
  232. signoff = ''
  233. elif data_type == 'no-license':
  234. license = ''
  235. elif data_type == 'spaces':
  236. tab = ' '
  237. elif data_type == 'indent':
  238. indent = tab
  239. else:
  240. print('not implemented')
  241. return data % (signoff, license, tab, indent, tab)
  242. def SetupData(self, data_type):
  243. inhandle, inname = tempfile.mkstemp()
  244. infd = os.fdopen(inhandle, 'w')
  245. data = self.GetData(data_type)
  246. infd.write(data)
  247. infd.close()
  248. return inname
  249. def testGood(self):
  250. """Test checkpatch operation"""
  251. inf = self.SetupData('good')
  252. result = checkpatch.CheckPatch(inf)
  253. self.assertEqual(result.ok, True)
  254. self.assertEqual(result.problems, [])
  255. self.assertEqual(result.errors, 0)
  256. self.assertEqual(result.warnings, 0)
  257. self.assertEqual(result.checks, 0)
  258. self.assertEqual(result.lines, 62)
  259. os.remove(inf)
  260. def testNoSignoff(self):
  261. inf = self.SetupData('no-signoff')
  262. result = checkpatch.CheckPatch(inf)
  263. self.assertEqual(result.ok, False)
  264. self.assertEqual(len(result.problems), 1)
  265. self.assertEqual(result.errors, 1)
  266. self.assertEqual(result.warnings, 0)
  267. self.assertEqual(result.checks, 0)
  268. self.assertEqual(result.lines, 62)
  269. os.remove(inf)
  270. def testNoLicense(self):
  271. inf = self.SetupData('no-license')
  272. result = checkpatch.CheckPatch(inf)
  273. self.assertEqual(result.ok, False)
  274. self.assertEqual(len(result.problems), 1)
  275. self.assertEqual(result.errors, 0)
  276. self.assertEqual(result.warnings, 1)
  277. self.assertEqual(result.checks, 0)
  278. self.assertEqual(result.lines, 62)
  279. os.remove(inf)
  280. def testSpaces(self):
  281. inf = self.SetupData('spaces')
  282. result = checkpatch.CheckPatch(inf)
  283. self.assertEqual(result.ok, False)
  284. self.assertEqual(len(result.problems), 3)
  285. self.assertEqual(result.errors, 0)
  286. self.assertEqual(result.warnings, 3)
  287. self.assertEqual(result.checks, 0)
  288. self.assertEqual(result.lines, 62)
  289. os.remove(inf)
  290. def testIndent(self):
  291. inf = self.SetupData('indent')
  292. result = checkpatch.CheckPatch(inf)
  293. self.assertEqual(result.ok, False)
  294. self.assertEqual(len(result.problems), 1)
  295. self.assertEqual(result.errors, 0)
  296. self.assertEqual(result.warnings, 0)
  297. self.assertEqual(result.checks, 1)
  298. self.assertEqual(result.lines, 62)
  299. os.remove(inf)
  300. def checkSingleMessage(self, pm, msg, pmtype = 'warning'):
  301. """Helper function to run checkpatch and check the result
  302. Args:
  303. pm: PatchMaker object to use
  304. msg: Expected message (e.g. 'LIVETREE')
  305. pmtype: Type of problem ('error', 'warning')
  306. """
  307. result = pm.run_checkpatch()
  308. if pmtype == 'warning':
  309. self.assertEqual(result.warnings, 1)
  310. elif pmtype == 'error':
  311. self.assertEqual(result.errors, 1)
  312. if len(result.problems) != 1:
  313. print(result.problems)
  314. self.assertEqual(len(result.problems), 1)
  315. self.assertIn(msg, result.problems[0]['cptype'])
  316. def testUclass(self):
  317. """Test for possible new uclass"""
  318. pm = PatchMaker()
  319. pm.add_line('include/dm/uclass-id.h', 'UCLASS_WIBBLE,')
  320. self.checkSingleMessage(pm, 'NEW_UCLASS')
  321. def testLivetree(self):
  322. """Test for using the livetree API"""
  323. pm = PatchMaker()
  324. pm.add_line('common/main.c', 'fdtdec_do_something()')
  325. self.checkSingleMessage(pm, 'LIVETREE')
  326. def testNewCommand(self):
  327. """Test for adding a new command"""
  328. pm = PatchMaker()
  329. pm.add_line('common/main.c', 'do_wibble(struct cmd_tbl *cmd_tbl)')
  330. self.checkSingleMessage(pm, 'CMD_TEST')
  331. def testPreferIf(self):
  332. """Test for using #ifdef"""
  333. pm = PatchMaker()
  334. pm.add_line('common/main.c', '#ifdef CONFIG_YELLOW')
  335. pm.add_line('common/init.h', '#ifdef CONFIG_YELLOW')
  336. pm.add_line('fred.dtsi', '#ifdef CONFIG_YELLOW')
  337. self.checkSingleMessage(pm, "PREFER_IF")
  338. def testCommandUseDefconfig(self):
  339. """Test for enabling/disabling commands using preprocesor"""
  340. pm = PatchMaker()
  341. pm.add_line('common/main.c', '#undef CONFIG_CMD_WHICH')
  342. self.checkSingleMessage(pm, 'DEFINE_CONFIG_CMD', 'error')
  343. def testBarredIncludeInHdr(self):
  344. """Test for using a barred include in a header file"""
  345. pm = PatchMaker()
  346. #pm.add_line('include/myfile.h', '#include <common.h>')
  347. pm.add_line('include/myfile.h', '#include <dm.h>')
  348. self.checkSingleMessage(pm, 'BARRED_INCLUDE_IN_HDR', 'error')
  349. def testConfigIsEnabledConfig(self):
  350. """Test for accidental CONFIG_IS_ENABLED(CONFIG_*) calls"""
  351. pm = PatchMaker()
  352. pm.add_line('common/main.c', 'if (CONFIG_IS_ENABLED(CONFIG_CLK))')
  353. self.checkSingleMessage(pm, 'CONFIG_IS_ENABLED_CONFIG', 'error')
  354. def check_struct(self, auto, suffix, warning):
  355. """Check one of the warnings for struct naming
  356. Args:
  357. auto: Auto variable name, e.g. 'per_child_auto'
  358. suffix: Suffix to expect on member, e.g. '_priv'
  359. warning: Warning name, e.g. 'PRIV_AUTO'
  360. """
  361. pm = PatchMaker()
  362. pm.add_line('common/main.c', '.%s = sizeof(struct(fred)),' % auto)
  363. pm.add_line('common/main.c', '.%s = sizeof(struct(mary%s)),' %
  364. (auto, suffix))
  365. self.checkSingleMessage(
  366. pm, warning, "struct 'fred' should have a %s suffix" % suffix)
  367. def testDmDriverAuto(self):
  368. """Check for the correct suffix on 'struct driver' auto members"""
  369. self.check_struct('priv_auto', '_priv', 'PRIV_AUTO')
  370. self.check_struct('plat_auto', '_plat', 'PLAT_AUTO')
  371. self.check_struct('per_child_auto', '_priv', 'CHILD_PRIV_AUTO')
  372. self.check_struct('per_child_plat_auto', '_plat', 'CHILD_PLAT_AUTO')
  373. def testDmUclassAuto(self):
  374. """Check for the correct suffix on 'struct uclass' auto members"""
  375. # Some of these are omitted since they match those from struct driver
  376. self.check_struct('per_device_auto', '_priv', 'DEVICE_PRIV_AUTO')
  377. self.check_struct('per_device_plat_auto', '_plat', 'DEVICE_PLAT_AUTO')
  378. def check_strl(self, func):
  379. """Check one of the checks for strn(cpy|cat)"""
  380. pm = PatchMaker()
  381. pm.add_line('common/main.c', "strn%s(foo, bar, sizeof(foo));" % func)
  382. self.checkSingleMessage(pm, "STRL",
  383. "strl%s is preferred over strn%s because it always produces a nul-terminated string\n"
  384. % (func, func))
  385. def testStrl(self):
  386. """Check for uses of strn(cat|cpy)"""
  387. self.check_strl("cat");
  388. self.check_strl("cpy");
  389. if __name__ == "__main__":
  390. unittest.main()
  391. gitutil.RunTests()