port GUI to RPX, use backend via simple IPC

This commit is contained in:
orboditilt 2019-08-14 22:19:46 +02:00
parent 0c0f9f36e2
commit fd6a711cb7
161 changed files with 3198 additions and 22766 deletions

16
.gitignore vendored
View File

@ -1,12 +1,6 @@
build/* build/
*.cbp *.rpx
*.elf *.elf
*.cscope_file_list *.exe
*.layout src/resources/filelist.h
screenshots/* *.cbp
release/*
*.mod
*.id*
*.nam
*.til
*.layout

4
.gitmodules vendored
View File

@ -1,4 +0,0 @@
[submodule "src/mocha"]
path = src/mocha
url = https://github.com/Maschell/mocha
branch = sd_access

322
Makefile
View File

@ -1,270 +1,164 @@
DO_LOGGING := 1 #-------------------------------------------------------------------------------
#---------------------------------------------------------------------------------
# Clear the implicit built in rules
#---------------------------------------------------------------------------------
.SUFFIXES: .SUFFIXES:
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPPC)),)
$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=<path to>devkitPPC")
endif
ifeq ($(strip $(DEVKITPRO)),) ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>devkitPRO") $(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif endif
export PATH := $(DEVKITPPC)/bin:$(PORTLIBS)/bin:$(PATH):$(DEVKITPRO)/tools/bin TOPDIR ?= $(CURDIR)
export PORTLIBS := $(DEVKITPRO)/portlibs/ppc
PREFIX := powerpc-eabi- include $(DEVKITPRO)/wut/share/wut_rules
export AS := $(PREFIX)as #-------------------------------------------------------------------------------
export CC := $(PREFIX)gcc
export CXX := $(PREFIX)g++
export AR := $(PREFIX)ar
export OBJCOPY := $(PREFIX)objcopy
print-% : ; @echo $* = $($*)
#---------------------------------------------------------------------------------
# TARGET is the name of the output # TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed # BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code # SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files # DATA is a list of directories containing data files
#--------------------------------------------------------------------------------- # INCLUDES is a list of directories containing header files
TARGET := wiiupluginloader #-------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build BUILD := build
BUILD_DBG := $(TARGET)_dbg SOURCES := src \
SOURCES := src/common \
src/custom/gui \ src/custom/gui \
src/libelf \ src/fs \
src/menu/content \ src/game \
src/menu \
src/mymemory \
src/mykernel \
src/myutils \
src/patcher \
src/plugin \ src/plugin \
src/language \
src/menu \
src/menu/content \
src/resources \ src/resources \
src/settings \ src/settings \
src/ src/system \
src/utils
DATA := data/images \ DATA := data \
data/images \
data/sounds \ data/sounds \
data/fonts \ data/fonts
INCLUDES := src
INCLUDES := src/libelf \ #-------------------------------------------------------------------------------
src/
#---------------------------------------------------------------------------------
# options for code generation # options for code generation
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
CFLAGS := -std=gnu11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math \ CFLAGS := -g -Wall -O2 -ffunction-sections \
-O0 -D__wiiu__ -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing -D_GNU_SOURCE $(INCLUDE) $(MACHDEP)
CXXFLAGS := -std=gnu++11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math \
-O0 -D__wiiu__ -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing -D_GNU_SOURCE $(INCLUDE)
ifeq ($(DO_LOGGING), 1) CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__
CFLAGS += -D__LOGGING__
CXXFLAGS += -D__LOGGING__
endif
ASFLAGS := -mregnames CXXFLAGS := $(CFLAGS)
LDFLAGS := -nostartfiles -Wl,-Map,$(notdir $@).map,-wrap,malloc,-wrap,free,-wrap,memalign,-wrap,calloc,-wrap,realloc,-wrap,malloc_usable_size,-wrap,_malloc_r,-wrap,_free_r,-wrap,_realloc_r,-wrap,_calloc_r,-wrap,_memalign_r,-wrap,_malloc_usable_size_r,-wrap,valloc,-wrap,_valloc_r,-wrap,_pvalloc_r,--gc-sections
#--------------------------------------------------------------------------------- ASFLAGS := -g $(ARCH)
Q := @ LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map)
MAKEFLAGS += --no-print-directory
#---------------------------------------------------------------------------------
# any extra libraries we wish to link with the project
#---------------------------------------------------------------------------------
LIBS := -lgui -lm -lgcc -lfat -liosuhax -lutils -ldynamiclibs -lfreetype -lgd -lpng -ljpeg -lz -lmad -lvorbisidec -logg -lbz2
#--------------------------------------------------------------------------------- LIBS := -lgui -lfreetype -lgd -lpng -ljpeg -lz -lmad -lvorbisidec -logg -lbz2 -lwut
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(CURDIR) \
$(DEVKITPPC)/lib \
$(DEVKITPRO)/wups
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level
# containing include and lib
#-------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(WUT_ROOT)
#-------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional # no real need to edit anything past this point unless you need to add additional
# rules for different file extensions # rules for different file extensions
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR))) ifneq ($(BUILD),$(notdir $(CURDIR)))
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
export PROJECTDIR := $(CURDIR)
export OUTPUT := $(CURDIR)/$(TARGETDIR)/$(TARGET)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
#---------------------------------------------------------------------------------
# automatically build a list of object files for our project
#---------------------------------------------------------------------------------
FILELIST := $(shell bash ./filelist.sh) FILELIST := $(shell bash ./filelist.sh)
LANGUAGES := $(shell bash ./updatelang.sh)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
TTFFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.ttf)))
PNGFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.png)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
export LD := $(CC)
else
export LD := $(CXX)
endif
export OFILES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \
$(sFILES:.s=.o) $(SFILES:.S=.o) \
$(PNGFILES:.png=.png.o) $(addsuffix .o,$(BINFILES))
#---------------------------------------------------------------------------------
# build a list of include paths
#---------------------------------------------------------------------------------
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(PORTLIBS)/include -I$(CURDIR)/$(BUILD) \
-I$(PORTLIBS)/include/libutils \
-I$(PORTLIBS)/include/freetype2 -I$(PORTLIBS)/include/libgui
#---------------------------------------------------------------------------------
# build a list of library paths
#---------------------------------------------------------------------------------
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \
-L$(PORTLIBS)/lib
export OUTPUT := $(CURDIR)/$(TARGET) export OUTPUT := $(CURDIR)/$(TARGET)
.PHONY: $(BUILD) clean install export TOPDIR := $(CURDIR)
#--------------------------------------------------------------------------------- export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(BUILD): $(CURDIR)/src/mocha/ios_kernel/ios_kernel.bin.h $(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#-------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#-------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#-------------------------------------------------------------------------------
export LD := $(CC)
#-------------------------------------------------------------------------------
else
#-------------------------------------------------------------------------------
export LD := $(CXX)
#-------------------------------------------------------------------------------
endif
#-------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD) -I$(PORTLIBS_PATH)/ppc/include/freetype2
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
.PHONY: $(BUILD) clean all
#-------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@ @[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
$(CURDIR)/src/mocha/ios_kernel/ios_kernel.bin.h: $(CURDIR)/src/mocha/ios_usb/ios_usb.bin.h $(CURDIR)/src/mocha/ios_mcp/ios_mcp.bin.h $(CURDIR)/src/mocha/ios_fs/ios_fs.bin.h $(CURDIR)/src/mocha/ios_bsp/ios_bsp.bin.h $(CURDIR)/src/mocha/ios_acp/ios_acp.bin.h #-------------------------------------------------------------------------------
@$(MAKE) -j1 --no-print-directory -C $(CURDIR)/src/mocha/ios_kernel -f $(CURDIR)/src/mocha/ios_kernel/Makefile
$(CURDIR)/src/mocha/ios_usb/ios_usb.bin.h:
@$(MAKE) -j1 --no-print-directory -C $(CURDIR)/src/mocha/ios_usb -f $(CURDIR)/src/mocha/ios_usb/Makefile
$(CURDIR)/src/mocha/ios_fs/ios_fs.bin.h:
@$(MAKE) -j1 --no-print-directory -C $(CURDIR)/src/mocha/ios_fs -f $(CURDIR)/src/mocha/ios_fs/Makefile
$(CURDIR)/src/mocha/ios_bsp/ios_bsp.bin.h:
@$(MAKE) -j1 --no-print-directory -C $(CURDIR)/src/mocha/ios_bsp -f $(CURDIR)/src/mocha/ios_bsp/Makefile
$(CURDIR)/src/mocha/ios_mcp/ios_mcp.bin.h:
@$(MAKE) -j1 --no-print-directory -C $(CURDIR)/src/mocha/ios_mcp -f $(CURDIR)/src/mocha/ios_mcp/Makefile
$(CURDIR)/src/mocha/ios_acp/ios_acp.bin.h:
@$(MAKE) -j1 --no-print-directory -C $(CURDIR)/src/mocha/ios_acp -f $(CURDIR)/src/mocha/ios_acp/Makefile
#---------------------------------------------------------------------------------
clean: clean:
@echo clean ... @echo clean ...
@rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).bin $(BUILD_DBG).elf @rm -fr $(BUILD) $(TARGET).rpx $(TARGET).elf
@$(MAKE) --no-print-directory -C $(CURDIR)/src/mocha/ios_kernel -f $(CURDIR)/src/mocha/ios_kernel/Makefile clean
@$(MAKE) --no-print-directory -C $(CURDIR)/src/mocha/ios_usb -f $(CURDIR)/src/mocha/ios_usb/Makefile clean
@$(MAKE) --no-print-directory -C $(CURDIR)/src/mocha/ios_fs -f $(CURDIR)/src/mocha/ios_fs/Makefile clean
@$(MAKE) --no-print-directory -C $(CURDIR)/src/mocha/ios_bsp -f $(CURDIR)/src/mocha/ios_bsp/Makefile clean
@$(MAKE) --no-print-directory -C $(CURDIR)/src/mocha/ios_mcp -f $(CURDIR)/src/mocha/ios_mcp/Makefile clean
@$(MAKE) --no-print-directory -C $(CURDIR)/src/mocha/ios_acp -f $(CURDIR)/src/mocha/ios_acp/Makefile clean
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
else else
.PHONY: all
DEPENDS := $(OFILES:.o=.d) DEPENDS := $(OFILES:.o=.d)
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# main targets # main targets
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
$(OUTPUT).elf: $(OFILES) all : $(OUTPUT).rpx
#--------------------------------------------------------------------------------- $(OUTPUT).rpx : $(OUTPUT).elf
# This rule links in binary data with the .jpg extension $(OUTPUT).elf : $(OFILES)
#---------------------------------------------------------------------------------
%.elf: link.ld $(OFILES)
@echo "linking ... $(TARGET).elf"
$(Q)$(LD) -n -T $^ $(LDFLAGS) -o ../$(BUILD_DBG).elf $(LIBPATHS) $(LIBS)
$(Q)$(OBJCOPY) -S -R .comment -R .gnu.attributes ../$(BUILD_DBG).elf $@
#--------------------------------------------------------------------------------- $(OFILES_SRC) : $(HFILES_BIN)
%.a:
#---------------------------------------------------------------------------------
@echo $(notdir $@)
@rm -f $@
@$(AR) -rc $@ $^
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
%.o: %.cpp # you need a rule like this for each extension you use as binary data
#-------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
@echo $(notdir $<) @echo $(notdir $<)
@$(CXX) -MMD -MP -MF $(DEPSDIR)/$*.d $(CXXFLAGS) -c $< -o $@ $(ERROR_FILTER) @$(bin2o)
#--------------------------------------------------------------------------------- %.png.o %_png.h : %.png
%.o: %.c
@echo $(notdir $<) @echo $(notdir $<)
@$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d $(CFLAGS) -c $< -o $@ $(ERROR_FILTER) @$(bin2o)
#--------------------------------------------------------------------------------- %.ogg.o %_ogg.h : %.ogg
%.o: %.S
@echo $(notdir $<) @echo $(notdir $<)
@$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER) @$(bin2o)
#--------------------------------------------------------------------------------- %.mp3.o %_mp3.h : %.mp3
%.o: %.s
@echo $(notdir $<) @echo $(notdir $<)
@$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER) @$(bin2o)
#--------------------------------------------------------------------------------- %.ttf.o %_ttf.h : %.ttf
%.png.o : %.png
@echo $(notdir $<) @echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@) @$(bin2o)
#---------------------------------------------------------------------------------
%.jpg.o : %.jpg
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.ttf.o : %.ttf
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.bin.o : %.bin
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.wav.o : %.wav
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.mp3.o : %.mp3
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.ogg.o : %.ogg
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.tga.o : %.tga
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
-include $(DEPENDS) -include $(DEPENDS)
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
endif endif
#--------------------------------------------------------------------------------- #-------------------------------------------------------------------------------

View File

@ -3,7 +3,7 @@
# Automatic resource file list generation # Automatic resource file list generation
# Created by Dimok # Created by Dimok
outFile="./src/resources/filelist.cpp" outFile="./src/resources/filelist.h"
count_old=$(cat $outFile 2>/dev/null | tr -d '\n\n' | sed 's/[^0-9]*\([0-9]*\).*/\1/') count_old=$(cat $outFile 2>/dev/null | tr -d '\n\n' | sed 's/[^0-9]*\([0-9]*\).*/\1/')
count=0 count=0
@ -29,18 +29,27 @@ fi
if [ "$count_old" != "$count" ] || [ ! -f $outFile ] if [ "$count_old" != "$count" ] || [ ! -f $outFile ]
then then
echo "Generating filelist.c for $count files." >&2 echo "Generating filelist.h for $count files." >&2
cat <<EOF > $outFile cat <<EOF > $outFile
/**************************************************************************** /****************************************************************************
* Resource files. * Loadiine resource files.
* This file is generated automatically. * This file is generated automatically.
* Includes $count files. * Includes $count files.
* *
* NOTE: * NOTE:
* Any manual modification of this file will be overwriten by the generation. * Any manual modification of this file will be overwriten by the generation.
*****************************************************************************/ ****************************************************************************/
#include <resources/filelist.h> #ifndef _FILELIST_H_
#include <stdint.h> #define _FILELIST_H_
typedef struct _RecourceFile
{
const char *filename;
const unsigned char *DefaultFile;
const unsigned int &DefaultFileSize;
unsigned char *CustomFile;
unsigned int CustomFileSize;
} RecourceFile;
EOF EOF
@ -48,12 +57,12 @@ for i in ${files[@]}
do do
filename=${i%.*} filename=${i%.*}
extension=${i##*.} extension=${i##*.}
echo 'extern const uint8_t '$filename'_'$extension'[];' >> $outFile echo 'extern const unsigned char '$filename'_'$extension'[];' >> $outFile
echo 'extern const uint32_t '$filename'_'$extension'_size;' >> $outFile echo 'extern const unsigned int '$filename'_'$extension'_size;' >> $outFile
echo '' >> $outFile echo '' >> $outFile
done done
echo 'static ResourceFile ResourceList[] =' >> $outFile echo 'static RecourceFile RecourceList[] =' >> $outFile
echo '{' >> $outFile echo '{' >> $outFile
for i in ${files[@]} for i in ${files[@]}
@ -65,7 +74,8 @@ done
echo -e '\t{NULL, NULL, 0, NULL, 0}' >> $outFile echo -e '\t{NULL, NULL, 0, NULL, 0}' >> $outFile
echo '};' >> $outFile echo '};' >> $outFile
echo '' >> $outFile echo '' >> $outFile
echo 'ResourceFile * getResourceList(){ return ResourceList; }' >> $outFile echo '#endif' >> $outFile
echo '' >> $outFile
fi fi

View File

@ -1,19 +0,0 @@
#! /bin/bash
#
7z x -y ./libs/portlibs.zip -o${DEVKITPRO}
mkdir portlib_repos
cd portlib_repos
((git clone https://github.com/Maschell/dynamic_libs.git -b lib && (7z x -y ./dynamic_libs/libs/portlibs.zip -o${DEVKITPRO})) || (cd dynamic_libs && git pull))
(git clone https://github.com/dimok789/libiosuhax.git || (cd libiosuhax && git pull))
(git clone https://github.com/Maschell/libfat.git || (cd libfat && git pull))
(git clone https://github.com/Maschell/libutils.git || (cd libutils && git pull))
((git clone https://github.com/Maschell/libgui.git && (7z x -y ./libgui/libs/portlibs.zip -o${DEVKITPRO})) || (cd libgui && git pull))
(git clone https://github.com/Maschell/fs_wrapper.git || (cd fs_wrapper && git pull))
(git clone https://github.com/Maschell/controller_patcher.git || (cd controller_patcher && git pull))
(cd dynamic_libs && ((make -j8 | grep -c "built ... ") && make install && echo "installed" ) || (echo "no need for make install" && make))
(cd libiosuhax && make -j8 && make install)
(cd libfat && make wiiu-release && make wiiu-install)
(cd libutils && ((make -j8 | grep -c "built ... ") && make install && echo "installed" ) || (echo "no need for make install" && make))
(cd libgui && ((make -j8 | grep -c "built ... ") && make install) || echo "no need for make install")
(cd fs_wrapper && ((make -j8 | grep -c "built ... ") && make install && echo "installed" ) || (echo "no need for make install" && make))
(cd controller_patcher && ((make -j8 | grep -c "built ... ") && make install && echo "installed" ) || (echo "no need for make install" && make))

Binary file not shown.

View File

@ -17,41 +17,46 @@
****************************************************************************/ ****************************************************************************/
#include "Application.h" #include "Application.h"
#include "common/common.h" #include "common/common.h"
#include <dynamic_libs/os_functions.h> #include <coreinit/core.h>
#include <coreinit/foreground.h>
#include <proc_ui/procui.h>
#include <sysapp/launch.h>
#include <gui/FreeTypeGX.h> #include <gui/FreeTypeGX.h>
#include <gui/VPadController.h> #include <gui/VPadController.h>
#include <gui/WPadController.h> #include <gui/WPadController.h>
#include "system/memory.h"
#include "resources/Resources.h" #include "resources/Resources.h"
#include <sounds/SoundHandler.hpp> #include <gui/sounds/SoundHandler.hpp>
#include <utils/logger.h> #include <utils/logger.h>
#include "settings/CSettings.h" #include "settings/CSettings.h"
#include "myutils/TcpReceiver.h" #include "utils/TcpReceiver.h"
#include "mymemory/memory_mapping.h"
Application *Application::applicationInstance = NULL; Application *Application::applicationInstance = NULL;
bool Application::exitApplication = false; bool Application::exitApplication = false;
bool Application::quitRequest = false;
Application::Application() Application::Application()
: CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff, 0, 0x20000) : CThread(CThread::eAttributeAffCore1 | CThread::eAttributePinnedAff, 0, 0x20000)
, bgMusic(NULL) , bgMusic(NULL)
, video(NULL) , video(NULL)
, mainWindow(NULL) , mainWindow(NULL)
, exitCode(EXIT_RELAUNCH_ON_LOAD) { , fontSystem(NULL)
, exitCode(0) {
controller[0] = new VPadController(GuiTrigger::CHANNEL_1); controller[0] = new VPadController(GuiTrigger::CHANNEL_1);
controller[1] = new WPadController(GuiTrigger::CHANNEL_2); controller[1] = new WPadController(GuiTrigger::CHANNEL_2);
controller[2] = new WPadController(GuiTrigger::CHANNEL_3); controller[2] = new WPadController(GuiTrigger::CHANNEL_3);
controller[3] = new WPadController(GuiTrigger::CHANNEL_4); controller[3] = new WPadController(GuiTrigger::CHANNEL_4);
controller[4] = new WPadController(GuiTrigger::CHANNEL_5); controller[4] = new WPadController(GuiTrigger::CHANNEL_5);
CSettings::instance()->Load();
//! create bgMusic //! create bgMusic
bgMusic = new GuiSound(Resources::GetFile("bgMusic.mp3"), Resources::GetFileSize("bgMusic.mp3")); bgMusic = new GuiSound(Resources::GetFile("bgMusic.mp3"), Resources::GetFileSize("bgMusic.mp3"));
bgMusic->SetLoop(true);
//! load language bgMusic->Play();
loadLanguageFromConfig(); bgMusic->SetVolume(50);
exitApplication = false; exitApplication = false;
ProcUIInit(OSSavesDone_ReadyToRelease);
} }
Application::~Application() { Application::~Application() {
@ -70,7 +75,7 @@ Application::~Application() {
AsyncDeleter::triggerDeleteProcess(); AsyncDeleter::triggerDeleteProcess();
while(!AsyncDeleter::realListEmpty()) { while(!AsyncDeleter::realListEmpty()) {
DEBUG_FUNCTION_LINE("Waiting...\n"); DEBUG_FUNCTION_LINE("Waiting...\n");
os_usleep(1000); OSSleepTicks(OSMicrosecondsToTicks(1000));
} }
} while(!AsyncDeleter::deleteListEmpty()); } while(!AsyncDeleter::deleteListEmpty());
AsyncDeleter::destroyInstance(); AsyncDeleter::destroyInstance();
@ -80,6 +85,8 @@ Application::~Application() {
DEBUG_FUNCTION_LINE("Stop sound handler\n"); DEBUG_FUNCTION_LINE("Stop sound handler\n");
SoundHandler::DestroyInstance(); SoundHandler::DestroyInstance();
ProcUIShutdown();
} }
int32_t Application::exec() { int32_t Application::exec() {
@ -91,15 +98,12 @@ int32_t Application::exec() {
return exitCode; return exitCode;
} }
void Application::reloadUI() {
reloadUIflag = true;
}
void Application::fadeOut() { void Application::fadeOut() {
GuiImage fadeOut(video->getTvWidth(), video->getTvHeight(), (GX2Color) { GuiImage fadeOut(video->getTvWidth(), video->getTvHeight(), (GX2Color) {
0, 0, 0, 255 0, 0, 0, 255
}); });
for(int32_t i = 0; i < 255; i += 10) { for(int i = 0; i < 255; i += 10) {
if(i > 255) if(i > 255)
i = 255; i = 255;
@ -109,9 +113,9 @@ void Application::fadeOut() {
video->prepareDrcRendering(); video->prepareDrcRendering();
mainWindow->drawDrc(video); mainWindow->drawDrc(video);
GX2SetDepthOnlyControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_ALWAYS); GX2SetDepthOnlyControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_FUNC_ALWAYS);
fadeOut.draw(video); fadeOut.draw(video);
GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_LEQUAL); GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL);
video->drcDrawDone(); video->drcDrawDone();
@ -120,9 +124,9 @@ void Application::fadeOut() {
mainWindow->drawTv(video); mainWindow->drawTv(video);
GX2SetDepthOnlyControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_ALWAYS); GX2SetDepthOnlyControl(GX2_DISABLE, GX2_DISABLE, GX2_COMPARE_FUNC_ALWAYS);
fadeOut.draw(video); fadeOut.draw(video);
GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_LEQUAL); GX2SetDepthOnlyControl(GX2_ENABLE, GX2_ENABLE, GX2_COMPARE_FUNC_LEQUAL);
video->tvDrawDone(); video->tvDrawDone();
@ -142,10 +146,48 @@ void Application::fadeOut() {
video->drcEnable(false); video->drcEnable(false);
} }
void Application::executeThread(void) { bool Application::procUI(void) {
DEBUG_FUNCTION_LINE("Initialize video\n"); bool executeProcess = false;
video = new CVideo(GX2_TV_SCAN_MODE_720P, GX2_DRC_SINGLE);
switch(ProcUIProcessMessages(true)) {
case PROCUI_STATUS_EXITING: {
DEBUG_FUNCTION_LINE("PROCUI_STATUS_EXITING\n");
exitCode = EXIT_SUCCESS;
exitApplication = true;
break;
}
case PROCUI_STATUS_RELEASE_FOREGROUND: {
DEBUG_FUNCTION_LINE("PROCUI_STATUS_RELEASE_FOREGROUND\n");
if(video != NULL) {
// we can turn of the screen but we don't need to and it will display the last image
video->tvEnable(true);
video->drcEnable(true);
DEBUG_FUNCTION_LINE("delete fontSystem\n");
delete fontSystem;
fontSystem = NULL;
DEBUG_FUNCTION_LINE("delete video\n");
delete video;
video = NULL;
DEBUG_FUNCTION_LINE("deinitialze memory\n");
memoryRelease();
ProcUIDrawDoneRelease();
} else {
ProcUIDrawDoneRelease();
}
break;
}
case PROCUI_STATUS_IN_FOREGROUND: {
if(!quitRequest) {
if(video == NULL) {
DEBUG_FUNCTION_LINE("PROCUI_STATUS_IN_FOREGROUND\n");
DEBUG_FUNCTION_LINE("initialze memory\n");
memoryInitialize();
DEBUG_FUNCTION_LINE("Initialize video\n");
video = new CVideo(GX2_TV_SCAN_MODE_720P, GX2_DRC_RENDER_MODE_SINGLE);
DEBUG_FUNCTION_LINE("Video size %i x %i\n", video->getTvWidth(), video->getTvHeight()); DEBUG_FUNCTION_LINE("Video size %i x %i\n", video->getTvWidth(), video->getTvHeight());
//! setup default Font //! setup default Font
@ -153,60 +195,54 @@ void Application::executeThread(void) {
FreeTypeGX *fontSystem = new FreeTypeGX(Resources::GetFile("font.ttf"), Resources::GetFileSize("font.ttf"), true); FreeTypeGX *fontSystem = new FreeTypeGX(Resources::GetFile("font.ttf"), Resources::GetFileSize("font.ttf"), true);
GuiText::setPresetFont(fontSystem); GuiText::setPresetFont(fontSystem);
reloadUIflag = true; if(mainWindow == NULL) {
if(bgMusic != NULL) { DEBUG_FUNCTION_LINE("Initialize main window\n");
bgMusic->SetLoop(true); Application::loadLanguageFromConfig();
bgMusic->SetVolume(50); mainWindow = MainWindow::getInstance(video->getTvWidth(), video->getTvHeight());
bgMusic->Stop(); //CHANG MEEEEEEEEEEEEEEEEEEE
} }
}
executeProcess = true;
}
break;
}
case PROCUI_STATUS_IN_BACKGROUND:
default:
break;
}
while(reloadUIflag) { return executeProcess;
reloadUIflag = false; }
exitCode = EXIT_RELAUNCH_ON_LOAD;
DEBUG_FUNCTION_LINE("Initialize the language\n");
loadLanguageFromConfig();
DEBUG_FUNCTION_LINE("Initialize main window\n");
mainWindow = MainWindow::getInstance(video->getTvWidth(), video->getTvHeight());
exitApplication = false; void Application::executeThread(void) {
//! main GX2 loop (60 Hz cycle with max priority on core 1)
DEBUG_FUNCTION_LINE("Starting TcpReceiver\n");
TcpReceiver pluginReceiver(4299);
DEBUG_FUNCTION_LINE("Entering main loop\n"); DEBUG_FUNCTION_LINE("Entering main loop\n");
while(!exitApplication && !reloadUIflag) {
//! main GX2 loop (60 Hz cycle with max priority on core 1)
while(!exitApplication) {
if(procUI() == false)
continue;
//! Read out inputs //! Read out inputs
for(int32_t i = 0; i < 5; i++) { for(int i = 0; i < 5; i++) {
if(controller[i]->update(video->getTvWidth(), video->getTvHeight()) == false) if(controller[i]->update(video->getTvWidth(), video->getTvHeight()) == false)
continue; continue;
if(controller[i]->data.buttons_d & VPAD_BUTTON_PLUS) { if(controller[i]->data.buttons_d & VPAD_BUTTON_PLUS) {
exitCode = APPLICATION_CLOSE_APPLY;
if(linkPluginsCallback != NULL) { if(linkPluginsCallback != NULL) {
bool result = linkPluginsCallback(); bool result = linkPluginsCallback();
if(!result) { if(!result) {
// On linking errors return to the HBL. // On linking errors return to the HBL.
#warning TODO: proper error handling when linking fails. #warning TODO: proper error handling when linking fails.
exitCode = APPLICATION_CLOSE_MIIMAKER;
} }
} }
exitApplication = true; SYSLaunchMenu();
} //quit(0);
if(controller[i]->data.buttons_d & VPAD_BUTTON_MINUS) {
exitCode = APPLICATION_CLOSE_APPLY_MEMORY;
exitApplication = true;
}
if(controller[i]->data.buttons_d & VPAD_BUTTON_HOME) {
exitCode = APPLICATION_CLOSE_MIIMAKER;
exitApplication = true;
} }
//! update controller states //! update controller states
mainWindow->update(controller[i]); mainWindow->update(controller[i]);
} }
mainWindow->process(); mainWindow->process();
//! start rendering DRC //! start rendering DRC
@ -225,7 +261,6 @@ void Application::executeThread(void) {
video->drcEnable(true); video->drcEnable(true);
} }
//! as last point update the effects as it can drop elements //! as last point update the effects as it can drop elements
mainWindow->updateEffects(); mainWindow->updateEffects();
@ -236,15 +271,26 @@ void Application::executeThread(void) {
//! and avoid blocking the GUI thread //! and avoid blocking the GUI thread
AsyncDeleter::triggerDeleteProcess(); AsyncDeleter::triggerDeleteProcess();
} }
DEBUG_FUNCTION_LINE("Fading out\n");
//! in case we exit to a homebrew let's smoothly fade out
if(video) {
fadeOut(); fadeOut();
DEBUG_FUNCTION_LINE("Destroying the MainWindow\n");
MainWindow::destroyInstance();
} }
DEBUG_FUNCTION_LINE("Delete fontSystem\n");
DEBUG_FUNCTION_LINE("delete mainWindow\n");
MainWindow::destroyInstance();
mainWindow = NULL;
DEBUG_FUNCTION_LINE("delete fontSystem\n");
delete fontSystem; delete fontSystem;
DEBUG_FUNCTION_LINE("Delete video\n"); fontSystem = NULL;
DEBUG_FUNCTION_LINE("delete video\n");
delete video; delete video;
video = NULL;
DEBUG_FUNCTION_LINE("deinitialze memory\n");
memoryRelease();
} }
void Application::loadLanguageFromConfig() { void Application::loadLanguageFromConfig() {

View File

@ -20,8 +20,9 @@
#include "menu/MainWindow.h" #include "menu/MainWindow.h"
#include <functional> #include <functional>
#include <video/CVideo.h> #include <gui/video/CVideo.h>
#include <system/CThread.h> #include <system/CThread.h>
#include "utils/logger.h"
#include <language/gettext.h> #include <language/gettext.h>
#define APPLICATION_CLOSE_APPLY 1 #define APPLICATION_CLOSE_APPLY 1
@ -61,6 +62,7 @@ public:
void quit(int32_t code) { void quit(int32_t code) {
exitCode = code; exitCode = code;
exitApplication = true; exitApplication = true;
quitRequest = true;
} }
void setLinkPluginsCallback(std::function<bool(void)> fun) { void setLinkPluginsCallback(std::function<bool(void)> fun) {
@ -69,23 +71,24 @@ public:
} }
private: private:
Application(); Application();
virtual ~Application(); virtual ~Application();
bool procUI(void);
static Application *applicationInstance; static Application *applicationInstance;
static bool exitApplication; static bool exitApplication;
static bool quitRequest;
void executeThread(void); void executeThread(void);
void loadLanguageFromConfig(); void loadLanguageFromConfig();
bool reloadUIflag = false;
GuiSound *bgMusic; GuiSound *bgMusic;
CVideo *video; CVideo *video;
MainWindow *mainWindow; MainWindow *mainWindow;
FreeTypeGX *fontSystem;
GuiController *controller[5]; GuiController *controller[5];
int32_t exitCode; int exitCode;
std::function<bool(void)> linkPluginsCallback = NULL; std::function<bool(void)> linkPluginsCallback = NULL;
}; };

View File

@ -5,8 +5,6 @@
extern "C" { extern "C" {
#endif #endif
#include <dynamic_libs/os_defs.h>
#define CAFE_OS_SD_PATH "/vol/external01" #define CAFE_OS_SD_PATH "/vol/external01"
#define WIIU_PATH "/wiiu" #define WIIU_PATH "/wiiu"
#define SD_PATH "sd:" #define SD_PATH "sd:"
@ -15,16 +13,6 @@ extern "C" {
#define NAME_PREFIX_SD "sd: " #define NAME_PREFIX_SD "sd: "
#define NAME_PREFIX_USB "usb:" #define NAME_PREFIX_USB "usb:"
#define ELF_DATA_ADDR (*(volatile uint32_t*)(MEM_BASE + 0x1300 + 0x00))
#define ELF_DATA_SIZE (*(volatile uint32_t*)(MEM_BASE + 0x1300 + 0x04))
#define MAIN_ENTRY_ADDR (*(volatile uint32_t*)(MEM_BASE + 0x1400 + 0x00))
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#define EXIT_HBL_EXIT 0xFFFFFFFE
#define EXIT_RELAUNCH_ON_LOAD 0xFFFFFFFD
#define DEFAULT_WUPSLOADER_PATH SD_PATH WIIU_PATH "/apps/wiiupluginsystem" #define DEFAULT_WUPSLOADER_PATH SD_PATH WIIU_PATH "/apps/wiiupluginsystem"
#define DEFAULT_LANG_PATH DEFAULT_WUPSLOADER_PATH "/languages" #define DEFAULT_LANG_PATH DEFAULT_WUPSLOADER_PATH "/languages"
#define LANGUAGE_FILE_EXT ".lang" #define LANGUAGE_FILE_EXT ".lang"

View File

@ -1,26 +0,0 @@
#include "retain_vars.h"
#include "myutils/overlay_helper.h"
replacement_data_t gbl_replacement_data __attribute__((section(".data")));
dyn_linking_relocation_data_t gbl_dyn_linking_data __attribute__((section(".data")));
uint8_t gAppStatus __attribute__((section(".data"))) = 0;
bool g_NotInLoader __attribute__((section(".data"))) = false;
uint64_t gGameTitleID __attribute__((section(".data"))) = 0;
volatile uint8_t gSDInitDone __attribute__((section(".data"))) = 0;
void * ntfs_mounts __attribute__((section(".data"))) = NULL;
int32_t ntfs_mount_count __attribute__((section(".data"))) = 0;
struct buffer_store drc_store __attribute__((section(".data")));
struct buffer_store tv_store __attribute__((section(".data")));
char gbl_common_data[0x20000] __attribute__((section(".data")));
char * gbl_common_data_ptr __attribute__((section(".data"))) = gbl_common_data;
GX2ColorBuffer g_vid_main_cbuf __attribute__((section(".data")));
GX2Texture g_vid_drcTex __attribute__((section(".data")));
GX2Sampler g_vid_sampler __attribute__((section(".data")));
GX2Texture g_vid_tvTex __attribute__((section(".data")));
GX2ContextState* g_vid_ownContextState __attribute__((section(".data")));
GX2ContextState* g_vid_originalContextSave __attribute__((section(".data")))= NULL;

View File

@ -1,31 +0,0 @@
#ifndef RETAINS_VARS_H_
#define RETAINS_VARS_H_
#include "patcher/function_patcher.h"
#include "plugin/dynamic_linking_defines.h"
#include <dynamic_libs/gx2_functions.h>
extern replacement_data_t gbl_replacement_data;
extern dyn_linking_relocation_data_t gbl_dyn_linking_data;
extern bool g_NotInLoader;
extern uint8_t gAppStatus;
extern uint64_t gGameTitleID;
extern volatile uint8_t gSDInitDone;
extern void * ntfs_mounts;
extern int32_t ntfs_mount_count;
extern struct buffer_store drc_store;
extern struct buffer_store tv_store;
extern GX2ColorBuffer g_vid_main_cbuf;
extern GX2Texture g_vid_drcTex;
extern GX2Texture g_vid_tvTex;
extern GX2ContextState* g_vid_ownContextState;
extern GX2ContextState* g_vid_originalContextSave;
extern GX2Sampler g_vid_sampler;
#endif // RETAINS_VARS_H_

View File

@ -1,7 +1,7 @@
#include <string.h> #include <string.h>
#include "main.h" #include "main.h"
int32_t __entry_menu(int32_t argc, char **argv) { int32_t main(int32_t argc, char **argv) {
//! ******************************************************************* //! *******************************************************************
//! * Jump to our application * //! * Jump to our application *
//! ******************************************************************* //! *******************************************************************

172
src/fs/CFile.cpp Normal file
View File

@ -0,0 +1,172 @@
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <fs/CFile.hpp>
CFile::CFile() {
iFd = -1;
mem_file = NULL;
filesize = 0;
pos = 0;
}
CFile::CFile(const std::string & filepath, eOpenTypes mode) {
iFd = -1;
this->open(filepath, mode);
}
CFile::CFile(const uint8_t * mem, int32_t size) {
iFd = -1;
this->open(mem, size);
}
CFile::~CFile() {
this->close();
}
int32_t CFile::open(const std::string & filepath, eOpenTypes mode) {
this->close();
int32_t openMode = 0;
switch(mode) {
default:
case ReadOnly:
openMode = O_RDONLY;
break;
case WriteOnly:
openMode = O_WRONLY;
break;
case ReadWrite:
openMode = O_RDWR;
break;
case Append:
openMode = O_APPEND | O_WRONLY;
break;
}
//! Using fopen works only on the first launch as expected
//! on the second launch it causes issues because we don't overwrite
//! the .data sections which is needed for a normal application to re-init
//! this will be added with launching as RPX
iFd = ::open(filepath.c_str(), openMode);
if(iFd < 0)
return iFd;
filesize = ::lseek(iFd, 0, SEEK_END);
::lseek(iFd, 0, SEEK_SET);
return 0;
}
int32_t CFile::open(const uint8_t * mem, int32_t size) {
this->close();
mem_file = mem;
filesize = size;
return 0;
}
void CFile::close() {
if(iFd >= 0)
::close(iFd);
iFd = -1;
mem_file = NULL;
filesize = 0;
pos = 0;
}
int32_t CFile::read(uint8_t * ptr, size_t size) {
if(iFd >= 0) {
int32_t ret = ::read(iFd, ptr,size);
if(ret > 0)
pos += ret;
return ret;
}
int32_t readsize = size;
if(readsize > (int64_t) (filesize-pos))
readsize = filesize-pos;
if(readsize <= 0)
return readsize;
if(mem_file != NULL) {
memcpy(ptr, mem_file+pos, readsize);
pos += readsize;
return readsize;
}
return -1;
}
int32_t CFile::write(const uint8_t * ptr, size_t size) {
if(iFd >= 0) {
size_t done = 0;
while(done < size) {
int32_t ret = ::write(iFd, ptr, size - done);
if(ret <= 0)
return ret;
ptr += ret;
done += ret;
pos += ret;
}
return done;
}
return -1;
}
int32_t CFile::seek(long int offset, int32_t origin) {
int32_t ret = 0;
int64_t newPos = pos;
if(origin == SEEK_SET) {
newPos = offset;
} else if(origin == SEEK_CUR) {
newPos += offset;
} else if(origin == SEEK_END) {
newPos = filesize+offset;
}
if(newPos < 0) {
pos = 0;
} else {
pos = newPos;
}
if(iFd >= 0)
ret = ::lseek(iFd, pos, SEEK_SET);
if(mem_file != NULL) {
if(pos > filesize) {
pos = filesize;
}
}
return ret;
}
int32_t CFile::fwrite(const char *format, ...) {
char tmp[512];
tmp[0] = 0;
int32_t result = -1;
va_list va;
va_start(va, format);
if((vsprintf(tmp, format, va) >= 0)) {
result = this->write((uint8_t *)tmp, strlen(tmp));
}
va_end(va);
return result;
}

61
src/fs/CFile.hpp Normal file
View File

@ -0,0 +1,61 @@
#ifndef CFILE_HPP_
#define CFILE_HPP_
#include <stdio.h>
#include <string>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <wut_types.h>
class CFile {
public:
enum eOpenTypes {
ReadOnly,
WriteOnly,
ReadWrite,
Append
};
CFile();
CFile(const std::string & filepath, eOpenTypes mode);
CFile(const uint8_t * memory, int32_t memsize);
virtual ~CFile();
int32_t open(const std::string & filepath, eOpenTypes mode);
int32_t open(const uint8_t * memory, int32_t memsize);
BOOL isOpen() const {
if(iFd >= 0)
return true;
if(mem_file)
return true;
return false;
}
void close();
int32_t read(uint8_t * ptr, size_t size);
int32_t write(const uint8_t * ptr, size_t size);
int32_t fwrite(const char *format, ...);
int32_t seek(long int offset, int32_t origin);
uint64_t tell() {
return pos;
};
uint64_t size() {
return filesize;
};
void rewind() {
this->seek(0, SEEK_SET);
};
protected:
int32_t iFd;
const uint8_t * mem_file;
uint64_t filesize;
uint64_t pos;
};
#endif

213
src/fs/DirList.cpp Normal file
View File

@ -0,0 +1,213 @@
/****************************************************************************
* Copyright (C) 2010
* by Dimok
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you
* must not claim that you wrote the original software. If you use
* this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and
* must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* DirList Class
* for WiiXplorer 2010
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <strings.h>
#include <algorithm>
#include <sys/stat.h>
#include <sys/dirent.h>
#include <fs/DirList.h>
#include <utils/StringTools.h>
DirList::DirList() {
Flags = 0;
Filter = 0;
Depth = 0;
}
DirList::DirList(const std::string & path, const char *filter, uint32_t flags, uint32_t maxDepth) {
this->LoadPath(path, filter, flags, maxDepth);
this->SortList();
}
DirList::~DirList() {
ClearList();
}
BOOL DirList::LoadPath(const std::string & folder, const char *filter, uint32_t flags, uint32_t maxDepth) {
if(folder.empty()) return false;
Flags = flags;
Filter = filter;
Depth = maxDepth;
std::string folderpath(folder);
uint32_t length = folderpath.size();
//! clear path of double slashes
StringTools::RemoveDoubleSlashs(folderpath);
//! remove last slash if exists
if(length > 0 && folderpath[length-1] == '/')
folderpath.erase(length-1);
//! add root slash if missing
if(folderpath.find('/') == std::string::npos) {
folderpath += '/';
}
return InternalLoadPath(folderpath);
}
BOOL DirList::InternalLoadPath(std::string &folderpath) {
if(folderpath.size() < 3)
return false;
struct dirent *dirent = NULL;
DIR *dir = NULL;
dir = opendir(folderpath.c_str());
if (dir == NULL)
return false;
while ((dirent = readdir(dir)) != 0) {
BOOL isDir = dirent->d_type & DT_DIR;
const char *filename = dirent->d_name;
if(isDir) {
if(strcmp(filename,".") == 0 || strcmp(filename,"..") == 0)
continue;
if((Flags & CheckSubfolders) && (Depth > 0)) {
int32_t length = folderpath.size();
if(length > 2 && folderpath[length-1] != '/') {
folderpath += '/';
}
folderpath += filename;
Depth--;
InternalLoadPath(folderpath);
folderpath.erase(length);
Depth++;
}
if(!(Flags & Dirs))
continue;
} else if(!(Flags & Files)) {
continue;
}
if(Filter) {
char * fileext = strrchr(filename, '.');
if(!fileext)
continue;
if(StringTools::strtokcmp(fileext, Filter, ",") == 0)
AddEntrie(folderpath, filename, isDir);
} else {
AddEntrie(folderpath, filename, isDir);
}
}
closedir(dir);
return true;
}
void DirList::AddEntrie(const std::string &filepath, const char * filename, BOOL isDir) {
if(!filename)
return;
int32_t pos = FileInfo.size();
FileInfo.resize(pos+1);
FileInfo[pos].FilePath = (char *) malloc(filepath.size()+strlen(filename)+2);
if(!FileInfo[pos].FilePath) {
FileInfo.resize(pos);
return;
}
sprintf(FileInfo[pos].FilePath, "%s/%s", filepath.c_str(), filename);
FileInfo[pos].isDir = isDir;
}
void DirList::ClearList() {
for(uint32_t i = 0; i < FileInfo.size(); ++i) {
if(FileInfo[i].FilePath) {
free(FileInfo[i].FilePath);
FileInfo[i].FilePath = NULL;
}
}
FileInfo.clear();
std::vector<DirEntry>().swap(FileInfo);
}
const char * DirList::GetFilename(int32_t ind) const {
if (!valid(ind))
return "";
return StringTools::FullpathToFilename(FileInfo[ind].FilePath);
}
static BOOL SortCallback(const DirEntry & f1, const DirEntry & f2) {
if(f1.isDir && !(f2.isDir)) return true;
if(!(f1.isDir) && f2.isDir) return false;
if(f1.FilePath && !f2.FilePath) return true;
if(!f1.FilePath) return false;
if(strcasecmp(f1.FilePath, f2.FilePath) > 0)
return false;
return true;
}
void DirList::SortList() {
if(FileInfo.size() > 1)
std::sort(FileInfo.begin(), FileInfo.end(), SortCallback);
}
void DirList::SortList(BOOL (*SortFunc)(const DirEntry &a, const DirEntry &b)) {
if(FileInfo.size() > 1)
std::sort(FileInfo.begin(), FileInfo.end(), SortFunc);
}
uint64_t DirList::GetFilesize(int32_t index) const {
struct stat st;
const char *path = GetFilepath(index);
if(!path || stat(path, &st) != 0)
return 0;
return st.st_size;
}
int32_t DirList::GetFileIndex(const char *filename) const {
if(!filename)
return -1;
for (uint32_t i = 0; i < FileInfo.size(); ++i) {
if (strcasecmp(GetFilename(i), filename) == 0)
return i;
}
return -1;
}

103
src/fs/DirList.h Normal file
View File

@ -0,0 +1,103 @@
/****************************************************************************
* Copyright (C) 2010
* by Dimok
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you
* must not claim that you wrote the original software. If you use
* this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and
* must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* DirList Class
* for WiiXplorer 2010
***************************************************************************/
#ifndef ___DIRLIST_H_
#define ___DIRLIST_H_
#include <vector>
#include <string>
#include <wut_types.h>
typedef struct {
char * FilePath;
BOOL isDir;
} DirEntry;
class DirList {
public:
//!Constructor
DirList(void);
//!\param path Path from where to load the filelist of all files
//!\param filter A fileext that needs to be filtered
//!\param flags search/filter flags from the enum
DirList(const std::string & path, const char *filter = NULL, uint32_t flags = Files | Dirs, uint32_t maxDepth = 0xffffffff);
//!Destructor
virtual ~DirList();
//! Load all the files from a directory
BOOL LoadPath(const std::string & path, const char *filter = NULL, uint32_t flags = Files | Dirs, uint32_t maxDepth = 0xffffffff);
//! Get a filename of the list
//!\param list index
const char * GetFilename(int32_t index) const;
//! Get the a filepath of the list
//!\param list index
const char *GetFilepath(int32_t index) const {
if (!valid(index)) return "";
else return FileInfo[index].FilePath;
}
//! Get the a filesize of the list
//!\param list index
uint64_t GetFilesize(int32_t index) const;
//! Is index a dir or a file
//!\param list index
BOOL IsDir(int32_t index) const {
if(!valid(index)) return false;
return FileInfo[index].isDir;
};
//! Get the filecount of the whole list
int32_t GetFilecount() const {
return FileInfo.size();
};
//! Sort list by filepath
void SortList();
//! Custom sort command for custom sort functions definitions
void SortList(BOOL (*SortFunc)(const DirEntry &a, const DirEntry &b));
//! Get the index of the specified filename
int32_t GetFileIndex(const char *filename) const;
//! Enum for search/filter flags
enum {
Files = 0x01,
Dirs = 0x02,
CheckSubfolders = 0x08,
};
protected:
// Internal parser
BOOL InternalLoadPath(std::string &path);
//!Add a list entrie
void AddEntrie(const std::string &filepath, const char * filename, BOOL isDir);
//! Clear the list
void ClearList();
//! Check if valid pos is requested
inline BOOL valid(uint32_t pos) const {
return (pos < FileInfo.size());
};
uint32_t Flags;
uint32_t Depth;
const char *Filter;
std::vector<DirEntry> FileInfo;
};
#endif

144
src/fs/FSUtils.cpp Normal file
View File

@ -0,0 +1,144 @@
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <fs/FSUtils.h>
#include <fs/CFile.hpp>
#include <utils/logger.h>
int32_t FSUtils::LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size) {
//! always initialze input
*inbuffer = NULL;
if(size)
*size = 0;
int32_t iFd = open(filepath, O_RDONLY);
if (iFd < 0)
return -1;
uint32_t filesize = lseek(iFd, 0, SEEK_END);
lseek(iFd, 0, SEEK_SET);
uint8_t *buffer = (uint8_t *) malloc(filesize);
if (buffer == NULL) {
close(iFd);
return -2;
}
uint32_t blocksize = 0x4000;
uint32_t done = 0;
int32_t readBytes = 0;
while(done < filesize) {
if(done + blocksize > filesize) {
blocksize = filesize - done;
}
readBytes = read(iFd, buffer + done, blocksize);
if(readBytes <= 0)
break;
done += readBytes;
}
close(iFd);
if (done != filesize) {
free(buffer);
buffer = NULL;
return -3;
}
*inbuffer = buffer;
//! sign is optional input
if(size) {
*size = filesize;
}
return filesize;
}
int32_t FSUtils::CheckFile(const char * filepath) {
if(!filepath)
return 0;
struct stat filestat;
char dirnoslash[strlen(filepath)+2];
snprintf(dirnoslash, sizeof(dirnoslash), "%s", filepath);
while(dirnoslash[strlen(dirnoslash)-1] == '/')
dirnoslash[strlen(dirnoslash)-1] = '\0';
char * notRoot = strrchr(dirnoslash, '/');
if(!notRoot) {
strcat(dirnoslash, "/");
}
if (stat(dirnoslash, &filestat) == 0)
return 1;
return 0;
}
int32_t FSUtils::CreateSubfolder(const char * fullpath) {
if(!fullpath)
return 0;
int32_t result = 0;
char dirnoslash[strlen(fullpath)+1];
strcpy(dirnoslash, fullpath);
int32_t pos = strlen(dirnoslash)-1;
while(dirnoslash[pos] == '/') {
dirnoslash[pos] = '\0';
pos--;
}
if(CheckFile(dirnoslash)) {
return 1;
} else {
char parentpath[strlen(dirnoslash)+2];
strcpy(parentpath, dirnoslash);
char * ptr = strrchr(parentpath, '/');
if(!ptr) {
//!Device root directory (must be with '/')
strcat(parentpath, "/");
struct stat filestat;
if (stat(parentpath, &filestat) == 0)
return 1;
return 0;
}
ptr++;
ptr[0] = '\0';
result = CreateSubfolder(parentpath);
}
if(!result)
return 0;
if (mkdir(dirnoslash, 0777) == -1) {
return 0;
}
return 1;
}
BOOL FSUtils::saveBufferToFile(const char * path, void * buffer, uint32_t size) {
int32_t res = open(path, O_CREAT | O_TRUNC | O_WRONLY);
close(res);
CFile file(path, CFile::WriteOnly);
if (!file.isOpen()) {
DEBUG_FUNCTION_LINE("Failed to open %s\n",path);
return false;
}
file.write((const uint8_t*) buffer,size);
file.close();
return true;
}

16
src/fs/FSUtils.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef __FS_UTILS_H_
#define __FS_UTILS_H_
#include <wut_types.h>
class FSUtils {
public:
static int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size);
//! todo: C++ class
static int32_t CreateSubfolder(const char * fullpath);
static int32_t CheckFile(const char * filepath);
static BOOL saveBufferToFile(const char * path, void * buffer, uint32_t size);
};
#endif // __FS_UTILS_H_

270
src/language/gettext.cpp Normal file
View File

@ -0,0 +1,270 @@
/****************************************************************************
* Copyright (C) 2015 Dimok
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <string>
#include <vector>
#include "language/gettext.h"
#include <fs/CFile.hpp>
#include <utils/StringTools.h>
char* strdup (const char* s)
{
size_t slen = strlen(s);
char* result = (char *) malloc(slen + 1);
if(result == NULL)
{
return NULL;
}
memcpy(result, s, slen+1);
return result;
}
typedef struct _MSG {
uint32_t id;
char* msgstr;
struct _MSG *next;
} MSG;
static MSG *baseMSG = 0;
#define HASHWORDBITS 32
/* Defines the so called `hashpjw' function by P.J. Weinberger
[see Aho/Sethi/Ullman, COMPILERS: Principles, Techniques and Tools,
1986, 1987 Bell Telephone Laboratories, Inc.] */
static inline uint32_t hash_string(const char *str_param) {
uint32_t hval, g;
const char *str = str_param;
/* Compute the hash value for the given string. */
hval = 0;
while (*str != '\0') {
hval <<= 4;
hval += (uint8_t) *str++;
g = hval & ((uint32_t) 0xf << (HASHWORDBITS - 4));
if (g != 0) {
hval ^= g >> (HASHWORDBITS - 8);
hval ^= g;
}
}
return hval;
}
/* Expand some escape sequences found in the argument string. */
static char *
expand_escape(const char *str) {
char *retval, *rp;
const char *cp = str;
retval = (char *) malloc(strlen(str) + 1);
if (retval == NULL) return NULL;
rp = retval;
while (cp[0] != '\0' && cp[0] != '\\')
*rp++ = *cp++;
if (cp[0] == '\0') goto terminate;
do {
/* Here cp[0] == '\\'. */
switch (*++cp) {
case '\"': /* " */
*rp++ = '\"';
++cp;
break;
case 'a': /* alert */
*rp++ = '\a';
++cp;
break;
case 'b': /* backspace */
*rp++ = '\b';
++cp;
break;
case 'f': /* form feed */
*rp++ = '\f';
++cp;
break;
case 'n': /* new line */
*rp++ = '\n';
++cp;
break;
case 'r': /* carriage return */
*rp++ = '\r';
++cp;
break;
case 't': /* horizontal tab */
*rp++ = '\t';
++cp;
break;
case 'v': /* vertical tab */
*rp++ = '\v';
++cp;
break;
case '\\':
*rp = '\\';
++cp;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': {
int ch = *cp++ - '0';
if (*cp >= '0' && *cp <= '7') {
ch *= 8;
ch += *cp++ - '0';
if (*cp >= '0' && *cp <= '7') {
ch *= 8;
ch += *cp++ - '0';
}
}
*rp = ch;
}
break;
default:
*rp = '\\';
break;
}
while (cp[0] != '\0' && cp[0] != '\\')
*rp++ = *cp++;
} while (cp[0] != '\0');
/* Terminate string. */
terminate:
*rp = '\0';
return retval;
}
static MSG *findMSG(uint32_t id) {
MSG *msg;
for (msg = baseMSG; msg; msg = msg->next) {
if (msg->id == id) return msg;
}
return NULL;
}
static MSG *setMSG(const char *msgid, const char *msgstr) {
uint32_t id = hash_string(msgid);
MSG *msg = findMSG(id);
if (!msg) {
msg = (MSG *) malloc(sizeof(MSG));
msg->id = id;
msg->msgstr = NULL;
msg->next = baseMSG;
baseMSG = msg;
}
if (msg) {
if (msgstr) {
if (msg->msgstr) free(msg->msgstr);
//msg->msgstr = strdup(msgstr);
msg->msgstr = expand_escape(msgstr);
}
return msg;
}
return NULL;
}
extern "C" void gettextCleanUp(void) {
while (baseMSG) {
MSG *nextMsg = baseMSG->next;
free(baseMSG->msgstr);
free(baseMSG);
baseMSG = nextMsg;
}
}
extern "C" BOOL gettextLoadLanguage(const char* langFile) {
char *lastID = NULL;
gettextCleanUp();
CFile file(langFile, CFile::ReadOnly);
if (!file.isOpen())
return false;
std::string strBuffer;
strBuffer.resize(file.size());
file.read((uint8_t *) &strBuffer[0], strBuffer.size());
file.close();
//! remove all windows crap signs
size_t position;
while(1) {
position = strBuffer.find('\r');
if(position == std::string::npos)
break;
strBuffer.erase(position, 1);
}
std::vector<std::string> lines = StringTools::stringSplit(strBuffer, "\n");
if(lines.empty())
return false;
for(unsigned int i = 0; i < lines.size(); i++) {
std::string & line = lines[i];
// lines starting with # are comments
if (line[0] == '#')
continue;
else if (strncmp(line.c_str(), "msgid \"", 7) == 0) {
char *msgid, *end;
if (lastID) {
free(lastID);
lastID = NULL;
}
msgid = &line[7];
end = strrchr(msgid, '"');
if (end && end - msgid > 1) {
*end = 0;
lastID = strdup(msgid);
}
} else if (strncmp(line.c_str(), "msgstr \"", 8) == 0) {
char *msgstr, *end;
if (lastID == NULL) continue;
msgstr = &line[8];
end = strrchr(msgstr, '"');
if (end && end - msgstr > 1) {
*end = 0;
setMSG(lastID, msgstr);
}
free(lastID);
lastID = NULL;
}
}
return true;
}
extern "C" const char *gettext(const char *msgid) {
if(!msgid) return NULL;
MSG *msg = findMSG(hash_string(msgid));
if (msg && msg->msgstr) return msg->msgstr;
return msgid;
}

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
* Copyright (C) 2018 Maschell * Copyright (C) 2015 Dimok
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -14,19 +14,31 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/ ****************************************************************************/
#ifndef __MEMORY_UTILS_UTILS_H_ #ifndef _GETTEXT_H_
#define __MEMORY_UTILS_UTILS_H_ #define _GETTEXT_H_
class MemoryUtils { #include <wut_types.h>
public:
static void init();
static void* alloc(uint32_t size, int32_t align); #ifdef __cplusplus
extern "C"
static void free(void * ptr); {
private:
MemoryUtils() {}
~MemoryUtils() {}
};
#endif #endif
#define tr(s) gettext(s)
#define trNOOP(s) s
BOOL gettextLoadLanguage(const char* langFile);
void gettextCleanUp(void);
/*
* input msg = a text in ASCII
* output = the translated msg in utf-8
*/
const char *gettext(const char *msg);
#define tr(s) gettext(s)
#define trNOOP(s) s
#ifdef __cplusplus
}
#endif
#endif /* _GETTEXT_H_ */

View File

@ -1,430 +0,0 @@
/*-
* Copyright (c) 2009 Joseph Koshy
* 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.
*
* $Id: _elftc.h 2495 2012-04-23 05:31:56Z jkoshy $
*/
/**
** Miscellanous definitions needed by multiple components.
**/
#ifndef _ELFTC_H
#define _ELFTC_H
#ifndef NULL
#define NULL ((void *) 0)
#endif
#ifndef offsetof
#define offsetof(T, M) ((int) &((T*) 0) -> M)
#endif
/* --QUEUE-MACROS-- [[ */
/*
* Supply macros missing from <sys/queue.h>
*/
/*
* Copyright (c) 1991, 1993
* 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:
* 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 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 REGENTS 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.
*/
#ifndef STAILQ_CONCAT
#define STAILQ_CONCAT(head1, head2) do { \
if (!STAILQ_EMPTY((head2))) { \
*(head1)->stqh_last = (head2)->stqh_first; \
(head1)->stqh_last = (head2)->stqh_last; \
STAILQ_INIT((head2)); \
} \
} while (/*CONSTCOND*/0)
#endif
#ifndef STAILQ_EMPTY
#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL)
#endif
#ifndef STAILQ_ENTRY
#define STAILQ_ENTRY(type) \
struct { \
struct type *stqe_next; /* next element */ \
}
#endif
#ifndef STAILQ_FIRST
#define STAILQ_FIRST(head) ((head)->stqh_first)
#endif
#ifndef STAILQ_HEAD
#define STAILQ_HEAD(name, type) \
struct name { \
struct type *stqh_first; /* first element */ \
struct type **stqh_last; /* addr of last next element */ \
}
#endif
#ifndef STAILQ_HEAD_INITIALIZER
#define STAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).stqh_first }
#endif
#ifndef STAILQ_FOREACH
#define STAILQ_FOREACH(var, head, field) \
for ((var) = ((head)->stqh_first); \
(var); \
(var) = ((var)->field.stqe_next))
#endif
#ifndef STAILQ_FOREACH_SAFE
#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = STAILQ_FIRST((head)); \
(var) && ((tvar) = STAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#endif
#ifndef STAILQ_INIT
#define STAILQ_INIT(head) do { \
(head)->stqh_first = NULL; \
(head)->stqh_last = &(head)->stqh_first; \
} while (/*CONSTCOND*/0)
#endif
#ifndef STAILQ_INSERT_HEAD
#define STAILQ_INSERT_HEAD(head, elm, field) do { \
if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \
(head)->stqh_last = &(elm)->field.stqe_next; \
(head)->stqh_first = (elm); \
} while (/*CONSTCOND*/0)
#endif
#ifndef STAILQ_INSERT_TAIL
#define STAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.stqe_next = NULL; \
*(head)->stqh_last = (elm); \
(head)->stqh_last = &(elm)->field.stqe_next; \
} while (/*CONSTCOND*/0)
#endif
#ifndef STAILQ_INSERT_AFTER
#define STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL)\
(head)->stqh_last = &(elm)->field.stqe_next; \
(listelm)->field.stqe_next = (elm); \
} while (/*CONSTCOND*/0)
#endif
#ifndef STAILQ_LAST
#define STAILQ_LAST(head, type, field) \
(STAILQ_EMPTY((head)) ? \
NULL : ((struct type *)(void *) \
((char *)((head)->stqh_last) - offsetof(struct type, field))))
#endif
#ifndef STAILQ_NEXT
#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next)
#endif
#ifndef STAILQ_REMOVE
#define STAILQ_REMOVE(head, elm, type, field) do { \
if ((head)->stqh_first == (elm)) { \
STAILQ_REMOVE_HEAD((head), field); \
} else { \
struct type *curelm = (head)->stqh_first; \
while (curelm->field.stqe_next != (elm)) \
curelm = curelm->field.stqe_next; \
if ((curelm->field.stqe_next = \
curelm->field.stqe_next->field.stqe_next) == NULL) \
(head)->stqh_last = &(curelm)->field.stqe_next; \
} \
} while (/*CONSTCOND*/0)
#endif
#ifndef STAILQ_REMOVE_HEAD
#define STAILQ_REMOVE_HEAD(head, field) do { \
if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == \
NULL) \
(head)->stqh_last = &(head)->stqh_first; \
} while (/*CONSTCOND*/0)
#endif
#ifndef TAILQ_FOREACH_SAFE
#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = TAILQ_FIRST((head)); \
(var) && ((tvar) = TAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#endif
/* ]] --QUEUE-MACROS-- */
/*
* VCS Ids.
*/
#ifndef ELFTC_VCSID
#if defined(GEKKO)
#define ELFTC_VCSID(ID) /**/
#endif
#if defined(__wiiu__)
#define ELFTC_VCSID(ID) /**/
#endif
#if defined(__DragonFly__)
#define ELFTC_VCSID(ID) __RCSID(ID)
#endif
#if defined(__FreeBSD__)
#define ELFTC_VCSID(ID) __FBSDID(ID)
#endif
#if defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)
#if defined(__GNUC__)
#define ELFTC_VCSID(ID) __asm__(".ident\t\"" ID "\"")
#else
#define ELFTC_VCSID(ID) /**/
#endif
#endif
#if defined(__minix)
#if defined(__GNUC__)
#define ELFTC_VCSID(ID) __asm__(".ident\t\"" ID "\"")
#else
#define ELFTC_VCSID(ID) /**/
#endif /* __GNU__ */
#endif
#if defined(__NetBSD__)
#define ELFTC_VCSID(ID) __RCSID(ID)
#endif
#if defined(__OpenBSD__)
#if defined(__GNUC__)
#define ELFTC_VCSID(ID) __asm__(".ident\t\"" ID "\"")
#else
#define ELFTC_VCSID(ID) /**/
#endif /* __GNUC__ */
#endif
#endif /* ELFTC_VCSID */
/*
* Provide an equivalent for getprogname(3).
*/
#ifndef ELFTC_GETPROGNAME
#if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__minix) || \
defined(__NetBSD__)
#include <stdlib.h>
#define ELFTC_GETPROGNAME() getprogname()
#endif /* __DragonFly__ || __FreeBSD__ || __minix || __NetBSD__ */
#if defined(__GLIBC__)
/*
* GLIBC based systems have a global 'char *' pointer referencing
* the executable's name.
*/
extern const char *program_invocation_short_name;
#define ELFTC_GETPROGNAME() program_invocation_short_name
#endif /* __GLIBC__ */
#if defined(__OpenBSD__)
extern const char *__progname;
#define ELFTC_GETPROGNAME() __progname
#endif /* __OpenBSD__ */
#endif /* ELFTC_GETPROGNAME */
/**
** Per-OS configuration.
**/
#if defined(GEKKO)
#include <sys/param.h>
#define ELFTC_BYTE_ORDER BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN BIG_ENDIAN
#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
#define roundup2 roundup
#define ELFTC_HAVE_MMAP 0
#define ELFTC_HAVE_STRMODE 0/
#define ELFTC_NEED_BYTEORDER_EXTENSIONS 1
#endif
#if defined(__wiiu__)
#include <sys/param.h>
#define ELFTC_BYTE_ORDER BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN BIG_ENDIAN
#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
#define roundup2 roundup
#define ELFTC_HAVE_MMAP 0
#define ELFTC_HAVE_STRMODE 0/
#define ELFTC_NEED_BYTEORDER_EXTENSIONS 1
#endif
#if defined(__DragonFly__)
#include <osreldate.h>
#include <sys/endian.h>
#define ELFTC_BYTE_ORDER _BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN _LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN _BIG_ENDIAN
#define ELFTC_HAVE_MMAP 1
#endif
#if defined(__GLIBC__)
#include <endian.h>
#define ELFTC_BYTE_ORDER __BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN __LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN __BIG_ENDIAN
#define ELFTC_HAVE_MMAP 1
/*
* Debian GNU/Linux and Debian GNU/kFreeBSD do not have strmode(3).
*/
#define ELFTC_HAVE_STRMODE 0
/* Whether we need to supply {be,le}32dec. */
#define ELFTC_NEED_BYTEORDER_EXTENSIONS 1
#define roundup2 roundup
#endif /* __GLIBC__ */
#if defined(__FreeBSD__)
#include <osreldate.h>
#include <sys/endian.h>
#define ELFTC_BYTE_ORDER _BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN _LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN _BIG_ENDIAN
#define ELFTC_HAVE_MMAP 1
#define ELFTC_HAVE_STRMODE 1
#if __FreeBSD_version <= 900000
#define ELFTC_BROKEN_YY_NO_INPUT 1
#endif
#endif /* __FreeBSD__ */
#if defined(__minix)
#define ELFTC_HAVE_MMAP 0
#endif /* __minix */
#if defined(__NetBSD__)
#include <sys/param.h>
#include <sys/endian.h>
#define ELFTC_BYTE_ORDER _BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN _LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN _BIG_ENDIAN
#define ELFTC_HAVE_MMAP 1
#define ELFTC_HAVE_STRMODE 1
#if __NetBSD_Version__ <= 599002100
/* from src/doc/CHANGES: flex(1): Import flex-2.5.35 [christos 20091025] */
/* and 5.99.21 was from Wed Oct 21 21:28:36 2009 UTC */
# define ELFTC_BROKEN_YY_NO_INPUT 1
#endif
#endif /* __NetBSD __ */
#if defined(__OpenBSD__)
#include <sys/param.h>
#include <sys/endian.h>
#define ELFTC_BYTE_ORDER _BYTE_ORDER
#define ELFTC_BYTE_ORDER_LITTLE_ENDIAN _LITTLE_ENDIAN
#define ELFTC_BYTE_ORDER_BIG_ENDIAN _BIG_ENDIAN
#define ELFTC_HAVE_MMAP 1
#define ELFTC_HAVE_STRMODE 1
#define ELFTC_NEED_BYTEORDER_EXTENSIONS 1
#define roundup2 roundup
#endif /* __OpenBSD__ */
#endif /* _ELFTC_H */

View File

@ -1,223 +0,0 @@
/*-
* Copyright (c) 2006,2008-2011 Joseph Koshy
* 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.
*
* $Id: _libelf.h 2365 2011-12-29 04:36:44Z jkoshy $
*/
#ifndef __LIBELF_H_
#define __LIBELF_H_
#include <sys/queue.h>
#include "_libelf_config.h"
#include "_elftc.h"
/*
* Library-private data structures.
*/
#define LIBELF_MSG_SIZE 256
struct _libelf_globals {
int libelf_arch;
unsigned int libelf_byteorder;
int libelf_class;
int libelf_error;
int libelf_fillchar;
unsigned int libelf_version;
char libelf_msg[LIBELF_MSG_SIZE];
};
extern struct _libelf_globals _libelf;
#define LIBELF_PRIVATE(N) (_libelf.libelf_##N)
#define LIBELF_ELF_ERROR_MASK 0xFF
#define LIBELF_OS_ERROR_SHIFT 8
#define LIBELF_ERROR(E, O) (((E) & LIBELF_ELF_ERROR_MASK) | \
((O) << LIBELF_OS_ERROR_SHIFT))
#define LIBELF_SET_ERROR(E, O) do { \
LIBELF_PRIVATE(error) = LIBELF_ERROR(ELF_E_##E, (O)); \
} while (0)
#define LIBELF_ADJUST_AR_SIZE(S) (((S) + 1U) & ~1U)
/*
* Flags for library internal use. These use the upper 16 bits of the
* `e_flags' field.
*/
#define LIBELF_F_API_MASK 0x00FFFF /* Flags defined by the API. */
#define LIBELF_F_AR_HEADER 0x010000 /* translated header available */
#define LIBELF_F_AR_VARIANT_SVR4 0x020000 /* BSD style ar(1) archive */
#define LIBELF_F_DATA_MALLOCED 0x040000 /* whether data was malloc'ed */
#define LIBELF_F_RAWFILE_MALLOC 0x080000 /* whether e_rawfile was malloc'ed */
#define LIBELF_F_RAWFILE_MMAP 0x100000 /* whether e_rawfile was mmap'ed */
#define LIBELF_F_SHDRS_LOADED 0x200000 /* whether all shdrs were read in */
#define LIBELF_F_SPECIAL_FILE 0x400000 /* non-regular file */
struct _Elf {
int e_activations; /* activation count */
unsigned int e_byteorder; /* ELFDATA* */
int e_class; /* ELFCLASS* */
Elf_Cmd e_cmd; /* ELF_C_* used at creation time */
int e_fd; /* associated file descriptor */
unsigned int e_flags; /* ELF_F_* & LIBELF_F_* flags */
Elf_Kind e_kind; /* ELF_K_* */
Elf *e_parent; /* non-NULL for archive members */
char *e_rawfile; /* uninterpreted bytes */
size_t e_rawsize; /* size of uninterpreted bytes */
unsigned int e_version; /* file version */
/*
* Header information for archive members. See the
* LIBELF_F_AR_HEADER flag.
*/
union {
Elf_Arhdr *e_arhdr; /* translated header */
char *e_rawhdr; /* untranslated header */
} e_hdr;
union {
struct { /* ar(1) archives */
off_t e_next; /* set by elf_rand()/elf_next() */
int e_nchildren;
char *e_rawstrtab; /* file name strings */
size_t e_rawstrtabsz;
char *e_rawsymtab; /* symbol table */
size_t e_rawsymtabsz;
Elf_Arsym *e_symtab;
size_t e_symtabsz;
} e_ar;
struct { /* regular ELF files */
union {
Elf32_Ehdr *e_ehdr32;
Elf64_Ehdr *e_ehdr64;
} e_ehdr;
union {
Elf32_Phdr *e_phdr32;
Elf64_Phdr *e_phdr64;
} e_phdr;
STAILQ_HEAD(, _Elf_Scn) e_scn; /* section list */
size_t e_nphdr; /* number of Phdr entries */
size_t e_nscn; /* number of sections */
size_t e_strndx; /* string table section index */
} e_elf;
} e_u;
};
/*
* The internal descriptor wrapping the "Elf_Data" type.
*/
struct _Libelf_Data {
Elf_Data d_data; /* The exported descriptor. */
Elf_Scn *d_scn; /* The containing section */
unsigned int d_flags;
STAILQ_ENTRY(_Libelf_Data) d_next;
};
struct _Elf_Scn {
union {
Elf32_Shdr s_shdr32;
Elf64_Shdr s_shdr64;
} s_shdr;
STAILQ_HEAD(, _Libelf_Data) s_data; /* translated data */
STAILQ_HEAD(, _Libelf_Data) s_rawdata; /* raw data */
STAILQ_ENTRY(_Elf_Scn) s_next;
struct _Elf *s_elf; /* parent ELF descriptor */
unsigned int s_flags; /* flags for the section as a whole */
size_t s_ndx; /* index# for this section */
uint64_t s_offset; /* managed by elf_update() */
uint64_t s_rawoff; /* original offset in the file */
uint64_t s_size; /* managed by elf_update() */
};
enum {
ELF_TOFILE,
ELF_TOMEMORY
};
#define LIBELF_COPY_U32(DST,SRC,NAME) do { \
if ((SRC)->NAME > UINT_MAX) { \
LIBELF_SET_ERROR(RANGE, 0); \
return (0); \
} \
(DST)->NAME = (SRC)->NAME; \
} while (0)
#define LIBELF_COPY_S32(DST,SRC,NAME) do { \
if ((SRC)->NAME > INT_MAX || \
(SRC)->NAME < INT_MIN) { \
LIBELF_SET_ERROR(RANGE, 0); \
return (0); \
} \
(DST)->NAME = (SRC)->NAME; \
} while (0)
/*
* Function Prototypes.
*/
struct _Libelf_Data *_libelf_allocate_data(Elf_Scn *_s);
Elf *_libelf_allocate_elf(void);
Elf_Scn *_libelf_allocate_scn(Elf *_e, size_t _ndx);
Elf_Arhdr *_libelf_ar_gethdr(Elf *_e);
Elf *_libelf_ar_open(Elf *_e, int _reporterror);
Elf *_libelf_ar_open_member(int _fd, Elf_Cmd _c, Elf *_ar);
int _libelf_ar_get_member(char *_s, size_t _sz, int _base, size_t *_ret);
Elf_Arsym *_libelf_ar_process_bsd_symtab(Elf *_ar, size_t *_dst);
Elf_Arsym *_libelf_ar_process_svr4_symtab(Elf *_ar, size_t *_dst);
unsigned long _libelf_checksum(Elf *_e, int _elfclass);
void *_libelf_ehdr(Elf *_e, int _elfclass, int _allocate);
int _libelf_falign(Elf_Type _t, int _elfclass);
size_t _libelf_fsize(Elf_Type _t, int _elfclass, unsigned int _version,
size_t count);
int (*_libelf_get_translator(Elf_Type _t, int _direction, int _elfclass))
(char *_dst, size_t dsz, char *_src, size_t _cnt, int _byteswap);
void *_libelf_getphdr(Elf *_e, int _elfclass);
void *_libelf_getshdr(Elf_Scn *_scn, int _elfclass);
void _libelf_init_elf(Elf *_e, Elf_Kind _kind);
int _libelf_load_section_headers(Elf *e, void *ehdr);
int _libelf_malign(Elf_Type _t, int _elfclass);
Elf *_libelf_memory(char *_image, size_t _sz, int _reporterror);
size_t _libelf_msize(Elf_Type _t, int _elfclass, unsigned int _version);
void *_libelf_newphdr(Elf *_e, int _elfclass, size_t _count);
Elf *_libelf_open_object(int _fd, Elf_Cmd _c, int _reporterror);
struct _Libelf_Data *_libelf_release_data(struct _Libelf_Data *_d);
Elf *_libelf_release_elf(Elf *_e);
Elf_Scn *_libelf_release_scn(Elf_Scn *_s);
int _libelf_setphnum(Elf *_e, void *_eh, int _elfclass, size_t _phnum);
int _libelf_setshnum(Elf *_e, void *_eh, int _elfclass, size_t _shnum);
int _libelf_setshstrndx(Elf *_e, void *_eh, int _elfclass,
size_t _shstrndx);
Elf_Data *_libelf_xlate(Elf_Data *_d, const Elf_Data *_s,
unsigned int _encoding, int _elfclass, int _direction);
int _libelf_xlate_shtype(uint32_t _sht);
#endif /* __LIBELF_H_ */

View File

@ -1,56 +0,0 @@
/*-
* Copyright (c) 2010 Joseph Koshy
* 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.
*
* $Id: _libelf_ar.h 2032 2011-10-23 09:07:00Z jkoshy $
*/
#ifndef __LIBELF_AR_H_
#define __LIBELF_AR_H_
/*
* Prototypes and declarations needed by libelf's ar(1) archive
* handling code.
*/
#include <ar.h>
#define LIBELF_AR_BSD_EXTENDED_NAME_PREFIX "#1/"
#define LIBELF_AR_BSD_SYMTAB_NAME "__.SYMDEF"
#define LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE \
(sizeof(LIBELF_AR_BSD_EXTENDED_NAME_PREFIX) - 1)
#define IS_EXTENDED_BSD_NAME(NAME) \
(strncmp((NAME), LIBELF_AR_BSD_EXTENDED_NAME_PREFIX, \
LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE) == 0)
char *_libelf_ar_get_string(const char *_buf, size_t _sz, int _rawname,
int _svr4names);
char *_libelf_ar_get_raw_name(const struct ar_hdr *_arh);
char *_libelf_ar_get_translated_name(const struct ar_hdr *_arh, Elf *_ar);
int _libelf_ar_get_number(const char *_buf, size_t _sz, int _base,
size_t *_ret);
#endif /* __LIBELF_AR_H_ */

View File

@ -1,193 +0,0 @@
/*-
* Copyright (c) 2008-2011 Joseph Koshy
* 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.
*
* $Id: _libelf_config.h 2287 2011-12-04 06:45:47Z jkoshy $
*/
#ifdef GEKKO
#define LIBELF_ARCH EM_PPC
#define LIBELF_BYTEORDER ELFDATA2MSB
#define LIBELF_CLASS ELFCLASS32
#endif /* GEKKO */
#ifdef __wiiu__
#define LIBELF_ARCH EM_PPC
#define LIBELF_BYTEORDER ELFDATA2MSB
#define LIBELF_CLASS ELFCLASS32
#endif /* __wiiu__ */
#ifdef __DragonFly__
#if defined(__amd64__)
#define LIBELF_ARCH EM_X86_64
#define LIBELF_BYTEORDER ELFDATA2LSB
#define LIBELF_CLASS ELFCLASS64
#elif defined(__i386__)
#define LIBELF_ARCH EM_386
#define LIBELF_BYTEORDER ELFDATA2LSB
#define LIBELF_CLASS ELFCLASS32
#endif
#endif /* __DragonFly__ */
#ifdef __FreeBSD__
/*
* Define LIBELF_{ARCH,BYTEORDER,CLASS} based on the machine architecture.
* See also: <machine/elf.h>.
*/
#if defined(__amd64__)
#define LIBELF_ARCH EM_X86_64
#define LIBELF_BYTEORDER ELFDATA2LSB
#define LIBELF_CLASS ELFCLASS64
#elif defined(__arm__)
#define LIBELF_ARCH EM_ARM
#if defined(__ARMEB__) /* Big-endian ARM. */
#define LIBELF_BYTEORDER ELFDATA2MSB
#else
#define LIBELF_BYTEORDER ELFDATA2LSB
#endif
#define LIBELF_CLASS ELFCLASS32
#elif defined(__i386__)
#define LIBELF_ARCH EM_386
#define LIBELF_BYTEORDER ELFDATA2LSB
#define LIBELF_CLASS ELFCLASS32
#elif defined(__ia64__)
#define LIBELF_ARCH EM_IA_64
#define LIBELF_BYTEORDER ELFDATA2LSB
#define LIBELF_CLASS ELFCLASS64
#elif defined(__mips__)
#define LIBELF_ARCH EM_MIPS
#if defined(__MIPSEB__)
#define LIBELF_BYTEORDER ELFDATA2MSB
#else
#define LIBELF_BYTEORDER ELFDATA2LSB
#endif
#define LIBELF_CLASS ELFCLASS32
#elif defined(__powerpc__)
#define LIBELF_ARCH EM_PPC
#define LIBELF_BYTEORDER ELFDATA2MSB
#define LIBELF_CLASS ELFCLASS32
#elif defined(__sparc__)
#define LIBELF_ARCH EM_SPARCV9
#define LIBELF_BYTEORDER ELFDATA2MSB
#define LIBELF_CLASS ELFCLASS64
#else
#error Unknown FreeBSD architecture.
#endif
#endif /* __FreeBSD__ */
/*
* Definitions for Minix3.
*/
#ifdef __minix
#define LIBELF_ARCH EM_386
#define LIBELF_BYTEORDER ELFDATA2LSB
#define LIBELF_CLASS ELFCLASS32
#endif /* __minix */
#ifdef __NetBSD__
#include <machine/elf_machdep.h>
#if !defined(ARCH_ELFSIZE)
#error ARCH_ELFSIZE is not defined.
#endif
#if ARCH_ELFSIZE == 32
#define LIBELF_ARCH ELF32_MACHDEP_ID
#define LIBELF_BYTEORDER ELF32_MACHDEP_ENDIANNESS
#define LIBELF_CLASS ELFCLASS32
#define Elf_Note Elf32_Nhdr
#else
#define LIBELF_ARCH ELF64_MACHDEP_ID
#define LIBELF_BYTEORDER ELF64_MACHDEP_ENDIANNESS
#define LIBELF_CLASS ELFCLASS64
#define Elf_Note Elf64_Nhdr
#endif
#endif /* __NetBSD__ */
#if defined(__OpenBSD__)
#include <machine/exec.h>
#define LIBELF_ARCH ELF_TARG_MACH
#define LIBELF_BYTEORDER ELF_TARG_DATA
#define LIBELF_CLASS ELF_TARG_CLASS
#endif
/*
* GNU & Linux compatibility.
*
* `__linux__' is defined in an environment runs the Linux kernel and glibc.
* `__GNU__' is defined in an environment runs a GNU kernel (Hurd) and glibc.
* `__GLIBC__' is defined for an environment that runs glibc over a non-GNU
* kernel such as GNU/kFreeBSD.
*/
#if defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)
#if defined(__linux__)
#include "native-elf-format.h"
#define LIBELF_CLASS ELFTC_CLASS
#define LIBELF_ARCH ELFTC_ARCH
#define LIBELF_BYTEORDER ELFTC_BYTEORDER
#endif /* defined(__linux__) */
#if LIBELF_CLASS == ELFCLASS32
#define Elf_Note Elf32_Nhdr
#elif LIBELF_CLASS == ELFCLASS64
#define Elf_Note Elf64_Nhdr
#else
#error LIBELF_CLASS needs to be one of ELFCLASS32 or ELFCLASS64
#endif
#endif /* defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) */

View File

@ -1,40 +0,0 @@
/*-
* Copyright (c) 2006,2008,2011 Joseph Koshy
* 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.
*/
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf.c 2225 2011-11-26 18:55:54Z jkoshy $");
struct _libelf_globals _libelf = {
.libelf_arch = LIBELF_ARCH,
.libelf_byteorder = LIBELF_BYTEORDER,
.libelf_class = LIBELF_CLASS,
.libelf_error = 0,
.libelf_fillchar = 0,
.libelf_version = EV_NONE
};

View File

@ -1,91 +0,0 @@
/*-
* Copyright (c) 2006,2008-2011 Joseph Koshy
* 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.
*/
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_begin.c 2364 2011-12-28 17:55:25Z jkoshy $");
Elf *
elf_begin(int fd, Elf_Cmd c, Elf *a)
{
Elf *e;
e = NULL;
if (LIBELF_PRIVATE(version) == EV_NONE) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (NULL);
}
switch (c) {
case ELF_C_NULL:
return (NULL);
case ELF_C_WRITE:
/*
* The ELF_C_WRITE command is required to ignore the
* descriptor passed in.
*/
a = NULL;
break;
case ELF_C_RDWR:
if (a != NULL) { /* not allowed for ar(1) archives. */
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
/*FALLTHROUGH*/
case ELF_C_READ:
/*
* Descriptor `a' could be for a regular ELF file, or
* for an ar(1) archive. If descriptor `a' was opened
* using a valid file descriptor, we need to check if
* the passed in `fd' value matches the original one.
*/
if (a &&
((a->e_fd != -1 && a->e_fd != fd) || c != a->e_cmd)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
break;
default:
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (a == NULL)
e = _libelf_open_object(fd, c, 1);
else if (a->e_kind == ELF_K_AR)
e = _libelf_ar_open_member(a->e_fd, c, a);
else
(e = a)->e_activations++;
return (e);
}

View File

@ -1,58 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_cntl.c 2225 2011-11-26 18:55:54Z jkoshy $");
int
elf_cntl(Elf *e, Elf_Cmd c)
{
if (e == NULL ||
(c != ELF_C_FDDONE && c != ELF_C_FDREAD)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (-1);
}
if (e->e_parent) {
LIBELF_SET_ERROR(ARCHIVE, 0);
return (-1);
}
if (c == ELF_C_FDREAD) {
if (e->e_cmd == ELF_C_WRITE) {
LIBELF_SET_ERROR(MODE, 0);
return (-1);
}
else
return (0);
}
e->e_fd = -1;
return 0;
}

View File

@ -1,254 +0,0 @@
/*-
* Copyright (c) 2006,2008,2011 Joseph Koshy
* 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.
*/
#include <assert.h>
#include <errno.h>
#include <libelf.h>
#include <stdlib.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_data.c 2272 2011-12-03 17:07:31Z jkoshy $");
Elf_Data *
elf_getdata(Elf_Scn *s, Elf_Data *ed)
{
Elf *e;
unsigned int sh_type;
int elfclass, elftype;
size_t fsz, msz, count;
struct _Libelf_Data *d;
uint64_t sh_align, sh_offset, sh_size;
int (*xlate)(char *_d, size_t _dsz, char *_s, size_t _c, int _swap);
d = (struct _Libelf_Data *) ed;
if (s == NULL || (e = s->s_elf) == NULL ||
(d != NULL && s != d->d_scn)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
assert(e->e_kind == ELF_K_ELF);
if (d == NULL && (d = STAILQ_FIRST(&s->s_data)) != NULL)
return (&d->d_data);
if (d != NULL)
return (&STAILQ_NEXT(d, d_next)->d_data);
if (e->e_rawfile == NULL) {
/*
* In the ELF_C_WRITE case, there is no source that
* can provide data for the section.
*/
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
elfclass = e->e_class;
assert(elfclass == ELFCLASS32 || elfclass == ELFCLASS64);
if (elfclass == ELFCLASS32) {
sh_type = s->s_shdr.s_shdr32.sh_type;
sh_offset = (uint64_t) s->s_shdr.s_shdr32.sh_offset;
sh_size = (uint64_t) s->s_shdr.s_shdr32.sh_size;
sh_align = (uint64_t) s->s_shdr.s_shdr32.sh_addralign;
} else {
sh_type = s->s_shdr.s_shdr64.sh_type;
sh_offset = s->s_shdr.s_shdr64.sh_offset;
sh_size = s->s_shdr.s_shdr64.sh_size;
sh_align = s->s_shdr.s_shdr64.sh_addralign;
}
if (sh_type == SHT_NULL) {
LIBELF_SET_ERROR(SECTION, 0);
return (NULL);
}
if ((elftype = _libelf_xlate_shtype(sh_type)) < ELF_T_FIRST ||
elftype > ELF_T_LAST || (sh_type != SHT_NOBITS &&
sh_offset + sh_size > (uint64_t) e->e_rawsize)) {
LIBELF_SET_ERROR(SECTION, 0);
return (NULL);
}
if ((fsz = (elfclass == ELFCLASS32 ? elf32_fsize : elf64_fsize)
(elftype, (size_t) 1, e->e_version)) == 0) {
LIBELF_SET_ERROR(UNIMPL, 0);
return (NULL);
}
if (sh_size % fsz) {
LIBELF_SET_ERROR(SECTION, 0);
return (NULL);
}
count = sh_size / fsz;
msz = _libelf_msize(elftype, elfclass, e->e_version);
assert(msz > 0);
if ((d = _libelf_allocate_data(s)) == NULL)
return (NULL);
d->d_data.d_buf = NULL;
d->d_data.d_off = 0;
d->d_data.d_align = sh_align;
d->d_data.d_size = msz * count;
d->d_data.d_type = elftype;
d->d_data.d_version = e->e_version;
if (sh_type == SHT_NOBITS || sh_size == 0) {
STAILQ_INSERT_TAIL(&s->s_data, d, d_next);
return (&d->d_data);
}
if ((d->d_data.d_buf = malloc(msz*count)) == NULL) {
(void) _libelf_release_data(d);
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
d->d_flags |= LIBELF_F_DATA_MALLOCED;
xlate = _libelf_get_translator(elftype, ELF_TOMEMORY, elfclass);
if (!(*xlate)(d->d_data.d_buf, d->d_data.d_size,
e->e_rawfile + sh_offset, count,
e->e_byteorder != LIBELF_PRIVATE(byteorder))) {
_libelf_release_data(d);
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
STAILQ_INSERT_TAIL(&s->s_data, d, d_next);
return (&d->d_data);
}
Elf_Data *
elf_newdata(Elf_Scn *s)
{
Elf *e;
struct _Libelf_Data *d;
if (s == NULL || (e = s->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
assert(e->e_kind == ELF_K_ELF);
/*
* elf_newdata() has to append a data descriptor, so
* bring in existing section data if not already present.
*/
if (e->e_rawfile && s->s_size > 0 && STAILQ_EMPTY(&s->s_data))
if (elf_getdata(s, NULL) == NULL)
return (NULL);
if ((d = _libelf_allocate_data(s)) == NULL)
return (NULL);
STAILQ_INSERT_TAIL(&s->s_data, d, d_next);
d->d_data.d_align = 1;
d->d_data.d_buf = NULL;
d->d_data.d_off = (uint64_t) ~0;
d->d_data.d_size = 0;
d->d_data.d_type = ELF_T_BYTE;
d->d_data.d_version = LIBELF_PRIVATE(version);
(void) elf_flagscn(s, ELF_C_SET, ELF_F_DIRTY);
return (&d->d_data);
}
/*
* Retrieve a data descriptor for raw (untranslated) data for section
* `s'.
*/
Elf_Data *
elf_rawdata(Elf_Scn *s, Elf_Data *ed)
{
Elf *e;
int elf_class;
uint32_t sh_type;
struct _Libelf_Data *d;
uint64_t sh_align, sh_offset, sh_size;
if (s == NULL || (e = s->s_elf) == NULL || e->e_rawfile == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
assert(e->e_kind == ELF_K_ELF);
d = (struct _Libelf_Data *) ed;
if (d == NULL && (d = STAILQ_FIRST(&s->s_rawdata)) != NULL)
return (&d->d_data);
if (d != NULL)
return (&STAILQ_NEXT(d, d_next)->d_data);
elf_class = e->e_class;
assert(elf_class == ELFCLASS32 || elf_class == ELFCLASS64);
if (elf_class == ELFCLASS32) {
sh_type = s->s_shdr.s_shdr32.sh_type;
sh_offset = (uint64_t) s->s_shdr.s_shdr32.sh_offset;
sh_size = (uint64_t) s->s_shdr.s_shdr32.sh_size;
sh_align = (uint64_t) s->s_shdr.s_shdr32.sh_addralign;
} else {
sh_type = s->s_shdr.s_shdr64.sh_type;
sh_offset = s->s_shdr.s_shdr64.sh_offset;
sh_size = s->s_shdr.s_shdr64.sh_size;
sh_align = s->s_shdr.s_shdr64.sh_addralign;
}
if (sh_type == SHT_NULL)
return (NULL);
if ((d = _libelf_allocate_data(s)) == NULL)
return (NULL);
d->d_data.d_buf = (sh_type == SHT_NOBITS || sh_size == 0) ? NULL :
e->e_rawfile + sh_offset;
d->d_data.d_off = 0;
d->d_data.d_align = sh_align;
d->d_data.d_size = sh_size;
d->d_data.d_type = ELF_T_BYTE;
d->d_data.d_version = e->e_version;
STAILQ_INSERT_TAIL(&s->s_rawdata, d, d_next);
return (&d->d_data);
}

View File

@ -1,97 +0,0 @@
/*-
* Copyright (c) 2006,2008-2009,2011 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <libelf.h>
#include <stdlib.h>
#include "_libelf.h"
#if ELFTC_HAVE_MMAP
#include <sys/mman.h>
#endif
ELFTC_VCSID("$Id: elf_end.c 2240 2011-11-28 06:36:48Z jkoshy $");
int
elf_end(Elf *e)
{
Elf *sv;
Elf_Scn *scn, *tscn;
if (e == NULL || e->e_activations == 0)
return (0);
if (--e->e_activations > 0)
return (e->e_activations);
assert(e->e_activations == 0);
while (e && e->e_activations == 0) {
switch (e->e_kind) {
case ELF_K_AR:
/*
* If we still have open child descriptors, we
* need to defer reclaiming resources till all
* the child descriptors for the archive are
* closed.
*/
if (e->e_u.e_ar.e_nchildren > 0)
return (0);
break;
case ELF_K_ELF:
/*
* Reclaim all section descriptors.
*/
STAILQ_FOREACH_SAFE(scn, &e->e_u.e_elf.e_scn, s_next,
tscn)
scn = _libelf_release_scn(scn);
break;
case ELF_K_NUM:
assert(0);
default:
break;
}
if (e->e_rawfile) {
if (e->e_flags & LIBELF_F_RAWFILE_MALLOC)
free(e->e_rawfile);
#if ELFTC_HAVE_MMAP
else if (e->e_flags & LIBELF_F_RAWFILE_MMAP)
(void) munmap(e->e_rawfile, e->e_rawsize);
#endif
}
sv = e;
if ((e = e->e_parent) != NULL)
e->e_u.e_ar.e_nchildren--;
sv = _libelf_release_elf(sv);
}
return (0);
}

View File

@ -1,85 +0,0 @@
/*-
* Copyright (c) 2006,2008,2011 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include <stdio.h>
#include <string.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_errmsg.c 2225 2011-11-26 18:55:54Z jkoshy $");
/*
* Retrieve a human readable translation for an error message.
*/
const char *_libelf_errors[] = {
#define DEFINE_ERROR(N,S) [ELF_E_##N] = S
DEFINE_ERROR(NONE, "No Error"),
DEFINE_ERROR(ARCHIVE, "Malformed ar(1) archive"),
DEFINE_ERROR(ARGUMENT, "Invalid argument"),
DEFINE_ERROR(CLASS, "ELF class mismatch"),
DEFINE_ERROR(DATA, "Invalid data buffer descriptor"),
DEFINE_ERROR(HEADER, "Missing or malformed ELF header"),
DEFINE_ERROR(IO, "I/O error"),
DEFINE_ERROR(LAYOUT, "Layout constraint violation"),
DEFINE_ERROR(MODE, "Incorrect ELF descriptor mode"),
DEFINE_ERROR(RANGE, "Value out of range of target"),
DEFINE_ERROR(RESOURCE, "Resource exhaustion"),
DEFINE_ERROR(SECTION, "Invalid section descriptor"),
DEFINE_ERROR(SEQUENCE, "API calls out of sequence"),
DEFINE_ERROR(UNIMPL, "Unimplemented feature"),
DEFINE_ERROR(VERSION, "Unknown ELF API version"),
DEFINE_ERROR(NUM, "Unknown error")
#undef DEFINE_ERROR
};
const char *
elf_errmsg(int error)
{
int oserr;
if (error == ELF_E_NONE &&
(error = LIBELF_PRIVATE(error)) == 0)
return NULL;
else if (error == -1)
error = LIBELF_PRIVATE(error);
oserr = error >> LIBELF_OS_ERROR_SHIFT;
error &= LIBELF_ELF_ERROR_MASK;
if (error < ELF_E_NONE || error >= ELF_E_NUM)
return _libelf_errors[ELF_E_NUM];
if (oserr) {
(void) snprintf(LIBELF_PRIVATE(msg),
sizeof(LIBELF_PRIVATE(msg)), "%s: %s",
_libelf_errors[error], strerror(oserr));
return (const char *)&LIBELF_PRIVATE(msg);
}
return _libelf_errors[error];
}

View File

@ -1,43 +0,0 @@
/*-
* Copyright (c) 2006,2008,2011 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_errno.c 2225 2011-11-26 18:55:54Z jkoshy $");
int
elf_errno(void)
{
int old;
old = LIBELF_PRIVATE(error);
LIBELF_PRIVATE(error) = 0;
return (old & LIBELF_ELF_ERROR_MASK);
}

View File

@ -1,39 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_fill.c 2225 2011-11-26 18:55:54Z jkoshy $");
void
elf_fill(int fill)
{
LIBELF_PRIVATE(fillchar) = fill;
}

View File

@ -1,198 +0,0 @@
/*-
* Copyright (c) 2006,2008-2009,2011 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_flag.c 2272 2011-12-03 17:07:31Z jkoshy $");
unsigned int
elf_flagarhdr(Elf_Arhdr *a, Elf_Cmd c, unsigned int flags)
{
unsigned int r;
if (a == NULL)
return (0);
if ((c != ELF_C_SET && c != ELF_C_CLR) ||
(flags & ~ELF_F_DIRTY) != 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (c == ELF_C_SET)
r = a->ar_flags |= flags;
else
r = a->ar_flags &= ~flags;
return (r & LIBELF_F_API_MASK);
}
unsigned int
elf_flagdata(Elf_Data *d, Elf_Cmd c, unsigned int flags)
{
unsigned int r;
struct _Libelf_Data *ld;
if (d == NULL)
return (0);
if ((c != ELF_C_SET && c != ELF_C_CLR) ||
(flags & ~ELF_F_DIRTY) != 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ld = (struct _Libelf_Data *) d;
if (c == ELF_C_SET)
r = ld->d_flags |= flags;
else
r = ld->d_flags &= ~flags;
return (r & LIBELF_F_API_MASK);
}
unsigned int
elf_flagehdr(Elf *e, Elf_Cmd c, unsigned int flags)
{
int ec;
void *ehdr;
if (e == NULL)
return (0);
if ((c != ELF_C_SET && c != ELF_C_CLR) ||
(e->e_kind != ELF_K_ELF) || (flags & ~ELF_F_DIRTY) != 0 ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32)
ehdr = e->e_u.e_elf.e_ehdr.e_ehdr32;
else
ehdr = e->e_u.e_elf.e_ehdr.e_ehdr64;
if (ehdr == NULL) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (0);
}
return (elf_flagelf(e, c, flags));
}
unsigned int
elf_flagelf(Elf *e, Elf_Cmd c, unsigned int flags)
{
int r;
if (e == NULL)
return (0);
if ((c != ELF_C_SET && c != ELF_C_CLR) ||
(e->e_kind != ELF_K_ELF) ||
(flags & ~(ELF_F_ARCHIVE | ELF_F_ARCHIVE_SYSV |
ELF_F_DIRTY | ELF_F_LAYOUT)) != 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if ((flags & ELF_F_ARCHIVE_SYSV) && (flags & ELF_F_ARCHIVE) == 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if ((flags & ELF_F_ARCHIVE) && e->e_cmd != ELF_C_WRITE) {
LIBELF_SET_ERROR(MODE, 0);
return (0);
}
if (c == ELF_C_SET)
r = e->e_flags |= flags;
else
r = e->e_flags &= ~flags;
return (r & LIBELF_F_API_MASK);
}
unsigned int
elf_flagphdr(Elf *e, Elf_Cmd c, unsigned int flags)
{
int ec;
void *phdr;
if (e == NULL)
return (0);
if ((c != ELF_C_SET && c != ELF_C_CLR) ||
(e->e_kind != ELF_K_ELF) || (flags & ~ELF_F_DIRTY) != 0 ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32)
phdr = e->e_u.e_elf.e_phdr.e_phdr32;
else
phdr = e->e_u.e_elf.e_phdr.e_phdr64;
if (phdr == NULL) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (0);
}
return (elf_flagelf(e, c, flags));
}
unsigned int
elf_flagscn(Elf_Scn *s, Elf_Cmd c, unsigned int flags)
{
int r;
if (s == NULL)
return (0);
if ((c != ELF_C_SET && c != ELF_C_CLR) ||
(flags & ~ELF_F_DIRTY) != 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (c == ELF_C_SET)
r = s->s_flags |= flags;
else
r = s->s_flags &= ~flags;
return (r & LIBELF_F_API_MASK);
}
unsigned int
elf_flagshdr(Elf_Scn *s, Elf_Cmd c, unsigned int flags)
{
return (elf_flagscn(s, c, flags));
}

View File

@ -1,47 +0,0 @@
/*-
* Copyright (c) 2006,2008,2010 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_getarhdr.c 2225 2011-11-26 18:55:54Z jkoshy $");
Elf_Arhdr *
elf_getarhdr(Elf *e)
{
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (e->e_flags & LIBELF_F_AR_HEADER)
return (e->e_hdr.e_arhdr);
return (_libelf_ar_gethdr(e));
}

View File

@ -1,58 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_getarsym.c 2225 2011-11-26 18:55:54Z jkoshy $");
Elf_Arsym *
elf_getarsym(Elf *ar, size_t *ptr)
{
size_t n;
Elf_Arsym *symtab;
n = 0;
symtab = NULL;
if (ar == NULL || ar->e_kind != ELF_K_AR)
LIBELF_SET_ERROR(ARGUMENT, 0);
else if ((symtab = ar->e_u.e_ar.e_symtab) != NULL)
n = ar->e_u.e_ar.e_symtabsz;
else if (ar->e_u.e_ar.e_rawsymtab)
symtab = (ar->e_flags & LIBELF_F_AR_VARIANT_SVR4) ?
_libelf_ar_process_svr4_symtab(ar, &n) :
_libelf_ar_process_bsd_symtab(ar, &n);
else
LIBELF_SET_ERROR(ARCHIVE, 0);
if (ptr)
*ptr = n;
return (symtab);
}

View File

@ -1,48 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_getbase.c 2225 2011-11-26 18:55:54Z jkoshy $");
off_t
elf_getbase(Elf *e)
{
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return ((off_t) -1);
}
if (e->e_parent == NULL)
return ((off_t) 0);
return ((off_t) ((uintptr_t) e->e_rawfile -
(uintptr_t) e->e_parent->e_rawfile));
}

View File

@ -1,68 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <ar.h>
#include <assert.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_getident.c 2225 2011-11-26 18:55:54Z jkoshy $");
char *
elf_getident(Elf *e, size_t *sz)
{
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
goto error;
}
if (e->e_cmd == ELF_C_WRITE && e->e_rawfile == NULL) {
LIBELF_SET_ERROR(SEQUENCE, 0);
goto error;
}
assert(e->e_kind != ELF_K_AR || e->e_cmd == ELF_C_READ);
if (sz) {
if (e->e_kind == ELF_K_AR)
*sz = SARMAG;
else if (e->e_kind == ELF_K_ELF)
*sz = EI_NIDENT;
else
*sz = e->e_rawsize;
}
return ((char *) e->e_rawfile);
error:
if (sz)
*sz = 0;
return (NULL);
}

View File

@ -1,56 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_hash.c 2225 2011-11-26 18:55:54Z jkoshy $");
/*
* This elf_hash function is defined by the System V ABI.
*/
unsigned long
elf_hash(const char *name)
{
unsigned long h, t;
const unsigned char *s;
s = (const unsigned char *) name;
h = t = 0;
for (; *s != '\0'; h = h & ~t) {
h = (h << 4) + *s++;
t = h & 0xF0000000UL;
if (t)
h ^= t >> 24;
}
return (h);
}

View File

@ -1,44 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_kind.c 2225 2011-11-26 18:55:54Z jkoshy $");
Elf_Kind
elf_kind(Elf *e)
{
if (e == NULL)
return (ELF_K_NONE);
if (e->e_kind == ELF_K_AR ||
e->e_kind == ELF_K_ELF)
return (e->e_kind);
return (ELF_K_NONE);
}

View File

@ -1,47 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_memory.c 2368 2011-12-29 06:34:28Z jkoshy $");
Elf *
elf_memory(char *image, size_t sz)
{
if (LIBELF_PRIVATE(version) == EV_NONE) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (NULL);
}
if (image == NULL || sz == 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
return (_libelf_memory(image, sz, 1));
}

View File

@ -1,62 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <ar.h>
#include <assert.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_next.c 2225 2011-11-26 18:55:54Z jkoshy $");
Elf_Cmd
elf_next(Elf *e)
{
off_t next;
Elf *parent;
if (e == NULL)
return (ELF_C_NULL);
if ((parent = e->e_parent) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (ELF_C_NULL);
}
assert (parent->e_kind == ELF_K_AR);
assert (parent->e_cmd == ELF_C_READ);
assert(e->e_rawfile > parent->e_rawfile);
next = e->e_rawfile - parent->e_rawfile + e->e_rawsize;
next = (next + 1) & ~1; /* round up to an even boundary */
parent->e_u.e_ar.e_next = (next >= (off_t) parent->e_rawsize) ?
(off_t) 0 : next;
return (ELF_C_READ);
}

View File

@ -1,67 +0,0 @@
/*-
* Copyright (c) 2011 Joseph Koshy
* 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.
*/
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id$");
/*
* Extension API: open a file for reading, ignoring parse errors.
*/
Elf *
elf_open(int fd)
{
if (LIBELF_PRIVATE(version) == EV_NONE) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (NULL);
}
return (_libelf_open_object(fd, ELF_C_READ, 0));
}
/*
* Extension API: create an ELF descriptor for an in-memory object,
* ignoring parse errors.
*/
Elf *
elf_openmemory(char *image, size_t sz)
{
if (LIBELF_PRIVATE(version) == EV_NONE) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (NULL);
}
if (image == NULL || sz == 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
return (_libelf_memory(image, sz, 0));
}

View File

@ -1,67 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <ar.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_phnum.c 2225 2011-11-26 18:55:54Z jkoshy $");
static int
_libelf_getphdrnum(Elf *e, size_t *phnum)
{
void *eh;
int ec;
if (e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (-1);
}
if ((eh = _libelf_ehdr(e, ec, 0)) == NULL)
return (-1);
*phnum = e->e_u.e_elf.e_nphdr;
return (0);
}
int
elf_getphdrnum(Elf *e, size_t *phnum)
{
return (_libelf_getphdrnum(e, phnum));
}
/* Deprecated API */
int
elf_getphnum(Elf *e, size_t *phnum)
{
return (_libelf_getphdrnum(e, phnum) >= 0);
}

View File

@ -1,59 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <ar.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_rand.c 2225 2011-11-26 18:55:54Z jkoshy $");
off_t
elf_rand(Elf *ar, off_t offset)
{
struct ar_hdr *arh;
if (ar == NULL || ar->e_kind != ELF_K_AR ||
(offset & 1) || offset < SARMAG ||
offset + sizeof(struct ar_hdr) >= ar->e_rawsize) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return 0;
}
arh = (struct ar_hdr *) (ar->e_rawfile + offset);
/* a too simple sanity check */
if (arh->ar_fmag[0] != '`' || arh->ar_fmag[1] != '\n') {
LIBELF_SET_ERROR(ARCHIVE, 0);
return 0;
}
ar->e_u.e_ar.e_next = offset;
return (offset);
}

View File

@ -1,53 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_rawfile.c 2225 2011-11-26 18:55:54Z jkoshy $");
char *
elf_rawfile(Elf *e, size_t *sz)
{
char *ptr;
size_t size;
size = e ? e->e_rawsize : 0;
ptr = NULL;
if (e == NULL)
LIBELF_SET_ERROR(ARGUMENT, 0);
else if ((ptr = e->e_rawfile) == NULL && e->e_cmd == ELF_C_WRITE)
LIBELF_SET_ERROR(SEQUENCE, 0);
if (sz)
*sz = size;
return (ptr);
}

View File

@ -1,233 +0,0 @@
/*-
* Copyright (c) 2006,2008-2010 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <sys/queue.h>
#include <assert.h>
#include <errno.h>
#include <gelf.h>
#include <libelf.h>
#include <stddef.h>
#include <stdlib.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_scn.c 2225 2011-11-26 18:55:54Z jkoshy $");
/*
* Load an ELF section table and create a list of Elf_Scn structures.
*/
int
_libelf_load_section_headers(Elf *e, void *ehdr)
{
int ec, swapbytes;
size_t fsz, i, shnum;
uint64_t shoff;
char *src;
Elf32_Ehdr *eh32;
Elf64_Ehdr *eh64;
Elf_Scn *scn;
int (*xlator)(char *_d, size_t _dsz, char *_s, size_t _c, int _swap);
assert(e != NULL);
assert(ehdr != NULL);
assert((e->e_flags & LIBELF_F_SHDRS_LOADED) == 0);
#define CHECK_EHDR(E,EH) do { \
if (fsz != (EH)->e_shentsize || \
shoff + fsz * shnum > e->e_rawsize) { \
LIBELF_SET_ERROR(HEADER, 0); \
return (0); \
} \
} while (0)
ec = e->e_class;
fsz = _libelf_fsize(ELF_T_SHDR, ec, e->e_version, (size_t) 1);
assert(fsz > 0);
shnum = e->e_u.e_elf.e_nscn;
if (ec == ELFCLASS32) {
eh32 = (Elf32_Ehdr *) ehdr;
shoff = (uint64_t) eh32->e_shoff;
CHECK_EHDR(e, eh32);
} else {
eh64 = (Elf64_Ehdr *) ehdr;
shoff = eh64->e_shoff;
CHECK_EHDR(e, eh64);
}
xlator = _libelf_get_translator(ELF_T_SHDR, ELF_TOMEMORY, ec);
swapbytes = e->e_byteorder != LIBELF_PRIVATE(byteorder);
src = e->e_rawfile + shoff;
/*
* If the file is using extended numbering then section #0
* would have already been read in.
*/
i = 0;
if (!STAILQ_EMPTY(&e->e_u.e_elf.e_scn)) {
/* commented out to prevent build error
assert(STAILQ_FIRST(&e->e_u.e_elf.e_scn) ==
STAILQ_LAST(&e->e_u.e_elf.e_scn, _Elf_Scn, s_next));*/
i = 1;
src += fsz;
}
for (; i < shnum; i++, src += fsz) {
if ((scn = _libelf_allocate_scn(e, i)) == NULL)
return (0);
(*xlator)((char *) &scn->s_shdr, sizeof(scn->s_shdr), src,
(size_t) 1, swapbytes);
if (ec == ELFCLASS32) {
scn->s_offset = scn->s_rawoff =
scn->s_shdr.s_shdr32.sh_offset;
scn->s_size = scn->s_shdr.s_shdr32.sh_size;
} else {
scn->s_offset = scn->s_rawoff =
scn->s_shdr.s_shdr64.sh_offset;
scn->s_size = scn->s_shdr.s_shdr64.sh_size;
}
}
e->e_flags |= LIBELF_F_SHDRS_LOADED;
return (1);
}
Elf_Scn *
elf_getscn(Elf *e, size_t index)
{
int ec;
void *ehdr;
Elf_Scn *s;
if (e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
return (NULL);
if (e->e_cmd != ELF_C_WRITE &&
(e->e_flags & LIBELF_F_SHDRS_LOADED) == 0 &&
_libelf_load_section_headers(e, ehdr) == 0)
return (NULL);
STAILQ_FOREACH(s, &e->e_u.e_elf.e_scn, s_next)
if (s->s_ndx == index)
return (s);
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
size_t
elf_ndxscn(Elf_Scn *s)
{
if (s == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (SHN_UNDEF);
}
return (s->s_ndx);
}
Elf_Scn *
elf_newscn(Elf *e)
{
int ec;
void *ehdr;
Elf_Scn *scn;
if (e == NULL || e->e_kind != ELF_K_ELF) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if ((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64) {
LIBELF_SET_ERROR(CLASS, 0);
return (NULL);
}
if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
return (NULL);
/*
* The application may be asking for a new section descriptor
* on an ELF object opened with ELF_C_RDWR or ELF_C_READ. We
* need to bring in the existing section information before
* appending a new one to the list.
*
* Per the ELF(3) API, an application is allowed to open a
* file using ELF_C_READ, mess with its internal structure and
* use elf_update(...,ELF_C_NULL) to compute its new layout.
*/
if (e->e_cmd != ELF_C_WRITE &&
(e->e_flags & LIBELF_F_SHDRS_LOADED) == 0 &&
_libelf_load_section_headers(e, ehdr) == 0)
return (NULL);
if (STAILQ_EMPTY(&e->e_u.e_elf.e_scn)) {
assert(e->e_u.e_elf.e_nscn == 0);
if ((scn = _libelf_allocate_scn(e, (size_t) SHN_UNDEF)) ==
NULL)
return (NULL);
e->e_u.e_elf.e_nscn++;
}
assert(e->e_u.e_elf.e_nscn > 0);
if ((scn = _libelf_allocate_scn(e, e->e_u.e_elf.e_nscn)) == NULL)
return (NULL);
e->e_u.e_elf.e_nscn++;
(void) elf_flagscn(scn, ELF_C_SET, ELF_F_DIRTY);
return (scn);
}
Elf_Scn *
elf_nextscn(Elf *e, Elf_Scn *s)
{
if (e == NULL || (e->e_kind != ELF_K_ELF) ||
(s && s->s_elf != e)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
return (s == NULL ? elf_getscn(e, (size_t) 1) :
STAILQ_NEXT(s, s_next));
}

View File

@ -1,67 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <ar.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_shnum.c 2225 2011-11-26 18:55:54Z jkoshy $");
static int
_libelf_getshdrnum(Elf *e, size_t *shnum)
{
void *eh;
int ec;
if (e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (-1);
}
if ((eh = _libelf_ehdr(e, ec, 0)) == NULL)
return (-1);
*shnum = e->e_u.e_elf.e_nscn;
return (0);
}
int
elf_getshdrnum(Elf *e, size_t *shnum)
{
return (_libelf_getshdrnum(e, shnum));
}
/* Deprecated API. */
int
elf_getshnum(Elf *e, size_t *shnum)
{
return (_libelf_getshdrnum(e, shnum) >= 0);
}

View File

@ -1,82 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <ar.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_shstrndx.c 2225 2011-11-26 18:55:54Z jkoshy $");
static int
_libelf_getshdrstrndx(Elf *e, size_t *strndx)
{
void *eh;
int ec;
if (e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (-1);
}
if ((eh = _libelf_ehdr(e, ec, 0)) == NULL)
return (-1);
*strndx = e->e_u.e_elf.e_strndx;
return (0);
}
int
elf_getshdrstrndx(Elf *e, size_t *strndx)
{
return (_libelf_getshdrstrndx(e, strndx));
}
int
elf_getshstrndx(Elf *e, size_t *strndx) /* Deprecated API. */
{
return (_libelf_getshdrstrndx(e, strndx) >= 0);
}
int
elf_setshstrndx(Elf *e, size_t strndx)
{
void *eh;
int ec;
if (e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64) ||
((eh = _libelf_ehdr(e, ec, 0)) == NULL)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
return (_libelf_setshstrndx(e, eh, ec, strndx));
}

View File

@ -1,132 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/param.h>
#include <assert.h>
#include <gelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_strptr.c 2271 2011-12-03 17:06:35Z jkoshy $");
/*
* Convert an ELF section#,offset pair to a string pointer.
*/
char *
elf_strptr(Elf *e, size_t scndx, size_t offset)
{
Elf_Scn *s;
Elf_Data *d;
size_t alignment, count;
GElf_Shdr shdr;
if (e == NULL || e->e_kind != ELF_K_ELF) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if ((s = elf_getscn(e, scndx)) == NULL ||
gelf_getshdr(s, &shdr) == NULL)
return (NULL);
if (shdr.sh_type != SHT_STRTAB ||
offset >= shdr.sh_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
d = NULL;
if (e->e_flags & ELF_F_LAYOUT) {
/*
* The application is taking responsibility for the
* ELF object's layout, so we can directly translate
* an offset to a `char *' address using the `d_off'
* members of Elf_Data descriptors.
*/
while ((d = elf_getdata(s, d)) != NULL) {
if (d->d_buf == 0 || d->d_size == 0)
continue;
if (d->d_type != ELF_T_BYTE) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
if (offset >= d->d_off &&
offset < d->d_off + d->d_size)
return ((char *) d->d_buf + offset - d->d_off);
}
} else {
/*
* Otherwise, the `d_off' members are not useable and
* we need to compute offsets ourselves, taking into
* account 'holes' in coverage of the section introduced
* by alignment requirements.
*/
count = (size_t) 0; /* cumulative count of bytes seen */
while ((d = elf_getdata(s, d)) != NULL && count <= offset) {
if (d->d_buf == NULL || d->d_size == 0)
continue;
if (d->d_type != ELF_T_BYTE) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
if ((alignment = d->d_align) > 1) {
if ((alignment & (alignment - 1)) != 0) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
count = roundup2(count, alignment);
}
if (offset < count) {
/* offset starts in the 'hole' */
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (offset < count + d->d_size) {
if (d->d_buf != NULL)
return ((char *) d->d_buf +
offset - count);
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
count += d->d_size;
}
}
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,52 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: elf_version.c 2225 2011-11-26 18:55:54Z jkoshy $");
unsigned int
elf_version(unsigned int v)
{
unsigned int old;
if ((old = LIBELF_PRIVATE(version)) == EV_NONE)
old = EV_CURRENT;
if (v == EV_NONE)
return old;
if (v > EV_CURRENT) {
LIBELF_SET_ERROR(VERSION, 0);
return EV_NONE;
}
LIBELF_PRIVATE(version) = v;
return (old);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,106 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*
* $Id: gelf.h 1168 2010-09-04 01:03:25Z jkoshy $
*/
#ifndef _GELF_H_
#define _GELF_H_
#include <sys/cdefs.h>
#include <libelf.h>
typedef Elf64_Addr GElf_Addr; /* Addresses */
typedef Elf64_Half GElf_Half; /* Half words (16 bit) */
typedef Elf64_Off GElf_Off; /* Offsets */
typedef Elf64_Sword GElf_Sword; /* Signed words (32 bit) */
typedef Elf64_Sxword GElf_Sxword; /* Signed long words (64 bit) */
typedef Elf64_Word GElf_Word; /* Unsigned words (32 bit) */
typedef Elf64_Xword GElf_Xword; /* Unsigned long words (64 bit) */
typedef Elf64_Dyn GElf_Dyn; /* ".dynamic" section entries */
typedef Elf64_Ehdr GElf_Ehdr; /* ELF header */
typedef Elf64_Phdr GElf_Phdr; /* Program header */
typedef Elf64_Shdr GElf_Shdr; /* Section header */
typedef Elf64_Sym GElf_Sym; /* Symbol table entries */
typedef Elf64_Rel GElf_Rel; /* Relocation entries */
typedef Elf64_Rela GElf_Rela; /* Relocation entries with addend */
typedef Elf64_Cap GElf_Cap; /* SW/HW capabilities */
typedef Elf64_Move GElf_Move; /* Move entries */
typedef Elf64_Syminfo GElf_Syminfo; /* Symbol information */
#define GELF_M_INFO ELF64_M_INFO
#define GELF_M_SIZE ELF64_M_SIZE
#define GELF_M_SYM ELF64_M_SYM
#define GELF_R_INFO ELF64_R_INFO
#define GELF_R_SYM ELF64_R_SYM
#define GELF_R_TYPE ELF64_R_TYPE
#define GELF_R_TYPE_DATA ELF64_R_TYPE_DATA
#define GELF_R_TYPE_ID ELF64_R_TYPE_ID
#define GELF_R_TYPE_INFO ELF64_R_TYPE_INFO
#define GELF_ST_BIND ELF64_ST_BIND
#define GELF_ST_INFO ELF64_ST_INFO
#define GELF_ST_TYPE ELF64_ST_TYPE
#define GELF_ST_VISIBILITY ELF64_ST_VISIBILITY
long gelf_checksum(Elf *_elf);
size_t gelf_fsize(Elf *_elf, Elf_Type _type, size_t _count,
unsigned int _version);
int gelf_getclass(Elf *_elf);
GElf_Dyn *gelf_getdyn(Elf_Data *_data, int _index, GElf_Dyn *_dst);
GElf_Ehdr *gelf_getehdr(Elf *_elf, GElf_Ehdr *_dst);
GElf_Phdr *gelf_getphdr(Elf *_elf, int _index, GElf_Phdr *_dst);
GElf_Rel *gelf_getrel(Elf_Data *_src, int _index, GElf_Rel *_dst);
GElf_Rela *gelf_getrela(Elf_Data *_src, int _index, GElf_Rela *_dst);
GElf_Shdr *gelf_getshdr(Elf_Scn *_scn, GElf_Shdr *_dst);
GElf_Sym *gelf_getsym(Elf_Data *_src, int _index, GElf_Sym *_dst);
GElf_Sym *gelf_getsymshndx(Elf_Data *_src, Elf_Data *_shindexsrc,
int _index, GElf_Sym *_dst, Elf32_Word *_shindexdst);
void * gelf_newehdr(Elf *_elf, int _class);
void * gelf_newphdr(Elf *_elf, size_t _phnum);
int gelf_update_dyn(Elf_Data *_dst, int _index, GElf_Dyn *_src);
int gelf_update_ehdr(Elf *_elf, GElf_Ehdr *_src);
int gelf_update_phdr(Elf *_elf, int _index, GElf_Phdr *_src);
int gelf_update_rel(Elf_Data *_dst, int _index, GElf_Rel *_src);
int gelf_update_rela(Elf_Data *_dst, int _index, GElf_Rela *_src);
int gelf_update_shdr(Elf_Scn *_dst, GElf_Shdr *_src);
int gelf_update_sym(Elf_Data *_dst, int _index, GElf_Sym *_src);
int gelf_update_symshndx(Elf_Data *_symdst, Elf_Data *_shindexdst,
int _index, GElf_Sym *_symsrc, Elf32_Word _shindexsrc);
Elf_Data *gelf_xlatetof(Elf *_elf, Elf_Data *_dst, const Elf_Data *_src, unsigned int _encode);
Elf_Data *gelf_xlatetom(Elf *_elf, Elf_Data *_dst, const Elf_Data *_src, unsigned int _encode);
GElf_Cap *gelf_getcap(Elf_Data *_data, int _index, GElf_Cap *_cap);
GElf_Move *gelf_getmove(Elf_Data *_src, int _index, GElf_Move *_dst);
GElf_Syminfo *gelf_getsyminfo(Elf_Data *_src, int _index, GElf_Syminfo *_dst);
int gelf_update_cap(Elf_Data *_dst, int _index, GElf_Cap *_src);
int gelf_update_move(Elf_Data *_dst, int _index, GElf_Move *_src);
int gelf_update_syminfo(Elf_Data *_dst, int _index, GElf_Syminfo *_src);
#endif /* _GELF_H_ */

View File

@ -1,151 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_cap.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Cap *
gelf_getcap(Elf_Data *ed, int ndx, GElf_Cap *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
Elf32_Cap *cap32;
Elf64_Cap *cap64;
uint32_t sh_type;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_CAP) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_CAP, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
cap32 = (Elf32_Cap *) d->d_data.d_buf + ndx;
dst->c_tag = cap32->c_tag;
dst->c_un.c_val = (Elf64_Xword) cap32->c_un.c_val;
} else {
cap64 = (Elf64_Cap *) d->d_data.d_buf + ndx;
*dst = *cap64;
}
return (dst);
}
int
gelf_update_cap(Elf_Data *ed, int ndx, GElf_Cap *gc)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
Elf32_Cap *cap32;
Elf64_Cap *cap64;
uint32_t sh_type;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || gc == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_CAP) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_CAP, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
cap32 = (Elf32_Cap *) d->d_data.d_buf + ndx;
LIBELF_COPY_U32(cap32, gc, c_tag);
LIBELF_COPY_U32(cap32, gc, c_un.c_val);
} else {
cap64 = (Elf64_Cap *) d->d_data.d_buf + ndx;
*cap64 = *gc;
}
return (1);
}

View File

@ -1,58 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_checksum.c 2225 2011-11-26 18:55:54Z jkoshy $");
long
elf32_checksum(Elf *e)
{
return (_libelf_checksum(e, ELFCLASS32));
}
long
elf64_checksum(Elf *e)
{
return (_libelf_checksum(e, ELFCLASS64));
}
long
gelf_checksum(Elf *e)
{
int ec;
if (e == NULL ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0L);
}
return (_libelf_checksum(e, ec));
}

View File

@ -1,150 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_dyn.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Dyn *
gelf_getdyn(Elf_Data *ed, int ndx, GElf_Dyn *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
Elf32_Dyn *dyn32;
Elf64_Dyn *dyn64;
uint32_t sh_type;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_DYN) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_DYN, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
dyn32 = (Elf32_Dyn *) d->d_data.d_buf + ndx;
dst->d_tag = dyn32->d_tag;
dst->d_un.d_val = (Elf64_Xword) dyn32->d_un.d_val;
} else {
dyn64 = (Elf64_Dyn *) d->d_data.d_buf + ndx;
*dst = *dyn64;
}
return (dst);
}
int
gelf_update_dyn(Elf_Data *ed, int ndx, GElf_Dyn *ds)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
Elf32_Dyn *dyn32;
Elf64_Dyn *dyn64;
uint32_t sh_type;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || ds == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_DYN) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_DYN, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
dyn32 = (Elf32_Dyn *) d->d_data.d_buf + ndx;
LIBELF_COPY_S32(dyn32, ds, d_tag);
LIBELF_COPY_U32(dyn32, ds, d_un.d_val);
} else {
dyn64 = (Elf64_Dyn *) d->d_data.d_buf + ndx;
*dyn64 = *ds;
}
return (1);
}

View File

@ -1,168 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <libelf.h>
#include <limits.h>
#include <string.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_ehdr.c 2268 2011-12-03 17:05:11Z jkoshy $");
Elf32_Ehdr *
elf32_getehdr(Elf *e)
{
return (_libelf_ehdr(e, ELFCLASS32, 0));
}
Elf64_Ehdr *
elf64_getehdr(Elf *e)
{
return (_libelf_ehdr(e, ELFCLASS64, 0));
}
GElf_Ehdr *
gelf_getehdr(Elf *e, GElf_Ehdr *d)
{
int ec;
Elf32_Ehdr *eh32;
Elf64_Ehdr *eh64;
if (d == NULL || e == NULL ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
if ((eh32 = _libelf_ehdr(e, ELFCLASS32, 0)) == NULL)
return (NULL);
(void) memcpy(d->e_ident, eh32->e_ident,
sizeof(eh32->e_ident));
d->e_type = eh32->e_type;
d->e_machine = eh32->e_machine;
d->e_version = eh32->e_version;
d->e_entry = eh32->e_entry;
d->e_phoff = eh32->e_phoff;
d->e_shoff = eh32->e_shoff;
d->e_flags = eh32->e_flags;
d->e_ehsize = eh32->e_ehsize;
d->e_phentsize = eh32->e_phentsize;
d->e_phnum = eh32->e_phnum;
d->e_shentsize = eh32->e_shentsize;
d->e_shnum = eh32->e_shnum;
d->e_shstrndx = eh32->e_shstrndx;
return (d);
}
assert(ec == ELFCLASS64);
if ((eh64 = _libelf_ehdr(e, ELFCLASS64, 0)) == NULL)
return (NULL);
*d = *eh64;
return (d);
}
Elf32_Ehdr *
elf32_newehdr(Elf *e)
{
return (_libelf_ehdr(e, ELFCLASS32, 1));
}
Elf64_Ehdr *
elf64_newehdr(Elf *e)
{
return (_libelf_ehdr(e, ELFCLASS64, 1));
}
void *
gelf_newehdr(Elf *e, int ec)
{
if (e != NULL &&
(ec == ELFCLASS32 || ec == ELFCLASS64))
return (_libelf_ehdr(e, ec, 1));
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
int
gelf_update_ehdr(Elf *e, GElf_Ehdr *s)
{
int ec;
void *ehdr;
Elf32_Ehdr *eh32;
Elf64_Ehdr *eh64;
if (s== NULL || e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (e->e_cmd == ELF_C_READ) {
LIBELF_SET_ERROR(MODE, 0);
return (0);
}
if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
return (0);
(void) elf_flagehdr(e, ELF_C_SET, ELF_F_DIRTY);
if (ec == ELFCLASS64) {
eh64 = (Elf64_Ehdr *) ehdr;
*eh64 = *s;
return (1);
}
eh32 = (Elf32_Ehdr *) ehdr;
(void) memcpy(eh32->e_ident, s->e_ident, sizeof(eh32->e_ident));
eh32->e_type = s->e_type;
eh32->e_machine = s->e_machine;
eh32->e_version = s->e_version;
LIBELF_COPY_U32(eh32, s, e_entry);
LIBELF_COPY_U32(eh32, s, e_phoff);
LIBELF_COPY_U32(eh32, s, e_shoff);
eh32->e_flags = s->e_flags;
eh32->e_ehsize = s->e_ehsize;
eh32->e_phentsize = s->e_phentsize;
eh32->e_phnum = s->e_phnum;
eh32->e_shentsize = s->e_shentsize;
eh32->e_shnum = s->e_shnum;
eh32->e_shstrndx = s->e_shstrndx;
return (1);
}

View File

@ -1,62 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_fsize.c 2225 2011-11-26 18:55:54Z jkoshy $");
size_t
elf32_fsize(Elf_Type t, size_t c, unsigned int v)
{
return (_libelf_fsize(t, ELFCLASS32, v, c));
}
size_t
elf64_fsize(Elf_Type t, size_t c, unsigned int v)
{
return (_libelf_fsize(t, ELFCLASS64, v, c));
}
size_t
gelf_fsize(Elf *e, Elf_Type t, size_t c, unsigned int v)
{
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (e->e_class == ELFCLASS32 || e->e_class == ELFCLASS64)
return (_libelf_fsize(t, e->e_class, v, c));
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}

View File

@ -1,39 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_getclass.c 2225 2011-11-26 18:55:54Z jkoshy $");
int
gelf_getclass(Elf *e)
{
return (e != NULL ? e->e_class : ELFCLASSNONE);
}

View File

@ -1,157 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_move.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Move *
gelf_getmove(Elf_Data *ed, int ndx, GElf_Move *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Move *move32;
Elf64_Move *move64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_MOVE) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_MOVE, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
move32 = (Elf32_Move *) d->d_data.d_buf + ndx;
dst->m_value = move32->m_value;
dst->m_info = (Elf64_Xword) move32->m_info;
dst->m_poffset = (Elf64_Xword) move32->m_poffset;
dst->m_repeat = move32->m_repeat;
dst->m_stride = move32->m_stride;
} else {
move64 = (Elf64_Move *) d->d_data.d_buf + ndx;
*dst = *move64;
}
return (dst);
}
int
gelf_update_move(Elf_Data *ed, int ndx, GElf_Move *gm)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Move *move32;
Elf64_Move *move64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || gm == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_MOVE) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_MOVE, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
move32 = (Elf32_Move *) d->d_data.d_buf + ndx;
move32->m_value = gm->m_value;
LIBELF_COPY_U32(move32, gm, m_info);
LIBELF_COPY_U32(move32, gm, m_poffset);
move32->m_repeat = gm->m_repeat;
move32->m_stride = gm->m_stride;
} else {
move64 = (Elf64_Move *) d->d_data.d_buf + ndx;
*move64 = *gm;
}
return (1);
}

View File

@ -1,178 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include <libelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_phdr.c 2268 2011-12-03 17:05:11Z jkoshy $");
Elf32_Phdr *
elf32_getphdr(Elf *e)
{
return (_libelf_getphdr(e, ELFCLASS32));
}
Elf64_Phdr *
elf64_getphdr(Elf *e)
{
return (_libelf_getphdr(e, ELFCLASS64));
}
GElf_Phdr *
gelf_getphdr(Elf *e, int index, GElf_Phdr *d)
{
int ec;
Elf32_Ehdr *eh32;
Elf64_Ehdr *eh64;
Elf32_Phdr *ep32;
Elf64_Phdr *ep64;
if (d == NULL || e == NULL ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64) ||
(e->e_kind != ELF_K_ELF) || index < 0) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
if ((eh32 = _libelf_ehdr(e, ELFCLASS32, 0)) == NULL ||
((ep32 = _libelf_getphdr(e, ELFCLASS32)) == NULL))
return (NULL);
if (index >= eh32->e_phnum) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ep32 += index;
d->p_type = ep32->p_type;
d->p_offset = ep32->p_offset;
d->p_vaddr = (Elf64_Addr) ep32->p_vaddr;
d->p_paddr = (Elf64_Addr) ep32->p_paddr;
d->p_filesz = (Elf64_Xword) ep32->p_filesz;
d->p_memsz = (Elf64_Xword) ep32->p_memsz;
d->p_flags = ep32->p_flags;
d->p_align = (Elf64_Xword) ep32->p_align;
} else {
if ((eh64 = _libelf_ehdr(e, ELFCLASS64, 0)) == NULL ||
(ep64 = _libelf_getphdr(e, ELFCLASS64)) == NULL)
return (NULL);
if (index >= eh64->e_phnum) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ep64 += index;
*d = *ep64;
}
return (d);
}
Elf32_Phdr *
elf32_newphdr(Elf *e, size_t count)
{
return (_libelf_newphdr(e, ELFCLASS32, count));
}
Elf64_Phdr *
elf64_newphdr(Elf *e, size_t count)
{
return (_libelf_newphdr(e, ELFCLASS64, count));
}
void *
gelf_newphdr(Elf *e, size_t count)
{
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
return (_libelf_newphdr(e, e->e_class, count));
}
int
gelf_update_phdr(Elf *e, int ndx, GElf_Phdr *s)
{
int ec, phnum;
void *ehdr;
Elf32_Phdr *ph32;
Elf64_Phdr *ph64;
if (s == NULL || e == NULL || e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (e->e_cmd == ELF_C_READ) {
LIBELF_SET_ERROR(MODE, 0);
return (0);
}
if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
return (0);
if (ec == ELFCLASS32)
phnum = ((Elf32_Ehdr *) ehdr)->e_phnum;
else
phnum = ((Elf64_Ehdr *) ehdr)->e_phnum;
if (ndx < 0 || ndx > phnum) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
(void) elf_flagphdr(e, ELF_C_SET, ELF_F_DIRTY);
if (ec == ELFCLASS64) {
ph64 = e->e_u.e_elf.e_phdr.e_phdr64 + ndx;
*ph64 = *s;
return (1);
}
ph32 = e->e_u.e_elf.e_phdr.e_phdr32 + ndx;
ph32->p_type = s->p_type;
ph32->p_flags = s->p_flags;
LIBELF_COPY_U32(ph32, s, p_offset);
LIBELF_COPY_U32(ph32, s, p_vaddr);
LIBELF_COPY_U32(ph32, s, p_paddr);
LIBELF_COPY_U32(ph32, s, p_filesz);
LIBELF_COPY_U32(ph32, s, p_memsz);
LIBELF_COPY_U32(ph32, s, p_align);
return (1);
}

View File

@ -1,159 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_rel.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Rel *
gelf_getrel(Elf_Data *ed, int ndx, GElf_Rel *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Rel *rel32;
Elf64_Rel *rel64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_REL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_REL, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
rel32 = (Elf32_Rel *) d->d_data.d_buf + ndx;
dst->r_offset = (Elf64_Addr) rel32->r_offset;
dst->r_info = ELF64_R_INFO(
(Elf64_Xword) ELF32_R_SYM(rel32->r_info),
ELF32_R_TYPE(rel32->r_info));
} else {
rel64 = (Elf64_Rel *) d->d_data.d_buf + ndx;
*dst = *rel64;
}
return (dst);
}
int
gelf_update_rel(Elf_Data *ed, int ndx, GElf_Rel *dr)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Rel *rel32;
Elf64_Rel *rel64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dr == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_REL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_REL, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
rel32 = (Elf32_Rel *) d->d_data.d_buf + ndx;
LIBELF_COPY_U32(rel32, dr, r_offset);
if (ELF64_R_SYM(dr->r_info) > ELF32_R_SYM(~0UL) ||
ELF64_R_TYPE(dr->r_info) > ELF32_R_TYPE(~0U)) {
LIBELF_SET_ERROR(RANGE, 0);
return (0);
}
rel32->r_info = ELF32_R_INFO(ELF64_R_SYM(dr->r_info),
ELF64_R_TYPE(dr->r_info));
} else {
rel64 = (Elf64_Rel *) d->d_data.d_buf + ndx;
*rel64 = *dr;
}
return (1);
}

