ftest.py 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # To run a single test, change to this directory, and:
  6. #
  7. # python -m unittest func_test.TestFunctional.testHelp
  8. import collections
  9. import gzip
  10. import hashlib
  11. from optparse import OptionParser
  12. import os
  13. import re
  14. import shutil
  15. import struct
  16. import sys
  17. import tempfile
  18. import unittest
  19. from binman import cbfs_util
  20. from binman import cmdline
  21. from binman import control
  22. from binman import elf
  23. from binman import elf_test
  24. from binman import fmap_util
  25. from binman import state
  26. from dtoc import fdt
  27. from dtoc import fdt_util
  28. from binman.etype import fdtmap
  29. from binman.etype import image_header
  30. from binman.image import Image
  31. from patman import command
  32. from patman import test_util
  33. from patman import tools
  34. from patman import tout
  35. # Contents of test files, corresponding to different entry types
  36. U_BOOT_DATA = b'1234'
  37. U_BOOT_IMG_DATA = b'img'
  38. U_BOOT_SPL_DATA = b'56780123456789abcdefghi'
  39. U_BOOT_TPL_DATA = b'tpl9876543210fedcbazyw'
  40. BLOB_DATA = b'89'
  41. ME_DATA = b'0abcd'
  42. VGA_DATA = b'vga'
  43. U_BOOT_DTB_DATA = b'udtb'
  44. U_BOOT_SPL_DTB_DATA = b'spldtb'
  45. U_BOOT_TPL_DTB_DATA = b'tpldtb'
  46. X86_START16_DATA = b'start16'
  47. X86_START16_SPL_DATA = b'start16spl'
  48. X86_START16_TPL_DATA = b'start16tpl'
  49. X86_RESET16_DATA = b'reset16'
  50. X86_RESET16_SPL_DATA = b'reset16spl'
  51. X86_RESET16_TPL_DATA = b'reset16tpl'
  52. PPC_MPC85XX_BR_DATA = b'ppcmpc85xxbr'
  53. U_BOOT_NODTB_DATA = b'nodtb with microcode pointer somewhere in here'
  54. U_BOOT_SPL_NODTB_DATA = b'splnodtb with microcode pointer somewhere in here'
  55. U_BOOT_TPL_NODTB_DATA = b'tplnodtb with microcode pointer somewhere in here'
  56. FSP_DATA = b'fsp'
  57. CMC_DATA = b'cmc'
  58. VBT_DATA = b'vbt'
  59. MRC_DATA = b'mrc'
  60. TEXT_DATA = 'text'
  61. TEXT_DATA2 = 'text2'
  62. TEXT_DATA3 = 'text3'
  63. CROS_EC_RW_DATA = b'ecrw'
  64. GBB_DATA = b'gbbd'
  65. BMPBLK_DATA = b'bmp'
  66. VBLOCK_DATA = b'vblk'
  67. FILES_DATA = (b"sorry I'm late\nOh, don't bother apologising, I'm " +
  68. b"sorry you're alive\n")
  69. COMPRESS_DATA = b'compress xxxxxxxxxxxxxxxxxxxxxx data'
  70. REFCODE_DATA = b'refcode'
  71. FSP_M_DATA = b'fsp_m'
  72. FSP_S_DATA = b'fsp_s'
  73. FSP_T_DATA = b'fsp_t'
  74. # The expected size for the device tree in some tests
  75. EXTRACT_DTB_SIZE = 0x3c9
  76. # Properties expected to be in the device tree when update_dtb is used
  77. BASE_DTB_PROPS = ['offset', 'size', 'image-pos']
  78. # Extra properties expected to be in the device tree when allow-repack is used
  79. REPACK_DTB_PROPS = ['orig-offset', 'orig-size']
  80. class TestFunctional(unittest.TestCase):
  81. """Functional tests for binman
  82. Most of these use a sample .dts file to build an image and then check
  83. that it looks correct. The sample files are in the test/ subdirectory
  84. and are numbered.
  85. For each entry type a very small test file is created using fixed
  86. string contents. This makes it easy to test that things look right, and
  87. debug problems.
  88. In some cases a 'real' file must be used - these are also supplied in
  89. the test/ diurectory.
  90. """
  91. @classmethod
  92. def setUpClass(cls):
  93. global entry
  94. from binman import entry
  95. # Handle the case where argv[0] is 'python'
  96. cls._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  97. cls._binman_pathname = os.path.join(cls._binman_dir, 'binman')
  98. # Create a temporary directory for input files
  99. cls._indir = tempfile.mkdtemp(prefix='binmant.')
  100. # Create some test files
  101. TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
  102. TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
  103. TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
  104. TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
  105. TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
  106. TestFunctional._MakeInputFile('me.bin', ME_DATA)
  107. TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
  108. cls._ResetDtbs()
  109. TestFunctional._MakeInputFile('u-boot-br.bin', PPC_MPC85XX_BR_DATA)
  110. TestFunctional._MakeInputFile('u-boot-x86-start16.bin', X86_START16_DATA)
  111. TestFunctional._MakeInputFile('spl/u-boot-x86-start16-spl.bin',
  112. X86_START16_SPL_DATA)
  113. TestFunctional._MakeInputFile('tpl/u-boot-x86-start16-tpl.bin',
  114. X86_START16_TPL_DATA)
  115. TestFunctional._MakeInputFile('u-boot-x86-reset16.bin',
  116. X86_RESET16_DATA)
  117. TestFunctional._MakeInputFile('spl/u-boot-x86-reset16-spl.bin',
  118. X86_RESET16_SPL_DATA)
  119. TestFunctional._MakeInputFile('tpl/u-boot-x86-reset16-tpl.bin',
  120. X86_RESET16_TPL_DATA)
  121. TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
  122. TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
  123. U_BOOT_SPL_NODTB_DATA)
  124. TestFunctional._MakeInputFile('tpl/u-boot-tpl-nodtb.bin',
  125. U_BOOT_TPL_NODTB_DATA)
  126. TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
  127. TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
  128. TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
  129. TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
  130. TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
  131. TestFunctional._MakeInputDir('devkeys')
  132. TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
  133. TestFunctional._MakeInputFile('refcode.bin', REFCODE_DATA)
  134. TestFunctional._MakeInputFile('fsp_m.bin', FSP_M_DATA)
  135. TestFunctional._MakeInputFile('fsp_s.bin', FSP_S_DATA)
  136. TestFunctional._MakeInputFile('fsp_t.bin', FSP_T_DATA)
  137. cls._elf_testdir = os.path.join(cls._indir, 'elftest')
  138. elf_test.BuildElfTestFiles(cls._elf_testdir)
  139. # ELF file with a '_dt_ucode_base_size' symbol
  140. TestFunctional._MakeInputFile('u-boot',
  141. tools.ReadFile(cls.ElfTestFile('u_boot_ucode_ptr')))
  142. # Intel flash descriptor file
  143. cls._SetupDescriptor()
  144. shutil.copytree(cls.TestFile('files'),
  145. os.path.join(cls._indir, 'files'))
  146. TestFunctional._MakeInputFile('compress', COMPRESS_DATA)
  147. # Travis-CI may have an old lz4
  148. cls.have_lz4 = True
  149. try:
  150. tools.Run('lz4', '--no-frame-crc', '-c',
  151. os.path.join(cls._indir, 'u-boot.bin'), binary=True)
  152. except:
  153. cls.have_lz4 = False
  154. @classmethod
  155. def tearDownClass(cls):
  156. """Remove the temporary input directory and its contents"""
  157. if cls.preserve_indir:
  158. print('Preserving input dir: %s' % cls._indir)
  159. else:
  160. if cls._indir:
  161. shutil.rmtree(cls._indir)
  162. cls._indir = None
  163. @classmethod
  164. def setup_test_args(cls, preserve_indir=False, preserve_outdirs=False,
  165. toolpath=None, verbosity=None):
  166. """Accept arguments controlling test execution
  167. Args:
  168. preserve_indir: Preserve the shared input directory used by all
  169. tests in this class.
  170. preserve_outdir: Preserve the output directories used by tests. Each
  171. test has its own, so this is normally only useful when running a
  172. single test.
  173. toolpath: ist of paths to use for tools
  174. """
  175. cls.preserve_indir = preserve_indir
  176. cls.preserve_outdirs = preserve_outdirs
  177. cls.toolpath = toolpath
  178. cls.verbosity = verbosity
  179. def _CheckLz4(self):
  180. if not self.have_lz4:
  181. self.skipTest('lz4 --no-frame-crc not available')
  182. def _CleanupOutputDir(self):
  183. """Remove the temporary output directory"""
  184. if self.preserve_outdirs:
  185. print('Preserving output dir: %s' % tools.outdir)
  186. else:
  187. tools._FinaliseForTest()
  188. def setUp(self):
  189. # Enable this to turn on debugging output
  190. # tout.Init(tout.DEBUG)
  191. command.test_result = None
  192. def tearDown(self):
  193. """Remove the temporary output directory"""
  194. self._CleanupOutputDir()
  195. def _SetupImageInTmpdir(self):
  196. """Set up the output image in a new temporary directory
  197. This is used when an image has been generated in the output directory,
  198. but we want to run binman again. This will create a new output
  199. directory and fail to delete the original one.
  200. This creates a new temporary directory, copies the image to it (with a
  201. new name) and removes the old output directory.
  202. Returns:
  203. Tuple:
  204. Temporary directory to use
  205. New image filename
  206. """
  207. image_fname = tools.GetOutputFilename('image.bin')
  208. tmpdir = tempfile.mkdtemp(prefix='binman.')
  209. updated_fname = os.path.join(tmpdir, 'image-updated.bin')
  210. tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
  211. self._CleanupOutputDir()
  212. return tmpdir, updated_fname
  213. @classmethod
  214. def _ResetDtbs(cls):
  215. TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
  216. TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
  217. TestFunctional._MakeInputFile('tpl/u-boot-tpl.dtb', U_BOOT_TPL_DTB_DATA)
  218. def _RunBinman(self, *args, **kwargs):
  219. """Run binman using the command line
  220. Args:
  221. Arguments to pass, as a list of strings
  222. kwargs: Arguments to pass to Command.RunPipe()
  223. """
  224. result = command.RunPipe([[self._binman_pathname] + list(args)],
  225. capture=True, capture_stderr=True, raise_on_error=False)
  226. if result.return_code and kwargs.get('raise_on_error', True):
  227. raise Exception("Error running '%s': %s" % (' '.join(args),
  228. result.stdout + result.stderr))
  229. return result
  230. def _DoBinman(self, *argv):
  231. """Run binman using directly (in the same process)
  232. Args:
  233. Arguments to pass, as a list of strings
  234. Returns:
  235. Return value (0 for success)
  236. """
  237. argv = list(argv)
  238. args = cmdline.ParseArgs(argv)
  239. args.pager = 'binman-invalid-pager'
  240. args.build_dir = self._indir
  241. # For testing, you can force an increase in verbosity here
  242. # args.verbosity = tout.DEBUG
  243. return control.Binman(args)
  244. def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
  245. entry_args=None, images=None, use_real_dtb=False,
  246. verbosity=None, allow_missing=False):
  247. """Run binman with a given test file
  248. Args:
  249. fname: Device-tree source filename to use (e.g. 005_simple.dts)
  250. debug: True to enable debugging output
  251. map: True to output map files for the images
  252. update_dtb: Update the offset and size of each entry in the device
  253. tree before packing it into the image
  254. entry_args: Dict of entry args to supply to binman
  255. key: arg name
  256. value: value of that arg
  257. images: List of image names to build
  258. use_real_dtb: True to use the test file as the contents of
  259. the u-boot-dtb entry. Normally this is not needed and the
  260. test contents (the U_BOOT_DTB_DATA string) can be used.
  261. But in some test we need the real contents.
  262. verbosity: Verbosity level to use (0-3, None=don't set it)
  263. allow_missing: Set the '--allow-missing' flag so that missing
  264. external binaries just produce a warning instead of an error
  265. """
  266. args = []
  267. if debug:
  268. args.append('-D')
  269. if verbosity is not None:
  270. args.append('-v%d' % verbosity)
  271. elif self.verbosity:
  272. args.append('-v%d' % self.verbosity)
  273. if self.toolpath:
  274. for path in self.toolpath:
  275. args += ['--toolpath', path]
  276. args += ['build', '-p', '-I', self._indir, '-d', self.TestFile(fname)]
  277. if map:
  278. args.append('-m')
  279. if update_dtb:
  280. args.append('-u')
  281. if not use_real_dtb:
  282. args.append('--fake-dtb')
  283. if entry_args:
  284. for arg, value in entry_args.items():
  285. args.append('-a%s=%s' % (arg, value))
  286. if allow_missing:
  287. args.append('-M')
  288. if images:
  289. for image in images:
  290. args += ['-i', image]
  291. return self._DoBinman(*args)
  292. def _SetupDtb(self, fname, outfile='u-boot.dtb'):
  293. """Set up a new test device-tree file
  294. The given file is compiled and set up as the device tree to be used
  295. for ths test.
  296. Args:
  297. fname: Filename of .dts file to read
  298. outfile: Output filename for compiled device-tree binary
  299. Returns:
  300. Contents of device-tree binary
  301. """
  302. tmpdir = tempfile.mkdtemp(prefix='binmant.')
  303. dtb = fdt_util.EnsureCompiled(self.TestFile(fname), tmpdir)
  304. with open(dtb, 'rb') as fd:
  305. data = fd.read()
  306. TestFunctional._MakeInputFile(outfile, data)
  307. shutil.rmtree(tmpdir)
  308. return data
  309. def _GetDtbContentsForSplTpl(self, dtb_data, name):
  310. """Create a version of the main DTB for SPL or SPL
  311. For testing we don't actually have different versions of the DTB. With
  312. U-Boot we normally run fdtgrep to remove unwanted nodes, but for tests
  313. we don't normally have any unwanted nodes.
  314. We still want the DTBs for SPL and TPL to be different though, since
  315. otherwise it is confusing to know which one we are looking at. So add
  316. an 'spl' or 'tpl' property to the top-level node.
  317. Args:
  318. dtb_data: dtb data to modify (this should be a value devicetree)
  319. name: Name of a new property to add
  320. Returns:
  321. New dtb data with the property added
  322. """
  323. dtb = fdt.Fdt.FromData(dtb_data)
  324. dtb.Scan()
  325. dtb.GetNode('/binman').AddZeroProp(name)
  326. dtb.Sync(auto_resize=True)
  327. dtb.Pack()
  328. return dtb.GetContents()
  329. def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
  330. update_dtb=False, entry_args=None, reset_dtbs=True):
  331. """Run binman and return the resulting image
  332. This runs binman with a given test file and then reads the resulting
  333. output file. It is a shortcut function since most tests need to do
  334. these steps.
  335. Raises an assertion failure if binman returns a non-zero exit code.
  336. Args:
  337. fname: Device-tree source filename to use (e.g. 005_simple.dts)
  338. use_real_dtb: True to use the test file as the contents of
  339. the u-boot-dtb entry. Normally this is not needed and the
  340. test contents (the U_BOOT_DTB_DATA string) can be used.
  341. But in some test we need the real contents.
  342. map: True to output map files for the images
  343. update_dtb: Update the offset and size of each entry in the device
  344. tree before packing it into the image
  345. entry_args: Dict of entry args to supply to binman
  346. key: arg name
  347. value: value of that arg
  348. reset_dtbs: With use_real_dtb the test dtb is overwritten by this
  349. function. If reset_dtbs is True, then the original test dtb
  350. is written back before this function finishes
  351. Returns:
  352. Tuple:
  353. Resulting image contents
  354. Device tree contents
  355. Map data showing contents of image (or None if none)
  356. Output device tree binary filename ('u-boot.dtb' path)
  357. """
  358. dtb_data = None
  359. # Use the compiled test file as the u-boot-dtb input
  360. if use_real_dtb:
  361. dtb_data = self._SetupDtb(fname)
  362. # For testing purposes, make a copy of the DT for SPL and TPL. Add
  363. # a node indicating which it is, so aid verification.
  364. for name in ['spl', 'tpl']:
  365. dtb_fname = '%s/u-boot-%s.dtb' % (name, name)
  366. outfile = os.path.join(self._indir, dtb_fname)
  367. TestFunctional._MakeInputFile(dtb_fname,
  368. self._GetDtbContentsForSplTpl(dtb_data, name))
  369. try:
  370. retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
  371. entry_args=entry_args, use_real_dtb=use_real_dtb)
  372. self.assertEqual(0, retcode)
  373. out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out')
  374. # Find the (only) image, read it and return its contents
  375. image = control.images['image']
  376. image_fname = tools.GetOutputFilename('image.bin')
  377. self.assertTrue(os.path.exists(image_fname))
  378. if map:
  379. map_fname = tools.GetOutputFilename('image.map')
  380. with open(map_fname) as fd:
  381. map_data = fd.read()
  382. else:
  383. map_data = None
  384. with open(image_fname, 'rb') as fd:
  385. return fd.read(), dtb_data, map_data, out_dtb_fname
  386. finally:
  387. # Put the test file back
  388. if reset_dtbs and use_real_dtb:
  389. self._ResetDtbs()
  390. def _DoReadFileRealDtb(self, fname):
  391. """Run binman with a real .dtb file and return the resulting data
  392. Args:
  393. fname: DT source filename to use (e.g. 082_fdt_update_all.dts)
  394. Returns:
  395. Resulting image contents
  396. """
  397. return self._DoReadFileDtb(fname, use_real_dtb=True, update_dtb=True)[0]
  398. def _DoReadFile(self, fname, use_real_dtb=False):
  399. """Helper function which discards the device-tree binary
  400. Args:
  401. fname: Device-tree source filename to use (e.g. 005_simple.dts)
  402. use_real_dtb: True to use the test file as the contents of
  403. the u-boot-dtb entry. Normally this is not needed and the
  404. test contents (the U_BOOT_DTB_DATA string) can be used.
  405. But in some test we need the real contents.
  406. Returns:
  407. Resulting image contents
  408. """
  409. return self._DoReadFileDtb(fname, use_real_dtb)[0]
  410. @classmethod
  411. def _MakeInputFile(cls, fname, contents):
  412. """Create a new test input file, creating directories as needed
  413. Args:
  414. fname: Filename to create
  415. contents: File contents to write in to the file
  416. Returns:
  417. Full pathname of file created
  418. """
  419. pathname = os.path.join(cls._indir, fname)
  420. dirname = os.path.dirname(pathname)
  421. if dirname and not os.path.exists(dirname):
  422. os.makedirs(dirname)
  423. with open(pathname, 'wb') as fd:
  424. fd.write(contents)
  425. return pathname
  426. @classmethod
  427. def _MakeInputDir(cls, dirname):
  428. """Create a new test input directory, creating directories as needed
  429. Args:
  430. dirname: Directory name to create
  431. Returns:
  432. Full pathname of directory created
  433. """
  434. pathname = os.path.join(cls._indir, dirname)
  435. if not os.path.exists(pathname):
  436. os.makedirs(pathname)
  437. return pathname
  438. @classmethod
  439. def _SetupSplElf(cls, src_fname='bss_data'):
  440. """Set up an ELF file with a '_dt_ucode_base_size' symbol
  441. Args:
  442. Filename of ELF file to use as SPL
  443. """
  444. TestFunctional._MakeInputFile('spl/u-boot-spl',
  445. tools.ReadFile(cls.ElfTestFile(src_fname)))
  446. @classmethod
  447. def _SetupTplElf(cls, src_fname='bss_data'):
  448. """Set up an ELF file with a '_dt_ucode_base_size' symbol
  449. Args:
  450. Filename of ELF file to use as TPL
  451. """
  452. TestFunctional._MakeInputFile('tpl/u-boot-tpl',
  453. tools.ReadFile(cls.ElfTestFile(src_fname)))
  454. @classmethod
  455. def _SetupDescriptor(cls):
  456. with open(cls.TestFile('descriptor.bin'), 'rb') as fd:
  457. TestFunctional._MakeInputFile('descriptor.bin', fd.read())
  458. @classmethod
  459. def TestFile(cls, fname):
  460. return os.path.join(cls._binman_dir, 'test', fname)
  461. @classmethod
  462. def ElfTestFile(cls, fname):
  463. return os.path.join(cls._elf_testdir, fname)
  464. def AssertInList(self, grep_list, target):
  465. """Assert that at least one of a list of things is in a target
  466. Args:
  467. grep_list: List of strings to check
  468. target: Target string
  469. """
  470. for grep in grep_list:
  471. if grep in target:
  472. return
  473. self.fail("Error: '%s' not found in '%s'" % (grep_list, target))
  474. def CheckNoGaps(self, entries):
  475. """Check that all entries fit together without gaps
  476. Args:
  477. entries: List of entries to check
  478. """
  479. offset = 0
  480. for entry in entries.values():
  481. self.assertEqual(offset, entry.offset)
  482. offset += entry.size
  483. def GetFdtLen(self, dtb):
  484. """Get the totalsize field from a device-tree binary
  485. Args:
  486. dtb: Device-tree binary contents
  487. Returns:
  488. Total size of device-tree binary, from the header
  489. """
  490. return struct.unpack('>L', dtb[4:8])[0]
  491. def _GetPropTree(self, dtb, prop_names, prefix='/binman/'):
  492. def AddNode(node, path):
  493. if node.name != '/':
  494. path += '/' + node.name
  495. for prop in node.props.values():
  496. if prop.name in prop_names:
  497. prop_path = path + ':' + prop.name
  498. tree[prop_path[len(prefix):]] = fdt_util.fdt32_to_cpu(
  499. prop.value)
  500. for subnode in node.subnodes:
  501. AddNode(subnode, path)
  502. tree = {}
  503. AddNode(dtb.GetRoot(), '')
  504. return tree
  505. def testRun(self):
  506. """Test a basic run with valid args"""
  507. result = self._RunBinman('-h')
  508. def testFullHelp(self):
  509. """Test that the full help is displayed with -H"""
  510. result = self._RunBinman('-H')
  511. help_file = os.path.join(self._binman_dir, 'README')
  512. # Remove possible extraneous strings
  513. extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
  514. gothelp = result.stdout.replace(extra, '')
  515. self.assertEqual(len(gothelp), os.path.getsize(help_file))
  516. self.assertEqual(0, len(result.stderr))
  517. self.assertEqual(0, result.return_code)
  518. def testFullHelpInternal(self):
  519. """Test that the full help is displayed with -H"""
  520. try:
  521. command.test_result = command.CommandResult()
  522. result = self._DoBinman('-H')
  523. help_file = os.path.join(self._binman_dir, 'README')
  524. finally:
  525. command.test_result = None
  526. def testHelp(self):
  527. """Test that the basic help is displayed with -h"""
  528. result = self._RunBinman('-h')
  529. self.assertTrue(len(result.stdout) > 200)
  530. self.assertEqual(0, len(result.stderr))
  531. self.assertEqual(0, result.return_code)
  532. def testBoard(self):
  533. """Test that we can run it with a specific board"""
  534. self._SetupDtb('005_simple.dts', 'sandbox/u-boot.dtb')
  535. TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
  536. result = self._DoBinman('build', '-b', 'sandbox')
  537. self.assertEqual(0, result)
  538. def testNeedBoard(self):
  539. """Test that we get an error when no board ius supplied"""
  540. with self.assertRaises(ValueError) as e:
  541. result = self._DoBinman('build')
  542. self.assertIn("Must provide a board to process (use -b <board>)",
  543. str(e.exception))
  544. def testMissingDt(self):
  545. """Test that an invalid device-tree file generates an error"""
  546. with self.assertRaises(Exception) as e:
  547. self._RunBinman('build', '-d', 'missing_file')
  548. # We get one error from libfdt, and a different one from fdtget.
  549. self.AssertInList(["Couldn't open blob from 'missing_file'",
  550. 'No such file or directory'], str(e.exception))
  551. def testBrokenDt(self):
  552. """Test that an invalid device-tree source file generates an error
  553. Since this is a source file it should be compiled and the error
  554. will come from the device-tree compiler (dtc).
  555. """
  556. with self.assertRaises(Exception) as e:
  557. self._RunBinman('build', '-d', self.TestFile('001_invalid.dts'))
  558. self.assertIn("FATAL ERROR: Unable to parse input tree",
  559. str(e.exception))
  560. def testMissingNode(self):
  561. """Test that a device tree without a 'binman' node generates an error"""
  562. with self.assertRaises(Exception) as e:
  563. self._DoBinman('build', '-d', self.TestFile('002_missing_node.dts'))
  564. self.assertIn("does not have a 'binman' node", str(e.exception))
  565. def testEmpty(self):
  566. """Test that an empty binman node works OK (i.e. does nothing)"""
  567. result = self._RunBinman('build', '-d', self.TestFile('003_empty.dts'))
  568. self.assertEqual(0, len(result.stderr))
  569. self.assertEqual(0, result.return_code)
  570. def testInvalidEntry(self):
  571. """Test that an invalid entry is flagged"""
  572. with self.assertRaises(Exception) as e:
  573. result = self._RunBinman('build', '-d',
  574. self.TestFile('004_invalid_entry.dts'))
  575. self.assertIn("Unknown entry type 'not-a-valid-type' in node "
  576. "'/binman/not-a-valid-type'", str(e.exception))
  577. def testSimple(self):
  578. """Test a simple binman with a single file"""
  579. data = self._DoReadFile('005_simple.dts')
  580. self.assertEqual(U_BOOT_DATA, data)
  581. def testSimpleDebug(self):
  582. """Test a simple binman run with debugging enabled"""
  583. self._DoTestFile('005_simple.dts', debug=True)
  584. def testDual(self):
  585. """Test that we can handle creating two images
  586. This also tests image padding.
  587. """
  588. retcode = self._DoTestFile('006_dual_image.dts')
  589. self.assertEqual(0, retcode)
  590. image = control.images['image1']
  591. self.assertEqual(len(U_BOOT_DATA), image.size)
  592. fname = tools.GetOutputFilename('image1.bin')
  593. self.assertTrue(os.path.exists(fname))
  594. with open(fname, 'rb') as fd:
  595. data = fd.read()
  596. self.assertEqual(U_BOOT_DATA, data)
  597. image = control.images['image2']
  598. self.assertEqual(3 + len(U_BOOT_DATA) + 5, image.size)
  599. fname = tools.GetOutputFilename('image2.bin')
  600. self.assertTrue(os.path.exists(fname))
  601. with open(fname, 'rb') as fd:
  602. data = fd.read()
  603. self.assertEqual(U_BOOT_DATA, data[3:7])
  604. self.assertEqual(tools.GetBytes(0, 3), data[:3])
  605. self.assertEqual(tools.GetBytes(0, 5), data[7:])
  606. def testBadAlign(self):
  607. """Test that an invalid alignment value is detected"""
  608. with self.assertRaises(ValueError) as e:
  609. self._DoTestFile('007_bad_align.dts')
  610. self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
  611. "of two", str(e.exception))
  612. def testPackSimple(self):
  613. """Test that packing works as expected"""
  614. retcode = self._DoTestFile('008_pack.dts')
  615. self.assertEqual(0, retcode)
  616. self.assertIn('image', control.images)
  617. image = control.images['image']
  618. entries = image.GetEntries()
  619. self.assertEqual(5, len(entries))
  620. # First u-boot
  621. self.assertIn('u-boot', entries)
  622. entry = entries['u-boot']
  623. self.assertEqual(0, entry.offset)
  624. self.assertEqual(len(U_BOOT_DATA), entry.size)
  625. # Second u-boot, aligned to 16-byte boundary
  626. self.assertIn('u-boot-align', entries)
  627. entry = entries['u-boot-align']
  628. self.assertEqual(16, entry.offset)
  629. self.assertEqual(len(U_BOOT_DATA), entry.size)
  630. # Third u-boot, size 23 bytes
  631. self.assertIn('u-boot-size', entries)
  632. entry = entries['u-boot-size']
  633. self.assertEqual(20, entry.offset)
  634. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  635. self.assertEqual(23, entry.size)
  636. # Fourth u-boot, placed immediate after the above
  637. self.assertIn('u-boot-next', entries)
  638. entry = entries['u-boot-next']
  639. self.assertEqual(43, entry.offset)
  640. self.assertEqual(len(U_BOOT_DATA), entry.size)
  641. # Fifth u-boot, placed at a fixed offset
  642. self.assertIn('u-boot-fixed', entries)
  643. entry = entries['u-boot-fixed']
  644. self.assertEqual(61, entry.offset)
  645. self.assertEqual(len(U_BOOT_DATA), entry.size)
  646. self.assertEqual(65, image.size)
  647. def testPackExtra(self):
  648. """Test that extra packing feature works as expected"""
  649. retcode = self._DoTestFile('009_pack_extra.dts')
  650. self.assertEqual(0, retcode)
  651. self.assertIn('image', control.images)
  652. image = control.images['image']
  653. entries = image.GetEntries()
  654. self.assertEqual(5, len(entries))
  655. # First u-boot with padding before and after
  656. self.assertIn('u-boot', entries)
  657. entry = entries['u-boot']
  658. self.assertEqual(0, entry.offset)
  659. self.assertEqual(3, entry.pad_before)
  660. self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
  661. # Second u-boot has an aligned size, but it has no effect
  662. self.assertIn('u-boot-align-size-nop', entries)
  663. entry = entries['u-boot-align-size-nop']
  664. self.assertEqual(12, entry.offset)
  665. self.assertEqual(4, entry.size)
  666. # Third u-boot has an aligned size too
  667. self.assertIn('u-boot-align-size', entries)
  668. entry = entries['u-boot-align-size']
  669. self.assertEqual(16, entry.offset)
  670. self.assertEqual(32, entry.size)
  671. # Fourth u-boot has an aligned end
  672. self.assertIn('u-boot-align-end', entries)
  673. entry = entries['u-boot-align-end']
  674. self.assertEqual(48, entry.offset)
  675. self.assertEqual(16, entry.size)
  676. # Fifth u-boot immediately afterwards
  677. self.assertIn('u-boot-align-both', entries)
  678. entry = entries['u-boot-align-both']
  679. self.assertEqual(64, entry.offset)
  680. self.assertEqual(64, entry.size)
  681. self.CheckNoGaps(entries)
  682. self.assertEqual(128, image.size)
  683. def testPackAlignPowerOf2(self):
  684. """Test that invalid entry alignment is detected"""
  685. with self.assertRaises(ValueError) as e:
  686. self._DoTestFile('010_pack_align_power2.dts')
  687. self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
  688. "of two", str(e.exception))
  689. def testPackAlignSizePowerOf2(self):
  690. """Test that invalid entry size alignment is detected"""
  691. with self.assertRaises(ValueError) as e:
  692. self._DoTestFile('011_pack_align_size_power2.dts')
  693. self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
  694. "power of two", str(e.exception))
  695. def testPackInvalidAlign(self):
  696. """Test detection of an offset that does not match its alignment"""
  697. with self.assertRaises(ValueError) as e:
  698. self._DoTestFile('012_pack_inv_align.dts')
  699. self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
  700. "align 0x4 (4)", str(e.exception))
  701. def testPackInvalidSizeAlign(self):
  702. """Test that invalid entry size alignment is detected"""
  703. with self.assertRaises(ValueError) as e:
  704. self._DoTestFile('013_pack_inv_size_align.dts')
  705. self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
  706. "align-size 0x4 (4)", str(e.exception))
  707. def testPackOverlap(self):
  708. """Test that overlapping regions are detected"""
  709. with self.assertRaises(ValueError) as e:
  710. self._DoTestFile('014_pack_overlap.dts')
  711. self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
  712. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  713. str(e.exception))
  714. def testPackEntryOverflow(self):
  715. """Test that entries that overflow their size are detected"""
  716. with self.assertRaises(ValueError) as e:
  717. self._DoTestFile('015_pack_overflow.dts')
  718. self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
  719. "but entry size is 0x3 (3)", str(e.exception))
  720. def testPackImageOverflow(self):
  721. """Test that entries which overflow the image size are detected"""
  722. with self.assertRaises(ValueError) as e:
  723. self._DoTestFile('016_pack_image_overflow.dts')
  724. self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
  725. "size 0x3 (3)", str(e.exception))
  726. def testPackImageSize(self):
  727. """Test that the image size can be set"""
  728. retcode = self._DoTestFile('017_pack_image_size.dts')
  729. self.assertEqual(0, retcode)
  730. self.assertIn('image', control.images)
  731. image = control.images['image']
  732. self.assertEqual(7, image.size)
  733. def testPackImageSizeAlign(self):
  734. """Test that image size alignemnt works as expected"""
  735. retcode = self._DoTestFile('018_pack_image_align.dts')
  736. self.assertEqual(0, retcode)
  737. self.assertIn('image', control.images)
  738. image = control.images['image']
  739. self.assertEqual(16, image.size)
  740. def testPackInvalidImageAlign(self):
  741. """Test that invalid image alignment is detected"""
  742. with self.assertRaises(ValueError) as e:
  743. self._DoTestFile('019_pack_inv_image_align.dts')
  744. self.assertIn("Section '/binman': Size 0x7 (7) does not match "
  745. "align-size 0x8 (8)", str(e.exception))
  746. def testPackAlignPowerOf2(self):
  747. """Test that invalid image alignment is detected"""
  748. with self.assertRaises(ValueError) as e:
  749. self._DoTestFile('020_pack_inv_image_align_power2.dts')
  750. self.assertIn("Image '/binman': Alignment size 131 must be a power of "
  751. "two", str(e.exception))
  752. def testImagePadByte(self):
  753. """Test that the image pad byte can be specified"""
  754. self._SetupSplElf()
  755. data = self._DoReadFile('021_image_pad.dts')
  756. self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0xff, 1) +
  757. U_BOOT_DATA, data)
  758. def testImageName(self):
  759. """Test that image files can be named"""
  760. retcode = self._DoTestFile('022_image_name.dts')
  761. self.assertEqual(0, retcode)
  762. image = control.images['image1']
  763. fname = tools.GetOutputFilename('test-name')
  764. self.assertTrue(os.path.exists(fname))
  765. image = control.images['image2']
  766. fname = tools.GetOutputFilename('test-name.xx')
  767. self.assertTrue(os.path.exists(fname))
  768. def testBlobFilename(self):
  769. """Test that generic blobs can be provided by filename"""
  770. data = self._DoReadFile('023_blob.dts')
  771. self.assertEqual(BLOB_DATA, data)
  772. def testPackSorted(self):
  773. """Test that entries can be sorted"""
  774. self._SetupSplElf()
  775. data = self._DoReadFile('024_sorted.dts')
  776. self.assertEqual(tools.GetBytes(0, 1) + U_BOOT_SPL_DATA +
  777. tools.GetBytes(0, 2) + U_BOOT_DATA, data)
  778. def testPackZeroOffset(self):
  779. """Test that an entry at offset 0 is not given a new offset"""
  780. with self.assertRaises(ValueError) as e:
  781. self._DoTestFile('025_pack_zero_size.dts')
  782. self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
  783. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  784. str(e.exception))
  785. def testPackUbootDtb(self):
  786. """Test that a device tree can be added to U-Boot"""
  787. data = self._DoReadFile('026_pack_u_boot_dtb.dts')
  788. self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
  789. def testPackX86RomNoSize(self):
  790. """Test that the end-at-4gb property requires a size property"""
  791. with self.assertRaises(ValueError) as e:
  792. self._DoTestFile('027_pack_4gb_no_size.dts')
  793. self.assertIn("Image '/binman': Section size must be provided when "
  794. "using end-at-4gb", str(e.exception))
  795. def test4gbAndSkipAtStartTogether(self):
  796. """Test that the end-at-4gb and skip-at-size property can't be used
  797. together"""
  798. with self.assertRaises(ValueError) as e:
  799. self._DoTestFile('098_4gb_and_skip_at_start_together.dts')
  800. self.assertIn("Image '/binman': Provide either 'end-at-4gb' or "
  801. "'skip-at-start'", str(e.exception))
  802. def testPackX86RomOutside(self):
  803. """Test that the end-at-4gb property checks for offset boundaries"""
  804. with self.assertRaises(ValueError) as e:
  805. self._DoTestFile('028_pack_4gb_outside.dts')
  806. self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) is outside "
  807. "the section starting at 0xffffffe0 (4294967264)",
  808. str(e.exception))
  809. def testPackX86Rom(self):
  810. """Test that a basic x86 ROM can be created"""
  811. self._SetupSplElf()
  812. data = self._DoReadFile('029_x86_rom.dts')
  813. self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 3) + U_BOOT_SPL_DATA +
  814. tools.GetBytes(0, 2), data)
  815. def testPackX86RomMeNoDesc(self):
  816. """Test that an invalid Intel descriptor entry is detected"""
  817. try:
  818. TestFunctional._MakeInputFile('descriptor-empty.bin', b'')
  819. with self.assertRaises(ValueError) as e:
  820. self._DoTestFile('163_x86_rom_me_empty.dts')
  821. self.assertIn("Node '/binman/intel-descriptor': Cannot find Intel Flash Descriptor (FD) signature",
  822. str(e.exception))
  823. finally:
  824. self._SetupDescriptor()
  825. def testPackX86RomBadDesc(self):
  826. """Test that the Intel requires a descriptor entry"""
  827. with self.assertRaises(ValueError) as e:
  828. self._DoTestFile('030_x86_rom_me_no_desc.dts')
  829. self.assertIn("Node '/binman/intel-me': No offset set with "
  830. "offset-unset: should another entry provide this correct "
  831. "offset?", str(e.exception))
  832. def testPackX86RomMe(self):
  833. """Test that an x86 ROM with an ME region can be created"""
  834. data = self._DoReadFile('031_x86_rom_me.dts')
  835. expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
  836. if data[:0x1000] != expected_desc:
  837. self.fail('Expected descriptor binary at start of image')
  838. self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
  839. def testPackVga(self):
  840. """Test that an image with a VGA binary can be created"""
  841. data = self._DoReadFile('032_intel_vga.dts')
  842. self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
  843. def testPackStart16(self):
  844. """Test that an image with an x86 start16 region can be created"""
  845. data = self._DoReadFile('033_x86_start16.dts')
  846. self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
  847. def testPackPowerpcMpc85xxBootpgResetvec(self):
  848. """Test that an image with powerpc-mpc85xx-bootpg-resetvec can be
  849. created"""
  850. data = self._DoReadFile('150_powerpc_mpc85xx_bootpg_resetvec.dts')
  851. self.assertEqual(PPC_MPC85XX_BR_DATA, data[:len(PPC_MPC85XX_BR_DATA)])
  852. def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
  853. """Handle running a test for insertion of microcode
  854. Args:
  855. dts_fname: Name of test .dts file
  856. nodtb_data: Data that we expect in the first section
  857. ucode_second: True if the microsecond entry is second instead of
  858. third
  859. Returns:
  860. Tuple:
  861. Contents of first region (U-Boot or SPL)
  862. Offset and size components of microcode pointer, as inserted
  863. in the above (two 4-byte words)
  864. """
  865. data = self._DoReadFile(dts_fname, True)
  866. # Now check the device tree has no microcode
  867. if ucode_second:
  868. ucode_content = data[len(nodtb_data):]
  869. ucode_pos = len(nodtb_data)
  870. dtb_with_ucode = ucode_content[16:]
  871. fdt_len = self.GetFdtLen(dtb_with_ucode)
  872. else:
  873. dtb_with_ucode = data[len(nodtb_data):]
  874. fdt_len = self.GetFdtLen(dtb_with_ucode)
  875. ucode_content = dtb_with_ucode[fdt_len:]
  876. ucode_pos = len(nodtb_data) + fdt_len
  877. fname = tools.GetOutputFilename('test.dtb')
  878. with open(fname, 'wb') as fd:
  879. fd.write(dtb_with_ucode)
  880. dtb = fdt.FdtScan(fname)
  881. ucode = dtb.GetNode('/microcode')
  882. self.assertTrue(ucode)
  883. for node in ucode.subnodes:
  884. self.assertFalse(node.props.get('data'))
  885. # Check that the microcode appears immediately after the Fdt
  886. # This matches the concatenation of the data properties in
  887. # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
  888. ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
  889. 0x78235609)
  890. self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
  891. # Check that the microcode pointer was inserted. It should match the
  892. # expected offset and size
  893. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  894. len(ucode_data))
  895. u_boot = data[:len(nodtb_data)]
  896. return u_boot, pos_and_size
  897. def testPackUbootMicrocode(self):
  898. """Test that x86 microcode can be handled correctly
  899. We expect to see the following in the image, in order:
  900. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  901. place
  902. u-boot.dtb with the microcode removed
  903. the microcode
  904. """
  905. first, pos_and_size = self._RunMicrocodeTest('034_x86_ucode.dts',
  906. U_BOOT_NODTB_DATA)
  907. self.assertEqual(b'nodtb with microcode' + pos_and_size +
  908. b' somewhere in here', first)
  909. def _RunPackUbootSingleMicrocode(self):
  910. """Test that x86 microcode can be handled correctly
  911. We expect to see the following in the image, in order:
  912. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  913. place
  914. u-boot.dtb with the microcode
  915. an empty microcode region
  916. """
  917. # We need the libfdt library to run this test since only that allows
  918. # finding the offset of a property. This is required by
  919. # Entry_u_boot_dtb_with_ucode.ObtainContents().
  920. data = self._DoReadFile('035_x86_single_ucode.dts', True)
  921. second = data[len(U_BOOT_NODTB_DATA):]
  922. fdt_len = self.GetFdtLen(second)
  923. third = second[fdt_len:]
  924. second = second[:fdt_len]
  925. ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
  926. self.assertIn(ucode_data, second)
  927. ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
  928. # Check that the microcode pointer was inserted. It should match the
  929. # expected offset and size
  930. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  931. len(ucode_data))
  932. first = data[:len(U_BOOT_NODTB_DATA)]
  933. self.assertEqual(b'nodtb with microcode' + pos_and_size +
  934. b' somewhere in here', first)
  935. def testPackUbootSingleMicrocode(self):
  936. """Test that x86 microcode can be handled correctly with fdt_normal.
  937. """
  938. self._RunPackUbootSingleMicrocode()
  939. def testUBootImg(self):
  940. """Test that u-boot.img can be put in a file"""
  941. data = self._DoReadFile('036_u_boot_img.dts')
  942. self.assertEqual(U_BOOT_IMG_DATA, data)
  943. def testNoMicrocode(self):
  944. """Test that a missing microcode region is detected"""
  945. with self.assertRaises(ValueError) as e:
  946. self._DoReadFile('037_x86_no_ucode.dts', True)
  947. self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
  948. "node found in ", str(e.exception))
  949. def testMicrocodeWithoutNode(self):
  950. """Test that a missing u-boot-dtb-with-ucode node is detected"""
  951. with self.assertRaises(ValueError) as e:
  952. self._DoReadFile('038_x86_ucode_missing_node.dts', True)
  953. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  954. "microcode region u-boot-dtb-with-ucode", str(e.exception))
  955. def testMicrocodeWithoutNode2(self):
  956. """Test that a missing u-boot-ucode node is detected"""
  957. with self.assertRaises(ValueError) as e:
  958. self._DoReadFile('039_x86_ucode_missing_node2.dts', True)
  959. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  960. "microcode region u-boot-ucode", str(e.exception))
  961. def testMicrocodeWithoutPtrInElf(self):
  962. """Test that a U-Boot binary without the microcode symbol is detected"""
  963. # ELF file without a '_dt_ucode_base_size' symbol
  964. try:
  965. TestFunctional._MakeInputFile('u-boot',
  966. tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
  967. with self.assertRaises(ValueError) as e:
  968. self._RunPackUbootSingleMicrocode()
  969. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
  970. "_dt_ucode_base_size symbol in u-boot", str(e.exception))
  971. finally:
  972. # Put the original file back
  973. TestFunctional._MakeInputFile('u-boot',
  974. tools.ReadFile(self.ElfTestFile('u_boot_ucode_ptr')))
  975. def testMicrocodeNotInImage(self):
  976. """Test that microcode must be placed within the image"""
  977. with self.assertRaises(ValueError) as e:
  978. self._DoReadFile('040_x86_ucode_not_in_image.dts', True)
  979. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
  980. "pointer _dt_ucode_base_size at fffffe14 is outside the "
  981. "section ranging from 00000000 to 0000002e", str(e.exception))
  982. def testWithoutMicrocode(self):
  983. """Test that we can cope with an image without microcode (e.g. qemu)"""
  984. TestFunctional._MakeInputFile('u-boot',
  985. tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
  986. data, dtb, _, _ = self._DoReadFileDtb('044_x86_optional_ucode.dts', True)
  987. # Now check the device tree has no microcode
  988. self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
  989. second = data[len(U_BOOT_NODTB_DATA):]
  990. fdt_len = self.GetFdtLen(second)
  991. self.assertEqual(dtb, second[:fdt_len])
  992. used_len = len(U_BOOT_NODTB_DATA) + fdt_len
  993. third = data[used_len:]
  994. self.assertEqual(tools.GetBytes(0, 0x200 - used_len), third)
  995. def testUnknownPosSize(self):
  996. """Test that microcode must be placed within the image"""
  997. with self.assertRaises(ValueError) as e:
  998. self._DoReadFile('041_unknown_pos_size.dts', True)
  999. self.assertIn("Section '/binman': Unable to set offset/size for unknown "
  1000. "entry 'invalid-entry'", str(e.exception))
  1001. def testPackFsp(self):
  1002. """Test that an image with a FSP binary can be created"""
  1003. data = self._DoReadFile('042_intel_fsp.dts')
  1004. self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
  1005. def testPackCmc(self):
  1006. """Test that an image with a CMC binary can be created"""
  1007. data = self._DoReadFile('043_intel_cmc.dts')
  1008. self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
  1009. def testPackVbt(self):
  1010. """Test that an image with a VBT binary can be created"""
  1011. data = self._DoReadFile('046_intel_vbt.dts')
  1012. self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
  1013. def testSplBssPad(self):
  1014. """Test that we can pad SPL's BSS with zeros"""
  1015. # ELF file with a '__bss_size' symbol
  1016. self._SetupSplElf()
  1017. data = self._DoReadFile('047_spl_bss_pad.dts')
  1018. self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
  1019. data)
  1020. def testSplBssPadMissing(self):
  1021. """Test that a missing symbol is detected"""
  1022. self._SetupSplElf('u_boot_ucode_ptr')
  1023. with self.assertRaises(ValueError) as e:
  1024. self._DoReadFile('047_spl_bss_pad.dts')
  1025. self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
  1026. str(e.exception))
  1027. def testPackStart16Spl(self):
  1028. """Test that an image with an x86 start16 SPL region can be created"""
  1029. data = self._DoReadFile('048_x86_start16_spl.dts')
  1030. self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
  1031. def _PackUbootSplMicrocode(self, dts, ucode_second=False):
  1032. """Helper function for microcode tests
  1033. We expect to see the following in the image, in order:
  1034. u-boot-spl-nodtb.bin with a microcode pointer inserted at the
  1035. correct place
  1036. u-boot.dtb with the microcode removed
  1037. the microcode
  1038. Args:
  1039. dts: Device tree file to use for test
  1040. ucode_second: True if the microsecond entry is second instead of
  1041. third
  1042. """
  1043. self._SetupSplElf('u_boot_ucode_ptr')
  1044. first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
  1045. ucode_second=ucode_second)
  1046. self.assertEqual(b'splnodtb with microc' + pos_and_size +
  1047. b'ter somewhere in here', first)
  1048. def testPackUbootSplMicrocode(self):
  1049. """Test that x86 microcode can be handled correctly in SPL"""
  1050. self._PackUbootSplMicrocode('049_x86_ucode_spl.dts')
  1051. def testPackUbootSplMicrocodeReorder(self):
  1052. """Test that order doesn't matter for microcode entries
  1053. This is the same as testPackUbootSplMicrocode but when we process the
  1054. u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
  1055. entry, so we reply on binman to try later.
  1056. """
  1057. self._PackUbootSplMicrocode('058_x86_ucode_spl_needs_retry.dts',
  1058. ucode_second=True)
  1059. def testPackMrc(self):
  1060. """Test that an image with an MRC binary can be created"""
  1061. data = self._DoReadFile('050_intel_mrc.dts')
  1062. self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
  1063. def testSplDtb(self):
  1064. """Test that an image with spl/u-boot-spl.dtb can be created"""
  1065. data = self._DoReadFile('051_u_boot_spl_dtb.dts')
  1066. self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
  1067. def testSplNoDtb(self):
  1068. """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
  1069. data = self._DoReadFile('052_u_boot_spl_nodtb.dts')
  1070. self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
  1071. def testSymbols(self):
  1072. """Test binman can assign symbols embedded in U-Boot"""
  1073. elf_fname = self.ElfTestFile('u_boot_binman_syms')
  1074. syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
  1075. addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
  1076. self.assertEqual(syms['_binman_u_boot_spl_prop_offset'].address, addr)
  1077. self._SetupSplElf('u_boot_binman_syms')
  1078. data = self._DoReadFile('053_symbols.dts')
  1079. sym_values = struct.pack('<LQLL', 0x00, 0x1c, 0x28, 0x04)
  1080. expected = (sym_values + U_BOOT_SPL_DATA[20:] +
  1081. tools.GetBytes(0xff, 1) + U_BOOT_DATA + sym_values +
  1082. U_BOOT_SPL_DATA[20:])
  1083. self.assertEqual(expected, data)
  1084. def testPackUnitAddress(self):
  1085. """Test that we support multiple binaries with the same name"""
  1086. data = self._DoReadFile('054_unit_address.dts')
  1087. self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
  1088. def testSections(self):
  1089. """Basic test of sections"""
  1090. data = self._DoReadFile('055_sections.dts')
  1091. expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
  1092. U_BOOT_DATA + tools.GetBytes(ord('a'), 12) +
  1093. U_BOOT_DATA + tools.GetBytes(ord('&'), 4))
  1094. self.assertEqual(expected, data)
  1095. def testMap(self):
  1096. """Tests outputting a map of the images"""
  1097. _, _, map_data, _ = self._DoReadFileDtb('055_sections.dts', map=True)
  1098. self.assertEqual('''ImagePos Offset Size Name
  1099. 00000000 00000000 00000028 main-section
  1100. 00000000 00000000 00000010 section@0
  1101. 00000000 00000000 00000004 u-boot
  1102. 00000010 00000010 00000010 section@1
  1103. 00000010 00000000 00000004 u-boot
  1104. 00000020 00000020 00000004 section@2
  1105. 00000020 00000000 00000004 u-boot
  1106. ''', map_data)
  1107. def testNamePrefix(self):
  1108. """Tests that name prefixes are used"""
  1109. _, _, map_data, _ = self._DoReadFileDtb('056_name_prefix.dts', map=True)
  1110. self.assertEqual('''ImagePos Offset Size Name
  1111. 00000000 00000000 00000028 main-section
  1112. 00000000 00000000 00000010 section@0
  1113. 00000000 00000000 00000004 ro-u-boot
  1114. 00000010 00000010 00000010 section@1
  1115. 00000010 00000000 00000004 rw-u-boot
  1116. ''', map_data)
  1117. def testUnknownContents(self):
  1118. """Test that obtaining the contents works as expected"""
  1119. with self.assertRaises(ValueError) as e:
  1120. self._DoReadFile('057_unknown_contents.dts', True)
  1121. self.assertIn("Image '/binman': Internal error: Could not complete "
  1122. "processing of contents: remaining ["
  1123. "<binman.etype._testing.Entry__testing ", str(e.exception))
  1124. def testBadChangeSize(self):
  1125. """Test that trying to change the size of an entry fails"""
  1126. try:
  1127. state.SetAllowEntryExpansion(False)
  1128. with self.assertRaises(ValueError) as e:
  1129. self._DoReadFile('059_change_size.dts', True)
  1130. self.assertIn("Node '/binman/_testing': Cannot update entry size from 2 to 3",
  1131. str(e.exception))
  1132. finally:
  1133. state.SetAllowEntryExpansion(True)
  1134. def testUpdateFdt(self):
  1135. """Test that we can update the device tree with offset/size info"""
  1136. _, _, _, out_dtb_fname = self._DoReadFileDtb('060_fdt_update.dts',
  1137. update_dtb=True)
  1138. dtb = fdt.Fdt(out_dtb_fname)
  1139. dtb.Scan()
  1140. props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
  1141. self.assertEqual({
  1142. 'image-pos': 0,
  1143. 'offset': 0,
  1144. '_testing:offset': 32,
  1145. '_testing:size': 2,
  1146. '_testing:image-pos': 32,
  1147. 'section@0/u-boot:offset': 0,
  1148. 'section@0/u-boot:size': len(U_BOOT_DATA),
  1149. 'section@0/u-boot:image-pos': 0,
  1150. 'section@0:offset': 0,
  1151. 'section@0:size': 16,
  1152. 'section@0:image-pos': 0,
  1153. 'section@1/u-boot:offset': 0,
  1154. 'section@1/u-boot:size': len(U_BOOT_DATA),
  1155. 'section@1/u-boot:image-pos': 16,
  1156. 'section@1:offset': 16,
  1157. 'section@1:size': 16,
  1158. 'section@1:image-pos': 16,
  1159. 'size': 40
  1160. }, props)
  1161. def testUpdateFdtBad(self):
  1162. """Test that we detect when ProcessFdt never completes"""
  1163. with self.assertRaises(ValueError) as e:
  1164. self._DoReadFileDtb('061_fdt_update_bad.dts', update_dtb=True)
  1165. self.assertIn('Could not complete processing of Fdt: remaining '
  1166. '[<binman.etype._testing.Entry__testing',
  1167. str(e.exception))
  1168. def testEntryArgs(self):
  1169. """Test passing arguments to entries from the command line"""
  1170. entry_args = {
  1171. 'test-str-arg': 'test1',
  1172. 'test-int-arg': '456',
  1173. }
  1174. self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
  1175. self.assertIn('image', control.images)
  1176. entry = control.images['image'].GetEntries()['_testing']
  1177. self.assertEqual('test0', entry.test_str_fdt)
  1178. self.assertEqual('test1', entry.test_str_arg)
  1179. self.assertEqual(123, entry.test_int_fdt)
  1180. self.assertEqual(456, entry.test_int_arg)
  1181. def testEntryArgsMissing(self):
  1182. """Test missing arguments and properties"""
  1183. entry_args = {
  1184. 'test-int-arg': '456',
  1185. }
  1186. self._DoReadFileDtb('063_entry_args_missing.dts', entry_args=entry_args)
  1187. entry = control.images['image'].GetEntries()['_testing']
  1188. self.assertEqual('test0', entry.test_str_fdt)
  1189. self.assertEqual(None, entry.test_str_arg)
  1190. self.assertEqual(None, entry.test_int_fdt)
  1191. self.assertEqual(456, entry.test_int_arg)
  1192. def testEntryArgsRequired(self):
  1193. """Test missing arguments and properties"""
  1194. entry_args = {
  1195. 'test-int-arg': '456',
  1196. }
  1197. with self.assertRaises(ValueError) as e:
  1198. self._DoReadFileDtb('064_entry_args_required.dts')
  1199. self.assertIn("Node '/binman/_testing': "
  1200. 'Missing required properties/entry args: test-str-arg, '
  1201. 'test-int-fdt, test-int-arg',
  1202. str(e.exception))
  1203. def testEntryArgsInvalidFormat(self):
  1204. """Test that an invalid entry-argument format is detected"""
  1205. args = ['build', '-d', self.TestFile('064_entry_args_required.dts'),
  1206. '-ano-value']
  1207. with self.assertRaises(ValueError) as e:
  1208. self._DoBinman(*args)
  1209. self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
  1210. def testEntryArgsInvalidInteger(self):
  1211. """Test that an invalid entry-argument integer is detected"""
  1212. entry_args = {
  1213. 'test-int-arg': 'abc',
  1214. }
  1215. with self.assertRaises(ValueError) as e:
  1216. self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
  1217. self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
  1218. "'test-int-arg' (value 'abc') to integer",
  1219. str(e.exception))
  1220. def testEntryArgsInvalidDatatype(self):
  1221. """Test that an invalid entry-argument datatype is detected
  1222. This test could be written in entry_test.py except that it needs
  1223. access to control.entry_args, which seems more than that module should
  1224. be able to see.
  1225. """
  1226. entry_args = {
  1227. 'test-bad-datatype-arg': '12',
  1228. }
  1229. with self.assertRaises(ValueError) as e:
  1230. self._DoReadFileDtb('065_entry_args_unknown_datatype.dts',
  1231. entry_args=entry_args)
  1232. self.assertIn('GetArg() internal error: Unknown data type ',
  1233. str(e.exception))
  1234. def testText(self):
  1235. """Test for a text entry type"""
  1236. entry_args = {
  1237. 'test-id': TEXT_DATA,
  1238. 'test-id2': TEXT_DATA2,
  1239. 'test-id3': TEXT_DATA3,
  1240. }
  1241. data, _, _, _ = self._DoReadFileDtb('066_text.dts',
  1242. entry_args=entry_args)
  1243. expected = (tools.ToBytes(TEXT_DATA) +
  1244. tools.GetBytes(0, 8 - len(TEXT_DATA)) +
  1245. tools.ToBytes(TEXT_DATA2) + tools.ToBytes(TEXT_DATA3) +
  1246. b'some text' + b'more text')
  1247. self.assertEqual(expected, data)
  1248. def testEntryDocs(self):
  1249. """Test for creation of entry documentation"""
  1250. with test_util.capture_sys_output() as (stdout, stderr):
  1251. control.WriteEntryDocs(control.GetEntryModules())
  1252. self.assertTrue(len(stdout.getvalue()) > 0)
  1253. def testEntryDocsMissing(self):
  1254. """Test handling of missing entry documentation"""
  1255. with self.assertRaises(ValueError) as e:
  1256. with test_util.capture_sys_output() as (stdout, stderr):
  1257. control.WriteEntryDocs(control.GetEntryModules(), 'u_boot')
  1258. self.assertIn('Documentation is missing for modules: u_boot',
  1259. str(e.exception))
  1260. def testFmap(self):
  1261. """Basic test of generation of a flashrom fmap"""
  1262. data = self._DoReadFile('067_fmap.dts')
  1263. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1264. expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
  1265. U_BOOT_DATA + tools.GetBytes(ord('a'), 12))
  1266. self.assertEqual(expected, data[:32])
  1267. self.assertEqual(b'__FMAP__', fhdr.signature)
  1268. self.assertEqual(1, fhdr.ver_major)
  1269. self.assertEqual(0, fhdr.ver_minor)
  1270. self.assertEqual(0, fhdr.base)
  1271. self.assertEqual(16 + 16 +
  1272. fmap_util.FMAP_HEADER_LEN +
  1273. fmap_util.FMAP_AREA_LEN * 3, fhdr.image_size)
  1274. self.assertEqual(b'FMAP', fhdr.name)
  1275. self.assertEqual(3, fhdr.nareas)
  1276. for fentry in fentries:
  1277. self.assertEqual(0, fentry.flags)
  1278. self.assertEqual(0, fentries[0].offset)
  1279. self.assertEqual(4, fentries[0].size)
  1280. self.assertEqual(b'RO_U_BOOT', fentries[0].name)
  1281. self.assertEqual(16, fentries[1].offset)
  1282. self.assertEqual(4, fentries[1].size)
  1283. self.assertEqual(b'RW_U_BOOT', fentries[1].name)
  1284. self.assertEqual(32, fentries[2].offset)
  1285. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1286. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1287. self.assertEqual(b'FMAP', fentries[2].name)
  1288. def testBlobNamedByArg(self):
  1289. """Test we can add a blob with the filename coming from an entry arg"""
  1290. entry_args = {
  1291. 'cros-ec-rw-path': 'ecrw.bin',
  1292. }
  1293. self._DoReadFileDtb('068_blob_named_by_arg.dts', entry_args=entry_args)
  1294. def testFill(self):
  1295. """Test for an fill entry type"""
  1296. data = self._DoReadFile('069_fill.dts')
  1297. expected = tools.GetBytes(0xff, 8) + tools.GetBytes(0, 8)
  1298. self.assertEqual(expected, data)
  1299. def testFillNoSize(self):
  1300. """Test for an fill entry type with no size"""
  1301. with self.assertRaises(ValueError) as e:
  1302. self._DoReadFile('070_fill_no_size.dts')
  1303. self.assertIn("'fill' entry must have a size property",
  1304. str(e.exception))
  1305. def _HandleGbbCommand(self, pipe_list):
  1306. """Fake calls to the futility utility"""
  1307. if pipe_list[0][0] == 'futility':
  1308. fname = pipe_list[0][-1]
  1309. # Append our GBB data to the file, which will happen every time the
  1310. # futility command is called.
  1311. with open(fname, 'ab') as fd:
  1312. fd.write(GBB_DATA)
  1313. return command.CommandResult()
  1314. def testGbb(self):
  1315. """Test for the Chromium OS Google Binary Block"""
  1316. command.test_result = self._HandleGbbCommand
  1317. entry_args = {
  1318. 'keydir': 'devkeys',
  1319. 'bmpblk': 'bmpblk.bin',
  1320. }
  1321. data, _, _, _ = self._DoReadFileDtb('071_gbb.dts', entry_args=entry_args)
  1322. # Since futility
  1323. expected = (GBB_DATA + GBB_DATA + tools.GetBytes(0, 8) +
  1324. tools.GetBytes(0, 0x2180 - 16))
  1325. self.assertEqual(expected, data)
  1326. def testGbbTooSmall(self):
  1327. """Test for the Chromium OS Google Binary Block being large enough"""
  1328. with self.assertRaises(ValueError) as e:
  1329. self._DoReadFileDtb('072_gbb_too_small.dts')
  1330. self.assertIn("Node '/binman/gbb': GBB is too small",
  1331. str(e.exception))
  1332. def testGbbNoSize(self):
  1333. """Test for the Chromium OS Google Binary Block having a size"""
  1334. with self.assertRaises(ValueError) as e:
  1335. self._DoReadFileDtb('073_gbb_no_size.dts')
  1336. self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
  1337. str(e.exception))
  1338. def _HandleVblockCommand(self, pipe_list):
  1339. """Fake calls to the futility utility"""
  1340. if pipe_list[0][0] == 'futility':
  1341. fname = pipe_list[0][3]
  1342. with open(fname, 'wb') as fd:
  1343. fd.write(VBLOCK_DATA)
  1344. return command.CommandResult()
  1345. def testVblock(self):
  1346. """Test for the Chromium OS Verified Boot Block"""
  1347. command.test_result = self._HandleVblockCommand
  1348. entry_args = {
  1349. 'keydir': 'devkeys',
  1350. }
  1351. data, _, _, _ = self._DoReadFileDtb('074_vblock.dts',
  1352. entry_args=entry_args)
  1353. expected = U_BOOT_DATA + VBLOCK_DATA + U_BOOT_DTB_DATA
  1354. self.assertEqual(expected, data)
  1355. def testVblockNoContent(self):
  1356. """Test we detect a vblock which has no content to sign"""
  1357. with self.assertRaises(ValueError) as e:
  1358. self._DoReadFile('075_vblock_no_content.dts')
  1359. self.assertIn("Node '/binman/vblock': Vblock must have a 'content' "
  1360. 'property', str(e.exception))
  1361. def testVblockBadPhandle(self):
  1362. """Test that we detect a vblock with an invalid phandle in contents"""
  1363. with self.assertRaises(ValueError) as e:
  1364. self._DoReadFile('076_vblock_bad_phandle.dts')
  1365. self.assertIn("Node '/binman/vblock': Cannot find node for phandle "
  1366. '1000', str(e.exception))
  1367. def testVblockBadEntry(self):
  1368. """Test that we detect an entry that points to a non-entry"""
  1369. with self.assertRaises(ValueError) as e:
  1370. self._DoReadFile('077_vblock_bad_entry.dts')
  1371. self.assertIn("Node '/binman/vblock': Cannot find entry for node "
  1372. "'other'", str(e.exception))
  1373. def testTpl(self):
  1374. """Test that an image with TPL and its device tree can be created"""
  1375. # ELF file with a '__bss_size' symbol
  1376. self._SetupTplElf()
  1377. data = self._DoReadFile('078_u_boot_tpl.dts')
  1378. self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
  1379. def testUsesPos(self):
  1380. """Test that the 'pos' property cannot be used anymore"""
  1381. with self.assertRaises(ValueError) as e:
  1382. data = self._DoReadFile('079_uses_pos.dts')
  1383. self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
  1384. "'pos'", str(e.exception))
  1385. def testFillZero(self):
  1386. """Test for an fill entry type with a size of 0"""
  1387. data = self._DoReadFile('080_fill_empty.dts')
  1388. self.assertEqual(tools.GetBytes(0, 16), data)
  1389. def testTextMissing(self):
  1390. """Test for a text entry type where there is no text"""
  1391. with self.assertRaises(ValueError) as e:
  1392. self._DoReadFileDtb('066_text.dts',)
  1393. self.assertIn("Node '/binman/text': No value provided for text label "
  1394. "'test-id'", str(e.exception))
  1395. def testPackStart16Tpl(self):
  1396. """Test that an image with an x86 start16 TPL region can be created"""
  1397. data = self._DoReadFile('081_x86_start16_tpl.dts')
  1398. self.assertEqual(X86_START16_TPL_DATA, data[:len(X86_START16_TPL_DATA)])
  1399. def testSelectImage(self):
  1400. """Test that we can select which images to build"""
  1401. expected = 'Skipping images: image1'
  1402. # We should only get the expected message in verbose mode
  1403. for verbosity in (0, 2):
  1404. with test_util.capture_sys_output() as (stdout, stderr):
  1405. retcode = self._DoTestFile('006_dual_image.dts',
  1406. verbosity=verbosity,
  1407. images=['image2'])
  1408. self.assertEqual(0, retcode)
  1409. if verbosity:
  1410. self.assertIn(expected, stdout.getvalue())
  1411. else:
  1412. self.assertNotIn(expected, stdout.getvalue())
  1413. self.assertFalse(os.path.exists(tools.GetOutputFilename('image1.bin')))
  1414. self.assertTrue(os.path.exists(tools.GetOutputFilename('image2.bin')))
  1415. self._CleanupOutputDir()
  1416. def testUpdateFdtAll(self):
  1417. """Test that all device trees are updated with offset/size info"""
  1418. data = self._DoReadFileRealDtb('082_fdt_update_all.dts')
  1419. base_expected = {
  1420. 'section:image-pos': 0,
  1421. 'u-boot-tpl-dtb:size': 513,
  1422. 'u-boot-spl-dtb:size': 513,
  1423. 'u-boot-spl-dtb:offset': 493,
  1424. 'image-pos': 0,
  1425. 'section/u-boot-dtb:image-pos': 0,
  1426. 'u-boot-spl-dtb:image-pos': 493,
  1427. 'section/u-boot-dtb:size': 493,
  1428. 'u-boot-tpl-dtb:image-pos': 1006,
  1429. 'section/u-boot-dtb:offset': 0,
  1430. 'section:size': 493,
  1431. 'offset': 0,
  1432. 'section:offset': 0,
  1433. 'u-boot-tpl-dtb:offset': 1006,
  1434. 'size': 1519
  1435. }
  1436. # We expect three device-tree files in the output, one after the other.
  1437. # Read them in sequence. We look for an 'spl' property in the SPL tree,
  1438. # and 'tpl' in the TPL tree, to make sure they are distinct from the
  1439. # main U-Boot tree. All three should have the same postions and offset.
  1440. start = 0
  1441. for item in ['', 'spl', 'tpl']:
  1442. dtb = fdt.Fdt.FromData(data[start:])
  1443. dtb.Scan()
  1444. props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS +
  1445. ['spl', 'tpl'])
  1446. expected = dict(base_expected)
  1447. if item:
  1448. expected[item] = 0
  1449. self.assertEqual(expected, props)
  1450. start += dtb._fdt_obj.totalsize()
  1451. def testUpdateFdtOutput(self):
  1452. """Test that output DTB files are updated"""
  1453. try:
  1454. data, dtb_data, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
  1455. use_real_dtb=True, update_dtb=True, reset_dtbs=False)
  1456. # Unfortunately, compiling a source file always results in a file
  1457. # called source.dtb (see fdt_util.EnsureCompiled()). The test
  1458. # source file (e.g. test/075_fdt_update_all.dts) thus does not enter
  1459. # binman as a file called u-boot.dtb. To fix this, copy the file
  1460. # over to the expected place.
  1461. start = 0
  1462. for fname in ['u-boot.dtb.out', 'spl/u-boot-spl.dtb.out',
  1463. 'tpl/u-boot-tpl.dtb.out']:
  1464. dtb = fdt.Fdt.FromData(data[start:])
  1465. size = dtb._fdt_obj.totalsize()
  1466. pathname = tools.GetOutputFilename(os.path.split(fname)[1])
  1467. outdata = tools.ReadFile(pathname)
  1468. name = os.path.split(fname)[0]
  1469. if name:
  1470. orig_indata = self._GetDtbContentsForSplTpl(dtb_data, name)
  1471. else:
  1472. orig_indata = dtb_data
  1473. self.assertNotEqual(outdata, orig_indata,
  1474. "Expected output file '%s' be updated" % pathname)
  1475. self.assertEqual(outdata, data[start:start + size],
  1476. "Expected output file '%s' to match output image" %
  1477. pathname)
  1478. start += size
  1479. finally:
  1480. self._ResetDtbs()
  1481. def _decompress(self, data):
  1482. return tools.Decompress(data, 'lz4')
  1483. def testCompress(self):
  1484. """Test compression of blobs"""
  1485. self._CheckLz4()
  1486. data, _, _, out_dtb_fname = self._DoReadFileDtb('083_compress.dts',
  1487. use_real_dtb=True, update_dtb=True)
  1488. dtb = fdt.Fdt(out_dtb_fname)
  1489. dtb.Scan()
  1490. props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
  1491. orig = self._decompress(data)
  1492. self.assertEquals(COMPRESS_DATA, orig)
  1493. expected = {
  1494. 'blob:uncomp-size': len(COMPRESS_DATA),
  1495. 'blob:size': len(data),
  1496. 'size': len(data),
  1497. }
  1498. self.assertEqual(expected, props)
  1499. def testFiles(self):
  1500. """Test bringing in multiple files"""
  1501. data = self._DoReadFile('084_files.dts')
  1502. self.assertEqual(FILES_DATA, data)
  1503. def testFilesCompress(self):
  1504. """Test bringing in multiple files and compressing them"""
  1505. self._CheckLz4()
  1506. data = self._DoReadFile('085_files_compress.dts')
  1507. image = control.images['image']
  1508. entries = image.GetEntries()
  1509. files = entries['files']
  1510. entries = files._entries
  1511. orig = b''
  1512. for i in range(1, 3):
  1513. key = '%d.dat' % i
  1514. start = entries[key].image_pos
  1515. len = entries[key].size
  1516. chunk = data[start:start + len]
  1517. orig += self._decompress(chunk)
  1518. self.assertEqual(FILES_DATA, orig)
  1519. def testFilesMissing(self):
  1520. """Test missing files"""
  1521. with self.assertRaises(ValueError) as e:
  1522. data = self._DoReadFile('086_files_none.dts')
  1523. self.assertIn("Node '/binman/files': Pattern \'files/*.none\' matched "
  1524. 'no files', str(e.exception))
  1525. def testFilesNoPattern(self):
  1526. """Test missing files"""
  1527. with self.assertRaises(ValueError) as e:
  1528. data = self._DoReadFile('087_files_no_pattern.dts')
  1529. self.assertIn("Node '/binman/files': Missing 'pattern' property",
  1530. str(e.exception))
  1531. def testExpandSize(self):
  1532. """Test an expanding entry"""
  1533. data, _, map_data, _ = self._DoReadFileDtb('088_expand_size.dts',
  1534. map=True)
  1535. expect = (tools.GetBytes(ord('a'), 8) + U_BOOT_DATA +
  1536. MRC_DATA + tools.GetBytes(ord('b'), 1) + U_BOOT_DATA +
  1537. tools.GetBytes(ord('c'), 8) + U_BOOT_DATA +
  1538. tools.GetBytes(ord('d'), 8))
  1539. self.assertEqual(expect, data)
  1540. self.assertEqual('''ImagePos Offset Size Name
  1541. 00000000 00000000 00000028 main-section
  1542. 00000000 00000000 00000008 fill
  1543. 00000008 00000008 00000004 u-boot
  1544. 0000000c 0000000c 00000004 section
  1545. 0000000c 00000000 00000003 intel-mrc
  1546. 00000010 00000010 00000004 u-boot2
  1547. 00000014 00000014 0000000c section2
  1548. 00000014 00000000 00000008 fill
  1549. 0000001c 00000008 00000004 u-boot
  1550. 00000020 00000020 00000008 fill2
  1551. ''', map_data)
  1552. def testExpandSizeBad(self):
  1553. """Test an expanding entry which fails to provide contents"""
  1554. with test_util.capture_sys_output() as (stdout, stderr):
  1555. with self.assertRaises(ValueError) as e:
  1556. self._DoReadFileDtb('089_expand_size_bad.dts', map=True)
  1557. self.assertIn("Node '/binman/_testing': Cannot obtain contents when "
  1558. 'expanding entry', str(e.exception))
  1559. def testHash(self):
  1560. """Test hashing of the contents of an entry"""
  1561. _, _, _, out_dtb_fname = self._DoReadFileDtb('090_hash.dts',
  1562. use_real_dtb=True, update_dtb=True)
  1563. dtb = fdt.Fdt(out_dtb_fname)
  1564. dtb.Scan()
  1565. hash_node = dtb.GetNode('/binman/u-boot/hash').props['value']
  1566. m = hashlib.sha256()
  1567. m.update(U_BOOT_DATA)
  1568. self.assertEqual(m.digest(), b''.join(hash_node.value))
  1569. def testHashNoAlgo(self):
  1570. with self.assertRaises(ValueError) as e:
  1571. self._DoReadFileDtb('091_hash_no_algo.dts', update_dtb=True)
  1572. self.assertIn("Node \'/binman/u-boot\': Missing \'algo\' property for "
  1573. 'hash node', str(e.exception))
  1574. def testHashBadAlgo(self):
  1575. with self.assertRaises(ValueError) as e:
  1576. self._DoReadFileDtb('092_hash_bad_algo.dts', update_dtb=True)
  1577. self.assertIn("Node '/binman/u-boot': Unknown hash algorithm",
  1578. str(e.exception))
  1579. def testHashSection(self):
  1580. """Test hashing of the contents of an entry"""
  1581. _, _, _, out_dtb_fname = self._DoReadFileDtb('099_hash_section.dts',
  1582. use_real_dtb=True, update_dtb=True)
  1583. dtb = fdt.Fdt(out_dtb_fname)
  1584. dtb.Scan()
  1585. hash_node = dtb.GetNode('/binman/section/hash').props['value']
  1586. m = hashlib.sha256()
  1587. m.update(U_BOOT_DATA)
  1588. m.update(tools.GetBytes(ord('a'), 16))
  1589. self.assertEqual(m.digest(), b''.join(hash_node.value))
  1590. def testPackUBootTplMicrocode(self):
  1591. """Test that x86 microcode can be handled correctly in TPL
  1592. We expect to see the following in the image, in order:
  1593. u-boot-tpl-nodtb.bin with a microcode pointer inserted at the correct
  1594. place
  1595. u-boot-tpl.dtb with the microcode removed
  1596. the microcode
  1597. """
  1598. self._SetupTplElf('u_boot_ucode_ptr')
  1599. first, pos_and_size = self._RunMicrocodeTest('093_x86_tpl_ucode.dts',
  1600. U_BOOT_TPL_NODTB_DATA)
  1601. self.assertEqual(b'tplnodtb with microc' + pos_and_size +
  1602. b'ter somewhere in here', first)
  1603. def testFmapX86(self):
  1604. """Basic test of generation of a flashrom fmap"""
  1605. data = self._DoReadFile('094_fmap_x86.dts')
  1606. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1607. expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('a'), 32 - 7)
  1608. self.assertEqual(expected, data[:32])
  1609. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1610. self.assertEqual(0x100, fhdr.image_size)
  1611. self.assertEqual(0, fentries[0].offset)
  1612. self.assertEqual(4, fentries[0].size)
  1613. self.assertEqual(b'U_BOOT', fentries[0].name)
  1614. self.assertEqual(4, fentries[1].offset)
  1615. self.assertEqual(3, fentries[1].size)
  1616. self.assertEqual(b'INTEL_MRC', fentries[1].name)
  1617. self.assertEqual(32, fentries[2].offset)
  1618. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1619. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1620. self.assertEqual(b'FMAP', fentries[2].name)
  1621. def testFmapX86Section(self):
  1622. """Basic test of generation of a flashrom fmap"""
  1623. data = self._DoReadFile('095_fmap_x86_section.dts')
  1624. expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('b'), 32 - 7)
  1625. self.assertEqual(expected, data[:32])
  1626. fhdr, fentries = fmap_util.DecodeFmap(data[36:])
  1627. self.assertEqual(0x100, fhdr.image_size)
  1628. self.assertEqual(0, fentries[0].offset)
  1629. self.assertEqual(4, fentries[0].size)
  1630. self.assertEqual(b'U_BOOT', fentries[0].name)
  1631. self.assertEqual(4, fentries[1].offset)
  1632. self.assertEqual(3, fentries[1].size)
  1633. self.assertEqual(b'INTEL_MRC', fentries[1].name)
  1634. self.assertEqual(36, fentries[2].offset)
  1635. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1636. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1637. self.assertEqual(b'FMAP', fentries[2].name)
  1638. def testElf(self):
  1639. """Basic test of ELF entries"""
  1640. self._SetupSplElf()
  1641. self._SetupTplElf()
  1642. with open(self.ElfTestFile('bss_data'), 'rb') as fd:
  1643. TestFunctional._MakeInputFile('-boot', fd.read())
  1644. data = self._DoReadFile('096_elf.dts')
  1645. def testElfStrip(self):
  1646. """Basic test of ELF entries"""
  1647. self._SetupSplElf()
  1648. with open(self.ElfTestFile('bss_data'), 'rb') as fd:
  1649. TestFunctional._MakeInputFile('-boot', fd.read())
  1650. data = self._DoReadFile('097_elf_strip.dts')
  1651. def testPackOverlapMap(self):
  1652. """Test that overlapping regions are detected"""
  1653. with test_util.capture_sys_output() as (stdout, stderr):
  1654. with self.assertRaises(ValueError) as e:
  1655. self._DoTestFile('014_pack_overlap.dts', map=True)
  1656. map_fname = tools.GetOutputFilename('image.map')
  1657. self.assertEqual("Wrote map file '%s' to show errors\n" % map_fname,
  1658. stdout.getvalue())
  1659. # We should not get an inmage, but there should be a map file
  1660. self.assertFalse(os.path.exists(tools.GetOutputFilename('image.bin')))
  1661. self.assertTrue(os.path.exists(map_fname))
  1662. map_data = tools.ReadFile(map_fname, binary=False)
  1663. self.assertEqual('''ImagePos Offset Size Name
  1664. <none> 00000000 00000007 main-section
  1665. <none> 00000000 00000004 u-boot
  1666. <none> 00000003 00000004 u-boot-align
  1667. ''', map_data)
  1668. def testPackRefCode(self):
  1669. """Test that an image with an Intel Reference code binary works"""
  1670. data = self._DoReadFile('100_intel_refcode.dts')
  1671. self.assertEqual(REFCODE_DATA, data[:len(REFCODE_DATA)])
  1672. def testSectionOffset(self):
  1673. """Tests use of a section with an offset"""
  1674. data, _, map_data, _ = self._DoReadFileDtb('101_sections_offset.dts',
  1675. map=True)
  1676. self.assertEqual('''ImagePos Offset Size Name
  1677. 00000000 00000000 00000038 main-section
  1678. 00000004 00000004 00000010 section@0
  1679. 00000004 00000000 00000004 u-boot
  1680. 00000018 00000018 00000010 section@1
  1681. 00000018 00000000 00000004 u-boot
  1682. 0000002c 0000002c 00000004 section@2
  1683. 0000002c 00000000 00000004 u-boot
  1684. ''', map_data)
  1685. self.assertEqual(data,
  1686. tools.GetBytes(0x26, 4) + U_BOOT_DATA +
  1687. tools.GetBytes(0x21, 12) +
  1688. tools.GetBytes(0x26, 4) + U_BOOT_DATA +
  1689. tools.GetBytes(0x61, 12) +
  1690. tools.GetBytes(0x26, 4) + U_BOOT_DATA +
  1691. tools.GetBytes(0x26, 8))
  1692. def testCbfsRaw(self):
  1693. """Test base handling of a Coreboot Filesystem (CBFS)
  1694. The exact contents of the CBFS is verified by similar tests in
  1695. cbfs_util_test.py. The tests here merely check that the files added to
  1696. the CBFS can be found in the final image.
  1697. """
  1698. data = self._DoReadFile('102_cbfs_raw.dts')
  1699. size = 0xb0
  1700. cbfs = cbfs_util.CbfsReader(data)
  1701. self.assertEqual(size, cbfs.rom_size)
  1702. self.assertIn('u-boot-dtb', cbfs.files)
  1703. cfile = cbfs.files['u-boot-dtb']
  1704. self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
  1705. def testCbfsArch(self):
  1706. """Test on non-x86 architecture"""
  1707. data = self._DoReadFile('103_cbfs_raw_ppc.dts')
  1708. size = 0x100
  1709. cbfs = cbfs_util.CbfsReader(data)
  1710. self.assertEqual(size, cbfs.rom_size)
  1711. self.assertIn('u-boot-dtb', cbfs.files)
  1712. cfile = cbfs.files['u-boot-dtb']
  1713. self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
  1714. def testCbfsStage(self):
  1715. """Tests handling of a Coreboot Filesystem (CBFS)"""
  1716. if not elf.ELF_TOOLS:
  1717. self.skipTest('Python elftools not available')
  1718. elf_fname = os.path.join(self._indir, 'cbfs-stage.elf')
  1719. elf.MakeElf(elf_fname, U_BOOT_DATA, U_BOOT_DTB_DATA)
  1720. size = 0xb0
  1721. data = self._DoReadFile('104_cbfs_stage.dts')
  1722. cbfs = cbfs_util.CbfsReader(data)
  1723. self.assertEqual(size, cbfs.rom_size)
  1724. self.assertIn('u-boot', cbfs.files)
  1725. cfile = cbfs.files['u-boot']
  1726. self.assertEqual(U_BOOT_DATA + U_BOOT_DTB_DATA, cfile.data)
  1727. def testCbfsRawCompress(self):
  1728. """Test handling of compressing raw files"""
  1729. self._CheckLz4()
  1730. data = self._DoReadFile('105_cbfs_raw_compress.dts')
  1731. size = 0x140
  1732. cbfs = cbfs_util.CbfsReader(data)
  1733. self.assertIn('u-boot', cbfs.files)
  1734. cfile = cbfs.files['u-boot']
  1735. self.assertEqual(COMPRESS_DATA, cfile.data)
  1736. def testCbfsBadArch(self):
  1737. """Test handling of a bad architecture"""
  1738. with self.assertRaises(ValueError) as e:
  1739. self._DoReadFile('106_cbfs_bad_arch.dts')
  1740. self.assertIn("Invalid architecture 'bad-arch'", str(e.exception))
  1741. def testCbfsNoSize(self):
  1742. """Test handling of a missing size property"""
  1743. with self.assertRaises(ValueError) as e:
  1744. self._DoReadFile('107_cbfs_no_size.dts')
  1745. self.assertIn('entry must have a size property', str(e.exception))
  1746. def testCbfsNoCOntents(self):
  1747. """Test handling of a CBFS entry which does not provide contentsy"""
  1748. with self.assertRaises(ValueError) as e:
  1749. self._DoReadFile('108_cbfs_no_contents.dts')
  1750. self.assertIn('Could not complete processing of contents',
  1751. str(e.exception))
  1752. def testCbfsBadCompress(self):
  1753. """Test handling of a bad architecture"""
  1754. with self.assertRaises(ValueError) as e:
  1755. self._DoReadFile('109_cbfs_bad_compress.dts')
  1756. self.assertIn("Invalid compression in 'u-boot': 'invalid-algo'",
  1757. str(e.exception))
  1758. def testCbfsNamedEntries(self):
  1759. """Test handling of named entries"""
  1760. data = self._DoReadFile('110_cbfs_name.dts')
  1761. cbfs = cbfs_util.CbfsReader(data)
  1762. self.assertIn('FRED', cbfs.files)
  1763. cfile1 = cbfs.files['FRED']
  1764. self.assertEqual(U_BOOT_DATA, cfile1.data)
  1765. self.assertIn('hello', cbfs.files)
  1766. cfile2 = cbfs.files['hello']
  1767. self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
  1768. def _SetupIfwi(self, fname):
  1769. """Set up to run an IFWI test
  1770. Args:
  1771. fname: Filename of input file to provide (fitimage.bin or ifwi.bin)
  1772. """
  1773. self._SetupSplElf()
  1774. self._SetupTplElf()
  1775. # Intel Integrated Firmware Image (IFWI) file
  1776. with gzip.open(self.TestFile('%s.gz' % fname), 'rb') as fd:
  1777. data = fd.read()
  1778. TestFunctional._MakeInputFile(fname,data)
  1779. def _CheckIfwi(self, data):
  1780. """Check that an image with an IFWI contains the correct output
  1781. Args:
  1782. data: Conents of output file
  1783. """
  1784. expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
  1785. if data[:0x1000] != expected_desc:
  1786. self.fail('Expected descriptor binary at start of image')
  1787. # We expect to find the TPL wil in subpart IBBP entry IBBL
  1788. image_fname = tools.GetOutputFilename('image.bin')
  1789. tpl_fname = tools.GetOutputFilename('tpl.out')
  1790. tools.RunIfwiTool(image_fname, tools.CMD_EXTRACT, fname=tpl_fname,
  1791. subpart='IBBP', entry_name='IBBL')
  1792. tpl_data = tools.ReadFile(tpl_fname)
  1793. self.assertEqual(U_BOOT_TPL_DATA, tpl_data[:len(U_BOOT_TPL_DATA)])
  1794. def testPackX86RomIfwi(self):
  1795. """Test that an x86 ROM with Integrated Firmware Image can be created"""
  1796. self._SetupIfwi('fitimage.bin')
  1797. data = self._DoReadFile('111_x86_rom_ifwi.dts')
  1798. self._CheckIfwi(data)
  1799. def testPackX86RomIfwiNoDesc(self):
  1800. """Test that an x86 ROM with IFWI can be created from an ifwi.bin file"""
  1801. self._SetupIfwi('ifwi.bin')
  1802. data = self._DoReadFile('112_x86_rom_ifwi_nodesc.dts')
  1803. self._CheckIfwi(data)
  1804. def testPackX86RomIfwiNoData(self):
  1805. """Test that an x86 ROM with IFWI handles missing data"""
  1806. self._SetupIfwi('ifwi.bin')
  1807. with self.assertRaises(ValueError) as e:
  1808. data = self._DoReadFile('113_x86_rom_ifwi_nodata.dts')
  1809. self.assertIn('Could not complete processing of contents',
  1810. str(e.exception))
  1811. def testCbfsOffset(self):
  1812. """Test a CBFS with files at particular offsets
  1813. Like all CFBS tests, this is just checking the logic that calls
  1814. cbfs_util. See cbfs_util_test for fully tests (e.g. test_cbfs_offset()).
  1815. """
  1816. data = self._DoReadFile('114_cbfs_offset.dts')
  1817. size = 0x200
  1818. cbfs = cbfs_util.CbfsReader(data)
  1819. self.assertEqual(size, cbfs.rom_size)
  1820. self.assertIn('u-boot', cbfs.files)
  1821. cfile = cbfs.files['u-boot']
  1822. self.assertEqual(U_BOOT_DATA, cfile.data)
  1823. self.assertEqual(0x40, cfile.cbfs_offset)
  1824. self.assertIn('u-boot-dtb', cbfs.files)
  1825. cfile2 = cbfs.files['u-boot-dtb']
  1826. self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
  1827. self.assertEqual(0x140, cfile2.cbfs_offset)
  1828. def testFdtmap(self):
  1829. """Test an FDT map can be inserted in the image"""
  1830. data = self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
  1831. fdtmap_data = data[len(U_BOOT_DATA):]
  1832. magic = fdtmap_data[:8]
  1833. self.assertEqual(b'_FDTMAP_', magic)
  1834. self.assertEqual(tools.GetBytes(0, 8), fdtmap_data[8:16])
  1835. fdt_data = fdtmap_data[16:]
  1836. dtb = fdt.Fdt.FromData(fdt_data)
  1837. dtb.Scan()
  1838. props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
  1839. self.assertEqual({
  1840. 'image-pos': 0,
  1841. 'offset': 0,
  1842. 'u-boot:offset': 0,
  1843. 'u-boot:size': len(U_BOOT_DATA),
  1844. 'u-boot:image-pos': 0,
  1845. 'fdtmap:image-pos': 4,
  1846. 'fdtmap:offset': 4,
  1847. 'fdtmap:size': len(fdtmap_data),
  1848. 'size': len(data),
  1849. }, props)
  1850. def testFdtmapNoMatch(self):
  1851. """Check handling of an FDT map when the section cannot be found"""
  1852. self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
  1853. # Mangle the section name, which should cause a mismatch between the
  1854. # correct FDT path and the one expected by the section
  1855. image = control.images['image']
  1856. image._node.path += '-suffix'
  1857. entries = image.GetEntries()
  1858. fdtmap = entries['fdtmap']
  1859. with self.assertRaises(ValueError) as e:
  1860. fdtmap._GetFdtmap()
  1861. self.assertIn("Cannot locate node for path '/binman-suffix'",
  1862. str(e.exception))
  1863. def testFdtmapHeader(self):
  1864. """Test an FDT map and image header can be inserted in the image"""
  1865. data = self.data = self._DoReadFileRealDtb('116_fdtmap_hdr.dts')
  1866. fdtmap_pos = len(U_BOOT_DATA)
  1867. fdtmap_data = data[fdtmap_pos:]
  1868. fdt_data = fdtmap_data[16:]
  1869. dtb = fdt.Fdt.FromData(fdt_data)
  1870. fdt_size = dtb.GetFdtObj().totalsize()
  1871. hdr_data = data[-8:]
  1872. self.assertEqual(b'BinM', hdr_data[:4])
  1873. offset = struct.unpack('<I', hdr_data[4:])[0] & 0xffffffff
  1874. self.assertEqual(fdtmap_pos - 0x400, offset - (1 << 32))
  1875. def testFdtmapHeaderStart(self):
  1876. """Test an image header can be inserted at the image start"""
  1877. data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
  1878. fdtmap_pos = 0x100 + len(U_BOOT_DATA)
  1879. hdr_data = data[:8]
  1880. self.assertEqual(b'BinM', hdr_data[:4])
  1881. offset = struct.unpack('<I', hdr_data[4:])[0]
  1882. self.assertEqual(fdtmap_pos, offset)
  1883. def testFdtmapHeaderPos(self):
  1884. """Test an image header can be inserted at a chosen position"""
  1885. data = self.data = self._DoReadFileRealDtb('118_fdtmap_hdr_pos.dts')
  1886. fdtmap_pos = 0x100 + len(U_BOOT_DATA)
  1887. hdr_data = data[0x80:0x88]
  1888. self.assertEqual(b'BinM', hdr_data[:4])
  1889. offset = struct.unpack('<I', hdr_data[4:])[0]
  1890. self.assertEqual(fdtmap_pos, offset)
  1891. def testHeaderMissingFdtmap(self):
  1892. """Test an image header requires an fdtmap"""
  1893. with self.assertRaises(ValueError) as e:
  1894. self.data = self._DoReadFileRealDtb('119_fdtmap_hdr_missing.dts')
  1895. self.assertIn("'image_header' section must have an 'fdtmap' sibling",
  1896. str(e.exception))
  1897. def testHeaderNoLocation(self):
  1898. """Test an image header with a no specified location is detected"""
  1899. with self.assertRaises(ValueError) as e:
  1900. self.data = self._DoReadFileRealDtb('120_hdr_no_location.dts')
  1901. self.assertIn("Invalid location 'None', expected 'start' or 'end'",
  1902. str(e.exception))
  1903. def testEntryExpand(self):
  1904. """Test expanding an entry after it is packed"""
  1905. data = self._DoReadFile('121_entry_expand.dts')
  1906. self.assertEqual(b'aaa', data[:3])
  1907. self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
  1908. self.assertEqual(b'aaa', data[-3:])
  1909. def testEntryExpandBad(self):
  1910. """Test expanding an entry after it is packed, twice"""
  1911. with self.assertRaises(ValueError) as e:
  1912. self._DoReadFile('122_entry_expand_twice.dts')
  1913. self.assertIn("Image '/binman': Entries changed size after packing",
  1914. str(e.exception))
  1915. def testEntryExpandSection(self):
  1916. """Test expanding an entry within a section after it is packed"""
  1917. data = self._DoReadFile('123_entry_expand_section.dts')
  1918. self.assertEqual(b'aaa', data[:3])
  1919. self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
  1920. self.assertEqual(b'aaa', data[-3:])
  1921. def testCompressDtb(self):
  1922. """Test that compress of device-tree files is supported"""
  1923. self._CheckLz4()
  1924. data = self.data = self._DoReadFileRealDtb('124_compress_dtb.dts')
  1925. self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
  1926. comp_data = data[len(U_BOOT_DATA):]
  1927. orig = self._decompress(comp_data)
  1928. dtb = fdt.Fdt.FromData(orig)
  1929. dtb.Scan()
  1930. props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
  1931. expected = {
  1932. 'u-boot:size': len(U_BOOT_DATA),
  1933. 'u-boot-dtb:uncomp-size': len(orig),
  1934. 'u-boot-dtb:size': len(comp_data),
  1935. 'size': len(data),
  1936. }
  1937. self.assertEqual(expected, props)
  1938. def testCbfsUpdateFdt(self):
  1939. """Test that we can update the device tree with CBFS offset/size info"""
  1940. self._CheckLz4()
  1941. data, _, _, out_dtb_fname = self._DoReadFileDtb('125_cbfs_update.dts',
  1942. update_dtb=True)
  1943. dtb = fdt.Fdt(out_dtb_fname)
  1944. dtb.Scan()
  1945. props = self._GetPropTree(dtb, BASE_DTB_PROPS + ['uncomp-size'])
  1946. del props['cbfs/u-boot:size']
  1947. self.assertEqual({
  1948. 'offset': 0,
  1949. 'size': len(data),
  1950. 'image-pos': 0,
  1951. 'cbfs:offset': 0,
  1952. 'cbfs:size': len(data),
  1953. 'cbfs:image-pos': 0,
  1954. 'cbfs/u-boot:offset': 0x38,
  1955. 'cbfs/u-boot:uncomp-size': len(U_BOOT_DATA),
  1956. 'cbfs/u-boot:image-pos': 0x38,
  1957. 'cbfs/u-boot-dtb:offset': 0xb8,
  1958. 'cbfs/u-boot-dtb:size': len(U_BOOT_DATA),
  1959. 'cbfs/u-boot-dtb:image-pos': 0xb8,
  1960. }, props)
  1961. def testCbfsBadType(self):
  1962. """Test an image header with a no specified location is detected"""
  1963. with self.assertRaises(ValueError) as e:
  1964. self._DoReadFile('126_cbfs_bad_type.dts')
  1965. self.assertIn("Unknown cbfs-type 'badtype'", str(e.exception))
  1966. def testList(self):
  1967. """Test listing the files in an image"""
  1968. self._CheckLz4()
  1969. data = self._DoReadFile('127_list.dts')
  1970. image = control.images['image']
  1971. entries = image.BuildEntryList()
  1972. self.assertEqual(7, len(entries))
  1973. ent = entries[0]
  1974. self.assertEqual(0, ent.indent)
  1975. self.assertEqual('main-section', ent.name)
  1976. self.assertEqual('section', ent.etype)
  1977. self.assertEqual(len(data), ent.size)
  1978. self.assertEqual(0, ent.image_pos)
  1979. self.assertEqual(None, ent.uncomp_size)
  1980. self.assertEqual(0, ent.offset)
  1981. ent = entries[1]
  1982. self.assertEqual(1, ent.indent)
  1983. self.assertEqual('u-boot', ent.name)
  1984. self.assertEqual('u-boot', ent.etype)
  1985. self.assertEqual(len(U_BOOT_DATA), ent.size)
  1986. self.assertEqual(0, ent.image_pos)
  1987. self.assertEqual(None, ent.uncomp_size)
  1988. self.assertEqual(0, ent.offset)
  1989. ent = entries[2]
  1990. self.assertEqual(1, ent.indent)
  1991. self.assertEqual('section', ent.name)
  1992. self.assertEqual('section', ent.etype)
  1993. section_size = ent.size
  1994. self.assertEqual(0x100, ent.image_pos)
  1995. self.assertEqual(None, ent.uncomp_size)
  1996. self.assertEqual(0x100, ent.offset)
  1997. ent = entries[3]
  1998. self.assertEqual(2, ent.indent)
  1999. self.assertEqual('cbfs', ent.name)
  2000. self.assertEqual('cbfs', ent.etype)
  2001. self.assertEqual(0x400, ent.size)
  2002. self.assertEqual(0x100, ent.image_pos)
  2003. self.assertEqual(None, ent.uncomp_size)
  2004. self.assertEqual(0, ent.offset)
  2005. ent = entries[4]
  2006. self.assertEqual(3, ent.indent)
  2007. self.assertEqual('u-boot', ent.name)
  2008. self.assertEqual('u-boot', ent.etype)
  2009. self.assertEqual(len(U_BOOT_DATA), ent.size)
  2010. self.assertEqual(0x138, ent.image_pos)
  2011. self.assertEqual(None, ent.uncomp_size)
  2012. self.assertEqual(0x38, ent.offset)
  2013. ent = entries[5]
  2014. self.assertEqual(3, ent.indent)
  2015. self.assertEqual('u-boot-dtb', ent.name)
  2016. self.assertEqual('text', ent.etype)
  2017. self.assertGreater(len(COMPRESS_DATA), ent.size)
  2018. self.assertEqual(0x178, ent.image_pos)
  2019. self.assertEqual(len(COMPRESS_DATA), ent.uncomp_size)
  2020. self.assertEqual(0x78, ent.offset)
  2021. ent = entries[6]
  2022. self.assertEqual(2, ent.indent)
  2023. self.assertEqual('u-boot-dtb', ent.name)
  2024. self.assertEqual('u-boot-dtb', ent.etype)
  2025. self.assertEqual(0x500, ent.image_pos)
  2026. self.assertEqual(len(U_BOOT_DTB_DATA), ent.uncomp_size)
  2027. dtb_size = ent.size
  2028. # Compressing this data expands it since headers are added
  2029. self.assertGreater(dtb_size, len(U_BOOT_DTB_DATA))
  2030. self.assertEqual(0x400, ent.offset)
  2031. self.assertEqual(len(data), 0x100 + section_size)
  2032. self.assertEqual(section_size, 0x400 + dtb_size)
  2033. def testFindFdtmap(self):
  2034. """Test locating an FDT map in an image"""
  2035. self._CheckLz4()
  2036. data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
  2037. image = control.images['image']
  2038. entries = image.GetEntries()
  2039. entry = entries['fdtmap']
  2040. self.assertEqual(entry.image_pos, fdtmap.LocateFdtmap(data))
  2041. def testFindFdtmapMissing(self):
  2042. """Test failing to locate an FDP map"""
  2043. data = self._DoReadFile('005_simple.dts')
  2044. self.assertEqual(None, fdtmap.LocateFdtmap(data))
  2045. def testFindImageHeader(self):
  2046. """Test locating a image header"""
  2047. self._CheckLz4()
  2048. data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
  2049. image = control.images['image']
  2050. entries = image.GetEntries()
  2051. entry = entries['fdtmap']
  2052. # The header should point to the FDT map
  2053. self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
  2054. def testFindImageHeaderStart(self):
  2055. """Test locating a image header located at the start of an image"""
  2056. data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
  2057. image = control.images['image']
  2058. entries = image.GetEntries()
  2059. entry = entries['fdtmap']
  2060. # The header should point to the FDT map
  2061. self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
  2062. def testFindImageHeaderMissing(self):
  2063. """Test failing to locate an image header"""
  2064. data = self._DoReadFile('005_simple.dts')
  2065. self.assertEqual(None, image_header.LocateHeaderOffset(data))
  2066. def testReadImage(self):
  2067. """Test reading an image and accessing its FDT map"""
  2068. self._CheckLz4()
  2069. data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
  2070. image_fname = tools.GetOutputFilename('image.bin')
  2071. orig_image = control.images['image']
  2072. image = Image.FromFile(image_fname)
  2073. self.assertEqual(orig_image.GetEntries().keys(),
  2074. image.GetEntries().keys())
  2075. orig_entry = orig_image.GetEntries()['fdtmap']
  2076. entry = image.GetEntries()['fdtmap']
  2077. self.assertEquals(orig_entry.offset, entry.offset)
  2078. self.assertEquals(orig_entry.size, entry.size)
  2079. self.assertEquals(orig_entry.image_pos, entry.image_pos)
  2080. def testReadImageNoHeader(self):
  2081. """Test accessing an image's FDT map without an image header"""
  2082. self._CheckLz4()
  2083. data = self._DoReadFileRealDtb('129_decode_image_nohdr.dts')
  2084. image_fname = tools.GetOutputFilename('image.bin')
  2085. image = Image.FromFile(image_fname)
  2086. self.assertTrue(isinstance(image, Image))
  2087. self.assertEqual('image', image.image_name[-5:])
  2088. def testReadImageFail(self):
  2089. """Test failing to read an image image's FDT map"""
  2090. self._DoReadFile('005_simple.dts')
  2091. image_fname = tools.GetOutputFilename('image.bin')
  2092. with self.assertRaises(ValueError) as e:
  2093. image = Image.FromFile(image_fname)
  2094. self.assertIn("Cannot find FDT map in image", str(e.exception))
  2095. def testListCmd(self):
  2096. """Test listing the files in an image using an Fdtmap"""
  2097. self._CheckLz4()
  2098. data = self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2099. # lz4 compression size differs depending on the version
  2100. image = control.images['image']
  2101. entries = image.GetEntries()
  2102. section_size = entries['section'].size
  2103. fdt_size = entries['section'].GetEntries()['u-boot-dtb'].size
  2104. fdtmap_offset = entries['fdtmap'].offset
  2105. try:
  2106. tmpdir, updated_fname = self._SetupImageInTmpdir()
  2107. with test_util.capture_sys_output() as (stdout, stderr):
  2108. self._DoBinman('ls', '-i', updated_fname)
  2109. finally:
  2110. shutil.rmtree(tmpdir)
  2111. lines = stdout.getvalue().splitlines()
  2112. expected = [
  2113. 'Name Image-pos Size Entry-type Offset Uncomp-size',
  2114. '----------------------------------------------------------------------',
  2115. 'main-section 0 c00 section 0',
  2116. ' u-boot 0 4 u-boot 0',
  2117. ' section 100 %x section 100' % section_size,
  2118. ' cbfs 100 400 cbfs 0',
  2119. ' u-boot 138 4 u-boot 38',
  2120. ' u-boot-dtb 180 105 u-boot-dtb 80 3c9',
  2121. ' u-boot-dtb 500 %x u-boot-dtb 400 3c9' % fdt_size,
  2122. ' fdtmap %x 3bd fdtmap %x' %
  2123. (fdtmap_offset, fdtmap_offset),
  2124. ' image-header bf8 8 image-header bf8',
  2125. ]
  2126. self.assertEqual(expected, lines)
  2127. def testListCmdFail(self):
  2128. """Test failing to list an image"""
  2129. self._DoReadFile('005_simple.dts')
  2130. try:
  2131. tmpdir, updated_fname = self._SetupImageInTmpdir()
  2132. with self.assertRaises(ValueError) as e:
  2133. self._DoBinman('ls', '-i', updated_fname)
  2134. finally:
  2135. shutil.rmtree(tmpdir)
  2136. self.assertIn("Cannot find FDT map in image", str(e.exception))
  2137. def _RunListCmd(self, paths, expected):
  2138. """List out entries and check the result
  2139. Args:
  2140. paths: List of paths to pass to the list command
  2141. expected: Expected list of filenames to be returned, in order
  2142. """
  2143. self._CheckLz4()
  2144. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2145. image_fname = tools.GetOutputFilename('image.bin')
  2146. image = Image.FromFile(image_fname)
  2147. lines = image.GetListEntries(paths)[1]
  2148. files = [line[0].strip() for line in lines[1:]]
  2149. self.assertEqual(expected, files)
  2150. def testListCmdSection(self):
  2151. """Test listing the files in a section"""
  2152. self._RunListCmd(['section'],
  2153. ['section', 'cbfs', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
  2154. def testListCmdFile(self):
  2155. """Test listing a particular file"""
  2156. self._RunListCmd(['*u-boot-dtb'], ['u-boot-dtb', 'u-boot-dtb'])
  2157. def testListCmdWildcard(self):
  2158. """Test listing a wildcarded file"""
  2159. self._RunListCmd(['*boot*'],
  2160. ['u-boot', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
  2161. def testListCmdWildcardMulti(self):
  2162. """Test listing a wildcarded file"""
  2163. self._RunListCmd(['*cb*', '*head*'],
  2164. ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
  2165. def testListCmdEmpty(self):
  2166. """Test listing a wildcarded file"""
  2167. self._RunListCmd(['nothing'], [])
  2168. def testListCmdPath(self):
  2169. """Test listing the files in a sub-entry of a section"""
  2170. self._RunListCmd(['section/cbfs'], ['cbfs', 'u-boot', 'u-boot-dtb'])
  2171. def _RunExtractCmd(self, entry_name, decomp=True):
  2172. """Extract an entry from an image
  2173. Args:
  2174. entry_name: Entry name to extract
  2175. decomp: True to decompress the data if compressed, False to leave
  2176. it in its raw uncompressed format
  2177. Returns:
  2178. data from entry
  2179. """
  2180. self._CheckLz4()
  2181. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2182. image_fname = tools.GetOutputFilename('image.bin')
  2183. return control.ReadEntry(image_fname, entry_name, decomp)
  2184. def testExtractSimple(self):
  2185. """Test extracting a single file"""
  2186. data = self._RunExtractCmd('u-boot')
  2187. self.assertEqual(U_BOOT_DATA, data)
  2188. def testExtractSection(self):
  2189. """Test extracting the files in a section"""
  2190. data = self._RunExtractCmd('section')
  2191. cbfs_data = data[:0x400]
  2192. cbfs = cbfs_util.CbfsReader(cbfs_data)
  2193. self.assertEqual(['u-boot', 'u-boot-dtb', ''], list(cbfs.files.keys()))
  2194. dtb_data = data[0x400:]
  2195. dtb = self._decompress(dtb_data)
  2196. self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
  2197. def testExtractCompressed(self):
  2198. """Test extracting compressed data"""
  2199. data = self._RunExtractCmd('section/u-boot-dtb')
  2200. self.assertEqual(EXTRACT_DTB_SIZE, len(data))
  2201. def testExtractRaw(self):
  2202. """Test extracting compressed data without decompressing it"""
  2203. data = self._RunExtractCmd('section/u-boot-dtb', decomp=False)
  2204. dtb = self._decompress(data)
  2205. self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
  2206. def testExtractCbfs(self):
  2207. """Test extracting CBFS data"""
  2208. data = self._RunExtractCmd('section/cbfs/u-boot')
  2209. self.assertEqual(U_BOOT_DATA, data)
  2210. def testExtractCbfsCompressed(self):
  2211. """Test extracting CBFS compressed data"""
  2212. data = self._RunExtractCmd('section/cbfs/u-boot-dtb')
  2213. self.assertEqual(EXTRACT_DTB_SIZE, len(data))
  2214. def testExtractCbfsRaw(self):
  2215. """Test extracting CBFS compressed data without decompressing it"""
  2216. data = self._RunExtractCmd('section/cbfs/u-boot-dtb', decomp=False)
  2217. dtb = tools.Decompress(data, 'lzma', with_header=False)
  2218. self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
  2219. def testExtractBadEntry(self):
  2220. """Test extracting a bad section path"""
  2221. with self.assertRaises(ValueError) as e:
  2222. self._RunExtractCmd('section/does-not-exist')
  2223. self.assertIn("Entry 'does-not-exist' not found in '/section'",
  2224. str(e.exception))
  2225. def testExtractMissingFile(self):
  2226. """Test extracting file that does not exist"""
  2227. with self.assertRaises(IOError) as e:
  2228. control.ReadEntry('missing-file', 'name')
  2229. def testExtractBadFile(self):
  2230. """Test extracting an invalid file"""
  2231. fname = os.path.join(self._indir, 'badfile')
  2232. tools.WriteFile(fname, b'')
  2233. with self.assertRaises(ValueError) as e:
  2234. control.ReadEntry(fname, 'name')
  2235. def testExtractCmd(self):
  2236. """Test extracting a file fron an image on the command line"""
  2237. self._CheckLz4()
  2238. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2239. fname = os.path.join(self._indir, 'output.extact')
  2240. try:
  2241. tmpdir, updated_fname = self._SetupImageInTmpdir()
  2242. with test_util.capture_sys_output() as (stdout, stderr):
  2243. self._DoBinman('extract', '-i', updated_fname, 'u-boot',
  2244. '-f', fname)
  2245. finally:
  2246. shutil.rmtree(tmpdir)
  2247. data = tools.ReadFile(fname)
  2248. self.assertEqual(U_BOOT_DATA, data)
  2249. def testExtractOneEntry(self):
  2250. """Test extracting a single entry fron an image """
  2251. self._CheckLz4()
  2252. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2253. image_fname = tools.GetOutputFilename('image.bin')
  2254. fname = os.path.join(self._indir, 'output.extact')
  2255. control.ExtractEntries(image_fname, fname, None, ['u-boot'])
  2256. data = tools.ReadFile(fname)
  2257. self.assertEqual(U_BOOT_DATA, data)
  2258. def _CheckExtractOutput(self, decomp):
  2259. """Helper to test file output with and without decompression
  2260. Args:
  2261. decomp: True to decompress entry data, False to output it raw
  2262. """
  2263. def _CheckPresent(entry_path, expect_data, expect_size=None):
  2264. """Check and remove expected file
  2265. This checks the data/size of a file and removes the file both from
  2266. the outfiles set and from the output directory. Once all files are
  2267. processed, both the set and directory should be empty.
  2268. Args:
  2269. entry_path: Entry path
  2270. expect_data: Data to expect in file, or None to skip check
  2271. expect_size: Size of data to expect in file, or None to skip
  2272. """
  2273. path = os.path.join(outdir, entry_path)
  2274. data = tools.ReadFile(path)
  2275. os.remove(path)
  2276. if expect_data:
  2277. self.assertEqual(expect_data, data)
  2278. elif expect_size:
  2279. self.assertEqual(expect_size, len(data))
  2280. outfiles.remove(path)
  2281. def _CheckDirPresent(name):
  2282. """Remove expected directory
  2283. This gives an error if the directory does not exist as expected
  2284. Args:
  2285. name: Name of directory to remove
  2286. """
  2287. path = os.path.join(outdir, name)
  2288. os.rmdir(path)
  2289. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2290. image_fname = tools.GetOutputFilename('image.bin')
  2291. outdir = os.path.join(self._indir, 'extract')
  2292. einfos = control.ExtractEntries(image_fname, None, outdir, [], decomp)
  2293. # Create a set of all file that were output (should be 9)
  2294. outfiles = set()
  2295. for root, dirs, files in os.walk(outdir):
  2296. outfiles |= set([os.path.join(root, fname) for fname in files])
  2297. self.assertEqual(9, len(outfiles))
  2298. self.assertEqual(9, len(einfos))
  2299. image = control.images['image']
  2300. entries = image.GetEntries()
  2301. # Check the 9 files in various ways
  2302. section = entries['section']
  2303. section_entries = section.GetEntries()
  2304. cbfs_entries = section_entries['cbfs'].GetEntries()
  2305. _CheckPresent('u-boot', U_BOOT_DATA)
  2306. _CheckPresent('section/cbfs/u-boot', U_BOOT_DATA)
  2307. dtb_len = EXTRACT_DTB_SIZE
  2308. if not decomp:
  2309. dtb_len = cbfs_entries['u-boot-dtb'].size
  2310. _CheckPresent('section/cbfs/u-boot-dtb', None, dtb_len)
  2311. if not decomp:
  2312. dtb_len = section_entries['u-boot-dtb'].size
  2313. _CheckPresent('section/u-boot-dtb', None, dtb_len)
  2314. fdtmap = entries['fdtmap']
  2315. _CheckPresent('fdtmap', fdtmap.data)
  2316. hdr = entries['image-header']
  2317. _CheckPresent('image-header', hdr.data)
  2318. _CheckPresent('section/root', section.data)
  2319. cbfs = section_entries['cbfs']
  2320. _CheckPresent('section/cbfs/root', cbfs.data)
  2321. data = tools.ReadFile(image_fname)
  2322. _CheckPresent('root', data)
  2323. # There should be no files left. Remove all the directories to check.
  2324. # If there are any files/dirs remaining, one of these checks will fail.
  2325. self.assertEqual(0, len(outfiles))
  2326. _CheckDirPresent('section/cbfs')
  2327. _CheckDirPresent('section')
  2328. _CheckDirPresent('')
  2329. self.assertFalse(os.path.exists(outdir))
  2330. def testExtractAllEntries(self):
  2331. """Test extracting all entries"""
  2332. self._CheckLz4()
  2333. self._CheckExtractOutput(decomp=True)
  2334. def testExtractAllEntriesRaw(self):
  2335. """Test extracting all entries without decompressing them"""
  2336. self._CheckLz4()
  2337. self._CheckExtractOutput(decomp=False)
  2338. def testExtractSelectedEntries(self):
  2339. """Test extracting some entries"""
  2340. self._CheckLz4()
  2341. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2342. image_fname = tools.GetOutputFilename('image.bin')
  2343. outdir = os.path.join(self._indir, 'extract')
  2344. einfos = control.ExtractEntries(image_fname, None, outdir,
  2345. ['*cb*', '*head*'])
  2346. # File output is tested by testExtractAllEntries(), so just check that
  2347. # the expected entries are selected
  2348. names = [einfo.name for einfo in einfos]
  2349. self.assertEqual(names,
  2350. ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
  2351. def testExtractNoEntryPaths(self):
  2352. """Test extracting some entries"""
  2353. self._CheckLz4()
  2354. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2355. image_fname = tools.GetOutputFilename('image.bin')
  2356. with self.assertRaises(ValueError) as e:
  2357. control.ExtractEntries(image_fname, 'fname', None, [])
  2358. self.assertIn('Must specify an entry path to write with -f',
  2359. str(e.exception))
  2360. def testExtractTooManyEntryPaths(self):
  2361. """Test extracting some entries"""
  2362. self._CheckLz4()
  2363. self._DoReadFileRealDtb('130_list_fdtmap.dts')
  2364. image_fname = tools.GetOutputFilename('image.bin')
  2365. with self.assertRaises(ValueError) as e:
  2366. control.ExtractEntries(image_fname, 'fname', None, ['a', 'b'])
  2367. self.assertIn('Must specify exactly one entry path to write with -f',
  2368. str(e.exception))
  2369. def testPackAlignSection(self):
  2370. """Test that sections can have alignment"""
  2371. self._DoReadFile('131_pack_align_section.dts')
  2372. self.assertIn('image', control.images)
  2373. image = control.images['image']
  2374. entries = image.GetEntries()
  2375. self.assertEqual(3, len(entries))
  2376. # First u-boot
  2377. self.assertIn('u-boot', entries)
  2378. entry = entries['u-boot']
  2379. self.assertEqual(0, entry.offset)
  2380. self.assertEqual(0, entry.image_pos)
  2381. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  2382. self.assertEqual(len(U_BOOT_DATA), entry.size)
  2383. # Section0
  2384. self.assertIn('section0', entries)
  2385. section0 = entries['section0']
  2386. self.assertEqual(0x10, section0.offset)
  2387. self.assertEqual(0x10, section0.image_pos)
  2388. self.assertEqual(len(U_BOOT_DATA), section0.size)
  2389. # Second u-boot
  2390. section_entries = section0.GetEntries()
  2391. self.assertIn('u-boot', section_entries)
  2392. entry = section_entries['u-boot']
  2393. self.assertEqual(0, entry.offset)
  2394. self.assertEqual(0x10, entry.image_pos)
  2395. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  2396. self.assertEqual(len(U_BOOT_DATA), entry.size)
  2397. # Section1
  2398. self.assertIn('section1', entries)
  2399. section1 = entries['section1']
  2400. self.assertEqual(0x14, section1.offset)
  2401. self.assertEqual(0x14, section1.image_pos)
  2402. self.assertEqual(0x20, section1.size)
  2403. # Second u-boot
  2404. section_entries = section1.GetEntries()
  2405. self.assertIn('u-boot', section_entries)
  2406. entry = section_entries['u-boot']
  2407. self.assertEqual(0, entry.offset)
  2408. self.assertEqual(0x14, entry.image_pos)
  2409. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  2410. self.assertEqual(len(U_BOOT_DATA), entry.size)
  2411. # Section2
  2412. self.assertIn('section2', section_entries)
  2413. section2 = section_entries['section2']
  2414. self.assertEqual(0x4, section2.offset)
  2415. self.assertEqual(0x18, section2.image_pos)
  2416. self.assertEqual(4, section2.size)
  2417. # Third u-boot
  2418. section_entries = section2.GetEntries()
  2419. self.assertIn('u-boot', section_entries)
  2420. entry = section_entries['u-boot']
  2421. self.assertEqual(0, entry.offset)
  2422. self.assertEqual(0x18, entry.image_pos)
  2423. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  2424. self.assertEqual(len(U_BOOT_DATA), entry.size)
  2425. def _RunReplaceCmd(self, entry_name, data, decomp=True, allow_resize=True,
  2426. dts='132_replace.dts'):
  2427. """Replace an entry in an image
  2428. This writes the entry data to update it, then opens the updated file and
  2429. returns the value that it now finds there.
  2430. Args:
  2431. entry_name: Entry name to replace
  2432. data: Data to replace it with
  2433. decomp: True to compress the data if needed, False if data is
  2434. already compressed so should be used as is
  2435. allow_resize: True to allow entries to change size, False to raise
  2436. an exception
  2437. Returns:
  2438. Tuple:
  2439. data from entry
  2440. data from fdtmap (excluding header)
  2441. Image object that was modified
  2442. """
  2443. dtb_data = self._DoReadFileDtb(dts, use_real_dtb=True,
  2444. update_dtb=True)[1]
  2445. self.assertIn('image', control.images)
  2446. image = control.images['image']
  2447. entries = image.GetEntries()
  2448. orig_dtb_data = entries['u-boot-dtb'].data
  2449. orig_fdtmap_data = entries['fdtmap'].data
  2450. image_fname = tools.GetOutputFilename('image.bin')
  2451. updated_fname = tools.GetOutputFilename('image-updated.bin')
  2452. tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
  2453. image = control.WriteEntry(updated_fname, entry_name, data, decomp,
  2454. allow_resize)
  2455. data = control.ReadEntry(updated_fname, entry_name, decomp)
  2456. # The DT data should not change unless resized:
  2457. if not allow_resize:
  2458. new_dtb_data = entries['u-boot-dtb'].data
  2459. self.assertEqual(new_dtb_data, orig_dtb_data)
  2460. new_fdtmap_data = entries['fdtmap'].data
  2461. self.assertEqual(new_fdtmap_data, orig_fdtmap_data)
  2462. return data, orig_fdtmap_data[fdtmap.FDTMAP_HDR_LEN:], image
  2463. def testReplaceSimple(self):
  2464. """Test replacing a single file"""
  2465. expected = b'x' * len(U_BOOT_DATA)
  2466. data, expected_fdtmap, _ = self._RunReplaceCmd('u-boot', expected,
  2467. allow_resize=False)
  2468. self.assertEqual(expected, data)
  2469. # Test that the state looks right. There should be an FDT for the fdtmap
  2470. # that we jsut read back in, and it should match what we find in the
  2471. # 'control' tables. Checking for an FDT that does not exist should
  2472. # return None.
  2473. path, fdtmap = state.GetFdtContents('fdtmap')
  2474. self.assertIsNotNone(path)
  2475. self.assertEqual(expected_fdtmap, fdtmap)
  2476. dtb = state.GetFdtForEtype('fdtmap')
  2477. self.assertEqual(dtb.GetContents(), fdtmap)
  2478. missing_path, missing_fdtmap = state.GetFdtContents('missing')
  2479. self.assertIsNone(missing_path)
  2480. self.assertIsNone(missing_fdtmap)
  2481. missing_dtb = state.GetFdtForEtype('missing')
  2482. self.assertIsNone(missing_dtb)
  2483. self.assertEqual('/binman', state.fdt_path_prefix)
  2484. def testReplaceResizeFail(self):
  2485. """Test replacing a file by something larger"""
  2486. expected = U_BOOT_DATA + b'x'
  2487. with self.assertRaises(ValueError) as e:
  2488. self._RunReplaceCmd('u-boot', expected, allow_resize=False,
  2489. dts='139_replace_repack.dts')
  2490. self.assertIn("Node '/u-boot': Entry data size does not match, but resize is disabled",
  2491. str(e.exception))
  2492. def testReplaceMulti(self):
  2493. """Test replacing entry data where multiple images are generated"""
  2494. data = self._DoReadFileDtb('133_replace_multi.dts', use_real_dtb=True,
  2495. update_dtb=True)[0]
  2496. expected = b'x' * len(U_BOOT_DATA)
  2497. updated_fname = tools.GetOutputFilename('image-updated.bin')
  2498. tools.WriteFile(updated_fname, data)
  2499. entry_name = 'u-boot'
  2500. control.WriteEntry(updated_fname, entry_name, expected,
  2501. allow_resize=False)
  2502. data = control.ReadEntry(updated_fname, entry_name)
  2503. self.assertEqual(expected, data)
  2504. # Check the state looks right.
  2505. self.assertEqual('/binman/image', state.fdt_path_prefix)
  2506. # Now check we can write the first image
  2507. image_fname = tools.GetOutputFilename('first-image.bin')
  2508. updated_fname = tools.GetOutputFilename('first-updated.bin')
  2509. tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
  2510. entry_name = 'u-boot'
  2511. control.WriteEntry(updated_fname, entry_name, expected,
  2512. allow_resize=False)
  2513. data = control.ReadEntry(updated_fname, entry_name)
  2514. self.assertEqual(expected, data)
  2515. # Check the state looks right.
  2516. self.assertEqual('/binman/first-image', state.fdt_path_prefix)
  2517. def testUpdateFdtAllRepack(self):
  2518. """Test that all device trees are updated with offset/size info"""
  2519. data = self._DoReadFileRealDtb('134_fdt_update_all_repack.dts')
  2520. SECTION_SIZE = 0x300
  2521. DTB_SIZE = 602
  2522. FDTMAP_SIZE = 608
  2523. base_expected = {
  2524. 'offset': 0,
  2525. 'size': SECTION_SIZE + DTB_SIZE * 2 + FDTMAP_SIZE,
  2526. 'image-pos': 0,
  2527. 'section:offset': 0,
  2528. 'section:size': SECTION_SIZE,
  2529. 'section:image-pos': 0,
  2530. 'section/u-boot-dtb:offset': 4,
  2531. 'section/u-boot-dtb:size': 636,
  2532. 'section/u-boot-dtb:image-pos': 4,
  2533. 'u-boot-spl-dtb:offset': SECTION_SIZE,
  2534. 'u-boot-spl-dtb:size': DTB_SIZE,
  2535. 'u-boot-spl-dtb:image-pos': SECTION_SIZE,
  2536. 'u-boot-tpl-dtb:offset': SECTION_SIZE + DTB_SIZE,
  2537. 'u-boot-tpl-dtb:image-pos': SECTION_SIZE + DTB_SIZE,
  2538. 'u-boot-tpl-dtb:size': DTB_SIZE,
  2539. 'fdtmap:offset': SECTION_SIZE + DTB_SIZE * 2,
  2540. 'fdtmap:size': FDTMAP_SIZE,
  2541. 'fdtmap:image-pos': SECTION_SIZE + DTB_SIZE * 2,
  2542. }
  2543. main_expected = {
  2544. 'section:orig-size': SECTION_SIZE,
  2545. 'section/u-boot-dtb:orig-offset': 4,
  2546. }
  2547. # We expect three device-tree files in the output, with the first one
  2548. # within a fixed-size section.
  2549. # Read them in sequence. We look for an 'spl' property in the SPL tree,
  2550. # and 'tpl' in the TPL tree, to make sure they are distinct from the
  2551. # main U-Boot tree. All three should have the same positions and offset
  2552. # except that the main tree should include the main_expected properties
  2553. start = 4
  2554. for item in ['', 'spl', 'tpl', None]:
  2555. if item is None:
  2556. start += 16 # Move past fdtmap header
  2557. dtb = fdt.Fdt.FromData(data[start:])
  2558. dtb.Scan()
  2559. props = self._GetPropTree(dtb,
  2560. BASE_DTB_PROPS + REPACK_DTB_PROPS + ['spl', 'tpl'],
  2561. prefix='/' if item is None else '/binman/')
  2562. expected = dict(base_expected)
  2563. if item:
  2564. expected[item] = 0
  2565. else:
  2566. # Main DTB and fdtdec should include the 'orig-' properties
  2567. expected.update(main_expected)
  2568. # Helpful for debugging:
  2569. #for prop in sorted(props):
  2570. #print('prop %s %s %s' % (prop, props[prop], expected[prop]))
  2571. self.assertEqual(expected, props)
  2572. if item == '':
  2573. start = SECTION_SIZE
  2574. else:
  2575. start += dtb._fdt_obj.totalsize()
  2576. def testFdtmapHeaderMiddle(self):
  2577. """Test an FDT map in the middle of an image when it should be at end"""
  2578. with self.assertRaises(ValueError) as e:
  2579. self._DoReadFileRealDtb('135_fdtmap_hdr_middle.dts')
  2580. self.assertIn("Invalid sibling order 'middle' for image-header: Must be at 'end' to match location",
  2581. str(e.exception))
  2582. def testFdtmapHeaderStartBad(self):
  2583. """Test an FDT map in middle of an image when it should be at start"""
  2584. with self.assertRaises(ValueError) as e:
  2585. self._DoReadFileRealDtb('136_fdtmap_hdr_startbad.dts')
  2586. self.assertIn("Invalid sibling order 'end' for image-header: Must be at 'start' to match location",
  2587. str(e.exception))
  2588. def testFdtmapHeaderEndBad(self):
  2589. """Test an FDT map at the start of an image when it should be at end"""
  2590. with self.assertRaises(ValueError) as e:
  2591. self._DoReadFileRealDtb('137_fdtmap_hdr_endbad.dts')
  2592. self.assertIn("Invalid sibling order 'start' for image-header: Must be at 'end' to match location",
  2593. str(e.exception))
  2594. def testFdtmapHeaderNoSize(self):
  2595. """Test an image header at the end of an image with undefined size"""
  2596. self._DoReadFileRealDtb('138_fdtmap_hdr_nosize.dts')
  2597. def testReplaceResize(self):
  2598. """Test replacing a single file in an entry with a larger file"""
  2599. expected = U_BOOT_DATA + b'x'
  2600. data, _, image = self._RunReplaceCmd('u-boot', expected,
  2601. dts='139_replace_repack.dts')
  2602. self.assertEqual(expected, data)
  2603. entries = image.GetEntries()
  2604. dtb_data = entries['u-boot-dtb'].data
  2605. dtb = fdt.Fdt.FromData(dtb_data)
  2606. dtb.Scan()
  2607. # The u-boot section should now be larger in the dtb
  2608. node = dtb.GetNode('/binman/u-boot')
  2609. self.assertEqual(len(expected), fdt_util.GetInt(node, 'size'))
  2610. # Same for the fdtmap
  2611. fdata = entries['fdtmap'].data
  2612. fdtb = fdt.Fdt.FromData(fdata[fdtmap.FDTMAP_HDR_LEN:])
  2613. fdtb.Scan()
  2614. fnode = fdtb.GetNode('/u-boot')
  2615. self.assertEqual(len(expected), fdt_util.GetInt(fnode, 'size'))
  2616. def testReplaceResizeNoRepack(self):
  2617. """Test replacing an entry with a larger file when not allowed"""
  2618. expected = U_BOOT_DATA + b'x'
  2619. with self.assertRaises(ValueError) as e:
  2620. self._RunReplaceCmd('u-boot', expected)
  2621. self.assertIn('Entry data size does not match, but allow-repack is not present for this image',
  2622. str(e.exception))
  2623. def testEntryShrink(self):
  2624. """Test contracting an entry after it is packed"""
  2625. try:
  2626. state.SetAllowEntryContraction(True)
  2627. data = self._DoReadFileDtb('140_entry_shrink.dts',
  2628. update_dtb=True)[0]
  2629. finally:
  2630. state.SetAllowEntryContraction(False)
  2631. self.assertEqual(b'a', data[:1])
  2632. self.assertEqual(U_BOOT_DATA, data[1:1 + len(U_BOOT_DATA)])
  2633. self.assertEqual(b'a', data[-1:])
  2634. def testEntryShrinkFail(self):
  2635. """Test not being allowed to contract an entry after it is packed"""
  2636. data = self._DoReadFileDtb('140_entry_shrink.dts', update_dtb=True)[0]
  2637. # In this case there is a spare byte at the end of the data. The size of
  2638. # the contents is only 1 byte but we still have the size before it
  2639. # shrunk.
  2640. self.assertEqual(b'a\0', data[:2])
  2641. self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)])
  2642. self.assertEqual(b'a\0', data[-2:])
  2643. def testDescriptorOffset(self):
  2644. """Test that the Intel descriptor is always placed at at the start"""
  2645. data = self._DoReadFileDtb('141_descriptor_offset.dts')
  2646. image = control.images['image']
  2647. entries = image.GetEntries()
  2648. desc = entries['intel-descriptor']
  2649. self.assertEqual(0xff800000, desc.offset);
  2650. self.assertEqual(0xff800000, desc.image_pos);
  2651. def testReplaceCbfs(self):
  2652. """Test replacing a single file in CBFS without changing the size"""
  2653. self._CheckLz4()
  2654. expected = b'x' * len(U_BOOT_DATA)
  2655. data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
  2656. updated_fname = tools.GetOutputFilename('image-updated.bin')
  2657. tools.WriteFile(updated_fname, data)
  2658. entry_name = 'section/cbfs/u-boot'
  2659. control.WriteEntry(updated_fname, entry_name, expected,
  2660. allow_resize=True)
  2661. data = control.ReadEntry(updated_fname, entry_name)
  2662. self.assertEqual(expected, data)
  2663. def testReplaceResizeCbfs(self):
  2664. """Test replacing a single file in CBFS with one of a different size"""
  2665. self._CheckLz4()
  2666. expected = U_BOOT_DATA + b'x'
  2667. data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
  2668. updated_fname = tools.GetOutputFilename('image-updated.bin')
  2669. tools.WriteFile(updated_fname, data)
  2670. entry_name = 'section/cbfs/u-boot'
  2671. control.WriteEntry(updated_fname, entry_name, expected,
  2672. allow_resize=True)
  2673. data = control.ReadEntry(updated_fname, entry_name)
  2674. self.assertEqual(expected, data)
  2675. def _SetupForReplace(self):
  2676. """Set up some files to use to replace entries
  2677. This generates an image, copies it to a new file, extracts all the files
  2678. in it and updates some of them
  2679. Returns:
  2680. List
  2681. Image filename
  2682. Output directory
  2683. Expected values for updated entries, each a string
  2684. """
  2685. data = self._DoReadFileRealDtb('143_replace_all.dts')
  2686. updated_fname = tools.GetOutputFilename('image-updated.bin')
  2687. tools.WriteFile(updated_fname, data)
  2688. outdir = os.path.join(self._indir, 'extract')
  2689. einfos = control.ExtractEntries(updated_fname, None, outdir, [])
  2690. expected1 = b'x' + U_BOOT_DATA + b'y'
  2691. u_boot_fname1 = os.path.join(outdir, 'u-boot')
  2692. tools.WriteFile(u_boot_fname1, expected1)
  2693. expected2 = b'a' + U_BOOT_DATA + b'b'
  2694. u_boot_fname2 = os.path.join(outdir, 'u-boot2')
  2695. tools.WriteFile(u_boot_fname2, expected2)
  2696. expected_text = b'not the same text'
  2697. text_fname = os.path.join(outdir, 'text')
  2698. tools.WriteFile(text_fname, expected_text)
  2699. dtb_fname = os.path.join(outdir, 'u-boot-dtb')
  2700. dtb = fdt.FdtScan(dtb_fname)
  2701. node = dtb.GetNode('/binman/text')
  2702. node.AddString('my-property', 'the value')
  2703. dtb.Sync(auto_resize=True)
  2704. dtb.Flush()
  2705. return updated_fname, outdir, expected1, expected2, expected_text
  2706. def _CheckReplaceMultiple(self, entry_paths):
  2707. """Handle replacing the contents of multiple entries
  2708. Args:
  2709. entry_paths: List of entry paths to replace
  2710. Returns:
  2711. List
  2712. Dict of entries in the image:
  2713. key: Entry name
  2714. Value: Entry object
  2715. Expected values for updated entries, each a string
  2716. """
  2717. updated_fname, outdir, expected1, expected2, expected_text = (
  2718. self._SetupForReplace())
  2719. control.ReplaceEntries(updated_fname, None, outdir, entry_paths)
  2720. image = Image.FromFile(updated_fname)
  2721. image.LoadData()
  2722. return image.GetEntries(), expected1, expected2, expected_text
  2723. def testReplaceAll(self):
  2724. """Test replacing the contents of all entries"""
  2725. entries, expected1, expected2, expected_text = (
  2726. self._CheckReplaceMultiple([]))
  2727. data = entries['u-boot'].data
  2728. self.assertEqual(expected1, data)
  2729. data = entries['u-boot2'].data
  2730. self.assertEqual(expected2, data)
  2731. data = entries['text'].data
  2732. self.assertEqual(expected_text, data)
  2733. # Check that the device tree is updated
  2734. data = entries['u-boot-dtb'].data
  2735. dtb = fdt.Fdt.FromData(data)
  2736. dtb.Scan()
  2737. node = dtb.GetNode('/binman/text')
  2738. self.assertEqual('the value', node.props['my-property'].value)
  2739. def testReplaceSome(self):
  2740. """Test replacing the contents of a few entries"""
  2741. entries, expected1, expected2, expected_text = (
  2742. self._CheckReplaceMultiple(['u-boot2', 'text']))
  2743. # This one should not change
  2744. data = entries['u-boot'].data
  2745. self.assertEqual(U_BOOT_DATA, data)
  2746. data = entries['u-boot2'].data
  2747. self.assertEqual(expected2, data)
  2748. data = entries['text'].data
  2749. self.assertEqual(expected_text, data)
  2750. def testReplaceCmd(self):
  2751. """Test replacing a file fron an image on the command line"""
  2752. self._DoReadFileRealDtb('143_replace_all.dts')
  2753. try:
  2754. tmpdir, updated_fname = self._SetupImageInTmpdir()
  2755. fname = os.path.join(tmpdir, 'update-u-boot.bin')
  2756. expected = b'x' * len(U_BOOT_DATA)
  2757. tools.WriteFile(fname, expected)
  2758. self._DoBinman('replace', '-i', updated_fname, 'u-boot', '-f', fname)
  2759. data = tools.ReadFile(updated_fname)
  2760. self.assertEqual(expected, data[:len(expected)])
  2761. map_fname = os.path.join(tmpdir, 'image-updated.map')
  2762. self.assertFalse(os.path.exists(map_fname))
  2763. finally:
  2764. shutil.rmtree(tmpdir)
  2765. def testReplaceCmdSome(self):
  2766. """Test replacing some files fron an image on the command line"""
  2767. updated_fname, outdir, expected1, expected2, expected_text = (
  2768. self._SetupForReplace())
  2769. self._DoBinman('replace', '-i', updated_fname, '-I', outdir,
  2770. 'u-boot2', 'text')
  2771. tools.PrepareOutputDir(None)
  2772. image = Image.FromFile(updated_fname)
  2773. image.LoadData()
  2774. entries = image.GetEntries()
  2775. # This one should not change
  2776. data = entries['u-boot'].data
  2777. self.assertEqual(U_BOOT_DATA, data)
  2778. data = entries['u-boot2'].data
  2779. self.assertEqual(expected2, data)
  2780. data = entries['text'].data
  2781. self.assertEqual(expected_text, data)
  2782. def testReplaceMissing(self):
  2783. """Test replacing entries where the file is missing"""
  2784. updated_fname, outdir, expected1, expected2, expected_text = (
  2785. self._SetupForReplace())
  2786. # Remove one of the files, to generate a warning
  2787. u_boot_fname1 = os.path.join(outdir, 'u-boot')
  2788. os.remove(u_boot_fname1)
  2789. with test_util.capture_sys_output() as (stdout, stderr):
  2790. control.ReplaceEntries(updated_fname, None, outdir, [])
  2791. self.assertIn("Skipping entry '/u-boot' from missing file",
  2792. stderr.getvalue())
  2793. def testReplaceCmdMap(self):
  2794. """Test replacing a file fron an image on the command line"""
  2795. self._DoReadFileRealDtb('143_replace_all.dts')
  2796. try:
  2797. tmpdir, updated_fname = self._SetupImageInTmpdir()
  2798. fname = os.path.join(self._indir, 'update-u-boot.bin')
  2799. expected = b'x' * len(U_BOOT_DATA)
  2800. tools.WriteFile(fname, expected)
  2801. self._DoBinman('replace', '-i', updated_fname, 'u-boot',
  2802. '-f', fname, '-m')
  2803. map_fname = os.path.join(tmpdir, 'image-updated.map')
  2804. self.assertTrue(os.path.exists(map_fname))
  2805. finally:
  2806. shutil.rmtree(tmpdir)
  2807. def testReplaceNoEntryPaths(self):
  2808. """Test replacing an entry without an entry path"""
  2809. self._DoReadFileRealDtb('143_replace_all.dts')
  2810. image_fname = tools.GetOutputFilename('image.bin')
  2811. with self.assertRaises(ValueError) as e:
  2812. control.ReplaceEntries(image_fname, 'fname', None, [])
  2813. self.assertIn('Must specify an entry path to read with -f',
  2814. str(e.exception))
  2815. def testReplaceTooManyEntryPaths(self):
  2816. """Test extracting some entries"""
  2817. self._DoReadFileRealDtb('143_replace_all.dts')
  2818. image_fname = tools.GetOutputFilename('image.bin')
  2819. with self.assertRaises(ValueError) as e:
  2820. control.ReplaceEntries(image_fname, 'fname', None, ['a', 'b'])
  2821. self.assertIn('Must specify exactly one entry path to write with -f',
  2822. str(e.exception))
  2823. def testPackReset16(self):
  2824. """Test that an image with an x86 reset16 region can be created"""
  2825. data = self._DoReadFile('144_x86_reset16.dts')
  2826. self.assertEqual(X86_RESET16_DATA, data[:len(X86_RESET16_DATA)])
  2827. def testPackReset16Spl(self):
  2828. """Test that an image with an x86 reset16-spl region can be created"""
  2829. data = self._DoReadFile('145_x86_reset16_spl.dts')
  2830. self.assertEqual(X86_RESET16_SPL_DATA, data[:len(X86_RESET16_SPL_DATA)])
  2831. def testPackReset16Tpl(self):
  2832. """Test that an image with an x86 reset16-tpl region can be created"""
  2833. data = self._DoReadFile('146_x86_reset16_tpl.dts')
  2834. self.assertEqual(X86_RESET16_TPL_DATA, data[:len(X86_RESET16_TPL_DATA)])
  2835. def testPackIntelFit(self):
  2836. """Test that an image with an Intel FIT and pointer can be created"""
  2837. data = self._DoReadFile('147_intel_fit.dts')
  2838. self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
  2839. fit = data[16:32];
  2840. self.assertEqual(b'_FIT_ \x01\x00\x00\x00\x00\x01\x80}' , fit)
  2841. ptr = struct.unpack('<i', data[0x40:0x44])[0]
  2842. image = control.images['image']
  2843. entries = image.GetEntries()
  2844. expected_ptr = entries['intel-fit'].image_pos - (1 << 32)
  2845. self.assertEqual(expected_ptr, ptr)
  2846. def testPackIntelFitMissing(self):
  2847. """Test detection of a FIT pointer with not FIT region"""
  2848. with self.assertRaises(ValueError) as e:
  2849. self._DoReadFile('148_intel_fit_missing.dts')
  2850. self.assertIn("'intel-fit-ptr' section must have an 'intel-fit' sibling",
  2851. str(e.exception))
  2852. def _CheckSymbolsTplSection(self, dts, expected_vals):
  2853. data = self._DoReadFile(dts)
  2854. sym_values = struct.pack('<LQLL', *expected_vals)
  2855. upto1 = 4 + len(U_BOOT_SPL_DATA)
  2856. expected1 = tools.GetBytes(0xff, 4) + sym_values + U_BOOT_SPL_DATA[20:]
  2857. self.assertEqual(expected1, data[:upto1])
  2858. upto2 = upto1 + 1 + len(U_BOOT_SPL_DATA)
  2859. expected2 = tools.GetBytes(0xff, 1) + sym_values + U_BOOT_SPL_DATA[20:]
  2860. self.assertEqual(expected2, data[upto1:upto2])
  2861. upto3 = 0x34 + len(U_BOOT_DATA)
  2862. expected3 = tools.GetBytes(0xff, 1) + U_BOOT_DATA
  2863. self.assertEqual(expected3, data[upto2:upto3])
  2864. expected4 = sym_values + U_BOOT_TPL_DATA[20:]
  2865. self.assertEqual(expected4, data[upto3:upto3 + len(U_BOOT_TPL_DATA)])
  2866. def testSymbolsTplSection(self):
  2867. """Test binman can assign symbols embedded in U-Boot TPL in a section"""
  2868. self._SetupSplElf('u_boot_binman_syms')
  2869. self._SetupTplElf('u_boot_binman_syms')
  2870. self._CheckSymbolsTplSection('149_symbols_tpl.dts',
  2871. [0x04, 0x1c, 0x10 + 0x34, 0x04])
  2872. def testSymbolsTplSectionX86(self):
  2873. """Test binman can assign symbols in a section with end-at-4gb"""
  2874. self._SetupSplElf('u_boot_binman_syms_x86')
  2875. self._SetupTplElf('u_boot_binman_syms_x86')
  2876. self._CheckSymbolsTplSection('155_symbols_tpl_x86.dts',
  2877. [0xffffff04, 0xffffff1c, 0xffffff34,
  2878. 0x04])
  2879. def testPackX86RomIfwiSectiom(self):
  2880. """Test that a section can be placed in an IFWI region"""
  2881. self._SetupIfwi('fitimage.bin')
  2882. data = self._DoReadFile('151_x86_rom_ifwi_section.dts')
  2883. self._CheckIfwi(data)
  2884. def testPackFspM(self):
  2885. """Test that an image with a FSP memory-init binary can be created"""
  2886. data = self._DoReadFile('152_intel_fsp_m.dts')
  2887. self.assertEqual(FSP_M_DATA, data[:len(FSP_M_DATA)])
  2888. def testPackFspS(self):
  2889. """Test that an image with a FSP silicon-init binary can be created"""
  2890. data = self._DoReadFile('153_intel_fsp_s.dts')
  2891. self.assertEqual(FSP_S_DATA, data[:len(FSP_S_DATA)])
  2892. def testPackFspT(self):
  2893. """Test that an image with a FSP temp-ram-init binary can be created"""
  2894. data = self._DoReadFile('154_intel_fsp_t.dts')
  2895. self.assertEqual(FSP_T_DATA, data[:len(FSP_T_DATA)])
  2896. def testMkimage(self):
  2897. """Test using mkimage to build an image"""
  2898. data = self._DoReadFile('156_mkimage.dts')
  2899. # Just check that the data appears in the file somewhere
  2900. self.assertIn(U_BOOT_SPL_DATA, data)
  2901. def testExtblob(self):
  2902. """Test an image with an external blob"""
  2903. data = self._DoReadFile('157_blob_ext.dts')
  2904. self.assertEqual(REFCODE_DATA, data)
  2905. def testExtblobMissing(self):
  2906. """Test an image with a missing external blob"""
  2907. with self.assertRaises(ValueError) as e:
  2908. self._DoReadFile('158_blob_ext_missing.dts')
  2909. self.assertIn("Filename 'missing-file' not found in input path",
  2910. str(e.exception))
  2911. def testExtblobMissingOk(self):
  2912. """Test an image with an missing external blob that is allowed"""
  2913. with test_util.capture_sys_output() as (stdout, stderr):
  2914. self._DoTestFile('158_blob_ext_missing.dts', allow_missing=True)
  2915. err = stderr.getvalue()
  2916. self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
  2917. def testExtblobMissingOkSect(self):
  2918. """Test an image with an missing external blob that is allowed"""
  2919. with test_util.capture_sys_output() as (stdout, stderr):
  2920. self._DoTestFile('159_blob_ext_missing_sect.dts',
  2921. allow_missing=True)
  2922. err = stderr.getvalue()
  2923. self.assertRegex(err, "Image 'main-section'.*missing.*: "
  2924. "blob-ext blob-ext2")
  2925. def testPackX86RomMeMissingDesc(self):
  2926. """Test that an missing Intel descriptor entry is allowed"""
  2927. with test_util.capture_sys_output() as (stdout, stderr):
  2928. self._DoTestFile('164_x86_rom_me_missing.dts', allow_missing=True)
  2929. err = stderr.getvalue()
  2930. self.assertRegex(err,
  2931. "Image 'main-section'.*missing.*: intel-descriptor")
  2932. def testPackX86RomMissingIfwi(self):
  2933. """Test that an x86 ROM with Integrated Firmware Image can be created"""
  2934. self._SetupIfwi('fitimage.bin')
  2935. pathname = os.path.join(self._indir, 'fitimage.bin')
  2936. os.remove(pathname)
  2937. with test_util.capture_sys_output() as (stdout, stderr):
  2938. self._DoTestFile('111_x86_rom_ifwi.dts', allow_missing=True)
  2939. err = stderr.getvalue()
  2940. self.assertRegex(err, "Image 'main-section'.*missing.*: intel-ifwi")
  2941. def testPackOverlap(self):
  2942. """Test that zero-size overlapping regions are ignored"""
  2943. self._DoTestFile('160_pack_overlap_zero.dts')
  2944. def testSimpleFit(self):
  2945. """Test an image with a FIT inside"""
  2946. data = self._DoReadFile('161_fit.dts')
  2947. self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
  2948. self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
  2949. fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
  2950. # The data should be inside the FIT
  2951. dtb = fdt.Fdt.FromData(fit_data)
  2952. dtb.Scan()
  2953. fnode = dtb.GetNode('/images/kernel')
  2954. self.assertIn('data', fnode.props)
  2955. fname = os.path.join(self._indir, 'fit_data.fit')
  2956. tools.WriteFile(fname, fit_data)
  2957. out = tools.Run('dumpimage', '-l', fname)
  2958. # Check a few features to make sure the plumbing works. We don't need
  2959. # to test the operation of mkimage or dumpimage here. First convert the
  2960. # output into a dict where the keys are the fields printed by dumpimage
  2961. # and the values are a list of values for each field
  2962. lines = out.splitlines()
  2963. # Converts "Compression: gzip compressed" into two groups:
  2964. # 'Compression' and 'gzip compressed'
  2965. re_line = re.compile(r'^ *([^:]*)(?:: *(.*))?$')
  2966. vals = collections.defaultdict(list)
  2967. for line in lines:
  2968. mat = re_line.match(line)
  2969. vals[mat.group(1)].append(mat.group(2))
  2970. self.assertEquals('FIT description: test-desc', lines[0])
  2971. self.assertIn('Created:', lines[1])
  2972. self.assertIn('Image 0 (kernel)', vals)
  2973. self.assertIn('Hash value', vals)
  2974. data_sizes = vals.get('Data Size')
  2975. self.assertIsNotNone(data_sizes)
  2976. self.assertEqual(2, len(data_sizes))
  2977. # Format is "4 Bytes = 0.00 KiB = 0.00 MiB" so take the first word
  2978. self.assertEqual(len(U_BOOT_DATA), int(data_sizes[0].split()[0]))
  2979. self.assertEqual(len(U_BOOT_SPL_DTB_DATA), int(data_sizes[1].split()[0]))
  2980. def testFitExternal(self):
  2981. """Test an image with an FIT with external images"""
  2982. data = self._DoReadFile('162_fit_external.dts')
  2983. fit_data = data[len(U_BOOT_DATA):-2] # _testing is 2 bytes
  2984. # The data should be outside the FIT
  2985. dtb = fdt.Fdt.FromData(fit_data)
  2986. dtb.Scan()
  2987. fnode = dtb.GetNode('/images/kernel')
  2988. self.assertNotIn('data', fnode.props)
  2989. def testSectionIgnoreHashSignature(self):
  2990. """Test that sections ignore hash, signature nodes for its data"""
  2991. data = self._DoReadFile('165_section_ignore_hash_signature.dts')
  2992. expected = (U_BOOT_DATA + U_BOOT_DATA)
  2993. self.assertEqual(expected, data)
  2994. def testPadInSections(self):
  2995. """Test pad-before, pad-after for entries in sections"""
  2996. data = self._DoReadFile('166_pad_in_sections.dts')
  2997. expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
  2998. U_BOOT_DATA + tools.GetBytes(ord('!'), 6) +
  2999. U_BOOT_DATA)
  3000. self.assertEqual(expected, data)
  3001. def testFitImageSubentryAlignment(self):
  3002. """Test relative alignability of FIT image subentries"""
  3003. entry_args = {
  3004. 'test-id': TEXT_DATA,
  3005. }
  3006. data, _, _, _ = self._DoReadFileDtb('167_fit_image_subentry_alignment.dts',
  3007. entry_args=entry_args)
  3008. dtb = fdt.Fdt.FromData(data)
  3009. dtb.Scan()
  3010. node = dtb.GetNode('/images/kernel')
  3011. data = dtb.GetProps(node)["data"].bytes
  3012. align_pad = 0x10 - (len(U_BOOT_SPL_DATA) % 0x10)
  3013. expected = (tools.GetBytes(0, 0x20) + U_BOOT_SPL_DATA +
  3014. tools.GetBytes(0, align_pad) + U_BOOT_DATA)
  3015. self.assertEqual(expected, data)
  3016. node = dtb.GetNode('/images/fdt-1')
  3017. data = dtb.GetProps(node)["data"].bytes
  3018. expected = (U_BOOT_SPL_DTB_DATA + tools.GetBytes(0, 20) +
  3019. tools.ToBytes(TEXT_DATA) + tools.GetBytes(0, 30) +
  3020. U_BOOT_DTB_DATA)
  3021. self.assertEqual(expected, data)
  3022. def testFitExtblobMissingOk(self):
  3023. """Test a FIT with a missing external blob that is allowed"""
  3024. with test_util.capture_sys_output() as (stdout, stderr):
  3025. self._DoTestFile('168_fit_missing_blob.dts',
  3026. allow_missing=True)
  3027. err = stderr.getvalue()
  3028. self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
  3029. def testBlobNamedByArgMissing(self):
  3030. """Test handling of a missing entry arg"""
  3031. with self.assertRaises(ValueError) as e:
  3032. self._DoReadFile('068_blob_named_by_arg.dts')
  3033. self.assertIn("Missing required properties/entry args: cros-ec-rw-path",
  3034. str(e.exception))
  3035. if __name__ == "__main__":
  3036. unittest.main()