ftest.py 151 KB

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