Add pak subdir

From https://github.com/myfreeer/chrome-pak-customizer
This commit is contained in:
Alexander David Frick 2022-02-08 17:03:53 -08:00 committed by GitHub
parent d67be4a2e2
commit aeaac2874e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 1945 additions and 0 deletions

26
pak/CMakeLists.txt Normal file
View file

@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 2.8)
project(chrome-pak C)
option(LGPL "Use custom startfiles on windows for smaller binary, requiring GNU Lesser General Public License 2.1+." ON)
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose the type of build, options are: Debug Release." FORCE)
endif (NOT CMAKE_BUILD_TYPE)
if (MSVC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /MT /wd4996 /wd4068")
set(CompilerFlags
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE)
foreach (CompilerFlag ${CompilerFlags})
string(REPLACE "/MD" "/MT" ${CompilerFlag} "${${CompilerFlag}}")
endforeach ()
endif ()
if ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")
set(CMAKE_C_FLAGS "-O3 -Os -pipe -Wall -Wextra -fmerge-all-constants -Wl,--gc-sections,--build-id=none")
set(CMAKE_C_FLAGS_DEBUG "-g")
set(CMAKE_C_FLAGS_RELEASE "-s")
if (WIN32 AND LGPL)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -nostartfiles -D_LGPL")
endif ()
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_C_FLAGS}")
endif ()
aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR} DIR_SRCS)
add_executable(pak ${DIR_SRCS})

21
pak/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 myfreeer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

504
pak/LICENSE.LGPL Normal file
View file

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

64
pak/README.md Normal file
View file