View File

@ -1,162 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_rela.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Rela *
gelf_getrela(Elf_Data *ed, int ndx, GElf_Rela *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Rela *rela32;
Elf64_Rela *rela64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_RELA) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_RELA, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
rela32 = (Elf32_Rela *) d->d_data.d_buf + ndx;
dst->r_offset = (Elf64_Addr) rela32->r_offset;
dst->r_info = ELF64_R_INFO(
(Elf64_Xword) ELF32_R_SYM(rela32->r_info),
ELF32_R_TYPE(rela32->r_info));
dst->r_addend = (Elf64_Sxword) rela32->r_addend;
} else {
rela64 = (Elf64_Rela *) d->d_data.d_buf + ndx;
*dst = *rela64;
}
return (dst);
}
int
gelf_update_rela(Elf_Data *ed, int ndx, GElf_Rela *dr)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Rela *rela32;
Elf64_Rela *rela64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dr == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_RELA) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_RELA, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
rela32 = (Elf32_Rela *) d->d_data.d_buf + ndx;
LIBELF_COPY_U32(rela32, dr, r_offset);
if (ELF64_R_SYM(dr->r_info) > ELF32_R_SYM(~0UL) ||
ELF64_R_TYPE(dr->r_info) > ELF32_R_TYPE(~0U)) {
LIBELF_SET_ERROR(RANGE, 0);
return (0);
}
rela32->r_info = ELF32_R_INFO(ELF64_R_SYM(dr->r_info),
ELF64_R_TYPE(dr->r_info));
LIBELF_COPY_S32(rela32, dr, r_addend);
} else {
rela64 = (Elf64_Rela *) d->d_data.d_buf + ndx;
*rela64 = *dr;
}
return (1);
}

