initial commit

This commit is contained in:
enderghast13 2025-04-27 18:47:47 -07:00
commit b4a39e9a51
16 changed files with 2206 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.vscode/
.venv/
__pycache__/
*.nds
*.sav

360
COPYING.md Normal file
View File

@ -0,0 +1,360 @@
# GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
The licenses for most software are designed to take away your freedom
to share and change it. By contrast, the GNU General Public License is
intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on,
we want its recipients to know that what they have is not the
original, so that any problems introduced by others will not reflect
on the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at
all.
The precise terms and conditions for copying, distribution and
modification follow.
## TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
**0.** This License applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work
based on the Program" means either the Program or any derivative work
under copyright law: that is to say, a work containing the Program or
a portion of it, either verbatim or with modifications and/or
translated into another language. (Hereinafter, translation is
included without limitation in the term "modification".) Each licensee
is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the Program
(independent of having been made by running the Program). Whether that
is true depends on what the Program does.
**1.** You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a
fee.
**2.** You may modify your copy or copies of the Program or any
portion of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
**a)** You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
**b)** You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any part
thereof, to be licensed as a whole at no charge to all third parties
under the terms of this License.
**c)** If the modified program normally reads commands interactively
when run, you must cause it, when started running for such interactive
use in the most ordinary way, to print or display an announcement
including an appropriate copyright notice and a notice that there is
no warranty (or else, saying that you provide a warranty) and that
users may redistribute the program under these conditions, and telling
the user how to view a copy of this License. (Exception: if the
Program itself is interactive but does not normally print such an
announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
**3.** You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
**a)** Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections 1
and 2 above on a medium customarily used for software interchange; or,
**b)** Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your cost of
physically performing source distribution, a complete machine-readable
copy of the corresponding source code, to be distributed under the
terms of Sections 1 and 2 above on a medium customarily used for
software interchange; or,
**c)** Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is allowed
only for noncommercial distribution and only if you received the
program in object code or executable form with such an offer, in
accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
**4.** You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt otherwise
to copy, modify, sublicense or distribute the Program is void, and
will automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
**5.** You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
**6.** Each time you redistribute the Program (or any work based on
the Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
**7.** If, as a consequence of a court judgment or allegation of
patent infringement or for any other reason (not limited to patent
issues), conditions are imposed on you (whether by court order,
agreement or otherwise) that contradict the conditions of this
License, they do not excuse you from the conditions of this License.
If you cannot distribute so as to satisfy simultaneously your
obligations under this License and any other pertinent obligations,
then as a consequence you may not distribute the Program at all. For
example, if a patent license would not permit royalty-free
redistribution of the Program by all those who receive copies directly
or indirectly through you, then the only way you could satisfy both it
and this License would be to refrain entirely from distribution of the
Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
**8.** If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
**9.** The Free Software Foundation may publish revised and/or new
versions of the General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Program does not specify a
version number of this License, you may choose any version ever
published by the Free Software Foundation.
**10.** If you wish to incorporate parts of the Program into other
free programs whose distribution conditions are different, write to
the author to ask for permission. For software which is copyrighted by
the Free Software Foundation, write to the Free Software Foundation;
we sometimes make exceptions for this. Our decision will be guided by
the two goals of preserving the free status of all derivatives of our
free software and of promoting the sharing and reuse of software
generally.
**NO WARRANTY**
**11.** BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
**12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than \`show w' and
\`show c'; they could even be mouse-clicks or menu items--whatever
suits your program.
You should also get your employer (if you work as a programmer) or
your school, if any, to sign a "copyright disclaimer" for the program,
if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Moe Ghoul, 1 April 1989
Moe Ghoul, President of Vice
This General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library,
you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
[GNU Lesser General Public
License](https://www.gnu.org/licenses/lgpl.html) instead of this
License.

133
DownloadStation/DemoMenu.py Normal file
View File

@ -0,0 +1,133 @@
from collections.abc import MutableSequence
u32_le = lambda i: i.to_bytes(length=4, byteorder='little')
class Rating:
EC = 0
E = 1
E10 = 2
T = 3
M = 4
AO = 5
RP = 6
class GuideMode:
N = 0x11 # nothing
B = 0x13 # buttons only
T = 0x15 # touch only
BT = 0x17 # buttons + touch
class Button:
START = 0
SELECT = 1
A = 2
B = 3
X = 4
Y = 5
L = 6
R = 7
DPAD = 8
class DemoMenu(MutableSequence):
def __init__(self):
self.entries: list[DemoMenu.DemoMenuEntry] = []
def encode(self) -> bytes:
return b''.join([
u32_le(len(self.entries)),
b''.join(entry.encode() for entry in self.entries),
u32_le(0)
])
__bytes__ = encode
def __getitem__(self, index):
return self.entries[index]
def __setitem__(self, index, value):
self.entries[index] = value
def __delitem__(self, index):
del self.entries[index]
def __len__(self):
return len(self.entries)
def insert(self, index, value):
self.entries.insert(index, value)
class DemoMenuEntry:
def __init__(self, data: bytes|None = None):
if data is None:
self.banner_image = bytes(0x200)
self.banner_palette = bytes(0x20)
self.banner_text = [''] * 2
self.rating = Rating.E
self.guide_mode = GuideMode.N
self.buttons_text = [''] * 9
self.unknown_text = [''] * 3
self.touch_text = [''] * 2
self.padding = bytes(0x40)
self.internal_name = ''
return
self.banner_image = data[:0x200]
self.banner_palette = data[0x200:0x220]
self.banner_text = [
data[i:i+0x80].decode('latin-1').rstrip('\0')
for i in range(0x220, 0x320, 0x80)
]
self.rating = data[0x320]
self.guide_mode = data[0x321]
self.buttons_text = [
data[i:i+0x20].decode('latin-1').rstrip('\0')
for i in range(0x322, 0x442, 0x20)
]
self.unknown_text = [
data[i:i+0x20].decode('latin-1').rstrip('\0')
for i in range(0x442, 0x4a2, 0x20)
]
self.touch_text = [
data[i:i+0x20].decode('latin-1').rstrip('\0')
for i in range(0x4a2, 0x4e2, 0x20)
]
self.padding = data[0x4e2:0x522]
self.internal_name = data[0x522:0x52c].decode('latin-1').rstrip('\0')
def encode(self) -> bytes:
return b''.join([
self.banner_image,
self.banner_palette,
b''.join(
text.ljust(0x80, '\0').encode('latin-1')
for text in self.banner_text
), self.rating.to_bytes(1),
self.guide_mode.to_bytes(1),
b''.join(
text.ljust(0x20, '\0').encode('latin-1')
for text in self.buttons_text
), b''.join(
text.ljust(0x20, '\0').encode('latin-1')
for text in self.unknown_text
), b''.join(
text.ljust(0x20, '\0').encode('latin-1')
for text in self.touch_text
), self.padding,
self.internal_name.ljust(0xa, '\0').encode('latin-1')
])
__bytes__ = encode
def __len__(self):
return 0x52c

View File

42
NDSCard/CRC16.py Normal file
View File

@ -0,0 +1,42 @@
crc16_table = (
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
)
def crc16(data: bytes, start: int = 0, length: int|None = None) -> int:
if length is None:
length = len(data) - start
result = 0xffff
for i in range(start, start + length):
result = (result >> 8) ^ crc16_table[(result ^ data[i]) & 0xff]
return result

742
NDSCard/NDSCard.py Normal file
View File

@ -0,0 +1,742 @@
import os
from io import BytesIO, BufferedIOBase
from typing import overload, BinaryIO
from collections.abc import MutableSequence
from .Utils import uint_le, u8_le, u16_le, u32_le, align
from .CRC16 import crc16
from .NitroFS import FileAllocationEntry, EntryNameTableEndOfDirectoryEntry
from .NitroFS import EntryNameTableDirectoryEntry, DirectoryTableEntry
from .NitroFS import EntryNameTableEntry, EntryNameTableFileEntry
class NDSCard:
def __init__(self, data: str|int|bytes|BinaryIO|None = None):
"""Read and parse a Nintendo DS ROM. If `data` is an open file object or file descriptor,
this does not close it.
"""
if data is None:
self.header = NDSCardHeader()
self.main_rom = b''
self.sub_rom = b''
self.fnt = NDSCardFNT()
self.main_ovt = NDSCardOVT()
self.sub_ovt = NDSCardOVT()
self.fat = NDSCardFAT()
self.file_data = []
return
if isinstance(data, bytes):
data = BytesIO(data)
elif isinstance(data, str): # file path
with open(data, 'rb') as fp:
data = BytesIO(fp.read())
elif isinstance(data, BufferedIOBase): # open file object
initial_fp = data
initial_pos = data.tell()
data = BytesIO(initial_fp.read())
initial_fp.seek(initial_pos)
del initial_fp, initial_pos
elif isinstance(data, int): # open file descriptor
fp = os.fdopen(data, 'rb')
initial_pos = fp.tell()
data = BytesIO(fp.read())
fp.seek(initial_pos)
del initial_pos
total_rom_size = data.seek(0, os.SEEK_END)
data.seek(0)
length = len(NDSCardHeader())
self.header = NDSCardHeader(data.read(length))
data.seek(self.header.main_rom_offset)
self.main_rom = data.read(self.header.main_size)
if uint_le(data.read(4)) == 0xDEC00621: # Nitro footer
data.seek(-4, os.SEEK_CUR)
length = len(NitroFooter())
self.static_footer = NitroFooter(data.read(length))
data.seek(self.header.sub_rom_offset)
self.sub_rom = data.read(self.header.sub_size)
data.seek(self.header.fnt_offset)
self.fnt = NDSCardFNT(data.read(self.header.fnt_size))
data.seek(self.header.main_ovt_offset)
self.main_ovt = NDSCardOVT(data.read(self.header.main_ovt_size))
data.seek(self.header.sub_ovt_offset)
self.sub_ovt = NDSCardOVT(data.read(self.header.sub_ovt_size))
data.seek(self.header.fat_offset)
self.fat = NDSCardFAT(data.read(self.header.fat_size))
if self.header.banner_offset != 0:
data.seek(self.header.banner_offset)
length = len(NDSCardBanner())
self.banner = NDSCardBanner(data.read(length))
self.file_data = []
for entry in self.fat:
data.seek(entry.start)
self.file_data.append(data.read(entry.end - entry.start))
# RSA signature
if self.header.rom_size+0x88 <= total_rom_size:
data.seek(self.header.rom_size)
rsa_sig = data.read(0x88)
# check whether it's just padding
for byte in rsa_sig:
if byte not in (0xff, 0):
self.rsa_sig = rsa_sig
break
def encode(self, multiboot: bool = False) -> bytes:
out = BytesIO()
# skip the header, and write it afterwards
self.header.header_size = 0x4000
out.write(bytes(0x4000))
# ARM9 ROM
self.header.main_rom_offset = out.tell()
self.header.main_size = len(self.main_rom)
out.write(self.main_rom)
# static footer
try:
out.write(self.static_footer.encode())
except AttributeError:
pass
# main OVT
if self.main_ovt:
# alignment
pos = out.tell()
out.write(bytes(align(pos, 0x200) - pos))
self.header.main_ovt_offset = out.tell()
length = len(NDSCardOVT.OverlayTableEntry())
self.header.main_ovt_size = len(self.main_ovt) * length
out.write(self.main_ovt.encode())
for overlay in self.main_ovt:
pos = out.tell()
out.write(bytes(align(pos, 0x200) - pos))
self.fat[overlay.file_id].start = out.tell()
self.fat[overlay.file_id].end = out.tell() + len(self.file_data[overlay.file_id])
out.write(self.file_data[overlay.file_id])
else:
self.header.main_ovt_offset = 0
self.header.main_ovt_size = 0
pos = out.tell()
out.write(b'\xff' * (align(pos, 0x200) - pos))
# ARM7 ROM
self.header.sub_rom_offset = out.tell()
self.header.sub_size = len(self.sub_rom)
out.write(self.sub_rom)
# sub OVT
if self.sub_ovt:
pos = out.tell()
out.write(bytes(align(pos, 0x200) - pos))
self.header.sub_ovt_offset = out.tell()
length = len(NDSCardOVT.OverlayTableEntry())
self.header.sub_ovt_size = len(self.sub_ovt) * length
out.write(self.sub_ovt.encode())
for overlay in self.sub_ovt:
pos = out.tell()
out.write(bytes(align(pos, 0x200) - pos))
self.fat[overlay.file_id].start = out.tell()
self.fat[overlay.file_id].end = out.tell() + len(self.file_data[overlay.file_id])
out.write(self.file_data[overlay.file_id])
else:
self.header.sub_ovt_offset = 0
self.header.sub_ovt_size = 0
pos = out.tell()
out.write(b'\xff' * (align(pos, 0x200) - pos))
# FNT
self.header.fnt_offset = out.tell()
out.write(self.fnt.encode())
self.header.fnt_size = out.tell() - self.header.fnt_offset
pos = out.tell()
out.write(b'\xff' * (align(pos, 0x200) - pos))
# FAT
self.header.fat_offset = out.tell()
self.header.fat_size = len(self.fat) * 8
# skip the FAT, and write it after writing file data
out.write(bytes(self.header.fat_size))
# banner
if hasattr(self, 'banner'):
pos = out.tell()
out.write(b'\xff' * (align(pos, 0x200) - pos))
self.header.banner_offset = out.tell()
out.write(self.banner.encode())
else:
self.header.banner_offset = 0
# files
for i in range(
self.header.main_ovt_size//32 + self.header.sub_ovt_size//32,
len(self.file_data)
):
pos = out.tell()
out.write(b'\xff' * (align(pos, 0x200) - pos))
self.fat[i].start = out.tell()
self.fat[i].end = out.tell() + len(self.file_data[i])
out.write(self.file_data[i])
pos = out.tell()
self.header.rom_size = pos
out.write(bytes(align(pos, 4) - pos))
# device size
if not multiboot:
capacity_size = self.header.rom_size
capacity_size |= capacity_size >> 16
capacity_size |= capacity_size >> 8
capacity_size |= capacity_size >> 4
capacity_size |= capacity_size >> 2
capacity_size |= capacity_size >> 1
capacity_size += 1
if capacity_size <= 0x20000:
capacity_size = 0x20000
capacity = -18
while capacity_size != 0:
capacity_size >>= 1
capacity += 1
self.header.device_size = 0 if capacity < 0 else capacity
else:
self.header.device_size = 0x0b
# RSA
try:
out.write(self.rsa_sig)
except AttributeError:
pass
# write FAT
out.seek(self.header.fat_offset)
out.write(self.fat.encode())
# write header
out.seek(0)
out.write(self.header.encode())
out.seek(0)
return out.read()
__bytes__ = encode
def __len__(self):
return len(self.encode())
class NDSCardHeader:
def __init__(self, data: bytes|None = None):
if data is None:
return
self.game_title = data[:0xc].decode('ascii', errors='surrogateescape').rstrip('\0')
self.game_code = data[0xc:0x10].decode('ascii', errors='surrogateescape').rstrip('\0')
self.maker_code = data[0x10:0x12].decode('ascii', errors='surrogateescape').rstrip('\0')
self.product_id = data[0x12:0x13]
self.device_type = data[0x13:0x14]
self.device_size = data[0x14]
self.reserved_a = data[0x15:0x1d]
self.region = data[0x1d:0x1e]
self.game_version = data[0x1e]
self.property = data[0x1f:0x20]
self.main_rom_offset = uint_le(data[0x20:0x24])
self.main_entry_address = uint_le(data[0x24:0x28])
self.main_ram_address = uint_le(data[0x28:0x2c])
self.main_size = uint_le(data[0x2c:0x30])
self.sub_rom_offset = uint_le(data[0x30:0x34])
self.sub_entry_address = uint_le(data[0x34:0x38])
self.sub_ram_address = uint_le(data[0x38:0x3c])
self.sub_size = uint_le(data[0x3c:0x40])
self.fnt_offset = uint_le(data[0x40:0x44])
self.fnt_size = uint_le(data[0x44:0x48])
self.fat_offset = uint_le(data[0x48:0x4c])
self.fat_size = uint_le(data[0x4c:0x50])
self.main_ovt_offset = uint_le(data[0x50:0x54])
self.main_ovt_size = uint_le(data[0x54:0x58])
self.sub_ovt_offset = uint_le(data[0x58:0x5c])
self.sub_ovt_size = uint_le(data[0x5c:0x60])
self.cmd_settings = data[0x60:0x64]
self.key1_cmd_settings = data[0x64:0x68]
self.banner_offset = uint_le(data[0x68:0x6c])
self.secure_crc = uint_le(data[0x6c:0x6e])
self.secure_delay = uint_le(data[0x6e:0x70])
self.main_autoload_done = uint_le(data[0x70:0x74])
self.sub_autoload_done = uint_le(data[0x74:0x78])
self.secure_disable = data[0x78:0x80]
self.rom_size = uint_le(data[0x80:0x84])
self.header_size = uint_le(data[0x84:0x88])
self.reserved_b = data[0x88:0x94]
self.nand_rom_offset = uint_le(data[0x94:0x96])
self.nand_rw_offset = uint_le(data[0x96:0x98])
self.reserved_c = data[0x98:0xc0]
self.logo_data = data[0xc0:0x15c]
self.logo_crc = uint_le(data[0x15c:0x15e])
self.header_crc = uint_le(data[0x15e:0x160])
def encode(self) -> bytes:
self.logo_crc = crc16(self.logo_data)
header_data = b''.join([
self.game_title.ljust(0xc, '\0').encode('ascii', errors='surrogateescape'),
self.game_code.ljust(4, '\0').encode('ascii', errors='surrogateescape'),
self.maker_code.ljust(2, '\0').encode('ascii', errors='surrogateescape'),
self.product_id,
self.device_type,
u8_le(self.device_size),
self.reserved_a,
self.region,
u8_le(self.game_version),
self.property,
u32_le(self.main_rom_offset),
u32_le(self.main_entry_address),
u32_le(self.main_ram_address),
u32_le(self.main_size),
u32_le(self.sub_rom_offset),
u32_le(self.sub_entry_address),
u32_le(self.sub_ram_address),
u32_le(self.sub_size),
u32_le(self.fnt_offset),
u32_le(self.fnt_size),
u32_le(self.fat_offset),
u32_le(self.fat_size),
u32_le(self.main_ovt_offset),
u32_le(self.main_ovt_size),
u32_le(self.sub_ovt_offset),
u32_le(self.sub_ovt_size),
self.cmd_settings,
self.key1_cmd_settings,
u32_le(self.banner_offset),
u16_le(self.secure_crc),
u16_le(self.secure_delay),
u32_le(self.main_autoload_done),
u32_le(self.sub_autoload_done),
self.secure_disable,
u32_le(self.rom_size),
u32_le(self.header_size),
self.reserved_b,
u16_le(self.nand_rom_offset),
u16_le(self.nand_rw_offset),
self.reserved_c,
self.logo_data,
u16_le(self.logo_crc)
])
self.header_crc = crc16(header_data)
return b''.join([
header_data,
u16_le(self.header_crc),
bytes(0x1000 - 0x160) # padding
])
__bytes__ = encode
def __len__(self):
return 0x1000
class NitroFooter:
def __init__(self, data: bytes|None = None):
if data is None:
self.nitro_code = 0
self.module_params_offset = 0
self.unknown = 0
return
self.nitro_code = uint_le(data[:4])
self.module_params_offset = uint_le(data[4:8])
self.unknown = uint_le(data[8:12])
def encode(self) -> bytes:
return b''.join([
u32_le(self.nitro_code),
u32_le(self.module_params_offset),
u32_le(self.unknown)
])
__bytes__ = encode
def __len__(self):
return 12
class NDSCardFNT:
def __init__(self, data: bytes|None = None):
if data is None:
self.directory_table = NDSCardFNT.DirectoryTable()
self.entry_name_table = NDSCardFNT.EntryNameTable()
return
num_dirs = uint_le(data[6:8])
length = len(DirectoryTableEntry())
self.directory_table = NDSCardFNT.DirectoryTable(data[:num_dirs*length])
ent_offset = num_dirs * len(DirectoryTableEntry())
self.entry_name_table = NDSCardFNT.EntryNameTable(data[ent_offset:], num_dirs)
def encode(self) -> bytes:
return b''.join([self.directory_table.encode(), self.entry_name_table.encode()])
__bytes__ = encode
def __len__(self):
return len(self.encode())
class DirectoryTable(MutableSequence):
def __init__(self, data: bytes|None = None):
self.entries: list[DirectoryTableEntry] = []
if data is None:
return
length = len(DirectoryTableEntry())
self.entries.append(DirectoryTableEntry(data[:length]))
# the parent ID of the first directory table entry is
# the total number of directories, including itself
num_dirs = self.entries[0].parent_id
for i in range(1, num_dirs):
entry_data = data[i*length : (i*length)+length]
self.entries.append(DirectoryTableEntry(entry_data))
def encode(self) -> bytes:
return b''.join(entry.encode() for entry in self.entries)
__bytes__ = encode
def __getitem__(self, index):
return self.entries[index]
def __setitem__(self, index, value):
self.entries[index] = value
def __delitem__(self, index):
del self.entries[index]
def __len__(self):
return len(self.entries)
def insert(self, index, value):
self.entries.insert(index, value)
class EntryNameTable(MutableSequence):
@overload
def __init__(self, data: bytes, num_dirs: int, /):
...
@overload
def __init__(self, data: None = None, /):
...
def __init__(self, *args):
self.entries: list[list[EntryNameTableEntry]] = []
if not args or args[0] is None:
return
data: bytes = args[0]
num_dirs: int = args[1]
offset = 0
isdir = 0x80
end_entries = 0
entries_in_dir = []
while end_entries < num_dirs:
entry_name_length = data[offset]
if entry_name_length == 0: # end entry
entries_in_dir.append(EntryNameTableEndOfDirectoryEntry())
self.entries.append(entries_in_dir)
entries_in_dir = []
end_entries += 1
offset += 1
elif entry_name_length < isdir: # file entry
entries_in_dir.append(
EntryNameTableFileEntry(data[offset : offset+entry_name_length+1])
)
offset += entry_name_length + 1
else: # directory entry
entries_in_dir.append(EntryNameTableDirectoryEntry(
data[offset : offset+(entry_name_length ^ isdir)+3]
))
offset += (entry_name_length ^ isdir) + 3
def encode(self) -> bytes:
return b''.join(
entry.encode()
for entries in self.entries
for entry in entries
)
__bytes__ = encode
def __getitem__(self, index):
return self.entries[index]
def __setitem__(self, index, value):
self.entries[index] = value
def __delitem__(self, index):
del self.entries[index]
def __len__(self):
return len(self.entries)
def insert(self, index, value):
self.entries.insert(index, value)
class NDSCardOVT(MutableSequence):
def __init__(self, data: bytes|None = None):
self.entries: list[NDSCardOVT.OverlayTableEntry] = []
if data is None:
return
length = len(NDSCardOVT.OverlayTableEntry())
for i in range(len(data) // length):
self.entries.append(data[i*length : i*length+length])
def encode(self) -> bytes:
return b''.join(entry.encode() for entry in self.entries)
__bytes__ = encode
def __getitem__(self, index):
return self.entries[index]
def __setitem__(self, index, value):
self.entries[index] = value
def __delitem__(self, index):
del self.entries[index]
def __len__(self):
return len(self.entries)
def __bool__(self):
return bool(self.entries)
def insert(self, index, value):
self.entries.insert(index, value)
class OverlayTableEntry:
def __init__(self, data: bytes|None = None):
if data is None:
self.id = 0
self.ram_address = 0
self.ram_size = 0
self.bss_size = 0
self.static_init_start = 0
self.static_init_end = 0
self.file_id = 0
self.flags = NDSCardOVT.OverlayTableEntry.Flags()
return
self.id = uint_le(data[:0x4])
self.ram_address = uint_le(data[0x4:0x8])
self.ram_size = uint_le(data[0x8:0xc])
self.bss_size = uint_le(data[0xc:0x10])
self.static_init_start = uint_le(data[0x10:0x14])
self.static_init_end = uint_le(data[0x14:0x18])
self.file_id = uint_le(data[0x18:0x1c])
self.flags = NDSCardOVT.OverlayTableEntry.Flags(data[0x1c:0x20])
def encode(self) -> bytes:
return b''.join([
u32_le(self.id),
u32_le(self.ram_address),
u32_le(self.ram_size),
u32_le(self.bss_size),
u32_le(self.static_init_start),
u32_le(self.static_init_end),
u32_le(self.file_id),
self.flags.encode()
])
__bytes__ = encode
def __len__(self):
return 32
class Flags:
def __init__(self, data: bytes|None = None):
if data is None:
self.compressed = 0
self.authentication_code = 0
return
data = uint_le(data[:4])
self.compressed = data & 0x00ffffff
self.authentication_code = (data >> 24) & 0xff
def encode(self) -> bytes:
return u32_le(
0
| (self.compressed & 0x00ffffff)
| ((self.authentication_code & 0xff) << 24)
)
__bytes__ = encode
class NDSCardFAT(MutableSequence):
def __init__(self, data: bytes|None = None):
self.entries: list[FileAllocationEntry] = []
if data is None:
return
length = len(FileAllocationEntry())
self.entries.extend(
FileAllocationEntry(data[i : i+length])
for i in range(0, len(data), length)
)
def encode(self) -> bytes:
return b''.join(entry.encode() for entry in self.entries)
__bytes__ = encode
def __getitem__(self, index):
return self.entries[index]
def __setitem__(self, index, value):
self.entries[index] = value
def __delitem__(self, index):
del self.entries[index]
def __len__(self):
return len(self.entries)
def __bool__(self):
return bool(self.entries)
def insert(self, index, value):
self.entries.insert(index, value)
class NDSCardBanner:
def __init__(self, data: bytes|None = None):
if data is None:
self.header = NDSCardBanner.BannerHeader()
self.banner = NDSCardBanner.BannerV1()
return
header_length = len(NDSCardBanner.BannerHeader())
banner_length = len(NDSCardBanner.BannerV1())
self.header = NDSCardBanner.BannerHeader(data[:header_length])
self.banner = NDSCardBanner.BannerV1(data[header_length : banner_length+header_length])
def encode(self) -> bytes:
self.header.crc16_v1 = crc16(self.banner.encode())
return b''.join([self.header.encode(), self.banner.encode()])
__bytes__ = encode
def __len__(self):
return 832
class BannerHeader:
def __init__(self, data: bytes|None = None):
if data is None:
self.version = 1
self.crc16_v1 = 0
self.reserved = bytes(28)
return
self.version = uint_le(data[0:2])
self.crc16_v1 = uint_le(data[2:4])
self.reserved = data[4:32]
def encode(self) -> bytes:
return b''.join([u16_le(self.version), u16_le(self.crc16_v1), self.reserved])
__bytes__ = encode
def __len__(self):
return 32
class BannerV1:
image_size = 512
palette_size = 32
game_name_size = 256
def __init__(self, data: bytes|None = None):
if data is None:
self.image = bytes(self.image_size)
self.palette = bytes(self.palette_size)
self.game_name = [''] * 6
return
offset = 0
self.image = data[offset : offset+self.image_size]
offset += self.image_size
self.palette = data[offset : offset+self.palette_size]
offset += self.palette_size
self.game_name = []
for _ in range(6):
name = data[offset : offset+self.game_name_size].decode('utf_16_le').rstrip('\0')
self.game_name.append(name)
offset += self.game_name_size
def encode(self) -> bytes:
return b''.join([
self.image,
self.palette,
b''.join(
name.ljust(self.game_name_size//2, '\0').encode('utf_16_le')
for name in self.game_name
)
])
__bytes__ = encode
def __len__(self):
return 800

178
NDSCard/NitroFS.py Normal file
View File

@ -0,0 +1,178 @@
from typing import overload
from .Utils import uint_le, u8_le, u16_le, u32_le
class FileAllocationEntry:
@overload
def __init__(self, offset: int = 0, length: int = 0, /):
...
@overload
def __init__(self, data: bytes|None = None, /):
...
def __init__(self, *args):
if len(args) == 2:
self.start = args[0]
self.end = args[0] + args[1]
elif not args or args[0] is None:
self.start = 0
self.end = 0
else:
data = args[0]
self.start = uint_le(data[:4])
self.end = uint_le(data[4:8])
def encode(self) -> bytes:
return b''.join([u32_le(self.start), u32_le(self.end)])
__bytes__ = encode
def __len__(self):
return 8
class DirectoryTableEntry:
@overload
def __init__(self, start: int, file_id: int, parent_id: int, /):
...
@overload
def __init__(self, data: bytes|None = None, /):
...
def __init__(self, *args):
if len(args) == 3:
self.start = args[0]
self.file_id = args[1]
self.parent_id = args[2]
elif not args or args[0] is None:
self.start = 0
self.file_id = 0
self.parent_id = 0
else:
data = args[0]
self.start = uint_le(data[:4])
self.file_id = uint_le(data[4:6])
self.parent_id = uint_le(data[6:8])
def encode(self) -> bytes:
return b''.join([
u32_le(self.start),
u16_le(self.file_id),
u16_le(self.parent_id)
])
__bytes__ = encode
def __len__(self):
return 8
class EntryNameTableEntry:
@overload
def __init__(self, length: int = 0, /):
...
@overload
def __init__(self, data: bytes|None = None, /):
...
def __init__(self, arg = 0):
if isinstance(arg, int):
self.entry_name_length = arg
elif isinstance(arg, bytes):
self.entry_name_length = arg[0]
else:
self.entry_name_length = 0
def encode(self) -> bytes:
return u8_le(self.entry_name_length)
__bytes__ = encode
class EntryNameTableEndOfDirectoryEntry(EntryNameTableEntry):
def __init__(self, *_):
super().__init__()
def __len__(self):
return 1
class EntryNameTableFileEntry(EntryNameTableEntry):
@overload
def __init__(self, name: str = '', /):
...
@overload
def __init__(self, data: bytes|None = None, /):
...
def __init__(self, arg = ''):
if arg is None:
super().__init__()
return
elif isinstance(arg, str):
super().__init__(len(arg))
self.entry_name = arg
else:
super().__init__(arg)
self.entry_name = arg[1:self.entry_name_length+1].decode('shift-jis')
def encode(self) -> bytes:
self.__init__(self.entry_name)
return b''.join([
super().encode(),
self.entry_name.encode('shift-jis')
])
def __len__(self):
return self.entry_name_length + 1
class EntryNameTableDirectoryEntry(EntryNameTableEntry):
@overload
def __init__(self, name: str = '', directory_id: int = 0, /):
...
@overload
def __init__(self, data: bytes|None = None, /):
...
def __init__(self, *args):
if len(args) == 2:
super().__init__(len(args[0]) | 0x80)
self.entry_name = args[0]
self.directory_id = args[1]
elif not args or args[0] is None:
super().__init__()
self.entry_name = ''
self.directory_id = 0
else:
data = args[0]
super().__init__(data[:1])
enl = self.entry_name_length ^ 0x80
self.entry_name = data[1 : enl+1].decode('shift-jis')
self.directory_id = uint_le(data[enl+1 : enl+3])
def encode(self) -> bytes:
return b''.join([
super().encode(),
self.entry_name.encode('shift-jis'),
u16_le(self.directory_id)
])
def __len__(self):
return (self.entry_name_length ^ 0x80) + 3

5
NDSCard/Utils.py Normal file
View File

@ -0,0 +1,5 @@
uint_le = lambda b: int.from_bytes(b, byteorder='little')
u8_le = lambda i: i.to_bytes(length=1)
u16_le = lambda i: i.to_bytes(length=2, byteorder='little')
u32_le = lambda i: i.to_bytes(length=4, byteorder='little')
align = lambda i, al: i + al - i % al if i % al else i

0
NDSCard/__init__.py Normal file
View File

262
NDSCard/shutil.py Normal file
View File

@ -0,0 +1,262 @@
import os
import os.path
from .NDSCard import NDSCard, NDSCardHeader, NitroFooter, NDSCardFNT
from .NDSCard import NDSCardBanner, NDSCardFAT
from .NitroFS import FileAllocationEntry, DirectoryTableEntry, EntryNameTableDirectoryEntry
from .NitroFS import EntryNameTableFileEntry, EntryNameTableEndOfDirectoryEntry
from .Utils import align
class Unpacker:
"""Callable for unpacking Nintendo DS ROMs. This is meant to be used with
`shutil.unpack_archive`. This does not currently support unpacking ROMs that use overlays.
"""
def __call__(self, *args, **kwargs):
card = NDSCard(args[0])
out_dir = args[1]
out_path = lambda *s: os.path.join(out_dir, *s)
if card.main_ovt or card.sub_ovt:
raise NotImplementedError("ROMs with OVTs are not currently supported")
with open(out_path('header.bin'), 'wb') as fp:
fp.write(card.header.encode())
with open(out_path('arm9.bin'), 'wb') as fp:
fp.write(card.main_rom)
with open(out_path('arm7.bin'), 'wb') as fp:
fp.write(card.sub_rom)
if hasattr(card, 'static_footer'):
with open(out_path('static_footer.bin'), 'wb') as fp:
fp.write(card.static_footer.encode())
if hasattr(card, 'banner'):
with open(out_path('banner.bin'), 'wb') as fp:
fp.write(card.banner.encode())
if hasattr(card, 'rsa_sig'):
with open(out_path('rsa_sig.bin'), 'wb') as fp:
fp.write(card.rsa_sig)
# NitroFS
dirnames = [None] * len(card.fnt.directory_table)
dirnames[0] = 'data/' # root directory name
filenames = [None] * len(card.fat)
Unpacker._get_files(
dirnames, filenames, card.fnt.directory_table,
card.fnt.entry_name_table, 0
)
for dirname_elems in (name.split('/') for name in dirnames):
os.makedirs(out_path(*dirname_elems), exist_ok=True)
for file_id in range(len(filenames)):
with open(out_path(filenames[file_id]), 'wb') as fp:
fp.write(card.file_data[file_id])
@staticmethod
def _get_files(
dirnames: list[str],
filenames: list[str],
dir_table: NDSCardFNT.DirectoryTable,
names_table: NDSCardFNT.EntryNameTable,
dir_id: int
):
"""Get all directory names and filenames info into `dirnames` and `filenames`"""
file_id = dir_table[dir_id].file_id
for entry in names_table[dir_id]:
if isinstance(entry, EntryNameTableEndOfDirectoryEntry):
break
if isinstance(entry, EntryNameTableDirectoryEntry):
subdir_id = entry.directory_id ^ 0xf000
parent_dir_id = dir_table[subdir_id].parent_id ^ 0xf000
subdir_name = dirnames[parent_dir_id] + entry.entry_name + '/'
dirnames[subdir_id] = subdir_name
Unpacker._get_files(
dirnames, filenames, dir_table, names_table, subdir_id
)
else: # EntryNameTableFileEntry
path = dirnames[dir_id] + entry.entry_name
filenames[file_id] = path
file_id += 1
class Archiver:
"""Callable for repacking Nintendo DS ROMs that were unpacked by `NDSCard.Unpacker`. This is
meant to be used with `shutil.make_archive`. This does not currently suppport repacking
overlays.
"""
def __call__(self, *args, **kwargs):
out_filename = args[0]
in_dir = args[1]
in_path = lambda *s: os.path.join(in_dir, *s)
card = NDSCard()
files_start_offset = 0
with open(in_path('header.bin'), 'rb') as fp:
card.header = NDSCardHeader(fp.read())
files_start_offset += card.header.header_size
with open(in_path('arm9.bin'), 'rb') as fp:
card.main_rom = fp.read()
files_start_offset += len(card.main_rom)
try:
with open(in_path('static_footer.bin'), 'rb') as fp:
card.static_footer = NitroFooter(fp.read())
files_start_offset += len(card.static_footer)
except FileNotFoundError:
pass
files_start_offset = align(files_start_offset, 0x200)
with open(in_path('arm7.bin'), 'rb') as fp:
card.sub_rom = fp.read()
files_start_offset += len(card.sub_rom)
files_start_offset = align(files_start_offset, 0x200)
try:
with open(in_path('banner.bin'), 'rb') as fp:
card.banner = NDSCardBanner(fp.read())
except FileNotFoundError:
pass
try:
with open(in_path('rsa_sig.bin'), 'rb') as fp:
card.rsa_sig = fp.read()
except FileNotFoundError:
pass
# NitroFS
dir_tree = list(os.walk(in_path('data/')))
names_table = Archiver._make_names_table(dir_tree)
num_files = 0
for ent_entries in names_table:
for ent_entry in ent_entries:
files_start_offset += len(ent_entry)
if isinstance(ent_entry, EntryNameTableFileEntry):
num_files += 1
dir_table = Archiver._make_dir_table(names_table)
length = len(dir_table) * len(DirectoryTableEntry())
files_start_offset += length
files_start_offset = align(files_start_offset, 0x200)
# reserve space for FAT
length = num_files * len(FileAllocationEntry())
files_start_offset += length
files_start_offset = align(files_start_offset, 0x200)
try:
files_start_offset += len(card.banner) # banner
files_start_offset = align(files_start_offset, 0x200)
except NameError:
pass
card.fat = Archiver._make_fat(dir_tree, dir_table, files_start_offset)
card.file_data = Archiver._get_files(dir_tree)
card.fnt = NDSCardFNT()
card.fnt.directory_table = dir_table
card.fnt.entry_name_table = names_table
with open(out_filename, 'wb') as fp:
fp.write(card.encode())
@staticmethod
def _make_names_table(
dir_tree: list[tuple[str, list[str], list[str]]]
) -> NDSCardFNT.EntryNameTable:
out = NDSCardFNT.EntryNameTable()
subdir_id = 0xf001
for dir_info in dir_tree:
dir_entry = []
# process directories
for dirname in dir_info[1]:
dir_entry.append(
EntryNameTableDirectoryEntry(dirname, subdir_id)
)
subdir_id += 1
# process files
for filename in dir_info[2]:
dir_entry.append(EntryNameTableFileEntry(filename))
# done with this directory, add end entry
dir_entry.append(EntryNameTableEndOfDirectoryEntry())
out.append(dir_entry)
# processed all directories
return out
@staticmethod
def _make_dir_table(names_table: NDSCardFNT.EntryNameTable) -> NDSCardFNT.DirectoryTable:
num_dirs = len(names_table)
out = [DirectoryTableEntry() for _ in range(num_dirs)]
out[0].parent_id = num_dirs # root dir
first_file_id = 0
subdir_idx = 1
for dir_idx in range(num_dirs):
# store size of corresponding FNT names table
# in `size` custom attribute
out[dir_idx].size = 0
out[dir_idx].file_id = first_file_id
for entry in names_table[dir_idx]:
out[dir_idx].size += len(entry)
if isinstance(entry, EntryNameTableDirectoryEntry):
# assign parent_id for subdirs not yet processed
out[subdir_idx].parent_id = dir_idx | 0xf000
subdir_idx += 1
elif isinstance(entry, EntryNameTableFileEntry):
first_file_id += 1
offset = num_dirs * 8
out[0].start = offset
for dir_idx in range(1, num_dirs):
offset += out[dir_idx-1].size
out[dir_idx].start = offset
# remove added `size` attributes
for entry in out:
del entry.size
# convert to DirectoryTable
out = NDSCardFNT.DirectoryTable(b''.join(
entry.encode() for entry in out
))
return out
@staticmethod
def _make_fat(
dir_tree: list[tuple[str, list[str], list[str]]],
dir_table: NDSCardFNT.DirectoryTable,
files_start_offset: int
) -> NDSCardFAT:
num_dirs = len(dir_table)
out = NDSCardFAT()
out.extend(
FileAllocationEntry()
for dir_info in dir_tree
for file in dir_info[2]
)
offset = align(files_start_offset, 0x200)
for dirtab_idx in range(num_dirs):
file_id = dir_table[dirtab_idx].file_id
for filename in dir_tree[dirtab_idx][2]:
file_path = os.path.join(dir_tree[dirtab_idx][0], filename)
length = os.stat(file_path).st_size
out[file_id].start = offset
out[file_id].end = offset + length
offset = align(offset, 0x200)
file_id += 1
return out
@staticmethod
def _get_files(dir_tree: list[tuple[str, list[str], list[str]]]) -> list[bytes]:
file_data = []
for dir_info in dir_tree:
for filename in dir_info[2]:
with open(os.path.join(dir_info[0], filename), 'rb') as fp:
file_data.append(fp.read())
return file_data

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# dspatch.py
This is an application written in Python made to replicate the functionality of [dspatch](https://github.com/Gericom/dspatch) by Gericom.
It accepts the same arguments as dspatch and outputs ROMs with the same functionality—namely modified DS Download Station ROMs that can send unsigned homebrew ROMs to other Nintendo DS, Nintendo DSi, and Nintendo 3DS systems over DS Download Play.
Like the original dspatch, this supports including multiple ROMs in the output. In addition, this application also supports compressing ROMs to decrease transfer times using the `-c` option (requires [Python-LZO](https://pypi.org/project/python-lzo/) to be installed).
# How to use
## Windows
Download and install Python from https://www.python.org/downloads/windows/.
If you want to use compression, install Python-LZO as well.
If running Python 3.13 (from the command prompt):
```
>python.exe -m pip install bin\python-lzo\python_lzo-1.16-cp313-cp313-win_amd64.whl
```
If running Python 3.7 - 3.11:
```
>python.exe -m pip install python-lzo
```
Alternatively, build and install Python-LZO from source by following the instructions [here](https://github.com/jd-boyd/python-lzo#building-from-source).
Run `dspatch.py` to produce the ROM. You can use `-i` or `-I` multiple times to specify multiple ROM files or folders, respectively.
```
>python.exe dspatch.py -s download_station.nds -o [out_filename] -i [in_rom] -I [in_folder] [-c]
```
## Linux
If it's not already installed, install Python using your distribution's package manager.
Optionally, install Python-LZO as well to use compression.
Ubuntu/Debian:
```
# apt-get install python3
# apt-get install python3-lzo
```
Fedora (python-lzo requires building from source):
```
# dnf install python3
# dnf install python3-pip lzo python3-devel lzo-devel gcc
$ pip3 install python-lzo
```
Arch Linux (python-lzo requires building from source):
```
# pacman -S python
# pacman -S python-pip lzo gcc
$ pip3 install python-lzo
```
openSUSE:
```
# zypper install python3
# zypper install python3-python-lzo
```
Run `dspatch.py` to produce the ROM. You can use `-i` or `-I` multiple times to specify multiple ROM files or folders, respectively.
```
$ ./dspatch.py -s download_station.nds -o [out_filename] -i [in_rom] -I [in_folder] [-c]
```
# Copyright
dspatch.py © 2025 enderghast13.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See COPYING.md for full details.
[HaxxStation](https://gbatemp.net/threads/haxxstation-ds-download-station-exploit.473648/) exploit by shutterbug2000, Gericom, and Apache Thunder.
This program uses data from [dspatch](https://github.com/Gericom/dspatch) © 2017 Gericom.
This program uses [Python-LZO](https://github.com/jd-boyd/python-lzo) © 2011 - 2024 Joshua D. Boyd et al, distributed under the terms of the GNU General Public License (GPL), version 2.
This program uses the LZO1X algorithm by Markus F.X.J. Oberhumer.

Binary file not shown.

405
dspatch.py Executable file
View File

@ -0,0 +1,405 @@
#!/usr/bin/env python3
import sys
import os
import os.path
import shutil
import pickle
import argparse
import hashlib
from tempfile import TemporaryDirectory, NamedTemporaryFile
try:
import lzo
except ModuleNotFoundError:
pass
from NDSCard import NDSCard
from NDSCard.shutil import Unpacker, Archiver
from NDSCard.Utils import u16_le, u32_le
from NDSCard.CRC16 import crc16
from DownloadStation import DemoMenu
title = 'dspatch.py'
version = '1.0'
author = 'enderghast13'
license = '''
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see
<https://www.gnu.org/licenses/>.
'''
rom_size = 16777216
rom_hash = (
b'\xF1\x8B\x55\xF3\xE1\x25\x9C\x03\xE1\x0D'
b'\x0E\xCB\x54\x96\x93\xB4\x29\x05\xCE\xB5'
)
join = os.path.join
silent = 0
u32_be = lambda i: i.to_bytes(length=4, byteorder='big')
# load HaxxStation data
class HaxxStationData:
icon_image: bytes
icon_palette: bytes
server: bytes
exploit_data: bytes
arm7_fix: bytes
banner_text: str
demomenu_touch_text: list[str]
haxxstation_data = HaxxStationData()
with open('haxxstation_data.pickle', 'rb') as fp:
haxxstation_data.icon_image = pickle.load(fp)
haxxstation_data.icon_palette = pickle.load(fp)
haxxstation_data.server = pickle.load(fp)
haxxstation_data.exploit_data = pickle.load(fp)
haxxstation_data.arm7_fix = pickle.load(fp)
haxxstation_data.banner_text = pickle.load(fp)
haxxstation_data.demomenu_touch_text = pickle.load(fp)
def main():
args = parse_cmdline()
#Verifications
if not verify_args(args):
return 1
if not verify_download_station_rom(args.dls_path):
return 1
rom_paths = get_rom_paths(args.in_files, args.in_dirs)
if not rom_paths:
error(f"{title}: error: no ROMs found or specified")
error('hint: ROMs in folders must end in ".nds" or ".srl"')
return 1
shutil.register_unpack_format(
'nds', ['.nds', '.srl'], Unpacker(), description='Nintendo DS ROM'
)
shutil.register_archive_format('nds', Archiver(), description='Nintendo DS ROM')
with TemporaryDirectory() as tmpdir:
# unpack all files in Download Station ROM into tmpdir
shutil.unpack_archive(args.dls_path, tmpdir, format='nds')
# remove all included ROMs
for filename in os.listdir(join(tmpdir, 'data', 'ds_demo')):
os.remove(join(tmpdir, 'data', 'ds_demo', filename))
# overwrite /mb/server, /mb/icon.nbfc, and /mb/icon.nbfp
with open(join(tmpdir, 'data', 'mb', 'server'), 'wb') as fp:
fp.write(haxxstation_data.server)
with open(join(tmpdir, 'data', 'mb', 'icon.nbfc'), 'wb') as fp:
fp.write(haxxstation_data.icon_image)
with open(join(tmpdir, 'data', 'mb', 'icon.nbfp'), 'wb') as fp:
fp.write(haxxstation_data.icon_palette)
# change banner
new_banner = NDSCard.NDSCardBanner()
new_banner.banner.image = haxxstation_data.icon_image
new_banner.banner.palette = haxxstation_data.icon_palette
for i in range(6):
new_banner.banner.game_name[i] = haxxstation_data.banner_text
with open(join(tmpdir, 'banner.bin'), 'wb') as fp:
fp.write(new_banner.encode())
# copy and patch all roms
rom_num = 0
for filename in rom_paths:
rom_name = f"rom{rom_num:04d}d"
status(
f"Adding {os.path.basename(filename)} as {rom_name}... ", end=''
)
shutil.copyfile(
filename, join(tmpdir, 'data', 'ds_demo', rom_name)
)
with open(join(tmpdir, 'data', 'ds_demo', rom_name), 'rb+') as fp:
patched_rom = patch_multiboot_rom(fp.read())
fp.seek(0)
fp.truncate()
fp.write(patched_rom)
rom_num += 1
status("Done")
# create new /ds_demo/demomenu
file_paths = [
join(tmpdir, 'data', 'ds_demo', filename)
for filename in os.listdir(join(tmpdir, 'data', 'ds_demo'))
]
status("Creating demomenu... ", end='')
with open(join(tmpdir, 'data', 'ds_demo', 'demomenu'), 'wb') as fp:
fp.write(make_demomenu(file_paths))
status("Done")
if args.compress:
status(f"Compressing ROMs... ", end='')
for path in file_paths:
with open(path, 'rb+') as fp:
cmp_data = lzon_compress(fp.read())
fp.seek(0)
fp.write(cmp_data)
fp.truncate()
status("Done")
if args.output != '-':
# repack Download Station ROM as out_path
shutil.make_archive(args.output, 'nds', tmpdir)
status(f"Output to {args.output}")
else:
# repack into stdout
with NamedTemporaryFile() as fp:
shutil.make_archive(fp.name, 'nds', tmpdir)
sys.stdout.buffer.write(fp.read())
status(f"Output to stdout")
return 0
def parse_cmdline(args=None) -> argparse.Namespace:
global silent
parser = argparse.ArgumentParser(
prog=title, description="DS Download Station patcher",
epilog=(
"You can add multiple roms by using -I or -i multiple times.\n"
"Compression requires Python-LZO to be installed."
), formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
'-s', required=True, help="DS Download Station Volume 1 (USA) ROM", metavar='station.nds',
dest='dls_path'
)
parser.add_argument(
'-o', required=True, help="destination ROM", metavar='result.nds', dest='output'
)
parser.add_argument(
'-i', action='append', default=[], help="ROM to add", metavar='rom.nds', dest='in_files'
)
parser.add_argument(
'-I', action='append', default=[], help="folder of ROMs", metavar='romfolder',
dest='in_dirs'
)
parser.add_argument('-c', action='store_true', help="compress ROMs", dest='compress')
parser.add_argument(
'-S', '--silent', action='count', default=0,
help=(
"suppress status messages\n"
"specify multiple times to suppress errors"
)
)
parser.add_argument(
'-v', '--version', action='version',
version=(
f"%(prog)s v{version} - DS Download Station patcher\n"
f"Copyright (c) 2025 {author}\n"
f"{license}\n"
"HaxxStation exploit by shutterbug2000, Gericom, and Apache Thunder\n"
"dspatch (c) 2017 Gericom\n"
"Python-LZO (c) 2011 - 2024 Joshua D. Boyd et al\n"
"LZO1X algorithm by Markus F.X.J. Oberhumer"
)
)
namespace = parser.parse_args(args)
silent = namespace.silent
return namespace
def verify_args(args: argparse.Namespace) -> bool:
if args.compress and 'lzo' not in globals():
error(f"{title}: error: compression option specified, but Python-LZO is not installed")
error("please install Python-LZO (instructions are in README.md)")
return False
files = False
if not os.path.isfile(args.dls_path):
error(f'{title}: error: file "{args.dls_path}" not found')
return False
if args.in_files:
files = True
for file in args.in_files:
if not os.path.isfile(file):
error(f'{title}: error: file "{file}" not found')
return False
if args.in_dirs:
files = True
for dir in args.in_dirs:
if not os.path.isdir(dir):
error(f'{title}: error: directory "{dir}" not found')
return False
if not files:
error(f"{title}: error: no ROMs or folders specified")
return False
return True
def verify_download_station_rom(filename: str) -> bool:
with open(filename, 'rb') as fp:
if os.fstat(fp.fileno()).st_size != rom_size:
error(f"{title}: error: incorrect size: {filename}")
error(f"must be {rom_size}")
return False
sha1 = hashlib.sha1()
for _ in range(rom_size // 65536):
sha1.update(fp.read(65536))
if sha1.digest() != rom_hash:
error(f"{title}: error: incorrect SHA-1 hash: {filename}")
error(f"must be {rom_hash.hex()}")
return False
return True
def get_rom_paths(filenames: list[str], dirnames: list[str]) -> frozenset:
return (
frozenset(os.path.realpath(file) for file in filenames)
| frozenset(
# collect realpaths of files in dirs specified in dirnames
os.path.realpath(join(dir, file))
# dir is an item from the dirnames list
for dir in dirnames
# file is an item from os.listdir(dir)
for file in os.listdir(dir)
# filter
if file.endswith('.nds') or file.endswith('.srl')
)
)
def patch_multiboot_rom(rom_data: bytes) -> bytes:
rom = NDSCard.NDSCard(rom_data)
if rom.header.sub_ram_address >= 0x03000000:
new_arm7 = bytearray(
b''.join([haxxstation_data.arm7_fix, rom.sub_rom])
)
new_arm7[0x28:0x2c] = u32_le(rom.header.sub_entry_address)
new_arm7[0x2c:0x30] = u32_le(rom.header.sub_ram_address)
new_arm7[0x30:0x34] = u32_le(rom.header.sub_size)
new_arm7 = bytes(new_arm7)
rom.sub_rom = new_arm7
rom.header.sub_size = len(new_arm7)
rom.header.sub_ram_address = 0x02380000
rom.header.sub_entry_address = 0x02380000
# this also fixes the header CRC
new_rom_data = bytearray(rom.encode(multiboot=True))
# store these for later
arm9_offset = new_rom_data[0x20:0x24]
arm9_load_addr = new_rom_data[0x28:0x2c]
arm9_size = new_rom_data[0x2c:0x30]
arm7_offset = new_rom_data[0x30:0x34]
# arm9 offset becomes 0x180
new_rom_data[0x20:0x24] = u32_le(0x00000180)
# arm9 load becomes 0x02332C40 (rsa_GetDecodedHash)
new_rom_data[0x28:0x2c] = u32_le(0x02332C40)
# arm9 size becomes 0x100
new_rom_data[0x2c:0x30] = u32_le(0x00000100)
# fix header CRC
new_crc = crc16(new_rom_data[:0x15e])
new_rom_data[0x15e:0x160] = u16_le(new_crc)
# copy exploit data
new_rom_data[0x180 : 0x180+len(haxxstation_data.exploit_data)] =\
haxxstation_data.exploit_data
# later
new_rom_data[0x1bc:0x1c0] = arm7_offset
new_rom_data[0x1c0:0x1c4] = arm9_offset
new_rom_data[0x1c4:0x1c8] = arm9_load_addr
new_rom_data[0x1c8:0x1cc] = arm9_size
return bytes(new_rom_data)
def make_demomenu(file_paths: list[str]) -> bytes:
demomenu = DemoMenu.DemoMenu()
for filename in file_paths:
basename = os.path.basename(filename)
entry = DemoMenu.DemoMenu.DemoMenuEntry()
entry.guide_mode = DemoMenu.GuideMode.T
entry.touch_text[0] = haxxstation_data.demomenu_touch_text[0]
entry.touch_text[1] = haxxstation_data.demomenu_touch_text[1]
entry.internal_name = basename
card = NDSCard.NDSCard(filename)
try:
# get suitable lines from all banner entries
candidate_lines = []
for lines in card.banner.banner.game_name:
if not lines:
# no text in this entry; skip over
continue
try:
# check if the whole string can be encoded
lines.encode('cp1252')
# if it can, add all lines as a single candidate entry
candidate_lines.append(lines.split('\n'))
break # we're only interested in the first viable candidate
except UnicodeDecodeError:
# cannot be encoded; skip over
pass
if not candidate_lines:
# no viable candidate lines were found
entry.banner_text[0] = "Bannerless Homebrew"
entry.banner_text[1] = ''
else:
# use the first viable candidate lines found
entry.banner_text[0] = candidate_lines[0][0]
if len(candidate_lines[0]) > 1:
entry.banner_text[1] = candidate_lines[0][1]
entry.banner_image = card.banner.banner.image
entry.banner_palette = card.banner.banner.palette
except AttributeError: # no banner
entry.banner_text[0] = "Bannerless Homebrew"
entry.banner_text[1] = ''
demomenu.append(entry)
if len(demomenu) < 3:
default_entry = DemoMenu.DemoMenu.DemoMenuEntry()
default_entry.guide_mode = DemoMenu.GuideMode.T
default_entry.touch_text[0] = haxxstation_data.demomenu_touch_text[0]
default_entry.touch_text[1] = haxxstation_data.demomenu_touch_text[1]
default_entry.internal_name = basename
while len(demomenu) < 3:
demomenu.append(default_entry)
return demomenu.encode()
def lzon_compress(data: bytes) -> bytes:
lzon_header = b'LZOn\x00\x2f\xf1\x71'
orig_size = len(data)
cmp_data = lzo.compress(data, 9, False)
if len(cmp_data) + 0x10 >= orig_size:
# compressed data + header is larger or the same size; leave uncompressed
return data
cmp_data = lzo.optimize(cmp_data, False, orig_size)
cmp_size = len(cmp_data)
return b''.join([
lzon_header, u32_be(orig_size), u32_be(cmp_size), cmp_data,
b'\0' if cmp_size % 2 else b'' # align to 2 bytes
])
def error(*args, **kwargs):
if silent < 2:
print(*args, **kwargs, file=sys.stderr)
def status(*args, **kwargs):
if not silent:
print(*args, **kwargs, file=sys.stderr)
if __name__ == '__main__':
sys.exit(main())

BIN
haxxstation_data.pickle Normal file

Binary file not shown.

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
python-lzo