ftest.py 183 KB

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