ftest.py 153 KB

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