View File

@ -1,131 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <libelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_shdr.c 2268 2011-12-03 17:05:11Z jkoshy $");
Elf32_Shdr *
elf32_getshdr(Elf_Scn *s)
{
return (_libelf_getshdr(s, ELFCLASS32));
}
Elf64_Shdr *
elf64_getshdr(Elf_Scn *s)
{
return (_libelf_getshdr(s, ELFCLASS64));
}
GElf_Shdr *
gelf_getshdr(Elf_Scn *s, GElf_Shdr *d)
{
int ec;
void *sh;
Elf32_Shdr *sh32;
Elf64_Shdr *sh64;
if (d == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if ((sh = _libelf_getshdr(s, ELFCLASSNONE)) == NULL)
return (NULL);
ec = s->s_elf->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32) {
sh32 = (Elf32_Shdr *) sh;
d->sh_name = sh32->sh_name;
d->sh_type = sh32->sh_type;
d->sh_flags = (Elf64_Xword) sh32->sh_flags;
d->sh_addr = (Elf64_Addr) sh32->sh_addr;
d->sh_offset = (Elf64_Off) sh32->sh_offset;
d->sh_size = (Elf64_Xword) sh32->sh_size;
d->sh_link = sh32->sh_link;
d->sh_info = sh32->sh_info;
d->sh_addralign = (Elf64_Xword) sh32->sh_addralign;
d->sh_entsize = (Elf64_Xword) sh32->sh_entsize;
} else {
sh64 = (Elf64_Shdr *) sh;
*d = *sh64;
}
return (d);
}
int
gelf_update_shdr(Elf_Scn *scn, GElf_Shdr *s)
{
int ec;
Elf *e;
Elf32_Shdr *sh32;
if (s == NULL || scn == NULL || (e = scn->s_elf) == NULL ||
e->e_kind != ELF_K_ELF ||
((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (e->e_cmd == ELF_C_READ) {
LIBELF_SET_ERROR(MODE, 0);
return (0);
}
(void) elf_flagscn(scn, ELF_C_SET, ELF_F_DIRTY);
if (ec == ELFCLASS64) {
scn->s_shdr.s_shdr64 = *s;
return (1);
}
sh32 = &scn->s_shdr.s_shdr32;
sh32->sh_name = s->sh_name;
sh32->sh_type = s->sh_type;
LIBELF_COPY_U32(sh32, s, sh_flags);
LIBELF_COPY_U32(sh32, s, sh_addr);
LIBELF_COPY_U32(sh32, s, sh_offset);
LIBELF_COPY_U32(sh32, s, sh_size);
sh32->sh_link = s->sh_link;
sh32->sh_info = s->sh_info;
LIBELF_COPY_U32(sh32, s, sh_addralign);
LIBELF_COPY_U32(sh32, s, sh_entsize);
return (1);
}

View File

@ -1,160 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <limits.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_sym.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Sym *
gelf_getsym(Elf_Data *ed, int ndx, GElf_Sym *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Sym *sym32;
Elf64_Sym *sym64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_SYM) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_SYM, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
sym32 = (Elf32_Sym *) d->d_data.d_buf + ndx;
dst->st_name = sym32->st_name;
dst->st_value = (Elf64_Addr) sym32->st_value;
dst->st_size = (Elf64_Xword) sym32->st_size;
dst->st_info = ELF64_ST_INFO(ELF32_ST_BIND(sym32->st_info),
ELF32_ST_TYPE(sym32->st_info));
dst->st_other = sym32->st_other;
dst->st_shndx = sym32->st_shndx;
} else {
sym64 = (Elf64_Sym *) d->d_data.d_buf + ndx;
*dst = *sym64;
}
return (dst);
}
int
gelf_update_sym(Elf_Data *ed, int ndx, GElf_Sym *gs)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
Elf32_Sym *sym32;
Elf64_Sym *sym64;
struct _Libelf_Data *d;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || gs == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_SYM) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_SYM, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
sym32 = (Elf32_Sym *) d->d_data.d_buf + ndx;
sym32->st_name = gs->st_name;
sym32->st_info = gs->st_info;
sym32->st_other = gs->st_other;
sym32->st_shndx = gs->st_shndx;
LIBELF_COPY_U32(sym32, gs, st_value);
LIBELF_COPY_U32(sym32, gs, st_size);
} else {
sym64 = (Elf64_Sym *) d->d_data.d_buf + ndx;
*sym64 = *gs;
}
return (1);
}

