project import

This commit is contained in:
Stefanos Kornilios Mitsis Poiitidis committed 2013-12-19 19:10:14 +02:00
commit 1c16baeb0e
620 files changed
+174969

No files matched your search

+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 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.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, 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.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+68
View File
@@ -0,0 +1,68 @@
reicast
===========
reicast is a sega dreamcast emulator
This is developer oriented resource, if you just want bins head over to http://reicast.com
Caution
-------
The source is a mess, and I need sleep.
We had to discover some interesting arm bugs on the cleaned/refactored branch right after the release.
Expect a much improved changed folder/make structure soon.
Rebranding/forks
----------------
If you are interested into further porting/adapting/whatever, *please* don't fork off. I hate that. Really.
Let’s try to keep everything under a single project :)
To build for android
--------------------
```
cd newdc\android\libnewdc
android update project -p .
cd ..\..\..\reicast\android
android update project -p .
ndk-build -j 4
ant debug
```
Donations and stuff
-------------------
Well, glad you liked the project so far!
We're currently short on hardware
If you would like to donate some devices, get in touch at team@reicast.com. GLES3 capable stuff, some mainstream hardware and rarities would be extremely appreciated.
Keep in mind we're located in Greece for the most part
This has been tested/developed on
* Galaxy tab 7.0 Plus
* P990
* Archos 10G9
* Some Chinese tablet
* OUYA
* Various development boards
* gcw zero
We had to buy all of these, except the gcw zero and a beaglebone which were donated (thanks! You rock!)
Apart from that, we don't accept monetary donations right now.
We also don't plan to be releasing a premium version at any store.
Most of the project has been developed by drk||Raziel (aka, skmp, drk, Raz, etc) but it has been based on the
Works of multiple people. It would be extremely unfair to charge for it and get all the credit :)
We're planning for an indiegogo campaign later on to help with sustained development and running costs, so follow @reicastdc on twitter for updates
Team
----
The active team consists of drk||Raziel (mostly just writing code), PsyMan (debugging/testing and everything else) and a little bit of gb_away
In previous iterations a lot of people have worked on this, notably David Miller (aka, ZeZu), the nullDC team, friends from #pcsx2 and all over the world :)
Thanks guys
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OpenGL ES info</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,4 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.source=1.5
+25
View File
@@ -0,0 +1,25 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ogles_info"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
+14
View File
@@ -0,0 +1,14 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-15
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

+62
View File
@@ -0,0 +1,62 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/menu_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="horizontal" >
<ToggleButton
android:id="@+id/tbn_alpha"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="Alpha"
android:textOn="Alpha" />
<ToggleButton
android:id="@+id/tbn_24bits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="True Color"
android:textOn="True Color" />
<ToggleButton
android:id="@+id/tbn_depth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
android:textOff="Depth"
android:textOn="Depth" />
<ToggleButton
android:id="@+id/tbn_stencil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
android:textOff="Stencil"
android:textOn="Stencil" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/menu_list" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/caps_list" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
+6
View File
@@ -0,0 +1,6 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings"
android:title="@string/menu_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
+7
View File
@@ -0,0 +1,7 @@
<resources>
<dimen name="padding_small">8dp</dimen>
<dimen name="padding_medium">16dp</dimen>
<dimen name="padding_large">16dp</dimen>
</resources>
+5
View File
@@ -0,0 +1,5 @@
<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light" />
</resources>
+5
View File
@@ -0,0 +1,5 @@
<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
</resources>
+7
View File
@@ -0,0 +1,7 @@
<resources>
<dimen name="padding_small">8dp</dimen>
<dimen name="padding_medium">8dp</dimen>
<dimen name="padding_large">16dp</dimen>
</resources>
+8
View File
@@ -0,0 +1,8 @@
<resources>
<string name="app_name">OpenGL ES info</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">OpenGL ES info</string>
</resources>
+5
View File
@@ -0,0 +1,5 @@
<resources>
<style name="AppTheme" parent="android:Theme.Light" />
</resources>
@@ -0,0 +1,156 @@
package com.example.ogles_info;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL11;
import android.opengl.GLES20;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
LinearLayout lv;
ToggleButton tbn_alpha;
ToggleButton tbn_24bits;
ToggleButton tbn_depth;
ToggleButton tbn_stencil;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (LinearLayout)findViewById(R.id.caps_list);
OnClickListener ocl =new OnClickListener() { public void onClick(View v) { MainActivity.this.populate_list(); } };
tbn_24bits=(ToggleButton)findViewById(R.id.tbn_24bits);
tbn_depth=(ToggleButton)findViewById(R.id.tbn_depth);
tbn_stencil=(ToggleButton)findViewById(R.id.tbn_stencil);
tbn_alpha=(ToggleButton)findViewById(R.id.tbn_alpha);
tbn_24bits.setOnClickListener(ocl);
tbn_depth.setOnClickListener(ocl);
tbn_stencil.setOnClickListener(ocl);
tbn_alpha.setOnClickListener(ocl);
populate_list();
}
void add_string(String s)
{
TextView tv = new TextView(this);
tv.setText(s);
lv.addView(tv);
}
void populate_list()
{
lv.removeAllViews();
EGL10 e = (EGL10)EGLContext.getEGL();
//EGL10 e = (EGL10)GLES20.glGetString(name)
add_string("BOARD: " + android.os.Build.BOARD);
add_string("BOOTLOADER: " + android.os.Build.BOOTLOADER);
add_string("BRAND: " + android.os.Build.BRAND);
add_string("CPU_ABI: " + android.os.Build.CPU_ABI);
add_string("CPU_ABI2: " + android.os.Build.CPU_ABI2);
add_string("DEVICE: " + android.os.Build.DEVICE);
add_string("DISPLAY: " + android.os.Build.DISPLAY);
add_string("FINGERPRINT: " + android.os.Build.FINGERPRINT);
add_string("HARDWARE: " + android.os.Build.HARDWARE);
add_string("HOST: " + android.os.Build.HOST);
add_string("ID: " + android.os.Build.ID);
add_string("MANUFACTURER: " + android.os.Build.MANUFACTURER);
add_string("MODEL: " + android.os.Build.MODEL);
add_string("PRODUCT: " + android.os.Build.PRODUCT);
//add_string("SERIAL: " + android.os.Build.SERIAL);
add_string("TAGS: " + android.os.Build.TAGS);
add_string("TYPE: " + android.os.Build.TYPE);
add_string("CODENAME: " + android.os.Build.VERSION.CODENAME);
add_string("RELEASE: " + android.os.Build.VERSION.RELEASE);
add_string("INCREMENTAL: " + android.os.Build.VERSION.INCREMENTAL);
add_string("SDK: " + android.os.Build.VERSION.SDK_INT);
EGLConfig[] cfgs = new EGLConfig[1000];
int[] cfg_cnt= new int[1];
EGLDisplay disp=e.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
e.eglInitialize(disp, version);
e.eglGetConfigs(disp, cfgs, cfgs.length, cfg_cnt);
for (int i=0;i<cfg_cnt[0];i++)
{
EGLConfig cfg=cfgs[i];
int[] temp= new int[1];
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_RENDERABLE_TYPE, temp);
if (0!= (temp[0]&4) )
{
String s="";
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_BUFFER_SIZE, temp);
if (tbn_24bits.isChecked() && temp[0]<24)
continue;
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_RED_SIZE, temp);
s+="R" + temp[0];
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_GREEN_SIZE, temp);
s+="G" + temp[0];
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_BLUE_SIZE, temp);
s+="B" + temp[0];
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_ALPHA_SIZE, temp);
if (tbn_alpha.isChecked() && temp[0]==0)
continue;
s+="A" + temp[0];
s+=" ";
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_DEPTH_SIZE, temp);
s+="D" + temp[0];
if (tbn_depth.isChecked() && temp[0]==0)
continue;
e.eglGetConfigAttrib(disp, cfg, EGL10.EGL_STENCIL_SIZE, temp);
s+="S" + temp[0];
if (tbn_stencil.isChecked() && temp[0]==0)
continue;
add_string(s);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
+4
View File
@@ -0,0 +1,4 @@
newdc
===========
The core of the emulator
+291
View File
@@ -0,0 +1,291 @@
#include <jni.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <android/log.h>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "types.h"
#include "profiler/profiler.h"
#include "cfg/cfg.h"
#include "rend/TexCache.h"
#include "util.h"
extern "C"
{
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_init(JNIEnv *env,jobject obj,jstring fileName) __attribute__((visibility("default")));
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_run(JNIEnv *env,jobject obj,jobject track) __attribute__((visibility("default")));
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_stop(JNIEnv *env,jobject obj) __attribute__((visibility("default")));
JNIEXPORT jint JNICALL Java_com_example_newdc_JNIdc_send(JNIEnv *env,jobject obj,jint id, jint v) __attribute__((visibility("default")));
JNIEXPORT jint JNICALL Java_com_example_newdc_JNIdc_data(JNIEnv *env,jobject obj,jint id, jbyteArray d) __attribute__((visibility("default")));
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_rendinit(JNIEnv *env,jobject obj,jint w,jint h) __attribute__((visibility("default")));
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_rendframe(JNIEnv *env,jobject obj) __attribute__((visibility("default")));
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_kcode(JNIEnv * env, jobject obj,u32 k_code, u32 l_t, u32 r_t, u32 jx, u32 jy) __attribute__((visibility("default")));
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_vjoy(JNIEnv * env, jobject obj,u32 id,float x, float y, float w, float h) __attribute__((visibility("default")));
//JNIEXPORT jint JNICALL Java_com_example_newdc_JNIdc_play(JNIEnv *env,jobject obj,jshortArray result,jint size);
};
void egl_stealcntx();
void SetApplicationPath(wchar *path);
int dc_init(int argc,wchar* argv[]);
void dc_run();
void dc_term();
bool VramLockedWrite(u8* address);
bool rend_single_frame();
bool gles_init();
//extern cResetEvent rs,re;
extern int screen_width,screen_height;
static u64 tvs_base;
static char CurFileName[256];
u16 kcode[4];
u32 vks[4];
s8 joyx[4],joyy[4];
u8 rt[4],lt[4];
float vjoy_pos[14][8];
extern bool print_stats;
void os_DoEvents()
{
// @@@ Nothing here yet
}
//
// Native thread that runs the actual nullDC emulator
//
static void *ThreadHandler(void *UserData)
{
char *Args[3];
const char *P;
// Make up argument list
P = (const char *)UserData;
Args[0] = "dc";
Args[1] = "-config";
Args[2] = P&&P[0]? (char *)malloc(strlen(P)+32):0;
if(Args[2])
{
strcpy(Args[2],"config:image=");
strcat(Args[2],P);
}
// Run nullDC emulator
dc_init(Args[2]? 3:1,Args);
}
//
// Platform-specific NullDC functions
//
int msgboxf(const wchar* Text,unsigned int Type,...)
{
wchar S[2048];
va_list Args;
va_start(Args,Type);
vsprintf(S,Text,Args);
va_end(Args);
puts(S);
return(MBX_OK);
}
void UpdateInputState(u32 Port)
{
// @@@ Nothing here yet
}
void *libPvr_GetRenderTarget()
{
// No X11 window in Android
return(0);
}
void *libPvr_GetRenderSurface()
{
// No X11 display in Android
return(0);
}
void common_linux_setup();
void os_SetWindowText(char const *Text)
{
putinf(Text);
}
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_init(JNIEnv *env,jobject obj,jstring fileName)
{
// Set home directory to SD card
SetHomeDir("/sdcard/dc");
printf("Home dir is: '%s'\n",GetPath("/").c_str());
// Get filename string from Java
const char* P = fileName? env->GetStringUTFChars(fileName,0):0;
if(!P) CurFileName[0] = '\0';
else
{
printf("Got URI: '%s'\n",P);
strncpy(CurFileName,(strlen(P)>=7)&&!memcmp(P,"file://",7)? P+7:P,sizeof(CurFileName));
CurFileName[sizeof(CurFileName)-1] = '\0';
env->ReleaseStringUTFChars(fileName,P);
}
printf("Opening file: '%s'\n",CurFileName);
// Initialize platform-specific stuff
common_linux_setup();
// Set configuration
settings.profile.run_counts = 0;
/*
// Start native thread
pthread_attr_init(&PTAttr);
pthread_attr_setdetachstate(&PTAttr,PTHREAD_CREATE_DETACHED);
pthread_create(&PThread,&PTAttr,ThreadHandler,CurFileName);
pthread_attr_destroy(&PTAttr);
*/
ThreadHandler(CurFileName);
}
#define SAMPLE_COUNT 512
JNIEnv* jenv;
jshortArray jsamples;
jmethodID writemid;
jobject track;
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_run(JNIEnv *env,jobject obj,jobject trk)
{
install_prof_handler(0);
jenv=env;
track=trk;
jsamples=env->NewShortArray(SAMPLE_COUNT*2);
writemid=env->GetMethodID(env->GetObjectClass(track),"WriteBuffer","([SI)I");
dc_run();
}
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_stop(JNIEnv *env,jobject obj)
{
//dc_stop();
}
JNIEXPORT jint JNICALL Java_com_example_newdc_JNIdc_send(JNIEnv *env,jobject obj,jint cmd, jint param)
{
if (cmd==0)
{
if (param==0)
{
KillTex=true;
printf("Killing texture cache\n");
}
if (param==1)
{
settings.pvr.ta_skip^=1;
printf("settings.pvr.ta_skip: %d\n",settings.pvr.ta_skip);
}
if (param==2)
{
print_stats=true;
printf("Storing blocks ...\n");
}
}
else if (cmd==1)
{
if (param==0)
sample_Stop();
else
sample_Start(param);
}
else if (cmd==2)
{
}
}
JNIEXPORT jint JNICALL Java_com_example_newdc_JNIdc_data(JNIEnv *env,jobject obj,jint id, jbyteArray d)
{
if (id==1)
{
printf("Loading symtable (%p,%p,%p,%p)\n",env,obj,id,d);
int len=env->GetArrayLength(d);
u8* syms=(u8*)malloc(len);
printf("Loading symtable to %p, %d\n",syms,len);
env->GetByteArrayRegion(d,0,len,(jbyte*)syms);
sample_Syms(syms,len);
}
}
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_rendframe(JNIEnv *env,jobject obj)
{
while(!rend_single_frame()) ;
}
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_kcode(JNIEnv * env, jobject obj,u32 k_code, u32 l_t, u32 r_t, u32 jx, u32 jy)
{
lt[0] = l_t;
rt[0] = r_t;
kcode[0] = k_code;
kcode[3] = kcode[2] = kcode[1] = 0xFFFF;
joyx[0]=jx;
joyy[0]=jy;
}
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_rendinit(JNIEnv * env, jobject obj, jint w,jint h)
{
screen_width = w;
screen_height = h;
//gles_term();
egl_stealcntx();
if (!gles_init())
die("OPENGL FAILED");
install_prof_handler(1);
}
JNIEXPORT void JNICALL Java_com_example_newdc_JNIdc_vjoy(JNIEnv * env, jobject obj,u32 id,float x, float y, float w, float h)
{
if(id<sizeof(vjoy_pos)/sizeof(vjoy_pos[0]))
{
vjoy_pos[id][0] = x;
vjoy_pos[id][1] = y;
vjoy_pos[id][2] = w;
vjoy_pos[id][3] = h;
}
}
u32 os_Push(void* frame, u32 amt, bool wait)
{
verify(amt==SAMPLE_COUNT);
//yeah, do some audio piping magic here !
jenv->SetShortArrayRegion(jsamples,0,amt*2,(jshort*)frame);
return jenv->CallIntMethod(track,writemid,jsamples,wait);
}
bool os_IsAudioBuffered()
{
return jenv->CallIntMethod(track,writemid,jsamples,-1)==0;
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newdc"
android:versionCode="1"
android:versionName="1.0">
</manifest>
+92
View File
@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="libnewdc" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- if sdk.dir was not set from one of the property file, then
get it from the ANDROID_HOME env var.
This must be done before we load project.properties since
the proguard config can use sdk.dir -->
<property environment="env" />
<condition property="sdk.dir" value="${env.ANDROID_HOME}">
<isset property="env.ANDROID_HOME" />
</condition>
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
@@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
+15
View File
@@ -0,0 +1,15 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
android.library=true
# Project target.
target=android-15
@@ -0,0 +1,23 @@
package com.example.newdc;
import android.media.AudioTrack;
public class JNIdc
{
static { System.loadLibrary("dc"); }
public static native void init(String fileName);
public static native void run(Object track);
public static native void stop();
public static native int send(int cmd, int opt);
public static native int data(int cmd, byte[] data);
public static native void rendinit(int w,int y);
public static native void rendframe();
public static native void kcode(int kcode,int lt, int rt, int jx, int jy);
public static native void vjoy(int id,float x, float y, float w, float h);
//public static native int play(short result[],int size);
}
+177
View File
@@ -0,0 +1,177 @@
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
extern "C" {
#include "deps/libpng/png.h"
}
#include "types.h"
#include "deps/libzip/zip.h"
#define TEXTURE_LOAD_ERROR 0
//Taken from http://en.wikibooks.org/wiki/OpenGL_Programming/Intermediate/Textures
/** loadTexture
* loads a png file into an opengl texture object, using cstdio , libpng, and opengl.
*
* \param filename : the png file to be loaded
* \param width : width of png, to be updated as a side effect of this function
* \param height : height of png, to be updated as a side effect of this function
*
* \return GLuint : an opengl texture id. Will be 0 if there is a major error,
* should be validated by the client of this function.
*
*/
zip_file* file;
zip* APKArchive;
void setAPK (const char* apkPath) {
LOGI("Loading APK %s", apkPath);
APKArchive = zip_open(apkPath, 0, NULL);
if (APKArchive == NULL) {
LOGE("Error loading APK");
return;
}
//Just for debug, print APK contents
int numFiles = zip_get_num_files(APKArchive);
for (int i=0; i<numFiles; i++) {
const char* name = zip_get_name(APKArchive, i, 0);
if (name == NULL) {
LOGE("Error reading zip file name at index %i : %s", zip_strerror(APKArchive));
return;
}
LOGI("File %i : %s\n", i, name);
}
}
void png_zip_read(png_structp png_ptr, png_bytep data, png_size_t length) {
zip_fread(file, data, length);
}
GLuint loadTextureFromPNG(const char* filename, int &width, int &height) {
file = zip_fopen(APKArchive, filename, 0);
if (!file) {
LOGE("Error opening %s from APK", filename);
return TEXTURE_LOAD_ERROR;
}
//header for testing if it is a png
png_byte header[8];
//read the header
zip_fread(file, header, 8);
//test if png
int is_png = !png_sig_cmp(header, 0, 8);
if (!is_png) {
zip_fclose(file);
LOGE("Not a png file : %s", filename);
return TEXTURE_LOAD_ERROR;
}
//create png struct
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,
NULL, NULL);
if (!png_ptr) {
zip_fclose(file);
LOGE("Unable to create png struct : %s", filename);
return (TEXTURE_LOAD_ERROR);
}
//create png info struct
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
LOGE("Unable to create png info : %s", filename);
zip_fclose(file);
return (TEXTURE_LOAD_ERROR);
}
//create png info struct
png_infop end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
LOGE("Unable to create png end info : %s", filename);
zip_fclose(file);
return (TEXTURE_LOAD_ERROR);
}
//png error stuff, not sure libpng man suggests this.
if (setjmp(png_jmpbuf(png_ptr))) {
zip_fclose(file);
LOGE("Error during setjmp : %s", filename);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
return (TEXTURE_LOAD_ERROR);
}
//init png reading
//png_init_io(png_ptr, fp);
png_set_read_fn(png_ptr, NULL, png_zip_read);
//let libpng know you already read the first 8 bytes
png_set_sig_bytes(png_ptr, 8);
// read all the info up to the image data
png_read_info(png_ptr, info_ptr);
//variables to pass to get info
int bit_depth, color_type;
png_uint_32 twidth, theight;
// get info about png
png_get_IHDR(png_ptr, info_ptr, &twidth, &theight, &bit_depth, &color_type,
NULL, NULL, NULL);
//update width and height based on png info
width = twidth;
height = theight;
// Update the png info struct.
png_read_update_info(png_ptr, info_ptr);
// Row size in bytes.
int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
// Allocate the image_data as a big block, to be given to opengl
png_byte *image_data = new png_byte[rowbytes * height];
if (!image_data) {
//clean up memory and close stuff
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
LOGE("Unable to allocate image_data while loading %s ", filename);
zip_fclose(file);
return TEXTURE_LOAD_ERROR;
}
//row_pointers is for pointing to image_data for reading the png with libpng
png_bytep *row_pointers = new png_bytep[height];
if (!row_pointers) {
//clean up memory and close stuff
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
delete[] image_data;
LOGE("Unable to allocate row_pointer while loading %s ", filename);
zip_fclose(file);
return TEXTURE_LOAD_ERROR;
}
// set the individual row_pointers to point at the correct offsets of image_data
for (int i = 0; i < height; ++i)
row_pointers[height - 1 - i] = image_data + i * rowbytes;
//read the png into image_data through row_pointers
png_read_image(png_ptr, row_pointers);
//Now generate the OpenGL texture object
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, (GLvoid*) image_data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//clean up memory and close stuff
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
delete[] image_data;
delete[] row_pointers;
zip_fclose(file);
return texture;
}
+8
View File
@@ -0,0 +1,8 @@
#ifndef UTILS_H_
#define UTILS_H_
void setAPK (const char* apkPath);
//Filename will be looked up in the apk (should start with assets/ or res/
GLuint loadTextureFromPNG (const char* filename, int &width, int &height);
#endif /* UTILS_H_ */
+83
View File
@@ -0,0 +1,83 @@
/*
* E_Branches.h
*
*/
#pragma once
namespace ARM
{
EAPI B(u32 sImm24, ConditionCode CC=AL)
{
DECL_Id(0x0A000000);
SET_CC;
I |= ((sImm24>>2)&0xFFFFFF);
EMIT_I;
}
EAPI BL(u32 sImm24, ConditionCode CC=AL)
{
DECL_Id(0x0B000000);
SET_CC;
I |= ((sImm24>>2)&0xFFFFFF);
EMIT_I;
}
// Note: Either X variant will switch to THUMB* if bit0 of addr is 1
//
EAPI BX(eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x012FFF10);
SET_CC;
I |= (Rm&15);
EMIT_I;
}
EAPI BLX(eReg Rm, ConditionCode CC=AL) // Form II
{
DECL_Id(0x012FFF30);
SET_CC;
I |= (Rm&15);
EMIT_I;
}
EAPI BXJ(eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x012FFF20);
SET_CC;
I |= (Rm&15);
EMIT_I;
}
// This encoding looks correct, but segfaults, the pc val is align(pc,4) but this should be right in ARM
//
#if defined(_DEVEL)
EAPI BLX(u32 sImm24) // Form I * H is derived so not needed, fixup sImm24 so one can just pass a real addr
{
DECL_Id(0xFA000000);
//if(sImm24&1)
// I |= 1<<24; // SET_H
I |= ((sImm24>>2)&0xFFFFFF);
EMIT_I;
}
#endif
};
+640
View File
@@ -0,0 +1,640 @@
/*
* <E_DataOp.h Title="ARMv7 ISA Emitter Middle-ware: Data-Processing Instructions" />
*
* <?CTYPE
*
* <opcode1>{<cond>}{S} <Rd>, <shifter_operand>
* <opcode1> := MOV | MVN
*
* <opcode2>{<cond>} <Rn>, <shifter_operand>
* <opcode2> := CMP | CMN | TST | TEQ
*
* <opcode3>{<cond>}{S} <Rd>, <Rn>, <shifter_operand>
* <opcode3> := ADD | SUB | RSB | ADC | SBC | RSC | AND | BIC | EOR | ORR
*
* ?/>
*/
#pragma once
namespace ARM
{
/*
* imm Rd,[Rn,] imm
* reg Rd,Rn,Rm shift
* rsr Rd,Rn,Rm type Rs
*
* sp.imm Rd {SP} imm
* sp.reg Rd {SP} Rm shift
*
*/
#if 0
#define dpInstr(iName, iId) \
EAPI iName (eReg Rd, eReg Rn, u32 Imm) ; \
EAPI iName (eReg Rd, eReg Rn, eReg Rm, eShiftOp type=S_LSL, u32 Imm=0) ; \
EAPI iName (eReg Rd, eReg Rn, eReg Rm, eShiftOp type, eReg Rs) ;
#endif
/*
ADC IMM 0x02A00000
ADC REG 0x00A00000
ADC RSR 0x00A00010
ADD IMM 0x02800000
ADD REG 0x00800000
ADD RSR 0x00800010
ADD.SP.IMM 0x028D0000
ADD.SP.REG 0x008D0000
AND IMM 0x02000000
AND REG 0x00000000
AND RSR 0x00000010
// ASR's do not fit this pattern moved elsewhere //
BIC IMM 0x03C00000
BIC REG 0x01C00000
BIC RSR 0x01C00010
CMN IMM 0x03700000 // N imm
CMN REG 0x01700000 // NMshift
CMN RSR 0x01700010 // NMtypeS
CMP IMM 0x03500000 // N imm
CMP REG 0x01500000
CMP RSR 0x01500010
EOR IMM 0x02200000
EOR REG 0x00200000
EOR REG 0x00200010
*/
#define DP_PARAMS (eReg Rd, eReg Rn, ShiftOp Shift, ConditionCode CC=AL)
#define DP_RPARAMS (eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
#define DP_COMMON \
DECL_I; \
\
SET_CC; \
I |= (Rn&15)<<16; \
I |= (Rd&15)<<12; \
I |= (Shift&0xFFF)
#define DP_RCOMMON \
DECL_I; \
\
SET_CC; \
I |= (Rn&15)<<16; \
I |= (Rd&15)<<12; \
I |= (Rm&15)
#define DP_OPCODE(opcode) \
I |= (opcode)<<21
EAPI AND DP_PARAMS { DP_COMMON; DP_OPCODE(DP_AND); EMIT_I; }
EAPI EOR DP_PARAMS { DP_COMMON; DP_OPCODE(DP_EOR); EMIT_I; }
EAPI SUB DP_PARAMS { DP_COMMON; DP_OPCODE(DP_SUB); EMIT_I; }
EAPI RSB DP_PARAMS { DP_COMMON; DP_OPCODE(DP_RSB); EMIT_I; }
EAPI ADD DP_PARAMS { DP_COMMON; DP_OPCODE(DP_ADD); EMIT_I; }
EAPI ADC DP_PARAMS { DP_COMMON; DP_OPCODE(DP_ADC); EMIT_I; }
EAPI SBC DP_PARAMS { DP_COMMON; DP_OPCODE(DP_SBC); EMIT_I; }
EAPI RSC DP_PARAMS { DP_COMMON; DP_OPCODE(DP_RSC); EMIT_I; }
EAPI TST DP_PARAMS { DP_COMMON; DP_OPCODE(DP_TST); EMIT_I; }
EAPI TEQ DP_PARAMS { DP_COMMON; DP_OPCODE(DP_TEQ); EMIT_I; }
EAPI CMP DP_PARAMS { DP_COMMON; DP_OPCODE(DP_CMP); EMIT_I; }
EAPI CMN DP_PARAMS { DP_COMMON; DP_OPCODE(DP_CMN); EMIT_I; }
EAPI ORR DP_PARAMS { DP_COMMON; DP_OPCODE(DP_ORR); EMIT_I; }
EAPI MOV DP_PARAMS { DP_COMMON; DP_OPCODE(DP_MOV); EMIT_I; }
EAPI BIC DP_PARAMS { DP_COMMON; DP_OPCODE(DP_BIC); EMIT_I; }
EAPI MVN DP_PARAMS { DP_COMMON; DP_OPCODE(DP_MVN); EMIT_I; }
#if defined(_DEVEL) && defined(_NODEF_) // These require testing -> CMP/MOV Shifter(Reg)? fmt broken? // Simple third reg type w/ no shifter
EAPI AND DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_AND); EMIT_I; }
EAPI EOR DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_EOR); EMIT_I; }
EAPI SUB DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_SUB); EMIT_I; }
EAPI RSB DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_RSB); EMIT_I; }
EAPI ADD DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_ADD); EMIT_I; }
EAPI ADC DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_ADC); EMIT_I; }
EAPI SBC DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_SBC); EMIT_I; }
EAPI RSC DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_RSC); EMIT_I; }
EAPI TST DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_TST); EMIT_I; }
EAPI TEQ DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_TEQ); EMIT_I; }
EAPI CMP DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_CMP); EMIT_I; }
EAPI CMN DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_CMN); EMIT_I; }
EAPI ORR DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_ORR); EMIT_I; }
EAPI MOV DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_MOV); EMIT_I; }
EAPI BIC DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_BIC); EMIT_I; }
EAPI MVN DP_PARAMS { DP_RCOMMON; DP_OPCODE(DP_MVN); EMIT_I; }
#endif
static u32 ARMImmid8r4_enc(u32 imm32)
{
for (int i=0;i<=30;i+=2)
{
u32 immv=(imm32<<i) | (imm32>>(32-i));
if (immv<256)
{
return ((i/2)<<8) | immv;
}
}
return -1;
}
static u32 ARMImmid8r4(u32 imm8r4)
{
u32 rv = ARMImmid8r4_enc(imm8r4);
verify(rv!=-1);
return rv;
}
static bool is_i8r4(u32 i32) { return ARMImmid8r4_enc(i32) != -1; }
EAPI ADD(eReg Rd, eReg Rn, eReg Rm, u32 RmLSL, bool S, ConditionCode CC=AL)
{
DECL_Id(0x00800000);
if (S)
I |= 1<<20;
I |= (RmLSL&31)<<7;
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI ADD(eReg Rd, eReg Rn, eReg Rm, bool S, ConditionCode CC=AL)
{
ADD(Rd,Rn,Rm,0,S,CC);
}
EAPI ADD(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
ADD(Rd,Rn,Rm,false,CC);
}
EAPI ADD(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x02800000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI ADC(eReg Rd, eReg Rn, eReg Rm, bool S, ConditionCode CC=AL)
{
DECL_Id(0x00A00000);
if (S)
I |= 1<<20;
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI ADC(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
ADC(Rd,Rn,Rm,false,CC);
}
EAPI ADC(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x02A00000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI ADR(eReg Rd, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x028F0000);
SET_CC;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI ADR_Zero(eReg Rd, s32 Imm8, ConditionCode CC=AL) // Special case for subtraction of 0
{
DECL_Id(0x024F0000);
SET_CC;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI ORR(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01800000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI ORR(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x03800000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI AND(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x00000000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI AND(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x02000000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI EOR(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x00200000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI EOR(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x02200000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI SUB(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x00400000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SUB(eReg Rd, eReg Rn, s32 Imm8, bool S, ConditionCode CC=AL)
{
DECL_Id(0x02400000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
if (S)
I |= 1<<20;
EMIT_I;
}
EAPI SUB(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL) { SUB(Rd,Rn,Imm8,false,CC); }
EAPI RSB(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x00600000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI RSB(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x02600000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI MVN(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01E00000);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI MVN(eReg Rd, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x03E00000);
SET_CC;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI TST(eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01100000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rm&15);
EMIT_I;
}
EAPI TST(eReg Rn, u32 Imm12, ConditionCode CC=AL)
{
DECL_Id(0x03100000);
SET_CC;
I |= (Rn&15)<<16;
I |= ARMImmid8r4(Imm12);
EMIT_I;
}
EAPI BIC(eReg Rd, eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x03C00000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= ARMImmid8r4(Imm8); // * 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
/*
*
*/
EAPI UBFX(eReg Rd, eReg Rm, u8 lsb, u8 width, ConditionCode CC=AL)
{
DECL_Id(0x07E00050);
verify(lsb+width<=32);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
I |= (lsb&31)<<7;
I |= ((width-1)&31)<<16;
EMIT_I;
}
EAPI MOV(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01A00000);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI MOVW(eReg Rd, u32 Imm16, ConditionCode CC=AL)
{
DECL_Id(0x03000000);
SET_CC;
I |= (Imm16&0xF000)<<4;
I |= (Rd&15)<<12;
I |= (Imm16&0x0FFF);
EMIT_I;
}
EAPI MOVT(eReg Rd, u32 Imm16, ConditionCode CC=AL)
{
DECL_Id(0x03400000);
SET_CC;
I |= (Imm16&0xF000)<<4;
I |= (Rd&15)<<12;
I |= (Imm16&0x0FFF);
EMIT_I;
}
EAPI CMP(eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01500000);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rm&15);
EMIT_I;
}
EAPI CMP(eReg Rn, s32 Imm8, ConditionCode CC=AL)
{
DECL_Id(0x03500000);
SET_CC;
I |= (Rn&15)<<16;
I |= ARMImmid8r4(Imm8); // *FIXME* 12b imm is 8b imm 4b rot. spec, add rot support!
EMIT_I;
}
EAPI LSL(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01A00010);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<8;
I |= (Rn&15)<<0;
EMIT_I;
}
EAPI LSL(eReg Rd, eReg Rm, s32 imm5, ConditionCode CC=AL)
{
DECL_Id(0x01A00000);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<0;
I |= (imm5&31)<<7;
EMIT_I;
}
EAPI LSR(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01A00030);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<8;
I |= (Rn&15)<<0;
EMIT_I;
}
EAPI RRX(eReg Rd, eReg Rm,bool S=false, ConditionCode CC=AL)
{
DECL_Id(0x01A00060);
if (S)
I |= 1<<20;
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<0;
EMIT_I;
}
EAPI LSR(eReg Rd, eReg Rm, s32 imm5, bool S, ConditionCode CC=AL)
{
DECL_Id(0x01A00020);
if (S)
I |= 1<<20;
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<0;
I |= (imm5&31)<<7;
EMIT_I;
}
EAPI LSR(eReg Rd, eReg Rm, s32 imm5, ConditionCode CC=AL)
{
LSR(Rd,Rm,imm5,false,CC);
}
EAPI ASR(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01A00050);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<8;
I |= (Rn&15)<<0;
EMIT_I;
}
EAPI ASR(eReg Rd, eReg Rm, s32 imm5, ConditionCode CC=AL)
{
DECL_Id(0x01A00040);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<0;
I |= (imm5&31)<<7;
EMIT_I;
}
EAPI ROR(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01A00070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<8;
I |= (Rn&15)<<0;
EMIT_I;
}
EAPI ROR(eReg Rd, eReg Rm, s32 imm5, ConditionCode CC=AL)
{
DECL_Id(0x01A00060);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15)<<0;
I |= (imm5&31)<<7;
EMIT_I;
}
#undef DP_PARAMS
#undef DP_RPARAMS
#undef DP_COMMON
#undef DP_RCOMMON
#undef DP_OPCODE
};
+151
View File
@@ -0,0 +1,151 @@
/*
* E_Extend.h
*
There are six basic instructions:
XTAB16 Extend bits[23:16] and bits[7:0] of one register to 16 bits, and add corresponding halfwordsto the values in another register.
XTAB Extend bits[ 7: 0] of one register to 32 bits, and add to the value in another register.
XTAH Extend bits[15: 0] of one register to 32 bits, and add to the value in another register.
XTB16 Extend bits[23:16] and bits[7:0] to 16 bits each.
XTB Extend bits[ 7: 0] to 32 bits.
XTH Extend bits[15: 0] to 32 bits.
Each of the six instructions is available in the following variations, indicated by the prefixes shown:
S Sign extension, with or without addition modulo 216 or 232.
U Zero (unsigned) extension, with or without addition modulo 216 or 232.
*/
#pragma once
namespace ARM
{
EAPI SXTAB16(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06800070);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SXTAB(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06A00070);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SXTAH(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06B00070);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SXTB16(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x068F0070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SXTB(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06AF0070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SXTH(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06BF0070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI UXTAB16(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06C00070);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI UXTAB(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06E00070);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI UXTAH(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06F00070);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI UXTB16(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06CF0070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI UXTB(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06EF0070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI UXTH(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06FF0070);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
};
+310
View File
@@ -0,0 +1,310 @@
/*
* E_LoadStore.h
*
* LDR|STR{<cond>}{B}{T} Rd, <addressing_mode>
*
*/
#pragma once
namespace ARM
{
enum AddrMode {
Offset, // [Rn, offset] - Base:Offset used for access, no writeback
PostIndexed, // [Rn, offset] ! - Base:Offset used for access, written back to Base reg.
PreIndexed // [Rn],offset - Base used then Base:Offset written back to Base reg.
// offset: imm{8,12}, Rm, Rm <Shifter> #Shift
};
#define SET_Rn I |= (Rn&15)<<16
#define SET_Rt I |= (Rt&15)<<12
#define SET_Rm I |= (Rm&15)
#define SET_Rtn SET_Rt; SET_Rn
#define SET_Rtnm SET_Rt; SET_Rn; SET_Rm
#define SET_I I |= (1<<25) // Sets Register (Rather than Immediate) Addressing
#define SET_P I |= (1<<24) // If NOT Set: post-indexed, else offset||pre-indexed (W. determines which)
#define SET_U I |= (1<<23) // If SET: Offset is added to base, else its subtracted (Sign of sImm12)
#define SET_B I |= (1<<22) // If SET: Access is a byte access, else its a word access.
#define SET_W I |= (1<<21) // (P==0) [ W==0: reg. post indexed, W==1: Unprivileged T variant ] (P==1) [ W==0: Offset , W==1: Pre-indexed ]
#define SET_L I |= (1<<20) // (L==1) Load / Store
#define SET_AddrMode \
if(mode==Offset) { SET_P; } \
else if(mode==PreIndexed) { SET_P; SET_W; }
/*
#define SET_AddrMode \
\
switch(mode) { \
case PostIndexed: break; \
case Offset: SET_P; break; \
case PreIndexed: SET_P; SET_W; break; \
}
*/
#define SET_sImm12 \
\
if (0 != sImm12) { \
if (sImm12 > 0) { SET_U; } \
I |= (abs(sImm12) &0xFFF); \
}
#define SET_sImm8 \
\
if(0 != sImm8) { \
verify(is_s8(sImm8)); \
if(sImm8 > 0) { SET_U; } \
sImm8 = abs(sImm8); \
I |= ((u32)sImm8 &0x0F); \
I |= ((u32)sImm8 &0xF0)<<4; \
}
#define SET_Imm5 I |= ((Imm5&0x1F)<<7)
#define SET_type I |= ((type&3)<<5)
/* - Load/Store Encoding
--------------------------------------------------------------------------------------
cond 01-IPUBWL Rn Rt addr_mode -- Load/Store Word || Unsigned Byte
I,P,U,W - Specify type of addressing mode
L - Specify Load (L==1), else Store
B - Specify Byte (B==1), else Word
--------------------------------------------------------------------------------------
cond 000-PUIWL Rn Rt addr_mode 1SH1 addr_mode -- Load/Store Halfword || Signed byte
I,P,U,W - Specify type of addressing mode
L - Specify Load (L==1), else Store
S - Specify signed (S==1), else unsigned access
H - Specify Halfword access, else signed byte
--------------------------------------------------------------------------------------
cond 010-PUBWL Rn Rt sImm12-iiii-iiii Imm Offset
cond 011-PUBWL Rn Rt #sft sft_op 0 Rm Reg Offset
cond 000 PU1WL Rn Rt imHI 1011 imLO Imm Offset - halfword
cond 000 PU0WL Rn Rt SBZ 1011 Rm Reg Offset - halfword
cond 000 PU1W1 Rn Rt imHI 11H1 imLO Imm Offset - signed halfword/byte
cond 000 PU0W1 Rn Rt SBZ 11H1 Rm Reg Offset - signed halfword/byte
cond 000 PU1W0 Rn Rt imHI 11S1 imLO Imm Offset - two words
cond 000 PU0W0 Rn Rt SBZ 11S1 Rm Reg Offset - two words
cond 100-PUSWL Rn Register-list Multiple
cond 110-PUNWL Rn CRd cp_num offs8 COP & double reg xfer
cond 0001 0B00 Rn Rt SBZ 1001 Rm Swap [byte]
--------------------------------------------------------------------------------------
LDR L 010 1U001 11 Rt imm12 - *no literal stores*
LDR I 010 PU0W1 Rn Rt imm12 - STR I 010 PU0W0 Rn Rt imm12
LDR R 011 PU0W1 Rn Rt imm5 type 0 Rm - STR R 011 PU0W0 Rn Rt imm5 type 0 Rm
LDRT I 010 0U011 Rn Rt imm12 - STRT I 010 0U010 Rn Rt imm12
LDRT R 011 0U011 Rn Rt imm5 type 0 Rm - STRT R 011 0U010 Rn Rt imm5 type 0 Rm
LDRB L 010 1U101 11 Rt imm12 - *^^
LDRB I 010 PU1W1 Rn Rt imm12 - STRB I 010 PU1W0 Rn Rt imm12
LDRB R 011 PU1W1 Rn Rt imm5 type 0 Rm - STRB R 011 PU1W0 Rn Rt imm5 type 0 Rm
LDRBT I
LDRBT R
--------------------------------------------------------------------------------------
LDRH L 000 1U101 11 Rt imm4H 1011 imm4L - *^^
LDRH I 000 PU1W1 Rn Rt imm4H 1011 imm4L - STRH I 000 PU1W0 Rn Rt imm4H 1011 imm4L
LDRH R 000 PU0W1 Rn Rt 0000 1011 Rm - STRH R 000 PU0W0 Rn Rt 0000 1011 Rm
LDRD L 000 1U100 11 Rt imm4H 1101 imm4L - *^^
LDRD I 000 PU1W0 Rn Rt imm4H 1101 imm4L - STRD I 000 PU1W0 Rn Rt imm4H 1111 imm4L
LDRD R 000 PU0W0 Rn Rt 0000 1101 Rm - STRD R 000 PU0W0 Rn Rt 0000 1111 Rm
--------------------------------------------------------------------------------------
LDRHT/STRHT
LDREX/STREX
LDREXB/STREXB
LDREXH/STREXH
LDREXD/STREXD
--------------------------------------------------------------------------------------
EAPI LDR 0x04100000 // These were all the A1 Versions for Imm IIRC
EAPI LDRB 0x04500000
EAPI LDRBT 0x06700000
EAPI LDRD 0x00000000
EAPI LDREX 0x01900090
EAPI LDRH 0x00100090
EAPI LDRSB 0x00100000
EAPI LDRSH 0x00100000
EAPI LDRT 0x04300000
EAPI STR 0x04000000
EAPI STRB 0x04400000
EAPI STRBT 0x06600000
EAPI STRD 0x00000000
EAPI STREX 0x01800090
EAPI STRH 0x00000090
EAPI STRT 0x04200000
*/
extern u8* emit_opt;
extern eReg reg_addr;
extern eReg reg_dst;
extern s32 imma;
EAPI LDR (eReg Rt, eReg Rn, s32 sImm12=0, AddrMode mode=Offset, ConditionCode CC=AL)
{
if (emit_opt+4==(u8*)EMIT_GET_PTR() && reg_addr==Rn && imma==sImm12)
{
if (reg_dst!=Rt)
MOV(Rt,reg_dst);
}
else
{
DECL_Id(0x04100000); SET_CC; SET_Rtn; SET_AddrMode; SET_sImm12; EMIT_I;
}
}
EAPI STR (eReg Rt, eReg Rn, s32 sImm12=0, AddrMode mode=Offset, ConditionCode CC=AL)
{
emit_opt=0;//(u8*)EMIT_GET_PTR();
reg_addr=Rn;
reg_dst=Rt;
imma=sImm12;
DECL_Id(0x04000000); SET_CC; SET_Rtn; SET_AddrMode; SET_sImm12; EMIT_I;
}
EAPI LDRB(eReg Rt, eReg Rn, s32 sImm12=0, AddrMode mode=Offset, ConditionCode CC=AL) { DECL_Id(0x04500000); SET_CC; SET_Rtn; SET_AddrMode; SET_sImm12; SET_B; EMIT_I; } // Prob don't need SET_B, in iID
EAPI STRB(eReg Rt, eReg Rn, s32 sImm12=0, AddrMode mode=Offset, ConditionCode CC=AL) { DECL_Id(0x04400000); SET_CC; SET_Rtn; SET_AddrMode; SET_sImm12; SET_B; EMIT_I; } // Prob don't need SET_B, in iID
EAPI LDRT (eReg Rt, eReg Rn, s32 sImm12=0, ConditionCode CC=AL) { DECL_Id(0x04300000); SET_CC; SET_Rtn; SET_sImm12; EMIT_I; }
EAPI STRT (eReg Rt, eReg Rn, s32 sImm12=0, ConditionCode CC=AL) { DECL_Id(0x04200000); SET_CC; SET_Rtn; SET_sImm12; EMIT_I; }
EAPI LDRBT(eReg Rt, eReg Rn, s32 sImm12=0, ConditionCode CC=AL) { DECL_Id(0x04700000); SET_CC; SET_Rtn; SET_sImm12; SET_B; EMIT_I; } // Prob don't need SET_B, in iID
EAPI STRBT(eReg Rt, eReg Rn, s32 sImm12=0, ConditionCode CC=AL) { DECL_Id(0x04600000); SET_CC; SET_Rtn; SET_sImm12; SET_B; EMIT_I; } // Prob don't need SET_B, in iID
// LDR(r1,r2,r3, Offset, true, L_LSL, 5, EQ); ... LDR r1, r2, +r3 LSL #5
EAPI LDR (eReg Rt, eReg Rn, eReg Rm, AddrMode mode=Offset, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06100000); SET_CC; SET_Rtnm; SET_AddrMode; SET_Imm5; SET_type; if(Add){ SET_U; } EMIT_I; }
EAPI STR (eReg Rt, eReg Rn, eReg Rm, AddrMode mode=Offset, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06000000); SET_CC; SET_Rtnm; SET_AddrMode; SET_Imm5; SET_type; if(Add){ SET_U; } EMIT_I; }
EAPI LDRB(eReg Rt, eReg Rn, eReg Rm, AddrMode mode=Offset, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06500000); SET_CC; SET_Rtnm; SET_AddrMode; SET_Imm5; SET_type; if(Add){ SET_U; } SET_B; EMIT_I; } // Prob don't need SET_B, in iID
EAPI STRB(eReg Rt, eReg Rn, eReg Rm, AddrMode mode=Offset, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06400000); SET_CC; SET_Rtnm; SET_AddrMode; SET_Imm5; SET_type; if(Add){ SET_U; } SET_B; EMIT_I; } // Prob don't need SET_B, in iID
EAPI LDRT (eReg Rt, eReg Rn, eReg Rm, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06300000); SET_CC; SET_Rtnm; SET_Imm5; SET_type; if(Add){ SET_U; } EMIT_I; }
EAPI STRT (eReg Rt, eReg Rn, eReg Rm, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06200000); SET_CC; SET_Rtnm; SET_Imm5; SET_type; if(Add){ SET_U; } EMIT_I; }
EAPI LDRBT(eReg Rt, eReg Rn, eReg Rm, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06700000); SET_CC; SET_Rtnm; SET_Imm5; SET_type; if(Add){ SET_U; } SET_B; EMIT_I; } // Prob don't need SET_B, in iID
EAPI STRBT(eReg Rt, eReg Rn, eReg Rm, bool Add=false, ShiftOp type=S_LSL, u32 Imm5=0, ConditionCode CC=AL) { DECL_Id(0x06600000); SET_CC; SET_Rtnm; SET_Imm5; SET_type; if(Add){ SET_U; } SET_B; EMIT_I; } // Prob don't need SET_B, in iID
// LDR Rt,[PC, #(s:+/-)Imm12] *Special Case - Literal / PC Relative
EAPI LDR(eReg Rt, s32 sImm12, ConditionCode CC=AL) {
DECL_Id(0x051F0000); SET_CC; SET_Rt; SET_sImm12; EMIT_I;
}
// LDRB Rt,[PC, #(s:+/-)Imm12] *Special Case - Literal / PC Relative
EAPI LDRB(eReg Rt, s32 sImm12, ConditionCode CC=AL) {
DECL_Id(0x055F0000); SET_CC; SET_Rt; SET_sImm12; EMIT_I;
}
// Note: Following support Post-Indexed addressing only //
EAPI LDRH(eReg Rt, eReg Rn, s32 sImm8, ConditionCode CC=AL) { DECL_Id(0x005000B0); SET_CC; SET_Rtn; SET_P; SET_sImm8; EMIT_I; }
EAPI STRH(eReg Rt, eReg Rn, s32 sImm8, ConditionCode CC=AL) { DECL_Id(0x004000B0); SET_CC; SET_Rtn; SET_P; SET_sImm8; EMIT_I; }
EAPI LDRD(eReg Rt, eReg Rn, s32 sImm8, ConditionCode CC=AL) { DECL_Id(0x004000D0); SET_CC; SET_Rtn; SET_P; SET_sImm8; EMIT_I; }
EAPI STRD(eReg Rt, eReg Rn, s32 sImm8, ConditionCode CC=AL) { DECL_Id(0x004000F0); SET_CC; SET_Rtn; SET_P; SET_sImm8; EMIT_I; }
EAPI LDRH(eReg Rt, eReg Rn, eReg Rm, bool Add=true,ConditionCode CC=AL) { DECL_Id(0x001000B0); SET_CC; SET_Rtnm; SET_P; if (Add) {SET_U;} EMIT_I; }
EAPI STRH(eReg Rt, eReg Rn, eReg Rm, bool Add=true,ConditionCode CC=AL) { DECL_Id(0x000000B0); SET_CC; SET_Rtnm; SET_P; if (Add) {SET_U;} EMIT_I; }
EAPI LDRD(eReg Rt, eReg Rn, eReg Rm, bool Add=true, ConditionCode CC=AL) { DECL_Id(0x000000D0); SET_CC; SET_Rtnm; SET_P; if (Add) {SET_U;} EMIT_I; }
EAPI STRD(eReg Rt, eReg Rn, eReg Rm, bool Add=true, ConditionCode CC=AL) { DECL_Id(0x000000F0); SET_CC; SET_Rtnm; SET_P; if (Add) {SET_U;} EMIT_I; }
EAPI LDRSB(eReg Rt, eReg Rn, eReg Rm, bool Add=true,ConditionCode CC=AL) { DECL_Id(0x001000D0); SET_CC; SET_Rtnm; SET_P; if (Add) {SET_U;} EMIT_I; }
EAPI LDRSH(eReg Rt, eReg Rn, eReg Rm, bool Add=true,ConditionCode CC=AL) { DECL_Id(0x001000F0); SET_CC; SET_Rtnm; SET_P; if (Add) {SET_U;} EMIT_I; }
EAPI LDRH(eReg Rt, s32 sImm8, ConditionCode CC=AL) { DECL_Id(0x015F00B0); SET_CC; SET_Rt; SET_sImm8; EMIT_I; } // *Special Case - Literal / PC Relative
EAPI STRH(eReg Rt, s32 sImm8, ConditionCode CC=AL) { DECL_Id(0x014F00D0); SET_CC; SET_Rt; SET_sImm8; EMIT_I; } // *Special Case - Literal / PC Relative
// TODO: {LD,ST}R{SB,EX*} && friends (If required).
// Must use _Reg format
EAPI PUSH(u32 RegList, ConditionCode CC=AL)
{
DECL_Id(0x092D0000);
SET_CC;
I |= (RegList&0xFFFF);
EMIT_I;
}
EAPI POP(u32 RegList, ConditionCode CC=AL)
{
DECL_Id(0x08BD0000);
SET_CC;
I |= (RegList&0xFFFF);
EMIT_I;
}
#undef SET_Rtn
#undef SET_Rtnm
#undef SET_Rn
#undef SET_Rt
#undef SET_Rm
#undef SET_I
#undef SET_P
#undef SET_U
#undef SET_B
#undef SET_W
#undef SET_L
#undef SET_AddrMode
#undef SET_sImm12
#undef SET_sImm8
#undef SET_Imm5
#undef SET_type
};
+208
View File
@@ -0,0 +1,208 @@
/*
* E_Misc.h
*
*/
#pragma once
namespace ARM
{
/*
* Misc. Arithmetic Instructions
*/
// Count Leading Zero's
//
EAPI CLZ(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x016F0F10);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
// Unsigned sum of absolute differences
//
EAPI USAD8(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL)
{
DECL_Id(0x0780F010);
SET_CC;
I |= (Rd&15)<<16;
I |= (Rs&15)<<8;
I |= (Rm&15);
EMIT_I;
}
EAPI USADA8(eReg Rd, eReg Rm, eReg Rs, eReg Rn, ConditionCode CC=AL)
{
DECL_Id(0x07800010);
SET_CC;
I |= (Rd&15)<<16;
I |= (Rn&15)<<12;
I |= (Rs&15)<<8;
I |= (Rm&15);
EMIT_I;
}
/*
* Packing Instructions
*/
EAPI PKHBT(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL) // * shift_imm
{
DECL_Id(0x06800010);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI PKHTB(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL) // * shift_imm
{
DECL_Id(0x06800050);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
/*
* Swapping Instructions
*/
EAPI REV(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06BF0F30);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI REV16(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06BF0FB0);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI REVSH(eReg Rd, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06FF0F30);
SET_CC;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
EAPI SEL(eReg Rd, eReg Rn, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06800FB0);
SET_CC;
I |= (Rn&15)<<16;
I |= (Rd&15)<<12;
I |= (Rm&15);
EMIT_I;
}
/*
* Saturate Instructions
*/
// SSAT{<cond>} <Rd>, #<immed>, <Rm>{, <shift>}
//
EAPI SSAT(eReg Rd, u32 sat_imm, eReg Rm, u32 sft_imm, ConditionCode CC=AL) // sh&1 << 6
{
DECL_Id(0x06A00010);
SET_CC;
I |= (sat_imm&31)<<16;
I |= (Rd&15)<<12;
I |= (sft_imm&31)<<7;
I |= (Rm&15);
EMIT_I;
}
// SSAT16{<cond>} <Rd>, #<immed>, <Rm>
//
EAPI SSAT16(eReg Rd, u32 sat_imm, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06A00030);
SET_CC;
I |= (sat_imm&15)<<16;
I |= (Rd&15)<<12;
I |= 15<<8; // * SBO
I |= (Rm&15);
EMIT_I;
}
// USAT{<cond>} <Rd>, #<immed>, <Rm>{, <shift>}
//
EAPI USAT(eReg Rd, u32 sat_imm, eReg Rm, u32 sft_imm, ConditionCode CC=AL)
{
DECL_Id(0x06E00010);
SET_CC;
I |= (sat_imm&31)<<16;
I |= (Rd&15)<<12;
I |= (sft_imm&31)<<7;
I |= (Rm&15);
EMIT_I;
}
// USAT16{<cond>} <Rd>, #<immed>, <Rm>
//
EAPI USAT16(eReg Rd, u32 sat_imm, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x06E00030);
SET_CC;
I |= (sat_imm&15)<<16;
I |= (Rd&15)<<12;
I |= 15<<8; // * SBO
I |= (Rm&15);
EMIT_I;
}
};
+76
View File
@@ -0,0 +1,76 @@
/*
* E_Multiply.h
*
*/
#pragma once
namespace ARM
{
EAPI MLA(eReg Rd, eReg Rn, eReg Rs, eReg Rm, ConditionCode CC=AL) // *FIXME* S
{
DECL_Id(0x00200090);
SET_CC;
I |= (Rd&15)<<16;
I |= (Rn&15)<<12;
I |= (Rs&15)<<8;
I |= (Rm&15);
EMIT_I;
}
EAPI MUL(eReg Rd, eReg Rs, eReg Rm, ConditionCode CC=AL) // *FIXME* S
{
DECL_Id(0x00000090);
SET_CC;
I |= (Rd&15)<<16;
I |= (Rs&15)<<8;
I |= (Rm&15);
EMIT_I;
}
#if 0
SMLA<x><y> Signed halfword Multiply Accumulate.
SMLAD Signed halfword Multiply Accumulate, Dual.
SMLAL Signed Multiply Accumulate Long.
SMLAL<x><y> Signed halfword Multiply Accumulate Long.
SMLALD Signed halfword Multiply Accumulate Long, Dual.
SMLAW<y> Signed halfword by word Multiply Accumulate.
SMLSD Signed halfword Multiply Subtract, Dual.
SMLSLD Signed halfword Multiply Subtract Long Dual.
SMMLA Signed Most significant word Multiply Accumulate.
SMMLS Signed Most significant word Multiply Subtract.
SMMUL Signed Most significant word Multiply.
SMUAD Signed halfword Multiply, Add, Dual.
SMUL<x><y> Signed halfword Multiply.
SMULL Signed Multiply Long.
SMULW<y> Signed halfword by word Multiply.
SMUSD Signed halfword Multiply, Subtract, Dual.
UMAAL Unsigned Multiply Accumulate significant Long.
UMLAL Unsigned Multiply Accumulate Long.
UMULL Unsigned Multiply Long.
#endif
};
+112
View File
@@ -0,0 +1,112 @@
/*
* E_Parallel.h
*
ADD8 Adds each byte of the second operand register to the corresponding byte of the first operand
register to form the corresponding byte of the result.
ADD16 Adds the top halfwords of two registers to form the top halfword of the result.
Adds the bottom halfwords of the same two registers to form the bottom halfword of the result.
SUB8 Subtracts each byte of the second operand register from the corresponding byte of the first
operand register to form the corresponding byte of the result.
SUB16 Subtracts the top halfword of the first operand register from the top halfword of the second operand register to form the top halfword of the result.
Subtracts the bottom halfword of the second operand registers from the bottom halfword of
the first operand register to form the bottom halfword of the result.
ADDSUBX Does the following:
1. Exchanges halfwords of the second operand register.
2. Adds top halfwords and subtracts bottom halfwords.
SUBADDX Does the following:
1. Exchanges halfwords of the second operand register.
2. Subtracts top halfwords and adds bottom halfwords.
Each of the six instructions is available in the following variations, indicated by the prefixes shown:
S Signed arithmetic modulo 28 or 216. Sets the CPSR GE bits (see The GE[3:0] bits on page A2-13).
Q Signed saturating arithmetic.
SH Signed arithmetic, halving the results to avoid overflow.
U Unsigned arithmetic modulo 28 or 216. Sets the CPSR GE bits (see The GE[3:0] bits on page A2-13).
UQ Unsigned saturating arithmetic.
UH Unsigned arithmetic, halving the results to avoid overflow.
Status:
These routines require implementation if needed.
*/
#pragma once
namespace ARM
{
#if defined(_DEVEL) && 0
// S
//
EAPI SADD8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SADD16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SSUB8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SSUB16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SADDSUBX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SSUBADDX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
// Q
//
EAPI QADD8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI QADD16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI QSUB8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI QSUB16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI QADDSUBX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI QSUBADDX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
// SH
//
EAPI SHADD8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SHADD16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SHSUB8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SHSUB16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SHADDSUBX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI SHSUBADDX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
// U
//
EAPI UADD8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UADD16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI USUB8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI USUB16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UADDSUBX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI USUBADDX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
// UQ
//
EAPI UQADD8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UQADD16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UQSUB8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UQSUB16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UQADDSUBX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UQSUBADDX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
// UH
//
EAPI UHADD8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UHADD16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UHSUB8 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UHSUB16 (eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UHADDSUBX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
EAPI UHSUBADDX(eReg Rd, eReg Rm, eReg Rs, ConditionCode CC=AL) ;
#endif
};
+74
View File
@@ -0,0 +1,74 @@
/*
* E_Special.h
*
*/
#pragma once
namespace ARM
{
EAPI ARMERROR()
{
DECL_Id(0xFFFFFFFF);
EMIT_I;
}
EAPI NOP()
{
DECL_Id(0xE320F000);
EMIT_I;
}
EAPI SVC(u32 code)
{
DECL_Id(0x0F000000);
I |= code&0xFFFFFF;
EMIT_I;
}
EAPI BKPT()
{
DECL_Id(0x01200070);
EMIT_I;
}
#define SWI SVC
/*
* Synchronization & Barrier Instructions.
*
*/
EAPI DSB()
{
DECL_Id(0xF57FF04F);
EMIT_I;
}
EAPI DMB()
{
DECL_Id(0xF57FF05F);
EMIT_I;
}
EAPI ISB()
{
DECL_Id(0xF57FF06F);
EMIT_I;
}
};
+99
View File
@@ -0,0 +1,99 @@
/*
* E_Status.h
*
*/
#pragma once
namespace ARM
{
#if defined(_DEVEL)
// MRS Move PSR to General-purpose Register.
//
EAPI MRS(eReg Rd, u32 R, ConditionCode CC=AL)
{
DECL_Id(0x01000000);
SET_CC;
I |= (R&1) << 22;
I |= 15<<16; // * SBO
I |= (Rd &15)<<12;
EMIT_I;
}
/* MSR Move General-purpose Register to PSR.
MSR{<cond>} CPSR_<fields>, #<immediate>
MSR{<cond>} CPSR_<fields>, <Rm>
MSR{<cond>} SPSR_<fields>, #<immediate>
MSR{<cond>} SPSR_<fields>, <Rm>
*/
// MSR: Immediate operand
//
EAPI MSR(u32 R, u32 fmask, u32 rot_imm, u32 imm8, ConditionCode CC=AL)
{
DECL_Id(0x03200000);
SET_CC;
I |= (R&1) << 22;
I |= (fmask &15)<<16;
I |= 15<<12; // * SBO
I |= (rot_imm &15)<<8;
I |= (imm8 &255);
EMIT_I;
}
// MSR: Register operand
//
EAPI MSR(u32 R, u32 fmask, eReg Rm, ConditionCode CC=AL)
{
DECL_Id(0x01200000);
SET_CC;
I |= (R&1) << 22;
I |= (fmask &15)<<16;
I |= 15<<12; // * SBO
I |= (Rm&15);
EMIT_I;
}
// CPS Change Processor State.
//
EAPI CPS(u32 imod, u32 mmod, u32 mode) // ** [A|I|F]
{
DECL_Id(0xF1000000);
// Note: UNconditional instruction!
I |= (imod&3)<<18;
I |= (mmod&1)<<17;
I |= (mode&15);
EMIT_I;
}
// SETEND Modifies the CPSR endianness, E, bit, without changing any other bits in the CPSR.
//
EAPI SETEND(u32 E)
{
DECL_Id(0xF1010000);
// Note: UNconditional instruction!
I |= (E &1) << 9;
EMIT_I;
}
#endif
};
+659
View File
@@ -0,0 +1,659 @@
/*
* E_VDataOp.h * VFP/A.SIMD Data Processing Instruction Set Encoding
*
* V{<modifier>}<operation>{<shape>}<c><q>{.<dt>} {<dest>,} <src1>, <src2>
*
* <modifier> Meaning
* Q The operation uses saturating arithmetic.
* R The operation performs rounding.
* D The operation doubles the result (before accumulation, if any).
* H The operation halves the result.
*
* <shape> Meaning Typical register shape
* (none) The operands and result are all the same width. Dd, Dn, Dm - Qd, Qn, Qm
* L Long operation - result is 2 x width of both operands Qd, Dn, Dm
* N Narrow operation - result is width/2 both operands Dd, Qn, Qm
* W Wide operation - result and oper[1] are 2x width oper[2] Qd, Qn, Dm
*/
#pragma once
namespace ARM
{
#define SET_Qd \
I |= (((Qd<<1)&0x0E)<<12); \
I |= (((Qd<<1)&0x10)<<18)
#define SET_Qn \
I |= (((Qn<<1)&0x0E)<<16); \
I |= (((Qn<<1)&0x10)<<3)
#define SET_Qm \
I |= (((Qm<<1)&0x0E)); \
I |= (((Qm<<1)&0x10)<<1)
#define SET_Dd \
I |= ((Dd&0x0F)<<12); \
I |= ((Dd&0x10)<<18)
#define SET_Dn \
I |= ((Dn&0x0F)<<16); \
I |= ((Dn&0x10)<<3)
#define SET_Dm \
I |= ((Dm&0x0F)); \
I |= ((Dm&0x10)<<1)
#define SET_Q I |= 0x40
#define SET_U I |= ((U&1)<<24);
#define SET_Size I |= (((Size>>4)&3)<<20) // 8,16,32 -> 0,1,2
#define SET_Qdnm \
SET_Qd; SET_Qn; SET_Qm; SET_Q
#define SET_Ddnm \
SET_Dd; SET_Dn; SET_Dm
#define DECL_Qdnm
#define VdpInstrF(viName, viId) \
EAPI V##viName##_F32 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { DECL_Id(viId); SET_Qdnm; EMIT_I; } \
EAPI V##viName##_F32 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { DECL_Id(viId); SET_Ddnm; EMIT_I; }
#define VdpInstrI_EOR(viName, viId) \
EAPI V##viName (eFQReg Qd, eFQReg Qn, eFQReg Qm) { DECL_Id(viId); SET_Qdnm; EMIT_I; } \
EAPI V##viName (eFDReg Dd, eFDReg Dn, eFDReg Dm) { DECL_Id(viId); SET_Ddnm; EMIT_I; } \
#define VdpInstrI(viName, viId) \
EAPI V##viName (eFQReg Qd, eFQReg Qn, eFQReg Qm, u32 Size=32) { DECL_Id(viId); SET_Qdnm; SET_Size; EMIT_I; } \
EAPI V##viName (eFDReg Dd, eFDReg Dn, eFDReg Dm, u32 Size=32) { DECL_Id(viId); SET_Ddnm; SET_Size; EMIT_I; } \
\
EAPI V##viName##_I8 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 8); } \
EAPI V##viName##_I8 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 8); } \
EAPI V##viName##_I16 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 16); } \
EAPI V##viName##_I16 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 16); } \
EAPI V##viName##_I32 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 32); } \
EAPI V##viName##_I32 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 32); }
#define VdpInstrU(viName, viId) \
EAPI V##viName (eFQReg Qd, eFQReg Qn, eFQReg Qm, u32 Size=32, u32 U=0) { DECL_Id(viId); SET_Qdnm; SET_U; SET_Size; EMIT_I; } \
EAPI V##viName (eFDReg Dd, eFDReg Dn, eFDReg Dm, u32 Size=32, u32 U=0) { DECL_Id(viId); SET_Ddnm; SET_U; SET_Size; EMIT_I; } \
\
EAPI V##viName##_U8 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 8, 1); } \
EAPI V##viName##_U8 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 8, 1); } \
EAPI V##viName##_S8 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 8, 0); } \
EAPI V##viName##_S8 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 8, 0); } \
EAPI V##viName##_U16 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 16, 1); } \
EAPI V##viName##_U16 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 16, 1); } \
EAPI V##viName##_S16 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 16, 0); } \
EAPI V##viName##_S16 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 16, 0); } \
EAPI V##viName##_U32 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 32, 1); } \
EAPI V##viName##_U32 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 32, 1); } \
EAPI V##viName##_S32 (eFQReg Qd, eFQReg Qn, eFQReg Qm) { V##viName (Qd, Qn, Qm, 32, 0); } \
EAPI V##viName##_S32 (eFDReg Dd, eFDReg Dn, eFDReg Dm) { V##viName (Dd, Dn, Dm, 32, 0); }
//# define VdpInstrImm (viName, viId)
// Another three or four like the above .. immN, above w/ size, F32 w/ sz
/*
* A.SIMD Parallel Add/Sub
*
Vector Add VADD (integer), VADD (floating-point)
Vector Add and Narrow, returning High Half VADDHN
Vector Add Long, Vector Add Wide VADDL, VADDW
Vector Halving Add, Vector Halving Subtract VHADD, VHSUB
Vector Pairwise Add and Accumulate Long VPADAL
Vector Pairwise Add VPADD (integer) , VPADD (floating-point)
Vector Pairwise Add Long VPADDL
Vector Rounding Add & Narrow, returning High Half VRADDHN
Vector Rounding Halving Add VRHADD
Vector Rounding Subtract & Narrow, ret. High Half VRSUBHN
Vector Saturating Add VQADD
Vector Saturating Subtract VQSUB
Vector Subtract VSUB (integer), VSUB (floating-point)
Vector Subtract and Narrow, returning High Half VSUBHN
Vector Subtract Long, Vector Subtract Wide VSUBL, VSUBW
*/
VdpInstrI(ADD, 0xF2000800)
VdpInstrF(ADD, 0xF2000D00)
VdpInstrI(HADD, 0xF2000800)
VdpInstrI(HSUB, 0xF2000A00)
VdpInstrI(PADD, 0xF2000B10)
VdpInstrF(PADD, 0xF3000D00)
VdpInstrU(RHADD, 0xF3000100)
VdpInstrU(QADD, 0xF2000010)
VdpInstrU(QSUB, 0xF3000210)
VdpInstrI(SUB, 0xF3000800)
VdpInstrF(SUB, 0xF2200D00)
// VADD I { DECL_Id(0xF2000800); SET_Qdnm; EMIT_I; }
// VADD F { DECL_Id(0xF2000D00); SET_Qdnm; EMIT_I; }
// VADDHN { DECL_Id(0xF2800400); SET_Qdnm; EMIT_I; } // DQQ
// VADD{L,W} { DECL_Id(0xF2800000); SET_Qdnm; EMIT_I; } // QDD || QQD
// VH{ADD,SUB} { DECL_Id(0xF2000000); SET_Qdnm; EMIT_I; }
// VPADAL { DECL_Id(0xF3B00600); SET_Qdnm; EMIT_I; } // QdQm || DdDm
// VPADD I { DECL_Id(0xF2000B10); SET_Qdnm; EMIT_I; } // DDD only
// VPADD F { DECL_Id(0xF3000D00); SET_Qdnm; EMIT_I; } // DDD only
// VPADDL { DECL_Id(0xF3B00200); SET_Qdnm; EMIT_I; } // QdQm || DdDm
// VRADDHN { DECL_Id(0xF3800400); SET_Qdnm; EMIT_I; } // DQQ
// VRHADD { DECL_Id(0xF3000100); SET_Qdnm; EMIT_I; }
// VRSUBHN { DECL_Id(0xF3800600); SET_Qdnm; EMIT_I; } // DQQ
// VQADD { DECL_Id(0xF2000010); SET_Qdnm; EMIT_I; }
// VQSUB { DECL_Id(0xF3000210); SET_Qdnm; EMIT_I; }
// VSUB I { DECL_Id(0xF3000800); SET_Qdnm; EMIT_I; }
// VSUB F { DECL_Id(0xF2200D00); SET_Qdnm; EMIT_I; }
// VSUBHN { DECL_Id(0xF2800600); SET_Qdnm; EMIT_I; } // DQQ
// VSUB{L,W} { DECL_Id(0xF2800200); SET_Qdnm; EMIT_I; } // QDD || QQD
/*
* A.SIMD Bitwise
*
Vector Bitwise AND VAND (register)
Vector Bitwise Bit Clear (AND complement) VBIC (immediate), VBIC (register)
Vector Bitwise Exclusive OR VEOR
Vector Bitwise Move VMOV (immediate), VMOV (register)
Vector Bitwise NOT VMVN (immediate), VMVN (register)
Vector Bitwise OR VORR (immediate), VORR (register)
Vector Bitwise OR NOT VORN (register)
Vector Bitwise Insert if False VBIF
Vector Bitwise Insert if True VBIT
Vector Bitwise Select VBSL
*/
VdpInstrI(AND, 0xF2000110)
VdpInstrI(BIC, 0xF2100110)
VdpInstrI_EOR(EOR, 0xF3000110)
VdpInstrI_EOR(BSL, 0xF3100110)
VdpInstrI_EOR(BIT, 0xF3200110)
VdpInstrI_EOR(BIF, 0xF3300110)
VdpInstrI(ORN, 0xF2300110)
// VAND R { DECL_Id(0xF2000110); SET_Qdnm; EMIT_I; }
// VBIC R { DECL_Id(0xF2100110); SET_Qdnm; EMIT_I; }
// VEOR { DECL_Id(0xF3000110); SET_Qdnm; EMIT_I; }
// VBSL { DECL_Id(0xF3100110); SET_Qdnm; EMIT_I; }
// VBIT { DECL_Id(0xF3200110); SET_Qdnm; EMIT_I; }
// VBIF { DECL_Id(0xF3300110); SET_Qdnm; EMIT_I; }
// VORN R { DECL_Id(0xF2300110); SET_Qdnm; EMIT_I; }
// VBIC I { DECL_Id(0xF2800030); SET_Qd; SET_IMM??; EMIT_I; }
// VMOV I { DECL_Id(0xF2800010); SET_Qd; SET_IMM??; EMIT_I; }
// VMVN I { DECL_Id(0xF2800030); SET_Qd; SET_IMM??; EMIT_I; }
// VORR I { DECL_Id(0xF2800010); SET_Qd; SET_IMM??; EMIT_I; }
// VAND I VBIC I
// VORN I VORR I
/*
* A.SIMD comparison
*
Vector Absolute Compare VACGE, VACGT, VACLE,VACLT
Vector Compare Equal VCEQ (register)
Vector Compare Equal to Zer VCEQ (immediate #0)
Vector Compare Greater Than or Equal VCGE (register)
Vector Compare Greater Than or Equal to Zero VCGE (immediate #0)
Vector Compare Greater Than VCGT (register)
Vector Compare Greater Than Zero VCGT (immediate #0)
Vector Compare Less Than or Equal to Zero VCLE (immediate #0)
Vector Compare Less Than Zero VCLT (immediate #0)
Vector Test Bits VTST
*/
// VAC{COND} { DECL_Id(0xF3000E10); SET_Vdnm; EMIT_I; }
// VCEQ { DECL_Id(0xF3000810); SET_Vdnm; EMIT_I; } .F32 { DECL_Id(0xF2000E00); SET_Vdnm; EMIT_I; }
// VCGE { DECL_Id(0xF2000310); SET_Vdnm; EMIT_I; } .F32 { DECL_Id(0xF3000E00); SET_Vdnm; EMIT_I; }
// VCGT { DECL_Id(0xF2000300); SET_Vdnm; EMIT_I; } .F32 { DECL_Id(0xF3200E00); SET_Vdnm; EMIT_I; }
// VCLE { DECL_Id(0xF3B10180); SET_Vdnm; EMIT_I; } // R is VCGE w/ operands reversed
// VCLT { DECL_Id(0xF3B10200); SET_Vdnm; EMIT_I; } // R is VCGT w/ operands reversed
// VTST { DECL_Id(0xF2000810); SET_Vdnm; EMIT_I; }
// VCEQZ { DECL_Id(0xF3B10100); SET_Vd; SET_Vm; EMIT_I; }
// VCGEZ { DECL_Id(0xF3B10080); SET_Vd; SET_Vm; EMIT_I; }
// VCGTZ { DECL_Id(0xF3B10000); SET_Vd; SET_Vm; EMIT_I; }
/*
* A.SIMD shift ** SET_imm6; needed for non Vdnm
*
Vector Saturating Rounding Shift Left VQRSHL
Vector Saturating Rounding Shift Right and Narrow VQRSHRN, VQRSHRUN
Vector Saturating Shift Left VQSHL (register), VQSHL, VQSHLU (immediate)
Vector Saturating Shift Right and Narrow VQSHRN, VQSHRUN
Vector Rounding Shift Left VRSHL
Vector Rounding Shift Right VRSHR
Vector Rounding Shift Right and Accumulate VRSRA
Vector Rounding Shift Right and Narrow VRSHRN
Vector Shift Left VSHL (immediate) on page A8-750 VSHL (register)
Vector Shift Left Long VSHLL
Vector Shift Right VSHR
Vector Shift Right and Narrow VSHRN
Vector Shift Left and Insert VSLI
Vector Shift Right and Accumulate VSRA
Vector Shift Right and Insert VSRI
*/
// VQRSHL { DECL_Id(0xF SET_Vdnm; EMIT_I; } // * TODO
// VQRSHRN { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VQRSHRUN { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VQSHL R { DECL_Id(0xF SET_Vdnm; EMIT_I; }
// VQSHL I { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VQSHLU { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VQSHRN { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VQSHRUN { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VRSHL { DECL_Id(0xF SET_Vdnm; EMIT_I; }
// VRSHR { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VRSRA { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VRSHRN { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSHL I { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSHL R { DECL_Id(0xF SET_Vdnm; EMIT_I; }
// VSHLL { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSHR { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSHRN { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSLI { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSRA { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
// VSRI { DECL_Id(0xF SET_Vd; SET_Vm; EMIT_I; }
/*
* A.SIMD multiply
*
Vector Multiply Accumulate VMLA, VMLAL, VMLS, VMLSL (integer) , VMLA, VMLS (floating-point), VMLA, VMLAL, VMLS, VMLSL (by scalar)
Vector Multiply Accumulate Long
Vector Multiply Subtract
Vector Multiply Subtract Long
Vector Multiply VMUL, VMULL (integer and polynomial)
Vector Multiply Long VMUL (floating-point) on page A8-664 VMUL, VMULL (by scalar)
Vector Saturating Doubling Multiply Accumulate Long VQDMLAL, VQDMLSL
Vector Saturating Doubling Multiply Subtract Long
Vector Saturating Doubling Multiply Returning High Half VQDMULH
Vector Saturating Rounding Doubling Multiply Ret. High Half VQRDMULH
Vector Saturating Doubling Multiply Long VQDMULL
*/
VdpInstrI(MLA, 0xF2000900)
VdpInstrI(MLS, 0xF3000900)
VdpInstrF(MLA, 0xF2000D10)
VdpInstrF(MLS, 0xF2200D10)
//by scalar
//this should be really qd,dn,sm not dm
EAPI VMUL_F32(eFQReg Qd,eFQReg Qn, eFDReg Dm, int idx)
{
DECL_Id(0xF2800840);
SET_Qd;
SET_Qn;
I |= 1<<8; //SET_F
SET_Dm;
I |= 0x1<<24; //SET_Q not compitable
I |= 2<<20; //size to 32
I |= Dm&15; //only lower 15 regs are avail
//set register sub index
if (idx)
I |= 1<<5;
EMIT_I;
}
EAPI VMLA_F32(eFQReg Qd,eFQReg Qn, eFDReg Dm, int idx)
{
DECL_Id(0xF2800040);
SET_Qd;
SET_Qn;
I |= 1<<8; //SET_F
SET_Dm;
I |= 0x1<<24; //SET_Q not compitable
I |= 2<<20; //size to 32
I |= Dm&15; //only lower 15 regs are avail
//set register sub index
if (idx)
I |= 1<<5;
EMIT_I;
}
// VdpInstrU(MLAL, 0xF2000D10) *QDD
// VdpInstrU(MLSL, 0xF2200D10) *QDD
VdpInstrI(MUL, 0xF2000910)
VdpInstrF(MUL, 0xF3000D10)
// VdpInstrU(MULL, 0xF3000D10) *QDD
// VMLA I { DECL_Id(0xF2000900); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VMLS I { DECL_Id(0xF3000900); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VMLAL I { DECL_Id(0xF2800800); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= ((U&1)<<24)
// VMLSL I { DECL_Id(0xF2800A00); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= ((U&1)<<24)
// VMLA F { DECL_Id(0xF2000D10); SET_Vdnm; EMIT_I; } // * I |= ((sz&1)<<20)
// VMLS F { DECL_Id(0xF2200D10); SET_Vdnm; EMIT_I; } // * I |= ((sz&1)<<20)
// VMLA S { DECL_Id(0xF2800040); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VMLS S { DECL_Id(0xF2800440); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// CMLAL S { DECL_Id(0xF2800240); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= ((U&1)<<24)
// VMLSL S { DECL_Id(0xF2800640); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= ((U&1)<<24)
// VMUL IP { DECL_Id(0xF2000910); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= 1<<24 for polynomial
// VMULL IP { DECL_Id(0xF2800C00); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= 1<<9 for polynomial * I |= ((U&1)<<24)
// VMUL F { DECL_Id(0xF3000D10); SET_Vdnm; EMIT_I; } // * I |= ((sz&1)<<20)
// VMUL S { DECL_Id(0xF2800840); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VMULL S { DECL_Id(0xF2800A40); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20) * I |= ((U&1)<<24)
// VQDMLAL { DECL_Id(0xF2800900); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VQDMLSL { DECL_Id(0xF2800B00); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VQDMULH { DECL_Id(0xF2000B00); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VQRDMULH { DECL_Id(0xF3000B00); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
// VQDMULL { DECL_Id(0xF2800D00); SET_Vdnm; EMIT_I; } // * I |= ((size&3)<<20)
/*
* A.SIMD misc
*
Vector Absolute Difference and Accumulate VABA, VABAL
Vector Absolute Difference VABD, VABDL (integer) , VABD (floating-point)
Vector Absolute VABS
Vector Convert between floating-point and fixed point VCVT (between floating-point and fixed-point, Advanced SIMD)
Vector Convert between floating-point and integer VCVT (between floating-point and integer, Advanced SIMD)
Vector Convert between half-precision and single-precision VCVT (between half-precision and single-precision, Advanced SIMD)
Vector Count Leading Sign Bits VCLS
Vector Count Leading Zeros VCLZ
Vector Count Set Bits VCNT
Vector Duplicate scalar VDUP (scalar)
Vector Extract VEXT
Vector Move and Narrow VMOVN
Vector Move Long VMOVL
Vector Maximum, Minimum VMAX, VMIN (integer) , VMAX, VMIN (floating-point)
Vector Negate VNEG
Vector Pairwise Maximum, Minimum VPMAX, VPMIN (integer) , VPMAX, VPMIN (floating-point)
Vector Reciprocal Estimate VRECPE
Vector Reciprocal Step VRECPS
Vector Reciprocal Square Root Estimate VRSQRTE
Vector Reciprocal Square Root Step VRSQRTS
Vector Reverse VREV16, VREV32, VREV64
Vector Saturating Absolute VQABS
Vector Saturating Move and Narrow VQMOVN, VQMOVUN
Vector Saturating Negate VQNEG
Vector Swap VSWP
Vector Table Lookup VTBL, VTBX
Vector Transpose VTRN
Vector Unzip VUZP
Vector Zip VZIP
*/
// VABA { DECL_Id(0xF2000710); // WIP
// VABAL { DECL_Id(0xF2800500);
// VABD I { DECL_Id(0xF);
// VABDL I { DECL_Id(0xF);
// VABD F { DECL_Id(0xF);
// VABS { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
EAPI VSQRT_F32(eFSReg Sd, eFSReg Sm, ConditionCode CC=AL)
{
DECL_Id(0x0EB10AC0); SET_CC;
I |= ((Sd&0x1E)<<11) | ((Sd&1)<<22);
I |= ((Sm&0x1E)>>1) | ((Sm&1)<<5);
EMIT_I;
}
EAPI VABS_F32(eFSReg Sd, eFSReg Sm, ConditionCode CC=AL)
{
DECL_Id(0x0EB00AC0); SET_CC;
I |= ((Sd&0x1E)<<11) | ((Sd&1)<<22);
I |= ((Sm&0x1E)>>1) | ((Sm&1)<<5);
EMIT_I;
}
EAPI VNEG_F32(eFSReg Sd, eFSReg Sm, ConditionCode CC=AL)
{
DECL_Id(0x0EB10A40); SET_CC;
I |= ((Sd&0x1E)<<11) | ((Sd&1)<<22);
I |= ((Sm&0x1E)>>1) | ((Sm&1)<<5);
EMIT_I;
}
//imm move, fpu
EAPI VMOV(eFSReg Sd, u32 imm8_fpu, ConditionCode CC=AL)
{
DECL_Id(0x0EB10A00); SET_CC;
I |= (imm8_fpu&0x0F); //bits 3:0
I |= (imm8_fpu&0xF0)<<12; //bits 19:16
I |= ((Sd&0x1E)<<11) | ((Sd&1)<<22);
EMIT_I;
}
const u32 fpu_imm_1=0x70;//01110000
EAPI VCMP_F32(eFSReg Sd, eFSReg Sm, ConditionCode CC=AL)
{
DECL_Id(0x0EB40A40); SET_CC;
I |= ((Sd&0x1E)<<11) | ((Sd&1)<<22);
I |= ((Sm&0x1E)>>1) | ((Sm&1)<<5);
EMIT_I;
}
VdpInstrF(CEQ, 0xF2000E00)
VdpInstrF(CGE, 0xF3000E00)
VdpInstrF(CGT, 0xF3200E00)
// VCVT FFP { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
// VCVT FI { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
// VCVT HS { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
// VCLS { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
// VCLZ { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
// VCNT { DECL_Id(0xF); SET_Vd; SET_Vm; EMIT_I; }
// VEXT { DECL_Id(0xF); SET_Vdnm; EMIT_I; }
// VMAX I { DECL_Id(0xF);
// VMIN I { DECL_Id(0xF);
// VMAX F { DECL_Id(0xF);
// VMIN F { DECL_Id(0xF);
// VNEG { DECL_Id(0xF);
// VPMAX I { DECL_Id(0xF);
// VPMIN I { DECL_Id(0xF);
// VPMAX F { DECL_Id(0xF);
// VPMIN F { DECL_Id(0xF);
// VRECPE { DECL_Id(0xF3B30400); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VRECPS { DECL_Id(0xF2000F10); SET_Vdnm; EMIT_I; } // sz&1<<20 (.F32)
// VRSQRTE { DECL_Id(0xF3B30480); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18 F&1<<8 ***
// VRSQRTS { DECL_Id(0xF2200F10); SET_Vdnm; EMIT_I; } // sz&1<<20 (.F32)
// VREVsz { DECL_Id(0xF3B00000); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18 op&3<<7 ***
// VQABS { DECL_Id(0xF3B00700); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VQMOVN { DECL_Id(0xF3B20200); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18 op&3<<6 op:00=MOVN op11=srcUnsigned op:x1=dstUnsigned
// VQMOVUN { DECL_Id(0xF3B20200); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VQNEG { DECL_Id(0xF3B00780); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VSWP { DECL_Id(0xF3B20000); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VTBL { DECL_Id(0xF3B00800); SET_Vdnm; EMIT_I; } // len&3<<8
// VTBX { DECL_Id(0xF3B00840); SET_Vdnm; EMIT_I; } // len&3<<8
// VTRN { DECL_Id(0xF3B20080); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VUZP { DECL_Id(0xF3B20100); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
// VZIP { DECL_Id(0xF3B20180); SET_Vd; SET_Vm; EMIT_I; } // size&3<<18
//
// VDUP & VMOVN & VMOVL are implemented in VRegXfer.h ...
/*
* VFPv3 Instructions
*
*/
#define SET_Sd \
I |= ((Sd&0x1E)<<11); \
I |= ((Sd&0x01)<<22)
#define SET_Sn \
I |= ((Sn&0x1E)<<15); \
I |= ((Sn&0x01)<<7)
#define SET_Sm \
I |= ((Sm&0x1E)>>1); \
I |= ((Sm&0x01)<<5)
#define SET_Sdnm SET_Sd; SET_Sn; SET_Sm
#define VfpInstrS(viName, viId) EAPI V##viName##_VFP (eFSReg Sd, eFSReg Sn, eFSReg Sm, ConditionCode CC=CC_AL) { DECL_Id(viId); SET_CC; SET_Sdnm; EMIT_I; }
VfpInstrS(MLA, 0x0E000A00)
VfpInstrS(MLS, 0x0E000A40)
VfpInstrS(NMLA, 0x0E100A40)
VfpInstrS(NMLS, 0x0E100A00)
VfpInstrS(NMUL, 0x0E200A40)
VfpInstrS(MUL, 0x0E200A00)
VfpInstrS(ADD, 0x0E300A00)
VfpInstrS(SUB, 0x0E300A40)
VfpInstrS(DIV, 0x0E800A00)
EAPI VCVT_to_S32_VFP (eFSReg Sd, eFSReg Sm, ConditionCode CC=CC_AL) { DECL_Id(0x0EBD0AC0); SET_CC; SET_Sd; SET_Sm; EMIT_I; } // VfpInstrS(ABS, 0x0EB00AC0) ** {D,S}dm
//EAPI VCVT_from_S32_VFP (eFSReg Sd, eFSReg Sm) { DECL_Id(0x0EB80A40); SET_CC; SET_Sd; SET_Sm; EMIT_I; } // VfpInstrS(ABS, 0x0EB00AC0) ** {D,S}dm
EAPI VABS_VFP (eFSReg Sd, eFSReg Sm, ConditionCode CC=CC_AL) { DECL_Id(0x0EB00AC0); SET_CC; SET_Sd; SET_Sm; EMIT_I; } // VfpInstrS(ABS, 0x0EB00AC0) ** {D,S}dm
EAPI VNEG_VFP (eFSReg Sd, eFSReg Sm, ConditionCode CC=CC_AL) { DECL_Id(0x0EB10A40); SET_CC; SET_Sd; SET_Sm; EMIT_I; } // VfpInstrS(NEG, 0x0EB10A40) ** {D,S}dm
EAPI VSQRT_VFP(eFSReg Sd, eFSReg Sm, ConditionCode CC=CC_AL) { DECL_Id(0x0EB10AC0); SET_CC; SET_Sd; SET_Sm; EMIT_I; } // VfpInstrS(SQRT, 0x0EB10AC0) ** {D,S}dm
// - x0 Vector Move VMOV (immediate) on page A8-640
// 0000 01 Vector Move VMOV (register) on page A8-642
// 001x x1 Vector Convert VCVTB, VCVTT (between half-precision and single-precision, VFP) on page A8-588
// 010x x1 Vector Compare VCMP, VCMPE on page A8-572
// 0111 11 Vector Convert VCVT (between double-precision and single-precision) on page A8-584
// 1000 x1 Vector Convert VCVT, VCVTR (between floating-point and integer, VFP) on page A8-578
// 101x x1 Vector Convert VCVT (between floating-point and fixed-point, VFP) on page A8-582
// 110x x1 Vector Convert VCVT, VCVTR (between floating-point and integer, VFP) on page A8-578
// 111x x1 Vector Convert VCVT (between floating-point and fixed-point, VFP) on page A8-582
////// hack
EAPI VDIV_HACKF32(eFDReg Sd, eFDReg Sn, eFDReg Sm)
{
ConditionCode CC=AL;
eFSReg SdS=(eFSReg)(Sd*2);
eFSReg SnS=(eFSReg)(Sn*2);
eFSReg SmS=(eFSReg)(Sm*2);
verify(Sd<32 && Sn<32 && Sm<32);
VDIV_VFP(SdS,SnS,SmS);
}
#undef SET_Qd
#undef SET_Dd
#undef SET_Qn
#undef SET_Dn
#undef SET_Qm
#undef SET_Dm
#undef SET_Q
#undef SET_Qdnm
#undef SET_Ddnm
};
+210
View File
@@ -0,0 +1,210 @@
/*
* E_VLoadStore.h * VFP/A.SIMD Load/Store Instruction Set Encoding
*
*/
#pragma once
namespace ARM
{
// [cond][110][Opcode][-Rn-][----][101][---------]
//
// cond != 0b1111 | LDC && STC consume these
#define SET_Dd \
I |= ((Dd&0x0F)<<12); \
I |= ((Dd&0x10)<<18)
#define SET_Sd \
I |= ((Sd&0x1E)<<11); \
I |= ((Sd&0x01)<<22)
#define SET_Rn \
I |= ((Rn&15)<<16)
#define SET_uImm8 \
I |= (uImm8 & 255)
#define SET_sImm8 \
if (sImm8 > 0) { \
I |= (1<<23); \
} \
I |= (abs(sImm8) & 255)
#define SET_PUW(_P,_U,_W) \
I |= ( ((_P&1)<<24) | ((_U&1)<<23) | ((_W&1)<<21) )
/*
* V{LD,ST}R: Vector Load/Store Register
*
* V{LD,ST}R.64 // VFP && A.SIMD
* V{LD,ST}R.32 // VFP
*/
EAPI VLDR(eFDReg Dd, eReg Rn, s32 sImm8, ConditionCode CC=AL) // VLDR.64
{
DECL_Id(0x0D100B00); SET_CC;
SET_Dd; SET_Rn; SET_sImm8;
EMIT_I;
}
EAPI VLDR(eFSReg Sd, eReg Rn, s32 sImm8, ConditionCode CC=AL) // VLDR.32
{
DECL_Id(0x0D100A00); SET_CC;
SET_Sd; SET_Rn; SET_sImm8;
EMIT_I;
}
EAPI VSTR(eFDReg Dd, eReg Rn, s32 sImm8, ConditionCode CC=AL) // VSTR.64
{
DECL_Id(0x0D000B00); SET_CC;
SET_Dd; SET_Rn; SET_sImm8;
EMIT_I;
}
EAPI VSTR(eFSReg Sd, eReg Rn, s32 sImm8, ConditionCode CC=AL) // VSTR.32
{
DECL_Id(0x0D000A00); SET_CC;
SET_Sd; SET_Rn; SET_sImm8;
EMIT_I;
}
/*
* V{LD,ST}M: Vector Load/Store Multiple
*
* V{LD,ST}R.64 // VFP && A.SIMD
* V{LD,ST}R.32 // VFP
*
* uImm8: directional count, abs(sImm8) is the reg. count
* Dd: Register to start sequential operation from..
*
* suffix DB: P=1 U=0 W=1, Decrement Before, Addresses end just before the address in Rn.
* suffix IA: P=0 U=1 W=?, Increment After, Addresses start at address in Rn
*
* ** These are very complicated encoding and require a lot of error checking and even more thought when used. **
* ** Simply using, MOV32(R4, &double_array[0]); VLDM(D0, R4, 4); should however work to load an array of 4 doubles **
*/
EAPI VLDM(eFDReg Dd, eReg Rn, u32 uImm8, u32 WB=0, ConditionCode CC=AL) // VLDM.64
{
// ASSERT( (uImm8>0) && (uImm8<=16) && ((Dd+uImm8) <= 32) )
uImm8<<=1;
DECL_Id(0x0C100B00); SET_CC;
SET_Dd; SET_Rn;
SET_uImm8; SET_PUW(0,1,WB); // Defaulting to IA w/o ! (Write-back)
EMIT_I;
}
EAPI VLDM(eFSReg Sd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VLDM.32
{
// ASSERT( (uImm8>0) && ((Dd+uImm8) <= 32) )
DECL_Id(0x0C100A00); SET_CC;
SET_Sd; SET_Rn;
SET_uImm8; SET_PUW(0,1,0); // Defaulting to IA w/o ! (Write-back)
EMIT_I;
}
EAPI VSTM(eFDReg Dd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VSTM.64
{
// ASSERT( (uImm8>0) && (uImm8<=16) && ((Dd+uImm8) <= 32) )
uImm8<<=1;
DECL_Id(0x0C000B00); SET_CC;
SET_Dd; SET_Rn;
SET_uImm8; SET_PUW(0,1,0); // Defaulting to IA w/o ! (Write-back)
EMIT_I;
}
EAPI VSTM(eFSReg Sd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VSTM.32
{
// ASSERT( (uImm8>0) && ((Dd+uImm8) <= 32) )
DECL_Id(0x0C000A00); SET_CC;
SET_Sd; SET_Rn;
SET_uImm8; SET_PUW(0,1,0); // Defaulting to IA w/o ! (Write-back)
EMIT_I;
}
/*
* V{LD,ST}n: Various extra load/store multiple.
*
* Not Implemented.
*
*/
/*
* VPUSH/VPOP: Vector Load/Store multiple consecutive vector registers to the stack.
*
* V{PUSH,POP} .64: A.SIMD .32 VFP
*/
EAPI VPUSH(eFDReg Dd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VPUSH.64
{
uImm8<<=1;
DECL_Id(0x0D2D0B00); SET_CC;
SET_Dd; SET_uImm8;
EMIT_I;
}
EAPI VPUSH(eFSReg Sd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VPUSH.32
{
DECL_Id(0x0D2D0A00); SET_CC;
SET_Sd; SET_uImm8;
EMIT_I;
}
EAPI VPOP(eFDReg Dd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VPOP.64
{
uImm8<<=1;
DECL_Id(0x0CBD0B00); SET_CC;
SET_Dd; SET_uImm8;
EMIT_I;
}
EAPI VPOP(eFSReg Sd, eReg Rn, u32 uImm8, ConditionCode CC=AL) // VPOP.32
{
DECL_Id(0x0CBD0A00); SET_CC;
SET_Sd; SET_uImm8;
EMIT_I;
}
/*
* Best practice is to remove macro definitions,
* this way they can't affect subsequent headers.
*/
#undef SET_Dd
#undef SET_Sd
#undef SET_Rn
#undef SET_uImm8
#undef SET_sImm8
#undef SET_PUW
};
+344
View File
@@ -0,0 +1,344 @@
/*
* E_VRegXfer.h * VFP/A.SIMD Register Transfer Instruction Set Encoding
*
*/
#pragma once
namespace ARM
{
/////// REPLACE THIS MESS W. SET_Rto16 / SET_Rto16_H22 , SET_Rto12 , SET_Rto0_H5 OR just leave it all in the fn's //////
#define SET_Qd \
I |= (((Qd<<1)&0x0E)<<16); \
I |= (((Qd<<1)&0x10)<<3)
#define SET_Qm \
I |= (((Qm<<1)&0x0E)); \
I |= (((Qm<<1)&0x10)<<1)
#define SET_Dd \
I |= ((Dd&0x0F)<<16); \
I |= ((Dd&0x10)<<3)
#define SET_Dm \
I |= ((Dm&0x0F)); \
I |= ((Dm&0x10)<<1)
#define SET_Sn \
I |= ((Sn&0x1E)<<15); \
I |= ((Sn&0x01)<<7)
#define SET_Sm \
I |= ((Sm&0x1E)>>1); \
I |= ((Sm&0x01)<<5)
#define SET_Rn \
I |= ((Rn&15)<<16)
#define SET_Rt \
I |= ((Rt&15)<<12)
#define SET_Rtx2 \
I |= ((Rt&15)<<12) | ((Rt2&15)<<16)
// VDUP VMOV VMRS VMSR
/*
* VDUP.SZ: Duplicates an element from ARM reg Rt into every element of {Q,D}d A.SIMD
*
*/
EAPI VDUP(eFQReg Qd, eReg Rt, u32 Size=32, ConditionCode CC=AL)
{
DECL_Id(0x0E800B10); SET_CC;
SET_Qd; SET_Rt; I |= (1<<21); // Q
if (Size==16) { I |= (1<<5); } // e
if (Size==8) { I |= (1<<22); } // b
EMIT_I;
}
EAPI VDUP(eFDReg Dd, eReg Rt, u32 Size=32, ConditionCode CC=AL)
{
DECL_Id(0x0E800B10); SET_CC;
SET_Dd; SET_Rt; // No Q
if (Size==16) { I |= (1<<5); } // e
if (Size==8) { I |= (1<<22); } // b
EMIT_I;
}
EAPI VDUP8 (eFQReg Qd, eReg Rt, ConditionCode=AL) { VDUP(Qd,Rt,8, CC); }
EAPI VDUP8 (eFDReg Dd, eReg Rt, ConditionCode=AL) { VDUP(Dd,Rt,8, CC); }
EAPI VDUP16(eFQReg Qd, eReg Rt, ConditionCode=AL) { VDUP(Qd,Rt,16,CC); }
EAPI VDUP16(eFDReg Dd, eReg Rt, ConditionCode=AL) { VDUP(Dd,Rt,16,CC); }
EAPI VDUP32(eFQReg Qd, eReg Rt, ConditionCode=AL) { VDUP(Qd,Rt,32,CC); }
EAPI VDUP32(eFDReg Dd, eReg Rt, ConditionCode=AL) { VDUP(Dd,Rt,32,CC); }
EAPI VDUP32(eFQReg Qd, eFDReg Dm, int idx)
{
DECL_Id(0xF3B00C00);
//Set_Qd seems to be incompitable here ?
I |= (((Qd<<1)&0x0E)<<12); \
I |= (((Qd<<1)&0x10)<<18);
SET_Dm;
I |= 0x40; //SET_Q
I |= 0x4 << 16; // 32 bits 4=0100
I |= (idx&1) << 19; // set idx
EMIT_I;
}
/*
* VMOV: (register)
*
* VMOV { <Qd, Qm> , <Dd, Dm> } A.SIMD
* VMOV { <Dd, Dm> , <Sd, Sm> } VFP sz1 UNDEFINED in single only VFP
*/
EAPI VMOV(eFQReg Qd, eFQReg Qm) // UNCONDITIONAL
{
DECL_Id(0xF2200110);
I |= ((Qd&0x0F)<<12) | ((Qd&0x10)<<18);
I |= ((Qm&0x0F)<<16) | ((Qm&0x10)<<1); // If !Consistent(M:Qm) then its VORR
I |= ((Qm&0x0F)) | ((Qm&0x10)<<3); // If !Consistent(M:Qm) then its VORR
EMIT_I;
}
EAPI VMOV(eFDReg Dd, eFDReg Dm) // UNCONDITIONAL
{
DECL_Id(0xF2200110);
I |= ((Dd&0x0F)<<12) | ((Dd&0x10)<<18);
I |= ((Dm&0x0F)<<16) | ((Dm&0x10)<<3); // If !Consistent(M:Dm) then its VORR
I |= ((Dm&0x0F)) | ((Dm&0x10)<<1); // If !Consistent(M:Dm) then its VORR
EMIT_I;
}
// EAPI VMOV(eFDReg Dd, eFDReg Dm, ConditionCode CC=AL) {} VFP Double Version Not Implemented here for obvious reasons : same as below except would set SZ @bit8 : 0x0EB00B40
EAPI VMOV(eFSReg Sd, eFSReg Sm, ConditionCode CC=AL)
{
DECL_Id(0x0EB00A40); SET_CC;
I |= ((Sd&0x1E)<<11) | ((Sd&1)<<22);
I |= ((Sm&0x1E)>>1) | ((Sm&1)<<5);
EMIT_I;
}
/*
* VMOV: (Immediate) A.SIMD / VFP
*
*/
//// TO BE IMPLEMENTED ////
/*
* VMOV: (ARM to scalar) A.SIMD / VFP IF Size=32
*
*/
EAPI VMOV(eFDReg Dd, u32 Index, eReg Rt, u32 Size=32, ConditionCode CC=AL)
{
DECL_Id(0x0E000B10); SET_CC;
SET_Dd; SET_Rt;
// Dd[x] where x==Index Dd is 64b, 2x32[0,1](1bit) 4x16[0-3](2bits) 8x8[0-7](3bits)
if (Size== 8) { I |= (1<<22) | ((Index&4)<<18) | ((Index&3)<<5) ; } // x -> opc1:0, opc2 (3bits) | opc1:1 SET
if (Size==16) { I |= (1<<5) | ((Index&2)<<20) | ((Index&1<<6)) ; } // x -> opc1:0, opc2:1 (2bits) | opc2:0 SET
if (Size==32) { I |= ((Index&1)<<21) ; } // x -> opc1:0 (1bit)
EMIT_I;
}
/*
* VMOV: (scalar to ARM) A.SIMD / VFP IF Size=32
*
* Note: U (bit32) is unsigned bit, invalid for 32b and we do not handle it at all.. might want to set it for byte,short
*/
EAPI VMOV(eReg Rt, eFDReg Dd, u32 Index, u32 Size=32, ConditionCode CC=AL) // This is really Vn, but we'll use the same macros..
{
DECL_Id(0x0E100B10); SET_CC;
SET_Dd; SET_Rt;
// Dd[x] where x==Index Dd is 64b, 2x32[0,1](1bit) 4x16[0-3](2bits) 8x8[0-7](3bits)
if (Size== 8) { I |= (1<<22) | ((Index&4)<<18) | ((Index&3)<<5) ; } // x -> opc1:0, opc2 (3bits) | opc1:1 SET
if (Size==16) { I |= (1<<5) | ((Index&2)<<20) | ((Index&1<<6)) ; } // x -> opc1:0, opc2:1 (2bits) | opc2:0 SET
if (Size==32) { I |= ((Index&1)<<21) ; } // x -> opc1:0 (1bit)
EMIT_I;
}
/*
* VMOV: (between ARM and single either direction) VFP
*
*/
EAPI VMOV(eReg Rt, eFSReg Sn, ConditionCode CC=AL) // Sn !d
{
DECL_Id(0x0E000A10); SET_CC;
SET_Sn; SET_Rt; I |= (1<<20); // op set = TO ARM reg
EMIT_I;
}
EAPI VMOV(eFSReg Sn, eReg Rt, ConditionCode CC=AL) // Sn !d
{
DECL_Id(0x0E000A10); SET_CC;
SET_Sn; SET_Rt; // op NOT set = TO FP Single reg
EMIT_I;
}
/*
* VMOV: (between two ARM regs and two contiguous singles either direction) VFP
*
*/
EAPI VMOV(eReg Rt, eReg Rt2, eFSReg Sm, ConditionCode CC=AL) // Sn !d
{
DECL_Id(0x0E000A10); SET_CC;
SET_Sm; SET_Rtx2; I |= (1<<20); // op set = TO ARM regs
EMIT_I;
}
EAPI VMOV(eFSReg Sm, eReg Rt, eReg Rt2, ConditionCode CC=AL) // Sn !d
{
DECL_Id(0x0E000A10); SET_CC;
SET_Sm; SET_Rtx2; // op NOT set = TO FP Single(s)
EMIT_I;
}
/*
* VMOV: (between two ARM regs and a Double) Dm <-> Rt2:Rt A.SIMD/VFP
*
*/
EAPI VMOV(eReg Rt, eReg Rt2, eFDReg Dm, ConditionCode CC=AL) // Sn !d
{
DECL_Id(0x0C400B10); SET_CC;
SET_Dm; SET_Rtx2; I |= (1<<20); // op set = TO ARM regs
EMIT_I;
}
EAPI VMOV(eFDReg Dm, eReg Rt, eReg Rt2, ConditionCode CC=AL) // Sn !d
{
DECL_Id(0x0C400B10); SET_CC;
SET_Dm; SET_Rtx2; // op NOT set = TO FP Single(s)
EMIT_I;
}
/*
* VMOVL: Takes each element in a VDouble && Sign or Zero extends into a VQuad A.SIMD
*
*/
EAPI VMOVL(eFQReg Qd, eFDReg Dm, u32 Size=32, u32 Sign=0) // UNCONDITIONAL Q & ~1
{
Size >>= 3; // Sz/8 = 1,2 or 4 else if >0 its VSHLL
Sign = (Sign>0)?0:1; // Invert to Unsigned
DECL_Id(0xF2800A10);
SET_Dm;
I |= ((Qd&0x0F)<<12);
I |= ((Qd&0x10)<<18);
I |= ((Size &7)<<19); // imm3
I |= ((Sign &1)<<24); // U
EMIT_I;
}
EAPI VMOVL_S8 (eFQReg Qd, eFDReg Dm) { VMOVL(Qd,Dm,8,1); }
EAPI VMOVL_U8 (eFQReg Qd, eFDReg Dm) { VMOVL(Qd,Dm,8,0); }
EAPI VMOVL_S16(eFQReg Qd, eFDReg Dm) { VMOVL(Qd,Dm,16,1); }
EAPI VMOVL_U16(eFQReg Qd, eFDReg Dm) { VMOVL(Qd,Dm,16,0); }
EAPI VMOVL_S32(eFQReg Qd, eFDReg Dm) { VMOVL(Qd,Dm,32,1); }
EAPI VMOVL_U32(eFQReg Qd, eFDReg Dm) { VMOVL(Qd,Dm,32,0); }
/*
* VMOVN: Copies least significant half of each element of a VQuad into the elements of a VDouble A.SIMD
*
*/
EAPI VMOVN(eFDReg Dd, eFQReg Qm, u32 Size=32) // UNCONDITIONAL Q & ~1
{
Size >>= 4; // Sz/32 = 0,1 or 2
DECL_Id(0xF3B20200);
SET_Qm;
I |= ((Dd&0x0F)<<12);
I |= ((Dd&0x10)<<18);
I |= ((Size &3)<<18); // size
EMIT_I;
}
EAPI VMOVN16(eFDReg Dd, eFQReg Qm) { VMOVN(Dd,Qm,16); }
EAPI VMOVN32(eFDReg Dd, eFQReg Qm) { VMOVN(Dd,Qm,32); }
EAPI VMOVN64(eFDReg Dd, eFQReg Qm) { VMOVN(Dd,Qm,64); }
/*
* VM{RS,SR} Move ARM reg To/From FPSCR A.SIMD/VFP
*/
EAPI VMRS(eReg Rt, ConditionCode CC=AL)
{
DECL_Id(0x0EF10A10);
SET_CC; SET_Rt;
EMIT_I;
}
EAPI VMSR(eReg Rt, ConditionCode CC=AL)
{
DECL_Id(0x0EE10A10);
SET_CC; SET_Rt;
EMIT_I;
}
#undef SET_Qd
#undef SET_Qm
#undef SET_Dd
#undef SET_Dm
#undef SET_Sn
#undef SET_Sm
#undef SET_Rn
#undef SET_Rt
#undef SET_Rtx2
};
+75
View File
@@ -0,0 +1,75 @@
/*
* H_Branches.h
*
*
*/
#pragma once
namespace ARM
{
inline static snat Literal(unat FnAddr)
{
u8* pc_addr = (u8*)EMIT_GET_PTR();
return (snat)((snat)FnAddr - ((snat)pc_addr+8));
//return -(snat)((pc_addr+8)-(snat)FnAddr);
}
EAPI CALL(unat FnAddr, ConditionCode CC=AL)
{
snat lit = Literal(FnAddr);
if(0==lit) {
printf("Error, Compiler caught NULL literal, CALL(%08X)\n", FnAddr);
verify(false);
return;
}
if( (lit<-33554432) || (lit>33554428) ) // ..28 for BL ..30 for BLX
{
printf("Warning, CALL(%08X) is out of range for literal(%08X)\n", FnAddr, lit);
// verify(false);
MOV32(IP, FnAddr, CC);
BLX(IP, CC);
return;
}
BL(lit,CC);
}
EAPI JUMP(unat FnAddr, ConditionCode CC=AL)
{
snat lit = Literal(FnAddr);
/*if(0==lit) {
printf("Error, Compiler caught NULL literal, JUMP(%08X)\n", FnAddr);
verify(false);
return;
}*/
if( (lit<-33554432) || (lit>33554428) ) // ..28 for BL ..30 for BLX
{
printf("Warning, %X is out of range for imm jump! \n", FnAddr);
//verify(false);
MOV32(IP, FnAddr, CC);
BX(IP, CC);
return;
}
B(lit,CC); // Note, wont work for THUMB*, have to use bx which is reg only !
}
}
+150
View File
@@ -0,0 +1,150 @@
/*
* H_LoadStore.h
*
*
*/
#pragma once
namespace ARM
{
/*
* Load Helpers
*/
EAPI LoadImmBase(eReg Rt, u32 Base, ConditionCode CC=AL)
{
MOV32(Rt, Base, CC);
#if defined(_DEVEL)
LDR(Rt,Rt,0, Offset, CC);
#else
LDR(Rt,Rt,0, CC);
#endif
}
EAPI LoadImmBase(eReg Rt, eReg Rn, u32 Base, ConditionCode CC=AL)
{
MOV32(Rn, Base, CC);
#if defined(_DEVEL)
LDR(Rt,Rn,0, Offset, CC);
#else
LDR(Rt,Rn,0, CC);
#endif
}
EAPI LoadImmBase16(eReg Rt, u32 Base, bool Extend=false, ConditionCode CC=AL)
{
MOV32(Rt, Base, CC);
LDRH(Rt,Rt,0, CC);
if(Extend)
SXTH(Rt,Rt);
}
EAPI LoadImmBase16(eReg Rt, eReg Rn, u32 Base, bool Extend=false, ConditionCode CC=AL)
{
MOV32(Rn, Base, CC);
LDRH(Rt,Rn,0, CC);
if(Extend)
SXTH(Rt,Rt);
}
/*
* Store Helpers
*/
// you pick regs, loads Base with reg addr, you supply data in Rt
EAPI StoreImmBase(eReg Rt, eReg Rn, u32 Base, ConditionCode CC=AL)
{
MOV32(Rn, Base, CC);
#if defined(_DEVEL)
STR(Rt,Rn,0, Offset, CC);
#else
STR(Rt,Rn,0, CC);
#endif
}
// you pick regs, loads Rt with const val, you supply base for Rn
EAPI StoreImmVal(eReg Rt, eReg Rn, u32 Val, ConditionCode CC=AL)
{
MOV32(Rt, Val, CC);
#if defined(_DEVEL)
STR(Rt,Rn,0, Offset, CC);
#else
STR(Rt,Rn,0, CC);
#endif
}
// you pick regs, loads Base with reg addr, loads Rt with const val
EAPI StoreImms(eReg Rt, eReg Rn, u32 Base, u32 Val, ConditionCode CC=AL)
{
MOV32(Rn, Base, CC);
MOV32(Rt, Val, CC);
#if defined(_DEVEL)
STR(Rt,Rn,0, Offset, CC);
#else
STR(Rt,Rn,0, CC);
#endif
}
#if defined(_DEVEL) && 0 // These require testing //
EAPI LoadImmBase8(eReg Rt, u32 Base, bool Extend=false, ConditionCode CC=AL)
{
MOV32(Rt, Base, CC);
LDRB(Rt,Rt,0, CC);
if(Extend)
SXTB(Rt,Rt);
}
EAPI LoadImmBase8(eReg Rt, eReg Rn, u32 Base, bool Extend=false, ConditionCode CC=AL)
{
MOV32(Rn, Base, CC);
LDRB(Rt,Rn,0, CC);
if(Extend)
SXTB(Rt,Rt);
}
#endif // defined(_DEVEL)
}
+102
View File
@@ -0,0 +1,102 @@
/*
* H_fp.h
*
* ARMv7 floating point help routines.
*/
#pragma once
/// WIP ///
namespace ARM
{
#if defined(_DEVEL)
/*
* vfpVersion(): Returns VFP Arch. Version, or -1 if not supported
*/
int vfpVersion()
{
// FPSID bits [22:16] contain version
return 0;
}
int neonVersion()
{
// ??
return 0;
}
#define VFP_SINGLE (1<<0)
#define VFP_DOUBLE (1<<1)
#define NEON_INTEGER (1<<2)
#define NEON_SINGLE (1<<3)
#define VFP_TRAPS (1<<8) // VFPv3U
#define FPEXT_HALF (1<<16) // Half precision extension
u32 fpFeatures()
{
return 0;
}
#endif // _DEVEL
#if 0
Version 1 of the Common VFP subarchitecture has special behavior when the FPSCR.IXE bit is set to 1.
The Common VFP subarchitecture version can be identified by checking FPSID bits [22:16]. This field is
0b0000001 for version 1. In version 1 of the Common VFP subarchitecture the FPEXC.DEX bit is RAZ/WI.
Detecting which VFP Common subarchitecture registers are implemented
An implementation can choose not to implement FPINST and FPINST2, if these registers are not required.
Set FPEXC.EX=1 and FPEXC.FP2V=1
Read back the FPEXC register
if FPEXC.EX == 0 then
Neither FPINST nor FPINST2 are implemented
else
if FPEXC.FP2V == 0 then
FPINST is implemented, FPINST2 is not implemented.
else
Both FPINST and FPINST2 are implemented.
Clean up
#endif
}
+29
View File
@@ -0,0 +1,29 @@
/*
* H_psuedo.h
*
*/
#pragma once
namespace ARM
{
EAPI MOV32(eReg Rd, u32 Imm32, ConditionCode CC=AL)
{
MOVW(Rd,((Imm32)&0xFFFF),CC);
if (Imm32>>16)
MOVT(Rd,((Imm32>>16)&0xFFFF),CC);
}
#if 0
EAPI NEG(eReg Rd,eReg Rs)
{
RSB(Rd,Rs,0);
}
#endif
EAPI NOT(eReg Rd,eReg Rs)
{
MVN(Rd,Rs);
}
}
+64
View File
@@ -0,0 +1,64 @@
/*
* H_state.h
*
*/
#pragma once
namespace ARM
{
enum InstructionSet {
IS_ARM,
IS_Thumb,
IS_Jazelle,
IS_ThumbEE
};
enum Endian {
E_Little,
E_Big
};
}
+254
View File
@@ -0,0 +1,254 @@
/*
* coding.h, arm binary instruction coding
*
*/
#pragma once
namespace ARM
{
/*
* Encoding Hi-Order 4bits, ConditionCode
*
*/
enum ConditionCode
{
EQ = 0x00, Equal = EQ, // 0000 Equal Z set
NE = 0x01, NotEqual = NE, // 0001 Not equal Z clear
CS = 0x02, CarrySet = CS, // 0010 Carry set/unsigned higher or same C set
CC = 0x03, CarryClr = CC, // 0011 Carry clear/unsigned lowe C clear
MI = 0x04, Minus = MI, // 0100 Minus/negative N set
PL = 0x05, Plus = PL, // 0101 Plus/positive or zero N clear
VS = 0x06, Overflow = VS, // 0110 Overflow V set
VC = 0x07, NoOverflow = VC, // 0111 No overflow V clear
HI = 0x08, UnHigher = HI, // 1000 Unsigned higher C set and Z clear
LS = 0x09, UnLower = LS, // 1001 Unsigned lower or same C clear or Z set
GE = 0x0A, GrOrEqual = GE, // 1010 Signed greater than or equal N set and V set, or N clear and V clear (N == V)
LT = 0x0B, Less = LT, // 1011 Signed less than N set and V clear, or N clear and V set (N != V)
GT = 0x0C, Greater = GT, // 1100 Signed greater than Z clear, and either N set and V set, or N clear and V clear (Z == 0,N == V)
LE = 0x0D, LessOrEqual = LE, // 1101 Signed less than or equal Z set, or N set and V clear, or N clear and V set (Z == 1 or N != V)
AL = 0x0E, Always = AL, // 1110 Always (unconditional) -
UC = 0x0F, Unconditional= UC, // 1111 Unconditional Special Instruction for ARMv5? and above
#define _ARM_COMPAT
#if defined(_ARM_COMPAT)
CC_EQ=EQ, CC_NE=NE, CC_CS=CS, CC_CC=CC, CC_MI=MI, CC_PL=PL, CC_VS=VS, CC_VC=VC,
CC_HI=HI, CC_LS=LS, CC_GE=GE, CC_LT=LT, CC_GT=GT, CC_LE=LE, CC_AL=AL, CC_UC=UC,
CC_HS=CS, CC_LO=CC,
#endif
ConditionCode_Size
};
/*
* Data-processing OPCODE 4bits, DPOP
*
*/
enum DPOP
{
DP_AND, // 0000 Logical AND Rd := Rn AND shifter_operand
DP_EOR, // 0001 Logical Exclusive OR Rd := Rn EOR shifter_operand
DP_SUB, // 0010 Subtract Rd := Rn - shifter_operand
DP_RSB, // 0011 Reverse Subtract Rd := shifter_operand - Rn
DP_ADD, // 0100 Add Rd := Rn + shifter_operand
DP_ADC, // 0101 Add with Carry Rd := Rn + shifter_operand + Carry Flag
DP_SBC, // 0110 Subtract with Carry Rd := Rn - shifter_operand - NOT(Carry Flag)
DP_RSC, // 0111 Reverse Subtract with Carry Rd := shifter_operand - Rn - NOT(Carry Flag)
DP_TST, // 1000 Test Update flags after Rn AND shifter_operand
DP_TEQ, // 1001 Test Equivalence Update flags after Rn EOR shifter_operand
DP_CMP, // 1010 Compare Update flags after Rn - shifter_operand
DP_CMN, // 1011 Compare Negated Update flags after Rn + shifter_operand
DP_ORR, // 1100 Logical (inclusive) OR Rd := Rn OR shifter_operand
DP_MOV, // 1101 Move Rd := shifter_operand (no first operand)
DP_BIC, // 1110 Bit Clear Rd := Rn AND NOT(shifter_operand)
DP_MVN // 1111 Move Not Rd := NOT shifter_operand (no first operand)
};
enum ShiftOp {
S_LSL,
S_LSR,
S_ASR,
S_ROR,
S_RRX=S_ROR
};
/*
* eReg: ARM Register ID
*
*/
enum eReg
{
r0=0,r1, r2, r3,
r4, r5, r6, r7,
r8, r9, r10, r11,
r12, r13, r14, r15,
R0=0,R1, R2, R3,
R4, R5, R6, R7,
R8, R9, R10, R11,
R12, R13, R14, R15,
// Aliases
a1 = r0, a2 = r1, a3 = r2, a4 = r3,
A1 = R0, A2 = R1, A3 = R2, A4 = R3,
v1 = r4, v2 = r5, v3 = r6, v4 = r7, v5 = r8, v6 = r9,
V1 = R4, V2 = R5, V3 = R6, V4 = R7, V5 = R8, V6 = R9,
rfp = r9, sl = r10, fp = r11, ip = r12, sp = r13, lr = r14, pc = r15,
RFP = R9, SL = R10, FP = R11, IP = R12, SP = R13, LR = R14, PC = R15,
};
/*
* eFQReg: Float [Quad] Register ID (A.SIMD)
*
*/
enum eFQReg
{
q0=0,q1, q2, q3,
q4, q5, q6, q7,
q8, q9, q10, q11,
q12, q13, q14, q15,
Q0=0,Q1, Q2, Q3,
Q4, Q5, Q6, Q7,
Q8, Q9, Q10, Q11,
Q12, Q13, Q14, Q15
};
/*
* eFDReg: Float [Double] Register ID (VFP / A.SIMD)
*
*/
enum eFDReg
{
d0=0,d1, d2, d3,
d4, d5, d6, d7,
d8, d9, d10, d11,
d12, d13, d14, d15,
d16, d17, d18, d19,
d20, d21, d22, d23,
d24, d25, d26, d27,
d28, d29, d30, d31,
D0=0,D1, D2, D3,
D4, D5, D6, D7,
D8, D9, D10, D11,
D12, D13, D14, D15,
D16, D17, D18, D19,
D20, D21, D22, D23,
D24, D25, D26, D27,
D28, D29, D30, D31
};
/*
* eFSReg: Float [Single] Register ID (VFP)
*
* Note: Using [f,F]regN syntax to avoid clash with s{8,16,32} types.
*/
enum eFSReg
{
f0=0,f1, f2, f3,
f4, f5, f6, f7,
f8, f9, f10, f11,
f12, f13, f14, f15,
f16, f17, f18, f19,
f20, f21, f22, f23,
f24, f25, f26, f27,
f28, f29, f30, f31,
F0=0,F1, F2, F3,
F4, F5, F6, F7,
F8, F9, F10, F11,
F12, F13, F14, F15,
F16, F17, F18, F19,
F20, F21, F22, F23,
F24, F25, F26, F27,
F28, F29, F30, F31
};
enum eFSpecialReg
{
// VM**
FPINST = 9,
FPINST2=10,
FP_R_ERROR=0xFF
};
enum ePushPopReg
{
_r0 =0x0001, _r1 =0x0002, _r2 =0x0004, _r3 =0x0008,
_r4 =0x0010, _r5 =0x0020, _r6 =0x0040, _r7 =0x0080,
_r8 =0x0100, _r9 =0x0200, _r10=0x0400, _r11=0x0800,
_r12=0x1000, _r13=0x2000, _r14=0x4000, _r15=0x8000,
_a1 = _r0, _a2 = _r1, _a3 = _r2, _a4 = _r3,
_v1 = _r4, _v2 = _r5, _v3 = _r6, _v4 = _r7,
_v5 = _r8, _v6 = _r9, _rfp = _r9, _sl = _r10,
_fp = _r11, _ip = _r12, _sp = _r13, _lr = _r14,
_pc = _r15,
_push_all = 0xFFFF, // Save All 15
_push_call = _lr|_rfp, // Save lr && _rfb(cycle count)
_push_eabi = _lr|_v1|_v2|_v3|_v4|_v5|_v6|_sl|_fp|_ip, // this is guesswork ..
};
/// WIP ///
struct FPReg
{
union
{
u8 vQ8[16];
u8 vD8[8];
u8 vS8[4];
u16 vQ16[8]; // *VFP: If half-word extensions are enabled
u16 vD16[4]; // *VFP: If half-word extensions are enabled
u16 vS16[2]; // *VFP: If half-word extensions are enabled
u32 vQ32[4];
u32 vD32[2];
u32 S;
// u64 vQ64[2];
// u64 D;
};
};
};
+195
View File
@@ -0,0 +1,195 @@
/*
* disasm.h, a horribly static yet (hopefully) correct disassembler
*
*/
#pragma once
namespace ARM
{
inline static void armdis_cc(u32 cond, char *ccbuff) // Length is always 8 for our static'{n,m}ess
{
switch(cond)
{
case EQ: sprintf(ccbuff, "EQ"); return;
case NE: sprintf(ccbuff, "NE"); return;
case CS: sprintf(ccbuff, "CS"); return;
case CC: sprintf(ccbuff, "CC"); return;
case MI: sprintf(ccbuff, "MI"); return;
case PL: sprintf(ccbuff, "PL"); return;
case VS: sprintf(ccbuff, "VS"); return;
case VC: sprintf(ccbuff, "VC"); return;
case HI: sprintf(ccbuff, "HI"); return;
case LS: sprintf(ccbuff, "LS"); return;
case GE: sprintf(ccbuff, "GE"); return;
case LT: sprintf(ccbuff, "LT"); return;
case GT: sprintf(ccbuff, "GT"); return;
case LE: sprintf(ccbuff, "LE"); return;
case AL: return; // sprintf(ccbuff, "AL"); -- ALways doesn't need to be specified
case UC: //
default: return; // DIE
}
}
inline static void armdis_dp(u32 dpop, char *dpbuff) // Length is always 8 ...
{
switch(dpop)
{
case DP_AND: sprintf(dpbuff, "AND"); return;
case DP_EOR: sprintf(dpbuff, "EOR"); return;
case DP_SUB: sprintf(dpbuff, "SUB"); return;
case DP_RSB: sprintf(dpbuff, "RSB"); return;
case DP_ADD: sprintf(dpbuff, "ADD"); return;
case DP_ADC: sprintf(dpbuff, "ADC"); return;
case DP_SBC: sprintf(dpbuff, "SBC"); return;
case DP_RSC: sprintf(dpbuff, "RSC"); return;
case DP_TST: sprintf(dpbuff, "TST"); return;
case DP_TEQ: sprintf(dpbuff, "TEQ"); return;
case DP_CMP: sprintf(dpbuff, "CMP"); return;
case DP_CMN: sprintf(dpbuff, "CMN"); return;
case DP_ORR: sprintf(dpbuff, "ORR"); return;
case DP_MOV: sprintf(dpbuff, "MOV"); return;
case DP_BIC: sprintf(dpbuff, "BIC"); return;
case DP_MVN: sprintf(dpbuff, "MVN"); return;
}
}
inline static void armdis(u32 op, char *disbuf, u32 len=512)
{
char ipref[8]={0}, isuff[8]={0}, icond[8]={0} ;
// u32 uOP = ((op>>12)&0xFF00) | ((op>>4)&255) ;
u32 uCC = ((op>>28) & 0x0F) ; //
u32 uO1 = ((op>>25) & 0x07) ; //
u32 uO2 = ((op>> 4) & 0x01) ; //
u32 uC1 = ((op>>21) & 0x0F) ; //
u32 uC2 = ((op>> 5) & 0x07) ; //
u32 uSB = ((op>>20) & 0x01) ; // Sign Change Bit
if (uCC == UC) {
printf ("DBG armdis has UC instruction %X\n", op);
sprintf (disbuf, "UNCONDITIONAL / UNHANDLED INSTRUCTION");
return;
}
if (uCC != AL) {
armdis_cc(uCC,isuff);
}
if (uO1 == 0)
{
if (uO2 == 0) {
if ((uC1 & 0xC) == 8) {
printf ("DBG armdis 0:0 10xx misc instruction \n", uCC);
sprintf (disbuf, "UNHANDLED INSTRUCTION 0:");
return;
}
// DP imm.shift
}
else if (uO2 == 1) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 0:");
}
}
else if (uO1 == 1) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 1:");
}
else if (uO1 == 2) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 2:");
}
else if (uO1 == 3) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 3:");
}
else if (uO1 == 4) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 4:");
}
else if (uO1 == 5) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 5:");
}
else if (uO1 == 6) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 6:");
}
else if (uO1 == 7) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 7:");
}
else if (uO1 == 8) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 8:");
}
else if (uO1 == 9) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 9:");
}
else if (uO1 == 10) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 10:");
}
else if (uO1 == 11) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 11:");
}
else if (uO1 == 12) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 12:");
}
else if (uO1 == 13) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 13:");
}
else if (uO1 == 14) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 14:");
}
else if (uO1 == 15) {
sprintf (disbuf, "UNHANDLED INSTRUCTION 15:");
}
else {
sprintf (disbuf, "INVALID INSTRUCTION");
}
}
};
+128
View File
@@ -0,0 +1,128 @@
/*
* Emitter.h
*
* ARMv7 ISA Emitter for code generation.
*
* David Miller, 2011.
*/
#pragma once
#include "arm_coding.h"
#include "arm_registers.h"
//#include "arm_disasm.h"
namespace ARM
{
/*
* Emitter - Reserved for use w/ static members ..
*
*
*/
class Emitter
{
};
#if defined(_DEBUG) || defined(DEBUG)
#define EAPI void
#define DECL_I \
u32 Instruction=0
#define DECL_Id(d) \
u32 Instruction=(d)
#else
// #define _inlineExSVoidA __extension__ static __inline void __attribute__ ((__always_inline__))
#define EAPI \
inline static void
#define DECL_I \
static u32 Instruction; \
Instruction=0
#define DECL_Id(d) \
static u32 Instruction; \
Instruction=(d)
#endif
/*
* TEMP
*/
#define I (Instruction)
#define SET_CC I |= (((u32)CC&15)<<28)
#ifndef EMIT_I
#define EMIT_I emit_Write32((I));
#endif
#ifndef EMIT_GET_PTR
#define EMIT_GET_PTR() emit_GetCCPtr()
#endif
};
/*
* ARM Core Instructions
*/
#include "E_Branches.h"
#include "E_DataOp.h"
#include "E_Multiply.h"
#include "E_Parallel.h"
#include "E_Extend.h"
#include "E_Misc.h"
#include "E_Status.h"
#include "E_LoadStore.h"
#include "E_Special.h"
/*
* ARM VFP/A.SIMD Extension Instructions
*/
#include "E_VLoadStore.h"
#include "E_VRegXfer.h"
#include "E_VDataOp.h"
/*
* Helper Routines & Psuedo-Instructions
*/
#include "H_psuedo.h"
#include "H_Branches.h"
#include "H_LoadStore.h"
//#include "H_state.h"
//#include "H_fp.h"
+487
View File
@@ -0,0 +1,487 @@
/*
* registers.h
*
* ARMv7-A system register(s).
*/
#pragma once
namespace ARM
{
/*************************************************************************************************
* CP15 Registers for VMSA Implementation. [ref.DDI0406B B3.12]
*************************************************************************************************/
/*
<CRn> <opc1> <CRm> <opc2> [NAME,] Description [Flags]
c0 {
0 c0 {
0 MIDR, Main ID RO
1 CTR, Cache Type RO
2 TCMTR, TCM Type RO, IMPL.DEFINED
3 TLBTR, TLB Type RO, IMPL.DEFINED
5 MPIDR, Multiprocessor Affinity RO
{4,6,7} MIDR$, Main ID Aliases RO
}
0 c[1-7] [0-7] CPUID ID_{PFRn,DFRn,AFR0,MMFRn,ISARn} RO
1 c0 0 CCSIDR, Cache Size ID RO
1 c0 1 CLIDR, Cache Level ID RO
1 c0 7 AIDR, Aux ID RO, IMPL.DEFINED
2 c0 0 CSSELR, Cache Size Selection RW
}
c1 0 c0 [0-2] System Control RW
c1 0 c1 [0-2] Security Extension RW, IMPL.OPTIONAL
c2 0 c0 [0-2] Translation Table Base RW
c3 0 c0 0 DACR, Domain Access Control RW
c5 0 c{0,1} {0,1} Fault Status RW
c6 0 c0 {0,2] Fault Address RW
c7 0 {
c0 4 NOP WO
c1 {0,6} Cache Maintenance operations, Multiprocessing Extensions WO
c4 0 PAR, Physical Address RW
c5 {0,1,6,7} Cache and branch predictor maintenance operations WO
c5 4 CP15ISB, Instruction barrier operation WO, USER
c6 {1,2} Cache Maintenance operations WO
c8 [0-7] VA to PA translation ops. WO
c10 {1,2} Cache management ops. WO
c10 {4,5} Data barrier ops. WO, USER
c11 1 DCCMVAU, Cache barrier ops. WO
c13 1 NOP WO
c14 {1,2} Cache management ops. WO
}
c8 0 c{3,5,6,7} [0-3] TLB maintenance ops. * WO
c9 [0-7] c{0,2,5,8} [0-7] Reserved for Branch Predictor, Cache and TCM ops. RSVD, OP.ACCESS
c9 [0-7] c[12-15] [0-7] Reserved for Performance monitors. RSVD, OP.ACCESS
c10 0 c{0,1,4,8} [0-7] Reserved for TLB lockdown ops. RSVD, OP.ACCESS
c10 0 c2 {0,1} PRRR, NMRRR, TEX Remap RW
c11 [0-7] c{0,8,15} [0-7] Reserved for DMA ops. TCM access. RSVD, OP.ACCESS
c12 0 c0 {0,1} Security Extensions RW, IMPL.OPTIONAL
c12 0 c1 0 ISR, Security Extensions RO, IMPL.OPTIONAL
c13 0 c0 0 FCSEIDR, FCSE PID RO-if-FCSE-!IMPL / RW?
c13 0 c0 [1-4] Software Thread and Context ID RW
c15 * * * IMPLEMENTATION DEFINED IMPL.DEFINED
*/
/*************************************************************************************************
* CP15 c0: ID codes registers
*************************************************************************************************/
/*
* MIDR: Main ID Register
*/
struct MIDR
{
u32 Revision : 4;
u32 PriPartNum : 12; // IF Impl:ARM && PriPartNo top 4bits are 0 || 7: arch&variant encoding differs
u32 Architecture : 4;
u32 Variant : 4;
u32 Implementer : 8;
};
enum MIDR_Implementer
{
ARM_Ltd = 0x41, // 'A'
DigitalEquipment_Corp = 0x44, // 'D'
Motorola_FreescaleSemi_Inc = 0x4D, // 'M'
QUALCOMM_Inc = 0x51, // 'Q'
MarvellSemi_Inc = 0x56, // 'V'
Intel_Corp = 0x69, // 'i'
TexasInstruments_Inc = 0xFF // 'T' ???
};
enum MIDR_Arch
{
ARMv4 = 1,
ARMv4T = 2,
ARMv5 = 3, // obselete
ARMv5T = 4,
ARMv5TE = 5,
ARMv5TEJ = 6,
ARMv6 = 7,
CPUID_Defined = 15
};
/*
* CTR, Cache Type Register
*/
struct CTR
{
u32 IminLine : 4;
u32 SBZ : 10;
u32 L1Ip : 2;
u32 DminLine : 4; //
u32 ERG : 4; // Exclusives Reservation Granule.
u32 CWG : 4; // Cache Writeback Granule.
u32 RAZ : 1;
u32 REGFMT : 3; // Set to 0b100 for ARMv7 register format, or 0b000 for <=ARMv6 format
};
/*
* TCMTR, TCM Type Register
*/
// High 3 bits is 0b100, the rest is IMPL.DEFINED
typedef u32 TCMTR;
/*
* TLBTR, TLB Type Register
*/
// Low bit is nU : SET:1: Not unified ( separate instruction and data TLBs )
typedef u32 TLBTR;
/*
* MPIDR, Multiprocessor Affinity Register
*/
struct MPIDR
{
u32 AffinityLevel0 : 8;
u32 AffinityLevel1 : 8;
u32 AffinityLevel2 : 8;
u32 MT : 1;
u32 RAZ : 5; // Reserved As Zero
u32 U : 1; // Set: Processor is part of a Uniprocessor system.
u32 MP_Impl : 1; // RAO if MP Extensions are implemented.
};
/*
* CCSIDR, Cache Size ID Registers
*/
struct CCSIDR
{
u32 LineSize : 3;
u32 Associativity : 10;
u32 NumSets : 15;
u32 WA : 1;
u32 RA : 1;
u32 WB : 1;
u32 WT : 1;
};
/*
* CLIDR, Cache Level ID Register
*/
struct CLIDR
{
u32 Ctype1 : 3;
u32 Ctype2 : 3;
u32 Ctype3 : 3;
u32 Ctype4 : 3;
u32 Ctype5 : 3;
u32 Ctype6 : 3;
u32 Ctype7 : 3;
u32 LoUIS : 3;
u32 LoC : 3;
u32 LoUU : 3;
u32 RAZ : 2; // RAZ
};
/*
* AIDR, Auxiliary ID Register.
*/
typedef u32 AIDR; // IMPLEMENTATION DEFINED
/*
* CSSELR, Cache Size Selection Register
*/
struct CSSELR
{
u32 InD : 1;
u32 Level : 3;
u32 SBZP : 28;
};
/*************************************************************************************************
* CP15 c1: System control registers
*************************************************************************************************/
// SCTRL, ACTLR ////////////////////// TODO ///////////////////////
/*
* CPACR: Coprocessor Access Control Register.
*
* Controls access to all coprocessors other than CP14 & CP15.
* It may be used to check for their presence by testing modification to cpN bits.
*
* Notes:
*
* D32DIS:1 && ASEDIS:0 is INVALID
* ASEDIS on hw { w. VFP & w.o A.SIMD } is RAO/WI, if bit is not supported it is RAZ/WI.
*
* When Security Extensions are enabled, NSACR controls CP access from non-secure state.
*
* VFP uses CP10 && CP11, the values of .cp10 && .cp11 should be the same.
*/
union CPACR
{
struct {
u32 cp0 : 2; // cpN [0-13]:
u32 cp1 : 2; // Defines access rights for individual coprocessors.
u32 cp2 : 2; // See CP_Access enum below for possible values;
u32 cp3 : 2; //
u32 cp4 : 2; // To test
u32 cp5 : 2;
u32 cp6 : 2;
u32 cp7 : 2;
u32 cp8 : 2;
u32 cp9 : 2;
u32 cp10 : 2;
u32 cp11 : 2;
u32 cp12 : 2;
u32 cp13 : 2;
u32 rsvcd: 2; // SBZP
u32 D32DIS:1; // SET: Disables use of D16-D32 of the VFP register file.
u32 ASEDIS:1; // SET: Disables all A.SIMD Instructions, VFPv3 shall remain valid.
};
u32 R;
};
/*
* CP_Access: Enumerates access rights for CPACR.cpN
*
*/
enum CP_Access
{
A_Deny, // Deny Access, Attempts to access cause Exception::Undefined_Instruction
A_Privileged, // Privileged Access, Attempts to access cause Exception::Undefined_Instruction in User mode.
A_Reserved, // Reserved Value, Use of this value is UNPREDICTABLE.
A_Full // Full Access, Access is defined by coprocessor.
};
/*
* SCR: Secure Configuration Register.
*
* Requires: Security Extension.
*/
union SCR
{
struct {
u32 NS : 1; //
u32 IRQ : 1; //
u32 FIQ : 1; //
u32 EA : 1; //
u32 FW : 1; //
u32 AW : 1; //
u32 nET : 1; //
u32 SBZP:25;
};
u32 R;
};
// SDER, Secure Debug Enable Register
// NSACR, Non-Secure Access Control Register
/*************************************************************************************************
* CP15 c{2,3}: Memory protection and control registers
*************************************************************************************************/
// TTBR0 TTVR1 TTVCR
// DACR, Domain Access Control Register
/*************************************************************************************************
* CP15 c4: Not used
*************************************************************************************************/
/*************************************************************************************************
* CP15 c{5,6}: Memory system fault registers
*************************************************************************************************/
// DFSR, Data Fault Status Register
// IFSR, Instruction Fault Status Register
// ADFSR, Aux. DFSR
// AIFSR, Aux. IFSR
// DFAR, Data Fault Address Register
// IFAR, Instruction Fault Address Register
/*************************************************************************************************
* CP15 c7: Cache maintenance / misc
*************************************************************************************************/
/*************************************************************************************************
*************************************************************************************************
* A.SIMD and VFP extension system registers
*************************************************************************************************
*************************************************************************************************/
enum FP_SysRegs
{
R_FPSID = 0, // 0b0000
R_MVFR1 = 6, // 0b0110
R_MVFR0 = 7, // 0b0111
};
// FPSID Floating Point System ID Register
// MVFR1 Media and VFP Feature Register 1
// MVFR0 Media and VFP Feature Register 0
struct FPSID
{
u32 Revision : 4; // IMPL.DEFINED
u32 Variant : 4; // IMPL.DEFINED
u32 PartNumber : 8; // IMPL.DEFINED
u32 SubArch : 7; // MSB:1 when designed by ARM
u32 SW : 1; // Is a software impl. if set
u32 Implementer : 8; // Same as MIDR.Implementer
};
enum FP_SubArch
{
VFPv1 = 0, // Not Permitted in ARMv7
VFPv2_Cv1, // Not Permitted in ARMv7
VFPv3_Cv2, //
VFPv3_Null, // Full hardware, no trap
VFPv3_Cv3, //
};
// Floating-point status and control register
//
struct FPSCR
{
u32 IOC : 1; // * All * bits are cumulative exception bits
u32 DZC : 1; // *
u32 OFC : 1; // *
u32 UFC : 1; // *
u32 IXC : 1; // *
u32 SBZP1 : 2; //
u32 IDC : 1; // *
u32 IOE : 1; // ** All ** bits are FP trap enable bits
u32 DZE : 1; // ** only supported in VFPv2 && VFPv3U
u32 OFE : 1; // ** - RAZ elsewhere -
u32 UFE : 1; // **
u32 IXE : 1; // **
u32 SBZP2 : 2; //
u32 IDE : 1; // **
u32 Len : 3; // SBZ for ARMv7 VFP, ignored for A.SIMD
u32 SBZP3 : 1; //
u32 Stride : 2; // SBZ for ARMv7 VFP, ignored for A.SIMD
u32 RMode : 2; // Rounding Mode
u32 FZ : 1; // Flush-to-Zero
u32 DN : 1; // Default NaN mode control
u32 AHP : 1; // Alt. Half-precision
u32 QC : 1; // Cumulative saturation, A.SIMD
u32 V : 1; // CC Overflow
u32 C : 1; // CC Carry
u32 Z : 1; // CC Zero
u32 N : 1; // CC Negative
};
enum FP_RoundingMode // A.SIMD Always uses RN !
{
RN, // Round to Nearest
RP, // Round towards Plus Infinity
RM, // Round towards Minus Infinity
RZ // Round towards Zero
};
struct MVFR0
{
u32 A_SIMD : 4;
u32 Single : 4;
u32 Double : 4;
u32 Trap : 4;
u32 Divide : 4;
u32 Sqrt : 4;
u32 ShortVec: 4;
u32 Rounding: 4;
};
struct MVFR1
{
u32 FtZ_mode : 4;
u32 D_NaN_mode : 4;
u32 NFP_LdStr : 4;
u32 NFP_int : 4;
u32 NFP_SPFP : 4;
u32 NFP_HPFP : 4;
u32 VFP_HPFP : 4;
u32 RAZ : 4;
};
};
+71
View File
@@ -0,0 +1,71 @@
/*
nullDC-Beagle build configuration options
fine grained options
HOST_OS,HOST_CPU, ..
build-level options
TARGET_BEAGLE, TARGET_WIN86, ...
code shoudn't depend on build level options whenever possible
*/
//ndc configs
#define NO_MMU
//#define HOST_NO_REC
#define DC_PLATFORM_MASK 7
#define DC_PLATFORM_NORMAL 0 /* Works, for the most part */
#define DC_PLATFORM_DEV_UNIT 1 /* This is missing hardware */
#define DC_PLATFORM_NAOMI 2 /* Works, for the most part */
#define DC_PLATFORM_NAOMI2 3 /* Needs to be done, 2xsh4 + 2xpvr + custom TNL */
#define DC_PLATFORM_ATOMISWAVE 4 /* Needs to be done, DC-like hardware with possibly more ram */
#define DC_PLATFORM_HIKARU 5 /* Needs to be done, 2xsh4, 2x aica , custom vpu */
#define DC_PLATFORM_AURORA 6 /* Needs to be done, Uses newer 300 mhz sh4 + 150 mhz pvr mbx SoC */
#define DC_PLATFORM DC_PLATFORM_NORMAL
//Target platform configs
//HOST_OS
#define OS_WINDOWS 0x10000001
#define OS_LINUX 0x10000002
//HOST_CPU
#define CPU_X86 0x20000001
#define CPU_ARM 0x20000002
#define CPU_MIPS 0x20000003
//BUILD_COMPILER
#define COMPILER_VC 0x30000001
#define COMPILER_GCC 0x30000002
///
#if (!defined(TARGET_WIN86) && !defined(TARGET_BEAGLE) && !defined(TARGET_NACL32) && !defined(TARGET_GCW0))
#define TARGET_WIN86
#endif
#ifdef TARGET_WIN86
#define HOST_OS OS_WINDOWS
#define HOST_CPU CPU_X86
#define BUILD_COMPILER COMPILER_VC
#elif TARGET_BEAGLE
#define HOST_OS OS_LINUX
#define HOST_CPU CPU_ARM
#define BUILD_COMPILER COMPILER_GCC
#elif TARGET_GCW0
#define HOST_OS OS_LINUX
#define HOST_CPU CPU_MIPS
#define BUILD_COMPILER COMPILER_GCC
#elif TARGET_NACL32
#define HOST_OS OS_LINUX
#define HOST_CPU CPU_X86
#define BUILD_COMPILER COMPILER_GCC
#else
#error Invalid Target: TARGET_* not defined
#endif
+435
View File
@@ -0,0 +1,435 @@
/*
Config file crap
Supports various things, as virtual config entries and such crap
Works suprisingly well considering how old it is ...
*/
#define _CRT_SECURE_NO_DEPRECATE (1)
#include "cfg.h"
string cfgPath;
//A config remains virtual only as long as a write at it
//doesnt override the virtual value.While a config is virtual, a copy of its 'real' value is held and preserved
//Is this a virtual entry ?
#define CEM_VIRTUAL 1
//Should the value be saved ?
#define CEM_SAVE 2
//is this entry readonly ?
#define CEM_READONLY 4
//the move is from loading ?
#define CEM_LOAD 8
struct ConfigEntry
{
ConfigEntry(ConfigEntry* pp)
{
next=pp;
flags=0;
}
u32 flags;
string name;
string value;
string valueVirtual;
ConfigEntry* next;
void SaveFile(FILE* file)
{
if (flags & CEM_SAVE)
fprintf(file,"%s=%s\n",name.c_str(),value.c_str());
}
string GetValue()
{
if (flags&CEM_VIRTUAL)
return valueVirtual;
else
return value;
}
};
struct ConfigSection
{
u32 flags;
string name;
ConfigEntry* entrys;
ConfigSection* next;
ConfigSection(ConfigSection* pp)
{
next=pp;
flags=0;
entrys=0;
}
ConfigEntry* FindEntry(string name)
{
ConfigEntry* c= entrys;
while(c)
{
if (stricmp(name.c_str(),c->name.c_str())==0)
return c;
c=c->next;
}
return 0;
}
void SetEntry(string name,string value,u32 eflags)
{
ConfigEntry* c=FindEntry(name);
if (c)
{
//readonly is read only =)
if (c->flags & CEM_READONLY)
return;
//virtual : save only if different value
if (c->flags & CEM_VIRTUAL)
{
if(stricmp(c->valueVirtual.c_str(),value.c_str())==0)
return;
c->flags&=~CEM_VIRTUAL;
}
}
else
{
entrys=c= new ConfigEntry(entrys);
c->name=name;
}
verify(!(c->flags&(CEM_VIRTUAL|CEM_READONLY)));
//Virtual
//Virtual | ReadOnly
//Save
if (eflags & CEM_VIRTUAL)
{
verify(!(eflags & CEM_SAVE));
c->flags|=eflags;
c->valueVirtual=value;
}
else if (eflags & CEM_SAVE)
{
verify(!(eflags & (CEM_VIRTUAL|CEM_READONLY)));
flags|=CEM_SAVE;
c->flags|=CEM_SAVE;
c->value=value;
}
else
{
die("Invalid eflags value");
}
}
~ConfigSection()
{
ConfigEntry* n=entrys;
while(n)
{
ConfigEntry* p=n;
n=n->next;
delete p;
}
}
void SaveFile(FILE* file)
{
if (flags&CEM_SAVE)
{
fprintf(file,"[%s]\n",name.c_str());
vector<ConfigEntry*> stuff;
ConfigEntry* n=entrys;
while(n)
{
stuff.push_back(n);
n=n->next;
}
for (int i=stuff.size()-1;i>=0;i--)
{
stuff[i]->SaveFile(file);
}
fprintf(file,"\n");
}
}
};
struct ConfigFile
{
ConfigSection* entrys;
ConfigSection* FindSection(string name)
{
ConfigSection* c= entrys;
while(c)
{
if (stricmp(name.c_str(),c->name.c_str())==0)
return c;
c=c->next;
}
return 0;
}
ConfigSection* GetEntry(string name)
{
ConfigSection* c=FindSection(name);
if (!c)
{
entrys=c= new ConfigSection(entrys);
c->name=name;
}
return c;
}
~ConfigFile()
{
ConfigSection* n=entrys;
while(n)
{
ConfigSection* p=n;
n=n->next;
delete p;
}
}
void PaseFile(FILE* file)
{
}
void SaveFile(FILE* file)
{
vector<ConfigSection*> stuff;
ConfigSection* n=entrys;
while(n)
{
stuff.push_back(n);
n=n->next;
}
for (int i=stuff.size()-1;i>=0;i--)
{
if (stuff[i]->name!="emu")
stuff[i]->SaveFile(file);
}
}
};
ConfigFile cfgdb;
void savecfgf()
{
FILE* cfgfile = fopen(cfgPath.c_str(),"wt");
if (!cfgfile)
printf("Error : Unable to open file for saving \n");
else
{
cfgdb.SaveFile(cfgfile);
fclose(cfgfile);
}
}
void cfgSaveStr(const wchar * Section, const wchar * Key, const wchar * String)
{
cfgdb.GetEntry(Section)->SetEntry(Key,String,CEM_SAVE);
savecfgf();
//WritePrivateProfileString(Section,Key,String,cfgPath);
}
//New config code
/*
I want config to be realy flexible .. so , here is the new implementation :
Functions :
cfgLoadInt : Load an int , if it does not exist save the default value to it and return it
cfgSaveInt : Save an int
cfgLoadStr : Load a str , if it does not exist save the default value to it and return it
cfgSaveStr : Save a str
cfgExists : Returns true if the Section:Key exists. If Key is null , it retuns true if Section exists
Config parameters can be readed from the config file , and can be given at the command line
-cfg section:key=value -> defines a value at command line
If a cfgSave* is made on a value defined by command line , then the command line value is replaced by it
cfg values set by command line are not writen to the cfg file , unless a cfgSave* is used
There are some special values , all of em are on the emu namespace :)
These are readonly :
emu:AppPath : Returns the path where the emulator is stored
emu:PluginPath : Returns the path where the plugins are loaded from
emu:DataPath : Returns the path where the bios/data files are
emu:FullName : str,returns the emulator's name + version string (ex."nullDC v1.0.0 Private Beta 2 built on {datetime}")
emu:ShortName : str,returns the emulator's name + version string , short form (ex."nullDC 1.0.0pb2")
emu:Name : str,returns the emulator's name (ex."nullDC")
These are read/write
emu:Caption : str , get/set the window caption
*/
///////////////////////////////
/*
** This will verify there is a working file @ ./szIniFn
** - if not present, it will write defaults
*/
struct vitem
{
string s;
string n;
string v;
vitem(string a,string b,string c){s=a;n=b;v=c;}
};
vector<vitem> vlist;
wchar* trim_ws(wchar* str);
bool cfgOpen()
{
cfgPath=GetPath("/emu.cfg");
FILE* cfgfile = fopen(cfgPath.c_str(),"r");
if(!cfgfile) {
cfgfile = fopen(cfgPath.c_str(),"wt");
if(!cfgfile)
printf("Unable to open the config file for reading or writing\nfile : %s\n",cfgPath.c_str());
else
{
fseek(cfgfile,0,SEEK_SET);
fclose(cfgfile);
cfgfile = fopen(cfgPath.c_str(),"r");
if(!cfgfile)
printf("Unable to open the config file for reading\nfile : %s\n",cfgPath.c_str());
}
}
wchar line[512];
wchar cur_sect[512]={0};
int cline=0;
while(cfgfile && !feof(cfgfile))
{
fgets(line,512,cfgfile);
if (feof(cfgfile))
break;
cline++;
if (strlen(line)<3)
continue;
if (line[strlen(line)-1]=='\r' || line[strlen(line)-1]=='\n')
line[strlen(line)-1]=0;
wchar* tl=trim_ws(line);
if (tl[0]=='[' && tl[strlen(tl)-1]==']')
{
tl[strlen(tl)-1]=0;
strcpy(cur_sect,tl+1);
trim_ws(cur_sect);
}
else
{
if (cur_sect[0]==0)
continue;//no open section
wchar* str1=strstr(tl,"=");
if (!str1)
{
printf("Malformed entry on cfg, ignoring @ %d(%s)\n",cline,tl);
continue;
}
*str1=0;
str1++;
wchar* v=trim_ws(str1);
wchar* k=trim_ws(tl);
if (v && k)
{
ConfigSection*cs=cfgdb.GetEntry(cur_sect);
//if (!cs->FindEntry(k))
cs->SetEntry(k,v,CEM_SAVE|CEM_LOAD);
}
else
{
printf("Malformed entry on cfg, ignoring @ %d(%s)\n",cline,tl);
}
}
}
for (size_t i=0;i<vlist.size();i++)
{
cfgdb.GetEntry(vlist[i].s)->SetEntry(vlist[i].n,vlist[i].v,CEM_VIRTUAL);
}
if (cfgfile)
{
cfgdb.SaveFile(cfgfile);
fclose(cfgfile);
}
return true;
}
//Implementations of the interface :)
//Section must be set
//If key is 0 , it looks for the section
//0 : not found
//1 : found section , key was 0
//2 : found section & key
s32 cfgExists(const wchar * Section, const wchar * Key)
{
if (Section==0)
return -1;
//return cfgRead(Section,Key,0);
ConfigSection*cs= cfgdb.FindSection(Section);
if (cs == 0)
return 0;
if (Key==0)
return 1;
ConfigEntry* ce=cs->FindEntry(Key);
if (ce!=0)
return 2;
else
return 0;
}
void cfgLoadStr(const wchar * Section, const wchar * Key, wchar * Return,const wchar* Default)
{
verify(Section!=0 && strlen(Section)!=0);
verify(Key!=0 && strlen(Key)!=0);
verify(Return!=0);
if (Default==0)
Default="";
ConfigSection* cs= cfgdb.GetEntry(Section);
ConfigEntry* ce=cs->FindEntry(Key);
if (!ce)
{
cs->SetEntry(Key,Default,CEM_SAVE);
strcpy(Return,Default);
}
else
{
strcpy(Return,ce->GetValue().c_str());
}
}
//These are helpers , mainly :)
s32 cfgLoadInt(const wchar * Section, const wchar * Key,s32 Default)
{
wchar temp_d[30];
wchar temp_o[30];
sprintf(temp_d,"%d",Default);
cfgLoadStr(Section,Key,temp_o,temp_d);
return atoi(temp_o);
}
void cfgSaveInt(const wchar * Section, const wchar * Key, s32 Int)
{
wchar tmp[32];
sprintf(tmp,"%d", Int);
cfgSaveStr(Section,Key,tmp);
}
void cfgSetVitual(const wchar * Section, const wchar * Key, const wchar * String)
{
vlist.push_back(vitem(Section,Key,String));
//cfgdb.GetEntry(Section,CEM_VIRTUAL)->SetEntry(Key,String,CEM_VIRTUAL);
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "types.h"
/*
** cfg* prototypes, if you pass NULL to a cfgSave* it will wipe out the section
** } if you pass it to lpKey it will wipe out that particular entry
** } if you add write to something it will create it if its not present
** } ** Strings passed to LoadStr should be MAX_PATH in size ! **
*/
bool cfgOpen();
s32 cfgLoadInt(const wchar * lpSection, const wchar * lpKey,s32 Default);
void cfgSaveInt(const wchar * lpSection, const wchar * lpKey, s32 Int);
void cfgLoadStr(const wchar * lpSection, const wchar * lpKey, wchar * lpReturn,const wchar* lpDefault);
void cfgSaveStr(const wchar * lpSection, const wchar * lpKey, const wchar * lpString);
s32 cfgExists(const wchar * Section, const wchar * Key);
void cfgSetVitual(const wchar * lpSection, const wchar * lpKey, const wchar * lpString);
bool ParseCommandLine(int argc,wchar* argv[]);
+138
View File
@@ -0,0 +1,138 @@
/*
Command line parsing
~yay~
Nothing too interesting here, really
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "cfg/cfg.h"
wchar* trim_ws(wchar* str)
{
if (str==0 || strlen(str)==0)
return 0;
while(*str)
{
if (!isspace(*str))
break;
str++;
}
size_t l=strlen(str);
if (l==0)
return 0;
while(l>0)
{
if (!isspace(str[l-1]))
break;
str[l-1]=0;
l--;
}
if (l==0)
return 0;
return str;
}
int setconfig(wchar** arg,int cl)
{
int rv=0;
for(;;)
{
if (cl<1)
{
printf("-config : invalid number of parameters, format is section:key=value\n");
return rv;
}
wchar* sep=strstr(arg[1],":");
if (sep==0)
{
printf("-config : invalid parameter %s, format is section:key=value\n",arg[1]);
return rv;
}
wchar* value=strstr(sep+1,"=");
if (value==0)
{
printf("-config : invalid parameter %s, format is section:key=value\n",arg[1]);
return rv;
}
*sep++=0;
*value++=0;
wchar* sect=trim_ws(arg[1]);
wchar* key=trim_ws(sep);
value=trim_ws(value);
if (sect==0 || key==0)
{
printf("-config : invalid parameter, format is section:key=value\n");
return rv;
}
if (value==0)
value="";
printf("Virtual cfg %s:%s=%s\n",sect,key,value);
cfgSetVitual(sect,key,value);
rv++;
if (cl>=3 && stricmp(arg[2],",")==0)
{
cl-=2;
arg+=2;
rv++;
continue;
}
else
break;
}
return rv;
}
int showhelp(wchar** arg,int cl)
{
printf("Available commands :\n");
printf("-config section:key=value [, ..]: add a virtual config value\n Virtual config values wont be saved to the .cfg file\n unless a different value is writen to em\nNote :\n You can specify many settings in the xx:yy=zz , gg:hh=jj , ...\n format.The spaces betwen the values and ',' are needed.");
return 0;
}
bool ParseCommandLine(int argc,wchar* argv[])
{
int cl=argc-2;
wchar** arg=argv+1;
while(cl>=0)
{
if (stricmp(*arg,"-help")==0)
{
int as=showhelp(arg,cl);
cl-=as;
arg+=as;
return true;
}
else if (stricmp(*arg,"-config")==0)
{
int as=setconfig(arg,cl);
cl-=as;
arg+=as;
}
else
{
printf("wtf %s is suposed to do ?\n",*arg);
}
arg++;
cl--;
}
printf("\n");
return false;
}
+139
View File
@@ -0,0 +1,139 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "cdipsr.h"
// Global variables
unsigned long temp_value;
/////////////////////////////////////////////////////////////////////////////
unsigned long ask_type(FILE *fsource, long header_position)
{
unsigned char filename_length;
unsigned long track_mode;
fseek(fsource, header_position, SEEK_SET);
fread(&temp_value, 4, 1, fsource);
if (temp_value != 0)
fseek(fsource, 8, SEEK_CUR); // extra data (DJ 3.00.780 and up)
fseek(fsource, 24, SEEK_CUR);
fread(&filename_length, 1, 1, fsource);
fseek(fsource, filename_length, SEEK_CUR);
fseek(fsource, 19, SEEK_CUR);
fread(&temp_value, 4, 1, fsource);
if (temp_value == 0x80000000)
fseek(fsource, 8, SEEK_CUR); // DJ4
fseek(fsource, 16, SEEK_CUR);
fread(&track_mode, 4, 1, fsource);
fseek(fsource, header_position, SEEK_SET);
return (track_mode);
}
/////////////////////////////////////////////////////////////////////////////
void CDI_read_track (FILE *fsource, image_s *image, track_s *track)
{
char TRACK_START_MARK[10] = { 0, 0, 0x01, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF };
char current_start_mark[10];
fread(&temp_value, 4, 1, fsource);
if (temp_value != 0)
fseek(fsource, 8, SEEK_CUR); // extra data (DJ 3.00.780 and up)
fread(&current_start_mark, 10, 1, fsource);
if (memcmp(TRACK_START_MARK, current_start_mark, 10)) printf( "Unsupported format: Could not find the track start mark");
fread(&current_start_mark, 10, 1, fsource);
if (memcmp(TRACK_START_MARK, current_start_mark, 10)) printf( "Unsupported format: Could not find the track start mark");
fseek(fsource, 4, SEEK_CUR);
fread(&track->filename_length, 1, 1, fsource);
fseek(fsource, track->filename_length, SEEK_CUR);
fseek(fsource, 11, SEEK_CUR);
fseek(fsource, 4, SEEK_CUR);
fseek(fsource, 4, SEEK_CUR);
fread(&temp_value, 4, 1, fsource);
if (temp_value == 0x80000000)
fseek(fsource, 8, SEEK_CUR); // DJ4
fseek(fsource, 2, SEEK_CUR);
fread(&track->pregap_length, 4, 1, fsource);
fread(&track->length, 4, 1, fsource);
fseek(fsource, 6, SEEK_CUR);
fread(&track->mode, 4, 1, fsource);
fseek(fsource, 12, SEEK_CUR);
fread(&track->start_lba, 4, 1, fsource);
fread(&track->total_length, 4, 1, fsource);
fseek(fsource, 16, SEEK_CUR);
fread(&track->sector_size_value, 4, 1, fsource);
switch(track->sector_size_value)
{
case 0 : track->sector_size = 2048; break;
case 1 : track->sector_size = 2336; break;
case 2 : track->sector_size = 2352; break;
default: printf("Unsupported sector size");
}
if (track->mode > 2) printf( "Unsupported format: Track mode not supported");
fseek(fsource, 29, SEEK_CUR);
if (image->version != CDI_V2)
{
fseek(fsource, 5, SEEK_CUR);
fread(&temp_value, 4, 1, fsource);
if (temp_value == 0xffffffff)
fseek(fsource, 78, SEEK_CUR); // extra data (DJ 3.00.780 and up)
}
}
void CDI_skip_next_session (FILE *fsource, image_s *image)
{
fseek(fsource, 4, SEEK_CUR);
fseek(fsource, 8, SEEK_CUR);
if (image->version != CDI_V2) fseek(fsource, 1, SEEK_CUR);
}
void CDI_get_tracks (FILE *fsource, image_s *image)
{
fread(&image->tracks, 2, 1, fsource);
}
void CDI_init (FILE *fsource, image_s *image, char *fsourcename)
{
fseek(fsource, 0L, SEEK_END);
image->length = ftell(fsource);
if (image->length < 8) printf( "Image file is too short");
fseek(fsource, image->length-8, SEEK_SET);
fread(&image->version, 4, 1, fsource);
fread(&image->header_offset, 4, 1, fsource);
// if (errno != 0) printf( fsourcename);
if (image->header_offset == 0) printf( "Bad image format");
}
void CDI_get_sessions (FILE *fsource, image_s *image)
{
#ifndef DEBUG_CDI
if (image->version == CDI_V35)
fseek(fsource, (image->length - image->header_offset), SEEK_SET);
else
fseek(fsource, image->header_offset, SEEK_SET);
#else
fseek(fsource, 0L, SEEK_SET);
#endif
fread(&image->sessions, 2, 1, fsource);
}
+49
View File
@@ -0,0 +1,49 @@
#ifndef __CDI_H__
#define __CDI_H__
/* Basic structures */
typedef struct image_s
{
long header_offset;
long header_position;
long length;
unsigned long version;
unsigned short int sessions;
unsigned short int tracks;
unsigned short int remaining_sessions;
unsigned short int remaining_tracks;
unsigned short int global_current_session;
} image_s;
typedef struct track_s
{
unsigned short int global_current_track;
unsigned short int number;
long position;
unsigned long mode;
unsigned long sector_size;
unsigned long sector_size_value;
long length;
long pregap_length;
long total_length;
unsigned long start_lba;
unsigned char filename_length;
} track_s;
#define CDI_V2 0x80000004
#define CDI_V3 0x80000005
#define CDI_V35 0x80000006
unsigned long ask_type(FILE *fsource, long header_position);
void CDI_init (FILE *fsource, image_s *image, char *fsourcename);
void CDI_get_sessions (FILE *fsource, image_s *image);
void CDI_get_tracks (FILE *fsource, image_s *image);
void CDI_read_track (FILE *fsource, image_s *image, track_s *track);
void CDI_skip_next_session (FILE *fsource, image_s *image);
#endif
+350
View File
@@ -0,0 +1,350 @@
/***************************************************************************
chd.h
MAME Compressed Hunks of Data file format
****************************************************************************
Copyright Aaron Giles
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name 'MAME' nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#pragma once
#ifndef __CHD_H__
#define __CHD_H__
#include "coretypes.h"
/***************************************************************************
Compressed Hunks of Data header format. All numbers are stored in
Motorola (big-endian) byte ordering. The header is 76 (V1) or 80 (V2)
bytes long.
V1 header:
[ 0] char tag[8]; // 'MComprHD'
[ 8] UINT32 length; // length of header (including tag and length fields)
[ 12] UINT32 version; // drive format version
[ 16] UINT32 flags; // flags (see below)
[ 20] UINT32 compression; // compression type
[ 24] UINT32 hunksize; // 512-byte sectors per hunk
[ 28] UINT32 totalhunks; // total # of hunks represented
[ 32] UINT32 cylinders; // number of cylinders on hard disk
[ 36] UINT32 heads; // number of heads on hard disk
[ 40] UINT32 sectors; // number of sectors on hard disk
[ 44] UINT8 md5[16]; // MD5 checksum of raw data
[ 60] UINT8 parentmd5[16]; // MD5 checksum of parent file
[ 76] (V1 header length)
V2 header:
[ 0] char tag[8]; // 'MComprHD'
[ 8] UINT32 length; // length of header (including tag and length fields)
[ 12] UINT32 version; // drive format version
[ 16] UINT32 flags; // flags (see below)
[ 20] UINT32 compression; // compression type
[ 24] UINT32 hunksize; // seclen-byte sectors per hunk
[ 28] UINT32 totalhunks; // total # of hunks represented
[ 32] UINT32 cylinders; // number of cylinders on hard disk
[ 36] UINT32 heads; // number of heads on hard disk
[ 40] UINT32 sectors; // number of sectors on hard disk
[ 44] UINT8 md5[16]; // MD5 checksum of raw data
[ 60] UINT8 parentmd5[16]; // MD5 checksum of parent file
[ 76] UINT32 seclen; // number of bytes per sector
[ 80] (V2 header length)
V3 header:
[ 0] char tag[8]; // 'MComprHD'
[ 8] UINT32 length; // length of header (including tag and length fields)
[ 12] UINT32 version; // drive format version
[ 16] UINT32 flags; // flags (see below)
[ 20] UINT32 compression; // compression type
[ 24] UINT32 totalhunks; // total # of hunks represented
[ 28] UINT64 logicalbytes; // logical size of the data (in bytes)
[ 36] UINT64 metaoffset; // offset to the first blob of metadata
[ 44] UINT8 md5[16]; // MD5 checksum of raw data
[ 60] UINT8 parentmd5[16]; // MD5 checksum of parent file
[ 76] UINT32 hunkbytes; // number of bytes per hunk
[ 80] UINT8 sha1[20]; // SHA1 checksum of raw data
[100] UINT8 parentsha1[20];// SHA1 checksum of parent file
[120] (V3 header length)
V4 header:
[ 0] char tag[8]; // 'MComprHD'
[ 8] UINT32 length; // length of header (including tag and length fields)
[ 12] UINT32 version; // drive format version
[ 16] UINT32 flags; // flags (see below)
[ 20] UINT32 compression; // compression type
[ 24] UINT32 totalhunks; // total # of hunks represented
[ 28] UINT64 logicalbytes; // logical size of the data (in bytes)
[ 36] UINT64 metaoffset; // offset to the first blob of metadata
[ 44] UINT32 hunkbytes; // number of bytes per hunk
[ 48] UINT8 sha1[20]; // combined raw+meta SHA1
[ 68] UINT8 parentsha1[20];// combined raw+meta SHA1 of parent
[ 88] UINT8 rawsha1[20]; // raw data SHA1
[108] (V4 header length)
Flags:
0x00000001 - set if this drive has a parent
0x00000002 - set if this drive allows writes
***************************************************************************/
/***************************************************************************
CONSTANTS
***************************************************************************/
/* header information */
#define CHD_HEADER_VERSION 4
#define CHD_V1_HEADER_SIZE 76
#define CHD_V2_HEADER_SIZE 80
#define CHD_V3_HEADER_SIZE 120
#define CHD_V4_HEADER_SIZE 108
#define CHD_MAX_HEADER_SIZE CHD_V4_HEADER_SIZE
/* checksumming information */
#define CHD_MD5_BYTES 16
#define CHD_SHA1_BYTES 20
/* CHD global flags */
#define CHDFLAGS_HAS_PARENT 0x00000001
#define CHDFLAGS_IS_WRITEABLE 0x00000002
#define CHDFLAGS_UNDEFINED 0xfffffffc
/* compression types */
#define CHDCOMPRESSION_NONE 0
#define CHDCOMPRESSION_ZLIB 1
#define CHDCOMPRESSION_ZLIB_PLUS 2
#define CHDCOMPRESSION_AV 3
/* A/V codec configuration parameters */
#define AV_CODEC_COMPRESS_CONFIG 1
#define AV_CODEC_DECOMPRESS_CONFIG 2
/* metadata parameters */
#define CHDMETATAG_WILDCARD 0
#define CHD_METAINDEX_APPEND ((UINT32)-1)
/* metadata flags */
#define CHD_MDFLAGS_CHECKSUM 0x01 /* indicates data is checksummed */
/* standard hard disk metadata */
#define HARD_DISK_METADATA_TAG 0x47444444 /* 'GDDD' */
#define HARD_DISK_METADATA_FORMAT "CYLS:%d,HEADS:%d,SECS:%d,BPS:%d"
/* hard disk identify information */
#define HARD_DISK_IDENT_METADATA_TAG 0x49444e54 /* 'IDNT' */
/* hard disk key information */
#define HARD_DISK_KEY_METADATA_TAG 0x4b455920 /* 'KEY ' */
/* pcmcia CIS information */
#define PCMCIA_CIS_METADATA_TAG 0x43495320 /* 'CIS ' */
/* standard CD-ROM metadata */
#define CDROM_OLD_METADATA_TAG 0x43484344 /* 'CHCD' */
#define CDROM_TRACK_METADATA_TAG 0x43485452 /* 'CHTR' */
#define CDROM_TRACK_METADATA_FORMAT "TRACK:%d TYPE:%s SUBTYPE:%s FRAMES:%d"
#define CDROM_TRACK_METADATA2_TAG 0x43485432 /* 'CHT2' */
#define CDROM_TRACK_METADATA2_FORMAT "TRACK:%d TYPE:%s SUBTYPE:%s FRAMES:%d PREGAP:%d PGTYPE:%s PGSUB:%s POSTGAP:%d"
/* standard A/V metadata */
#define AV_METADATA_TAG 0x41564156 /* 'AVAV' */
#define AV_METADATA_FORMAT "FPS:%d.%06d WIDTH:%d HEIGHT:%d INTERLACED:%d CHANNELS:%d SAMPLERATE:%d"
/* A/V laserdisc frame metadata */
#define AV_LD_METADATA_TAG 0x41564C44 /* 'AVLD' */
/* CHD open values */
#define CHD_OPEN_READ 1
#define CHD_OPEN_READWRITE 2
/* error types */
enum _chd_error
{
CHDERR_NONE,
CHDERR_NO_INTERFACE,
CHDERR_OUT_OF_MEMORY,
CHDERR_INVALID_FILE,
CHDERR_INVALID_PARAMETER,
CHDERR_INVALID_DATA,
CHDERR_FILE_NOT_FOUND,
CHDERR_REQUIRES_PARENT,
CHDERR_FILE_NOT_WRITEABLE,
CHDERR_READ_ERROR,
CHDERR_WRITE_ERROR,
CHDERR_CODEC_ERROR,
CHDERR_INVALID_PARENT,
CHDERR_HUNK_OUT_OF_RANGE,
CHDERR_DECOMPRESSION_ERROR,
CHDERR_COMPRESSION_ERROR,
CHDERR_CANT_CREATE_FILE,
CHDERR_CANT_VERIFY,
CHDERR_NOT_SUPPORTED,
CHDERR_METADATA_NOT_FOUND,
CHDERR_INVALID_METADATA_SIZE,
CHDERR_UNSUPPORTED_VERSION,
CHDERR_VERIFY_INCOMPLETE,
CHDERR_INVALID_METADATA,
CHDERR_INVALID_STATE,
CHDERR_OPERATION_PENDING,
CHDERR_NO_ASYNC_OPERATION,
CHDERR_UNSUPPORTED_FORMAT
};
typedef enum _chd_error chd_error;
/***************************************************************************
TYPE DEFINITIONS
***************************************************************************/
/* opaque types */
typedef struct _chd_file chd_file;
/* extract header structure (NOT the on-disk header structure) */
typedef struct _chd_header chd_header;
struct _chd_header
{
UINT32 length; /* length of header data */
UINT32 version; /* drive format version */
UINT32 flags; /* flags field */
UINT32 compression; /* compression type */
UINT32 hunkbytes; /* number of bytes per hunk */
UINT32 totalhunks; /* total # of hunks represented */
UINT64 logicalbytes; /* logical size of the data */
UINT64 metaoffset; /* offset in file of first metadata */
UINT8 md5[CHD_MD5_BYTES]; /* overall MD5 checksum */
UINT8 parentmd5[CHD_MD5_BYTES]; /* overall MD5 checksum of parent */
UINT8 sha1[CHD_SHA1_BYTES]; /* overall SHA1 checksum */
UINT8 rawsha1[CHD_SHA1_BYTES]; /* SHA1 checksum of raw data */
UINT8 parentsha1[CHD_SHA1_BYTES]; /* overall SHA1 checksum of parent */
UINT32 obsolete_cylinders; /* obsolete field -- do not use! */
UINT32 obsolete_sectors; /* obsolete field -- do not use! */
UINT32 obsolete_heads; /* obsolete field -- do not use! */
UINT32 obsolete_hunksize; /* obsolete field -- do not use! */
};
/* structure for returning information about a verification pass */
typedef struct _chd_verify_result chd_verify_result;
struct _chd_verify_result
{
UINT8 md5[CHD_MD5_BYTES]; /* overall MD5 checksum */
UINT8 sha1[CHD_SHA1_BYTES]; /* overall SHA1 checksum */
UINT8 rawsha1[CHD_SHA1_BYTES]; /* SHA1 checksum of raw data */
UINT8 metasha1[CHD_SHA1_BYTES]; /* SHA1 checksum of metadata */
};
/***************************************************************************
FUNCTION PROTOTYPES
***************************************************************************/
/* ----- CHD file management ----- */
/* create a new CHD file fitting the given description */
chd_error chd_create(const char *filename, UINT64 logicalbytes, UINT32 hunkbytes, UINT32 compression, chd_file *parent);
/* same as chd_create(), but accepts an already-opened core_file object */
chd_error chd_create_file(core_file *file, UINT64 logicalbytes, UINT32 hunkbytes, UINT32 compression, chd_file *parent);
/* open an existing CHD file */
chd_error chd_open(const wchar *filename, int mode, chd_file *parent, chd_file **chd);
/* close a CHD file */
void chd_close(chd_file *chd);
/* return the associated core_file */
core_file *chd_core_file(chd_file *chd);
/* return an error string for the given CHD error */
const char *chd_error_string(chd_error err);
/* ----- CHD header management ----- */
/* return a pointer to the extracted CHD header data */
const chd_header *chd_get_header(chd_file *chd);
/* ----- core data read/write ----- */
/* read one hunk from the CHD file */
chd_error chd_read(chd_file *chd, UINT32 hunknum, void *buffer);
/* ----- metadata management ----- */
/* get indexed metadata of a particular sort */
chd_error chd_get_metadata(chd_file *chd, UINT32 searchtag, UINT32 searchindex, void *output, UINT32 outputlen, UINT32 *resultlen, UINT32 *resulttag, UINT8 *resultflags);
/* ----- verification management ----- */
/* begin verifying a CHD */
chd_error chd_verify_begin(chd_file *chd);
/* verify a single hunk of data */
chd_error chd_verify_hunk(chd_file *chd);
/* finish verifying a CHD, returning the computed MD5 and SHA1 */
chd_error chd_verify_finish(chd_file *chd, chd_verify_result *result);
/* ----- codec interfaces ----- */
/* set internal codec parameters */
chd_error chd_codec_config(chd_file *chd, int param, void *config);
/* return a string description of a codec */
const char *chd_get_codec_name(UINT32 codec);
#endif /* __CHD_H__ */
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
#include "types.h"
typedef u64 UINT64;
typedef u32 UINT32;
typedef u16 UINT16;
typedef u8 UINT8;
typedef s64 INT64;
typedef s32 INT32;
typedef s16 INT16;
typedef s8 INT8;
#ifndef INLINE
#define INLINE inline
#endif
#define core_file FILE
#define ARRAY_LENGTH(x) (sizeof(x)/sizeof(x[0]))
+239
View File
@@ -0,0 +1,239 @@
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*
* Changed so as no longer to depend on Colin Plumb's `usual.h' header
* definitions; now uses stuff from dpkg's config.h.
* - Ian Jackson <[email protected]>.
* Still in the public domain.
*/
#include <string.h> /* for memcpy() */
#include "md5.h"
#ifndef LSB_FIRST
void
byteSwap(UWORD32 *buf, unsigned words)
{
md5byte *p = (md5byte *)buf;
do {
*buf++ = (UWORD32)((unsigned)p[3] << 8 | p[2]) << 16 |
((unsigned)p[1] << 8 | p[0]);
p += 4;
} while (--words);
}
#else
#define byteSwap(buf,words)
#endif
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void
MD5Init(struct MD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bytes[0] = 0;
ctx->bytes[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
void
MD5Update(struct MD5Context *ctx, md5byte const *buf, unsigned len)
{
UWORD32 t;
/* Update byte count */
t = ctx->bytes[0];
if ((ctx->bytes[0] = t + len) < t)
ctx->bytes[1]++; /* Carry from low to high */
t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
if (t > len) {
memcpy((md5byte *)ctx->in + 64 - t, buf, len);
return;
}
/* First chunk is an odd size */
memcpy((md5byte *)ctx->in + 64 - t, buf, t);
byteSwap(ctx->in, 16);
MD5Transform(ctx->buf, ctx->in);
buf += t;
len -= t;
/* Process data in 64-byte chunks */
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteSwap(ctx->in, 16);
MD5Transform(ctx->buf, ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memcpy(ctx->in, buf, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
void
MD5Final(md5byte digest[16], struct MD5Context *ctx)
{
int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
md5byte *p = (md5byte *)ctx->in + count;
/* Set the first char of padding to 0x80. There is always room. */
*p++ = 0x80;
/* Bytes of padding needed to make 56 bytes (-8..55) */
count = 56 - 1 - count;
if (count < 0) { /* Padding forces an extra block */
memset(p, 0, count + 8);
byteSwap(ctx->in, 16);
MD5Transform(ctx->buf, ctx->in);
p = (md5byte *)ctx->in;
count = 56;
}
memset(p, 0, count);
byteSwap(ctx->in, 14);
/* Append length in bits and transform */
ctx->in[14] = ctx->bytes[0] << 3;
ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
MD5Transform(ctx->buf, ctx->in);
byteSwap(ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
}
#ifndef ASM_MD5
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f,w,x,y,z,in,s) \
(w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
void
MD5Transform(UWORD32 buf[4], UWORD32 const in[16])
{
register UWORD32 a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
#endif
+42
View File
@@ -0,0 +1,42 @@
/*
* This is the header file for the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*
* Changed so as no longer to depend on Colin Plumb's `usual.h'
* header definitions; now uses stuff from dpkg's config.h
* - Ian Jackson <[email protected]>.
* Still in the public domain.
*/
#ifndef MD5_H
#define MD5_H
typedef unsigned int UWORD32;
#define md5byte unsigned char
struct MD5Context {
UWORD32 buf[4];
UWORD32 bytes[2];
UWORD32 in[16];
};
void MD5Init(struct MD5Context *context);
void MD5Update(struct MD5Context *context, md5byte const *buf, unsigned len);
void MD5Final(unsigned char digest[16], struct MD5Context *context);
void MD5Transform(UWORD32 buf[4], UWORD32 const in[16]);
#endif /* !MD5_H */
+387
View File
@@ -0,0 +1,387 @@
/* sha1.h
*
* The sha1 hash function.
*/
/* nettle, low-level cryptographics library
*
* Copyright 2001 Peter Gutmann, Andrew Kuchling, Niels Moeller
*
* The nettle 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.
*
* The nettle 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 the nettle library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "sha1.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
static unsigned int READ_UINT32(const UINT8* data)
{
return ((UINT32)data[0] << 24) |
((UINT32)data[1] << 16) |
((UINT32)data[2] << 8) |
((UINT32)data[3]);
}
static void WRITE_UINT32(unsigned char* data, UINT32 val)
{
data[0] = (val >> 24) & 0xFF;
data[1] = (val >> 16) & 0xFF;
data[2] = (val >> 8) & 0xFF;
data[3] = (val >> 0) & 0xFF;
}
/* A block, treated as a sequence of 32-bit words. */
#define SHA1_DATA_LENGTH 16
/* The SHA f()-functions. The f1 and f3 functions can be optimized to
save one boolean operation each - thanks to Rich Schroeppel,
[email protected] for discovering this */
/* #define f1(x,y,z) ( ( x & y ) | ( ~x & z ) ) Rounds 0-19 */
#define f1(x,y,z) ( z ^ ( x & ( y ^ z ) ) ) /* Rounds 0-19 */
#define f2(x,y,z) ( x ^ y ^ z ) /* Rounds 20-39 */
/* #define f3(x,y,z) ( ( x & y ) | ( x & z ) | ( y & z ) ) Rounds 40-59 */
#define f3(x,y,z) ( ( x & y ) | ( z & ( x | y ) ) ) /* Rounds 40-59 */
#define f4(x,y,z) ( x ^ y ^ z ) /* Rounds 60-79 */
/* The SHA Mysterious Constants */
#define K1 0x5A827999L /* Rounds 0-19 */
#define K2 0x6ED9EBA1L /* Rounds 20-39 */
#define K3 0x8F1BBCDCL /* Rounds 40-59 */
#define K4 0xCA62C1D6L /* Rounds 60-79 */
/* SHA initial values */
#define h0init 0x67452301L
#define h1init 0xEFCDAB89L
#define h2init 0x98BADCFEL
#define h3init 0x10325476L
#define h4init 0xC3D2E1F0L
/* 32-bit rotate left - kludged with shifts */
#ifdef _MSC_VER
#define ROTL(n,X) _lrotl(X, n)
#else
#define ROTL(n,X) ( ( (X) << (n) ) | ( (X) >> ( 32 - (n) ) ) )
#endif
/* The initial expanding function. The hash function is defined over an
80-word expanded input array W, where the first 16 are copies of the input
data, and the remaining 64 are defined by
W[ i ] = W[ i - 16 ] ^ W[ i - 14 ] ^ W[ i - 8 ] ^ W[ i - 3 ]
This implementation generates these values on the fly in a circular
buffer - thanks to Colin Plumb, [email protected] for this
optimization.
The updated SHA changes the expanding function by adding a rotate of 1
bit. Thanks to Jim Gillogly, [email protected], and an anonymous contributor
for this information */
#define expand(W,i) ( W[ i & 15 ] = \
ROTL( 1, ( W[ i & 15 ] ^ W[ (i - 14) & 15 ] ^ \
W[ (i - 8) & 15 ] ^ W[ (i - 3) & 15 ] ) ) )
/* The prototype SHA sub-round. The fundamental sub-round is:
a' = e + ROTL( 5, a ) + f( b, c, d ) + k + data;
b' = a;
c' = ROTL( 30, b );
d' = c;
e' = d;
but this is implemented by unrolling the loop 5 times and renaming the
variables ( e, a, b, c, d ) = ( a', b', c', d', e' ) each iteration.
This code is then replicated 20 times for each of the 4 functions, using
the next 20 values from the W[] array each time */
#define subRound(a, b, c, d, e, f, k, data) \
( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
/* Initialize the SHA values */
void
sha1_init(struct sha1_ctx *ctx)
{
/* Set the h-vars to their initial values */
ctx->digest[ 0 ] = h0init;
ctx->digest[ 1 ] = h1init;
ctx->digest[ 2 ] = h2init;
ctx->digest[ 3 ] = h3init;
ctx->digest[ 4 ] = h4init;
/* Initialize bit count */
ctx->count_low = ctx->count_high = 0;
/* Initialize buffer */
ctx->index = 0;
}
/* Perform the SHA transformation. Note that this code, like MD5, seems to
break some optimizing compilers due to the complexity of the expressions
and the size of the basic block. It may be necessary to split it into
sections, e.g. based on the four subrounds
Note that this function destroys the data area */
static void
sha1_transform(UINT32 *state, UINT32 *data)
{
UINT32 A, B, C, D, E; /* Local vars */
/* Set up first buffer and local data buffer */
A = state[0];
B = state[1];
C = state[2];
D = state[3];
E = state[4];
/* Heavy mangling, in 4 sub-rounds of 20 interations each. */
subRound( A, B, C, D, E, f1, K1, data[ 0] );
subRound( E, A, B, C, D, f1, K1, data[ 1] );
subRound( D, E, A, B, C, f1, K1, data[ 2] );
subRound( C, D, E, A, B, f1, K1, data[ 3] );
subRound( B, C, D, E, A, f1, K1, data[ 4] );
subRound( A, B, C, D, E, f1, K1, data[ 5] );
subRound( E, A, B, C, D, f1, K1, data[ 6] );
subRound( D, E, A, B, C, f1, K1, data[ 7] );
subRound( C, D, E, A, B, f1, K1, data[ 8] );
subRound( B, C, D, E, A, f1, K1, data[ 9] );
subRound( A, B, C, D, E, f1, K1, data[10] );
subRound( E, A, B, C, D, f1, K1, data[11] );
subRound( D, E, A, B, C, f1, K1, data[12] );
subRound( C, D, E, A, B, f1, K1, data[13] );
subRound( B, C, D, E, A, f1, K1, data[14] );
subRound( A, B, C, D, E, f1, K1, data[15] );
subRound( E, A, B, C, D, f1, K1, expand( data, 16 ) );
subRound( D, E, A, B, C, f1, K1, expand( data, 17 ) );
subRound( C, D, E, A, B, f1, K1, expand( data, 18 ) );
subRound( B, C, D, E, A, f1, K1, expand( data, 19 ) );
subRound( A, B, C, D, E, f2, K2, expand( data, 20 ) );
subRound( E, A, B, C, D, f2, K2, expand( data, 21 ) );
subRound( D, E, A, B, C, f2, K2, expand( data, 22 ) );
subRound( C, D, E, A, B, f2, K2, expand( data, 23 ) );
subRound( B, C, D, E, A, f2, K2, expand( data, 24 ) );
subRound( A, B, C, D, E, f2, K2, expand( data, 25 ) );
subRound( E, A, B, C, D, f2, K2, expand( data, 26 ) );
subRound( D, E, A, B, C, f2, K2, expand( data, 27 ) );
subRound( C, D, E, A, B, f2, K2, expand( data, 28 ) );
subRound( B, C, D, E, A, f2, K2, expand( data, 29 ) );
subRound( A, B, C, D, E, f2, K2, expand( data, 30 ) );
subRound( E, A, B, C, D, f2, K2, expand( data, 31 ) );
subRound( D, E, A, B, C, f2, K2, expand( data, 32 ) );
subRound( C, D, E, A, B, f2, K2, expand( data, 33 ) );
subRound( B, C, D, E, A, f2, K2, expand( data, 34 ) );
subRound( A, B, C, D, E, f2, K2, expand( data, 35 ) );
subRound( E, A, B, C, D, f2, K2, expand( data, 36 ) );
subRound( D, E, A, B, C, f2, K2, expand( data, 37 ) );
subRound( C, D, E, A, B, f2, K2, expand( data, 38 ) );
subRound( B, C, D, E, A, f2, K2, expand( data, 39 ) );
subRound( A, B, C, D, E, f3, K3, expand( data, 40 ) );
subRound( E, A, B, C, D, f3, K3, expand( data, 41 ) );
subRound( D, E, A, B, C, f3, K3, expand( data, 42 ) );
subRound( C, D, E, A, B, f3, K3, expand( data, 43 ) );
subRound( B, C, D, E, A, f3, K3, expand( data, 44 ) );
subRound( A, B, C, D, E, f3, K3, expand( data, 45 ) );
subRound( E, A, B, C, D, f3, K3, expand( data, 46 ) );
subRound( D, E, A, B, C, f3, K3, expand( data, 47 ) );
subRound( C, D, E, A, B, f3, K3, expand( data, 48 ) );
subRound( B, C, D, E, A, f3, K3, expand( data, 49 ) );
subRound( A, B, C, D, E, f3, K3, expand( data, 50 ) );
subRound( E, A, B, C, D, f3, K3, expand( data, 51 ) );
subRound( D, E, A, B, C, f3, K3, expand( data, 52 ) );
subRound( C, D, E, A, B, f3, K3, expand( data, 53 ) );
subRound( B, C, D, E, A, f3, K3, expand( data, 54 ) );
subRound( A, B, C, D, E, f3, K3, expand( data, 55 ) );
subRound( E, A, B, C, D, f3, K3, expand( data, 56 ) );
subRound( D, E, A, B, C, f3, K3, expand( data, 57 ) );
subRound( C, D, E, A, B, f3, K3, expand( data, 58 ) );
subRound( B, C, D, E, A, f3, K3, expand( data, 59 ) );
subRound( A, B, C, D, E, f4, K4, expand( data, 60 ) );
subRound( E, A, B, C, D, f4, K4, expand( data, 61 ) );
subRound( D, E, A, B, C, f4, K4, expand( data, 62 ) );
subRound( C, D, E, A, B, f4, K4, expand( data, 63 ) );
subRound( B, C, D, E, A, f4, K4, expand( data, 64 ) );
subRound( A, B, C, D, E, f4, K4, expand( data, 65 ) );
subRound( E, A, B, C, D, f4, K4, expand( data, 66 ) );
subRound( D, E, A, B, C, f4, K4, expand( data, 67 ) );
subRound( C, D, E, A, B, f4, K4, expand( data, 68 ) );
subRound( B, C, D, E, A, f4, K4, expand( data, 69 ) );
subRound( A, B, C, D, E, f4, K4, expand( data, 70 ) );
subRound( E, A, B, C, D, f4, K4, expand( data, 71 ) );
subRound( D, E, A, B, C, f4, K4, expand( data, 72 ) );
subRound( C, D, E, A, B, f4, K4, expand( data, 73 ) );
subRound( B, C, D, E, A, f4, K4, expand( data, 74 ) );
subRound( A, B, C, D, E, f4, K4, expand( data, 75 ) );
subRound( E, A, B, C, D, f4, K4, expand( data, 76 ) );
subRound( D, E, A, B, C, f4, K4, expand( data, 77 ) );
subRound( C, D, E, A, B, f4, K4, expand( data, 78 ) );
subRound( B, C, D, E, A, f4, K4, expand( data, 79 ) );
/* Build message digest */
state[0] += A;
state[1] += B;
state[2] += C;
state[3] += D;
state[4] += E;
}
static void
sha1_block(struct sha1_ctx *ctx, const UINT8 *block)
{
UINT32 data[SHA1_DATA_LENGTH];
int i;
/* Update block count */
if (!++ctx->count_low)
++ctx->count_high;
/* Endian independent conversion */
for (i = 0; i<SHA1_DATA_LENGTH; i++, block += 4)
data[i] = READ_UINT32(block);
sha1_transform(ctx->digest, data);
}
void
sha1_update(struct sha1_ctx *ctx,
unsigned length, const UINT8 *buffer)
{
if (ctx->index)
{ /* Try to fill partial block */
unsigned left = SHA1_DATA_SIZE - ctx->index;
if (length < left)
{
memcpy(ctx->block + ctx->index, buffer, length);
ctx->index += length;
return; /* Finished */
}
else
{
memcpy(ctx->block + ctx->index, buffer, left);
sha1_block(ctx, ctx->block);
buffer += left;
length -= left;
}
}
while (length >= SHA1_DATA_SIZE)
{
sha1_block(ctx, buffer);
buffer += SHA1_DATA_SIZE;
length -= SHA1_DATA_SIZE;
}
ctx->index = length;
if (length)
/* Buffer leftovers */
memcpy(ctx->block, buffer, length);
}
/* Final wrapup - pad to SHA1_DATA_SIZE-byte boundary with the bit pattern
1 0* (64-bit count of bits processed, MSB-first) */
void
sha1_final(struct sha1_ctx *ctx)
{
UINT32 data[SHA1_DATA_LENGTH];
int i;
int words;
i = ctx->index;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
assert(i < SHA1_DATA_SIZE);
ctx->block[i++] = 0x80;
/* Fill rest of word */
for( ; i & 3; i++)
ctx->block[i] = 0;
/* i is now a multiple of the word size 4 */
words = i >> 2;
for (i = 0; i < words; i++)
data[i] = READ_UINT32(ctx->block + 4*i);
if (words > (SHA1_DATA_LENGTH-2))
{ /* No room for length in this block. Process it and
* pad with another one */
for (i = words ; i < SHA1_DATA_LENGTH; i++)
data[i] = 0;
sha1_transform(ctx->digest, data);
for (i = 0; i < (SHA1_DATA_LENGTH-2); i++)
data[i] = 0;
}
else
for (i = words ; i < SHA1_DATA_LENGTH - 2; i++)
data[i] = 0;
/* There are 512 = 2^9 bits in one block */
data[SHA1_DATA_LENGTH-2] = (ctx->count_high << 9) | (ctx->count_low >> 23);
data[SHA1_DATA_LENGTH-1] = (ctx->count_low << 9) | (ctx->index << 3);
sha1_transform(ctx->digest, data);
}
void
sha1_digest(const struct sha1_ctx *ctx,
unsigned length,
UINT8 *digest)
{
unsigned i;
unsigned words;
unsigned leftover;
assert(length <= SHA1_DIGEST_SIZE);
words = length / 4;
leftover = length % 4;
for (i = 0; i < words; i++, digest += 4)
WRITE_UINT32(digest, ctx->digest[i]);
if (leftover)
{
UINT32 word;
unsigned j = leftover;
assert(i < _SHA1_DIGEST_LENGTH);
word = ctx->digest[i];
switch (leftover)
{
default:
/* this is just here to keep the compiler happy; it can never happen */
case 3:
digest[--j] = (word >> 8) & 0xff;
/* Fall through */
case 2:
digest[--j] = (word >> 16) & 0xff;
/* Fall through */
case 1:
digest[--j] = (word >> 24) & 0xff;
}
}
}
+63
View File
@@ -0,0 +1,63 @@
/* sha1.h
*
* The sha1 hash function.
*/
/* nettle, low-level cryptographics library
*
* Copyright 2001 Niels Moeller
*
* The nettle 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.
*
* The nettle 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 the nettle library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#ifndef NETTLE_SHA1_H_INCLUDED
#define NETTLE_SHA1_H_INCLUDED
#include "../chdr/coretypes.h"
#define SHA1_DIGEST_SIZE 20
#define SHA1_DATA_SIZE 64
/* Digest is kept internally as 4 32-bit words. */
#define _SHA1_DIGEST_LENGTH 5
struct sha1_ctx
{
UINT32 digest[_SHA1_DIGEST_LENGTH]; /* Message digest */
UINT32 count_low, count_high; /* 64-bit block count */
UINT8 block[SHA1_DATA_SIZE]; /* SHA1 data buffer */
unsigned int index; /* index into buffer */
};
void
sha1_init(struct sha1_ctx *ctx);
void
sha1_update(struct sha1_ctx *ctx,
unsigned length,
const UINT8 *data);
void
sha1_final(struct sha1_ctx *ctx);
void
sha1_digest(const struct sha1_ctx *ctx,
unsigned length,
UINT8 *digest);
#endif /* NETTLE_SHA1_H_INCLUDED */
+87
View File
@@ -0,0 +1,87 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
#ifndef __ELF_DEBUG_32_H__
#define __ELF_DEBUG_32_H__
#include <stdio.h>
#include "elf32.h"
void elf32_fprintf(FILE *f, struct Elf32_Header *file, int size, const char *name, int flags);
#endif /* __ELF_DEBUG_32_H__ */
+376
View File
@@ -0,0 +1,376 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
#include <stdint.h>
#include "elf.h"
#include "debug.h"
#include <string.h>
#include <stdio.h>
#ifndef UINT64_MAX
# define UINT64_MAX (__UINT64_C(18446744073709551615))
#endif
/*
* Checks that elfFile points to a valid elf file. Returns 0 if the elf
* file is valid, < 0 if invalid.
*/
#define ISELF32(elfFile) ( ((struct Elf32_Header*)elfFile)->e_ident[EI_CLASS] == ELFCLASS32 )
#define ISELF64(elfFile) ( ((struct Elf64_Header*)elfFile)->e_ident[EI_CLASS] == ELFCLASS64 )
int
elf_checkFile(void *elfFile)
{
return ISELF32 (elfFile)
? elf32_checkFile((Elf32_Header*)elfFile)
: elf64_checkFile((Elf64_Header*)elfFile);
}
/* Program Headers Access functions */
uint16_t
elf_getNumProgramHeaders(void *elfFile)
{
return ISELF32 (elfFile)
? elf32_getNumProgramHeaders((Elf32_Header*)elfFile)
: elf64_getNumProgramHeaders((Elf64_Header*)elfFile);
}
uint32_t
elf_getProgramHeaderFlags(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderFlags((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderFlags((Elf64_Header*)elfFile, ph);
}
uint32_t
elf_getProgramHeaderType(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderType((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderType((Elf64_Header*)elfFile, ph);
}
uint64_t
elf_getProgramHeaderPaddr(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderPaddr((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderPaddr((Elf64_Header*)elfFile, ph);
}
uint64_t
elf_getProgramHeaderVaddr(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderVaddr((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderVaddr((Elf64_Header*)elfFile, ph);
}
uint64_t
elf_getProgramHeaderMemorySize(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderMemorySize((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderMemorySize((Elf64_Header*)elfFile, ph);
}
uint64_t
elf_getProgramHeaderFileSize(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderFileSize((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderFileSize((Elf64_Header*)elfFile, ph);
}
uint64_t
elf_getProgramHeaderOffset(void *elfFile, uint16_t ph)
{
return ISELF32 (elfFile)
? elf32_getProgramHeaderOffset((Elf32_Header*)elfFile, ph)
: elf64_getProgramHeaderOffset((Elf64_Header*)elfFile, ph);
}
char *
elf_getSegmentStringTable(void *elfFile)
{
return ISELF32 (elfFile)
? elf32_getSegmentStringTable((Elf32_Header*)elfFile)
: elf64_getSegmentStringTable((Elf64_Header*)elfFile);
}
char *
elf_getStringTable(void *elfFile, int string_segment)
{
return ISELF32 (elfFile)
? elf32_getStringTable((Elf32_Header*)elfFile)
: elf64_getStringTable((Elf64_Header*)elfFile, string_segment);
}
unsigned
elf_getNumSections(void *elfFile)
{
return ISELF32 (elfFile)
? elf32_getNumSections((Elf32_Header*)elfFile)
: elf64_getNumSections((Elf64_Header*)elfFile);
}
char *
elf_getSectionName(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSectionName((Elf32_Header*)elfFile, i)
: elf64_getSectionName((Elf64_Header*)elfFile, i);
}
uint32_t
elf_getSectionFlags(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSectionFlags((Elf32_Header*)elfFile, i)
: elf64_getSectionFlags((Elf64_Header*)elfFile, i);
}
uint32_t
elf_getSectionType(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSectionType((Elf32_Header*)elfFile, i)
: elf64_getSectionType((Elf64_Header*)elfFile, i);
}
uint64_t
elf_getSectionSize(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSectionSize((Elf32_Header*)elfFile, i)
: elf64_getSectionSize((Elf64_Header*)elfFile, i);
}
uint64_t
elf_getSectionLink(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSectionLink((Elf32_Header*)elfFile, i)
: 0;
}
uint64_t
elf_getSectionAddr(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSectionAddr((Elf32_Header*)elfFile, i)
: elf64_getSectionAddr((Elf64_Header*)elfFile, i);
}
void *
elf_getSection(void *elfFile, int i)
{
return ISELF32 (elfFile)
? elf32_getSection((Elf32_Header*)elfFile, i)
: elf64_getSection((Elf64_Header*)elfFile, i);
}
void *
elf_getSectionNamed(void *elfFile, char *_str)
{
return ISELF32 (elfFile)
? elf32_getSectionNamed((Elf32_Header*)elfFile, _str)
: elf64_getSectionNamed((Elf64_Header*)elfFile, _str);
}
void
elf_getProgramHeaderInfo(void *elfFile, uint16_t ph, uint64_t *p_vaddr,
uint64_t *p_paddr, uint64_t *p_filesz, uint64_t *p_offset,
uint64_t *p_memsz)
{
*p_vaddr = elf_getProgramHeaderVaddr(elfFile, ph);
*p_paddr = elf_getProgramHeaderPaddr(elfFile, ph);
*p_filesz = elf_getProgramHeaderFileSize(elfFile, ph);
*p_offset = elf_getProgramHeaderOffset(elfFile, ph);
*p_memsz = elf_getProgramHeaderMemorySize(elfFile, ph);
}
uint64_t
elf_getEntryPoint(void *elfFile)
{
return ISELF32 (elfFile)
? elf32_getEntryPoint ((Elf32_Header*)elfFile)
: elf64_getEntryPoint ((Elf64_Header*)elfFile);
}
void
elf_fprintf(FILE *f, void *file, int size, const char *name, int flags)
{
elf32_fprintf(f, (Elf32_Header*)file, size, name, flags);
}
bool
elf_getMemoryBounds(void *elfFile, bool phys, uint64_t *min, uint64_t *max)
{
uint64_t mem_min = UINT64_MAX;
uint64_t mem_max = 0;
int i;
if (elf_checkFile(elfFile) != 0) {
return false;
}
for(i=0; i < elf_getNumProgramHeaders(elfFile); i++) {
uint64_t sect_min, sect_max;
if (elf_getProgramHeaderMemorySize(elfFile, i) == 0) {
continue;
}
if (phys) {
sect_min = elf_getProgramHeaderPaddr(elfFile, i);
} else {
sect_min = elf_getProgramHeaderVaddr(elfFile, i);
}
sect_max = sect_min + elf_getProgramHeaderMemorySize(elfFile, i);
if (sect_max > mem_max) {
mem_max = sect_max;
}
if (sect_min < mem_min) {
mem_min = sect_min;
}
}
*min = mem_min;
*max = mem_max;
return true;
}
bool
elf_vaddrInProgramHeader(void *elfFile, uint16_t ph, uint64_t vaddr)
{
uint64_t min = elf_getProgramHeaderVaddr(elfFile, ph);
uint64_t max = min + elf_getProgramHeaderMemorySize(elfFile, ph);
if (vaddr >= min && vaddr < max) {
return true;
} else {
return false;
}
}
uint64_t
elf_vtopProgramHeader(void *elfFile, uint16_t ph, uint64_t vaddr)
{
uint64_t ph_phys = elf_getProgramHeaderPaddr(elfFile, ph);
uint64_t ph_virt = elf_getProgramHeaderVaddr(elfFile, ph);
uint64_t paddr;
paddr = vaddr - ph_virt + ph_phys;
return paddr;
}
bool
elf_loadFile(void *elfFile, bool phys)
{
int i;
if (elf_checkFile(elfFile) != 0) {
return false;
}
for(i=0; i < elf_getNumProgramHeaders(elfFile); i++) {
/* Load that section */
uint64_t dest, src;
size_t len;
if (phys) {
dest = elf_getProgramHeaderPaddr(elfFile, i);
} else {
dest = elf_getProgramHeaderVaddr(elfFile, i);
}
len = elf_getProgramHeaderFileSize(elfFile, i);
src = (uint64_t) (uintptr_t) elfFile + elf_getProgramHeaderOffset(elfFile, i);
memcpy((void*) (uintptr_t) dest, (void*) (uintptr_t) src, len);
dest += len;
memset((void*) (uintptr_t) dest, 0, elf_getProgramHeaderMemorySize(elfFile, i) - len);
}
return true;
}
+380
View File
@@ -0,0 +1,380 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 1999-2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
/*
Authors: Luke Deller, Ben Leslie
Created: 24/Sep/1999
*/
/**
\file
\brief Generic ELF library
The ELF library is designed to make the task of parsing and getting information
out of an ELF file easier.
It provides function to obtain the various different fields in the ELF header, and
the program and segment information.
Also importantly, it provides a function elf_loadFile which will load a given
ELF file into memory.
*/
#ifndef __ELF_ELF_H__
#define __ELF_ELF_H__
#include <stdint.h>
#include <stdio.h>
#include "elf32.h"
#include "elf64.h"
struct elf_symbol {
uint32_t st_name; // Symbol name (string table index)
uint32_t st_value; // Symbol value
uint32_t st_size; // Symbol size
uint8_t st_info; // Symbol type and binding
uint8_t st_other; // No defined meaning, 0
uint16_t st_shndx; // Section index
};
/*
* constants for Elf32_Phdr.p_flags
*/
#define PF_X 1 /* readable segment */
#define PF_W 2 /* writeable segment */
#define PF_R 4 /* executable segment */
/*
* constants for indexing into Elf64_Header_t.e_ident
*/
#define EI_MAG0 0
#define EI_MAG1 1
#define EI_MAG2 2
#define EI_MAG3 3
#define EI_CLASS 4
#define EI_DATA 5
#define EI_VERSION 6
#define ELFMAG0 '\177'
#define ELFMAG1 'E'
#define ELFMAG2 'L'
#define ELFMAG3 'F'
#define ELFCLASS32 1
#define ELFCLASS64 2
#define PT_NULL 0
#define PT_LOAD 1
#define PT_DYNAMIC 2
#define PT_INTERP 3
#define PT_NOTE 4
#define ELFDATA2LSB 1
#define ELFDATA2MSB 2
/* Section Header type bits */
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_NOBITS 8
#define SHT_REL 9
/* Section Header flag bits */
#define SHF_WRITE 1
#define SHF_ALLOC 2
#define SHF_EXECINSTR 4
/**/
#define ELF_PRINT_PROGRAM_HEADERS 1
#define ELF_PRINT_SECTIONS 2
#define ELF_PRINT_ALL (ELF_PRINT_PROGRAM_HEADERS | ELF_PRINT_SECTIONS)
/**
* Checks that elfFile points to a valid elf file.
*
* @param elfFile Potential ELF file to check
*
* \return 0 on success. -1 if not and elf, -2 if not 32 bit.
*/
int elf_checkFile(void *elfFile);
/**
* Determine number of sections in an ELF file.
*
* @param elfFile Pointer to a valid ELF header.
*
* \return Number of sections in the ELF file.
*/
unsigned elf_getNumSections(void *elfFile);
/**
* Determine number of program headers in an ELF file.
*
* @param elfFile Pointer to a valid ELF header.
*
* \return Number of program headers in the ELF file.
*/
uint16_t elf_getNumProgramHeaders(void *elfFile);
/**
* Return the base physical address of given program header in an ELF file
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The memory size of the specified program header
*/
uint64_t elf_getProgramHeaderPaddr(void *elfFile, uint16_t ph);
/**
* Return the base virtual address of given program header in an ELF file
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The memory size of the specified program header
*/
uint64_t elf_getProgramHeaderVaddr(void *elfFile, uint16_t ph);
/**
* Return the memory size of a given program header in an ELF file
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The memory size of the specified program header
*/
uint64_t elf_getProgramHeaderMemorySize(void *elfFile, uint16_t ph);
/**
* Return the file size of a given program header in an ELF file
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The file size of the specified program header
*/
uint64_t elf_getProgramHeaderFileSize(void *elfFile, uint16_t ph);
/**
* Return the start offset of he file
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The offset of this program header with relation to the start
* of the elfFile.
*/
uint64_t elf_getProgramHeaderOffset(void *elfFile, uint16_t ph);
/**
* Return the flags for a given program header
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The flags of a given program header
*/
uint32_t elf_getProgramHeaderFlags(void *elfFile, uint16_t ph);
/**
* Return the type for a given program header
*
* @param elfFile Pointer to a valid ELF header
* @param ph Index of the program header
*
* \return The type of a given program header
*/
uint32_t elf_getProgramHeaderType(void *elfFile, uint16_t ph);
/**
* Return the physical translation of a physical address, with respect
* to a given program header
*
*/
uint64_t elf_vtopProgramHeader(void *elfFile, uint16_t ph, uint64_t vaddr);
/**
*
* \return true if the address in in this program header
*/
bool elf_vaddrInProgramHeader(void *elfFile, uint16_t ph, uint64_t vaddr);
/**
* Determine the memory bounds of an ELF file
*
* @param elfFile Pointer to a valid ELF header
* @param phys If true return bounds of physical memory, otherwise return
* bounds of virtual memory
* @param min Pointer to return value of the minimum
* @param max Pointer to return value of the maximum
*
* \return true on success. false on failure, if for example, it is an invalid ELF file
*/
bool elf_getMemoryBounds(void *elfFile, bool phys, uint64_t *min, uint64_t *max);
/**
* Find the entry point of an ELF file.
*
* @param elfFile Pointer to a valid ELF header
*
* \return The entry point address as a 64-bit integer.
*/
uint64_t elf_getEntryPoint(void *elfFile);
/**
* Load an ELF file into memory
*
* @param elfFile Pointer to a valid ELF file
* @param phys If true load using the physical address, otherwise using the virtual addresses
*
* \return true on success, false on failure.
*
* The function assumes that the ELF file is loaded in memory at some
* address different to the target address at which it will be loaded.
* It also assumes direct access to the source and destination address, i.e:
* Memory must be ale to me loaded with a simple memcpy.
*
* Obviously this also means that if we are loading a 64bit ELF on a 32bit
* platform, we assume that any memory address are within the first 4GB.
*
*/
bool elf_loadFile(void *elfFile, bool phys);
char *elf_getStringTable(void *elfFile, int string_segment);
char *elf_getSegmentStringTable(void *elfFile);
void *elf_getSectionNamed(void *elfFile, char *str);
char *elf_getSectionName(void *elfFile, int i);
uint64_t elf_getSectionSize(void *elfFile, int i);
uint64_t elf_getSectionLink(void *elfFile, int i);
uint64_t elf_getSectionAddr(void *elfFile, int i);
/**
* Return the flags for a given sections
*
* @param elfFile Pointer to a valid ELF header
* @param i Index of the sections
*
* \return The flags of a given section
*/
uint32_t elf_getSectionFlags(void *elfFile, int i);
/**
* Return the type for a given sections
*
* @param elfFile Pointer to a valid ELF header
* @param i Index of the sections
*
* \return The type of a given section
*/
uint32_t elf_getSectionType(void *elfFile, int i);
void *elf_getSection(void *elfFile, int i);
void elf_getProgramHeaderInfo(void *elfFile, uint16_t ph, uint64_t *p_vaddr,
uint64_t *p_paddr, uint64_t *p_filesz,
uint64_t *p_offset, uint64_t *p_memsz);
/**
* output the details of an ELF file to the stream f
*/
void elf_fprintf(FILE *f, void *elfFile, int size, const char *name, int flags);
#define SHT_DYNSYM 0xB
#if 0
/*
* Returns a pointer to the program segment table, which is an array of
* ELF64_Phdr_t structs. The size of the array can be found by calling
* getNumProgramSegments.
*/
struct Elf32_Phdr *elf_getProgramSegmentTable(void *elfFile);
#endif
#if 0
/**
* Returns a pointer to the program segment table, which is an array of
* ELF64_Phdr_t structs. The size of the array can be found by calling
* getNumProgramSegments.
*/
struct Elf32_Shdr *elf_getSectionTable(void *elfFile);
#endif
#endif
+329
View File
@@ -0,0 +1,329 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
#include "elf.h"
#include "debug.h"
#include <string.h>
#include <stdint.h>
int
elf32_checkFile(struct Elf32_Header *file)
{
if (file->e_ident[EI_MAG0] != ELFMAG0
|| file->e_ident[EI_MAG1] != ELFMAG1
|| file->e_ident[EI_MAG2] != ELFMAG2
|| file->e_ident[EI_MAG3] != ELFMAG3)
return -1; /* not an elf file */
if (file->e_ident[EI_CLASS] != ELFCLASS32)
return -2; /* not 32-bit file */
return 0; /* elf file looks OK */
}
/*
* Returns the number of program segments in this elf file.
*/
unsigned
elf32_getNumSections(struct Elf32_Header *elfFile)
{
return elfFile->e_shnum;
}
char *
elf32_getStringTable(struct Elf32_Header *elfFile)
{
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return (char *)elfFile + sections[elfFile->e_shstrndx].sh_offset;
}
/* Returns a pointer to the program segment table, which is an array of
* ELF32_Phdr_t structs. The size of the array can be found by calling
* getNumProgramSegments. */
struct Elf32_Phdr *
elf32_getProgramSegmentTable(struct Elf32_Header *elfFile)
{
struct Elf32_Header *fileHdr = elfFile;
return (struct Elf32_Phdr *) (fileHdr->e_phoff + (long) elfFile);
}
/* Returns the number of program segments in this elf file. */
uint16_t
elf32_getNumProgramHeaders(struct Elf32_Header *elfFile)
{
struct Elf32_Header *fileHdr = elfFile;
return fileHdr->e_phnum;
}
char *
elf32_getSectionName(struct Elf32_Header *elfFile, int i)
{
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
char *str_table = elf32_getSegmentStringTable(elfFile);
if (str_table == NULL) {
return "<corrupted>";
} else {
return str_table + sections[i].sh_name;
}
}
uint32_t
elf32_getSectionSize(struct Elf32_Header *elfFile, int i)
{
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return sections[i].sh_size;
}
uint32_t
elf32_getSectionLink(struct Elf32_Header *elfFile, int i)
{
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return sections[i].sh_link;
}
uint32_t
elf32_getSectionAddr(struct Elf32_Header *elfFile, int i)
{
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return sections[i].sh_addr;
}
void *
elf32_getSection(struct Elf32_Header *elfFile, int i)
{
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
return (char *)elfFile + sections[i].sh_offset;
}
void *
elf32_getSectionNamed(struct Elf32_Header *elfFile, char *str)
{
int numSections = elf32_getNumSections(elfFile);
int i;
for (i = 0; i < numSections; i++) {
if (strcmp(str, elf32_getSectionName(elfFile, i)) == 0) {
return elf32_getSection(elfFile, i);
}
}
return NULL;
}
char *
elf32_getSegmentStringTable(struct Elf32_Header *elfFile)
{
struct Elf32_Header *fileHdr = (struct Elf32_Header *) elfFile;
if (fileHdr->e_shstrndx == 0) {
return NULL;
} else {
return elf32_getStringTable(elfFile);
}
}
#ifdef ELF_DEBUG
void
elf32_printStringTable(struct Elf32_Header *elfFile)
{
int counter;
struct Elf32_Shdr *sections = elf32_getSectionTable(elfFile);
char * stringTable;
if (!sections) {
printf("No sections.\n");
return;
}
stringTable = ((void *)elfFile) + sections[elfFile->e_shstrndx].sh_offset;
printf("File is %p; sections is %p; string table is %p\n", elfFile, sections, stringTable);
for (counter=0; counter < sections[elfFile->e_shstrndx].sh_size; counter++) {
printf("%02x %c ", stringTable[counter],
stringTable[counter] >= 0x20 ? stringTable[counter] : '.');
}
}
#endif
int
elf32_getSegmentType (struct Elf32_Header *elfFile, int segment)
{
return elf32_getProgramSegmentTable(elfFile)[segment].p_type;
}
void
elf32_getSegmentInfo(struct Elf32_Header *elfFile, int segment, uint64_t *p_vaddr, uint64_t *p_addr, uint64_t *p_filesz, uint64_t *p_offset, uint64_t *p_memsz)
{
struct Elf32_Phdr *segments;
segments = elf32_getProgramSegmentTable(elfFile);
*p_addr = segments[segment].p_paddr;
*p_vaddr = segments[segment].p_vaddr;
*p_filesz = segments[segment].p_filesz;
*p_offset = segments[segment].p_offset;
*p_memsz = segments[segment].p_memsz;
}
uint32_t
elf32_getEntryPoint (struct Elf32_Header *elfFile)
{
return elfFile->e_entry;
}
/*
* Debugging functions
*/
/*
* prints out some details of one elf file
*/
void
elf32_fprintf(FILE *f, struct Elf32_Header *file, int size, const char *name, int flags)
{
struct Elf32_Phdr *segments;
unsigned numSegments;
struct Elf32_Shdr *sections;
unsigned numSections;
int i, r;
char *str_table;
fprintf(f, "Found an elf32 file called \"%s\" located "
"at address 0x%p\n", name, file);
if ((r = elf32_checkFile(file)) != 0) {
char *magic = (char*) file;
fprintf(f, "Invalid elf file (%d)\n", r);
fprintf(f, "Magic is: %2.2hhx %2.2hhx %2.2hhx %2.2hhx\n",
magic[0], magic[1], magic[2], magic[3]);
return;
}
/*
* get a pointer to the table of program segments
*/
segments = elf32_getProgramHeaderTable(file);
numSegments = elf32_getNumProgramHeaders(file);
sections = elf32_getSectionTable(file);
numSections = elf32_getNumSections(file);
if ((uintptr_t) sections > ((uintptr_t) file + size)) {
fprintf(f, "Corrupted elfFile..\n");
return;
}
/*
* print out info about each section
*/
if (flags & ELF_PRINT_PROGRAM_HEADERS) {
/*
* print out info about each program segment
*/
fprintf(f, "Program Headers:\n");
fprintf(f, " Type Offset VirtAddr PhysAddr "
"FileSiz MemSiz Flg Align\n");
for (i = 0; i < numSegments; i++) {
if (segments[i].p_type != 1) {
fprintf(f, "segment %d is not loadable, "
"skipping\n", i);
} else {
fprintf(f, " LOAD 0x%06d 0x%08d 0x%08d 0x%05d 0x%05d %c%c%c 0x%04d\n",
segments[i].p_offset, segments[i].p_vaddr,
segments[i].p_paddr,
segments[i].p_filesz, segments[i].p_memsz,
(segments[i].p_flags & PF_R) ? 'R' : ' ',
(segments[i].p_flags & PF_W) ? 'W' : ' ',
(segments[i].p_flags & PF_X) ? 'E' : ' ',
segments[i].p_align);
}
}
}
if (flags & ELF_PRINT_SECTIONS) {
str_table = elf32_getSegmentStringTable(file);
printf("Section Headers:\n");
printf(" [Nr] Name Type Addr Off\n");
for (i = 0; i < numSections; i++) {
//if (elf_checkSection(file, i) == 0) {
fprintf(f, "[%2d] %s %x %x\n", i, elf32_getSectionName(file, i),
//fprintf(f, "[%2d] %-17.17s %-15.15s %x %x\n", i, elf32_getSectionName(file, i), " ",
///fprintf(f, "%-17.17s %-15.15s %08x %06x\n", elf32_getSectionName(file, i), " " /* sections[i].sh_type
// */ ,
sections[i].sh_addr, sections[i].sh_offset);
//}
}
}
}
+239
View File
@@ -0,0 +1,239 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
#ifndef __ELF_ELF_32_H__
#define __ELF_ELF_32_H__
#include <stdint.h>
/*
* File header
*/
struct Elf32_Header {
unsigned char e_ident[16];
uint16_t e_type; /* Relocatable=1, Executable=2 (+ some
* more ..) */
uint16_t e_machine; /* Target architecture: MIPS=8 */
uint32_t e_version; /* Elf version (should be 1) */
uint32_t e_entry; /* Code entry point */
uint32_t e_phoff; /* Program header table */
uint32_t e_shoff; /* Section header table */
uint32_t e_flags; /* Flags */
uint16_t e_ehsize; /* ELF header size */
uint16_t e_phentsize; /* Size of one program segment
* header */
uint16_t e_phnum; /* Number of program segment
* headers */
uint16_t e_shentsize; /* Size of one section header */
uint16_t e_shnum; /* Number of section headers */
uint16_t e_shstrndx; /* Section header index of the
* string table for section header
* * names */
};
/*
* Section header
*/
struct Elf32_Shdr {
uint32_t sh_name;
uint32_t sh_type;
uint32_t sh_flags;
uint32_t sh_addr;
uint32_t sh_offset;
uint32_t sh_size;
uint32_t sh_link;
uint32_t sh_info;
uint32_t sh_addralign;
uint32_t sh_entsize;
};
/*
* Program header
*/
struct Elf32_Phdr {
uint32_t p_type; /* Segment type: Loadable segment = 1 */
uint32_t p_offset; /* Offset of segment in file */
uint32_t p_vaddr; /* Reqd virtual address of segment
* when loading */
uint32_t p_paddr; /* Reqd physical address of
* segment (ignore) */
uint32_t p_filesz; /* How many bytes this segment
* occupies in file */
uint32_t p_memsz; /* How many bytes this segment
* should occupy in * memory (when
* * loading, expand the segment
* by * concatenating enough zero
* bytes to it) */
uint32_t p_flags; /* Flags: logical "or" of PF_
* constants below */
uint32_t p_align; /* Reqd alignment of segment in
* memory */
};
int elf32_checkFile(struct Elf32_Header *file);
struct Elf32_Phdr * elf32_getProgramSegmentTable(struct Elf32_Header *file);
unsigned elf32_getNumSections(struct Elf32_Header *file);
char * elf32_getStringTable(struct Elf32_Header *file);
char * elf32_getSegmentStringTable(struct Elf32_Header *file);
static inline struct Elf32_Shdr *
elf32_getSectionTable(struct Elf32_Header *file)
{
/* Cast heaven! */
return (struct Elf32_Shdr*) (uintptr_t) (((uintptr_t) file) + file->e_shoff);
}
/* accessor functions */
static inline uint32_t
elf32_getSectionType(struct Elf32_Header *file, uint16_t s)
{
return elf32_getSectionTable(file)[s].sh_type;
}
static inline uint32_t
elf32_getSectionFlags(struct Elf32_Header *file, uint16_t s)
{
return elf32_getSectionTable(file)[s].sh_flags;
}
char * elf32_getSectionName(struct Elf32_Header *file, int i);
uint32_t elf32_getSectionSize(struct Elf32_Header *file, int i);
uint32_t elf32_getSectionLink(struct Elf32_Header *elfFile, int i);
uint32_t elf32_getSectionAddr(struct Elf32_Header *elfFile, int i);
void * elf32_getSection(struct Elf32_Header *file, int i);
void * elf32_getSectionNamed(struct Elf32_Header *file, char *str);
int elf32_getSegmentType (struct Elf32_Header *file, int segment);
void elf32_getSegmentInfo(struct Elf32_Header *file, int segment, uint64_t *p_vaddr,
uint64_t *p_paddr, uint64_t *p_filesz,
uint64_t *p_offset, uint64_t *p_memsz);
uint32_t elf32_getEntryPoint (struct Elf32_Header *file);
/* Program header functions */
uint16_t elf32_getNumProgramHeaders(struct Elf32_Header *file);
static inline struct Elf32_Phdr *
elf32_getProgramHeaderTable(struct Elf32_Header *file)
{
/* Cast heaven! */
return (struct Elf32_Phdr*) (uintptr_t) (((uintptr_t) file) + file->e_phoff);
}
/* accessor functions */
static inline uint32_t
elf32_getProgramHeaderFlags(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_flags;
}
static inline uint32_t
elf32_getProgramHeaderType(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_type;
}
static inline uint32_t
elf32_getProgramHeaderFileSize(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_filesz;
}
static inline uint32_t
elf32_getProgramHeaderMemorySize(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_memsz;
}
static inline uint32_t
elf32_getProgramHeaderVaddr(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_vaddr;
}
static inline uint32_t
elf32_getProgramHeaderPaddr(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_paddr;
}
static inline uint32_t
elf32_getProgramHeaderOffset(struct Elf32_Header *file, uint16_t ph)
{
return elf32_getProgramHeaderTable(file)[ph].p_offset;
}
#endif /* __ELF_ELF_32_H__ */
+321
View File
@@ -0,0 +1,321 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
#include "elf.h"
#include <string.h>
int
elf64_checkFile(void *elfFile)
{
struct Elf64_Header *fileHdr = (struct Elf64_Header *) elfFile;
if (fileHdr->e_ident[EI_MAG0] != ELFMAG0
|| fileHdr->e_ident[EI_MAG1] != ELFMAG1
|| fileHdr->e_ident[EI_MAG2] != ELFMAG2
|| fileHdr->e_ident[EI_MAG3] != ELFMAG3)
return -1; /* not an elf file */
if (fileHdr->e_ident[EI_CLASS] != ELFCLASS64)
return -2; /* not 64-bit file */
#if 0
if (fileHdr->e_ident[EI_DATA] != ELFDATA2LSB)
return -3; /* not big-endian file */
if (fileHdr->e_ident[EI_VERSION] != 1)
return -4; /* wrong version of elf */
if (fileHdr->e_machine != 8)
return -5; /* wrong architecture (not MIPS) */
if (fileHdr->e_type != 2)
return -6; /* not an executable program */
if (fileHdr->e_phentsize != sizeof(struct Elf64_Phdr))
return -7; /* unexpected size of program segment
* header */
if (fileHdr->e_phnum == 0)
return -8; /* no program segments */
if ((fileHdr->e_flags & 0x7e) != 0)
return -9; /* wrong flags (did you forgot to compile
* with -mno-abicalls?) */
#endif
return 0; /* elf file looks OK */
}
struct Elf64_Phdr *
elf64_getProgramSegmentTable(void *elfFile)
/*
* Returns a pointer to the program segment table, which is an array of
* ELF64_Phdr_t structs. The size of the array can be found by calling
* getNumProgramSegments.
*/
{
struct Elf64_Header *fileHdr = (struct Elf64_Header *) elfFile;
return (struct Elf64_Phdr *) ((size_t)fileHdr->e_phoff + (size_t) elfFile);
}
unsigned
elf64_getNumSections(void *elfFile)
/*
* Returns the number of program segments in this elf file.
*/
{
struct Elf64_Header *fileHdr = (struct Elf64_Header *) elfFile;
return fileHdr->e_shnum;
}
char *
elf64_getStringTable(void *elfFile, int string_segment)
{
struct Elf64_Shdr *sections = elf64_getSectionTable((Elf64_Header*)elfFile);
return (char *) elfFile + sections[string_segment].sh_offset;
}
char *
elf64_getSegmentStringTable(void *elfFile)
{
struct Elf64_Header *fileHdr = (struct Elf64_Header *) elfFile;
if (fileHdr->e_shstrndx == 0) {
return NULL;
} else {
return elf64_getStringTable(elfFile, fileHdr->e_shstrndx);
}
}
char *
elf64_getSectionName(void *elfFile, int i)
{
struct Elf64_Shdr *sections = elf64_getSectionTable((Elf64_Header*)elfFile);
char *str_table = elf64_getSegmentStringTable((Elf64_Header*)elfFile);
if (str_table == NULL) {
return "<corrupted>";
} else {
return str_table + sections[i].sh_name;
}
}
uint64_t
elf64_getSectionSize(void *elfFile, int i)
{
struct Elf64_Shdr *sections = elf64_getSectionTable((Elf64_Header*)elfFile);
return sections[i].sh_size;
}
uint64_t
elf64_getSectionAddr(struct Elf64_Header *elfFile, int i)
{
struct Elf64_Shdr *sections = elf64_getSectionTable(elfFile);
return sections[i].sh_addr;
}
void *
elf64_getSection(void *elfFile, int i)
{
struct Elf64_Shdr *sections = elf64_getSectionTable((Elf64_Header*)elfFile);
return (char *)elfFile + sections[i].sh_offset;
}
void *
elf64_getSectionNamed(void *elfFile, char *str)
{
int numSections = elf64_getNumSections(elfFile);
int i;
for (i = 0; i < numSections; i++) {
if (strcmp(str, elf64_getSectionName(elfFile, i)) == 0) {
return elf64_getSection(elfFile, i);
}
}
return NULL;
}
uint16_t
elf64_getNumProgramHeaders(struct Elf64_Header *elfFile)
{
return elfFile->e_phnum;
}
int
elf64_getSegmentType (void *elfFile, int segment)
{
return elf64_getProgramSegmentTable(elfFile)[segment].p_type;
}
void
elf64_getSegmentInfo(void *elfFile, int segment, uint64_t *p_vaddr,
uint64_t *p_paddr, uint64_t *p_filesz, uint64_t *p_offset,
uint64_t *p_memsz)
{
struct Elf64_Phdr *segments;
segments = elf64_getProgramSegmentTable(elfFile);
*p_vaddr = segments[segment].p_vaddr;
*p_paddr = segments[segment].p_paddr;
*p_filesz = segments[segment].p_filesz;
*p_offset = segments[segment].p_offset;
*p_memsz = segments[segment].p_memsz;
}
uint64_t
elf64_getEntryPoint (struct Elf64_Header *elfFile)
{
return elfFile->e_entry;
}
/*
* Debugging functions
*/
#if 0
/*
* prints out some details of one elf file
*/
void
elf64_showDetails(void *elfFile, int size, char *name)
{
struct Elf64_Phdr *segments;
unsigned numSegments;
struct Elf64_Shdr *sections;
unsigned numSections;
int i,
r;
char *str_table;
printf("Found an elf64 file called \"%s\" located "
"at address 0x%lx\n", name, elfFile);
if ((r = elf64_checkFile(elfFile)) != 0) {
char *magic = elfFile;
printf("Invalid elf file (%d)\n", r);
printf("Magic is: %02.2hhx %02.2hhx %02.2hhx %02.2hhx\n",
magic[0], magic[1], magic[2], magic[3]);
return;
}
str_table = elf64_getSegmentStringTable(elfFile);
printf("Got str_table... %p\n", str_table);
/*
* get a pointer to the table of program segments
*/
segments = elf64_getProgramSegmentTable(elfFile);
numSegments = elf64_getNumProgramSegments(elfFile);
sections = elf64_getSectionTable(elfFile);
numSections = elf64_getNumSections(elfFile);
if ((void *) sections > (void *) elfFile + size ||
(((uintptr_t) sections & 0xf) != 0)) {
printf("Corrupted elfFile..\n");
return;
}
printf("Sections: %p\n", sections);
/*
* print out info about each section
*/
/*
* print out info about each program segment
*/
printf("Program Headers:\n");
printf(" Type Offset VirtAddr PhysAddr "
"FileSiz MemSiz Flg Align\n");
for (i = 0; i < numSegments; i++) {
if (segments[i].p_type != 1) {
printf("segment %d is not loadable, "
"skipping\n", i);
} else {
printf(" LOAD 0x%06lx 0x%08lx 0x%08lx"
" 0x%05lx 0x%05lx %c%c%c 0x%04lx\n",
segments[i].p_offset, segments[i].p_vaddr,
segments[i].p_vaddr,
segments[i].p_filesz, segments[i].p_memsz,
segments[i].p_flags & PF_R ? 'R' : ' ',
segments[i].p_flags & PF_W ? 'W' : ' ',
segments[i].p_flags & PF_X ? 'E' : ' ',
segments[i].p_align);
}
}
printf("Section Headers:\n");
printf(" [Nr] Name Type Addr Off\n");
for (i = 0; i < numSections; i++) {
if (elf_checkSection(elfFile, i) == 0) {
printf("%-17.17s %-15.15s %08x %06x\n", elf64_getSectionName(elfFile, i), " " /* sections[i].sh_type
*/ ,
sections[i].sh_addr, sections[i].sh_offset);
}
}
}
#endif
+240
View File
@@ -0,0 +1,240 @@
/*
* Australian Public Licence B (OZPLB)
*
* Version 1-0
*
* Copyright (c) 2004 University of New South Wales
*
* All rights reserved.
*
* Developed by: Operating Systems and Distributed Systems Group (DiSy)
* University of New South Wales
* http://www.disy.cse.unsw.edu.au
*
* Permission is granted by University of New South Wales, free of charge, to
* any person obtaining a copy of this software and any associated
* documentation files (the "Software") to deal with the Software without
* restriction, including (without limitation) the rights to use, copy,
* modify, adapt, merge, publish, distribute, communicate to the public,
* sublicense, and/or sell, lend or rent out copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of University of New South Wales, nor the names of its
* contributors, may be used to endorse or promote products derived
* from this Software without specific prior written permission.
*
* EXCEPT AS EXPRESSLY STATED IN THIS LICENCE AND TO THE FULL EXTENT
* PERMITTED BY APPLICABLE LAW, THE SOFTWARE IS PROVIDED "AS-IS", AND
* NATIONAL ICT AUSTRALIA AND ITS CONTRIBUTORS MAKE NO REPRESENTATIONS,
* WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY REPRESENTATIONS, WARRANTIES OR CONDITIONS
* REGARDING THE CONTENTS OR ACCURACY OF THE SOFTWARE, OR OF TITLE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT,
* THE ABSENCE OF LATENT OR OTHER DEFECTS, OR THE PRESENCE OR ABSENCE OF
* ERRORS, WHETHER OR NOT DISCOVERABLE.
*
* TO THE FULL EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
* NATIONAL ICT AUSTRALIA OR ITS CONTRIBUTORS BE LIABLE ON ANY LEGAL
* THEORY (INCLUDING, WITHOUT LIMITATION, IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHERWISE) FOR ANY CLAIM, LOSS, DAMAGES OR OTHER
* LIABILITY, INCLUDING (WITHOUT LIMITATION) LOSS OF PRODUCTION OR
* OPERATION TIME, LOSS, DAMAGE OR CORRUPTION OF DATA OR RECORDS; OR LOSS
* OF ANTICIPATED SAVINGS, OPPORTUNITY, REVENUE, PROFIT OR GOODWILL, OR
* OTHER ECONOMIC LOSS; OR ANY SPECIAL, INCIDENTAL, INDIRECT,
* CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES, ARISING OUT OF OR IN
* CONNECTION WITH THIS LICENCE, THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS WITH THE SOFTWARE, EVEN IF NATIONAL ICT AUSTRALIA OR ITS
* CONTRIBUTORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH CLAIM, LOSS,
* DAMAGES OR OTHER LIABILITY.
*
* If applicable legislation implies representations, warranties, or
* conditions, or imposes obligations or liability on University of New South
* Wales or one of its contributors in respect of the Software that
* cannot be wholly or partly excluded, restricted or modified, the
* liability of University of New South Wales or the contributor is limited, to
* the full extent permitted by the applicable legislation, at its
* option, to:
* a. in the case of goods, any one or more of the following:
* i. the replacement of the goods or the supply of equivalent goods;
* ii. the repair of the goods;
* iii. the payment of the cost of replacing the goods or of acquiring
* equivalent goods;
* iv. the payment of the cost of having the goods repaired; or
* b. in the case of services:
* i. the supplying of the services again; or
* ii. the payment of the cost of having the services supplied again.
*
* The construction, validity and performance of this licence is governed
* by the laws in force in New South Wales, Australia.
*/
#ifndef __LIBELF_64_H__
#define __LIBELF_64_H__
#include <stdint.h>
/*
* File header
*/
struct Elf64_Header {
unsigned char e_ident[16];
uint16_t e_type; /* Relocatable=1, Executable=2 (+ some
* more ..) */
uint16_t e_machine; /* Target architecture: MIPS=8 */
uint32_t e_version; /* Elf version (should be 1) */
uint64_t e_entry; /* Code entry point */
uint64_t e_phoff; /* Program header table */
uint64_t e_shoff; /* Section header table */
uint32_t e_flags; /* Flags */
uint16_t e_ehsize; /* ELF header size */
uint16_t e_phentsize; /* Size of one program segment
* header */
uint16_t e_phnum; /* Number of program segment
* headers */
uint16_t e_shentsize; /* Size of one section header */
uint16_t e_shnum; /* Number of section headers */
uint16_t e_shstrndx; /* Section header index of the
* string table for section header
* * names */
};
/*
* Section header
*/
struct Elf64_Shdr {
uint32_t sh_name;
uint32_t sh_type;
uint64_t sh_flags;
uint64_t sh_addr;
uint64_t sh_offset;
uint64_t sh_size;
uint32_t sh_link;
uint32_t sh_info;
uint64_t sh_addralign;
uint64_t sh_entsize;
};
/*
* Program header
*/
struct Elf64_Phdr {
uint32_t p_type; /* Segment type: Loadable segment = 1 */
uint32_t p_flags; /* Flags: logical "or" of PF_
* constants below */
uint64_t p_offset; /* Offset of segment in file */
uint64_t p_vaddr; /* Reqd virtual address of segment
* when loading */
uint64_t p_paddr; /* Reqd physical address of
* segment */
uint64_t p_filesz; /* How many bytes this segment
* occupies in file */
uint64_t p_memsz; /* How many bytes this segment
* should occupy in * memory (when
* * loading, expand the segment
* by * concatenating enough zero
* bytes to it) */
uint64_t p_align; /* Reqd alignment of segment in
* memory */
};
int elf64_checkFile(void *elfFile);
struct Elf64_Phdr * elf64_getProgramSegmentTable(void *elfFile);
unsigned elf64_getNumSections(void *elfFile);
char * elf64_getStringTable(void *elfFile, int string_segment);
char * elf64_getSegmentStringTable(void *elfFile);
static inline struct Elf64_Shdr *
elf64_getSectionTable(struct Elf64_Header *file)
{
/* Cast heaven! */
return (struct Elf64_Shdr*) (uintptr_t) (((uintptr_t) file) + file->e_shoff);
}
/* accessor functions */
static inline uint32_t
elf64_getSectionType(struct Elf64_Header *file, uint16_t s)
{
return elf64_getSectionTable(file)[s].sh_type;
}
static inline uint32_t
elf64_getSectionFlags(struct Elf64_Header *file, uint16_t s)
{
return elf64_getSectionTable(file)[s].sh_flags;
}
char * elf64_getSectionName(void *elfFile, int i);
uint64_t elf64_getSectionSize(void *elfFile, int i);
uint64_t elf64_getSectionAddr(struct Elf64_Header *elfFile, int i);
void * elf64_getSection(void *elfFile, int i);
void * elf64_getSectionNamed(void *elfFile, char *str);
int elf64_getSegmentType (void *elfFile, int segment);
void elf64_getSegmentInfo(void *elfFile, int segment, uint64_t *p_vaddr,
uint64_t *p_paddr, uint64_t *p_filesz,
uint64_t *p_offset, uint64_t *p_memsz);
void elf64_showDetails(void *elfFile, int size, char *name);
uint64_t elf64_getEntryPoint (struct Elf64_Header *elfFile);
/* Program Headers functions */
/* Program header functions */
uint16_t elf64_getNumProgramHeaders(struct Elf64_Header *file);
static inline struct Elf64_Phdr *
elf64_getProgramHeaderTable(struct Elf64_Header *file)
{
/* Cast hell! */
return (struct Elf64_Phdr*) (uintptr_t) (((uintptr_t) file) + file->e_phoff);
}
/* accessor functions */
static inline uint32_t
elf64_getProgramHeaderFlags(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_flags;
}
static inline uint32_t
elf64_getProgramHeaderType(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_type;
}
static inline uint64_t
elf64_getProgramHeaderFileSize(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_filesz;
}
static inline uint64_t
elf64_getProgramHeaderMemorySize(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_memsz;
}
static inline uint64_t
elf64_getProgramHeaderVaddr(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_vaddr;
}
static inline uint64_t
elf64_getProgramHeaderPaddr(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_paddr;
}
static inline uint64_t
elf64_getProgramHeaderOffset(struct Elf64_Header *file, uint16_t ph)
{
return elf64_getProgramHeaderTable(file)[ph].p_offset;
}
#endif /* __LIBELF_64_H__ */
+87
View File
@@ -0,0 +1,87 @@
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 0
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 0
/* Define to 1 if you have the `m' library (-lm). */
#define HAVE_LIBM 1
/* Define to 1 if you have the `z' library (-lz). */
#define HAVE_LIBZ 1
/* Define to 1 if you have the <malloc.h> header file. */
#define HAVE_MALLOC_H 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 0
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the `pow' function. */
/* #undef HAVE_POW */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "libpng"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "[email protected]"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libpng"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libpng 1.4.1"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libpng"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "1.4.1"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
/* #undef TM_IN_SYS_TIME */
/* Version number of package */
#define VERSION "1.4.1"
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
+916
View File
@@ -0,0 +1,916 @@
/* png.c - location for general purpose libpng functions
*
* Last changed in libpng 1.4.1 [February 25, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
#define PNG_NO_EXTERN
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#include "pngpriv.h"
/* Generate a compiler error if there is an old png.h in the search path. */
typedef version_1_4_1 Your_png_h_is_not_version_1_4_1;
/* Version information for C files. This had better match the version
* string defined in png.h.
*/
/* Tells libpng that we have already handled the first "num_bytes" bytes
* of the PNG file signature. If the PNG data is embedded into another
* stream we can set num_bytes = 8 so that libpng will not attempt to read
* or write any of the magic bytes before it starts on the IHDR.
*/
#ifdef PNG_READ_SUPPORTED
void PNGAPI
png_set_sig_bytes(png_structp png_ptr, int num_bytes)
{
png_debug(1, "in png_set_sig_bytes");
if (png_ptr == NULL)
return;
if (num_bytes > 8)
png_error(png_ptr, "Too many bytes for PNG signature");
png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
}
/* Checks whether the supplied bytes match the PNG signature. We allow
* checking less than the full 8-byte signature so that those apps that
* already read the first few bytes of a file to determine the file type
* can simply check the remaining bytes for extra assurance. Returns
* an integer less than, equal to, or greater than zero if sig is found,
* respectively, to be less than, to match, or be greater than the correct
* PNG signature (this is the same behaviour as strcmp, memcmp, etc).
*/
int PNGAPI
png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
{
png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
if (num_to_check > 8)
num_to_check = 8;
else if (num_to_check < 1)
return (-1);
if (start > 7)
return (-1);
if (start + num_to_check > 8)
num_to_check = 8 - start;
return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
}
#endif /* PNG_READ_SUPPORTED */
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
/* Function to allocate memory for zlib and clear it to 0. */
voidpf /* PRIVATE */
png_zalloc(voidpf png_ptr, uInt items, uInt size)
{
png_voidp ptr;
png_structp p=(png_structp)png_ptr;
png_uint_32 save_flags=p->flags;
png_alloc_size_t num_bytes;
if (png_ptr == NULL)
return (NULL);
if (items > PNG_UINT_32_MAX/size)
{
png_warning (p, "Potential overflow in png_zalloc()");
return (NULL);
}
num_bytes = (png_alloc_size_t)items * size;
p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
p->flags=save_flags;
return ((voidpf)ptr);
}
/* Function to free memory for zlib */
void /* PRIVATE */
png_zfree(voidpf png_ptr, voidpf ptr)
{
png_free((png_structp)png_ptr, (png_voidp)ptr);
}
/* Reset the CRC variable to 32 bits of 1's. Care must be taken
* in case CRC is > 32 bits to leave the top bits 0.
*/
void /* PRIVATE */
png_reset_crc(png_structp png_ptr)
{
png_ptr->crc = crc32(0, Z_NULL, 0);
}
/* Calculate the CRC over a section of data. We can only pass as
* much data to this routine as the largest single buffer size. We
* also check that this data will actually be used before going to the
* trouble of calculating it.
*/
void /* PRIVATE */
png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
{
int need_crc = 1;
if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
{
if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
(PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
need_crc = 0;
}
else /* critical */
{
if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
need_crc = 0;
}
if (need_crc)
png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
}
/* Allocate the memory for an info_struct for the application. We don't
* really need the png_ptr, but it could potentially be useful in the
* future. This should be used in favour of malloc(png_sizeof(png_info))
* and png_info_init() so that applications that want to use a shared
* libpng don't have to be recompiled if png_info changes size.
*/
png_infop PNGAPI
png_create_info_struct(png_structp png_ptr)
{
png_infop info_ptr;
png_debug(1, "in png_create_info_struct");
if (png_ptr == NULL)
return (NULL);
#ifdef PNG_USER_MEM_SUPPORTED
info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
png_ptr->malloc_fn, png_ptr->mem_ptr);
#else
info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
#endif
if (info_ptr != NULL)
png_info_init_3(&info_ptr, png_sizeof(png_info));
return (info_ptr);
}
/* This function frees the memory associated with a single info struct.
* Normally, one would use either png_destroy_read_struct() or
* png_destroy_write_struct() to free an info struct, but this may be
* useful for some applications.
*/
void PNGAPI
png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
{
png_infop info_ptr = NULL;
png_debug(1, "in png_destroy_info_struct");
if (png_ptr == NULL)
return;
if (info_ptr_ptr != NULL)
info_ptr = *info_ptr_ptr;
if (info_ptr != NULL)
{
png_info_destroy(png_ptr, info_ptr);
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
png_ptr->mem_ptr);
#else
png_destroy_struct((png_voidp)info_ptr);
#endif
*info_ptr_ptr = NULL;
}
}
/* Initialize the info structure. This is now an internal function (0.89)
* and applications using it are urged to use png_create_info_struct()
* instead.
*/
void PNGAPI
png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
{
png_infop info_ptr = *ptr_ptr;
png_debug(1, "in png_info_init_3");
if (info_ptr == NULL)
return;
if (png_sizeof(png_info) > png_info_struct_size)
{
png_destroy_struct(info_ptr);
info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
*ptr_ptr = info_ptr;
}
/* Set everything to 0 */
png_memset(info_ptr, 0, png_sizeof(png_info));
}
void PNGAPI
png_data_freer(png_structp png_ptr, png_infop info_ptr,
int freer, png_uint_32 mask)
{
png_debug(1, "in png_data_freer");
if (png_ptr == NULL || info_ptr == NULL)
return;
if (freer == PNG_DESTROY_WILL_FREE_DATA)
info_ptr->free_me |= mask;
else if (freer == PNG_USER_WILL_FREE_DATA)
info_ptr->free_me &= ~mask;
else
png_warning(png_ptr,
"Unknown freer parameter in png_data_freer");
}
void PNGAPI
png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
int num)
{
png_debug(1, "in png_free_data");
if (png_ptr == NULL || info_ptr == NULL)
return;
#ifdef PNG_TEXT_SUPPORTED
/* Free text item num or (if num == -1) all text items */
if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
{
if (num != -1)
{
if (info_ptr->text && info_ptr->text[num].key)
{
png_free(png_ptr, info_ptr->text[num].key);
info_ptr->text[num].key = NULL;
}
}
else
{
int i;
for (i = 0; i < info_ptr->num_text; i++)
png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
png_free(png_ptr, info_ptr->text);
info_ptr->text = NULL;
info_ptr->num_text=0;
}
}
#endif
#ifdef PNG_tRNS_SUPPORTED
/* Free any tRNS entry */
if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
{
png_free(png_ptr, info_ptr->trans_alpha);
info_ptr->trans_alpha = NULL;
info_ptr->valid &= ~PNG_INFO_tRNS;
}
#endif
#ifdef PNG_sCAL_SUPPORTED
/* Free any sCAL entry */
if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
{
#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
png_free(png_ptr, info_ptr->scal_s_width);
png_free(png_ptr, info_ptr->scal_s_height);
info_ptr->scal_s_width = NULL;
info_ptr->scal_s_height = NULL;
#endif
info_ptr->valid &= ~PNG_INFO_sCAL;
}
#endif
#ifdef PNG_pCAL_SUPPORTED
/* Free any pCAL entry */
if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
{
png_free(png_ptr, info_ptr->pcal_purpose);
png_free(png_ptr, info_ptr->pcal_units);
info_ptr->pcal_purpose = NULL;
info_ptr->pcal_units = NULL;
if (info_ptr->pcal_params != NULL)
{
int i;
for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
{
png_free(png_ptr, info_ptr->pcal_params[i]);
info_ptr->pcal_params[i] = NULL;
}
png_free(png_ptr, info_ptr->pcal_params);
info_ptr->pcal_params = NULL;
}
info_ptr->valid &= ~PNG_INFO_pCAL;
}
#endif
#ifdef PNG_iCCP_SUPPORTED
/* Free any iCCP entry */
if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
{
png_free(png_ptr, info_ptr->iccp_name);
png_free(png_ptr, info_ptr->iccp_profile);
info_ptr->iccp_name = NULL;
info_ptr->iccp_profile = NULL;
info_ptr->valid &= ~PNG_INFO_iCCP;
}
#endif
#ifdef PNG_sPLT_SUPPORTED
/* Free a given sPLT entry, or (if num == -1) all sPLT entries */
if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
{
if (num != -1)
{
if (info_ptr->splt_palettes)
{
png_free(png_ptr, info_ptr->splt_palettes[num].name);
png_free(png_ptr, info_ptr->splt_palettes[num].entries);
info_ptr->splt_palettes[num].name = NULL;
info_ptr->splt_palettes[num].entries = NULL;
}
}
else
{
if (info_ptr->splt_palettes_num)
{
int i;
for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
png_free(png_ptr, info_ptr->splt_palettes);
info_ptr->splt_palettes = NULL;
info_ptr->splt_palettes_num = 0;
}
info_ptr->valid &= ~PNG_INFO_sPLT;
}
}
#endif
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
if (png_ptr->unknown_chunk.data)
{
png_free(png_ptr, png_ptr->unknown_chunk.data);
png_ptr->unknown_chunk.data = NULL;
}
if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
{
if (num != -1)
{
if (info_ptr->unknown_chunks)
{
png_free(png_ptr, info_ptr->unknown_chunks[num].data);
info_ptr->unknown_chunks[num].data = NULL;
}
}
else
{
int i;
if (info_ptr->unknown_chunks_num)
{
for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
png_free(png_ptr, info_ptr->unknown_chunks);
info_ptr->unknown_chunks = NULL;
info_ptr->unknown_chunks_num = 0;
}
}
}
#endif
#ifdef PNG_hIST_SUPPORTED
/* Free any hIST entry */
if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
{
png_free(png_ptr, info_ptr->hist);
info_ptr->hist = NULL;
info_ptr->valid &= ~PNG_INFO_hIST;
}
#endif
/* Free any PLTE entry that was internally allocated */
if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
{
png_zfree(png_ptr, info_ptr->palette);
info_ptr->palette = NULL;
info_ptr->valid &= ~PNG_INFO_PLTE;
info_ptr->num_palette = 0;
}
#ifdef PNG_INFO_IMAGE_SUPPORTED
/* Free any image bits attached to the info structure */
if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
{
if (info_ptr->row_pointers)
{
int row;
for (row = 0; row < (int)info_ptr->height; row++)
{
png_free(png_ptr, info_ptr->row_pointers[row]);
info_ptr->row_pointers[row] = NULL;
}
png_free(png_ptr, info_ptr->row_pointers);
info_ptr->row_pointers = NULL;
}
info_ptr->valid &= ~PNG_INFO_IDAT;
}
#endif
if (num == -1)
info_ptr->free_me &= ~mask;
else
info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
}
/* This is an internal routine to free any memory that the info struct is
* pointing to before re-using it or freeing the struct itself. Recall
* that png_free() checks for NULL pointers for us.
*/
void /* PRIVATE */
png_info_destroy(png_structp png_ptr, png_infop info_ptr)
{
png_debug(1, "in png_info_destroy");
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
if (png_ptr->num_chunk_list)
{
png_free(png_ptr, png_ptr->chunk_list);
png_ptr->chunk_list = NULL;
png_ptr->num_chunk_list = 0;
}
#endif
png_info_init_3(&info_ptr, png_sizeof(png_info));
}
#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
/* This function returns a pointer to the io_ptr associated with the user
* functions. The application should free any memory associated with this
* pointer before png_write_destroy() or png_read_destroy() are called.
*/
png_voidp PNGAPI
png_get_io_ptr(png_structp png_ptr)
{
if (png_ptr == NULL)
return (NULL);
return (png_ptr->io_ptr);
}
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#ifdef PNG_STDIO_SUPPORTED
/* Initialize the default input/output functions for the PNG file. If you
* use your own read or write routines, you can call either png_set_read_fn()
* or png_set_write_fn() instead of png_init_io(). If you have defined
* PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
* necessarily available.
*/
void PNGAPI
png_init_io(png_structp png_ptr, png_FILE_p fp)
{
png_debug(1, "in png_init_io");
if (png_ptr == NULL)
return;
png_ptr->io_ptr = (png_voidp)fp;
}
#endif
#ifdef PNG_TIME_RFC1123_SUPPORTED
/* Convert the supplied time into an RFC 1123 string suitable for use in
* a "Creation Time" or other text-based time string.
*/
png_charp PNGAPI
png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
{
static PNG_CONST char short_months[12][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
if (png_ptr == NULL)
return (NULL);
if (png_ptr->time_buffer == NULL)
{
png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
png_sizeof(char)));
}
#ifdef USE_FAR_KEYWORD
{
char near_time_buf[29];
png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
png_memcpy(png_ptr->time_buffer, near_time_buf,
29*png_sizeof(char));
}
#else
png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
#endif
return ((png_charp)png_ptr->time_buffer);
}
#endif /* PNG_TIME_RFC1123_SUPPORTED */
#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
png_charp PNGAPI
png_get_copyright(png_structp png_ptr)
{
png_ptr = png_ptr; /* Silence compiler warning about unused png_ptr */
#ifdef PNG_STRING_COPYRIGHT
return PNG_STRING_COPYRIGHT
#else
#ifdef __STDC__
return ((png_charp) PNG_STRING_NEWLINE \
"libpng version 1.4.1 - February 25, 2010" PNG_STRING_NEWLINE \
"Copyright (c) 1998-2010 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
PNG_STRING_NEWLINE);
#else
return ((png_charp) "libpng version 1.4.1 - February 25, 2010\
Copyright (c) 1998-2010 Glenn Randers-Pehrson\
Copyright (c) 1996-1997 Andreas Dilger\
Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.");
#endif
#endif
}
/* The following return the library version as a short string in the
* format 1.0.0 through 99.99.99zz. To get the version of *.h files
* used with your application, print out PNG_LIBPNG_VER_STRING, which
* is defined in png.h.
* Note: now there is no difference between png_get_libpng_ver() and
* png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
* it is guaranteed that png.c uses the correct version of png.h.
*/
png_charp PNGAPI
png_get_libpng_ver(png_structp png_ptr)
{
/* Version of *.c files used when building libpng */
png_ptr = png_ptr; /* Silence compiler warning about unused png_ptr */
return ((png_charp) PNG_LIBPNG_VER_STRING);
}
png_charp PNGAPI
png_get_header_ver(png_structp png_ptr)
{
/* Version of *.h files used when building libpng */
png_ptr = png_ptr; /* Silence compiler warning about unused png_ptr */
return ((png_charp) PNG_LIBPNG_VER_STRING);
}
png_charp PNGAPI
png_get_header_version(png_structp png_ptr)
{
/* Returns longer string containing both version and date */
png_ptr = png_ptr; /* Silence compiler warning about unused png_ptr */
#ifdef __STDC__
return ((png_charp) PNG_HEADER_VERSION_STRING
#ifndef PNG_READ_SUPPORTED
" (NO READ SUPPORT)"
#endif
PNG_STRING_NEWLINE);
#else
return ((png_charp) PNG_HEADER_VERSION_STRING);
#endif
}
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
int PNGAPI
png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
{
/* Check chunk_name and return "keep" value if it's on the list, else 0 */
int i;
png_bytep p;
if (png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
return 0;
p = png_ptr->chunk_list + png_ptr->num_chunk_list*5 - 5;
for (i = png_ptr->num_chunk_list; i; i--, p -= 5)
if (!png_memcmp(chunk_name, p, 4))
return ((int)*(p + 4));
return 0;
}
#endif
/* This function, added to libpng-1.0.6g, is untested. */
int PNGAPI
png_reset_zstream(png_structp png_ptr)
{
if (png_ptr == NULL)
return Z_STREAM_ERROR;
return (inflateReset(&png_ptr->zstream));
}
#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
/* This function was added to libpng-1.0.7 */
png_uint_32 PNGAPI
png_access_version_number(void)
{
/* Version of *.c files used when building libpng */
return((png_uint_32) PNG_LIBPNG_VER);
}
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#ifdef PNG_SIZE_T
/* Added at libpng version 1.2.6 */
PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
png_size_t PNGAPI
png_convert_size(size_t size)
{
if (size > (png_size_t)-1)
PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
return ((png_size_t)size);
}
#endif /* PNG_SIZE_T */
/* Added at libpng version 1.2.34 and 1.4.0 (moved from pngset.c) */
#ifdef PNG_cHRM_SUPPORTED
#ifdef PNG_CHECK_cHRM_SUPPORTED
/*
* Multiply two 32-bit numbers, V1 and V2, using 32-bit
* arithmetic, to produce a 64 bit result in the HI/LO words.
*
* A B
* x C D
* ------
* AD || BD
* AC || CB || 0
*
* where A and B are the high and low 16-bit words of V1,
* C and D are the 16-bit words of V2, AD is the product of
* A and D, and X || Y is (X << 16) + Y.
*/
void /* PRIVATE */
png_64bit_product (long v1, long v2, unsigned long *hi_product,
unsigned long *lo_product)
{
int a, b, c, d;
long lo, hi, x, y;
a = (v1 >> 16) & 0xffff;
b = v1 & 0xffff;
c = (v2 >> 16) & 0xffff;
d = v2 & 0xffff;
lo = b * d; /* BD */
x = a * d + c * b; /* AD + CB */
y = ((lo >> 16) & 0xffff) + x;
lo = (lo & 0xffff) | ((y & 0xffff) << 16);
hi = (y >> 16) & 0xffff;
hi += a * c; /* AC */
*hi_product = (unsigned long)hi;
*lo_product = (unsigned long)lo;
}
int /* PRIVATE */
png_check_cHRM_fixed(png_structp png_ptr,
png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
png_fixed_point blue_x, png_fixed_point blue_y)
{
int ret = 1;
unsigned long xy_hi,xy_lo,yx_hi,yx_lo;
png_debug(1, "in function png_check_cHRM_fixed");
if (png_ptr == NULL)
return 0;
if (white_x < 0 || white_y <= 0 ||
red_x < 0 || red_y < 0 ||
green_x < 0 || green_y < 0 ||
blue_x < 0 || blue_y < 0)
{
png_warning(png_ptr,
"Ignoring attempt to set negative chromaticity value");
ret = 0;
}
if (white_x > (png_fixed_point) PNG_UINT_31_MAX ||
white_y > (png_fixed_point) PNG_UINT_31_MAX ||
red_x > (png_fixed_point) PNG_UINT_31_MAX ||
red_y > (png_fixed_point) PNG_UINT_31_MAX ||
green_x > (png_fixed_point) PNG_UINT_31_MAX ||
green_y > (png_fixed_point) PNG_UINT_31_MAX ||
blue_x > (png_fixed_point) PNG_UINT_31_MAX ||
blue_y > (png_fixed_point) PNG_UINT_31_MAX )
{
png_warning(png_ptr,
"Ignoring attempt to set chromaticity value exceeding 21474.83");
ret = 0;
}
if (white_x > 100000L - white_y)
{
png_warning(png_ptr, "Invalid cHRM white point");
ret = 0;
}
if (red_x > 100000L - red_y)
{
png_warning(png_ptr, "Invalid cHRM red point");
ret = 0;
}
if (green_x > 100000L - green_y)
{
png_warning(png_ptr, "Invalid cHRM green point");
ret = 0;
}
if (blue_x > 100000L - blue_y)
{
png_warning(png_ptr, "Invalid cHRM blue point");
ret = 0;
}
png_64bit_product(green_x - red_x, blue_y - red_y, &xy_hi, &xy_lo);
png_64bit_product(green_y - red_y, blue_x - red_x, &yx_hi, &yx_lo);
if (xy_hi == yx_hi && xy_lo == yx_lo)
{
png_warning(png_ptr,
"Ignoring attempt to set cHRM RGB triangle with zero area");
ret = 0;
}
return ret;
}
#endif /* PNG_CHECK_cHRM_SUPPORTED */
#endif /* PNG_cHRM_SUPPORTED */
void /* PRIVATE */
png_check_IHDR(png_structp png_ptr,
png_uint_32 width, png_uint_32 height, int bit_depth,
int color_type, int interlace_type, int compression_type,
int filter_type)
{
int error = 0;
/* Check for width and height valid values */
if (width == 0)
{
png_warning(png_ptr, "Image width is zero in IHDR");
error = 1;
}
if (height == 0)
{
png_warning(png_ptr, "Image height is zero in IHDR");
error = 1;
}
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
if (width > png_ptr->user_width_max || width > PNG_USER_WIDTH_MAX)
#else
if (width > PNG_USER_WIDTH_MAX)
#endif
{
png_warning(png_ptr, "Image width exceeds user limit in IHDR");
error = 1;
}
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
if (height > png_ptr->user_height_max || height > PNG_USER_HEIGHT_MAX)
#else
if (height > PNG_USER_HEIGHT_MAX)
#endif
{
png_warning(png_ptr, "Image height exceeds user limit in IHDR");
error = 1;
}
if (width > PNG_UINT_31_MAX)
{
png_warning(png_ptr, "Invalid image width in IHDR");
error = 1;
}
if ( height > PNG_UINT_31_MAX)
{
png_warning(png_ptr, "Invalid image height in IHDR");
error = 1;
}
if ( width > (PNG_UINT_32_MAX
>> 3) /* 8-byte RGBA pixels */
- 64 /* bigrowbuf hack */
- 1 /* filter byte */
- 7*8 /* rounding of width to multiple of 8 pixels */
- 8) /* extra max_pixel_depth pad */
png_warning(png_ptr, "Width is too large for libpng to process pixels");
/* Check other values */
if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
bit_depth != 8 && bit_depth != 16)
{
png_warning(png_ptr, "Invalid bit depth in IHDR");
error = 1;
}
if (color_type < 0 || color_type == 1 ||
color_type == 5 || color_type > 6)
{
png_warning(png_ptr, "Invalid color type in IHDR");
error = 1;
}
if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
((color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
{
png_warning(png_ptr, "Invalid color type/bit depth combination in IHDR");
error = 1;
}
if (interlace_type >= PNG_INTERLACE_LAST)
{
png_warning(png_ptr, "Unknown interlace method in IHDR");
error = 1;
}
if (compression_type != PNG_COMPRESSION_TYPE_BASE)
{
png_warning(png_ptr, "Unknown compression method in IHDR");
error = 1;
}
#ifdef PNG_MNG_FEATURES_SUPPORTED
/* Accept filter_method 64 (intrapixel differencing) only if
* 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
* 2. Libpng did not read a PNG signature (this filter_method is only
* used in PNG datastreams that are embedded in MNG datastreams) and
* 3. The application called png_permit_mng_features with a mask that
* included PNG_FLAG_MNG_FILTER_64 and
* 4. The filter_method is 64 and
* 5. The color_type is RGB or RGBA
*/
if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) &&
png_ptr->mng_features_permitted)
png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
if (filter_type != PNG_FILTER_TYPE_BASE)
{
if (!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
(filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) &&
(color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
{
png_warning(png_ptr, "Unknown filter method in IHDR");
error = 1;
}
if (png_ptr->mode & PNG_HAVE_PNG_SIGNATURE)
{
png_warning(png_ptr, "Invalid filter method in IHDR");
error = 1;
}
}
#else
if (filter_type != PNG_FILTER_TYPE_BASE)
{
png_warning(png_ptr, "Unknown filter method in IHDR");
error = 1;
}
#endif
if (error == 1)
png_error(png_ptr, "Invalid IHDR data");
}
#endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+402
View File
@@ -0,0 +1,402 @@
/* pngerror.c - stub functions for i/o and memory allocation
*
* Last changed in libpng 1.4.0 [January 3, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* This file provides a location for all error handling. Users who
* need special error handling are expected to write replacement functions
* and use png_set_error_fn() to use those functions. See the instructions
* at each function.
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#include "pngpriv.h"
static void /* PRIVATE */
png_default_error PNGARG((png_structp png_ptr,
png_const_charp error_message)) PNG_NORETURN;
#ifdef PNG_WARNINGS_SUPPORTED
static void /* PRIVATE */
png_default_warning PNGARG((png_structp png_ptr,
png_const_charp warning_message));
#endif /* PNG_WARNINGS_SUPPORTED */
/* This function is called whenever there is a fatal error. This function
* should not be changed. If there is a need to handle errors differently,
* you should supply a replacement error function and use png_set_error_fn()
* to replace the error function at run-time.
*/
#ifdef PNG_ERROR_TEXT_SUPPORTED
void PNGAPI
png_error(png_structp png_ptr, png_const_charp error_message)
{
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
char msg[16];
if (png_ptr != NULL)
{
if (png_ptr->flags&
(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
{
if (*error_message == PNG_LITERAL_SHARP)
{
/* Strip "#nnnn " from beginning of error message. */
int offset;
for (offset = 1; offset<15; offset++)
if (error_message[offset] == ' ')
break;
if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
{
int i;
for (i = 0; i < offset - 1; i++)
msg[i] = error_message[i + 1];
msg[i - 1] = '\0';
error_message = msg;
}
else
error_message += offset;
}
else
{
if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
{
msg[0] = '0';
msg[1] = '\0';
error_message = msg;
}
}
}
}
#endif
if (png_ptr != NULL && png_ptr->error_fn != NULL)
(*(png_ptr->error_fn))(png_ptr, error_message);
/* If the custom handler doesn't exist, or if it returns,
use the default handler, which will not return. */
png_default_error(png_ptr, error_message);
}
#else
void PNGAPI
png_err(png_structp png_ptr)
{
if (png_ptr != NULL && png_ptr->error_fn != NULL)
(*(png_ptr->error_fn))(png_ptr, '\0');
/* If the custom handler doesn't exist, or if it returns,
use the default handler, which will not return. */
png_default_error(png_ptr, '\0');
}
#endif /* PNG_ERROR_TEXT_SUPPORTED */
#ifdef PNG_WARNINGS_SUPPORTED
/* This function is called whenever there is a non-fatal error. This function
* should not be changed. If there is a need to handle warnings differently,
* you should supply a replacement warning function and use
* png_set_error_fn() to replace the warning function at run-time.
*/
void PNGAPI
png_warning(png_structp png_ptr, png_const_charp warning_message)
{
int offset = 0;
if (png_ptr != NULL)
{
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
if (png_ptr->flags&
(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
#endif
{
if (*warning_message == PNG_LITERAL_SHARP)
{
for (offset = 1; offset < 15; offset++)
if (warning_message[offset] == ' ')
break;
}
}
}
if (png_ptr != NULL && png_ptr->warning_fn != NULL)
(*(png_ptr->warning_fn))(png_ptr, warning_message + offset);
else
png_default_warning(png_ptr, warning_message + offset);
}
#endif /* PNG_WARNINGS_SUPPORTED */
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
void PNGAPI
png_benign_error(png_structp png_ptr, png_const_charp error_message)
{
if (png_ptr->flags & PNG_FLAG_BENIGN_ERRORS_WARN)
png_warning(png_ptr, error_message);
else
png_error(png_ptr, error_message);
}
#endif
/* These utilities are used internally to build an error message that relates
* to the current chunk. The chunk name comes from png_ptr->chunk_name,
* this is used to prefix the message. The message is limited in length
* to 63 bytes, the name characters are output as hex digits wrapped in []
* if the character is invalid.
*/
#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
static PNG_CONST char png_digit[16] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};
#define PNG_MAX_ERROR_TEXT 64
#if defined(PNG_WARNINGS_SUPPORTED) || defined(PNG_ERROR_TEXT_SUPPORTED)
static void /* PRIVATE */
png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
error_message)
{
int iout = 0, iin = 0;
while (iin < 4)
{
int c = png_ptr->chunk_name[iin++];
if (isnonalpha(c))
{
buffer[iout++] = PNG_LITERAL_LEFT_SQUARE_BRACKET;
buffer[iout++] = png_digit[(c & 0xf0) >> 4];
buffer[iout++] = png_digit[c & 0x0f];
buffer[iout++] = PNG_LITERAL_RIGHT_SQUARE_BRACKET;
}
else
{
buffer[iout++] = (png_byte)c;
}
}
if (error_message == NULL)
buffer[iout] = '\0';
else
{
buffer[iout++] = ':';
buffer[iout++] = ' ';
png_memcpy(buffer + iout, error_message, PNG_MAX_ERROR_TEXT);
buffer[iout + PNG_MAX_ERROR_TEXT - 1] = '\0';
}
}
#ifdef PNG_READ_SUPPORTED
void PNGAPI
png_chunk_error(png_structp png_ptr, png_const_charp error_message)
{
char msg[18+PNG_MAX_ERROR_TEXT];
if (png_ptr == NULL)
png_error(png_ptr, error_message);
else
{
png_format_buffer(png_ptr, msg, error_message);
png_error(png_ptr, msg);
}
}
#endif /* PNG_READ_SUPPORTED */
#endif /* PNG_WARNINGS_SUPPORTED || PNG_ERROR_TEXT_SUPPORTED */
#ifdef PNG_WARNINGS_SUPPORTED
void PNGAPI
png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
{
char msg[18+PNG_MAX_ERROR_TEXT];
if (png_ptr == NULL)
png_warning(png_ptr, warning_message);
else
{
png_format_buffer(png_ptr, msg, warning_message);
png_warning(png_ptr, msg);
}
}
#endif /* PNG_WARNINGS_SUPPORTED */
#ifdef PNG_READ_SUPPORTED
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
void PNGAPI
png_chunk_benign_error(png_structp png_ptr, png_const_charp error_message)
{
if (png_ptr->flags & PNG_FLAG_BENIGN_ERRORS_WARN)
png_chunk_warning(png_ptr, error_message);
else
png_chunk_error(png_ptr, error_message);
}
#endif
#endif /* PNG_READ_SUPPORTED */
#ifdef PNG_SETJMP_SUPPORTED
/* This API only exists if ANSI-C style error handling is used,
* otherwise it is necessary for png_default_error to be overridden.
*/
jmp_buf* PNGAPI
png_set_longjmp_fn(png_structp png_ptr, png_longjmp_ptr longjmp_fn,
size_t jmp_buf_size)
{
if (png_ptr == NULL || jmp_buf_size != png_sizeof(jmp_buf))
return NULL;
png_ptr->longjmp_fn = longjmp_fn;
return &png_ptr->jmpbuf;
}
#endif
/* This is the default error handling function. Note that replacements for
* this function MUST NOT RETURN, or the program will likely crash. This
* function is used by default, or if the program supplies NULL for the
* error function pointer in png_set_error_fn().
*/
static void /* PRIVATE */
png_default_error(png_structp png_ptr, png_const_charp error_message)
{
#ifdef PNG_CONSOLE_IO_SUPPORTED
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
if (*error_message == PNG_LITERAL_SHARP)
{
/* Strip "#nnnn " from beginning of error message. */
int offset;
char error_number[16];
for (offset = 0; offset<15; offset++)
{
error_number[offset] = error_message[offset + 1];
if (error_message[offset] == ' ')
break;
}
if ((offset > 1) && (offset < 15))
{
error_number[offset - 1] = '\0';
fprintf(stderr, "libpng error no. %s: %s",
error_number, error_message + offset + 1);
fprintf(stderr, PNG_STRING_NEWLINE);
}
else
{
fprintf(stderr, "libpng error: %s, offset=%d",
error_message, offset);
fprintf(stderr, PNG_STRING_NEWLINE);
}
}
else
#endif
{
fprintf(stderr, "libpng error: %s", error_message);
fprintf(stderr, PNG_STRING_NEWLINE);
}
#endif
#ifdef PNG_SETJMP_SUPPORTED
if (png_ptr && png_ptr->longjmp_fn)
{
# ifdef USE_FAR_KEYWORD
{
jmp_buf jmpbuf;
png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
png_ptr->longjmp_fn(jmpbuf, 1);
}
# else
png_ptr->longjmp_fn(png_ptr->jmpbuf, 1);
# endif
}
#endif
/* Here if not setjmp support or if png_ptr is null. */
PNG_ABORT();
#ifndef PNG_CONSOLE_IO_SUPPORTED
error_message = error_message; /* Make compiler happy */
#endif
}
#ifdef PNG_WARNINGS_SUPPORTED
/* This function is called when there is a warning, but the library thinks
* it can continue anyway. Replacement functions don't have to do anything
* here if you don't want them to. In the default configuration, png_ptr is
* not used, but it is passed in case it may be useful.
*/
static void /* PRIVATE */
png_default_warning(png_structp png_ptr, png_const_charp warning_message)
{
#ifdef PNG_CONSOLE_IO_SUPPORTED
# ifdef PNG_ERROR_NUMBERS_SUPPORTED
if (*warning_message == PNG_LITERAL_SHARP)
{
int offset;
char warning_number[16];
for (offset = 0; offset < 15; offset++)
{
warning_number[offset] = warning_message[offset + 1];
if (warning_message[offset] == ' ')
break;
}
if ((offset > 1) && (offset < 15))
{
warning_number[offset + 1] = '\0';
fprintf(stderr, "libpng warning no. %s: %s",
warning_number, warning_message + offset);
fprintf(stderr, PNG_STRING_NEWLINE);
}
else
{
fprintf(stderr, "libpng warning: %s",
warning_message);
fprintf(stderr, PNG_STRING_NEWLINE);
}
}
else
# endif
{
fprintf(stderr, "libpng warning: %s", warning_message);
fprintf(stderr, PNG_STRING_NEWLINE);
}
#else
warning_message = warning_message; /* Make compiler happy */
#endif
png_ptr = png_ptr; /* Make compiler happy */
}
#endif /* PNG_WARNINGS_SUPPORTED */
/* This function is called when the application wants to use another method
* of handling errors and warnings. Note that the error function MUST NOT
* return to the calling routine or serious problems will occur. The return
* method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
*/
void PNGAPI
png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warning_fn)
{
if (png_ptr == NULL)
return;
png_ptr->error_ptr = error_ptr;
png_ptr->error_fn = error_fn;
png_ptr->warning_fn = warning_fn;
}
/* This function returns a pointer to the error_ptr associated with the user
* functions. The application should free any memory associated with this
* pointer before png_write_destroy and png_read_destroy are called.
*/
png_voidp PNGAPI
png_get_error_ptr(png_structp png_ptr)
{
if (png_ptr == NULL)
return NULL;
return ((png_voidp)png_ptr->error_ptr);
}
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
void PNGAPI
png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
{
if (png_ptr != NULL)
{
png_ptr->flags &=
((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
}
}
#endif
#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
+925
View File
@@ -0,0 +1,925 @@
/* pngget.c - retrieval of values from info struct
*
* Last changed in libpng 1.4.1 [February 25, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#include "pngpriv.h"
png_uint_32 PNGAPI
png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
{
if (png_ptr != NULL && info_ptr != NULL)
return(info_ptr->valid & flag);
else
return(0);
}
png_size_t PNGAPI
png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return(info_ptr->rowbytes);
else
return(0);
}
#ifdef PNG_INFO_IMAGE_SUPPORTED
png_bytepp PNGAPI
png_get_rows(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return(info_ptr->row_pointers);
else
return(0);
}
#endif
#ifdef PNG_EASY_ACCESS_SUPPORTED
/* Easy access to info, added in libpng-0.99 */
png_uint_32 PNGAPI
png_get_image_width(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->width;
return (0);
}
png_uint_32 PNGAPI
png_get_image_height(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->height;
return (0);
}
png_byte PNGAPI
png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->bit_depth;
return (0);
}
png_byte PNGAPI
png_get_color_type(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->color_type;
return (0);
}
png_byte PNGAPI
png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->filter_type;
return (0);
}
png_byte PNGAPI
png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->interlace_type;
return (0);
}
png_byte PNGAPI
png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return info_ptr->compression_type;
return (0);
}
png_uint_32 PNGAPI
png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_pHYs_SUPPORTED
if (info_ptr->valid & PNG_INFO_pHYs)
{
png_debug1(1, "in %s retrieval function", "png_get_x_pixels_per_meter");
if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
return (0);
else
return (info_ptr->x_pixels_per_unit);
}
#else
return (0);
#endif
return (0);
}
png_uint_32 PNGAPI
png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_pHYs_SUPPORTED
if (info_ptr->valid & PNG_INFO_pHYs)
{
png_debug1(1, "in %s retrieval function", "png_get_y_pixels_per_meter");
if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
return (0);
else
return (info_ptr->y_pixels_per_unit);
}
#else
return (0);
#endif
return (0);
}
png_uint_32 PNGAPI
png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_pHYs_SUPPORTED
if (info_ptr->valid & PNG_INFO_pHYs)
{
png_debug1(1, "in %s retrieval function", "png_get_pixels_per_meter");
if (info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
return (0);
else
return (info_ptr->x_pixels_per_unit);
}
#else
return (0);
#endif
return (0);
}
#ifdef PNG_FLOATING_POINT_SUPPORTED
float PNGAPI
png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_pHYs_SUPPORTED
if (info_ptr->valid & PNG_INFO_pHYs)
{
png_debug1(1, "in %s retrieval function", "png_get_aspect_ratio");
if (info_ptr->x_pixels_per_unit == 0)
return ((float)0.0);
else
return ((float)((float)info_ptr->y_pixels_per_unit
/(float)info_ptr->x_pixels_per_unit));
}
#else
return (0.0);
#endif
return ((float)0.0);
}
#endif
png_int_32 PNGAPI
png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_oFFs_SUPPORTED
if (info_ptr->valid & PNG_INFO_oFFs)
{
png_debug1(1, "in %s retrieval function", "png_get_x_offset_microns");
if (info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
return (0);
else
return (info_ptr->x_offset);
}
#else
return (0);
#endif
return (0);
}
png_int_32 PNGAPI
png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_oFFs_SUPPORTED
if (info_ptr->valid & PNG_INFO_oFFs)
{
png_debug1(1, "in %s retrieval function", "png_get_y_offset_microns");
if (info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
return (0);
else
return (info_ptr->y_offset);
}
#else
return (0);
#endif
return (0);
}
png_int_32 PNGAPI
png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_oFFs_SUPPORTED
if (info_ptr->valid & PNG_INFO_oFFs)
{
png_debug1(1, "in %s retrieval function", "png_get_x_offset_microns");
if (info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
return (0);
else
return (info_ptr->x_offset);
}
#else
return (0);
#endif
return (0);
}
png_int_32 PNGAPI
png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
#ifdef PNG_oFFs_SUPPORTED
if (info_ptr->valid & PNG_INFO_oFFs)
{
png_debug1(1, "in %s retrieval function", "png_get_y_offset_microns");
if (info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
return (0);
else
return (info_ptr->y_offset);
}
#else
return (0);
#endif
return (0);
}
#if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
png_uint_32 PNGAPI
png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
{
return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
*.0254 +.5));
}
png_uint_32 PNGAPI
png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
{
return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
*.0254 +.5));
}
png_uint_32 PNGAPI
png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
{
return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
*.0254 +.5));
}
float PNGAPI
png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
{
return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
*.00003937);
}
float PNGAPI
png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
{
return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
*.00003937);
}
#ifdef PNG_pHYs_SUPPORTED
png_uint_32 PNGAPI
png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
{
png_uint_32 retval = 0;
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
{
png_debug1(1, "in %s retrieval function", "pHYs");
if (res_x != NULL)
{
*res_x = info_ptr->x_pixels_per_unit;
retval |= PNG_INFO_pHYs;
}
if (res_y != NULL)
{
*res_y = info_ptr->y_pixels_per_unit;
retval |= PNG_INFO_pHYs;
}
if (unit_type != NULL)
{
*unit_type = (int)info_ptr->phys_unit_type;
retval |= PNG_INFO_pHYs;
if (*unit_type == 1)
{
if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
}
}
}
return (retval);
}
#endif /* PNG_pHYs_SUPPORTED */
#endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
/* png_get_channels really belongs in here, too, but it's been around longer */
#endif /* PNG_EASY_ACCESS_SUPPORTED */
png_byte PNGAPI
png_get_channels(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return(info_ptr->channels);
else
return (0);
}
png_bytep PNGAPI
png_get_signature(png_structp png_ptr, png_infop info_ptr)
{
if (png_ptr != NULL && info_ptr != NULL)
return(info_ptr->signature);
else
return (NULL);
}
#ifdef PNG_bKGD_SUPPORTED
png_uint_32 PNGAPI
png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
png_color_16p *background)
{
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
&& background != NULL)
{
png_debug1(1, "in %s retrieval function", "bKGD");
*background = &(info_ptr->background);
return (PNG_INFO_bKGD);
}
return (0);
}
#endif
#ifdef PNG_cHRM_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED
png_uint_32 PNGAPI
png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
double *white_x, double *white_y, double *red_x, double *red_y,
double *green_x, double *green_y, double *blue_x, double *blue_y)
{
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
{
png_debug1(1, "in %s retrieval function", "cHRM");
if (white_x != NULL)
*white_x = (double)info_ptr->x_white;
if (white_y != NULL)
*white_y = (double)info_ptr->y_white;
if (red_x != NULL)
*red_x = (double)info_ptr->x_red;
if (red_y != NULL)
*red_y = (double)info_ptr->y_red;
if (green_x != NULL)
*green_x = (double)info_ptr->x_green;
if (green_y != NULL)
*green_y = (double)info_ptr->y_green;
if (blue_x != NULL)
*blue_x = (double)info_ptr->x_blue;
if (blue_y != NULL)
*blue_y = (double)info_ptr->y_blue;
return (PNG_INFO_cHRM);
}
return (0);
}
#endif
#ifdef PNG_FIXED_POINT_SUPPORTED
png_uint_32 PNGAPI
png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
png_fixed_point *blue_x, png_fixed_point *blue_y)
{
png_debug1(1, "in %s retrieval function", "cHRM");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
{
if (white_x != NULL)
*white_x = info_ptr->int_x_white;
if (white_y != NULL)
*white_y = info_ptr->int_y_white;
if (red_x != NULL)
*red_x = info_ptr->int_x_red;
if (red_y != NULL)
*red_y = info_ptr->int_y_red;
if (green_x != NULL)
*green_x = info_ptr->int_x_green;
if (green_y != NULL)
*green_y = info_ptr->int_y_green;
if (blue_x != NULL)
*blue_x = info_ptr->int_x_blue;
if (blue_y != NULL)
*blue_y = info_ptr->int_y_blue;
return (PNG_INFO_cHRM);
}
return (0);
}
#endif
#endif
#ifdef PNG_gAMA_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED
png_uint_32 PNGAPI
png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
{
png_debug1(1, "in %s retrieval function", "gAMA");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
&& file_gamma != NULL)
{
*file_gamma = (double)info_ptr->gamma;
return (PNG_INFO_gAMA);
}
return (0);
}
#endif
#ifdef PNG_FIXED_POINT_SUPPORTED
png_uint_32 PNGAPI
png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
png_fixed_point *int_file_gamma)
{
png_debug1(1, "in %s retrieval function", "gAMA");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
&& int_file_gamma != NULL)
{
*int_file_gamma = info_ptr->int_gamma;
return (PNG_INFO_gAMA);
}
return (0);
}
#endif
#endif
#ifdef PNG_sRGB_SUPPORTED
png_uint_32 PNGAPI
png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
{
png_debug1(1, "in %s retrieval function", "sRGB");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
&& file_srgb_intent != NULL)
{
*file_srgb_intent = (int)info_ptr->srgb_intent;
return (PNG_INFO_sRGB);
}
return (0);
}
#endif
#ifdef PNG_iCCP_SUPPORTED
png_uint_32 PNGAPI
png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
png_charpp name, int *compression_type,
png_charpp profile, png_uint_32 *proflen)
{
png_debug1(1, "in %s retrieval function", "iCCP");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
&& name != NULL && profile != NULL && proflen != NULL)
{
*name = info_ptr->iccp_name;
*profile = info_ptr->iccp_profile;
/* Compression_type is a dummy so the API won't have to change
* if we introduce multiple compression types later.
*/
*proflen = (int)info_ptr->iccp_proflen;
*compression_type = (int)info_ptr->iccp_compression;
return (PNG_INFO_iCCP);
}
return (0);
}
#endif
#ifdef PNG_sPLT_SUPPORTED
png_uint_32 PNGAPI
png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
png_sPLT_tpp spalettes)
{
if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
{
*spalettes = info_ptr->splt_palettes;
return ((png_uint_32)info_ptr->splt_palettes_num);
}
return (0);
}
#endif
#ifdef PNG_hIST_SUPPORTED
png_uint_32 PNGAPI
png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
{
png_debug1(1, "in %s retrieval function", "hIST");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
&& hist != NULL)
{
*hist = info_ptr->hist;
return (PNG_INFO_hIST);
}
return (0);
}
#endif
png_uint_32 PNGAPI
png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
png_uint_32 *width, png_uint_32 *height, int *bit_depth,
int *color_type, int *interlace_type, int *compression_type,
int *filter_type)
{
png_debug1(1, "in %s retrieval function", "IHDR");
if (png_ptr == NULL || info_ptr == NULL || width == NULL ||
height == NULL || bit_depth == NULL || color_type == NULL)
return (0);
*width = info_ptr->width;
*height = info_ptr->height;
*bit_depth = info_ptr->bit_depth;
*color_type = info_ptr->color_type;
if (compression_type != NULL)
*compression_type = info_ptr->compression_type;
if (filter_type != NULL)
*filter_type = info_ptr->filter_type;
if (interlace_type != NULL)
*interlace_type = info_ptr->interlace_type;
/* This is redundant if we can be sure that the info_ptr values were all
* assigned in png_set_IHDR(). We do the check anyhow in case an
* application has ignored our advice not to mess with the members
* of info_ptr directly.
*/
png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height,
info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type,
info_ptr->compression_type, info_ptr->filter_type);
return (1);
}
#ifdef PNG_oFFs_SUPPORTED
png_uint_32 PNGAPI
png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
{
png_debug1(1, "in %s retrieval function", "oFFs");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
&& offset_x != NULL && offset_y != NULL && unit_type != NULL)
{
*offset_x = info_ptr->x_offset;
*offset_y = info_ptr->y_offset;
*unit_type = (int)info_ptr->offset_unit_type;
return (PNG_INFO_oFFs);
}
return (0);
}
#endif
#ifdef PNG_pCAL_SUPPORTED
png_uint_32 PNGAPI
png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
png_charp *units, png_charpp *params)
{
png_debug1(1, "in %s retrieval function", "pCAL");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
&& purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
nparams != NULL && units != NULL && params != NULL)
{
*purpose = info_ptr->pcal_purpose;
*X0 = info_ptr->pcal_X0;
*X1 = info_ptr->pcal_X1;
*type = (int)info_ptr->pcal_type;
*nparams = (int)info_ptr->pcal_nparams;
*units = info_ptr->pcal_units;
*params = info_ptr->pcal_params;
return (PNG_INFO_pCAL);
}
return (0);
}
#endif
#ifdef PNG_sCAL_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED
png_uint_32 PNGAPI
png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
int *unit, double *width, double *height)
{
if (png_ptr != NULL && info_ptr != NULL &&
(info_ptr->valid & PNG_INFO_sCAL))
{
*unit = info_ptr->scal_unit;
*width = info_ptr->scal_pixel_width;
*height = info_ptr->scal_pixel_height;
return (PNG_INFO_sCAL);
}
return(0);
}
#else
#ifdef PNG_FIXED_POINT_SUPPORTED
png_uint_32 PNGAPI
png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
int *unit, png_charpp width, png_charpp height)
{
if (png_ptr != NULL && info_ptr != NULL &&
(info_ptr->valid & PNG_INFO_sCAL))
{
*unit = info_ptr->scal_unit;
*width = info_ptr->scal_s_width;
*height = info_ptr->scal_s_height;
return (PNG_INFO_sCAL);
}
return(0);
}
#endif
#endif
#endif
#ifdef PNG_pHYs_SUPPORTED
png_uint_32 PNGAPI
png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
{
png_uint_32 retval = 0;
png_debug1(1, "in %s retrieval function", "pHYs");
if (png_ptr != NULL && info_ptr != NULL &&
(info_ptr->valid & PNG_INFO_pHYs))
{
if (res_x != NULL)
{
*res_x = info_ptr->x_pixels_per_unit;
retval |= PNG_INFO_pHYs;
}
if (res_y != NULL)
{
*res_y = info_ptr->y_pixels_per_unit;
retval |= PNG_INFO_pHYs;
}
if (unit_type != NULL)
{
*unit_type = (int)info_ptr->phys_unit_type;
retval |= PNG_INFO_pHYs;
}
}
return (retval);
}
#endif
png_uint_32 PNGAPI
png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
int *num_palette)
{
png_debug1(1, "in %s retrieval function", "PLTE");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
&& palette != NULL)
{
*palette = info_ptr->palette;
*num_palette = info_ptr->num_palette;
png_debug1(3, "num_palette = %d", *num_palette);
return (PNG_INFO_PLTE);
}
return (0);
}
#ifdef PNG_sBIT_SUPPORTED
png_uint_32 PNGAPI
png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
{
png_debug1(1, "in %s retrieval function", "sBIT");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
&& sig_bit != NULL)
{
*sig_bit = &(info_ptr->sig_bit);
return (PNG_INFO_sBIT);
}
return (0);
}
#endif
#ifdef PNG_TEXT_SUPPORTED
png_uint_32 PNGAPI
png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
int *num_text)
{
if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
{
png_debug1(1, "in %s retrieval function",
(png_ptr->chunk_name[0] == '\0' ? "text"
: (png_const_charp)png_ptr->chunk_name));
if (text_ptr != NULL)
*text_ptr = info_ptr->text;
if (num_text != NULL)
*num_text = info_ptr->num_text;
return ((png_uint_32)info_ptr->num_text);
}
if (num_text != NULL)
*num_text = 0;
return(0);
}
#endif
#ifdef PNG_tIME_SUPPORTED
png_uint_32 PNGAPI
png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
{
png_debug1(1, "in %s retrieval function", "tIME");
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
&& mod_time != NULL)
{
*mod_time = &(info_ptr->mod_time);
return (PNG_INFO_tIME);
}
return (0);
}
#endif
#ifdef PNG_tRNS_SUPPORTED
png_uint_32 PNGAPI
png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
png_bytep *trans_alpha, int *num_trans, png_color_16p *trans_color)
{
png_uint_32 retval = 0;
if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
{
png_debug1(1, "in %s retrieval function", "tRNS");
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
if (trans_alpha != NULL)
{
*trans_alpha = info_ptr->trans_alpha;
retval |= PNG_INFO_tRNS;
}
if (trans_color != NULL)
*trans_color = &(info_ptr->trans_color);
}
else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
{
if (trans_color != NULL)
{
*trans_color = &(info_ptr->trans_color);
retval |= PNG_INFO_tRNS;
}
if (trans_alpha != NULL)
*trans_alpha = NULL;
}
if (num_trans != NULL)
{
*num_trans = info_ptr->num_trans;
retval |= PNG_INFO_tRNS;
}
}
return (retval);
}
#endif
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
png_uint_32 PNGAPI
png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
png_unknown_chunkpp unknowns)
{
if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
{
*unknowns = info_ptr->unknown_chunks;
return ((png_uint_32)info_ptr->unknown_chunks_num);
}
return (0);
}
#endif
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
png_byte PNGAPI
png_get_rgb_to_gray_status (png_structp png_ptr)
{
return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
}
#endif
#ifdef PNG_USER_CHUNKS_SUPPORTED
png_voidp PNGAPI
png_get_user_chunk_ptr(png_structp png_ptr)
{
return (png_ptr? png_ptr->user_chunk_ptr : NULL);
}
#endif
png_size_t PNGAPI
png_get_compression_buffer_size(png_structp png_ptr)
{
return (png_ptr ? png_ptr->zbuf_size : 0L);
}
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* These functions were added to libpng 1.2.6 and were enabled
* by default in libpng-1.4.0 */
png_uint_32 PNGAPI
png_get_user_width_max (png_structp png_ptr)
{
return (png_ptr? png_ptr->user_width_max : 0);
}
png_uint_32 PNGAPI
png_get_user_height_max (png_structp png_ptr)
{
return (png_ptr? png_ptr->user_height_max : 0);
}
/* This function was added to libpng 1.4.0 */
png_uint_32 PNGAPI
png_get_chunk_cache_max (png_structp png_ptr)
{
return (png_ptr? png_ptr->user_chunk_cache_max : 0);
}
/* This function was added to libpng 1.4.1 */
png_alloc_size_t PNGAPI
png_get_chunk_malloc_max (png_structp png_ptr)
{
return (png_ptr?
png_ptr->user_chunk_malloc_max : 0);
}
#endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
/* These functions were added to libpng 1.4.0 */
#ifdef PNG_IO_STATE_SUPPORTED
png_uint_32 PNGAPI
png_get_io_state (png_structp png_ptr)
{
return png_ptr->io_state;
}
png_bytep PNGAPI
png_get_io_chunk_name (png_structp png_ptr)
{
return png_ptr->chunk_name;
}
#endif /* ?PNG_IO_STATE_SUPPORTED */
#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
+611
View File
@@ -0,0 +1,611 @@
/* pngmem.c - stub functions for memory allocation
*
* Last changed in libpng 1.4.0 [February 25, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* This file provides a location for all memory allocation. Users who
* need special memory handling are expected to supply replacement
* functions for png_malloc() and png_free(), and to use
* png_create_read_struct_2() and png_create_write_struct_2() to
* identify the replacement functions.
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#include "pngpriv.h"
/* Borland DOS special memory handler */
#if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
/* If you change this, be sure to change the one in png.h also */
/* Allocate memory for a png_struct. The malloc and memset can be replaced
by a single call to calloc() if this is thought to improve performance. */
png_voidp /* PRIVATE */
png_create_struct(int type)
{
#ifdef PNG_USER_MEM_SUPPORTED
return (png_create_struct_2(type, NULL, NULL));
}
/* Alternate version of png_create_struct, for use with user-defined malloc. */
png_voidp /* PRIVATE */
png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
{
#endif /* PNG_USER_MEM_SUPPORTED */
png_size_t size;
png_voidp struct_ptr;
if (type == PNG_STRUCT_INFO)
size = png_sizeof(png_info);
else if (type == PNG_STRUCT_PNG)
size = png_sizeof(png_struct);
else
return (png_get_copyright(NULL));
#ifdef PNG_USER_MEM_SUPPORTED
if (malloc_fn != NULL)
{
png_struct dummy_struct;
png_structp png_ptr = &dummy_struct;
png_ptr->mem_ptr=mem_ptr;
struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
}
else
#endif /* PNG_USER_MEM_SUPPORTED */
struct_ptr = (png_voidp)farmalloc(size);
if (struct_ptr != NULL)
png_memset(struct_ptr, 0, size);
return (struct_ptr);
}
/* Free memory allocated by a png_create_struct() call */
void /* PRIVATE */
png_destroy_struct(png_voidp struct_ptr)
{
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2(struct_ptr, NULL, NULL);
}
/* Free memory allocated by a png_create_struct() call */
void /* PRIVATE */
png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
png_voidp mem_ptr)
{
#endif
if (struct_ptr != NULL)
{
#ifdef PNG_USER_MEM_SUPPORTED
if (free_fn != NULL)
{
png_struct dummy_struct;
png_structp png_ptr = &dummy_struct;
png_ptr->mem_ptr=mem_ptr;
(*(free_fn))(png_ptr, struct_ptr);
return;
}
#endif /* PNG_USER_MEM_SUPPORTED */
farfree (struct_ptr);
}
}
/* Allocate memory. For reasonable files, size should never exceed
* 64K. However, zlib may allocate more then 64K if you don't tell
* it not to. See zconf.h and png.h for more information. zlib does
* need to allocate exactly 64K, so whatever you call here must
* have the ability to do that.
*
* Borland seems to have a problem in DOS mode for exactly 64K.
* It gives you a segment with an offset of 8 (perhaps to store its
* memory stuff). zlib doesn't like this at all, so we have to
* detect and deal with it. This code should not be needed in
* Windows or OS/2 modes, and only in 16 bit mode. This code has
* been updated by Alexander Lehmann for version 0.89 to waste less
* memory.
*
* Note that we can't use png_size_t for the "size" declaration,
* since on some systems a png_size_t is a 16-bit quantity, and as a
* result, we would be truncating potentially larger memory requests
* (which should cause a fatal error) and introducing major problems.
*/
png_voidp PNGAPI
png_calloc(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ret;
ret = (png_malloc(png_ptr, size));
if (ret != NULL)
png_memset(ret,0,(png_size_t)size);
return (ret);
}
png_voidp PNGAPI
png_malloc(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ret;
if (png_ptr == NULL || size == 0)
return (NULL);
#ifdef PNG_USER_MEM_SUPPORTED
if (png_ptr->malloc_fn != NULL)
ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
else
ret = (png_malloc_default(png_ptr, size));
if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out of memory");
return (ret);
}
png_voidp PNGAPI
png_malloc_default(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ret;
#endif /* PNG_USER_MEM_SUPPORTED */
if (png_ptr == NULL || size == 0)
return (NULL);
#ifdef PNG_MAX_MALLOC_64K
if (size > (png_uint_32)65536L)
{
png_warning(png_ptr, "Cannot Allocate > 64K");
ret = NULL;
}
else
#endif
if (size != (size_t)size)
ret = NULL;
else if (size == (png_uint_32)65536L)
{
if (png_ptr->offset_table == NULL)
{
/* Try to see if we need to do any of this fancy stuff */
ret = farmalloc(size);
if (ret == NULL || ((png_size_t)ret & 0xffff))
{
int num_blocks;
png_uint_32 total_size;
png_bytep table;
int i;
png_byte huge * hptr;
if (ret != NULL)
{
farfree(ret);
ret = NULL;
}
if (png_ptr->zlib_window_bits > 14)
num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
else
num_blocks = 1;
if (png_ptr->zlib_mem_level >= 7)
num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
else
num_blocks++;
total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
table = farmalloc(total_size);
if (table == NULL)
{
#ifndef PNG_USER_MEM_SUPPORTED
if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out Of Memory"); /* Note "O", "M" */
else
png_warning(png_ptr, "Out Of Memory");
#endif
return (NULL);
}
if ((png_size_t)table & 0xfff0)
{
#ifndef PNG_USER_MEM_SUPPORTED
if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr,
"Farmalloc didn't return normalized pointer");
else
png_warning(png_ptr,
"Farmalloc didn't return normalized pointer");
#endif
return (NULL);
}
png_ptr->offset_table = table;
png_ptr->offset_table_ptr = farmalloc(num_blocks *
png_sizeof(png_bytep));
if (png_ptr->offset_table_ptr == NULL)
{
#ifndef PNG_USER_MEM_SUPPORTED
if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out Of memory"); /* Note "O", "m" */
else
png_warning(png_ptr, "Out Of memory");
#endif
return (NULL);
}
hptr = (png_byte huge *)table;
if ((png_size_t)hptr & 0xf)
{
hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
}
for (i = 0; i < num_blocks; i++)
{
png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
}
png_ptr->offset_table_number = num_blocks;
png_ptr->offset_table_count = 0;
png_ptr->offset_table_count_free = 0;
}
}
if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
{
#ifndef PNG_USER_MEM_SUPPORTED
if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out of Memory"); /* Note "o" and "M" */
else
png_warning(png_ptr, "Out of Memory");
#endif
return (NULL);
}
ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
}
else
ret = farmalloc(size);
#ifndef PNG_USER_MEM_SUPPORTED
if (ret == NULL)
{
if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out of memory"); /* Note "o" and "m" */
else
png_warning(png_ptr, "Out of memory"); /* Note "o" and "m" */
}
#endif
return (ret);
}
/* Free a pointer allocated by png_malloc(). In the default
* configuration, png_ptr is not used, but is passed in case it
* is needed. If ptr is NULL, return without taking any action.
*/
void PNGAPI
png_free(png_structp png_ptr, png_voidp ptr)
{
if (png_ptr == NULL || ptr == NULL)
return;
#ifdef PNG_USER_MEM_SUPPORTED
if (png_ptr->free_fn != NULL)
{
(*(png_ptr->free_fn))(png_ptr, ptr);
return;
}
else
png_free_default(png_ptr, ptr);
}
void PNGAPI
png_free_default(png_structp png_ptr, png_voidp ptr)
{
#endif /* PNG_USER_MEM_SUPPORTED */
if (png_ptr == NULL || ptr == NULL)
return;
if (png_ptr->offset_table != NULL)
{
int i;
for (i = 0; i < png_ptr->offset_table_count; i++)
{
if (ptr == png_ptr->offset_table_ptr[i])
{
ptr = NULL;
png_ptr->offset_table_count_free++;
break;
}
}
if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
{
farfree(png_ptr->offset_table);
farfree(png_ptr->offset_table_ptr);
png_ptr->offset_table = NULL;
png_ptr->offset_table_ptr = NULL;
}
}
if (ptr != NULL)
{
farfree(ptr);
}
}
#else /* Not the Borland DOS special memory handler */
/* Allocate memory for a png_struct or a png_info. The malloc and
memset can be replaced by a single call to calloc() if this is thought
to improve performance noticably. */
png_voidp /* PRIVATE */
png_create_struct(int type)
{
#ifdef PNG_USER_MEM_SUPPORTED
return (png_create_struct_2(type, NULL, NULL));
}
/* Allocate memory for a png_struct or a png_info. The malloc and
memset can be replaced by a single call to calloc() if this is thought
to improve performance noticably. */
png_voidp /* PRIVATE */
png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
{
#endif /* PNG_USER_MEM_SUPPORTED */
png_size_t size;
png_voidp struct_ptr;
if (type == PNG_STRUCT_INFO)
size = png_sizeof(png_info);
else if (type == PNG_STRUCT_PNG)
size = png_sizeof(png_struct);
else
return (NULL);
#ifdef PNG_USER_MEM_SUPPORTED
if (malloc_fn != NULL)
{
png_struct dummy_struct;
png_structp png_ptr = &dummy_struct;
png_ptr->mem_ptr=mem_ptr;
struct_ptr = (*(malloc_fn))(png_ptr, size);
if (struct_ptr != NULL)
png_memset(struct_ptr, 0, size);
return (struct_ptr);
}
#endif /* PNG_USER_MEM_SUPPORTED */
#if defined(__TURBOC__) && !defined(__FLAT__)
struct_ptr = (png_voidp)farmalloc(size);
#else
# if defined(_MSC_VER) && defined(MAXSEG_64K)
struct_ptr = (png_voidp)halloc(size, 1);
# else
struct_ptr = (png_voidp)malloc(size);
# endif
#endif
if (struct_ptr != NULL)
png_memset(struct_ptr, 0, size);
return (struct_ptr);
}
/* Free memory allocated by a png_create_struct() call */
void /* PRIVATE */
png_destroy_struct(png_voidp struct_ptr)
{
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2(struct_ptr, NULL, NULL);
}
/* Free memory allocated by a png_create_struct() call */
void /* PRIVATE */
png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
png_voidp mem_ptr)
{
#endif /* PNG_USER_MEM_SUPPORTED */
if (struct_ptr != NULL)
{
#ifdef PNG_USER_MEM_SUPPORTED
if (free_fn != NULL)
{
png_struct dummy_struct;
png_structp png_ptr = &dummy_struct;
png_ptr->mem_ptr=mem_ptr;
(*(free_fn))(png_ptr, struct_ptr);
return;
}
#endif /* PNG_USER_MEM_SUPPORTED */
#if defined(__TURBOC__) && !defined(__FLAT__)
farfree(struct_ptr);
#else
# if defined(_MSC_VER) && defined(MAXSEG_64K)
hfree(struct_ptr);
# else
free(struct_ptr);
# endif
#endif
}
}
/* Allocate memory. For reasonable files, size should never exceed
* 64K. However, zlib may allocate more then 64K if you don't tell
* it not to. See zconf.h and png.h for more information. zlib does
* need to allocate exactly 64K, so whatever you call here must
* have the ability to do that.
*/
png_voidp PNGAPI
png_calloc(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ret;
ret = (png_malloc(png_ptr, size));
if (ret != NULL)
png_memset(ret,0,(png_size_t)size);
return (ret);
}
png_voidp PNGAPI
png_malloc(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ret;
#ifdef PNG_USER_MEM_SUPPORTED
if (png_ptr == NULL || size == 0)
return (NULL);
if (png_ptr->malloc_fn != NULL)
ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
else
ret = (png_malloc_default(png_ptr, size));
if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out of Memory");
return (ret);
}
png_voidp PNGAPI
png_malloc_default(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ret;
#endif /* PNG_USER_MEM_SUPPORTED */
if (png_ptr == NULL || size == 0)
return (NULL);
#ifdef PNG_MAX_MALLOC_64K
if (size > (png_uint_32)65536L)
{
#ifndef PNG_USER_MEM_SUPPORTED
if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Cannot Allocate > 64K");
else
#endif
return NULL;
}
#endif
/* Check for overflow */
#if defined(__TURBOC__) && !defined(__FLAT__)
if (size != (unsigned long)size)
ret = NULL;
else
ret = farmalloc(size);
#else
# if defined(_MSC_VER) && defined(MAXSEG_64K)
if (size != (unsigned long)size)
ret = NULL;
else
ret = halloc(size, 1);
# else
if (size != (size_t)size)
ret = NULL;
else
ret = malloc((size_t)size);
# endif
#endif
#ifndef PNG_USER_MEM_SUPPORTED
if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
png_error(png_ptr, "Out of Memory");
#endif
return (ret);
}
/* Free a pointer allocated by png_malloc(). If ptr is NULL, return
* without taking any action.
*/
void PNGAPI
png_free(png_structp png_ptr, png_voidp ptr)
{
if (png_ptr == NULL || ptr == NULL)
return;
#ifdef PNG_USER_MEM_SUPPORTED
if (png_ptr->free_fn != NULL)
{
(*(png_ptr->free_fn))(png_ptr, ptr);
return;
}
else
png_free_default(png_ptr, ptr);
}
void PNGAPI
png_free_default(png_structp png_ptr, png_voidp ptr)
{
if (png_ptr == NULL || ptr == NULL)
return;
#endif /* PNG_USER_MEM_SUPPORTED */
#if defined(__TURBOC__) && !defined(__FLAT__)
farfree(ptr);
#else
# if defined(_MSC_VER) && defined(MAXSEG_64K)
hfree(ptr);
# else
free(ptr);
# endif
#endif
}
#endif /* Not Borland DOS special memory handler */
/* This function was added at libpng version 1.2.3. The png_malloc_warn()
* function will set up png_malloc() to issue a png_warning and return NULL
* instead of issuing a png_error, if it fails to allocate the requested
* memory.
*/
png_voidp PNGAPI
png_malloc_warn(png_structp png_ptr, png_alloc_size_t size)
{
png_voidp ptr;
png_uint_32 save_flags;
if (png_ptr == NULL)
return (NULL);
save_flags = png_ptr->flags;
png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
png_ptr->flags=save_flags;
return(ptr);
}
#ifdef PNG_USER_MEM_SUPPORTED
/* This function is called when the application wants to use another method
* of allocating and freeing memory.
*/
void PNGAPI
png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
malloc_fn, png_free_ptr free_fn)
{
if (png_ptr != NULL)
{
png_ptr->mem_ptr = mem_ptr;
png_ptr->malloc_fn = malloc_fn;
png_ptr->free_fn = free_fn;
}
}
/* This function returns a pointer to the mem_ptr associated with the user
* functions. The application should free any memory associated with this
* pointer before png_write_destroy and png_read_destroy are called.
*/
png_voidp PNGAPI
png_get_mem_ptr(png_structp png_ptr)
{
if (png_ptr == NULL)
return (NULL);
return ((png_voidp)png_ptr->mem_ptr);
}
#endif /* PNG_USER_MEM_SUPPORTED */
#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
File diff suppressed because it is too large. Load diff
+956
View File
@@ -0,0 +1,956 @@
/* pngpriv.h - private declarations for use inside libpng
*
* libpng version 1.4.1 - February 25, 2010
* For conditions of distribution and use, see copyright notice in png.h
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
/* The symbols declared in this file (including the functions declared
* as PNG_EXTERN) are PRIVATE. They are not part of the libpng public
* interface, and are not recommended for use by regular applications.
* Some of them may become public in the future; others may stay private,
* change in an incompatible way, or even disappear.
* Although the libpng users are not forbidden to include this header,
* they should be well aware of the issues that may arise from doing so.
*/
#ifndef PNGPRIV_H
#define PNGPRIV_H
#ifndef PNG_VERSION_INFO_ONLY
#include <stdlib.h>
/* The functions exported by PNG_EXTERN are internal functions, which
* aren't usually used outside the library (as far as I know), so it is
* debatable if they should be exported at all. In the future, when it
* is possible to have run-time registry of chunk-handling functions,
* some of these will be made available again.
#define PNG_EXTERN extern
*/
#define PNG_EXTERN
/* Other defines specific to compilers can go here. Try to keep
* them inside an appropriate ifdef/endif pair for portability.
*/
#ifdef PNG_FLOATING_POINT_SUPPORTED
# ifdef MACOS
/* We need to check that <math.h> hasn't already been included earlier
* as it seems it doesn't agree with <fp.h>, yet we should really use
* <fp.h> if possible.
*/
# if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
# include <fp.h>
# endif
# else
# include <math.h>
# endif
# if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
/* Amiga SAS/C: We must include builtin FPU functions when compiling using
* MATH=68881
*/
# include <m68881.h>
# endif
#endif
/* Codewarrior on NT has linking problems without this. */
#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
# define PNG_ALWAYS_EXTERN
#endif
/* This provides the non-ANSI (far) memory allocation routines. */
#if defined(__TURBOC__) && defined(__MSDOS__)
# include <mem.h>
# include <alloc.h>
#endif
#if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \
defined(_WIN32) || defined(__WIN32__)
# include <windows.h> /* defines _WINDOWS_ macro */
/* I have no idea why is this necessary... */
# ifdef _MSC_VER
# include <malloc.h>
# endif
#endif
/* Various modes of operation. Note that after an init, mode is set to
* zero automatically when the structure is created.
*/
#define PNG_HAVE_IHDR 0x01
#define PNG_HAVE_PLTE 0x02
#define PNG_HAVE_IDAT 0x04
#define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
#define PNG_HAVE_IEND 0x10
#define PNG_HAVE_gAMA 0x20
#define PNG_HAVE_cHRM 0x40
#define PNG_HAVE_sRGB 0x80
#define PNG_HAVE_CHUNK_HEADER 0x100
#define PNG_WROTE_tIME 0x200
#define PNG_WROTE_INFO_BEFORE_PLTE 0x400
#define PNG_BACKGROUND_IS_GRAY 0x800
#define PNG_HAVE_PNG_SIGNATURE 0x1000
#define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
/* Flags for the transformations the PNG library does on the image data */
#define PNG_BGR 0x0001
#define PNG_INTERLACE 0x0002
#define PNG_PACK 0x0004
#define PNG_SHIFT 0x0008
#define PNG_SWAP_BYTES 0x0010
#define PNG_INVERT_MONO 0x0020
#define PNG_DITHER 0x0040
#define PNG_BACKGROUND 0x0080
#define PNG_BACKGROUND_EXPAND 0x0100
/* 0x0200 unused */
#define PNG_16_TO_8 0x0400
#define PNG_RGBA 0x0800
#define PNG_EXPAND 0x1000
#define PNG_GAMMA 0x2000
#define PNG_GRAY_TO_RGB 0x4000
#define PNG_FILLER 0x8000L
#define PNG_PACKSWAP 0x10000L
#define PNG_SWAP_ALPHA 0x20000L
#define PNG_STRIP_ALPHA 0x40000L
#define PNG_INVERT_ALPHA 0x80000L
#define PNG_USER_TRANSFORM 0x100000L
#define PNG_RGB_TO_GRAY_ERR 0x200000L
#define PNG_RGB_TO_GRAY_WARN 0x400000L
#define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
/* 0x800000L Unused */
#define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
#define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
/* 0x4000000L unused */
/* 0x8000000L unused */
/* 0x10000000L unused */
/* 0x20000000L unused */
/* 0x40000000L unused */
/* Flags for png_create_struct */
#define PNG_STRUCT_PNG 0x0001
#define PNG_STRUCT_INFO 0x0002
/* Scaling factor for filter heuristic weighting calculations */
#define PNG_WEIGHT_SHIFT 8
#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
#define PNG_COST_SHIFT 3
#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
/* Flags for the png_ptr->flags rather than declaring a byte for each one */
#define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
#define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
#define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
#define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
#define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
#define PNG_FLAG_ZLIB_FINISHED 0x0020
#define PNG_FLAG_ROW_INIT 0x0040
#define PNG_FLAG_FILLER_AFTER 0x0080
#define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
#define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
#define PNG_FLAG_CRC_CRITICAL_USE 0x0400
#define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
/* 0x1000 unused */
/* 0x2000 unused */
/* 0x4000 unused */
#define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
#define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
#define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
#define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
#define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
#define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
#define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
#define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
#define PNG_FLAG_BENIGN_ERRORS_WARN 0x800000L /* Added to libpng-1.4.0 */
/* 0x1000000L unused */
/* 0x2000000L unused */
/* 0x4000000L unused */
/* 0x8000000L unused */
/* 0x10000000L unused */
/* 0x20000000L unused */
/* 0x40000000L unused */
#define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
PNG_FLAG_CRC_ANCILLARY_NOWARN)
#define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
PNG_FLAG_CRC_CRITICAL_IGNORE)
#define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
PNG_FLAG_CRC_CRITICAL_MASK)
/* Save typing and make code easier to understand */
#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
abs((int)((c1).green) - (int)((c2).green)) + \
abs((int)((c1).blue) - (int)((c2).blue)))
/* Added to libpng-1.2.6 JB */
#define PNG_ROWBYTES(pixel_bits, width) \
((pixel_bits) >= 8 ? \
((png_size_t)(width) * (((png_size_t)(pixel_bits)) >> 3)) : \
(( ((png_size_t)(width) * ((png_size_t)(pixel_bits))) + 7) >> 3) )
/* PNG_OUT_OF_RANGE returns true if value is outside the range
* ideal-delta..ideal+delta. Each argument is evaluated twice.
* "ideal" and "delta" should be constants, normally simple
* integers, "value" a variable. Added to libpng-1.2.6 JB
*/
#define PNG_OUT_OF_RANGE(value, ideal, delta) \
( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
/* Constant strings for known chunk types. If you need to add a chunk,
* define the name here, and add an invocation of the macro wherever it's
* needed.
*/
#define PNG_IHDR PNG_CONST png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
#define PNG_IDAT PNG_CONST png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
#define PNG_IEND PNG_CONST png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
#define PNG_PLTE PNG_CONST png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
#define PNG_bKGD PNG_CONST png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
#define PNG_cHRM PNG_CONST png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
#define PNG_gAMA PNG_CONST png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
#define PNG_hIST PNG_CONST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
#define PNG_iCCP PNG_CONST png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
#define PNG_iTXt PNG_CONST png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
#define PNG_oFFs PNG_CONST png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
#define PNG_pCAL PNG_CONST png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
#define PNG_sCAL PNG_CONST png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
#define PNG_pHYs PNG_CONST png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
#define PNG_sBIT PNG_CONST png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
#define PNG_sPLT PNG_CONST png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
#define PNG_sRGB PNG_CONST png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
#define PNG_sTER PNG_CONST png_byte png_sTER[5] = {115, 84, 69, 82, '\0'}
#define PNG_tEXt PNG_CONST png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
#define PNG_tIME PNG_CONST png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
#define PNG_tRNS PNG_CONST png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
#define PNG_zTXt PNG_CONST png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
/* Inhibit C++ name-mangling for libpng functions but not for system calls. */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* These functions are used internally in the code. They generally
* shouldn't be used unless you are writing code to add or replace some
* functionality in libpng. More information about most functions can
* be found in the files where the functions are located.
*/
/* Allocate memory for an internal libpng struct */
PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
/* Free memory from internal libpng struct */
PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
malloc_fn, png_voidp mem_ptr));
PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
png_free_ptr free_fn, png_voidp mem_ptr));
/* Free any memory that info_ptr points to and reset struct. */
PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
png_infop info_ptr));
/* Function to allocate memory for zlib. PNGAPI is disallowed. */
PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
/* Function to free memory for zlib. PNGAPI is disallowed. */
PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
/* Next four functions are used internally as callbacks. PNGAPI is required
* but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
png_bytep data, png_size_t length));
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
png_bytep buffer, png_size_t length));
#endif
PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
png_bytep data, png_size_t length));
#ifdef PNG_WRITE_FLUSH_SUPPORTED
#ifdef PNG_STDIO_SUPPORTED
PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
#endif
#endif
/* Reset the CRC variable */
PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
/* Write the "data" buffer to whatever output you are using */
PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
png_size_t length));
/* Read the chunk header (length + type name) */
PNG_EXTERN png_uint_32 png_read_chunk_header PNGARG((png_structp png_ptr));
/* Read data from whatever input you are using into the "data" buffer */
PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
png_size_t length));
/* Read bytes into buf, and update png_ptr->crc */
PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
png_size_t length));
/* Decompress data in a chunk that uses compression */
#if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
PNG_EXTERN void png_decompress_chunk PNGARG((png_structp png_ptr,
int comp_type, png_size_t chunklength, png_size_t prefix_length,
png_size_t *data_length));
#endif
/* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
/* Read the CRC from the file and compare it to the libpng calculated CRC */
PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
/* Calculate the CRC over a section of data. Note that we are only
* passing a maximum of 64K on systems that have this as a memory limit,
* since this is the maximum buffer size we can specify.
*/
PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
png_size_t length));
#ifdef PNG_WRITE_FLUSH_SUPPORTED
PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
#endif
/* Write various chunks */
/* Write the IHDR chunk, and update the png_struct with the necessary
* information.
*/
PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
png_uint_32 height,
int bit_depth, int color_type, int compression_method, int filter_method,
int interlace_method));
PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
png_uint_32 num_pal));
PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
png_size_t length));
PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
#ifdef PNG_WRITE_gAMA_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
#endif
#ifdef PNG_FIXED_POINT_SUPPORTED
PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr,
png_fixed_point file_gamma));
#endif
#endif
#ifdef PNG_WRITE_sBIT_SUPPORTED
PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
int color_type));
#endif
#ifdef PNG_WRITE_cHRM_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
double white_x, double white_y,
double red_x, double red_y, double green_x, double green_y,
double blue_x, double blue_y));
#endif
PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
png_fixed_point int_white_x, png_fixed_point int_white_y,
png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
png_fixed_point int_blue_y));
#endif
#ifdef PNG_WRITE_sRGB_SUPPORTED
PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
int intent));
#endif
#ifdef PNG_WRITE_iCCP_SUPPORTED
PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
png_charp name, int compression_type,
png_charp profile, int proflen));
/* Note to maintainer: profile should be png_bytep */
#endif
#ifdef PNG_WRITE_sPLT_SUPPORTED
PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
png_sPLT_tp palette));
#endif
#ifdef PNG_WRITE_tRNS_SUPPORTED
PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
png_color_16p values, int number, int color_type));
#endif
#ifdef PNG_WRITE_bKGD_SUPPORTED
PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
png_color_16p values, int color_type));
#endif
#ifdef PNG_WRITE_hIST_SUPPORTED
PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
int num_hist));
#endif
#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
png_charp key, png_charpp new_key));
#endif
#ifdef PNG_WRITE_tEXt_SUPPORTED
PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
png_charp text, png_size_t text_len));
#endif
#ifdef PNG_WRITE_zTXt_SUPPORTED
PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
png_charp text, png_size_t text_len, int compression));
#endif
#ifdef PNG_WRITE_iTXt_SUPPORTED
PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
int compression, png_charp key, png_charp lang, png_charp lang_key,
png_charp text));
#endif
#ifdef PNG_TEXT_SUPPORTED /* Added at version 1.0.14 and 1.2.4 */
PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
png_infop info_ptr, png_textp text_ptr, int num_text));
#endif
#ifdef PNG_WRITE_oFFs_SUPPORTED
PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
png_int_32 x_offset, png_int_32 y_offset, int unit_type));
#endif
#ifdef PNG_WRITE_pCAL_SUPPORTED
PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
png_int_32 X0, png_int_32 X1, int type, int nparams,
png_charp units, png_charpp params));
#endif
#ifdef PNG_WRITE_pHYs_SUPPORTED
PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
int unit_type));
#endif
#ifdef PNG_WRITE_tIME_SUPPORTED
PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
png_timep mod_time));
#endif
#ifdef PNG_WRITE_sCAL_SUPPORTED
#if defined(PNG_FLOATING_POINT_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
int unit, double width, double height));
#else
#ifdef PNG_FIXED_POINT_SUPPORTED
PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
int unit, png_charp width, png_charp height));
#endif
#endif
#endif
/* Called when finished processing a row of data */
PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
/* Internal use only. Called before first row of data */
PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
#ifdef PNG_READ_GAMMA_SUPPORTED
PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr,
png_byte bit_depth));
#endif
/* Combine a row of data, dealing with alpha, etc. if requested */
PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
int mask));
#ifdef PNG_READ_INTERLACING_SUPPORTED
/* Expand an interlaced row */
/* OLD pre-1.0.9 interface:
PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
png_bytep row, int pass, png_uint_32 transformations));
*/
PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
#endif
/* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Grab pixels out of a row for an interlaced pass */
PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
png_bytep row, int pass));
#endif
/* Unfilter a row */
PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
/* Choose the best filter to use and filter the row data */
PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
png_row_infop row_info));
/* Write out the filtered row. */
PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
png_bytep filtered_row));
/* Finish a row while reading, dealing with interlacing passes, etc. */
PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
/* Initialize the row buffers, etc. */
PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
/* Optional call to update the users info structure */
PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
png_infop info_ptr));
/* These are the functions that do the transformations */
#ifdef PNG_READ_FILLER_SUPPORTED
PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
png_bytep row, png_uint_32 filler, png_uint_32 flags));
#endif
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
png_bytep row, png_uint_32 flags));
#endif
#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
#endif
#if defined(PNG_READ_PACKSWAP_SUPPORTED) || \
defined(PNG_WRITE_PACKSWAP_SUPPORTED)
PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
#endif
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
row_info, png_bytep row));
#endif
#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
png_bytep row));
#endif
#ifdef PNG_READ_PACK_SUPPORTED
PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
#endif
#ifdef PNG_READ_SHIFT_SUPPORTED
PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
png_color_8p sig_bits));
#endif
#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
#endif
#ifdef PNG_READ_16_TO_8_SUPPORTED
PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
#endif
#ifdef PNG_READ_DITHER_SUPPORTED
PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
# ifdef PNG_CORRECT_PALETTE_SUPPORTED
PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
png_colorp palette, int num_palette));
# endif
#endif
#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
#endif
#ifdef PNG_WRITE_PACK_SUPPORTED
PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
png_bytep row, png_uint_32 bit_depth));
#endif
#ifdef PNG_WRITE_SHIFT_SUPPORTED
PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
png_color_8p bit_depth));
#endif
#ifdef PNG_READ_BACKGROUND_SUPPORTED
#ifdef PNG_READ_GAMMA_SUPPORTED
PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
png_color_16p trans_color, png_color_16p background,
png_color_16p background_1,
png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
png_uint_16pp gamma_16_to_1, int gamma_shift));
#else
PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
png_color_16p trans_color, png_color_16p background));
#endif
#endif
#ifdef PNG_READ_GAMMA_SUPPORTED
PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
png_bytep gamma_table, png_uint_16pp gamma_16_table,
int gamma_shift));
#endif
#ifdef PNG_READ_EXPAND_SUPPORTED
PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
png_bytep row, png_color_16p trans_value));
#endif
/* The following decodes the appropriate chunks, and does error correction,
* then calls the appropriate callback for the chunk if it is valid.
*/
/* Decode the IHDR chunk */
PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#ifdef PNG_READ_bKGD_SUPPORTED
PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_cHRM_SUPPORTED
PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_gAMA_SUPPORTED
PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_hIST_SUPPORTED
PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_iCCP_SUPPORTED
extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif /* PNG_READ_iCCP_SUPPORTED */
#ifdef PNG_READ_iTXt_SUPPORTED
PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_oFFs_SUPPORTED
PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_pCAL_SUPPORTED
PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_pHYs_SUPPORTED
PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_sBIT_SUPPORTED
PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_sCAL_SUPPORTED
PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_sPLT_SUPPORTED
extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif /* PNG_READ_sPLT_SUPPORTED */
#ifdef PNG_READ_sRGB_SUPPORTED
PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_tEXt_SUPPORTED
PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_tIME_SUPPORTED
PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_tRNS_SUPPORTED
PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
#ifdef PNG_READ_zTXt_SUPPORTED
PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
png_uint_32 length));
#endif
PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
png_bytep chunk_name));
/* Handle the transformations for reading and writing */
PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
png_uint_32 length));
PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
png_bytep buffer, png_size_t buffer_length));
PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
png_bytep buffer, png_size_t buffer_length));
PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
png_infop info_ptr));
PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
#ifdef PNG_READ_tEXt_SUPPORTED
PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
png_infop info_ptr));
#endif
#ifdef PNG_READ_zTXt_SUPPORTED
PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
png_infop info_ptr));
#endif
#ifdef PNG_READ_iTXt_SUPPORTED
PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 length));
PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
png_infop info_ptr));
#endif
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
#ifdef PNG_MNG_FEATURES_SUPPORTED
PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
png_bytep row));
PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
png_bytep row));
#endif
/* Added at libpng version 1.4.0 */
#ifdef PNG_cHRM_SUPPORTED
PNG_EXTERN int png_check_cHRM_fixed PNGARG((png_structp png_ptr,
png_fixed_point int_white_x, png_fixed_point int_white_y,
png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
png_fixed_point int_blue_y));
#endif
#ifdef PNG_cHRM_SUPPORTED
#ifdef PNG_CHECK_cHRM_SUPPORTED
/* Added at libpng version 1.2.34 and 1.4.0 */
PNG_EXTERN void png_64bit_product PNGARG((long v1, long v2,
unsigned long *hi_product, unsigned long *lo_product));
#endif
#endif
/* Added at libpng version 1.4.0 */
PNG_EXTERN void png_check_IHDR PNGARG((png_structp png_ptr,
png_uint_32 width, png_uint_32 height, int bit_depth,
int color_type, int interlace_type, int compression_type,
int filter_type));
/* Free all memory used by the read (old method - NOT DLL EXPORTED) */
extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
png_infop end_info_ptr));
/* Free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
extern void png_write_destroy PNGARG((png_structp png_ptr));
#ifdef USE_FAR_KEYWORD /* memory model conversion function */
extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
int check));
#endif /* USE_FAR_KEYWORD */
/* Define PNG_DEBUG at compile time for debugging information. Higher
* numbers for PNG_DEBUG mean more debugging information. This has
* only been added since version 0.95 so it is not implemented throughout
* libpng yet, but more support will be added as needed.
*/
#ifdef PNG_DEBUG
#if (PNG_DEBUG > 0)
#if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
#include <crtdbg.h>
#if (PNG_DEBUG > 1)
#ifndef _DEBUG
# define _DEBUG
#endif
#ifndef png_debug
#define png_debug(l,m) _RPT0(_CRT_WARN,m PNG_STRING_NEWLINE)
#endif
#ifndef png_debug1
#define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m PNG_STRING_NEWLINE,p1)
#endif
#ifndef png_debug2
#define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m PNG_STRING_NEWLINE,p1,p2)
#endif
#endif
#else /* PNG_DEBUG_FILE || !_MSC_VER */
#ifndef PNG_DEBUG_FILE
#define PNG_DEBUG_FILE stderr
#endif /* PNG_DEBUG_FILE */
#if (PNG_DEBUG > 1)
/* Note: ["%s"m PNG_STRING_NEWLINE] probably does not work on
* non-ISO compilers
*/
# ifdef __STDC__
# ifndef png_debug
# define png_debug(l,m) \
{ \
int num_tabs=l; \
fprintf(PNG_DEBUG_FILE,"%s"m PNG_STRING_NEWLINE,(num_tabs==1 ? "\t" : \
(num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
}
# endif
# ifndef png_debug1
# define png_debug1(l,m,p1) \
{ \
int num_tabs=l; \
fprintf(PNG_DEBUG_FILE,"%s"m PNG_STRING_NEWLINE,(num_tabs==1 ? "\t" : \
(num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
}
# endif
# ifndef png_debug2
# define png_debug2(l,m,p1,p2) \
{ \
int num_tabs=l; \
fprintf(PNG_DEBUG_FILE,"%s"m PNG_STRING_NEWLINE,(num_tabs==1 ? "\t" : \
(num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
}
# endif
# else /* __STDC __ */
# ifndef png_debug
# define png_debug(l,m) \
{ \
int num_tabs=l; \
char format[256]; \
snprintf(format,256,"%s%s%s",(num_tabs==1 ? "\t" : \
(num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))), \
m,PNG_STRING_NEWLINE); \
fprintf(PNG_DEBUG_FILE,format); \
}
# endif
# ifndef png_debug1
# define png_debug1(l,m,p1) \
{ \
int num_tabs=l; \
char format[256]; \
snprintf(format,256,"%s%s%s",(num_tabs==1 ? "\t" : \
(num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))), \
m,PNG_STRING_NEWLINE); \
fprintf(PNG_DEBUG_FILE,format,p1); \
}
# endif
# ifndef png_debug2
# define png_debug2(l,m,p1,p2) \
{ \
int num_tabs=l; \
char format[256]; \
snprintf(format,256,"%s%s%s",(num_tabs==1 ? "\t" : \
(num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))), \
m,PNG_STRING_NEWLINE); \
fprintf(PNG_DEBUG_FILE,format,p1,p2); \
}
# endif
# endif /* __STDC __ */
#endif /* (PNG_DEBUG > 1) */
#endif /* _MSC_VER */
#endif /* (PNG_DEBUG > 0) */
#endif /* PNG_DEBUG */
#ifndef png_debug
#define png_debug(l, m)
#endif
#ifndef png_debug1
#define png_debug1(l, m, p1)
#endif
#ifndef png_debug2
#define png_debug2(l, m, p1, p2)
#endif
/* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
#ifdef __cplusplus
}
#endif
#endif /* PNG_VERSION_INFO_ONLY */
#endif /* PNGPRIV_H */
File diff suppressed because it is too large. Load diff
+163
View File
@@ -0,0 +1,163 @@
/* pngrio.c - functions for data input
*
* Last changed in libpng 1.4.1 [February 25, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* This file provides a location for all input. Users who need
* special handling are expected to write a function that has the same
* arguments as this and performs a similar function, but that possibly
* has a different input method. Note that you shouldn't change this
* function, but rather write a replacement function and then make
* libpng use it at run time with png_set_read_fn(...).
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#ifdef PNG_READ_SUPPORTED
#include "pngpriv.h"
/* Read the data from whatever input you are using. The default routine
* reads from a file pointer. Note that this routine sometimes gets called
* with very small lengths, so you should implement some kind of simple
* buffering if you are using unbuffered reads. This should never be asked
* to read more then 64K on a 16 bit machine.
*/
void /* PRIVATE */
png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_debug1(4, "reading %d bytes", (int)length);
if (png_ptr->read_data_fn != NULL)
(*(png_ptr->read_data_fn))(png_ptr, data, length);
else
png_error(png_ptr, "Call to NULL read function");
}
#ifdef PNG_STDIO_SUPPORTED
/* This is the function that does the actual reading of data. If you are
* not reading from a standard C stream, you should create a replacement
* read_data function and use it at run time with png_set_read_fn(), rather
* than changing the library.
*/
#ifndef USE_FAR_KEYWORD
void PNGAPI
png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_size_t check;
if (png_ptr == NULL)
return;
/* fread() returns 0 on error, so it is OK to store this in a png_size_t
* instead of an int, which is what fread() actually returns.
*/
check = fread(data, 1, length, (png_FILE_p)png_ptr->io_ptr);
if (check != length)
png_error(png_ptr, "Read Error");
}
#else
/* This is the model-independent version. Since the standard I/O library
can't handle far buffers in the medium and small models, we have to copy
the data.
*/
#define NEAR_BUF_SIZE 1024
#define MIN(a,b) (a <= b ? a : b)
static void PNGAPI
png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_size_t check;
png_byte *n_data;
png_FILE_p io_ptr;
if (png_ptr == NULL)
return;
/* Check if data really is near. If so, use usual code. */
n_data = (png_byte *)CVT_PTR_NOCHECK(data);
io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
if ((png_bytep)n_data == data)
{
check = fread(n_data, 1, length, io_ptr);
}
else
{
png_byte buf[NEAR_BUF_SIZE];
png_size_t read, remaining, err;
check = 0;
remaining = length;
do
{
read = MIN(NEAR_BUF_SIZE, remaining);
err = fread(buf, 1, read, io_ptr);
png_memcpy(data, buf, read); /* copy far buffer to near buffer */
if (err != read)
break;
else
check += err;
data += read;
remaining -= read;
}
while (remaining != 0);
}
if ((png_uint_32)check != (png_uint_32)length)
png_error(png_ptr, "read Error");
}
#endif
#endif
/* This function allows the application to supply a new input function
* for libpng if standard C streams aren't being used.
*
* This function takes as its arguments:
* png_ptr - pointer to a png input data structure
* io_ptr - pointer to user supplied structure containing info about
* the input functions. May be NULL.
* read_data_fn - pointer to a new input function that takes as its
* arguments a pointer to a png_struct, a pointer to
* a location where input data can be stored, and a 32-bit
* unsigned int that is the number of bytes to be read.
* To exit and output any fatal error messages the new write
* function should call png_error(png_ptr, "Error msg").
* May be NULL, in which case libpng's default function will
* be used.
*/
void PNGAPI
png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr read_data_fn)
{
if (png_ptr == NULL)
return;
png_ptr->io_ptr = io_ptr;
#ifdef PNG_STDIO_SUPPORTED
if (read_data_fn != NULL)
png_ptr->read_data_fn = read_data_fn;
else
png_ptr->read_data_fn = png_default_read_data;
#else
png_ptr->read_data_fn = read_data_fn;
#endif
/* It is an error to write to a read device */
if (png_ptr->write_data_fn != NULL)
{
png_ptr->write_data_fn = NULL;
png_warning(png_ptr,
"It's an error to set both read_data_fn and write_data_fn in the ");
png_warning(png_ptr,
"same structure. Resetting write_data_fn to NULL");
}
#ifdef PNG_WRITE_FLUSH_SUPPORTED
png_ptr->output_flush_fn = NULL;
#endif
}
#endif /* PNG_READ_SUPPORTED */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+676
View File
@@ -0,0 +1,676 @@
/* pngtrans.c - transforms the data in a row (used by both readers and writers)
*
* Last changed in libpng 1.4.0 [January 3, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
#include "pngpriv.h"
#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
/* Turn on BGR-to-RGB mapping */
void PNGAPI
png_set_bgr(png_structp png_ptr)
{
png_debug(1, "in png_set_bgr");
if (png_ptr == NULL)
return;
png_ptr->transformations |= PNG_BGR;
}
#endif
#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
/* Turn on 16 bit byte swapping */
void PNGAPI
png_set_swap(png_structp png_ptr)
{
png_debug(1, "in png_set_swap");
if (png_ptr == NULL)
return;
if (png_ptr->bit_depth == 16)
png_ptr->transformations |= PNG_SWAP_BYTES;
}
#endif
#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
/* Turn on pixel packing */
void PNGAPI
png_set_packing(png_structp png_ptr)
{
png_debug(1, "in png_set_packing");
if (png_ptr == NULL)
return;
if (png_ptr->bit_depth < 8)
{
png_ptr->transformations |= PNG_PACK;
png_ptr->usr_bit_depth = 8;
}
}
#endif
#if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
/* Turn on packed pixel swapping */
void PNGAPI
png_set_packswap(png_structp png_ptr)
{
png_debug(1, "in png_set_packswap");
if (png_ptr == NULL)
return;
if (png_ptr->bit_depth < 8)
png_ptr->transformations |= PNG_PACKSWAP;
}
#endif
#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
void PNGAPI
png_set_shift(png_structp png_ptr, png_color_8p true_bits)
{
png_debug(1, "in png_set_shift");
if (png_ptr == NULL)
return;
png_ptr->transformations |= PNG_SHIFT;
png_ptr->shift = *true_bits;
}
#endif
#if defined(PNG_READ_INTERLACING_SUPPORTED) || \
defined(PNG_WRITE_INTERLACING_SUPPORTED)
int PNGAPI
png_set_interlace_handling(png_structp png_ptr)
{
png_debug(1, "in png_set_interlace handling");
if (png_ptr && png_ptr->interlaced)
{
png_ptr->transformations |= PNG_INTERLACE;
return (7);
}
return (1);
}
#endif
#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
/* Add a filler byte on read, or remove a filler or alpha byte on write.
* The filler type has changed in v0.95 to allow future 2-byte fillers
* for 48-bit input data, as well as to avoid problems with some compilers
* that don't like bytes as parameters.
*/
void PNGAPI
png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
{
png_debug(1, "in png_set_filler");
if (png_ptr == NULL)
return;
png_ptr->transformations |= PNG_FILLER;
png_ptr->filler = (png_uint_16)filler;
if (filler_loc == PNG_FILLER_AFTER)
png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
else
png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
/* This should probably go in the "do_read_filler" routine.
* I attempted to do that in libpng-1.0.1a but that caused problems
* so I restored it in libpng-1.0.2a
*/
if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
{
png_ptr->usr_channels = 4;
}
/* Also I added this in libpng-1.0.2a (what happens when we expand
* a less-than-8-bit grayscale to GA? */
if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
{
png_ptr->usr_channels = 2;
}
}
/* Added to libpng-1.2.7 */
void PNGAPI
png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
{
png_debug(1, "in png_set_add_alpha");
if (png_ptr == NULL)
return;
png_set_filler(png_ptr, filler, filler_loc);
png_ptr->transformations |= PNG_ADD_ALPHA;
}
#endif
#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
void PNGAPI
png_set_swap_alpha(png_structp png_ptr)
{
png_debug(1, "in png_set_swap_alpha");
if (png_ptr == NULL)
return;
png_ptr->transformations |= PNG_SWAP_ALPHA;
}
#endif
#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
void PNGAPI
png_set_invert_alpha(png_structp png_ptr)
{
png_debug(1, "in png_set_invert_alpha");
if (png_ptr == NULL)
return;
png_ptr->transformations |= PNG_INVERT_ALPHA;
}
#endif
#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
void PNGAPI
png_set_invert_mono(png_structp png_ptr)
{
png_debug(1, "in png_set_invert_mono");
if (png_ptr == NULL)
return;
png_ptr->transformations |= PNG_INVERT_MONO;
}
/* Invert monochrome grayscale data */
void /* PRIVATE */
png_do_invert(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_invert");
/* This test removed from libpng version 1.0.13 and 1.2.0:
* if (row_info->bit_depth == 1 &&
*/
if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
{
png_bytep rp = row;
png_uint_32 i;
png_uint_32 istop = row_info->rowbytes;
for (i = 0; i < istop; i++)
{
*rp = (png_byte)(~(*rp));
rp++;
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
row_info->bit_depth == 8)
{
png_bytep rp = row;
png_uint_32 i;
png_uint_32 istop = row_info->rowbytes;
for (i = 0; i < istop; i+=2)
{
*rp = (png_byte)(~(*rp));
rp+=2;
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
row_info->bit_depth == 16)
{
png_bytep rp = row;
png_uint_32 i;
png_uint_32 istop = row_info->rowbytes;
for (i = 0; i < istop; i+=4)
{
*rp = (png_byte)(~(*rp));
*(rp+1) = (png_byte)(~(*(rp+1)));
rp+=4;
}
}
}
#endif
#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
/* Swaps byte order on 16 bit depth images */
void /* PRIVATE */
png_do_swap(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_swap");
if (
row_info->bit_depth == 16)
{
png_bytep rp = row;
png_uint_32 i;
png_uint_32 istop= row_info->width * row_info->channels;
for (i = 0; i < istop; i++, rp += 2)
{
png_byte t = *rp;
*rp = *(rp + 1);
*(rp + 1) = t;
}
}
}
#endif
#if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
static PNG_CONST png_byte onebppswaptable[256] = {
0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
};
static PNG_CONST png_byte twobppswaptable[256] = {
0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
};
static PNG_CONST png_byte fourbppswaptable[256] = {
0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
};
/* Swaps pixel packing order within bytes */
void /* PRIVATE */
png_do_packswap(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_packswap");
if (
row_info->bit_depth < 8)
{
png_bytep rp, end, table;
end = row + row_info->rowbytes;
if (row_info->bit_depth == 1)
table = (png_bytep)onebppswaptable;
else if (row_info->bit_depth == 2)
table = (png_bytep)twobppswaptable;
else if (row_info->bit_depth == 4)
table = (png_bytep)fourbppswaptable;
else
return;
for (rp = row; rp < end; rp++)
*rp = table[*rp];
}
}
#endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
#if defined(PNG_WRITE_FILLER_SUPPORTED) || \
defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
/* Remove filler or alpha byte(s) */
void /* PRIVATE */
png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
{
png_debug(1, "in png_do_strip_filler");
{
png_bytep sp=row;
png_bytep dp=row;
png_uint_32 row_width=row_info->width;
png_uint_32 i;
if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
(row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
(flags & PNG_FLAG_STRIP_ALPHA))) &&
row_info->channels == 4)
{
if (row_info->bit_depth == 8)
{
/* This converts from RGBX or RGBA to RGB */
if (flags & PNG_FLAG_FILLER_AFTER)
{
dp+=3; sp+=4;
for (i = 1; i < row_width; i++)
{
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
sp++;
}
}
/* This converts from XRGB or ARGB to RGB */
else
{
for (i = 0; i < row_width; i++)
{
sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
}
}
row_info->pixel_depth = 24;
row_info->rowbytes = row_width * 3;
}
else /* if (row_info->bit_depth == 16) */
{
if (flags & PNG_FLAG_FILLER_AFTER)
{
/* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
sp += 8; dp += 6;
for (i = 1; i < row_width; i++)
{
/* This could be (although png_memcpy is probably slower):
png_memcpy(dp, sp, 6);
sp += 8;
dp += 6;
*/
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
sp += 2;
}
}
else
{
/* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
for (i = 0; i < row_width; i++)
{
/* This could be (although png_memcpy is probably slower):
png_memcpy(dp, sp, 6);
sp += 8;
dp += 6;
*/
sp+=2;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
*dp++ = *sp++;
}
}
row_info->pixel_depth = 48;
row_info->rowbytes = row_width * 6;
}
row_info->channels = 3;
}
else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
(row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
(flags & PNG_FLAG_STRIP_ALPHA))) &&
row_info->channels == 2)
{
if (row_info->bit_depth == 8)
{
/* This converts from GX or GA to G */
if (flags & PNG_FLAG_FILLER_AFTER)
{
for (i = 0; i < row_width; i++)
{
*dp++ = *sp++;
sp++;
}
}
/* This converts from XG or AG to G */
else
{
for (i = 0; i < row_width; i++)
{
sp++;
*dp++ = *sp++;
}
}
row_info->pixel_depth = 8;
row_info->rowbytes = row_width;
}
else /* if (row_info->bit_depth == 16) */
{
if (flags & PNG_FLAG_FILLER_AFTER)
{
/* This converts from GGXX or GGAA to GG */
sp += 4; dp += 2;
for (i = 1; i < row_width; i++)
{
*dp++ = *sp++;
*dp++ = *sp++;
sp += 2;
}
}
else
{
/* This converts from XXGG or AAGG to GG */
for (i = 0; i < row_width; i++)
{
sp += 2;
*dp++ = *sp++;
*dp++ = *sp++;
}
}
row_info->pixel_depth = 16;
row_info->rowbytes = row_width * 2;
}
row_info->channels = 1;
}
if (flags & PNG_FLAG_STRIP_ALPHA)
row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
}
}
#endif
#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
/* Swaps red and blue bytes within a pixel */
void /* PRIVATE */
png_do_bgr(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_bgr");
if (
(row_info->color_type & PNG_COLOR_MASK_COLOR))
{
png_uint_32 row_width = row_info->width;
if (row_info->bit_depth == 8)
{
if (row_info->color_type == PNG_COLOR_TYPE_RGB)
{
png_bytep rp;
png_uint_32 i;
for (i = 0, rp = row; i < row_width; i++, rp += 3)
{
png_byte save = *rp;
*rp = *(rp + 2);
*(rp + 2) = save;
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
png_bytep rp;
png_uint_32 i;
for (i = 0, rp = row; i < row_width; i++, rp += 4)
{
png_byte save = *rp;
*rp = *(rp + 2);
*(rp + 2) = save;
}
}
}
else if (row_info->bit_depth == 16)
{
if (row_info->color_type == PNG_COLOR_TYPE_RGB)
{
png_bytep rp;
png_uint_32 i;
for (i = 0, rp = row; i < row_width; i++, rp += 6)
{
png_byte save = *rp;
*rp = *(rp + 4);
*(rp + 4) = save;
save = *(rp + 1);
*(rp + 1) = *(rp + 5);
*(rp + 5) = save;
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
png_bytep rp;
png_uint_32 i;
for (i = 0, rp = row; i < row_width; i++, rp += 8)
{
png_byte save = *rp;
*rp = *(rp + 4);
*(rp + 4) = save;
save = *(rp + 1);
*(rp + 1) = *(rp + 5);
*(rp + 5) = save;
}
}
}
}
}
#endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
void PNGAPI
png_set_user_transform_info(png_structp png_ptr, png_voidp
user_transform_ptr, int user_transform_depth, int user_transform_channels)
{
png_debug(1, "in png_set_user_transform_info");
if (png_ptr == NULL)
return;
#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED
png_ptr->user_transform_ptr = user_transform_ptr;
png_ptr->user_transform_depth = (png_byte)user_transform_depth;
png_ptr->user_transform_channels = (png_byte)user_transform_channels;
#else
if (user_transform_ptr || user_transform_depth || user_transform_channels)
png_warning(png_ptr,
"This version of libpng does not support user transform info");
#endif
}
#endif
/* This function returns a pointer to the user_transform_ptr associated with
* the user transform functions. The application should free any memory
* associated with this pointer before png_write_destroy and png_read_destroy
* are called.
*/
png_voidp PNGAPI
png_get_user_transform_ptr(png_structp png_ptr)
{
if (png_ptr == NULL)
return (NULL);
#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED
return ((png_voidp)png_ptr->user_transform_ptr);
#else
return (NULL);
#endif
}
#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
+241
View File
@@ -0,0 +1,241 @@
/* pngwio.c - functions for data output
*
* Last changed in libpng 1.4.0 [January 3, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*
* This file provides a location for all output. Users who need
* special handling are expected to write functions that have the same
* arguments as these and perform similar functions, but that possibly
* use different output methods. Note that you shouldn't change these
* functions, but rather write replacement functions and then change
* them at run time with png_set_write_fn(...).
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#ifdef PNG_WRITE_SUPPORTED
#include "pngpriv.h"
/* Write the data to whatever output you are using. The default routine
* writes to a file pointer. Note that this routine sometimes gets called
* with very small lengths, so you should implement some kind of simple
* buffering if you are using unbuffered writes. This should never be asked
* to write more than 64K on a 16 bit machine.
*/
void /* PRIVATE */
png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
if (png_ptr->write_data_fn != NULL )
(*(png_ptr->write_data_fn))(png_ptr, data, length);
else
png_error(png_ptr, "Call to NULL write function");
}
#ifdef PNG_STDIO_SUPPORTED
/* This is the function that does the actual writing of data. If you are
* not writing to a standard C stream, you should create a replacement
* write_data function and use it at run time with png_set_write_fn(), rather
* than changing the library.
*/
#ifndef USE_FAR_KEYWORD
void PNGAPI
png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_uint_32 check;
if (png_ptr == NULL)
return;
check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
if (check != length)
png_error(png_ptr, "Write Error");
}
#else
/* This is the model-independent version. Since the standard I/O library
* can't handle far buffers in the medium and small models, we have to copy
* the data.
*/
#define NEAR_BUF_SIZE 1024
#define MIN(a,b) (a <= b ? a : b)
void PNGAPI
png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
png_uint_32 check;
png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
png_FILE_p io_ptr;
if (png_ptr == NULL)
return;
/* Check if data really is near. If so, use usual code. */
near_data = (png_byte *)CVT_PTR_NOCHECK(data);
io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
if ((png_bytep)near_data == data)
{
check = fwrite(near_data, 1, length, io_ptr);
}
else
{
png_byte buf[NEAR_BUF_SIZE];
png_size_t written, remaining, err;
check = 0;
remaining = length;
do
{
written = MIN(NEAR_BUF_SIZE, remaining);
png_memcpy(buf, data, written); /* Copy far buffer to near buffer */
err = fwrite(buf, 1, written, io_ptr);
if (err != written)
break;
else
check += err;
data += written;
remaining -= written;
}
while (remaining != 0);
}
if (check != length)
png_error(png_ptr, "Write Error");
}
#endif
#endif
/* This function is called to output any data pending writing (normally
* to disk). After png_flush is called, there should be no data pending
* writing in any buffers.
*/
#ifdef PNG_WRITE_FLUSH_SUPPORTED
void /* PRIVATE */
png_flush(png_structp png_ptr)
{
if (png_ptr->output_flush_fn != NULL)
(*(png_ptr->output_flush_fn))(png_ptr);
}
#ifdef PNG_STDIO_SUPPORTED
void PNGAPI
png_default_flush(png_structp png_ptr)
{
png_FILE_p io_ptr;
if (png_ptr == NULL)
return;
io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
fflush(io_ptr);
}
#endif
#endif
/* This function allows the application to supply new output functions for
* libpng if standard C streams aren't being used.
*
* This function takes as its arguments:
* png_ptr - pointer to a png output data structure
* io_ptr - pointer to user supplied structure containing info about
* the output functions. May be NULL.
* write_data_fn - pointer to a new output function that takes as its
* arguments a pointer to a png_struct, a pointer to
* data to be written, and a 32-bit unsigned int that is
* the number of bytes to be written. The new write
* function should call png_error(png_ptr, "Error msg")
* to exit and output any fatal error messages. May be
* NULL, in which case libpng's default function will
* be used.
* flush_data_fn - pointer to a new flush function that takes as its
* arguments a pointer to a png_struct. After a call to
* the flush function, there should be no data in any buffers
* or pending transmission. If the output method doesn't do
* any buffering of ouput, a function prototype must still be
* supplied although it doesn't have to do anything. If
* PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
* time, output_flush_fn will be ignored, although it must be
* supplied for compatibility. May be NULL, in which case
* libpng's default function will be used, if
* PNG_WRITE_FLUSH_SUPPORTED is defined. This is not
* a good idea if io_ptr does not point to a standard
* *FILE structure.
*/
void PNGAPI
png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
{
if (png_ptr == NULL)
return;
png_ptr->io_ptr = io_ptr;
#ifdef PNG_STDIO_SUPPORTED
if (write_data_fn != NULL)
png_ptr->write_data_fn = write_data_fn;
else
png_ptr->write_data_fn = png_default_write_data;
#else
png_ptr->write_data_fn = write_data_fn;
#endif
#ifdef PNG_WRITE_FLUSH_SUPPORTED
#ifdef PNG_STDIO_SUPPORTED
if (output_flush_fn != NULL)
png_ptr->output_flush_fn = output_flush_fn;
else
png_ptr->output_flush_fn = png_default_flush;
#else
png_ptr->output_flush_fn = output_flush_fn;
#endif
#endif /* PNG_WRITE_FLUSH_SUPPORTED */
/* It is an error to read while writing a png file */
if (png_ptr->read_data_fn != NULL)
{
png_ptr->read_data_fn = NULL;
png_warning(png_ptr,
"Attempted to set both read_data_fn and write_data_fn in");
png_warning(png_ptr,
"the same structure. Resetting read_data_fn to NULL");
}
}
#ifdef USE_FAR_KEYWORD
#ifdef _MSC_VER
void *png_far_to_near(png_structp png_ptr, png_voidp ptr, int check)
{
void *near_ptr;
void FAR *far_ptr;
FP_OFF(near_ptr) = FP_OFF(ptr);
far_ptr = (void FAR *)near_ptr;
if (check != 0)
if (FP_SEG(ptr) != FP_SEG(far_ptr))
png_error(png_ptr, "segment lost in conversion");
return(near_ptr);
}
# else
void *png_far_to_near(png_structp png_ptr, png_voidp ptr, int check)
{
void *near_ptr;
void FAR *far_ptr;
near_ptr = (void FAR *)ptr;
far_ptr = (void FAR *)near_ptr;
if (check != 0)
if (far_ptr != ptr)
png_error(png_ptr, "segment lost in conversion");
return(near_ptr);
}
# endif
# endif
#endif /* PNG_WRITE_SUPPORTED */
File diff suppressed because it is too large. Load diff
+566
View File
@@ -0,0 +1,566 @@
/* pngwtran.c - transforms the data in a row for PNG writers
*
* Last changed in libpng 1.4.1 [February 25, 2010]
* Copyright (c) 1998-2010 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
#define PNG_NO_PEDANTIC_WARNINGS
#include "png.h"
#ifdef PNG_WRITE_SUPPORTED
#include "pngpriv.h"
/* Transform the data according to the user's wishes. The order of
* transformations is significant.
*/
void /* PRIVATE */
png_do_write_transformations(png_structp png_ptr)
{
png_debug(1, "in png_do_write_transformations");
if (png_ptr == NULL)
return;
#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
if (png_ptr->transformations & PNG_USER_TRANSFORM)
if (png_ptr->write_user_transform_fn != NULL)
(*(png_ptr->write_user_transform_fn)) /* User write transform
function */
(png_ptr, /* png_ptr */
&(png_ptr->row_info), /* row_info: */
/* png_uint_32 width; width of row */
/* png_uint_32 rowbytes; number of bytes in row */
/* png_byte color_type; color type of pixels */
/* png_byte bit_depth; bit depth of samples */
/* png_byte channels; number of channels (1-4) */
/* png_byte pixel_depth; bits per pixel (depth*channels) */
png_ptr->row_buf + 1); /* start of pixel data for row */
#endif
#ifdef PNG_WRITE_FILLER_SUPPORTED
if (png_ptr->transformations & PNG_FILLER)
png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
png_ptr->flags);
#endif
#ifdef PNG_WRITE_PACKSWAP_SUPPORTED
if (png_ptr->transformations & PNG_PACKSWAP)
png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#ifdef PNG_WRITE_PACK_SUPPORTED
if (png_ptr->transformations & PNG_PACK)
png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
(png_uint_32)png_ptr->bit_depth);
#endif
#ifdef PNG_WRITE_SWAP_SUPPORTED
if (png_ptr->transformations & PNG_SWAP_BYTES)
png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#ifdef PNG_WRITE_SHIFT_SUPPORTED
if (png_ptr->transformations & PNG_SHIFT)
png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
&(png_ptr->shift));
#endif
#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
if (png_ptr->transformations & PNG_SWAP_ALPHA)
png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
if (png_ptr->transformations & PNG_INVERT_ALPHA)
png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#ifdef PNG_WRITE_BGR_SUPPORTED
if (png_ptr->transformations & PNG_BGR)
png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#ifdef PNG_WRITE_INVERT_SUPPORTED
if (png_ptr->transformations & PNG_INVERT_MONO)
png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
}
#ifdef PNG_WRITE_PACK_SUPPORTED
/* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
* row_info bit depth should be 8 (one pixel per byte). The channels
* should be 1 (this only happens on grayscale and paletted images).
*/
void /* PRIVATE */
png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
{
png_debug(1, "in png_do_pack");
if (row_info->bit_depth == 8 &&
row_info->channels == 1)
{
switch ((int)bit_depth)
{
case 1:
{
png_bytep sp, dp;
int mask, v;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
sp = row;
dp = row;
mask = 0x80;
v = 0;
for (i = 0; i < row_width; i++)
{
if (*sp != 0)
v |= mask;
sp++;
if (mask > 1)
mask >>= 1;
else
{
mask = 0x80;
*dp = (png_byte)v;
dp++;
v = 0;
}
}
if (mask != 0x80)
*dp = (png_byte)v;
break;
}
case 2:
{
png_bytep sp, dp;
int shift, v;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
sp = row;
dp = row;
shift = 6;
v = 0;
for (i = 0; i < row_width; i++)
{
png_byte value;
value = (png_byte)(*sp & 0x03);
v |= (value << shift);
if (shift == 0)
{
shift = 6;
*dp = (png_byte)v;
dp++;
v = 0;
}
else
shift -= 2;
sp++;
}
if (shift != 6)
*dp = (png_byte)v;
break;
}
case 4:
{
png_bytep sp, dp;
int shift, v;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
sp = row;
dp = row;
shift = 4;
v = 0;
for (i = 0; i < row_width; i++)
{
png_byte value;
value = (png_byte)(*sp & 0x0f);
v |= (value << shift);
if (shift == 0)
{
shift = 4;
*dp = (png_byte)v;
dp++;
v = 0;
}
else
shift -= 4;
sp++;
}
if (shift != 4)
*dp = (png_byte)v;
break;
}
}
row_info->bit_depth = (png_byte)bit_depth;
row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
row_info->width);
}
}
#endif
#ifdef PNG_WRITE_SHIFT_SUPPORTED
/* Shift pixel values to take advantage of whole range. Pass the
* true number of bits in bit_depth. The row should be packed
* according to row_info->bit_depth. Thus, if you had a row of
* bit depth 4, but the pixels only had values from 0 to 7, you
* would pass 3 as bit_depth, and this routine would translate the
* data to 0 to 15.
*/
void /* PRIVATE */
png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
{
png_debug(1, "in png_do_shift");
if (
row_info->color_type != PNG_COLOR_TYPE_PALETTE)
{
int shift_start[4], shift_dec[4];
int channels = 0;
if (row_info->color_type & PNG_COLOR_MASK_COLOR)
{
shift_start[channels] = row_info->bit_depth - bit_depth->red;
shift_dec[channels] = bit_depth->red;
channels++;
shift_start[channels] = row_info->bit_depth - bit_depth->green;
shift_dec[channels] = bit_depth->green;
channels++;
shift_start[channels] = row_info->bit_depth - bit_depth->blue;
shift_dec[channels] = bit_depth->blue;
channels++;
}
else
{
shift_start[channels] = row_info->bit_depth - bit_depth->gray;
shift_dec[channels] = bit_depth->gray;
channels++;
}
if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
{
shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
shift_dec[channels] = bit_depth->alpha;
channels++;
}
/* With low row depths, could only be grayscale, so one channel */
if (row_info->bit_depth < 8)
{
png_bytep bp = row;
png_uint_32 i;
png_byte mask;
png_uint_32 row_bytes = row_info->rowbytes;
if (bit_depth->gray == 1 && row_info->bit_depth == 2)
mask = 0x55;
else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
mask = 0x11;
else
mask = 0xff;
for (i = 0; i < row_bytes; i++, bp++)
{
png_uint_16 v;
int j;
v = *bp;
*bp = 0;
for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
{
if (j > 0)
*bp |= (png_byte)((v << j) & 0xff);
else
*bp |= (png_byte)((v >> (-j)) & mask);
}
}
}
else if (row_info->bit_depth == 8)
{
png_bytep bp = row;
png_uint_32 i;
png_uint_32 istop = channels * row_info->width;
for (i = 0; i < istop; i++, bp++)
{
png_uint_16 v;
int j;
int c = (int)(i%channels);
v = *bp;
*bp = 0;
for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
{
if (j > 0)
*bp |= (png_byte)((v << j) & 0xff);
else
*bp |= (png_byte)((v >> (-j)) & 0xff);
}
}
}
else
{
png_bytep bp;
png_uint_32 i;
png_uint_32 istop = channels * row_info->width;
for (bp = row, i = 0; i < istop; i++)
{
int c = (int)(i%channels);
png_uint_16 value, v;
int j;
v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
value = 0;
for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
{
if (j > 0)
value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
else
value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
}
*bp++ = (png_byte)(value >> 8);
*bp++ = (png_byte)(value & 0xff);
}
}
}
}
#endif
#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
void /* PRIVATE */
png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_write_swap_alpha");
{
if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
/* This converts from ARGB to RGBA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save;
}
}
/* This converts from AARRGGBB to RRGGBBAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save[2];
save[0] = *(sp++);
save[1] = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save[0];
*(dp++) = save[1];
}
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
/* This converts from AG to GA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save;
}
}
/* This converts from AAGG to GGAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save[2];
save[0] = *(sp++);
save[1] = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save[0];
*(dp++) = save[1];
}
}
}
}
}
#endif
#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
void /* PRIVATE */
png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_write_invert_alpha");
{
if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
/* This inverts the alpha channel in RGBA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
/* Does nothing
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*/
sp+=3; dp = sp;
*(dp++) = (png_byte)(255 - *(sp++));
}
}
/* This inverts the alpha channel in RRGGBBAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
/* Does nothing
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*/
sp+=6; dp = sp;
*(dp++) = (png_byte)(255 - *(sp++));
*(dp++) = (png_byte)(255 - *(sp++));
}
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
/* This inverts the alpha channel in GA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
*(dp++) = *(sp++);
*(dp++) = (png_byte)(255 - *(sp++));
}
}
/* This inverts the alpha channel in GGAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
/* Does nothing
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*/
sp+=2; dp = sp;
*(dp++) = (png_byte)(255 - *(sp++));
*(dp++) = (png_byte)(255 - *(sp++));
}
}
}
}
}
#endif
#ifdef PNG_MNG_FEATURES_SUPPORTED
/* Undoes intrapixel differencing */
void /* PRIVATE */
png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_write_intrapixel");
if (
(row_info->color_type & PNG_COLOR_MASK_COLOR))
{
int bytes_per_pixel;
png_uint_32 row_width = row_info->width;
if (row_info->bit_depth == 8)
{
png_bytep rp;
png_uint_32 i;
if (row_info->color_type == PNG_COLOR_TYPE_RGB)
bytes_per_pixel = 3;
else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
bytes_per_pixel = 4;
else
return;
for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
{
*(rp) = (png_byte)((*rp - *(rp+1))&0xff);
*(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
}
}
else if (row_info->bit_depth == 16)
{
png_bytep rp;
png_uint_32 i;
if (row_info->color_type == PNG_COLOR_TYPE_RGB)
bytes_per_pixel = 6;
else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
bytes_per_pixel = 8;
else
return;
for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
{
png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
*(rp ) = (png_byte)((red >> 8) & 0xff);
*(rp+1) = (png_byte)(red & 0xff);
*(rp+4) = (png_byte)((blue >> 8) & 0xff);
*(rp+5) = (png_byte)(blue & 0xff);
}
}
}
}
#endif /* PNG_MNG_FEATURES_SUPPORTED */
#endif /* PNG_WRITE_SUPPORTED */
File diff suppressed because it is too large. Load diff
+97
View File
@@ -0,0 +1,97 @@
/* Config header for Android */
/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
*/
/* #undef HAVE_DECL_TZNAME */
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 0
/* Define to 1 if you have the `fseeko' function. */
#define HAVE_FSEEKO 0
/* Define to 1 if you have the `ftello' function. */
#define HAVE_FTELLO 0
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 0
/* Define to 1 if you have the `z' library (-lz). */
#define HAVE_LIBZ 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 0
/* Define to 1 if you have the `mkstemp' function. */
#define HAVE_MKSTEMP 0
/* Define to 1 if you have the `MoveFileExA' function. */
/* #undef HAVE_MOVEFILEEXA */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if `tm_zone' is a member of `struct tm'. */
#define HAVE_STRUCT_TM_TM_ZONE 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
`HAVE_STRUCT_TM_TM_ZONE' instead. */
#define HAVE_TM_ZONE 1
/* Define to 1 if you don't have `tm_zone' but do have the external array
`tzname'. */
/* #undef HAVE_TZNAME */
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Define to 1 if your C compiler doesn't accept -c and -o together. */
/* #undef NO_MINUS_C_MINUS_O */
/* Name of package */
#define PACKAGE "libzip"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "[email protected]"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libzip"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libzip 0.9.3"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libzip"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.9.3"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
/* #undef TM_IN_SYS_TIME */
/* Version number of package */
#define VERSION "0.9.3"
Loaded 100 of 620 files, more files were not shown because too many files have changed in this diff. Show more