cmdpack-1.03-src/0000755000175000017500000000000011731303760013537 5ustar corlettcorlettcmdpack-1.03-src/doc/0000755000175000017500000000000011731303760014304 5ustar corlettcorlettcmdpack-1.03-src/doc/cmdpack.txt0000644000175000017500000003127011731303760016452 0ustar corlettcorlett-------------------------------------------------------------------------------- Command-Line Pack v1.03 Copyright (C) 1996-2011 Neill Corlett http://www.neillcorlett.com/cmdpack/ -------------------------------------------------------------------------------- This is a collection of command-line tools I've written over the years that I decided to clean up and repackage. All of the tools are released under the terms of the GNU General Public License version 3. -------------------------------------------------------------------------------- Contents -------------------------------------------------------------------------------- bin2iso - Convert CD .BIN to .ISO --------------------------------- Converts CD-ROM .BIN images (including full 2352-byte sectors) into .ISO format (2048-byte sectors). Automatically detects mode 1 or 2. Will warn if there are any form 2 sectors, which are not convertible. Usage: bin2iso [-f] input_file output_file -f: Force conversion and bypass checks bincomp - Compare binary files ------------------------------ Similar to the old DOS "FC /B" command. The default output is a side-by-side table showing 16 bytes per line. The "-l" flag will show one byte per line. Usage: bincomp file1 file2 [-l] -l Use long format brrrip - Rip SNES BRR sound samples ----------------------------------- Automatically detects and rips sound samples from SNES ROMs. Works great with uncompressed .SPC files too. Usage: brrrip romfile [samplerate [minblocks]] "samplerate" should be given in Hz. Samples will only be detected if they are at least "minblocks" long (default=50). The output files will be named (hex address).wav. byteshuf - Shuffle or unshuffle bytes in a file ----------------------------------------------- Divides a file into its interleaved even/odd bytes, or recombines them. Can also divide every 3rd, 4th, etc. byte, depending on how many subfiles you specify. Useful for dealing with certain types of ROM images. Usage: To unshuffle: byteshuf [-o] -u source [subfiles...] To shuffle: byteshuf [-o] -s destination [subfiles...] Options: -o Force overwrite For example, "byteshuf -u abc def0 def1" will split all the even bytes from "abc" into "def0", and the odd bytes into "def1". byteswap - Swap byte order of files ----------------------------------- Swaps the byte order of each record in a file, in place. If the record size is 2, this means every even and odd byte is swapped, but the record size can also be larger than 2. Useful for dealing with certain types of ROM images. Usage: byteswap [-q] [-s recordsize] files... -q: Quiet -s: Size, in bytes, of each record to swap (default: 2) cdpatch - CD-XA image insert/extract utility -------------------------------------------- Inserts or extracts files in-place into CD-ROM images in either .BIN or .ISO format. Properly handles CD-XA streams from Mode 2 CDs (Video CDs, PlayStation movie files, etc.) and patches ECC/EDC data as appropriate. Usage: To insert: cdpatch -i bin_or_iso [options] [files...] To extract: cdpatch -x bin_or_iso [options] [files...] Options: -be Favor big-endian values in ISO9660 metadata -boot Insert or extract boot area -d dir Set the base directory for inserted or extracted files (defaults to .) -f Skip filesystem consistency checks -le Favor little-endian values in ISO9660 metadata -o Force overwrite when extracting files -r Recurse into subdirectories -v Verbose By default, cdpatch will attempt to insert or extract every file in the CD image, the same as if you'd specified "-r ." The "-boot" option will insert or extract the 32KiB boot sector area to a file named "boot". Some CD images may have conflicting sets big- and little-endian metadata as a platform-specific quirk or copy protection scheme; the "-be" and "-le" options can be used to override this. Specifying both -f and -v will list all filesystem errors, while still ignoring them for extraction purposes. When extracting files via -x, cdpatch preserves file modification times when possible. ecm - Encoder/decoder for Error Code Modeler format --------------------------------------------------- ECM is a compression format for CD images which removes ECC/EDC data where it's possible to do so losslessly. Compressing a CD image with ECM first, then compressing the ECM file with a general-purpose compressor such as 7z or RAR, can result in better compression than 7z or RAR alone. See http://www.neillcorlett.com/ecm/ for more details. Usage: To encode: ecm cdimagefile ecm cdimagefile ecmfile ecm e cdimagefile ecmfile To decode: unecm ecmfile unecm ecmfile cdimagefile ecm d ecmfile cdimagefile fakecrc - Fake the CRC32 of a file ---------------------------------- Modifies a file to force it to have a particular CRC32 checksum, by patching 4 consecutive bytes anywhere in the file. Can also obtain the CRC32 checksum of a file. Usage: To obtain the CRC32 of a file: fakecrc file To modify the CRC32 of a file: fakecrc file desired_crc [offset] The 4 bytes at "offset" will be modified. If no offset is given, the last 4 bytes of the file are used. hax65816 - Simple 65816 disassembler ------------------------------------ A simple 65c816 disassembler with basic flag following. This is the disassembler I used for the Seiken Densetsu 3 project, among others. Usage: hax65816 imagefile start address [length] [options] Output is written to stdout. All values must be given in hex. If no length is given, disassembly will stop at the end of the bank. Options: -m0 Assume M flag = 0 -m1 Assume M flag = 1 (default) -x0 Assume X flag = 0 (default) -x1 Assume X flag = 1 -noreturn Disable flag reset after RTS/RTL/RTI -noguess Disable flag guess on BRK/COP/WDM/STP -nofollow Disable REP/SEP following (not recommended) id3point - Pointless ID3v1 Tagger --------------------------------- A basic ID3v1 tagger for MP3 files. Probably superseded by newer tools, but included here nonetheless. Usage: id3point [options] mp3file(s) Options: -t title Set ID3 title -t- Clear ID3 title -a artist Set ID3 artist -a- Clear ID3 artist -m album Set ID3 album -m- Clear ID3 album -y year Set ID3 year -y- Clear ID3 year -c comment Set ID3 comment -c- Clear ID3 comment -k track# Set ID3 track # -k- Clear ID3 track # -g genre# Set ID3 genre # -g- Clear ID3 genre # -tf Set ID3 title based on the filename Notes: - Only ID3v1 tags are supported. - The track number increments automatically for each additional file. - The -tf option will turn "Artist - Title.mp3" into "Title", but be sure to check the titles by hand in case it gets confused. pecompat - Maximize compatibility of a Win32 PE file ---------------------------------------------------- Patches a Windows 32-bit PE executable file to maximize its compatibility with older versions of Windows. - Clears the linker timestamp - Sets the required OS version and subsystem version to "4.00" - Recalculates the PE file checksum - Warns if any Unicode import functions are used Usage: pecompat pe_exe_file(s) rels - Relative Searcher ------------------------ Searches for a string in a group of files by comparing the relative difference between each letter. This allows finding strings in non-ASCII character sets. Also attempts double values (e.g. 00=A, 02=B, 04=C) and wide values (every other byte, as in UCS-2). A staple ROM hacking tool. Usage: rels string files Search strings may include '.' characters as wildcards, but must include at least two non-wildcard characters. screamf - .AMF to .S3M converter -------------------------------- Converts AMF music files to S3M. AMF was a format used exclusively by Otto Chrons' DOS Sound and Music Interface (DSMI) library and Dual Module Player. Various DOS games and demos in the 1990s used this format. AMF files were the result of running MOD2AMF on an existing S3M or other module; screamf does the opposite. It's round-trippable for the most part. Usage: screamf inputfile.amf outputfile.s3m subfile - Extract a portion of a file ------------------------------------- Extracts a portion of a file, given a starting offset and length, in bytes. Offset and length may be specified in C style "0x123" or "0123" notation for hexadecimal or octal. Usage: subfile infile offset length outfile uips - Universal IPS patch create/apply utility ----------------------------------------------- UIPS is a command-line utility for creating and applying IPS patches. IPS is an old patch format for binary files, limited to 16 MiB in size, and not to be confused with the newer UPS format. Multiple source files and IPS v2 truncation are supported. Usage: To create an IPS patch: uips c patch_file source_file(s) target_file To apply an IPS patch: uips a patch_file target_file For example, "uips c patch.ips file1 file2 file3 file4" will create a patch file capable of transforming any of file1, file2, or file3 to file4. usfv - Universal SFV create/verify utility ------------------------------------------ USFV is a utility for creating and verifying SFV (Simple File Verification) files, such as those created by Win-SFV32. A SFV file contains a list of filenames and their corresponding CRC32 checksums. Caveat: CRC32 is not a cryptographic hash and cannot be used to ensure that a file was not maliciously modified (see fakecrc, above). Usage: To create a SFV file: usfv c sfvfile filenames To verify a SFV file: usfv v sfvfile vb2rip - VB2 sound format ripping utility ----------------------------------------- Rips music in .VB2 and various similar formats found in PlayStation and PlayStation 2 games. See http://www.neillcorlett.com/vb2rip/ for more details. Usage: vb2rip [options] inputfile(s) Options: -fmt format Specify the input file format -o path Specify the output filename (if one input file is given) or specify the output directory (if several are given) -mono Treat input file as monaural -stereo Treat input file as stereo -rate n Specify the sample rate -interleave n Specify the block interleave size -skip n Skip this many bytes after each block -offset n Start at the given offset in the input file -endflag Stop decoding when the sample end flag is reached -noendflag Ignore the sample end flag -maxbytes n Set the maximum number of input bytes to decode Supported input formats: Format Description ------------------------------------------------------------ raw Raw data (for experimentation) vb2 Konami multi-song .BIN/.VB2 file (Dance Dance Revolution, etc.) 8 .8 file (Suikoden) msa .MSA file (Psyvariar, possibly other PS2 games) xa2 .XA2 file (Extreme-G 3, possibly other PS2 games) wordadd - Addition word puzzle solver ------------------------------------- Finds solutions to letter/digit substitution puzzles of the "WORD + WORD = OTHER" variety. Supports multiple addends and digits mixed in with letters. Usage: wordadd words... sum Examples: wordadd BEEF BACON MEATS zerofill - Create a large, empty file ------------------------------------- Creates a file filled with bytes of value zero. Similar to "dd if=/dev/zero", except not all platforms have dd, and there's a progress indicator. Inside a virtual machine, zerofill can be used to create a large dummy file in order to zero out all the unused sectors before compressing the drive image. (zerofill is also useful for creating drive images in the first place.) Usage: zerofill [-f] [-q] size filename -f: Force overwrite -q: Quiet "size" may be specified in C style "0x123" or "0123" notation for hexadecimal or octal. -------------------------------------------------------------------------------- Terms of use -------------------------------------------------------------------------------- All of the programs included in Command-Line Pack are subject to the following terms of use: 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 3 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 . -------------------------------------------------------------------------------- cmdpack-1.03-src/doc/gpl.txt0000644000175000017500000010451311731303760015633 0ustar corlettcorlett GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 3 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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 instead of this License. But first, please read . cmdpack-1.03-src/src/0000755000175000017500000000000011731303760014326 5ustar corlettcorlettcmdpack-1.03-src/src/banner.h0000644000175000017500000000414111731303760015744 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// void banner_ok(void) { printf(TITLE "\n" " " COPYR "\n" " from Command-Line Pack " #include "version.h" " (%d-bit " #if defined(__CYGWIN__) "Windows, Cygwin" #elif defined(__MINGW32__) "Windows, MinGW" #elif defined(_WIN32) && defined(_MSC_VER) && (defined(__alpha) || defined(__ALPHA) || defined(__Alpha_AXP)) "Windows, Digital AXP C" #elif defined(_WIN32) && defined(_MSC_VER) && defined(_M_ALPHA) "Windows, Microsoft C, Alpha" #elif defined(_WIN32) && defined(_MSC_VER) && defined(_M_MRX000) "Windows, Microsoft C, MIPS" #elif defined(_WIN32) && defined(_MSC_VER) "Windows, Microsoft C" #elif defined(__WIN32__) || defined(_WIN32) "Windows" #elif defined(__DJGPP__) "DOS, DJGPP" #elif defined(__MSDOS__) && defined(__TURBOC__) "DOS, Turbo C" #elif defined(_DOS) && defined(__WATCOMC__) "DOS, Watcom" #elif defined(__MSDOS__) || defined(MSDOS) || defined(_DOS) "DOS" #elif defined(__APPLE__) "Mac OS" #elif defined(__linux) || defined(__linux__) || defined(__gnu_linux__) || defined(linux) "Linux" #elif defined(__OpenBSD__) "OpenBSD" #elif defined(BSD) "BSD" #elif defined(human68k) || defined(HUMAN68K) || defined(__human68k) || defined(__HUMAN68K) || defined(__human68k__) || defined(__HUMAN68K__) "Human68k" #elif defined(__unix__) || defined(__unix) || defined(unix) "unknown Unix" #else "unknown platform" #endif "%s)\n" " http://www.neillcorlett.com/cmdpack/\n" "\n", (int)(sizeof(size_t) * 8), (sizeof(off_t) > 4 && sizeof(off_t) > sizeof(size_t)) ? ", large file support" : "" ); } void banner_error(void) { printf("Configuration error\n"); exit(1); } static void banner(void) { ((sizeof(off_t) >= sizeof(size_t)) ? banner_ok : banner_error)(); // // If we've displayed the banner, we'll also want to warn that this is a // command-line app when we exit // atexit(commandlinewarning); } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/bin2iso.c0000644000175000017500000001732711731303760016051 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "bin2iso - Convert CD .BIN to .ISO" #define COPYR "Copyright (C) 2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// // // Sector buffer // uint8_t buffer[2352]; //////////////////////////////////////////////////////////////////////////////// static const char* w(int force) { return force ? "Warning" : "Error"; } int main(int argc, char** argv) { int returncode = 0; const char* binfilename = NULL; const char* isofilename = NULL; FILE* binfile = NULL; FILE* isofile = NULL; int force = 0; time_t tstart = time(NULL) - 1; off_t binfilelength = 0; off_t binfilepos = 0; char warning_shown_sync = 0; char warning_shown_mode = 0; char warning_shown_form2 = 0; normalize_argv0(argv[0]); // // Process command line // { int fn = 0; int i; for(i = 1; i < argc; i++) { if(argv[i][0] == '-' && !fn) { // An option if(argv[i][1] == '-' && argv[i][2] == 0) { // No more options fn = 1; continue; } if(argv[i][1] == 'f' && argv[i][2] == 0) { // Force force = 1; continue; } printf("Unknown option: %s\n", argv[i]); goto usage; } else { // A filename switch(fn) { case 0: case 1: binfilename = argv[i]; fn = 2; break; case 2: isofilename = argv[i]; fn = 3; break; default: goto usage; } } } } if(!binfilename || !isofilename) { goto usage; } // // Make sure the iso doesn't already exist // { int exists = 0; FILE* test = fopen(isofilename, "rb"); exists = (test != NULL); if(test) { fclose(test); } if(exists) { printf("%s: %s already exists.\n", w(force), isofilename); if(!force) { goto error_override; } printf("Overwriting.\n"); } } // // Open bin for reading // binfile = fopen(binfilename, "rb"); if(!binfile) { goto error_bin; } // // Verify the file length // if(fseeko(binfile, 0, SEEK_END) != 0) { goto error_bin; } binfilelength = ftello(binfile); if(!binfilelength) { printf("Error: %s: Empty file; nothing to convert.\n", binfilename); goto error; } if((binfilelength % ((off_t)2352)) != 0) { printf("%s: %s: File size is not a multiple of 2352.\n", w(force), binfilename); printf("Likely not a BIN file.\n"); if(!force) { goto error_override; } } // // Open iso for writing // isofile = fopen(isofilename, "wb"); if(!isofile) { goto error_iso; } // // Convert // if(fseeko(binfile, 0, SEEK_SET) != 0) { goto error_bin; } for(binfilepos = 0;; binfilepos += 2352) { size_t data_ofs = 0x10; size_t s; time_t t = time(NULL); // // Progress indicator // if(t != tstart) { off_t a = binfilepos / ((off_t)2352); off_t b = binfilelength / ((off_t)2352); off_t percent = b ? ((((off_t)100) * a) / b) : 0; fprintf(stderr, "%d%%...\r", (int)percent); tstart = t; } s = fread(buffer, 1, 2352, binfile); if(ferror(binfile)) { goto error_bin; } if(s == 0 && feof(binfile)) { // Done converting break; } if(s > 2352) { s = 2352; } if(s < 2352) { printf("%s: %s: Last sector is incomplete\n", w(force), binfilename); if(!force) { goto error_override; } // Zero-fill the remaining data memset(buffer + s, 0, 2352 - s); } // // Check for sync // if(memcmp(buffer, "\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00", 12)) { if(!warning_shown_sync) { printf("%s: %s: Sync area missing at 0x", w(force), binfilename); fprinthex(stdout, binfilepos, 1); printf("\n"); printf("Likely not a BIN file.\n"); } if(!force) { goto error_override; } warning_shown_sync = 1; } // // Determine sector mode // switch(buffer[0xF]) { case 0x00: // // Mode 0: technically legal, all zeroes // data_ofs = 0x10; break; case 0x01: // // Mode 1: ok // data_ofs = 0x10; break; case 0x02: // // Mode 2: Check form // data_ofs = 0x18; if( ((buffer[0x12] & 0x20) != 0) || ((buffer[0x16] & 0x20) != 0) ) { if(!warning_shown_form2) { printf("%s: %s: Form 2 sector at 0x", w(force), binfilename); fprinthex(stdout, binfilepos, 1); printf("\n"); printf("Information will be lost.\n"); } if(!force) { goto error_override; } warning_shown_form2 = 1; } break; default: // // Unknown mode // if(!warning_shown_mode) { printf("%s: %s: Unknown sector mode 0x%x at 0x", w(force), binfilename, buffer[0xF]); fprinthex(stdout, binfilepos, 1); printf("\n"); } if(!force) { goto error_override; } data_ofs = 0x10; if(!warning_shown_mode) { printf("Assuming mode 1.\n"); } warning_shown_mode = 1; break; } // // Write sector to ISO // s = fwrite(buffer + data_ofs, 1, 2048, isofile); if(ferror(isofile)) { goto error_iso; } if(s != 2048) { goto error_iso; } } printf("%s -> %s done\n", binfilename, isofilename); goto done; usage: banner(); printf( "Usage: %s [-f] input_file output_file\n" " -f: Force conversion and bypass checks\n", argv[0] ); goto error; error_bin: printfileerror(binfile, binfilename); goto error; error_iso: printfileerror(isofile, isofilename); goto error; error_override: printf("Use -f to override.\n"); error: returncode = 1; done: if(binfile) { fclose(binfile); } if(isofile) { fclose(isofile); // If there was an error, remove the partial ISO file if(returncode && isofilename) { remove(isofilename); } } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/bincomp.c0000644000175000017500000001037711731303760016131 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "bincomp - Compare binary files" #define COPYR "Copyright (C) 2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static void dumpline(off_t ofs, uint16_t mask, uint8_t* bytes, off_t limit) { off_t i; fprinthex(stdout, ofs, 8); printf(": "); for(i = 0; i < 16; i++) { if((mask >> i) & 1) { printf("%02X", (int)bytes[i]); } else { printf((ofs + i) < limit ? ". " : " "); } } printf(" "); for(i = 0; i < 16; i++) { if((mask >> i) & 1) { printf("%02X", (int)bytes[16 + i]); } else { printf((ofs + i) < limit ? ". " : " "); } } printf("\n"); } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int returncode = 0; FILE* fa = NULL; FILE* fb = NULL; off_t ofs; int8_t is_different = 0; int longform = 0; off_t line_ofs = -1; uint16_t line_mask = 0; uint8_t line_bytes[32]; normalize_argv0(argv[0]); if(argc == 4) { if(strcmp(argv[3], "-l")) { goto usage; } longform = 1; } else if(argc == 3) { longform = 0; } else { goto usage; } if(!strcmp(argv[1], argv[2])) { printf("You specified the same file\n"); goto done; } fa = fopen(argv[1], "rb"); if(!fa) { goto error_fa; } fb = fopen(argv[2], "rb"); if(!fb) { goto error_fb; } for(ofs = 0;; ofs++) { int ca; int cb; if(line_mask && ((ofs | 0xF) != (line_ofs | 0xF))) { dumpline(line_ofs, line_mask, line_bytes, line_ofs + 0x10); line_mask = 0; } ca = fgetc(fa); if(ca == EOF && ferror(fa)) { goto error_fa; } cb = fgetc(fb); if(cb == EOF && ferror(fb)) { goto error_fb; } is_different |= (ca != cb); if(ca == EOF && cb != EOF) { if(line_mask) { dumpline(line_ofs, line_mask, line_bytes, ofs); } printf("%s is longer than %s\n", argv[2], argv[1]); break; } if(cb == EOF && ca != EOF) { if(line_mask) { dumpline(line_ofs, line_mask, line_bytes, ofs); } printf("%s is longer than %s\n", argv[1], argv[2]); break; } if(ca == EOF && cb == EOF) { if(line_mask) { dumpline(line_ofs, line_mask, line_bytes, ofs); } break; } if(ca != cb) { if(longform) { fprinthex(stdout, ofs, 8); printf(": %02X %02X\n", ca, cb); } else { line_ofs = (ofs | 0xF) ^ 0xF; line_mask |= 1 << (ofs & 0xF); line_bytes[ (ofs & 0xF)] = (uint8_t)ca; line_bytes[16 + (ofs & 0xF)] = (uint8_t)cb; } } } if(!is_different) { printf("Files match\n"); } returncode = is_different; goto done; error_fa: printfileerror(fa, argv[1]); goto error; error_fb: printfileerror(fb, argv[2]); goto error; usage: banner(); printf( "Usage: %s file1 file2 [-l]\n" " -l Use long format\n", argv[0] ); goto error; error: returncode = 1; done: if(fa != NULL) { fclose(fa); } if(fb != NULL) { fclose(fb); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/brrrip.c0000644000175000017500000001606111731303760015776 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "brrrip - Rip SNES BRR sound samples" #define COPYR "Copyright (C) 2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static void set32lsb(uint8_t* dest, uint32_t n) { dest[0] = (uint8_t)(n >> 0); dest[1] = (uint8_t)(n >> 8); dest[2] = (uint8_t)(n >> 16); dest[3] = (uint8_t)(n >> 24); } //////////////////////////////////////////////////////////////////////////////// static int writewav( FILE* src, const char* srcfilename, off_t startpos, off_t endpos, off_t samplerate ) { int returncode = 0; static uint8_t wavhdr[] = { 0x52,0x49,0x46,0x46,0x16,0x63,0x01,0x00, 0x57,0x41,0x56,0x45,0x66,0x6D,0x74,0x20, 0x10,0x00,0x00,0x00,0x01,0x00,0x01,0x00, 0x44,0xAC,0x00,0x00,0x88,0x58,0x01,0x00, 0x02,0x00,0x10,0x00,0x64,0x61,0x74,0x61, 0x40,0x62,0x01,0x00 }; FILE *wav = NULL; char wavfilename[24]; int32_t p1 = 0; int32_t p2 = 0; if(fseeko(src, startpos, SEEK_SET) != 0) { goto error_src; } sprintf(wavfilename, "%06lx.wav", (unsigned long)((uint32_t)(startpos))); fprinthex(stdout, startpos, 6); printf(".."); fprinthex(stdout, endpos , 6); printf(" -> %s: ", wavfilename); fflush(stdout); wav = fopen(wavfilename, "wb"); if(!wav) { goto error_wav; } set32lsb(wavhdr + 0x04, (uint32_t)(0x24+32*((endpos - startpos) / 9))); set32lsb(wavhdr + 0x28, (uint32_t)( 32*((endpos - startpos) / 9))); set32lsb(wavhdr + 0x18, (uint32_t)(samplerate )); set32lsb(wavhdr + 0x1C, (uint32_t)(samplerate * 2)); if(fwrite(wavhdr, 1, 0x2C, wav) != 0x2C) { goto error_wav; } for(; startpos < endpos; startpos += 9) { static const int8_t coef1[4] = { -128, -68, -6, -13 }; static const int8_t coef2[4] = { 0, 0, -15, -13 }; int32_t c1, c2; uint8_t block[9]; uint8_t shift; size_t s = fread(block, 1, 9, src); if(s != 9) { goto error_src; } shift = block[0] >> 4; c1 = coef1[(block[0] >> 2) & 3]; c2 = coef2[(block[0] >> 2) & 3]; for(s = 0; s < 16; s++) { int32_t sample = block[1 + (s >> 1)]; sample <<= 24 + 4 * (s & 1); sample >>= 28; if(shift <= 12) { sample <<= shift; sample >>= 1; } else { sample &= -0x800; } sample += (p1 << 1) + ((c1 * p1) >> 6); sample += (c2 * p2) >> 4; if(sample < -32768) { sample = -32768; } if(sample > 32767) { sample = 32767; } fputc((sample ) & 0xFF, wav); fputc((sample >> 8) & 0xFF, wav); p2 = p1; p1 = sample; } } printf("ok\n"); goto done; error_wav: printfileerror(wav, wavfilename); goto error; error_src: printfileerror(src, srcfilename); goto error; error: returncode = 1; goto done; done: if(wav) { fclose(wav); } return returncode; } //////////////////////////////////////////////////////////////////////////////// static int isvalidblock(const uint8_t* block) { if(block[0] >= 0xD0) { return 0; } if( (!block[1]) && (!block[2]) && (!block[3]) && (!block[4]) && (!block[5]) && (!block[6]) && (!block[7]) && (!block[8]) ) { return 0; } return 1; } //////////////////////////////////////////////////////////////////////////////// static int analyze( FILE* f, const char* filename, off_t* nsamples, off_t samplerate, off_t minblocks ) { int returncode = 0; clearerr(f); for(;;) { uint8_t block[9]; size_t s; off_t startpos, endpos; startpos = ftello(f); if(startpos == -1) { goto error_f; } // // Find a sample beginning // for(;; startpos += 9) { s = fread(block, 1, 9, f); if(s != 9) { if(ferror(f)) { goto error_f; } goto done; } if(!isvalidblock(block)) { continue; } break; } endpos = ftello(f); if(endpos == -1) { goto error_f; } // // Find a sample end // for(;; endpos += 9) { s = fread(block, 1, 9, f); if(s != 9) { if(ferror(f)) { goto error_f; } break; } if(!isvalidblock(block)) { break; } // end before this block if(block[0] & 1) { endpos += 9; break; } // end after this block } // // If the sample is long enough, write it out // if(((endpos - startpos) / 9) >= minblocks) { if(writewav(f, filename, startpos, endpos, samplerate)) { goto error; } (*nsamples)++; } if(fseeko(f, endpos, SEEK_SET) != 0) { goto error_f; } } error_f: printfileerror(f, filename); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int returncode = 0; off_t samplerate = 16000; off_t minblocks = 50; off_t nsamples = 0; FILE *f = NULL; int i; normalize_argv0(argv[0]); if(argc < 2) { goto usage; } if(argc >= 3) { samplerate = strtoofft(argv[2], NULL, 0); } if(argc >= 4) { minblocks = strtoofft(argv[3], NULL, 0); } if(argc >= 5) { goto usage; } f = fopen(argv[1], "rb"); if(!f) { goto error_f; } for(i = 0; i < 9; i++) { printf("Pass %d/9:\n", (int)(i + 1)); if(fseeko(f, i, SEEK_SET) != 0) { goto error_f; } if(analyze(f, argv[1], &nsamples, samplerate, minblocks)) { goto error; } } goto done; usage: banner(); printf("Usage: %s romfile [samplerate [minblocks]]\n", argv[0]); goto error; error_f: printfileerror(f, argv[1]); error: returncode = 1; goto done; done: if(nsamples) { printf("Ripped "); fprintdec(stdout, nsamples); printf(" sample%s\n", nsamples != 1 ? "s" : ""); } if(f) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/byteshuf.c0000644000175000017500000001777011731303760016337 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "byteshuf - Shuffle or unshuffle bytes in a file" #define COPYR "Copyright (C) 2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static int shuffle( int shuffling, const char* mainfile, const char** subfiles, size_t subfiles_count, int overwrite ) { int returncode = 0; size_t i; int* chars = calloc(1, sizeof(int) * subfiles_count); FILE* mf = NULL; FILE** sf = calloc(1, sizeof(FILE*) * subfiles_count); if(!sf || !chars) { printf("Error: Out of memory\n"); goto error; } if(shuffling && !overwrite) { // // Ensure main file doesn't already exist // mf = fopen(mainfile, "rb"); if(mf) { printf("Error: %s already exists (use -o to overwrite)\n", mainfile ); goto error; } } if(!shuffling && !overwrite) { // // Ensure sub files don't already exist // for(i = 0; i < subfiles_count; i++) { sf[i] = fopen(subfiles[i], "rb"); if(sf[i]) { printf("Error: %s already exists (use -o to overwrite)\n", subfiles[i] ); goto error; } } } if(shuffling) { size_t num_chars_last = subfiles_count; // // Open sub files // for(i = 0; i < subfiles_count; i++) { sf[i] = fopen(subfiles[i], "rb"); if(!sf[i]) { goto error_sf_i; } clearerr(sf[i]); } // // Open main file // mf = fopen(mainfile, "wb"); if(!mf) { goto error_mf; } clearerr(mf); for(;;) { size_t num_chars = 0; for(i = 0; i < subfiles_count; i++) { chars[i] = fgetc(sf[i]); if(chars[i] == EOF) { if(ferror(sf[i])) { goto error_sf_i; } chars[i] = 0; } else { chars[i] &= 0xFF; num_chars = i + 1; } } if(!num_chars) { break; } for(i = num_chars_last; i < subfiles_count; i++) { if(fputc(0, mf) == EOF) { goto error_mf; } } for(i = 0; i < num_chars; i++) { if(fputc(chars[i], mf) == EOF) { goto error_mf; } } num_chars_last = num_chars; } } else { // // Open main file // mf = fopen(mainfile, "rb"); if(!mf) { goto error_mf; } clearerr(mf); // // Open sub files // for(i = 0; i < subfiles_count; i++) { sf[i] = fopen(subfiles[i], "wb"); if(!sf[i]) { goto error_sf_i; } clearerr(sf[i]); } for(;;) { for(i = 0; i < subfiles_count; i++) { int c = fgetc(mf); if(c == EOF) { if(ferror(mf)) { goto error_mf; } break; } if(fputc(c & 0xFF, sf[i]) == EOF) { goto error_sf_i; } } if(i < subfiles_count) { break; } } } goto done; error_mf: printfileerror(mf, mainfile); goto error; error_sf_i: printfileerror(sf[i], subfiles[i]); goto error; error: returncode = 1; goto done; done: if(mf) { fclose(mf); } if(sf) { for(i = 0; i < subfiles_count; i++) { if(sf[i]) { fclose(sf[i]); } } free(sf); } if(chars) { free(chars); } return returncode; } //////////////////////////////////////////////////////////////////////////////// static int checkboth(int a, int b, const char* ab) { if(a && b) { printf("Error: Cannot specify both -%c and -%c\n", ab[0], ab[1]); return 1; } return 0; } static int checkeither(int a, int b, const char* ab) { if((!a) && (!b)) { printf("Error: Must specify either -%c or -%c\n", ab[0], ab[1]); return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int returncode = 0; struct { int8_t shuffle; int8_t unshuffle; int8_t overwrite; const char* mainfile; const char** files; size_t files_count; } opt; int i; normalize_argv0(argv[0]); memset(&opt, 0, sizeof(opt)); // // Check options // if(argc == 1) { goto usage; } for(i = 1; i < argc; i++) { if(argv[i][0] == '-') { // An option if(argv[i][1] == '-' && argv[i][2] == 0) { // No more options i++; break; } else if(argv[i][1] == 's' && argv[i][2] == 0) { if(opt.shuffle) { goto error_dup; } if(i >= (argc - 1)) { goto error_missing; } opt.shuffle = 1; opt.mainfile = argv[++i]; continue; } else if(argv[i][1] == 'u' && argv[i][2] == 0) { if(opt.unshuffle) { goto error_dup; } if(i >= (argc - 1)) { goto error_missing; } opt.unshuffle = 1; opt.mainfile = argv[++i]; continue; } else if(argv[i][1] == 'o' && argv[i][2] == 0) { opt.overwrite = 1; continue; } printf("Error: Unknown option: %s\n", argv[i]); goto error_usage; } else { // Not an option - stop here break; } } if(checkeither(opt.shuffle, opt.unshuffle, "su")) { goto error_usage; } if(checkboth (opt.shuffle, opt.unshuffle, "su")) { goto error_usage; } // // At least two files must be specified // opt.files = (const char**)(argv + i); opt.files_count = (argc - i); if(opt.files_count < 2) { printf("Error: Must specify at least two subfiles\n"); goto error_usage; } // // Go // if(opt.shuffle) { returncode = shuffle( 1, opt.mainfile, opt.files, opt.files_count, opt.overwrite ); } else if(opt.unshuffle) { returncode = shuffle( 0, opt.mainfile, opt.files, opt.files_count, opt.overwrite ); } goto done; error_dup: printf("Error: Specified %s twice\n", argv[i]); goto error_usage; error_missing: printf("Error: Missing parameter for %s\n", argv[i]); goto error_usage; error_usage: printf("\n"); goto usage; usage: banner(); printf( "Usage:\n" " To unshuffle: %s [-o] -u source [subfiles...]\n" " To shuffle: %s [-o] -s destination [subfiles...]\n" "\n" "Options:\n" " -o Force overwrite\n" "\n" "For example, \"%s -u abc def0 def1\" will split all the even bytes from\n" "\"abc\" into \"def0\", and the odd bytes into \"def1\".\n", argv[0], argv[0], argv[0] ); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/byteswap.c0000644000175000017500000001332311731303760016332 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "byteswap - Swap byte order of files" #define COPYR "Copyright (C) 2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static int byteswap( const char* filename, uint8_t* buf, size_t buffersize, size_t recordsize, int quiet ) { int returncode = 0; FILE* f = NULL; f = fopen(filename, "r+b"); if(!f) { goto error_f; } for(;;) { size_t rec; size_t size; // // Read // clearerr(f); size = fread(buf, 1, buffersize, f); if(size == 0) { // Check for error if(ferror(f)) { goto error_f; } // Otherwise, done break; } // // Seek backwards // if(fseeko(f, -((off_t)size), SEEK_CUR) != 0) { goto error_f; } if(size > buffersize) { size = buffersize; } if(size < buffersize) { // // Round up to the next record, filling with zeroes as we go // size_t extra = size % recordsize; if(extra) { for(; extra < recordsize; extra++) { buf[size++] = 0; } } } // // Reverse each record in memory // for(rec = 0; rec < size; rec += recordsize) { size_t a = rec; size_t b = rec + recordsize - 1; for(; a < b; a++, b--) { uint8_t t = buf[a]; buf[a] = buf[b]; buf[b] = t; } } // // Write // if(fwrite(buf, 1, size, f) != size) { goto error_f; } fflush(f); } if(!quiet) { printf("%s: Done\n", filename); } goto done; error_f: printfileerror(f, filename); goto error; error: returncode = 1; done: if(f != NULL) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int returncode = 0; unsigned long recordsize = 2; unsigned long recordsize_max = (sizeof(size_t) < sizeof(unsigned long)) ? ((unsigned long)((size_t)(-1))) : LONG_MAX; int quiet = 0; int i; uint8_t* buf = NULL; size_t buffersize = 0; size_t buffersize_min = 8192; normalize_argv0(argv[0]); // // Check options // if(argc == 1) { goto usage; } for(i = 1; i < argc; i++) { if(argv[i][0] == '-') { // An option if(argv[i][1] == '-' && argv[i][2] == 0) { // No more options i++; break; } else if(argv[i][1] == 'q' && argv[i][2] == 0) { // Quiet quiet = 1; continue; } else if(argv[i][1] == 's' && argv[i][2] == 0) { // Record size i++; if(i >= argc) { goto usage; } if(argv[i][0] == '-') { printf("Error: Record size must not be negative\n"); goto error; } if(!isdigit((int)(argv[i][0]))) { goto usage; } recordsize = strtoul(argv[i], NULL, 0); continue; } printf("Unknown option: %s\n", argv[i]); goto usage; } else { // Not an option - stop here break; } } if(i >= argc) { printf("Error: No files were specified\n"); goto usage; } if(recordsize > recordsize_max || recordsize > LONG_MAX) { printf("Error: Record size is too large\n"); goto error; } if(recordsize < 2) { printf("Error: Record size must be at least 2\n"); goto error; } // // Figure out how big the buffer should be // buffersize = ((size_t)(recordsize)); if(buffersize < buffersize_min) { buffersize = buffersize_min - ( buffersize_min % ((size_t)(recordsize)) ); } // // Allocate buffer // buf = malloc(buffersize); if(!buf) { printf("Error: Out of memory\n"); goto error; } // // Process files // for(; i < argc; i++) { if(byteswap(argv[i], buf, buffersize, (size_t)recordsize, quiet)) { returncode = 1; } } goto done; usage: banner(); printf("Swaps the byte order of each record in a file, in place.\n"); printf("\n"); printf("Usage: %s [-q] [-s recordsize] files...\n", argv[0]); printf(" -q: Quiet\n"); printf(" -s: Size, in bytes, of each record to swap (default: 2)\n"); goto error; error: returncode = 1; done: if(buf != NULL) { free(buf); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/cdpatch.c0000644000175000017500000016666511731303760016124 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "cdpatch - CD-XA image insert/extract utility" #define COPYR "Copyright (C) 2001,2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static const uint32_t max_path_depth = 256; //////////////////////////////////////////////////////////////////////////////// // // Program options // struct cdpatch_options { int8_t insert; int8_t extract; const char* binname; const char* basedir; int8_t big; int8_t little; int8_t boot; int8_t enforce_fscheck; int8_t overwrite; int8_t verbose; int8_t recurse; const char** files; int files_count; }; static const char* fsoverride = " (use -f to override)"; //////////////////////////////////////////////////////////////////////////////// static int exists(const char* filename) { FILE* f = fopen(filename, "rb"); if(f) { fclose(f); return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// static const char* oom = "Error: Out of memory\n"; //////////////////////////////////////////////////////////////////////////////// static uint32_t get32lsb(const uint8_t* p) { return (((uint32_t)(p[0])) << 0) | (((uint32_t)(p[1])) << 8) | (((uint32_t)(p[2])) << 16) | (((uint32_t)(p[3])) << 24); } static uint32_t get32msb(const uint8_t* p) { return (((uint32_t)(p[0])) << 24) | (((uint32_t)(p[1])) << 16) | (((uint32_t)(p[2])) << 8) | (((uint32_t)(p[3])) << 0); } static void set32lsb(uint8_t* p, uint32_t value) { p[0] = (uint8_t)(value >> 0); p[1] = (uint8_t)(value >> 8); p[2] = (uint8_t)(value >> 16); p[3] = (uint8_t)(value >> 24); } static void set32msb(uint8_t* p, uint32_t value) { p[0] = (uint8_t)(value >> 24); p[1] = (uint8_t)(value >> 16); p[2] = (uint8_t)(value >> 8); p[3] = (uint8_t)(value >> 0); } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero if any bytes in the array are nonzero // static int anynonzero(const uint8_t* data, size_t len) { for(; len; len--) { if(*data++) { return 1; } } return 0; } //////////////////////////////////////////////////////////////////////////////// // // Convert ISO9660 file size to sector count, rounding up // static uint32_t sectorcount(uint32_t size) { return (size >> 11) + ((size & 0x7FF) != 0); } //////////////////////////////////////////////////////////////////////////////// // // LUTs for computing ECC/EDC // static uint8_t ecc_f_lut[256]; static uint8_t ecc_b_lut[256]; static uint32_t edc_lut [256]; static void eccedc_init(void) { uint32_t i, j, edc; for(i = 0; i < 256; i++) { j = (i << 1) ^ (i & 0x80 ? 0x11D : 0); ecc_f_lut[i ] = (uint8_t)j; ecc_b_lut[i ^ j] = (uint8_t)i; edc = i; for(j = 0; j < 8; j++) { edc = (edc >> 1) ^ (edc & 1 ? 0xD8018001 : 0); } edc_lut[i] = edc; } } //////////////////////////////////////////////////////////////////////////////// // // Compute EDC for a block // static void edc_computeblock(const uint8_t* src, size_t size, uint8_t* dest) { uint32_t edc = 0; while(size--) { edc = (edc >> 8) ^ edc_lut[(edc ^ (*src++)) & 0xFF]; } set32lsb(dest, edc); } //////////////////////////////////////////////////////////////////////////////// // // Compute ECC for a block (can do either P or Q) // static void ecc_computeblock( uint8_t* src, uint32_t major_count, uint32_t minor_count, uint32_t major_mult, uint32_t minor_inc, uint8_t* dest ) { uint32_t size = major_count * minor_count; uint32_t major, minor; for(major = 0; major < major_count; major++) { uint32_t index = (major >> 1) * major_mult + (major & 1); uint8_t ecc_a = 0; uint8_t ecc_b = 0; for(minor = 0; minor < minor_count; minor++) { uint8_t temp = src[index]; index += minor_inc; if(index >= size) index -= size; ecc_a ^= temp; ecc_b ^= temp; ecc_a = ecc_f_lut[ecc_a]; } ecc_a = ecc_b_lut[ecc_f_lut[ecc_a] ^ ecc_b]; dest[major ] = ecc_a; dest[major + major_count] = ecc_a ^ ecc_b; } } // // Generate ECC P and Q codes for a block // static void ecc_generate(uint8_t* sector, int zeroaddress) { uint8_t saved_address[4]; // // Save the address and zero it out, if necessary // if(zeroaddress) { memmove(saved_address, sector + 12, 4); memset(sector + 12, 0, 4); } // // Compute ECC P code // ecc_computeblock(sector + 0xC, 86, 24, 2, 86, sector + 0x81C); // // Compute ECC Q code // ecc_computeblock(sector + 0xC, 52, 43, 86, 88, sector + 0x8C8); // // Restore the address, if necessary // if(zeroaddress) { memmove(sector + 12, saved_address, 4); } } //////////////////////////////////////////////////////////////////////////////// // // CD sync header // static const uint8_t sync_header[12] = { 0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00 }; //////////////////////////////////////////////////////////////////////////////// // // Generate ECC/EDC information for a sector (must be 2352 = 0x930 bytes) // static void eccedc_generate(uint8_t* sector) { // // Generate sync // memmove(sector, sync_header, sizeof(sync_header)); switch(sector[0x0F]) { case 0x00: // // Mode 0: no data; generate zeroes // memset(sector + 0x10, 0, 0x920); break; case 0x01: // // Mode 1: // // Compute EDC // edc_computeblock(sector + 0x00, 0x810, sector + 0x810); // // Zero out reserved area // memset(sector + 0x814, 0, 8); // // Generate ECC P/Q codes // ecc_generate(sector, 0); break; case 0x02: // // Mode 2: // // Make sure XA flags match // memmove(sector + 0x14, sector + 0x10, 4); if(!(sector[0x12] & 0x20)) { // // Form 1: Compute EDC // edc_computeblock(sector + 0x10, 0x808, sector + 0x818); // // Generate ECC P/Q codes // ecc_generate(sector, 1); } else { // // Form 2: Compute EDC // edc_computeblock(sector + 0x10, 0x91C, sector + 0x92C); } break; } } //////////////////////////////////////////////////////////////////////////////// // // Verify EDC for a sector (must be 2352 = 0x930 bytes) // Returns 0 on success // static int edc_verify(const uint8_t* sector) { uint8_t myedc[4]; // // Verify sync // if(memcmp(sector, sync_header, sizeof(sync_header))) { return 1; } switch(sector[0x0F]) { case 0x00: // // Mode 0: no data; everything had better be zero // return anynonzero(sector + 0x10, 0x920); case 0x01: // // Mode 1 // edc_computeblock(sector + 0x00, 0x810, myedc); return memcmp(myedc, sector + 0x810, 4); case 0x02: // // Mode 2: Verify that the XA type is correctly copied twice // if(memcmp(sector + 0x10, sector + 0x14, 4)) { return 1; } if(!(sector[0x12] & 0x20)) { // // Form 1 // edc_computeblock(sector + 0x10, 0x808, myedc); return memcmp(myedc, sector + 0x818, 4); } else { // // Form 2 // edc_computeblock(sector + 0x10, 0x91C, myedc); return memcmp(myedc, sector + 0x92C, 4); } } // // Invalid mode // return 1; } //////////////////////////////////////////////////////////////////////////////// struct cacheentry { uint8_t* data; uint32_t sector; uint8_t valid; }; enum { CACHE_ENTRIES = 4 }; enum { BINTYPE_UNKNOWN = 0, BINTYPE_2048 = 1, BINTYPE_2352 = 2 }; struct binfile { FILE* f; const char* name; int type; uint32_t sectors; struct cacheentry cache[CACHE_ENTRIES]; }; static void bin_quit(struct binfile* bin) { size_t i; if(bin->f) { fclose(bin->f); } for(i = 0; i < CACHE_ENTRIES; i++) { if(bin->cache[i].data) { free(bin->cache[i].data); } } } static int bin_init(struct binfile* bin) { size_t i; memset(bin, 0, sizeof(struct binfile)); for(i = 0; i < CACHE_ENTRIES; i++) { bin->cache[i].data = malloc(2352); if(!bin->cache[i].data) { printf("%s", oom); bin_quit(bin); return 1; } } return 0; } static void cache_mtf(struct binfile* bin, size_t entry) { if(entry) { struct cacheentry tmp = bin->cache[entry]; memmove(bin->cache + 1, bin->cache, sizeof(struct cacheentry) * entry); bin->cache[0] = tmp; } } static uint8_t* cache_find(struct binfile* bin, uint32_t sector) { size_t i; for(i = 0; i < CACHE_ENTRIES; i++) { if((bin->cache[i].sector == sector) && bin->cache[i].valid) { cache_mtf(bin, i); return bin->cache[0].data; } } return NULL; } static uint8_t* cache_allocbegin(struct binfile* bin, uint32_t sector) { bin->cache[CACHE_ENTRIES - 1].valid = 0; bin->cache[CACHE_ENTRIES - 1].sector = sector; return bin->cache[CACHE_ENTRIES - 1].data; } static void cache_allocend(struct binfile* bin) { cache_mtf(bin, CACHE_ENTRIES - 1); bin->cache[0].valid = 1; } //////////////////////////////////////////////////////////////////////////////// // // Detect whether image is ISO or BIN // Returns nonzero on error // static int bintype_detect(struct binfile* bin) { uint8_t* sector = NULL; off_t size; bin->type = BINTYPE_UNKNOWN; if(fseeko(bin->f, 0, SEEK_END) != 0) { goto error_bin; } size = ftello(bin->f); if(size == -1) { goto error_bin; } if(fseeko(bin->f, 0, SEEK_SET) != 0) { goto error_bin; } if(size <= 0 || ((size % 2352) != 0 && (size % 2048) != 0)) { // // Size is zero or not cleanly divisible // printf("Error: %s: Unable to determine BIN or ISO format based on size\n", bin->name ); goto error; } else if((size % 2352) != 0) { // // If indivisible by 2352, assume ISO // bin->type = BINTYPE_2048; } else if((size % 2048) != 0) { // // If indivisible by 2048, assume BIN // bin->type = BINTYPE_2352; } else { // // If divisible by both, read the first 2352 bytes and see if it's a // valid raw sector. If so, assume BIN. // sector = malloc(2352); if(!sector) { goto error_mem; } if(fread(sector, 1, 2352, bin->f) != 2352) { goto error_bin; } bin->type = edc_verify(sector) ? BINTYPE_2048 : BINTYPE_2352; } // // Figure out the number of sectors // { off_t sectorsize = (bin->type == BINTYPE_2048) ? 2048 : 2352; bin->sectors = (sizeof(off_t) > 4) ? ( ((((off_t)(size / sectorsize)) >> 31) > 1) ? ((uint32_t)(0xFFFFFFFFLU)) : ((uint32_t)(size / sectorsize)) ) : (((uint32_t)size) / ((uint32_t)sectorsize)); } goto done; error_mem: printf("%s", oom); goto error; error_bin: printfileerror(bin->f, bin->name); goto error; error: bin->type = BINTYPE_UNKNOWN; goto done; done: if(sector) { free(sector); } return (bin->type == BINTYPE_UNKNOWN); } //////////////////////////////////////////////////////////////////////////////// // // Ensure that the sector number is within the seekable range for the bin file; // returns nonzero on error // int check_bin_sector_range(const struct binfile* bin, uint32_t sector) { if(sector >= bin->sectors) { printf("Error: Sector %lu is out of range\n", (unsigned long)sector); return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// // // Returns NULL on failure // The returned buffer is valid until the next call // static uint8_t* read_raw_sector(struct binfile* bin, uint32_t sector) { uint8_t* data = NULL; if(check_bin_sector_range(bin, sector)) { goto error; } if(bin->type != BINTYPE_2352) { printf("Error: Tried to read raw sector from ISO\n"); goto error; } data = cache_find(bin, sector); if(!data) { data = cache_allocbegin(bin, sector); if(fseeko(bin->f, 2352 * ((off_t)sector), SEEK_SET) != 0) { goto error_f; } if(fread(data, 1, 2352, bin->f) != 2352) { goto error_f; } cache_allocend(bin); } return data; error_f: printf("At sector %lu: ", (unsigned long)sector); printfileerror(bin->f, bin->name); goto error; error: return NULL; } //////////////////////////////////////////////////////////////////////////////// // // Returns NULL on failure // The returned buffer is valid until the next call // static uint8_t* read_cooked_sector( struct binfile* bin, uint32_t sector, const struct cdpatch_options* opt ) { uint8_t* data = NULL; if(check_bin_sector_range(bin, sector)) { goto error; } data = cache_find(bin, sector); if(!data) { data = cache_allocbegin(bin, sector); if(bin->type == BINTYPE_2048) { if(fseeko(bin->f, 2048 * ((off_t)sector), SEEK_SET) != 0) { goto error_f; } if(fread(data, 1, 2048, bin->f) != 2048) { goto error_f; } } else { if(fseeko(bin->f, 2352 * ((off_t)sector), SEEK_SET) != 0) { goto error_f; } if(fread(data, 1, 2352, bin->f) != 2352) { goto error_f; } // // Verify the EDC // if(edc_verify(data)) { if(opt->enforce_fscheck || opt->verbose) { printf("%s: CD sector %lu is corrupt%s\n", opt->enforce_fscheck ? "Error" : "Warning", (unsigned long)sector, opt->enforce_fscheck ? fsoverride : "" ); } if(opt->enforce_fscheck) { goto error; } } } cache_allocend(bin); } if(bin->type == BINTYPE_2352) { // // Figure out where the data actually resides in the sector // switch(data[0xF]) { case 1: data += 0x10; break; case 2: if(data[0x12] & 0x20) { if(opt->enforce_fscheck || opt->verbose) { printf("%s: Attempted to read Form 2 sector %lu%s\n", opt->enforce_fscheck ? "Error" : "Warning", (unsigned long)sector, opt->enforce_fscheck ? fsoverride : "" ); } if(opt->enforce_fscheck) { goto error; } } data += 0x18; break; default: if(opt->enforce_fscheck || opt->verbose) { printf("%s: Invalid mode 0x%02X at sector %lu%s\n", opt->enforce_fscheck ? "Error" : "Warning", (int)data[0xF], (unsigned long)sector, opt->enforce_fscheck ? fsoverride : "" ); if(opt->enforce_fscheck) { goto error; } } data += 0x10; // assume mode 1 break; } } return data; error_f: printf("At sector %lu: ", (unsigned long)sector); printfileerror(bin->f, bin->name); goto error; error: return NULL; } //////////////////////////////////////////////////////////////////////////////// // // Allocate space for a cooked sector, with the understanding that we will // overwrite all of it // // Returns NULL on failure // The returned buffer is valid until the next call // static uint8_t* alloc_cooked_sector( struct binfile* bin, uint32_t sector, const struct cdpatch_options* opt ) { if(bin->type == BINTYPE_2048) { uint8_t* data; if(check_bin_sector_range(bin, sector)) { return NULL; } // // Just allocate space and not initialize it // data = cache_find(bin, sector); if(!data) { data = cache_allocbegin(bin, sector); cache_allocend(bin); } return data; } else { // // We need to read the sector anyway, so just read it // return read_cooked_sector(bin, sector, opt); } } //////////////////////////////////////////////////////////////////////////////// // // Returns 0 on success // static int writeback_raw_sector(struct binfile* bin, uint32_t sector) { int returncode = 0; const uint8_t* data; if(check_bin_sector_range(bin, sector)) { goto error; } if(bin->type != BINTYPE_2352) { printf("Error: Tried to write raw sector to ISO\n"); goto error; } data = cache_find(bin, sector); if(!data) { printf("Error: Sector not in cache\n"); goto error; } // // Seek and write // if(fseeko(bin->f, 2352 * ((off_t)sector), SEEK_SET) != 0) { goto error_f; } if(fwrite(data, 1, 2352, bin->f) != 2352) { goto error_f; } fflush(bin->f); goto done; error_f: printf("At sector %lu: ", (unsigned long)sector); printfileerror(bin->f, bin->name); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// // // Returns 0 on success // static int writeback_cooked_sector( struct binfile* bin, uint32_t sector, int redoflags, int last ) { int returncode = 0; uint8_t* data; if(check_bin_sector_range(bin, sector)) { goto error; } data = cache_find(bin, sector); if(!data) { printf("Error: Sector not in cache\n"); goto error; } if(bin->type == BINTYPE_2048) { // // If this is an ISO file, just seek and write directly // if(fseeko(bin->f, 2048 * ((off_t)sector), SEEK_SET) != 0) { goto error_f; } if(fwrite(data, 1, 2048, bin->f) != 2048) { goto error_f; } } else { // // If mode 2, and we care about the XA flags, set those up // if(redoflags && (data[0xF] == 2)) { data[0x10] = data[0x14] = 0; data[0x11] = data[0x15] = 0; data[0x12] = data[0x16] = 0x08 | (last ? 0x81 : 0x00); data[0x13] = data[0x17] = 0; } // // Regenerate ECC/EDC // eccedc_generate(data); // // Seek and write // if(fseeko(bin->f, 2352 * ((off_t)sector), SEEK_SET) != 0) { goto error_f; } if(fwrite(data, 1, 2352, bin->f) != 2352) { goto error_f; } } fflush(bin->f); goto done; error_f: printf("At sector %lu: ", (unsigned long)sector); printfileerror(bin->f, bin->name); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// // // Read or write arbitrary cooked data; returns nonzero on error // static int rw_cooked_data( struct binfile* bin, uint32_t sector, uint32_t offset, uint8_t* data, size_t size, const struct cdpatch_options* opt, int write ) { int returncode = 0; // // Normalize sector/offset, and verify the range // if((offset >> 11) > (0xFFFFFFFFLU - sector)) { goto error_range; } sector += offset >> 11; offset &= 0x7FF; if(check_bin_sector_range(bin, sector)) { goto error; } if(bin->type == BINTYPE_2048) { // // Read or write the image file directly // if(fseeko( bin->f, 2048 * ((off_t)sector) + ((off_t)offset), SEEK_SET ) != 0) { goto error_f; } if(write) { if(fwrite(data, 1, size, bin->f) != size) { goto error_f; } } else { if(fread (data, 1, size, bin->f) != size) { goto error_f; } } } else { // // Read or write sector-by-sector // for(; size; sector++) { size_t insector = 0x800 - offset; size_t z = size < insector ? size : insector; uint8_t* d = read_cooked_sector(bin, sector, opt); if(!d) { goto error; } if(write) { memmove(d + offset, data, z); if(writeback_cooked_sector(bin, sector, 0, 0)) { goto error; } } else { memmove(data, d + offset, z); } data += z; size -= z; offset = 0; if(size && (sector == 0xFFFFFFFFLU)) { goto error_range; } } } goto done; error_f: printf("At sector %lu: ", (unsigned long)sector); printfileerror(bin->f, bin->name); goto error; error_range: printf("Error: %s out of range: sector=%lu offset=%lu\n", write ? "Write" : "Read", (unsigned long)sector, (unsigned long)offset ); goto error; error: returncode = 1; done: return returncode; } static int read_cooked_data( struct binfile* bin, uint32_t sector, uint32_t offset, uint8_t* data, size_t size, const struct cdpatch_options* opt ) { return rw_cooked_data(bin, sector, offset, data, size, opt, 0); } static int write_cooked_data( struct binfile* bin, uint32_t sector, uint32_t offset, const uint8_t* data, size_t size, const struct cdpatch_options* opt ) { return rw_cooked_data(bin, sector, offset, (uint8_t*)data, size, opt, 1); } //////////////////////////////////////////////////////////////////////////////// // // Use RIFF if: // - The sector is mode 0, or invalid // - The sector is mode 2 and any of the flag bits besides 'data', 'last sector // of data record', or 'last sector of file' are set. // static int should_use_riff_format(const uint8_t* sector) { if(sector[0xF] == 1) { return 0; } if(sector[0xF] == 2) { return ( sector[0x10] != 0) || ( sector[0x11] != 0) || ((sector[0x12] & 0x76) != 0) || ( sector[0x13] != 0); } return 1; } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero on error // static int extract_file( struct binfile* bin, uint32_t sector, uint32_t filesize, time_t modtime, const char* filename, const struct cdpatch_options* opt ) { int returncode = 0; FILE* f = NULL; uint8_t* data = NULL; if(!opt->overwrite && exists(filename)) { printf("Error: %s already exists (use -o to override)\n", filename); goto error; } f = fopen(filename, "wb"); if(!f) { goto error_f; } // // Check for RIFF format // if(bin->type == BINTYPE_2352) { data = read_raw_sector(bin, sector); if(!data) { goto error; } } if(data && should_use_riff_format(data)) { // // Extract in RIFF format // uint32_t sectors = sectorcount(filesize); if(sectors > 1826091LU) { sectors = 1826091LU; // Exceeds uint32_t - just cap it } if(opt->verbose) { printf( "Extract %7lu %10lu %s (CDXA)\n", (unsigned long)sector, (unsigned long)(2352 * sectors + 0x2C), filename ); } // // Write header // { uint8_t hdr[0x2C]; memset(hdr, 0, sizeof(hdr)); memmove (hdr + 0x00, "RIFF", 4); set32lsb(hdr + 0x04, 2352 * sectors + 0x2C); memmove (hdr + 0x08, "CDXA", 4); set32lsb(hdr + 0x0C, 2352 * sectors); if(fwrite(hdr, 1, 0x2C, f) != 0x2C) { goto error_f; } } // // Write contents // for(; sectors; sector++, sectors--) { data = read_raw_sector(bin, sector); if(!data) { goto error; } if(edc_verify(data)) { if(opt->enforce_fscheck || opt->verbose) { printf("%s: %s: CD sector %lu is corrupt%s\n", opt->enforce_fscheck ? "Error" : "Warning", filename, (unsigned long)sector, opt->enforce_fscheck ? fsoverride : "" ); } if(opt->enforce_fscheck) { goto error; } } if(fwrite(data, 1, 2352, f) != 2352) { goto error_f; } } } else { if(opt->verbose) { printf( "Extract %7lu %10lu %s\n", (unsigned long)sector, (unsigned long)filesize, filename ); } // // Extract normally // for(; filesize; sector++) { size_t remain = filesize < 2048 ? filesize : 2048; data = read_cooked_sector(bin, sector, opt); if(!data) { goto error; } if(fwrite(data, 1, remain, f) != remain) { goto error_f; } filesize -= remain; } } if(f) { fclose(f); f = NULL; } // // Set modification time, if it was valid // if(modtime != ((time_t)(-1))) { struct utimbuf b; b.actime = modtime; b.modtime = modtime; if(utime((char*)filename, &b) != 0) { // Silently fail - preserving modtime shouldn't be considered critical } } goto done; error_f: printfileerror(f, filename); goto error; error: returncode = 1; goto done; done: if(f) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero on error // Outputs the new size in *filesize // static int insert_file( struct binfile* bin, uint32_t sector, uint32_t* filesize, const char* filename, const struct cdpatch_options* opt ) { int returncode = 0; uint8_t* data = NULL; FILE* f = NULL; uint32_t newfilesize; uint32_t sectors = sectorcount(*filesize); f = fopen(filename, "rb"); if(!f) { goto error_f; } // // Get the replacement file size // { off_t size; if(fseeko(f, 0, SEEK_END) != 0) { goto error_f; } size = ftello(f); if(size == -1) { goto error_f; } if(fseeko(f, 0, SEEK_SET) != 0) { goto error_f; } // Verify size is not out of uint32_t range if(sizeof(size) > 4 && (size >> 31) > 1) { printf("Error: %s: Too large for ISO9660 (> 4GiB)\n", filename); goto error; } newfilesize = (uint32_t)size; } // // Check for RIFF format // if(bin->type == BINTYPE_2352) { data = read_raw_sector(bin, sector); if(!data) { goto error; } } if(data && should_use_riff_format(data)) { // // Insert in RIFF format // if(sectors > 1826091LU) { sectors = 1826091LU; // Exceeds uint32_t - just cap it } if(opt->verbose) { printf( "Insert %7lu %10lu %s (CDXA)\n", (unsigned long)sector, (unsigned long)newfilesize, filename ); } if( (newfilesize < 0x2C) || ((newfilesize - 0x2C) % 2352) != 0 ) { printf("Error: %s: CDXA file has invalid size\n", filename); goto error; } // // Make sure we're not expanding the file, at all // if(newfilesize > (2352 * sectors + 0x2C)) { printf("Error: %s: Cannot expand CDXA data beyond %lu bytes\n", filename, (unsigned long)(2352 * sectors) ); goto error; } // // Read and verify header // { uint8_t hdr[0x2C]; if(fread(hdr, 1, 0x2C, f) != 0x2C) { goto error_f; } if( memcmp(hdr + 0x00, "RIFF", 4) || memcmp(hdr + 0x08, "CDXA", 4) || anynonzero(hdr + 0x10, 0x1C) ) { printf("Error: %s: RIFF header is invalid\n", filename); goto error; } if( get32lsb(hdr + 0x04) != (newfilesize ) || get32lsb(hdr + 0x0C) != (newfilesize - 0x2C) ) { printf("Error: %s: RIFF header mismatches actual file size\n", filename ); goto error; } } // // Read contents // newfilesize -= 0x2C; *filesize = (newfilesize / 2352) * 2048; for(; newfilesize >= 2352; sector++) { data = read_raw_sector(bin, sector); if(!data) { goto error; } // Ignore sync and address if(fread(data + 0x00F, 1, 0x00F, f) != 0x00F) { goto error_f; } // Read mode and everything else if(fread(data + 0x00F, 1, 0x921, f) != 0x921) { goto error_f; } // Regenerate sync and ECC/EDC memmove(data, sync_header, sizeof(sync_header)); eccedc_generate(data); if(writeback_raw_sector(bin, sector)) { goto error; } newfilesize -= 2352; } } else { // // Make sure we're not expanding the file too much // uint32_t bytelimit = (sectors >= 0x200000LU) ? ((uint32_t)(0xFFFFFFFFLU)) : ((uint32_t)(sectors << 11)); if(newfilesize > bytelimit) { printf("Error: %s: Cannot expand file beyond %lu bytes\n", filename, (unsigned long)bytelimit ); goto error; } if(opt->verbose) { printf( "Insert %7lu %10lu %s\n", (unsigned long)sector, (unsigned long)newfilesize, filename ); } // // Insert normally // *filesize = newfilesize; for(; newfilesize; sector++) { size_t remain = newfilesize < 2048 ? newfilesize : 2048; data = alloc_cooked_sector(bin, sector, opt); if(!data) { goto error; } if(fread(data, 1, remain, f) != remain) { goto error_f; } if(remain < 2048) { memset(data + remain, 0, 2048 - remain); } if(writeback_cooked_sector(bin, sector, 1, newfilesize <= 2048)) { goto error; } newfilesize -= remain; } } goto done; error_f: printfileerror(f, filename); goto error; error: returncode = 1; goto done; done: if(f) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// // // ISO9660 data structure offsets // enum { PD_type = 0, PD_id = 1, PD_version = 6, PD_unused1 = 7, PD_system_id = 8, PD_volume_id = 40, PD_unused2 = 72, PD_volume_space_size = 80, PD_unused3 = 88, PD_volume_set_size = 120, PD_volume_sequence_number = 124, PD_logical_block_size = 128, PD_path_table_size = 132, PD_type_l_path_table = 140, PD_opt_type_l_path_table = 144, PD_type_m_path_table = 148, PD_opt_type_m_path_table = 152, PD_root_dir_record = 156, PD_volume_set_id = 190, PD_publisher_id = 318, PD_preparer_id = 446, PD_application_id = 574, PD_copyright_file_id = 702, PD_abstract_file_id = 739, PD_bibliographic_file_id = 776, PD_creation_date = 813, PD_modification_date = 830, PD_expiration_date = 847, PD_effective_date = 864, PD_file_structure_version = 881, PD_unused4 = 882, PD_application_data = 883, PD_unused5 = 1395 }; enum { DR_length = 0, DR_ext_attr_length = 1, DR_extent = 2, DR_size = 10, DR_date = 18, DR_flags = 25, DR_file_unit_size = 26, DR_interleave = 27, DR_volume_sequence_number = 28, DR_name_len = 32, DR_name = 33 }; //////////////////////////////////////////////////////////////////////////////// static void printsafestring(const uint8_t* src, size_t size) { size_t i; for(i = 0; i < size; i++) { int c = src[i]; if(!c) { break; } if(isprint(c)) { fputc(c, stdout); } } } //////////////////////////////////////////////////////////////////////////////// // // Node: Info about a ISO9660 directory or file // struct node { // // Location of the ISO DR representing this node // uint32_t dr_sector; uint32_t dr_ofs; // // Info copied from the ISO DR // uint8_t name[256]; int8_t isdir; uint32_t sector; uint32_t size; time_t modtime; // // Internal data // uint32_t depth; struct node* up; // // Current state, if this is a directory and we're reading it // uint32_t dirread; }; static void rewindnode(struct node* n) { n->dirread = 0; } static void freesubnodes(struct node* n, struct node* root) { while(n && n != root) { struct node* up = n->up; free(n); n = up; } } static void printnodename(struct node* n) { struct node* prev = NULL; // // Special case root directory // if(n && !n->up) { printf("/"); } else { int num = 0; // // Momentarily reverse node order // while(n) { struct node* up = n->up; n->up = prev; prev = n; n = up; } n = prev; prev = NULL; // // Reverse node order again while printing names // while(n) { struct node* up = n->up; n->up = prev; if(strcmp((const char*)(n->name), ".")) { if(num++) { printf("/"); } printsafestring(n->name, strlen((const char*)(n->name))); } prev = n; n = up; } } } static size_t nodenamelen(const struct node* n) { size_t len = 0; for(; n && n->up; n = n->up) { len += strlen((const char*)(n->name)); if(n->up->up) { len++; // directory separator } } return len; } static void copynodename(char* end, const struct node* n) { for(; n && n->up; n = n->up) { size_t len = strlen((const char*)(n->name)); memmove(end - len, n->name, len); end -= len; if(n->up->up) { *(--end) = '/'; } } } //////////////////////////////////////////////////////////////////////////////// // // Read an ISO9660 directory record // // Returns the number of bytes in the record, 0 on end, or -1 on error // static int read_iso_dr( struct binfile* bin, struct node* n, uint32_t sector, uint32_t ofs, uint32_t size, const struct cdpatch_options* opt ) { uint8_t dr[256]; uint32_t little; uint32_t big; size_t i, namelen; n->dr_sector = sector; n->dr_ofs = ofs; n->name[0] = 0; n->isdir = 0; n->sector = 0; n->size = 0; n->modtime = (time_t)(-1); rewindnode(n); if(ofs >= size) { return 0; } // // Read DR length // if(read_cooked_data(bin, sector, ofs, dr, 1, opt)) { return -1; } if(dr[DR_length] == 0) { return 0; } if(dr[DR_length] > (size - ofs)) { dr[DR_length] = (uint8_t)(size - ofs); goto malformed; } if(dr[DR_length] < DR_name) { goto malformed; } // // Read DR // if(read_cooked_data(bin, sector, ofs+1, dr+1, dr[DR_length]-1, opt)) { return -1; } if(dr[DR_name_len] > (dr[DR_length] - DR_name)) { goto malformed; } if(dr[DR_name_len] == 0) { goto malformed; } namelen = dr[DR_name_len]; // // Get name (but don't normalize yet) // memmove(n->name, dr + DR_name, namelen); n->name[namelen] = 0; // // Get directory flag // n->isdir = (dr[DR_flags] & 0x02) != 0; // // Normalize name, checking it for errors in the process // if(namelen == 1 && n->name[0] == 0) { n->name[0] = '.'; } else if(namelen == 1 && n->name[0] == 1) { n->name[0] = '.'; n->name[1] = '.'; n->name[2] = 0; namelen = 2; } else { for(i = 0; i < namelen; i++) { uint8_t c = n->name[i]; if( (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_') ) { // acceptable character } else if(c >= 'A' && c <= 'Z') { // uppercase alpha - convert to lowercase c += ('a' - 'A'); } else if(c == '.') { // if the next character is the end, or version number, then // eat the dot if(n->name[i + 1] == 0 || n->name[i + 1] == ';') { memmove(n->name + i, n->name + i + 1, namelen - i); namelen--; i--; continue; } } else if(c == ';') { // semicolon - strip the rest of the name if ";1" if(i == (namelen - 2) && n->name[i + 1] == '1') { c = 0; namelen = i; } } else { // not ok - just replace with an underscore c = '_'; } n->name[i] = c; } } // // Get sector // little = get32lsb(dr + DR_extent + 0); big = get32msb(dr + DR_extent + 4); if(little == big || opt->little) { n->sector = little; } else if(opt->big) { n->sector = big; } else { goto error_mismatch; } // // Get size // little = get32lsb(dr + DR_size + 0); big = get32msb(dr + DR_size + 4); if(little == big || opt->little) { n->size = little; } else if(opt->big) { n->size = big; } else { goto error_mismatch; } // // Get modified time // { int32_t year = ((uint8_t)(dr[DR_date + 0])); int32_t month = ((uint8_t)(dr[DR_date + 1])); int32_t day = ((uint8_t)(dr[DR_date + 2])); int32_t hour = ((uint8_t)(dr[DR_date + 3])); int32_t minute = ((uint8_t)(dr[DR_date + 4])); int32_t second = ((uint8_t)(dr[DR_date + 5])); int32_t gmtofs = (( int8_t)(dr[DR_date + 6])); year -= 70; // year = Years since 1970 if(year < 0) { // Before 1970: Invalid n->modtime = (time_t)(-1); } else { int32_t i; // Calculate modtime = days since 1970 n->modtime = year; n->modtime *= 365; // Adjust for leap years if(year > 2) { n->modtime += (year + 1) / 4; } if(((((year+2) % 4)) == 0) && (month > 2)) { n->modtime += 1; } // Add days from previous months for(i = 1; i < month; i++) { static const int32_t md[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; n->modtime += md[i - 1]; } // Add days from this month n->modtime += day - 1; // Multiply out modtime from days into seconds n->modtime *= 24; n->modtime += hour; n->modtime *= 60; n->modtime += minute; n->modtime *= 60; n->modtime += second; // Adjust modtime into GMT using the provided offset if(gmtofs >= -52 && gmtofs <= 52) { n->modtime -= gmtofs * 15 * 60; } } } // // Success: Return the length of the directory record // return dr[DR_length]; malformed: if(opt->enforce_fscheck || opt->verbose) { printf("%s: ", opt->enforce_fscheck ? "Error" : "Warning" ); printnodename(n); printf(": Malformed directory record%s\n", opt->enforce_fscheck ? fsoverride : "" ); } if(opt->enforce_fscheck) { return -1; } return dr[DR_length]; error_mismatch: printf("Error: "); printnodename(n); printf(": Mismatched little vs. big-endian metadata\n"); printf("Use -le or -be to override\n"); return -1; } //////////////////////////////////////////////////////////////////////////////// // // Get the next directory entry in a directory // Returns nonzero on error // Returns zero, but NULL node, if nothing was found // static int findnext( struct binfile* bin, struct node* n, struct node** out, const struct cdpatch_options* opt ) { int returncode = 0; // // Allocate a new node // *out = malloc(sizeof(struct node)); if(!(*out)) { goto error_mem; } (*out)->up = n; (*out)->depth = n->depth + 1; // // Read node data from DR // returncode = read_iso_dr(bin, *out, n->sector, n->dirread, n->size, opt); if(returncode < 0) { goto error; } if(returncode == 0) { goto notfound; } // // Advance // n->dirread += returncode; returncode = 0; goto done; error_mem: printf("%s", oom); goto error; error: returncode = 1; goto notfound; notfound: if(*out) { free(*out); *out = NULL; } goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// static int pathsep(char c) { return c == '/' || c == '\\'; } static int pathend(char c) { return c == 0 || pathsep(c); } //////////////////////////////////////////////////////////////////////////////// // // Pass f=NULL to get the boot area // static void dofile( struct binfile* bin, struct node* filenode, const struct cdpatch_options* opt, int automatic, uint32_t* numerrors, uint32_t* numsuccesses ) { // // Construct base filename from base name and node name // char* filename = NULL; size_t basedirlen = strlen(opt->basedir); size_t addsep = !(basedirlen && pathsep(opt->basedir[basedirlen - 1])); size_t filenamelen = basedirlen + addsep + (filenode ? nodenamelen(filenode) : 4); filename = malloc(filenamelen + 1); if(!filename) { goto error_mem; } memmove(filename, opt->basedir, basedirlen); if(addsep) { filename[basedirlen] = '/'; } if(filenode) { copynodename(filename + filenamelen, filenode); } else { memmove(filename + filenamelen - 4, "boot", 4); } filename[filenamelen] = 0; if(opt->extract) { // // Ensure that all parent directories are created // char* t = filename; while(*t) { while(pathsep(*t)) { t++; } while(!pathend(*t)) { t++; } if(pathsep(*t)) { char c = *t; *t = 0; mkdir(filename); // OK if it doesn't succeed *t = c; } } // // Extract // if(filenode) { if(extract_file( bin, filenode->sector, filenode->size, filenode->modtime, filename, opt )) { goto error; } } else { if(extract_file(bin, 0, 32768, (time_t)(-1), filename, opt)) { goto error; } } (*numsuccesses)++; } else if(opt->insert && (!automatic || exists(filename))) { // // Insert // if(filenode) { uint32_t newsize = filenode->size; if(insert_file(bin, filenode->sector, &newsize, filename, opt)) { goto error; } // // If the size changed, update the size in the DR // if(newsize != filenode->size) { uint8_t sz[8]; set32lsb(sz + 0, newsize); set32msb(sz + 4, newsize); if(write_cooked_data( bin, filenode->dr_sector, filenode->dr_ofs + DR_size, sz, 8, opt )) { goto error; } } } else { uint32_t newsize = 32768; if(insert_file(bin, 0, &newsize, filename, opt)) { goto error; } } (*numsuccesses)++; } goto done; error_mem: printf("%s", oom); goto error; error: (*numerrors)++; goto done; done: if(filename) { free(filename); } } //////////////////////////////////////////////////////////////////////////////// // // Recursively walk a directory // static void walkdirectory( struct binfile* bin, struct node* root, const struct cdpatch_options* opt, uint32_t* numerrors, uint32_t* numsuccesses ) { struct node* n = root; struct node* f = NULL; rewindnode(n); for(;;) { if(findnext(bin, n, &f, opt)) { goto error; } if(!f) { if(n == root) { // Done with entire tree walk break; } else { // Back to previous directory f = n; n = n->up; freesubnodes(f, n); f = NULL; } } else if(!f->name[0]) { // // Probably a malformed entry which was ignored // } else if(f->isdir) { if( strcmp((const char*)(f->name), ".") && strcmp((const char*)(f->name), "..") ) { // Ensure this directory didn't appear anywhere up the chain struct node* t; for(t = n; t != root; t = t->up) { if(t->sector == f->sector) { break; } } if(t->sector == f->sector) { if(opt->enforce_fscheck || opt->verbose) { printf("%s: Infinite recursion: ", opt->enforce_fscheck ? "Error" : "Warning" ); printnodename(f); printf(" points to "); printnodename(t); printf("%s\n", opt->enforce_fscheck ? fsoverride : "" ); } if(opt->enforce_fscheck) { goto error; } // Ignore the error, but we still can't descend into it } else { // Check depth limit. // Allow out-of-ISO9660 spec, but impose our own limit if(f->depth > max_path_depth) { printf("Error: "); printnodename(f); printf(": Path is too deep\n"); goto error; } // Descend into this directory n = f; } } } else { // // This is a file // dofile(bin, f, opt, 1, numerrors, numsuccesses); } freesubnodes(f, n); f = NULL; } goto done; error: (*numerrors)++; goto done; done: freesubnodes(f, n); freesubnodes(n, root); } //////////////////////////////////////////////////////////////////////////////// static int arenamesequal(const char* a, const char* b) { for(;;) { int ca = (*a++) & 0xff; int cb = (*b++) & 0xff; if(pathend(ca) && pathend(cb)) { return 1; } if(pathend(ca)) { return 0; } if(pathend(cb)) { return 0; } ca = tolower(ca); cb = tolower(cb); if(ca != cb) { return 0; } } } //////////////////////////////////////////////////////////////////////////////// // // Find a file or directory in the ISO9660 filesystem // Returns NULL if not found // static struct node* findnode( struct binfile* bin, struct node* root, const char* filename, const struct cdpatch_options* opt ) { struct node* n = root; struct node* f = NULL; const char* p = filename; const char* next = p; while(pathsep(*p)) { p++; } for(; *p; p = next) { // // Figure out the next path component, if any // next = p; while(!pathend(*next)) { next++; } while(pathsep(*next)) { next++; } // // Special case "." and ".." // if(p[0] == '.' && pathend(p[1])) { continue; } if(p[0] == '.' && p[1] == '.' && pathend(p[2])) { if(n != root && n->up) { f = n; n = n->up; freesubnodes(f, n); f = NULL; } continue; } // // Find n = path component p in directory node n // rewindnode(n); for(;;) { if(findnext(bin, n, &f, opt)) { goto error; } if(!f) { goto error_pathnotfound; } if( arenamesequal(p, (const char*)(f->name)) && (f->isdir || !(*next)) ) { n = f; break; } freesubnodes(f, n); f = NULL; } } return n; error_pathnotfound: printf("Error: %s: Path not found in ISO\n", filename); goto error; error: freesubnodes(f, n); freesubnodes(n, root); return NULL; } //////////////////////////////////////////////////////////////////////////////// static void visit_arg( struct binfile* bin, struct node* root, const char* filename, const struct cdpatch_options* opt, uint32_t* numerrors, uint32_t* numsuccesses ) { struct node* n = NULL; // // First, find the node in the ISO9660 filesystem // n = findnode(bin, root, filename, opt); if(!n) { goto error; } if(n->isdir) { // // If it's a directory: // // If we're not recursing, that's an error // if(!opt->recurse) { printf("Error: %s: Is a directory\n", filename); goto error; } // // Walk the directory // walkdirectory(bin, n, opt, numerrors, numsuccesses); } else { // // If it's a file, visit it // dofile(bin, n, opt, 0, numerrors, numsuccesses); } goto done; error: (*numerrors)++; goto done; done: freesubnodes(n, root); } //////////////////////////////////////////////////////////////////////////////// static int cdpatch(const struct cdpatch_options* opt) { int returncode = 0; struct binfile bin; struct node* root = NULL; int i; uint32_t numerrors = 0; uint32_t numsuccesses = 0; if(bin_init(&bin)) { goto error; } bin.name = opt->binname; // // Attempt to open bin/iso file // bin.f = fopen(bin.name, opt->insert ? "r+b" : "rb"); if(!bin.f) { goto error_bin; } if(bintype_detect(&bin)) { goto error; } if(opt->verbose) { printf("Image file: %s\n", opt->binname); printf("Format: "); switch(bin.type) { case BINTYPE_2048: printf("ISO (2048-byte sectors)\n"); break; case BINTYPE_2352: printf("BIN (2352-byte sectors)\n"); break; } } // // Read primary descriptor // { uint8_t* data = read_cooked_sector(&bin, 16, opt); if(!data) { goto error; } if(opt->verbose) { printf("System ID: "); printsafestring(data + PD_system_id, 32); printf("\nVolume ID: "); printsafestring(data + PD_volume_id, 32); printf("\n"); } } // // Insert or extract boot area, if desired // if(opt->boot) { dofile(&bin, NULL, opt, 0, &numerrors, &numsuccesses); } // // Retrive root directory info // root = malloc(sizeof(struct node)); if(!root) { goto error_mem; } root->depth = 0; root->up = NULL; i = read_iso_dr(&bin, root, 16, PD_root_dir_record, 2048, opt); if(i < 0) { goto error; } if(i == 0) { printf("Error: Root directory descriptor is missing\n"); goto error; } // // Visit each of the arguments // for(i = 0; i < opt->files_count; i++) { const char* file = opt->files[i]; if(*file) { // If non-empty visit_arg(&bin, root, file, opt, &numerrors, &numsuccesses); } } if(numsuccesses || !numerrors) { printf("%lu file%s %s\n", (unsigned long)numsuccesses, numsuccesses != 1 ? "s" : "", opt->extract ? "extracted" : "inserted" ); } if(numerrors) { printf("%lu error%s encountered\n", (unsigned long)numerrors, numerrors != 1 ? "s" : "" ); } returncode = (numerrors != 0); goto done; error_mem: printf("%s", oom); goto error; error_bin: printfileerror(bin.f, bin.name); goto error; error: returncode = 1; goto done; done: if(root) { free(root); } bin_quit(&bin); return returncode; } //////////////////////////////////////////////////////////////////////////////// static int checkboth(int a, int b, const char* opa, const char* opb) { if(a && b) { printf("Error: Cannot specify both %s and %s\n", opa, opb); return 1; } return 0; } static int checkeither(int a, int b, const char* opa, const char* opb) { if((!a) && (!b)) { printf("Error: Must specify either %s or %s\n", opa, opb); return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int returncode = 0; static const char* default_files[1] = { "." }; static const int default_files_count = 1; const char* warn_missing = NULL; struct cdpatch_options opt; int i; normalize_argv0(argv[0]); memset(&opt, 0, sizeof(opt)); // // Enforce filesystem checks by default (unless overridden with -f) // opt.enforce_fscheck = 1; // // Check options // if(argc == 1) { goto usage; } for(i = 1; i < argc; i++) { if(argv[i][0] == '-') { // An option if(!strcmp(argv[i], "--")) { // No more options i++; break; } else if(!strcmp(argv[i], "-i")) { if(opt.insert) { goto error_dup; } if(i >= (argc - 1)) { goto error_missing; } if(argv[i+1][0] == '-') { warn_missing = argv[i]; } opt.insert = 1; opt.binname = argv[++i]; continue; } else if(!strcmp(argv[i], "-x")) { if(opt.extract) { goto error_dup; } if(i >= (argc - 1)) { goto error_missing; } if(argv[i+1][0] == '-') { warn_missing = argv[i]; } opt.extract = 1; opt.binname = argv[++i]; continue; } else if(!strcmp(argv[i], "-d")) { if(opt.basedir) { goto error_dup; } if(i >= (argc - 1)) { goto error_missing; } if(argv[i+1][0] == '-') { warn_missing = argv[i]; } opt.basedir = argv[++i]; continue; } else if(!strcmp(argv[i], "-be")) { opt.big = 1; continue; } else if(!strcmp(argv[i], "-le")) { opt.little = 1; continue; } else if(!strcmp(argv[i], "-boot")) { opt.boot = 1; continue; } else if(!strcmp(argv[i], "-f")) { opt.enforce_fscheck = 0; continue; } else if(!strcmp(argv[i], "-o")) { opt.overwrite = 1; continue; } else if(!strcmp(argv[i], "-v")) { opt.verbose = 1; continue; } else if(!strcmp(argv[i], "-r")) { opt.recurse = 1; continue; } printf("Unknown option: %s\n", argv[i]); goto error_usage; } else { // Not an option - stop here break; } } if(checkeither(opt.insert, opt.extract ,"-i","-x")) { goto error_usage; } warn_missing = NULL; if(checkboth (opt.big , opt.little ,"-be","-le")) { goto error_usage; } if(checkboth (opt.insert, opt.extract ,"-i","-x")) { goto error_usage; } if(checkboth (opt.insert, opt.overwrite,"-i","-o")) { goto error_usage; } // // If base directory wasn't specified, default to "." // if(!opt.basedir) { opt.basedir = "."; } // // If no files or -boot were specified, default to "-r ." // if(i >= argc && !opt.boot) { opt.recurse = 1; opt.files = default_files; opt.files_count = default_files_count; } else { opt.files = (const char**)(argv + i); opt.files_count = (argc - i); } // // Initialize ECC/EDC tables // eccedc_init(); // // Go // returncode = cdpatch(&opt); goto done; error_dup: printf("Error: Specified %s twice\n", argv[i]); goto error_usage; error_missing: printf("Error: Missing parameter for %s\n", argv[i]); goto error_usage; error_usage: if(warn_missing) { printf("(Missing parameter after %s?)\n", warn_missing); } printf("\n"); goto usage; usage: banner(); printf( "Usage:\n" " To insert: %s -i bin_or_iso [options] [files...]\n" " To extract: %s -x bin_or_iso [options] [files...]\n" "\nOptions:\n" " -be Favor big-endian values in ISO9660 metadata\n" " -boot Insert or extract boot area\n" " -d dir Set the base directory for inserted or extracted files\n" " (defaults to .)\n" " -f Skip filesystem consistency checks\n" " -le Favor little-endian values in ISO9660 metadata\n" " -o Force overwrite when extracting files\n" " -r Recurse into subdirectories\n" " -v Verbose\n", argv[0], argv[0] ); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/common.h0000644000175000017500000003637511731303760016005 0ustar corlettcorlett#ifndef __CMDPACK_COMMON_H__ #define __CMDPACK_COMMON_H__ //////////////////////////////////////////////////////////////////////////////// // // Common headers for Command-Line Pack programs // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// // Disable fopen() warnings on VC++. It means well... #define _CRT_SECURE_NO_WARNINGS // Try to enable 64-bit file offsets on platforms where it's optional #define _LARGEFILE64_SOURCE 1 #define __USE_FILE_OFFSET64 1 #define __USE_LARGEFILE64 1 #define _FILE_OFFSET_BITS 64 // Try to enable long filename support on Watcom #define __WATCOM_LFN__ 1 // Convince MinGW that we want to glob arguments #ifdef __MINGW32__ int _dowildcard = -1; #endif //////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include #include // MSC toolchains use sys/utime.h; everything else uses utime.h #if defined(_MSC_VER) #include #else #include #endif // Try to bring in unistd.h if possible #if !defined(__TURBOC__) && !defined(_MSC_VER) #include #endif // Bring in direct.h if we need to; sometimes mkdir/rmdir is defined here #if defined(__WATCOMC__) || defined(_MSC_VER) #include #endif // Fill in S_ISDIR #if !defined(_POSIX_VERSION) && !defined(S_ISDIR) #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #endif #if defined(__TURBOC__) || defined(__WATCOMC__) || defined(__MINGW32__) || defined(_MSC_VER) // // Already have a single-argument mkdir() // #else // // Provide a single-argument mkdir() // #define mkdir(a) mkdir(a, S_IRWXU | S_IRWXG | S_IRWXO) #endif //////////////////////////////////////////////////////////////////////////////// // // Enforce large memory model for 16-bit DOS targets // #if defined(__MSDOS__) || defined(MSDOS) #if defined(__TURBOC__) || defined(__WATCOMC__) #if !defined(__LARGE__) #error This is not the memory model we should be using! #endif #endif #endif //////////////////////////////////////////////////////////////////////////////// // // Try to figure out integer types // #if defined(_STDINT_H) || defined(_EXACT_WIDTH_INTS) // _STDINT_H_ - presume stdint.h has already been included // _EXACT_WIDTH_INTS - OpenWatcom already provides int*_t in sys/types.h #elif defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L // Assume C99 compliance when the compiler specifically tells us it is #include #elif defined(_MSC_VER) // On Visual Studio, use its integral types typedef signed __int8 int8_t; typedef unsigned __int8 uint8_t; typedef signed __int16 int16_t; typedef unsigned __int16 uint16_t; typedef signed __int32 int32_t; typedef unsigned __int32 uint32_t; #else // Guess integer sizes from limits.h // // int8_t // #ifndef __int8_t_defined #if SCHAR_MIN == -128 && SCHAR_MAX == 127 && UCHAR_MAX == 255 typedef signed char int8_t; #else #error Unknown how to define int8_t! #endif #endif // // uint8_t // #ifndef __uint8_t_defined #if SCHAR_MIN == -128 && SCHAR_MAX == 127 && UCHAR_MAX == 255 typedef unsigned char uint8_t; #else #error Unknown how to define uint8_t! #endif #endif // // int16_t // #ifndef __int16_t_defined #if SHRT_MIN == -32768 && SHRT_MAX == 32767 && USHRT_MAX == 65535 typedef signed short int16_t; #else #error Unknown how to define int16_t! #endif #endif // // uint16_t // #ifndef __uint16_t_defined #if SHRT_MIN == -32768 && SHRT_MAX == 32767 && USHRT_MAX == 65535 typedef unsigned short uint16_t; #else #error Unknown how to define uint16_t! #endif #endif // // int32_t // #ifndef __int32_t_defined #if INT_MIN == -2147483648 && INT_MAX == 2147483647 && UINT_MAX == 4294967295 typedef signed int int32_t; #elif LONG_MIN == -2147483648 && LONG_MAX == 2147483647 && ULONG_MAX == 4294967295 typedef signed long int32_t; #else #error Unknown how to define int32_t! #endif #endif // // uint32_t // #ifndef __uint32_t_defined #if INT_MIN == -2147483648 && INT_MAX == 2147483647 && UINT_MAX == 4294967295 typedef unsigned int uint32_t; #elif LONG_MIN == -2147483648 && LONG_MAX == 2147483647 && ULONG_MAX == 4294967295 typedef unsigned long uint32_t; #else #error Unknown how to define uint32_t! #endif #endif #endif // // There are some places in the code where it's assumed 'long' can hold at least // 32 bits. Verify that here: // #if LONG_MAX < 2147483647 || ULONG_MAX < 4294967295 #error long type must be at least 32 bits! #endif //////////////////////////////////////////////////////////////////////////////// // // Figure out how big file offsets should be // #if defined(_OFF64_T_) || defined(_OFF64_T_DEFINED) || defined(__off64_t_defined) // // We have off64_t // Regular off_t may be smaller, so check this first // #ifdef off_t #undef off_t #endif #ifdef fseeko #undef fseeko #endif #ifdef ftello #undef ftello #endif #define off_t off64_t #define fseeko fseeko64 #define ftello ftello64 #elif defined(_OFF_T) || defined(__OFF_T_TYPE) || defined(__off_t_defined) || defined(_OFF_T_DEFINED_) // // We have off_t // #else // // Assume offsets are just 'long' // #ifdef off_t #undef off_t #endif #ifdef fseeko #undef fseeko #endif #ifdef ftello #undef ftello #endif #define off_t long #define fseeko fseek #define ftello ftell #endif // // Add the ability to read off_t // (assumes off_t is a signed type) // off_t strtoofft(const char* s_start, char** endptr, int base) { off_t max = ((((off_t)1) << ((sizeof(off_t)*8)-2)) - 1) + ((((off_t)1) << ((sizeof(off_t)*8)-2)) ); off_t min = ((-1) - max); const char* s = s_start; off_t accumulator; off_t limit_tens; off_t limit_ones; int c; int negative = 0; int anyinput; do { c = *s++; } while(isspace(c)); if(c == '-') { negative = 1; c = *s++; } else if (c == '+') { c = *s++; } if( (base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X') ) { c = s[1]; s += 2; base = 16; } if(!base) { base = (c == '0') ? 8 : 10; } limit_ones = max % ((off_t)base); limit_tens = max / ((off_t)base); if(negative) { limit_ones++; if(limit_ones >= base) { limit_ones = 0; limit_tens++; } } for(accumulator = 0, anyinput = 0;; c = *s++) { if(isdigit(c)) { c -= '0'; } else if(isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; } else { break; } if(c >= base) { break; } if( (anyinput < 0) || (accumulator < 0) || (accumulator > limit_tens) || (accumulator == limit_tens && c > limit_ones) ) { anyinput = -1; } else { anyinput = 1; accumulator *= base; accumulator += c; } } if(anyinput < 0) { accumulator = negative ? min : max; errno = ERANGE; } else if(negative) { accumulator = -accumulator; } if(endptr) { *endptr = (char*)(anyinput ? (char*)s - 1 : s_start); } return accumulator; } // // Add the ability to print off_t // void fprinthex(FILE* f, off_t off, int min_digits) { unsigned anydigit = 0; int place; for(place = 2 * sizeof(off_t) - 1; place >= 0; place--) { if(sizeof(off_t) > (((size_t)(place)) / 2)) { unsigned digit = (off >> (4 * place)) & 0xF; anydigit |= digit; if(anydigit || place < min_digits) { fputc("0123456789ABCDEF"[digit], f); } } } } static void fprintdec_digit(FILE* f, off_t off) { if(off == 0) { return; } if(off >= 10) { fprintdec_digit(f, off / ((off_t)10)); off %= ((off_t)10); } fputc('0' + off, f); } void fprintdec(FILE* f, off_t off) { if(off == 0) { fputc('0', f); return; } if(off < 0) { fputc('-', f); off = -off; if(off < 0) { off_t ones = off % ((off_t)10); off /= ((off_t)10); off = -off; fprintdec_digit(f, off); fputc('0' - ones, f); return; } } fprintdec_digit(f, off); } //////////////////////////////////////////////////////////////////////////////// // // Define truncate() for systems that don't have it // #if !defined(_POSIX_VERSION) #if (defined(__MSDOS__) || defined(MSDOS)) && (defined(__TURBOC__) || defined(__WATCOMC__)) #include #include #include int truncate(const char *filename, off_t size) { if(size < 0) { errno = EINVAL; return -1; } // // Extend (or do nothing) if necessary // { off_t end; FILE* f = fopen(filename, "rb"); if(!f) { return -1; } if(fseeko(f, 0, SEEK_END) != 0) { fclose(f); return -1; } end = ftello(f); if(end <= size) { for(; end < size; end++) { if(fputc(0, f) == EOF) { fclose(f); return -1; } } fclose(f); return 0; } fclose(f); } // // Shrink if necessary (DOS-specific call) // { int doshandle = 0; unsigned nwritten = 0; if(_dos_open(filename, O_WRONLY, &doshandle)) { return -1; } if(lseek(doshandle, size, SEEK_SET) == -1L) { _dos_close(doshandle); return -1; } if(_dos_write(doshandle, &doshandle, 0, &nwritten)) { _dos_close(doshandle); return -1; } _dos_close(doshandle); } // // Success // return 0; } #elif (defined(_WIN32) && defined(_MSC_VER)) #if defined(_MSC_VER) // Disable extension warnings for and friends #pragma warning (disable: 4226) #endif #include #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)(-1)) #endif int truncate(const char *filename, off_t size) { if(size < 0) { errno = EINVAL; return -1; } // // Extend (or do nothing) if necessary // { off_t end; FILE* f = fopen(filename, "rb"); if(!f) { return -1; } if(fseeko(f, 0, SEEK_END) != 0) { fclose(f); return -1; } end = ftello(f); if(end <= size) { for(; end < size; end++) { if(fputc(0, f) == EOF) { fclose(f); return -1; } } fclose(f); return 0; } fclose(f); } // // Shrink if necessary (Windows-specific call) // { HANDLE f = CreateFile( filename, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if(f == INVALID_HANDLE_VALUE) { return -1; } if(size > ((off_t)0x7FFFFFFFL)) { // use fancy 64-bit SetFilePointer LONG lo = size; LONG hi = size >> 32; if(SetFilePointer(f, lo, &hi, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { CloseHandle(f); return -1; } } else { // use plain 32-bit SetFilePointer if(SetFilePointer(f, size, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { CloseHandle(f); return -1; } } if(!SetEndOfFile(f)) { CloseHandle(f); return -1; } } // // Success // return 0; } #endif #endif // !defined(_POSIX_VERSION) //////////////////////////////////////////////////////////////////////////////// // // Normalize argv[0] // void normalize_argv0(char* argv0) { size_t i; size_t start = 0; int c; for(i = 0; argv0[i]; i++) { if(argv0[i] == '/' || argv0[i] == '\\') { start = i + 1; } } i = 0; do { c = ((unsigned char)(argv0[start + i])); if(c == '.') { c = 0; } if(c != 0) { c = tolower(c); } argv0[i++] = c; } while(c != 0); } //////////////////////////////////////////////////////////////////////////////// void printfileerror(FILE* f, const char* name) { int e = errno; printf("Error: "); if(name) { printf("%s: ", name); } printf("%s\n", f && feof(f) ? "Unexpected end-of-file" : strerror(e)); } //////////////////////////////////////////////////////////////////////////////// #if defined(_WIN32) // // Detect if the user double-clicked on the .exe rather than executing this from // the command line, and if so, display a warning and wait for input before // exiting // #include static HWND getconsolewindow(void) { HWND hConsoleWindow = NULL; HANDLE k32; // // See if GetConsoleWindow is available (Windows 2000 or later) // k32 = GetModuleHandle(TEXT("kernel32.dll")); if(k32) { typedef HWND (* WINAPI gcw_t)(void); gcw_t gcw = (gcw_t)GetProcAddress(k32, TEXT("GetConsoleWindow")); if(gcw) { hConsoleWindow = gcw(); } } // // There is an alternative method that involves FindWindow, but it's too // cumbersome for just printing a warning. // return hConsoleWindow; } void commandlinewarning(void) { HWND hConsoleWindow; DWORD processId = 0; // // This trick doesn't work in Win9x // if(GetVersion() >= ((DWORD)0x80000000LU)) { return; } // // See if the console window belongs to my own process // hConsoleWindow = getconsolewindow(); if(!hConsoleWindow) { return; } GetWindowThreadProcessId(hConsoleWindow, &processId); if(GetCurrentProcessId() == processId) { printf( "\n" "Note: This is a command-line application.\n" "It was meant to run from a Windows command prompt.\n\n" "Press ENTER to close this window..." ); fflush(stdout); fgetc(stdin); } } #else void commandlinewarning(void) {} #endif //////////////////////////////////////////////////////////////////////////////// // // Work around some problems with the Mariko CC toolchain // #ifdef MARIKO_CC // 32-bit signed and unsigned mod seem buggy; this solves it unsigned long __umodsi3(unsigned long a, unsigned long b) { return a - (a / b) * b; } signed long __modsi3(signed long a, signed long b) { return a - (a / b) * b; } // Some kind of soft float linkage issue? void __cmpdf2(void) {} #endif //////////////////////////////////////////////////////////////////////////////// #endif cmdpack-1.03-src/src/ecm.c0000644000175000017500000007476511731303760015261 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "ecm - Encoder/decoder for Error Code Modeler format" #define COPYR "Copyright (C) 2002-2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// // // Sector types // // Mode 1 // ----------------------------------------------------- // 0 1 2 3 4 5 6 7 8 9 A B C D E F // 0000h 00 FF FF FF FF FF FF FF FF FF FF 00 [-ADDR-] 01 // 0010h [---DATA... // ... // 0800h ...DATA---] // 0810h [---EDC---] 00 00 00 00 00 00 00 00 [---ECC... // ... // 0920h ...ECC---] // ----------------------------------------------------- // // Mode 2 (XA), form 1 // ----------------------------------------------------- // 0 1 2 3 4 5 6 7 8 9 A B C D E F // 0000h 00 FF FF FF FF FF FF FF FF FF FF 00 [-ADDR-] 02 // 0010h [--FLAGS--] [--FLAGS--] [---DATA... // ... // 0810h ...DATA---] [---EDC---] [---ECC... // ... // 0920h ...ECC---] // ----------------------------------------------------- // // Mode 2 (XA), form 2 // ----------------------------------------------------- // 0 1 2 3 4 5 6 7 8 9 A B C D E F // 0000h 00 FF FF FF FF FF FF FF FF FF FF 00 [-ADDR-] 02 // 0010h [--FLAGS--] [--FLAGS--] [---DATA... // ... // 0920h ...DATA---] [---EDC---] // ----------------------------------------------------- // // ADDR: Sector address, encoded as minutes:seconds:frames in BCD // FLAGS: Used in Mode 2 (XA) sectors describing the type of sector; repeated // twice for redundancy // DATA: Area of the sector which contains the actual data itself // EDC: Error Detection Code // ECC: Error Correction Code // //////////////////////////////////////////////////////////////////////////////// static uint32_t get32lsb(const uint8_t* src) { return (((uint32_t)(src[0])) << 0) | (((uint32_t)(src[1])) << 8) | (((uint32_t)(src[2])) << 16) | (((uint32_t)(src[3])) << 24); } static void put32lsb(uint8_t* dest, uint32_t value) { dest[0] = (uint8_t)(value ); dest[1] = (uint8_t)(value >> 8); dest[2] = (uint8_t)(value >> 16); dest[3] = (uint8_t)(value >> 24); } //////////////////////////////////////////////////////////////////////////////// // // LUTs used for computing ECC/EDC // static uint8_t ecc_f_lut[256]; static uint8_t ecc_b_lut[256]; static uint32_t edc_lut [256]; static void eccedc_init(void) { size_t i; for(i = 0; i < 256; i++) { uint32_t edc = i; size_t j = (i << 1) ^ (i & 0x80 ? 0x11D : 0); ecc_f_lut[i] = j; ecc_b_lut[i ^ j] = i; for(j = 0; j < 8; j++) { edc = (edc >> 1) ^ (edc & 1 ? 0xD8018001 : 0); } edc_lut[i] = edc; } } //////////////////////////////////////////////////////////////////////////////// // // Compute EDC for a block // static uint32_t edc_compute( uint32_t edc, const uint8_t* src, size_t size ) { for(; size; size--) { edc = (edc >> 8) ^ edc_lut[(edc ^ (*src++)) & 0xFF]; } return edc; } //////////////////////////////////////////////////////////////////////////////// // // Check ECC block (either P or Q) // Returns true if the ECC data is an exact match // static int8_t ecc_checkpq( const uint8_t* address, const uint8_t* data, size_t major_count, size_t minor_count, size_t major_mult, size_t minor_inc, const uint8_t* ecc ) { size_t size = major_count * minor_count; size_t major; for(major = 0; major < major_count; major++) { size_t index = (major >> 1) * major_mult + (major & 1); uint8_t ecc_a = 0; uint8_t ecc_b = 0; size_t minor; for(minor = 0; minor < minor_count; minor++) { uint8_t temp; if(index < 4) { temp = address[index]; } else { temp = data[index - 4]; } index += minor_inc; if(index >= size) { index -= size; } ecc_a ^= temp; ecc_b ^= temp; ecc_a = ecc_f_lut[ecc_a]; } ecc_a = ecc_b_lut[ecc_f_lut[ecc_a] ^ ecc_b]; if( ecc[major ] != (ecc_a ) || ecc[major + major_count] != (ecc_a ^ ecc_b) ) { return 0; } } return 1; } // // Write ECC block (either P or Q) // static void ecc_writepq( const uint8_t* address, const uint8_t* data, size_t major_count, size_t minor_count, size_t major_mult, size_t minor_inc, uint8_t* ecc ) { size_t size = major_count * minor_count; size_t major; for(major = 0; major < major_count; major++) { size_t index = (major >> 1) * major_mult + (major & 1); uint8_t ecc_a = 0; uint8_t ecc_b = 0; size_t minor; for(minor = 0; minor < minor_count; minor++) { uint8_t temp; if(index < 4) { temp = address[index]; } else { temp = data[index - 4]; } index += minor_inc; if(index >= size) { index -= size; } ecc_a ^= temp; ecc_b ^= temp; ecc_a = ecc_f_lut[ecc_a]; } ecc_a = ecc_b_lut[ecc_f_lut[ecc_a] ^ ecc_b]; ecc[major ] = (ecc_a ); ecc[major + major_count] = (ecc_a ^ ecc_b); } } // // Check ECC P and Q codes for a sector // Returns true if the ECC data is an exact match // static int8_t ecc_checksector( const uint8_t *address, const uint8_t *data, const uint8_t *ecc ) { return ecc_checkpq(address, data, 86, 24, 2, 86, ecc) && // P ecc_checkpq(address, data, 52, 43, 86, 88, ecc + 0xAC); // Q } // // Write ECC P and Q codes for a sector // static void ecc_writesector( const uint8_t *address, const uint8_t *data, uint8_t *ecc ) { ecc_writepq(address, data, 86, 24, 2, 86, ecc); // P ecc_writepq(address, data, 52, 43, 86, 88, ecc + 0xAC); // Q } //////////////////////////////////////////////////////////////////////////////// static const uint8_t zeroaddress[4] = {0, 0, 0, 0}; //////////////////////////////////////////////////////////////////////////////// // // Check if this is a sector we can compress // // Sector types: // 0: Literal bytes (not a sector) // 1: 2352 mode 1 predict sync, mode, reserved, edc, ecc // 2: 2336 mode 2 form 1 predict redundant flags, edc, ecc // 3: 2336 mode 2 form 2 predict redundant flags, edc // static int8_t detect_sector(const uint8_t* sector, size_t size_available) { if( size_available >= 2352 && sector[0x000] == 0x00 && // sync (12 bytes) sector[0x001] == 0xFF && sector[0x002] == 0xFF && sector[0x003] == 0xFF && sector[0x004] == 0xFF && sector[0x005] == 0xFF && sector[0x006] == 0xFF && sector[0x007] == 0xFF && sector[0x008] == 0xFF && sector[0x009] == 0xFF && sector[0x00A] == 0xFF && sector[0x00B] == 0x00 && sector[0x00F] == 0x01 && // mode (1 byte) sector[0x814] == 0x00 && // reserved (8 bytes) sector[0x815] == 0x00 && sector[0x816] == 0x00 && sector[0x817] == 0x00 && sector[0x818] == 0x00 && sector[0x819] == 0x00 && sector[0x81A] == 0x00 && sector[0x81B] == 0x00 ) { // // Might be Mode 1 // if( ecc_checksector( sector + 0xC, sector + 0x10, sector + 0x81C ) && edc_compute(0, sector, 0x810) == get32lsb(sector + 0x810) ) { return 1; // Mode 1 } } else if( size_available >= 2336 && sector[0] == sector[4] && // flags (4 bytes) sector[1] == sector[5] && // versus redundant copy sector[2] == sector[6] && sector[3] == sector[7] ) { // // Might be Mode 2, Form 1 or 2 // if( ecc_checksector( zeroaddress, sector, sector + 0x80C ) && edc_compute(0, sector, 0x808) == get32lsb(sector + 0x808) ) { return 2; // Mode 2, Form 1 } // // Might be Mode 2, Form 2 // if( edc_compute(0, sector, 0x91C) == get32lsb(sector + 0x91C) ) { return 3; // Mode 2, Form 2 } } // // Nothing // return 0; } //////////////////////////////////////////////////////////////////////////////// // // Reconstruct a sector based on type // static void reconstruct_sector( uint8_t* sector, // must point to a full 2352-byte sector int8_t type ) { // // Sync // sector[0x000] = 0x00; sector[0x001] = 0xFF; sector[0x002] = 0xFF; sector[0x003] = 0xFF; sector[0x004] = 0xFF; sector[0x005] = 0xFF; sector[0x006] = 0xFF; sector[0x007] = 0xFF; sector[0x008] = 0xFF; sector[0x009] = 0xFF; sector[0x00A] = 0xFF; sector[0x00B] = 0x00; switch(type) { case 1: // // Mode // sector[0x00F] = 0x01; // // Reserved // sector[0x814] = 0x00; sector[0x815] = 0x00; sector[0x816] = 0x00; sector[0x817] = 0x00; sector[0x818] = 0x00; sector[0x819] = 0x00; sector[0x81A] = 0x00; sector[0x81B] = 0x00; break; case 2: case 3: // // Mode // sector[0x00F] = 0x02; // // Flags // sector[0x010] = sector[0x014]; sector[0x011] = sector[0x015]; sector[0x012] = sector[0x016]; sector[0x013] = sector[0x017]; break; } // // Compute EDC // switch(type) { case 1: put32lsb(sector+0x810, edc_compute(0, sector , 0x810)); break; case 2: put32lsb(sector+0x818, edc_compute(0, sector+0x10, 0x808)); break; case 3: put32lsb(sector+0x92C, edc_compute(0, sector+0x10, 0x91C)); break; } // // Compute ECC // switch(type) { case 1: ecc_writesector(sector+0xC , sector+0x10, sector+0x81C); break; case 2: ecc_writesector(zeroaddress, sector+0x10, sector+0x81C); break; } // // Done // } //////////////////////////////////////////////////////////////////////////////// // // Encode a type/count combo // // Returns nonzero on error // static int8_t write_type_count( const char* outfilename, FILE *out, int8_t type, uint32_t count ) { int8_t returncode = 0; count--; if(fputc(((count >= 32) << 7) | ((count & 31) << 2) | type, out) == EOF) { goto error_out; } count >>= 5; while(count) { if(fputc(((count >= 128) << 7) | (count & 127), out) == EOF) { goto error_out; } count >>= 7; } // // Success // returncode = 0; goto done; error_out: printfileerror(out, outfilename); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// static uint8_t sector_buffer[2352]; //////////////////////////////////////////////////////////////////////////////// static off_t mycounter_analyze = (off_t)-1; static off_t mycounter_encode = (off_t)-1; static off_t mycounter_decode = (off_t)-1; static off_t mycounter_total = 0; static void resetcounter(off_t total) { mycounter_analyze = (off_t)-1; mycounter_encode = (off_t)-1; mycounter_decode = (off_t)-1; mycounter_total = total; } static void encode_progress(void) { off_t a = (mycounter_analyze + 64) / 128; off_t e = (mycounter_encode + 64) / 128; off_t t = (mycounter_total + 64) / 128; if(!t) { t = 1; } fprintf(stderr, "Analyze(%02u%%) Encode(%02u%%)\r", (unsigned)((((off_t)100) * a) / t), (unsigned)((((off_t)100) * e) / t) ); } static void decode_progress(void) { off_t d = (mycounter_decode + 64) / 128; off_t t = (mycounter_total + 64) / 128; if(!t) { t = 1; } fprintf(stderr, "Decode(%02u%%)\r", (unsigned)((((off_t)100) * d) / t) ); } static void setcounter_analyze(off_t n) { int8_t p = ((n >> 20) != (mycounter_analyze >> 20)); mycounter_analyze = n; if(p) { encode_progress(); } } static void setcounter_encode(off_t n) { int8_t p = ((n >> 20) != (mycounter_encode >> 20)); mycounter_encode = n; if(p) { encode_progress(); } } static void setcounter_decode(off_t n) { int8_t p = ((n >> 20) != (mycounter_decode >> 20)); mycounter_decode = n; if(p) { decode_progress(); } } //////////////////////////////////////////////////////////////////////////////// // // Encode a run of sectors/literals of the same type // // Returns nonzero on error // static int8_t write_sectors( int8_t type, uint32_t count, const char* infilename, const char* outfilename, FILE* in, FILE* out ) { int8_t returncode = 0; if(write_type_count(outfilename, out, type, count)) { goto error; } if(type == 0) { while(count) { uint32_t b = count; if(b > sizeof(sector_buffer)) { b = sizeof(sector_buffer); } if(fread(sector_buffer, 1, b, in) != b) { goto error_in; } if(fwrite(sector_buffer, 1, b, out) != b) { goto error_out; } count -= b; setcounter_encode(ftello(in)); } return 0; } for(; count; count--) { switch(type) { case 1: if(fread(sector_buffer, 1, 2352, in) != 2352) { goto error_in; } if(fwrite(sector_buffer + 0x00C, 1, 0x003, out) != 0x003) { goto error_out; } if(fwrite(sector_buffer + 0x010, 1, 0x800, out) != 0x800) { goto error_out; } break; case 2: if(fread(sector_buffer, 1, 2336, in) != 2336) { goto error_in; } if(fwrite(sector_buffer + 0x004, 1, 0x804, out) != 0x804) { goto error_out; } break; case 3: if(fread(sector_buffer, 1, 2336, in) != 2336) { goto error_in; } if(fwrite(sector_buffer + 0x004, 1, 0x918, out) != 0x918) { goto error_out; } break; } setcounter_encode(ftello(in)); } // // Success // returncode = 0; goto done; error_in: printfileerror(in, infilename); goto error; error_out: printfileerror(out, outfilename); goto error; error: returncode = 1; goto done; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero on error // static int8_t ecmify( const char* infilename, const char* outfilename ) { int8_t returncode = 0; FILE* in = NULL; FILE* out = NULL; uint8_t* queue = NULL; size_t queue_start_ofs = 0; size_t queue_bytes_available = 0; uint32_t input_edc = 0; // // Current sector type (run) // int8_t curtype = -1; // not a valid type uint32_t curtype_count = 0; off_t curtype_in_start = 0; uint32_t literal_skip = 0; off_t input_file_length; off_t input_bytes_checked = 0; off_t input_bytes_queued = 0; off_t typetally[4] = {0,0,0,0}; static const size_t sectorsize[4] = { 1, 2352, 2336, 2336 }; size_t queue_size = ((size_t)(-1)) - 4095; if((unsigned long)queue_size > 0x40000lu) { queue_size = (size_t)0x40000lu; } // // Allocate space for queue // queue = malloc(queue_size); if(!queue) { printf("Out of memory\n"); goto error; } // // Ensure the output file doesn't already exist // out = fopen(outfilename, "rb"); if(out) { printf("Error: %s exists; refusing to overwrite\n", outfilename); goto error; } // // Open both files // in = fopen(infilename, "rb"); if(!in) { goto error_in; } out = fopen(outfilename, "wb"); if(!out) { goto error_out; } printf("Encoding %s to %s...\n", infilename, outfilename); // // Get the length of the input file // if(fseeko(in, 0, SEEK_END) != 0) { goto error_in; } input_file_length = ftello(in); if(input_file_length < 0) { goto error_in; } resetcounter(input_file_length); // // Magic identifier // if(fputc('E' , out) == EOF) { goto error_out; } if(fputc('C' , out) == EOF) { goto error_out; } if(fputc('M' , out) == EOF) { goto error_out; } if(fputc(0x00, out) == EOF) { goto error_out; } for(;;) { int8_t detecttype; // // Refill queue if necessary // if( (queue_bytes_available < 2352) && (((off_t)queue_bytes_available) < (input_file_length - input_bytes_queued)) ) { // // We need to read more data // off_t willread = input_file_length - input_bytes_queued; off_t maxread = queue_size - queue_bytes_available; if(willread > maxread) { willread = maxread; } if(queue_start_ofs > 0) { memmove(queue, queue + queue_start_ofs, queue_bytes_available); queue_start_ofs = 0; } if(willread) { setcounter_analyze(input_bytes_queued); if(fseeko(in, input_bytes_queued, SEEK_SET) != 0) { goto error_in; } if(fread(queue + queue_bytes_available, 1, willread, in) != (size_t)willread) { goto error_in; } input_edc = edc_compute( input_edc, queue + queue_bytes_available, willread ); input_bytes_queued += willread; queue_bytes_available += willread; } } if(queue_bytes_available == 0) { // // No data left to read -> quit // detecttype = -1; } else if(literal_skip > 0) { // // Skipping through literal bytes // literal_skip--; detecttype = 0; } else { // // Heuristic to skip past CD sync after a mode 2 sector // if( curtype >= 2 && queue_bytes_available >= 0x10 && queue[queue_start_ofs + 0x0] == 0x00 && queue[queue_start_ofs + 0x1] == 0xFF && queue[queue_start_ofs + 0x2] == 0xFF && queue[queue_start_ofs + 0x3] == 0xFF && queue[queue_start_ofs + 0x4] == 0xFF && queue[queue_start_ofs + 0x5] == 0xFF && queue[queue_start_ofs + 0x6] == 0xFF && queue[queue_start_ofs + 0x7] == 0xFF && queue[queue_start_ofs + 0x8] == 0xFF && queue[queue_start_ofs + 0x9] == 0xFF && queue[queue_start_ofs + 0xA] == 0xFF && queue[queue_start_ofs + 0xB] == 0x00 && queue[queue_start_ofs + 0xF] == 0x02 ) { // Treat this byte as a literal... detecttype = 0; // ...and skip the next 15 literal_skip = 15; } else { // // Detect the sector type at the current offset // detecttype = detect_sector(queue + queue_start_ofs, queue_bytes_available); } } if( (detecttype == curtype) && (curtype_count <= 0x7FFFFFFF) // avoid overflow ) { // // Same type as last sector // curtype_count++; } else { // // Changing types: Flush the input // if(curtype_count > 0) { if(fseeko(in, curtype_in_start, SEEK_SET) != 0) { goto error_in; } typetally[curtype] += curtype_count; if(write_sectors( curtype, curtype_count, infilename, outfilename, in, out )) { goto error; } } curtype = detecttype; curtype_in_start = input_bytes_checked; curtype_count = 1; } // // Current type is negative ==> quit // if(curtype < 0) { break; } // // Advance to the next sector // input_bytes_checked += sectorsize[curtype]; queue_start_ofs += sectorsize[curtype]; queue_bytes_available -= sectorsize[curtype]; } // // Store the end-of-records indicator // if(write_type_count(outfilename, out, 0, 0)) { goto error; } // // Store the EDC of the input file // put32lsb(sector_buffer, input_edc); if(fwrite(sector_buffer, 1, 4, out) != 4) { goto error_out; } // // Show report // printf("Literal bytes........... "); fprintdec(stdout, typetally[0]); printf("\n"); printf("Mode 1 sectors.......... "); fprintdec(stdout, typetally[1]); printf("\n"); printf("Mode 2 form 1 sectors... "); fprintdec(stdout, typetally[2]); printf("\n"); printf("Mode 2 form 2 sectors... "); fprintdec(stdout, typetally[3]); printf("\n"); printf("Encoded "); fprintdec(stdout, input_file_length); printf(" bytes -> "); fprintdec(stdout, ftello(out)); printf(" bytes\n"); // // Success // printf("Done\n"); returncode = 0; goto done; error_in: printfileerror(in, infilename); goto error; error_out: printfileerror(out, outfilename); goto error; error: returncode = 1; goto done; done: if(queue != NULL) { free(queue); } if(in != NULL) { fclose(in ); } if(out != NULL) { fclose(out); } return returncode; } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero on error // static int8_t unecmify( const char* infilename, const char* outfilename ) { int8_t returncode = 0; FILE* in = NULL; FILE* out = NULL; off_t input_file_length; uint32_t output_edc = 0; int8_t type; uint32_t num; // // Ensure the output file doesn't already exist // out = fopen(outfilename, "rb"); if(out) { printf("Error: %s exists; refusing to overwrite\n", outfilename); goto error; } // // Open both files // in = fopen(infilename, "rb"); if(!in) { goto error_in; } // // Get the length of the input file // if(fseeko(in, 0, SEEK_END) != 0) { goto error_in; } input_file_length = ftello(in); if(input_file_length < 0) { goto error_in; } resetcounter(input_file_length); if(fseeko(in, 0, SEEK_SET) != 0) { goto error_in; } // // Magic header // if( (fgetc(in) != 'E') || (fgetc(in) != 'C') || (fgetc(in) != 'M') || (fgetc(in) != 0x00) ) { printf("Header missing; does not appear to be an ECM file\n"); goto error; } // // Open output file // out = fopen(outfilename, "wb"); if(!out) { goto error_out; } printf("Decoding %s to %s...\n", infilename, outfilename); for(;;) { int c = fgetc(in); int bits = 5; if(c == EOF) { goto error_in; } type = c & 3; num = (c >> 2) & 0x1F; while(c & 0x80) { c = fgetc(in); if(c == EOF) { goto error_in; } if( (bits > 31) || ((uint32_t)(c & 0x7F)) >= (((uint32_t)0x80000000LU) >> (bits-1)) ) { printf("Corrupt ECM file; invalid sector count\n"); goto error; } num |= ((uint32_t)(c & 0x7F)) << bits; bits += 7; } if(num == 0xFFFFFFFF) { // End indicator break; } num++; if(type == 0) { while(num) { uint32_t b = num; if(b > sizeof(sector_buffer)) { b = sizeof(sector_buffer); } if(fread(sector_buffer, 1, b, in) != b) { goto error_in; } output_edc = edc_compute(output_edc, sector_buffer, b); if(fwrite(sector_buffer, 1, b, out) != b) { goto error_out; } num -= b; setcounter_decode(ftello(in)); } } else { for(; num; num--) { switch(type) { case 1: if(fread(sector_buffer + 0x00C, 1, 0x003, in) != 0x003) { goto error_in; } if(fread(sector_buffer + 0x010, 1, 0x800, in) != 0x800) { goto error_in; } reconstruct_sector(sector_buffer, 1); output_edc = edc_compute(output_edc, sector_buffer, 2352); if(fwrite(sector_buffer, 1, 2352, out) != 2352) { goto error_out; } break; case 2: if(fread(sector_buffer + 0x014, 1, 0x804, in) != 0x804) { goto error_in; } reconstruct_sector(sector_buffer, 2); output_edc = edc_compute(output_edc, sector_buffer + 0x10, 2336); if(fwrite(sector_buffer + 0x10, 1, 2336, out) != 2336) { goto error_out; } break; case 3: if(fread(sector_buffer + 0x014, 1, 0x918, in) != 0x918) { goto error_in; } reconstruct_sector(sector_buffer, 3); output_edc = edc_compute(output_edc, sector_buffer + 0x10, 2336); if(fwrite(sector_buffer + 0x10, 1, 2336, out) != 2336) { goto error_out; } break; } setcounter_decode(ftello(in)); } } } // // Verify the EDC of the entire output file // if(fread(sector_buffer, 1, 4, in) != 4) { goto error_in; } printf("Decoded "); fprintdec(stdout, ftello(in)); printf(" bytes -> "); fprintdec(stdout, ftello(out)); printf(" bytes\n"); if(get32lsb(sector_buffer) != output_edc) { printf("Checksum error (0x%08lX, should be 0x%08lX)\n", (unsigned long)output_edc, (unsigned long)get32lsb(sector_buffer) ); goto error; } // // Success // printf("Done\n"); returncode = 0; goto done; error_in: printfileerror(in, infilename); goto error; error_out: printfileerror(out, outfilename); goto error; error: returncode = 1; goto done; done: if(in != NULL) { fclose(in ); } if(out != NULL) { fclose(out); } return returncode; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int returncode = 0; int8_t encode = 0; char* infilename = NULL; char* outfilename = NULL; char* tempfilename = NULL; normalize_argv0(argv[0]); // // Check command line // switch(argc) { case 2: // // ecm source // unecm source // encode = (strcmp(argv[0], "unecm") != 0); infilename = argv[1]; tempfilename = malloc(strlen(infilename) + 7); if(!tempfilename) { printf("Out of memory\n"); goto error; } strcpy(tempfilename, infilename); if(encode) { // // Append ".ecm" to the input filename // strcat(tempfilename, ".ecm"); } else { // // Remove ".ecm" from the input filename // size_t l = strlen(tempfilename); if( (l > 4) && tempfilename[l - 4] == '.' && tolower(tempfilename[l - 3]) == 'e' && tolower(tempfilename[l - 2]) == 'c' && tolower(tempfilename[l - 1]) == 'm' ) { tempfilename[l - 4] = 0; } else { // // If that fails, append ".unecm" to the input filename // strcat(tempfilename, ".unecm"); } } outfilename = tempfilename; break; case 3: // // ecm source dest // unecm source dest // encode = (strcmp(argv[0], "unecm") != 0); infilename = argv[1]; outfilename = argv[2]; break; case 4: // // ecm e source dest // ecm d source dest // if(!strcmp(argv[1], "e")) { encode = 1; } else if(!strcmp(argv[1], "d")) { encode = 0; } else { goto usage; } infilename = argv[2]; outfilename = argv[3]; break; default: goto usage; } // // Initialize the ECC/EDC tables // eccedc_init(); // // Go! // if(encode) { if(ecmify(infilename, outfilename)) { goto error; } } else { if(unecmify(infilename, outfilename)) { goto error; } } // // Success // returncode = 0; goto done; usage: banner(); printf( "Usage:\n" "\n" "To encode:\n" " ecm cdimagefile\n" " ecm cdimagefile ecmfile\n" " ecm e cdimagefile ecmfile\n" "\n" "To decode:\n" " unecm ecmfile\n" " unecm ecmfile cdimagefile\n" " ecm d ecmfile cdimagefile\n" ); error: returncode = 1; goto done; done: if(tempfilename) { free(tempfilename); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/fakecrc.c0000644000175000017500000002141611731303760016074 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "fakecrc - Fake the CRC32 of a file" #define COPYR "Copyright (C) 2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static uint32_t crctable_f[256]; static uint32_t crctable_r[256]; static void crc_init(void) { uint32_t i, j, k; for(i = 0; i < 256; i++) { j = i; for(k = 0; k < 8; k++) { j = (j >> 1) ^ ((j & 1) ? 0x80000000 : 0x6DB88320); } crctable_f[i] = j; j = i << 24; for(k = 0; k < 8; k++) { j = (j << 1) ^ ((((int32_t)j) < 0) ? 0x00000001 : 0xDB710640); } crctable_r[i] = j; } } static uint32_t crc_nextbyte(uint32_t crc, uint8_t byte) { return (crc >> 8) ^ crctable_f[(crc ^ byte) & 0xFF]; } static uint32_t crc_prevbyte(uint32_t crc, uint8_t byte) { return (crc << 8) ^ byte ^ crctable_r[crc >> 24]; } //////////////////////////////////////////////////////////////////////////////// // // Compute CRC forward for a section of a file // static uint8_t crc_buffer[4096]; // Returns nonzero on error static int crc_f(uint32_t crc, FILE* f, off_t start, off_t end, uint32_t* result) { if(start < 0) { printf("error - start is negative\n"); return 1; } if(end < 0) { printf("error - end is negative\n"); return 1; } if(start > end) { printf("error - start > end\n"); return 1; } if(fseeko(f, start, SEEK_SET) != 0) { printf("seek error\n"); return 1; } while(start < end) { off_t i; off_t diff = end - start; if(diff > ((off_t)sizeof(crc_buffer))) { diff = sizeof(crc_buffer); } if(fread(crc_buffer, 1, (size_t)diff, f) != (size_t)diff) { printf("read error\n"); return 1; } for(i = 0; i < diff; i++) { crc = crc_nextbyte(crc, crc_buffer[i]); } start += diff; } if(result) { *result = crc; } return 0; } // // Compute CRC reverse for a section of a file // // Returns nonzero on error static int crc_r(uint32_t crc, FILE* f, off_t start, off_t end, uint32_t* result) { if(start < 0) { printf("error - start is negative\n"); return 1; } if(end < 0) { printf("error - end is negative\n"); return 1; } if(start > end) { printf("error - start > end\n"); return 1; } while(start < end) { off_t i; off_t diff = end - start; if(diff > ((off_t)sizeof(crc_buffer))) { diff = sizeof(crc_buffer); } end -= diff; if(fseeko(f, end, SEEK_SET) != 0) { printf("seek error\n"); return 1; } if(fread(crc_buffer, 1, (size_t)diff, f) != (size_t)diff) { printf("read error\n"); return 1; } for(i = diff; i > 0; i--) { crc = crc_prevbyte(crc, crc_buffer[i - 1]); } } if(result) { *result = crc; } return 0; } //////////////////////////////////////////////////////////////////////////////// // // Returns the 4 data bytes necessary to go from current->desired // static uint32_t crc32_preimage(uint32_t current_crc, uint32_t desired_crc) { uint32_t x = desired_crc ^ 0x2144DF1Clu; return current_crc ^ ( x & 0x47FF01FFlu) ^ (((x<< 1)|(x>>31)) & 0x8F0003C1lu) ^ (((x<< 2)|(x>>30)) & 0xFE0FFE03lu) ^ (((x<< 3)|(x>>29)) & 0x3FE003C0lu) ^ (((x<< 4)|(x>>28)) & 0x7830FE00lu) ^ (((x<< 5)|(x>>27)) & 0xF01F03DFlu) ^ (((x<< 6)|(x>>26)) & 0x00C001C0lu) ^ (((x<< 7)|(x>>25)) & 0x3E00FC40lu) ^ (((x<< 8)|(x>>24)) & 0x7F0FFEC0lu) ^ (((x<< 9)|(x>>23)) & 0xF9EF03FFlu) ^ (((x<<10)|(x>>22)) & 0x0FDFFE00lu) ^ (((x<<11)|(x>>21)) & 0x07CF05C0lu) ^ (((x<<12)|(x>>20)) & 0x30E00C00lu) ^ (((x<<13)|(x>>19)) & 0x7ECF0000lu) ^ (((x<<14)|(x>>18)) & 0xC1E001FFlu) ^ (((x<<15)|(x>>17)) & 0x78CF03C0lu) ^ (((x<<16)|(x>>16)) & 0xF61FFFFFlu) ^ (((x<<17)|(x>>15)) & 0x0F310000lu) ^ (((x<<18)|(x>>14)) & 0x39E0FE00lu) ^ (((x<<19)|(x>>13)) & 0x4F37FC00lu) ^ (((x<<20)|(x>>12)) & 0x8610003Flu) ^ (((x<<21)|(x>>11)) & 0xCF30FFFFlu) ^ (((x<<22)|(x>>10)) & 0x79EFFFC0lu) ^ (((x<<23)|(x>> 9)) & 0xCF2001FFlu) ^ (((x<<24)|(x>> 8)) & 0x793FFC00lu) ^ (((x<<25)|(x>> 7)) & 0xCF0F01FFlu) ^ (((x<<26)|(x>> 6)) & 0x7AE003C0lu) ^ (((x<<27)|(x>> 5)) & 0xC9C0003Flu) ^ (((x<<28)|(x>> 4)) & 0x78000000lu) ^ (((x<<29)|(x>> 3)) & 0xD70FFE3Flu) ^ (((x<<30)|(x>> 2)) & 0x4E1F0200lu) ^ (((x<<31)|(x>> 1)) & 0xC03FFC3Flu); } //////////////////////////////////////////////////////////////////////////////// int main( int argc, char **argv ) { int returncode = 0; FILE *f = NULL; uint32_t i; uint32_t desired_crc = 0; off_t file_size; off_t patch_offset; uint32_t pre_crc = 0; uint32_t post_crc = 0; uint32_t preimage = 0; uint8_t initial_bytes[4]; uint8_t patched_bytes[4]; normalize_argv0(argv[0]); crc_init(); if(argc != 2 && argc != 3 && argc != 4) { banner(); printf( "Usage:\n" "To obtain the CRC32 of a file:\n" " %s file\n" "To modify the CRC32 of a file:\n" " %s file desired_crc [offset]\n" "Patches 4 consecutive bytes at the given offset to force the file's CRC32.\n" "If no offset is given, the last 4 bytes of the file are used.\n", argv[0], argv[0] ); goto error; } if(argc == 2) { // // Just get the file's CRC // f = fopen(argv[1], "rb"); if(!f) { goto error_f; } if(fseeko(f, 0, SEEK_END) != 0) { goto error_f; } file_size = ftello(f); if(fseeko(f, 0, SEEK_SET) != 0) { goto error_f; } if(crc_f(0, f, 0, file_size, &pre_crc)) { goto error; } printf("0x%08lX\n", (unsigned long)pre_crc); goto done; } if(argc >= 3) { desired_crc = strtoul(argv[2], NULL, 0); } f = fopen(argv[1], "r+b"); if(!f) { goto error_f; } if(fseeko(f, 0, SEEK_END) != 0) { goto error_f; } file_size = ftello(f); if(fseeko(f, 0, SEEK_SET) != 0) { goto error_f; } if(file_size < 4) { printf("error: file must be at least 4 bytes\n"); goto error; } patch_offset = file_size - 4; if(argc >= 4) { patch_offset = strtoofft(argv[3], NULL, 0); if(patch_offset < 0) { printf("patch offset must not be negative\n"); goto error; } } if(patch_offset > (file_size - 4)) { printf("offset 0x"); fprinthex(stdout, patch_offset, 1); printf(" is out of range of the file\n"); goto error; } // // Compute pre- and post-crc // if(crc_f(0x00000000 , f, 0 , patch_offset, &pre_crc )) { goto error; } if(crc_r(desired_crc, f, patch_offset + 4, file_size , &post_crc)) { goto error; } // // Compute preimage from pre to post // preimage = crc32_preimage(pre_crc, post_crc); patched_bytes[0] = (uint8_t)(preimage >> 0); patched_bytes[1] = (uint8_t)(preimage >> 8); patched_bytes[2] = (uint8_t)(preimage >> 16); patched_bytes[3] = (uint8_t)(preimage >> 24); // // Write preimage at the patch offset // if(fseeko(f, patch_offset, SEEK_SET) != 0) { goto error_f; } if(fread (initial_bytes, 1, 4, f) != 4) { goto error_f; } if(fseeko(f, patch_offset, SEEK_SET) != 0) { goto error_f; } if(fwrite(patched_bytes, 1, 4, f) != 4) { goto error_f; } fflush(f); // // Done // for(i = 0; i < 4; i++) { printf("0x"); fprinthex(stdout, patch_offset + i, 1); printf(": 0x%02X -> 0x%02X\n", initial_bytes[i], patched_bytes[i]); } printf("Done! CRC32 is now 0x%08lX\n", (unsigned long)desired_crc); goto done; error_f: printfileerror(f, argv[1]); error: returncode = 1; done: if(f != NULL) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/hax65816.c0000644000175000017500000004774311731303760015703 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "hax65816 - Simple 65816 disassembler" #define COPYR "Copyright (C) 1998,2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static char aluop[8][4] = {"ora", "and", "eor", "adc", "sta", "lda", "cmp", "sbc" }; static char rmwop[8][4] = {"asl", "rol", "lsr", "ror", "???", "???", "dec", "inc" }; static int8_t mflag_default = 1; static int8_t xflag_default = 0; static int8_t flag_return = 1; static int8_t flag_guess = 1; static int8_t flag_follow = 1; static uint32_t dasm_address, ins_address; static int8_t mflag, xflag; static int getbyte(void); //////////////////////////////////////////////////////////////////////////////// static int fetchlist[10]; static int unfetchstack[10]; static int fetchn, unfetchn; static int fetchbyte(void) { int b; dasm_address++; if(unfetchn) b = unfetchstack[--unfetchn]; else b = getbyte(); fetchlist[fetchn++] = b; return b; } static void unfetchbyte(int b) { dasm_address--; fetchn--; if(fetchn < 0) fetchn = 0; unfetchstack[unfetchn++] = b; } enum { INS_COLUMN = 23 }; static void ins(const char* fmt, ...) { static char outputstr[100]; int outputn = INS_COLUMN; va_list ap; va_start(ap, fmt); for(;;) { char c = *fmt++; if(!c) break; if(c == '%') { c = *fmt++; switch(c) { case '%': { outputstr[outputn++] = '%'; break; } case 'A': { int n = (va_arg(ap, int) >> 5) & 7; outputstr[outputn++] = aluop[n][0]; outputstr[outputn++] = aluop[n][1]; outputstr[outputn++] = aluop[n][2]; break; } case 'M': { int n = (va_arg(ap, int) >> 5) & 7; outputstr[outputn++] = rmwop[n][0]; outputstr[outputn++] = rmwop[n][1]; outputstr[outputn++] = rmwop[n][2]; break; } case 'B': { int n = fetchbyte(); outputstr[outputn++] = '$'; if(n < 0) { outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; } else { sprintf( outputstr + outputn, "%02lX", (unsigned long)n ); outputn += 2; } break; } case 'R': { int n = fetchbyte(); outputstr[outputn++] = '$'; if(n < 0) { outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; } else { n = ((int8_t)(n)) + dasm_address; sprintf( outputstr + outputn, "%04lX", (unsigned long)(n & 0xFFFF) ); outputn += 4; } break; } case 'Z': { int n1 = fetchbyte(); int n2 = fetchbyte(); outputstr[outputn++] = '$'; if((n1 < 0) || (n2 < 0)) { for(n1 = 0; n1 < 6; n1++) { outputstr[outputn++] = '-'; } } else { int n = (n2 << 8) | (n1 & 0xFF); n = ((int16_t)(n)) + dasm_address; sprintf( outputstr + outputn, "%04lX", (unsigned long)(n & 0xFFFF) ); outputn += 6; } break; } case 'G': { int n = va_arg(ap, int); outputstr[outputn++] = '$'; if(n < 0) { outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; } else { sprintf( outputstr + outputn, "%02lX", (unsigned long)(n) ); outputn += 2; } break; } case 'W': { int q, n[2]; n[1] = fetchbyte(); n[0] = fetchbyte(); outputstr[outputn++] = '$'; for(q = 0; q < 2; q++) { if(n[q] < 0) { outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; } else { sprintf( outputstr + outputn, "%02lX", (unsigned long)(n[q]) ); outputn += 2; } } break; } case 'L': { int q, n[3]; n[2] = fetchbyte(); n[1] = fetchbyte(); n[0] = fetchbyte(); outputstr[outputn++] = '$'; for(q = 0; q < 3; q++) { if(n[q] < 0) { outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; } else { sprintf( outputstr + outputn, "%02lX", (unsigned long)(n[q]) ); outputn += 2; } } break; } case 'I': case 'X': { int q, n[3]; int8_t* sflag = (c == 'I') ? (&mflag) : (&xflag); outputstr[outputn++] = '$'; if(*sflag) { n[0] = fetchbyte(); n[1] = fetchbyte(); // // BRK/COP/WDM/STP after this? // switch(n[1]) { case 0x00: case 0x02: case 0x42: case 0xDB: if(flag_follow && flag_guess ) { (*sflag) = 0; q = 2; break; } default: unfetchbyte(n[1]); q = 1; break; } } else { n[0] = fetchbyte(); n[1] = fetchbyte(); n[2] = fetchbyte(); // // BRK/COP/WDM/STP after this? // switch(n[2]) { case 0x00: case 0x02: case 0x42: case 0xDB: if(flag_follow && flag_guess ) { (*sflag) = 1; unfetchbyte(n[2]); unfetchbyte(n[1]); q = 1; break; } default: unfetchbyte(n[2]); q = 2; break; } } while(q--) { if(n[q] < 0) { outputstr[outputn++] = '-'; outputstr[outputn++] = '-'; } else { sprintf( outputstr + outputn, "%02lX", (unsigned long)(n[q]) ); outputn += 2; } } break; } } } else { outputstr[outputn++] = c; } } outputstr[outputn] = 0; sprintf(outputstr, "%02lX/%04lX:", (unsigned long)(ins_address >> 16), (unsigned long)(ins_address & 0xFFFF) ); memset(outputstr + 8, ' ', INS_COLUMN - 8); outputn = 9; { int i; for(i = 0; i < fetchn; i++) { int n = fetchlist[i]; if(n < 0) { outputstr[outputn ] = '-'; outputstr[outputn+1] = '-'; } else { sprintf(outputstr + outputn, "%02X", n); outputstr[outputn+2] = ' '; } outputn += 3; } } fetchn = 0; printf("%s\n", outputstr); va_end(ap); } static void disassemble_one(void) { int opcode; ins_address = dasm_address; opcode = fetchbyte(); if(opcode < 0) return; if (opcode == 0x00) { ins("brk %B"); } else if(opcode == 0x20) { ins("jsr %W"); } else if(opcode == 0x40) { ins("rti"); if(flag_return) { mflag = mflag_default; xflag = xflag_default; } } else if(opcode == 0x60) { ins("rts"); if(flag_return) { mflag = mflag_default; xflag = xflag_default; } } else if(opcode == 0x80) { ins("bra %R"); } else if(opcode == 0xA0) { ins("ldy #%X"); } else if(opcode == 0xC0) { ins("cpy #%X"); } else if(opcode == 0xE0) { ins("cpx #%X"); } else if(opcode == 0x10) { ins("bpl %R"); } else if(opcode == 0x30) { ins("bmi %R"); } else if(opcode == 0x50) { ins("bvc %R"); } else if(opcode == 0x70) { ins("bvs %R"); } else if(opcode == 0x90) { ins("bcc %R"); } else if(opcode == 0xB0) { ins("bcs %R"); } else if(opcode == 0xD0) { ins("bne %R"); } else if(opcode == 0xF0) { ins("beq %R"); } else if((opcode & 0x1F) == 0x01) { ins("%A (%B,x)" , opcode); } else if((opcode & 0x1F) == 0x11) { ins("%A (%B),y" , opcode); } else if(opcode == 0x02) { ins("cop %B"); } else if(opcode == 0x22) { ins("jsr %L"); } else if(opcode == 0x42) { ins("wdm %B"); } else if(opcode == 0x62) { ins("per %Z"); } else if(opcode == 0x82) { ins("brl %Z"); } else if(opcode == 0xA2) { ins("ldx #%X"); } else if(opcode == 0xC2) { int n = fetchbyte(); if(flag_follow) if(n >= 0) { if(n & 0x10) xflag = 0; if(n & 0x20) mflag = 0; } ins("rep #%G", n); } else if(opcode == 0xE2) { int n = fetchbyte(); if(flag_follow) if(n >= 0) { if(n & 0x10) xflag = 1; if(n & 0x20) mflag = 1; } ins("sep #%G", n); } else if((opcode & 0x1F) == 0x12) { ins("%A (%B)" , opcode); } else if((opcode & 0x1F) == 0x03) { ins("%A %B,s" , opcode); } else if((opcode & 0x1F) == 0x13) { ins("%A (%B,s),y", opcode); } else if(opcode == 0x04) { ins("tsb %B"); } else if(opcode == 0x24) { ins("bit %B"); } else if(opcode == 0x44) { ins("mvp %B,%B"); } else if(opcode == 0x64) { ins("stz %B"); } else if(opcode == 0x84) { ins("sty %B"); } else if(opcode == 0xA4) { ins("ldy %B"); } else if(opcode == 0xC4) { ins("cpy %B"); } else if(opcode == 0xE4) { ins("cpx %B"); } else if(opcode == 0x14) { ins("trb %B"); } else if(opcode == 0x34) { ins("bit %B,x"); } else if(opcode == 0x54) { ins("mvn %B,%B"); } else if(opcode == 0x74) { ins("stz %B,x"); } else if(opcode == 0x94) { ins("sty %B,x"); } else if(opcode == 0xB4) { ins("ldy %B,x"); } else if(opcode == 0xD4) { ins("pei (%B)"); } else if(opcode == 0xF4) { ins("pea %W"); } else if((opcode & 0x1F) == 0x05) { ins("%A %B" , opcode); } else if((opcode & 0x1F) == 0x15) { ins("%A %B,x" , opcode); } else if(((opcode & 0x1F) == 0x06) && ((opcode & 0xC0) != 0x80)) { ins("%M %B", opcode); } else if(opcode == 0x86) { ins("stx %B"); } else if(opcode == 0xA6) { ins("ldx %B"); } else if(((opcode & 0x1F) == 0x16) && ((opcode & 0xC0) != 0x80)) { ins("%M %B,x", opcode); } else if(opcode == 0x96) { ins("stx %B,y"); } else if(opcode == 0xB6) { ins("ldx %B,y"); } else if((opcode & 0x1F) == 0x07) { ins("%A [%B]" , opcode); } else if((opcode & 0x1F) == 0x17) { ins("%A [%B],y" , opcode); } else if(opcode == 0x08) { ins("php"); } else if(opcode == 0x28) { ins("plp"); } else if(opcode == 0x48) { ins("pha"); } else if(opcode == 0x68) { ins("pla"); } else if(opcode == 0x88) { ins("dey"); } else if(opcode == 0xA8) { ins("tay"); } else if(opcode == 0xC8) { ins("iny"); } else if(opcode == 0xE8) { ins("inx"); } else if(opcode == 0x18) { ins("clc"); } else if(opcode == 0x38) { ins("sec"); } else if(opcode == 0x58) { ins("cli"); } else if(opcode == 0x78) { ins("sei"); } else if(opcode == 0x98) { ins("tya"); } else if(opcode == 0xB8) { ins("clv"); } else if(opcode == 0xD8) { ins("cld"); } else if(opcode == 0xF8) { ins("sed"); } else if((opcode & 0x1F) == 0x09) { if(opcode == 0x89) ins("bit #%I"); else ins("%A #%I", opcode); } else if((opcode & 0x1F) == 0x19) { ins("%A %W,y" , opcode); } else if(opcode == 0x0A) { ins("asl"); } else if(opcode == 0x2A) { ins("rol"); } else if(opcode == 0x4A) { ins("lsr"); } else if(opcode == 0x6A) { ins("ror"); } else if(opcode == 0x8A) { ins("txa"); } else if(opcode == 0xAA) { ins("tax"); } else if(opcode == 0xCA) { ins("dex"); } else if(opcode == 0xEA) { ins("nop"); } else if(opcode == 0x1A) { ins("inc"); } else if(opcode == 0x3A) { ins("dec"); } else if(opcode == 0x5A) { ins("phy"); } else if(opcode == 0x7A) { ins("ply"); } else if(opcode == 0x9A) { ins("txs"); } else if(opcode == 0xBA) { ins("tsx"); } else if(opcode == 0xDA) { ins("phx"); } else if(opcode == 0xFA) { ins("plx"); } else if(opcode == 0x0B) { ins("phd"); } else if(opcode == 0x2B) { ins("pld"); } else if(opcode == 0x4B) { ins("phk"); } else if(opcode == 0x6B) { ins("rtl"); if(flag_return) { mflag = mflag_default; xflag = xflag_default; } } else if(opcode == 0x8B) { ins("phb"); } else if(opcode == 0xAB) { ins("plb"); } else if(opcode == 0xCB) { ins("wai"); } else if(opcode == 0xEB) { ins("xba"); } else if(opcode == 0x1B) { ins("tcs"); } else if(opcode == 0x3B) { ins("tsc"); } else if(opcode == 0x5B) { ins("tcd"); } else if(opcode == 0x7B) { ins("tdc"); } else if(opcode == 0x9B) { ins("txy"); } else if(opcode == 0xBB) { ins("tyx"); } else if(opcode == 0xDB) { ins("stp"); } else if(opcode == 0xFB) { ins("xce"); } else if(opcode == 0x0C) { ins("tsb %W"); } else if(opcode == 0x2C) { ins("bit %W"); } else if(opcode == 0x4C) { ins("jmp %W"); } else if(opcode == 0x6C) { ins("jmp (%W)"); } else if(opcode == 0x8C) { ins("sty %W"); } else if(opcode == 0xAC) { ins("ldy %W"); } else if(opcode == 0xCC) { ins("cpy %W"); } else if(opcode == 0xEC) { ins("cpx %W"); } else if(opcode == 0x1C) { ins("trb %W"); } else if(opcode == 0x3C) { ins("bit %W,x"); } else if(opcode == 0x5C) { ins("jmp %L"); } else if(opcode == 0x7C) { ins("jmp (%W,x)"); } else if(opcode == 0x9C) { ins("stz %W"); } else if(opcode == 0xBC) { ins("ldy %W,x"); } else if(opcode == 0xDC) { ins("jmp [%W]"); } else if(opcode == 0xFC) { ins("jsr (%W,x)"); } else if((opcode & 0x1F) == 0x0D) { ins("%A %W" , opcode); } else if((opcode & 0x1F) == 0x1D) { ins("%A %W,x" , opcode); } else if(((opcode & 0x1F) == 0x0E) && ((opcode & 0xC0) != 0x80)) { ins("%M %W", opcode); } else if(opcode == 0x8E) { ins("stx %W"); } else if(opcode == 0xAE) { ins("ldx %W"); } else if(((opcode & 0x1F) == 0x1E) && ((opcode & 0xC0) != 0x80)) { ins("%M %W,x", opcode); } else if(opcode == 0x9E) { ins("stz %W,x"); } else if(opcode == 0xBE) { ins("ldx %W,y"); } else if((opcode & 0x1F) == 0x0F) { ins("%A %L" , opcode); } else if((opcode & 0x1F) == 0x1F) { ins("%A %L,x" , opcode); } else { ins("???"); } } //////////////////////////////////////////////////////////////////////////////// static FILE* infile = NULL; static uint32_t infile_bytes_left; static int getbyte(void) { if(infile_bytes_left) { int n = fgetc(infile); if(n == EOF) { infile_bytes_left = 0; return -1; } else { infile_bytes_left--; return (n & 0xFF); } } return -1; } static void disasm_range(uint32_t fileoffset, uint32_t len, uint32_t addr) { fseeko(infile, fileoffset, SEEK_SET); dasm_address = addr; infile_bytes_left = len; mflag = mflag_default; xflag = xflag_default; fetchn = unfetchn = 0; while(infile_bytes_left > 0) { disassemble_one(); } } static uint32_t gethex(const char* s) { if(!s[0]) return 0; if(s[0] == '$') s++; if(s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) s += 2; return (uint32_t)strtoul(s, NULL, 16); } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { const char* infilename; uint32_t arg_start; uint32_t arg_len; uint32_t arg_addr; int option_argn = 4; normalize_argv0(argv[0]); if(argc < 4) { banner(); printf( "Usage: %s imagefile start address [length] [options]\n" "Output is written to stdout. All values must be given in hex.\n" "If no length is given, disassembly will stop at the end of the bank.\n" "Options:\n" " -m0 Assume M flag = 0\n" " -m1 Assume M flag = 1 (default)\n" " -x0 Assume X flag = 0 (default)\n" " -x1 Assume X flag = 1\n" " -noreturn Disable flag reset after RTS/RTL/RTI\n" " -noguess Disable flag guess on BRK/COP/WDM/STP\n" " -nofollow Disable REP/SEP following (not recommended)\n", argv[0] ); return 1; } infilename = argv[1]; arg_start = gethex(argv[2]); arg_addr = gethex(argv[3]); arg_len = ((arg_addr & 0xFFFF) ^ 0xFFFF) + 1; if((argc >= 5) && (argv[4][0] != '-')) { arg_len = gethex(argv[4]); option_argn = 5; } while(option_argn < argc) { const char* s = argv[option_argn]; if (!strcmp(s, "-m0")) { mflag_default = 0; } else if(!strcmp(s, "-m1")) { mflag_default = 1; } else if(!strcmp(s, "-x0")) { xflag_default = 0; } else if(!strcmp(s, "-x1")) { xflag_default = 1; } else if(!strcmp(s, "-noreturn")) { flag_return = 0; } else if(!strcmp(s, "-noguess" )) { flag_guess = 0; } else if(!strcmp(s, "-nofollow")) { flag_follow = 0; } else { printf("unknown option: %s\n", s); return 1; } option_argn++; } printf( "Disassembly of %s\n" "Starting at offset $%lX for $%lX bytes\n" "65816 address starts at $%lX\n" "return=%s guess=%s follow=%s\n" "\n", infilename, (unsigned long)arg_start, (unsigned long)arg_len, (unsigned long)arg_addr, flag_return ? "on" : "off", flag_guess ? "on" : "off", flag_follow ? "on" : "off" ); infile = fopen(infilename, "rb"); if(!infile) { fprintf(stderr, "Error: %s: %s\n", infilename, strerror(errno)); return 1; } disasm_range(arg_start, arg_len, arg_addr); fclose(infile); return 0; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/id3point.c0000644000175000017500000002052511731303760016227 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "id3point - Pointless ID3v1 Tagger" #define COPYR "Copyright (C) 2001,2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// enum { TITLE_START = 3, TITLE_LEN = 30, ARTIST_START = 33, ARTIST_LEN = 30, ALBUM_START = 63, ALBUM_LEN = 30, YEAR_START = 93, YEAR_LEN = 4, COMMENT_START = 97, COMMENT_LEN = 29, TRACKNUM_START = 126, GENRE_START = 127 }; //////////////////////////////////////////////////////////////////////////////// static void usage(const char *name) { banner(); printf( "Usage: %s [options] mp3file(s)\n" "\n" "Options:\n" " -t title Set ID3 title -t- Clear ID3 title\n" " -a artist Set ID3 artist -a- Clear ID3 artist\n" " -m album Set ID3 album -m- Clear ID3 album\n" " -y year Set ID3 year -y- Clear ID3 year\n" " -c comment Set ID3 comment -c- Clear ID3 comment\n" " -k track# Set ID3 track # -k- Clear ID3 track #\n" " -g genre# Set ID3 genre # -g- Clear ID3 genre #\n" " -tf Set ID3 title based on the filename\n" "\n" "Notes:\n" " - Only ID3v1 tags are supported.\n" " - The track number increments automatically for each additional file.\n" " - The -tf option will turn \"Artist - Title.mp3\" into \"Title\", but\n" " be sure to check the titles by hand in case it gets confused.\n", name ); } //////////////////////////////////////////////////////////////////////////////// static void cleanstring( char *s, int size ) { int l = strlen(s) + 1; int z = size - l; if(z > 0) memset(s + l, 0, z); } //////////////////////////////////////////////////////////////////////////////// int main( int argc, char **argv ) { FILE *f = NULL; int returncode = 0; int n; int8_t set_title = 0; char title [TITLE_LEN +1] = {0}; int8_t set_artist = 0; char artist [ARTIST_LEN +1] = {0}; int8_t set_album = 0; char album [ALBUM_LEN +1] = {0}; int8_t set_year = 0; char year [YEAR_LEN +1] = {0}; int8_t set_comment = 0; char comment[COMMENT_LEN+1] = {0}; int8_t set_tracknum = 0; int tracknum = 0; int8_t set_genre = 0; int genre = 0; normalize_argv0(argv[0]); for(n = 1; n < argc; n++) { if(argv[n][0] != '-') break; if(!strcmp(argv[n], "--")) { n++; break; } if(!strcmp(argv[n], "-t")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_title = 1; strncpy(title , argv[n], TITLE_LEN ); } if(!strcmp(argv[n], "-a")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_artist = 1; strncpy(artist , argv[n], ARTIST_LEN ); } if(!strcmp(argv[n], "-m")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_album = 1; strncpy(album , argv[n], ALBUM_LEN ); } if(!strcmp(argv[n], "-y")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_year = 1; strncpy(year , argv[n], YEAR_LEN ); } if(!strcmp(argv[n], "-c")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_comment = 1; strncpy(comment, argv[n], COMMENT_LEN); } if(!strcmp(argv[n], "-k")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_tracknum = 1; tracknum = atoi(argv[n]); } if(!strcmp(argv[n], "-g")) { n++; if(n >= argc) { usage(argv[0]); goto error; } set_genre = 1; genre = atoi(argv[n]); } if(!strcmp(argv[n], "-t-")) { set_title = 1; title [0] = 0; } if(!strcmp(argv[n], "-a-")) { set_artist = 1; artist [0] = 0; } if(!strcmp(argv[n], "-m-")) { set_album = 1; album [0] = 0; } if(!strcmp(argv[n], "-y-")) { set_year = 1; year [0] = 0; } if(!strcmp(argv[n], "-c-")) { set_comment = 1; comment[0] = 0; } if(!strcmp(argv[n], "-k-")) { set_tracknum = 1; tracknum = 0; } if(!strcmp(argv[n], "-g-")) { set_genre = 1; genre = 255; } if(!strcmp(argv[n], "-tf")) { set_title = -1; } } if(n >= argc) { usage(argv[0]); goto error; } cleanstring(title , sizeof(title )); cleanstring(artist , sizeof(artist )); cleanstring(album , sizeof(album )); cleanstring(year , sizeof(year )); cleanstring(comment, sizeof(comment)); for(; n < argc; n++) { char *mp3filename = argv[n]; printf("%s: ", mp3filename); if(f) { fclose(f); f = NULL; } f = fopen(mp3filename, "r+b"); if(!f) { printf("%s\n", strerror(errno)); returncode = 1; continue; } // // File must be at least 128 bytes // fseeko(f, 0, SEEK_END); if(ftello(f) < 128) { fclose(f); f = NULL; printf("file is too short\n"); returncode = 1; continue; } // // See if there's an ID3 tag, and if not, create one // fseeko(f, -128, SEEK_END); if( (fgetc(f) != 'T') || (fgetc(f) != 'A') || (fgetc(f) != 'G') ) { int i; printf("(creating tag) "); fseeko(f, 0, SEEK_END); fputc('T', f); fputc('A', f); fputc('G', f); for(i = 3; i < 127; i++) fputc(0, f); fputc(255, f); } // // Get title from the filename if we need to // if(set_title == -1) { char *m; m = strrchr(mp3filename, '-'); if(!m) { m = mp3filename; } else { m++; } // // Skip spaces/underscores // while(((*m) == ' ') || ((*m) == '_')) m++; // // Skip track numbers // while((*m >= '0') && (*m <= '9')) m++; // // Skip more spaces/underscores // while(((*m) == ' ') || ((*m) == '_')) m++; strncpy(title, m, TITLE_LEN); m = strchr(title, '.'); if(m) *m = 0; while((m = strchr (title, '_')) != NULL) { *m = ' '; } while(strlen(title) && title[strlen(title) - 1] == ' ') { title[strlen(title) - 1] = 0; // rare case: difficult to test in DOS } cleanstring(title, sizeof(title)); } // // Set various things // if(set_title ) { fseeko(f, -128 + TITLE_START , SEEK_END); fwrite(title , TITLE_LEN , 1, f); } if(set_artist ) { fseeko(f, -128 + ARTIST_START , SEEK_END); fwrite(artist , ARTIST_LEN , 1, f); } if(set_album ) { fseeko(f, -128 + ALBUM_START , SEEK_END); fwrite(album , ALBUM_LEN , 1, f); } if(set_year ) { fseeko(f, -128 + YEAR_START , SEEK_END); fwrite(year , YEAR_LEN , 1, f); } if(set_comment ) { fseeko(f, -128 + COMMENT_START , SEEK_END); fwrite(comment, COMMENT_LEN, 1, f); } if(set_tracknum) { fseeko(f, -128 + TRACKNUM_START, SEEK_END); fputc(tracknum, f); } if(set_genre ) { fseeko(f, -128 + GENRE_START , SEEK_END); fputc(genre, f); } fclose(f); f = NULL; printf("ok\n"); if(tracknum) { tracknum++; } } goto done; error: returncode = 1; done: if(f) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/pecompat.c0000644000175000017500000004146511731303760016314 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "pecompat - Maximize compatibility of a Win32 PE file" #define COPYR "Copyright (C) 2012 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// // // Seek in a way that doesn't involve seeking past the end of the file // void safe_seek(FILE* f, unsigned long offset) { long limit; clearerr(f); fseek(f, 0, SEEK_END); if(ferror(f)) { return; } limit = ftell(f); if(ferror(f)) { return; } if(limit >= 0) { if(offset > ((unsigned long)limit)) { fgetc(f); // force EOF return; } } fseek(f, offset, SEEK_SET); } //////////////////////////////////////////////////////////////////////////////// unsigned get16lsb(FILE* f) { int c0, c1; clearerr(f); c0 = fgetc(f); if(ferror(f) || feof(f)) { return 0; } c1 = fgetc(f); if(ferror(f) || feof(f)) { return 0; } return (((unsigned)(c1 & 0xff)) << 8) + (((unsigned)(c0 & 0xff)) ); } unsigned get16lsb_at(FILE* f, unsigned long offset) { safe_seek(f, offset); if(ferror(f) || feof(f)) { return 0; } return get16lsb(f); } unsigned long get32lsb(FILE* f) { int c0, c1, c2, c3; clearerr(f); c0 = fgetc(f); if(ferror(f) || feof(f)) { return 0; } c1 = fgetc(f); if(ferror(f) || feof(f)) { return 0; } c2 = fgetc(f); if(ferror(f) || feof(f)) { return 0; } c3 = fgetc(f); if(ferror(f) || feof(f)) { return 0; } return (((unsigned long)(c3 & 0xff)) << 24) + (((unsigned long)(c2 & 0xff)) << 16) + (((unsigned long)(c1 & 0xff)) << 8) + (((unsigned long)(c0 & 0xff)) ); } unsigned long get32lsb_at(FILE* f, unsigned long offset) { safe_seek(f, offset); if(ferror(f) || feof(f)) { return 0; } return get32lsb(f); } int put16lsb(unsigned value, FILE* f) { clearerr(f); fputc(((value >> 0) & 0xff), f); if(ferror(f) || feof(f)) { return 1; } fputc(((value >> 8) & 0xff), f); if(ferror(f) || feof(f)) { return 1; } fflush(f); return 0; } int put16lsb_at(unsigned value, FILE* f, unsigned long offset) { safe_seek(f, offset); if(ferror(f) || feof(f)) { return 0; } return put16lsb(value, f); } int put32lsb(unsigned long value, FILE* f) { clearerr(f); fputc(((value >> 0) & 0xff), f); if(ferror(f) || feof(f)) { return 1; } fputc(((value >> 8) & 0xff), f); if(ferror(f) || feof(f)) { return 1; } fputc(((value >> 16) & 0xff), f); if(ferror(f) || feof(f)) { return 1; } fputc(((value >> 24) & 0xff), f); if(ferror(f) || feof(f)) { return 1; } fflush(f); return 0; } int put32lsb_at(unsigned long value, FILE* f, unsigned long offset) { safe_seek(f, offset); if(ferror(f) || feof(f)) { return 0; } return put32lsb(value, f); } //////////////////////////////////////////////////////////////////////////////// // // Convert virtual address to file offset // Returns 0 if not found // unsigned long virtual_to_fileoffset(FILE* f, unsigned long v) { unsigned long pe; unsigned long imagebase; unsigned long obj; unsigned long nobjs; unsigned long i; pe = get32lsb_at(f, 0x3c); if(ferror(f) || feof(f)) { return 0; } imagebase = get32lsb_at(f, pe + 0x34); if(ferror(f) || feof(f)) { return 0; } nobjs = get16lsb_at(f, pe + 0x06); if(ferror(f) || feof(f)) { return 0; } obj = pe + 0x18 + get16lsb_at(f, pe + 0x14); if(ferror(f) || feof(f)) { return 0; } for(i = 0; i < nobjs; i++) { unsigned long record = 0x28 * i + obj; unsigned long vsize; unsigned long vaddr; unsigned long psize; unsigned long fileoffset; unsigned long size; vsize = get32lsb_at(f, record + 0x08); if(ferror(f) || feof(f)) { return 0; } vaddr = get32lsb_at(f, record + 0x0c) + imagebase; if(ferror(f) || feof(f)) { return 0; } psize = get32lsb_at(f, record + 0x10); if(ferror(f) || feof(f)) { return 0; } fileoffset = get32lsb_at(f, record + 0x14); if(ferror(f) || feof(f)) { return 0; } size = vsize; if(size > psize) { size = psize; } if((v >= vaddr) && (v < (vaddr + size))) { return (v - vaddr) + fileoffset; } } return 0; } //////////////////////////////////////////////////////////////////////////////// void dumpstring(FILE* f, unsigned long offset) { safe_seek(f, offset); if(ferror(f) || feof(f)) { return; } for(;;) { int c = fgetc(f); if((c == 0) || (c == EOF) || (!isprint(c))) { break; } fputc(c, stdout); } } //////////////////////////////////////////////////////////////////////////////// int fixpe(const char* filename) { int returnvalue = 1; FILE* f = NULL; unsigned long pe_header; unsigned cpu_type; unsigned long old_pe_checksum; unsigned long new_pe_checksum; f = fopen(filename, "r+b"); if(!f) { goto fileerror; } // // Check MZ header // { unsigned mz = get16lsb_at(f, 0); if(ferror(f) || feof(f)) { goto fileerror; } if(mz != 0x5a4d) { printf("%s: Error: Incorrect MZ signature\n", filename); goto error; } } // // Check PE header // pe_header = get32lsb_at(f, 0x3c); if(ferror(f)) { goto fileerror; } if(feof(f)) { printf("%s: Error: Too short, not a PE file\n", filename); goto error; } { unsigned long pe = get32lsb_at(f, pe_header); if(ferror(f)) { goto fileerror; } if(feof(f)) { printf("%s: Error: PE signature not found\n", filename); goto error; } if(pe != 0x00004550) { printf("%s: Error: Incorrect PE signature\n", filename); goto error; } } // // Check CPU type (but don't patch it) // cpu_type = get16lsb_at(f, pe_header+0x04); if(ferror(f) || feof(f)) { goto fileerror; } switch(cpu_type) { case 0x014c: // 80386 - OK break; case 0x014d: case 0x014e: // 80486 or 80586 - warn printf("%s: Warning: CPU type of 0x%x is not strictly 80386 compatible\n", filename, cpu_type); break; case 0x8664: // x86-64 - will not work printf("%s: Error: x86-64 architecture; not supported\n", filename); goto error; default: // Unknown architecture printf("%s: Error: Unknown CPU architecture 0x%x\n", filename, cpu_type); goto error; } // // Patch the linker timestamp // { unsigned long old_timestamp; unsigned long new_timestamp = 0; old_timestamp = get32lsb_at(f, pe_header+0x08); if(ferror(f) || feof(f)) { goto fileerror; } if(old_timestamp != new_timestamp) { printf("%s: Patching linker timestamp: 0x%lx -> 0x%lx\n", filename, old_timestamp, new_timestamp ); if(put32lsb_at(new_timestamp, f, pe_header+0x08)) { goto fileerror; } } } // // Patch the OS version // { unsigned old_os_major; unsigned old_os_minor; unsigned new_os_major = 4; unsigned new_os_minor = 0; old_os_major = get16lsb_at(f, pe_header+0x40); if(ferror(f) || feof(f)) { goto fileerror; } old_os_minor = get16lsb_at(f, pe_header+0x42); if(ferror(f) || feof(f)) { goto fileerror; } if( old_os_major != new_os_major || old_os_minor != new_os_minor ) { printf("%s: Patching OS version: %u.%u -> %u.%u\n", filename, old_os_major, old_os_minor, new_os_major, new_os_minor ); if(put16lsb_at(new_os_major, f, pe_header+0x40)) { goto fileerror; } if(put16lsb_at(new_os_minor, f, pe_header+0x42)) { goto fileerror; } } } // // Patch the subsystem version // { unsigned old_sub_major; unsigned old_sub_minor; unsigned new_sub_major = 4; unsigned new_sub_minor = 0; old_sub_major = get16lsb_at(f, pe_header+0x48); if(ferror(f) || feof(f)) { goto fileerror; } old_sub_minor = get16lsb_at(f, pe_header+0x4a); if(ferror(f) || feof(f)) { goto fileerror; } if( old_sub_major != new_sub_major || old_sub_minor != new_sub_minor ) { printf("%s: Patching subsystem version: %u.%u -> %u.%u\n", filename, old_sub_major, old_sub_minor, new_sub_major, new_sub_minor ); if(put16lsb_at(new_sub_major, f, pe_header+0x48)) { goto fileerror; } if(put16lsb_at(new_sub_minor, f, pe_header+0x4a)) { goto fileerror; } } } // // Grab the old PE checksum // old_pe_checksum = get32lsb_at(f, pe_header+0x58); if(ferror(f) || feof(f)) { goto fileerror; } // // Calculate the new PE checksum // new_pe_checksum = 0; { unsigned long offset = 0; safe_seek(f, 0); if(ferror(f) || feof(f)) { goto fileerror; } for(;;) { unsigned long len = 0; int c0, c1; c0 = fgetc(f); if(ferror(f)) { goto fileerror; } if(c0 == EOF) { break; } else { len++; } c1 = fgetc(f); if(ferror(f)) { goto fileerror; } if(c1 == EOF) { c1 = 0; } else { len++; } // // Treat existing checksum field as zero for purposes of checksumming // if( offset >= (pe_header + 0x58) && offset < (pe_header + 0x5c) ) { c0 = c1 = 0; } // // Add word with carry // { unsigned long word = (((unsigned long)(c0 & 0xff)) << 0) + (((unsigned long)(c1 & 0xff)) << 8); new_pe_checksum += word; new_pe_checksum += (new_pe_checksum >> 16); new_pe_checksum &= ((unsigned long)(0xffff)); } offset += len; } // // Finally, add the file size // new_pe_checksum += offset; } // // Patch checksum if necessary // if(old_pe_checksum != new_pe_checksum) { printf("%s: Patching checksum: 0x%lx -> 0x%lx\n", filename, old_pe_checksum, new_pe_checksum ); if(put32lsb_at(new_pe_checksum, f, pe_header+0x58)) { goto fileerror; } } // // Look at the import table // { unsigned long imagebase; unsigned long import_table_vaddr; unsigned long import_table_size; unsigned long import_table_fileoffset; unsigned long i; unsigned long warned_functions = 0; unsigned long max_warned_functions = 5; imagebase = get32lsb_at(f, pe_header+0x34); if(ferror(f) || feof(f)) { goto fileerror; } import_table_vaddr = get32lsb_at(f, pe_header+0x80) + imagebase; if(ferror(f) || feof(f)) { goto fileerror; } import_table_size = get32lsb_at(f, pe_header+0x84); if(ferror(f) || feof(f)) { goto fileerror; } import_table_fileoffset = virtual_to_fileoffset(f, import_table_vaddr); if(ferror(f) || feof(f)) { goto fileerror; } if(!import_table_fileoffset) { printf("%s: Error: Unable to find import table\n", filename); goto error; } for(i = 0; i < import_table_size; i += 0x14) { unsigned long function_list_vaddr; unsigned long dll_name_vaddr; unsigned long function_list_fileoffset; unsigned long dll_name_fileoffset; function_list_vaddr = get32lsb_at(f, import_table_fileoffset + i + 0x00); if(ferror(f) || feof(f)) { goto fileerror; } dll_name_vaddr = get32lsb_at(f, import_table_fileoffset + i + 0x0c); if(ferror(f) || feof(f)) { goto fileerror; } // // These lists seem to be NULL-terminated // if(function_list_vaddr == 0) { break; } if(dll_name_vaddr == 0) { break; } function_list_vaddr += imagebase; dll_name_vaddr += imagebase; function_list_fileoffset = virtual_to_fileoffset(f, function_list_vaddr); if(ferror(f) || feof(f)) { goto fileerror; } dll_name_fileoffset = virtual_to_fileoffset(f, dll_name_vaddr); if(ferror(f) || feof(f)) { goto fileerror; } if(!function_list_fileoffset) { printf("%s: Error: Malformed import table: Unable to map function list address 0x%lx\n", filename, function_list_vaddr ); goto error; } if(!dll_name_fileoffset) { printf("%s: Error: Malformed import table: Unable to map DLL filename address 0x%lx\n", filename, dll_name_vaddr ); goto error; } for(;;) { int c0 = 0, c1 = 0; unsigned long methodname_vaddr; unsigned long methodname_fileoffset; methodname_vaddr = get32lsb_at(f, function_list_fileoffset); if(ferror(f) || feof(f)) { goto fileerror; } if(methodname_vaddr == 0) { break; } methodname_vaddr += imagebase; function_list_fileoffset += 4; methodname_fileoffset = virtual_to_fileoffset(f, methodname_vaddr); if(ferror(f) || feof(f)) { goto fileerror; } if(!methodname_fileoffset) { printf("%s: Error: Malformed import table: Unable to map method name address 0x%lx\n", filename, methodname_vaddr ); goto error; } // // Method name ending in 'W'? // safe_seek(f, methodname_fileoffset + 2); if(ferror(f) || feof(f)) { goto fileerror; } for(;;) { c0 = c1; c1 = fgetc(f); if(c1 == 0 || c1 == EOF) { break; } } if(c0 == 'W') { if(warned_functions < max_warned_functions) { if(warned_functions == 0) { printf("%s: Warning: The following Unicode imports are used:\n", filename ); } printf(" "); dumpstring(f, dll_name_fileoffset); printf(": "); dumpstring(f, methodname_fileoffset + 2); printf("\n"); } warned_functions++; } } } if(warned_functions > max_warned_functions) { printf(" ...plus %lu more\n", (warned_functions - max_warned_functions)); } } printf("%s: Done\n", filename); returnvalue = 0; goto done; fileerror: if((!f) || ferror(f)) { printf("%s: Error: %s\n", filename, strerror(errno)); } else if(feof(f)) { printf("%s: Error: Unexpected end of file\n", filename); } else { printf("%s: Error: Unknown error\n", filename); } goto error; error: returnvalue = 1; done: if(f) { fclose(f); } return returnvalue; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int error = 0; int i; normalize_argv0(argv[0]); if(argc < 2) { banner(); printf("Usage: %s pe_exe_file(s)\n", argv[0]); return 1; } for(i = 1; i < argc; i++) { if(fixpe(argv[i])) { error = 1; } } return error; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/rels.c0000644000175000017500000001430211731303760015437 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "rels - Relative Searcher" #define COPYR "Copyright (C) 2002,2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// void report( off_t filepos, const uint8_t* src, size_t len, const char* type ) { fprinthex(stdout, filepos, 8); printf(": "); while(len--) { uint8_t c = *src++; printf("%02X ", c); } printf("(%s)\n", type); } //////////////////////////////////////////////////////////////////////////////// int matchtest( const uint8_t* string, const uint8_t* buffer, size_t increment, int shift ) { int16_t stringstart; int16_t bufferstart; for(;;) { uint8_t c = *string; if(!c) { return 1; } if(c != '.') { stringstart = ((int16_t)( c )) & 0xFF; bufferstart = ((int16_t)(*buffer)) & 0xFF; break; } string++; buffer += increment; } for(;;) { uint8_t c = *string; if(!c) { break; } if(c != '.') { int16_t stringnow = ((int16_t)( c )) & 0xFF; int16_t buffernow = ((int16_t)(*buffer)) & 0xFF; stringnow -= stringstart; buffernow -= bufferstart; stringnow <<= shift; if(stringnow != buffernow) { return 0; } } string++; buffer += increment; } return 1; } //////////////////////////////////////////////////////////////////////////////// off_t relsearch( const uint8_t* string, const char* filename ) { FILE* f = NULL; uint8_t* buffer = NULL; size_t stringlen; size_t buffersize; off_t matchesfound = 0; off_t bufferbase; size_t bufferpos; size_t bufferlen; // // Examine length of search string // stringlen = strlen((const char*)string); // Avoid overflow if(stringlen > (((size_t)(-1)) / 2)) { printf("String is too long\n"); // very rare case goto done; // very rare case } // // Allocate buffer // buffersize = 2 * stringlen - 1; if(buffersize < 4096) { buffersize = 4096; } buffer = malloc(buffersize); if(!buffer) { printf("Out of memory\n"); goto done; } f = fopen(filename, "rb"); if(!f) { goto error_f; } printf("%s: ", filename); bufferbase = 0; bufferpos = 0; bufferlen = 0; for(;;) { size_t readsize; if(bufferlen && ((buffersize - bufferpos) < (2 * stringlen - 1))) { memmove(buffer, buffer + bufferpos, bufferlen); bufferbase += bufferpos; bufferpos = 0; } readsize = buffersize - (bufferpos + bufferlen); if((readsize > 0) && (!feof(f))) { readsize = fread(buffer + (bufferpos + bufferlen), 1, readsize, f); bufferlen += readsize; } if(bufferlen < stringlen) break; if(matchtest(string, buffer + bufferpos, 1, 0)) { if(matchesfound < 1) printf("\n"); matchesfound++; report(bufferbase + bufferpos, buffer + bufferpos, stringlen, "normal"); } else if(matchtest(string, buffer + bufferpos, 1, 1)) { if(matchesfound < 1) printf("\n"); matchesfound++; report(bufferbase + bufferpos, buffer + bufferpos, stringlen, "double"); } if(bufferlen >= (2 * stringlen - 1)) { if(matchtest(string, buffer + bufferpos, 2, 0)) { if(matchesfound < 1) printf("\n"); matchesfound++; report(bufferbase + bufferpos, buffer + bufferpos, 2 * stringlen - 1, "wide"); } else if(matchtest(string, buffer + bufferpos, 2, 1)) { if(matchesfound < 1) printf("\n"); matchesfound++; report(bufferbase + bufferpos, buffer + bufferpos, 2 * stringlen - 1, "wide double"); } } bufferpos++; bufferlen--; } printf( "%lu match%s found\n", (unsigned long)matchesfound, (matchesfound == 1) ? "" : "es" ); goto done; error_f: printfileerror(f, filename); done: if(f != NULL) { fclose(f); } if(buffer != NULL) { free(buffer); } return matchesfound; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { const uint8_t* string; int i; off_t total = 0; normalize_argv0(argv[0]); if(argc < 3) { banner(); printf( "Usage: %s string files\n" "\n" "Search string may include '.' characters as wildcards, but must include at\n" "least two non-wildcard characters.\n", argv[0] ); return 1; } string = (const uint8_t*)(argv[1]); { size_t nwc = 0; const uint8_t* s = string; for(;;) { uint8_t c = *s++; if(!c) { break; } if(c != '.') { nwc++; } } if(nwc < 2) { printf( "Search string must contain at least two non-wildcard characters\n" ); return 1; } } printf("Searching for \"%s\":\n", string); for(i = 2; i < argc; i++) { total += relsearch(string, argv[i]); } printf( "Total: %lu %s found\n", (unsigned long)total, (total == 1) ? "match" : "matches" ); return 0; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/screamf.c0000644000175000017500000006356111731303760016125 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "screamf - .AMF to .S3M converter" #define COPYR "Copyright (C) 1996,2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// // S3M parapointer limit static const off_t S3MFILESIZELIMIT = (off_t)0xFFFFFLU; // Pattern size limit static const off_t S3MPATTERNSIZELIMIT = (off_t) 0xFFFFLU; //////////////////////////////////////////////////////////////////////////////// struct INSTRUMENT { char name [33]; char filename[14]; uint8_t sampled; uint32_t samplelength; uint32_t loopstart; uint32_t loopend; uint16_t c4spd; uint8_t defaultvol; uint8_t* sampledata; }; struct PLACE { int8_t note; int8_t octave; int8_t instrument; int8_t effect; int16_t volume; int16_t parameter; }; struct TRACK { struct PLACE place[64]; }; struct MODULE { char title[33]; uint8_t insnum; uint8_t ordnum; size_t tracknum; // AMF only uint8_t channels; int8_t panposition[32]; uint8_t tempo; uint8_t speed; }; //////////////////////////////////////////////////////////////////////////////// static void fput32lsb(uint32_t c, FILE* stream) { fputc(((c ) & 0xFF), stream); fputc(((c >> 8) & 0xFF), stream); fputc(((c >> 16) & 0xFF), stream); fputc(((c >> 24) & 0xFF), stream); } static void fput16lsb(uint16_t c, FILE* stream) { fputc(((c ) & 0xFF), stream); fputc(((c >> 8) & 0xFF), stream); } static uint32_t fget32lsb(FILE* stream) { uint32_t t; t = (((uint32_t)(fgetc(stream) & 0xFF)) << 0); t |= (((uint32_t)(fgetc(stream) & 0xFF)) << 8); t |= (((uint32_t)(fgetc(stream) & 0xFF)) << 16); t |= (((uint32_t)(fgetc(stream) & 0xFF)) << 24); return t; } static uint16_t fget16lsb(FILE* stream) { uint16_t t; t = (((uint16_t)(fgetc(stream) & 0xFF)) << 0); t |= (((uint16_t)(fgetc(stream) & 0xFF)) << 8); return t; } // // Align file offset to a paragraph (16 bytes) // static void alignpara(FILE* f) { while((ftello(f) & 0xF) != 0) { fputc(0, f); } } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero on error // static int amf_decodetrack( FILE* amffile, struct TRACK* track, uint8_t insnum ) { int16_t i,c,n,row,num,effect; struct PLACE* place = track->place; // // Initialize track to empty/unused // for(i = 0; i < 64; i++) { place[i].note = -1; place[i].octave = -1; place[i].instrument = -1; place[i].volume = -1; place[i].effect = -1; place[i].parameter = -1; } n = fgetc(amffile); num = fgetc(amffile); // lost? effect = fgetc(amffile); // lost? for(c = 0; c < n; c++) { row = fgetc(amffile); num = fgetc(amffile); effect = fgetc(amffile); if(row == 0xFF) { break; } if(row >= 64) { printf("row out of bounds"); goto errorat; } if(num == 0x80) { for(i = row; i < 64; i++) { if(effect >= insnum) { printf("instrument out of bounds"); goto errorat; } place[i].instrument = (int8_t)effect; } } else if(num > 0x80) { place[row].effect = num & 0x7F; place[row].parameter = (int8_t)effect; } else { place[row].note = num % 12; place[row].octave = num / 12; place[row].volume = effect; } } // // Postprocess the track // for(i = 0; i < 64; i++) { // // remove phantom instruments // if(place[i].note == -1) { place[i].instrument = -1; } // // Convert effects // switch(place[i].effect) { case -1: break; case 1: // Set Speed [A] place[i].effect='A'-64; break; case 2: // Volume Slide [D] place[i].effect='D'-64; // // Convert to S3M style // if(place[i].parameter < 0) { place[i].parameter=-(place[i].parameter); } else { place[i].parameter<<=4; } break; case 3: // Volume Change // (What's this doing in here?) place[i].volume = place[i].parameter; place[i].effect = -1; place[i].parameter = -1; break; case 4: // Portamento [E]+, [F]- if(place[i].parameter < 0) { place[i].effect='F'-64; place[i].parameter=-(place[i].parameter); } else { place[i].effect='E'-64; } break; case 6: // Tone Portamento [G] place[i].effect='G'-64; break; case 7: // Tremolo [R] place[i].effect='R'-64; break; case 8: // [J] place[i].effect='J'-64; break; case 9: // [H] place[i].effect='H'-64; break; case 10: // [L] (negative) place[i].effect='L'-64; place[i].parameter=-(place[i].parameter); break; case 11: // [K] (negative) place[i].effect='K'-64; place[i].parameter=-(place[i].parameter); break; case 12: // [C] place[i].effect='C'-64; break; case 13: // [B] place[i].effect='B'-64; break; case 15: // [Q] place[i].effect='Q'-64; break; case 16: // Set Sample Offset [O] place[i].effect='O'-64; break; case 17: // Find Volume Slide [DxF]+, [DFx]- place[i].effect='D'-64; // // convert to S3M style // if(place[i].parameter<(-14))place[i].parameter=(-14); if(place[i].parameter>( 14))place[i].parameter=( 14); if(place[i].parameter<0) { place[i].parameter=-(place[i].parameter); place[i].parameter|=0xF0; } else if(place[i].parameter>0) { place[i].parameter<<=4; place[i].parameter|=0x0F; } else { place[i].effect=-1; place[i].parameter=-1; } break; case 18: // Fine Portamento [EF]+, [FF]- if(place[i].parameter<0) { place[i].effect='F'-64; place[i].parameter=-(place[i].parameter); } else { place[i].effect='E'-64; } if(place[i].parameter>0xF)place[i].parameter=0xF; place[i].parameter|=0xF0; break; case 21: // Set Tempo [T] place[i].effect='T'-64; break; case 22: // Extra Fine Portamento [EE]+, [FE]- if(place[i].parameter<0) { place[i].effect='F'-64; place[i].parameter=-(place[i].parameter); } else { place[i].effect='E'-64; } if(place[i].parameter>0xF)place[i].parameter=0xF; place[i].parameter|=0xE0; break; case 23: // [X] place[i].effect='X'-64; break; default: // Remove the unknown effect printf( "Unknown effect %02X-%02X\n", place[i].effect, place[i].parameter ); place[i].effect=-1; break; } } return 0; errorat: printf(" @ 0x"); fprinthex(stdout, ftello(amffile), 1); printf("\n"); return 1; } static void amf_decodeinstrument( FILE* amffile, struct INSTRUMENT* instrument ) { size_t i; instrument->sampled = fgetc(amffile); for(i = 0; i < 32; i++) { instrument->name[i] = fgetc(amffile); } instrument->name[i] = 0; for(i = 0; i < 13; i++) { instrument->filename[i] = fgetc(amffile); } instrument->filename[i] = 0; fget32lsb(amffile); // TODO: unknown instrument->samplelength = fget32lsb(amffile); instrument->c4spd = fget16lsb(amffile); instrument->defaultvol = fgetc (amffile); instrument->loopstart = fget32lsb(amffile); instrument->loopend = fget32lsb(amffile); } static void s3m_writeinstrument( const struct INSTRUMENT* instrument, FILE* f ) { fputc(instrument->sampled, f); fwrite(instrument->filename, 1, 13, f); fput16lsb(0, f); // sample pointer - zero by default fput32lsb(instrument->samplelength, f); fput32lsb(instrument->loopstart, f); fput32lsb(instrument->loopend, f); fputc(instrument->defaultvol, f); fputc(0, f); fputc(0, f); if( instrument->loopstart != 0 || instrument->loopend != 0 ) { fputc(1, f); } else { fputc(0, f); } fput32lsb(instrument->c4spd, f); // // Next 12 bytes are reserved // fput32lsb(0, f); fput32lsb(0, f); fput32lsb(0, f); fwrite(instrument->name, 1, 28, f); fputc('S', f); fputc('C', f); fputc('R', f); fputc('S', f); } //////////////////////////////////////////////////////////////////////////////// static uint8_t s3morderlist[256]; int main(int argc, char** argv) { int returncode = 0; FILE* amffile = NULL; FILE* s3mfile = NULL; const char* amffilename = ""; const char* s3mfilename = ""; uint16_t* ordertable = NULL; uint16_t* tracktable = NULL; struct INSTRUMENT* instrument = NULL; uint16_t* s3mpatterntable = NULL; uint8_t s3mpatterns; struct TRACK** amftrack = NULL; size_t amftracknum = 0; char amfheader[4]; struct MODULE module; off_t fpos_tracktable; off_t fpos_instrument; off_t fpos_samples; off_t s3minstrumentstart; off_t s3mpatternpointers; uint32_t i, j, k; normalize_argv0(argv[0]); if(argc != 3) { banner(); printf( "Usage: %s inputfile.amf outputfile.s3m\n", argv[0] ); goto error; } amffilename = argv[1]; amffile = fopen(amffilename, "rb"); if(!amffile) { goto error_amffile; } amfheader[0] = fgetc(amffile); amfheader[1] = fgetc(amffile); amfheader[2] = fgetc(amffile); amfheader[3] = 0; if(strcmp(amfheader, "AMF")) { printf("'%s' is not an AMF file\n",amffilename); goto conversionfailed; } if(fgetc(amffile) != 0xE) { printf("'%s' - unrecognized AMF version\n",amffilename); goto conversionfailed; } // // Ensure the S3M file doesn't already exist // s3mfilename = argv[2]; s3mfile = fopen(s3mfilename, "rb"); if(s3mfile != NULL) { printf("%s already exists; refusing to overwrite\n", s3mfilename); goto conversionfailed; } for(i = 0; i < 32; i++) { module.title[i] = fgetc(amffile); } module.title[i] = 0; module.insnum = fgetc (amffile); module.ordnum = fgetc (amffile); module.tracknum = fget16lsb(amffile); module.channels = fgetc (amffile); for(i = 0; i < 32; i++) { module.panposition[i] = fgetc(amffile); } module.tempo = fgetc (amffile); module.speed = fgetc (amffile); if(module.insnum == 0) { printf("Module apparently has zero instruments\n"); goto conversionfailed; } if(module.ordnum == 0) { printf("Module apparently has zero orders\n"); goto conversionfailed; } if(module.tracknum == 0) { printf("Module apparently has zero tracks\n"); goto conversionfailed; } if(module.channels == 0) { printf("Module apparently has zero channels\n"); goto conversionfailed; } if(module.channels > 32) { printf("Module reports too many channels (%u); max is 32\n", module.channels); goto conversionfailed; } // // Print out general information // printf( "Title..........%s\n" "Channels.......%lu\n" "Orders.........%lu\n" "Track entries..%lu\n" "Instruments....%lu\n" "Tempo..........%lu bpm\n" "Speed..........%lu\n\n", module.title, (unsigned long)module.channels, (unsigned long)module.ordnum, (unsigned long)module.tracknum, (unsigned long)module.insnum, (unsigned long)module.tempo, (unsigned long)module.speed ); // // Allocate memory for all kinds of things, except AMF tracks // ordertable = malloc(sizeof(*ordertable) * module.channels * module.ordnum); if(!ordertable) { printf("Out of memory\n"); goto conversionfailed; } if(module.tracknum > (((size_t)(-1)) / sizeof(*tracktable))) { printf("Too many tracks (%lu)\n", (unsigned long)module.tracknum); goto conversionfailed; } tracktable = malloc(sizeof(*tracktable) * module.tracknum); if(!tracktable) { printf("Out of memory\n"); goto conversionfailed; } instrument = malloc(sizeof(*instrument) * module.insnum); if(!instrument) { printf("Out of memory\n"); goto conversionfailed; } // // Determine the number of real tracks present // printf("Reading and decoding AMF...\n"); fpos_instrument = (off_t)0x4B + ((((off_t)module.channels + 1) * (off_t)module.ordnum) * 2); fpos_tracktable = (off_t)fpos_instrument + (off_t)65 * (off_t)module.insnum; fseeko(amffile, fpos_tracktable, SEEK_SET); for(i = 0; i < module.tracknum; i++) { tracktable[i] = fget16lsb(amffile); if(tracktable[i] > amftracknum) { amftracknum = tracktable[i]; } // make zero-based if(tracktable[i] > 0) { tracktable[i]--; } } // // Allocate space for real tracks // if(amftracknum > (((size_t)(-1)) / sizeof(*amftrack))) { printf("Too many amftracks (%lu)\n", (unsigned long)amftracknum); goto conversionfailed; } amftrack = malloc(sizeof(*amftrack) * amftracknum); if(!amftrack) { printf("Out of memory\n"); goto conversionfailed; } for(i = 0; i < amftracknum; i++) { amftrack[i] = NULL; } for(i = 0; i < amftracknum; i++) { amftrack[i] = malloc(sizeof(*amftrack[i])); if(!amftrack[i]) { printf("Out of memory\n"); goto conversionfailed; } } // // Decode the AMF tracks // for(i = 0; i < amftracknum; i++) { if(amf_decodetrack(amffile, amftrack[i], module.insnum)) { goto conversionfailed; } } // // Save this place, this is where the samples are stored // fpos_samples = ftello(amffile); // // Now decode the orderlist, replacing track tags with real track numbers // fseeko(amffile, 0x4B, SEEK_SET); for(i = 0; i < module.ordnum; i++) { fget16lsb(amffile); for(j = 0; j < module.channels; j++) { uint16_t x = fget16lsb(amffile); ordertable[i*module.channels+j] = tracktable[x ? x-1 : 0]; } } // // Now decode the instrument headers // for(i = 0; i < module.insnum; i++) { amf_decodeinstrument(amffile, instrument + i); } printf("Processing patterns..."); // // Rearrange the patterns in a more S3M-friendly way // s3mpatterntable = malloc(sizeof(*s3mpatterntable) * module.ordnum * module.channels); if(!s3mpatterntable) { printf("Out of memory\n"); goto conversionfailed; } // // Start numbering S3M patterns with 0 // s3mpatterns = 0; // // Go through the entire AMF orderlist // for(i = 0; i < module.ordnum; i++) { // // Is there already a S3M pattern with this track configuration? // for(j = 0; j < s3mpatterns; j++) { if(!memcmp( s3mpatterntable + j * module.channels, ordertable + i * module.channels, sizeof(*s3mpatterntable) * module.channels )) { break; } } s3morderlist[i] = (uint8_t)j; if(j == s3mpatterns) { // We need to create a new pattern memmove( s3mpatterntable + j * module.channels, ordertable + i * module.channels, sizeof(*s3mpatterntable) * module.channels ); if(s3mpatterns >= 0xFF) { printf("Too many patterns!\n"); goto conversionfailed; } s3mpatterns++; } } printf(" (%u patterns used)\n", s3mpatterns); // // Now s3mpatterns holds the number of S3M patterns required. // (plus, we know how to set up each pattern now) // // // Try creating the S3M file // s3mfile = fopen(s3mfilename, "wb"); if(!s3mfile) { goto error_s3mfile; } // // Begin writing it // printf("Writing S3M header information...\n"); fwrite(module.title, 1, 28, s3mfile); fput32lsb(0x101A, s3mfile); // // OrdNum has to be even in the S3M file, so adjust it // fput16lsb((module.ordnum + 1) & (~1), s3mfile); fput16lsb(module.insnum, s3mfile); fput16lsb(s3mpatterns, s3mfile); fput16lsb(64, s3mfile); // flags fput16lsb(0x1301, s3mfile); // created with Scream Tracker 3.01 fput16lsb(2, s3mfile); // unsigned samples fputc('S', s3mfile); fputc('C', s3mfile); fputc('R', s3mfile); fputc('M', s3mfile); fputc(0x40, s3mfile); // global volume fputc(module.speed, s3mfile); // initial speed fputc(module.tempo, s3mfile); // initial tempo fputc(0xB0, s3mfile); // master volume fputc(16, s3mfile); // ultraclick removal level=8 fputc(0, s3mfile); // don't bother with pan positions // // next 10 bytes are reserved // fputc(0, s3mfile);fputc(0, s3mfile);fputc(0, s3mfile);fputc(0, s3mfile); fputc(0, s3mfile);fputc(0, s3mfile);fputc(0, s3mfile);fputc(0, s3mfile); fputc(0, s3mfile);fputc(0, s3mfile); // // Now set up the default LRLR... panning // for(i = 0; i < module.channels; i++) { fputc(((i & 1) << 3) | (i >> 1), s3mfile); } for(i = module.channels; i < 32; i++) { fputc(0xFF, s3mfile); } // // Write out the orderlist // for(i = 0; i < module.ordnum;i++) { fputc(s3morderlist[i], s3mfile); } // // Adjust for that even-ordnum thing // if(module.ordnum & 1) { fputc(0xFF, s3mfile); module.ordnum++; } // // Precompute and write out where all the instrument headers are going to be // s3minstrumentstart = ( ((0x60 + module.ordnum + 2 * module.insnum + 2 * s3mpatterns) + 0xF) & (~0xF) ); for(i = 0; i < module.insnum; i++) { fput16lsb((uint16_t)((s3minstrumentstart + 80 * i) >> 4), s3mfile); } // // Zero out the pattern parapointers for now // s3mpatternpointers = ftello(s3mfile); for(i = 0; i < s3mpatterns; i++) { fput16lsb(0, s3mfile); } // // Wait until the boundary is an even paragraph // alignpara(s3mfile); // // Write out all instrument headers (making up sample locations) // for(i = 0; i < module.insnum;i++) { s3m_writeinstrument(instrument + i, s3mfile); } // // Squeeze some extra bytes out of each track // for(i = 0; i < amftracknum; i++) { struct PLACE* place = amftrack[i]->place; for(j = 0; j < 64; j++) { if( place[j].note != -1 && place[j].instrument != -1 && place[j].volume == instrument[place[j].instrument].defaultvol ) { place[j].volume = -1; } } } // // Now encode and write patterns // printf("Writing patterns...\n"); for(i = 0; i < s3mpatterns; i++) { off_t pattern_start; off_t pattern_end; // // Align to the next paragraph offset // alignpara(s3mfile); // // Obtain the pattern pointer // pattern_start = ftello(s3mfile); if(pattern_start > S3MFILESIZELIMIT) { printf("S3M file is too large!\n"); goto conversionfailed; } // // Go back and write the pattern parapointer // fseeko(s3mfile, s3mpatternpointers + 2 * i, SEEK_SET); fput16lsb((uint16_t)(pattern_start >> 4), s3mfile); fseeko(s3mfile, pattern_start, SEEK_SET); // Dummy size - fill it in later fput16lsb(0, s3mfile); for(j = 0; j < 64; j++) { for(k = 0; k < module.channels; k++) { struct PLACE* thisplace = amftrack[ s3mpatterntable[module.channels * i + k] ]->place + j; uint8_t s3mbytewhat = 0; if(thisplace->note != -1) { s3mbytewhat |= 0x20; } if(thisplace->volume != -1) { s3mbytewhat |= 0x40; } if(thisplace->effect != -1) { s3mbytewhat |= 0x80; } if(s3mbytewhat != 0) { s3mbytewhat |= k; fputc(s3mbytewhat, s3mfile); if((s3mbytewhat & 0x20) != 0) { if(thisplace->octave > 0) { fputc(((thisplace->note)| (((thisplace->octave)-1)<<4)), s3mfile); fputc(thisplace->instrument+1, s3mfile); } else { // note cut fputc(254, s3mfile); fputc(0, s3mfile); } } if((s3mbytewhat & 0x40) != 0) { fputc(thisplace->volume , s3mfile); } if((s3mbytewhat & 0x80) != 0) { fputc(thisplace->effect , s3mfile); fputc(thisplace->parameter, s3mfile); } } } fputc(0, s3mfile); } // // Mark end of pattern // pattern_end = ftello(s3mfile); if((pattern_end - pattern_start) > S3MPATTERNSIZELIMIT) { printf("S3M pattern is too large!\n"); goto conversionfailed; } // // Go back and write the pattern size // fseeko(s3mfile, pattern_start, SEEK_SET); fput16lsb((uint16_t)(pattern_end - pattern_start), s3mfile); fseeko(s3mfile, pattern_end, SEEK_SET); } // // Now write out the samples // printf("Writing samples...\n"); fseeko(amffile, fpos_samples, SEEK_SET); for(i = 0; i < module.insnum; i++) { if(instrument[i].sampled == 1) { off_t sample_start; // // Align to the next paragraph offset // alignpara(s3mfile); // // Obtain the sample pointer // sample_start = ftello(s3mfile); if(sample_start > S3MFILESIZELIMIT) { printf("S3M file is too large!\n"); goto conversionfailed; } // // Go back and write the sample pointer in the instrument // fseeko(s3mfile, s3minstrumentstart + 80 * i + 14, SEEK_SET); fput16lsb((uint16_t)(sample_start >> 4), s3mfile); fseeko(s3mfile, sample_start, SEEK_SET); // // Copy the actual sample // for(j = 0; j < instrument[i].samplelength; j++) { fputc(fgetc(amffile), s3mfile); } } } printf("Done!\n"); // // Success (hopefully) // goto done; conversionfailed: printf("Conversion failed\n"); goto error; error_amffile: printfileerror(amffile, amffilename); goto error; error_s3mfile: printfileerror(s3mfile, s3mfilename); goto error; error: returncode = 1; done: // // Free up all allocated memory // if(ordertable != NULL) { free(ordertable ); } if(tracktable != NULL) { free(tracktable ); } if(instrument != NULL) { free(instrument ); } if(s3mpatterntable != NULL) { free(s3mpatterntable); } if(amftrack != NULL) { for(i = 0; i < amftracknum; i++) { if(amftrack[i] != NULL) { free(amftrack[i]); } } free(amftrack); } // // Close both files // if(amffile != NULL) { fclose(amffile); } if(s3mfile != NULL) { fclose(s3mfile); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/subfile.c0000644000175000017500000000676211731303760016136 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "subfile - Extract a portion of a file" #define COPYR "Copyright (C) 2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static uint8_t buf[0x8000LU]; int main(int argc, char **argv) { int returncode = 0; FILE *inf = NULL; FILE *outf = NULL; off_t offset = 0; off_t length = 0; off_t in_length; const char *infilename = NULL; const char *outfilename = NULL; normalize_argv0(argv[0]); if(argc != 5) { banner(); printf("Usage: %s infile offset length outfile\n", argv[0]); goto error; } infilename = argv[1]; offset = strtoofft(argv[2], NULL, 0); length = strtoofft(argv[3], NULL, 0); outfilename = argv[4]; if(offset < 0) { printf("Offset must not be negative\n"); goto error; } if(length < 0) { printf("Length must not be negative\n"); goto error; } inf = fopen(infilename, "rb"); if(!inf) { goto infileerror; } clearerr(inf); // // Verify offset and length against the size of the input file // if(fseeko(inf, 0, SEEK_END) != 0) { goto infileerror; } in_length = ftello(inf); if(in_length < 0) { goto infileerror; } if(offset > in_length) { printf("Offset is past the end of %s\n", infilename); goto error; } if(length > in_length) { printf("Length is past the end of %s\n", infilename); goto error; } if(offset > (in_length - length)) { printf("Offset+length is past the end of %s\n", infilename); goto error; } // // Seek to the desired offset // if(fseeko(inf, offset, SEEK_SET) != 0) { goto infileerror; } // // Ensure the output file doesn't already exist // outf = fopen(outfilename, "rb"); if(outf) { printf("Error: %s already exists; cannot overwrite\n", outfilename); goto error; } outf = fopen(outfilename, "wb"); if(!outf) { goto outfileerror; } clearerr(outf); while(length > 0) { size_t r, w; off_t l = length; if(l > ((off_t)sizeof(buf))) { l = sizeof(buf); } r = fread(buf, 1, (size_t)l, inf); if(r != ((size_t)l)) { goto infileerror; } w = fwrite(buf, 1, r, outf); if(w != r) { goto outfileerror; } length -= r; } goto end; infileerror: printfileerror(inf, infilename); goto error; outfileerror: printfileerror(outf, outfilename); goto error; error: returncode = 1; end: if(inf != NULL) { fclose(inf ); } if(outf != NULL) { fclose(outf); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/uips.c0000644000175000017500000003456411731303760015466 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "uips - Universal IPS patch create/apply utility" #define COPYR "Copyright (C) 1999,2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static const off_t IPS_EOF = 0x00454F46L; static const off_t IPS_LIMIT = 0x01000000L; // // Wrapper for fopen that does various things // static FILE *my_fopen(const char *filename, const char *mode, off_t *size) { FILE *f = fopen(filename, mode); if(!f) { goto error; } if(size) { if(fseeko(f, 0, SEEK_END) == -1) { goto error; } *size = ftello(f); if(*size < 0) { goto error; } if(fseeko(f, 0, SEEK_SET) == -1) { goto error; } } return f; error: printfileerror(f, filename); if(f) { fclose(f); } return NULL; } // // Read a number from a file, MSB first // Returns -1 on end of file // static int32_t readvalue(FILE *f, size_t nbytes) { int32_t v = 0; while(nbytes--) { int c = fgetc(f); if(c == EOF) { return -1; } v = (v << 8) | (c & 0xFF); } return v; } // // Write a number to a file, MSB first // static void writevalue(int32_t value, FILE *f, size_t nbytes) { size_t i = nbytes << 3; while(nbytes--) { i -= 8; fputc(value >> i, f); } } // // Search for the next difference between the target file and a number of // source files // static off_t get_next_difference( off_t ofs, FILE **source_file, const off_t *source_size, size_t source_nfiles, FILE *target_file, off_t target_size ) { size_t i; if(ofs >= target_size) { return target_size; } fseeko(target_file, ofs, SEEK_SET); for(i = 0; i < source_nfiles; i++) { if(ofs >= source_size[i]) { return ofs; } } for(i = 0; i < source_nfiles; i++) { fseeko(source_file[i], ofs, SEEK_SET); } for(;;) { int tc = fgetc(target_file); if(tc == EOF) { return target_size; } for(i = 0; i < source_nfiles; i++) { if(fgetc(source_file[i]) != tc) { return ofs; } } ofs++; } } // // Search for the end of a difference block // static off_t get_difference_end( off_t ofs, off_t similar_limit, FILE **source_file, const off_t *source_size, size_t source_nfiles, FILE *target_file, off_t target_size ) { size_t i; off_t similar_rl = 0; if(ofs >= target_size) { return target_size; } fseeko(target_file, ofs, SEEK_SET); for(i = 0; i < source_nfiles; i++) { if(ofs >= source_size[i]) { return target_size; } } for(i = 0; i < source_nfiles; i++) { fseeko(source_file[i], ofs, SEEK_SET); } for(;;) { char is_different = 0; int tc = fgetc(target_file); if(tc == EOF) { return target_size - similar_rl; } for(i = 0; i < source_nfiles; i++) { int fc = fgetc(source_file[i]); if((fc == EOF) || (fc != tc)) { is_different = 1; } } ofs++; if(is_different) { similar_rl = 0; } else { similar_rl++; if(similar_rl == similar_limit) { break; } } } return ofs - similar_rl; } // // Encode a difference block into a patch file // static void encode_patch_block( FILE* patch_file, FILE* target_file, off_t ofs, off_t ofs_end ) { while(ofs < ofs_end) { off_t ofs_block_end; off_t rl; int c; // // Avoid accidental "EOF" marker // if(ofs == IPS_EOF) { ofs--; } // // Write the offset to the patch file // writevalue(ofs, patch_file, 3); fseeko(target_file, ofs, SEEK_SET); // // If there is a beginning run of at least 9 bytes, use it // c = fgetc(target_file); rl = 1; while( (fgetc(target_file) == c) && (rl < 0xFFFF) && ((ofs + rl) < ofs_end) ) { rl++; } // // Encode a run, if the run was long enough // if(rl >= 9) { writevalue( 0, patch_file, 2); writevalue(rl, patch_file, 2); writevalue( c, patch_file, 1); ofs += rl; continue; } // // Search for the end of the block. // The block ends if there's an internal run of at least 14, or an ending // run of at least 9, or the block length == 0xFFFF, or the block reaches // ofs_end. // fseeko(target_file, ofs, SEEK_SET); ofs_block_end = ofs; c = -1; while( (ofs_block_end < ofs_end) && ((ofs_block_end - ofs) < 0xFFFF) ) { int c2 = fgetc(target_file); ofs_block_end++; if(c == c2) { rl++; if(rl == 14) { ofs_block_end -= 14; break; } } else { rl = 1; c = c2; } } // // Look for a sufficiently long ending run // if((ofs_block_end == ofs_end) && (rl >= 9)) { ofs_block_end -= rl; if(ofs_block_end == IPS_EOF) { ofs_block_end++; } } // // Encode a regular patch block // writevalue(ofs_block_end - ofs, patch_file, 2); fseeko(target_file, ofs, SEEK_SET); while(ofs < ofs_block_end) { fputc(fgetc(target_file), patch_file); ofs++; } } } // // Create a patch given a list of source filenames and a target filename. // Returns 0 on success. // static int create_patch( const char *patch_filename, size_t source_nfiles, const char **source_filename, const char *target_filename ) { int returncode = 0; FILE *patch_file = NULL; FILE **source_file = NULL; off_t *source_size = NULL; FILE *target_file = NULL; off_t target_size; off_t ofs; size_t i; char will_truncate = 0; // // Allocate memory for list of source file streams and sizes // if( source_nfiles > (((size_t)(-1)) / sizeof(*source_file)) || source_nfiles > (((size_t)(-1)) / sizeof(*source_size)) || ((source_file = malloc(sizeof(*source_file) * source_nfiles)) == NULL) || ((source_size = malloc(sizeof(*source_size) * source_nfiles)) == NULL) ) { printf("Out of memory\n"); goto err; } for(i = 0; i < source_nfiles; i++) { source_file[i] = NULL; } // // Open target file // target_file = my_fopen(target_filename, "rb", &target_size); if(!target_file) { goto err; } // // Open source files // for(i = 0; i < source_nfiles; i++) { source_file[i] = my_fopen(source_filename[i], "rb", source_size + i); if(!source_file[i]) { goto err; } if(source_size[i] > target_size) { will_truncate = 1; } } // // Create patch file // patch_file = my_fopen(patch_filename, "wb", NULL); if(!patch_file) { goto err; } printf("Creating %s...\n", patch_filename); // // Write "PATCH" signature // if(fwrite("PATCH", 1, 5, patch_file) != 5) { goto err_patch_file; } // // Main patch creation loop // ofs = 0; for(;;) { off_t ofs_end; // // Search for next difference // ofs = get_next_difference( ofs, source_file, source_size, source_nfiles, target_file, target_size ); if(ofs == target_size) { break; } if(ofs >= IPS_LIMIT) { printf("Warning: Differences beyond 16MiB were ignored\n"); break; } // // Determine the length of the difference block // ofs_end = get_difference_end( ofs, 5, source_file, source_size, source_nfiles, target_file, target_size ); // // Encode the difference block into the patch file // encode_patch_block(patch_file, target_file, ofs, ofs_end); ofs = ofs_end; } // // Write EOF marker // writevalue(IPS_EOF, patch_file, 3); if(will_truncate) { if(target_size >= IPS_LIMIT) { printf("Warning: Can't truncate beyond 16MiB\n"); } else { writevalue(target_size, patch_file, 3); } } // // Finished // printf("Done\n"); goto no_err; err_patch_file: printfileerror(patch_file, patch_filename); goto err; err: returncode = 1; no_err: if(patch_file) { fclose(patch_file); } for(i = 0; i < source_nfiles; i++) { if(source_file[i]) { fclose(source_file[i]); } } if(target_file) { fclose(target_file); } if(source_file) { free(source_file); } if(source_size) { free(source_size); } return returncode; } // // Apply a patch to a given target. // Returns 0 on success. // static int apply_patch( const char* patch_filename, const char* target_filename ) { int returncode = 0; FILE *patch_file = NULL; FILE *target_file = NULL; off_t target_size; off_t ofs; // // Open patch file // patch_file = my_fopen(patch_filename, "rb", NULL); if(!patch_file) { goto err; } // // Verify first five characters // if( (fgetc(patch_file) != 'P') || (fgetc(patch_file) != 'A') || (fgetc(patch_file) != 'T') || (fgetc(patch_file) != 'C') || (fgetc(patch_file) != 'H') ) { printf("%s: Invalid patch file format\n", patch_filename); goto err; } // // Open target file // target_file = my_fopen(target_filename, "r+b", &target_size); if(!target_file) { goto err; } printf("Applying %s...\n", patch_filename); // // Main patch application loop // for(;;) { off_t ofs, len; off_t rlen = 0; int rchar = 0; // // Read the beginning of a patch record // ofs = readvalue(patch_file, 3); if(ofs == -1) { goto err_eof; } if(ofs == IPS_EOF) { break; } len = readvalue(patch_file, 2); if(len == -1) { goto err_eof; } if(!len) { rlen = readvalue(patch_file, 2); if(rlen == -1) { goto err_eof; } rchar = fgetc(patch_file); if(rchar == EOF) { goto err_eof; } } // // Seek to the appropriate position in the target file // if(ofs <= target_size) { fseeko(target_file, ofs, SEEK_SET); } else { fseeko(target_file, 0, SEEK_END); while(target_size < ofs) { fputc(0, target_file); target_size++; } } // // Apply patch block // if(len) { ofs += len; if(ofs > target_size) { target_size = ofs; } while(len--) { rchar = fgetc(patch_file); if(rchar == EOF) { goto err_eof; } fputc(rchar, target_file); } } else { ofs += rlen; if(ofs > target_size) { target_size = ofs; } while(rlen--) { fputc(rchar, target_file); } } } // // Perform truncation if necessary // fclose(target_file); target_file = NULL; ofs = readvalue(patch_file, 3); if(ofs != -1 && ofs < target_size) { if(truncate(target_filename, ofs) != 0) { printf("Warning: Truncate failed\n"); } } // // Finished // printf("Done\n"); goto no_err; err_eof: printf( "Error: %s: Unexpected end-of-file; patch incomplete\n", patch_filename ); err: returncode = 1; no_err: if(target_file) { fclose(target_file); } if( patch_file) { fclose( patch_file); } return returncode; } //////////////////////////////////////////////////////////////////////////////// int main( int argc, char **argv ) { int returncode = 1; char cmd; normalize_argv0(argv[0]); if(argc < 2) { banner(); goto usage; } cmd = argv[1][0]; if(cmd && argv[1][1]) { cmd = 0; } switch(cmd) { case 'c': case 'C': if(argc < 5) { goto usage; } returncode = create_patch( argv[2], argc - 4, (const char**)(argv + 3), argv[argc - 1] ); break; case 'a': case 'A': if(argc != 4) { goto usage; } returncode = apply_patch(argv[2], argv[3]); break; default: printf("Unknown command: %s\n", argv[1]); goto usage; } goto done; usage: printf( "Usage:\n" "To create an IPS patch:\n" " %s c patch_file source_file(s) target_file\n" "To apply an IPS patch:\n" " %s a patch_file target_file\n", argv[0], argv[0] ); returncode = 1; done: return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/usfv.c0000644000175000017500000002442211731303760015461 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "usfv - Universal SFV create/verify utility" #define COPYR "Copyright (C) 2003,2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// enum { BIG_FILENAME_SIZE = 30000 }; //////////////////////////////////////////////////////////////////////////////// static int usfv_isspace(int c) { return ( (c == 32) || ((c >= 9) && (c <= 13)) ); } //////////////////////////////////////////////////////////////////////////////// static int getfilecrc( const char *filename, uint32_t *crc_out ) { static uint32_t crctable[256]; static char initialized = 0; uint32_t crc = 0; FILE *f; if(!initialized) { uint32_t i, j, k; for(i = 0; i < 256; i++) { j = i ^ 0xFF; for (k = 0; k < 8; k++) { j = (j & 1) ? 0xEDB88320 ^ (j >> 1) : j >> 1; } crctable[i] = j ^ 0xFF000000; } initialized = 1; } f = fopen(filename, "rb"); if(!f) { return -1; } if(crc_out) { for(;;) { int c = fgetc(f); if(c == EOF) { break; } crc = (crc >> 8) ^ crctable[(crc ^ c) & 0xFF]; } *crc_out = crc; } fclose(f); return 0; } //////////////////////////////////////////////////////////////////////////////// // // Convert a time_t to a struct tm, safely // static struct tm my_localtime(time_t t) { struct tm *p_tm = localtime(&t); if(!p_tm) { t = 0; p_tm = localtime(&t); } if(!p_tm) { struct tm fallback; memset(&fallback, 0, sizeof(fallback)); return fallback; } return (*p_tm); } //////////////////////////////////////////////////////////////////////////////// // // Returns the number of errors // static off_t sfvcreate( char *sfvfilename, char **filename, size_t n ) { off_t nerrors = 0; FILE *sfvfile = NULL; size_t i = 0; off_t nfiles_done = 0; sfvfile = fopen(sfvfilename, "rb"); if(sfvfile) { printf("Error: %s already exists; will not overwrite\n", sfvfilename); goto error; } sfvfile = fopen(sfvfilename, "wb"); if(!sfvfile) { goto error_sfvfile; } printf("Creating SFV file %s\n", sfvfilename); { char buf[24]; size_t r; struct tm my_tm = my_localtime(time(NULL)); memset(buf, 0, sizeof(buf)); r = strftime(buf, sizeof(buf)-1, "%Y-%m-%d at %H:%M.%S", &my_tm); if(r < 1) { strncpy(buf, "9999-99-99 at 99:99.99", sizeof(buf)-1); } fprintf(sfvfile, "; Generated by WIN-SFV32 v1.1a " "(usfv) " "on %s", buf ); } // // Note: SFV newlines have to be in CRLF format, regardless of platform // fputc('\r', sfvfile); fputc('\n', sfvfile); fputc(';' , sfvfile); fputc('\r', sfvfile); fputc('\n', sfvfile); // // Write comments indicating file lengths/times // for(i = 0; i < n; i++) { struct stat mystat; int r; memset(&mystat, 0, sizeof(mystat)); r = stat(filename[i], &mystat); if(r >= 0) { size_t s; struct tm my_tm; char buf[24]; if(S_ISDIR(mystat.st_mode)) { // Skip directories filename[i] = NULL; continue; } my_tm = my_localtime(mystat.st_mtime); memset(buf, 0, sizeof(buf)); s = strftime(buf, sizeof(buf)-1, "%H:%M.%S %Y-%m-%d", &my_tm); if(s < 1) { strncpy(buf, " ", sizeof(buf)-1); } fprintf(sfvfile, ";%13lu %s %s", ((unsigned long)(mystat.st_size)), buf, filename[i]); fputc('\r', sfvfile); fputc('\n', sfvfile); } } // // Calculate CRCs // for(i = 0; i < n; i++) { uint32_t crc = 0; int r; if(!filename[i]) { continue; } printf("%-22s ", filename[i]); fflush(stdout); r = getfilecrc(filename[i], &crc); if(r) { printf("%s\n", strerror(errno)); nerrors++; continue; } printf("%02X%02X%02X%02X\n", (int)((crc >> 24) & 0xFF), (int)((crc >> 16) & 0xFF), (int)((crc >> 8) & 0xFF), (int)((crc >> 0) & 0xFF) ); fprintf(sfvfile, "%s %02X%02X%02X%02X", filename[i], (int)((crc >> 24) & 0xFF), (int)((crc >> 16) & 0xFF), (int)((crc >> 8) & 0xFF), (int)((crc >> 0) & 0xFF) ); fputc('\r', sfvfile); fputc('\n', sfvfile); nfiles_done++; } printf( "%lu file%s processed\n" "%lu error%s encountered\n", (unsigned long)nfiles_done, nfiles_done == 1 ? "" : "s", (unsigned long)nerrors , nerrors == 1 ? "" : "s" ); goto done; error_sfvfile: printfileerror(sfvfile, sfvfilename); goto error; error: nerrors = 1; done: if(sfvfile != NULL) { fclose(sfvfile); } return nerrors; } //////////////////////////////////////////////////////////////////////////////// // // Returns the number of errors // static off_t sfvverify( char *sfvfilename ) { off_t returncode = 0; FILE *sfvfile = NULL; char *filename = NULL; int filename_size = 0; size_t nfiles = 0; size_t nfiles_ok = 0; size_t nfiles_bad = 0; size_t nfiles_err = 0; sfvfile = fopen(sfvfilename, "rb"); if(!sfvfile) { goto error_sfvfile; } printf("Verifying SFV file %s\n", sfvfilename); for(;;) { int c, i, filename_len; const char *crcstr; uint32_t crcnum, filecrcnum; do { c = fgetc(sfvfile); } while(c != EOF && usfv_isspace(c)); if(c == EOF) { break; } // Skip comments if(c == ';') { do { c = fgetc(sfvfile); } while(c != EOF && c != '\n'); if(c == EOF) { break; } continue; } // Assume this is a filename filename_len = 0; for(;;) { if((filename_len + 1) >= filename_size) { if(filename_size > BIG_FILENAME_SIZE) { fflush(stdout); printf("Corrupt SFV file\n"); goto error; } filename_size += 100; filename = realloc(filename, filename_size); if(!filename) { printf("Out of memory\n"); goto error; } } filename[filename_len++] = c; if(!c) { break; } c = fgetc(sfvfile); if(c == EOF || c == '\n') { c = 0; } } filename_len--; while(filename_len && usfv_isspace(filename[filename_len - 1])) { filename_len--; } filename[filename_len] = 0; i = filename_len; while(i && !usfv_isspace(filename[i - 1])) { i--; } crcstr = filename + i; while(i && usfv_isspace(filename[i - 1])) { i--; } // No filename? just one thing on a line? ignore it if(!i) { continue; } filename[i] = 0; crcnum = strtoul(crcstr, NULL, 16); printf("%-22s ", filename); fflush(stdout); filecrcnum = 0; i = getfilecrc(filename, &filecrcnum); if(i) { nfiles_err++; printf("%s\n", strerror(errno)); continue; } nfiles++; if(filecrcnum == crcnum) { nfiles_ok++; printf("ok\n"); } else { nfiles_bad++; printf("*** BAD *** (%02X%02X%02X%02X, should be %02X%02X%02X%02X)\n", (int)((filecrcnum >> 24) & 0xFF), (int)((filecrcnum >> 16) & 0xFF), (int)((filecrcnum >> 8) & 0xFF), (int)((filecrcnum >> 0) & 0xFF), (int)(( crcnum >> 24) & 0xFF), (int)(( crcnum >> 16) & 0xFF), (int)(( crcnum >> 8) & 0xFF), (int)(( crcnum >> 0) & 0xFF) ); } } printf( "%lu file%s checked (%lu ok, %lu bad)\n" "%lu error%s encountered\n", (unsigned long)nfiles , nfiles == 1 ? "" : "s", (unsigned long)nfiles_ok , (unsigned long)nfiles_bad, (unsigned long)nfiles_err, nfiles_err == 1 ? "" : "s" ); returncode = nfiles_err + nfiles_bad; goto done; error_sfvfile: printfileerror(sfvfile, sfvfilename); goto error; error: returncode = 1; done: if(sfvfile != NULL) { fclose(sfvfile); } if(filename != NULL) { free(filename); } return returncode; } //////////////////////////////////////////////////////////////////////////////// int main( int argc, char **argv ) { normalize_argv0(argv[0]); tzset(); if( (argc < 3) || (argv[1][0] == 0) || (argv[1][1] != 0) || (argv[1][0] != 'c' && argv[1][0] != 'v') || (argv[1][0] == 'c' && argc == 3) || (argv[1][0] == 'v' && argc > 3) ) { banner(); printf( "Usage:\n" "To create a SFV file: %s c sfvfile filenames\n" "To verify a SFV file: %s v sfvfile\n", argv[0], argv[0] ); return 1; } if(argv[1][0] == 'c') { return sfvcreate(argv[2], argv + 3, argc - 3); } else { return sfvverify(argv[2]); } } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/vb2rip.c0000644000175000017500000011044511731303760015703 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "vb2rip - VB2 sound format ripping utility" #define COPYR "Copyright (C) 2001,2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// static const char* oom = "Error: Out of memory\n"; //////////////////////////////////////////////////////////////////////////////// struct vb2rip_options { const char* fmt; const char* outname; size_t inputfilecount; int8_t use_channels; int8_t use_honor_endflag; int8_t use_maxbytes; int8_t use_samplerate; int8_t use_offset; int8_t use_interleave; int8_t use_skip; int8_t channels; int8_t honor_endflag; off_t maxbytes; uint32_t samplerate; off_t offset; off_t interleave; off_t skip; }; //////////////////////////////////////////////////////////////////////////////// static uint32_t get32lsb(const uint8_t *data) { return (((uint32_t)(data[0])) ) | (((uint32_t)(data[1])) << 8) | (((uint32_t)(data[2])) << 16) | (((uint32_t)(data[3])) << 24); } static void put32lsb(uint8_t *data, uint32_t value) { data[0] = (uint8_t)(value ); data[1] = (uint8_t)(value >> 8); data[2] = (uint8_t)(value >> 16); data[3] = (uint8_t)(value >> 24); } //////////////////////////////////////////////////////////////////////////////// static FILE *wav_create( const char* filename, uint8_t channels, uint32_t samplerate ) { // .WAV file header uint8_t wavhdr[0x2C] = { 0x52,0x49,0x46,0x46,0x00,0x00,0x00,0x00,0x57,0x41,0x56,0x45,0x66,0x6D,0x74,0x20, 0x10,0x00,0x00,0x00,0x01,0x00,0x02,0x00,0x44,0xAC,0x00,0x00,0x10,0xB1,0x02,0x00, 0x04,0x00,0x10,0x00,0x64,0x61,0x74,0x61,0x00,0x00,0x00,0x00 }; FILE *f = fopen(filename, "wb"); if(!f) { goto error; } wavhdr[0x16] = channels; put32lsb(wavhdr + 0x18, samplerate); put32lsb(wavhdr + 0x1C, samplerate * channels * 2); if(fwrite(wavhdr, 1, sizeof(wavhdr), f) != sizeof(wavhdr)) { goto error; } return f; error: printfileerror(f, filename); if(f) { fclose(f); } return NULL; } //////////////////////////////////////////////////////////////////////////////// // // Returns nonzero on error // static int wav_close(FILE *f) { off_t tl = ftello(f); uint8_t buf[4]; if(tl == -1) { goto error; } fflush(f); if(fseeko(f, 0x04, SEEK_SET) != 0) { goto error; } put32lsb(buf, (uint32_t)(tl - 0x08)); if(fwrite(buf, 1, 4, f) != 4) { goto error; } fflush(f); if(fseeko(f, 0x28, SEEK_SET) != 0) { goto error; } put32lsb(buf, (uint32_t)(tl - 0x2C)); if(fwrite(buf, 1, 4, f) != 4) { goto error; } fflush(f); if(fseeko(f, tl, SEEK_SET) != 0) { goto error; } fflush(f); fclose(f); return 0; error: printfileerror(f, NULL); fclose(f); return 1; } //////////////////////////////////////////////////////////////////////////////// // // Decode a line of samples // static void decodeline( const uint8_t* src, int16_t* outbuf, int32_t* p1, int32_t* p2 ) { static int32_t coef[5][2] = { { 0, 0}, { 60, 0}, {115, -52}, { 98, -55}, {122, -60} }; int32_t c; size_t i; uint8_t fm = *src++; uint32_t filter = (fm >> 4) & 0xF; uint32_t magnitude = (fm ) & 0xF; if(magnitude > 12 || filter > 4) { magnitude = 12; filter = 0; } src++; for(i = 0; i < 14; i++) { uint32_t d = *src++; int32_t d1 = (d & 0x0F) << (12 + 16); int32_t d2 = (d & 0xF0) << ( 8 + 16); d1 >>= magnitude + 16; d2 >>= magnitude + 16; c = d1 + ((((*p1) * coef[filter][0]) + ((*p2) * coef[filter][1])) >> 6); if(c < -32768) c = -32768; if(c > 32767) c = 32767; *outbuf++ = (int16_t)c; (*p2) = (*p1); (*p1) = c; c = d2 + ((((*p1) * coef[filter][0]) + ((*p2) * coef[filter][1])) >> 6); if(c < -32768) c = -32768; if(c > 32767) c = 32767; *outbuf++ = (int16_t)c; (*p2) = (*p1); (*p1) = c; } } //////////////////////////////////////////////////////////////////////////////// static int cmpcase(const char* a, const char* b) { for(;;) { int ca = (*a++) & 0xFF; int cb = (*b++) & 0xFF; int la = tolower(ca) & 0xFF; int lb = tolower(cb) & 0xFF; if(la != lb) { return (la - lb); } if(!la) { return 0; } } } //////////////////////////////////////////////////////////////////////////////// // // callback which should detect the beginning of a new block // typedef off_t (*blockdetect_t)(FILE* f, off_t ofs, off_t size); //////////////////////////////////////////////////////////////////////////////// // // returns the number of errors // static int rip( FILE *inf, struct vb2rip_options opts, blockdetect_t blockdetect ) { int returncode = 1; char *outname = NULL; uint8_t *block = NULL; uint8_t *block_r = NULL; FILE *outf = NULL; off_t in_start; off_t in_end; off_t in_pos; off_t out_indicator_pos; size_t readsize; int8_t endflag = 0; int32_t p1[2] = {0, 0}; // per channel int32_t p2[2] = {0, 0}; // per channel in_pos = in_start = ftello(inf); if(in_start == -1) { goto error_in; } if(fseeko(inf, 0, SEEK_END) != 0) { goto error_in; } in_end = ftello(inf); if(in_end == -1) { goto error_in; } if(fseeko(inf, in_start, SEEK_SET) != 0) { goto error_in; } // use a default for the output filename if it doesn't exist if(!opts.outname) { opts.outname = "out"; } { size_t outname_l = strlen(opts.outname); outname = malloc(outname_l + 4 + 1); if(!outname) { printf("%s", oom); goto error; } strcpy(outname, opts.outname); if( (outname_l < 4) || cmpcase(outname + outname_l - 4, ".wav") ) { strcat(outname, ".wav"); } } printf("writing %s: ", outname); fflush(stdout); // fill in and validate all parts of opts // channel count if(!opts.use_channels) { opts.channels = 1; } if(opts.channels < 1 || opts.channels > 2) { printf("invalid channel count (%d)", (int)opts.channels); goto error; } // honor end flag if(!opts.use_honor_endflag) { opts.honor_endflag = 1; } // max bytes will be used/checked later // sample rate if(!opts.use_samplerate) { opts.samplerate = 44100; } // offset if(!opts.use_offset) { opts.offset = 0; } // interleave size // defaults to 16K for stereo, 16 bytes (the minimum) for mono if(!opts.use_interleave) { opts.interleave = (opts.channels == 2) ? 0x4000 : 0x10; } if((opts.interleave < 1) || ((opts.interleave) & 0xF)) { printf("invalid interleave size ("); fprintdec(stdout, opts.interleave); printf("); must be a positive multiple of 16"); goto error; } // skip if(!opts.use_skip) { opts.skip = 0; } // apply the starting offset if necessary in_start += opts.offset; in_pos = in_start; // max bytes if(opts.use_maxbytes) { if(opts.maxbytes < (in_end - in_start)) { in_end = in_start + opts.maxbytes; } } // // allocate input blocks // readsize = (size_t)(opts.interleave < 0x8000 ? opts.interleave : 0x8000); block = malloc(readsize); if(!block) { printf("%s", oom); goto error; } if(opts.channels == 2) { block_r = malloc(readsize); if(!block_r) { printf("%s", oom); goto error; } } // // now, open the output wav file // outf = wav_create(outname, opts.channels, opts.samplerate); if(!outf) { goto error; } out_indicator_pos = ftello(outf); if(out_indicator_pos == -1) { goto error_out; } endflag = 0; for(in_pos = in_start; in_pos < in_end && (in_pos + (opts.channels * opts.interleave)) <= in_end && !endflag; ) { off_t b; // // See if there's a new first block here // if((in_pos != in_start) && (blockdetect)) { off_t size = opts.channels * opts.interleave; if(size > (in_end - in_pos)) { size = in_end - in_pos; } if(blockdetect(inf, in_pos, size) != 0) { break; } } // // Get through this block // for(b = 0; b < opts.interleave && !endflag; ) { int16_t outbuf [28]; int16_t outbuf_r[28]; uint8_t outline[28 * 2 * 2]; size_t i, j; size_t bpc = (opts.interleave - b) < ((off_t)readsize) ? (size_t)(opts.interleave - b) : readsize; // // Read left // if(fseeko(inf, in_pos + b, SEEK_SET) != 0) { goto error_in; } clearerr(inf); i = fread(block, 1, bpc, inf); if(i != bpc) { if(ferror(inf)) { goto error_in; } break; } // // Read right // if(opts.channels == 2) { if(fseeko(inf, in_pos + opts.interleave + b, SEEK_SET) != 0) { goto error_in; } clearerr(inf); i = fread(block_r, 1, bpc, inf); if(i != bpc) { if(ferror(inf)) { goto error_in; } break; } } // // If we're honoring the end flag, look for it, and cut this block // short if it's there // if(opts.honor_endflag) { for(i = 0; i < bpc; i += 0x10) { if( (block[i + 1] & 1) || (block_r && (block_r[i + 1] & 1)) ) { endflag = 1; bpc = i + 0x10; break; } } } if(opts.channels == 1) { for(i = 0; i < bpc; i += 0x10) { decodeline(block + i, outbuf, p1, p2); for(j = 0; j < 28; j++) { outline[2 * j + 0] = (uint8_t)(outbuf[j] ); outline[2 * j + 1] = (uint8_t)(outbuf[j] >> 8); } if(fwrite(outline, 1, 28 * 2, outf) != (28 * 2)) { goto error_out; } } } else { for(i = 0; i < bpc; i += 0x10) { decodeline(block + i, outbuf , p1+0, p2+0); decodeline(block_r + i, outbuf_r, p1+1, p2+1); for(j = 0; j < 28; j++) { outline[4 * j + 0] = (uint8_t)(outbuf [j] ); outline[4 * j + 1] = (uint8_t)(outbuf [j] >> 8); outline[4 * j + 2] = (uint8_t)(outbuf_r[j] ); outline[4 * j + 3] = (uint8_t)(outbuf_r[j] >> 8); } if(fwrite(outline, 1, 28 * 2 * 2, outf) != (28 * 2 * 2)) { goto error_out; } } } b += bpc; } // if we couldn't process the whole block, stop here if(b < opts.interleave) { break; } // progress indicator if((out_indicator_pos >> 20) != (ftello(outf) >> 20)) { out_indicator_pos = ftello(outf); printf("."); fflush(stdout); } // seek to next block in_pos += (opts.channels * opts.interleave) + opts.skip; } printf("ok"); goto success; error_in: printfileerror(inf , NULL ); goto error; error_out: printfileerror(outf, outname); goto error; error: returncode = 1; goto end; success: returncode = 0; goto end; end: if(outf) { wav_close(outf); } if(outname) { free(outname); } if(block ) { free(block ); } if(block_r) { free(block_r); } if(inf) { fseeko(inf, in_pos, SEEK_SET); } printf("\n"); fflush(stdout); return returncode; } //////////////////////////////////////////////////////////////////////////////// // // Format: 8 // // Used by: Suikoden // //////////////////////////////////////////////////////////////////////////////// static int fmt_8_detect(FILE *inf, const char* ext) { int score = 50; // base the entire test on the file extension for now (void)inf; if(!cmpcase(ext, "8")) { return 90; } return score; } static int fmt_8_rip( FILE *inf, struct vb2rip_options opts ) { // set .8-specific options if(!opts.use_channels) { opts.use_channels = 1; opts.channels = 2; } if(!opts.use_honor_endflag) { opts.use_honor_endflag = 1; opts.honor_endflag = 1; } if(!opts.use_samplerate) { opts.use_samplerate = 1; opts.samplerate = 44100; } if(!opts.use_interleave) { opts.use_interleave = 1; opts.interleave = 0x4000; } // now pass these options to rip return rip(inf, opts, NULL); } //////////////////////////////////////////////////////////////////////////////// // // Format: MSA // // Used by: Psyvariar Complete Edition, maybe other PS2 games. // //////////////////////////////////////////////////////////////////////////////// static int fmt_msa_detect(FILE *inf, const char* ext) { int score = 50; // base the entire test on the file extension for now (void)inf; if(!cmpcase(ext, "msa")) { return 90; } return score; } static int fmt_msa_rip( FILE *inf, struct vb2rip_options opts ) { uint8_t hdr[0x14]; if(opts.use_offset) { if(fseeko(inf, opts.offset, SEEK_CUR) != 0) { goto error_in; } } opts.use_offset = 0; if(fread(hdr, 1, 0x14, inf) != 0x14) { goto error_in; } if(!opts.use_channels) { opts.use_channels = 1; opts.channels = 2; } if(!opts.use_honor_endflag) { opts.use_honor_endflag = 1; opts.honor_endflag = 1; } if(!opts.use_samplerate) { opts.use_samplerate = 1; opts.samplerate = get32lsb(hdr + 0x10); if(opts.samplerate < 8000 || opts.samplerate > 48000) { opts.samplerate = 44100; } } if(!opts.use_interleave) { opts.use_interleave = 1; opts.interleave = 0x4000; } return rip(inf, opts, NULL); error_in: printfileerror(inf, NULL); return 1; } //////////////////////////////////////////////////////////////////////////////// // // Format: Raw // // Used for experimentation. // //////////////////////////////////////////////////////////////////////////////// static int fmt_raw_detect(FILE *inf, const char* ext) { int score = 50; (void)inf; (void)ext; // can never be quite sure if a file is "raw" or not return score; } static int fmt_raw_rip(FILE *inf, struct vb2rip_options opts) { // just pass these options directly to rip return rip(inf, opts, NULL); } //////////////////////////////////////////////////////////////////////////////// // // Format: VB2 // // Used by: DDR, Castlevania Chronicles, other Konami games // //////////////////////////////////////////////////////////////////////////////// static int fmt_vb2_detect(FILE *inf, const char* ext) { int score = 50; (void)inf; // if it ends in vb2, we're pretty sure if(!cmpcase(ext, "vb2")) { return 90; } // otherwise, it's not so clear - would have to search around for the // start of the data return score; } // // Tell if a block of bytes is all zero // static int iszeroes(const uint8_t *buf, uint32_t n) { uint32_t i; for(i = 0; i < n; i++) { if(buf[i]) { return 0; } } return 1; } // // Detect the beginning of a vb2 music block // Returns the interleave size if successful // Returns 0 if no beginning was detected // static off_t blockdetect_vb2(FILE* f, off_t ofs, off_t size) { uint8_t buf0[0x20]; uint8_t buf2[0x20]; uint8_t buf4[0x20]; uint8_t buf8[0x20]; if(size >= 0x2000) { if(fseeko(f, ofs + 0x0000, SEEK_SET) != 0) { return 0; } if(fread(buf0, 1, 0x20, f) != 0x20) { return 0; } } if(size >= 0x4000) { if(fseeko(f, ofs + 0x2000, SEEK_SET) != 0) { return 0; } if(fread(buf2, 1, 0x20, f) != 0x20) { return 0; } } if(size >= 0x8000) { if(fseeko(f, ofs + 0x4000, SEEK_SET) != 0) { return 0; } if(fread(buf4, 1, 0x20, f) != 0x20) { return 0; } } if(size >= 0x10000) { if(fseeko(f, ofs + 0x8000, SEEK_SET) != 0) { return 0; } if(fread(buf8, 1, 0x20, f) != 0x20) { return 0; } } // // DDR, various versions // if(size >= 0x8000) { if( (buf0[0x01] == 0x00) && (buf0[0x11] == 0x06) && (buf4[0x01] == 0x00) && (buf4[0x11] == 0x06) ) { return 0x4000; } } // // DDRMAX2 // if(size >= 0x4000) { if( iszeroes(buf0 + 0x00, 0x10) && ((buf0[0x11] == 0x06) || (buf0[0x11] == 0x04)) && iszeroes(buf2 + 0x00, 0x10) && ((buf2[0x11] == 0x06) || (buf2[0x11] == 0x04)) ) { return 0x2000; } } // // Castlevania Chronicles (J) // if(size >= 0x8000) { if( ((buf0[0x00] == 0x00) && ( iszeroes(buf0 + 0x02, 0x0E))) && ((buf4[0x00] == 0x00) && ( iszeroes(buf4 + 0x02, 0x0E))) && ((buf0[0x10] != 0x00) || (!iszeroes(buf0 + 0x12, 0x0E))) && ((buf4[0x10] != 0x00) || (!iszeroes(buf4 + 0x12, 0x0E))) && ((buf0[0x11] == 0x02) || (buf0[0x11] == 0x06)) && ((buf4[0x11] == 0x02) || (buf4[0x11] == 0x06)) && (buf0[0x01] == buf4[0x01]) && (buf0[0x11] == buf4[0x11]) ) { return 0x4000; } } // // Castlevania Chronicles (US) // if(size >= 0x10000) { if( ((buf0[0x00] == 0x00) && ( iszeroes(buf0 + 0x02, 0x0E))) && ((buf8[0x00] == 0x00) && ( iszeroes(buf8 + 0x02, 0x0E))) && ((buf0[0x10] != 0x00) || (!iszeroes(buf0 + 0x12, 0x0E))) && ((buf8[0x10] != 0x00) || (!iszeroes(buf8 + 0x12, 0x0E))) && ((buf0[0x11] == 0x02) || (buf0[0x11] == 0x06)) && ((buf8[0x11] == 0x02) || (buf8[0x11] == 0x06)) && (buf0[0x01] == buf8[0x01]) && (buf0[0x11] == buf8[0x11]) ) { return 0x8000; } } // all tests failed return 0; } static int fmt_vb2_rip( FILE *inf, struct vb2rip_options opts ) { int errors = 0; off_t bytesskipped = 0; off_t startpos; off_t addpos; off_t in_size; off_t searchstartpos = -1; off_t lastsongendedat = 0; int songnum = 0; const char* orig_outname; char *outname = NULL; orig_outname = opts.outname; if(!orig_outname) orig_outname = "out"; outname = malloc(strlen(orig_outname) + 20); if(!outname) { printf("%s", oom); goto error; } startpos = ftello(inf); if(startpos == -1) { goto error_in; } if(fseeko(inf, 0, SEEK_END) != 0) { goto error_in; } in_size = ftello(inf); if(in_size == -1) { goto error_in; } if(fseeko(inf, startpos, SEEK_SET) != 0) { goto error_in; } if(!opts.use_channels) { opts.use_channels = 1; opts.channels = 2; } if(!opts.use_honor_endflag) { opts.use_honor_endflag = 1; opts.honor_endflag = 1; } addpos = 0; while((startpos + addpos) < in_size) { off_t interleave = blockdetect_vb2( inf, startpos + addpos, in_size - (startpos + addpos) ); if(!interleave) { if(addpos >= lastsongendedat) { if(searchstartpos < 0) { searchstartpos = startpos + addpos; printf("searching at 0x"); fprinthex(stdout, searchstartpos, 1); printf("..."); fflush(stdout); } bytesskipped += 0x800; } addpos += 0x800; continue; } if(searchstartpos >= 0) { printf("skipped "); fprintdec(stdout, (startpos + addpos) - searchstartpos); printf(" bytes\n"); searchstartpos = -1; } opts.use_interleave = 1; opts.interleave = interleave; sprintf(outname, "%s%04ld", orig_outname, (long)songnum); opts.outname = outname; songnum++; if(fseeko(inf, startpos + addpos, SEEK_SET) != 0) { goto error_in; } errors += rip(inf, opts, blockdetect_vb2); // // rather than advancing completely beyond this song, we should seek back // 2*interleave to make sure the last block isn't short/malformed. // this fixes DDRMAX/DDRMAX2 // lastsongendedat = ((ftello(inf) - startpos) | 0x7FF) ^ 0x7FF; { off_t newaddpos = lastsongendedat - 2 * interleave; if(newaddpos <= addpos) { newaddpos = addpos + 0x800; } addpos = newaddpos; } } if(searchstartpos >= 0) { printf("nothing found\n"); } printf("total bytes skipped: "); fprintdec(stdout, bytesskipped); printf("\n"); goto end; error_in: printfileerror(inf, NULL); goto error; error: errors++; end: if(outname) free(outname); return errors; } //////////////////////////////////////////////////////////////////////////////// // // Format: XA2 // // Used by: Extreme-G 3, possibly other PS2 // //////////////////////////////////////////////////////////////////////////////// static int fmt_xa2_detect(FILE *inf, const char* ext) { int score = 50; (void)inf; // base the entire test on the file extension for now if(!cmpcase(ext, "xa2")) { return 90; } return score; } static int fmt_xa2_rip( FILE *inf, struct vb2rip_options opts ) { int errors = 0; static uint8_t hdr[0x800]; // TODO: not very clean uint32_t streams; off_t interleave; uint32_t sn; off_t startpos; const char* orig_outname; orig_outname = opts.outname; if(!orig_outname) { orig_outname = "out"; } // get the header memset(hdr, 0, sizeof(hdr)); if(fread(hdr, 1, 0x800, inf) != 0x800) { goto error_in; } startpos = ftello(inf); if(startpos == -1) { goto error_in; } streams = get32lsb(hdr); interleave = get32lsb(hdr + 4); if(streams < 1) { printf("invalid stream count present: %ld\n", (long)streams); return 1; } if( (interleave <= 0) || (interleave & (interleave - 1)) ) { printf("invalid interleave value present: 0x"); fprinthex(stdout, interleave, 1); printf("\n"); return 1; } if(!opts.use_channels) { opts.use_channels = 1; opts.channels = (streams >= 2) ? 2 : 1; } if(!opts.use_honor_endflag) { opts.use_honor_endflag = 1; opts.honor_endflag = 1; } if(!opts.use_samplerate) { opts.use_samplerate = 1; opts.samplerate = 44100; } if(!opts.use_interleave) { opts.use_interleave = 1; opts.interleave = interleave; } for(sn = 0; sn < streams; sn += opts.channels) { char *outname = malloc(strlen(orig_outname) + 20); if(!outname) { printf("%s", oom); errors++; break; } sprintf(outname, "%s%ld", orig_outname, (long)sn); opts.outname = outname; // if there's only one stream left, rip it as a mono if(sn == (streams - 1)) { opts.channels = 1; } // seek to the appropriate spot if(fseeko(inf, startpos + sn * opts.interleave, SEEK_SET) != 0) { goto error_in; } // set the appropriate skip value to skip over the other streams opts.use_skip = 1; opts.skip = (streams - opts.channels) * opts.interleave; errors += rip(inf, opts, NULL); free(outname); } return errors; error_in: printfileerror(inf, NULL); return 1; } //////////////////////////////////////////////////////////////////////////////// // // Table of recognized formats // typedef int (*fmt_rip_t)(FILE *inf, struct vb2rip_options opts); typedef int (*fmt_detect_t)(FILE *inf, const char* ext); struct FMT_TABLE { const char* name; fmt_rip_t rip; fmt_detect_t detect; const char* desc; }; static const struct FMT_TABLE fmt_table[] = { { "raw", fmt_raw_rip, fmt_raw_detect, "Raw data (for experimentation)" }, { "vb2", fmt_vb2_rip, fmt_vb2_detect, "Konami multi-song .BIN/.VB2 file (Dance Dance Revolution, etc.)" }, { "8" , fmt_8_rip , fmt_8_detect , ".8 file (Suikoden)" }, { "msa", fmt_msa_rip, fmt_msa_detect, ".MSA file (Psyvariar, possibly other PS2 games)" }, { "xa2", fmt_xa2_rip, fmt_xa2_detect, ".XA2 file (Extreme-G 3, possibly other PS2 games)" }, { NULL, NULL, NULL, NULL } }; //////////////////////////////////////////////////////////////////////////////// static void fmt_printtable(void) { const struct FMT_TABLE *t; printf(" Format Description\n"); printf(" ------------------------------------------------------------\n"); for(t = fmt_table; t->name; t++) { printf(" %-9s%s\n", t->name, t->desc); } } //////////////////////////////////////////////////////////////////////////////// // // determine if a given format name is recognized // static int fmt_isvalid(const char* fmt) { const struct FMT_TABLE *t; for(t = fmt_table; t->name; t++) { if(!strcmp(t->name, fmt)) return 1; } return 0; } //////////////////////////////////////////////////////////////////////////////// // // detect the format of a file if none was given // (must return at least some valid string pointer) // static const char* fmt_detect(FILE *inf, const char* ext) { const struct FMT_TABLE *t; const char* fmt_highest = "raw"; int fmt_highest_score = 50; for(t = fmt_table; t->name; t++) { if(t->detect) { int score = t->detect(inf, ext); if(score > fmt_highest_score) { fmt_highest = t->name; fmt_highest_score = score; } } } return fmt_highest; } //////////////////////////////////////////////////////////////////////////////// // // rip the actual music from a file // returns the number of errors that occurred // fmt and outname must be valid in opts // static int fmt_rip(FILE *inf, struct vb2rip_options opts) { const struct FMT_TABLE *t; if(!opts.fmt) { opts.fmt = "raw"; } if(!opts.outname) { opts.outname = "out"; } if(opts.use_offset) { if(fseeko(inf, opts.offset, SEEK_CUR) != 0) { goto error_in; } opts.use_offset = 0; opts.offset = 0; } for(t = fmt_table; t->name; t++) { if(!strcmp(t->name, opts.fmt)) { return t->rip(inf, opts); } } printf("unknown format '%s'\n", opts.fmt); return 1; error_in: printfileerror(inf, NULL); return 1; } //////////////////////////////////////////////////////////////////////////////// void usage(const char* progname) { banner(); printf("Usage: %s [options] inputfile(s)\n\n", progname); printf( "Options:\n" " -fmt format Specify the input file format\n" " -o path Specify the output filename (if one input file is given)\n" " or specify the output directory (if several are given)\n" " -mono Treat input file as monaural\n" " -stereo Treat input file as stereo\n" " -rate n Specify the sample rate\n" " -interleave n Specify the block interleave size\n" " -skip n Skip this many bytes after each block\n" " -offset n Start at the given offset in the input file\n" " -endflag Stop decoding when the sample end flag is reached\n" " -noendflag Ignore the sample end flag\n" " -maxbytes n Set the maximum number of input bytes to decode\n" "\n" ); printf("Supported input formats:\n"); fmt_printtable(); } //////////////////////////////////////////////////////////////////////////////// // // returns how many argv spots were used // returns 0 on error // if opts is NULL, there are no side effects // static int decodeoption( struct vb2rip_options* opts, int argc, char **argv ) { if(argc < 1) return 0; if(!strcmp(argv[0], "-fmt")) { if(argc < 2) { goto needextra; } if(!fmt_isvalid(argv[1])) { printf("unknown format '%s'\n", argv[1]); return 0; } opts->fmt = argv[1]; return 2; } else if(!strcmp(argv[0], "-o")) { if(argc < 2) { goto needextra; } opts->outname = argv[1]; return 2; } else if(!strcmp(argv[0], "-mono")) { opts->use_channels = 1; opts->channels = 1; return 1; } else if(!strcmp(argv[0], "-stereo")) { opts->use_channels = 1; opts->channels = 2; return 1; } else if(!strcmp(argv[0], "-rate")) { if(argc < 2) { goto needextra; } opts->use_samplerate = 1; opts->samplerate = strtoul(argv[1], NULL, 0); return 2; } else if(!strcmp(argv[0], "-interleave")) { if(argc < 2) { goto needextra; } opts->use_interleave = 1; opts->interleave = strtoofft(argv[1], NULL, 0); return 2; } else if(!strcmp(argv[0], "-skip")) { if(argc < 2) { goto needextra; } opts->use_skip = 1; opts->skip = strtoofft(argv[1], NULL, 0); return 2; } else if(!strcmp(argv[0], "-offset")) { if(argc < 2) { goto needextra; } opts->use_offset = 1; opts->offset = strtoofft(argv[1], NULL, 0); return 2; } else if(!strcmp(argv[0], "-noendflag")) { opts->use_honor_endflag = 1; opts->honor_endflag = 0; return 1; } else if(!strcmp(argv[0], "-endflag")) { opts->use_honor_endflag = 1; opts->honor_endflag = 1; return 1; } else if(!strcmp(argv[0], "-maxbytes")) { if(argc < 2) { goto needextra; } opts->use_maxbytes = 1; opts->maxbytes = strtoofft(argv[1], NULL, 0); return 2; } printf("unknown option '%s'\n", argv[0]); return 0; needextra: printf("option '%s' needs an extra parameter\n", argv[0]); return 0; } // // returns nonzero on error // static int getoptions( struct vb2rip_options* opts, int argc, char **argv ) { int endopts = 0; int i; for(i = 1; i < argc; i++) { if(endopts || (argv[i][0] != '-')) { opts->inputfilecount++; } else if(!strcmp(argv[i], "--")) { endopts = 1; } else { int advance = decodeoption(opts, argc - i, argv + i); if(advance < 1) return 1; i += (advance - 1); } } // success return 0; } //////////////////////////////////////////////////////////////////////////////// // // returns the number of errors that occurred // static int processfile(const char* infilename, struct vb2rip_options opts) { int returncode = 1; const char* fmt; FILE* f = NULL; char* innameonly = NULL; char* outname = NULL; char separator = '/'; if(!infilename) { printf("no input filename given\n"); goto error; } // allocate memory for filename strings innameonly = malloc(strlen(infilename) + 1); if(!innameonly) { printf("%s", oom); goto error; } { int maxoutl = strlen(infilename); if(opts.outname) { maxoutl += strlen(opts.outname); } maxoutl += 10; outname = malloc(maxoutl); if(!outname) { printf("%s", oom); goto error; } } // count directory separators in both input and output names { const char* t; int sepunix = 0; int sepdos = 0; if(infilename) { for(t = infilename; *t; t++) { switch(*t) { case '/' : sepunix++; break; case '\\': sepdos++; break; } } } if(opts.outname) { for(t = opts.outname; *t; t++) { switch(*t) { case '/' : sepunix++; break; case '\\': sepdos++; break; } } } // if one beats the other, use it; otherwise leave at the default if(sepunix > sepdos ) { separator = '/'; } if(sepdos > sepunix) { separator = '\\'; } } // strip the input filename to its name only { const char* t, *base; base = infilename; for(t = infilename; *t; t++) { switch(*t) { case '/' : case '\\': base = t + 1; break; } } strcpy(innameonly, base); { char *p = strrchr(innameonly, '.'); if(p) *p = 0; } } // if no output name was specified at all, then we use innameonly if(!opts.outname) { strcpy(outname, innameonly); // if we only have one input file, we use outname directly } else if(opts.inputfilecount == 1) { strcpy(outname, opts.outname); // otherwise, outname is actually a path to which we'll add innameonly } else { int l = strlen(opts.outname); strcpy(outname, opts.outname); if(l > 0) { char c = outname[l - 1]; if(c != '/' && c != '\\') { outname[l] = separator; outname[l + 1] = 0; } } strcat(outname, innameonly); } // now we actually open the input file printf("reading %s: ", infilename); fflush(stdout); f = fopen(infilename, "rb"); if(!f) { goto error_in; } // determine the format if necessary, or use the override fmt = opts.fmt; if(opts.use_offset) { if(fseeko(f, opts.offset, SEEK_SET) != 0) { goto error_in; } opts.use_offset = 0; opts.offset = 0; } if(fmt) { printf("(format set to: %s)", fmt); } else { const char* ext = strrchr(infilename, '.'); if(ext) { ext++; } else { ext = ""; } fmt = fmt_detect(f, ext); printf("(format detected as: %s)", fmt); } // set fmt and outname in the options for fmt_rip opts.fmt = fmt; opts.outname = outname; printf("\n"); // call fmt_rip to do the actual ripping work if(fmt_rip(f, opts)) { goto error; } goto success; error_in: printfileerror(f, infilename); goto error; error: returncode = 1; goto end; success: returncode = 0; goto end; end: if(f) { fclose(f); } if(innameonly) { free(innameonly); } if(outname) { free(outname); } return returncode; } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { struct vb2rip_options opts; const char* progname = argv[0]; int i; int endopts = 0; int errors = 0; // get options from command line memset(&opts, 0, sizeof(opts)); if(getoptions(&opts, argc, argv)) return 1; // make sure at least one input file was specified if((opts.inputfilecount) < 1) { usage(progname); return 1; } // now process each file endopts = 0; for(i = 1; i < argc; i++) { if(endopts || (argv[i][0] != '-')) { errors += processfile(argv[i], opts); } else if(!strcmp(argv[i], "--")) { endopts = 1; } else { struct vb2rip_options dummy; int advance = decodeoption(&dummy, argc - i, argv + i); if(advance < 1) return 1; i += (advance - 1); } } return errors; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/version.h0000644000175000017500000000001011731303760016153 0ustar corlettcorlett"v1.03" cmdpack-1.03-src/src/wordadd.c0000644000175000017500000002031211731303760016114 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "wordadd - Addition word puzzle solver" #define COPYR "Copyright (C) 2010 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// // // Count trailing zeroes // static uint8_t ctztable[1024]; static void init_ctztable(void) { size_t i, j, k; ctztable[0] = 0; for(i = 1; i < 1024; i++) { for(k = 0, j = i; !(j & 1); k++, j >>= 1) { } ctztable[i] = k; } } //////////////////////////////////////////////////////////////////////////////// enum { DIGIT = 0x0F, KNOWN = 0x10, NONZERO = 0x20 }; static char** lines; static size_t n_lines; static uint8_t digitmap[256]; static uint16_t available = 0x3FF; static uint32_t solutions = 0; static char printresults = 0; static void init_puzzle(void) { size_t i; // // Reset digit maps // memset(digitmap, 0, 256); // // Digits not present: 0 // digitmap[0] = KNOWN | 0; // // 0-9 are literal // for(i = 0; i < 10; i++) { digitmap['0' + i] = KNOWN | i; } // // First letter of each word must be nonzero // for(i = 0; i < n_lines; i++) { if(lines[i][0]) { digitmap[(uint8_t)lines[i][0]] |= NONZERO; } } } void print_puzzle(void) { size_t i; for(i = 0; i < n_lines; i++) { if(i == (n_lines - 1)) { printf(" = "); } else if(i > 0) { printf(" + "); } printf("%s", lines[i]); } printf("\n"); } void print_solution(void) { size_t i, j; for(i = 0; i < n_lines; i++) { if(i == (n_lines - 1)) { printf(" = "); } else if(i > 0) { printf(" + "); } for(j = 0; lines[i][j]; j++) { fputc('0' + (digitmap[(uint8_t)(lines[i][j])] & DIGIT), stdout); } } printf("\n"); } //////////////////////////////////////////////////////////////////////////////// void solve_puzzle( size_t line, size_t place, // 0 = rightmost int carry_in, char final ) { // // Obtain the current letter, or 0 if none // size_t len = strlen(lines[line]); uint8_t letter = (place < len) ? (letter = lines[line][(len - 1) - place]) : 0; if(letter) { final = 0; } if(line == (n_lines - 1)) { // // This is the sum line // if(final) { // // We have finished the addition // if(carry_in == 0) { // // Sum matches: Found a solution // if(printresults) { print_solution(); } solutions++; } } else { // // Get next carry digit // int carry_out = carry_in / 10; carry_in %= 10; if(digitmap[letter] & KNOWN) { // // Letter is mapped // if((digitmap[letter] & DIGIT) == carry_in) { // // Letter is mapped to the correct digit; move on // solve_puzzle(0, place + 1, carry_out, 1); } } else { // // Letter is not mapped yet. // We will need to map it to carry_in. // int mask = 1 << carry_in; if( (available & mask) && (carry_in || !(digitmap[letter] & NONZERO)) ) { // // Digit we need is available; map it and move on // digitmap[letter] |= KNOWN | carry_in; available ^= mask; solve_puzzle(0, place + 1, carry_out, 1); digitmap[letter] &= ~(KNOWN | DIGIT); available ^= mask; } } } } else { // // This is not the sum line // if(digitmap[letter] & KNOWN) { // // Letter is mapped; add it and move on // solve_puzzle(line + 1, place, carry_in + (digitmap[letter] & DIGIT), final); } else { // // Letter is not mapped // // // Try all available digits, and count the solutions // int t = available; if(digitmap[letter] & NONZERO) { t &= ~1; } for(; t; t &= t - 1) { int digit = ctztable[t]; int mask = 1 << digit; digitmap[letter] |= KNOWN | digit; available ^= mask; solve_puzzle(line + 1, place, carry_in + digit, final); digitmap[letter] &= ~(KNOWN | DIGIT); available ^= mask; } } } } static void solve_puzzle_all(void) { solve_puzzle(0, 0, 0, 1); } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { int i; // Bitmask of letters A-Z that were used uint32_t letters = 0; int lettercount; int avdigitcount; if(argc < 3) { banner(); printf( "Usage: %s words... sum\n" "Examples:\n" " %s BEEF BACON MEATS\n", argv[0], argv[0] ); return 1; } for(i = 1; i < argc; i++) { char* s = argv[i]; size_t j; for(j = 0; s[j]; j++) { int c = ((unsigned char)(s[j])); static const char* allletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static const char* alldigits = "0123456789"; if(isalpha(c)) { const char* t; s[j] = c = toupper(c); t = strchr(allletters, c); if(t) { letters |= ((uint32_t)1) << (t - allletters); continue; } } else if(isdigit(c)) { const char* t = strchr(alldigits, c); if(t) { // // Allow digits, but don't allow letters to use that digit // available &= ~(1 << (t - alldigits)); continue; } } printf("Not a word: \"%s\"\n", s); return 1; } } lines = argv + 1; n_lines = argc - 1; // // Count letters // lettercount = 0; for(i = 0; i < 26; i++) { lettercount += (letters >> i) & 1; } if(lettercount < 1) { printf("Not enough letters\n"); return 1; } if(lettercount > 10) { printf("Too many letters (%d)\n", lettercount); return 1; } // // Count available digits // avdigitcount = 0; for(i = 0; i < 10; i++) { avdigitcount += (available >> i) & 1; } if(lettercount > avdigitcount) { printf( "There are more letters (%d) than available digits (%d)\n", lettercount, avdigitcount ); return 1; } // // Solve // init_ctztable(); init_puzzle(); print_puzzle(); printresults = 1; solve_puzzle_all(); printf("Solutions: %lu\n", (unsigned long)solutions); return 0; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/zerofill.c0000644000175000017500000001440011731303760016317 0ustar corlettcorlett//////////////////////////////////////////////////////////////////////////////// // #define TITLE "zerofill - Create a large, empty file" #define COPYR "Copyright (C) 2011 Neill Corlett" // // 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 3 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 . // //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "banner.h" //////////////////////////////////////////////////////////////////////////////// // // Convert a time_t to a struct tm, safely // static struct tm my_localtime(time_t t) { struct tm *p_tm = localtime(&t); if(!p_tm) { t = 0; p_tm = localtime(&t); } if(!p_tm) { struct tm fallback; memset(&fallback, 0, sizeof(fallback)); return fallback; } return (*p_tm); } //////////////////////////////////////////////////////////////////////////////// static void fprinttime(FILE* f, time_t t) { size_t r; char buf[64]; struct tm my_tm = my_localtime(t); memset(buf, 0, sizeof(buf)); r = strftime(buf, sizeof(buf)-1, "%c", &my_tm); if(r < 1) { strncpy(buf, "(invalid date)", sizeof(buf)-1); } fputs(buf, f); } //////////////////////////////////////////////////////////////////////////////// static void progress( FILE* f, off_t written, off_t size, time_t time_cur, time_t time_start ) { time_t elapsed = time_cur - time_start; { off_t divider; off_t percent; divider = size / 100; if(divider < 1) { divider = 1; } percent = (size == 0) ? 100 : (written / divider); if(percent < 0) { percent = 0; } if(percent > 100) { percent = 100; } fprintf(f, "%3d%%", (int)percent); } if(elapsed >= 5) { off_t rate = written / ((off_t)(elapsed > 1 ? elapsed : 1)); off_t sec_remain = (size - written) / (rate > 1 ? rate : 1); if(sec_remain <= 1000000) { time_t eta = time_cur + sec_remain; fputs(" (", f); fprintdec(f, rate); fputs(" byte/sec, ETA ", f); fprinttime(f, eta); fputs(") ", f); } } fputs("\r", f); fflush(f); } //////////////////////////////////////////////////////////////////////////////// static uint8_t buf[0x8000LU]; int main(int argc, char **argv) { int returncode = 0; int force = 0; int quiet = 0; const char* filename = NULL; FILE* f = NULL; off_t size = 0; off_t written = 0; time_t time_start = time(NULL); time_t time_cur = 0; normalize_argv0(argv[0]); // // Check command line // { int argn = 0; int i; for(i = 1; i < argc; i++) { if(argv[i][0] == '-' && argn == 0) { // An option if(argv[i][1] != 0 && argv[i][2] == 0) { switch(argv[i][1]) { case '-': // No more options argn = 1; continue; case 'f': // Force force = 1; continue; case 'q': // Quiet quiet = 1; continue; } } printf("Unknown option: %s\n", argv[i]); goto usage; } else { switch(argn) { case 0: case 1: size = strtoofft(argv[i], NULL, 0); argn = 2; break; case 2: filename = argv[i]; argn = 3; break; default: goto usage; } } } if(argn != 3) { goto usage; } } if(size < 0) { printf("Error: Size must not be negative\n"); goto error; } if(!force) { // // Make sure the file doesn't already exist // f = fopen(filename, "rb"); if(f) { printf("Error: %s already exists (use -f to overwrite)\n", filename); goto error; } } f = fopen(filename, "wb"); if(!f) { goto fileerror; } if(!quiet) { printf("Writing "); fprintdec(stdout, size); printf(" bytes to file: %s\n", filename); } memset(buf, 0, sizeof(buf)); while(written < size) { off_t remain; size_t s; // // Do progress indicator // if(!quiet) { time_t t = time(NULL); if(t != time_cur) { time_cur = t; progress(stderr, written, size, time_cur, time_start); } } // // Write a block // remain = size - written; if(remain > ((off_t)(sizeof(buf)))) { remain = ((off_t)(sizeof(buf))); } s = fwrite(buf, 1, (size_t)remain, f); if(s != ((size_t)remain)) { if(!quiet) { fputs("\n", stdout); } goto fileerror; } written += remain; } // // Done // if(!quiet) { time_cur = time(NULL); progress(stderr, written, size, time_cur, time_start); printf("\nDone\n"); } goto end; fileerror: printfileerror(f, filename); goto error; usage: banner(); printf("Usage: %s [-f] [-q] size filename\n", argv[0]); printf(" -f: Force overwrite\n"); printf(" -q: Quiet\n"); goto error; error: returncode = 1; end: if(f != NULL) { fclose(f); } return returncode; } //////////////////////////////////////////////////////////////////////////////// cmdpack-1.03-src/src/mkdjgpp.bat0000644000175000017500000000135511731303760016456 0ustar corlettcorlett@echo off if "%1" == "" goto usage if not exist %1.c goto notfound echo (DJGPP 32-bit DOS) %1 rem - You need djdev203, binutils/gcc, and pmode13b. rem - This assumes DJGPP is in Y:\DJGPP\BIN. rem - This also assumes UPX is somewhere in your path. gcc -O9 -Wall -Wextra -Werror -fomit-frame-pointer %1.c -s -o %1.exe IF ERRORLEVEL 1 goto exit if exist %1.obj del %1.obj if exist %1.o del %1.o exe2coff %1.exe IF ERRORLEVEL 1 goto exit copy /b Y:\DJGPP\BIN\PMODSTUB.EXE+%1 %1.exe > nul IF ERRORLEVEL 1 goto exit del %1 IF ERRORLEVEL 1 goto exit upx --best %1.exe > nul IF ERRORLEVEL 1 goto exit goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit cmdpack-1.03-src/src/mkgcc0000755000175000017500000000014211731303760015335 0ustar corlettcorlett#!/bin/sh MYFLAGS= gcc $MYFLAGS -O9 -Wall -Wextra -Werror -fomit-frame-pointer "$1.c" -s -o "$1" cmdpack-1.03-src/src/mkhuman.bat0000644000175000017500000000064411731303760016462 0ustar corlettcorlettecho off rem I'm using gcc 2.6.3 and the "Mr. DON" libcd4.tgz, and g2cpp.x is replaced with cpp.x from rem the gcc 2.95.2 beta if "%1" == "" goto usage if not exist %1.c goto notfound echo (gcc2 Human68k) %1 gcc2 -O9 -Wall -Werror -fomit-frame-pointer %1.c -s -o %1.x del tmp.o > nul goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit cmdpack-1.03-src/src/mkmacppc0000755000175000017500000000015511731303760016050 0ustar corlettcorlett#!/bin/sh MYFLAGS="-arch ppc" gcc $MYFLAGS -O9 -Wall -Wextra -Werror -fomit-frame-pointer "$1.c" -s -o "$1" cmdpack-1.03-src/src/mkmacx640000755000175000017500000000020711731303760015705 0ustar corlettcorlett#!/bin/sh MYFLAGS="-mmacosx-version-min=10.4 -arch x86_64" gcc $MYFLAGS -O9 -Wall -Wextra -Werror -fomit-frame-pointer "$1.c" -o "$1" cmdpack-1.03-src/src/mkmacx860000755000175000017500000000020511731303760015707 0ustar corlettcorlett#!/bin/sh MYFLAGS="-mmacosx-version-min=10.4 -arch i386" gcc $MYFLAGS -O9 -Wall -Wextra -Werror -fomit-frame-pointer "$1.c" -o "$1" cmdpack-1.03-src/src/mkming32.bat0000644000175000017500000000051011731303760016441 0ustar corlettcorlett@echo off if "%1" == "" goto usage if not exist %1.c goto notfound echo (MinGW 32-bit Windows) %1 i686-w64-mingw32-gcc -DWINVER=0x0400 -O9 -Wall -Wextra -Werror -fomit-frame-pointer %1.c -s -o %1.exe goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit cmdpack-1.03-src/src/mkming64.bat0000644000175000017500000000047211731303760016455 0ustar corlettcorlett@echo off if "%1" == "" goto usage if not exist %1.c goto notfound echo (MinGW 64-bit Windows) %1 x86_64-w64-mingw32-gcc -O9 -Wall -Wextra -Werror -fomit-frame-pointer %1.c -s -o %1.exe goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit cmdpack-1.03-src/src/mkmsc.bat0000644000175000017500000000157511731303760016140 0ustar corlettcorlett@echo off rem - Build using various Microsoft C++ variants if "%1" == "" goto usage if not exist %1.c goto notfound rem - Platform selection if "%CPU%" == "ALPHA" goto axp goto msc rem - Build using the Microsoft/Digital AXP C++ compiler rem - (part of the NT 3.5 SDK, I think) :axp echo (Digital AXP C++) %1 cl /W3 /WX /O /Gs /Gy %1.c /link /subsystem:console /opt:ref /fixed /release /nodefaultlib:oldnames.lib kernel32.lib user32.lib setargv.obj IF ERRORLEVEL 1 goto exit goto cleanup rem - Build using just regular Microsoft C++? :msc echo (Microsoft C++) %1 cl /W3 /WX /Ox /Gy %1.c /link /fixed /opt:ref /release user32.lib setargv.obj IF ERRORLEVEL 1 goto exit goto cleanup :cleanup if exist %1.obj del %1.obj if exist %1.o del %1.o goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit cmdpack-1.03-src/src/mkturboc.bat0000644000175000017500000000103011731303760016636 0ustar corlettcorlett@echo off if "%1" == "" goto usage if not exist %1.c goto notfound echo (Turbo C 16-bit DOS) %1 rem - rem - Have to be careful with optimization options; in rem - particular, -O has demonstrably generated wrong code rem - TCC -IY:\TURBOC\INCLUDE -LY:\TURBOC\LIB -ml %1.c Y:\TURBOC\LIB\WILDARGS.OBJ if errorlevel 1 goto exit if exist %1.obj del %1.obj if exist %1.o del %1.o upx --best %1.exe > nul goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit cmdpack-1.03-src/src/mkwatcom.bat0000644000175000017500000000155411731303760016645 0ustar corlettcorlett@echo off if "%1" == "" goto usage if not exist %1.c goto notfound echo (OpenWatcom 16-bit DOS) %1 PATH Y:\WATCOM\BINW;%PATH% SET INCLUDE=Y:\WATCOM\H SET WATCOM=Y:\WATCOM SET EDPATH=Y:\WATCOM\EDDAT SET WIPFC=Y:\WATCOM\WIPFC if exist %1.err del %1.err wcc -ml -j -0 -d0 -obmilers -we -wx -q %WATCOM%\src\startup\wildargv.c if errorlevel 1 goto doerr wcc -ml -j -0 -d0 -obmilers -we -wx -q %1.c if exist %1.err goto doerr if errorlevel 1 goto doerr wlink system dos name %1.exe file %1.obj file wildargv.obj if exist %1.err goto doerr if errorlevel 1 goto doerr if exist %1.obj del %1.obj upx --best %1.exe > nul goto exit :doerr if exist %1 type %1.err if exist %1 del %1.err goto exit :usage echo Usage: %0 program_name goto exit :notfound echo %1.c not found goto exit :exit if exist wildargv.obj del wildargv.obj