View File

@ -1,151 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_syminfo.c 2272 2011-12-03 17:07:31Z jkoshy $");
GElf_Syminfo *
gelf_getsyminfo(Elf_Data *ed, int ndx, GElf_Syminfo *dst)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
struct _Libelf_Data *d;
Elf32_Syminfo *syminfo32;
Elf64_Syminfo *syminfo64;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || dst == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_SYMINFO) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_SYMINFO, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
syminfo32 = (Elf32_Syminfo *) d->d_data.d_buf + ndx;
dst->si_boundto = syminfo32->si_boundto;
dst->si_flags = syminfo32->si_flags;
} else {
syminfo64 = (Elf64_Syminfo *) d->d_data.d_buf + ndx;
*dst = *syminfo64;
}
return (dst);
}
int
gelf_update_syminfo(Elf_Data *ed, int ndx, GElf_Syminfo *gs)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
struct _Libelf_Data *d;
Elf32_Syminfo *syminfo32;
Elf64_Syminfo *syminfo64;
d = (struct _Libelf_Data *) ed;
if (d == NULL || ndx < 0 || gs == NULL ||
(scn = d->d_scn) == NULL ||
(e = scn->s_elf) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_SYMINFO) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_SYMINFO, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= d->d_data.d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
if (ec == ELFCLASS32) {
syminfo32 = (Elf32_Syminfo *) d->d_data.d_buf + ndx;
syminfo32->si_boundto = gs->si_boundto;
syminfo32->si_flags = gs->si_flags;
} else {
syminfo64 = (Elf64_Syminfo *) d->d_data.d_buf + ndx;
*syminfo64 = *gs;
}
return (1);
}

View File

@ -1,136 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_symshndx.c 2283 2011-12-04 04:07:24Z jkoshy $");
GElf_Sym *
gelf_getsymshndx(Elf_Data *d, Elf_Data *id, int ndx, GElf_Sym *dst,
Elf32_Word *shindex)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
struct _Libelf_Data *ld, *lid;
ld = (struct _Libelf_Data *) d;
lid = (struct _Libelf_Data *) id;
if (gelf_getsym(d, ndx, dst) == 0)
return (NULL);
if (lid == NULL || (scn = lid->d_scn) == NULL ||
(e = scn->s_elf) == NULL || (e != ld->d_scn->s_elf) ||
shindex == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_WORD ||
id->d_type != ELF_T_WORD) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_WORD, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= id->d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
*shindex = ((Elf32_Word *) id->d_buf)[ndx];
return (dst);
}
int
gelf_update_symshndx(Elf_Data *d, Elf_Data *id, int ndx, GElf_Sym *gs,
Elf32_Word xindex)
{
int ec;
Elf *e;
size_t msz;
Elf_Scn *scn;
uint32_t sh_type;
struct _Libelf_Data *ld, *lid;
ld = (struct _Libelf_Data *) d;
lid = (struct _Libelf_Data *) id;
if (gelf_update_sym(d, ndx, gs) == 0)
return (0);
if (lid == NULL || (scn = lid->d_scn) == NULL ||
(e = scn->s_elf) == NULL || (e != ld->d_scn->s_elf)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
ec = e->e_class;
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (ec == ELFCLASS32)
sh_type = scn->s_shdr.s_shdr32.sh_type;
else
sh_type = scn->s_shdr.s_shdr64.sh_type;
if (_libelf_xlate_shtype(sh_type) != ELF_T_WORD ||
d->d_type != ELF_T_WORD) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
msz = _libelf_msize(ELF_T_WORD, ec, e->e_version);
assert(msz > 0);
if (msz * ndx >= id->d_size) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0);
}
*(((Elf32_Word *) id->d_buf) + ndx) = xindex;
return (1);
}

View File