@ -0,0 +1,64 @@
# chrome-pak-customizer
a simple batch tool to customize pak files in chrome or chromium-based browser
## Badges
[![Build status](https://ci.appveyor.com/api/projects/status/4ji3guqh4yyjfiaa?svg=true)](https://ci.appveyor.com/project/myfreeer/chrome-pak-customizer)
[![Download](https://img.shields.io/github/downloads/myfreeer/chrome-pak-customizer/total.svg)](https://github.com/myfreeer/chrome-pak-customizer/releases)
[![Latest Release](https://img.shields.io/github/release/myfreeer/chrome-pak-customizer.svg)](https://github.com/myfreeer/chrome-pak-customizer/releases/latest)
## License
* Windows builds are licensed `LGPL 2.1+` **by default**, can be disabled by appending `-DLGPL=OFF` to cmake.
* Non-windows builds and builds with `-DLGPL=OFF` are licensed MIT.
## Usage (Windows Only)
1. Download `chrome-pak.7z` from [releases](https://github.com/myfreeer/chrome-pak-customizer/releases) and extract it to any folder.
2. Drag the pak file and drop it to `unpack.bat`.
3. The pak file would be extracted to subfolder of the folder of the pak file,
with the same name of the pak file with an `_unpacked` suffix.
4. (Optional) modify extracted files.
5. Drag `pak_index.ini` to `pack.bat`.
6. Repacked pak file would be in the same folder of `pak_index.ini` with a name like `pak_index_packed.pak`.
There is also a [GIF Guide](https://github.com/myfreeer/chrome-pak-customizer/wiki/GIF-Guide-v2) on windows.
## Usage (Command line)
```
pak.exe -u pak_file destination_path
Unpack chrome pak file at pak_file to destination_path.
pak.exe -p pak_index_file destination_pak_file
Pack chrome pak file using pak_index_file to destination_pak_file.
pak_index_file would be found in unpacked path.
Note: existing destination files would be overwritten
```
## Building
### Prerequires
* gcc
* cmake
* ninja
### Build script example
```bash
# Getting source
git clone https://github.com/myfreeer/chrome-pak-customizer --branch=develop --single-branch
cd chrome-pak-customizer
# Creating folder for build
mkdir -p build
cd build
# Running cmake
cmake -GNinja -DLGPL=OFF ..
# Building
ninja
```
### CMake options
* `LGPL`: Enable LGPL 2.1+ licensed custom startfiles on windows for smaller binary
## Credits
* <https://www.chromium.org/>
* <https://github.com/shuax/ChromePAK>
* <https://github.com/myfreeer/win-startup-headers>

40
pak/appveyor.bat Normal file
View file

@ -0,0 +1,40 @@
echo Syncing msys2 packages...
C:\msys64\usr\bin\pacman -Sq --noconfirm --needed --noprogressbar --ask=20 mingw-w64-x86_64-ninja mingw-w64-i686-ninja
rem C:\msys64\usr\bin\pacman -Scq --noconfirm
echo Fetching test files
if not exist tests mkdir tests
cd tests
for %%i in (test_v4_474896_1.pak test_v4_474896_2.pak test_v4_474896_r.pak test_v5_550886_1.pak test_v5_550886_2.pak test_v5_550886_r.pak) do if not exist "%%~i" appveyor.exe DownloadFile "https://github.com/myfreeer/chrome-pak-customizer/releases/download/1.0/%%~i"
cd ..
echo Building and testing 64-bit version...
set MSYSTEM=MINGW64
call C:\msys64\usr\bin\bash -lc "cd \"$APPVEYOR_BUILD_FOLDER\" && exec ./test.sh"
move /Y .\build_x86_64-w64-mingw32\pak.exe .\pak_mingw64.exe
echo Building and testing 32-bit version...
set MSYSTEM=MINGW32
call C:\msys64\usr\bin\bash -lc "cd \"$APPVEYOR_BUILD_FOLDER\" && exec ./test.sh"
move /Y .\build_i686-w64-mingw32\pak.exe .\pak_mingw32.exe
echo Building with msvc 32-bit...
mkdir msvc_32
cd msvc_32
cmake ..
cmake --build . --target ALL_BUILD --config Release
move /Y .\Release\pak.exe ..\pak_msvc32.exe
cd ..
echo Building with msvc 64-bit...
mkdir msvc_64
cd msvc_64
cmake -G "Visual Studio 14 2015 Win64" ..
cmake --build . --target ALL_BUILD --config Release
move /Y .\Release\pak.exe ..\pak_msvc64.exe
cd ..
echo Packaging...
7z a -mx9 chrome-pak.7z .\pak_mingw64.exe .\pak_mingw32.exe .\pack.bat .\unpack.bat
7z a -mx9 chrome-pak_msvc.7z .\pak_msvc32.exe .\pak_msvc64.exe .\pack.bat .\unpack.bat
echo Done.

25
pak/appveyor.yml Normal file
View file

@ -0,0 +1,25 @@
version: 2.0-{build}
skip_tags: true
build_script:
- cmd: >-
appveyor.bat
on_failure:
- 7z a -mx9 -r fail.7z *.exe *.sln *.txt *.log
- appveyor.exe PushArtifact fail.7z
shallow_clone: true
test: off
artifacts:
- path: pak_mingw64.exe
- path: pak_mingw32.exe
- path: pak_msvc64.exe
- path: pak_msvc32.exe
- path: chrome-pak.7z
- path: chrome-pak_msvc.7z
cache:
- tests
skip_commits:
files:
- 'LICENSE'
- '*.md'
- '.gitingore'
- '.gitattributes'

235
pak/commandlinetoargva.h Normal file
View file

@ -0,0 +1,235 @@
#pragma once
#ifndef COMMANDLINETOARGVA_H
#define COMMANDLINETOARGVA_H
#include <string.h>
#include <windows.h>
// https://github.com/wine-mirror/wine/blob/5946973021285dd6ecb8df224956fea4817f8fed/dlls/shell32/shell32_main.c
// https://github.com/futurist/CommandLineToArgvA/blob/09765ffef215f0a066d6b0ea5c1edda88b6739af/CommandLineToArgvA.c
/*************************************************************************
* CommandLineToArgvA [SHELL32.@]
*
* We must interpret the quotes in the command line to rebuild the argv
* array correctly:
* - arguments are separated by spaces or tabs
* - quotes serve as optional argument delimiters
* '"a b"' -> 'a b'
* - escaped quotes must be converted back to '"'
* '\"' -> '"'
* - consecutive backslashes preceding a quote see their number halved with
* the remainder escaping the quote:
* 2n backslashes + quote -> n backslashes + quote as an argument delimiter
* 2n+1 backslashes + quote -> n backslashes + literal quote
* - backslashes that are not followed by a quote are copied literally:
* 'a\b' -> 'a\b'
* 'a\\b' -> 'a\\b'
* - in quoted strings, consecutive quotes see their number divided by three
* with the remainder modulo 3 deciding whether to close the string or not.
* Note that the opening quote must be counted in the consecutive quotes,
* that's the (1+) below:
* (1+) 3n quotes -> n quotes
* (1+) 3n+1 quotes -> n quotes plus closes the quoted string
* (1+) 3n+2 quotes -> n+1 quotes plus closes the quoted string
* - in unquoted strings, the first quote opens the quoted string and the
* remaining consecutive quotes follow the above rule.
*/
LPSTR WINAPI *CommandLineToArgvA(LPCSTR lpCmdline, int *numargs) {
DWORD argc;
LPSTR *argv;
LPCSTR s;
LPSTR d;
LPSTR cmdline;
int qcount, bcount;
if (!numargs) {
SetLastError(ERROR_INVALID_PARAMETER);
return NULL;
}
if (lpCmdline == NULL || *lpCmdline == 0) {
/* Return the path to the executable */
DWORD len, deslen = MAX_PATH, size;
size = sizeof(LPSTR) * 2 + deslen * sizeof(char);
for (;;) {
if (!(argv = LocalAlloc(LMEM_FIXED, size)))
return NULL;
len = GetModuleFileNameA(0, (LPSTR)(argv + 2), deslen);
if (!len) {
LocalFree(argv);
return NULL;
}
if (len < deslen)
break;
deslen *= 2;
size = sizeof(LPSTR) * 2 + deslen * sizeof(char);
LocalFree(argv);
}
argv[0] = (LPSTR)(argv + 2);
argv[1] = NULL;
*numargs = 1;
return argv;
}
/* --- First count the arguments */
argc = 1;
s = lpCmdline;
/* The first argument, the executable path, follows special rules */
if (*s == '"') {
/* The executable path ends at the next quote, no matter what */
s++;
while (*s)
if (*s++ == '"')
break;
} else {
/* The executable path ends at the next space, no matter what */
while (*s && *s != ' ' && *s != '\t')
s++;
}
/* skip to the first argument, if any */
while (*s == ' ' || *s == '\t')
s++;
if (*s)
argc++;
/* Analyze the remaining arguments */
qcount = bcount = 0;
while (*s) {
if ((*s == ' ' || *s == '\t') && qcount == 0) {
/* skip to the next argument and count it if any */
while (*s == ' ' || *s == '\t')
s++;
if (*s)
argc++;
bcount = 0;
} else if (*s == '\\') {
/* '\', count them */
bcount++;
s++;
} else if (*s == '"') {
/* '"' */
if ((bcount & 1) == 0)
qcount++; /* unescaped '"' */
s++;
bcount = 0;
/* consecutive quotes, see comment in copying code below */
while (*s == '"') {
qcount++;
s++;
}
qcount = qcount % 3;
if (qcount == 2)
qcount = 0;
} else {
/* a regular character */
bcount = 0;
s++;
}
}
/* Allocate in a single lump, the string array, and the strings that go
* with it. This way the caller can make a single LocalFree() call to free
* both, as per MSDN.
*/
argv = LocalAlloc(LMEM_FIXED, (argc + 1) * sizeof(LPSTR) +
(strlen(lpCmdline) + 1) * sizeof(char));
if (!argv)
return NULL;
cmdline = (LPSTR)(argv + argc + 1);
strcpy(cmdline, lpCmdline);
/* --- Then split and copy the arguments */
argv[0] = d = cmdline;
argc = 1;
/* The first argument, the executable path, follows special rules */
if (*d == '"') {
/* The executable path ends at the next quote, no matter what */
s = d + 1;
while (*s) {
if (*s == '"') {
s++;
break;
}
*d++ = *s++;
}
} else {
/* The executable path ends at the next space, no matter what */
while (*d && *d != ' ' && *d != '\t')
d++;
s = d;
if (*s)
s++;
}
/* close the executable path */
*d++ = 0;
/* skip to the first argument and initialize it if any */
while (*s == ' ' || *s == '\t')
s++;
if (!*s) {
/* There are no parameters so we are all done */
argv[argc] = NULL;
*numargs = (int) argc;
return argv;
}
/* Split and copy the remaining arguments */
argv[argc++] = d;
qcount = bcount = 0;
while (*s) {
if ((*s == ' ' || *s == '\t') && qcount == 0) {
/* close the argument */
*d++ = 0;
bcount = 0;
/* skip to the next one and initialize it if any */
do {
s++;
} while (*s == ' ' || *s == '\t');
if (*s)
argv[argc++] = d;
} else if (*s == '\\') {
*d++ = *s++;
bcount++;
} else if (*s == '"') {
if ((bcount & 1) == 0) {
/* Preceded by an even number of '\', this is half that
* number of '\', plus a quote which we erase.
*/
d -= bcount / 2;
qcount++;
} else {
/* Preceded by an odd number of '\', this is half that
* number of '\' followed by a '"'
*/
d = d - bcount / 2 - 1;
*d++ = '"';
}
s++;
bcount = 0;
/* Now count the number of consecutive quotes. Note that qcount
* already takes into account the opening quote if any, as well as
* the quote that lead us here.
*/
while (*s == '"') {
if (++qcount == 3) {
*d++ = '"';
qcount = 0;
}
s++;
}
if (qcount == 2)
qcount = 0;
} else {
/* a regular character */
*d++ = *s++;
bcount = 0;
}
}
*d = '\0';
argv[argc] = NULL;
*numargs = (int) argc;
return argv;
}
#endif

68
pak/gitignore Normal file
View file

@ -0,0 +1,68 @@
# Prerequisites
*.d
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
# pak file
*.pak
# pak unpacked files
tests/*
# builds
build_*/*
# codeblocks
bin/*
obj/*
*.cbp
*.depend
*.layout

178
pak/main.c Normal file
View file

@ -0,0 +1,178 @@
#if defined(_WIN32) && defined(_LGPL)
#include "main.h"
#endif
#include "pak_defs.h"
#include "pak_file.h"
#include "pak_file_io.h"
#include "pak_get_file_type.h"
#include "pak_header.h"
#include "pak_pack.h"
#define HELP_TEXT \
"Pack/Unpack chrome pak file.\n\n" \
"%s -u pak_file destination_path\n" \
"Unpack chrome pak file at pak_file to destination_path.\n\n" \
"%s -p pak_index_file destination_pak_file\n" \
"Pack chrome pak file using pak_index_file to destination_pak_file.\n" \
"pak_index_file would be found in unpacked path.\n" \
"\nNote: existing destination files would be overwritten\n"
void printHelp() {
// get self path
char selfName[PATH_MAX];
#ifdef _WIN32
GetModuleFileName(NULL, selfName, PATH_MAX);
// get file name from path
const char *ptr = strrchr(selfName, '\\');
#else
int ret = readlink("/proc/self/exe", selfName, sizeof(selfName) - 1);
if (ret == -1)
strcpy(selfName, "pak");
else
selfName[ret] = 0;
// get file name from path
const char *ptr = strrchr(selfName, '/');
#endif
if (ptr != NULL)
strcpy(selfName, ptr + 1);
printf(HELP_TEXT, selfName, selfName);
}
int pakUnpackPath(char *pakFilePath, char *outputPath) {
PakFile pakFile = readFile(pakFilePath);
if (pakFile.buffer == NULL) {
printf("Error: cannot read pak file %s", pakFilePath);
return 1;
}
MyPakHeader myHeader;
if (!pakParseHeader(pakFile.buffer, &myHeader)) {
return 2;
}
if (!pakCheckFormat(pakFile.buffer, pakFile.size)) {
return 3;
}
if (!pakUnpack(pakFile.buffer, outputPath)) {
freeFile(pakFile);
return 4;
}
freeFile(pakFile);
return 0;
}
int pakPackIndexFile(char *indexPath, char *outputFilePath) {
int returnCode = 0;
PakFile pakPackedFile = NULL_File;
PakFile pakIndexFile = NULL_File;
char *filesPath = NULL;
bool freeFilesPath = false;
char *outputFilePath2 = NULL;
char *index = strrchr(indexPath, '\\');
if (index == NULL) {
index = strrchr(indexPath, '/');
}
if (index != NULL && index > indexPath) {
filesPath = calloc(index - indexPath + 2, sizeof(char));
if (filesPath == NULL) {
returnCode = 5;
goto PAK_PACK_INDEX_END;
}
strncpy(filesPath, indexPath, index - indexPath + 1);
freeFilesPath = true;
} else {
filesPath = "";
}
pakIndexFile = readFile(indexPath);
if (pakIndexFile.buffer == NULL) {
printf("Error: cannot read file %s", indexPath);
returnCode = 6;
goto PAK_PACK_INDEX_END;
}
// workaround outputFilePath="" after pakPack()
outputFilePath2 = calloc(strlen(outputFilePath) + 1, sizeof(char));
if (outputFilePath2 == NULL) {
returnCode = 7;
goto PAK_PACK_INDEX_END;
}
strcpy(outputFilePath2, outputFilePath);
pakPackedFile = pakPack(pakIndexFile, filesPath);
if (pakPackedFile.buffer == NULL) {
returnCode = 8;
goto PAK_PACK_INDEX_END;
}
if (!writeFile(outputFilePath2, pakPackedFile)) {
printf("Error: cannot write to %s", outputFilePath2);
returnCode = 9;
goto PAK_PACK_INDEX_END;
}
PAK_PACK_INDEX_END:
if (pakIndexFile.buffer != NULL)
freeFile(pakIndexFile);
if (pakPackedFile.buffer != NULL)
freeFile(pakPackedFile);
if (outputFilePath2 != NULL)
free(outputFilePath2);
if (freeFilesPath && filesPath != NULL)
free(filesPath);
return returnCode;
}
#define PAK_FLAGS_HELP 0
#define PAK_FLAGS_UNPACK 1
#define PAK_FLAGS_PACK 2
int main(int argc, char *argv[]) {
uint32_t flags = 0;
bool process = false;
char path1[PATH_MAX];
memset(path1, 0, PATH_MAX);
char path2[PATH_MAX];
memset(path2, 0, PATH_MAX);
for (int i = 1; i < argc; i++) {
char *arg = argv[i];
bool isConfig = false;
if (*arg != '\0' && (*arg == '/' || *arg == '-')) {
arg++;
isConfig = true;
}
if (isConfig) {
switch (*arg) {
case 'h':
flags = PAK_FLAGS_HELP;
break;
case 'a':
case 'p':
flags = PAK_FLAGS_PACK;
break;
case 'u':
case 'e':
case 'x':
flags = PAK_FLAGS_UNPACK;
break;
}
}
if ((flags == PAK_FLAGS_UNPACK || flags == PAK_FLAGS_PACK) &&
argc - i > 2) {
strcpy(path1, argv[i + 1]);
strcpy(path2, argv[i + 2]);
process = true;
break;
}
}
if (flags == PAK_FLAGS_HELP || !process) {
printHelp();
return 0;
}
if (flags == PAK_FLAGS_UNPACK) {
return pakUnpackPath(path1, path2);
} else if (flags == PAK_FLAGS_PACK) {
return pakPackIndexFile(path1, path2);
}
return 32;
}

31
pak/main.h Normal file
View file

@ -0,0 +1,31 @@
// Small alternative startfile for main()
// Build with gcc perms:
// -nostartfiles
#pragma once
#ifndef STARTFILE_MAIN_H
#define STARTFILE_MAIN_H
#include <windows.h>
#ifdef UNICODE
#define wmain(argc, argv) _wmain(argc, argv)
int wmain(int argc, wchar_t *argv[]);
#else
#include "commandlinetoargva.h"
// workaround undefined reference to `_pei386_runtime_relocator'
#define main(argc, argv) _main(argc, argv)
int main(int argc, char *argv[]);
#endif
int __cdecl mainCRTStartup() {
int __arg_c;
#ifdef UNICODE
wchar_t **__arg_v = CommandLineToArgvW(GetCommandLineW(), &__arg_c);
const int exitCode = wmain(__arg_c, __arg_v);
#else
char **__arg_v = CommandLineToArgvA(GetCommandLineA(), &__arg_c);
const int exitCode = main(__arg_c, __arg_v);
#endif
LocalFree(__arg_v);
ExitProcess((UINT) exitCode);
return exitCode;
}
#endif

18
pak/pack.bat Normal file
View file

@ -0,0 +1,18 @@
@echo off
setlocal EnableExtensions EnableDelayedExpansion
if exist "%SystemRoot%\SysWOW64\cmd.exe" set x64=1
pushd "%~dp0"
set core_x64=pak_mingw64.exe
if not exist "%core_x64%" if exist pak_msvc64.exe set core_x64=pak_msvc64.exe
set core_x86=pak_mingw32.exe
if not exist "%core_x86%" if exist pak_msvc32.exe set core_x86=pak_msvc32.exe
set "WORK_DIR=%~dp0"
set "file=%~1"
set "pack_file=%~dpn1_packed.pak"
if not exist "%WORK_DIR%" md "%WORK_DIR%"
pushd "%WORK_DIR%"
if "%x64%"=="1" ( set core=%core_x64% ) else ( set core=%core_x86% )
if not exist %core% echo core program (%core%) NOT FOUND! &pause &exit
if exist "%file%" %core% -p "%file%" "%pack_file%"
if exist "%pack_file%" echo packed "%pack_file%" from "%file%"
timeout /t 5||pause

99
pak/pak_defs.h Normal file
View file

@ -0,0 +1,99 @@
#pragma once
#ifndef __PAK_DEFINITIONS_H__
#define __PAK_DEFINITIONS_H__
// msvc hacks
#ifdef _MSC_VER
#include <windows.h>
#define ftello ftell
#define fseeko fseek
#define PATH_MAX MAX_PATH
#endif
// linux header
#ifdef __linux__
#include <linux/limits.h>
#include <unistd.h>
#endif
// macOS headers
#ifdef __APPLE__
#include <sys/syslimits.h>
#include <unistd.h>
#endif
#include <stdbool.h>
#include <stdint.h>
#pragma pack(push)
#pragma pack(1)
// v5 header:
// uint32(version), uint8(encoding), 3 bytes padding,
// uint16(resource_count), uint16(alias_count)
typedef struct PakHeaderV5 {
uint32_t version;
uint8_t encoding;
uint8_t _padding[3];
uint16_t resource_count;
uint16_t alias_count;
} PakHeaderV5;
// v4 header: uint32(version), uint32(resource_count), uint8(encoding)
typedef struct PakHeaderV4 {
uint32_t version;
uint32_t resource_count;
uint8_t encoding;
} PakHeaderV4;
// Entry: uint16_t resourceId; uint32_t offset;
typedef struct PakEntry {
uint16_t resource_id;
uint32_t offset;
} PakEntry;
// Alias: uint16_t resourceId; uint16_t entry_index;
typedef struct PakAlias {
uint16_t resource_id;
uint16_t entry_index;
} PakAlias;
#pragma pack(pop)
/**
* Get pak version from pak buffer.
* @param void *buffer - pointer to pak.
* @return uint32_t - pak version.
*/
#define pakGetVerison(buffer) (*(uint32_t *)(buffer))
#define PAK_HEADER_SIZE_V4 sizeof(PakHeaderV4)
#define PAK_HEADER_SIZE_V5 sizeof(PakHeaderV5)
#define PAK_ENTRY_SIZE sizeof(PakEntry)
#define PAK_ALIAS_SIZE sizeof(PakAlias)
#define PAK_ERROR_UNKNOWN_VER "Error: Unknown pak version."
#define PAK_ERROR_TRUNCATED "Error: Probably truncated pak file."
#define PAK_ERROR_BROKEN_INDEX "Error: Probably broken pak index file."
typedef struct MyPakHeader {
uint32_t version;
uint32_t resource_count;
uint16_t alias_count;
uint8_t encoding;
uint8_t size;
} MyPakHeader;
typedef struct PakFile {
uint16_t id;
uint32_t size;
void *buffer;
} PakFile;
// file-io
#define NULL_File ((PakFile){0, 0, NULL})
#define freeFile(file) (free((file).buffer))
// pack/unpack
#define PAK_BUFFER_BLOCK_SIZE 4096
#define PAK_BUFFER_MIN_FREE_SIZE 512
#define PAK_INDEX_GLOBAL_TAG "[Global]"
#define PAK_INDEX_RES_TAG "[Resources]"
#define PAK_INDEX_ALIAS_TAG "[Alias]"
#endif // __PAK_DEFINITIONS_H__

94
pak/pak_file.c Normal file
View file

@ -0,0 +1,94 @@
#include "pak_file.h"
PakFile pakPackFiles(MyPakHeader *myHeader, PakFile *pakResFile,
PakAlias *pakAlias) {
uint8_t *buffer = NULL;
uint32_t size = myHeader->size;
uint32_t entrySize = (myHeader->resource_count + 1) * PAK_ENTRY_SIZE;
uint32_t aliasSize = myHeader->alias_count * PAK_ALIAS_SIZE;
size += entrySize + aliasSize;
for (uint32_t i = 0; i < myHeader->resource_count; i++) {
size += (pakResFile + i)->size;
}
buffer = calloc(size, sizeof(uint8_t));
if (buffer == NULL)
return NULL_File;
uint32_t offset = pakWriteHeader(myHeader, buffer);
if (offset == 0) {
free(buffer);
return NULL_File;
}
PakEntry *enrtyPtr = (PakEntry *)(buffer + offset);
uint8_t *filePtr = buffer + offset + entrySize + aliasSize;
for (uint32_t i = 0; i < myHeader->resource_count; i++) {
memcpy(filePtr, pakResFile->buffer, pakResFile->size);
enrtyPtr->resource_id = pakResFile->id;
enrtyPtr->offset = filePtr - buffer;
filePtr += pakResFile->size;
enrtyPtr++;
pakResFile++;
}
enrtyPtr->resource_id = 0;
enrtyPtr->offset = (pakResFile - 1)->size + (enrtyPtr - 1)->offset;
void *aliasPtr = (void *)(enrtyPtr + 1);
memcpy(aliasPtr, pakAlias, aliasSize);
PakFile pakFile;
pakFile.buffer = buffer;
pakFile.size = size;
return pakFile;
}
PakFile pakGetFile(uint8_t *pakBuffer, uint16_t id) {
PakFile pakFile = NULL_File;
MyPakHeader myHeader;
if (!pakParseHeader(pakBuffer, &myHeader)) {
return NULL_File;
}
PakEntry *entryPtr = (PakEntry *)(pakBuffer + myHeader.size);
if (myHeader.version == 5) {
PakAlias *aliasPtr =
(PakAlias *)(pakBuffer + myHeader.size +
(myHeader.resource_count + 1) * PAK_ENTRY_SIZE);
for (uint16_t i = 0; i < myHeader.alias_count; i++) {
if (aliasPtr->resource_id == id) {
entryPtr += aliasPtr->entry_index;
pakFile.buffer = pakBuffer + entryPtr->offset;
pakFile.size = (entryPtr + 1)->offset - entryPtr->offset;
return pakFile;
}
}
}
for (uint32_t i = 0; i < myHeader.resource_count; i++) {
if (entryPtr->resource_id == id) {
pakFile.buffer = pakBuffer + entryPtr->offset;
pakFile.size = (entryPtr + 1)->offset - entryPtr->offset;
return pakFile;
}
entryPtr++;
}
return NULL_File;
}
PakFile *pakGetFiles(uint8_t *buffer) {
PakFile *pakResFile = NULL;
MyPakHeader myHeader;
if (!pakParseHeader(buffer, &myHeader)) {
return NULL;
}
pakResFile = (PakFile *)calloc(myHeader.resource_count, sizeof(PakFile));
PakFile *returnValue = pakResFile;
if (pakResFile == NULL) {
return NULL;
}
PakEntry *pakEntryPtr = (PakEntry *)(buffer + myHeader.size);
for (uint32_t i = 0; i < myHeader.resource_count; i++) {
uint32_t offset = pakEntryPtr->offset;
pakResFile->id = pakEntryPtr->resource_id;
pakResFile->buffer = buffer + offset;
pakEntryPtr++;
pakResFile->size = pakEntryPtr->offset - offset;
pakResFile++;
}
return returnValue;
}

38
pak/pak_file.h Normal file
View file

@ -0,0 +1,38 @@
#pragma once
#ifndef __PAK_FILE_H__
#define __PAK_FILE_H__
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "pak_defs.h"
#include "pak_header.h"
/**
* Package a pak file, returns NULL_File on failure.
* Note: this would allocate memory.
* @param MyPakHeader *myHeader - pointer to MyPakHeader struct.
* @param PakFile *pakResFile - pointer to all resource files.
* @param PakAlias *pakAlias - pointer to all alias.
* @return PakFile - the packed file.
*/
PakFile pakPackFiles(MyPakHeader *myHeader, PakFile *pakResFile,
PakAlias *pakAlias);
/**
* Get a single file from pak, returns NULL_File on failure.
* @param void *pakBuffer - pointer to pak.
* @param uint16_t *id - target file id.
* @return PakFile - the target file.
*/
PakFile pakGetFile(uint8_t *pakBuffer, uint16_t id);
/**
* Get all files from pak, returns NULL on failure.
* Note: this would allocate memory.
* @param void* buffer - pointer to pak.
* @return PakFile* - pointer to all files in pak.
*/
PakFile *pakGetFiles(uint8_t *buffer);
#endif // __PAK_FILE_H__

41
pak/pak_file_io.c Normal file
View file

@ -0,0 +1,41 @@
#include "pak_file_io.h"
PakFile readFile(const char *fileName) {
PakFile file;
/* declare a file pointer */
FILE *filePtr = fopen(fileName, "rb");
/* quit if the file does not exist */
if (filePtr == NULL)
return NULL_File;
/* Get the number of bytes */
fseeko(filePtr, 0, SEEK_END);
file.size = (uint32_t) ftello(filePtr);
/* reset the file position indicator to
the beginning of the file */
fseeko(filePtr, 0, SEEK_SET);
/* grab sufficient memory for the
buffer to hold the text */
file.buffer = calloc(file.size + 1, sizeof(uint8_t));
/* memory error */
if (file.buffer == NULL)
return NULL_File;
/* copy all the text into the buffer */
fread(file.buffer, sizeof(uint8_t), file.size, filePtr);
fclose(filePtr);
return file;
}
bool writeFile(const char *fileName, const PakFile file) {
FILE *filePtr = fopen(fileName, "wb");
if (filePtr == NULL)
return false;
const size_t result = fwrite(file.buffer, sizeof(uint8_t), file.size, filePtr);
fclose(filePtr);
return (result == file.size);
}

26
pak/pak_file_io.h Normal file
View file

@ -0,0 +1,26 @@
#pragma once
#ifndef __PAK_FILE_IO_H__
#define __PAK_FILE_IO_H__
#include "pak_defs.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
/**
* Read a file into memory, returns NULL_File on failure.
* Note: this would allocate memory.
* @param const char *fileName - target file name.
* @return PakFile - target file content.
*/
PakFile readFile(const char *fileName);
/**
* Write a file to storage, this would overwrite existing file.
* @param const char *fileName - target file name.
* @param PakFile file - target file content.
* @return bool - succeed or not.
*/
bool writeFile(const char *fileName, const PakFile file);
#endif // __PAK_FILE_IO_H__

27
pak/pak_get_file_type.c Normal file
View file

@ -0,0 +1,27 @@
#include "pak_get_file_type.h"
static const FileType FILE_TYPES[] = {
PAK_GEN_FILE_TYPE(".png", "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"),
PAK_GEN_FILE_TYPE(".html", "<!doctype html>"),
PAK_GEN_FILE_TYPE(".html", "<!DOCTYPE html>"),
PAK_GEN_FILE_TYPE(".html", "<html>"),
PAK_GEN_FILE_TYPE(".html", "<!--"),
PAK_GEN_FILE_TYPE(".html", "<link"),
PAK_GEN_FILE_TYPE(".svg", "<svg "),
PAK_GEN_FILE_TYPE(".js", "// "),
PAK_GEN_FILE_TYPE(".js", "(function"),
PAK_GEN_FILE_TYPE(".css", "/*"),
PAK_GEN_FILE_TYPE(".json", "{"),
PAK_GEN_FILE_TYPE(".gz", "\x1f\x8b")};
static const unsigned int FILE_TYPE_COUNT =
sizeof(FILE_TYPES) / sizeof(FileType);
char *pakGetFileType(PakFile file) {
for (unsigned int i = 0; i < FILE_TYPE_COUNT; i++)
if (file.size > FILE_TYPES[i].size &&
memcmp(file.buffer, FILE_TYPES[i].identifer, FILE_TYPES[i].size) ==
0)
return FILE_TYPES[i].type;
return "";
}

32
pak/pak_get_file_type.h Normal file
View file

@ -0,0 +1,32 @@
#pragma once
#ifndef __PAK_GET_FILE_TYPE_H__
#define __PAK_GET_FILE_TYPE_H__
#include "pak_defs.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
typedef struct FileType {
char *type;
char *identifer;
uint8_t size;
} FileType;
/**
* Generate a FileType, for internal uses only.
* @param char* type - file extension.
* @param char* identifer - file header identifer in string.
* @see pakGetFileType()
* @return FileType
*/
#define PAK_GEN_FILE_TYPE(type, identifer) \
{type, identifer, sizeof(identifer) - 1}
/**
* Get file extension form a file, returns "" on failure.
* @param PakFile file - the file to parse.
* @return char* - pointer to file extension.
*/
char *pakGetFileType(PakFile file);
#endif // __PAK_GET_FILE_TYPE_H__

66
pak/pak_header.c Normal file
View file

@ -0,0 +1,66 @@
#include "pak_header.h"
bool pakParseHeader(void *buffer, MyPakHeader *myHeader) {
memset(myHeader, 0, sizeof(MyPakHeader));
myHeader->version = pakGetVerison(buffer);
if (myHeader->version == 5) {
PakHeaderV5 *header = (PakHeaderV5 *)buffer;
myHeader->resource_count = header->resource_count;
myHeader->encoding = header->encoding;
myHeader->alias_count = header->alias_count;
myHeader->size = PAK_HEADER_SIZE_V5;
} else if (myHeader->version == 4) {
PakHeaderV4 *header = (PakHeaderV4 *)buffer;
myHeader->resource_count = header->resource_count;
myHeader->encoding = header->encoding;
myHeader->alias_count = 0;
myHeader->size = PAK_HEADER_SIZE_V4;
} else {
puts(PAK_ERROR_UNKNOWN_VER);
return false;
}
return true;
}
unsigned int pakWriteHeader(MyPakHeader *myHeader, void *buffer) {
if (buffer == NULL || myHeader == NULL)
return 0;
if (myHeader->version == 5) {
PakHeaderV5 *header = (PakHeaderV5 *)buffer;
header->version = myHeader->version;
header->resource_count = (uint16_t) myHeader->resource_count;
header->encoding = myHeader->encoding;
header->alias_count = myHeader->alias_count;
} else if (myHeader->version == 4) {
PakHeaderV4 *header = (PakHeaderV4 *)buffer;
header->version = myHeader->version;
header->resource_count = myHeader->resource_count;
header->encoding = myHeader->encoding;
} else {
puts(PAK_ERROR_UNKNOWN_VER);
return 0;
}
return myHeader->size;
}
bool pakCheckFormat(uint8_t *buffer, unsigned int size) {
MyPakHeader myHeader;
if (!pakParseHeader(buffer, &myHeader)) {
return false;
}
if (size < myHeader.size + (myHeader.resource_count + 1) * PAK_ENTRY_SIZE +
myHeader.alias_count * PAK_ALIAS_SIZE) {
puts(PAK_ERROR_TRUNCATED);
return false;
}
PakEntry *entryPtr = (PakEntry *)(buffer + myHeader.size);
for (unsigned int i = 0; i <= myHeader.resource_count; i++) {
uint32_t offset = entryPtr->offset;
if (size < offset) {
puts(PAK_ERROR_TRUNCATED);
return false;
}
entryPtr++;
}
return true;
}

32
pak/pak_header.h Normal file
View file

@ -0,0 +1,32 @@
#pragma once
#ifndef __PAK_HEADERS_H__
#define __PAK_HEADERS_H__
#include "pak_defs.h"
#include <stdio.h>
#include <string.h>
/**
* Generate MyPakHeader struct from pak buffer.
* @param _in_ void *buffer - pointer to pak buffer.
* @param _out_ MyPakHeader myHeader - target file content.
* @return bool - succeed or not.
*/
bool pakParseHeader(void *buffer, MyPakHeader *myHeader);
/**
* Write pak header from MyPakHeader struct to buffer.
* @param MyPakHeader myHeader - target MyPakHeader struct.
* @param void *buffer - pointer to target pak buffer.
* @return unsigned int - pak header size, 0 on failure.
*/
unsigned int pakWriteHeader(MyPakHeader *myHeader, void *buffer);
/**
* Check if pak format is legal.
* @param void *buffer - pointer to pak buffer.
* @param unsigned int size - pak buffer size in bytes.
* @return bool - succeed or not.
*/
bool pakCheckFormat(uint8_t *buffer, unsigned int size);
#endif // __PAK_HEADERS_H__

195
pak/pak_pack.c Normal file
View file

@ -0,0 +1,195 @@
#include "pak_pack.h"
bool pakUnpack(uint8_t *buffer, char *outputPath) {
MyPakHeader myHeader;
if (!pakParseHeader(buffer, &myHeader)) {
return false;
}
PakFile *files = pakGetFiles(buffer);
if (files == NULL) {
return false;
}
char fileNameBuf[FILENAME_MAX];
memset(fileNameBuf, 0, FILENAME_MAX);
char pathBuf[PATH_MAX + 2];
memset(pathBuf, 0, PATH_MAX);
#ifdef _WIN32
CreateDirectory(outputPath, NULL);
#else
mkdir(outputPath, 0777);
#endif
char *pakIndexStr = calloc(PAK_BUFFER_BLOCK_SIZE, sizeof(char));
if (pakIndexStr == NULL) {
free(files);
return false;
}
uint32_t offset = 0;
uint32_t length = PAK_BUFFER_BLOCK_SIZE;
offset +=
sprintf(pakIndexStr + offset, PAK_INDEX_GLOBAL_TAG "\r\nversion=%u\r\n",
myHeader.version);
offset += sprintf(pakIndexStr + offset,
"encoding=%u\r\n\r\n" PAK_INDEX_RES_TAG "\r\n",
myHeader.encoding);
for (uint32_t i = 0; i < myHeader.resource_count; i++) {
sprintf(fileNameBuf, "%u%s", files[i].id, pakGetFileType(files[i]));
offset += sprintf(pakIndexStr + offset, "%u=%s\r\n", files[i].id,
fileNameBuf);
if (length - offset < PAK_BUFFER_MIN_FREE_SIZE) {
pakIndexStr = realloc(pakIndexStr, length + PAK_BUFFER_BLOCK_SIZE);
length += PAK_BUFFER_BLOCK_SIZE;
}
sprintf(pathBuf, "%s/%s", outputPath, fileNameBuf);
writeFile(pathBuf, files[i]);
}
PakAlias *aliasBuf = NULL;
if (myHeader.alias_count > 0) {
offset +=
sprintf(pakIndexStr + offset, "\r\n" PAK_INDEX_ALIAS_TAG "\r\n");
aliasBuf = (PakAlias *)(buffer + myHeader.size +
(myHeader.resource_count + 1) * PAK_ENTRY_SIZE);
}
for (unsigned int i = 0; i < myHeader.alias_count; i++) {
offset += sprintf(pakIndexStr + offset, "%u=%u\r\n",
aliasBuf->resource_id, aliasBuf->entry_index);
aliasBuf++;
if (length - offset < PAK_BUFFER_MIN_FREE_SIZE) {
pakIndexStr = realloc(pakIndexStr, length + PAK_BUFFER_BLOCK_SIZE);
length += PAK_BUFFER_BLOCK_SIZE;
}
}
PakFile pakIndexBuf;
// puts(pakIndexStr);
pakIndexBuf.buffer = pakIndexStr;
pakIndexBuf.size = offset;
sprintf(pathBuf, "%s/pak_index.ini", outputPath);
writeFile(pathBuf, pakIndexBuf);
freeFile(pakIndexBuf);
free(files);
return true;
}
uint32_t countChar(const char *string, uint32_t length, char toCount) {
uint32_t count = 0;
for (uint32_t i = 0; i < length; i++) {
if (string[i] == toCount)
count++;
}
return count;
}
PakFile pakPack(PakFile pakIndex, char *path) { // TODO
MyPakHeader myHeader;
memset(&myHeader, 0, sizeof(myHeader));
char *pakIndexBuf = pakIndex.buffer;
PakFile pakFile = NULL_File;
PakFile *resFiles = NULL;
PakAlias *pakAlias = NULL;
uint32_t count = 0;
uint32_t offset = sizeof(PAK_INDEX_GLOBAL_TAG) - 1;
sscanf(pakIndexBuf + offset, " version=%u%n", &myHeader.version, &count);
if (count == 0) {
goto PAK_PACK_END;
}
offset += count;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
#pragma GCC diagnostic ignored "-Wformat-extra-args"
sscanf(pakIndexBuf + offset, " encoding=%hhu%n", &myHeader.encoding,
&count);
#pragma GCC diagnostic pop
// printf("version=%u\nencoding=%u\n", myHeader.version,
// myHeader.encoding);
if (myHeader.version == 5) {
myHeader.size = PAK_HEADER_SIZE_V5;
} else if (myHeader.version == 4) {
myHeader.size = PAK_HEADER_SIZE_V4;
} else {
puts(PAK_ERROR_UNKNOWN_VER);
goto PAK_PACK_END;
}
char *pakIndexEnd = pakIndexBuf + pakIndex.size - 1;
char *pakEntryIndex =
strstr(pakIndexBuf, PAK_INDEX_RES_TAG) + sizeof(PAK_INDEX_RES_TAG) - 1;
char *pakAliasIndex = strstr(pakIndexBuf, PAK_INDEX_ALIAS_TAG);
if (myHeader.version == 4 || pakAliasIndex == NULL) {
myHeader.alias_count = 0;
pakAliasIndex = pakIndexEnd;
} else {
pakAliasIndex += sizeof(PAK_INDEX_ALIAS_TAG) - 1;
myHeader.alias_count =
(uint16_t) countChar(pakAliasIndex, pakIndexEnd - pakAliasIndex, '=');
}
myHeader.resource_count =
countChar(pakEntryIndex, pakAliasIndex - pakEntryIndex, '=');
// printf("resource_count=%u\nalias_count=%u\n", myHeader.resource_count,
// myHeader.alias_count);
char fileNameBuf[FILENAME_MAX];
memset(fileNameBuf, 0, FILENAME_MAX);
char pathBuf[PATH_MAX];
memset(pathBuf, 0, PATH_MAX);
resFiles = calloc(myHeader.resource_count, sizeof(PakFile));
if (resFiles == NULL) {
goto PAK_PACK_END;
}
offset = 0;
for (uint32_t i = 0; i < myHeader.resource_count; i++) {
uint32_t id = 0;
sscanf(pakEntryIndex + offset, " %u=%s%n ", &id, fileNameBuf, &count);
if (count == 0 || sprintf(pathBuf, "%s%s", path, fileNameBuf) == 0) {
puts(PAK_ERROR_BROKEN_INDEX);
myHeader.resource_count = i;
goto PAK_PACK_END;
}
offset += count;
resFiles[i] = readFile(pathBuf);
if (resFiles[i].buffer == NULL) {
puts(PAK_ERROR_BROKEN_INDEX);
myHeader.resource_count = i;
goto PAK_PACK_END;
}
resFiles[i].id = (uint16_t) id;
// printf("id=%u\tfile_name=%s\tpath=%s\tsize=%u\n",id,
// fileNameBuf, pathBuf, resFiles[i].size);
}
if (myHeader.alias_count > 0) {
offset = 0;
pakAlias = calloc(myHeader.alias_count, sizeof(PakAlias));
if (pakAlias == NULL) {
goto PAK_PACK_END;
}
for (uint32_t i = 0; i < myHeader.alias_count; i++) {
sscanf(pakAliasIndex + offset, " %hu=%hu%n ",
&pakAlias[i].resource_id, &pakAlias[i].entry_index, &count);
if (count == 0) {
puts(PAK_ERROR_BROKEN_INDEX);
goto PAK_PACK_END;
}
offset += count;
// printf("resource_id=%hu\tentry_index=%hu\n",pakAlias[i].resource_id,
// pakAlias[i].entry_index);
}
}
pakFile = pakPackFiles(&myHeader, resFiles, pakAlias);
printf("\nresource_count=%u\nalias_count=%u\n", myHeader.resource_count,
myHeader.alias_count);
printf("version=%u\nencoding=%u\n", myHeader.version, myHeader.encoding);
printf("\npak size: %u\n", pakFile.size);
PAK_PACK_END:
if (resFiles != NULL) {
for (uint32_t i = 0; i < myHeader.resource_count; i++) {
if (resFiles[i].buffer != NULL)
free(resFiles[i].buffer);
}
free(resFiles);
}
if (pakAlias != NULL)
free(pakAlias);
return pakFile;
}

49
pak/pak_pack.h Normal file
View file

@ -0,0 +1,49 @@
#pragma once
#ifndef __PAK_PACKER_UNPACKER_H__
#define __PAK_PACKER_UNPACKER_H__
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "pak_defs.h"
#include "pak_file.h"
#include "pak_file_io.h"
#include "pak_get_file_type.h"
#include "pak_header.h"
/**
* Unpack a pak file to target path.
* @param void *buffer - pointer to target pak buffer.
* @param char *outputPath - target path.
* @return bool - succeed or not.
*/
bool pakUnpack(uint8_t *buffer, char *outputPath);
/**
* Pack a pak file from target index (ini) file,
* returns NULL_File on failure.
* Note: this would allocate memory.
* @param PakFile pakIndex - target pak index file.
* @param char *path - target path.
* @return PakFile - packed pak.
*/
PakFile pakPack(PakFile pakIndex, char *path);
/**
* Count number of specified char in string.
* @param char *string - target string.
* @param uint32_t length - target string length.
* @param char toCount - specified char to count.
* @return uint32_t - number of specified char.
*/
uint32_t countChar(const char *string, uint32_t length, char toCount);
#endif // __PAK_PACKER_UNPACKER_H__

17
pak/test.sh Normal file
View file

@ -0,0 +1,17 @@
#!/bin/bash
MACHINE="$(gcc -dumpmachine)"
echo Building...
mkdir -p "build_${MACHINE}"
cd "build_${MACHINE}"
rm -f *.pak
cmake -GNinja ..
ninja
echo Testing...
for i in $(ls ../tests | grep pak | cut -f1 -d '.')
do
./pak -u "../tests/${i}.pak" "./${i}_unpacked"
./pak -p "./${i}_unpacked/pak_index.ini" "${i}_repacked.pak"
cmp "../tests/${i}.pak" "${i}_repacked.pak" && rm -rf "./${i}_unpacked"
done
cd ..

19
pak/unpack.bat Normal file
View file

@ -0,0 +1,19 @@
@echo off
setlocal EnableExtensions EnableDelayedExpansion
if exist "%SystemRoot%\SysWOW64\cmd.exe" set x64=1
pushd "%~dp0"
set core_x64=pak_mingw64.exe
if not exist "%core_x64%" if exist pak_msvc64.exe set core_x64=pak_msvc64.exe
set core_x86=pak_mingw32.exe
if not exist "%core_x86%" if exist pak_msvc32.exe set core_x86=pak_msvc32.exe
set "WORK_DIR=%~dp0"
set "file=%~1"
set unpack_dir=%~dpn1_unpacked
if not exist "%WORK_DIR%" md "%WORK_DIR%"
pushd "%WORK_DIR%"
if "%x64%"=="1" ( set core=%core_x64% ) else ( set core=%core_x86% )
if not exist %core% echo core program (%core%) NOT FOUND! &pause &exit
if not exist "%unpack_dir%" md "%unpack_dir%"
if exist "%file%" %core% -u "%file%" "%unpack_dir%"
if exist "%unpack_dir%\pak_index.ini" echo Unpacked "%file%" to "%unpack_dir%"
timeout /t 5||pause