├── LICENSE.md
├── README.md
├── cmd
└── amddump.go
├── directory.go
├── directory_test.go
├── entry.go
├── entry_test.go
├── fet.go
├── fet_test.go
├── go.mod
├── go.sum
├── image.go
├── image_test.go
├── mapping.go
├── mapping_test.go
├── rom.go
└── rom_test.go
/LICENSE.md:
--------------------------------------------------------------------------------
1 | ### GNU GENERAL PUBLIC LICENSE
2 |
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 |
7 |
8 | Everyone is permitted to copy and distribute verbatim copies of this
9 | license document, but changing it is not allowed.
10 |
11 | ### Preamble
12 |
13 | The GNU General Public License is a free, copyleft license for
14 | software and other kinds of works.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | the GNU General Public License is intended to guarantee your freedom
19 | to share and change all versions of a program--to make sure it remains
20 | free software for all its users. We, the Free Software Foundation, use
21 | the GNU General Public License for most of our software; it applies
22 | also to any other work released this way by its authors. You can apply
23 | it to your programs, too.
24 |
25 | When we speak of free software, we are referring to freedom, not
26 | price. Our General Public Licenses are designed to make sure that you
27 | have the freedom to distribute copies of free software (and charge for
28 | them if you wish), that you receive source code or can get it if you
29 | want it, that you can change the software or use pieces of it in new
30 | free programs, and that you know you can do these things.
31 |
32 | To protect your rights, we need to prevent others from denying you
33 | these rights or asking you to surrender the rights. Therefore, you
34 | have certain responsibilities if you distribute copies of the
35 | software, or if you modify it: responsibilities to respect the freedom
36 | of others.
37 |
38 | For example, if you distribute copies of such a program, whether
39 | gratis or for a fee, you must pass on to the recipients the same
40 | freedoms that you received. You must make sure that they, too, receive
41 | or can get the source code. And you must show them these terms so they
42 | know their rights.
43 |
44 | Developers that use the GNU GPL protect your rights with two steps:
45 | (1) assert copyright on the software, and (2) offer you this License
46 | giving you legal permission to copy, distribute and/or modify it.
47 |
48 | For the developers' and authors' protection, the GPL clearly explains
49 | that there is no warranty for this free software. For both users' and
50 | authors' sake, the GPL requires that modified versions be marked as
51 | changed, so that their problems will not be attributed erroneously to
52 | authors of previous versions.
53 |
54 | Some devices are designed to deny users access to install or run
55 | modified versions of the software inside them, although the
56 | manufacturer can do so. This is fundamentally incompatible with the
57 | aim of protecting users' freedom to change the software. The
58 | systematic pattern of such abuse occurs in the area of products for
59 | individuals to use, which is precisely where it is most unacceptable.
60 | Therefore, we have designed this version of the GPL to prohibit the
61 | practice for those products. If such problems arise substantially in
62 | other domains, we stand ready to extend this provision to those
63 | domains in future versions of the GPL, as needed to protect the
64 | freedom of users.
65 |
66 | Finally, every program is threatened constantly by software patents.
67 | States should not allow patents to restrict development and use of
68 | software on general-purpose computers, but in those that do, we wish
69 | to avoid the special danger that patents applied to a free program
70 | could make it effectively proprietary. To prevent this, the GPL
71 | assures that patents cannot be used to render the program non-free.
72 |
73 | The precise terms and conditions for copying, distribution and
74 | modification follow.
75 |
76 | ### TERMS AND CONDITIONS
77 |
78 | #### 0. Definitions.
79 |
80 | "This License" refers to version 3 of the GNU General Public License.
81 |
82 | "Copyright" also means copyright-like laws that apply to other kinds
83 | of works, such as semiconductor masks.
84 |
85 | "The Program" refers to any copyrightable work licensed under this
86 | License. Each licensee is addressed as "you". "Licensees" and
87 | "recipients" may be individuals or organizations.
88 |
89 | To "modify" a work means to copy from or adapt all or part of the work
90 | in a fashion requiring copyright permission, other than the making of
91 | an exact copy. The resulting work is called a "modified version" of
92 | the earlier work or a work "based on" the earlier work.
93 |
94 | A "covered work" means either the unmodified Program or a work based
95 | on the Program.
96 |
97 | To "propagate" a work means to do anything with it that, without
98 | permission, would make you directly or secondarily liable for
99 | infringement under applicable copyright law, except executing it on a
100 | computer or modifying a private copy. Propagation includes copying,
101 | distribution (with or without modification), making available to the
102 | public, and in some countries other activities as well.
103 |
104 | To "convey" a work means any kind of propagation that enables other
105 | parties to make or receive copies. Mere interaction with a user
106 | through a computer network, with no transfer of a copy, is not
107 | conveying.
108 |
109 | An interactive user interface displays "Appropriate Legal Notices" to
110 | the extent that it includes a convenient and prominently visible
111 | feature that (1) displays an appropriate copyright notice, and (2)
112 | tells the user that there is no warranty for the work (except to the
113 | extent that warranties are provided), that licensees may convey the
114 | work under this License, and how to view a copy of this License. If
115 | the interface presents a list of user commands or options, such as a
116 | menu, a prominent item in the list meets this criterion.
117 |
118 | #### 1. Source Code.
119 |
120 | The "source code" for a work means the preferred form of the work for
121 | making modifications to it. "Object code" means any non-source form of
122 | a work.
123 |
124 | A "Standard Interface" means an interface that either is an official
125 | standard defined by a recognized standards body, or, in the case of
126 | interfaces specified for a particular programming language, one that
127 | is widely used among developers working in that language.
128 |
129 | The "System Libraries" of an executable work include anything, other
130 | than the work as a whole, that (a) is included in the normal form of
131 | packaging a Major Component, but which is not part of that Major
132 | Component, and (b) serves only to enable use of the work with that
133 | Major Component, or to implement a Standard Interface for which an
134 | implementation is available to the public in source code form. A
135 | "Major Component", in this context, means a major essential component
136 | (kernel, window system, and so on) of the specific operating system
137 | (if any) on which the executable work runs, or a compiler used to
138 | produce the work, or an object code interpreter used to run it.
139 |
140 | The "Corresponding Source" for a work in object code form means all
141 | the source code needed to generate, install, and (for an executable
142 | work) run the object code and to modify the work, including scripts to
143 | control those activities. However, it does not include the work's
144 | System Libraries, or general-purpose tools or generally available free
145 | programs which are used unmodified in performing those activities but
146 | which are not part of the work. For example, Corresponding Source
147 | includes interface definition files associated with source files for
148 | the work, and the source code for shared libraries and dynamically
149 | linked subprograms that the work is specifically designed to require,
150 | such as by intimate data communication or control flow between those
151 | subprograms and other parts of the work.
152 |
153 | The Corresponding Source need not include anything that users can
154 | regenerate automatically from other parts of the Corresponding Source.
155 |
156 | The Corresponding Source for a work in source code form is that same
157 | work.
158 |
159 | #### 2. Basic Permissions.
160 |
161 | All rights granted under this License are granted for the term of
162 | copyright on the Program, and are irrevocable provided the stated
163 | conditions are met. This License explicitly affirms your unlimited
164 | permission to run the unmodified Program. The output from running a
165 | covered work is covered by this License only if the output, given its
166 | content, constitutes a covered work. This License acknowledges your
167 | rights of fair use or other equivalent, as provided by copyright law.
168 |
169 | You may make, run and propagate covered works that you do not convey,
170 | without conditions so long as your license otherwise remains in force.
171 | You may convey covered works to others for the sole purpose of having
172 | them make modifications exclusively for you, or provide you with
173 | facilities for running those works, provided that you comply with the
174 | terms of this License in conveying all material for which you do not
175 | control copyright. Those thus making or running the covered works for
176 | you must do so exclusively on your behalf, under your direction and
177 | control, on terms that prohibit them from making any copies of your
178 | copyrighted material outside their relationship with you.
179 |
180 | Conveying under any other circumstances is permitted solely under the
181 | conditions stated below. Sublicensing is not allowed; section 10 makes
182 | it unnecessary.
183 |
184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185 |
186 | No covered work shall be deemed part of an effective technological
187 | measure under any applicable law fulfilling obligations under article
188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 | similar laws prohibiting or restricting circumvention of such
190 | measures.
191 |
192 | When you convey a covered work, you waive any legal power to forbid
193 | circumvention of technological measures to the extent such
194 | circumvention is effected by exercising rights under this License with
195 | respect to the covered work, and you disclaim any intention to limit
196 | operation or modification of the work as a means of enforcing, against
197 | the work's users, your or third parties' legal rights to forbid
198 | circumvention of technological measures.
199 |
200 | #### 4. Conveying Verbatim Copies.
201 |
202 | You may convey verbatim copies of the Program's source code as you
203 | receive it, in any medium, provided that you conspicuously and
204 | appropriately publish on each copy an appropriate copyright notice;
205 | keep intact all notices stating that this License and any
206 | non-permissive terms added in accord with section 7 apply to the code;
207 | keep intact all notices of the absence of any warranty; and give all
208 | recipients a copy of this License along with the Program.
209 |
210 | You may charge any price or no price for each copy that you convey,
211 | and you may offer support or warranty protection for a fee.
212 |
213 | #### 5. Conveying Modified Source Versions.
214 |
215 | You may convey a work based on the Program, or the modifications to
216 | produce it from the Program, in the form of source code under the
217 | terms of section 4, provided that you also meet all of these
218 | conditions:
219 |
220 | - a) The work must carry prominent notices stating that you modified
221 | it, and giving a relevant date.
222 | - b) The work must carry prominent notices stating that it is
223 | released under this License and any conditions added under
224 | section 7. This requirement modifies the requirement in section 4
225 | to "keep intact all notices".
226 | - c) You must license the entire work, as a whole, under this
227 | License to anyone who comes into possession of a copy. This
228 | License will therefore apply, along with any applicable section 7
229 | additional terms, to the whole of the work, and all its parts,
230 | regardless of how they are packaged. This License gives no
231 | permission to license the work in any other way, but it does not
232 | invalidate such permission if you have separately received it.
233 | - d) If the work has interactive user interfaces, each must display
234 | Appropriate Legal Notices; however, if the Program has interactive
235 | interfaces that do not display Appropriate Legal Notices, your
236 | work need not make them do so.
237 |
238 | A compilation of a covered work with other separate and independent
239 | works, which are not by their nature extensions of the covered work,
240 | and which are not combined with it such as to form a larger program,
241 | in or on a volume of a storage or distribution medium, is called an
242 | "aggregate" if the compilation and its resulting copyright are not
243 | used to limit the access or legal rights of the compilation's users
244 | beyond what the individual works permit. Inclusion of a covered work
245 | in an aggregate does not cause this License to apply to the other
246 | parts of the aggregate.
247 |
248 | #### 6. Conveying Non-Source Forms.
249 |
250 | You may convey a covered work in object code form under the terms of
251 | sections 4 and 5, provided that you also convey the machine-readable
252 | Corresponding Source under the terms of this License, in one of these
253 | ways:
254 |
255 | - a) Convey the object code in, or embodied in, a physical product
256 | (including a physical distribution medium), accompanied by the
257 | Corresponding Source fixed on a durable physical medium
258 | customarily used for software interchange.
259 | - b) Convey the object code in, or embodied in, a physical product
260 | (including a physical distribution medium), accompanied by a
261 | written offer, valid for at least three years and valid for as
262 | long as you offer spare parts or customer support for that product
263 | model, to give anyone who possesses the object code either (1) a
264 | copy of the Corresponding Source for all the software in the
265 | product that is covered by this License, on a durable physical
266 | medium customarily used for software interchange, for a price no
267 | more than your reasonable cost of physically performing this
268 | conveying of source, or (2) access to copy the Corresponding
269 | Source from a network server at no charge.
270 | - c) Convey individual copies of the object code with a copy of the
271 | written offer to provide the Corresponding Source. This
272 | alternative is allowed only occasionally and noncommercially, and
273 | only if you received the object code with such an offer, in accord
274 | with subsection 6b.
275 | - d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 | - e) Convey the object code using peer-to-peer transmission,
288 | provided you inform other peers where the object code and
289 | Corresponding Source of the work are being offered to the general
290 | public at no charge under subsection 6d.
291 |
292 | A separable portion of the object code, whose source code is excluded
293 | from the Corresponding Source as a System Library, need not be
294 | included in conveying the object code work.
295 |
296 | A "User Product" is either (1) a "consumer product", which means any
297 | tangible personal property which is normally used for personal,
298 | family, or household purposes, or (2) anything designed or sold for
299 | incorporation into a dwelling. In determining whether a product is a
300 | consumer product, doubtful cases shall be resolved in favor of
301 | coverage. For a particular product received by a particular user,
302 | "normally used" refers to a typical or common use of that class of
303 | product, regardless of the status of the particular user or of the way
304 | in which the particular user actually uses, or expects or is expected
305 | to use, the product. A product is a consumer product regardless of
306 | whether the product has substantial commercial, industrial or
307 | non-consumer uses, unless such uses represent the only significant
308 | mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to
312 | install and execute modified versions of a covered work in that User
313 | Product from a modified version of its Corresponding Source. The
314 | information must suffice to ensure that the continued functioning of
315 | the modified object code is in no case prevented or interfered with
316 | solely because modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or
331 | updates for a work that has been modified or installed by the
332 | recipient, or for the User Product in which it has been modified or
333 | installed. Access to a network may be denied when the modification
334 | itself materially and adversely affects the operation of the network
335 | or violates the rules and protocols for communication across the
336 | network.
337 |
338 | Corresponding Source conveyed, and Installation Information provided,
339 | in accord with this section must be in a format that is publicly
340 | documented (and with an implementation available to the public in
341 | source code form), and must require no special password or key for
342 | unpacking, reading or copying.
343 |
344 | #### 7. Additional Terms.
345 |
346 | "Additional permissions" are terms that supplement the terms of this
347 | License by making exceptions from one or more of its conditions.
348 | Additional permissions that are applicable to the entire Program shall
349 | be treated as though they were included in this License, to the extent
350 | that they are valid under applicable law. If additional permissions
351 | apply only to part of the Program, that part may be used separately
352 | under those permissions, but the entire Program remains governed by
353 | this License without regard to the additional permissions.
354 |
355 | When you convey a copy of a covered work, you may at your option
356 | remove any additional permissions from that copy, or from any part of
357 | it. (Additional permissions may be written to require their own
358 | removal in certain cases when you modify the work.) You may place
359 | additional permissions on material, added by you to a covered work,
360 | for which you have or can give appropriate copyright permission.
361 |
362 | Notwithstanding any other provision of this License, for material you
363 | add to a covered work, you may (if authorized by the copyright holders
364 | of that material) supplement the terms of this License with terms:
365 |
366 | - a) Disclaiming warranty or limiting liability differently from the
367 | terms of sections 15 and 16 of this License; or
368 | - b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 | - c) Prohibiting misrepresentation of the origin of that material,
372 | or requiring that modified versions of such material be marked in
373 | reasonable ways as different from the original version; or
374 | - d) Limiting the use for publicity purposes of names of licensors
375 | or authors of the material; or
376 | - e) Declining to grant rights under trademark law for use of some
377 | trade names, trademarks, or service marks; or
378 | - f) Requiring indemnification of licensors and authors of that
379 | material by anyone who conveys the material (or modified versions
380 | of it) with contractual assumptions of liability to the recipient,
381 | for any liability that these contractual assumptions directly
382 | impose on those licensors and authors.
383 |
384 | All other non-permissive additional terms are considered "further
385 | restrictions" within the meaning of section 10. If the Program as you
386 | received it, or any part of it, contains a notice stating that it is
387 | governed by this License along with a term that is a further
388 | restriction, you may remove that term. If a license document contains
389 | a further restriction but permits relicensing or conveying under this
390 | License, you may add to a covered work material governed by the terms
391 | of that license document, provided that the further restriction does
392 | not survive such relicensing or conveying.
393 |
394 | If you add terms to a covered work in accord with this section, you
395 | must place, in the relevant source files, a statement of the
396 | additional terms that apply to those files, or a notice indicating
397 | where to find the applicable terms.
398 |
399 | Additional terms, permissive or non-permissive, may be stated in the
400 | form of a separately written license, or stated as exceptions; the
401 | above requirements apply either way.
402 |
403 | #### 8. Termination.
404 |
405 | You may not propagate or modify a covered work except as expressly
406 | provided under this License. Any attempt otherwise to propagate or
407 | modify it is void, and will automatically terminate your rights under
408 | this License (including any patent licenses granted under the third
409 | paragraph of section 11).
410 |
411 | However, if you cease all violation of this License, then your license
412 | from a particular copyright holder is reinstated (a) provisionally,
413 | unless and until the copyright holder explicitly and finally
414 | terminates your license, and (b) permanently, if the copyright holder
415 | fails to notify you of the violation by some reasonable means prior to
416 | 60 days after the cessation.
417 |
418 | Moreover, your license from a particular copyright holder is
419 | reinstated permanently if the copyright holder notifies you of the
420 | violation by some reasonable means, this is the first time you have
421 | received notice of violation of this License (for any work) from that
422 | copyright holder, and you cure the violation prior to 30 days after
423 | your receipt of the notice.
424 |
425 | Termination of your rights under this section does not terminate the
426 | licenses of parties who have received copies or rights from you under
427 | this License. If your rights have been terminated and not permanently
428 | reinstated, you do not qualify to receive new licenses for the same
429 | material under section 10.
430 |
431 | #### 9. Acceptance Not Required for Having Copies.
432 |
433 | You are not required to accept this License in order to receive or run
434 | a copy of the Program. Ancillary propagation of a covered work
435 | occurring solely as a consequence of using peer-to-peer transmission
436 | to receive a copy likewise does not require acceptance. However,
437 | nothing other than this License grants you permission to propagate or
438 | modify any covered work. These actions infringe copyright if you do
439 | not accept this License. Therefore, by modifying or propagating a
440 | covered work, you indicate your acceptance of this License to do so.
441 |
442 | #### 10. Automatic Licensing of Downstream Recipients.
443 |
444 | Each time you convey a covered work, the recipient automatically
445 | receives a license from the original licensors, to run, modify and
446 | propagate that work, subject to this License. You are not responsible
447 | for enforcing compliance by third parties with this License.
448 |
449 | An "entity transaction" is a transaction transferring control of an
450 | organization, or substantially all assets of one, or subdividing an
451 | organization, or merging organizations. If propagation of a covered
452 | work results from an entity transaction, each party to that
453 | transaction who receives a copy of the work also receives whatever
454 | licenses to the work the party's predecessor in interest had or could
455 | give under the previous paragraph, plus a right to possession of the
456 | Corresponding Source of the work from the predecessor in interest, if
457 | the predecessor has it or can get it with reasonable efforts.
458 |
459 | You may not impose any further restrictions on the exercise of the
460 | rights granted or affirmed under this License. For example, you may
461 | not impose a license fee, royalty, or other charge for exercise of
462 | rights granted under this License, and you may not initiate litigation
463 | (including a cross-claim or counterclaim in a lawsuit) alleging that
464 | any patent claim is infringed by making, using, selling, offering for
465 | sale, or importing the Program or any portion of it.
466 |
467 | #### 11. Patents.
468 |
469 | A "contributor" is a copyright holder who authorizes use under this
470 | License of the Program or a work on which the Program is based. The
471 | work thus licensed is called the contributor's "contributor version".
472 |
473 | A contributor's "essential patent claims" are all patent claims owned
474 | or controlled by the contributor, whether already acquired or
475 | hereafter acquired, that would be infringed by some manner, permitted
476 | by this License, of making, using, or selling its contributor version,
477 | but do not include claims that would be infringed only as a
478 | consequence of further modification of the contributor version. For
479 | purposes of this definition, "control" includes the right to grant
480 | patent sublicenses in a manner consistent with the requirements of
481 | this License.
482 |
483 | Each contributor grants you a non-exclusive, worldwide, royalty-free
484 | patent license under the contributor's essential patent claims, to
485 | make, use, sell, offer for sale, import and otherwise run, modify and
486 | propagate the contents of its contributor version.
487 |
488 | In the following three paragraphs, a "patent license" is any express
489 | agreement or commitment, however denominated, not to enforce a patent
490 | (such as an express permission to practice a patent or covenant not to
491 | sue for patent infringement). To "grant" such a patent license to a
492 | party means to make such an agreement or commitment not to enforce a
493 | patent against the party.
494 |
495 | If you convey a covered work, knowingly relying on a patent license,
496 | and the Corresponding Source of the work is not available for anyone
497 | to copy, free of charge and under the terms of this License, through a
498 | publicly available network server or other readily accessible means,
499 | then you must either (1) cause the Corresponding Source to be so
500 | available, or (2) arrange to deprive yourself of the benefit of the
501 | patent license for this particular work, or (3) arrange, in a manner
502 | consistent with the requirements of this License, to extend the patent
503 | license to downstream recipients. "Knowingly relying" means you have
504 | actual knowledge that, but for the patent license, your conveying the
505 | covered work in a country, or your recipient's use of the covered work
506 | in a country, would infringe one or more identifiable patents in that
507 | country that you have reason to believe are valid.
508 |
509 | If, pursuant to or in connection with a single transaction or
510 | arrangement, you convey, or propagate by procuring conveyance of, a
511 | covered work, and grant a patent license to some of the parties
512 | receiving the covered work authorizing them to use, propagate, modify
513 | or convey a specific copy of the covered work, then the patent license
514 | you grant is automatically extended to all recipients of the covered
515 | work and works based on it.
516 |
517 | A patent license is "discriminatory" if it does not include within the
518 | scope of its coverage, prohibits the exercise of, or is conditioned on
519 | the non-exercise of one or more of the rights that are specifically
520 | granted under this License. You may not convey a covered work if you
521 | are a party to an arrangement with a third party that is in the
522 | business of distributing software, under which you make payment to the
523 | third party based on the extent of your activity of conveying the
524 | work, and under which the third party grants, to any of the parties
525 | who would receive the covered work from you, a discriminatory patent
526 | license (a) in connection with copies of the covered work conveyed by
527 | you (or copies made from those copies), or (b) primarily for and in
528 | connection with specific products or compilations that contain the
529 | covered work, unless you entered into that arrangement, or that patent
530 | license was granted, prior to 28 March 2007.
531 |
532 | Nothing in this License shall be construed as excluding or limiting
533 | any implied license or other defenses to infringement that may
534 | otherwise be available to you under applicable patent law.
535 |
536 | #### 12. No Surrender of Others' Freedom.
537 |
538 | If conditions are imposed on you (whether by court order, agreement or
539 | otherwise) that contradict the conditions of this License, they do not
540 | excuse you from the conditions of this License. If you cannot convey a
541 | covered work so as to satisfy simultaneously your obligations under
542 | this License and any other pertinent obligations, then as a
543 | consequence you may not convey it at all. For example, if you agree to
544 | terms that obligate you to collect a royalty for further conveying
545 | from those to whom you convey the Program, the only way you could
546 | satisfy both those terms and this License would be to refrain entirely
547 | from conveying the Program.
548 |
549 | #### 13. Use with the GNU Affero General Public License.
550 |
551 | Notwithstanding any other provision of this License, you have
552 | permission to link or combine any covered work with a work licensed
553 | under version 3 of the GNU Affero General Public License into a single
554 | combined work, and to convey the resulting work. The terms of this
555 | License will continue to apply to the part which is the covered work,
556 | but the special requirements of the GNU Affero General Public License,
557 | section 13, concerning interaction through a network will apply to the
558 | combination as such.
559 |
560 | #### 14. Revised Versions of this License.
561 |
562 | The Free Software Foundation may publish revised and/or new versions
563 | of the GNU General Public License from time to time. Such new versions
564 | will be similar in spirit to the present version, but may differ in
565 | detail to address new problems or concerns.
566 |
567 | Each version is given a distinguishing version number. If the Program
568 | specifies that a certain numbered version of the GNU General Public
569 | License "or any later version" applies to it, you have the option of
570 | following the terms and conditions either of that numbered version or
571 | of any later version published by the Free Software Foundation. If the
572 | Program does not specify a version number of the GNU General Public
573 | License, you may choose any version ever published by the Free
574 | Software Foundation.
575 |
576 | If the Program specifies that a proxy can decide which future versions
577 | of the GNU General Public License can be used, that proxy's public
578 | statement of acceptance of a version permanently authorizes you to
579 | choose that version for the Program.
580 |
581 | Later license versions may give you additional or different
582 | permissions. However, no additional obligations are imposed on any
583 | author or copyright holder as a result of your choosing to follow a
584 | later version.
585 |
586 | #### 15. Disclaimer of Warranty.
587 |
588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
596 | CORRECTION.
597 |
598 | #### 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
609 |
610 | #### 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | ### How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these
626 | terms.
627 |
628 | To do so, attach the following notices to the program. It is safest to
629 | attach them to the start of each source file to most effectively state
630 | the exclusion of warranty; and each file should have at least the
631 | "copyright" line and a pointer to where the full notice is found.
632 |
633 |
634 | Copyright (C)
635 |
636 | This program is free software: you can redistribute it and/or modify
637 | it under the terms of the GNU General Public License as published by
638 | the Free Software Foundation, either version 3 of the License, or
639 | (at your option) any later version.
640 |
641 | This program is distributed in the hope that it will be useful,
642 | but WITHOUT ANY WARRANTY; without even the implied warranty of
643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 | GNU General Public License for more details.
645 |
646 | You should have received a copy of the GNU General Public License
647 | along with this program. If not, see .
648 |
649 | Also add information on how to contact you by electronic and paper
650 | mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands \`show w' and \`show c' should show the
661 | appropriate parts of the General Public License. Of course, your
662 | program's commands might be different; for a GUI interface, you would
663 | use an "about box".
664 |
665 | You should also get your employer (if you work as a programmer) or
666 | school, if any, to sign a "copyright disclaimer" for the program, if
667 | necessary. For more information on this, and how to apply and follow
668 | the GNU GPL, see .
669 |
670 | The GNU General Public License does not permit incorporating your
671 | program into proprietary programs. If your program is a subroutine
672 | library, you may consider it more useful to permit linking proprietary
673 | applications with the library. If this is what you want to do, use the
674 | GNU Lesser General Public License instead of this License. But first,
675 | please read .
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # amdfw
2 |
3 | Golang library for reading and writing AMD firmware components
4 |
5 | Credit goes to @cwerling for his [psptool](https://github.com/cwerling/psptool)
6 |
7 | ## amddump
8 | cmd/amddump is a small tool, that dumps all informations known to this library on a specfic image.
9 |
10 |
11 | ```
12 | amddump ryzeimage.rom
13 |
14 | ```
15 |
16 | ## Current Limitations
17 | - Always assumes valid FirmwareEntryTable.
18 | - Some AM1 CPUs are not using it.
19 | - Older FETs might be parsed wrong
20 | - Non Directory-Based Firmware (IMC, GEC, XHCI) cannot be extracted
21 | - All Offsets are treated as absolute. Partial Images often can't be read.
22 |
23 | ## Usage
24 |
25 | See cmd/amddump.go for read-only example code.
26 |
27 | ```golang
28 |
29 | func main() {
30 |
31 | imageBytes, err := ioutil.ReadFile(os.Args[1])
32 |
33 | if err != nil {
34 | log.Fatal("Could not read file: ", err)
35 | }
36 |
37 | image, err := amdfw.ParseImage(imageBytes)
38 |
39 | if err != nil {
40 | log.Println("Error while parse Image: ", err.Error())
41 | }
42 |
43 | targetAddress := uint32(0x1C1000)
44 | image.FET.ImcRomBase = &targetAddress
45 |
46 | image.FET.Write(imageBytes, image.FET.Location)
47 |
48 | ioutil.WriteFile(os.Args[1], imageBytes, 666)
49 | }
50 |
51 | ```
52 |
--------------------------------------------------------------------------------
/cmd/amddump.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "github.com/jedib0t/go-pretty/table"
6 | "github.com/mimoja/amdfw"
7 | "io/ioutil"
8 | "log"
9 | "os"
10 | "reflect"
11 | )
12 |
13 | func main() {
14 |
15 | imageBytes, err := ioutil.ReadFile(os.Args[1])
16 |
17 | if err != nil {
18 | log.Fatal("Could not read file: ", err)
19 | }
20 |
21 | image, err := amdfw.ParseImage(imageBytes)
22 |
23 | if err != nil {
24 | log.Println("Error while parse Image: ", err.Error())
25 | }
26 |
27 | renderFET(*image)
28 |
29 | for _, rom := range image.Roms {
30 | println()
31 | renderRom(*rom)
32 | }
33 |
34 | }
35 |
36 | func renderRom(rom amdfw.Rom) {
37 | t := table.NewWriter()
38 | t.SetOutputMirror(os.Stdout)
39 | t.SetStyle(table.StyleColoredBright)
40 |
41 | t.AppendHeader(table.Row{rom.Type})
42 | t.Render()
43 |
44 | for _, directory := range rom.Directories {
45 |
46 | t = table.NewWriter()
47 | t.SetOutputMirror(os.Stdout)
48 | t.SetStyle(table.StyleColoredBright)
49 | t.AppendHeader(table.Row{"Field", "Value"})
50 |
51 | checksum := "✓"
52 | if valid, should := directory.ValidateChecksum(); !valid {
53 | checksum = fmt.Sprintf("✕ (0x%08X)", should)
54 | }
55 | t.AppendRows([]table.Row{
56 | {"Magic", fmt.Sprintf("%s (0x%08X)", string(directory.Header.Cookie[:]), directory.Header.Cookie)},
57 | {"Checksum", fmt.Sprintf("0x%08X %s", directory.Header.Checksum, checksum)},
58 | {"Number of Entries", fmt.Sprintf("0x%08X", directory.Header.TotalEntries)},
59 | {"Reserved", fmt.Sprintf("0x%08X", directory.Header.Reserved)},
60 | })
61 | t.Render()
62 |
63 | t = table.NewWriter()
64 | t.SetOutputMirror(os.Stdout)
65 | t.SetStyle(table.StyleColoredBright)
66 | t.AppendHeader(table.Row{
67 | "Index",
68 | "Type",
69 | "Location",
70 | "Size",
71 | "Name",
72 | "ID",
73 | "SizeSigned",
74 | "Signed",
75 | "SigFingerprint",
76 | "Zipped",
77 | "FullSize",
78 | "Version",
79 | "SizePacked",
80 | })
81 | for entryID, entry := range directory.Entries {
82 | name := ""
83 | if entry.TypeInfo != nil {
84 | name = entry.TypeInfo.Name
85 | }
86 |
87 | nextRow := table.Row{
88 | fmt.Sprintf("0x%04X", entryID),
89 | fmt.Sprintf("0x%04X", entry.DirectoryEntry.Type),
90 | fmt.Sprintf("0x%08X", entry.DirectoryEntry.Location),
91 | fmt.Sprintf("0x%08X", entry.DirectoryEntry.Size),
92 | name,
93 | }
94 | if entry.Header != nil {
95 | nextRow = append(nextRow,
96 | fmt.Sprintf("0x%08X", entry.Header.ID),
97 | fmt.Sprintf("0x%08X", entry.Header.SizeSigned),
98 | fmt.Sprintf("0x%08X", entry.Header.IsSigned),
99 | fmt.Sprintf("0x%08X", entry.Header.SigFingerprint),
100 | fmt.Sprintf("%X", entry.Header.IsCompressed),
101 | fmt.Sprintf("0x%08X", entry.Header.FullSize),
102 | entry.Version,
103 | fmt.Sprintf("0x%08X", entry.Header.SizePacked),
104 | )
105 | }
106 |
107 | t.AppendRow(nextRow)
108 | }
109 | t.Render()
110 |
111 | for entryID, entry := range directory.Entries {
112 |
113 | if entry.Header != nil {
114 | t = table.NewWriter()
115 | t.SetOutputMirror(os.Stdout)
116 | //t.SetStyle(table.StyleColoredBright)
117 |
118 | t.AppendHeader(table.Row{entryID, fmt.Sprintf("@ 0x%X", entry.DirectoryEntry.Location)})
119 |
120 | reflectVal := reflect.Indirect(reflect.ValueOf(entry.Header))
121 | for i := 0; i < reflectVal.Type().NumField(); i++ {
122 | fieldName := reflectVal.Type().Field(i).Name
123 | fieldValue := reflectVal.Field(i)
124 | t.AppendRow(table.Row{fieldName, fmt.Sprintf("0x%X", fieldValue)})
125 | }
126 | t.Render()
127 | }
128 | }
129 |
130 | }
131 | }
132 |
133 | func renderFET(image amdfw.Image) {
134 |
135 | t := table.NewWriter()
136 | t.SetOutputMirror(os.Stdout)
137 | t.SetStyle(table.StyleColoredBright)
138 |
139 | t.AppendHeader(table.Row{"Firmware Entry Table"})
140 | t.Render()
141 |
142 | t = table.NewWriter()
143 | t.SetOutputMirror(os.Stdout)
144 | t.SetStyle(table.StyleColoredBright)
145 | t.AppendHeader(table.Row{"Field", "Value"})
146 | t.AppendRows([]table.Row{
147 | {"Signature", fmt.Sprintf("0x%08X", image.FET.Signature)},
148 | {"ImcRomBase", fmt.Sprintf("0x%08X", *image.FET.ImcRomBase)},
149 | {"GecRomBase", fmt.Sprintf("0x%08X", *image.FET.GecRomBase)},
150 | {"XHCRomBase", fmt.Sprintf("0x%08X", *image.FET.XHCRomBase)},
151 | {"PSPDirBase", fmt.Sprintf("0x%08X", *image.FET.PSPDirBase)},
152 | {"NewPSPDirBase", fmt.Sprintf("0x%08X", *image.FET.NewPSPDirBase)},
153 | {"BHDDirBase", fmt.Sprintf("0x%08X", *image.FET.BHDDirBase)},
154 | {"NewBHDDirBase", fmt.Sprintf("0x%08X", *image.FET.NewBHDDirBase)},
155 | })
156 | t.Render()
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/directory.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "fmt"
7 | "io"
8 | )
9 |
10 | const PSPCOOCKIE = "$PSP"
11 | const DUALPSPCOOCKIE = "2PSP"
12 | const BHDCOOCKIE = "$BHD"
13 | const SECONDPSPCOOCKIE = "$PL2"
14 | const SECONDBHDCOOCKIE = "$BL2"
15 |
16 | type (
17 | Directory struct {
18 | Header DirectoryHeader
19 | Entries []Entry
20 | Location uint32
21 | }
22 |
23 | DirectoryHeader struct {
24 | Cookie [4]byte
25 | Checksum uint32
26 | TotalEntries uint32
27 | Reserved uint32
28 | }
29 |
30 | DirectoryEntry struct {
31 | Type uint32
32 | Size uint32
33 | Location uint32
34 | Reserved uint32
35 | Unknown *uint64
36 | }
37 |
38 | binaryDirectoryEntry struct {
39 | Type uint32
40 | Size uint32
41 | Location uint32
42 | Reserved uint32
43 | }
44 | )
45 |
46 | func ParseDirectory(firmwareBytes []byte, address uint32, flashMapping uint32) (*Directory, error) {
47 | directory := Directory{}
48 |
49 | if address > flashMapping {
50 | address -= flashMapping
51 | }
52 |
53 | if address > uint32(len(firmwareBytes)) {
54 | return nil, fmt.Errorf("Firmwarebytes not long enough for reading directory header..")
55 | }
56 |
57 | directory.Location = address
58 | directoryBytes := firmwareBytes[address:]
59 | directoryReader := bytes.NewReader(directoryBytes)
60 |
61 | directoryHeader := DirectoryHeader{}
62 | err := binary.Read(directoryReader, binary.LittleEndian, &directoryHeader)
63 | if err != nil {
64 | return nil, fmt.Errorf("Could not read directory header: %v", err)
65 | }
66 |
67 | cookie := string(directoryHeader.Cookie[:])
68 |
69 | isCookieKnown := false
70 |
71 | for _, c := range []string{PSPCOOCKIE, DUALPSPCOOCKIE, SECONDPSPCOOCKIE, BHDCOOCKIE, SECONDBHDCOOCKIE} {
72 | if isCookieKnown = c == cookie; isCookieKnown {
73 | break
74 | }
75 | }
76 |
77 | if !isCookieKnown {
78 | return nil, fmt.Errorf("No Valid Cookie at start of directory: %v", directoryHeader.Cookie[:])
79 | }
80 |
81 | directory.Header = directoryHeader
82 |
83 | if int(directory.Header.TotalEntries)*4*8 > len(firmwareBytes[address+8:]) {
84 | return nil, fmt.Errorf("Could not read directory entries from image: Too many entries(%d)!", directory.Header.TotalEntries)
85 | }
86 |
87 | if cookie == DUALPSPCOOCKIE {
88 | if _, err := directoryReader.Seek(16, io.SeekCurrent); err != nil {
89 | return nil, fmt.Errorf("Could not read 2PSP directory header: %v", err)
90 | }
91 | }
92 |
93 | directory.Entries = make([]Entry, directory.Header.TotalEntries)
94 |
95 | for i := 0; i < int(directory.Header.TotalEntries); i++ {
96 | directoryEntry := DirectoryEntry{}
97 | binDirEntry := binaryDirectoryEntry{}
98 |
99 | if err := binary.Read(directoryReader, binary.LittleEndian, &binDirEntry); err != nil {
100 | return nil, fmt.Errorf("Coulf not read directory directoryEntry")
101 | }
102 |
103 | directoryEntry.Type = binDirEntry.Type
104 | directoryEntry.Size = binDirEntry.Size
105 | directoryEntry.Location = binDirEntry.Location
106 | directoryEntry.Reserved = binDirEntry.Reserved
107 |
108 | entry, _ := ParseEntry(firmwareBytes, directoryEntry, flashMapping)
109 |
110 | if cookie == DUALPSPCOOCKIE {
111 | entry.TypeInfo.Name = "PSP_DIRECTORY"
112 | entry.TypeInfo.Comment = "Full PSP Directory"
113 | } else if cookie == BHDCOOCKIE || cookie == SECONDBHDCOOCKIE {
114 | //BHD Entries adds 2 additional bytes
115 | unknownBytes := make([]byte, 8)
116 | if c, err := directoryReader.Read(unknownBytes); err != nil || c != 8 {
117 | return nil, fmt.Errorf("Could not read BHD directory entry: %v", err)
118 | }
119 | val := binary.LittleEndian.Uint64(unknownBytes)
120 |
121 | entry.DirectoryEntry.Unknown = &val
122 | }
123 |
124 | directory.Entries[i] = *entry
125 | }
126 |
127 | return &directory, nil
128 | }
129 |
130 | func (header *DirectoryHeader) Write(baseImage []byte, address uint32) error {
131 | buf := new(bytes.Buffer)
132 |
133 | if int(address)+binary.Size(header) > len(baseImage) {
134 | return fmt.Errorf("Writing DirectoryHeader failed: BaseImage to small")
135 |
136 | }
137 |
138 | err := binary.Write(buf, binary.LittleEndian, header)
139 | if err != nil {
140 | return fmt.Errorf("Writing binary failed: %v", err)
141 | }
142 |
143 | copy(baseImage[address:], buf.Bytes())
144 |
145 | return nil
146 | }
147 |
148 | func (entry *DirectoryEntry) Write(baseImage []byte, address uint32) error {
149 | buf := new(bytes.Buffer)
150 |
151 | binEntry := binaryDirectoryEntry{
152 | Type: entry.Type,
153 | Size: entry.Size,
154 | Location: entry.Location,
155 | Reserved: entry.Reserved,
156 | }
157 |
158 | if int(address)+binary.Size(binEntry) > len(baseImage) {
159 | return fmt.Errorf("Writing DirectoryHeader failed: BaseImage to small")
160 |
161 | }
162 |
163 | err := binary.Write(buf, binary.LittleEndian, binEntry)
164 | if err != nil {
165 | return fmt.Errorf("Writing binary failed: %v", err)
166 | }
167 |
168 | bytesNeeded := binary.Size(binaryDirectoryEntry{})
169 |
170 | if entry.Unknown != nil {
171 | binary.Write(buf, binary.LittleEndian, *entry.Unknown)
172 | bytesNeeded += binary.Size(*entry.Unknown)
173 | }
174 |
175 | bytesCopied := copy(baseImage[address:], buf.Bytes())
176 |
177 | if bytesCopied != bytesNeeded {
178 | return fmt.Errorf("Writing binary failed: Not all Bytes copied!")
179 | }
180 |
181 | return nil
182 | }
183 |
184 | func (directory *Directory) Write(baseImage []byte, flashMapping uint32) error {
185 | if int(directory.Location) > len(baseImage) {
186 | return fmt.Errorf("BaseImage to small to insert Directory")
187 | }
188 |
189 | err := directory.Header.Write(baseImage, directory.Location)
190 | if err != nil {
191 | return err
192 | }
193 |
194 | location := directory.Location + 0x10
195 |
196 | cookie := string(directory.Header.Cookie[:])
197 |
198 | if cookie == DUALPSPCOOCKIE {
199 | location += 0x10
200 | }
201 |
202 | for i, entry := range directory.Entries {
203 |
204 | entryLength := uint32(16)
205 |
206 | if entry.DirectoryEntry.Unknown != nil {
207 | entryLength += 8
208 | }
209 |
210 | entryAddress := location + uint32(i)*entryLength
211 | err := entry.DirectoryEntry.Write(baseImage, entryAddress)
212 | if err != nil {
213 | return err
214 | }
215 |
216 | entryLocation := entry.DirectoryEntry.Location
217 |
218 | err = entry.Write(baseImage, entryLocation&^flashMapping)
219 | if err != nil {
220 | return err
221 | }
222 | }
223 | return nil
224 | }
225 |
226 | func fletcher32(data []byte) uint32 {
227 | c0 := 0xFFFF
228 | c1 := 0xFFFF
229 |
230 | count := len(data)
231 | for index := 0; index < count; index += 2 {
232 | next := binary.LittleEndian.Uint16(data[index:])
233 | c0 += int(next)
234 | c1 += c0
235 | if index > 255 || index == count-2 {
236 | c0 = (c0 & 0xFFFF) + (c0 >> 16)
237 | c1 = (c1 & 0xFFFF) + (c1 >> 16)
238 | }
239 | }
240 | return uint32((c1 << 16) | c0)
241 | }
242 |
243 | // Validates the Directory Checksum and return the actual value
244 | func (directory *Directory) ValidateChecksum() (valid bool, actual uint32) {
245 | uint32Buffer := make([]byte, 4)
246 | buf := new(bytes.Buffer)
247 |
248 | //Rest of the header
249 |
250 | binary.LittleEndian.PutUint32(uint32Buffer, directory.Header.TotalEntries)
251 | buf.Write(uint32Buffer)
252 |
253 | binary.LittleEndian.PutUint32(uint32Buffer, directory.Header.Reserved)
254 | buf.Write(uint32Buffer)
255 |
256 | cookie := string(directory.Header.Cookie[:])
257 | if cookie == DUALPSPCOOCKIE {
258 | buf.Write(bytes.Repeat([]byte{0}, 16))
259 | }
260 |
261 | for _, entry := range directory.Entries {
262 |
263 | binary.LittleEndian.PutUint32(uint32Buffer, entry.DirectoryEntry.Type)
264 | buf.Write(uint32Buffer)
265 |
266 | binary.LittleEndian.PutUint32(uint32Buffer, entry.DirectoryEntry.Size)
267 | buf.Write(uint32Buffer)
268 |
269 | binary.LittleEndian.PutUint32(uint32Buffer, entry.DirectoryEntry.Location)
270 | buf.Write(uint32Buffer)
271 |
272 | binary.LittleEndian.PutUint32(uint32Buffer, entry.DirectoryEntry.Reserved)
273 | buf.Write(uint32Buffer)
274 |
275 | if cookie == BHDCOOCKIE || cookie == SECONDBHDCOOCKIE {
276 | uint64Buffer := make([]byte, 8)
277 | binary.LittleEndian.PutUint64(uint64Buffer, *entry.DirectoryEntry.Unknown)
278 | buf.Write(uint64Buffer)
279 | }
280 | }
281 |
282 | sum := fletcher32(buf.Bytes())
283 | return sum == directory.Header.Checksum, sum
284 | }
285 |
--------------------------------------------------------------------------------
/directory_test.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "fmt"
5 | "github.com/stretchr/testify/assert"
6 | "testing"
7 | )
8 |
9 | var (
10 |
11 | /**
12 | 00100000 32 50 53 50 ad 33 60 7f 04 00 00 00 00 00 00 00 |2PSP.3`.........|
13 | 00100010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
14 | 00100020 00 00 00 00 00 05 0b bc 00 90 2e 00 00 00 00 00 |................|
15 | 00100030 00 00 00 00 00 00 0a bc 00 d0 1d ff 00 00 00 00 |................|
16 | 00100040 00 00 00 00 00 01 0a bc 00 d0 1d ff 00 00 00 00 |................|
17 | 00100050 00 00 00 00 00 00 09 bc 00 10 11 ff 00 00 00 00 |................|
18 | 00100060 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
19 | */
20 |
21 | test2PSPDirectoryBytes = []byte{
22 | 0x32, 0x50, 0x53, 0x50, 0xad, 0x33, 0x60, 0x7f, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
23 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x0b, 0xbc, 0x00, 0x90, 0x2e, 0x00, 0x00, 0x00, 0x00, 0x00,
25 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xbc, 0x00, 0xd0, 0x1d, 0xff, 0x00, 0x00, 0x00, 0x00,
26 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0a, 0xbc, 0x00, 0xd0, 0x1d, 0xff, 0x00, 0x00, 0x00, 0x00,
27 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xbc, 0x00, 0x10, 0x11, 0xff, 0x00, 0x00, 0x00, 0x00,
28 | }
29 |
30 | test2PSPDirectory = Directory{
31 | Header: DirectoryHeader{
32 | Cookie: [4]uint8{0x32, 0x50, 0x53, 0x50},
33 | Checksum: 0x7f6033ad,
34 | TotalEntries: 0x4,
35 | Reserved: 0x0,
36 | },
37 | Location: testNewPSPDirBase,
38 | Entries: []Entry{
39 | {DirectoryEntry: DirectoryEntry{Type: 0x0, Size: 0xbc0b0500, Location: 0x002e9000, Reserved: 0x0}},
40 | {DirectoryEntry: DirectoryEntry{Type: 0x0, Size: 0xbc0a0000, Location: 0xff1dd000, Reserved: 0x0}},
41 | {DirectoryEntry: DirectoryEntry{Type: 0x0, Size: 0xbc0a0100, Location: 0xff1dd000, Reserved: 0x0}},
42 | {DirectoryEntry: DirectoryEntry{Type: 0x0, Size: 0xbc090000, Location: 0xff111000, Reserved: 0x0}},
43 | },
44 | }
45 | /*
46 | 000c0000 24 50 53 50 70 2e 88 ea 14 00 00 00 01 0e 18 80 |$PSPp...........|
47 | 000c0010 00 00 00 00 40 02 00 00 00 10 0c ff 00 00 00 00 |....@...........|
48 | 000c0020 01 00 00 00 00 80 00 00 00 10 18 ff 00 00 00 00 |................|
49 | 000c0030 08 00 00 00 00 40 01 00 00 90 18 ff 00 00 00 00 |.....@..........|
50 | 000c0040 03 00 00 00 00 60 00 00 00 20 0c ff 00 00 00 00 |.....`... ......|
51 | 000c0050 05 00 00 00 40 03 00 00 00 80 0c ff 00 00 00 00 |....@...........|
52 | 000c0060 06 00 00 00 00 10 00 00 00 f0 ff ff 00 00 00 00 |................|
53 | 000c0070 02 00 00 00 00 e0 01 00 00 d0 19 ff 00 00 00 00 |................|
54 | 000c0080 04 00 00 00 00 00 01 00 00 00 09 ff 00 00 00 00 |................|
55 | 000c0090 08 01 00 00 00 40 01 00 00 b0 1b ff 00 00 00 00 |.....@..........|
56 | 000c00a0 09 00 00 00 40 03 00 00 00 90 0c ff 00 00 00 00 |....@...........|
57 | 000c00b0 0b 00 00 00 ff ff ff ff 01 00 00 00 00 00 00 00 |................|
58 | 000c00c0 0c 00 00 00 00 a0 01 00 00 f0 1c ff 00 00 00 00 |................|
59 | 000c00d0 0d 00 00 00 40 03 00 00 00 a0 0c ff 00 00 00 00 |....@...........|
60 | 000c00e0 10 00 00 00 00 80 00 00 00 90 1e ff 00 00 00 00 |................|
61 | 000c00f0 12 00 00 00 00 b0 00 00 00 10 1f ff 00 00 00 00 |................|
62 | 000c0100 14 00 00 00 00 00 02 00 00 c0 1f ff 00 00 00 00 |................|
63 | 000c0110 12 01 00 00 00 b0 00 00 00 c0 21 ff 00 00 00 00 |..........!.....|
64 | 000c0120 5f 00 00 00 00 10 00 00 00 70 22 ff 00 00 00 00 |_........p".....|
65 | 000c0130 5f 01 00 00 00 10 00 00 00 80 22 ff 00 00 00 00 |_.........".....|
66 | 000c0140 1a 00 00 00 00 30 00 00 00 90 22 ff 00 00 00 00 |.....0....".....|
67 | 000c0150 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
68 | */
69 |
70 | testPSPDirectoryBytes = []byte{
71 | 0x24, 0x50, 0x53, 0x50, 0x70, 0x2e, 0x88, 0xea, 0x14, 0x00, 0x00, 0x00, 0x01, 0x0e, 0x18, 0x80,
72 | 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x10, 0x0c, 0xff, 0x00, 0x00, 0x00, 0x00,
73 | 0x01, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x10, 0x18, 0xff, 0x00, 0x00, 0x00, 0x00,
74 | 0x08, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0x90, 0x18, 0xff, 0x00, 0x00, 0x00, 0x00,
75 | 0x03, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x20, 0x0c, 0xff, 0x00, 0x00, 0x00, 0x00,
76 | 0x05, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x00, 0x00, 0x80, 0x0c, 0xff, 0x00, 0x00, 0x00, 0x00,
77 | 0x06, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
78 | 0x02, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x00, 0xd0, 0x19, 0xff, 0x00, 0x00, 0x00, 0x00,
79 | 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0xff, 0x00, 0x00, 0x00, 0x00,
80 | 0x08, 0x01, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0xb0, 0x1b, 0xff, 0x00, 0x00, 0x00, 0x00,
81 | 0x09, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x00, 0x00, 0x90, 0x0c, 0xff, 0x00, 0x00, 0x00, 0x00,
82 | 0x0b, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
83 | 0x0c, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x01, 0x00, 0x00, 0xf0, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00,
84 | 0x0d, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x00, 0x00, 0xa0, 0x0c, 0xff, 0x00, 0x00, 0x00, 0x00,
85 | 0x10, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x90, 0x1e, 0xff, 0x00, 0x00, 0x00, 0x00,
86 | 0x12, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x10, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00,
87 | 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0xc0, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00,
88 | 0x12, 0x01, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0xc0, 0x21, 0xff, 0x00, 0x00, 0x00, 0x00,
89 | 0x5f, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x70, 0x22, 0xff, 0x00, 0x00, 0x00, 0x00,
90 | 0x5f, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x80, 0x22, 0xff, 0x00, 0x00, 0x00, 0x00,
91 | 0x1a, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x90, 0x22, 0xff, 0x00, 0x00, 0x00, 0x00,
92 | }
93 |
94 | testPSPDirectory = Directory{
95 | Header: DirectoryHeader{
96 | Cookie: [4]byte{0x24, 0x50, 0x53, 0x50},
97 | Checksum: 0xea882e70,
98 | TotalEntries: 0x14,
99 | Reserved: 0x80180e01,
100 | },
101 | Location: testPSPDirBase - DefaultFlashMapping,
102 | Entries: []Entry{
103 | {DirectoryEntry: DirectoryEntry{Type: 0x0, Size: 0x240, Location: 0xff0c1000, Reserved: 0x0}},
104 | {DirectoryEntry: DirectoryEntry{Type: 0x1, Size: 0x8000, Location: 0xff181000, Reserved: 0x0}},
105 | {DirectoryEntry: DirectoryEntry{Type: 0x8, Size: 0x14000, Location: 0xff189000, Reserved: 0x0}},
106 | {DirectoryEntry: DirectoryEntry{Type: 0x3, Size: 0x6000, Location: 0xff0c2000, Reserved: 0x0}},
107 | {DirectoryEntry: DirectoryEntry{Type: 0x5, Size: 0x340, Location: 0xff0c8000, Reserved: 0x0}},
108 | {DirectoryEntry: DirectoryEntry{Type: 0x6, Size: 0x1000, Location: 0xfffff000, Reserved: 0x0}},
109 | {DirectoryEntry: DirectoryEntry{Type: 0x2, Size: 0x1e000, Location: 0xff19d000, Reserved: 0x0}},
110 | {DirectoryEntry: DirectoryEntry{Type: 0x4, Size: 0x10000, Location: 0xff090000, Reserved: 0x0}},
111 | {DirectoryEntry: DirectoryEntry{Type: 0x108, Size: 0x14000, Location: 0xff1bb000, Reserved: 0x0}},
112 | {DirectoryEntry: DirectoryEntry{Type: 0x9, Size: 0x340, Location: 0xff0c9000, Reserved: 0x0}},
113 | {DirectoryEntry: DirectoryEntry{Type: 0xb, Size: 0xffffffff, Location: 0x1, Reserved: 0x0}},
114 | {DirectoryEntry: DirectoryEntry{Type: 0xc, Size: 0x1a000, Location: 0xff1cf000, Reserved: 0x0}},
115 | {DirectoryEntry: DirectoryEntry{Type: 0xd, Size: 0x340, Location: 0xff0ca000, Reserved: 0x0}},
116 | {DirectoryEntry: DirectoryEntry{Type: 0x10, Size: 0x8000, Location: 0xff1e9000, Reserved: 0x0}},
117 | {DirectoryEntry: DirectoryEntry{Type: 0x12, Size: 0xb000, Location: 0xff1f1000, Reserved: 0x0}},
118 | {DirectoryEntry: DirectoryEntry{Type: 0x14, Size: 0x20000, Location: 0xff1fc000, Reserved: 0x0}},
119 | {DirectoryEntry: DirectoryEntry{Type: 0x112, Size: 0xb000, Location: 0xff21c000, Reserved: 0x0}},
120 | {DirectoryEntry: DirectoryEntry{Type: 0x5f, Size: 0x1000, Location: 0xff227000, Reserved: 0x0}},
121 | {DirectoryEntry: DirectoryEntry{Type: 0x15f, Size: 0x1000, Location: 0xff228000, Reserved: 0x0}},
122 | {DirectoryEntry: DirectoryEntry{Type: 0x1a, Size: 0x3000, Location: 0xff229000, Reserved: 0x0}}},
123 | }
124 |
125 | testPSPDirectoryHeaderBytes = testPSPDirectoryBytes[:16]
126 | testPSPDirectoryEntryBytes = testPSPDirectoryBytes[16:32]
127 |
128 | testPSPMiniDirectoryBytes = []byte{
129 | 0x24, 0x50, 0x53, 0x50, 0x70, 0x2e, 0x88, 0xea, 0x01, 0x00, 0x00, 0x00, 0x01, 0x0e, 0x18, 0x80,
130 | 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x10, 0x0c, 0xff, 0x00, 0x00, 0x00, 0x00,
131 | }
132 |
133 | testPSPMiniDirectory = Directory{
134 | Header: DirectoryHeader{
135 | Cookie: [4]byte{0x24, 0x50, 0x53, 0x50},
136 | Checksum: 0xea882e70, // Not checked and wrong
137 | TotalEntries: 0x1,
138 | Reserved: 0x80180e01,
139 | },
140 | Location: testPSPDirBase - DefaultFlashMapping,
141 | Entries: []Entry{
142 | {DirectoryEntry: DirectoryEntry{Type: 0x0, Size: 0x240, Location: 0xff0c1000, Reserved: 0x0}},
143 | },
144 | }
145 |
146 | testBHDDirectoryBytes = []byte{
147 | 0x24, 0x42, 0x48, 0x44, 0x52, 0xf8, 0x63, 0x9e, 0x0b, 0x00, 0x00, 0x00, 0x1c, 0x04, 0x00, 0x00,
148 | 0x60, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00,
149 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x60, 0x00, 0x20, 0x00, 0x00, 0x20, 0x00, 0x00,
150 | 0x00, 0x40, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
151 | 0x68, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x60, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00,
152 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x68, 0x00, 0x20, 0x00, 0x00, 0x20, 0x00, 0x00,
153 | 0x00, 0x80, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
154 | 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
155 | 0x00, 0x00, 0x20, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00,
156 | 0x00, 0x00, 0xe0, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x09, 0x00, 0x00, 0x00, 0x00,
157 | 0x64, 0x00, 0x10, 0x00, 0x40, 0x3c, 0x00, 0x00, 0x00, 0xa0, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00,
158 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x65, 0x00, 0x10, 0x00, 0x30, 0x03, 0x00, 0x00,
159 | 0x00, 0xdd, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
160 | 0x64, 0x00, 0x40, 0x00, 0x10, 0x46, 0x00, 0x00, 0x00, 0xe1, 0x1c, 0xff, 0x00, 0x00, 0x00, 0x00,
161 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x65, 0x00, 0x40, 0x00, 0x20, 0x03, 0x00, 0x00,
162 | 0x00, 0x28, 0x1d, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
163 | 0x70, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x10, 0x64, 0xff, 0x00, 0x00, 0x00, 0x00,
164 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
165 | }
166 |
167 | testBHDDirectoryHeaderBytes = testBHDDirectoryBytes[0:16]
168 | testBHDDirectoryEntryBytes = testBHDDirectoryBytes[16 : 16+4*6]
169 |
170 | testBHDDirectoryHeader = DirectoryHeader{Cookie: [4]uint8{0x24, 0x42, 0x48, 0x44}, Checksum: 0x9e63f852, TotalEntries: 0xb, Reserved: 0x41c}
171 | testBHDDirEntryUnknown0xFF = uint64(0xffffffffffffffff)
172 | testBHDDirEntryKnown0xA2 = uint64(0xa200000)
173 | testBHDDirEntryKnown0x9E = uint64(0x9e00000)
174 |
175 | testBHDDirectory = Directory{
176 | Header: testBHDDirectoryHeader,
177 | Entries: []Entry{
178 | {DirectoryEntry: DirectoryEntry{Type: 0x60, Size: 0x2000, Location: 0xff1c2000, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
179 | {DirectoryEntry: DirectoryEntry{Type: 0x200060, Size: 0x2000, Location: 0xff1c4000, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
180 | {DirectoryEntry: DirectoryEntry{Type: 0x68, Size: 0x2000, Location: 0xff1c6000, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
181 | {DirectoryEntry: DirectoryEntry{Type: 0x200068, Size: 0x2000, Location: 0xff1c8000, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
182 | {DirectoryEntry: DirectoryEntry{Type: 0x61, Size: 0x0, Location: 0x0, Reserved: 0x0, Unknown: &testBHDDirEntryKnown0xA2}},
183 | {DirectoryEntry: DirectoryEntry{Type: 0x30062, Size: 0x200000, Location: 0xffe00000, Reserved: 0x0, Unknown: &testBHDDirEntryKnown0x9E}},
184 | {DirectoryEntry: DirectoryEntry{Type: 0x100064, Size: 0x3c40, Location: 0xff1ca000, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
185 | {DirectoryEntry: DirectoryEntry{Type: 0x100065, Size: 0x330, Location: 0xff1cdd00, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
186 | {DirectoryEntry: DirectoryEntry{Type: 0x400064, Size: 0x4610, Location: 0xff1ce100, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
187 | {DirectoryEntry: DirectoryEntry{Type: 0x400065, Size: 0x320, Location: 0xff1d2800, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
188 | {DirectoryEntry: DirectoryEntry{Type: 0x70, Size: 0x400, Location: 0xff641000, Reserved: 0x0, Unknown: &testBHDDirEntryUnknown0xFF}},
189 | },
190 | Location: testBHDDirBase - DefaultFlashMapping,
191 | }
192 | )
193 |
194 | func TestParseDirectoryHeaderToSmall(t *testing.T) {
195 | imageToSmall := make([]byte, FETDefaultOffset/2)
196 |
197 | dir, err := ParseDirectory(imageToSmall, DefaultFlashMapping+FETDefaultOffset, DefaultFlashMapping)
198 |
199 | assert.EqualError(t, err, "Firmwarebytes not long enough for reading directory header..")
200 | assert.Nil(t, dir)
201 |
202 | }
203 |
204 | func TestParseDirectoryHeaderCookieWrong(t *testing.T) {
205 | imageBytes := make([]byte, testImage16MB)
206 | copy(imageBytes[testPSPDirBase-DefaultFlashMapping:], "$INV")
207 |
208 | dir, err := ParseDirectory(imageBytes, uint32(testPSPDirBase), DefaultFlashMapping)
209 |
210 | assert.EqualError(t, err, "No Valid Cookie at start of directory: [36 73 78 86]")
211 | assert.Nil(t, dir)
212 | }
213 |
214 | func TestParseDirectoryHeaderToManyEntries(t *testing.T) {
215 | overSizedDirectory := testPSPDirectory
216 | overSizedDirectory.Header.TotalEntries = 1
217 |
218 | imgSize := testPSPDirBase - DefaultFlashMapping + 16
219 | imageBytes := make([]byte, imgSize)
220 | overSizedDirectory.Header.Write(imageBytes, testPSPDirBase-DefaultFlashMapping)
221 |
222 | // Read with mapping
223 | dir, err := ParseDirectory(imageBytes, testPSPDirBase, DefaultFlashMapping)
224 |
225 | assert.EqualError(t, err, "Could not read directory entries from image: Too many entries(1)!")
226 | assert.Nil(t, dir)
227 |
228 | }
229 |
230 | func TestParseDirectoryPass(t *testing.T) {
231 | imageBytes := make([]byte, testImage16MB)
232 | copy(imageBytes[testPSPDirBase-DefaultFlashMapping:], testPSPDirectoryBytes)
233 |
234 | // Read with mapping
235 | dir, err := ParseDirectory(imageBytes, testPSPDirBase, DefaultFlashMapping)
236 |
237 | assert.Nil(t, err)
238 | assert.NotNil(t, dir)
239 |
240 | // And without
241 | dir2, err2 := ParseDirectory(imageBytes, testPSPDirBase, DefaultFlashMapping)
242 |
243 | assert.Nil(t, err2)
244 | assert.NotNil(t, dir2)
245 | assert.Equal(t, *dir, *dir2)
246 |
247 | assert.Equal(t, testPSPDirectory.Header, dir.Header)
248 | assert.Equal(t, len(testPSPDirectory.Entries), len(dir.Entries))
249 |
250 | for i := 0; i < len(dir.Entries); i++ {
251 | assert.Equal(t, testPSPDirectory.Entries[i].DirectoryEntry, dir.Entries[i].DirectoryEntry)
252 | }
253 | }
254 |
255 | func TestParse2PSPDirectory(t *testing.T) {
256 | imageBytes := make([]byte, testImage16MB)
257 | copy(imageBytes[testPSPDirBase-DefaultFlashMapping:], test2PSPDirectoryBytes)
258 |
259 | // Read with mapping
260 | dir, err := ParseDirectory(imageBytes, testPSPDirBase, DefaultFlashMapping)
261 |
262 | assert.Nil(t, err)
263 | assert.NotNil(t, dir)
264 |
265 | assert.Equal(t, test2PSPDirectory.Header, dir.Header)
266 | assert.Equal(t, len(test2PSPDirectory.Entries), len(dir.Entries))
267 |
268 | for i := 0; i < len(dir.Entries); i++ {
269 | assert.Equal(t, test2PSPDirectory.Entries[i].DirectoryEntry, dir.Entries[i].DirectoryEntry)
270 | }
271 | }
272 |
273 | func TestParseBHDDirectory(t *testing.T) {
274 | imageBytes := make([]byte, testImage16MB)
275 | copy(imageBytes[testBHDDirBase-DefaultFlashMapping:], testBHDDirectoryBytes)
276 |
277 | // Read with mapping
278 | dir, err := ParseDirectory(imageBytes, testBHDDirBase, DefaultFlashMapping)
279 |
280 | assert.Nil(t, err)
281 | assert.NotNil(t, dir)
282 |
283 | assert.Equal(t, testBHDDirectory.Header, dir.Header)
284 | assert.Equal(t, len(testBHDDirectory.Entries), len(dir.Entries))
285 | assert.Equal(t, testBHDDirBase-DefaultFlashMapping, dir.Location)
286 |
287 | for i := 0; i < len(dir.Entries); i++ {
288 | assert.Equal(t, *testBHDDirectory.Entries[i].DirectoryEntry.Unknown, *dir.Entries[i].DirectoryEntry.Unknown, fmt.Sprint("Entries padding does not match: ", i))
289 |
290 | // Whipe unknown Pointer
291 | dir.Entries[i].DirectoryEntry.Unknown = testBHDDirectory.Entries[i].DirectoryEntry.Unknown
292 | assert.Equal(t, testBHDDirectory.Entries[i].DirectoryEntry, dir.Entries[i].DirectoryEntry)
293 | }
294 | }
295 |
296 | func TestDirectory_ValidateChecksum(t *testing.T) {
297 | valid, actual := testPSPDirectory.ValidateChecksum()
298 |
299 | assert.Equal(t, true, valid)
300 | assert.Equal(t, testPSPDirectory.Header.Checksum, actual)
301 | }
302 |
303 | func TestDirectory_ValidateChecksum2PSP(t *testing.T) {
304 | valid, actual := test2PSPDirectory.ValidateChecksum()
305 |
306 | assert.Equal(t, true, valid)
307 | assert.Equal(t, test2PSPDirectory.Header.Checksum, actual)
308 | }
309 |
310 | func TestDirectory_ValidateChecksumBHD(t *testing.T) {
311 | valid, actual := testBHDDirectory.ValidateChecksum()
312 |
313 | assert.Equal(t, true, valid)
314 | assert.Equal(t, testBHDDirectory.Header.Checksum, actual)
315 | }
316 |
317 | func TestDirectory_Write(t *testing.T) {
318 | baseImage := make([]byte, testImage16MB)
319 | expectedImage := make([]byte, testImage16MB)
320 | copy(expectedImage[testPSPDirectory.Location:], testPSPDirectoryBytes)
321 |
322 | err := testPSPDirectory.Write(baseImage, DefaultFlashMapping)
323 |
324 | assert.Nil(t, err)
325 | assert.Equal(t, expectedImage, baseImage)
326 | }
327 |
328 | func TestDirectoryHeader_Write(t *testing.T) {
329 | baseImage := make([]byte, testImage16MB)
330 | expectedImage := make([]byte, testImage16MB)
331 | copy(expectedImage[testPSPDirectory.Location:], testPSPDirectoryHeaderBytes)
332 |
333 | err := testPSPDirectory.Header.Write(baseImage, testPSPDirectory.Location)
334 |
335 | assert.Nil(t, err)
336 | assert.Equal(t, expectedImage, baseImage)
337 | }
338 |
339 | func TestDirectoryEntry_Write(t *testing.T) {
340 | baseImage := make([]byte, testImage16MB)
341 | expectedImage := make([]byte, testImage16MB)
342 | copy(expectedImage[testPSPDirectory.Location+16:], testPSPDirectoryEntryBytes)
343 |
344 | err := testPSPDirectory.Entries[0].DirectoryEntry.Write(baseImage, testPSPDirectory.Location+16)
345 |
346 | assert.Nil(t, err)
347 | assert.Equal(t, expectedImage, baseImage)
348 | }
349 |
350 | func TestDirectoryEntry_WriteBHD(t *testing.T) {
351 | baseImage := make([]byte, testBHDDirectory.Location+0x100)
352 | expectedImage := make([]byte, testBHDDirectory.Location+0x100)
353 | copy(expectedImage[testBHDDirectory.Location+16:], testBHDDirectoryEntryBytes)
354 |
355 | err := testBHDDirectory.Entries[0].DirectoryEntry.Write(baseImage, testBHDDirectory.Location+16)
356 |
357 | assert.Nil(t, err)
358 | assert.Equal(t, expectedImage, baseImage)
359 | }
360 |
361 | func TestDirectory_WriteToSmall(t *testing.T) {
362 | baseImage := make([]byte, FETDefaultOffset+5)
363 |
364 | err := testPSPDirectory.Write(baseImage, DefaultFlashMapping)
365 |
366 | assert.EqualError(t, err, "BaseImage to small to insert Directory")
367 | }
368 |
369 | func TestDirectory_WriteBHD(t *testing.T) {
370 | baseImage := make([]byte, testImage16MB)
371 | expectedImage := make([]byte, testImage16MB)
372 | copy(expectedImage[testBHDDirectory.Location:], testBHDDirectoryBytes)
373 |
374 | err := testBHDDirectory.Write(baseImage, DefaultFlashMapping)
375 |
376 | assert.Nil(t, err)
377 | assert.Equal(t, expectedImage, baseImage)
378 | }
379 |
380 | func TestDirectory_Write2PSP(t *testing.T) {
381 | baseImage := make([]byte, testImage16MB)
382 | expectedImage := make([]byte, testImage16MB)
383 | copy(expectedImage[test2PSPDirectory.Location:], test2PSPDirectoryBytes)
384 |
385 | err := test2PSPDirectory.Write(baseImage, DefaultFlashMapping)
386 |
387 | assert.Nil(t, err)
388 | assert.Equal(t, expectedImage, baseImage)
389 | }
390 |
--------------------------------------------------------------------------------
/entry.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "fmt"
7 | pspentries "github.com/Mimoja/PSP-Entry-Types"
8 | )
9 |
10 | type (
11 | Entry struct {
12 | DirectoryEntry DirectoryEntry
13 | Header *EntryHeader
14 | Raw []byte
15 | Signature []byte
16 | Comment []string
17 | TypeInfo *TypeInfo
18 | Version string
19 | }
20 |
21 | EntryHeader struct {
22 | Unknown00 [0x10]byte // 0x00
23 | ID uint32 // 0x10
24 | SizeSigned uint32 // 0x14
25 | IsEncrypted uint32 // 0x18
26 | Unknown1C uint32 // 0x1C
27 | EncFingerprint [0x10]byte // 0x20
28 | IsSigned uint32 // 0x30
29 | Unknown34 uint32 // 0x34
30 | SigFingerprint [0x10]byte // 0x38
31 | IsCompressed uint32 // 0x48
32 | Unknown4C uint32 // 0x4C
33 | FullSize uint32 // 0x50
34 | Unknown54 uint32 // 0x54
35 | Unknown58 [0x08]byte // 0x58
36 | Version [0x04]byte // 0x60
37 | Unknown64 uint32 // 0x64
38 | Unknown68 uint32 // 0x68
39 | SizePacked uint32 // 0x6C
40 | Unknown70 [0x10]byte // 0x70
41 | Unknown80 [0x10]byte // 0x80
42 | Unknown90 uint32 // 0x90
43 | Unknown94 uint32 // 0x94
44 | Unknown98 uint32 // 0x98
45 | Unknown9C uint32 // 0x9C
46 | UnknownA0 uint32 // 0xA0
47 | UnknownA4 uint32 // 0xA4
48 | UnknownA8 uint32 // 0xA8
49 | UnknownAC uint32 // 0xAC
50 | UnknownB0 [0x50]byte // 0xB0
51 |
52 | }
53 |
54 | TypeInfo struct {
55 | Name string
56 | Comment string
57 | }
58 | )
59 |
60 | var knownTypes = pspentries.Types()
61 |
62 | func ParseEntry(firmwareBytes []byte, directoryEntry DirectoryEntry, flashMapping uint32) (*Entry, error) {
63 | entry := Entry{
64 | DirectoryEntry: directoryEntry,
65 | }
66 |
67 | /**
68 | * Typechecking
69 | */
70 | for _, knownType := range knownTypes {
71 | if knownType.Type == directoryEntry.Type {
72 | name := knownType.Name
73 | if name == "" {
74 | name = knownType.ProposedName
75 | }
76 | info := TypeInfo{
77 | Name: name,
78 | Comment: knownType.Comment,
79 | }
80 | entry.TypeInfo = &info
81 | break
82 | }
83 | }
84 |
85 | if entry.TypeInfo == nil {
86 | errorAndComment(&entry, fmt.Errorf("Unknown Type: 0x%08X", directoryEntry.Type))
87 | }
88 |
89 | /**
90 | * Raw Data logic
91 | */
92 |
93 | location := directoryEntry.Location
94 | size := directoryEntry.Size
95 |
96 | if location >= flashMapping {
97 | location -= flashMapping
98 | }
99 |
100 | if int(location) > len(firmwareBytes) {
101 | return errorAndComment(&entry, fmt.Errorf("Not a parsable Entry: Location out of bounds (0x%08X)", location))
102 | }
103 |
104 | if int(size) > len(firmwareBytes)-int(location) {
105 | return errorAndComment(&entry, fmt.Errorf("Not a parsable Entry: Size to big (0x%08X)", size))
106 | }
107 |
108 | entryBytes := firmwareBytes[location : location+size]
109 | entry.Raw = entryBytes
110 |
111 | /**
112 | * Header Parsing
113 | */
114 |
115 | if size < 0x100 && size > 0 {
116 | return errorAndComment(&entry, fmt.Errorf("Not a parsable Entry: Entry to small for header parsing: (0x%08X) bytes", size))
117 | }
118 |
119 | headerBytes := entryBytes[:0x100]
120 |
121 | if allOneValue(headerBytes) {
122 | return errorAndComment(&entry, fmt.Errorf("Not a parsable Entry: All Fields are 0x%02X", headerBytes[1]))
123 | }
124 |
125 | header := EntryHeader{}
126 | err := binary.Read(bytes.NewReader(entryBytes), binary.LittleEndian, &header)
127 |
128 | if err != nil {
129 | return errorAndComment(&entry, fmt.Errorf("Error: Could not read header: %v", err))
130 | }
131 |
132 | if header.IsCompressed > 1 {
133 | return errorAndComment(&entry, fmt.Errorf("Not a parsable Entry: Compressed Field is 0x%02X", header.IsCompressed))
134 | }
135 |
136 | if header.SizePacked == 0 &&
137 | header.SizeSigned == 0 &&
138 | header.FullSize == 0 {
139 | return errorAndComment(&entry, fmt.Errorf("Not a parsable Entry: Size Values not reasonable"))
140 | }
141 |
142 | entry.Header = &header
143 | if header.SizeSigned != 0 || header.IsSigned != 0 || len(header.SigFingerprint) == 0 {
144 | if header.SizePacked-header.SizeSigned == 0x300 {
145 | entry.Signature = entryBytes[len(entryBytes)-0x200:]
146 | } else {
147 | entry.Signature = entryBytes[len(entryBytes)-0x100:]
148 | }
149 | }
150 |
151 | entry.Version = fmt.Sprintf("%X.%X.%X.%X", header.Version[3], header.Version[2], header.Version[1], header.Version[0])
152 |
153 | return &entry, nil
154 | }
155 |
156 | func (entry Entry) Write(baseImage []byte, address uint32) error {
157 | copied := copy(baseImage[address:], entry.Raw)
158 |
159 | if copied != len(entry.Raw) {
160 | return fmt.Errorf("Could not write Entry: Failed after 0x08%X Bytes", copied)
161 | }
162 | return nil
163 | }
164 |
165 | func allOneValue(s []byte) bool {
166 | reference := s[0]
167 | for _, v := range s {
168 | if v != reference {
169 | return false
170 | }
171 | }
172 | return true
173 | }
174 |
175 | func errorAndComment(entry *Entry, err error) (*Entry, error) {
176 | entry.Comment = append(entry.Comment, err.Error())
177 | return entry, err
178 | }
179 |
--------------------------------------------------------------------------------
/entry_test.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "github.com/stretchr/testify/assert"
7 | "testing"
8 | )
9 |
10 | var (
11 |
12 | /**
13 | 002fdc00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
14 | 002fdc10 30 42 41 52 a8 04 00 00 00 00 00 00 00 00 00 00 |0BAR............|
15 | 002fdc20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
16 | 002fdc30 01 00 00 00 00 00 00 00 27 93 94 ca c2 c2 4e fb |........'.....N.|
17 | 002fdc40 97 ae da 24 1d 31 c8 de 01 00 00 00 00 00 00 00 |...$.1..........|
18 | 002fdc50 a8 04 00 00 cf 02 00 00 00 00 00 00 00 00 00 00 |................|
19 | 002fdc60 01 15 05 17 50 5a 4c 42 00 01 00 00 d0 04 00 00 |....PZLB........|
20 | 002fdc70 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
21 | *
22 | 002fdca0 25 00 00 00 0d 00 00 00 01 00 00 00 00 00 00 00 |%...............|
23 | 002fdcb0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
24 | *
25 | 002fdd00 78 da a5 d2 4f 48 db 50 18 00 f0 ef 25 fd 67 36 |x...OH.P....%.g6|
26 | 002fdd10 86 63 3b b8 d1 c1 13 eb ec 60 32 ad f5 ef a9 ad |.c;......`2.....|
27 | 002fdd20 34 ad 9d b5 5d 95 39 87 68 b3 ae ce ba da 96 da |4...].9.h.......|
28 | 002fdd30 b2 81 30 1c 08 63 3b 95 fd a3 bb ac 82 97 1e d5 |..0..c;.........|
29 | 002fdd40 e1 c1 83 b0 83 3b 0a e9 6d b7 d4 83 68 3d f5 b0 |.....;..m...h=..|
30 | 002fdd50 6a c0 6a f6 92 cd 52 c1 c2 60 81 24 5f de f7 fb |j.j...R..`.$_...|
31 | 002fdd60 be 47 78 5f 03 9f d9 6d c0 99 5d 93 74 6f 07 f8 |.Gx_...m..].to..|
32 | 002fdd70 a5 9d fa 7c 66 b7 fe ef f7 a9 24 1d 80 99 06 b5 |...|f.....$.....|
33 | 002fdd80 0f 81 fe 01 82 3b e4 5d 5c 7f b3 82 b2 60 d8 2e |.....;.]\....`..|
34 | 002fdd90 d0 16 15 56 a7 6e 38 35 cd 54 8a ca 6a 3e dd 16 |...V.n85.T..j>..|
35 | 002fdda0 50 da 52 44 80 c8 57 8b 70 7d c8 73 78 12 a3 53 |P.RD..W.p}.sx..S|
36 | 002fddb0 08 6f 17 d4 6a 2a bb 5d 40 0f 5b 84 17 7a 25 72 |.o..j*.]@.[..z%r|
37 | 002fddc0 c8 f6 c7 9a 96 e4 90 46 d6 f2 1a 95 95 57 bf af |.......F.....W..|
38 | 002fddd0 d9 0f 00 2f 95 9a ad 8f 7b 29 1e 61 ed 4a 71 13 |.../....{).a.Jq.|
39 | 002fdde0 f0 f1 1e d0 3f 4f e3 00 e5 9e 75 28 59 bc d6 43 |....?O....u(Y..C|
40 | 002fddf0 b0 5d 62 d5 03 f0 7e 86 e5 45 91 6e 15 54 2c bd |.]b...~..E.n.T,.|
41 | 002fde00 a4 11 30 db b3 09 00 1f 69 a8 b3 3a ec c3 56 ec |..0.....i..:..V.|
42 | 002fde10 b6 bb 71 2b 1e 88 84 12 21 2e 8c ad de 7e 1b 1e |..q+....!....~..|
43 | 002fde20 4e c6 62 d1 78 82 21 0e c7 1c f2 ad 5b d7 38 67 |N.b.x.!.....[.8g|
44 | 002fde30 58 cd 00 12 74 1b 90 ae df f0 14 a5 36 10 20 ad |X...t.......6. .|
45 | 002fde40 93 7b ad d0 00 3c 0d ad 85 f2 a4 aa 89 fc d3 3c |.{...<.........<|
46 | 002fde50 e7 19 63 05 71 f1 35 e7 e2 9c 8c c0 91 5d 75 25 |..c.q.5......]u%|
47 | 002fde60 cb c8 94 53 5b 5a 48 6e 89 fb 74 d0 b9 55 38 d6 |...S[ZHn..t..U8.|
48 | 002fde70 a2 ac 5e 08 dc f7 14 81 59 14 7f 2d f7 b1 28 ed |..^.....Y..-..(.|
49 | 002fde80 6f fc 7a 93 32 5e e1 91 f1 32 ff 96 dd 12 c5 6b |o.z.2^...2.....k|
50 | 002fde90 d2 d1 23 09 be 4d 63 12 d3 08 2f 8a 65 fa 56 de |..#..Mc.../.e.V.|
51 | 002fdea0 a2 64 a0 51 3a 7a 27 a9 60 3e d7 89 67 d8 5e 16 |.d.Q:z'.`>..g.^.|
52 | 002fdeb0 3e 53 82 0a a6 73 90 06 e3 2b 7e 88 ec 69 61 b3 |>S...s...+~..ia.|
53 | 002fdec0 0e 15 fb 80 44 a1 3c a9 f8 40 aa 97 a1 d1 c2 4a |....D.<..@.....J|
54 | 002fded0 47 11 52 37 99 93 33 ed 55 b5 2e a5 d6 cf 8f 54 |G.R7..3.U......T|
55 | 002fdee0 6a 47 49 04 77 5d b9 ae 2a d5 ad 28 37 3f 5a 51 |jGI.w]..*..(7?ZQ|
56 | 002fdef0 63 8a ea ce 99 aa 94 41 51 7d fc 58 45 8d 2b ca |c......AQ}.XE.+.|
57 | 002fdf00 90 eb a8 52 57 15 d5 c2 8f 57 d4 04 89 cc 1b e6 |...RW....W......|
58 | 002fdf10 2a 43 f1 90 ce ae ea f2 90 4e ad 4e 54 9c 9f 44 |*C.......N.NT..D|
59 | 002fdf20 75 2e 55 53 9d 73 8c f5 e9 19 21 a0 9c 2c 08 9b |u.US.s....!..,..|
60 | 002fdf30 fb e5 8c b4 87 0c c5 3d 72 2e 7e 44 1e 34 94 f3 |.......=r.~D.4..|
61 | 002fdf40 70 b0 40 e6 82 b1 da 06 db c8 51 bb b9 50 04 93 |p.@.......Q..P..|
62 | 002fdf50 18 db 5f 06 03 c9 44 28 1a 61 e0 84 cc 2e f2 fd |.._...D(.a......|
63 | 002fdf60 f1 4c 3f 17 0e 87 22 cf 14 d3 89 6d 83 64 0e 18 |.L?..."....m.d..|
64 | 002fdf70 5f 30 91 8c 47 82 4f f1 54 3c 3a 5b 9d 81 7f 9a |_0..G.O.T<:[....|
65 | 002fdf80 a3 73 3d db 6b f6 6c 3f eb 79 ce 77 d5 f4 5d 17 |.s=.k.l?.y.w..].|
66 | 002fdf90 7a 53 4d 6f ba d0 77 d4 f4 1d 17 7a 73 4d 6f ae |zSMo..w....zsMo.|
67 | 002fdfa0 78 6b 38 2c af cc e1 fe e8 6c 2c 1c 4c 04 b1 31 |xk8,.....l,.L..1|
68 | 002fdfb0 c6 cd cd e1 40 34 92 88 47 c3 f8 09 17 78 8e 13 |....@4..G....x..|
69 | 002fdfc0 51 ec 1d f6 9e d5 7c f9 cf eb 37 10 13 a1 d9 00 |Q.....|...7.....|
70 | 002fdfd0 0b df 7b 33 d7 24 d1 37 bd bb 4f a3 8d fa c4 bb |..{3.$.7..O.....|
71 | 002fdfe0 91 09 66 68 bc 4f ae 62 a8 c2 b4 a3 c6 43 b2 3b |..fh.O.b.....C.;|
72 | 002fdff0 e2 8a da 21 2f 66 1b 82 6e 59 b3 cb 67 61 6d 03 |...!/f..nY..gam.|
73 | 002fe000 50 13 25 f0 06 e9 41 45 8a 25 19 6f 73 71 46 be |P.%...AE.%.osqF.|
74 | 002fe010 b4 cb d7 54 60 23 78 5f 0c 7c e7 11 8e 53 23 7c |...T`#x_.|...S#||
75 | 002fe020 be 09 90 2b 76 d7 bc cc 54 db 16 2f de 3c 4a 76 |...+v...T../. len(firmware)+binary.Size(FirmwareEntryTable{}) {
70 | return fmt.Errorf("Not AMD Table Header: Address out of bounds")
71 | }
72 | potentialMagic := binary.LittleEndian.Uint32(firmware[address:])
73 | if potentialMagic == FETSignature {
74 | return nil
75 | }
76 |
77 | return fmt.Errorf("Not AMD Table Header")
78 | }
79 |
80 | // Parses the FET at the given Address
81 | // Default address is 0x20000 but some PSP versions appear to be able to search on different offsets
82 | func ParseFirmwareEntryTable(firmware []byte, address uint32) (*FirmwareEntryTable, error) {
83 |
84 | if err := checkValidFirmwareEntryTable(firmware, address); err != nil {
85 | return nil, fmt.Errorf("Could not find FirmwareEntryTable Signature: %v", err)
86 | }
87 |
88 | tempTable := binaryFet{}
89 |
90 | if err := binary.Read(bytes.NewReader(firmware[address:]), binary.LittleEndian, &tempTable); err != nil {
91 | return nil, fmt.Errorf("Could not read FirmwareEntryTable: %v", err)
92 | }
93 |
94 | fet := FirmwareEntryTable{
95 | Signature: tempTable.Signature,
96 | ImcRomBase: &tempTable.ImcRomBase,
97 | GecRomBase: &tempTable.GecRomBase,
98 | XHCRomBase: &tempTable.XHCRomBase,
99 | PSPDirBase: &tempTable.PSPDirBase,
100 | NewPSPDirBase: &tempTable.NewPSPDirBase,
101 | BHDDirBase: &tempTable.BHDDirBase,
102 | NewBHDDirBase: &tempTable.NewBHDDirBase,
103 | Location: uint32(address),
104 | }
105 |
106 | // Not a full AMDFirmwareEntryTable. XHCI Rom is following...
107 | if *fet.PSPDirBase&0xFFFF == 0x55AA {
108 | fet.PSPDirBase = nil
109 | fet.NewPSPDirBase = nil
110 | fet.BHDDirBase = nil
111 | fet.NewBHDDirBase = nil
112 | }
113 |
114 | return &fet, nil
115 | }
116 |
117 | // Writes FET into existing image
118 | func (fet *FirmwareEntryTable) Write(baseImage []byte, address uint32) error {
119 |
120 | var tempTable interface{}
121 |
122 | if fet.PSPDirBase == nil &&
123 | fet.NewPSPDirBase == nil &&
124 | fet.NewBHDDirBase == nil &&
125 | fet.BHDDirBase == nil {
126 | tempTable = binaryShortFet{
127 | Signature: fet.Signature,
128 | ImcRomBase: *fet.ImcRomBase,
129 | GecRomBase: *fet.GecRomBase,
130 | XHCRomBase: *fet.XHCRomBase,
131 | }
132 | } else {
133 | tempTable = binaryFet{
134 | Signature: fet.Signature,
135 | ImcRomBase: *fet.ImcRomBase,
136 | GecRomBase: *fet.GecRomBase,
137 | XHCRomBase: *fet.XHCRomBase,
138 | PSPDirBase: *fet.PSPDirBase,
139 | NewPSPDirBase: *fet.NewPSPDirBase,
140 | BHDDirBase: *fet.BHDDirBase,
141 | NewBHDDirBase: *fet.NewBHDDirBase,
142 | }
143 | }
144 |
145 | fetSize := binary.Size(tempTable)
146 |
147 | if len(baseImage) < int(address)+fetSize {
148 | return fmt.Errorf("BaseImage to small to insert FET")
149 | }
150 |
151 | buf := new(bytes.Buffer)
152 |
153 | err := binary.Write(buf, binary.LittleEndian, tempTable)
154 | if err != nil {
155 | return fmt.Errorf("Writing binary failed: %v", err)
156 | }
157 |
158 | bytesCopied := copy(baseImage[address:], buf.Bytes())
159 |
160 | if bytesCopied != fetSize {
161 | return fmt.Errorf("Writing binary failed: Not all Bytes copied!")
162 | }
163 |
164 | return nil
165 | }
166 |
--------------------------------------------------------------------------------
/fet_test.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "github.com/stretchr/testify/assert"
5 | "testing"
6 | )
7 |
8 | const testImage16MB = 16777216
9 |
10 | /** Demo FET
11 | 00020000 aa 55 aa 55 00 00 00 00 00 00 00 00 00 10 02 ff |.U.U............|
12 | 00020010 00 10 10 ff 00 00 10 00 00 10 1c ff 00 d0 2b ff |..............+.|
13 | 00020020 00 90 3e 00 fe ff ff ff ff ff ff ff ff ff ff ff |..>.............|
14 | 00020030 00 00 00 00 00 00 9a ff ff ff ff ff ff ff ff ff |................|
15 | 00020040 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
16 | */
17 |
18 | var (
19 | fetBytes = []byte{
20 | 0xaa, 0x55, 0xaa, 0x55, 0x00, 0x00, 0x00, 0x00, 0x67, 0x45, 0x23, 0x01, 0x00, 0x10, 0x02, 0xff,
21 | 0x00, 0x10, 0x10, 0xff, 0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x1c, 0xff, 0x00, 0xd0, 0x2b, 0xff,
22 | }
23 |
24 | fetXHCIBytes = []byte{
25 | 0xaa, 0x55, 0xaa, 0x55, 0x00, 0x00, 0x00, 0x00, 0x67, 0x45, 0x23, 0x01, 0x00, 0x10, 0x02, 0xff,
26 | 0xaa, 0x55, 0xaa, 0x55,
27 | }
28 |
29 | testImcRomBase uint32 = 0
30 | testGecRomBase uint32 = 0x01234567
31 | testXHCRomBase uint32 = 0xFF021000
32 | testPSPDirBase uint32 = 0xFF101000
33 | testNewPSPDirBase uint32 = 0x100000
34 | testBHDDirBase uint32 = 0xFF1C1000
35 | testUnknown1 uint32 = 0xFF2BD000
36 |
37 | testFet = FirmwareEntryTable{
38 | Signature: 0x55AA55AA,
39 | ImcRomBase: &testImcRomBase,
40 | GecRomBase: &testGecRomBase,
41 | XHCRomBase: &testXHCRomBase,
42 | PSPDirBase: &testPSPDirBase,
43 | NewPSPDirBase: &testNewPSPDirBase,
44 | BHDDirBase: &testBHDDirBase,
45 | NewBHDDirBase: &testUnknown1,
46 | Location: 0x20000,
47 | }
48 |
49 | testShortFet = FirmwareEntryTable{
50 | Signature: 0x55AA55AA,
51 | ImcRomBase: &testImcRomBase,
52 | GecRomBase: &testGecRomBase,
53 | XHCRomBase: &testXHCRomBase,
54 | Location: 0x20000,
55 | }
56 | )
57 |
58 | func mockFetImage() []byte {
59 | imageBytes := make([]byte, testImage16MB)
60 | copy(imageBytes[FETDefaultOffset:], fetBytes)
61 |
62 | // Copy $PSP Header
63 | copy(imageBytes[testPSPDirBase-DefaultFlashMapping:], PSPCOOCKIE)
64 | return imageBytes
65 | }
66 |
67 | func TestCheckValidFET(t *testing.T) {
68 |
69 | err := checkValidFirmwareEntryTable(mockFetImage(), FETDefaultOffset)
70 |
71 | assert.Nil(t, err)
72 | }
73 |
74 | func TestCheckValidFETFailSize(t *testing.T) {
75 | imageToSmall := make([]byte, FETDefaultOffset/2)
76 |
77 | err := checkValidFirmwareEntryTable(imageToSmall, FETDefaultOffset)
78 |
79 | assert.EqualError(t, err, "Not AMD Table Header: Address out of bounds")
80 | }
81 |
82 | func TestCheckValidFETFailInvalid(t *testing.T) {
83 |
84 | err := checkValidFirmwareEntryTable(mockFetImage(), 0x1234)
85 |
86 | assert.EqualError(t, err, "Not AMD Table Header")
87 | }
88 |
89 | func TestFindFirmwareEntryTableByScanFail(t *testing.T) {
90 | smallImage := make([]byte, 500)
91 |
92 | offset, err := FindFirmwareEntryTable(smallImage)
93 |
94 | assert.EqualError(t, err, "No FirmwareTable found")
95 | assert.Equal(t, uint32(0), offset)
96 | }
97 |
98 | func TestFindFirmwareEntryTableFail(t *testing.T) {
99 | smallImage := make([]byte, testImage16MB)
100 |
101 | offset, err := FindFirmwareEntryTable(smallImage)
102 |
103 | assert.EqualError(t, err, "No FirmwareTable found")
104 | assert.Equal(t, uint32(0), offset)
105 | }
106 |
107 | func TestFindFirmwareEntryTableByScanFETDefaultOffset(t *testing.T) {
108 | offset, err := FindFirmwareEntryTableByScan(mockFetImage())
109 |
110 | assert.Nil(t, err)
111 | assert.Equal(t, FETDefaultOffset, offset)
112 | }
113 |
114 | func TestFindFirmwareEntryTableFETDefaultOffset(t *testing.T) {
115 | offset, err := FindFirmwareEntryTable(mockFetImage())
116 |
117 | assert.Nil(t, err)
118 | assert.Equal(t, FETDefaultOffset, offset)
119 | }
120 |
121 | func TestParseFirmwareEntryTable(t *testing.T) {
122 | entryTable, err := ParseFirmwareEntryTable(fetBytes, 0)
123 |
124 | expectedFet := testFet
125 | expectedFet.Location = 0
126 |
127 | assert.Nil(t, err)
128 | assert.Equal(t, expectedFet, *entryTable)
129 | }
130 |
131 | func TestParseFirmwareEntryTableShort(t *testing.T) {
132 | imageBytes := make([]byte, 500)
133 | copy(imageBytes[0:], fetXHCIBytes)
134 |
135 | entryTable, err := ParseFirmwareEntryTable(imageBytes, 0)
136 |
137 | expectedFet := testShortFet
138 | expectedFet.Location = 0
139 |
140 | assert.Nil(t, err)
141 | assert.Equal(t, expectedFet, *entryTable)
142 | }
143 |
144 | func TestParseFirmwareEntryTableAtAddress(t *testing.T) {
145 | baseImage := mockFetImage()
146 | entryTable, err := ParseFirmwareEntryTable(baseImage, FETDefaultOffset)
147 |
148 | assert.Nil(t, err)
149 | assert.Equal(t, testFet, *entryTable)
150 | }
151 |
152 | func TestParseFirmwareEntryTableFailToSmall(t *testing.T) {
153 | entryTable, err := ParseFirmwareEntryTable(fetBytes, FETDefaultOffset)
154 |
155 | assert.EqualError(t, err, "Could not find FirmwareEntryTable Signature: Not AMD Table Header: Address out of bounds")
156 | assert.Nil(t, entryTable)
157 | }
158 |
159 | func TestParseFirmwareEntryTableWithWrongSignature(t *testing.T) {
160 | wrongBytes := []byte{
161 | 0x12, 0x23, 0x34, 0x45,
162 | 0x67, 0x00, 0x00, 0x00,
163 | 0x00, 0x00, 0x00, 0x00,
164 | 0x00, 0x00, 0x00, 0x00,
165 | 0x00, 0x00, 0x00, 0x00,
166 | 0x00, 0x00, 0x00, 0x00,
167 | }
168 |
169 | entryTable, err := ParseFirmwareEntryTable(wrongBytes, 0)
170 |
171 | assert.EqualError(t, err, "Could not find FirmwareEntryTable Signature: Not AMD Table Header")
172 | assert.Nil(t, entryTable)
173 | }
174 |
175 | func TestFirmwareEntryTable_Write(t *testing.T) {
176 | imageBytes := make([]byte, 500)
177 | expectedBytes := make([]byte, 500)
178 |
179 | err := testFet.Write(imageBytes, 100)
180 |
181 | copy(expectedBytes[100:], fetBytes)
182 |
183 | assert.Nil(t, err)
184 | assert.Equal(t, imageBytes, expectedBytes)
185 | }
186 |
187 | func TestFirmwareEntryTable_WriteNILed(t *testing.T) {
188 | imageBytes := make([]byte, 500)
189 | expectedBytes := make([]byte, 500)
190 |
191 | nilFet := testFet
192 | nilFet.PSPDirBase = nil
193 | nilFet.NewPSPDirBase = nil
194 | nilFet.BHDDirBase = nil
195 | nilFet.NewBHDDirBase = nil
196 |
197 | err := testShortFet.Write(imageBytes, 100)
198 |
199 | copy(expectedBytes[100:], fetXHCIBytes[:0x10])
200 |
201 | assert.Nil(t, err)
202 | assert.Equal(t, expectedBytes, imageBytes)
203 | }
204 |
205 | func TestFirmwareEntryTable_WriteFailToSmall(t *testing.T) {
206 | imageBytes := make([]byte, FETDefaultOffset+5)
207 |
208 | err := testFet.Write(imageBytes, FETDefaultOffset)
209 |
210 | assert.EqualError(t, err, "BaseImage to small to insert FET")
211 | }
212 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/mimoja/amdfw
2 |
3 | go 1.13
4 |
5 | require (
6 | github.com/Mimoja/PSP-Entry-Types v0.0.0-20190620172056-b980f3fbafa7
7 | github.com/go-openapi/strfmt v0.19.0 // indirect
8 | github.com/jedib0t/go-pretty v4.2.1+incompatible
9 | github.com/mattn/go-runewidth v0.0.4 // indirect
10 | )
11 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/Mimoja/PSP-Entry-Types v0.0.0-20190620172056-b980f3fbafa7 h1:M9QDkfQ8oE94q0+odPUcw2u0F9cbTT7o9YStV2WragM=
2 | github.com/Mimoja/PSP-Entry-Types v0.0.0-20190620172056-b980f3fbafa7/go.mod h1:iZDm2Dh5T8SliuWA1nTbUfSAWTMWWn1fMVHR3CbkrpA=
3 | github.com/asaskevich/govalidator v0.0.0-20180720115003-f9ffefc3facf h1:eg0MeVzsP1G42dRafH3vf+al2vQIJU0YHX+1Tw87oco=
4 | github.com/asaskevich/govalidator v0.0.0-20180720115003-f9ffefc3facf/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY=
5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/globalsign/mgo v0.0.0-20180905125535-1ca0a4f7cbcb h1:D4uzjWwKYQ5XnAvUbuvHW93esHg7F8N/OYeBBcJoTr0=
7 | github.com/globalsign/mgo v0.0.0-20180905125535-1ca0a4f7cbcb/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q=
8 | github.com/go-openapi/errors v0.17.0 h1:g5DzIh94VpuR/dd6Ff8KqyHNnw7yBa2xSHIPPzjRDUo=
9 | github.com/go-openapi/errors v0.17.0/go.mod h1:LcZQpmvG4wyF5j4IhA73wkLFQg+QJXOQHVjmcZxhka0=
10 | github.com/go-openapi/strfmt v0.19.0 h1:0Dn9qy1G9+UJfRU7TR8bmdGxb4uifB7HNrJjOnV0yPk=
11 | github.com/go-openapi/strfmt v0.19.0/go.mod h1:+uW+93UVvGGq2qGaZxdDeJqSAqBqBdl+ZPMF/cC8nDY=
12 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
13 | github.com/jedib0t/go-pretty v4.2.1+incompatible h1:YgpgCwastS5GrAK9z7OEv6rsgolGjU6h1WT3MmM5Hp8=
14 | github.com/jedib0t/go-pretty v4.2.1+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
15 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
16 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
17 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
18 | github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329 h1:2gxZ0XQIU/5z3Z3bUBu+FXuk2pFbkN6tcwi/pjyaDic=
19 | github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
20 | github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
21 | github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
22 | github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
23 | github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
24 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
25 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
26 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
27 |
--------------------------------------------------------------------------------
/image.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type (
8 | Image struct {
9 | FET *FirmwareEntryTable
10 | FlashMapping *uint32
11 | Roms []*Rom
12 | }
13 | )
14 |
15 | func ParseImage(firmwareBytes []byte) (*Image, error) {
16 | image := Image{}
17 |
18 | fetOffset, err := FindFirmwareEntryTable(firmwareBytes)
19 | if err != nil {
20 | return nil, fmt.Errorf("Could not parse Image: %v", err)
21 | }
22 |
23 | fet, err := ParseFirmwareEntryTable(firmwareBytes, fetOffset)
24 | if err != nil {
25 | return nil, fmt.Errorf("Could not parse Image: %v", err)
26 | }
27 | image.FET = fet
28 |
29 | mapping, err := GetFlashMapping(firmwareBytes, fet)
30 | if err != nil {
31 | return nil, fmt.Errorf("Could not parse Image: %v", err)
32 | }
33 | image.FlashMapping = &mapping
34 |
35 | roms, errs := ParseRoms(firmwareBytes, fet, mapping)
36 | if len(errs) != 0 {
37 | err = fmt.Errorf("Errors parsing images %v", errs)
38 | } else {
39 | err = nil
40 | }
41 |
42 | image.Roms = roms
43 | return &image, err
44 | }
45 |
46 | func (image *Image) Write(baseImage []byte) ([]byte, error) {
47 | var err error
48 | if err = image.FET.Write(baseImage, image.FET.Location); err != nil {
49 | return nil, err
50 | }
51 |
52 | if image.FlashMapping != nil {
53 | for _, rom := range image.Roms {
54 | if err = rom.Write(baseImage, image.FET, *image.FlashMapping); err != nil {
55 | return nil, err
56 | }
57 |
58 | }
59 | }
60 | return baseImage, nil
61 | }
62 |
--------------------------------------------------------------------------------
/image_test.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "fmt"
5 | "github.com/stretchr/testify/assert"
6 | "testing"
7 | )
8 |
9 | var (
10 | testFlashMapping = DefaultFlashMapping
11 | testImage = Image{
12 | FET: &testFet,
13 | FlashMapping: &testFlashMapping,
14 | Roms: []*Rom{
15 | {
16 | Type: PSPRom,
17 | Directories: []*Directory{
18 | &testPSPMiniDirectory,
19 | },
20 | Raw: nil,
21 | },
22 | &testRawRom,
23 | },
24 | }
25 | )
26 |
27 | func mockImage() []byte {
28 | baseImage := mockFetImage()
29 | copy(baseImage[testPSPDirBase-DefaultFlashMapping:], testPSPMiniDirectoryBytes)
30 | copy(baseImage[testXHCRomBase-DefaultFlashMapping:], testRawRomBytes)
31 | return baseImage
32 | }
33 |
34 | func TestImage_Write(t *testing.T) {
35 | baseImage := make([]byte, testImage16MB)
36 |
37 | baseImage, err := testImage.Write(baseImage)
38 |
39 | assert.Nil(t, err)
40 |
41 | for pos, byteVal := range mockImage() {
42 | if baseImage[pos] != byteVal {
43 | assert.Equal(t, byteVal, baseImage[pos], fmt.Sprintf("Bytes not Equal at 0x%08X", pos))
44 | }
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/mapping.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | )
7 |
8 | const DefaultFlashMapping = uint32(0xFF000000)
9 |
10 | func GetFlashMapping(firmwareBytes []byte, fet *FirmwareEntryTable) (uint32, error) {
11 |
12 | type mappingMagic struct {
13 | addr *uint32
14 | magic []string
15 | }
16 |
17 | for _, s := range []mappingMagic{{
18 | addr: fet.PSPDirBase,
19 | magic: []string{PSPCOOCKIE, DUALPSPCOOCKIE},
20 | }, {
21 | addr: fet.NewPSPDirBase,
22 | magic: []string{PSPCOOCKIE, DUALPSPCOOCKIE},
23 | }, {
24 | addr: fet.BHDDirBase,
25 | magic: []string{BHDCOOCKIE},
26 | }, {
27 | addr: fet.BHDDirBase,
28 | magic: []string{BHDCOOCKIE},
29 | },
30 | } {
31 | for _, m := range s.magic {
32 |
33 | if s.addr != nil && *s.addr != 0 {
34 | mapping, err := testMapping(firmwareBytes, *s.addr, m)
35 | if err == nil {
36 | return mapping, nil
37 | }
38 | }
39 | }
40 | }
41 | return 0, fmt.Errorf("No valid mapping found!")
42 | }
43 |
44 | func testMapping(firmwareBytes []byte, address uint32, expected string) (uint32, error) {
45 |
46 | for _, mapping := range []uint32{
47 | DefaultFlashMapping + 0x000000, //16M
48 | DefaultFlashMapping + 0x800000, // 8M
49 | DefaultFlashMapping + 0xB00000, // 4M
50 | DefaultFlashMapping + 0xD00000, // 2M
51 | DefaultFlashMapping + 0xE00000, // 1M
52 | DefaultFlashMapping + 0xE80000, // 512K
53 | } {
54 |
55 | expectedBytes := []byte(expected)
56 | testAddr := address - mapping
57 | if int(testAddr) > len(firmwareBytes) {
58 | continue
59 | }
60 |
61 | if bytes.Equal(firmwareBytes[testAddr:testAddr+4], expectedBytes) {
62 | return mapping, nil
63 | }
64 | }
65 | return 0, fmt.Errorf("No Default Mapping fits")
66 | }
67 |
--------------------------------------------------------------------------------
/mapping_test.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "github.com/stretchr/testify/assert"
5 | "testing"
6 | )
7 |
8 | func mockPspHeaderImage() []byte {
9 |
10 | imageBytes := mockFetImage()
11 |
12 | // Copy $PSP Header
13 | copy(imageBytes[testPSPDirBase-DefaultFlashMapping:], PSPCOOCKIE)
14 | return imageBytes
15 | }
16 |
17 | func TestGetFlashMappingValid(t *testing.T) {
18 |
19 | mapping, err := GetFlashMapping(mockPspHeaderImage(), &testFet)
20 |
21 | assert.Nil(t, err)
22 | assert.Equal(t, DefaultFlashMapping, mapping)
23 | }
24 |
25 | func TestGetFlashMappingInvalid(t *testing.T) {
26 | empty := make([]byte, testImage16MB)
27 | mapping, err := GetFlashMapping(empty, &testFet)
28 |
29 | assert.EqualError(t, err, "No valid mapping found!")
30 | assert.Equal(t, uint32(0), mapping)
31 | }
32 |
--------------------------------------------------------------------------------
/rom.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | )
7 |
8 | const (
9 | IMCRom RomType = "IMC"
10 | GECRom RomType = "GEC"
11 | XHCIRom RomType = "XHCI"
12 | PSPRom RomType = "PSP"
13 | NewPSPRom RomType = "NEWPSP"
14 | BHDRom RomType = "BHD"
15 | NewBHDRom RomType = "NEWBDH"
16 | )
17 |
18 | type (
19 | RomType string
20 |
21 | Rom struct {
22 | Type RomType
23 | Directories []*Directory
24 | Raw []byte
25 | }
26 | )
27 |
28 | func ParseRoms(firmwareBytes []byte, table *FirmwareEntryTable, flashMapping uint32) ([]*Rom, []error) {
29 | var roms []*Rom
30 |
31 | var errors []error
32 | // Parsing ROMs without length is annoying. Not going to implement soon...
33 | //TODO IMC
34 | //TODO GEC
35 | //TODO XHCI
36 |
37 | // PSP
38 | rom, err := ParsePSPRom(firmwareBytes, table, flashMapping)
39 | if err != nil {
40 | errors = append(errors, fmt.Errorf("Could not parse psp rom: %v", err))
41 | }
42 | if rom != nil {
43 | roms = append(roms, rom)
44 | }
45 |
46 | // newPSP
47 | rom, err = ParseNewPSPRom(firmwareBytes, table, flashMapping)
48 | if err != nil {
49 | errors = append(errors, fmt.Errorf("Could not parse newpsp rom: %v", err))
50 | }
51 | if rom != nil {
52 | roms = append(roms, rom)
53 | }
54 |
55 | // BHD
56 | rom, err = ParseBHDRom(firmwareBytes, table, flashMapping)
57 | if err != nil {
58 | errors = append(errors, fmt.Errorf("Could not parse bhd rom: %v", err))
59 | }
60 | if rom != nil {
61 | roms = append(roms, rom)
62 | }
63 |
64 | // newBHD
65 | rom, err = ParseNewBHDRom(firmwareBytes, table, flashMapping)
66 | if err != nil {
67 | errors = append(errors, fmt.Errorf("Could not parse new bhd rom: %v", err))
68 | }
69 | if rom != nil {
70 | roms = append(roms, rom)
71 | }
72 |
73 | return roms, errors
74 | }
75 |
76 | func ParsePSPRom(firmwareBytes []byte, table *FirmwareEntryTable, flashMapping uint32) (*Rom, error) {
77 | return parseDirectoryRom(firmwareBytes, table.PSPDirBase, flashMapping, PSPRom)
78 | }
79 |
80 | func ParseNewPSPRom(firmwareBytes []byte, table *FirmwareEntryTable, flashMapping uint32) (*Rom, error) {
81 | return parseDirectoryRom(firmwareBytes, table.NewPSPDirBase, flashMapping, NewPSPRom)
82 | }
83 |
84 | func ParseBHDRom(firmwareBytes []byte, table *FirmwareEntryTable, flashMapping uint32) (*Rom, error) {
85 | return parseDirectoryRom(firmwareBytes, table.BHDDirBase, flashMapping, BHDRom)
86 | }
87 |
88 | func ParseNewBHDRom(firmwareBytes []byte, table *FirmwareEntryTable, flashMapping uint32) (*Rom, error) {
89 | return parseDirectoryRom(firmwareBytes, table.NewBHDDirBase, flashMapping, NewBHDRom)
90 | }
91 |
92 | func parseDirectoryRom(firmwareBytes []byte, address *uint32, flashMapping uint32, romType RomType) (*Rom, error) {
93 | rom := Rom{
94 | Type: romType,
95 | }
96 |
97 | if address == nil {
98 | return nil, fmt.Errorf("No %s offset available", romType)
99 | }
100 |
101 | directory, err := ParseDirectory(firmwareBytes, *address, flashMapping)
102 |
103 | if err != nil {
104 | return nil, fmt.Errorf("Could not read %s Rom: %v", romType, err)
105 | }
106 |
107 | rom.Directories = append(rom.Directories, directory)
108 | others, err := recursiveDirectories(firmwareBytes, directory, flashMapping)
109 |
110 | rom.Directories = append(rom.Directories, others...)
111 | return &rom, err
112 |
113 | }
114 |
115 | func recursiveDirectories(firmwareBytes []byte, directory *Directory, flashMapping uint32) ([]*Directory, error) {
116 | var directories []*Directory
117 | for _, entry := range directory.Entries {
118 | if entry.DirectoryEntry.Type == 0x40 ||
119 | entry.DirectoryEntry.Type == 0x70 ||
120 | bytes.Equal(directory.Header.Cookie[:], []byte(DUALPSPCOOCKIE)) {
121 |
122 | newDirectory, err := ParseDirectory(firmwareBytes, entry.DirectoryEntry.Location, flashMapping)
123 |
124 | if err != nil {
125 | return directories, fmt.Errorf("Could not read Directory: %v", err)
126 | }
127 |
128 | directories = append(directories, newDirectory)
129 | others, err := recursiveDirectories(firmwareBytes, newDirectory, flashMapping)
130 | if err != nil {
131 | return directories, fmt.Errorf("Could not read Directory: %v", err)
132 | }
133 | directories = append(directories, others...)
134 | }
135 | }
136 | return directories, nil
137 | }
138 |
139 | func GetAddressFromTable(romType RomType, table *FirmwareEntryTable) (uint32, error) {
140 | switch romType {
141 | case PSPRom:
142 | return *table.PSPDirBase, nil
143 | case NewPSPRom:
144 | return *table.NewPSPDirBase, nil
145 | case BHDRom:
146 | return *table.BHDDirBase, nil
147 | case NewBHDRom:
148 | return *table.NewBHDDirBase, nil
149 | case GECRom:
150 | return *table.GecRomBase, nil
151 | case IMCRom:
152 | return *table.ImcRomBase, nil
153 | case XHCIRom:
154 | return *table.XHCRomBase, nil
155 | default:
156 | return 0, fmt.Errorf("Cannot get Address: Unknown Type")
157 | }
158 |
159 | }
160 |
161 | func (rom Rom) Write(baseImage []byte, table *FirmwareEntryTable, flashMapping uint32) error {
162 | var err error
163 | if rom.Raw != nil {
164 | address, err := GetAddressFromTable(rom.Type, table)
165 |
166 | if err != nil {
167 | return fmt.Errorf("Cannot Write: Unknown Type")
168 | }
169 |
170 | address = address &^ flashMapping
171 |
172 | if int(address)+len(rom.Raw) > len(baseImage) {
173 | return fmt.Errorf("Cannot write Rom: Invalid address in FET")
174 | }
175 |
176 | copy(baseImage[address:], rom.Raw)
177 | } else if rom.Directories != nil {
178 | for _, directory := range rom.Directories {
179 | err = directory.Write(baseImage, flashMapping)
180 | if err != nil {
181 | return fmt.Errorf("Cannot Write Rom: %v", err)
182 | }
183 | }
184 | }
185 | return nil
186 | }
187 |
--------------------------------------------------------------------------------
/rom_test.go:
--------------------------------------------------------------------------------
1 | package amdfw
2 |
3 | import (
4 | "github.com/stretchr/testify/assert"
5 | "testing"
6 | )
7 |
8 | var (
9 | testRawRomBytes = []byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7}
10 | testRawRom = Rom{
11 | Type: XHCIRom,
12 | Raw: testRawRomBytes,
13 | }
14 | testDirectoryRom = Rom{
15 | Type: PSPRom,
16 | Directories: []*Directory{
17 | &testPSPDirectory,
18 | },
19 | }
20 | )
21 |
22 | func mockRawRom(address uint32) []byte {
23 | baseImage := make([]byte, testImage16MB)
24 |
25 | copy(baseImage[address:], testRawRomBytes)
26 | return baseImage
27 | }
28 |
29 | func TestRom_WriteRawToSmall(t *testing.T) {
30 | baseImage := make([]byte, testXHCRomBase-DefaultFlashMapping)
31 | untouched := make([]byte, testXHCRomBase-DefaultFlashMapping)
32 |
33 | err := testRawRom.Write(baseImage, &testFet, DefaultFlashMapping)
34 |
35 | assert.EqualError(t, err, "Cannot write Rom: Invalid address in FET")
36 | assert.Equal(t, baseImage, untouched)
37 | }
38 |
39 | func TestRom_WriteRaw(t *testing.T) {
40 | baseImage := make([]byte, testImage16MB)
41 |
42 | expectedImage := mockRawRom(testXHCRomBase - DefaultFlashMapping)
43 |
44 | err := testRawRom.Write(baseImage, &testFet, DefaultFlashMapping)
45 |
46 | assert.Nil(t, err)
47 | assert.Equal(t, expectedImage, baseImage)
48 | }
49 |
50 | func TestRom_WriteDir(t *testing.T) {
51 | baseImage := make([]byte, testImage16MB)
52 | expectedImage := make([]byte, testImage16MB)
53 | testPSPDirectory.Write(expectedImage, testPSPDirBase)
54 |
55 | err := testDirectoryRom.Write(baseImage, &testFet, DefaultFlashMapping)
56 |
57 | assert.Nil(t, err)
58 | assert.Equal(t, expectedImage, baseImage)
59 | }
60 |
61 | func TestRom_WriteDirFailed(t *testing.T) {
62 | baseImage := make([]byte, testPSPDirBase-5-DefaultFlashMapping)
63 | untouchedImage := make([]byte, testPSPDirBase-5-DefaultFlashMapping)
64 |
65 | err := testDirectoryRom.Write(baseImage, &testFet, DefaultFlashMapping)
66 |
67 | assert.EqualError(t, err, "Cannot Write Rom: BaseImage to small to insert Directory")
68 | assert.Equal(t, untouchedImage, baseImage)
69 | }
70 |
71 | func TestGetAddressFromTable(t *testing.T) {
72 | addressFromTable, err := GetAddressFromTable(PSPRom, &testFet)
73 |
74 | assert.Nil(t, err)
75 | assert.Equal(t, testPSPDirBase, addressFromTable)
76 | }
77 |
78 | func TestGetAddressFromTableUnknown(t *testing.T) {
79 |
80 | addressFromTable, err := GetAddressFromTable("FooBar", &testFet)
81 |
82 | assert.EqualError(t, err, "Cannot get Address: Unknown Type")
83 | assert.Equal(t, addressFromTable, uint32(0))
84 | }
85 |
86 | func TestParseRomsRecursiv(t *testing.T) {
87 | imageBytes := make([]byte, testImage16MB)
88 | copy(imageBytes[testPSPDirBase-DefaultFlashMapping:], test2PSPDirectoryBytes)
89 |
90 | for _, entry := range test2PSPDirectory.Entries {
91 |
92 | copy(imageBytes[entry.DirectoryEntry.Location&^DefaultFlashMapping:], testPSPMiniDirectoryBytes)
93 | }
94 |
95 | directories, err := recursiveDirectories(imageBytes, &test2PSPDirectory, DefaultFlashMapping)
96 |
97 | assert.Nil(t, err)
98 | assert.Equal(t, len(directories), 4)
99 |
100 | for _, dir := range directories {
101 | assert.Equal(t, testPSPMiniDirectory.Header, dir.Header)
102 | for i, _ := range dir.Entries {
103 | assert.Equal(t, testPSPMiniDirectory.Entries[i].DirectoryEntry, dir.Entries[i].DirectoryEntry)
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------