@ -1,81 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include <libelf.h>
#include <string.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: gelf_xlate.c 2225 2011-11-26 18:55:54Z jkoshy $");
Elf_Data *
elf32_xlatetof(Elf_Data *dst, const Elf_Data *src, unsigned int encoding)
{
return _libelf_xlate(dst, src, encoding, ELFCLASS32, ELF_TOFILE);
}
Elf_Data *
elf64_xlatetof(Elf_Data *dst, const Elf_Data *src, unsigned int encoding)
{
return _libelf_xlate(dst, src, encoding, ELFCLASS64, ELF_TOFILE);
}
Elf_Data *
elf32_xlatetom(Elf_Data *dst, const Elf_Data *src, unsigned int encoding)
{
return _libelf_xlate(dst, src, encoding, ELFCLASS32, ELF_TOMEMORY);
}
Elf_Data *
elf64_xlatetom(Elf_Data *dst, const Elf_Data *src, unsigned int encoding)
{
return _libelf_xlate(dst, src, encoding, ELFCLASS64, ELF_TOMEMORY);
}
Elf_Data *
gelf_xlatetom(Elf *e, Elf_Data *dst, const Elf_Data *src,
unsigned int encoding)
{
if (e != NULL)
return (_libelf_xlate(dst, src, encoding, e->e_class,
ELF_TOMEMORY));
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
Elf_Data *
gelf_xlatetof(Elf *e, Elf_Data *dst, const Elf_Data *src,
unsigned int encoding)
{
if (e != NULL)
return (_libelf_xlate(dst, src, encoding, e->e_class,
ELF_TOFILE));
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}

View File

@ -1,250 +0,0 @@
/*-
* Copyright (c) 2006,2008-2010 Joseph Koshy
* 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.
*
* $Id: libelf.h 2366 2011-12-29 06:12:14Z jkoshy $
*/
#ifndef _LIBELF_H_
#define _LIBELF_H_
#include <sys/types.h>
#include <elfdefinitions.h>
/* Library private data structures */
typedef struct _Elf Elf;
typedef struct _Elf_Scn Elf_Scn;
/* File types */
typedef enum {
ELF_K_NONE = 0,
ELF_K_AR, /* `ar' archives */
ELF_K_COFF, /* COFF files (unsupported) */
ELF_K_ELF, /* ELF files */
ELF_K_NUM
} Elf_Kind;
#define ELF_K_FIRST ELF_K_NONE
#define ELF_K_LAST ELF_K_NUM
/* Data types */
typedef enum {
ELF_T_ADDR,
ELF_T_BYTE,
ELF_T_CAP,
ELF_T_DYN,
ELF_T_EHDR,
ELF_T_HALF,
ELF_T_LWORD,
ELF_T_MOVE,
ELF_T_MOVEP,
ELF_T_NOTE,
ELF_T_OFF,
ELF_T_PHDR,
ELF_T_REL,
ELF_T_RELA,
ELF_T_SHDR,
ELF_T_SWORD,
ELF_T_SXWORD,
ELF_T_SYMINFO,
ELF_T_SYM,
ELF_T_VDEF,
ELF_T_VNEED,
ELF_T_WORD,
ELF_T_XWORD,
ELF_T_GNUHASH, /* GNU style hash tables. */
ELF_T_NUM
} Elf_Type;
#define ELF_T_FIRST ELF_T_ADDR
#define ELF_T_LAST ELF_T_GNUHASH
/* Commands */
typedef enum {
ELF_C_NULL = 0,
ELF_C_CLR,
ELF_C_FDDONE,
ELF_C_FDREAD,
ELF_C_RDWR,
ELF_C_READ,
ELF_C_SET,
ELF_C_WRITE,
ELF_C_NUM
} Elf_Cmd;
#define ELF_C_FIRST ELF_C_NULL
#define ELF_C_LAST ELF_C_NUM
/*
* An `Elf_Data' structure describes data in an
* ELF section.
*/
typedef struct _Elf_Data {
/*
* `Public' members that are part of the ELF(3) API.
*/
uint64_t d_align;
void *d_buf;
uint64_t d_off;
uint64_t d_size;
Elf_Type d_type;
unsigned int d_version;
} Elf_Data;
/*
* An `Elf_Arhdr' structure describes an archive
* header.
*/
typedef struct {
time_t ar_date;
char *ar_name; /* archive member name */
gid_t ar_gid;
mode_t ar_mode;
char *ar_rawname; /* 'raw' member name */
size_t ar_size;
uid_t ar_uid;
/*
* Members that are not part of the public API.
*/
int ar_flags;
} Elf_Arhdr;
/*
* An `Elf_Arsym' describes an entry in the archive
* symbol table.
*/
typedef struct {
off_t as_off; /* byte offset to member's header */
unsigned long as_hash; /* elf_hash() value for name */
char *as_name; /* null terminated symbol name */
} Elf_Arsym;
/*
* Error numbers.
*/
enum Elf_Error {
ELF_E_NONE, /* No error */
ELF_E_ARCHIVE, /* Malformed ar(1) archive */
ELF_E_ARGUMENT, /* Invalid argument */
ELF_E_CLASS, /* Mismatched ELF class */
ELF_E_DATA, /* Invalid data descriptor */
ELF_E_HEADER, /* Missing or malformed ELF header */
ELF_E_IO, /* I/O error */
ELF_E_LAYOUT, /* Layout constraint violation */
ELF_E_MODE, /* Wrong mode for ELF descriptor */
ELF_E_RANGE, /* Value out of range */
ELF_E_RESOURCE, /* Resource exhaustion */
ELF_E_SECTION, /* Invalid section descriptor */
ELF_E_SEQUENCE, /* API calls out of sequence */
ELF_E_UNIMPL, /* Feature is unimplemented */
ELF_E_VERSION, /* Unknown API version */
ELF_E_NUM /* Max error number */
};
/*
* Flags defined by the API.
*/
#define ELF_F_LAYOUT 0x001U /* application will layout the file */
#define ELF_F_DIRTY 0x002U /* a section or ELF file is dirty */
/* ELF(3) API extensions. */
#define ELF_F_ARCHIVE 0x100U /* archive creation */
#define ELF_F_ARCHIVE_SYSV 0x200U /* SYSV style archive */
Elf *elf_begin(int _fd, Elf_Cmd _cmd, Elf *_elf);
int elf_cntl(Elf *_elf, Elf_Cmd _cmd);
int elf_end(Elf *_elf);
const char *elf_errmsg(int _error);
int elf_errno(void);
void elf_fill(int _fill);
unsigned int elf_flagarhdr(Elf_Arhdr *_arh, Elf_Cmd _cmd,
unsigned int _flags);
unsigned int elf_flagdata(Elf_Data *_data, Elf_Cmd _cmd,
unsigned int _flags);
unsigned int elf_flagehdr(Elf *_elf, Elf_Cmd _cmd, unsigned int _flags);
unsigned int elf_flagelf(Elf *_elf, Elf_Cmd _cmd, unsigned int _flags);
unsigned int elf_flagphdr(Elf *_elf, Elf_Cmd _cmd, unsigned int _flags);
unsigned int elf_flagscn(Elf_Scn *_scn, Elf_Cmd _cmd, unsigned int _flags);
unsigned int elf_flagshdr(Elf_Scn *_scn, Elf_Cmd _cmd, unsigned int _flags);
Elf_Arhdr *elf_getarhdr(Elf *_elf);
Elf_Arsym *elf_getarsym(Elf *_elf, size_t *_ptr);
off_t elf_getbase(Elf *_elf);
Elf_Data *elf_getdata(Elf_Scn *, Elf_Data *);
char *elf_getident(Elf *_elf, size_t *_ptr);
int elf_getphdrnum(Elf *_elf, size_t *_dst);
int elf_getphnum(Elf *_elf, size_t *_dst); /* Deprecated */
Elf_Scn *elf_getscn(Elf *_elf, size_t _index);
int elf_getshdrnum(Elf *_elf, size_t *_dst);
int elf_getshnum(Elf *_elf, size_t *_dst); /* Deprecated */
int elf_getshdrstrndx(Elf *_elf, size_t *_dst);
int elf_getshstrndx(Elf *_elf, size_t *_dst); /* Deprecated */
unsigned long elf_hash(const char *_name);
Elf_Kind elf_kind(Elf *_elf);
Elf *elf_memory(char *_image, size_t _size);
size_t elf_ndxscn(Elf_Scn *_scn);
Elf_Data *elf_newdata(Elf_Scn *_scn);
Elf_Scn *elf_newscn(Elf *_elf);
Elf_Scn *elf_nextscn(Elf *_elf, Elf_Scn *_scn);
Elf_Cmd elf_next(Elf *_elf);
Elf *elf_open(int _fd);
Elf *elf_openmemory(char *_image, size_t _size);
off_t elf_rand(Elf *_elf, off_t _off);
Elf_Data *elf_rawdata(Elf_Scn *_scn, Elf_Data *_data);
char *elf_rawfile(Elf *_elf, size_t *_size);
int elf_setshstrndx(Elf *_elf, size_t _shnum);
char *elf_strptr(Elf *_elf, size_t _section, size_t _offset);
off_t elf_update(Elf *_elf, Elf_Cmd _cmd);
unsigned int elf_version(unsigned int _version);
long elf32_checksum(Elf *_elf);
size_t elf32_fsize(Elf_Type _type, size_t _count,
unsigned int _version);
Elf32_Ehdr *elf32_getehdr(Elf *_elf);
Elf32_Phdr *elf32_getphdr(Elf *_elf);
Elf32_Shdr *elf32_getshdr(Elf_Scn *_scn);
Elf32_Ehdr *elf32_newehdr(Elf *_elf);
Elf32_Phdr *elf32_newphdr(Elf *_elf, size_t _count);
Elf_Data *elf32_xlatetof(Elf_Data *_dst, const Elf_Data *_src,
unsigned int _enc);
Elf_Data *elf32_xlatetom(Elf_Data *_dst, const Elf_Data *_src,
unsigned int _enc);
long elf64_checksum(Elf *_elf);
size_t elf64_fsize(Elf_Type _type, size_t _count,
unsigned int _version);
Elf64_Ehdr *elf64_getehdr(Elf *_elf);
Elf64_Phdr *elf64_getphdr(Elf *_elf);
Elf64_Shdr *elf64_getshdr(Elf_Scn *_scn);
Elf64_Ehdr *elf64_newehdr(Elf *_elf);
Elf64_Phdr *elf64_newphdr(Elf *_elf, size_t _count);
Elf_Data *elf64_xlatetof(Elf_Data *_dst, const Elf_Data *_src,
unsigned int _enc);
Elf_Data *elf64_xlatetom(Elf_Data *_dst, const Elf_Data *_src,
unsigned int _enc);
#endif /* _LIBELF_H_ */

View File

@ -1,137 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <sys/types.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_align.c 2225 2011-11-26 18:55:54Z jkoshy $");
struct align {
int a32;
int a64;
};
#ifdef __GNUC__
#define MALIGN(N) { \
.a32 = __alignof__(Elf32_##N), \
.a64 = __alignof__(Elf64_##N) \
}
#define MALIGN64(V) { \
.a32 = 0, \
.a64 = __alignof__(Elf64_##V) \
}
#define MALIGN_WORD() { \
.a32 = __alignof__(int32_t), \
.a64 = __alignof__(int64_t) \
}
#else
#error Need the __alignof__ builtin.
#endif
#define UNSUPPORTED() { \
.a32 = 0, \
.a64 = 0 \
}
static struct align malign[ELF_T_NUM] = {
[ELF_T_ADDR] = MALIGN(Addr),
[ELF_T_BYTE] = { .a32 = 1, .a64 = 1 },
[ELF_T_CAP] = MALIGN(Cap),
[ELF_T_DYN] = MALIGN(Dyn),
[ELF_T_EHDR] = MALIGN(Ehdr),
[ELF_T_HALF] = MALIGN(Half),
[ELF_T_LWORD] = MALIGN(Lword),
[ELF_T_MOVE] = MALIGN(Move),
[ELF_T_MOVEP] = UNSUPPORTED(),
[ELF_T_NOTE] = MALIGN(Nhdr),
[ELF_T_OFF] = MALIGN(Off),
[ELF_T_PHDR] = MALIGN(Phdr),
[ELF_T_REL] = MALIGN(Rel),
[ELF_T_RELA] = MALIGN(Rela),
[ELF_T_SHDR] = MALIGN(Shdr),
[ELF_T_SWORD] = MALIGN(Sword),
[ELF_T_SXWORD] = MALIGN64(Sxword),
[ELF_T_SYM] = MALIGN(Sym),
[ELF_T_SYMINFO] = MALIGN(Syminfo),
[ELF_T_VDEF] = MALIGN(Verdef),
[ELF_T_VNEED] = MALIGN(Verneed),
[ELF_T_WORD] = MALIGN(Word),
[ELF_T_XWORD] = MALIGN64(Xword),
[ELF_T_GNUHASH] = MALIGN_WORD()
};
int
_libelf_malign(Elf_Type t, int elfclass)
{
if (t >= ELF_T_NUM || (int) t < 0)
return (0);
return (elfclass == ELFCLASS32 ? malign[t].a32 :
malign[t].a64);
}
#define FALIGN(A32,A64) { .a32 = (A32), .a64 = (A64) }
static struct align falign[ELF_T_NUM] = {
[ELF_T_ADDR] = FALIGN(4,8),
[ELF_T_BYTE] = FALIGN(1,1),
[ELF_T_CAP] = FALIGN(4,8),
[ELF_T_DYN] = FALIGN(4,8),
[ELF_T_EHDR] = FALIGN(4,8),
[ELF_T_HALF] = FALIGN(2,2),
[ELF_T_LWORD] = FALIGN(8,8),
[ELF_T_MOVE] = FALIGN(8,8),
[ELF_T_MOVEP] = UNSUPPORTED(),
[ELF_T_NOTE] = FALIGN(4,4),
[ELF_T_OFF] = FALIGN(4,8),
[ELF_T_PHDR] = FALIGN(4,8),
[ELF_T_REL] = FALIGN(4,8),
[ELF_T_RELA] = FALIGN(4,8),
[ELF_T_SHDR] = FALIGN(4,8),
[ELF_T_SWORD] = FALIGN(4,4),
[ELF_T_SXWORD] = FALIGN(0,8),
[ELF_T_SYM] = FALIGN(4,8),
[ELF_T_SYMINFO] = FALIGN(2,2),
[ELF_T_VDEF] = FALIGN(4,4),
[ELF_T_VNEED] = FALIGN(4,4),
[ELF_T_WORD] = FALIGN(4,4),
[ELF_T_XWORD] = FALIGN(0,8),
[ELF_T_GNUHASH] = FALIGN(4,8)
};
int
_libelf_falign(Elf_Type t, int elfclass)
{
if (t >= ELF_T_NUM || (int) t < 0)
return (0);
return (elfclass == ELFCLASS32 ? falign[t].a32 :
falign[t].a64);
}

View File

@ -1,212 +0,0 @@
/*-
* Copyright (c) 2006,2008,2010 Joseph Koshy
* 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.
*/
/*
* Internal APIs
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <errno.h>
#include <libelf.h>
#include <stdlib.h>
#include <string.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_allocate.c 2272 2011-12-03 17:07:31Z jkoshy $");
Elf *
_libelf_allocate_elf(void)
{
Elf *e;
if ((e = malloc(sizeof(*e))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, errno);
return NULL;
}
e->e_activations = 1;
e->e_hdr.e_rawhdr = NULL;
e->e_byteorder = ELFDATANONE;
e->e_class = ELFCLASSNONE;
e->e_cmd = ELF_C_NULL;
e->e_fd = -1;
e->e_flags = 0;
e->e_kind = ELF_K_NONE;
e->e_parent = NULL;
e->e_rawfile = NULL;
e->e_rawsize = 0;
e->e_version = LIBELF_PRIVATE(version);
(void) memset(&e->e_u, 0, sizeof(e->e_u));
return (e);
}
void
_libelf_init_elf(Elf *e, Elf_Kind kind)
{
assert(e != NULL);
assert(e->e_kind == ELF_K_NONE);
e->e_kind = kind;
switch (kind) {
case ELF_K_ELF:
STAILQ_INIT(&e->e_u.e_elf.e_scn);
break;
default:
break;
}
}
#define FREE(P) do { \
if (P) \
free(P); \
} while (0)
Elf *
_libelf_release_elf(Elf *e)
{
Elf_Arhdr *arh;
switch (e->e_kind) {
case ELF_K_AR:
FREE(e->e_u.e_ar.e_symtab);
break;
case ELF_K_ELF:
switch (e->e_class) {
case ELFCLASS32:
FREE(e->e_u.e_elf.e_ehdr.e_ehdr32);
FREE(e->e_u.e_elf.e_phdr.e_phdr32);
break;
case ELFCLASS64:
FREE(e->e_u.e_elf.e_ehdr.e_ehdr64);
FREE(e->e_u.e_elf.e_phdr.e_phdr64);
break;
}
assert(STAILQ_EMPTY(&e->e_u.e_elf.e_scn));
if (e->e_flags & LIBELF_F_AR_HEADER) {
arh = e->e_hdr.e_arhdr;
FREE(arh->ar_name);
FREE(arh->ar_rawname);
free(arh);
}
break;
default:
break;
}
free(e);
return (NULL);
}
struct _Libelf_Data *
_libelf_allocate_data(Elf_Scn *s)
{
struct _Libelf_Data *d;
if ((d = calloc((size_t) 1, sizeof(*d))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
d->d_scn = s;
return (d);
}
struct _Libelf_Data *
_libelf_release_data(struct _Libelf_Data *d)
{
if (d->d_flags & LIBELF_F_DATA_MALLOCED)
free(d->d_data.d_buf);
free(d);
return (NULL);
}
Elf_Scn *
_libelf_allocate_scn(Elf *e, size_t ndx)
{
Elf_Scn *s;
if ((s = calloc((size_t) 1, sizeof(Elf_Scn))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, errno);
return (NULL);
}
s->s_elf = e;
s->s_ndx = ndx;
STAILQ_INIT(&s->s_data);
STAILQ_INIT(&s->s_rawdata);
STAILQ_INSERT_TAIL(&e->e_u.e_elf.e_scn, s, s_next);
return (s);
}
Elf_Scn *
_libelf_release_scn(Elf_Scn *s)
{
Elf *e;
struct _Libelf_Data *d, *td;
assert(s != NULL);
STAILQ_FOREACH_SAFE(d, &s->s_data, d_next, td) {
STAILQ_REMOVE(&s->s_data, d, _Libelf_Data, d_next);
d = _libelf_release_data(d);
}
STAILQ_FOREACH_SAFE(d, &s->s_rawdata, d_next, td) {
assert((d->d_flags & LIBELF_F_DATA_MALLOCED) == 0);
STAILQ_REMOVE(&s->s_rawdata, d, _Libelf_Data, d_next);
d = _libelf_release_data(d);
}
e = s->s_elf;
assert(e != NULL);
STAILQ_REMOVE(&e->e_u.e_elf.e_scn, s, _Elf_Scn, s_next);
free(s);
return (NULL);
}

View File

@ -1,461 +0,0 @@
/*-
* Copyright (c) 2006,2008,2010 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <ctype.h>
#include <libelf.h>
#include <stdlib.h>
#include <string.h>
#include "_libelf.h"
#include "_libelf_ar.h"
ELFTC_VCSID("$Id: libelf_ar.c 2225 2011-11-26 18:55:54Z jkoshy $");
#define LIBELF_NALLOC_SIZE 16
/*
* `ar' archive handling.
*
* `ar' archives start with signature `ARMAG'. Each archive member is
* preceded by a header containing meta-data for the member. This
* header is described in <ar.h> (struct ar_hdr). The header always
* starts on an even address. File data is padded with "\n"
* characters to keep this invariant.
*
* Special considerations for `ar' archives:
*
* There are two variants of the `ar' archive format: traditional BSD
* and SVR4. These differ in the way long file names are treated, and
* in the layout of the archive symbol table.
*
* The `ar' header only has space for a 16 character file name.
*
* In the SVR4 format, file names are terminated with a '/', so this
* effectively leaves 15 characters for the actual file name. Longer
* file names stored in a separate 'string table' and referenced
* indirectly from the name field. The string table itself appears as
* an archive member with name "// ". An `indirect' file name in an
* `ar' header matches the pattern "/[0-9]*". The digits form a
* decimal number that corresponds to a byte offset into the string
* table where the actual file name of the object starts. Strings in
* the string table are padded to start on even addresses.
*
* In the BSD format, file names can be upto 16 characters. File
* names shorter than 16 characters are padded to 16 characters using
* (ASCII) space characters. File names with embedded spaces and file
* names longer than 16 characters are stored immediately after the
* archive header and the name field set to a special indirect name
* matching the pattern "#1/[0-9]+". The digits form a decimal number
* that corresponds to the actual length of the file name following
* the archive header. The content of the archive member immediately
* follows the file name, and the size field of the archive member
* holds the sum of the sizes of the member and of the appended file
* name.
*
* Archives may also have a symbol table (see ranlib(1)), mapping
* program symbols to object files inside the archive.
*
* In the SVR4 format, a symbol table uses a file name of "/ " in its
* archive header. The symbol table is structured as:
* - a 4-byte count of entries stored as a binary value, MSB first
* - 'n' 4-byte offsets, stored as binary values, MSB first
* - 'n' NUL-terminated strings, for ELF symbol names, stored unpadded.
*
* In the BSD format, the symbol table uses a file name of "__.SYMDEF".
* It is structured as two parts:
* - The first part is an array of "ranlib" structures preceded by
* the size of the array in bytes. Each "ranlib" structure
* describes one symbol. Each structure contains an offset into
* the string table for the symbol name, and a file offset into the
* archive for the member defining the symbol.
* - The second part is a string table containing NUL-terminated
* strings, preceded by the size of the string table in bytes.
*
* If the symbol table and string table are is present in an archive
* they must be the very first objects and in that order.
*/
/*
* Retrieve an archive header descriptor.
*/
Elf_Arhdr *
_libelf_ar_gethdr(Elf *e)
{
Elf *parent;
char *namelen;
Elf_Arhdr *eh;
size_t n, nlen;
struct ar_hdr *arh;
if ((parent = e->e_parent) == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
assert((e->e_flags & LIBELF_F_AR_HEADER) == 0);
arh = (struct ar_hdr *) (uintptr_t) e->e_hdr.e_rawhdr;
assert((uintptr_t) arh >= (uintptr_t) parent->e_rawfile + SARMAG);
assert((uintptr_t) arh <= (uintptr_t) parent->e_rawfile +
parent->e_rawsize - sizeof(struct ar_hdr));
if ((eh = malloc(sizeof(Elf_Arhdr))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
e->e_hdr.e_arhdr = eh;
e->e_flags |= LIBELF_F_AR_HEADER;
eh->ar_name = eh->ar_rawname = NULL;
if ((eh->ar_name = _libelf_ar_get_translated_name(arh, parent)) ==
NULL)
goto error;
if (_libelf_ar_get_number(arh->ar_uid, sizeof(arh->ar_uid), 10,
&n) == 0)
goto error;
eh->ar_uid = (uid_t) n;
if (_libelf_ar_get_number(arh->ar_gid, sizeof(arh->ar_gid), 10,
&n) == 0)
goto error;
eh->ar_gid = (gid_t) n;
if (_libelf_ar_get_number(arh->ar_mode, sizeof(arh->ar_mode), 8,
&n) == 0)
goto error;
eh->ar_mode = (mode_t) n;
if (_libelf_ar_get_number(arh->ar_size, sizeof(arh->ar_size), 10,
&n) == 0)
goto error;
/*
* Get the true size of the member if extended naming is being used.
*/
if (IS_EXTENDED_BSD_NAME(arh->ar_name)) {
namelen = arh->ar_name +
LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE;
if (_libelf_ar_get_number(namelen, sizeof(arh->ar_name) -
LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE, 10, &nlen) == 0)
goto error;
n -= nlen;
}
eh->ar_size = n;
if ((eh->ar_rawname = _libelf_ar_get_raw_name(arh)) == NULL)
goto error;
eh->ar_flags = 0;
return (eh);
error:
if (eh) {
if (eh->ar_name)
free(eh->ar_name);
if (eh->ar_rawname)
free(eh->ar_rawname);
free(eh);
}
e->e_flags &= ~LIBELF_F_AR_HEADER;
e->e_hdr.e_rawhdr = (char *) arh;
return (NULL);
}
Elf *
_libelf_ar_open_member(int fd, Elf_Cmd c, Elf *elf)
{
Elf *e;
char *member, *namelen;
size_t nsz, sz;
off_t next;
struct ar_hdr *arh;
assert(elf->e_kind == ELF_K_AR);
next = elf->e_u.e_ar.e_next;
/*
* `next' is only set to zero by elf_next() when the last
* member of an archive is processed.
*/
if (next == (off_t) 0)
return (NULL);
assert((next & 1) == 0);
arh = (struct ar_hdr *) (elf->e_rawfile + next);
/*
* Retrieve the size of the member.
*/
if (_libelf_ar_get_number(arh->ar_size, sizeof(arh->ar_size), 10,
&sz) == 0) {
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}
/*
* Adjust the size field for members in BSD archives using
* extended naming.
*/
if (IS_EXTENDED_BSD_NAME(arh->ar_name)) {
namelen = arh->ar_name +
LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE;
if (_libelf_ar_get_number(namelen, sizeof(arh->ar_name) -
LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE, 10, &nsz) == 0) {
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}
member = (char *) (arh + 1) + nsz;
sz -= nsz;
} else
member = (char *) (arh + 1);
if ((e = elf_memory((char *) member, sz)) == NULL)
return (NULL);
e->e_fd = fd;
e->e_cmd = c;
e->e_hdr.e_rawhdr = (char *) arh;
elf->e_u.e_ar.e_nchildren++;
e->e_parent = elf;
return (e);
}
/*
* A BSD-style ar(1) symbol table has the following layout:
*
* - A count of bytes used by the following array of 'ranlib'
* structures, stored as a 'long'.
* - An array of 'ranlib' structures. Each array element is
* two 'long's in size.
* - A count of bytes used for the following symbol table.
* - The symbol table itself.
*/
/*
* A helper macro to read in a 'long' value from the archive. We use
* memcpy() since the source pointer may be misaligned with respect to
* the natural alignment for a C 'long'.
*/
#define GET_LONG(P, V)do { \
memcpy(&(V), (P), sizeof(long)); \
(P) += sizeof(long); \
} while (0)
Elf_Arsym *
_libelf_ar_process_bsd_symtab(Elf *e, size_t *count)
{
Elf_Arsym *symtab, *sym;
unsigned char *end, *p, *p0, *s, *s0;
const unsigned int entrysize = 2 * sizeof(long);
long arraysize, fileoffset, n, nentries, stroffset, strtabsize;
assert(e != NULL);
assert(count != NULL);
assert(e->e_u.e_ar.e_symtab == NULL);
symtab = NULL;
/*
* The BSD symbol table always contains the count fields even
* if there are no entries in it.
*/
if (e->e_u.e_ar.e_rawsymtabsz < 2 * sizeof(long))
goto symtaberror;
p = p0 = (unsigned char *) e->e_u.e_ar.e_rawsymtab;
end = p0 + e->e_u.e_ar.e_rawsymtabsz;
/*
* Retrieve the size of the array of ranlib descriptors and
* check it for validity.
*/
GET_LONG(p, arraysize);
if (p0 + arraysize >= end || (arraysize % entrysize != 0))
goto symtaberror;
/*
* Check the value of the string table size.
*/
s = p + arraysize;
GET_LONG(s, strtabsize);
s0 = s; /* Start of string table. */
if (s0 + strtabsize > end)
goto symtaberror;
nentries = arraysize / entrysize;
/*
* Allocate space for the returned Elf_Arsym array.
*/
if ((symtab = malloc(sizeof(Elf_Arsym) * (nentries + 1))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
/* Read in symbol table entries. */
for (n = 0, sym = symtab; n < nentries; n++, sym++) {
GET_LONG(p, stroffset);
GET_LONG(p, fileoffset);
s = s0 + stroffset;
if (s >= end)
goto symtaberror;
sym->as_off = fileoffset;
sym->as_hash = elf_hash((char *) s);
sym->as_name = (char *) s;
}
/* Fill up the sentinel entry. */
sym->as_name = NULL;
sym->as_hash = ~0UL;
sym->as_off = (off_t) 0;
/* Remember the processed symbol table. */
e->e_u.e_ar.e_symtab = symtab;
*count = e->e_u.e_ar.e_symtabsz = nentries + 1;
return (symtab);
symtaberror:
if (symtab)
free(symtab);
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}
/*
* An SVR4-style ar(1) symbol table has the following layout:
*
* - The first 4 bytes are a binary count of the number of entries in the
* symbol table, stored MSB-first.
* - Then there are 'n' 4-byte binary offsets, also stored MSB first.
* - Following this, there are 'n' null-terminated strings.
*/
#define GET_WORD(P, V) do { \
(V) = 0; \
(V) = (P)[0]; (V) <<= 8; \
(V) += (P)[1]; (V) <<= 8; \
(V) += (P)[2]; (V) <<= 8; \
(V) += (P)[3]; \
} while (0)
#define INTSZ 4
Elf_Arsym *
_libelf_ar_process_svr4_symtab(Elf *e, size_t *count)
{
size_t n, nentries, off;
Elf_Arsym *symtab, *sym;
unsigned char *p, *s, *end;
assert(e != NULL);
assert(count != NULL);
assert(e->e_u.e_ar.e_symtab == NULL);
symtab = NULL;
if (e->e_u.e_ar.e_rawsymtabsz < INTSZ)
goto symtaberror;
p = (unsigned char *) e->e_u.e_ar.e_rawsymtab;
end = p + e->e_u.e_ar.e_rawsymtabsz;
GET_WORD(p, nentries);
p += INTSZ;
if (nentries == 0 || p + nentries * INTSZ >= end)
goto symtaberror;
/* Allocate space for a nentries + a sentinel. */
if ((symtab = malloc(sizeof(Elf_Arsym) * (nentries+1))) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
s = p + (nentries * INTSZ); /* start of the string table. */
for (n = nentries, sym = symtab; n > 0; n--) {
if (s >= end)
goto symtaberror;
off = 0;
GET_WORD(p, off);
sym->as_off = off;
sym->as_hash = elf_hash((char *) s);
sym->as_name = (char *) s;
p += INTSZ;
sym++;
for (; s < end && *s++ != '\0';) /* skip to next string */
;
}
/* Fill up the sentinel entry. */
sym->as_name = NULL;
sym->as_hash = ~0UL;
sym->as_off = (off_t) 0;
*count = e->e_u.e_ar.e_symtabsz = nentries + 1;
e->e_u.e_ar.e_symtab = symtab;
return (symtab);
symtaberror:
if (symtab)
free(symtab);
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}

View File

@ -1,359 +0,0 @@
/*-
* Copyright (c) 2006,2009,2010 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <libelf.h>
#include <stdlib.h>
#include <string.h>
#include "_libelf.h"
#include "_libelf_ar.h"
ELFTC_VCSID("$Id: libelf_ar_util.c 2365 2011-12-29 04:36:44Z jkoshy $");
/*
* Convert a string bounded by `start' and `start+sz' (exclusive) to a
* number in the specified base.
*/
int
_libelf_ar_get_number(const char *s, size_t sz, int base, size_t *ret)
{
int c, v;
size_t r;
const char *e;
assert(base <= 10);
e = s + sz;
/* skip leading blanks */
for (;s < e && (c = *s) == ' '; s++)
;
r = 0L;
for (;s < e; s++) {
if ((c = *s) == ' ')
break;
if (c < '0' || c > '9')
return (0);
v = c - '0';
if (v >= base) /* Illegal digit. */
break;
r *= base;
r += v;
}
*ret = r;
return (1);
}
/*
* Return the translated name for an archive member.
*/
char *
_libelf_ar_get_translated_name(const struct ar_hdr *arh, Elf *ar)
{
char c, *s;
size_t len, offset;
const char *buf, *p, *q, *r;
const size_t bufsize = sizeof(arh->ar_name);
assert(arh != NULL);
assert(ar->e_kind == ELF_K_AR);
assert((const char *) arh >= ar->e_rawfile &&
(const char *) arh < ar->e_rawfile + ar->e_rawsize);
buf = arh->ar_name;
/*
* Check for extended naming.
*
* If the name matches the pattern "^/[0-9]+", it is an
* SVR4-style extended name. If the name matches the pattern
* "#1/[0-9]+", the entry uses BSD style extended naming.
*/
if (buf[0] == '/' && (c = buf[1]) >= '0' && c <= '9') {
/*
* The value in field ar_name is a decimal offset into
* the archive string table where the actual name
* resides.
*/
if (_libelf_ar_get_number(buf + 1, bufsize - 1, 10,
&offset) == 0) {
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}
if (offset > ar->e_u.e_ar.e_rawstrtabsz) {
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}
p = q = ar->e_u.e_ar.e_rawstrtab + offset;
r = ar->e_u.e_ar.e_rawstrtab + ar->e_u.e_ar.e_rawstrtabsz;
for (; p < r && *p != '/'; p++)
;
len = p - q + 1; /* space for the trailing NUL */
if ((s = malloc(len)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
(void) strncpy(s, q, len - 1);
s[len - 1] = '\0';
return (s);
} else if (IS_EXTENDED_BSD_NAME(buf)) {
r = buf + LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE;
if (_libelf_ar_get_number(r, bufsize -
LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE, 10,
&len) == 0) {
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}
/*
* Allocate space for the file name plus a
* trailing NUL.
*/
if ((s = malloc(len + 1)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
/*
* The file name follows the archive header.
*/
q = (const char *) (arh + 1);
(void) strncpy(s, q, len);
s[len] = '\0';
return (s);
}
/*
* A 'normal' name.
*
* Skip back over trailing blanks from the end of the field.
* In the SVR4 format, a '/' is used as a terminator for
* non-special names.
*/
for (q = buf + bufsize - 1; q >= buf && *q == ' '; --q)
;
if (q >= buf) {
if (*q == '/') {
/*
* SVR4 style names: ignore the trailing
* character '/', but only if the name is not
* one of the special names "/" and "//".
*/
if (q > buf + 1 ||
(q == (buf + 1) && *buf != '/'))
q--;
}
len = q - buf + 2; /* Add space for a trailing NUL. */
} else {
/* The buffer only had blanks. */
buf = "";
len = 1;
}
if ((s = malloc(len)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
(void) strncpy(s, buf, len - 1);
s[len - 1] = '\0';
return (s);
}
/*
* Return the raw name for an archive member, inclusive of any
* formatting characters.
*/
char *
_libelf_ar_get_raw_name(const struct ar_hdr *arh)
{
char *rawname;
const size_t namesz = sizeof(arh->ar_name);
if ((rawname = malloc(namesz + 1)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
(void) strncpy(rawname, arh->ar_name, namesz);
rawname[namesz] = '\0';
return (rawname);
}
/*
* Open an 'ar' archive.
*/
Elf *
_libelf_ar_open(Elf *e, int reporterror)
{
size_t sz;
int scanahead;
char *s, *end;
struct ar_hdr arh;
_libelf_init_elf(e, ELF_K_AR);
e->e_u.e_ar.e_nchildren = 0;
e->e_u.e_ar.e_next = (off_t) -1;
/*
* Look for special members.
*/
s = e->e_rawfile + SARMAG;
end = e->e_rawfile + e->e_rawsize;
assert(e->e_rawsize > 0);
/*
* We use heuristics to determine the flavor of the archive we
* are examining.
*
* SVR4 flavor archives use the name "/ " and "// " for
* special members.
*
* In BSD flavor archives the symbol table, if present, is the
* first archive with name "__.SYMDEF".
*/
#define READ_AR_HEADER(S, ARH, SZ, END) \
do { \
if ((S) + sizeof((ARH)) > (END)) \
goto error; \
(void) memcpy(&(ARH), (S), sizeof((ARH))); \
if ((ARH).ar_fmag[0] != '`' || (ARH).ar_fmag[1] != '\n') \
goto error; \
if (_libelf_ar_get_number((ARH).ar_size, \
sizeof((ARH).ar_size), 10, &(SZ)) == 0) \
goto error; \
} while (0)
READ_AR_HEADER(s, arh, sz, end);
/*
* Handle special archive members for the SVR4 format.
*/
if (arh.ar_name[0] == '/') {
assert(sz > 0);
e->e_flags |= LIBELF_F_AR_VARIANT_SVR4;
scanahead = 0;
/*
* The symbol table (file name "/ ") always comes before the
* string table (file name "// ").
*/
if (arh.ar_name[1] == ' ') {
/* "/ " => symbol table. */
scanahead = 1; /* The string table to follow. */
s += sizeof(arh);
e->e_u.e_ar.e_rawsymtab = s;
e->e_u.e_ar.e_rawsymtabsz = sz;
sz = LIBELF_ADJUST_AR_SIZE(sz);
s += sz;
} else if (arh.ar_name[1] == '/' && arh.ar_name[2] == ' ') {
/* "// " => string table for long file names. */
s += sizeof(arh);
e->e_u.e_ar.e_rawstrtab = s;
e->e_u.e_ar.e_rawstrtabsz = sz;
sz = LIBELF_ADJUST_AR_SIZE(sz);
s += sz;
}
/*
* If the string table hasn't been seen yet, look for
* it in the next member.
*/
if (scanahead) {
READ_AR_HEADER(s, arh, sz, end);
/* "// " => string table for long file names. */
if (arh.ar_name[0] == '/' && arh.ar_name[1] == '/' &&
arh.ar_name[2] == ' ') {
s += sizeof(arh);
e->e_u.e_ar.e_rawstrtab = s;
e->e_u.e_ar.e_rawstrtabsz = sz;
sz = LIBELF_ADJUST_AR_SIZE(sz);
s += sz;
}
}
} else if (strncmp(arh.ar_name, LIBELF_AR_BSD_SYMTAB_NAME,
sizeof(LIBELF_AR_BSD_SYMTAB_NAME) - 1) == 0) {
/*
* BSD style archive symbol table.
*/
s += sizeof(arh);
e->e_u.e_ar.e_rawsymtab = s;
e->e_u.e_ar.e_rawsymtabsz = sz;
sz = LIBELF_ADJUST_AR_SIZE(sz);
s += sz;
}
/*
* Update the 'next' offset, so that a subsequent elf_begin()
* works as expected.
*/
e->e_u.e_ar.e_next = (off_t) (s - e->e_rawfile);
return (e);
error:
if (!reporterror) {
e->e_kind = ELF_K_NONE;
return (e);
}
LIBELF_SET_ERROR(ARCHIVE, 0);
return (NULL);
}

View File

@ -1,100 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_checksum.c 2225 2011-11-26 18:55:54Z jkoshy $");
static unsigned long
_libelf_sum(unsigned long c, const unsigned char *s, size_t size)
{
if (s == NULL || size == 0)
return (c);
while (size--)
c += *s++;
return (c);
}
unsigned long
_libelf_checksum(Elf *e, int elfclass)
{
size_t shn;
Elf_Scn *scn;
Elf_Data *d;
unsigned long checksum;
GElf_Ehdr eh;
GElf_Shdr shdr;
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (0L);
}
if (e->e_class != elfclass) {
LIBELF_SET_ERROR(CLASS, 0);
return (0L);
}
if (gelf_getehdr(e, &eh) == NULL)
return (0);
/*
* Iterate over all sections in the ELF file, computing the
* checksum along the way.
*
* The first section is always SHN_UNDEF and can be skipped.
* Non-allocatable sections are skipped, as are sections that
* could be affected by utilities such as strip(1).
*/
checksum = 0;
for (shn = 1; shn < e->e_u.e_elf.e_nscn; shn++) {
if ((scn = elf_getscn(e, shn)) == NULL)
return (0);
if (gelf_getshdr(scn, &shdr) == NULL)
return (0);
if ((shdr.sh_flags & SHF_ALLOC) == 0 ||
shdr.sh_type == SHT_DYNAMIC ||
shdr.sh_type == SHT_DYNSYM)
continue;
d = NULL;
while ((d = elf_rawdata(scn, d)) != NULL)
checksum = _libelf_sum(checksum,
(unsigned char *) d->d_buf, d->d_size);
}
/*
* Return a 16-bit checksum compatible with Solaris.
*/
return (((checksum >> 16) & 0xFFFFUL) + (checksum & 0xFFFFUL));
}

File diff suppressed because it is too large Load Diff

View File

@ -1,88 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_data.c 2225 2011-11-26 18:55:54Z jkoshy $");
int
_libelf_xlate_shtype(uint32_t sht)
{
switch (sht) {
case SHT_DYNAMIC:
return (ELF_T_DYN);
case SHT_DYNSYM:
return (ELF_T_SYM);
case SHT_FINI_ARRAY:
return (ELF_T_ADDR);
case SHT_GNU_HASH:
return (ELF_T_GNUHASH);
case SHT_GNU_LIBLIST:
return (ELF_T_WORD);
case SHT_GROUP:
return (ELF_T_WORD);
case SHT_HASH:
return (ELF_T_WORD);
case SHT_INIT_ARRAY:
return (ELF_T_ADDR);
case SHT_NOBITS:
return (ELF_T_BYTE);
case SHT_NOTE:
return (ELF_T_NOTE);
case SHT_PREINIT_ARRAY:
return (ELF_T_ADDR);
case SHT_PROGBITS:
return (ELF_T_BYTE);
case SHT_REL:
return (ELF_T_REL);
case SHT_RELA:
return (ELF_T_RELA);
case SHT_STRTAB:
return (ELF_T_BYTE);
case SHT_SYMTAB:
return (ELF_T_SYM);
case SHT_SYMTAB_SHNDX:
return (ELF_T_WORD);
case SHT_SUNW_dof:
return (ELF_T_BYTE);
case SHT_SUNW_move:
return (ELF_T_MOVE);
case SHT_SUNW_syminfo:
return (ELF_T_SYMINFO);
case SHT_SUNW_verdef: /* == SHT_GNU_verdef */
return (ELF_T_VDEF);
case SHT_SUNW_verneed: /* == SHT_GNU_verneed */
return (ELF_T_VNEED);
case SHT_SUNW_versym: /* == SHT_GNU_versym */
return (ELF_T_HALF);
default:
return (-1);
}
}

View File

@ -1,204 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <libelf.h>
#include <stdlib.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_ehdr.c 2225 2011-11-26 18:55:54Z jkoshy $");
/*
* Retrieve counts for sections, phdrs and the section string table index
* from section header #0 of the ELF object.
*/
static int
_libelf_load_extended(Elf *e, int ec, uint64_t shoff, uint16_t phnum,
uint16_t strndx)
{
Elf_Scn *scn;
size_t fsz;
int (*xlator)(char *_d, size_t _dsz, char *_s, size_t _c, int _swap);
uint32_t shtype;
assert(STAILQ_EMPTY(&e->e_u.e_elf.e_scn));
fsz = _libelf_fsize(ELF_T_SHDR, ec, e->e_version, 1);
assert(fsz > 0);
if (e->e_rawsize < shoff + fsz) { /* raw file too small */
LIBELF_SET_ERROR(HEADER, 0);
return (0);
}
if ((scn = _libelf_allocate_scn(e, (size_t) 0)) == NULL)
return (0);
xlator = _libelf_get_translator(ELF_T_SHDR, ELF_TOMEMORY, ec);
(*xlator)((char *) &scn->s_shdr, sizeof(scn->s_shdr),
e->e_rawfile + shoff, (size_t) 1,
e->e_byteorder != LIBELF_PRIVATE(byteorder));
#define GET_SHDR_MEMBER(M) ((ec == ELFCLASS32) ? scn->s_shdr.s_shdr32.M : \
scn->s_shdr.s_shdr64.M)
if ((shtype = GET_SHDR_MEMBER(sh_type)) != SHT_NULL) {
LIBELF_SET_ERROR(SECTION, 0);
return (0);
}
e->e_u.e_elf.e_nscn = GET_SHDR_MEMBER(sh_size);
e->e_u.e_elf.e_nphdr = (phnum != PN_XNUM) ? phnum :
GET_SHDR_MEMBER(sh_info);
e->e_u.e_elf.e_strndx = (strndx != SHN_XINDEX) ? strndx :
GET_SHDR_MEMBER(sh_link);
#undef GET_SHDR_MEMBER
return (1);
}
#define EHDR_INIT(E,SZ) do { \
Elf##SZ##_Ehdr *eh = (E); \
eh->e_ident[EI_MAG0] = ELFMAG0; \
eh->e_ident[EI_MAG1] = ELFMAG1; \
eh->e_ident[EI_MAG2] = ELFMAG2; \
eh->e_ident[EI_MAG3] = ELFMAG3; \
eh->e_ident[EI_CLASS] = ELFCLASS##SZ; \
eh->e_ident[EI_DATA] = ELFDATANONE; \
eh->e_ident[EI_VERSION] = LIBELF_PRIVATE(version); \
eh->e_machine = EM_NONE; \
eh->e_type = ELF_K_NONE; \
eh->e_version = LIBELF_PRIVATE(version); \
} while (0)
void *
_libelf_ehdr(Elf *e, int ec, int allocate)
{
void *ehdr;
size_t fsz, msz;
uint16_t phnum, shnum, strndx;
uint64_t shoff;
int (*xlator)(char *_d, size_t _dsz, char *_s, size_t _c, int _swap);
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (e == NULL || e->e_kind != ELF_K_ELF) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (e->e_class != ELFCLASSNONE && e->e_class != ec) {
LIBELF_SET_ERROR(CLASS, 0);
return (NULL);
}
if (e->e_version != EV_CURRENT) {
LIBELF_SET_ERROR(VERSION, 0);
return (NULL);
}
if (e->e_class == ELFCLASSNONE)
e->e_class = ec;
if (ec == ELFCLASS32)
ehdr = (void *) e->e_u.e_elf.e_ehdr.e_ehdr32;
else
ehdr = (void *) e->e_u.e_elf.e_ehdr.e_ehdr64;
if (ehdr != NULL) /* already have a translated ehdr */
return (ehdr);
fsz = _libelf_fsize(ELF_T_EHDR, ec, e->e_version, (size_t) 1);
assert(fsz > 0);
if (e->e_cmd != ELF_C_WRITE && e->e_rawsize < fsz) {
LIBELF_SET_ERROR(HEADER, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_EHDR, ec, EV_CURRENT);
assert(msz > 0);
if ((ehdr = calloc((size_t) 1, msz)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
e->e_u.e_elf.e_ehdr.e_ehdr32 = ehdr;
EHDR_INIT(ehdr,32);
} else {
e->e_u.e_elf.e_ehdr.e_ehdr64 = ehdr;
EHDR_INIT(ehdr,64);
}
if (allocate)
e->e_flags |= ELF_F_DIRTY;
if (e->e_cmd == ELF_C_WRITE)
return (ehdr);
xlator = _libelf_get_translator(ELF_T_EHDR, ELF_TOMEMORY, ec);
(*xlator)(ehdr, msz, e->e_rawfile, (size_t) 1,
e->e_byteorder != LIBELF_PRIVATE(byteorder));
/*
* If extended numbering is being used, read the correct
* number of sections and program header entries.
*/
if (ec == ELFCLASS32) {
phnum = ((Elf32_Ehdr *) ehdr)->e_phnum;
shnum = ((Elf32_Ehdr *) ehdr)->e_shnum;
shoff = ((Elf32_Ehdr *) ehdr)->e_shoff;
strndx = ((Elf32_Ehdr *) ehdr)->e_shstrndx;
} else {
phnum = ((Elf64_Ehdr *) ehdr)->e_phnum;
shnum = ((Elf64_Ehdr *) ehdr)->e_shnum;
shoff = ((Elf64_Ehdr *) ehdr)->e_shoff;
strndx = ((Elf64_Ehdr *) ehdr)->e_shstrndx;
}
if (shnum >= SHN_LORESERVE ||
(shoff == 0LL && (shnum != 0 || phnum == PN_XNUM ||
strndx == SHN_XINDEX))) {
LIBELF_SET_ERROR(HEADER, 0);
return (NULL);
}
if (shnum != 0 || shoff == 0LL) { /* not using extended numbering */
e->e_u.e_elf.e_nphdr = phnum;
e->e_u.e_elf.e_nscn = shnum;
e->e_u.e_elf.e_strndx = strndx;
} else if (_libelf_load_extended(e, ec, shoff, phnum, strndx) == 0)
return (NULL);
return (ehdr);
}

View File

@ -1,136 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_extended.c 2225 2011-11-26 18:55:54Z jkoshy $");
/*
* Retrieve section #0, allocating a new section if needed.
*/
static Elf_Scn *
_libelf_getscn0(Elf *e)
{
Elf_Scn *s;
if ((s = STAILQ_FIRST(&e->e_u.e_elf.e_scn)) != NULL)
return (s);
return (_libelf_allocate_scn(e, (size_t) SHN_UNDEF));
}
int
_libelf_setshnum(Elf *e, void *eh, int ec, size_t shnum)
{
Elf_Scn *scn;
if (shnum >= SHN_LORESERVE) {
if ((scn = _libelf_getscn0(e)) == NULL)
return (0);
assert(scn->s_ndx == SHN_UNDEF);
if (ec == ELFCLASS32)
scn->s_shdr.s_shdr32.sh_size = shnum;
else
scn->s_shdr.s_shdr64.sh_size = shnum;
(void) elf_flagshdr(scn, ELF_C_SET, ELF_F_DIRTY);
shnum = 0;
}
if (ec == ELFCLASS32)
((Elf32_Ehdr *) eh)->e_shnum = shnum;
else
((Elf64_Ehdr *) eh)->e_shnum = shnum;
return (1);
}
int
_libelf_setshstrndx(Elf *e, void *eh, int ec, size_t shstrndx)
{
Elf_Scn *scn;
if (shstrndx >= SHN_LORESERVE) {
if ((scn = _libelf_getscn0(e)) == NULL)
return (0);
assert(scn->s_ndx == SHN_UNDEF);
if (ec == ELFCLASS32)
scn->s_shdr.s_shdr32.sh_link = shstrndx;
else
scn->s_shdr.s_shdr64.sh_link = shstrndx;
(void) elf_flagshdr(scn, ELF_C_SET, ELF_F_DIRTY);
shstrndx = SHN_XINDEX;
}
if (ec == ELFCLASS32)
((Elf32_Ehdr *) eh)->e_shstrndx = shstrndx;
else
((Elf64_Ehdr *) eh)->e_shstrndx = shstrndx;
return (1);
}
int
_libelf_setphnum(Elf *e, void *eh, int ec, size_t phnum)
{
Elf_Scn *scn;
if (phnum >= PN_XNUM) {
if ((scn = _libelf_getscn0(e)) == NULL)
return (0);
assert(scn->s_ndx == SHN_UNDEF);
if (ec == ELFCLASS32)
scn->s_shdr.s_shdr32.sh_info = phnum;
else
scn->s_shdr.s_shdr64.sh_info = phnum;
(void) elf_flagshdr(scn, ELF_C_SET, ELF_F_DIRTY);
phnum = PN_XNUM;
}
if (ec == ELFCLASS32)
((Elf32_Ehdr *) eh)->e_phnum = phnum;
else
((Elf64_Ehdr *) eh)->e_phnum = phnum;
return (1);
}

View File

@ -1,197 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*
* $Id: elf_types.m4 321 2009-03-07 16:59:14Z jkoshy $
*/
/*
* ELF types, defined in the "enum Elf_Type" API.
*
* The members of the list form a 2-tuple: (name, C-type-suffix).
* + name is an Elf_Type symbol without the ELF_T_ prefix.
* + C-type-suffix is the suffix for Elf32_ and Elf64_ type names.
*/
/*
* DEFINE_STRUCT(NAME,MEMBERLIST...)
*
* Map a type name to its members.
*
* Each member-list element comprises of pairs of (field name, type),
* in the sequence used in the file representation of NAME.
*
* Each member list element comprises a pair containing a field name
* and a basic type. Basic types include IDENT, HALF, WORD, LWORD,
* ADDR{32,64}, OFF{32,64}, SWORD, XWORD, SXWORD.
*
* The last element of a member list is the null element: _,_.
*/
/*-
* Copyright (c) 2006,2008-2011 Joseph Koshy
* 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.
*/
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_fsize.m4 2225 2011-11-26 18:55:54Z jkoshy $");
/* WARNING: GENERATED FROM libelf_fsize.m4. */
/*
* Create an array of file sizes from the elf_type definitions
*/
struct fsize {
size_t fsz32;
size_t fsz64;
};
static struct fsize fsize[ELF_T_NUM] = {
[ELF_T_ADDR] = { .fsz32 = sizeof(Elf32_Addr), .fsz64 = sizeof(Elf64_Addr) },
[ELF_T_BYTE] = { .fsz32 = 1, .fsz64 = 1 },
[ELF_T_CAP] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+0 },
[ELF_T_DYN] = { .fsz32 = sizeof(Elf32_Sword)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Sxword)+sizeof(Elf64_Xword)+0 },
[ELF_T_EHDR] = { .fsz32 = EI_NIDENT+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Word)+sizeof(Elf32_Addr)+sizeof(Elf32_Off)+sizeof(Elf32_Off)+sizeof(Elf32_Word)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+0, .fsz64 = EI_NIDENT+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Word)+sizeof(Elf64_Addr)+sizeof(Elf64_Off)+sizeof(Elf64_Off)+sizeof(Elf64_Word)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+0 },
[ELF_T_GNUHASH] = { .fsz32 = 1, .fsz64 = 1 },
[ELF_T_HALF] = { .fsz32 = sizeof(Elf32_Half), .fsz64 = sizeof(Elf64_Half) },
[ELF_T_LWORD] = { .fsz32 = sizeof(Elf32_Lword), .fsz64 = sizeof(Elf64_Lword) },
[ELF_T_MOVE] = { .fsz32 = sizeof(Elf32_Lword)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Half)+sizeof(Elf32_Half)+0, .fsz64 = sizeof(Elf64_Lword)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+sizeof(Elf64_Half)+sizeof(Elf64_Half)+0 },
[ELF_T_MOVEP] = { .fsz32 = 0, .fsz64 = 0 },
[ELF_T_NOTE] = { .fsz32 = 1, .fsz64 = 1 },
[ELF_T_OFF] = { .fsz32 = sizeof(Elf32_Off), .fsz64 = sizeof(Elf64_Off) },
[ELF_T_PHDR] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Off)+sizeof(Elf32_Addr)+sizeof(Elf32_Addr)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Word)+sizeof(Elf64_Word)+sizeof(Elf64_Off)+sizeof(Elf64_Addr)+sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+0 },
[ELF_T_REL] = { .fsz32 = sizeof(Elf32_Addr)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+0 },
[ELF_T_RELA] = { .fsz32 = sizeof(Elf32_Addr)+sizeof(Elf32_Word)+sizeof(Elf32_Sword)+0, .fsz64 = sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+sizeof(Elf64_Sxword)+0 },
[ELF_T_SHDR] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Addr)+sizeof(Elf32_Off)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+sizeof(Elf32_Word)+0, .fsz64 = sizeof(Elf64_Word)+sizeof(Elf64_Word)+sizeof(Elf64_Xword)+sizeof(Elf64_Addr)+sizeof(Elf64_Off)+sizeof(Elf64_Xword)+sizeof(Elf64_Word)+sizeof(Elf64_Word)+sizeof(Elf64_Xword)+sizeof(Elf64_Xword)+0 },
[ELF_T_SWORD] = { .fsz32 = sizeof(Elf32_Sword), .fsz64 = sizeof(Elf64_Sword) },
[ELF_T_SXWORD] = { .fsz32 = 0, .fsz64 = sizeof(Elf64_Sxword) },
[ELF_T_SYMINFO] = { .fsz32 = sizeof(Elf32_Half)+sizeof(Elf32_Half)+0, .fsz64 = sizeof(Elf64_Half)+sizeof(Elf64_Half)+0 },
[ELF_T_SYM] = { .fsz32 = sizeof(Elf32_Word)+sizeof(Elf32_Addr)+sizeof(Elf32_Word)+1+1+sizeof(Elf32_Half)+0, .fsz64 = sizeof(Elf64_Word)+1+1+sizeof(Elf64_Half)+sizeof(Elf64_Addr)+sizeof(Elf64_Xword)+0 },
[ELF_T_VDEF] = { .fsz32 = 1, .fsz64 = 1 },
[ELF_T_VNEED] = { .fsz32 = 1, .fsz64 = 1 },
[ELF_T_WORD] = { .fsz32 = sizeof(Elf32_Word), .fsz64 = sizeof(Elf64_Word) },
[ELF_T_XWORD] = { .fsz32 = 0, .fsz64 = sizeof(Elf64_Xword) },
};
size_t
_libelf_fsize(Elf_Type t, int ec, unsigned int v, size_t c)
{
size_t sz;
sz = 0;
if (v != EV_CURRENT)
LIBELF_SET_ERROR(VERSION, 0);
else if ((int) t < ELF_T_FIRST || t > ELF_T_LAST)
LIBELF_SET_ERROR(ARGUMENT, 0);
else {
sz = ec == ELFCLASS64 ? fsize[t].fsz64 : fsize[t].fsz32;
if (sz == 0)
LIBELF_SET_ERROR(UNIMPL, 0);
}
return (sz*c);
}

View File

@ -1,96 +0,0 @@
/*-
* Copyright (c) 2011 Joseph Koshy
* 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.
*/
#include <ar.h>
#include <assert.h>
#include <string.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_memory.c 2368 2011-12-29 06:34:28Z jkoshy $");
/*
* Create an ELF descriptor for a memory image, optionally reporting
* parse errors.
*/
Elf *
_libelf_memory(char *image, size_t sz, int reporterror)
{
Elf *e;
int e_class;
enum Elf_Error error;
unsigned int e_byteorder, e_version;
assert(image != NULL);
assert(sz > 0);
if ((e = _libelf_allocate_elf()) == NULL)
return (NULL);
e->e_cmd = ELF_C_READ;
e->e_rawfile = image;
e->e_rawsize = sz;
#undef LIBELF_IS_ELF
#define LIBELF_IS_ELF(P) ((P)[EI_MAG0] == ELFMAG0 && \
(P)[EI_MAG1] == ELFMAG1 && (P)[EI_MAG2] == ELFMAG2 && \
(P)[EI_MAG3] == ELFMAG3)
if (sz > EI_NIDENT && LIBELF_IS_ELF(image)) {
e_byteorder = image[EI_DATA];
e_class = image[EI_CLASS];
e_version = image[EI_VERSION];
error = ELF_E_NONE;
if (e_version > EV_CURRENT)
error = ELF_E_VERSION;
else if ((e_byteorder != ELFDATA2LSB && e_byteorder !=
ELFDATA2MSB) || (e_class != ELFCLASS32 && e_class !=
ELFCLASS64))
error = ELF_E_HEADER;
if (error != ELF_E_NONE) {
if (reporterror) {
LIBELF_PRIVATE(error) = LIBELF_ERROR(error, 0);
(void) _libelf_release_elf(e);
return (NULL);
}
} else {
_libelf_init_elf(e, ELF_K_ELF);
e->e_byteorder = e_byteorder;
e->e_class = e_class;
e->e_version = e_version;
}
} else if (sz >= SARMAG &&
strncmp(image, ARMAG, (size_t) SARMAG) == 0)
return (_libelf_ar_open(e, reporterror));
return (e);
}

