initial commit

This commit is contained in:
2024-08-18 02:50:11 -06:00
commit c6f61bffb0
144 changed files with 19082 additions and 0 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

+71
View File
@@ -0,0 +1,71 @@
Entry main: 0x40043A2C
Resides in: 0x40040000 to 0x4005FFFF - 128KB - Internal ROM 1
Address space begins at: 0x3FF00000 ?
list available machines:
/home/kali/.emulate-debug/qemu-xtensa/bin/qemu-system-xtensa -machine help
/home/kali/.emulate-debug/qemu-riscv/bin/qemu-system-riscv32 -machine help
emulate esp32s3:
/home/kali/.emulate-debug/qemu-xtensa/bin/qemu-system-xtensa -machine esp32s3
emulate riscv:
/home/kali/.emulate-debug/qemu-riscv/bin/qemu-system-riscv32 -machine esp32c3
espressif gdb
/home/kali/.emulate-debug/binutils-gdb/gdb/gdb --help
/home/kali/.emulate-debug/binutils-gdb/gdb/gdb -l 300 # set timeount to 300 seconds
exploit_dev folder:
/home/kali/sync/esp32s3-boot-rom-elf-uni.rep/exploit_dev/
.emulation-debug folder:
/home/kali/.emulate-debug/
esptool.py --chip esp32s3 elf2image --use_segments esp32s3_rev0_rom.elf
--output bin_file_name.bin
--flash_size 8MB
--pad-to-size 8MB
ROM Elfs:
./esp-rom-elfs-20230320
https://github.com/espressif/esp-rom-elfs/releases/tag/20230320
Full version in ROM ELF's filenames (major * 100 + minor). E.g:
esp32_rev300_rom.elf is for version 3.0
esp32c3_rev3_rom.elf is for version 0.3
Fix esp32c2 revision to 1.0
todo:
x reinstall esp-idf fucking again to test the reinstall script
- run dump on freenove fuckin again (twice) with latest for testing and final binutils
- run dump fuckin twice on another esp32s3 for compare
- save the shit and back the shit up
- add and push git projects
- document lmfao
- study the fuck out of cuork's c3 exploit
- get on that fuckin binary exploit lmfao
== scratch ==
# running on byobu:
export ESPBAUD=115200; ./espdump.sh devkit; ./espdump.sh devkit; export ESPPORT=/dev/ttyACM1; ./espdump.sh freenove; ./espdump.sh freenove;
#dump_section "internal-ROM0" "instruction-bus" 0x4000_0000 0x4003_FFFF $chip
#dump_section "internal-ROM1" "data-bus" 0x3FF0_0000 0x3FF1_FFFF $chip
#dump_section "internal-ROM1" "instruction-bus" 0x4004_0000 0x4005_FFFF $chip
# internal ROM0, instruction bus, 0x4000_0000 to 0x4003_FFFF, 0x3FFFF length (256KB)
#echo "\n\ninterenal ROM0, instruction bus, 0x4000_0000 to 0x4003_FFFF, 0x3FFFF length (256KB)\n\n"
#esptool.py --baud $ESPBAUD --port $ESPPORT --chip esp32s3 dump_mem 0x4000_0000 0x3FFFF "$out_dir/live-freenove-boot-ROM0-instruction-bus-0x4000_0000-0x4003_FFFF-0x3FFFF-full-address-esp32s3-$datestamp.bin"
# internal ROM1, data bus, 0x3FF0_0000 to 0x3FF1_FFFF, 0x1FFFF length (128KB)
#echo "\n\ninternal ROM1, data bus, 0x3FF0_0000 to 0x3FF1_FFFF, 0x1FFFF length (128KB)\n\n"
#esptool.py --baud $ESPBAUD --port $ESPPORT --chip esp32s3 dump_mem 0x3FF00000 0x1FFFF "$out_dir/live-freenove-boot-ROM1-data-bus-0x3FF0_0000-0x3FF1_FFFF-0x1FFFF-full-address-esp32s3-$datestamp.bin"
# internal ROM1, instruction bus, 0x4004_0000 to 0x4005_FFFF, 0x1FFFF length (128KB)
#echo "\n\ninternal ROM1, instruction bus, 0x4004_0000 to 0x4005_FFFF, 0x1FFFF length (128KB)\n\n"
#esptool.py --baud $ESPBAUD --port $ESPPORT --chip esp32s3 dump_mem 0x3FF0_0000 0x1FFFF "$out_dir/live-freenove-boot-ROM1-instruction-bus-0x4004_0000-0x4005_FFF-0x1FFFF-full-address-esp32s3-$datestamp.bin"
Binary file not shown.
Binary file not shown.
Submodule libs/TinyBasicPlus added at d319264b6c
+64
View File
@@ -0,0 +1,64 @@
PROJECT(miniz)
cmake_minimum_required(VERSION 2.8)
option(BUILD_X64 "build 64-bit" TRUE)
message("Initial BUILD_X64=${BUILD_X64}")
message("Initial CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
if( NOT CMAKE_BUILD_TYPE )
set( CMAKE_BUILD_TYPE Release )
endif( NOT CMAKE_BUILD_TYPE )
message( ${PROJECT_NAME} " build type: " ${CMAKE_BUILD_TYPE} )
if (BUILD_X64)
message("Building 64-bit")
else()
message("Building 32-bit")
endif(BUILD_X64)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -Wall -Wextra")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -Wall -Wextra")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -Wextra")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -Wextra")
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
set(EXAMPLE1_SRC_LIST ${COMMON_SRC_LIST} example1.c)
set(EXAMPLE2_SRC_LIST ${COMMON_SRC_LIST} example2.c)
set(EXAMPLE3_SRC_LIST ${COMMON_SRC_LIST} example3.c)
set(EXAMPLE4_SRC_LIST ${COMMON_SRC_LIST} example4.c)
set(EXAMPLE5_SRC_LIST ${COMMON_SRC_LIST} example5.c)
set(EXAMPLE6_SRC_LIST ${COMMON_SRC_LIST} example6.c)
set(MINIZ_TESTER_SRC_LIST ${COMMON_SRC_LIST} miniz_tester.cpp miniz.c timer.cpp timer.h)
# -fno-strict-aliasing is probably not required to build miniz.c (I've been testing with it not defined for a while), but it's what I'm used to from working with Visual Studio.
set(GCC_COMPILE_FLAGS "-fno-strict-aliasing -D_LARGEFILE64_SOURCE=1 -D_FILE_OFFSET_BITS=64")
if (NOT BUILD_X64)
set(GCC_COMPILE_FLAGS "${GCC_COMPILE_FLAGS} -m32")
endif()
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_LINK_FLAGS}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GCC_COMPILE_FLAGS}")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${GCC_COMPILE_FLAGS}")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${GCC_COMPILE_FLAGS} -D_DEBUG")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COMPILE_FLAGS}")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${GCC_COMPILE_FLAGS}")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${GCC_COMPILE_FLAGS} -D_DEBUG")
include_directories(${PROJECT_SOURCE_DIR}/.)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin_linux)
add_executable(example1 ${EXAMPLE1_SRC_LIST})
add_executable(example2 ${EXAMPLE2_SRC_LIST})
add_executable(example3 ${EXAMPLE3_SRC_LIST})
add_executable(example4 ${EXAMPLE4_SRC_LIST})
add_executable(example5 ${EXAMPLE5_SRC_LIST})
add_executable(example6 ${EXAMPLE6_SRC_LIST})
target_link_libraries(example6 m)
add_executable(miniz_tester ${MINIZ_TESTER_SRC_LIST})
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+105
View File
@@ -0,0 +1,105 @@
// example1.c - Demonstrates miniz.c's compress() and uncompress() functions (same as zlib's).
// Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c.
#include "miniz.c"
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;
// The string to compress.
static const char *s_pStr = "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \
"Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \
"Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \
"Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \
"Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \
"Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \
"Good morning Dr. Chandra. This is Hal. I am ready for my first lesson.";
int main(int argc, char *argv[])
{
uint step = 0;
int cmp_status;
uLong src_len = (uLong)strlen(s_pStr);
uLong cmp_len = compressBound(src_len);
uLong uncomp_len = src_len;
uint8 *pCmp, *pUncomp;
uint total_succeeded = 0;
(void)argc, (void)argv;
printf("miniz.c version: %s\n", MZ_VERSION);
do
{
// Allocate buffers to hold compressed and uncompressed data.
pCmp = (mz_uint8 *)malloc((size_t)cmp_len);
pUncomp = (mz_uint8 *)malloc((size_t)src_len);
if ((!pCmp) || (!pUncomp))
{
printf("Out of memory!\n");
return EXIT_FAILURE;
}
// Compress the string.
cmp_status = compress(pCmp, &cmp_len, (const unsigned char *)s_pStr, src_len);
if (cmp_status != Z_OK)
{
printf("compress() failed!\n");
free(pCmp);
free(pUncomp);
return EXIT_FAILURE;
}
printf("Compressed from %u to %u bytes\n", (mz_uint32)src_len, (mz_uint32)cmp_len);
if (step)
{
// Purposely corrupt the compressed data if fuzzy testing (this is a very crude fuzzy test).
uint n = 1 + (rand() % 3);
while (n--)
{
uint i = rand() % cmp_len;
pCmp[i] ^= (rand() & 0xFF);
}
}
// Decompress.
cmp_status = uncompress(pUncomp, &uncomp_len, pCmp, cmp_len);
total_succeeded += (cmp_status == Z_OK);
if (step)
{
printf("Simple fuzzy test: step %u total_succeeded: %u\n", step, total_succeeded);
}
else
{
if (cmp_status != Z_OK)
{
printf("uncompress failed!\n");
free(pCmp);
free(pUncomp);
return EXIT_FAILURE;
}
printf("Decompressed from %u to %u bytes\n", (mz_uint32)cmp_len, (mz_uint32)uncomp_len);
// Ensure uncompress() returned the expected data.
if ((uncomp_len != src_len) || (memcmp(pUncomp, s_pStr, (size_t)src_len)))
{
printf("Decompression failed!\n");
free(pCmp);
free(pUncomp);
return EXIT_FAILURE;
}
}
free(pCmp);
free(pUncomp);
step++;
// Keep on fuzzy testing if there's a non-empty command line.
} while (argc >= 2);
printf("Success.\n");
return EXIT_SUCCESS;
}
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="example1" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug Win32">
<Option output="$(SolutionDir)bin_mingw\example1D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example1\Debug Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-Wall" />
<Add option="-g" />
<Add option="-O0" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
</Compiler>
<Linker>
<Add option="-m32" />
</Linker>
</Target>
<Target title="Debug x64">
<Option output="$(SolutionDir)bin_mingw\example1_x64D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example1\Debug x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O0" />
</Compiler>
</Target>
<Target title="Release Win32">
<Option output="$(SolutionDir)bin_mingw\example1" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example1\Release Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O3" />
<Add option="-Wall" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
</Compiler>
<Linker>
<Add option="-s" />
<Add option="-m32" />
</Linker>
</Target>
<Target title="Release x64">
<Option output="$(SolutionDir)bin_mingw\example1_x64" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example1\Release x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
</Target>
</Build>
<Unit filename="example1.c">
<Option compilerVar="CC" />
</Unit>
<Extensions>
<code_completion />
<debugger />
</Extensions>
</Project>
</CodeBlocks_project_file>
+346
View File
@@ -0,0 +1,346 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="example1"
ProjectGUID="{BE273522-92D8-4B60-95C7-C3AEE10A303E}"
RootNamespace="example1"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64.exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\example1.c"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+163
View File
@@ -0,0 +1,163 @@
// example2.c - Simple demonstration of miniz.c's ZIP archive API's.
// Note this test deletes the test archive file "__mz_example2_test__.zip" in the current directory, then creates a new one with test data.
// Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c.
#if defined(__GNUC__)
// Ensure we get the 64-bit variants of the CRT's file I/O calls
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE 1
#endif
#endif
#include "miniz.c"
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;
// The string to compress.
static const char *s_pTest_str =
"MISSION CONTROL I wouldn't worry too much about the computer. First of all, there is still a chance that he is right, despite your tests, and" \
"if it should happen again, we suggest eliminating this possibility by allowing the unit to remain in place and seeing whether or not it" \
"actually fails. If the computer should turn out to be wrong, the situation is still not alarming. The type of obsessional error he may be" \
"guilty of is not unknown among the latest generation of HAL 9000 computers. It has almost always revolved around a single detail, such as" \
"the one you have described, and it has never interfered with the integrity or reliability of the computer's performance in other areas." \
"No one is certain of the cause of this kind of malfunctioning. It may be over-programming, but it could also be any number of reasons. In any" \
"event, it is somewhat analogous to human neurotic behavior. Does this answer your query? Zero-five-three-Zero, MC, transmission concluded.";
static const char *s_pComment = "This is a comment";
int main(int argc, char *argv[])
{
int i, sort_iter;
mz_bool status;
size_t uncomp_size;
mz_zip_archive zip_archive;
void *p;
const int N = 50;
char data[2048];
char archive_filename[64];
static const char *s_Test_archive_filename = "__mz_example2_test__.zip";
assert((strlen(s_pTest_str) + 64) < sizeof(data));
printf("miniz.c version: %s\n", MZ_VERSION);
(void)argc, (void)argv;
// Delete the test archive, so it doesn't keep growing as we run this test
remove(s_Test_archive_filename);
// Append a bunch of text files to the test archive
for (i = (N - 1); i >= 0; --i)
{
sprintf(archive_filename, "%u.txt", i);
sprintf(data, "%u %s %u", (N - 1) - i, s_pTest_str, i);
// Add a new file to the archive. Note this is an IN-PLACE operation, so if it fails your archive is probably hosed (its central directory may not be complete) but it should be recoverable using zip -F or -FF. So use caution with this guy.
// A more robust way to add a file to an archive would be to read it into memory, perform the operation, then write a new archive out to a temp file and then delete/rename the files.
// Or, write a new archive to disk to a temp file, then delete/rename the files. For this test this API is fine.
status = mz_zip_add_mem_to_archive_file_in_place(s_Test_archive_filename, archive_filename, data, strlen(data) + 1, s_pComment, (uint16)strlen(s_pComment), MZ_BEST_COMPRESSION);
if (!status)
{
printf("mz_zip_add_mem_to_archive_file_in_place failed!\n");
return EXIT_FAILURE;
}
}
// Add a directory entry for testing
status = mz_zip_add_mem_to_archive_file_in_place(s_Test_archive_filename, "directory/", NULL, 0, "no comment", (uint16)strlen("no comment"), MZ_BEST_COMPRESSION);
if (!status)
{
printf("mz_zip_add_mem_to_archive_file_in_place failed!\n");
return EXIT_FAILURE;
}
// Now try to open the archive.
memset(&zip_archive, 0, sizeof(zip_archive));
status = mz_zip_reader_init_file(&zip_archive, s_Test_archive_filename, 0);
if (!status)
{
printf("mz_zip_reader_init_file() failed!\n");
return EXIT_FAILURE;
}
// Get and print information about each file in the archive.
for (i = 0; i < (int)mz_zip_reader_get_num_files(&zip_archive); i++)
{
mz_zip_archive_file_stat file_stat;
if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat))
{
printf("mz_zip_reader_file_stat() failed!\n");
mz_zip_reader_end(&zip_archive);
return EXIT_FAILURE;
}
printf("Filename: \"%s\", Comment: \"%s\", Uncompressed size: %u, Compressed size: %u, Is Dir: %u\n", file_stat.m_filename, file_stat.m_comment, (uint)file_stat.m_uncomp_size, (uint)file_stat.m_comp_size, mz_zip_reader_is_file_a_directory(&zip_archive, i));
if (!strcmp(file_stat.m_filename, "directory/"))
{
if (!mz_zip_reader_is_file_a_directory(&zip_archive, i))
{
printf("mz_zip_reader_is_file_a_directory() didn't return the expected results!\n");
mz_zip_reader_end(&zip_archive);
return EXIT_FAILURE;
}
}
}
// Close the archive, freeing any resources it was using
mz_zip_reader_end(&zip_archive);
// Now verify the compressed data
for (sort_iter = 0; sort_iter < 2; sort_iter++)
{
memset(&zip_archive, 0, sizeof(zip_archive));
status = mz_zip_reader_init_file(&zip_archive, s_Test_archive_filename, sort_iter ? MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY : 0);
if (!status)
{
printf("mz_zip_reader_init_file() failed!\n");
return EXIT_FAILURE;
}
for (i = 0; i < N; i++)
{
sprintf(archive_filename, "%u.txt", i);
sprintf(data, "%u %s %u", (N - 1) - i, s_pTest_str, i);
// Try to extract all the files to the heap.
p = mz_zip_reader_extract_file_to_heap(&zip_archive, archive_filename, &uncomp_size, 0);
if (!p)
{
printf("mz_zip_reader_extract_file_to_heap() failed!\n");
mz_zip_reader_end(&zip_archive);
return EXIT_FAILURE;
}
// Make sure the extraction really succeeded.
if ((uncomp_size != (strlen(data) + 1)) || (memcmp(p, data, strlen(data))))
{
printf("mz_zip_reader_extract_file_to_heap() failed to extract the proper data\n");
mz_free(p);
mz_zip_reader_end(&zip_archive);
return EXIT_FAILURE;
}
printf("Successfully extracted file \"%s\", size %u\n", archive_filename, (uint)uncomp_size);
printf("File data: \"%s\"\n", (const char *)p);
// We're done.
mz_free(p);
}
// Close the archive, freeing any resources it was using
mz_zip_reader_end(&zip_archive);
}
printf("Success.\n");
return EXIT_SUCCESS;
}
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="example2" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug Win32">
<Option output="$(SolutionDir)bin_mingw\example2D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example2\Debug Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-Wall" />
<Add option="-g" />
<Add option="-O0" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
</Compiler>
<Linker>
<Add option="-m32" />
</Linker>
</Target>
<Target title="Debug x64">
<Option output="$(SolutionDir)bin_mingw\example2_x64D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example2\Debug x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O0" />
</Compiler>
</Target>
<Target title="Release Win32">
<Option output="$(SolutionDir)bin_mingw\example2" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example2\Release Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O3" />
<Add option="-Wall" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
</Compiler>
<Linker>
<Add option="-s" />
<Add option="-m32" />
</Linker>
</Target>
<Target title="Release x64">
<Option output="$(SolutionDir)bin_mingw\example2_x64" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example2\Release x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
</Target>
</Build>
<Unit filename="example2.c">
<Option compilerVar="CC" />
</Unit>
<Extensions>
<code_completion />
<debugger />
</Extensions>
</Project>
</CodeBlocks_project_file>
+346
View File
@@ -0,0 +1,346 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="example2"
ProjectGUID="{AE273522-92D8-4B60-95C7-C3AEE10A303E}"
RootNamespace="example2"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64.exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\example2.c"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+268
View File
@@ -0,0 +1,268 @@
// example3.c - Demonstrates how to use miniz.c's deflate() and inflate() functions for simple file compression.
// Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c.
// For simplicity, this example is limited to files smaller than 4GB, but this is not a limitation of miniz.c.
#include "miniz.c"
#include <limits.h>
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;
#define my_max(a,b) (((a) > (b)) ? (a) : (b))
#define my_min(a,b) (((a) < (b)) ? (a) : (b))
#define BUF_SIZE (1024 * 1024)
static uint8 s_inbuf[BUF_SIZE];
static uint8 s_outbuf[BUF_SIZE];
int main(int argc, char *argv[])
{
const char *pMode;
FILE *pInfile, *pOutfile;
uint infile_size;
int level = Z_BEST_COMPRESSION;
z_stream stream;
int p = 1;
const char *pSrc_filename;
const char *pDst_filename;
long file_loc;
printf("miniz.c version: %s\n", MZ_VERSION);
if (argc < 4)
{
printf("Usage: example3 [options] [mode:c or d] infile outfile\n");
printf("\nModes:\n");
printf("c - Compresses file infile to a zlib stream in file outfile\n");
printf("d - Decompress zlib stream in file infile to file outfile\n");
printf("\nOptions:\n");
printf("-l[0-10] - Compression level, higher values are slower.\n");
return EXIT_FAILURE;
}
while ((p < argc) && (argv[p][0] == '-'))
{
switch (argv[p][1])
{
case 'l':
{
level = atoi(&argv[1][2]);
if ((level < 0) || (level > 10))
{
printf("Invalid level!\n");
return EXIT_FAILURE;
}
break;
}
default:
{
printf("Invalid option: %s\n", argv[p]);
return EXIT_FAILURE;
}
}
p++;
}
if ((argc - p) < 3)
{
printf("Must specify mode, input filename, and output filename after options!\n");
return EXIT_FAILURE;
}
else if ((argc - p) > 3)
{
printf("Too many filenames!\n");
return EXIT_FAILURE;
}
pMode = argv[p++];
if (!strchr("cCdD", pMode[0]))
{
printf("Invalid mode!\n");
return EXIT_FAILURE;
}
pSrc_filename = argv[p++];
pDst_filename = argv[p++];
printf("Mode: %c, Level: %u\nInput File: \"%s\"\nOutput File: \"%s\"\n", pMode[0], level, pSrc_filename, pDst_filename);
// Open input file.
pInfile = fopen(pSrc_filename, "rb");
if (!pInfile)
{
printf("Failed opening input file!\n");
return EXIT_FAILURE;
}
// Determine input file's size.
fseek(pInfile, 0, SEEK_END);
file_loc = ftell(pInfile);
fseek(pInfile, 0, SEEK_SET);
if ((file_loc < 0) || (file_loc > INT_MAX))
{
// This is not a limitation of miniz or tinfl, but this example.
printf("File is too large to be processed by this example.\n");
return EXIT_FAILURE;
}
infile_size = (uint)file_loc;
// Open output file.
pOutfile = fopen(pDst_filename, "wb");
if (!pOutfile)
{
printf("Failed opening output file!\n");
return EXIT_FAILURE;
}
printf("Input file size: %u\n", infile_size);
// Init the z_stream
memset(&stream, 0, sizeof(stream));
stream.next_in = s_inbuf;
stream.avail_in = 0;
stream.next_out = s_outbuf;
stream.avail_out = BUF_SIZE;
if ((pMode[0] == 'c') || (pMode[0] == 'C'))
{
// Compression.
uint infile_remaining = infile_size;
if (deflateInit(&stream, level) != Z_OK)
{
printf("deflateInit() failed!\n");
return EXIT_FAILURE;
}
for ( ; ; )
{
int status;
if (!stream.avail_in)
{
// Input buffer is empty, so read more bytes from input file.
uint n = my_min(BUF_SIZE, infile_remaining);
if (fread(s_inbuf, 1, n, pInfile) != n)
{
printf("Failed reading from input file!\n");
return EXIT_FAILURE;
}
stream.next_in = s_inbuf;
stream.avail_in = n;
infile_remaining -= n;
//printf("Input bytes remaining: %u\n", infile_remaining);
}
status = deflate(&stream, infile_remaining ? Z_NO_FLUSH : Z_FINISH);
if ((status == Z_STREAM_END) || (!stream.avail_out))
{
// Output buffer is full, or compression is done, so write buffer to output file.
uint n = BUF_SIZE - stream.avail_out;
if (fwrite(s_outbuf, 1, n, pOutfile) != n)
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
stream.next_out = s_outbuf;
stream.avail_out = BUF_SIZE;
}
if (status == Z_STREAM_END)
break;
else if (status != Z_OK)
{
printf("deflate() failed with status %i!\n", status);
return EXIT_FAILURE;
}
}
if (deflateEnd(&stream) != Z_OK)
{
printf("deflateEnd() failed!\n");
return EXIT_FAILURE;
}
}
else if ((pMode[0] == 'd') || (pMode[0] == 'D'))
{
// Decompression.
uint infile_remaining = infile_size;
if (inflateInit(&stream))
{
printf("inflateInit() failed!\n");
return EXIT_FAILURE;
}
for ( ; ; )
{
int status;
if (!stream.avail_in)
{
// Input buffer is empty, so read more bytes from input file.
uint n = my_min(BUF_SIZE, infile_remaining);
if (fread(s_inbuf, 1, n, pInfile) != n)
{
printf("Failed reading from input file!\n");
return EXIT_FAILURE;
}
stream.next_in = s_inbuf;
stream.avail_in = n;
infile_remaining -= n;
}
status = inflate(&stream, Z_SYNC_FLUSH);
if ((status == Z_STREAM_END) || (!stream.avail_out))
{
// Output buffer is full, or decompression is done, so write buffer to output file.
uint n = BUF_SIZE - stream.avail_out;
if (fwrite(s_outbuf, 1, n, pOutfile) != n)
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
stream.next_out = s_outbuf;
stream.avail_out = BUF_SIZE;
}
if (status == Z_STREAM_END)
break;
else if (status != Z_OK)
{
printf("inflate() failed with status %i!\n", status);
return EXIT_FAILURE;
}
}
if (inflateEnd(&stream) != Z_OK)
{
printf("inflateEnd() failed!\n");
return EXIT_FAILURE;
}
}
else
{
printf("Invalid mode!\n");
return EXIT_FAILURE;
}
fclose(pInfile);
if (EOF == fclose(pOutfile))
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
printf("Total input bytes: %u\n", (mz_uint32)stream.total_in);
printf("Total output bytes: %u\n", (mz_uint32)stream.total_out);
printf("Success.\n");
return EXIT_SUCCESS;
}
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="example3" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug Win32">
<Option output="$(SolutionDir)bin_mingw\example3D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example3\Debug Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O0" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-g" />
</Compiler>
<Linker>
<Add option="-m32" />
</Linker>
</Target>
<Target title="Debug x64">
<Option output="$(SolutionDir)bin_mingw\example3_x64D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example3\Debug x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O0" />
</Compiler>
</Target>
<Target title="Release Win32">
<Option output="$(SolutionDir)bin_mingw\example3" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example3\Release Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
<Linker>
<Add option="-s" />
<Add option="-m32" />
</Linker>
</Target>
<Target title="Release x64">
<Option output="$(SolutionDir)bin_mingw\example3_x64" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example3\Release x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
</Target>
</Build>
<Unit filename="example3.c">
<Option compilerVar="CC" />
</Unit>
<Extensions>
<code_completion />
<debugger />
</Extensions>
</Project>
</CodeBlocks_project_file>
+346
View File
@@ -0,0 +1,346 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="example3"
ProjectGUID="{AE273522-92D8-4B60-95C7-C3AEE10A303F}"
RootNamespace="example3"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64.exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\example3.c"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+102
View File
@@ -0,0 +1,102 @@
// example4.c - Uses tinfl.c to decompress a zlib stream in memory to an output file
// Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c.
#include "tinfl.c"
#include <stdio.h>
#include <limits.h>
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;
#define my_max(a,b) (((a) > (b)) ? (a) : (b))
#define my_min(a,b) (((a) < (b)) ? (a) : (b))
static int tinfl_put_buf_func(const void* pBuf, int len, void *pUser)
{
return len == (int)fwrite(pBuf, 1, len, (FILE*)pUser);
}
int main(int argc, char *argv[])
{
int status;
FILE *pInfile, *pOutfile;
uint infile_size, outfile_size;
size_t in_buf_size;
uint8 *pCmp_data;
long file_loc;
if (argc != 3)
{
printf("Usage: example4 infile outfile\n");
printf("Decompresses zlib stream in file infile to file outfile.\n");
printf("Input file must be able to fit entirely in memory.\n");
printf("example3 can be used to create compressed zlib streams.\n");
return EXIT_FAILURE;
}
// Open input file.
pInfile = fopen(argv[1], "rb");
if (!pInfile)
{
printf("Failed opening input file!\n");
return EXIT_FAILURE;
}
// Determine input file's size.
fseek(pInfile, 0, SEEK_END);
file_loc = ftell(pInfile);
fseek(pInfile, 0, SEEK_SET);
if ((file_loc < 0) || (file_loc > INT_MAX))
{
// This is not a limitation of miniz or tinfl, but this example.
printf("File is too large to be processed by this example.\n");
return EXIT_FAILURE;
}
infile_size = (uint)file_loc;
pCmp_data = (uint8 *)malloc(infile_size);
if (!pCmp_data)
{
printf("Out of memory!\n");
return EXIT_FAILURE;
}
if (fread(pCmp_data, 1, infile_size, pInfile) != infile_size)
{
printf("Failed reading input file!\n");
return EXIT_FAILURE;
}
// Open output file.
pOutfile = fopen(argv[2], "wb");
if (!pOutfile)
{
printf("Failed opening output file!\n");
return EXIT_FAILURE;
}
printf("Input file size: %u\n", infile_size);
in_buf_size = infile_size;
status = tinfl_decompress_mem_to_callback(pCmp_data, &in_buf_size, tinfl_put_buf_func, pOutfile, TINFL_FLAG_PARSE_ZLIB_HEADER);
if (!status)
{
printf("tinfl_decompress_mem_to_callback() failed with status %i!\n", status);
return EXIT_FAILURE;
}
outfile_size = ftell(pOutfile);
fclose(pInfile);
if (EOF == fclose(pOutfile))
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
printf("Total input bytes: %u\n", (uint)in_buf_size);
printf("Total output bytes: %u\n", outfile_size);
printf("Success.\n");
return EXIT_SUCCESS;
}
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="example4" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug Win32">
<Option output="$(SolutionDir)bin_mingw\example4D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example4\Debug Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O0" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-g" />
</Compiler>
<Linker>
<Add option="-m32" />
</Linker>
</Target>
<Target title="Debug x64">
<Option output="$(SolutionDir)bin_mingw\example4_x64D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example4\Debug x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O0" />
</Compiler>
</Target>
<Target title="Release Win32">
<Option output="$(SolutionDir)bin_mingw\example4" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example4\Release Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
<Linker>
<Add option="-s" />
<Add option="-m32" />
</Linker>
</Target>
<Target title="Release x64">
<Option output="$(SolutionDir)bin_mingw\example4_x64" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example4\Release x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
</Target>
</Build>
<Unit filename="example4.c">
<Option compilerVar="CC" />
</Unit>
<Extensions>
<code_completion />
<debugger />
</Extensions>
</Project>
</CodeBlocks_project_file>
+346
View File
@@ -0,0 +1,346 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="example4"
ProjectGUID="{AE293522-92D8-4B60-95C7-C3AEE10A303F}"
RootNamespace="example4"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64.exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FD737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\example4.c"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{17DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+327
View File
@@ -0,0 +1,327 @@
// example5.c - Demonstrates how to use miniz.c's low-level tdefl_compress() and tinfl_inflate() API's for simple file to file compression/decompression.
// The low-level API's are the fastest, make no use of dynamic memory allocation, and are the most flexible functions exposed by miniz.c.
// Public domain, April 11 2012, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c.
// For simplicity, this example is limited to files smaller than 4GB, but this is not a limitation of miniz.c.
// Purposely disable a whole bunch of stuff this low-level example doesn't use.
#define MINIZ_NO_STDIO
#define MINIZ_NO_ARCHIVE_APIS
#define MINIZ_NO_TIME
#define MINIZ_NO_ZLIB_APIS
#define MINIZ_NO_MALLOC
#include "miniz.c"
// Now include stdio.h because this test uses fopen(), etc. (but we still don't want miniz.c's stdio stuff, for testing).
#include <stdio.h>
#include <limits.h>
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;
#define my_max(a,b) (((a) > (b)) ? (a) : (b))
#define my_min(a,b) (((a) < (b)) ? (a) : (b))
// IN_BUF_SIZE is the size of the file read buffer.
// IN_BUF_SIZE must be >= 1
#define IN_BUF_SIZE (1024*512)
static uint8 s_inbuf[IN_BUF_SIZE];
// COMP_OUT_BUF_SIZE is the size of the output buffer used during compression.
// COMP_OUT_BUF_SIZE must be >= 1 and <= OUT_BUF_SIZE
#define COMP_OUT_BUF_SIZE (1024*512)
// OUT_BUF_SIZE is the size of the output buffer used during decompression.
// OUT_BUF_SIZE must be a power of 2 >= TINFL_LZ_DICT_SIZE (because the low-level decompressor not only writes, but reads from the output buffer as it decompresses)
//#define OUT_BUF_SIZE (TINFL_LZ_DICT_SIZE)
#define OUT_BUF_SIZE (1024*512)
static uint8 s_outbuf[OUT_BUF_SIZE];
// tdefl_compressor contains all the state needed by the low-level compressor so it's a pretty big struct (~300k).
// This example makes it a global vs. putting it on the stack, of course in real-world usage you'll probably malloc() or new it.
tdefl_compressor g_deflator;
int main(int argc, char *argv[])
{
const char *pMode;
FILE *pInfile, *pOutfile;
uint infile_size;
int level = 9;
int p = 1;
const char *pSrc_filename;
const char *pDst_filename;
const void *next_in = s_inbuf;
size_t avail_in = 0;
void *next_out = s_outbuf;
size_t avail_out = OUT_BUF_SIZE;
size_t total_in = 0, total_out = 0;
long file_loc;
assert(COMP_OUT_BUF_SIZE <= OUT_BUF_SIZE);
printf("miniz.c example5 (demonstrates tinfl/tdefl)\n");
if (argc < 4)
{
printf("File to file compression/decompression using the low-level tinfl/tdefl API's.\n");
printf("Usage: example5 [options] [mode:c or d] infile outfile\n");
printf("\nModes:\n");
printf("c - Compresses file infile to a zlib stream in file outfile\n");
printf("d - Decompress zlib stream in file infile to file outfile\n");
printf("\nOptions:\n");
printf("-l[0-10] - Compression level, higher values are slower, 0 is none.\n");
return EXIT_FAILURE;
}
while ((p < argc) && (argv[p][0] == '-'))
{
switch (argv[p][1])
{
case 'l':
{
level = atoi(&argv[1][2]);
if ((level < 0) || (level > 10))
{
printf("Invalid level!\n");
return EXIT_FAILURE;
}
break;
}
default:
{
printf("Invalid option: %s\n", argv[p]);
return EXIT_FAILURE;
}
}
p++;
}
if ((argc - p) < 3)
{
printf("Must specify mode, input filename, and output filename after options!\n");
return EXIT_FAILURE;
}
else if ((argc - p) > 3)
{
printf("Too many filenames!\n");
return EXIT_FAILURE;
}
pMode = argv[p++];
if (!strchr("cCdD", pMode[0]))
{
printf("Invalid mode!\n");
return EXIT_FAILURE;
}
pSrc_filename = argv[p++];
pDst_filename = argv[p++];
printf("Mode: %c, Level: %u\nInput File: \"%s\"\nOutput File: \"%s\"\n", pMode[0], level, pSrc_filename, pDst_filename);
// Open input file.
pInfile = fopen(pSrc_filename, "rb");
if (!pInfile)
{
printf("Failed opening input file!\n");
return EXIT_FAILURE;
}
// Determine input file's size.
fseek(pInfile, 0, SEEK_END);
file_loc = ftell(pInfile);
fseek(pInfile, 0, SEEK_SET);
if ((file_loc < 0) || (file_loc > INT_MAX))
{
// This is not a limitation of miniz or tinfl, but this example.
printf("File is too large to be processed by this example.\n");
return EXIT_FAILURE;
}
infile_size = (uint)file_loc;
// Open output file.
pOutfile = fopen(pDst_filename, "wb");
if (!pOutfile)
{
printf("Failed opening output file!\n");
return EXIT_FAILURE;
}
printf("Input file size: %u\n", infile_size);
if ((pMode[0] == 'c') || (pMode[0] == 'C'))
{
// The number of dictionary probes to use at each compression level (0-10). 0=implies fastest/minimal possible probing.
static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
tdefl_status status;
uint infile_remaining = infile_size;
// create tdefl() compatible flags (we have to compose the low-level flags ourselves, or use tdefl_create_comp_flags_from_zip_params() but that means MINIZ_NO_ZLIB_APIS can't be defined).
mz_uint comp_flags = TDEFL_WRITE_ZLIB_HEADER | s_tdefl_num_probes[MZ_MIN(10, level)] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
if (!level)
comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
// Initialize the low-level compressor.
status = tdefl_init(&g_deflator, NULL, NULL, comp_flags);
if (status != TDEFL_STATUS_OKAY)
{
printf("tdefl_init() failed!\n");
return EXIT_FAILURE;
}
avail_out = COMP_OUT_BUF_SIZE;
// Compression.
for ( ; ; )
{
size_t in_bytes, out_bytes;
if (!avail_in)
{
// Input buffer is empty, so read more bytes from input file.
uint n = my_min(IN_BUF_SIZE, infile_remaining);
if (fread(s_inbuf, 1, n, pInfile) != n)
{
printf("Failed reading from input file!\n");
return EXIT_FAILURE;
}
next_in = s_inbuf;
avail_in = n;
infile_remaining -= n;
//printf("Input bytes remaining: %u\n", infile_remaining);
}
in_bytes = avail_in;
out_bytes = avail_out;
// Compress as much of the input as possible (or all of it) to the output buffer.
status = tdefl_compress(&g_deflator, next_in, &in_bytes, next_out, &out_bytes, infile_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
next_in = (const char *)next_in + in_bytes;
avail_in -= in_bytes;
total_in += in_bytes;
next_out = (char *)next_out + out_bytes;
avail_out -= out_bytes;
total_out += out_bytes;
if ((status != TDEFL_STATUS_OKAY) || (!avail_out))
{
// Output buffer is full, or compression is done or failed, so write buffer to output file.
uint n = COMP_OUT_BUF_SIZE - (uint)avail_out;
if (fwrite(s_outbuf, 1, n, pOutfile) != n)
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
next_out = s_outbuf;
avail_out = COMP_OUT_BUF_SIZE;
}
if (status == TDEFL_STATUS_DONE)
{
// Compression completed successfully.
break;
}
else if (status != TDEFL_STATUS_OKAY)
{
// Compression somehow failed.
printf("tdefl_compress() failed with status %i!\n", status);
return EXIT_FAILURE;
}
}
}
else if ((pMode[0] == 'd') || (pMode[0] == 'D'))
{
// Decompression.
uint infile_remaining = infile_size;
tinfl_decompressor inflator;
tinfl_init(&inflator);
for ( ; ; )
{
size_t in_bytes, out_bytes;
tinfl_status status;
if (!avail_in)
{
// Input buffer is empty, so read more bytes from input file.
uint n = my_min(IN_BUF_SIZE, infile_remaining);
if (fread(s_inbuf, 1, n, pInfile) != n)
{
printf("Failed reading from input file!\n");
return EXIT_FAILURE;
}
next_in = s_inbuf;
avail_in = n;
infile_remaining -= n;
}
in_bytes = avail_in;
out_bytes = avail_out;
status = tinfl_decompress(&inflator, (const mz_uint8 *)next_in, &in_bytes, s_outbuf, (mz_uint8 *)next_out, &out_bytes, (infile_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0) | TINFL_FLAG_PARSE_ZLIB_HEADER);
avail_in -= in_bytes;
next_in = (const mz_uint8 *)next_in + in_bytes;
total_in += in_bytes;
avail_out -= out_bytes;
next_out = (mz_uint8 *)next_out + out_bytes;
total_out += out_bytes;
if ((status <= TINFL_STATUS_DONE) || (!avail_out))
{
// Output buffer is full, or decompression is done, so write buffer to output file.
uint n = OUT_BUF_SIZE - (uint)avail_out;
if (fwrite(s_outbuf, 1, n, pOutfile) != n)
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
next_out = s_outbuf;
avail_out = OUT_BUF_SIZE;
}
// If status is <= TINFL_STATUS_DONE then either decompression is done or something went wrong.
if (status <= TINFL_STATUS_DONE)
{
if (status == TINFL_STATUS_DONE)
{
// Decompression completed successfully.
break;
}
else
{
// Decompression failed.
printf("tinfl_decompress() failed with status %i!\n", status);
return EXIT_FAILURE;
}
}
}
}
else
{
printf("Invalid mode!\n");
return EXIT_FAILURE;
}
fclose(pInfile);
if (EOF == fclose(pOutfile))
{
printf("Failed writing to output file!\n");
return EXIT_FAILURE;
}
printf("Total input bytes: %u\n", (mz_uint32)total_in);
printf("Total output bytes: %u\n", (mz_uint32)total_out);
printf("Success.\n");
return EXIT_SUCCESS;
}
+88
View File
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="example5" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug Win32">
<Option output="$(SolutionDir)bin_mingw\example5D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example5\Debug Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O0" />
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-g" />
</Compiler>
<Linker>
<Add option="-m32" />
</Linker>
</Target>
<Target title="Debug x64">
<Option output="$(SolutionDir)bin_mingw\example5_x64D" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example5\Debug x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-D_DEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O0" />
</Compiler>
</Target>
<Target title="Release Win32">
<Option output="$(SolutionDir)bin_mingw\example5" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example5\Release Win32_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-m32" />
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
<Linker>
<Add option="-s" />
<Add option="-m32" />
</Linker>
</Target>
<Target title="Release x64">
<Option output="$(SolutionDir)bin_mingw\example5_x64" prefix_auto="1" extension_auto="1" />
<Option working_dir="$(SolutionDir)bin_mingw" />
<Option object_output="example5\Release x64_Win32" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-DWIN32" />
<Add option="-DNDEBUG" />
<Add option="-D_CONSOLE" />
<Add option="-D_CRT_SECURE_NO_WARNINGS" />
<Add option="-Wall" />
<Add option="-O3" />
</Compiler>
</Target>
</Build>
<Unit filename="example5.c">
<Option compilerVar="CC" />
</Unit>
<Extensions>
<code_completion />
<debugger />
</Extensions>
</Project>
</CodeBlocks_project_file>
+346
View File
@@ -0,0 +1,346 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="example5"
ProjectGUID="{AE293522-92D8-4B60-95C7-B4AEE10A303F}"
RootNamespace="example5"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64.exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FD737F1-C7A5-4376-A066-2A32D752A31F}"
>
<File
RelativePath=".\example5.c"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{17DA6AB6-F800-4c08-8B7A-83BB121AAC02}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+163
View File
@@ -0,0 +1,163 @@
// example6.c - Demonstrates how to miniz's PNG writer func
// Public domain, April 11 2012, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c.
// Mandlebrot set code from http://rosettacode.org/wiki/Mandelbrot_set#C
// Must link this example against libm on Linux.
// Purposely disable a whole bunch of stuff this low-level example doesn't use.
#define MINIZ_NO_STDIO
#define MINIZ_NO_ARCHIVE_APIS
#define MINIZ_NO_TIME
#define MINIZ_NO_ZLIB_APIS
#include "miniz.c"
// Now include stdio.h because this test uses fopen(), etc. (but we still don't want miniz.c's stdio stuff, for testing).
#include <stdio.h>
#include <limits.h>
#include <math.h>
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;
typedef struct
{
uint8 r, g, b;
} rgb_t;
static void hsv_to_rgb(int hue, int min, int max, rgb_t *p)
{
const int invert = 0;
const int saturation = 1;
const int color_rotate = 0;
if (min == max) max = min + 1;
if (invert) hue = max - (hue - min);
if (!saturation) {
p->r = p->g = p->b = 255 * (max - hue) / (max - min);
return;
}
double h = fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6);
double c = 255.0f * saturation;
double X = c * (1 - fabs(fmod(h, 2) - 1));
p->r = p->g = p->b = 0;
switch((int)h) {
case 0: p->r = c; p->g = X; return;
case 1: p->r = X; p->g = c; return;
case 2: p->g = c; p->b = X; return;
case 3: p->g = X; p->b = c; return;
case 4: p->r = X; p->b = c; return;
default:p->r = c; p->b = X;
}
}
int main(int argc, char *argv[])
{
(void)argc, (void)argv;
// Image resolution
const int iXmax = 4096;
const int iYmax = 4096;
// Output filename
static const char *pFilename = "mandelbrot.png";
int iX, iY;
const double CxMin = -2.5;
const double CxMax = 1.5;
const double CyMin = -2.0;
const double CyMax = 2.0;
double PixelWidth = (CxMax - CxMin) / iXmax;
double PixelHeight = (CyMax - CyMin) / iYmax;
// Z=Zx+Zy*i ; Z0 = 0
double Zx, Zy;
double Zx2, Zy2; // Zx2=Zx*Zx; Zy2=Zy*Zy
int Iteration;
const int IterationMax = 200;
// bail-out value , radius of circle
const double EscapeRadius = 2;
double ER2=EscapeRadius * EscapeRadius;
uint8 *pImage = (uint8 *)malloc(iXmax * 3 * iYmax);
// world ( double) coordinate = parameter plane
double Cx,Cy;
int MinIter = 9999, MaxIter = 0;
for(iY = 0; iY < iYmax; iY++)
{
Cy = CyMin + iY * PixelHeight;
if (fabs(Cy) < PixelHeight/2)
Cy = 0.0; // Main antenna
for(iX = 0; iX < iXmax; iX++)
{
uint8 *color = pImage + (iX * 3) + (iY * iXmax * 3);
Cx = CxMin + iX * PixelWidth;
// initial value of orbit = critical point Z= 0
Zx = 0.0;
Zy = 0.0;
Zx2 = Zx * Zx;
Zy2 = Zy * Zy;
for (Iteration=0;Iteration<IterationMax && ((Zx2+Zy2)<ER2);Iteration++)
{
Zy = 2 * Zx * Zy + Cy;
Zx =Zx2 - Zy2 + Cx;
Zx2 = Zx * Zx;
Zy2 = Zy * Zy;
};
color[0] = (uint8)Iteration;
color[1] = (uint8)Iteration >> 8;
color[2] = 0;
if (Iteration < MinIter)
MinIter = Iteration;
if (Iteration > MaxIter)
MaxIter = Iteration;
}
}
for(iY = 0; iY < iYmax; iY++)
{
for(iX = 0; iX < iXmax; iX++)
{
uint8 *color = (uint8 *)(pImage + (iX * 3) + (iY * iXmax * 3));
uint Iterations = color[0] | (color[1] << 8U);
hsv_to_rgb(Iterations, MinIter, MaxIter, (rgb_t *)color);
}
}
// Now write the PNG image.
{
size_t png_data_size = 0;
void *pPNG_data = tdefl_write_image_to_png_file_in_memory_ex(pImage, iXmax, iYmax, 3, &png_data_size, 6, MZ_FALSE);
if (!pPNG_data)
fprintf(stderr, "tdefl_write_image_to_png_file_in_memory_ex() failed!\n");
else
{
FILE *pFile = fopen(pFilename, "wb");
fwrite(pPNG_data, 1, png_data_size, pFile);
fclose(pFile);
printf("Wrote %s\n", pFilename);
}
// mz_free() is by default just an alias to free() internally, but if you've overridden miniz's allocation funcs you'll probably need to call mz_free().
mz_free(pPNG_data);
}
free(pImage);
return EXIT_SUCCESS;
}
+76
View File
@@ -0,0 +1,76 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example1", "example1.vcproj", "{BE273522-92D8-4B60-95C7-C3AEE10A303E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example2", "example2.vcproj", "{AE273522-92D8-4B60-95C7-C3AEE10A303E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example3", "example3.vcproj", "{AE273522-92D8-4B60-95C7-C3AEE10A303F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example4", "example4.vcproj", "{AE293522-92D8-4B60-95C7-C3AEE10A303F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example5", "example5.vcproj", "{AE293522-92D8-4B60-95C7-B4AEE10A303F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniz_tester", "miniz_tester.vcproj", "{AE293522-92D9-1B60-95C7-B4AEE10A303F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|Win32.ActiveCfg = Debug|Win32
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|Win32.Build.0 = Debug|Win32
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|x64.ActiveCfg = Debug|x64
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|x64.Build.0 = Debug|x64
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|Win32.ActiveCfg = Release|Win32
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|Win32.Build.0 = Release|Win32
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|x64.ActiveCfg = Release|x64
{BE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|x64.Build.0 = Release|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|Win32.ActiveCfg = Debug|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|Win32.Build.0 = Debug|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|x64.ActiveCfg = Debug|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Debug|x64.Build.0 = Debug|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|Win32.ActiveCfg = Release|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|Win32.Build.0 = Release|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|x64.ActiveCfg = Release|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303E}.Release|x64.Build.0 = Release|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Debug|Win32.ActiveCfg = Debug|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Debug|Win32.Build.0 = Debug|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Debug|x64.ActiveCfg = Debug|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Debug|x64.Build.0 = Debug|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Release|Win32.ActiveCfg = Release|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Release|Win32.Build.0 = Release|Win32
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Release|x64.ActiveCfg = Release|x64
{AE273522-92D8-4B60-95C7-C3AEE10A303F}.Release|x64.Build.0 = Release|x64
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Debug|Win32.ActiveCfg = Debug|Win32
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Debug|Win32.Build.0 = Debug|Win32
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Debug|x64.ActiveCfg = Debug|x64
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Debug|x64.Build.0 = Debug|x64
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Release|Win32.ActiveCfg = Release|Win32
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Release|Win32.Build.0 = Release|Win32
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Release|x64.ActiveCfg = Release|x64
{AE293522-92D8-4B60-95C7-C3AEE10A303F}.Release|x64.Build.0 = Release|x64
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Debug|Win32.ActiveCfg = Debug|Win32
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Debug|Win32.Build.0 = Debug|Win32
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Debug|x64.ActiveCfg = Debug|x64
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Debug|x64.Build.0 = Debug|x64
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Release|Win32.ActiveCfg = Release|Win32
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Release|Win32.Build.0 = Release|Win32
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Release|x64.ActiveCfg = Release|x64
{AE293522-92D8-4B60-95C7-B4AEE10A303F}.Release|x64.Build.0 = Release|x64
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Debug|Win32.ActiveCfg = Debug|Win32
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Debug|Win32.Build.0 = Debug|Win32
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Debug|x64.ActiveCfg = Debug|x64
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Debug|x64.Build.0 = Debug|x64
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Release|Win32.ActiveCfg = Release|Win32
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Release|Win32.Build.0 = Release|Win32
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Release|x64.ActiveCfg = Release|x64
{AE293522-92D9-1B60-95C7-B4AEE10A303F}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_workspace_file>
<Workspace title="Workspace">
<Project filename="example1.cbp" />
<Project filename="example2.cbp" active="1" />
<Project filename="example3.cbp" />
<Project filename="example4.cbp" />
<Project filename="example5.cbp" />
</Workspace>
</CodeBlocks_workspace_file>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+358
View File
@@ -0,0 +1,358 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="miniz_tester"
ProjectGUID="{AE293522-92D9-1B60-95C7-B4AEE10A303F}"
RootNamespace="miniz_tester"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64D.exe"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)bin"
IntermediateDirectory="$(ProjectName)\$(ConfigurationName)_$(PlatformName)"
ConfigurationType="1"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="3"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="4"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\$(ProjectName)_x64.exe"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FD737F1-C7A5-4376-A066-2A32D752A31F}"
>
<File
RelativePath=".\miniz.c"
>
</File>
<File
RelativePath=".\miniz_tester.cpp"
>
</File>
<File
RelativePath=".\timer.cpp"
>
</File>
<File
RelativePath=".\timer.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{17DA6AB6-F800-4c08-8B7A-83BB121AAC02}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+152
View File
@@ -0,0 +1,152 @@
// File: timer.cpp - Simple high-precision timer class. Supports Win32, X360, and POSIX/Linux
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include "timer.h"
#if defined(WIN32)
#include <windows.h>
#elif defined(_XBOX)
#include <xtl.h>
#endif
unsigned long long timer::g_init_ticks;
unsigned long long timer::g_freq;
double timer::g_inv_freq;
#if defined(WIN32) || defined(_XBOX)
inline void query_counter(timer_ticks *pTicks)
{
QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(pTicks));
}
inline void query_counter_frequency(timer_ticks *pTicks)
{
QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(pTicks));
}
#elif defined(__GNUC__)
#include <sys/timex.h>
inline void query_counter(timer_ticks *pTicks)
{
struct timeval cur_time;
gettimeofday(&cur_time, NULL);
*pTicks = static_cast<unsigned long long>(cur_time.tv_sec)*1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
}
inline void query_counter_frequency(timer_ticks *pTicks)
{
*pTicks = 1000000;
}
#endif
timer::timer() :
m_start_time(0),
m_stop_time(0),
m_started(false),
m_stopped(false)
{
if (!g_inv_freq)
init();
}
timer::timer(timer_ticks start_ticks)
{
if (!g_inv_freq)
init();
m_start_time = start_ticks;
m_started = true;
m_stopped = false;
}
void timer::start(timer_ticks start_ticks)
{
m_start_time = start_ticks;
m_started = true;
m_stopped = false;
}
void timer::start()
{
query_counter(&m_start_time);
m_started = true;
m_stopped = false;
}
void timer::stop()
{
assert(m_started);
query_counter(&m_stop_time);
m_stopped = true;
}
double timer::get_elapsed_secs() const
{
assert(m_started);
if (!m_started)
return 0;
timer_ticks stop_time = m_stop_time;
if (!m_stopped)
query_counter(&stop_time);
timer_ticks delta = stop_time - m_start_time;
return delta * g_inv_freq;
}
timer_ticks timer::get_elapsed_us() const
{
assert(m_started);
if (!m_started)
return 0;
timer_ticks stop_time = m_stop_time;
if (!m_stopped)
query_counter(&stop_time);
timer_ticks delta = stop_time - m_start_time;
return (delta * 1000000ULL + (g_freq >> 1U)) / g_freq;
}
void timer::init()
{
if (!g_inv_freq)
{
query_counter_frequency(&g_freq);
g_inv_freq = 1.0f / g_freq;
query_counter(&g_init_ticks);
}
}
timer_ticks timer::get_init_ticks()
{
if (!g_inv_freq)
init();
return g_init_ticks;
}
timer_ticks timer::get_ticks()
{
if (!g_inv_freq)
init();
timer_ticks ticks;
query_counter(&ticks);
return ticks - g_init_ticks;
}
double timer::ticks_to_secs(timer_ticks ticks)
{
if (!g_inv_freq)
init();
return ticks * g_inv_freq;
}
+40
View File
@@ -0,0 +1,40 @@
// File: timer.h
#pragma once
typedef unsigned long long timer_ticks;
class timer
{
public:
timer();
timer(timer_ticks start_ticks);
void start();
void start(timer_ticks start_ticks);
void stop();
double get_elapsed_secs() const;
inline double get_elapsed_ms() const { return get_elapsed_secs() * 1000.0f; }
timer_ticks get_elapsed_us() const;
static void init();
static inline timer_ticks get_ticks_per_sec() { return g_freq; }
static timer_ticks get_init_ticks();
static timer_ticks get_ticks();
static double ticks_to_secs(timer_ticks ticks);
static inline double ticks_to_ms(timer_ticks ticks) { return ticks_to_secs(ticks) * 1000.0f; }
static inline double get_secs() { return ticks_to_secs(get_ticks()); }
static inline double get_ms() { return ticks_to_ms(get_ticks()); }
private:
static timer_ticks g_init_ticks;
static timer_ticks g_freq;
static double g_inv_freq;
timer_ticks m_start_time;
timer_ticks m_stop_time;
bool m_started : 1;
bool m_stopped : 1;
};
+592
View File
@@ -0,0 +1,592 @@
/* tinfl.c v1.11 - public domain inflate with zlib header parsing/adler32 checking (inflate-only subset of miniz.c)
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated May 20, 2011
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
The entire decompressor coroutine is implemented in tinfl_decompress(). The other functions are optional high-level helpers.
*/
#ifndef TINFL_HEADER_INCLUDED
#define TINFL_HEADER_INCLUDED
#include <stdlib.h>
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef unsigned long long mz_uint64;
#if defined(_M_IX86) || defined(_M_X64)
// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 if integer loads and stores to unaligned addresses are acceptable on the target platform (slightly faster).
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#if defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if the processor has 64-bit general purpose registers (enables 64-bit bitbuffer in inflator)
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
// Works around MSVC's spammy "warning C4127: conditional expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
enum
{
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
// The caller must free() the returned block when it's no longer needed.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.
// Returns 1 on success or 0 on failure.
typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum
{
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.
// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum
{
TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct
{
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag
{
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
#endif // #ifdef TINFL_HEADER_INCLUDED
// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
#ifndef TINFL_HEADER_FILE_ONLY
#include <string.h>
// MZ_MALLOC, etc. are only used by the optional high-level helper functions.
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a,b) (((a)>(b))?(a):(b))
#define MZ_MIN(a,b) (((a)<(b))?(a):(b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
#else
#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#endif
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN switch(r->m_state) { case 0:
#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
#define TINFL_CR_FINISH }
// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
#define TINFL_GET_BYTE(state_index, c) do { \
if (pIn_buf_cur >= pIn_buf_end) { \
for ( ; ; ) { \
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
if (pIn_buf_cur < pIn_buf_end) { \
c = *pIn_buf_cur++; \
break; \
} \
} else { \
c = 0; \
break; \
} \
} \
} else c = *pIn_buf_cur++; } MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
// bit buffer contains >=15 bits (deflate's max. Huffman code size).
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do { \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) { \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) \
break; \
} else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
} TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
} while (num_bits < 15);
// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
// The slow path is only executed at the very end of the input buffer.
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
int temp; mz_uint code_len, c; \
if (num_bits < 15) { \
if ((pIn_buf_end - pIn_buf_cur) < 2) { \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} else { \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
code_len = temp >> 9, temp &= 511; \
else { \
code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
} sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
{
static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
static const int s_min_table_sizes[3] = { 257, 1, 4 };
tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
// Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }
num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); }
}
do
{
TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1;
if (r->m_type == 0)
{
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); }
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); }
while ((counter) && (num_bits))
{
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); }
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter)
{
size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); }
while (pIn_buf_cur >= pIn_buf_end)
{
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
{
TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
}
else
{
TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
}
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
}
}
else if (r->m_type == 3)
{
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
}
else
{
if (r->m_type == 1)
{
mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8;
}
else
{
for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }
r->m_table_sizes[2] = 19;
}
for ( ; (int)r->m_type >= 0; r->m_type--)
{
int tree_next, tree_cur; tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); }
if ((65536 != total) && (used_syms > 1))
{
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
{
mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue;
cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; }
if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
{
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2)
{
for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
{
mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
if ((dist == 16) && (!counter))
{
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
{
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
}
}
for ( ; ; )
{
mz_uint8 *pSrc;
for ( ; ; )
{
if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
{
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256)
break;
while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); }
*pOut_buf_cur++ = (mz_uint8)counter;
}
else
{
int sym2; mz_uint code_len;
#if TINFL_USE_64BIT_BITBUF
if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; }
#else
if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
#endif
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
}
counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
if (counter & 256)
break;
#if !TINFL_USE_64BIT_BITBUF
if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
#endif
if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
code_len = sym2 >> 9;
else
{
code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
}
bit_buf >>= code_len; num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256)
{
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256) break;
num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; }
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; }
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
{
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
{
while (counter--)
{
while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); }
*pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
}
continue;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
else if ((counter >= 9) && (counter <= dist))
{
const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
do
{
((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
pOut_buf_cur += 8;
} while ((pSrc += 8) < pSrc_end);
if ((counter &= 7) < 3)
{
if (counter)
{
pOut_buf_cur[0] = pSrc[0];
if (counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
continue;
}
}
#endif
do
{
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3; pSrc += 3;
} while ((int)(counter -= 3) > 2);
if ((int)counter > 0)
{
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
} while (!(r->m_final & 1));
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
{
TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; }
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
{
const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
while (buf_len)
{
for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
{
s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
}
for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
// Higher level helper functions.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
{
tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
*pOut_len = 0;
tinfl_init(&decomp);
for ( ; ; )
{
size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,
(flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
{
MZ_FREE(pBuf); *pOut_len = 0; return NULL;
}
src_buf_ofs += src_buf_size;
*pOut_len += dst_buf_size;
if (status == TINFL_STATUS_DONE) break;
new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
if (!pNew_buf)
{
MZ_FREE(pBuf); *pOut_len = 0; return NULL;
}
pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
}
return pBuf;
}
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
{
tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp);
status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
{
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict)
return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for ( ; ; )
{
size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
{
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
#endif // #ifndef TINFL_HEADER_FILE_ONLY
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
+2
View File
@@ -0,0 +1,2 @@
.build
*.syms
+95
View File
@@ -0,0 +1,95 @@
idf_build_get_property(target IDF_TARGET)
if(${target} STREQUAL "linux")
return() # This component is not supported by the POSIX/Linux simulator
endif()
set(include_dirs "platform_include")
if(BOOTLOADER_BUILD)
# Bootloader builds need the platform_include directory (for assert.h), but nothing else
idf_component_register(INCLUDE_DIRS platform_include)
return()
endif()
set(srcs
"abort.c"
"assert.c"
"heap.c"
"flockfile.c"
"locks.c"
"poll.c"
"pthread.c"
"random.c"
"getentropy.c"
"reent_init.c"
"newlib_init.c"
"syscalls.c"
"termios.c"
"stdatomic.c"
"time.c"
"sysconf.c"
"realpath.c"
"scandir.c"
)
if(CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND)
list(APPEND srcs "port/xtensa/stdatomic_s32c1i.c")
endif()
if(CONFIG_SPIRAM_CACHE_WORKAROUND)
set(ldfragments "esp32-spiram-rom-functions-c.lf")
endif()
list(APPEND ldfragments "newlib.lf" "system_libs.lf")
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS "${include_dirs}"
PRIV_INCLUDE_DIRS priv_include
PRIV_REQUIRES soc spi_flash
LDFRAGMENTS "${ldfragments}")
# Toolchain libraries require code defined in this component
idf_component_get_property(newlib newlib COMPONENT_LIB)
target_link_libraries(${COMPONENT_LIB} INTERFACE c m ${CONFIG_COMPILER_RT_LIB_NAME} "$<TARGET_FILE:${newlib}>")
set_source_files_properties(heap.c PROPERTIES COMPILE_FLAGS -fno-builtin)
if(CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND)
set_source_files_properties("port/xtensa/stdatomic_s32c1i.c"
PROPERTIES COMPILE_FLAGS "-mno-disable-hardware-atomics")
endif()
# Forces the linker to include heap, syscall, pthread, assert, and retargetable locks from this component,
# instead of the implementations provided by newlib.
list(APPEND EXTRA_LINK_FLAGS "-u newlib_include_heap_impl")
list(APPEND EXTRA_LINK_FLAGS "-u newlib_include_syscalls_impl")
list(APPEND EXTRA_LINK_FLAGS "-u newlib_include_pthread_impl")
list(APPEND EXTRA_LINK_FLAGS "-u newlib_include_assert_impl")
list(APPEND EXTRA_LINK_FLAGS "-u newlib_include_getentropy_impl")
target_link_libraries(${COMPONENT_LIB} INTERFACE "${EXTRA_LINK_FLAGS}")
# Forces the linker to include newlib_init.c
target_link_libraries(${COMPONENT_LIB} INTERFACE "-u newlib_include_init_funcs")
if(CONFIG_NEWLIB_NANO_FORMAT)
if(CMAKE_C_COMPILER_ID MATCHES "Clang")
set(libc_dir_cmd ${CMAKE_C_COMPILER})
string(REPLACE " " ";" cflags_list ${CMAKE_C_FLAGS})
list(APPEND libc_dir_cmd ${cflags_list} "-print-file-name=libc.a")
execute_process(
COMMAND ${libc_dir_cmd}
OUTPUT_VARIABLE libc_dir
)
get_filename_component(libc_dir ${libc_dir} DIRECTORY)
target_link_directories(${COMPONENT_LIB} INTERFACE "${libc_dir}/nano")
else()
target_link_libraries(${COMPONENT_LIB} INTERFACE "--specs=nano.specs")
endif()
endif()
add_subdirectory(port)
# if lwip is included in the build, add it as a public requirement so that
# #include <sys/socket.h> works without any special provisions.
idf_component_optional_requires(PUBLIC lwip)
+952
View File
@@ -0,0 +1,952 @@
The newlib subdirectory is a collection of software from several sources.
Each file may have its own copyright/license that is embedded in the source
file. Unless otherwise noted in the body of the source file(s), the following copyright
notices will apply to the contents of the newlib subdirectory:
(1) Red Hat Incorporated
Copyright (c) 1994-2009 Red Hat, Inc. All rights reserved.
This copyrighted material is made available to anyone wishing to use,
modify, copy, or redistribute it subject to the terms and conditions
of the BSD License. This program is distributed in the hope that
it will be useful, but WITHOUT ANY WARRANTY expressed or implied,
including the implied warranties of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. A copy of this license is available at
http://www.opensource.org/licenses. Any Red Hat trademarks that are
incorporated in the source code or documentation are not subject to
the BSD License and may only be used or replicated with the express
permission of Red Hat, Inc.
(2) University of California, Berkeley
Copyright (c) 1981-2000 The Regents of the University of California.
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 of the University 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
(3) David M. Gay (AT&T 1991, Lucent 1998)
The author of this software is David M. Gay.
Copyright (c) 1991 by AT&T.
Permission to use, copy, modify, and distribute this software for any
purpose without fee is hereby granted, provided that this entire notice
is included in all copies of any software which is or includes a copy
or modification of this software and in all copies of the supporting
documentation for such software.
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
-------------------------------------------------------------------
The author of this software is David M. Gay.
Copyright (C) 1998-2001 by Lucent Technologies
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of Lucent or any of its entities
not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
(4) Advanced Micro Devices
Copyright 1989, 1990 Advanced Micro Devices, Inc.
This software is the property of Advanced Micro Devices, Inc (AMD) which
specifically grants the user the right to modify, use and distribute this
software provided this notice is not removed or altered. All other rights
are reserved by AMD.
AMD MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO THIS
SOFTWARE. IN NO EVENT SHALL AMD BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL
DAMAGES IN CONNECTION WITH OR ARISING FROM THE FURNISHING, PERFORMANCE, OR
USE OF THIS SOFTWARE.
So that all may benefit from your experience, please report any problems
or suggestions about this software to the 29K Technical Support Center at
800-29-29-AMD (800-292-9263) in the USA, or 0800-89-1131 in the UK, or
0031-11-1129 in Japan, toll free. The direct dial number is 512-462-4118.
Advanced Micro Devices, Inc.
29K Support Products
Mail Stop 573
5900 E. Ben White Blvd.
Austin, TX 78741
800-292-9263
(5)
(6)
(7) Sun Microsystems
Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
Developed at SunPro, a Sun Microsystems, Inc. business.
Permission to use, copy, modify, and distribute this
software is freely granted, provided that this notice is preserved.
(8) Hewlett Packard
(c) Copyright 1986 HEWLETT-PACKARD COMPANY
To anyone who acknowledges that this file is provided "AS IS"
without any express or implied warranty:
permission to use, copy, modify, and distribute this file
for any purpose is hereby granted without fee, provided that
the above copyright notice and this notice appears in all
copies, and that the name of Hewlett-Packard Company not be
used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
Hewlett-Packard Company makes no representations about the
suitability of this software for any purpose.
(9) Hans-Peter Nilsson
Copyright (C) 2001 Hans-Peter Nilsson
Permission to use, copy, modify, and distribute this software is
freely granted, provided that the above copyright notice, this notice
and the following disclaimer are preserved with no changes.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.
(10) Stephane Carrez (m68hc11-elf/m68hc12-elf targets only)
Copyright (C) 1999, 2000, 2001, 2002 Stephane Carrez (stcarrez@nerim.fr)
The authors hereby grant permission to use, copy, modify, distribute,
and license this software and its documentation for any purpose, provided
that existing copyright notices are retained in all copies and that this
notice is included verbatim in any distributions. No written agreement,
license, or royalty fee is required for any of the authorized uses.
Modifications to this software may be copyrighted by their authors
and need not follow the licensing terms described here, provided that
the new terms are clearly indicated on the first page of each file where
they apply.
(11) Christopher G. Demetriou
Copyright (c) 2001 Christopher G. Demetriou
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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.
(12) SuperH, Inc.
Copyright 2002 SuperH, Inc. All rights reserved
This software is the property of SuperH, Inc (SuperH) which specifically
grants the user the right to modify, use and distribute this software
provided this notice is not removed or altered. All other rights are
reserved by SuperH.
SUPERH MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO
THIS SOFTWARE. IN NO EVENT SHALL SUPERH BE LIABLE FOR INDIRECT, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES IN CONNECTION WITH OR ARISING FROM
THE FURNISHING, PERFORMANCE, OR USE OF THIS SOFTWARE.
So that all may benefit from your experience, please report any problems
or suggestions about this software to the SuperH Support Center via
e-mail at softwaresupport@superh.com .
SuperH, Inc.
405 River Oaks Parkway
San Jose
CA 95134
USA
(13) Royal Institute of Technology
Copyright (c) 1999 Kungliga Tekniska Högskolan
(Royal Institute of Technology, Stockholm, Sweden).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of KTH 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 KTH AND ITS CONTRIBUTORS ``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 KTH OR ITS CONTRIBUTORS 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.
(14) Alexey Zelkin
Copyright (c) 2000, 2001 Alexey Zelkin <phantom@FreeBSD.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(15) Andrey A. Chernov
Copyright (C) 1997 by Andrey A. Chernov, Moscow, Russia.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE REGENTS OR CONTRIBUTORS 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.
(16) FreeBSD
Copyright (c) 1997-2002 FreeBSD Project.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(17) S. L. Moshier
Author: S. L. Moshier.
Copyright (c) 1984,2000 S.L. Moshier
Permission to use, copy, modify, and distribute this software for any
purpose without fee is hereby granted, provided that this entire notice
is included in all copies of any software which is or includes a copy
or modification of this software and in all copies of the supporting
documentation for such software.
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN PARTICULAR, THE AUTHOR MAKES NO REPRESENTATION
OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY OF THIS
SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
(18) Citrus Project
Copyright (c)1999 Citrus Project,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(19) Todd C. Miller
Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``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
THE AUTHOR 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.
(20) DJ Delorie (i386)
Copyright (C) 1991 DJ Delorie
All rights reserved.
Redistribution, modification, and use in source and binary forms is permitted
provided that the above copyright notice and following paragraph are
duplicated in all such forms.
This file is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
(21) Free Software Foundation LGPL License (*-linux* targets only)
Copyright (C) 1990-1999, 2000, 2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Mark Kettenis <kettenis@phys.uva.nl>, 1997.
The GNU C 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 GNU C 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 GNU C Library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
(22) Xavier Leroy LGPL License (i[3456]86-*-linux* targets only)
Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Library 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 Library General Public License for more details.
(23) Intel (i960)
Copyright (c) 1993 Intel Corporation
Intel hereby grants you permission to copy, modify, and distribute this
software and its documentation. Intel grants this permission provided
that the above copyright notice appears in all copies and that both the
copyright notice and this permission notice appear in supporting
documentation. In addition, Intel grants this permission provided that
you prominently mark as "not part of the original" any modifications
made to this software or documentation, and that the name of Intel
Corporation not be used in advertising or publicity pertaining to
distribution of the software or the documentation without specific,
written prior permission.
Intel Corporation provides this AS IS, WITHOUT ANY WARRANTY, EXPRESS OR
IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Intel makes no guarantee or
representations regarding the use of, or the results of the use of,
the software and documentation in terms of correctness, accuracy,
reliability, currentness, or otherwise; and you rely on the software,
documentation and results solely at your own risk.
IN NO EVENT SHALL INTEL BE LIABLE FOR ANY LOSS OF USE, LOSS OF BUSINESS,
LOSS OF PROFITS, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES
OF ANY KIND. IN NO EVENT SHALL INTEL'S TOTAL LIABILITY EXCEED THE SUM
PAID TO INTEL FOR THE PRODUCT LICENSED HEREUNDER.
(24) Hewlett-Packard (hppa targets only)
(c) Copyright 1986 HEWLETT-PACKARD COMPANY
To anyone who acknowledges that this file is provided "AS IS"
without any express or implied warranty:
permission to use, copy, modify, and distribute this file
for any purpose is hereby granted without fee, provided that
the above copyright notice and this notice appears in all
copies, and that the name of Hewlett-Packard Company not be
used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
Hewlett-Packard Company makes no representations about the
suitability of this software for any purpose.
(25) Henry Spencer (only *-linux targets)
Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved.
This software is not subject to any license of the American Telephone
and Telegraph Company or of the Regents of the University of California.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
(26) Mike Barcroft
Copyright (c) 2001 Mike Barcroft <mike@FreeBSD.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(27) Konstantin Chuguev (--enable-newlib-iconv)
Copyright (c) 1999, 2000
Konstantin Chuguev. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
iconv (Charset Conversion Library) v2.0
(28) Artem Bityuckiy (--enable-newlib-iconv)
Copyright (c) 2003, Artem B. Bityuckiy, SoftMine Corporation.
Rights transferred to Franklin Electronic Publishers.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(29) IBM, Sony, Toshiba (only spu-* targets)
(C) Copyright 2001,2006,
International Business Machines Corporation,
Sony Computer Entertainment, Incorporated,
Toshiba Corporation,
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 names of the copyright holders nor the names of their
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
(30) - Alex Tatmanjants (targets using libc/posix)
Copyright (c) 1995 Alex Tatmanjants <alex@elvisti.kiev.ua>
at Electronni Visti IA, Kiev, Ukraine.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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.
(31) - M. Warner Losh (targets using libc/posix)
Copyright (c) 1998, M. Warner Losh <imp@freebsd.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(32) - Andrey A. Chernov (targets using libc/posix)
Copyright (C) 1996 by Andrey A. Chernov, Moscow, Russia.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE REGENTS OR CONTRIBUTORS 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.
(33) - Daniel Eischen (targets using libc/posix)
Copyright (c) 2001 Daniel Eischen <deischen@FreeBSD.org>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE REGENTS OR CONTRIBUTORS 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.
(34) - Jon Beniston (only lm32-* targets)
Contributed by Jon Beniston <jon@beniston.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
(35) - ARM Ltd (arm and thumb variant targets only)
Copyright (c) 2009 ARM Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the company may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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.
(36) - Xilinx, Inc. (microblaze-* and powerpc-* targets)
Copyright (c) 2004, 2009 Xilinx, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of Xilinx 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 THE COPYRIGHT HOLDER AND CONTRIBUTORS "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 THE COPYRIGHT
HOLDER OR CONTRIBUTORS 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.
(37) Texas Instruments Incorporated (tic6x-*, *-tirtos targets)
Copyright (c) 1996-2010,2014 Texas Instruments Incorporated
http://www.ti.com/
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 of Texas Instruments Incorporated 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
(38) National Semiconductor (cr16-* and crx-* targets)
Copyright (c) 2004 National Semiconductor Corporation
The authors hereby grant permission to use, copy, modify, distribute,
and license this software and its documentation for any purpose, provided
that existing copyright notices are retained in all copies and that this
notice is included verbatim in any distributions. No written agreement,
license, or royalty fee is required for any of the authorized uses.
Modifications to this software may be copyrighted by their authors
and need not follow the licensing terms described here, provided that
the new terms are clearly indicated on the first page of each file where
they apply.
(39) - Adapteva, Inc. (epiphany-* targets)
Copyright (c) 2011, Adapteva, Inc.
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 of Adapteva 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
(40) - Altera Corportion (nios2-* targets)
Copyright (c) 2003 Altera Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
o Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
o 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.
o Neither the name of Altera Corporation 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 ALTERA CORPORATION, THE COPYRIGHT HOLDER,
AND ITS CONTRIBUTORS "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
THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
(41) Ed Schouten - Free BSD
Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
+124
View File
@@ -0,0 +1,124 @@
menu "Newlib"
choice NEWLIB_STDOUT_LINE_ENDING
prompt "Line ending for UART output"
default NEWLIB_STDOUT_LINE_ENDING_CRLF
help
This option allows configuring the desired line endings sent to UART
when a newline ('\n', LF) appears on stdout.
Three options are possible:
CRLF: whenever LF is encountered, prepend it with CR
LF: no modification is applied, stdout is sent as is
CR: each occurrence of LF is replaced with CR
This option doesn't affect behavior of the UART driver (drivers/uart.h).
config NEWLIB_STDOUT_LINE_ENDING_CRLF
bool "CRLF"
config NEWLIB_STDOUT_LINE_ENDING_LF
bool "LF"
config NEWLIB_STDOUT_LINE_ENDING_CR
bool "CR"
endchoice
choice NEWLIB_STDIN_LINE_ENDING
prompt "Line ending for UART input"
default NEWLIB_STDIN_LINE_ENDING_CR
help
This option allows configuring which input sequence on UART produces
a newline ('\n', LF) on stdin.
Three options are possible:
CRLF: CRLF is converted to LF
LF: no modification is applied, input is sent to stdin as is
CR: each occurrence of CR is replaced with LF
This option doesn't affect behavior of the UART driver (drivers/uart.h).
config NEWLIB_STDIN_LINE_ENDING_CRLF
bool "CRLF"
config NEWLIB_STDIN_LINE_ENDING_LF
bool "LF"
config NEWLIB_STDIN_LINE_ENDING_CR
bool "CR"
endchoice
config NEWLIB_NANO_FORMAT
bool "Enable 'nano' formatting options for printf/scanf family"
default y if IDF_TARGET_ESP32C2
help
In most chips the ROM contains parts of newlib C library, including printf/scanf family
of functions. These functions have been compiled with so-called "nano"
formatting option. This option doesn't support 64-bit integer formats and C99
features, such as positional arguments.
For more details about "nano" formatting option, please see newlib readme file,
search for '--enable-newlib-nano-formatted-io':
https://sourceware.org/git/?p=newlib-cygwin.git;a=blob_plain;f=newlib/README;hb=HEAD
If this option is enabled and the ROM contains functions from newlib-nano, the build system
will use functions available in ROM, reducing the application binary size.
Functions available in ROM run faster than functions which run from flash. Functions available
in ROM can also run when flash instruction cache is disabled.
Some chips (e.g. ESP32-C6) has the full formatting versions of printf/scanf in ROM instead of
the nano versions and in this building with newlib nano might actually increase the size of
the binary. Which functions are present in ROM can be seen from ROM caps:
ESP_ROM_HAS_NEWLIB_NANO_FORMAT and ESP_ROM_HAS_NEWLIB_NORMAL_FORMAT.
If you need 64-bit integer formatting support or C99 features, keep this
option disabled.
choice NEWLIB_TIME_SYSCALL
prompt "Timers used for gettimeofday function"
default NEWLIB_TIME_SYSCALL_USE_RTC_HRT
help
This setting defines which hardware timers are used to
implement 'gettimeofday' and 'time' functions in C library.
- If both high-resolution (systimer for all targets except ESP32)
and RTC timers are used, timekeeping will continue in deep sleep.
Time will be reported at 1 microsecond resolution.
This is the default, and the recommended option.
- If only high-resolution timer (systimer) is used, gettimeofday will
provide time at microsecond resolution.
Time will not be preserved when going into deep sleep mode.
- If only RTC timer is used, timekeeping will continue in
deep sleep, but time will be measured at 6.(6) microsecond
resolution. Also the gettimeofday function itself may take
longer to run.
- If no timers are used, gettimeofday and time functions
return -1 and set errno to ENOSYS; they are defined as weak,
so they could be overridden.
If you want to customize gettimeofday() and other time functions,
please choose this option and refer to the 'time.c' source file
for the exact prototypes of these functions.
- When RTC is used for timekeeping, two RTC_STORE registers are
used to keep time in deep sleep mode.
config NEWLIB_TIME_SYSCALL_USE_RTC_HRT
bool "RTC and high-resolution timer"
select ESP_TIME_FUNCS_USE_RTC_TIMER
select ESP_TIME_FUNCS_USE_ESP_TIMER
config NEWLIB_TIME_SYSCALL_USE_RTC
bool "RTC"
select ESP_TIME_FUNCS_USE_RTC_TIMER
config NEWLIB_TIME_SYSCALL_USE_HRT
bool "High-resolution timer"
select ESP_TIME_FUNCS_USE_ESP_TIMER
config NEWLIB_TIME_SYSCALL_USE_NONE
bool "None"
select ESP_TIME_FUNCS_USE_NONE
endchoice
endmenu # Newlib
config STDATOMIC_S32C1I_SPIRAM_WORKAROUND
bool
default SPIRAM && (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S3) && !IDF_TOOLCHAIN_CLANG # TODO IDF-9032
+39
View File
@@ -0,0 +1,39 @@
/*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <string.h>
#include "esp_system.h"
#include "esp_cpu.h"
#include "soc/soc_caps.h"
void __attribute__((noreturn)) abort(void)
{
#define ERR_STR1 "abort() was called at PC 0x"
#define ERR_STR2 " on core "
_Static_assert(UINTPTR_MAX == 0xffffffff, "abort() assumes 32-bit addresses");
_Static_assert(SOC_CPU_CORES_NUM < 10, "abort() assumes number of cores is 1 to 9");
char addr_buf[9] = { 0 };
char core_buf[2] = { 0 };
char buf[sizeof(ERR_STR1) + sizeof(addr_buf) + sizeof(core_buf) + sizeof(ERR_STR2) + 1 /* null char */] = { 0 };
itoa((uint32_t)(__builtin_return_address(0) - 3), addr_buf, 16);
itoa(esp_cpu_get_core_id(), core_buf, 10);
const char *str[] = { ERR_STR1, addr_buf, ERR_STR2, core_buf };
char *dest = buf;
for (size_t i = 0; i < sizeof(str) / sizeof(str[0]); i++) {
strcat(dest, str[i]);
}
esp_system_abort(buf);
}
+92
View File
@@ -0,0 +1,92 @@
/*
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <sys/param.h>
#include "esp_system.h"
#include "soc/soc_memory_layout.h"
#include "esp_private/cache_utils.h"
#define ASSERT_STR "assert failed: "
#define CACHE_DISABLED_STR "<cached disabled>"
#if __XTENSA__
#define INST_LEN 3
#elif __riscv
#define INST_LEN 4
#endif
static inline void ra_to_str(char *addr)
{
addr[0] = '0';
addr[1] = 'x';
itoa((uint32_t)(__builtin_return_address(0) - INST_LEN), addr + 2, 16);
}
/* Overriding assert function so that whenever assert is called from critical section,
* it does not lead to a crash of its own.
*/
void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *expr)
{
#if CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT
char buff[sizeof(ASSERT_STR) + 11 + 1] = ASSERT_STR;
ra_to_str(&buff[sizeof(ASSERT_STR) - 1]);
esp_system_abort(buff);
#else
char addr[11] = { 0 };
char buff[200];
char lbuf[5];
uint32_t rem_len = sizeof(buff) - 1;
uint32_t off = 0;
itoa(line, lbuf, 10);
#if !CONFIG_APP_BUILD_TYPE_PURE_RAM_APP
if (!spi_flash_cache_enabled())
#endif
{
if (esp_ptr_in_drom(file)) {
file = CACHE_DISABLED_STR;
}
if (esp_ptr_in_drom(func)) {
ra_to_str(addr);
func = addr;
}
if (esp_ptr_in_drom(expr)) {
expr = CACHE_DISABLED_STR;
}
}
const char *str[] = {ASSERT_STR, func ? func : "\b", " ", file, ":", lbuf, " (", expr, ")"};
for (int i = 0; i < sizeof(str) / sizeof(str[0]); i++) {
uint32_t len = strlen(str[i]);
uint32_t cpy_len = MIN(len, rem_len);
memcpy(buff + off, str[i], cpy_len);
rem_len -= cpy_len;
off += cpy_len;
if (rem_len == 0) {
break;
}
}
buff[off] = '\0';
esp_system_abort(buff);
#endif /* CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT */
}
void __attribute__((noreturn)) __assert(const char *file, int line, const char *failedexpr)
{
__assert_func(file, line, NULL, failedexpr);
}
/* No-op function, used to force linker to include these changes */
void newlib_include_assert_impl(void)
{
}
+171
View File
@@ -0,0 +1,171 @@
# If the Newlib functions in ROM aren't used (eg because the external SPI RAM workaround is active), these functions will
# be linked into the application directly instead. Normally, they would end up in flash, which is undesirable because esp-idf
# and/or applications may assume that because these functions normally are in ROM, they are accessible even when flash is
# inaccessible. To work around this, this ld fragment places these functions in RAM instead. If the ROM functions are used,
# these defines do nothing, so they can still be included in that situation.
#
#
# Note: the only difference between esp32-spiram-rom-functions-c.lf
# and esp32-spiram-rom-functions-psram-workaround.lf is the archive name.
[mapping:libc]
archive:
if NEWLIB_NANO_FORMAT = y:
libc_nano.a
else:
libc.a
entries:
if SPIRAM_CACHE_WORKAROUND = y:
# The following libs are either used in a lot of places or in critical
# code. (such as panic or abort)
# Thus, they shall always be placed in IRAM.
libc_a-itoa (noflash)
libc_a-memcmp (noflash)
libc_a-memcpy (noflash)
libc_a-memset (noflash)
libc_a-strcat (noflash)
libc_a-strcmp (noflash)
libc_a-strlen (noflash)
if SPIRAM_CACHE_LIBJMP_IN_IRAM = y:
libc_a-longjmp (noflash)
libc_a-setjmp (noflash)
if SPIRAM_CACHE_LIBMATH_IN_IRAM = y:
libc_a-abs (noflash)
libc_a-div (noflash)
libc_a-labs (noflash)
libc_a-ldiv (noflash)
libc_a-quorem (noflash)
libc_a-s_fpclassify (noflash)
libc_a-sf_nan (noflash)
if SPIRAM_CACHE_LIBNUMPARSER_IN_IRAM = y:
libc_a-utoa (noflash)
libc_a-atoi (noflash)
libc_a-atol (noflash)
libc_a-strtol (noflash)
libc_a-strtoul (noflash)
if SPIRAM_CACHE_LIBIO_IN_IRAM = y:
libc_a-wcrtomb (noflash)
libc_a-fvwrite (noflash)
libc_a-wbuf (noflash)
libc_a-wsetup (noflash)
libc_a-fputwc (noflash)
libc_a-wctomb_r (noflash)
libc_a-ungetc (noflash)
libc_a-makebuf (noflash)
libc_a-fflush (noflash)
libc_a-refill (noflash)
libc_a-sccl (noflash)
if SPIRAM_CACHE_LIBTIME_IN_IRAM = y:
libc_a-asctime (noflash)
libc_a-asctime_r (noflash)
libc_a-ctime (noflash)
libc_a-ctime_r (noflash)
libc_a-lcltime (noflash)
libc_a-lcltime_r (noflash)
libc_a-gmtime (noflash)
libc_a-gmtime_r (noflash)
libc_a-strftime (noflash)
libc_a-mktime (noflash)
libc_a-tzset_r (noflash)
libc_a-tzset (noflash)
libc_a-time (noflash)
libc_a-gettzinfo (noflash)
libc_a-systimes (noflash)
libc_a-month_lengths (noflash)
libc_a-timelocal (noflash)
libc_a-tzvars (noflash)
libc_a-tzlock (noflash)
libc_a-tzcalc_limits (noflash)
libc_a-strptime (noflash)
if SPIRAM_CACHE_LIBCHAR_IN_IRAM = y:
libc_a-ctype_ (noflash)
libc_a-toupper (noflash)
libc_a-tolower (noflash)
libc_a-toascii (noflash)
libc_a-strupr (noflash)
libc_a-bzero (noflash)
libc_a-isalnum (noflash)
libc_a-isalpha (noflash)
libc_a-isascii (noflash)
libc_a-isblank (noflash)
libc_a-iscntrl (noflash)
libc_a-isdigit (noflash)
libc_a-isgraph (noflash)
libc_a-islower (noflash)
libc_a-isprint (noflash)
libc_a-ispunct (noflash)
libc_a-isspace (noflash)
libc_a-isupper (noflash)
if SPIRAM_CACHE_LIBMEM_IN_IRAM = y:
libc_a-memccpy (noflash)
libc_a-memchr (noflash)
libc_a-memmove (noflash)
libc_a-memrchr (noflash)
if SPIRAM_CACHE_LIBSTR_IN_IRAM = y:
libc_a-strcasecmp (noflash)
libc_a-strcasestr (noflash)
libc_a-strchr (noflash)
libc_a-strcoll (noflash)
libc_a-strcpy (noflash)
libc_a-strcspn (noflash)
libc_a-strdup (noflash)
libc_a-strdup_r (noflash)
libc_a-strlcat (noflash)
libc_a-strlcpy (noflash)
libc_a-strlwr (noflash)
libc_a-strncasecmp (noflash)
libc_a-strncat (noflash)
libc_a-strncmp (noflash)
libc_a-strncpy (noflash)
libc_a-strndup (noflash)
libc_a-strndup_r (noflash)
libc_a-strnlen (noflash)
libc_a-strrchr (noflash)
libc_a-strsep (noflash)
libc_a-strspn (noflash)
libc_a-strstr (noflash)
libc_a-strtok_r (noflash)
libc_a-strupr (noflash)
if SPIRAM_CACHE_LIBRAND_IN_IRAM = y:
libc_a-srand (noflash)
libc_a-rand (noflash)
libc_a-rand_r (noflash)
if SPIRAM_CACHE_LIBENV_IN_IRAM = y:
libc_a-environ (noflash)
libc_a-envlock (noflash)
libc_a-getenv_r (noflash)
if SPIRAM_CACHE_LIBFILE_IN_IRAM = y:
lock (noflash)
isatty (noflash)
creat (noflash)
libc_a-fclose (noflash)
libc_a-open (noflash)
libc_a-close (noflash)
libc_a-creat (noflash)
libc_a-read (noflash)
libc_a-rshift (noflash)
libc_a-sbrk (noflash)
libc_a-stdio (noflash)
libc_a-syssbrk (noflash)
libc_a-sysclose (noflash)
libc_a-sysopen (noflash)
libc_a-sysread (noflash)
libc_a-syswrite (noflash)
libc_a-impure (noflash)
libc_a-fwalk (noflash)
libc_a-findfp (noflash)
if SPIRAM_CACHE_LIBMISC_IN_IRAM = y:
libc_a-raise (noflash)
libc_a-system (noflash)
+32
View File
@@ -0,0 +1,32 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <sys/lock.h>
#include <sys/reent.h>
void flockfile(FILE *fp)
{
if (fp && !(fp->_flags & __SSTR)) {
__lock_acquire_recursive(fp->_lock);
}
}
int ftrylockfile(FILE *fp)
{
if (fp && !(fp->_flags & __SSTR)) {
return __lock_try_acquire_recursive(fp->_lock);
}
return 0;
}
void funlockfile(FILE *fp)
{
if (fp && !(fp->_flags & __SSTR)) {
__lock_release_recursive(fp->_lock);
}
}
+35
View File
@@ -0,0 +1,35 @@
/*
* SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <sys/random.h>
#include <errno.h>
int getentropy(void *buffer, size_t length)
{
ssize_t ret;
if (buffer == NULL) {
errno = EFAULT;
return -1;
}
if (length > 256) {
errno = EIO;
return -1;
}
ret = getrandom(buffer, length, 0);
if (ret == -1) {
return -1;
}
return 0;
}
void newlib_include_getentropy_impl(void)
{
// Linker hook, exists for no other purpose
}
+139
View File
@@ -0,0 +1,139 @@
/*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdlib.h>
#include <sys/reent.h>
#include <errno.h>
#include <malloc.h>
#include "esp_heap_caps.h"
/*
These contain the business logic for the malloc() and realloc() implementation. Because of heap tracing
wrapping reasons, we do not want these to be a public api, however, so they're not defined publicly.
*/
extern void *heap_caps_malloc_default(size_t size);
extern void *heap_caps_realloc_default(void *ptr, size_t size);
extern void *heap_caps_aligned_alloc_default(size_t alignment, size_t size);
void* malloc(size_t size)
{
return heap_caps_malloc_default(size);
}
void* calloc(size_t n, size_t size)
{
return _calloc_r(_REENT, n, size);
}
void* realloc(void* ptr, size_t size)
{
return heap_caps_realloc_default(ptr, size);
}
void free(void *ptr)
{
heap_caps_free(ptr);
}
void* _malloc_r(struct _reent *r, size_t size)
{
return heap_caps_malloc_default(size);
}
void _free_r(struct _reent *r, void* ptr)
{
heap_caps_free(ptr);
}
void* _realloc_r(struct _reent *r, void* ptr, size_t size)
{
return heap_caps_realloc_default(ptr, size);
}
void* _calloc_r(struct _reent *r, size_t nmemb, size_t size)
{
void *result;
size_t size_bytes;
if (__builtin_mul_overflow(nmemb, size, &size_bytes)) {
return NULL;
}
result = heap_caps_malloc_default(size_bytes);
if (result != NULL) {
bzero(result, size_bytes);
}
return result;
}
void* memalign(size_t alignment, size_t n)
{
return heap_caps_aligned_alloc_default(alignment, n);
}
void* aligned_alloc(size_t alignment, size_t n)
{
return heap_caps_aligned_alloc_default(alignment, n);
}
int posix_memalign(void **out_ptr, size_t alignment, size_t size)
{
if (size == 0) {
/* returning NULL for zero size is allowed, don't treat this as an error */
*out_ptr = NULL;
return 0;
}
void *result = heap_caps_aligned_alloc_default(alignment, size);
if (result != NULL) {
/* Modify output pointer only on success */
*out_ptr = result;
return 0;
}
/* Note: error returned, not set via errno! */
return ENOMEM;
}
/* No-op function, used to force linking this file,
instead of the heap implementation from newlib.
*/
void newlib_include_heap_impl(void)
{
}
/* The following functions are implemented by newlib's heap allocator,
but aren't available in the heap component.
Define them as non-functional stubs here, so that the application
can not cause the newlib heap implementation to be linked in
*/
int malloc_trim(size_t pad)
{
return 0; // indicates failure
}
size_t malloc_usable_size(void* p)
{
return 0;
}
void malloc_stats(void)
{
}
int mallopt(int parameter_number, int parameter_value)
{
return 0; // indicates failure
}
struct mallinfo mallinfo(void)
{
struct mallinfo dummy = {0};
return dummy;
}
void* valloc(size_t n) __attribute__((alias("malloc")));
void* pvalloc(size_t n) __attribute__((alias("malloc")));
void cfree(void* p) __attribute__((alias("free")));
+407
View File
@@ -0,0 +1,407 @@
/*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <sys/lock.h>
#include <stdlib.h>
#include <sys/reent.h>
#include "esp_attr.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "freertos/portable.h"
#include "esp_rom_caps.h"
/* Notes on our newlib lock implementation:
*
* - Use FreeRTOS mutex semaphores as locks.
* - lock_t is int, but we store an SemaphoreHandle_t there.
* - Locks are no-ops until the FreeRTOS scheduler is running.
* - Due to this, locks need to be lazily initialised the first time
* they are acquired. Initialisation/deinitialisation of locks is
* protected by lock_init_spinlock.
* - Race conditions around lazy initialisation (via lock_acquire) are
* protected against.
* - Anyone calling lock_close is reponsible for ensuring noone else
* is holding the lock at this time.
* - Race conditions between lock_close & lock_init (for the same lock)
* are the responsibility of the caller.
*/
static portMUX_TYPE lock_init_spinlock = portMUX_INITIALIZER_UNLOCKED;
/* Initialize the given lock by allocating a new mutex semaphore
as the _lock_t value.
Called by _lock_init*, also called by _lock_acquire* to lazily initialize locks that might have
been initialised (to zero only) before the RTOS scheduler started.
*/
static void IRAM_ATTR lock_init_generic(_lock_t *lock, uint8_t mutex_type)
{
portENTER_CRITICAL(&lock_init_spinlock);
if (*lock) {
/* Lock already initialised (either we didn't check earlier,
or it got initialised while we were waiting for the
spinlock.) */
} else {
/* Create a new semaphore
this is a bit of an API violation, as we're calling the
private function xQueueCreateMutex(x) directly instead of
the xSemaphoreCreateMutex / xSemaphoreCreateRecursiveMutex
wrapper functions...
The better alternative would be to pass pointers to one of
the two xSemaphoreCreate___Mutex functions, but as FreeRTOS
implements these as macros instead of inline functions
(*party like it's 1998!*) it's not possible to do this
without writing wrappers. Doing it this way seems much less
spaghetti-like.
*/
SemaphoreHandle_t new_sem = xQueueCreateMutex(mutex_type);
if (!new_sem) {
abort(); /* No more semaphores available or OOM */
}
*lock = (_lock_t)new_sem;
}
portEXIT_CRITICAL(&lock_init_spinlock);
}
void IRAM_ATTR _lock_init(_lock_t *lock)
{
*lock = 0; // In case lock's memory is uninitialized
lock_init_generic(lock, queueQUEUE_TYPE_MUTEX);
}
void IRAM_ATTR _lock_init_recursive(_lock_t *lock)
{
*lock = 0; // In case lock's memory is uninitialized
lock_init_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}
/* Free the mutex semaphore pointed to by *lock, and zero it out.
Note that FreeRTOS doesn't account for deleting mutexes while they
are held, and neither do we... so take care not to delete newlib
locks while they may be held by other tasks!
Also, deleting a lock in this way will cause it to be lazily
re-initialised if it is used again. Caller has to avoid doing
this!
*/
void IRAM_ATTR _lock_close(_lock_t *lock)
{
portENTER_CRITICAL(&lock_init_spinlock);
if (*lock) {
SemaphoreHandle_t h = (SemaphoreHandle_t)(*lock);
#if (INCLUDE_xSemaphoreGetMutexHolder == 1)
configASSERT(xSemaphoreGetMutexHolder(h) == NULL); /* mutex should not be held */
#endif
vSemaphoreDelete(h);
*lock = 0;
}
portEXIT_CRITICAL(&lock_init_spinlock);
}
void _lock_close_recursive(_lock_t *lock) __attribute__((alias("_lock_close")));
/* Acquire the mutex semaphore for lock. wait up to delay ticks.
mutex_type is queueQUEUE_TYPE_RECURSIVE_MUTEX or queueQUEUE_TYPE_MUTEX
*/
static int IRAM_ATTR lock_acquire_generic(_lock_t *lock, uint32_t delay, uint8_t mutex_type)
{
SemaphoreHandle_t h = (SemaphoreHandle_t)(*lock);
if (!h) {
if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
return 0; /* locking is a no-op before scheduler is up, so this "succeeds" */
}
/* lazy initialise lock - might have had a static initializer (that we don't use) */
lock_init_generic(lock, mutex_type);
h = (SemaphoreHandle_t)(*lock);
configASSERT(h != NULL);
}
if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
return 0; /* locking is a no-op before scheduler is up, so this "succeeds" */
}
BaseType_t success;
if (!xPortCanYield()) {
/* In ISR Context */
if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
abort(); /* recursive mutexes make no sense in ISR context */
}
BaseType_t higher_task_woken = false;
success = xSemaphoreTakeFromISR(h, &higher_task_woken);
if (!success && delay > 0) {
abort(); /* Tried to block on mutex from ISR, couldn't... rewrite your program to avoid libc interactions in ISRs! */
}
if (higher_task_woken) {
portYIELD_FROM_ISR();
}
} else {
/* In task context */
if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
success = xSemaphoreTakeRecursive(h, delay);
} else {
success = xSemaphoreTake(h, delay);
}
}
return (success == pdTRUE) ? 0 : -1;
}
void IRAM_ATTR _lock_acquire(_lock_t *lock)
{
lock_acquire_generic(lock, portMAX_DELAY, queueQUEUE_TYPE_MUTEX);
}
void IRAM_ATTR _lock_acquire_recursive(_lock_t *lock)
{
lock_acquire_generic(lock, portMAX_DELAY, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}
int IRAM_ATTR _lock_try_acquire(_lock_t *lock)
{
return lock_acquire_generic(lock, 0, queueQUEUE_TYPE_MUTEX);
}
int IRAM_ATTR _lock_try_acquire_recursive(_lock_t *lock)
{
return lock_acquire_generic(lock, 0, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}
/* Release the mutex semaphore for lock.
mutex_type is queueQUEUE_TYPE_RECURSIVE_MUTEX or queueQUEUE_TYPE_MUTEX
*/
static void IRAM_ATTR lock_release_generic(_lock_t *lock, uint8_t mutex_type)
{
if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
return; /* locking is a no-op before scheduler is up */
}
SemaphoreHandle_t h = (SemaphoreHandle_t)(*lock);
assert(h);
if (!xPortCanYield()) {
if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
abort(); /* indicates logic bug, it shouldn't be possible to lock recursively in ISR */
}
BaseType_t higher_task_woken = false;
xSemaphoreGiveFromISR(h, &higher_task_woken);
if (higher_task_woken) {
portYIELD_FROM_ISR();
}
} else {
if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
xSemaphoreGiveRecursive(h);
} else {
xSemaphoreGive(h);
}
}
}
void IRAM_ATTR _lock_release(_lock_t *lock)
{
lock_release_generic(lock, queueQUEUE_TYPE_MUTEX);
}
void IRAM_ATTR _lock_release_recursive(_lock_t *lock)
{
lock_release_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}
/* To ease the transition to newlib 3.3.0, this part is kept under an ifdef.
* After the toolchain with newlib 3.3.0 is released and merged, the ifdefs
* can be removed.
*
* Also the retargetable locking functions still rely on the previous
* implementation. Once support for !_RETARGETABLE_LOCKING is removed,
* the code can be simplified, removing support for lazy initialization of
* locks. At the same time, IDF code which relies on _lock_acquire/_lock_release
* will have to be updated to not depend on lazy initialization.
*
* Explanation of the different lock types:
*
* Newlib 2.2.0 and 3.0.0:
* _lock_t is defined as int, stores SemaphoreHandle_t.
*
* Newlib 3.3.0:
* struct __lock is (or contains) StaticSemaphore_t
* _LOCK_T is a pointer to struct __lock, equivalent to SemaphoreHandle_t.
* It has the same meaning as _lock_t in the previous implementation.
*
*/
/* This ensures the platform-specific definition in lock.h is correct.
* We use "greater or equal" since the size of StaticSemaphore_t may
* vary by 2 words, depending on whether configUSE_TRACE_FACILITY is enabled.
*/
_Static_assert(sizeof(struct __lock) >= sizeof(StaticSemaphore_t),
"Incorrect size of struct __lock");
/* FreeRTOS configuration check */
_Static_assert(configSUPPORT_STATIC_ALLOCATION,
"FreeRTOS should be configured with static allocation support");
/* These 2 locks are used instead of 9 distinct newlib static locks,
* as most of the locks are required for lesser-used features, so
* the chance of performance degradation due to lock contention is low.
*/
static StaticSemaphore_t s_common_mutex;
static StaticSemaphore_t s_common_recursive_mutex;
#if ESP_ROM_HAS_RETARGETABLE_LOCKING
/* C3 and S3 ROMs are built without Newlib static lock symbols exported, and
* with an extra level of _LOCK_T indirection in mind.
* The following is a workaround for this:
* - on startup, we call esp_rom_newlib_init_common_mutexes to set
* the two mutex pointers to magic values.
* - if in __retarget_lock_acquire*, we check if the argument dereferences
* to the magic value. If yes, we lock the correct mutex defined in the app,
* instead.
* Casts from &StaticSemaphore_t to _LOCK_T are okay because _LOCK_T
* (which is SemaphoreHandle_t) is a pointer to the corresponding
* StaticSemaphore_t structure. This is ensured by asserts below.
*/
#define ROM_NEEDS_MUTEX_OVERRIDE
#endif // ESP_ROM_HAS_RETARGETABLE_LOCKING
#ifdef ROM_NEEDS_MUTEX_OVERRIDE
#define ROM_MUTEX_MAGIC 0xbb10c433
/* This is a macro, since we are overwriting the argument */
#define MAYBE_OVERRIDE_LOCK(_lock, _lock_to_use_instead) \
if (*(int*)_lock == ROM_MUTEX_MAGIC) { \
(_lock) = (_LOCK_T) (_lock_to_use_instead); \
}
#else // ROM_NEEDS_MUTEX_OVERRIDE
#define MAYBE_OVERRIDE_LOCK(_lock, _lock_to_use_instead)
#endif // ROM_NEEDS_MUTEX_OVERRIDE
void IRAM_ATTR __retarget_lock_init(_LOCK_T *lock)
{
*lock = NULL; /* In case lock's memory is uninitialized */
lock_init_generic(lock, queueQUEUE_TYPE_MUTEX);
}
void IRAM_ATTR __retarget_lock_init_recursive(_LOCK_T *lock)
{
*lock = NULL; /* In case lock's memory is uninitialized */
lock_init_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
}
void IRAM_ATTR __retarget_lock_close(_LOCK_T lock)
{
_lock_close(&lock);
}
void IRAM_ATTR __retarget_lock_close_recursive(_LOCK_T lock)
{
_lock_close_recursive(&lock);
}
/* Separate function, to prevent generating multiple assert strings */
static void IRAM_ATTR check_lock_nonzero(_LOCK_T lock)
{
assert(lock != NULL && "Uninitialized lock used");
}
void IRAM_ATTR __retarget_lock_acquire(_LOCK_T lock)
{
check_lock_nonzero(lock);
MAYBE_OVERRIDE_LOCK(lock, &s_common_mutex);
_lock_acquire(&lock);
}
void IRAM_ATTR __retarget_lock_acquire_recursive(_LOCK_T lock)
{
check_lock_nonzero(lock);
MAYBE_OVERRIDE_LOCK(lock, &s_common_recursive_mutex);
_lock_acquire_recursive(&lock);
}
int IRAM_ATTR __retarget_lock_try_acquire(_LOCK_T lock)
{
check_lock_nonzero(lock);
MAYBE_OVERRIDE_LOCK(lock, &s_common_mutex);
return _lock_try_acquire(&lock);
}
int IRAM_ATTR __retarget_lock_try_acquire_recursive(_LOCK_T lock)
{
check_lock_nonzero(lock);
MAYBE_OVERRIDE_LOCK(lock, &s_common_recursive_mutex);
return _lock_try_acquire_recursive(&lock);
}
void IRAM_ATTR __retarget_lock_release(_LOCK_T lock)
{
check_lock_nonzero(lock);
_lock_release(&lock);
}
void IRAM_ATTR __retarget_lock_release_recursive(_LOCK_T lock)
{
check_lock_nonzero(lock);
_lock_release_recursive(&lock);
}
/* When _RETARGETABLE_LOCKING is enabled, newlib expects the following locks to be provided: */
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___sinit_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___malloc_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___env_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___sfp_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_recursive_mutex"))) __lock___atexit_recursive_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___at_quick_exit_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___tz_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___dd_hash_mutex;
extern StaticSemaphore_t __attribute__((alias("s_common_mutex"))) __lock___arc4random_mutex;
void esp_newlib_locks_init(void)
{
/* Initialize the two mutexes used for the locks above.
* Asserts below check our assumption that SemaphoreHandle_t will always
* point to the corresponding StaticSemaphore_t structure.
*/
SemaphoreHandle_t handle;
handle = xSemaphoreCreateMutexStatic(&s_common_mutex);
assert(handle == (SemaphoreHandle_t) &s_common_mutex);
handle = xSemaphoreCreateRecursiveMutexStatic(&s_common_recursive_mutex);
assert(handle == (SemaphoreHandle_t) &s_common_recursive_mutex);
(void) handle;
/* Chip ROMs are built with older versions of newlib, and rely on different lock variables.
* Initialize these locks to the same values.
*/
#ifdef CONFIG_IDF_TARGET_ESP32
/* Newlib 2.2.0 is used in ROM, the following lock symbols are defined: */
extern _lock_t __sfp_lock;
__sfp_lock = (_lock_t) &s_common_recursive_mutex;
extern _lock_t __sinit_lock;
__sinit_lock = (_lock_t) &s_common_recursive_mutex;
extern _lock_t __env_lock_object;
__env_lock_object = (_lock_t) &s_common_recursive_mutex;
extern _lock_t __tz_lock_object;
__tz_lock_object = (_lock_t) &s_common_mutex;
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
/* Newlib 3.0.0 is used in ROM, the following lock symbols are defined: */
extern _lock_t __sinit_recursive_mutex;
__sinit_recursive_mutex = (_lock_t) &s_common_recursive_mutex;
extern _lock_t __sfp_recursive_mutex;
__sfp_recursive_mutex = (_lock_t) &s_common_recursive_mutex;
#elif ESP_ROM_HAS_RETARGETABLE_LOCKING
/* Newlib 3.3.0 is used in ROM, built with _RETARGETABLE_LOCKING.
* No access to lock variables for the purpose of ECO forward compatibility,
* however we have an API to initialize lock variables used in the ROM.
*/
extern void esp_rom_newlib_init_common_mutexes(_LOCK_T, _LOCK_T);
/* See notes about ROM_NEEDS_MUTEX_OVERRIDE above */
int magic_val = ROM_MUTEX_MAGIC;
_LOCK_T magic_mutex = (_LOCK_T) &magic_val;
esp_rom_newlib_init_common_mutexes(magic_mutex, magic_mutex);
#else // other target
#error Unsupported target
#endif
}
+9
View File
@@ -0,0 +1,9 @@
[mapping:newlib]
archive: libnewlib.a
entries:
heap (noflash)
abort (noflash)
assert (noflash)
stdatomic (noflash)
if STDATOMIC_S32C1I_SPIRAM_WORKAROUND = y:
stdatomic_s32c1i (noflash)
+214
View File
@@ -0,0 +1,214 @@
/*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "sdkconfig.h"
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <sys/unistd.h>
#include <sys/reent.h>
#include <assert.h>
#include "esp_newlib.h"
#include "esp_attr.h"
#include "soc/soc_caps.h"
#include "esp_rom_caps.h"
#include "esp_rom_libc_stubs.h"
#include "esp_private/startup_internal.h"
extern int _printf_float(struct _reent *rptr,
void *pdata,
FILE * fp,
int (*pfunc)(struct _reent *, FILE *, const char *, size_t len),
va_list * ap);
extern int _scanf_float(struct _reent *rptr,
void *pdata,
FILE *fp,
va_list *ap);
static void raise_r_stub(struct _reent *rptr)
{
_raise_r(rptr, 0);
}
static void esp_cleanup_r(struct _reent *rptr)
{
if (_REENT_STDIN(rptr) != _REENT_STDIN(_GLOBAL_REENT)) {
_fclose_r(rptr, _REENT_STDIN(rptr));
}
if (_REENT_STDOUT(rptr) != _REENT_STDOUT(_GLOBAL_REENT)) {
_fclose_r(rptr, _REENT_STDOUT(rptr));
}
if (_REENT_STDERR(rptr) != _REENT_STDERR(_GLOBAL_REENT)) {
_fclose_r(rptr, _REENT_STDERR(rptr));
}
}
static struct syscall_stub_table s_stub_table = {
.__getreent = &__getreent,
._malloc_r = &_malloc_r,
._free_r = &_free_r,
._realloc_r = &_realloc_r,
._calloc_r = &_calloc_r,
._abort = &abort,
._system_r = &_system_r,
._rename_r = &_rename_r,
._times_r = &_times_r,
._gettimeofday_r = &_gettimeofday_r,
._raise_r = &raise_r_stub,
._unlink_r = &_unlink_r,
._link_r = &_link_r,
._stat_r = &_stat_r,
._fstat_r = &_fstat_r,
._sbrk_r = &_sbrk_r,
._getpid_r = &_getpid_r,
._kill_r = &_kill_r,
._exit_r = NULL, // never called in ROM
._close_r = &_close_r,
._open_r = &_open_r,
._write_r = (int (*)(struct _reent * r, int, const void *, int)) &_write_r,
._lseek_r = (int (*)(struct _reent * r, int, int, int)) &_lseek_r,
._read_r = (int (*)(struct _reent * r, int, void *, int)) &_read_r,
#if ESP_ROM_HAS_RETARGETABLE_LOCKING
._retarget_lock_init = &__retarget_lock_init,
._retarget_lock_init_recursive = &__retarget_lock_init_recursive,
._retarget_lock_close = &__retarget_lock_close,
._retarget_lock_close_recursive = &__retarget_lock_close_recursive,
._retarget_lock_acquire = &__retarget_lock_acquire,
._retarget_lock_acquire_recursive = &__retarget_lock_acquire_recursive,
._retarget_lock_try_acquire = &__retarget_lock_try_acquire,
._retarget_lock_try_acquire_recursive = &__retarget_lock_try_acquire_recursive,
._retarget_lock_release = &__retarget_lock_release,
._retarget_lock_release_recursive = &__retarget_lock_release_recursive,
#else
._lock_init = &_lock_init,
._lock_init_recursive = &_lock_init_recursive,
._lock_close = &_lock_close,
._lock_close_recursive = &_lock_close_recursive,
._lock_acquire = &_lock_acquire,
._lock_acquire_recursive = &_lock_acquire_recursive,
._lock_try_acquire = &_lock_try_acquire,
._lock_try_acquire_recursive = &_lock_try_acquire_recursive,
._lock_release = &_lock_release,
._lock_release_recursive = &_lock_release_recursive,
#endif
#ifdef CONFIG_NEWLIB_NANO_FORMAT
._printf_float = &_printf_float,
._scanf_float = &_scanf_float,
#else
._printf_float = NULL,
._scanf_float = NULL,
#endif
#if !CONFIG_IDF_TARGET_ESP32 && !CONFIG_IDF_TARGET_ESP32S2
/* TODO IDF-2570 : mark that this assert failed in ROM, to avoid confusion between IDF & ROM
assertion failures (as function names & source file names will be similar)
*/
.__assert_func = __assert_func,
/* We don't expect either ROM code to ever call __sinit, so it's implemented as abort() for now.
__sinit may be called in IDF side only if /dev/console used as input/output. It called only
once for _GLOBAL_REENT. Then reuse std file pointers from _GLOBAL_REENT in another reents.
See esp_newlib_init() and esp_reent_init() for details.
*/
.__sinit = (void *)abort,
._cleanup_r = &esp_cleanup_r,
#endif
};
void esp_newlib_init(void)
{
#if CONFIG_IDF_TARGET_ESP32
syscall_table_ptr_pro = syscall_table_ptr_app = &s_stub_table;
#elif CONFIG_IDF_TARGET_ESP32S2
syscall_table_ptr_pro = &s_stub_table;
#else
syscall_table_ptr = &s_stub_table;
#endif
memset(&__sglue, 0, sizeof(__sglue));
_global_impure_ptr = _GLOBAL_REENT;
/* Ensure that the initialization of sfp is prevented until esp_newlib_init_global_stdio() is explicitly invoked. */
_GLOBAL_REENT->__cleanup = esp_cleanup_r;
_REENT_SDIDINIT(_GLOBAL_REENT) = 1;
environ = malloc(sizeof(char*));
if (environ == 0) {
// if allocation fails this early in startup process, there's nothing else other than to panic.
abort();
}
environ[0] = NULL;
esp_newlib_locks_init();
}
ESP_SYSTEM_INIT_FN(init_newlib, CORE, BIT(0), 102)
{
esp_newlib_init();
return ESP_OK;
}
void esp_setup_newlib_syscalls(void) __attribute__((alias("esp_newlib_init")));
/**
* Postponed _GLOBAL_REENT stdio FPs initialization.
*
* Can not be a part of esp_reent_init() because stdio device may not initialized yet.
*
* Called from startup code and FreeRTOS, not intended to be called from
* application code.
*/
void esp_newlib_init_global_stdio(const char *stdio_dev)
{
if (stdio_dev == NULL) {
_GLOBAL_REENT->__cleanup = NULL;
_REENT_SDIDINIT(_GLOBAL_REENT) = 0;
__sinit(_GLOBAL_REENT);
_GLOBAL_REENT->__cleanup = esp_cleanup_r;
_REENT_SDIDINIT(_GLOBAL_REENT) = 1;
} else {
_REENT_STDIN(_GLOBAL_REENT) = fopen(stdio_dev, "r");
_REENT_STDOUT(_GLOBAL_REENT) = fopen(stdio_dev, "w");
_REENT_STDERR(_GLOBAL_REENT) = fopen(stdio_dev, "w");
#if ESP_ROM_NEEDS_SWSETUP_WORKAROUND
/*
- This workaround for printf functions using 32-bit time_t after the 64-bit time_t upgrade
- The 32-bit time_t usage is triggered through ROM Newlib functions printf related functions calling __swsetup_r() on
the first call to a particular file pointer (i.e., stdin, stdout, stderr)
- Thus, we call the toolchain version of __swsetup_r() now (before any printf calls are made) to setup all of the
file pointers. Thus, the ROM newlib code will never call the ROM version of __swsetup_r().
- See IDFGH-7728 for more details
*/
extern int __swsetup_r(struct _reent *, FILE *);
__swsetup_r(_GLOBAL_REENT, _REENT_STDIN(_GLOBAL_REENT));
__swsetup_r(_GLOBAL_REENT, _REENT_STDOUT(_GLOBAL_REENT));
__swsetup_r(_GLOBAL_REENT, _REENT_STDERR(_GLOBAL_REENT));
#endif /* ESP_ROM_NEEDS_SWSETUP_WORKAROUND */
}
}
ESP_SYSTEM_INIT_FN(init_newlib_stdio, CORE, BIT(0), 115)
{
#if defined(CONFIG_VFS_SUPPORT_IO)
esp_newlib_init_global_stdio("/dev/console");
#else
esp_newlib_init_global_stdio(NULL);
#endif
return ESP_OK;
}
// Hook to force the linker to include this file
void newlib_include_init_funcs(void)
{
}
+43
View File
@@ -0,0 +1,43 @@
/*
* SPDX-FileCopyrightText: 2017-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
/* This header file wraps newlib's own unmodified assert.h and adds
support for silent assertion failure.
*/
#pragma once
#include <sdkconfig.h>
#include <stdlib.h>
#include <stdint.h>
#include_next <assert.h>
/* moved part of libc provided assert to here allows
* tweaking the assert macro to use __builtin_expect()
* and reduce jumps in the "asserts OK" code path
*
* Note: using __builtin_expect() not likely() to avoid defining the likely
* macro in namespace of non-IDF code that may include this standard header.
*/
#undef assert
/* __FILENAME__ points to the file name instead of path + filename
* e.g __FILE__ points to "/apps/test.c" where as __FILENAME__ points to "test.c"
*/
#define __FILENAME__ (__builtin_strrchr( "/" __FILE__, '/') + 1)
#if defined(NDEBUG)
#define assert(__e) ((void)(__e))
#elif CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT
#define assert(__e) (__builtin_expect(!!(__e), 1) ? (void)0 : __assert_func(NULL, 0, NULL, NULL))
#else // !CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT
#define assert(__e) (__builtin_expect(!!(__e), 1) ? (void)0 : __assert_func (__FILENAME__, __LINE__, \
__ASSERT_FUNC, #__e))
#endif
+208
View File
@@ -0,0 +1,208 @@
/*
* All the code below is a rework of
* https://github.com/freebsd/freebsd/blob/master/sys/sys/endian.h
* to import symbols defining non-standard endian handling functions.
* The aforementioned source code license terms are included here.
* For further license info, please look at https://github.com/freebsd/freebsd
*/
/*-
* SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2020 Francesco Giancane <francesco.giancane@accenture.com>
* SPDX-FileCopyrightText: 2002 Thomas Moestl <tmm@FreeBSD.org>
* SPDX-License-Identifier: BSD-2-Clause-FreeBSD AND Apache-2.0
*
* Copyright (c) 2002 Thomas Moestl <tmm@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR OR CONTRIBUTORS 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.
*
* $FreeBSD$
*/
#pragma once
#include <stdint.h>
/*
* This is a compatibility header for <endian.h>.
* In xtensa-newlib distribution it is located in <machine/endian.h>
* but most program expect to be plain <endian.h>.
*/
#include <machine/endian.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* General byte order swapping functions.
*/
#define bswap16(x) __bswap16(x)
#define bswap32(x) __bswap32(x)
#define bswap64(x) __bswap64(x)
/*
* Host to big endian, host to little endian, big endian to host, and little
* endian to host byte order functions as detailed in byteorder(9).
*/
#if _BYTE_ORDER == _LITTLE_ENDIAN
#define htobe16(x) bswap16((x))
#define htobe32(x) bswap32((x))
#define htobe64(x) bswap64((x))
#define htole16(x) ((uint16_t)(x))
#define htole32(x) ((uint32_t)(x))
#define htole64(x) ((uint64_t)(x))
#define be16toh(x) bswap16((x))
#define be32toh(x) bswap32((x))
#define be64toh(x) bswap64((x))
#define le16toh(x) ((uint16_t)(x))
#define le32toh(x) ((uint32_t)(x))
#define le64toh(x) ((uint64_t)(x))
#else /* _BYTE_ORDER != _LITTLE_ENDIAN */
#define htobe16(x) ((uint16_t)(x))
#define htobe32(x) ((uint32_t)(x))
#define htobe64(x) ((uint64_t)(x))
#define htole16(x) bswap16((x))
#define htole32(x) bswap32((x))
#define htole64(x) bswap64((x))
#define be16toh(x) ((uint16_t)(x))
#define be32toh(x) ((uint32_t)(x))
#define be64toh(x) ((uint64_t)(x))
#define le16toh(x) bswap16((x))
#define le32toh(x) bswap32((x))
#define le64toh(x) bswap64((x))
#endif /* _BYTE_ORDER == _LITTLE_ENDIAN */
/* Alignment-agnostic encode/decode bytestream to/from little/big endian. */
static __inline uint16_t
be16dec(const void *pp)
{
uint8_t const *p = (uint8_t const *)pp;
return ((p[0] << 8) | p[1]);
}
static __inline uint32_t
be32dec(const void *pp)
{
uint8_t const *p = (uint8_t const *)pp;
return (((unsigned)p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
}
static __inline uint64_t
be64dec(const void *pp)
{
uint8_t const *p = (uint8_t const *)pp;
return (((uint64_t)be32dec(p) << 32) | be32dec(p + 4));
}
static __inline uint16_t
le16dec(const void *pp)
{
uint8_t const *p = (uint8_t const *)pp;
return ((p[1] << 8) | p[0]);
}
static __inline uint32_t
le32dec(const void *pp)
{
uint8_t const *p = (uint8_t const *)pp;
return (((unsigned)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
}
static __inline uint64_t
le64dec(const void *pp)
{
uint8_t const *p = (uint8_t const *)pp;
return (((uint64_t)le32dec(p + 4) << 32) | le32dec(p));
}
static __inline void
be16enc(void *pp, uint16_t u)
{
uint8_t *p = (uint8_t *)pp;
p[0] = (u >> 8) & 0xff;
p[1] = u & 0xff;
}
static __inline void
be32enc(void *pp, uint32_t u)
{
uint8_t *p = (uint8_t *)pp;
p[0] = (u >> 24) & 0xff;
p[1] = (u >> 16) & 0xff;
p[2] = (u >> 8) & 0xff;
p[3] = u & 0xff;
}
static __inline void
be64enc(void *pp, uint64_t u)
{
uint8_t *p = (uint8_t *)pp;
be32enc(p, (uint32_t)(u >> 32));
be32enc(p + 4, (uint32_t)(u & 0xffffffffU));
}
static __inline void
le16enc(void *pp, uint16_t u)
{
uint8_t *p = (uint8_t *)pp;
p[0] = u & 0xff;
p[1] = (u >> 8) & 0xff;
}
static __inline void
le32enc(void *pp, uint32_t u)
{
uint8_t *p = (uint8_t *)pp;
p[0] = u & 0xff;
p[1] = (u >> 8) & 0xff;
p[2] = (u >> 16) & 0xff;
p[3] = (u >> 24) & 0xff;
}
static __inline void
le64enc(void *pp, uint64_t u)
{
uint8_t *p = (uint8_t *)pp;
le32enc(p, (uint32_t)(u & 0xffffffffU));
le32enc(p + 4, (uint32_t)(u >> 32));
}
#ifdef __cplusplus
}
#endif
+31
View File
@@ -0,0 +1,31 @@
/*
* SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _ESP_PLATFORM_ERRNO_H_
#define _ESP_PLATFORM_ERRNO_H_
#include_next "errno.h"
//
// Possibly define some missing errors
//
#ifndef ESHUTDOWN
#define ESHUTDOWN 110 /* Cannot send after transport endpoint shutdown */
#endif
#ifndef EAI_SOCKTYPE
#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
#endif
#ifndef EAI_AGAIN
#define EAI_AGAIN 2 /* temporary failure in name resolution */
#endif
#ifndef EAI_BADFLAGS
#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
#endif
#endif // _ESP_PLATFORM_ERRNO_H_
+76
View File
@@ -0,0 +1,76 @@
/*
* SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <sys/reent.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Initialize newlib time functions
*/
void esp_newlib_time_init(void);
/**
* Replacement for newlib's _REENT_INIT_PTR and __sinit.
*
* Called from startup code and FreeRTOS, not intended to be called from
* application code.
*/
void esp_reent_init(struct _reent* r);
/**
* Postponed _GLOBAL_REENT stdio FPs initialization.
*
* Can not be a part of esp_reent_init() because stdio device may not initialized yet.
*
* Called from startup code and FreeRTOS, not intended to be called from
* application code.
*
*/
void esp_newlib_init_global_stdio(const char* stdio_dev);
/**
* Clean up some of lazily allocated buffers in REENT structures.
*/
void esp_reent_cleanup(void);
/**
* Function which sets up newlib in ROM for use with ESP-IDF
*
* Includes defining the syscall table, setting up any common locks, etc.
*
* Called from the startup code, not intended to be called from application
* code.
*/
void esp_newlib_init(void);
void esp_setup_syscall_table(void) __attribute__((deprecated("Please call esp_newlib_init() in newer code")));
/**
* Update current microsecond time from RTC
*/
void esp_set_time_from_rtc(void);
/*
* Sync timekeeping timers, RTC and high-resolution timer. Update boot_time.
*/
void esp_sync_timekeeping_timers(void);
/* Kept for backward compatibility */
#define esp_sync_counters_rtc_and_frc esp_sync_timekeeping_timers
/**
* Initialize newlib static locks
*/
void esp_newlib_locks_init(void);
#ifdef __cplusplus
}
#endif
+39
View File
@@ -0,0 +1,39 @@
/*
* SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _ESP_PLATFORM_NET_IF_H_
#define _ESP_PLATFORM_NET_IF_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "lwip/sockets.h"
#include "lwip/if_api.h"
#define MSG_DONTROUTE 0x4 /* send without using routing tables */
#define SOCK_SEQPACKET 5 /* sequenced packet stream */
#define MSG_EOR 0x8 /* data completes record */
#define SOCK_SEQPACKET 5 /* sequenced packet stream */
#define SOMAXCONN 128
#define IPV6_UNICAST_HOPS 4 /* int; IP6 hops */
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
#define NI_NUMERICSERV 0x00000008
#define NI_DGRAM 0x00000010
typedef u32_t socklen_t;
unsigned int if_nametoindex(const char *ifname);
char *if_indextoname(unsigned int ifindex, char *ifname);
#ifdef __cplusplus
}
#endif
#endif // _ESP_PLATFORM_NET_IF_H_
+27
View File
@@ -0,0 +1,27 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __ESP_PLATFORM_PTHREAD_H__
#define __ESP_PLATFORM_PTHREAD_H__
#include <sys/types.h>
#include <sys/time.h>
#include <sys/features.h>
#include_next <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
int pthread_condattr_getclock(const pthread_condattr_t * attr, clockid_t * clock_id);
int pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clock_id);
#ifdef __cplusplus
}
#endif
#endif // __ESP_PLATFORM_PTHREAD_H__
+73
View File
@@ -0,0 +1,73 @@
/*
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned int sem_t;
/**
* This is the maximum value to which any POSIX semaphore can count on ESP chips.
*/
#define SEM_VALUE_MAX 0x7FFF
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*
* Must NOT be called if threads are still blocked on semaphore!
*/
int sem_destroy(sem_t *sem);
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*
* Note that on ESP chips, pshared is ignored. Semaphores can always be shared between FreeRTOS tasks.
*/
int sem_init(sem_t *sem, int pshared, unsigned value);
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*
* Note that, unlike specified in POSIX, this implementation returns -1 and sets errno to
* EAGAIN if the semaphore can not be unlocked (posted) due to its value being SEM_VALUE_MAX.
*/
int sem_post(sem_t *sem);
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*
* Note the following three deviations/issues originating from the underlying FreeRTOS implementation:
* * The time value passed by abstime will be rounded up to the next FreeRTOS tick.
* * The actual timeout will happen after the tick the time was rounded to
* and before the following tick.
* * It is possible, though unlikely, that the task is preempted directly after the timeout calculation,
* delaying timeout of the following blocking operating system call by the duration of the preemption.
*/
int sem_timedwait(sem_t *semaphore, const struct timespec *abstime);
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*/
int sem_trywait(sem_t *sem);
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*/
int sem_wait(sem_t *sem);
/**
* This is a POSIX function, please refer to the POSIX specification for a detailed description.
*/
int sem_getvalue(sem_t *sem, int *sval);
#ifdef __cplusplus
}
#endif
+70
View File
@@ -0,0 +1,70 @@
/*
* SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifdef __clang__ // TODO LLVM-330
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
/**
* This header file provides POSIX-compatible definitions of directory
* access data types. Starting with newlib 3.3, related functions are defined
* in 'dirent.h' bundled with newlib.
* See http://pubs.opengroup.org/onlinepubs/7908799/xsh/dirent.h.html
* for reference.
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque directory structure
*/
typedef struct {
uint16_t dd_vfs_idx; /*!< VFS index, not to be used by applications */
uint16_t dd_rsv; /*!< field reserved for future extension */
/* remaining fields are defined by VFS implementation */
} DIR;
/**
* @brief Directory entry structure
*/
struct dirent {
ino_t d_ino; /*!< file number */
uint8_t d_type; /*!< not defined in POSIX, but present in BSD and Linux */
#define DT_UNKNOWN 0
#define DT_REG 1
#define DT_DIR 2
#if __BSD_VISIBLE
#define MAXNAMLEN 255
char d_name[MAXNAMLEN + 1]; /*!< zero-terminated file name */
#else
char d_name[256];
#endif
};
DIR* opendir(const char* name);
struct dirent* readdir(DIR* pdir);
long telldir(DIR* pdir);
void seekdir(DIR* pdir, long loc);
void rewinddir(DIR* pdir);
int closedir(DIR* pdir);
int readdir_r(DIR* pdir, struct dirent* entry, struct dirent** out_dirent);
int scandir(const char *dirname, struct dirent ***out_dirlist,
int (*select_func)(const struct dirent *),
int (*cmp_func)(const struct dirent **, const struct dirent **));
int alphasort(const struct dirent **d1, const struct dirent **d2);
#ifdef __cplusplus
}
#endif
#else // __clang__ TODO: IDF-10675
#include_next <sys/dirent.h>
#include <dirent.h>
#endif // __clang__
+17
View File
@@ -0,0 +1,17 @@
/*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
int ioctl(int fd, int request, ...);
#ifdef __cplusplus
}
#endif
+51
View File
@@ -0,0 +1,51 @@
/*
* SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include_next <sys/lock.h>
#include "sdkconfig.h"
#ifdef _RETARGETABLE_LOCKING
/* Actual platfrom-specific definition of struct __lock.
* The size here should be sufficient for a FreeRTOS mutex.
* This is checked by a static assertion in locks.c
*
* Note: this might need to be made dependent on whether FreeRTOS
* is included in the build.
*/
struct __lock {
#if (CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES && CONFIG_FREERTOS_USE_TRACE_FACILITY)
int reserved[29];
#elif (CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES && !CONFIG_FREERTOS_USE_TRACE_FACILITY)
int reserved[27];
#elif (!CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES && CONFIG_FREERTOS_USE_TRACE_FACILITY)
int reserved[23];
#else
int reserved[21];
#endif /* #if (CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES && CONFIG_FREERTOS_USE_TRACE_FACILITY) */
};
/* Compatibility definitions for the legacy ESP-specific locking implementation.
* These used to be provided by libc/sys/xtensa/sys/lock.h in newlib.
* Newer versions of newlib don't have this ESP-specific lock.h header, and are
* built with _RETARGETABLE_LOCKING enabled, instead.
*/
typedef _LOCK_T _lock_t;
void _lock_init(_lock_t *plock);
void _lock_init_recursive(_lock_t *plock);
void _lock_close(_lock_t *plock);
void _lock_close_recursive(_lock_t *plock);
void _lock_acquire(_lock_t *plock);
void _lock_acquire_recursive(_lock_t *plock);
int _lock_try_acquire(_lock_t *plock);
int _lock_try_acquire_recursive(_lock_t *plock);
void _lock_release(_lock_t *plock);
void _lock_release_recursive(_lock_t *plock);
#endif // _RETARGETABLE_LOCKING
+40
View File
@@ -0,0 +1,40 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _ESP_PLATFORM_SYS_POLL_H_
#define _ESP_PLATFORM_SYS_POLL_H_
#define POLLIN (1u << 0) /* data other than high-priority may be read without blocking */
#define POLLRDNORM (1u << 1) /* normal data may be read without blocking */
#define POLLRDBAND (1u << 2) /* priority data may be read without blocking */
#define POLLPRI (POLLRDBAND) /* high-priority data may be read without blocking */
// Note: POLLPRI is made equivalent to POLLRDBAND in order to fit all these events into one byte
#define POLLOUT (1u << 3) /* normal data may be written without blocking */
#define POLLWRNORM (POLLOUT) /* equivalent to POLLOUT */
#define POLLWRBAND (1u << 4) /* priority data my be written */
#define POLLERR (1u << 5) /* some poll error occurred */
#define POLLHUP (1u << 6) /* file descriptor was "hung up" */
#define POLLNVAL (1u << 7) /* the specified file descriptor is invalid */
#ifdef __cplusplus
extern "C" {
#endif
struct pollfd {
int fd; /* The descriptor. */
short events; /* The event(s) is/are specified here. */
short revents; /* Events found are returned here. */
};
typedef unsigned int nfds_t;
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // _ESP_PLATFORM_SYS_POLL_H_
+22
View File
@@ -0,0 +1,22 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __SYS_RANDOM__
#define __SYS_RANDOM__
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
ssize_t getrandom(void *buf, size_t buflen, unsigned int flags);
#ifdef __cplusplus
} // extern "C"
#endif
#endif //__SYS_RANDOM__
+26
View File
@@ -0,0 +1,26 @@
/*
* SPDX-FileCopyrightText: 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#define _REENT_BACKWARD_BINARY_COMPAT
#define _REENT_SDIDINIT(_ptr) ((_ptr)->_reserved_0)
#define _REENT_SGLUE(_ptr) (__sglue)
#include_next<sys/reent.h>
#ifdef __cplusplus
extern "C" {
#endif
extern void __sinit(struct _reent *);
extern struct _glue __sglue;
extern struct _reent * _global_impure_ptr;
#ifdef __cplusplus
}
#endif
+42
View File
@@ -0,0 +1,42 @@
/*
* SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __ESP_SYS_SELECT_H__
#define __ESP_SYS_SELECT_H__
/* Newlib 2.2.0 does not provide sys/select.h, and fd_set is defined in sys/types.h */
#include <sys/types.h>
#ifndef fd_set
#include_next <sys/select.h>
#else // fd_set
#include <sys/time.h>
#ifdef __cplusplus
extern "C" {
#endif
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // fd_set
#if defined(FD_ISSET) || defined(FD_SET) || defined(FD_CLR)
#undef FD_SET
#undef FD_CLR
#undef FD_ISSET
#define __FD_SAFE_SET(n, code) do { if ((unsigned)(n) < FD_SETSIZE) { code; } } while(0)
#define __FD_SAFE_GET(n, code) (((unsigned)(n) < FD_SETSIZE) ? (code) : 0)
#define FD_SET(n, p) __FD_SAFE_SET(n, ((p)->fds_bits[(n) / NFDBITS] |= (1L << ((n) % NFDBITS))))
#define FD_CLR(n, p) __FD_SAFE_SET(n, ((p)->fds_bits[(n) / NFDBITS] &= ~(1L << ((n) % NFDBITS))))
#define FD_ISSET(n, p) __FD_SAFE_GET(n, ((p)->fds_bits[(n) / NFDBITS] & (1L << ((n) % NFDBITS))))
#endif // FD_ISSET || FD_SET || FD_CLR
#endif //__ESP_SYS_SELECT_H__
+286
View File
@@ -0,0 +1,286 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
//
// This header file is based on the termios header of
// "The Single UNIX (r) Specification, Version 2, Copyright (c) 1997 The Open Group".
#ifndef __ESP_SYS_TERMIOS_H__
#define __ESP_SYS_TERMIOS_H__
// ESP-IDF NOTE: This header provides only a compatibility layer for macros and functions defined in sys/termios.h.
// Not everything has a defined meaning for ESP-IDF (e.g. process leader IDs) and therefore are likely to be stubbed
// in actual implementations.
#include <stdint.h>
#include <sys/types.h>
#include "sdkconfig.h"
#ifdef CONFIG_VFS_SUPPORT_TERMIOS
// subscripts for the array c_cc:
#define VEOF 0 /** EOF character */
#define VEOL 1 /** EOL character */
#define VERASE 2 /** ERASE character */
#define VINTR 3 /** INTR character */
#define VKILL 4 /** KILL character */
#define VMIN 5 /** MIN value */
#define VQUIT 6 /** QUIT character */
#define VSTART 7 /** START character */
#define VSTOP 8 /** STOP character */
#define VSUSP 9 /** SUSP character */
#define VTIME 10 /** TIME value */
#define NCCS (VTIME + 1) /** Size of the array c_cc for control characters */
// input modes for use as flags in the c_iflag field
#define BRKINT (1u << 0) /** Signal interrupt on break. */
#define ICRNL (1u << 1) /** Map CR to NL on input. */
#define IGNBRK (1u << 2) /** Ignore break condition. */
#define IGNCR (1u << 3) /** Ignore CR. */
#define IGNPAR (1u << 4) /** Ignore characters with parity errors. */
#define INLCR (1u << 5) /** Map NL to CR on input. */
#define INPCK (1u << 6) /** Enable input parity check. */
#define ISTRIP (1u << 7) /** Strip character. */
#define IUCLC (1u << 8) /** Map upper-case to lower-case on input (LEGACY). */
#define IXANY (1u << 9) /** Enable any character to restart output. */
#define IXOFF (1u << 10) /** Enable start/stop input control. */
#define IXON (1u << 11) /** Enable start/stop output control. */
#define PARMRK (1u << 12) /** Mark parity errors. */
// output Modes for use as flags in the c_oflag field
#define OPOST (1u << 0) /** Post-process output */
#define OLCUC (1u << 1) /** Map lower-case to upper-case on output (LEGACY). */
#define ONLCR (1u << 2) /** Map NL to CR-NL on output. */
#define OCRNL (1u << 3) /** Map CR to NL on output. */
#define ONOCR (1u << 4) /** No CR output at column 0. */
#define ONLRET (1u << 5) /** NL performs CR function. */
#define OFILL (1u << 6) /** Use fill characters for delay. */
#define NLDLY (1u << 7) /** Select newline delays: */
#define NL0 (0u << 7) /** Newline character type 0. */
#define NL1 (1u << 7) /** Newline character type 1. */
#define CRDLY (3u << 8) /** Select carriage-return delays: */
#define CR0 (0u << 8) /** Carriage-return delay type 0. */
#define CR1 (1u << 8) /** Carriage-return delay type 1. */
#define CR2 (2u << 8) /** Carriage-return delay type 2. */
#define CR3 (3u << 8) /** Carriage-return delay type 3. */
#define TABDLY (3u << 10) /** Select horizontal-tab delays: */
#define TAB0 (0u << 10) /** Horizontal-tab delay type 0. */
#define TAB1 (1u << 10) /** Horizontal-tab delay type 1. */
#define TAB2 (2u << 10) /** Horizontal-tab delay type 2. */
#define TAB3 (3u << 10) /** Expand tabs to spaces. */
#define BSDLY (1u << 12) /** Select backspace delays: */
#define BS0 (0u << 12) /** Backspace-delay type 0. */
#define BS1 (1u << 12) /** Backspace-delay type 1. */
#define VTDLY (1u << 13) /** Select vertical-tab delays: */
#define VT0 (0u << 13) /** Vertical-tab delay type 0. */
#define VT1 (1u << 13) /** Vertical-tab delay type 1. */
#define FFDLY (1u << 14) /** Select form-feed delays: */
#define FF0 (0u << 14) /** Form-feed delay type 0. */
#define FF1 (1u << 14) /** Form-feed delay type 1. */
// Baud Rate Selection. Valid values for objects of type speed_t:
// CBAUD range B0 - B38400
#define B0 0 /** Hang up */
#define B50 1
#define B75 2
#define B110 3
#define B134 4
#define B150 5
#define B200 6
#define B300 7
#define B600 8
#define B1200 9
#define B1800 10
#define B2400 11
#define B4800 12
#define B9600 13
#define B19200 14
#define B38400 15
// CBAUDEX range B57600 - B4000000
#define B57600 16
#define B115200 17
#define B230400 18
#define B460800 19
#define B500000 20
#define B576000 21
#define B921600 22
#define B1000000 23
#define B1152000 24
#define B1500000 25
#define B2000000 26
#define B2500000 27
#define B3000000 28
#define B3500000 29
#define B4000000 30
// Control Modes for the c_cflag field:
#define CSIZE (3u << 0) /* Character size: */
#define CS5 (0u << 0) /** 5 bits. */
#define CS6 (1u << 0) /** 6 bits. */
#define CS7 (2u << 0) /** 7 bits. */
#define CS8 (3u << 0) /** 8 bits. */
#define CSTOPB (1u << 2) /** Send two stop bits, else one. */
#define CREAD (1u << 3) /** Enable receiver. */
#define PARENB (1u << 4) /** Parity enable. */
#define PARODD (1u << 5) /** Odd parity, else even. */
#define HUPCL (1u << 6) /** Hang up on last close. */
#define CLOCAL (1u << 7) /** Ignore modem status lines. */
#define CBAUD (1u << 8) /** Use baud rates defined by B0-B38400 macros. */
#define CBAUDEX (1u << 9) /** Use baud rates defined by B57600-B4000000 macros. */
#define BOTHER (1u << 10) /** Use custom baud rates */
// Local Modes for c_lflag field:
#define ECHO (1u << 0) /** Enable echo. */
#define ECHOE (1u << 1) /** Echo erase character as error-correcting backspace. */
#define ECHOK (1u << 2) /** Echo KILL. */
#define ECHONL (1u << 3) /** Echo NL. */
#define ICANON (1u << 4) /** Canonical input (erase and kill processing). */
#define IEXTEN (1u << 5) /** Enable extended input character processing. */
#define ISIG (1u << 6) /** Enable signals. */
#define NOFLSH (1u << 7) /** Disable flush after interrupt or quit. */
#define TOSTOP (1u << 8) /** Send SIGTTOU for background output. */
#define XCASE (1u << 9) /** Canonical upper/lower presentation (LEGACY). */
// Attribute Selection constants for use with tcsetattr():
#define TCSANOW 0 /** Change attributes immediately. */
#define TCSADRAIN 1 /** Change attributes when output has drained. */
#define TCSAFLUSH 2 /** Change attributes when output has drained; also flush pending input. */
// Line Control constants for use with tcflush():
#define TCIFLUSH 0 /** Flush pending input. Flush untransmitted output. */
#define TCIOFLUSH 1 /** Flush both pending input and untransmitted output. */
#define TCOFLUSH 2 /** Flush untransmitted output. */
// constants for use with tcflow():
#define TCIOFF 0 /** Transmit a STOP character, intended to suspend input data. */
#define TCION 1 /** Transmit a START character, intended to restart input data. */
#define TCOOFF 2 /** Suspend output. */
#define TCOON 3 /** Restart output. */
typedef uint8_t cc_t;
typedef uint32_t speed_t;
typedef uint16_t tcflag_t;
struct termios {
tcflag_t c_iflag; /** Input modes */
tcflag_t c_oflag; /** Output modes */
tcflag_t c_cflag; /** Control modes */
tcflag_t c_lflag; /** Local modes */
cc_t c_cc[NCCS]; /** Control characters */
speed_t c_ispeed; /** input baud rate */
speed_t c_ospeed; /** output baud rate */
};
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Extracts the input baud rate from the input structure exactly (without interpretation).
*
* @param p input termios structure
* @return input baud rate
*/
speed_t cfgetispeed(const struct termios *p);
/**
* @brief Extracts the output baud rate from the input structure exactly (without interpretation).
*
* @param p input termios structure
* @return output baud rate
*/
speed_t cfgetospeed(const struct termios *p);
/**
* @brief Set input baud rate in the termios structure
*
* There is no effect in hardware until a subsequent call of tcsetattr().
*
* @param p input termios structure
* @param sp input baud rate
* @return 0 when successful, -1 otherwise with errno set
*/
int cfsetispeed(struct termios *p, speed_t sp);
/**
* @brief Set output baud rate in the termios structure
*
* There is no effect in hardware until a subsequent call of tcsetattr().
*
* @param p input termios structure
* @param sp output baud rate
* @return 0 when successful, -1 otherwise with errno set
*/
int cfsetospeed(struct termios *p, speed_t sp);
/**
* @brief Wait for transmission of output
*
* @param fd file descriptor of the terminal
* @return 0 when successful, -1 otherwise with errno set
*/
int tcdrain(int fd);
/**
* @brief Suspend or restart the transmission or reception of data
*
* @param fd file descriptor of the terminal
* @param action selects actions to do
* @return 0 when successful, -1 otherwise with errno set
*/
int tcflow(int fd, int action);
/**
* @brief Flush non-transmitted output data and non-read input data
*
* @param fd file descriptor of the terminal
* @param select selects what should be flushed
* @return 0 when successful, -1 otherwise with errno set
*/
int tcflush(int fd, int select);
/**
* @brief Gets the parameters of the terminal
*
* @param fd file descriptor of the terminal
* @param p output termios structure
* @return 0 when successful, -1 otherwise with errno set
*/
int tcgetattr(int fd, struct termios *p);
/**
* @brief Get process group ID for session leader for controlling terminal
*
* @param fd file descriptor of the terminal
* @return process group ID when successful, -1 otherwise with errno set
*/
pid_t tcgetsid(int fd);
/**
* @brief Send a break for a specific duration
*
* @param fd file descriptor of the terminal
* @param duration duration of break
* @return 0 when successful, -1 otherwise with errno set
*/
int tcsendbreak(int fd, int duration);
/**
* @brief Sets the parameters of the terminal
*
* @param fd file descriptor of the terminal
* @param optional_actions optional actions
* @param p input termios structure
* @return 0 when successful, -1 otherwise with errno set
*/
int tcsetattr(int fd, int optional_actions, const struct termios *p);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // CONFIG_VFS_SUPPORT_TERMIOS
#endif //__ESP_SYS_TERMIOS_H__
+22
View File
@@ -0,0 +1,22 @@
/*
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
/* Newlib sys/time.h defines timerisset, timerclear, timercmp, timeradd, timersub macros
for __CYGWIN__ and __rtems__. We want to define these macros in IDF as well.
Since we wish to use un-modified newlib headers until a patched newlib version is
available, temporarily define __rtems__ here before including sys/time.h.
__rtems__ is chosen instead of __CYGWIN__ since there are no other checks in sys/time.h
which depend on __rtems__.
Also, so that __rtems__ define does not affect other headers included from sys/time.h,
we include them here in advance (_ansi.h and sys/types.h).
*/
#include <_ansi.h>
#include <sys/types.h>
#define __rtems__
#include_next <sys/time.h>
#undef __rtems__
+24
View File
@@ -0,0 +1,24 @@
/*
* SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
struct iovec;
int writev(int s, const struct iovec *iov, int iovcnt);
ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
#ifdef __cplusplus
}
#endif
+21
View File
@@ -0,0 +1,21 @@
/*
* SPDX-FileCopyrightText: 2018-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#define AF_UNIX 1 /* local to host (pipes) */
struct sockaddr_un {
short sun_family; /*AF_UNIX*/
char sun_path[108]; /*path name */
};
#ifdef __cplusplus
}
#endif
+23
View File
@@ -0,0 +1,23 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <sys/types.h>
#include_next <sys/unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
int truncate(const char *, off_t __length);
int gethostname(char *__name, size_t __len);
int getentropy(void *buffer, size_t length);
#ifdef __cplusplus
}
#endif
+27
View File
@@ -0,0 +1,27 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _UTIME_H_
#define _UTIME_H_
#include <sys/time.h>
#ifdef __cplusplus
extern "C" {
#endif
struct utimbuf {
time_t actime; // access time
time_t modtime; // modification time
};
int utime(const char *path, const struct utimbuf *times);
#ifdef __cplusplus
};
#endif
#endif /* _UTIME_H_ */
+31
View File
@@ -0,0 +1,31 @@
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <sys/types.h>
#include_next <time.h>
#ifdef __cplusplus
extern "C" {
#endif
#define _POSIX_TIMERS 1
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC (clockid_t)4
#endif
#ifndef CLOCK_BOOTTIME
#define CLOCK_BOOTTIME (clockid_t)4
#endif
int clock_settime(clockid_t clock_id, const struct timespec *tp);
int clock_gettime(clockid_t clock_id, struct timespec *tp);
int clock_getres(clockid_t clock_id, struct timespec *res);
#ifdef __cplusplus
}
#endif
+87
View File
@@ -0,0 +1,87 @@
/*
* SPDX-FileCopyrightText: 2019-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stddef.h>
#include <sys/poll.h>
#include <sys/select.h>
#include <sys/errno.h>
#include <sys/param.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
struct timeval tv = {
// timeout is in milliseconds
.tv_sec = timeout / 1000,
.tv_usec = (timeout % 1000) * 1000,
};
int max_fd = -1;
fd_set readfds;
fd_set writefds;
fd_set errorfds;
struct _reent* r = __getreent();
int ret = 0;
if (fds == NULL) {
__errno_r(r) = ENOENT;
return -1;
}
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&errorfds);
for (unsigned int i = 0; i < nfds; ++i) {
fds[i].revents = 0;
if (fds[i].fd < 0) {
// revents should remain 0 and events ignored (according to the documentation of poll()).
continue;
}
if (fds[i].fd >= FD_SETSIZE) {
fds[i].revents |= POLLNVAL;
++ret;
continue;
}
if (fds[i].events & (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
FD_SET(fds[i].fd, &readfds);
FD_SET(fds[i].fd, &errorfds);
max_fd = MAX(max_fd, fds[i].fd);
}
if (fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND)) {
FD_SET(fds[i].fd, &writefds);
FD_SET(fds[i].fd, &errorfds);
max_fd = MAX(max_fd, fds[i].fd);
}
}
const int select_ret = select(max_fd + 1, &readfds, &writefds, &errorfds, timeout < 0 ? NULL : &tv);
if (select_ret > 0) {
ret += select_ret;
for (unsigned int i = 0; i < nfds; ++i) {
if (FD_ISSET(fds[i].fd, &readfds)) {
fds[i].revents |= POLLIN;
}
if (FD_ISSET(fds[i].fd, &writefds)) {
fds[i].revents |= POLLOUT;
}
if (FD_ISSET(fds[i].fd, &errorfds)) {
fds[i].revents |= POLLERR;
}
}
} else {
ret = select_ret;
// keeping the errno from select()
}
return ret;
}
+1
View File
@@ -0,0 +1 @@
target_sources(${COMPONENT_LIB} PRIVATE "${CMAKE_CURRENT_LIST_DIR}/esp_time_impl.c")
+145
View File
@@ -0,0 +1,145 @@
/*
* SPDX-FileCopyrightText: 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <sys/lock.h>
#include "esp_attr.h"
#include "esp_system.h"
#include "soc/rtc.h"
#include "esp_rom_sys.h"
#include "esp_private/system_internal.h"
#include "esp_private/esp_clk.h"
#include "esp_time_impl.h"
#include "sdkconfig.h"
#if CONFIG_IDF_TARGET_ESP32
#include "esp32/rom/rtc.h"
#include "esp32/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/rtc.h"
#include "esp32s2/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S3
#include "esp32s3/rom/rtc.h"
#include "esp32s3/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/rtc.h"
#include "esp32c3/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C2
#include "esp32c2/rom/rtc.h"
#include "esp32c2/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C6
#include "esp32c6/rom/rtc.h"
#include "esp32c6/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C61 //TODO: IDF-9526, refactor this
#include "esp32c61/rom/rtc.h"
#include "esp32c61/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C5
#include "esp32c5/rom/rtc.h"
#include "esp32c5/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32H2
#include "esp32h2/rom/rtc.h"
#include "esp32h2/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32P4
#include "esp32p4/rom/rtc.h"
#include "esp32p4/rtc.h"
#endif
// Offset between High resolution timer and the RTC.
// Initialized after reset or light sleep.
#if defined(CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER) && defined(CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER)
int64_t s_microseconds_offset = 0;
#endif
#ifndef CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER
static uint64_t s_boot_time; // when RTC is used to persist time, two RTC_STORE registers are used to store boot time instead
#endif
static _lock_t s_boot_time_lock;
#if defined( CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER ) || defined( CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER )
uint64_t esp_time_impl_get_time_since_boot(void)
{
uint64_t microseconds = 0;
#ifdef CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER
#ifdef CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER
microseconds = s_microseconds_offset + esp_system_get_time();
#else
microseconds = esp_system_get_time();
#endif // CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER
#elif defined(CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER)
microseconds = esp_rtc_get_time_us();
#endif // CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER
return microseconds;
}
uint64_t esp_time_impl_get_time(void)
{
uint64_t microseconds = 0;
#if defined( CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER )
microseconds = esp_system_get_time();
#elif defined( CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER )
microseconds = esp_rtc_get_time_us();
#endif // CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER
return microseconds;
}
#endif // defined( CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER ) || defined( CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER )
void esp_time_impl_set_boot_time(uint64_t time_us)
{
_lock_acquire(&s_boot_time_lock);
#ifdef CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER
REG_WRITE(RTC_BOOT_TIME_LOW_REG, (uint32_t)(time_us & 0xffffffff));
REG_WRITE(RTC_BOOT_TIME_HIGH_REG, (uint32_t)(time_us >> 32));
#else
s_boot_time = time_us;
#endif
_lock_release(&s_boot_time_lock);
}
uint64_t esp_time_impl_get_boot_time(void)
{
uint64_t result;
_lock_acquire(&s_boot_time_lock);
#ifdef CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER
result = ((uint64_t) REG_READ(RTC_BOOT_TIME_LOW_REG)) + (((uint64_t) REG_READ(RTC_BOOT_TIME_HIGH_REG)) << 32);
#else
result = s_boot_time;
#endif
_lock_release(&s_boot_time_lock);
return result;
}
void esp_set_time_from_rtc(void)
{
#if defined( CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER ) && defined( CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER )
// initialize time from RTC clock
s_microseconds_offset = esp_rtc_get_time_us() - esp_system_get_time();
#endif // CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER && CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER
}
void esp_sync_timekeeping_timers(void)
{
#if defined( CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER ) && defined( CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER )
struct timeval tv;
gettimeofday(&tv, NULL);
settimeofday(&tv, NULL);
int64_t s_microseconds_offset_cur = esp_rtc_get_time_us() - esp_system_get_time();
esp_time_impl_set_boot_time(esp_time_impl_get_boot_time() + ((int64_t)s_microseconds_offset - s_microseconds_offset_cur));
#endif
}
void esp_time_impl_init(void)
{
esp_set_time_from_rtc();
}
@@ -0,0 +1,79 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdbool.h>
#include <stdint.h>
#include "esp_stdatomic.h"
#undef SYNC_OP_FUNCTIONS
#undef _ATOMIC_OP_FUNCTION
#undef ATOMIC_LOAD
#undef ATOMIC_CMP_EXCHANGE
#undef ATOMIC_STORE
#undef ATOMIC_EXCHANGE
#undef SYNC_BOOL_CMP_EXCHANGE
#undef SYNC_VAL_CMP_EXCHANGE
#undef SYNC_LOCK_TEST_AND_SET
#undef SYNC_LOCK_RELEASE
#define SYNC_OP_FUNCTIONS(n, type, name)
#define _ATOMIC_OP_FUNCTION(n, type, name_1, name_2, ret_var, operation, inverse) \
type __atomic_s32c1i_ ##name_1 ##_ ##name_2 ##_ ##n (volatile void* ptr, type value, int memorder) \
{ \
return __atomic_ ##name_1 ##_ ##name_2 ##_ ##n (ptr, value, memorder); \
}
#define ATOMIC_LOAD(n, type) \
type __atomic_s32c1i_load_ ## n (const volatile void* ptr, int memorder) \
{ \
return __atomic_load_ ## n (ptr, memorder); \
}
#define ATOMIC_CMP_EXCHANGE(n, type) \
bool __atomic_s32c1i_compare_exchange_ ## n (volatile void* ptr, void* expected, type desired, bool weak, int success, int failure) \
{ \
return __atomic_compare_exchange_ ## n (ptr, expected, desired, weak, success, failure); \
}
#define ATOMIC_STORE(n, type) \
void __atomic_s32c1i_store_ ## n (volatile void * ptr, type value, int memorder) \
{ \
__atomic_store_ ## n (ptr, value, memorder); \
}
#define ATOMIC_EXCHANGE(n, type) \
type __atomic_s32c1i_exchange_ ## n (volatile void* ptr, type value, int memorder) \
{ \
return __atomic_exchange_ ## n (ptr, value, memorder); \
}
#define SYNC_BOOL_CMP_EXCHANGE(n, type) \
bool __sync_s32c1i_bool_compare_and_swap_ ## n (volatile void* ptr, type expected, type desired) \
{ \
return __sync_bool_compare_and_swap_ ## n (ptr, expected, desired); \
}
#define SYNC_VAL_CMP_EXCHANGE(n, type) \
type __sync_s32c1i_val_compare_and_swap_ ## n (volatile void* ptr, type expected, type desired) \
{ \
return __sync_val_compare_and_swap_ ## n (ptr, expected, desired); \
}
#define SYNC_LOCK_TEST_AND_SET(n, type) \
type __sync_s32c1i_lock_test_and_set_ ## n (volatile void* ptr, type value) \
{ \
return __sync_lock_test_and_set_ ## n (ptr, value); \
}
#define SYNC_LOCK_RELEASE(n, type) \
void __sync_s32c1i_lock_release_ ## n (volatile void* ptr) \
{ \
__sync_lock_release_ ## n (ptr); \
}
ATOMIC_FUNCTIONS(1, unsigned char)
ATOMIC_FUNCTIONS(2, short unsigned int)
ATOMIC_FUNCTIONS(4, unsigned int)
+296
View File
@@ -0,0 +1,296 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "freertos/FreeRTOS.h"
#include "soc/soc_caps.h"
#include "sdkconfig.h"
#ifdef __XTENSA__
#include "xtensa/config/core-isa.h"
#ifndef XCHAL_HAVE_S32C1I
#error "XCHAL_HAVE_S32C1I not defined, include correct header!"
#endif // XCHAL_HAVE_S32C1I
#ifndef CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND
#define CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND 0
#endif
#define HAS_ATOMICS_32 ((XCHAL_HAVE_S32C1I == 1) && !CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND)
// no 64-bit atomics on Xtensa
#define HAS_ATOMICS_64 0
#else // RISCV
// GCC toolchain will define this pre-processor if "A" extension is supported
#ifndef __riscv_atomic
#define __riscv_atomic 0
#endif
#define HAS_ATOMICS_32 (__riscv_atomic == 1)
#define HAS_ATOMICS_64 ((__riscv_atomic == 1) && (__riscv_xlen == 64))
#endif // (__XTENSA__, __riscv)
#if SOC_CPU_CORES_NUM == 1
// Single core SoC: atomics can be implemented using portSET_INTERRUPT_MASK_FROM_ISR
// and portCLEAR_INTERRUPT_MASK_FROM_ISR, which disables and enables interrupts.
#if CONFIG_FREERTOS_SMP
#define _ATOMIC_ENTER_CRITICAL() unsigned int state = portDISABLE_INTERRUPTS();
#define _ATOMIC_EXIT_CRITICAL() portRESTORE_INTERRUPTS(state)
#else // CONFIG_FREERTOS_SMP
#define _ATOMIC_ENTER_CRITICAL() unsigned int state = portSET_INTERRUPT_MASK_FROM_ISR()
#define _ATOMIC_EXIT_CRITICAL() portCLEAR_INTERRUPT_MASK_FROM_ISR(state)
#endif // CONFIG_FREERTOS_SMP
#else // SOC_CPU_CORES_NUM
#define _ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL_SAFE(&s_atomic_lock);
#define _ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL_SAFE(&s_atomic_lock);
#endif // SOC_CPU_CORES_NUM
#if CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND
#define _ATOMIC_IF_NOT_EXT_RAM() \
if (!((uintptr_t)ptr >= SOC_EXTRAM_DATA_LOW && (uintptr_t) ptr < SOC_EXTRAM_DATA_HIGH))
#define _ATOMIC_HW_STUB_OP_FUNCTION(n, type, name_1, name_2) \
_ATOMIC_IF_NOT_EXT_RAM() { \
type __atomic_s32c1i_ ##name_1 ##_ ##name_2 ##_ ##n (volatile void* ptr, type value, int memorder); \
return __atomic_s32c1i_ ##name_1 ##_ ##name_2 ##_ ##n (ptr, value, memorder); \
}
#define _ATOMIC_HW_STUB_EXCHANGE(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
type __atomic_s32c1i_exchange_ ## n (volatile void* ptr, type value, int memorder); \
return __atomic_s32c1i_exchange_ ## n (ptr, value, memorder); \
}
#define _ATOMIC_HW_STUB_STORE(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
void __atomic_s32c1i_store_ ## n (volatile void * ptr, type value, int memorder); \
__atomic_s32c1i_store_ ## n (ptr, value, memorder); \
return; \
}
#define _ATOMIC_HW_STUB_CMP_EXCHANGE(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
bool __atomic_s32c1i_compare_exchange_ ## n (volatile void* ptr, void* expected, type desired, bool weak, int success, int failure); \
return __atomic_s32c1i_compare_exchange_ ## n (ptr, expected, desired, weak, success, failure); \
}
#define _ATOMIC_HW_STUB_LOAD(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
type __atomic_s32c1i_load_ ## n (const volatile void* ptr, int memorder); \
return __atomic_s32c1i_load_ ## n (ptr,memorder); \
}
#define _ATOMIC_HW_STUB_SYNC_BOOL_CMP_EXCHANGE(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
bool __sync_s32c1i_bool_compare_and_swap_ ## n (volatile void* ptr, type expected, type desired); \
return __sync_s32c1i_bool_compare_and_swap_ ## n (ptr, expected, desired); \
}
#define _ATOMIC_HW_STUB_SYNC_VAL_CMP_EXCHANGE(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
type __sync_s32c1i_val_compare_and_swap_ ## n (volatile void* ptr, type expected, type desired); \
return __sync_s32c1i_val_compare_and_swap_ ## n (ptr, expected, desired); \
}
#define _ATOMIC_HW_STUB_SYNC_LOCK_TEST_AND_SET(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
type __sync_s32c1i_lock_test_and_set_ ## n (volatile void* ptr, type value); \
return __sync_s32c1i_lock_test_and_set_ ## n (ptr, value); \
}
#define _ATOMIC_HW_STUB_SYNC_LOCK_RELEASE(n, type) \
_ATOMIC_IF_NOT_EXT_RAM() { \
void __sync_s32c1i_lock_release_ ## n (volatile void* ptr); \
__sync_s32c1i_lock_release_ ## n (ptr); \
return; \
}
#else // CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND
#define _ATOMIC_HW_STUB_OP_FUNCTION(n, type, name_1, name_2)
#define _ATOMIC_HW_STUB_EXCHANGE(n, type)
#define _ATOMIC_HW_STUB_STORE(n, type)
#define _ATOMIC_HW_STUB_CMP_EXCHANGE(n, type)
#define _ATOMIC_HW_STUB_LOAD(n, type)
#define _ATOMIC_HW_STUB_SYNC_BOOL_CMP_EXCHANGE(n, type)
#define _ATOMIC_HW_STUB_SYNC_VAL_CMP_EXCHANGE(n, type)
#define _ATOMIC_HW_STUB_SYNC_LOCK_TEST_AND_SET(n, type)
#define _ATOMIC_HW_STUB_SYNC_LOCK_RELEASE(n, type)
#endif // CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND
#ifdef __clang__
// Clang doesn't allow to define "__sync_*" atomics. The workaround is to define function with name "__sync_*_builtin",
// which implements "__sync_*" atomic functionality and use asm directive to set the value of symbol "__sync_*" to the name
// of defined function.
#define CLANG_ATOMIC_SUFFIX(name_) name_ ## _builtin
#define CLANG_DECLARE_ALIAS(name_) \
__asm__(".type " # name_ ", @function\n" \
".global " #name_ "\n" \
".equ " #name_ ", " #name_ "_builtin");
#else // __clang__
#define CLANG_ATOMIC_SUFFIX(name_) name_
#define CLANG_DECLARE_ALIAS(name_)
#endif // __clang__
#define ATOMIC_OP_FUNCTIONS(n, type, name, operation, inverse) \
_ATOMIC_OP_FUNCTION(n, type, fetch, name, old, operation, inverse) \
_ATOMIC_OP_FUNCTION(n, type, name, fetch, new, operation, inverse)
#define _ATOMIC_OP_FUNCTION(n, type, name_1, name_2, ret_var, operation, inverse) \
type __atomic_ ##name_1 ##_ ##name_2 ##_ ##n (volatile void* ptr, type value, int memorder) \
{ \
type old, new; \
_ATOMIC_HW_STUB_OP_FUNCTION(n, type, name_1, name_2); \
_ATOMIC_ENTER_CRITICAL(); \
old = (*(volatile type*)ptr); \
new = inverse(old operation value); \
*(volatile type*)ptr = new; \
_ATOMIC_EXIT_CRITICAL(); \
return ret_var; \
}
#define ATOMIC_LOAD(n, type) \
type __atomic_load_ ## n (const volatile void* ptr, int memorder) \
{ \
type old; \
_ATOMIC_HW_STUB_LOAD(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
old = *(const volatile type*)ptr; \
_ATOMIC_EXIT_CRITICAL(); \
return old; \
}
#define ATOMIC_CMP_EXCHANGE(n, type) \
bool __atomic_compare_exchange_ ## n (volatile void* ptr, void* expected, type desired, bool weak, int success, int failure) \
{ \
bool ret = false; \
_ATOMIC_HW_STUB_CMP_EXCHANGE(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
if (*(volatile type*)ptr == *(type*)expected) { \
ret = true; \
*(volatile type*)ptr = desired; \
} else { \
*(type*)expected = *(volatile type*)ptr; \
} \
_ATOMIC_EXIT_CRITICAL(); \
return ret; \
}
#define ATOMIC_STORE(n, type) \
void __atomic_store_ ## n (volatile void * ptr, type value, int memorder) \
{ \
_ATOMIC_HW_STUB_STORE(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
*(volatile type*)ptr = value; \
_ATOMIC_EXIT_CRITICAL(); \
}
#define ATOMIC_EXCHANGE(n, type) \
type __atomic_exchange_ ## n (volatile void* ptr, type value, int memorder) \
{ \
type old; \
_ATOMIC_HW_STUB_EXCHANGE(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
old = *(volatile type*)ptr; \
*(volatile type*)ptr = value; \
_ATOMIC_EXIT_CRITICAL(); \
return old; \
}
#define SYNC_OP_FUNCTIONS(n, type, name) \
_SYNC_OP_FUNCTION(n, type, fetch, name) \
_SYNC_OP_FUNCTION(n, type, name, fetch)
#define _SYNC_OP_FUNCTION(n, type, name_1, name_2) \
type CLANG_ATOMIC_SUFFIX(__sync_ ##name_1 ##_and_ ##name_2 ##_ ##n) (volatile void* ptr, type value) \
{ \
return __atomic_ ##name_1 ##_ ##name_2 ##_ ##n (ptr, value, __ATOMIC_SEQ_CST); \
} \
CLANG_DECLARE_ALIAS( __sync_##name_1 ##_and_ ##name_2 ##_ ##n )
#define SYNC_BOOL_CMP_EXCHANGE(n, type) \
bool CLANG_ATOMIC_SUFFIX(__sync_bool_compare_and_swap_ ## n) (volatile void* ptr, type expected, type desired) \
{ \
bool ret = false; \
_ATOMIC_HW_STUB_SYNC_BOOL_CMP_EXCHANGE(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
if (*(volatile type*)ptr == expected) { \
*(volatile type*)ptr = desired; \
ret = true; \
} \
_ATOMIC_EXIT_CRITICAL(); \
return ret; \
} \
CLANG_DECLARE_ALIAS( __sync_bool_compare_and_swap_ ## n )
#define SYNC_VAL_CMP_EXCHANGE(n, type) \
type CLANG_ATOMIC_SUFFIX(__sync_val_compare_and_swap_ ## n) (volatile void* ptr, type expected, type desired) \
{ \
type old; \
_ATOMIC_HW_STUB_SYNC_VAL_CMP_EXCHANGE(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
old = *(volatile type*)ptr; \
if (old == expected) { \
*(volatile type*)ptr = desired; \
} \
_ATOMIC_EXIT_CRITICAL(); \
return old; \
} \
CLANG_DECLARE_ALIAS( __sync_val_compare_and_swap_ ## n )
#define SYNC_LOCK_TEST_AND_SET(n, type) \
type CLANG_ATOMIC_SUFFIX(__sync_lock_test_and_set_ ## n) (volatile void* ptr, type value) \
{ \
type old; \
_ATOMIC_HW_STUB_SYNC_LOCK_TEST_AND_SET(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
old = *(volatile type*)ptr; \
*(volatile type*)ptr = value; \
_ATOMIC_EXIT_CRITICAL(); \
return old; \
} \
CLANG_DECLARE_ALIAS( __sync_lock_test_and_set_ ## n )
#define SYNC_LOCK_RELEASE(n, type) \
void CLANG_ATOMIC_SUFFIX(__sync_lock_release_ ## n) (volatile void* ptr) \
{ \
_ATOMIC_HW_STUB_SYNC_LOCK_RELEASE(n, type); \
_ATOMIC_ENTER_CRITICAL(); \
*(volatile type*)ptr = 0; \
_ATOMIC_EXIT_CRITICAL(); \
} \
CLANG_DECLARE_ALIAS( __sync_lock_release_ ## n )
#define ATOMIC_FUNCTIONS(n, type) \
ATOMIC_EXCHANGE(n, type) \
ATOMIC_CMP_EXCHANGE(n, type) \
ATOMIC_OP_FUNCTIONS(n, type, add, +, ) \
ATOMIC_OP_FUNCTIONS(n, type, sub, -, ) \
ATOMIC_OP_FUNCTIONS(n, type, and, &, ) \
ATOMIC_OP_FUNCTIONS(n, type, or, |, ) \
ATOMIC_OP_FUNCTIONS(n, type, xor, ^, ) \
ATOMIC_OP_FUNCTIONS(n, type, nand, &, ~) \
/* LLVM has not implemented native atomic load/stores for riscv targets without the Atomic extension. LLVM thread: https://reviews.llvm.org/D47553. \
* Even though GCC does transform them, these libcalls need to be available for the case where a LLVM based project links against IDF. */ \
ATOMIC_LOAD(n, type) \
ATOMIC_STORE(n, type) \
SYNC_OP_FUNCTIONS(n, type, add) \
SYNC_OP_FUNCTIONS(n, type, sub) \
SYNC_OP_FUNCTIONS(n, type, and) \
SYNC_OP_FUNCTIONS(n, type, or) \
SYNC_OP_FUNCTIONS(n, type, xor) \
SYNC_OP_FUNCTIONS(n, type, nand) \
SYNC_BOOL_CMP_EXCHANGE(n, type) \
SYNC_VAL_CMP_EXCHANGE(n, type) \
SYNC_LOCK_TEST_AND_SET(n, type) \
SYNC_LOCK_RELEASE(n, type)
+18
View File
@@ -0,0 +1,18 @@
/*
* SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
void esp_time_impl_init(void);
uint64_t esp_time_impl_get_time(void);
uint64_t esp_time_impl_get_time_since_boot(void);
uint32_t esp_time_impl_get_time_resolution(void);
void esp_time_impl_set_boot_time(uint64_t t);
uint64_t esp_time_impl_get_boot_time(void);
+3
View File
@@ -0,0 +1,3 @@
if(CONFIG_STDATOMIC_S32C1I_SPIRAM_WORKAROUND)
idf_build_set_property(COMPILE_OPTIONS "-mdisable-hardware-atomics" APPEND)
endif()

Some files were not shown because too many files have changed in this diff Show More