View File

@ -1,196 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*
* $Id: elf_types.m4 321 2009-03-07 16:59:14Z jkoshy $
*/
/*
* ELF types, defined in the "enum Elf_Type" API.
*
* The members of the list form a 2-tuple: (name, C-type-suffix).
* + name is an Elf_Type symbol without the ELF_T_ prefix.
* + C-type-suffix is the suffix for Elf32_ and Elf64_ type names.
*/
/*
* DEFINE_STRUCT(NAME,MEMBERLIST...)
*
* Map a type name to its members.
*
* Each member-list element comprises of pairs of (field name, type),
* in the sequence used in the file representation of NAME.
*
* Each member list element comprises a pair containing a field name
* and a basic type. Basic types include IDENT, HALF, WORD, LWORD,
* ADDR{32,64}, OFF{32,64}, SWORD, XWORD, SXWORD.
*
* The last element of a member list is the null element: _,_.
*/
/*-
* Copyright (c) 2006,2008-2011 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <libelf.h>
#include <string.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_msize.m4 2225 2011-11-26 18:55:54Z jkoshy $");
/* WARNING: GENERATED FROM libelf_msize.m4. */
struct msize {
size_t msz32;
size_t msz64;
};
static struct msize msize[ELF_T_NUM] = {
[ELF_T_ADDR] = { .msz32 = sizeof(Elf32_Addr), .msz64 = sizeof(Elf64_Addr) },
[ELF_T_BYTE] = { .msz32 = 1, .msz64 = 1 },
[ELF_T_CAP] = { .msz32 = sizeof(Elf32_Cap), .msz64 = sizeof(Elf64_Cap) },
[ELF_T_DYN] = { .msz32 = sizeof(Elf32_Dyn), .msz64 = sizeof(Elf64_Dyn) },
[ELF_T_EHDR] = { .msz32 = sizeof(Elf32_Ehdr), .msz64 = sizeof(Elf64_Ehdr) },
[ELF_T_GNUHASH] = { .msz32 = 1, .msz64 = 1 },
[ELF_T_HALF] = { .msz32 = sizeof(Elf32_Half), .msz64 = sizeof(Elf64_Half) },
[ELF_T_LWORD] = { .msz32 = sizeof(Elf32_Lword), .msz64 = sizeof(Elf64_Lword) },
[ELF_T_MOVE] = { .msz32 = sizeof(Elf32_Move), .msz64 = sizeof(Elf64_Move) },
[ELF_T_MOVEP] = { .msz32 = 0, .msz64 = 0 },
[ELF_T_NOTE] = { .msz32 = 1, .msz64 = 1 },
[ELF_T_OFF] = { .msz32 = sizeof(Elf32_Off), .msz64 = sizeof(Elf64_Off) },
[ELF_T_PHDR] = { .msz32 = sizeof(Elf32_Phdr), .msz64 = sizeof(Elf64_Phdr) },
[ELF_T_REL] = { .msz32 = sizeof(Elf32_Rel), .msz64 = sizeof(Elf64_Rel) },
[ELF_T_RELA] = { .msz32 = sizeof(Elf32_Rela), .msz64 = sizeof(Elf64_Rela) },
[ELF_T_SHDR] = { .msz32 = sizeof(Elf32_Shdr), .msz64 = sizeof(Elf64_Shdr) },
[ELF_T_SWORD] = { .msz32 = sizeof(Elf32_Sword), .msz64 = sizeof(Elf64_Sword) },
[ELF_T_SXWORD] = { .msz32 = 0, .msz64 = sizeof(Elf64_Sxword) },
[ELF_T_SYMINFO] = { .msz32 = sizeof(Elf32_Syminfo), .msz64 = sizeof(Elf64_Syminfo) },
[ELF_T_SYM] = { .msz32 = sizeof(Elf32_Sym), .msz64 = sizeof(Elf64_Sym) },
[ELF_T_VDEF] = { .msz32 = 1, .msz64 = 1 },
[ELF_T_VNEED] = { .msz32 = 1, .msz64 = 1 },
[ELF_T_WORD] = { .msz32 = sizeof(Elf32_Word), .msz64 = sizeof(Elf64_Word) },
[ELF_T_XWORD] = { .msz32 = 0, .msz64 = sizeof(Elf64_Xword) },
};
size_t
_libelf_msize(Elf_Type t, int elfclass, unsigned int version)
{
size_t sz;
assert(elfclass == ELFCLASS32 || elfclass == ELFCLASS64);
assert((signed) t >= ELF_T_FIRST && t <= ELF_T_LAST);
if (version != EV_CURRENT) {
LIBELF_SET_ERROR(VERSION, 0);
return (0);
}
sz = (elfclass == ELFCLASS32) ? msize[t].msz32 : msize[t].msz64;
return (sz);
}

View File

@ -1,240 +0,0 @@
/*-
* Copyright (c) 2006,2008-2011 Joseph Koshy
* 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.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <errno.h>
#include <libelf.h>
#include <stdlib.h>
#include <unistd.h>
#include "_libelf.h"
#if ELFTC_HAVE_MMAP
#include <sys/mman.h>
#endif
ELFTC_VCSID("$Id: libelf_open.c 2364 2011-12-28 17:55:25Z jkoshy $");
#define _LIBELF_INITSIZE (64*1024)
/*
* Read from a device file, pipe or socket.
*/
static void *
_libelf_read_special_file(int fd, size_t *fsz)
{
ssize_t readsz;
size_t bufsz, datasz;
unsigned char *buf, *t;
datasz = 0;
readsz = 0;
bufsz = _LIBELF_INITSIZE;
if ((buf = malloc(bufsz)) == NULL)
goto resourceerror;
/*
* Read data from the file descriptor till we reach EOF, or
* till an error is encountered.
*/
do {
/* Check if we need to expand the data buffer. */
if (datasz == bufsz) {
bufsz *= 2;
if ((t = realloc(buf, bufsz)) == NULL)
goto resourceerror;
buf = t;
}
do {
readsz = bufsz - datasz;
t = buf + datasz;
if ((readsz = read(fd, t, readsz)) <= 0)
break;
datasz += readsz;
} while (datasz < bufsz);
} while (readsz > 0);
if (readsz < 0) {
LIBELF_SET_ERROR(IO, errno);
goto error;
}
assert(readsz == 0);
/*
* Free up extra buffer space.
*/
if (bufsz > datasz) {
if (datasz > 0) {
if ((t = realloc(buf, datasz)) == NULL)
goto resourceerror;
buf = t;
} else { /* Zero bytes read. */
LIBELF_SET_ERROR(ARGUMENT, 0);
free(buf);
buf = NULL;
}
}
*fsz = datasz;
return (buf);
resourceerror:
LIBELF_SET_ERROR(RESOURCE, 0);
error:
if (buf != NULL)
free(buf);
return (NULL);
}
/*
* Read the contents of the file referenced by the file descriptor
* 'fd'.
*/
Elf *
_libelf_open_object(int fd, Elf_Cmd c, int reporterror)
{
Elf *e;
void *m;
mode_t mode;
size_t fsize;
struct stat sb;
unsigned int flags;
assert(c == ELF_C_READ || c == ELF_C_RDWR || c == ELF_C_WRITE);
if (fstat(fd, &sb) < 0) {
LIBELF_SET_ERROR(IO, errno);
return (NULL);
}
mode = sb.st_mode;
fsize = (size_t) sb.st_size;
/*
* Reject unsupported file types.
*/
if (!S_ISREG(mode) && !S_ISCHR(mode) && !S_ISFIFO(mode) &&
!S_ISSOCK(mode)) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
/*
* For ELF_C_WRITE mode, allocate and return a descriptor.
*/
if (c == ELF_C_WRITE) {
if ((e = _libelf_allocate_elf()) != NULL) {
_libelf_init_elf(e, ELF_K_ELF);
e->e_byteorder = LIBELF_PRIVATE(byteorder);
e->e_fd = fd;
e->e_cmd = c;
if (!S_ISREG(mode))
e->e_flags |= LIBELF_F_SPECIAL_FILE;
}
return (e);
}
/*
* ELF_C_READ and ELF_C_RDWR mode.
*/
m = NULL;
flags = 0;
if (S_ISREG(mode)) {
#if ELFTC_HAVE_MMAP
/*
* Always map regular files in with 'PROT_READ'
* permissions.
*
* For objects opened in ELF_C_RDWR mode, when
* elf_update(3) is called, we remove this mapping,
* write file data out using write(2), and map the new
* contents back.
*/
m = mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, (off_t) 0);
if (m == MAP_FAILED)
m = NULL;
else
flags = LIBELF_F_RAWFILE_MMAP;
#endif
/*
* Fallback to a read() if the call to mmap() failed,
* or if mmap() is not available.
*/
if (m == NULL) {
if ((m = malloc(fsize)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
if (read(fd, m, fsize) != (ssize_t) fsize) {
LIBELF_SET_ERROR(IO, errno);
free(m);
return (NULL);
}
flags = LIBELF_F_RAWFILE_MALLOC;
}
} else if ((m = _libelf_read_special_file(fd, &fsize)) != NULL)
flags = LIBELF_F_RAWFILE_MALLOC | LIBELF_F_SPECIAL_FILE;
else
return (NULL);
if ((e = _libelf_memory(m, fsize, reporterror)) == NULL) {
assert((flags & LIBELF_F_RAWFILE_MALLOC) ||
(flags & LIBELF_F_RAWFILE_MMAP));
if (flags & LIBELF_F_RAWFILE_MALLOC)
free(m);
#if ELFTC_HAVE_MMAP
else
(void) munmap(m, fsize);
#endif
return (NULL);
}
/* ar(1) archives aren't supported in RDWR mode. */
if (c == ELF_C_RDWR && e->e_kind == ELF_K_AR) {
(void) elf_end(e);
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
e->e_flags |= flags;
e->e_fd = fd;
e->e_cmd = c;
return (e);
}

View File

@ -1,156 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <gelf.h>
#include <libelf.h>
#include <stdlib.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_phdr.c 2225 2011-11-26 18:55:54Z jkoshy $");
void *
_libelf_getphdr(Elf *e, int ec)
{
size_t phnum, phentsize;
size_t fsz, msz;
uint64_t phoff;
Elf32_Ehdr *eh32;
Elf64_Ehdr *eh64;
void *ehdr, *phdr;
int (*xlator)(char *_d, size_t _dsz, char *_s, size_t _c, int _swap);
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if ((phdr = (ec == ELFCLASS32 ?
(void *) e->e_u.e_elf.e_phdr.e_phdr32 :
(void *) e->e_u.e_elf.e_phdr.e_phdr64)) != NULL)
return (phdr);
/*
* Check the PHDR related fields in the EHDR for sanity.
*/
if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL)
return (NULL);
phnum = e->e_u.e_elf.e_nphdr;
if (ec == ELFCLASS32) {
eh32 = (Elf32_Ehdr *) ehdr;
phentsize = eh32->e_phentsize;
phoff = (uint64_t) eh32->e_phoff;
} else {
eh64 = (Elf64_Ehdr *) ehdr;
phentsize = eh64->e_phentsize;
phoff = (uint64_t) eh64->e_phoff;
}
fsz = gelf_fsize(e, ELF_T_PHDR, phnum, e->e_version);
assert(fsz > 0);
if ((uint64_t) e->e_rawsize < (phoff + fsz)) {
LIBELF_SET_ERROR(HEADER, 0);
return (NULL);
}
msz = _libelf_msize(ELF_T_PHDR, ec, EV_CURRENT);
assert(msz > 0);
if ((phdr = calloc(phnum, msz)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
if (ec == ELFCLASS32)
e->e_u.e_elf.e_phdr.e_phdr32 = phdr;
else
e->e_u.e_elf.e_phdr.e_phdr64 = phdr;
xlator = _libelf_get_translator(ELF_T_PHDR, ELF_TOMEMORY, ec);
(*xlator)(phdr, phnum * msz, e->e_rawfile + phoff, phnum,
e->e_byteorder != LIBELF_PRIVATE(byteorder));
return (phdr);
}
void *
_libelf_newphdr(Elf *e, int ec, size_t count)
{
void *ehdr, *newphdr, *oldphdr;
size_t msz;
if (e == NULL) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL) {
LIBELF_SET_ERROR(SEQUENCE, 0);
return (NULL);
}
assert(e->e_class == ec);
assert(ec == ELFCLASS32 || ec == ELFCLASS64);
assert(e->e_version == EV_CURRENT);
msz = _libelf_msize(ELF_T_PHDR, ec, e->e_version);
assert(msz > 0);
newphdr = NULL;
if (count > 0 && (newphdr = calloc(count, msz)) == NULL) {
LIBELF_SET_ERROR(RESOURCE, 0);
return (NULL);
}
if (ec == ELFCLASS32) {
if ((oldphdr = (void *) e->e_u.e_elf.e_phdr.e_phdr32) != NULL)
free(oldphdr);
e->e_u.e_elf.e_phdr.e_phdr32 = (Elf32_Phdr *) newphdr;
} else {
if ((oldphdr = (void *) e->e_u.e_elf.e_phdr.e_phdr64) != NULL)
free(oldphdr);
e->e_u.e_elf.e_phdr.e_phdr64 = (Elf64_Phdr *) newphdr;
}
e->e_u.e_elf.e_nphdr = count;
elf_flagphdr(e, ELF_C_SET, ELF_F_DIRTY);
return (newphdr);
}

View File

@ -1,56 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <gelf.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_shdr.c 2225 2011-11-26 18:55:54Z jkoshy $");
void *
_libelf_getshdr(Elf_Scn *s, int ec)
{
Elf *e;
if (s == NULL || (e = s->s_elf) == NULL ||
e->e_kind != ELF_K_ELF) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
if (ec == ELFCLASSNONE)
ec = e->e_class;
if (ec != e->e_class) {
LIBELF_SET_ERROR(CLASS, 0);
return (NULL);
}
return ((void *) &s->s_shdr);
}

View File

@ -1,150 +0,0 @@
/*-
* Copyright (c) 2006,2008 Joseph Koshy
* 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.
*/
#include <sys/cdefs.h>
#include <assert.h>
#include <libelf.h>
#include "_libelf.h"
ELFTC_VCSID("$Id: libelf_xlate.c 2225 2011-11-26 18:55:54Z jkoshy $");
/*
* Translate to/from the file representation of ELF objects.
*
* Translation could potentially involve the following
* transformations:
*
* - an endianness conversion,
* - a change of layout, as the file representation of ELF objects
* can differ from their in-memory representation.
* - a change in representation due to a layout version change.
*/
Elf_Data *
_libelf_xlate(Elf_Data *dst, const Elf_Data *src, unsigned int encoding,
int elfclass, int direction)
{
int byteswap;
size_t cnt, dsz, fsz, msz;
uintptr_t sb, se, db, de;
if (encoding == ELFDATANONE)
encoding = LIBELF_PRIVATE(byteorder);
if ((encoding != ELFDATA2LSB && encoding != ELFDATA2MSB) ||
dst == NULL || src == NULL || dst == src) {
LIBELF_SET_ERROR(ARGUMENT, 0);
return (NULL);
}
assert(elfclass == ELFCLASS32 || elfclass == ELFCLASS64);
assert(direction == ELF_TOFILE || direction == ELF_TOMEMORY);
if (dst->d_version != src->d_version) {
LIBELF_SET_ERROR(UNIMPL, 0);
return (NULL);
}
if (src->d_buf == NULL || dst->d_buf == NULL) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
if ((int) src->d_type < 0 || src->d_type >= ELF_T_NUM) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
if ((fsz = (elfclass == ELFCLASS32 ? elf32_fsize : elf64_fsize)
(src->d_type, (size_t) 1, src->d_version)) == 0)
return (NULL);
msz = _libelf_msize(src->d_type, elfclass, src->d_version);
assert(msz > 0);
if (src->d_size % (direction == ELF_TOMEMORY ? fsz : msz)) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
/*
* Determine the number of objects that need to be converted, and
* the space required for the converted objects in the destination
* buffer.
*/
if (direction == ELF_TOMEMORY) {
cnt = src->d_size / fsz;
dsz = cnt * msz;
} else {
cnt = src->d_size / msz;
dsz = cnt * fsz;
}
if (dst->d_size < dsz) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
sb = (uintptr_t) src->d_buf;
se = sb + src->d_size;
db = (uintptr_t) dst->d_buf;
de = db + dst->d_size;
/*
* Check for overlapping buffers. Note that db == sb is
* allowed.
*/
if (db != sb && de > sb && se > db) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
if ((direction == ELF_TOMEMORY ? db : sb) %
_libelf_malign(src->d_type, elfclass)) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
dst->d_type = src->d_type;
dst->d_size = dsz;
byteswap = encoding != LIBELF_PRIVATE(byteorder);
if (src->d_size == 0 ||
(db == sb && !byteswap && fsz == msz))
return (dst); /* nothing more to do */
if (!(_libelf_get_translator(src->d_type, direction, elfclass))
(dst->d_buf, dsz, src->d_buf, cnt, byteswap)) {
LIBELF_SET_ERROR(DATA, 0);
return (NULL);
}
return (dst);
}

View File

@ -1,40 +0,0 @@
OUTPUT(wiiupluginloader.elf);
/* Tell linker where our application entry is so the garbage collect can work correct */
ENTRY(__entry_menu);
SECTIONS {
. = 0x00802000;
.text : {
*(.kernel_code*);
*(.text*);
/* Tell linker to not garbage collect this section as it is not referenced anywhere */
KEEP(*(.kernel_code*));
}
.rodata : {
*(.rodata*);
}
.data : {
*(.data*);
__sdata_start = .;
*(.sdata*);
__sdata_end = .;
__sdata2_start = .;
*(.sdata2*);
__sdata2_end = .;
}
.bss : {
__bss_start = .;
*(.bss*);
*(.sbss*);
*(COMMON);
__bss_end = .;
}
__CODE_END = .;
/DISCARD/ : {
*(*);
}
}

View File

@ -1,328 +1,60 @@
#include <string> #include <nsysnet/socket.h>
#include <vector> #include <coreinit/ios.h>
#include <string.h> #include <sysapp/launch.h>
#include <stdlib.h> #include "Application.h"
#include <stddef.h> #include "system/memory.h"
#include <stdarg.h> #include "utils/logger.h"
#include <stdio.h> #include "utils/utils.h"
#include <malloc.h> #include "utils/ipcclient.h"
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dynamic_libs/os_functions.h>
#include <dynamic_libs/gx2_functions.h>
#include <dynamic_libs/ax_functions.h>
#include <dynamic_libs/socket_functions.h>
#include <dynamic_libs/sys_functions.h>
#include <dynamic_libs/fs_functions.h>
#include <dynamic_libs/nn_nim_functions.h>
#include <dynamic_libs/vpad_functions.h>
#include <dynamic_libs/padscore_functions.h>
#include <dynamic_libs/proc_ui_functions.h>
#include <fs/FSUtils.h>
#include <fs/sd_fat_devoptab.h>
#include <utils/logger.h>
#include <utils/utils.h>
#include <utils/function_patcher.h>
#include <system/exception_handler.h>
#include <system/memory.h>
#include <kernel/kernel_utils.h>
#include <mykernel/kernel_utils.h>
#include "mymemory/memory_mapping.h"
#include "common/retain_vars.h"
#include "common/common.h"
#include "plugin/PluginLoader.h" #include "plugin/PluginLoader.h"
#include "plugin/PluginInformation.h" #include "plugin/PluginInformation.h"
#include "plugin/DynamicLinkingHelper.h"
#include <wups.h>
#include <iosuhax.h>
#include <fat.h>
#include <ntfs.h>
#include "main.h"
#include "utils.h"
#include "Application.h"
#include "patcher/function_patcher.h"
#include "patcher/hooks_patcher.h"
#include "patcher/hooks_patcher_static.h"
#include "plugin/dynamic_linking_defines.h"
#include "myutils/mem_utils.h"
#include "myutils/mocha.h"
#include "myutils/libntfs.h"
#include "myutils/libfat.h"
#include "myutils/overlay_helper.h"
#include "myutils/ConfigUtils.h"
#include "version.h"
#include "settings/CSettings.h"
static void ApplyPatchesAndCallHookStartingApp();
static void RestorePatches();
int32_t isInMiiMakerHBL();
void readAndPrintSegmentRegister(CThread *thread, void *arg);
extern "C" int32_t Menu_Main(int32_t argc, char **argv) {
if(gAppStatus == 2) {
//"No, we don't want to patch stuff again.");
return EXIT_RELAUNCH_ON_LOAD;
}
InitOSFunctionPointers();
InitSocketFunctionPointers(); //For logging
InitSysFunctionPointers();
InitFSFunctionPointers();
InitGX2FunctionPointers();
InitSysFunctionPointers();
InitVPadFunctionPointers();
InitPadScoreFunctionPointers();
InitAXFunctionPointers();
InitProcUIFunctionPointers();
/* Entry point */
extern "C" int Menu_Main(int32_t argc, char **argv) {
//!*******************************************************************
//! Initialize function pointers *
//!*******************************************************************
socket_lib_init();
//! do OS (for acquire) and sockets first so we got logging
log_init(); log_init();
DEBUG_FUNCTION_LINE("We have %d kb for plugins.\n",(PLUGIN_LOCATION_END_ADDRESS-getApplicationEndAddr())/1024); log_print("Initialize memory management\n");
//setup_os_exceptions(); memoryInitialize();
DEBUG_FUNCTION_LINE("Wii U Plugin System Loader %s\n",APP_VERSION); /*PluginLoader * loader = PluginLoader::createInstance(0x00A00000, 0x01000000);
DEBUG_FUNCTION_LINE("Sizeof dyn_linking_relocation_data_t %d\n",sizeof(dyn_linking_relocation_data_t)); if(loader != NULL) {
Init(); std::vector<PluginInformation*> plugins = loader->getPluginsByPath("sd:/wiiu/plugins3/");
uint32_t counter = 0;
for (std::vector<PluginInformation *>::iterator it = plugins.begin() ; it != plugins.end(); ++it) {
PluginInformation * curPlugin = *it;
DEBUG_FUNCTION_LINE("Found plugin %d: %s\n",counter, curPlugin->getPath().c_str());
counter++;
}
loader->loadAndLinkPlugins(plugins);
loader->clearPluginInformation(plugins);
plugins.clear();
init_kernel_syscalls(); std::vector<PluginInformation*> pluginsInMemory = loader->getPluginsLoadedInMemory();
wups_init_kernel_syscalls(); counter = 0;
for (std::vector<PluginInformation *>::iterator it = pluginsInMemory.begin() ; it != pluginsInMemory.end(); ++it) {
if(!MemoryMapping::isMemoryMapped()) { PluginInformation * curPlugin = *it;
MemoryMapping::setupMemoryMapping(); DEBUG_FUNCTION_LINE("Is loaded %d: %s\n",counter, curPlugin->getPath().c_str());
counter++;
} }
gGameTitleID = OSGetTitleID(); loader->clearPluginInformation(pluginsInMemory);
g_vid_ownContextState = NULL; delete loader;
g_vid_originalContextSave = NULL; }*/
int32_t result = 0;
//Reset everything when were going back to the Mii Maker
if(isInMiiMakerHBL()) {
CallHook(WUPS_LOADER_HOOK_DEINIT_PLUGIN);
// Restore patches as the patched functions could change.
RestorePatches();
DynamicLinkingHelper::getInstance()->clearAll();
//PluginLoader * pluginLoader = PluginLoader::getInstance();
//std::vector<PluginInformation *> pluginList = pluginLoader->getPluginInformation("sd:/wiiu/plugins/");
//pluginLoader->loadAndLinkPlugins(pluginList);
//pluginLoader->clearPluginInformation(pluginList);
//!******************************************************************* //!*******************************************************************
//! Initialize heap memory * //! Initialize heap memory *
//!******************************************************************* //!*******************************************************************
DEBUG_FUNCTION_LINE("Initialize memory management\n");
memoryInitialize();
DEBUG_FUNCTION_LINE("Start main application\n"); log_printf("Start main application\n");
result = Application::instance()->exec(); Application::instance()->exec();
DEBUG_FUNCTION_LINE("Main application stopped result: %d\n",result);
DEBUG_FUNCTION_LINE("Application::destroyInstance\n");
Application::destroyInstance(); Application::destroyInstance();
DEBUG_FUNCTION_LINE("Release memory\n");
memoryRelease();
CSettings::destroyInstance();
PluginLoader::destroyInstance();
MemoryUtils::init();
// Memory on custon heap is reset anyway so we don't need to free the image buffers.
memset((void*)&g_vid_main_cbuf,0,sizeof(g_vid_main_cbuf));
memset((void*)&g_vid_drcTex,0,sizeof(g_vid_drcTex));
memset((void*)&g_vid_tvTex,0,sizeof(g_vid_tvTex));
g_vid_originalContextSave = NULL;
g_vid_ownContextState = NULL;
g_NotInLoader = false;
} else {
g_NotInLoader = true;
}
DEBUG_FUNCTION_LINE("Patch own stuff\n");
PatchInvidualMethodHooks(method_hooks_hooks_static, method_hooks_size_hooks_static, method_calls_hooks_static);
DEBUG_FUNCTION_LINE("Do relocations\n");
std::vector<dyn_linking_relocation_entry_t *> relocations = DynamicLinkingHelper::getInstance()->getAllValidDynamicLinkingRelocations();
DEBUG_FUNCTION_LINE("Found relocation information for %d functions\n",relocations.size());
if(!DynamicLinkingHelper::getInstance()->fillRelocations(relocations)) {
OSFatal("fillRelocations failed.");
}
if(!isInMiiMakerHBL()) {
DEBUG_FUNCTION_LINE("Apply patches.\n");
ApplyPatchesAndCallHookStartingApp();
if(MemoryMapping::isMemoryMapped()) {
DEBUG_FUNCTION_LINE("Mapping was already done. Running %016llX\n",gGameTitleID);
readAndPrintSegmentRegister(NULL,NULL);
//MemoryMapping::readTestValuesFromMemory();
} else {
DEBUG_FUNCTION_LINE("<-----------------------------------------------------> \n");
DEBUG_FUNCTION_LINE("<---------------- COPY PASTE ME START-----------------> \n");
DEBUG_FUNCTION_LINE("<-----------------------------------------------------> \n");
DEBUG_FUNCTION_LINE("Mapping was't done. Running %016llX\n",gGameTitleID);
readAndPrintSegmentRegister(NULL,NULL);
DEBUG_FUNCTION_LINE("<-----------------------------------------------------> \n");
DEBUG_FUNCTION_LINE("<----------------- COPY PASTE ME END -----------------> \n");
DEBUG_FUNCTION_LINE("<-----------------------------------------------------> \n");
}
return EXIT_RELAUNCH_ON_LOAD;
}
if(result == APPLICATION_CLOSE_APPLY || result == APPLICATION_CLOSE_APPLY_MEMORY) {
CallHook(WUPS_LOADER_HOOK_INIT_VID_MEM);
CallHook(WUPS_LOADER_HOOK_INIT_KERNEL);
CallHook(WUPS_LOADER_HOOK_INIT_FS);
CallHook(WUPS_LOADER_HOOK_INIT_OVERLAY);
ConfigUtils::loadConfigFromSD();
CallHook(WUPS_LOADER_HOOK_INIT_PLUGIN);
DEBUG_FUNCTION_LINE("Loading the system menu.\n");
DeInit();
SYSLaunchMenu();
return EXIT_RELAUNCH_ON_LOAD;
}
DEBUG_FUNCTION_LINE("Let's go to back to the Homebrew Launcher\n");
DEBUG_FUNCTION_LINE("Restoring the patched functions\n");
RestorePatches();
DEBUG_FUNCTION_LINE("Calling the plugin deinit hook\n");
//CallHook(WUPS_LOADER_HOOK_DEINIT_PLUGIN);
DEBUG_FUNCTION_LINE("Unmounting SD/USB devices\n");
DeInit();
DEBUG_FUNCTION_LINE("Bye bye!\n");
return EXIT_SUCCESS;
}
void ApplyPatchesAndCallHookStartingApp() {
PatchInvidualMethodHooks(method_hooks_hooks_static, method_hooks_size_hooks_static, method_calls_hooks_static);
PatchInvidualMethodHooks(method_hooks_hooks, method_hooks_size_hooks, method_calls_hooks);
for(int32_t plugin_index=0; plugin_index<gbl_replacement_data.number_used_plugins; plugin_index++) {
CallHookEx(WUPS_LOADER_HOOK_STARTING_APPLICATION,plugin_index);
new_PatchInvidualMethodHooks(&gbl_replacement_data.plugin_data[plugin_index]);
CallHookEx(WUPS_LOADER_HOOK_FUNCTIONS_PATCHED,plugin_index);
}
}
void DeInit() {
DeInit_SD_USB();
}
void RestorePatches() {
for(int32_t plugin_index=gbl_replacement_data.number_used_plugins-1; plugin_index>=0; plugin_index--) {
DEBUG_FUNCTION_LINE("Restoring function for plugin: %d\n",plugin_index);
new_RestoreInvidualInstructions(&gbl_replacement_data.plugin_data[plugin_index]);
}
RestoreInvidualInstructions(method_hooks_hooks, method_hooks_size_hooks);
RestoreInvidualInstructions(method_hooks_hooks_static, method_hooks_size_hooks_static);
}
int32_t isInMiiMakerHBL() {
if (OSGetTitleID != 0 && (
OSGetTitleID() == 0x000500101004A200 || // mii maker eur
OSGetTitleID() == 0x000500101004A100 || // mii maker usa
OSGetTitleID() == 0x000500101004A000 ||// mii maker jpn
OSGetTitleID() == 0x0005000013374842)) {
return 1;
}
return 0; return 0;
} }
void Init() {
memset(&tv_store,0,sizeof(tv_store));
memset(&drc_store,0,sizeof(drc_store));
DEBUG_FUNCTION_LINE("Mount SD partition\n");
Init_SD_USB();
}
void Init_SD_USB() {
int32_t res = IOSUHAX_Open(NULL);
if(res < 0) {
ExecuteIOSExploitWithDefaultConfig();
}
deleteDevTabsNames();
mount_fake();
gSDInitDone |= WUPS_SDUSB_MOUNTED_FAKE;
if(res < 0) {
DEBUG_FUNCTION_LINE("IOSUHAX_open failed\n");
if((res = mount_sd_fat("sd")) >= 0) {
DEBUG_FUNCTION_LINE("mount_sd_fat success\n");
gSDInitDone |= WUPS_SDUSB_MOUNTED_OS_SD;
} else {
DEBUG_FUNCTION_LINE("mount_sd_fat failed %d\n",res);
}
} else {
DEBUG_FUNCTION_LINE("Using IOSUHAX for SD/USB access\n");
gSDInitDone |= WUPS_SDUSB_LIBIOSU_LOADED;
int32_t ntfs_mounts = mountAllNTFS();
if(ntfs_mounts > 0) {
gSDInitDone |= WUPS_USB_MOUNTED_LIBNTFS;
}
if(mount_libfatAll() == 0) {
gSDInitDone |= WUPS_SD_MOUNTED_LIBFAT;
gSDInitDone |= WUPS_USB_MOUNTED_LIBFAT;
}
}
}
void DeInit_SD_USB() {
DEBUG_FUNCTION_LINE("Called this function.\n");
if(gSDInitDone & WUPS_SDUSB_MOUNTED_FAKE) {
DEBUG_FUNCTION_LINE("Unmounting fake\n");
unmount_fake();
gSDInitDone &= ~WUPS_SDUSB_MOUNTED_FAKE;
}
if(gSDInitDone & WUPS_SDUSB_MOUNTED_OS_SD) {
DEBUG_FUNCTION_LINE("Unmounting OS SD\n");
unmount_sd_fat("sd");
gSDInitDone &= ~WUPS_SDUSB_MOUNTED_OS_SD;
}
if(gSDInitDone & WUPS_SD_MOUNTED_LIBFAT) {
DEBUG_FUNCTION_LINE("Unmounting LIBFAT SD\n");
unmount_libfat("sd");
gSDInitDone &= ~WUPS_SD_MOUNTED_LIBFAT;
}
if(gSDInitDone & WUPS_USB_MOUNTED_LIBFAT) {
DEBUG_FUNCTION_LINE("Unmounting LIBFAT USB\n");
unmount_libfat("usb");
gSDInitDone &= ~WUPS_USB_MOUNTED_LIBFAT;
}
if(gSDInitDone & WUPS_USB_MOUNTED_LIBNTFS) {
DEBUG_FUNCTION_LINE("Unmounting LIBNTFS USB\n");
unmountAllNTFS();
gSDInitDone &= ~WUPS_USB_MOUNTED_LIBNTFS;
}
if(gSDInitDone & WUPS_SDUSB_LIBIOSU_LOADED) {
DEBUG_FUNCTION_LINE("Calling IOSUHAX_Close\n");
IOSUHAX_Close();
gSDInitDone &= ~WUPS_SDUSB_LIBIOSU_LOADED;
}
deleteDevTabsNames();
if(gSDInitDone != WUPS_SDUSB_MOUNTED_NONE) {
DEBUG_FUNCTION_LINE("WARNING. Some devices are still mounted.\n");
}
DEBUG_FUNCTION_LINE("Function end.\n");
}

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
* Copyright (C) 2018 Maschell * Copyright (C) 2018,2019 Maschell
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -18,26 +18,15 @@
#ifndef _MAIN_H_ #ifndef _MAIN_H_
#define _MAIN_H_ #define _MAIN_H_
#include <dynamic_libs/os_functions.h> #include <stdint.h>
#include <dynamic_libs/os_types.h>
/* Main */ /* Main */
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
#include <libelf.h>
//! C wrapper for our C++ functions //! C wrapper for our C++ functions
int32_t Menu_Main(int32_t argc, char **argv); int32_t Menu_Main(int32_t argc, char **argv);
void Init_SD_USB();
void DeInit_SD_USB();
void Init();
void DeInit();
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -15,12 +15,8 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/ ****************************************************************************/
#include <dynamic_libs/os_functions.h>
#include <dynamic_libs/socket_functions.h>
#include <dynamic_libs/padscore_functions.h>
#include <utils/StringTools.h> #include <utils/StringTools.h>
#include <utils/logger.h> #include <utils/logger.h>
#include "myutils/overlay_helper.h"
#include "MainWindow.h" #include "MainWindow.h"
#include "MainWindowGUI.h" #include "MainWindowGUI.h"
#include "Application.h" #include "Application.h"

View File

@ -16,9 +16,9 @@
****************************************************************************/ ****************************************************************************/
#include "common/common.h" #include "common/common.h"
#include "ContentHome.h" #include "ContentHome.h"
#include "plugin/PluginLoader.h"
#include "custom/gui/DefaultGuiSwitch.h" #include "custom/gui/DefaultGuiSwitch.h"
#include "Application.h" #include "Application.h"
#include "plugin/PluginLoader.h"
ContentHome::ContentHome():ContentTemplate() ContentHome::ContentHome():ContentTemplate()
, welcomeHeadLineLabel(gettext("Welcome to the Wii U plugin loader")) , welcomeHeadLineLabel(gettext("Welcome to the Wii U plugin loader"))
@ -89,8 +89,13 @@ ContentHome::ContentHome():ContentTemplate()
DPADButtons.clicked.connect(this, &ContentHome::OnDPADClick); DPADButtons.clicked.connect(this, &ContentHome::OnDPADClick);
append(&DPADButtons); append(&DPADButtons);
PluginLoader * pluginLoader = PluginLoader::getInstance(); PluginLoader * pluginLoader = PluginLoader::createInstance(0x00A00000, 0x01000000);
std::vector<PluginInformation *> pluginList = pluginLoader->getPluginInformation(WUPS_PLUGIN_PATH);
std::vector<PluginInformation *> pluginList = pluginLoader->getPluginsByPath(WUPS_PLUGIN_PATH);
std::vector<PluginInformation *> autoboot_list = pluginLoader->getPluginsByPath("sd:/wiiu/autoboot_plugins/");
pluginList.insert(pluginList.end(), autoboot_list.begin(), autoboot_list.end());
std::vector<PluginInformation *> pluginListLoaded = pluginLoader->getPluginsLoadedInMemory(); std::vector<PluginInformation *> pluginListLoaded = pluginLoader->getPluginsLoadedInMemory();
pluginsFrame.setAlignment(ALIGN_TOP_CENTER); pluginsFrame.setAlignment(ALIGN_TOP_CENTER);
@ -102,6 +107,7 @@ ContentHome::ContentHome():ContentTemplate()
float frameheight = 50.0f; float frameheight = 50.0f;
int32_t selectionMappingIndex = 0; int32_t selectionMappingIndex = 0;
selectionMappingMin = 0; selectionMappingMin = 0;
for (std::vector<PluginInformation *>::iterator it = pluginList.begin() ; it != pluginList.end(); ++it) { for (std::vector<PluginInformation *>::iterator it = pluginList.begin() ; it != pluginList.end(); ++it) {
PluginInformation * curPlugin = *it; PluginInformation * curPlugin = *it;
@ -155,11 +161,13 @@ ContentHome::ContentHome():ContentTemplate()
toDelete.push_back(right); toDelete.push_back(right);
toDelete.push_back(text); toDelete.push_back(text);
} }
selectionMappingMax = selectionMapping.size() -1; selectionMappingMax = selectionMapping.size() -1;
if(selectionMappingMax < 0) { if(selectionMappingMax < 0) {
selectionMappingMax = 0; selectionMappingMax = 0;
} }
//pluginLoader->clearPluginInformation(pluginList); // will be cleared in destructor.
pluginLoader->clearPluginInformation(pluginListLoaded); pluginLoader->clearPluginInformation(pluginListLoaded);
append(&welcomeHeadLineLabel); append(&welcomeHeadLineLabel);
@ -172,6 +180,7 @@ ContentHome::ContentHome():ContentTemplate()
auto fp = std::bind(&ContentHome::linkPlugins, this); auto fp = std::bind(&ContentHome::linkPlugins, this);
Application::instance()->setLinkPluginsCallback(fp); Application::instance()->setLinkPluginsCallback(fp);
this->loader = pluginLoader;
} }
void ContentHome::OnDPADClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) { void ContentHome::OnDPADClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger) {
@ -220,12 +229,17 @@ bool ContentHome::linkPlugins() {
GuiToggle * guiElement = x.first; GuiToggle * guiElement = x.first;
if(guiElement->getValue()) { if(guiElement->getValue()) {
PluginInformation* pluginInformation = x.second; PluginInformation* pluginInformation = x.second;
DEBUG_FUNCTION_LINE("We want to link %s\n",pluginInformation->getName().c_str()); //DEBUG_FUNCTION_LINE("We want to link %s\n",pluginInformation->getName().c_str());
willBeLoaded.push_back(pluginInformation); willBeLoaded.push_back(pluginInformation);
} }
} }
if(loader != NULL) {
return this->loader->loadAndLinkPlugins(willBeLoaded);
}
return false;
return PluginLoader::getInstance()->loadAndLinkPlugins(willBeLoaded);
} }
@ -268,4 +282,7 @@ ContentHome::~ContentHome() {
for (std::vector<GuiElement *>::iterator it = toDelete.begin() ; it != toDelete.end(); ++it) { for (std::vector<GuiElement *>::iterator it = toDelete.begin() ; it != toDelete.end(); ++it) {
delete *it; delete *it;
} }
if(loader != NULL) {
delete loader;
}
} }

View File

@ -20,8 +20,10 @@
#include "gui/Gui.h" #include "gui/Gui.h"
#include "ContentTemplate.h" #include "ContentTemplate.h"
#include "language/gettext.h" #include "language/gettext.h"
#include "plugin/PluginInformation.h"
#include "custom/gui/DefaultGuiSwitch.h" #include "custom/gui/DefaultGuiSwitch.h"
#include "plugin/PluginInformation.h"
#include "plugin/PluginLoader.h"
class ContentHome : public ContentTemplate { class ContentHome : public ContentTemplate {
public: public:
@ -66,6 +68,7 @@ private:
GuiButton DPADButtons; GuiButton DPADButtons;
GuiFrame pluginsFrame; GuiFrame pluginsFrame;
PluginLoader * loader = NULL;
std::vector<GuiElement*> toDelete; std::vector<GuiElement*> toDelete;
void OnDPADClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger); void OnDPADClick(GuiButton *button, const GuiController *controller, GuiTrigger *trigger);

@ -1 +0,0 @@
Subproject commit 74f723e2ab5c77e6f79da2816114627a46ee9f2f

View File

@ -1,30 +0,0 @@
#ifndef __WUPS_KERNEL_DEFS_H_
#define __WUPS_KERNEL_DEFS_H_
#include <dynamic_libs/fs_functions.h>
#include <dynamic_libs/os_types.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _sr_table_t {
uint32_t value[16];
uint32_t sdr1;
} sr_table_t;
typedef struct _bat_t {
uint32_t h;
uint32_t l;
} bat_t;
typedef struct _bat_table_t {
bat_t bat[8];
} bat_table_t;
#ifdef __cplusplus
}
#endif
#endif // __KERNEL_DEFS_H_

View File

@ -1,181 +0,0 @@
#include <dynamic_libs/os_defs.h>
#include <dynamic_libs/os_functions.h>
#include "kernel_defs.h"
#include <kernel/syscalls.h>
static void KernelReadSRs(sr_table_t * table) {
uint32_t i = 0;
// calculate PT_size ((end-start)*8/4096)*4 or (end-start)/128
// Minimum page table size is 64Kbytes.
asm volatile("eieio; isync");
asm volatile("mfspr %0, 25" : "=r" (table->sdr1));
asm volatile("mfsr %0, 0" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 1" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 2" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 3" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 4" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 5" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 6" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 7" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 8" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 9" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 10" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 11" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 12" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 13" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 14" : "=r" (table->value[i]));
i++;
asm volatile("mfsr %0, 15" : "=r" (table->value[i]));
i++;
asm volatile("eieio; isync");
}
static void KernelWriteSRs(sr_table_t * table) {
uint32_t i = 0;
asm volatile("eieio; isync");
// Writing didn't work for all at once so we only write number 8.
// TODO: fix this and change it if required.
/*asm volatile("mtsr 0, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 1, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 2, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 3, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 4, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 5, %0" : : "r" (table->value[i])); i++;*/
//asm volatile("mtsr 6, %0" : : "r" (table->value[6])); i++;
/*asm volatile("mtsr 7, %0" : : "r" (table->value[i])); i++;*/
asm volatile("mtsr 8, %0" : : "r" (table->value[8]));
i++;
/*asm volatile("mtsr 9, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 10, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 11, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 12, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 13, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 14, %0" : : "r" (table->value[i])); i++;
asm volatile("mtsr 15, %0" : : "r" (table->value[i])); i++;*/
asm volatile("isync");
}
void KernelReadPTE(uint32_t* dest, uint32_t size) {
uint32_t msr = 0;
uint32_t oldmsr = 0;
//TODO: Calculate from SDR1
uint32_t addr_base = 0xFFE20000;
asm volatile("mfmsr %0" : "=r" (msr));
oldmsr = msr;
msr &= ~0x10;
for(uint32_t i = 0; i<size/0x04; i++) {
uint32_t value_read = 0;
uint32_t addr = addr_base + (i*4);
// Disable Data address translation
asm volatile("mtmsr %0" : : "r" (msr));
__asm __volatile("lwz %0,0(%1)" : "=r"(value_read) : "r"(addr));
// Enable Data address translation
asm volatile("mtmsr %0" : : "r" (oldmsr));
dest[i] = value_read;
}
}
void KernelWritePTE(uint32_t * in_addr, uint32_t size) {
uint32_t msr = 0;
uint32_t oldmsr = 0;
//TODO: Calculate from SDR1
uint32_t addr_base = 0xFFE20000;
asm volatile("mfmsr %0" : "=r" (msr));
oldmsr = msr;
msr &= ~0x10;
for(uint32_t i = 0; i<size/0x04; i++) {
uint32_t addr = addr_base + (i*4);
uint32_t value = in_addr[i];
// Disable Data address translation
asm volatile("mtmsr %0" : : "r" (msr));
__asm __volatile("stw %0,0(%1)" : : "r"(value),"r"(addr));
// Enable Data address translation
asm volatile("mtmsr %0" : : "r" (oldmsr));
}
}
void KernelWriteWitoutDAT(uint32_t addr, uint32_t value) {
uint32_t msr = 0;
uint32_t oldmsr = 0;
//TODO: Calculate from SDR1
//uint32_t addr_base = 0xFFE20000;
asm volatile("mfmsr %0" : "=r" (msr));
oldmsr = msr;
msr &= ~0x10;
// Disable Data address translation
asm volatile("mtmsr %0" : : "r" (msr));
__asm __volatile("stw %0,0(%1)" : : "r"(value),"r"(addr));
// Enable Data address translation
asm volatile("mtmsr %0" : : "r" (oldmsr));
}
void SC0x0A_KernelWriteWitoutDAT(uint32_t addr,uint32_t value);
void wups_init_kernel_syscalls() {
//! assign 1 so that this variable gets into the retained .data section
static uint8_t ucSyscallsSetupRequired = 1;
if(!ucSyscallsSetupRequired)
return;
ucSyscallsSetupRequired = 0;
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x0A * 4)), (uint32_t)KernelWriteWitoutDAT);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x0A * 4)), (uint32_t)KernelWriteWitoutDAT);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x0A * 4)), (uint32_t)KernelWriteWitoutDAT);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x0A * 4)), (uint32_t)KernelWriteWitoutDAT);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x0A * 4)), (uint32_t)KernelWriteWitoutDAT);
// Override all writes to SR8 with nops.
SC0x0A_KernelWriteWitoutDAT(0xFFF1D754,0x60000000);
SC0x0A_KernelWriteWitoutDAT(0xFFF1D64C,0x60000000);
SC0x0A_KernelWriteWitoutDAT(0xFFE00638,0x60000000);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x36 * 4)), (uint32_t)KernelReadSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x36 * 4)), (uint32_t)KernelReadSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x36 * 4)), (uint32_t)KernelReadSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x36 * 4)), (uint32_t)KernelReadSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x36 * 4)), (uint32_t)KernelReadSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x37 * 4)), (uint32_t)KernelReadPTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x37 * 4)), (uint32_t)KernelReadPTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x37 * 4)), (uint32_t)KernelReadPTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x37 * 4)), (uint32_t)KernelReadPTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x37 * 4)), (uint32_t)KernelReadPTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x09 * 4)), (uint32_t)KernelWritePTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x09 * 4)), (uint32_t)KernelWritePTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x09 * 4)), (uint32_t)KernelWritePTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x09 * 4)), (uint32_t)KernelWritePTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x09 * 4)), (uint32_t)KernelWritePTE);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x0A * 4)), (uint32_t)KernelWriteSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x0A * 4)), (uint32_t)KernelWriteSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x0A * 4)), (uint32_t)KernelWriteSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x0A * 4)), (uint32_t)KernelWriteSRs);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x0A * 4)), (uint32_t)KernelWriteSRs);
}

View File

@ -1,14 +0,0 @@
#ifndef __WUPS_KERNEL_UTILS_H_
#define __WUPS_KERNEL_UTILS_H_
#ifdef __cplusplus
extern "C" {
#endif
void wups_init_kernel_syscalls();
#ifdef __cplusplus
}
#endif
#endif // __WUPS_KERNEL_UTILS_H_

View File

@ -1,20 +0,0 @@
#ifndef __WUPS_SYSCALLS_H_
#define __WUPS_SYSCALLS_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "kernel_defs.h"
void SC0x0A_KernelWriteSRs(sr_table_t * table);
void SC0x36_KernelReadSRs(sr_table_t * table);
void SC0x37_KernelReadPTE(uint32_t* dest, uint32_t size);
void SC0x09_KernelWritePTE(uint32_t* addr,uint32_t size);
void KernelTest();
#ifdef __cplusplus
}
#endif
#endif // __WUPS_SYSCALLS_H_

View File

@ -1,30 +0,0 @@
.globl SC0x36_KernelReadSRs
SC0x36_KernelReadSRs:
li r0, 0x3600
sc
blr
.globl SC0x0A_KernelWriteSRs
SC0x0A_KernelWriteSRs:
li r0, 0x0A00
sc
blr
.globl SC0x0A_KernelWriteWitoutDAT
SC0x0A_KernelWriteWitoutDAT:
li r0, 0x0A00
sc
blr
.globl SC0x37_KernelReadPTE
SC0x37_KernelReadPTE:
li r0, 0x3700
sc
blr
.globl SC0x09_KernelWritePTE
SC0x09_KernelWritePTE:
li r0, 0x0900
sc
blr

View File

@ -1,748 +0,0 @@
#include "memory_mapping.h"
#include "mykernel/syscalls.h"
#include "common/retain_vars.h"
#include <kernel/syscalls.h>
#include <utils/logger.h>
#include <utils/utils.h>
#include <system/CThread.h>
#include <fs/FSUtils.h>
#include <vector>
#include <dynamic_libs/os_functions.h>
#include <stdio.h>
#include <string.h>
void runOnAllCores(CThread::Callback callback, void *callbackArg, int32_t iAttr = 0, int32_t iPriority = 16, int32_t iStackSize = 0x8000) {
int32_t aff[] = {CThread::eAttributeAffCore2,CThread::eAttributeAffCore1,CThread::eAttributeAffCore0};
for(uint32_t i = 0; i <(sizeof(aff)/sizeof(aff[0])); i++) {
CThread * thread = CThread::create(callback, callbackArg, iAttr | aff[i],iPriority,iStackSize);
thread->resumeThread();
delete thread;
}
}
void writeSegmentRegister(CThread *thread, void *arg) {
sr_table_t * table = (sr_table_t *) arg;
uint16_t core = OSGetThreadAffinity(OSGetCurrentThread());
DEBUG_FUNCTION_LINE("Writing segment register to core %d\n",core);
DCFlushRange(table,sizeof(sr_table_t));
SC0x0A_KernelWriteSRs(table);
}
void readAndPrintSegmentRegister(CThread *thread, void *arg) {
uint16_t core = OSGetThreadAffinity(OSGetCurrentThread());
DEBUG_FUNCTION_LINE("Reading segment register and page table from core %d\n",core);
sr_table_t srTable;
memset(&srTable,0,sizeof(srTable));
SC0x36_KernelReadSRs(&srTable);
DCFlushRange(&srTable,sizeof(srTable));
for(int32_t i = 0; i < 16; i++) {
DEBUG_FUNCTION_LINE("[%d] SR[%d]=%08X\n",core,i,srTable.value[i]);
}
uint32_t pageTable[0x8000];
memset(pageTable,0,sizeof(pageTable));
DEBUG_FUNCTION_LINE("Reading pageTable now.\n");
SC0x37_KernelReadPTE(pageTable,sizeof(pageTable));
DCFlushRange(pageTable,sizeof(pageTable));
DEBUG_FUNCTION_LINE("Reading pageTable done\n");
MemoryMapping::printPageTableTranslation(srTable,pageTable);
DEBUG_FUNCTION_LINE("-----------------------------\n");
}
bool MemoryMapping::isMemoryMapped() {
sr_table_t srTable;
memset(&srTable,0,sizeof(srTable));
SC0x36_KernelReadSRs(&srTable);
if((srTable.value[MEMORY_START_BASE >> 28] & 0x00FFFFFF) == SEGMENT_UNIQUE_ID) {
return true;
}
return false;
}
uint32_t MemoryMapping::getHeapAddress() {
return MEMORY_START_PLUGIN_HEAP;
}
uint32_t MemoryMapping::getHeapSize() {
return getAreaSizeFromPageTable(MEMORY_START_PLUGIN_HEAP,MEMORY_START_PLUGIN_HEAP_END - MEMORY_START_PLUGIN_HEAP);
}
uint32_t MemoryMapping::getVideoMemoryAddress() {
return MEMORY_START_VIDEO_SPACE;
}
uint32_t MemoryMapping::getVideoMemorySize() {
return getAreaSizeFromPageTable(MEMORY_START_VIDEO_SPACE,MEMORY_START_VIDEO_SPACE_END - MEMORY_START_VIDEO_SPACE);
}
void MemoryMapping::searchEmptyMemoryRegions() {
DEBUG_FUNCTION_LINE("Searching for empty memory.\n");
for(int32_t i = 0;; i++) {
if(mem_mapping[i].physical_addresses == NULL) {
break;
}
uint32_t ea_start_address = mem_mapping[i].effective_start_address;
const memory_values_t * mem_vals = mem_mapping[i].physical_addresses;
uint32_t ea_size = 0;
for(uint32_t j = 0;; j++) {
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if(pa_end_address == 0 && pa_start_address == 0) {
break;
}
ea_size += pa_end_address - pa_start_address;
}
uint32_t* flush_start = (uint32_t*)ea_start_address;
uint32_t flush_size = ea_size;
DEBUG_FUNCTION_LINE("Flushing %08X (%d kB) at %08X.\n",flush_size,flush_size/1024, flush_start);
DCFlushRange(flush_start,flush_size);
DEBUG_FUNCTION_LINE("Searching in memory region %d. 0x%08X - 0x%08X. Size 0x%08X (%d KBytes).\n",i+1,ea_start_address,ea_start_address+ea_size,ea_size,ea_size/1024);
bool success = true;
uint32_t * memory_ptr = (uint32_t*) ea_start_address;
bool inFailRange = false;
uint32_t startFailing = 0;
uint32_t startGood = ea_start_address;
for(uint32_t j=0; j < ea_size/4; j++) {
if(memory_ptr[j] != 0) {
success = false;
if(!success && !inFailRange) {
if((((uint32_t)&memory_ptr[j])-(uint32_t)startGood)/1024 > 512) {
uint32_t start_addr = startGood & 0xFFFE0000;
if(start_addr != startGood) {
start_addr += 0x20000;
}
uint32_t end_addr = ((uint32_t)&memory_ptr[j]) - MEMORY_START_BASE;
end_addr = (end_addr & 0xFFFE0000);
DEBUG_FUNCTION_LINE("+ Free between 0x%08X and 0x%08X size: %u kB\n",start_addr - MEMORY_START_BASE,end_addr,(((uint32_t)end_addr)-((uint32_t)startGood - MEMORY_START_BASE))/1024);
}
startFailing = (uint32_t)&memory_ptr[j];
inFailRange = true;
startGood = 0;
j = ((j & 0xFFFF8000) + 0x00008000)-1;
}
//break;
} else {
if(inFailRange) {
//DEBUG_FUNCTION_LINE("- Error between 0x%08X and 0x%08X size: %u kB\n",startFailing,&memory_ptr[j],(((uint32_t)&memory_ptr[j])-(uint32_t)startFailing)/1024);
startFailing = 0;
startGood = (uint32_t) &memory_ptr[j];
inFailRange = false;
}
}
}
if(startGood != 0 && (startGood != ea_start_address + ea_size)) {
DEBUG_FUNCTION_LINE("+ Good between 0x%08X and 0x%08X size: %u kB\n",startGood - MEMORY_START_BASE,((uint32_t)(ea_start_address + ea_size) - (uint32_t)MEMORY_START_BASE),((uint32_t)(ea_start_address + ea_size) - (uint32_t)startGood)/1024);
} else if(inFailRange) {
DEBUG_FUNCTION_LINE("- Used between 0x%08X and 0x%08X size: %u kB\n",startFailing,ea_start_address + ea_size,((uint32_t)(ea_start_address + ea_size) - (uint32_t)startFailing)/1024);
}
if(success) {
DEBUG_FUNCTION_LINE("Test %d was successful!\n",i+1);
}
}
DEBUG_FUNCTION_LINE("All tests done.\n");
}
void MemoryMapping::writeTestValuesToMemory() {
//don't smash the stack.
uint32_t chunk_size = 0x1000;
uint32_t testBuffer[chunk_size];
for(int32_t i = 0;; i++) {
if(mem_mapping[i].physical_addresses == NULL) {
break;
}
uint32_t cur_ea_start_address = mem_mapping[i].effective_start_address;
DEBUG_FUNCTION_LINE("Preparing memory test for region %d. Region start at effective address %08X.\n",i+1,cur_ea_start_address);
const memory_values_t * mem_vals = mem_mapping[i].physical_addresses;
uint32_t counter = 0;
for(uint32_t j = 0;; j++) {
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if(pa_end_address == 0 && pa_start_address == 0) {
break;
}
uint32_t pa_size = pa_end_address - pa_start_address;
DEBUG_FUNCTION_LINE("Writing region %d of mapping %d. From %08X to %08X Size: %d KBytes...\n",j+1,i+1,pa_start_address,pa_end_address,pa_size/1024);
for(uint32_t k=0; k<=pa_size/4; k++) {
if(k > 0 && (k % chunk_size) == 0) {
DCFlushRange(&testBuffer,sizeof(testBuffer));
DCInvalidateRange(&testBuffer,sizeof(testBuffer));
uint32_t destination = pa_start_address + ((k*4) - sizeof(testBuffer));
SC0x25_KernelCopyData(destination,(uint32_t)OSEffectiveToPhysical(testBuffer),sizeof(testBuffer));
//DEBUG_FUNCTION_LINE("Copy testBuffer into %08X\n",destination);
}
if(k != pa_size/4) {
testBuffer[k % chunk_size] = counter++;
}
//DEBUG_FUNCTION_LINE("testBuffer[%d] = %d\n",i % chunk_size,i);
}
uint32_t* flush_start = (uint32_t*)cur_ea_start_address;
uint32_t flush_size = pa_size;
cur_ea_start_address += pa_size;
DEBUG_FUNCTION_LINE("Flushing %08X (%d kB) at %08X to map memory.\n",flush_size,flush_size/1024, flush_start);
DCFlushRange(flush_start,flush_size);
}
DEBUG_FUNCTION_LINE("Done writing region %d\n",i+1);
}
}
void MemoryMapping::readTestValuesFromMemory() {
DEBUG_FUNCTION_LINE("Testing reading the written values.\n");
for(int32_t i = 0;; i++) {
if(mem_mapping[i].physical_addresses == NULL) {
break;
}
uint32_t ea_start_address = mem_mapping[i].effective_start_address;
const memory_values_t * mem_vals = mem_mapping[i].physical_addresses;
//uint32_t counter = 0;
uint32_t ea_size = 0;
for(uint32_t j = 0;; j++) {
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if(pa_end_address == 0 && pa_start_address == 0) {
break;
}
ea_size += pa_end_address - pa_start_address;
}
uint32_t* flush_start = (uint32_t*)ea_start_address;
uint32_t flush_size = ea_size;
DEBUG_FUNCTION_LINE("Flushing %08X (%d kB) at %08X to map memory.\n",flush_size,flush_size/1024, flush_start);
DCFlushRange(flush_start,flush_size);
DEBUG_FUNCTION_LINE("Testing memory region %d. 0x%08X - 0x%08X. Size 0x%08X (%d KBytes).\n",i+1,ea_start_address,ea_start_address+ea_size,ea_size,ea_size/1024);
bool success = true;
uint32_t * memory_ptr = (uint32_t*) ea_start_address;
bool inFailRange = false;
uint32_t startFailing = 0;
uint32_t startGood = ea_start_address;
for(uint32_t j=0; j < ea_size/4; j++) {
if(memory_ptr[j] != j) {
success = false;
if(!success && !inFailRange) {
DEBUG_FUNCTION_LINE("+ Good between 0x%08X and 0x%08X size: %u kB\n",startGood,&memory_ptr[j],(((uint32_t)&memory_ptr[j])-(uint32_t)startGood)/1024);
startFailing = (uint32_t)&memory_ptr[j];
inFailRange = true;
startGood = 0;
j = ((j & 0xFFFF8000) + 0x00008000)-1;
}
//break;
} else {
if(inFailRange) {
DEBUG_FUNCTION_LINE("- Error between 0x%08X and 0x%08X size: %u kB\n",startFailing,&memory_ptr[j],(((uint32_t)&memory_ptr[j])-(uint32_t)startFailing)/1024);
startFailing = 0;
startGood = (uint32_t) &memory_ptr[j];
inFailRange = false;
}
}
}
if(startGood != 0 && (startGood != ea_start_address + ea_size)) {
DEBUG_FUNCTION_LINE("+ Good between 0x%08X and 0x%08X size: %u kB\n",startGood,ea_start_address + ea_size,((uint32_t)(ea_start_address + ea_size) - (uint32_t)startGood)/1024);
} else if(inFailRange) {
DEBUG_FUNCTION_LINE("- Error between 0x%08X and 0x%08X size: %u kB\n",startFailing,ea_start_address + ea_size,((uint32_t)(ea_start_address + ea_size) - (uint32_t)startFailing)/1024);
}
if(success) {
DEBUG_FUNCTION_LINE("Test %d was successful!\n",i+1);
}
}
DEBUG_FUNCTION_LINE("All tests done.\n");
}
void MemoryMapping::memoryMappingForRegions(const memory_mapping_t * memory_mapping, sr_table_t SRTable, uint32_t * translation_table) {
for(int32_t i = 0; /* waiting for a break */; i++) {
DEBUG_FUNCTION_LINE("In loop %d\n",i);
if(memory_mapping[i].physical_addresses == NULL) {
DEBUG_FUNCTION_LINE("break %d\n",i);
break;
}
uint32_t cur_ea_start_address = memory_mapping[i].effective_start_address;
DEBUG_FUNCTION_LINE("Mapping area %d. effective address %08X...\n",i+1,cur_ea_start_address);
const memory_values_t * mem_vals = memory_mapping[i].physical_addresses;
for(uint32_t j = 0;; j++) {
DEBUG_FUNCTION_LINE("In inner loop %d\n",j);
uint32_t pa_start_address = mem_vals[j].start_address;
uint32_t pa_end_address = mem_vals[j].end_address;
if(pa_end_address == 0 && pa_start_address == 0) {
DEBUG_FUNCTION_LINE("inner break %d\n",j);
// Break if entry was empty.
break;
}
uint32_t pa_size = pa_end_address - pa_start_address;
DEBUG_FUNCTION_LINE("Adding page table entry %d for mapping area %d. %08X-%08X => %08X-%08X...\n",j+1,i+1,cur_ea_start_address,memory_mapping[i].effective_start_address+pa_size,pa_start_address,pa_end_address);
if(!mapMemory(pa_start_address,pa_end_address,cur_ea_start_address,SRTable,translation_table)) {
log_print("error =(\n");
DEBUG_FUNCTION_LINE("Failed to map memory.\n");
//OSFatal("Failed to map memory.");
return;
break;
}
cur_ea_start_address += pa_size;
log_print("done\n");
}
}
}
void MemoryMapping::setupMemoryMapping() {
//runOnAllCores(readAndPrintSegmentRegister,NULL,0,16,0x20000);
sr_table_t srTableCpy;
uint32_t pageTableCpy[0x8000];
SC0x36_KernelReadSRs(&srTableCpy);
SC0x37_KernelReadPTE(pageTableCpy,sizeof(pageTableCpy));
DCFlushRange(&srTableCpy,sizeof(srTableCpy));
DCFlushRange(pageTableCpy,sizeof(pageTableCpy));
for(int32_t i = 0; i < 16; i++) {
DEBUG_FUNCTION_LINE("SR[%d]=%08X\n",i,srTableCpy.value[i]);
}
printPageTableTranslation(srTableCpy,pageTableCpy);
// According to
// http://wiiubrew.org/wiki/Cafe_OS#Virtual_Memory_Map 0x80000000
// is currently unmapped.
// This is nice because it leads to SR[8] which also seems to be unused (was set to 0x30FFFFFF)
// The content of the segment was chosen randomly.
uint32_t segment_index = MEMORY_START_BASE >> 28;
uint32_t segment_content = 0x00000000 | SEGMENT_UNIQUE_ID;
DEBUG_FUNCTION_LINE("Setting SR[%d] to %08X\n",segment_index,segment_content);
srTableCpy.value[segment_index] = segment_content;
DCFlushRange(&srTableCpy,sizeof(srTableCpy));
DEBUG_FUNCTION_LINE("Writing segment registers...\n",segment_index,segment_content);
// Writing the segment registers to ALL cores.
runOnAllCores(writeSegmentRegister,&srTableCpy);
memoryMappingForRegions(mem_mapping,srTableCpy,pageTableCpy);
//printPageTableTranslation(srTableCpy,pageTableCpy);
DEBUG_FUNCTION_LINE("Writing PageTable... ");
DCFlushRange(pageTableCpy,sizeof(pageTableCpy));
SC0x09_KernelWritePTE(pageTableCpy,sizeof(pageTableCpy));
DCFlushRange(pageTableCpy,sizeof(pageTableCpy));
log_print("done\n");
//printPageTableTranslation(srTableCpy,pageTableCpy);
runOnAllCores(readAndPrintSegmentRegister,NULL,0,16,0x80000);
//searchEmptyMemoryRegions();
//writeTestValuesToMemory();
//readTestValuesFromMemory();
}
uint32_t MemoryMapping::getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize) {
sr_table_t srTable;
uint32_t pageTable[0x8000];
SC0x36_KernelReadSRs(&srTable);
SC0x37_KernelReadPTE(pageTable,sizeof(pageTable));
uint32_t sr_start = start >> 28;
uint32_t sr_end = (start + maxSize) >> 28;
if(sr_end < sr_start) {
return 0;
}
uint32_t cur_address = start;
uint32_t end_address = start + maxSize;
uint32_t memSize = 0;
for(uint32_t segment = sr_start; segment <= sr_end ; segment++) {
uint32_t sr = srTable.value[segment];
if(sr >> 31) {
DEBUG_FUNCTION_LINE("Direct access not supported\n");
} else {
uint32_t vsid = sr & 0xFFFFFF;
uint32_t pageSize = 1 << PAGE_INDEX_SHIFT;
uint32_t cur_end_addr = 0;
if(segment == sr_end) {
cur_end_addr = end_address;
} else {
cur_end_addr = (segment + 1) * 0x10000000;
}
if(segment != sr_start) {
cur_address = (segment) * 0x10000000;
}
bool success = true;
for(uint32_t addr = cur_address; addr < cur_end_addr; addr += pageSize) {
uint32_t PTEH = 0;
uint32_t PTEL = 0;
if(getPageEntryForAddress(srTable.sdr1, addr, vsid, pageTable, &PTEH, &PTEL, false)) {
memSize += pageSize;
} else {
success = false;
break;
}
}
if(!success) {
break;
}
}
}
return memSize;
}
bool MemoryMapping::getPageEntryForAddress(uint32_t SDR1,uint32_t addr, uint32_t vsid, uint32_t * translation_table,uint32_t* oPTEH, uint32_t* oPTEL, bool checkSecondHash) {
uint32_t pageMask = SDR1 & 0x1FF;
uint32_t pageIndex = (addr >> PAGE_INDEX_SHIFT) & PAGE_INDEX_MASK;
uint32_t primaryHash = (vsid & 0x7FFFF) ^ pageIndex;
if(getPageEntryForAddressEx(SDR1, addr, vsid, primaryHash, translation_table, oPTEH, oPTEL, 0)) {
return true;
}
if(checkSecondHash) {
if(getPageEntryForAddressEx(pageMask, addr, vsid, ~primaryHash, translation_table, oPTEH, oPTEL, 1)) {
return true;
}
}
return false;
}
bool MemoryMapping::getPageEntryForAddressEx(uint32_t pageMask, uint32_t addr, uint32_t vsid, uint32_t primaryHash, uint32_t * translation_table,uint32_t* oPTEH, uint32_t* oPTEL,uint32_t H) {
uint32_t maskedHash = primaryHash & ((pageMask << 10) | 0x3FF);
uint32_t api = (addr >> 22) & 0x3F;
uint32_t pteAddrOffset = (maskedHash << 6);
for (int32_t j = 0; j < 8; j++, pteAddrOffset += 8) {
uint32_t PTEH = 0;
uint32_t PTEL = 0;
uint32_t pteh_index = pteAddrOffset / 4;
uint32_t ptel_index = pteh_index + 1;
PTEH = translation_table[pteh_index];
PTEL = translation_table[ptel_index];
//Check validity
if (!(PTEH >> 31)) {
//printf("PTE is not valid \n");
continue;
}
//DEBUG_FUNCTION_LINE("in\n");
// the H bit indicated if the PTE was found using the second hash.
if (((PTEH >> 6) & 1) != H) {
//DEBUG_FUNCTION_LINE("Secondary hash is used\n",((PTEH >> 6) & 1));
continue;
}
// Check if the VSID matches, otherwise this is a PTE for another SR
// This is the place where collision could happen.
// Hopefully no collision happen and only the PTEs of the SR will match.
if (((PTEH >> 7) & 0xFFFFFF) != vsid) {
//DEBUG_FUNCTION_LINE("VSID mismatch\n");
continue;
}
// Check the API (Abbreviated Page Index)
if ((PTEH & 0x3F) != api) {
//DEBUG_FUNCTION_LINE("API mismatch\n");
continue;
}
*oPTEH = PTEH;
*oPTEL = PTEL;
return true;
}
return false;
}
void MemoryMapping::printPageTableTranslation(sr_table_t srTable, uint32_t * translation_table) {
uint32_t SDR1 = srTable.sdr1;
pageInformation current;
memset(&current,0,sizeof(current));
std::vector<pageInformation> pageInfos;
for(uint32_t segment = 0; segment < 16 ; segment++) {
uint32_t sr = srTable.value[segment];
if(sr >> 31) {
DEBUG_FUNCTION_LINE("Direct access not supported\n");
} else {
uint32_t ks = (sr >> 30) & 1;
uint32_t kp = (sr >> 29) & 1;
uint32_t nx = (sr >> 28) & 1;
uint32_t vsid = sr & 0xFFFFFF;
DEBUG_FUNCTION_LINE("ks %08X kp %08X nx %08X vsid %08X\n",ks,kp,nx,vsid);
uint32_t pageSize = 1 << PAGE_INDEX_SHIFT;
for(uint32_t addr = segment * 0x10000000; addr < (segment + 1) * 0x10000000; addr += pageSize) {
uint32_t PTEH = 0;
uint32_t PTEL = 0;
if(getPageEntryForAddress(SDR1, addr, vsid, translation_table, &PTEH, &PTEL, false)) {
uint32_t pp = PTEL & 3;
uint32_t phys = PTEL & 0xFFFFF000;
//DEBUG_FUNCTION_LINE("current.phys == phys - current.size ( %08X %08X)\n",current.phys, phys - current.size);
if( current.ks == ks &&
current.kp == kp &&
current.nx == nx &&
current.pp == pp &&
current.phys == phys - current.size
) {
current.size += pageSize;
//DEBUG_FUNCTION_LINE("New size of %08X is %08X\n",current.addr,current.size);
} else {
if(current.addr != 0 && current.size != 0) {
/*DEBUG_FUNCTION_LINE("Saving old block from %08X\n",current.addr);
DEBUG_FUNCTION_LINE("ks %08X new %08X\n",current.ks,ks);
DEBUG_FUNCTION_LINE("kp %08X new %08X\n",current.kp,kp);
DEBUG_FUNCTION_LINE("nx %08X new %08X\n",current.nx,nx);
DEBUG_FUNCTION_LINE("pp %08X new %08X\n",current.pp,pp);*/
pageInfos.push_back(current);
memset(&current,0,sizeof(current));
}
//DEBUG_FUNCTION_LINE("Found new block at %08X\n",addr);
current.addr = addr;
current.size = pageSize;
current.kp = kp;
current.ks = ks;
current.nx = nx;
current.pp = pp;
current.phys = phys;
}
} else {
if(current.addr != 0 && current.size != 0) {
pageInfos.push_back(current);
memset(&current,0,sizeof(current));
}
}
}
}
}
const char *access1[] = {"read/write", "read/write", "read/write", "read only"};
const char *access2[] = {"no access", "read only", "read/write", "read only"};
for(std::vector<pageInformation>::iterator it = pageInfos.begin(); it != pageInfos.end(); ++it) {
pageInformation cur = *it;
DEBUG_FUNCTION_LINE("%08X %08X -> %08X %08X. user access %s. supervisor access %s. %s\n",cur.addr,cur.addr+cur.size,cur.phys,cur.phys+cur.size,cur.kp ? access2[cur.pp] : access1[cur.pp],
cur.ks ? access2[cur.pp] : access1[cur.pp],cur.nx? "not executable" : "executable");
}
}
bool MemoryMapping::mapMemory(uint32_t pa_start_address,uint32_t pa_end_address,uint32_t ea_start_address, sr_table_t SRTable, uint32_t * translation_table) {
// Based on code from dimok. Thanks!
//uint32_t byteOffsetMask = (1 << PAGE_INDEX_SHIFT) - 1;
//uint32_t apiShift = 22 - PAGE_INDEX_SHIFT;
// Information on page 5.
// https://www.nxp.com/docs/en/application-note/AN2794.pdf
uint32_t HTABORG = SRTable.sdr1 >> 16;
uint32_t HTABMASK = SRTable.sdr1 & 0x1FF;
// Iterate to all possible pages. Each page is 1<<(PAGE_INDEX_SHIFT) big.
uint32_t pageSize = 1<<(PAGE_INDEX_SHIFT);
for(uint32_t i = 0; i < pa_end_address - pa_start_address; i += pageSize) {
// Calculate the current effective address.
uint32_t ea_addr = ea_start_address + i;
// Calculate the segement.
uint32_t segment = SRTable.value[ea_addr >> 28];
// Unique ID from the segment which is the input for the hash function.
// Change it to prevent collisions.
uint32_t VSID = segment & 0x00FFFFFF;
uint32_t V = 1;
//Indicated if second hash is used.
uint32_t H = 0;
// Abbreviated Page Index
// Real page number
uint32_t RPN = (pa_start_address + i) >> 12;
uint32_t RC = 3;
uint32_t WIMG = 0x02;
uint32_t PP = 0x02;
uint32_t page_index = (ea_addr >> PAGE_INDEX_SHIFT) & PAGE_INDEX_MASK;
uint32_t API = (ea_addr >> 22) & 0x3F;
uint32_t PTEH = (V << 31) | (VSID << 7) | (H << 6) | API;
uint32_t PTEL = (RPN << 12) | (RC << 7) | (WIMG << 3) | PP;
//unsigned long long virtual_address = ((unsigned long long)VSID << 28UL) | (page_index << PAGE_INDEX_SHIFT) | (ea_addr & 0xFFF);
uint32_t primary_hash = (VSID & 0x7FFFF);
uint32_t hashvalue1 = primary_hash ^ page_index;
// hashvalue 2 is the complement of the first hash.
uint32_t hashvalue2 = ~hashvalue1;
//uint32_t pageMask = SRTable.sdr1 & 0x1FF;
// calculate the address of the PTE groups.
// PTEs are saved in a group of 8 PTEs
// When PTEGaddr1 is full (all 8 PTEs set), PTEGaddr2 is used.
// Then H in PTEH needs to be set to 1.
uint32_t PTEGaddr1 = (HTABORG << 16) | (((hashvalue1 >> 10) & HTABMASK) << 16) | ((hashvalue1 & 0x3FF) << 6);
uint32_t PTEGaddr2 = (HTABORG << 16) | (((hashvalue2 >> 10) & HTABMASK) << 16) | ((hashvalue2 & 0x3FF) << 6);
//offset of the group inside the PTE Table.
uint32_t PTEGoffset = PTEGaddr1 - (HTABORG << 16);
bool setSuccessfully = false;
PTEGoffset += 7*8;
// Lets iterate through the PTE group where out PTE should be saved.
for(int32_t j = 7; j>0; PTEGoffset -= 8) {
int32_t index = (PTEGoffset/4);
uint32_t pteh = translation_table[index];
// Check if it's already taken. The first bit indicates if the PTE-slot inside
// this group is already taken.
if ((pteh == 0)) {
// If we found a free slot, set the PTEH and PTEL value.
DEBUG_FUNCTION_LINE("Used slot %d. PTEGaddr1 %08X addr %08X\n",j+1,PTEGaddr1 - (HTABORG << 16),PTEGoffset);
translation_table[index] = PTEH;
translation_table[index+1] = PTEL;
setSuccessfully = true;
break;
} else {
//printf("PTEGoffset %08X was taken\n",PTEGoffset);
}
j--;
}
// Check if we already found a slot.
if(!setSuccessfully) {
DEBUG_FUNCTION_LINE("-------------- Using second slot -----------------------\n");
// We still have a chance to find a slot in the PTEGaddr2 using the complement of the hash.
// We need to set the H flag in PTEH and use PTEGaddr2.
// (Not well tested)
H = 1;
PTEH = (V << 31) | (VSID << 7) | (H << 6) | API;
PTEGoffset = PTEGaddr2 - (HTABORG << 16);
PTEGoffset += 7*8;
// Same as before.
for(int32_t j = 7; j>0; PTEGoffset -= 8) {
int32_t index = (PTEGoffset/4);
uint32_t pteh = translation_table[index];
//Check if it's already taken.
if ((pteh == 0)) {
translation_table[index] = PTEH;
translation_table[index+1] = PTEL;
setSuccessfully = true;
break;
} else {
//printf("PTEGoffset %08X was taken\n",PTEGoffset);
}
j--;
}
if(!setSuccessfully) {
// Fail if we couldn't find a free slot.
DEBUG_FUNCTION_LINE("-------------- No more free PTE -----------------------\n");
return false;
}
}
}
return true;
}
uint32_t MemoryMapping::PhysicalToEffective(uint32_t phyiscalAddress) {
uint32_t result = 0;
const memory_values_t * curMemValues = NULL;
int32_t curOffset = 0;
//iterate through all own mapped memory regions
for(int32_t i = 0; true; i++) {
if(mem_mapping[i].physical_addresses == NULL) {
break;
}
curMemValues = mem_mapping[i].physical_addresses;
uint32_t curOffsetInEA = 0;
// iterate through all memory values of this region
for(int32_t j= 0; true; j++) {
if(curMemValues[j].end_address == 0) {
break;
}
if(phyiscalAddress >= curMemValues[j].start_address && phyiscalAddress < curMemValues[j].end_address) {
// calculate the EA
result = (phyiscalAddress - curMemValues[j].start_address) + (mem_mapping[i].effective_start_address + curOffsetInEA);
return result;
}
curOffsetInEA += curMemValues[j].end_address - curMemValues[j].start_address;
}
}
return result;
}
uint32_t MemoryMapping::EffectiveToPhysical(uint32_t effectiveAddress) {
uint32_t result = 0;
// CAUTION: The data may be fragmented between multiple areas in PA.
const memory_values_t * curMemValues = NULL;
int32_t curOffset = 0;
for(int32_t i = 0; true; i++) {
if(mem_mapping[i].physical_addresses == NULL) {
break;
}
if(effectiveAddress >= mem_mapping[i].effective_start_address && effectiveAddress < mem_mapping[i].effective_end_address) {
curMemValues = mem_mapping[i].physical_addresses;
curOffset = mem_mapping[i].effective_start_address;
break;
}
}
if(curMemValues == NULL) {
return result;
}
for(int32_t i= 0; true; i++) {
if(curMemValues[i].end_address == 0) {
break;
}
int32_t curChunkSize = curMemValues[i].end_address - curMemValues[i].start_address;
if(effectiveAddress < (curOffset + curChunkSize)) {
result = (effectiveAddress - curOffset) + curMemValues[i].start_address;
break;
}
curOffset += curChunkSize;
}
return result;
}

View File

@ -1,201 +0,0 @@
#ifndef __WUPS_MEMORY_MAPPING_H_
#define __WUPS_MEMORY_MAPPING_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <dynamic_libs/os_types.h>
#include "mykernel/kernel_defs.h"
typedef struct pageInformation_ {
uint32_t addr;
uint32_t size;
uint32_t ks;
uint32_t kp;
uint32_t nx;
uint32_t pp;
uint32_t phys;
} pageInformation;
typedef struct _memory_values_t {
uint32_t start_address;
uint32_t end_address;
} memory_values_t;
typedef struct _memory_mapping_t {
uint32_t effective_start_address;
uint32_t effective_end_address;
const memory_values_t* physical_addresses;
} memory_mapping_t;
#define SEGMENT_UNIQUE_ID 0x00AABBCC // Unique ID. Chosen arbitrary.
#define PAGE_INDEX_SHIFT (32-15)
#define PAGE_INDEX_MASK ((1 << (28 - PAGE_INDEX_SHIFT)) - 1)
#define MEMORY_START_BASE 0x80000000
#define MEMORY_LOADER_SPACE_SIZE 0x00800000 // At most: 8MB for the plugin loader.
#define MEMORY_PLUGIN_SPACE_SIZE 0x04000000 // At most: 64MB for plugins.
#define MEMORY_VIDEO_SPACE_SIZE 0x03600000 // At most: 56MB for video.
#define MEMORY_PLUGIN_HEAP_SIZE 0x08000000 // At most: 128MB for plugins heap.
#define MEMORY_START_PLUGIN_LOADER MEMORY_START_BASE
#define MEMORY_START_PLUGIN_LOADER_END MEMORY_START_PLUGIN_LOADER + MEMORY_LOADER_SPACE_SIZE
#define MEMORY_START_PLUGIN_SPACE MEMORY_START_PLUGIN_LOADER_END
#define MEMORY_START_PLUGIN_SPACE_END MEMORY_START_PLUGIN_SPACE + MEMORY_PLUGIN_SPACE_SIZE
#define MEMORY_START_VIDEO_SPACE MEMORY_START_PLUGIN_SPACE_END
#define MEMORY_START_VIDEO_SPACE_END MEMORY_START_VIDEO_SPACE + MEMORY_VIDEO_SPACE_SIZE
#define MEMORY_START_PLUGIN_HEAP MEMORY_START_VIDEO_SPACE_END
#define MEMORY_START_PLUGIN_HEAP_END MEMORY_START_PLUGIN_HEAP + MEMORY_PLUGIN_HEAP_SIZE
const memory_values_t mem_vals_loader[] = {
{0x28000000 + 0x06620000, 0x28000000 + 0x06E20000}, // 8MB 0x80000000 0x80800000 -> 0x2E700000 0x2EF00000
{0,0}
};
const memory_values_t mem_vals_plugins[] = {
{0x28000000 + 0x06E20000, 0x28000000 + 0x07E20000}, // 16MB 0x80800000 0x81800000 -> 0x2EF00000 0x2FF00000
{0,0}
};
const memory_values_t mem_vals_video[] = {
// The GPU doesn't have access to the 0x28000000 - 0x32000000 area, so we need memory from somewhere else.
// From the SharedReadHeap of the loader.
//
// #define TinyHeap_Alloc ((int32_t (*)(void* heap, int32_t size, int32_t align,void ** outPtr))0x0101235C)
// #define TinyHeap_Free ((void (*)(void* heap, void * ptr))0x01012814)
// uint32_t SharedReadHeapTrackingAddr = 0xFA000000 + 0x18 + 0x830 // see https://github.com/decaf-emu/decaf-emu/blob/master/src/libdecaf/src/cafe/loader/cafe_loader_shared.cpp#L490
//
// Map the area of the heap to somewhere in the user space and test allocation with
// void * heap = (void*) SharedReadHeapTrackingAddr - [delta due mapping e.g (0xF8000000 + 0x80000000)];
// int size = 0x20000; // value have to be a multiple of 0x20000;
// while(true){
// void * outPtr = NULL;
// if(TinyHeap_Alloc(heap,size, 0x20000,&outPtr) == 0){ // value have to be a multiple of 0x20000;
// DEBUG_FUNCTION_LINE("Allocated %d kb on heap %08X (PA %08X)\n",size/1024,(uint32_t)outPtr, OSEffectiveToPhysical(outPtr));
// TinyHeap_Free(heap, outPtr);
// }else{
// DEBUG_FUNCTION_LINE("Failed %08X\n",(uint32_t)outPtr);
// break;
// }
// size += 0x20000; // value have to be a multiple of 0x20000;
// }
//
{0x1A020000, 0x1A020000 +0xE60000}, // size: 14720 kB
// The following chunk were empty while early tests and are maybe promising. However we can get 15mb from
// a loader heap. Which should be enough for now.
//{0x14000000 + 0x02E00000 , 0x14000000 +0x034E0000}, // size: 7040 kB
//{0x14000000 + 0x02820000 , 0x14000000 +0x02C20000}, // size: 4096 kB
//{0x14000000 + 0x05AE0000 , 0x14000000 +0x06000000}, // size: 5248 kB
//{0x14000000 + 0x08040000 , 0x14000000 +0x08400000}, // size: 3840 kB
//{0x18000000 , 0x18000000 +0x3000000}, // size: 3840 kB
{0,0}
};
// Values needs to be aligned to 0x20000 and size needs to be a multiple of 0x20000
const memory_values_t mem_vals_heap[] = {
// 5.5.2 EUR
{0x28000000 + 0x09000000, 0x28000000 + 0x09E20000}, // size: 14464 kB
{0x28000000 + 0x058E0000, 0x28000000 + 0x06000000}, // size: 7296 kB
{0x28000000 + 0x053C0000, 0x28000000 + 0x05880000}, // size: 4864 kB
{0x28000000 + 0x08C20000, 0x28000000 + 0x08F20000}, // size: 3072 kB
{0x28000000 + 0x00900000, 0x28000000 + 0x00B00000}, // size: 2048 kB
{0x28000000 + 0x07E20000, 0x28000000 + 0x07F80000}, // size: 1408 kB
{0x28000000 + 0x02060000, 0x28000000 + 0x021A0000}, // size: 1280 kB
{0x28000000 + 0x083C0000, 0x28000000 + 0x084C0000}, // size: 1024 kB
{0x28000000 + 0x003C0000, 0x28000000 + 0x004C0000}, // size: 1024 kB
{0x28000000 + 0x02BC0000, 0x28000000 + 0x02CA0000}, // size: 896 kB
{0x28000000 + 0x080E0000, 0x28000000 + 0x08180000}, // size: 640 kB
{0x28000000 + 0x000E0000, 0x28000000 + 0x00160000}, // size: 512 kB
{0x28000000 + 0x00E40000, 0x28000000 + 0x00EC0000}, // size: 512 kB
{0x28000000 + 0x00EE0000, 0x28000000 + 0x00F60000}, // size: 512 kB
{0x28000000 + 0x00FA0000, 0x28000000 + 0x01020000}, // size: 512 kB
{0x28000000 + 0x086E0000, 0x28000000 + 0x08760000}, // size: 512 kB
{0x28000000 + 0x04B60000, 0x28000000 + 0x04B80000}, // size: 128 kB
// This chunk was reduced several times, it _might_ be dangerous to use, let's put it right to the end.
{0x28000000 + 0x01040000, 0x28000000 + 0x01340000}, // size: 3072 kB
// Not usable on 5.5.2
//
// Used in notifications {0x28000000 + 0x01720000, 0x28000000 + 0x018A0000}, // size: 1536 kB
// {0x28000000 + 0x03820000, 0x28000000 + 0x038C0000}, // size: 640 kB
// {0x28000000 + 0x03920000, 0x28000000 + 0x039A0000}, // size: 512 kB
// Used in notifications {0x28000000 + 0x04B80000, 0x28000000 + 0x051E0000}, // size: 6528 kB
// {0x28000000 + 0x08F20000, 0x28000000 + 0x09000000}, // size: 896 kB
// {0x28000000 + 0x013A0000, 0x28000000 + 0x013C0000}, // size: 128 kB
// Porting to other/newer firmware:
// Map this to check for free regions.
// Use MemoryMapper::testFreeMemory() to see regions with are 0x00000000;
// Then map the promising regions, and do the write/read check.
// Writing numbers into the area, open the home menu and all background apps an check if anything was
// overridden.
// {0x28000000 + 0x00000000, 0x28000000 + 0x0A000000}, //
{0,0}
};
const memory_mapping_t mem_mapping[] = {
{MEMORY_START_VIDEO_SPACE, MEMORY_START_VIDEO_SPACE_END, mem_vals_video},
{MEMORY_START_PLUGIN_LOADER, MEMORY_START_PLUGIN_LOADER_END, mem_vals_loader},
{MEMORY_START_PLUGIN_SPACE, MEMORY_START_PLUGIN_SPACE_END, mem_vals_plugins},
{MEMORY_START_PLUGIN_HEAP, MEMORY_START_PLUGIN_HEAP_END, mem_vals_heap},
{0,0,NULL}
};
class MemoryMapping {
public:
static bool isMemoryMapped();
static void setupMemoryMapping();
static void printPageTableTranslation(sr_table_t srTable, uint32_t * translation_table);
static void writeTestValuesToMemory();
static void readTestValuesFromMemory();
static void searchEmptyMemoryRegions();
static uint32_t getHeapAddress();
static uint32_t getHeapSize();
static uint32_t getVideoMemoryAddress();
static uint32_t getVideoMemorySize();
static uint32_t getAreaSizeFromPageTable(uint32_t start, uint32_t maxSize);
// Caution when using the result. A chunk of memory in effective address may be split up
// into several small chunks inside physical space.
static uint32_t PhysicalToEffective(uint32_t phyiscalAddress);
// Caution when using the result. A chunk of memory in effective address may be split up
// into several small chunks inside physical space.
static uint32_t EffectiveToPhysical(uint32_t effectiveAddress);
private:
static void memoryMappingForRegions(const memory_mapping_t * memory_mapping, sr_table_t SRTable, uint32_t * translation_table);
static bool mapMemory(uint32_t pa_start_address,uint32_t pa_end_address,uint32_t ea_start_address, sr_table_t SRTable, uint32_t * translation_table);
static bool getPageEntryForAddress(uint32_t SDR1, uint32_t addr, uint32_t vsid, uint32_t * translation_table,uint32_t* oPTEH, uint32_t* oPTEL, bool checkSecondHash);
static bool getPageEntryForAddressEx(uint32_t pageMask, uint32_t addr, uint32_t vsid, uint32_t primaryHash, uint32_t * translation_table,uint32_t* oPTEH, uint32_t* oPTEL,uint32_t H) ;
};
#ifdef __cplusplus
}
#endif
#endif // __KERNEL_DEFS_H_

View File

@ -1,117 +0,0 @@
/****************************************************************************
* Copyright (C) 2018 Maschell
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/
#include <map>
#include <string>
#include <wups/config/WUPSConfig.h>
#include "ConfigInformation.h"
ConfigInformation::ConfigInformation(WUPSConfig * config, std::string persistPath, std::string persistFileName) {
this->config = config;
this->persistPath = persistPath;
this->persistFileName = persistFileName;
createConfigSettings();
}
ConfigInformation::~ConfigInformation() {
if(configSettings != NULL) {
delete configSettings;
configSettings = NULL;
}
if(config != NULL) {
delete config;
config = NULL;
}
}
bool ConfigInformation::createConfigSettings() {
if(this->config == NULL) {
return false;
}
if(this->configSettings != NULL) {
delete this->configSettings;
}
std::map<int32_t,std::string> defaultValues;
std::map<int32_t,std::string> settingsNames;
int32_t index = 0;
for (auto & curCat : this->config->getCategories()) {
for (auto & curItem : curCat->getItems()) {
std::string configID = curItem->getConfigID();
std::string defaultValue = curItem->persistValue();
defaultValues[index] = defaultValue;
settingsNames[index] = configID;
index++;
}
}
configSettings = new ConfigSettings(persistPath, persistFileName, defaultValues, settingsNames);
return (configSettings != NULL);
}
bool ConfigInformation::loadValuesFromSD() {
if(this->config == NULL || this->configSettings == NULL) {
return false;
}
for (auto & curCat : this->config->getCategories()) {
for (auto & curItem : curCat->getItems()) {
std::string configID = curItem->getConfigID();
std::string prevValue = curItem->persistValue();
std::string loadedValue = this->configSettings->getValueAsString(this->configSettings->getIdByName(configID));
//DEBUG_FUNCTION_LINE("Loaded %s(%d) to %s. Previous value was %s \n",configID.c_str(),this->configSettings->getIdByName(configID), loadedValue.c_str(), prevValue.c_str());
if(prevValue.compare(loadedValue) != 0) {
//DEBUG_FUNCTION_LINE("Call loadValue\n");
curItem->loadValue(loadedValue);
curItem->callCallback();
}
}
}
return true;
}
void ConfigInformation::updateAndSaveSettings(bool forceAll) {
if(this->config == NULL || this->configSettings == NULL) {
return;
}
updateConfigSettings();
configSettings->Save(forceAll);
}
bool ConfigInformation::updateConfigSettings() {
if(this->config == NULL || this->configSettings == NULL) {
return false;
}
for (auto & curCat : this->config->getCategories()) {
for (auto & curItem : curCat->getItems()) {
std::string configID = curItem->getConfigID();
std::string newValue = curItem->persistValue();
if(this->configSettings->setValueAsString(this->configSettings->getIdByName(configID), newValue)) {
// When the value has changed, call the callback.
DEBUG_FUNCTION_LINE("Called callback. Reason. Menu was closed and value has changed\n");
curItem->callCallback();
}
//DEBUG_FUNCTION_LINE("Set %s(%d) to %s\n",configID.c_str(),this->configSettings->getIdByName(configID), newValue.c_str());
}
}
return true;
}

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