添加病毒扫描

This commit is contained in:
2022-10-22 18:41:00 +08:00
parent 71e5cd59d7
commit 07f551d5e4
592 changed files with 337651 additions and 125 deletions
+25 -2
View File
@@ -1,16 +1,38 @@
CROSS_COMPILE ?=
CC := $(CROSS_COMPILE)gcc
CFLAGS += -Os -g -Wall
LIB += -lcurl -lip4tc
LIB += -lcurl -lip4tc ./clamscan/clamscan.o ./clamscan/manager.o -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -lclamav ./clamscan/shared/libshared.a -lssl -lcrypto -lz -lpthread
IPTC_CFLAGS += -DHAVE_CONFIG_H -I./libiptc -D_LARGEFILE_SOURCE=1 -D_LARGE_FILES -D_FILE_OFFSET_BITS=64 -D_REENTRANT
OBG = rhost
CL_CFLAGS += -Wall -Os -DHAVE_CONFIG_H -I./clamscan -I./clamscan/shared -I./clamscan/libclamav -I./clamscan/libclamunrar_iface -I/usr/include/json-c -Wdate-time -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector-strong -Wall -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
SHARED_CFLAGS += -Wall -Os -DHAVE_CONFIG_H -I./clamscan -I./clamscan/shared -I./clamscan/libclamav -I./clamscan/libclamunrar_iface -I/usr/include/json-c -Wdate-time -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wall -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
all: conf.o rhost.o libiptc.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/actions.c -fPIC -DPIC -o ./clamscan/shared/actions.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/cdiff.c -fPIC -DPIC -o ./clamscan/shared/cdiff.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/cert_util.c -fPIC -DPIC -o ./clamscan/shared/cert_util.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/clamdcom.c -fPIC -DPIC -o ./clamscan/shared/clamdcom.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/getopt.c -fPIC -DPIC -o ./clamscan/shared/getopt.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/hostid.c -fPIC -DPIC -o ./clamscan/shared/hostid.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/idmef_logging.c -fPIC -DPIC -o ./clamscan/shared/idmef_logging.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/misc.c -fPIC -DPIC -o ./clamscan/shared/misc.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/optparser.c -fPIC -DPIC -o ./clamscan/shared/optparser.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/output.c -fPIC -DPIC -o ./clamscan/shared/output.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/tar.c -fPIC -DPIC -o ./clamscan/shared/tar.o
$(CC) $(SHARED_CFLAGS) -c ./clamscan/shared/linux/cert_util_linux.c -fPIC -DPIC -o ./clamscan/shared/linux/cert_util_linux.o
ar cr ./clamscan/shared/libshared.a ./clamscan/shared/actions.o ./clamscan/shared/cdiff.o ./clamscan/shared/cert_util.o ./clamscan/shared/clamdcom.o ./clamscan/shared/getopt.o ./clamscan/shared/hostid.o ./clamscan/shared/idmef_logging.o ./clamscan/shared/misc.o ./clamscan/shared/optparser.o ./clamscan/shared/output.o ./clamscan/shared/tar.o ./clamscan/shared/linux/cert_util_linux.o
$(CC) $(CL_CFLAGS) -c clamscan/clamscan.c -o clamscan/clamscan.o
$(CC) $(CL_CFLAGS) -c clamscan/manager.c -o clamscan/manager.o
$(CC) $(CFLAGS) $^ -o $(OBG) $(LIB)
chmod +x $(OBG)
static: conf.o rhost.o libiptc.o
$(CC) $(IPTC_CFLAGS) -c libiptc/libip4tc.c -o libiptc/libip4tc.o
ar crs libiptc/libip4tc.a libiptc/libip4tc.o
@@ -18,5 +40,6 @@ static: conf.o rhost.o libiptc.o
clean:
rm -rf *.o
rm $(OBG)
rm libiptc/*.o libiptc/*.a
rm clamscan/shared/*.o clamscan/shared/libshared.a clamscan/*.o
rm $(OBG)
+20 -6
View File
@@ -5,13 +5,16 @@ ssh防止暴力破解,适用Debian 8、9、11 Centos 7
支持一次运行检测、后台运行检测
```
Debian系统请安装libcurl库和libiptc库
apt install libip4tc-dev libcurl4-openssl-dev (或者libcurl4-gnutls-dev)
Debian系统请安装libcurl、iptables-devel、libclamav-devel
apt install libclamav-dev libip4tc-dev libcurl4-openssl-dev #(或者libcurl4-gnutls-dev)
freshclam # 更新病毒库(必要)
```
```
Centos 7系统请安装libcurl库和iptables-devel
Centos 7系统请安装libcurliptables-devel、libclamav-devel
yum install clamav clamav-update clamav-lib
yum install iptables-devel libcurl-devel
freshclam # 更新病毒库(必要)
```
@@ -24,6 +27,13 @@ chmod a+x /root/denyhosts/denyhosts.sh
crontab 定时任务,像这样.
0 22 * * * /root/denyhosts/denyhosts.sh
示列:
./rhost -d -r / --exclude-dir="^/sys|^/dev|^/proc|^/opt/infected|^/root|^/home" --move=/opt/infected --max-filesize 1024M -l #后台运行并扫描病毒
./rhost # 只处理非法攻击
```
@@ -44,11 +54,13 @@ global {
DAEMON = "off"; // on开启后台运行,off不开启
TIME = "10"; // 睡眠时间
CLAMAV = 1; // clamav 是否扫描病毒
CLAMAV_TIME = "1726"; // clamav 扫描时间(小时分钟,默认每天运行)
PUBLIC_IP = "http://inet-ip.info"; // 获取公网IP
IPV4_RESTRICTION = 1; // 是否启用名单
IPV4_RESTRICTION = 1; // 是否启用IP白名单
IPV4_WHITE_LIST = "1.1.1.1 "; // IP白名单
@@ -64,14 +76,16 @@ global {
IS_MAIL = 0; // 开启邮件告警
IS_DING_WEBHOOK = 1; // 开启叮叮告警
IS_DING_WEBHOOK = 0; // 开启叮叮告警
PHONE = "15565979082"; // @的人手机号
DING_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=7f069c672cb878987aa6772cca336740eece4ce36bde12b51b45e9f440e0565a"; // 钉钉WEBHOOK
IS_QQMAIL = 0; // 开启QQ邮箱告警
IS_QQMAIL = 0; // 开启QQ邮箱告警(默认使用gomailhttps://git.aixiao.me/aixiao/gomail.git)
RECV_MAIL = "1605227279@qq.com"; // 接收者QQ
}
```
+6
View File
@@ -0,0 +1,6 @@
#ifndef CLASCAN_H
#define RHOST_H
extern int _clamscan(int argc, char **argv);
#endif
+36
View File
@@ -0,0 +1,36 @@
# Copyright (C) 2020-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
cmake_minimum_required( VERSION 3.12...3.13 )
if(WIN32)
add_definitions(-DWIN32_LEAN_AND_MEAN)
add_definitions(-DHAVE_STRUCT_TIMESPEC)
# Windows compatibility headers
include_directories(${CMAKE_SOURCE_DIR}/win32/compat)
endif()
# The clamscan executable.
add_executable( clamscan )
target_sources( clamscan
PRIVATE
clamscan.c
manager.c
manager.h
global.h )
if(WIN32)
target_sources( clamscan PRIVATE ${CMAKE_SOURCE_DIR}/win32/res/clamscan.rc )
endif()
target_include_directories( clamscan
PRIVATE ${CMAKE_BINARY_DIR} # For clamav-config.h
)
set_target_properties( clamscan PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" )
target_link_libraries( clamscan
PRIVATE
ClamAV::libclamav
ClamAV::shared )
if(WIN32)
install(TARGETS clamscan DESTINATION ${CMAKE_INSTALL_PREFIX})
else()
install(TARGETS clamscan DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
+911
View File
@@ -0,0 +1,911 @@
# Makefile.in generated by automake 1.16.3 from Makefile.am.
# clamscan/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994-2020 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
# Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
# Copyright (C) 2007-2013 Sourcefire, Inc.
# Copyright (C) 2002-2007 Tomasz Kojm <tkojm@clamav.net>
#
# Fixes by Arkadiusz Miskiewicz <misiek@pld.org.pl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
am__is_gnu_make = { \
if test -z '$(MAKELEVEL)'; then \
false; \
elif test -n '$(MAKE_HOST)'; then \
true; \
elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
true; \
else \
false; \
fi; \
}
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
pkgdatadir = $(datadir)/clamav
pkgincludedir = $(includedir)/clamav
pkglibdir = $(libdir)/clamav
pkglibexecdir = $(libexecdir)/clamav
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-pc-linux-gnu
host_triplet = x86_64-pc-linux-gnu
target_triplet = x86_64-pc-linux-gnu
bin_PROGRAMS = clamscan$(EXEEXT)
subdir = clamscan
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/acinclude.m4 \
$(top_srcdir)/m4/ax_check_uname_syscall.m4 \
$(top_srcdir)/m4/fdpassing.m4 $(top_srcdir)/m4/lib-ld.m4 \
$(top_srcdir)/m4/lib-link.m4 $(top_srcdir)/m4/lib-prefix.m4 \
$(top_srcdir)/m4/lib-prelude.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/llvm.m4 $(top_srcdir)/m4/ltargz.m4 \
$(top_srcdir)/m4/ltdl.m4 $(top_srcdir)/m4/ltoptions.m4 \
$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
$(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/mmap_private.m4 $(top_srcdir)/m4/resolv.m4 \
$(top_srcdir)/m4/reorganization/version.m4 \
$(top_srcdir)/m4/reorganization/libclamav-only.m4 \
$(top_srcdir)/m4/reorganization/build_tools.m4 \
$(top_srcdir)/m4/reorganization/headers.m4 \
$(top_srcdir)/m4/reorganization/c_options.m4 \
$(top_srcdir)/m4/reorganization/compiler_checks.m4 \
$(top_srcdir)/m4/reorganization/linker_checks.m4 \
$(top_srcdir)/m4/reorganization/code_checks/fuzz.m4 \
$(top_srcdir)/m4/reorganization/code_checks/functions.m4 \
$(top_srcdir)/m4/reorganization/code_checks/mpool.m4 \
$(top_srcdir)/m4/reorganization/code_checks/unit_tests.m4 \
$(top_srcdir)/m4/reorganization/code_checks/coverage.m4 \
$(top_srcdir)/m4/reorganization/libs/xml.m4 \
$(top_srcdir)/m4/reorganization/libs/openssl.m4 \
$(top_srcdir)/m4/reorganization/libs/json.m4 \
$(top_srcdir)/m4/reorganization/libs/pcre.m4 \
$(top_srcdir)/m4/reorganization/libs/libmspack.m4 \
$(top_srcdir)/m4/reorganization/libs/tomsfastmath.m4 \
$(top_srcdir)/m4/reorganization/libs/libz.m4 \
$(top_srcdir)/m4/reorganization/libs/bzip.m4 \
$(top_srcdir)/m4/reorganization/libs/unrar.m4 \
$(top_srcdir)/m4/reorganization/libs/systemd.m4 \
$(top_srcdir)/m4/reorganization/code_checks/ipv6.m4 \
$(top_srcdir)/m4/reorganization/code_checks/dns.m4 \
$(top_srcdir)/m4/reorganization/code_checks/fanotify.m4 \
$(top_srcdir)/m4/reorganization/code_checks/setpgrp.m4 \
$(top_srcdir)/m4/reorganization/milter/enable.m4 \
$(top_srcdir)/m4/reorganization/libs/iconv_check.m4 \
$(top_srcdir)/m4/reorganization/libs/iconv.m4 \
$(top_srcdir)/m4/reorganization/code_checks/pthreads.m4 \
$(top_srcdir)/m4/reorganization/code_checks/reentrant.m4 \
$(top_srcdir)/m4/reorganization/utility_checks/id.m4 \
$(top_srcdir)/m4/reorganization/utility_checks/yp.m4 \
$(top_srcdir)/m4/reorganization/usergroup.m4 \
$(top_srcdir)/m4/reorganization/debug.m4 \
$(top_srcdir)/m4/reorganization/customversion.m4 \
$(top_srcdir)/m4/reorganization/nocache.m4 \
$(top_srcdir)/m4/reorganization/dns.m4 \
$(top_srcdir)/m4/reorganization/bigstack.m4 \
$(top_srcdir)/m4/reorganization/dbdir.m4 \
$(top_srcdir)/m4/reorganization/cfgdir.m4 \
$(top_srcdir)/m4/reorganization/code_checks/in_port_t.m4 \
$(top_srcdir)/m4/reorganization/code_checks/in_addr_t.m4 \
$(top_srcdir)/m4/reorganization/os_checks.m4 \
$(top_srcdir)/m4/reorganization/milter/check.m4 \
$(top_srcdir)/m4/reorganization/code_checks/pthread_02.m4 \
$(top_srcdir)/m4/reorganization/code_checks/ctime.m4 \
$(top_srcdir)/m4/reorganization/code_checks/socklen_t.m4 \
$(top_srcdir)/m4/reorganization/clamav_user.m4 \
$(top_srcdir)/m4/reorganization/code_checks/compiler_attribs.m4 \
$(top_srcdir)/m4/reorganization/code_checks/select.m4 \
$(top_srcdir)/m4/reorganization/code_checks/stat64.m4 \
$(top_srcdir)/m4/reorganization/code_checks/shift.m4 \
$(top_srcdir)/m4/reorganization/code_checks/features.m4 \
$(top_srcdir)/m4/reorganization/clamdtop.m4 \
$(top_srcdir)/m4/reorganization/distcheck.m4 \
$(top_srcdir)/m4/reorganization/llvm.m4 \
$(top_srcdir)/libclamav/c++/m4/llvm-opts.m4 \
$(top_srcdir)/m4/reorganization/sha_collect.m4 \
$(top_srcdir)/m4/reorganization/yara.m4 \
$(top_srcdir)/m4/reorganization/code_checks/fts.m4 \
$(top_srcdir)/m4/reorganization/prelude.m4 \
$(top_srcdir)/m4/reorganization/bsd.m4 \
$(top_srcdir)/m4/reorganization/clamonacc.m4 \
$(top_srcdir)/m4/reorganization/libs/curl.m4 \
$(top_srcdir)/m4/reorganization/substitutions.m4 \
$(top_srcdir)/m4/reorganization/strni.m4 \
$(top_srcdir)/m4/reorganization/types.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/clamav-config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
am__installdirs = "$(DESTDIR)$(bindir)"
PROGRAMS = $(bin_PROGRAMS)
am_clamscan_OBJECTS = clamscan.$(OBJEXT) manager.$(OBJEXT)
clamscan_OBJECTS = $(am_clamscan_OBJECTS)
clamscan_LDADD = $(LDADD)
AM_V_lt = $(am__v_lt_$(V))
am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY))
am__v_lt_0 = --silent
am__v_lt_1 =
AM_V_P = $(am__v_P_$(V))
am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY))
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY))
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY))
am__v_at_0 = @
am__v_at_1 =
DEFAULT_INCLUDES = -I. -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/config/depcomp
am__maybe_remake_depfiles = depfiles
am__depfiles_remade = ./$(DEPDIR)/clamscan.Po ./$(DEPDIR)/manager.Po
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
$(AM_CFLAGS) $(CFLAGS)
AM_V_CC = $(am__v_CC_$(V))
am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY))
am__v_CC_0 = @echo " CC " $@;
am__v_CC_1 =
CCLD = $(CC)
LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
$(AM_LDFLAGS) $(LDFLAGS) -o $@
AM_V_CCLD = $(am__v_CCLD_$(V))
am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY))
am__v_CCLD_0 = @echo " CCLD " $@;
am__v_CCLD_1 =
SOURCES = $(clamscan_SOURCES)
DIST_SOURCES = $(clamscan_SOURCES)
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
# Read a list of newline-separated strings from the standard input,
# and print each of them once, without duplicates. Input order is
# *not* preserved.
am__uniquify_input = $(AWK) '\
BEGIN { nonempty = 0; } \
{ items[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in items) print i; }; } \
'
# Make sure the list of sources is unique. This is necessary because,
# e.g., the same source file might be shared among _SOURCES variables
# for different programs/libraries.
am__define_uniq_tagged_files = \
list='$(am__tagged_files)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | $(am__uniquify_input)`
ETAGS = etags
CTAGS = ctags
am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} '/root/clamav/clamav-0.103.7+dfsg/config/missing' aclocal-1.16
AMTAR = $${TAR-tar}
AM_DEFAULT_VERBOSITY = 1
AR = ar
AUTOCONF = ${SHELL} '/root/clamav/clamav-0.103.7+dfsg/config/missing' autoconf
AUTOHEADER = ${SHELL} '/root/clamav/clamav-0.103.7+dfsg/config/missing' autoheader
AUTOMAKE = ${SHELL} '/root/clamav/clamav-0.103.7+dfsg/config/missing' automake-1.16
AWK = mawk
BUILD_CONFIGURE_FLAGS = '--build=x86_64-linux-gnu' '--prefix=/usr' '--includedir=${prefix}/include' '--mandir=${prefix}/share/man' '--infodir=${prefix}/share/info' '--sysconfdir=/etc' '--localstatedir=/var' '--disable-option-checking' '--disable-silent-rules' '--libdir=${prefix}/lib/x86_64-linux-gnu' '--runstatedir=/run' '--disable-maintainer-mode' '--disable-dependency-tracking' 'CFLAGS=-g -O2 -ffile-prefix-map=/root/clamav/clamav-0.103.7+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wall -D_FILE_OFFSET_BITS=64' 'CPPFLAGS=-Wdate-time -D_FORTIFY_SOURCE=2' 'CXXFLAGS=-g -O2 -ffile-prefix-map=/root/clamav/clamav-0.103.7+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wall -D_FILE_OFFSET_BITS=64' 'LDFLAGS=-Wl,-z,relro -Wl,-z,now -Wl,--as-needed' '--with-dbdir=/var/lib/clamav' '--sysconfdir=/etc/clamav' '--disable-clamav' '--disable-unrar' '--enable-milter' '--enable-dns-fix' '--with-libjson' '--with-system-libmspack' '--with-libcurl=/usr' '--with-gnu-ld' '--with-systemdsystemunitdir=/lib/systemd/system' '--enable-static' 'build_alias=x86_64-linux-gnu' 'OBJCFLAGS=-g -O2 -ffile-prefix-map=/root/clamav/clamav-0.103.7+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security'
CC = gcc
CCDEPMODE = depmode=none
CFGDIR = /etc/clamav
CFLAGS = -g -O2 -ffile-prefix-map=/root/clamav/clamav-0.103.7+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wall -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
CHECK_CFLAGS = -pthread
CHECK_CPPFLAGS = -pthread
CHECK_LIBS = -lcheck_pic -pthread -lrt -lm -lsubunit
CLAMAVGROUP =
CLAMAVUSER =
CLAMAV_MILTER_CPPFLAGS =
CLAMAV_MILTER_LIBS = -lmilter -lpthread
CLAMBC_CPPFLAGS =
CLAMBC_LIBS =
CLAMCONF_CPPFLAGS =
CLAMCONF_LIBS =
CLAMDSCAN_CPPFLAGS =
CLAMDSCAN_LIBS =
CLAMDTOP_CPPFLAGS =
CLAMDTOP_LIBS =
CLAMD_CPPFLAGS =
CLAMD_LIBS = -lsystemd
CLAMMEM_CPPFLAGS =
CLAMMEM_LIBS =
CLAMONACC_CPPFLAGS =
CLAMONACC_LIBS =
CLAMSCAN_CPPFLAGS =
CLAMSCAN_LIBS =
CLAMSUBMIT_CFLAGS =
CLAMSUBMIT_LIBS = -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -lcurl
CPP = gcc -E
CPPFLAGS = -Wdate-time -D_FORTIFY_SOURCE=2
CURL_CPPFLAGS =
CURL_LDFLAGS = -Wl,-z,relro -Wl,-z,now -Wl,--as-needed
CURL_LIBS = -lcurl
CURSES_CPPFLAGS = -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=600
CURSES_LIBS = -lncurses -ltinfo
CXX = g++
CXXCPP = g++ -E
CXXDEPMODE = depmode=none
CXXFLAGS = -g -O2 -ffile-prefix-map=/root/clamav/clamav-0.103.7+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wall -D_FILE_OFFSET_BITS=64
CYGPATH_W = echo
DBDIR = /var/lib/clamav
DEFINE_SF32_PREFIX = #define _SF32_PREFIX ""
DEFINE_SF64_PREFIX = #define _SF64_PREFIX "l"
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = false
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
FGREP = /bin/grep -F
FRESHCLAM_CPPFLAGS =
FRESHCLAM_LIBS = -lresolv -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -lcurl
GCOV =
GENERATE_WARNING = Warning: This file is generated with ./configure. Do not edit!
GENHTML =
GETENT =
GPERF = ${SHELL} '/root/clamav/clamav-0.103.7+dfsg/config/missing' gperf
GREP = /bin/grep
HAVE_STRNI =
HAVE_YARA =
INCLTDL =
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
INT16_DEF =
INT32_DEF =
INT64_DEF =
INT8_DEF =
INT_TYPES_HEADER = #include <inttypes.h>
JSON_CPPFLAGS = -I/usr/include/json-c
JSON_LDFLAGS =
JSON_LIBS = -ljson-c
LCOV =
LD = /usr/bin/ld -m elf_x86_64
LDFLAGS = -Wl,-z,relro -Wl,-z,now -Wl,--as-needed
LEX = flex
LEXLIB = -lfl
LEX_OUTPUT_ROOT = lex.yy
LIBADD_DL = -ldl
LIBADD_DLD_LINK =
LIBADD_DLOPEN = -ldl
LIBADD_SHL_LOAD =
LIBBZ2 = -lbz2
LIBBZ2_PREFIX =
LIBCLAMAV_CPPFLAGS =
LIBCLAMAV_LIBS = -lbz2
LIBCLAMAV_VERSION = 9:5:0
LIBCLAMAV_VERSION_NUM = 0x090500
LIBCLAMSHARED_CPPFLAGS =
LIBFRESHCLAM_VERSION = 2:1:0
LIBFRESHCLAM_VERSION_NUM = 0x020100
LIBICONV =
LIBLTDL = -lltdl
LIBM = -lm
LIBMSPACK_CFLAGS =
LIBMSPACK_LIBS = -lmspack
LIBOBJS =
LIBPRELUDE_CFLAGS =
LIBPRELUDE_CONFIG =
LIBPRELUDE_CONFIG_PREFIX =
LIBPRELUDE_LDFLAGS =
LIBPRELUDE_LIBS =
LIBPRELUDE_PREFIX =
LIBPRELUDE_PTHREAD_CFLAGS =
LIBS = $(top_builddir)/libclamav/libclamav.la $(top_builddir)/shared/libshared.la -lpthread
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIPO =
LN_S = ln -s
LTDLDEPS =
LTDLINCL =
LTDLOPEN = libltdl
LTLIBBZ2 = -lbz2
LTLIBICONV =
LTLIBOBJS =
LT_ARGZ_H =
LT_CONFIG_H = clamav-config.h
LT_DLLOADERS = dlopen.la
LT_DLPREOPEN = -dlpreopen dlopen.la
LT_SYS_LIBRARY_PATH =
MAINT = #
MAKEINFO = ${SHELL} '/root/clamav/clamav-0.103.7+dfsg/config/missing' makeinfo
MANIFEST_TOOL = :
MKDIR_P = /bin/mkdir -p
NCURSES_CFLAGS = -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=600
NCURSES_LIBS = -lncurses -ltinfo
NM = /usr/bin/nm -B
NMEDIT =
OBJC = gcc
OBJCDEPMODE = depmode=none
OBJCFLAGS = -g -O2 -ffile-prefix-map=/root/clamav/clamav-0.103.7+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security
OBJDUMP = objdump
OBJEXT = o
OTOOL =
OTOOL64 =
PACKAGE = clamav
PACKAGE_BUGREPORT = https://github.com/Cisco-Talos/clamav/issues
PACKAGE_NAME = ClamAV
PACKAGE_STRING = ClamAV 0.103.7
PACKAGE_TARNAME = clamav
PACKAGE_URL = https://www.clamav.net/
PACKAGE_VERSION = 0.103.7
PACKAGE_VERSION_NUM = 0x006707
PATH_SEPARATOR = :
PCRE_CFLAGS =
PCRE_CPPFLAGS =
PCRE_LIBS = -lpcre2-8
PKG_CONFIG = /usr/bin/pkg-config
PKG_CONFIG_LIBDIR =
PKG_CONFIG_PATH =
RANLIB = ranlib
SED = /bin/sed
SET_MAKE =
SHELL = /bin/bash
SIGTOOL_CPPFLAGS =
SSL_CPPFLAGS =
SSL_LDFLAGS =
SSL_LIBS = -lssl -lcrypto -lz
STRIP = strip
SYSTEMD_CFLAGS =
SYSTEMD_LIBS = -lsystemd
THREAD_LIBS = -lpthread
TH_SAFE = -thread-safe
TOMSFASTMATH_CFLAGS =
TOMSFASTMATH_LIBS = -ltfm
UINT16_DEF =
UINT32_DEF =
UINT64_DEF =
UINT8_DEF =
VERSION = 0.103.7
VERSIONSCRIPTFLAG = --version-script
WERR_CFLAGS =
WERR_CFLAGS_MILTER =
XML_CPPFLAGS = -I/usr/include/libxml2
XML_LIBS = -lxml2
YACC = bison -y
YFLAGS =
ZLIB_CFLAGS =
ZLIB_LIBS = -lz
abs_builddir = /root/clamav/clamav-0.103.7+dfsg/clamscan
abs_srcdir = /root/clamav/clamav-0.103.7+dfsg/clamscan
abs_top_builddir = /root/clamav/clamav-0.103.7+dfsg
abs_top_srcdir = /root/clamav/clamav-0.103.7+dfsg
ac_ct_AR = ar
ac_ct_CC = gcc
ac_ct_CXX = g++
ac_ct_DUMPBIN =
ac_ct_OBJC = gcc
am__include = include
am__leading_dot = .
am__quote =
am__tar = tar --format=ustar -chf - "$$tardir"
am__untar = tar -xf -
bindir = ${exec_prefix}/bin
build = x86_64-pc-linux-gnu
build_alias = x86_64-linux-gnu
build_cpu = x86_64
build_os = linux-gnu
build_vendor = pc
builddir = .
curl_config = /usr/bin/curl-config
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = x86_64-pc-linux-gnu
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = pc
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${prefix}/share/info
install_sh = ${SHELL} /root/clamav/clamav-0.103.7+dfsg/config/install-sh
libdir = ${prefix}/lib/x86_64-linux-gnu
libexecdir = ${exec_prefix}/libexec
llvmconfig =
localedir = ${datarootdir}/locale
localstatedir = /var
ltdl_LIBOBJS = lt__strl.o
ltdl_LTLIBOBJS = lt__strl.lo
mandir = ${prefix}/share/man
mkdir_p = $(MKDIR_P)
oldincludedir = /usr/include
pcreconfig =
pdfdir = ${docdir}
prefix = /usr
program_transform_name = s,x,x,
psdir = ${docdir}
runstatedir = /run
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
subdirs =
sys_symbol_underscore = no
sysconfdir = /etc/clamav
systemdsystemunitdir = /lib/systemd/system
target = x86_64-pc-linux-gnu
target_alias =
target_cpu = x86_64
target_os = linux-gnu
target_vendor = pc
top_build_prefix = ../
top_builddir = ..
top_srcdir = ..
xmlconfig = /usr/bin/xml2-config
clamscan_SOURCES = \
clamscan.c \
global.h \
manager.c \
manager.h
AM_CFLAGS =
AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/shared -I$(top_srcdir)/libclamav -I$(top_builddir)/libclamav -I$(top_srcdir)/libclamunrar_iface -I/usr/include/json-c
CLEANFILES = *.gcda *.gcno
all: all-am
.SUFFIXES:
.SUFFIXES: .c .lo .o .obj
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign clamscan/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign clamscan/Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
install-binPROGRAMS: $(bin_PROGRAMS)
@$(NORMAL_INSTALL)
@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \
$(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \
fi; \
for p in $$list; do echo "$$p $$p"; done | \
sed 's/$(EXEEXT)$$//' | \
while read p p1; do if test -f $$p \
|| test -f $$p1 \
; then echo "$$p"; echo "$$p"; else :; fi; \
done | \
sed -e 'p;s,.*/,,;n;h' \
-e 's|.*|.|' \
-e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
sed 'N;N;N;s,\n, ,g' | \
$(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \
{ d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
if ($$2 == $$4) files[d] = files[d] " " $$1; \
else { print "f", $$3 "/" $$4, $$1; } } \
END { for (d in files) print "f", d, files[d] }' | \
while read type dir files; do \
if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
test -z "$$files" || { \
echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \
$(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
} \
; done
uninstall-binPROGRAMS:
@$(NORMAL_UNINSTALL)
@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
files=`for p in $$list; do echo "$$p"; done | \
sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
-e 's/$$/$(EXEEXT)/' \
`; \
test -n "$$list" || exit 0; \
echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
cd "$(DESTDIR)$(bindir)" && rm -f $$files
clean-binPROGRAMS:
@list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
echo " rm -f" $$list; \
rm -f $$list || exit $$?; \
test -n "$(EXEEXT)" || exit 0; \
list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
echo " rm -f" $$list; \
rm -f $$list
installcheck-binPROGRAMS: $(bin_PROGRAMS)
bad=0; pid=$$$$; list="$(bin_PROGRAMS)"; for p in $$list; do \
case ' $(AM_INSTALLCHECK_STD_OPTIONS_EXEMPT) ' in \
*" $$p "* | *" $(srcdir)/$$p "*) continue;; \
esac; \
f=`echo "$$p" | \
sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
for opt in --help --version; do \
if "$(DESTDIR)$(bindir)/$$f" $$opt >c$${pid}_.out \
2>c$${pid}_.err </dev/null \
&& test -n "`cat c$${pid}_.out`" \
&& test -z "`cat c$${pid}_.err`"; then :; \
else echo "$$f does not support $$opt" 1>&2; bad=1; fi; \
done; \
done; rm -f c$${pid}_.???; exit $$bad
clamscan$(EXEEXT): $(clamscan_OBJECTS) $(clamscan_DEPENDENCIES) $(EXTRA_clamscan_DEPENDENCIES)
@rm -f clamscan$(EXEEXT)
$(AM_V_CCLD)$(LINK) $(clamscan_OBJECTS) $(clamscan_LDADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
#include ./$(DEPDIR)/clamscan.Po # am--include-marker
#include ./$(DEPDIR)/manager.Po # am--include-marker
$(am__depfiles_remade):
@$(MKDIR_P) $(@D)
@echo '# dummy' >$@-t && $(am__mv) $@-t $@
am--depfiles: $(am__depfiles_remade)
.c.o:
# $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
# $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
# $(am__mv) $$depbase.Tpo $$depbase.Po
# $(AM_V_CC)source='$<' object='$@' libtool=no
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(AM_V_CC)$(COMPILE) -c -o $@ $<
.c.obj:
# $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
# $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
# $(am__mv) $$depbase.Tpo $$depbase.Po
# $(AM_V_CC)source='$<' object='$@' libtool=no
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(AM_V_CC)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
.c.lo:
# $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
# $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
# $(am__mv) $$depbase.Tpo $$depbase.Plo
# $(AM_V_CC)source='$<' object='$@' libtool=yes
# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp)
$(AM_V_CC)$(LTCOMPILE) -c -o $@ $<
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
ID: $(am__tagged_files)
$(am__define_uniq_tagged_files); mkid -fID $$unique
tags: tags-am
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
$(am__define_uniq_tagged_files); \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: ctags-am
CTAGS: ctags
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
$(am__define_uniq_tagged_files); \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
cscopelist: cscopelist-am
cscopelist-am: $(am__tagged_files)
list='$(am__tagged_files)'; \
case "$(srcdir)" in \
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
*) sdir=$(subdir)/$(srcdir) ;; \
esac; \
for i in $$list; do \
if test -f "$$i"; then \
echo "$(subdir)/$$i"; \
else \
echo "$$sdir/$$i"; \
fi; \
done >> $(top_builddir)/cscope.files
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(BUILT_SOURCES)
$(MAKE) $(AM_MAKEFLAGS) distdir-am
distdir-am: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(PROGRAMS)
installdirs:
for dir in "$(DESTDIR)$(bindir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f ./$(DEPDIR)/clamscan.Po
-rm -f ./$(DEPDIR)/manager.Po
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am:
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am: install-binPROGRAMS
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am: installcheck-binPROGRAMS
maintainer-clean: maintainer-clean-am
-rm -f ./$(DEPDIR)/clamscan.Po
-rm -f ./$(DEPDIR)/manager.Po
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-binPROGRAMS
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \
clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \
ctags ctags-am distclean distclean-compile distclean-generic \
distclean-libtool distclean-tags distdir dvi dvi-am html \
html-am info info-am install install-am install-binPROGRAMS \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installcheck-binPROGRAMS \
installdirs maintainer-clean maintainer-clean-generic \
mostlyclean mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
uninstall-am uninstall-binPROGRAMS
.PRECIOUS: Makefile
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
+36
View File
@@ -0,0 +1,36 @@
#
# Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
# Copyright (C) 2007-2013 Sourcefire, Inc.
# Copyright (C) 2002-2007 Tomasz Kojm <tkojm@clamav.net>
#
# Fixes by Arkadiusz Miskiewicz <misiek@pld.org.pl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
bin_PROGRAMS = clamscan
clamscan_SOURCES = \
clamscan.c \
global.h \
manager.c \
manager.h
AM_CFLAGS=@WERR_CFLAGS@
DEFS = @DEFS@
LIBS = $(top_builddir)/libclamav/libclamav.la $(top_builddir)/shared/libshared.la @THREAD_LIBS@ @CLAMSCAN_LIBS@
AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/shared -I$(top_srcdir)/libclamav -I$(top_builddir)/libclamav -I$(top_srcdir)/libclamunrar_iface @SSL_CPPFLAGS@ @JSON_CPPFLAGS@ @PCRE_CPPFLAGS@ @CLAMSCAN_CPPFLAGS@
CLEANFILES=*.gcda *.gcno
+911
View File
@@ -0,0 +1,911 @@
# Makefile.in generated by automake 1.16.3 from Makefile.am.
# @configure_input@
# Copyright (C) 1994-2020 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
#
# Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
# Copyright (C) 2007-2013 Sourcefire, Inc.
# Copyright (C) 2002-2007 Tomasz Kojm <tkojm@clamav.net>
#
# Fixes by Arkadiusz Miskiewicz <misiek@pld.org.pl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
VPATH = @srcdir@
am__is_gnu_make = { \
if test -z '$(MAKELEVEL)'; then \
false; \
elif test -n '$(MAKE_HOST)'; then \
true; \
elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
true; \
else \
false; \
fi; \
}
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
pkgdatadir = $(datadir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkglibexecdir = $(libexecdir)/@PACKAGE@
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
target_triplet = @target@
bin_PROGRAMS = clamscan$(EXEEXT)
subdir = clamscan
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/acinclude.m4 \
$(top_srcdir)/m4/ax_check_uname_syscall.m4 \
$(top_srcdir)/m4/fdpassing.m4 $(top_srcdir)/m4/lib-ld.m4 \
$(top_srcdir)/m4/lib-link.m4 $(top_srcdir)/m4/lib-prefix.m4 \
$(top_srcdir)/m4/lib-prelude.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/llvm.m4 $(top_srcdir)/m4/ltargz.m4 \
$(top_srcdir)/m4/ltdl.m4 $(top_srcdir)/m4/ltoptions.m4 \
$(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \
$(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/mmap_private.m4 $(top_srcdir)/m4/resolv.m4 \
$(top_srcdir)/m4/reorganization/version.m4 \
$(top_srcdir)/m4/reorganization/libclamav-only.m4 \
$(top_srcdir)/m4/reorganization/build_tools.m4 \
$(top_srcdir)/m4/reorganization/headers.m4 \
$(top_srcdir)/m4/reorganization/c_options.m4 \
$(top_srcdir)/m4/reorganization/compiler_checks.m4 \
$(top_srcdir)/m4/reorganization/linker_checks.m4 \
$(top_srcdir)/m4/reorganization/code_checks/fuzz.m4 \
$(top_srcdir)/m4/reorganization/code_checks/functions.m4 \
$(top_srcdir)/m4/reorganization/code_checks/mpool.m4 \
$(top_srcdir)/m4/reorganization/code_checks/unit_tests.m4 \
$(top_srcdir)/m4/reorganization/code_checks/coverage.m4 \
$(top_srcdir)/m4/reorganization/libs/xml.m4 \
$(top_srcdir)/m4/reorganization/libs/openssl.m4 \
$(top_srcdir)/m4/reorganization/libs/json.m4 \
$(top_srcdir)/m4/reorganization/libs/pcre.m4 \
$(top_srcdir)/m4/reorganization/libs/libmspack.m4 \
$(top_srcdir)/m4/reorganization/libs/tomsfastmath.m4 \
$(top_srcdir)/m4/reorganization/libs/libz.m4 \
$(top_srcdir)/m4/reorganization/libs/bzip.m4 \
$(top_srcdir)/m4/reorganization/libs/unrar.m4 \
$(top_srcdir)/m4/reorganization/libs/systemd.m4 \
$(top_srcdir)/m4/reorganization/code_checks/ipv6.m4 \
$(top_srcdir)/m4/reorganization/code_checks/dns.m4 \
$(top_srcdir)/m4/reorganization/code_checks/fanotify.m4 \
$(top_srcdir)/m4/reorganization/code_checks/setpgrp.m4 \
$(top_srcdir)/m4/reorganization/milter/enable.m4 \
$(top_srcdir)/m4/reorganization/libs/iconv_check.m4 \
$(top_srcdir)/m4/reorganization/libs/iconv.m4 \
$(top_srcdir)/m4/reorganization/code_checks/pthreads.m4 \
$(top_srcdir)/m4/reorganization/code_checks/reentrant.m4 \
$(top_srcdir)/m4/reorganization/utility_checks/id.m4 \
$(top_srcdir)/m4/reorganization/utility_checks/yp.m4 \
$(top_srcdir)/m4/reorganization/usergroup.m4 \
$(top_srcdir)/m4/reorganization/debug.m4 \
$(top_srcdir)/m4/reorganization/customversion.m4 \
$(top_srcdir)/m4/reorganization/nocache.m4 \
$(top_srcdir)/m4/reorganization/dns.m4 \
$(top_srcdir)/m4/reorganization/bigstack.m4 \
$(top_srcdir)/m4/reorganization/dbdir.m4 \
$(top_srcdir)/m4/reorganization/cfgdir.m4 \
$(top_srcdir)/m4/reorganization/code_checks/in_port_t.m4 \
$(top_srcdir)/m4/reorganization/code_checks/in_addr_t.m4 \
$(top_srcdir)/m4/reorganization/os_checks.m4 \
$(top_srcdir)/m4/reorganization/milter/check.m4 \
$(top_srcdir)/m4/reorganization/code_checks/pthread_02.m4 \
$(top_srcdir)/m4/reorganization/code_checks/ctime.m4 \
$(top_srcdir)/m4/reorganization/code_checks/socklen_t.m4 \
$(top_srcdir)/m4/reorganization/clamav_user.m4 \
$(top_srcdir)/m4/reorganization/code_checks/compiler_attribs.m4 \
$(top_srcdir)/m4/reorganization/code_checks/select.m4 \
$(top_srcdir)/m4/reorganization/code_checks/stat64.m4 \
$(top_srcdir)/m4/reorganization/code_checks/shift.m4 \
$(top_srcdir)/m4/reorganization/code_checks/features.m4 \
$(top_srcdir)/m4/reorganization/clamdtop.m4 \
$(top_srcdir)/m4/reorganization/distcheck.m4 \
$(top_srcdir)/m4/reorganization/llvm.m4 \
$(top_srcdir)/libclamav/c++/m4/llvm-opts.m4 \
$(top_srcdir)/m4/reorganization/sha_collect.m4 \
$(top_srcdir)/m4/reorganization/yara.m4 \
$(top_srcdir)/m4/reorganization/code_checks/fts.m4 \
$(top_srcdir)/m4/reorganization/prelude.m4 \
$(top_srcdir)/m4/reorganization/bsd.m4 \
$(top_srcdir)/m4/reorganization/clamonacc.m4 \
$(top_srcdir)/m4/reorganization/libs/curl.m4 \
$(top_srcdir)/m4/reorganization/substitutions.m4 \
$(top_srcdir)/m4/reorganization/strni.m4 \
$(top_srcdir)/m4/reorganization/types.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/clamav-config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
am__installdirs = "$(DESTDIR)$(bindir)"
PROGRAMS = $(bin_PROGRAMS)
am_clamscan_OBJECTS = clamscan.$(OBJEXT) manager.$(OBJEXT)
clamscan_OBJECTS = $(am_clamscan_OBJECTS)
clamscan_LDADD = $(LDADD)
AM_V_lt = $(am__v_lt_@AM_V@)
am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
am__v_lt_0 = --silent
am__v_lt_1 =
AM_V_P = $(am__v_P_@AM_V@)
am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_@AM_V@)
am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_@AM_V@)
am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
am__v_at_0 = @
am__v_at_1 =
DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/config/depcomp
am__maybe_remake_depfiles = depfiles
am__depfiles_remade = ./$(DEPDIR)/clamscan.Po ./$(DEPDIR)/manager.Po
am__mv = mv -f
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
$(AM_CFLAGS) $(CFLAGS)
AM_V_CC = $(am__v_CC_@AM_V@)
am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
am__v_CC_0 = @echo " CC " $@;
am__v_CC_1 =
CCLD = $(CC)
LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
$(AM_LDFLAGS) $(LDFLAGS) -o $@
AM_V_CCLD = $(am__v_CCLD_@AM_V@)
am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
am__v_CCLD_0 = @echo " CCLD " $@;
am__v_CCLD_1 =
SOURCES = $(clamscan_SOURCES)
DIST_SOURCES = $(clamscan_SOURCES)
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
# Read a list of newline-separated strings from the standard input,
# and print each of them once, without duplicates. Input order is
# *not* preserved.
am__uniquify_input = $(AWK) '\
BEGIN { nonempty = 0; } \
{ items[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in items) print i; }; } \
'
# Make sure the list of sources is unique. This is necessary because,
# e.g., the same source file might be shared among _SOURCES variables
# for different programs/libraries.
am__define_uniq_tagged_files = \
list='$(am__tagged_files)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | $(am__uniquify_input)`
ETAGS = etags
CTAGS = ctags
am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/config/depcomp
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = @ACLOCAL@
AMTAR = @AMTAR@
AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
AR = @AR@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
BUILD_CONFIGURE_FLAGS = @BUILD_CONFIGURE_FLAGS@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFGDIR = @CFGDIR@
CFLAGS = @CFLAGS@
CHECK_CFLAGS = @CHECK_CFLAGS@
CHECK_CPPFLAGS = @CHECK_CPPFLAGS@
CHECK_LIBS = @CHECK_LIBS@
CLAMAVGROUP = @CLAMAVGROUP@
CLAMAVUSER = @CLAMAVUSER@
CLAMAV_MILTER_CPPFLAGS = @CLAMAV_MILTER_CPPFLAGS@
CLAMAV_MILTER_LIBS = @CLAMAV_MILTER_LIBS@
CLAMBC_CPPFLAGS = @CLAMBC_CPPFLAGS@
CLAMBC_LIBS = @CLAMBC_LIBS@
CLAMCONF_CPPFLAGS = @CLAMCONF_CPPFLAGS@
CLAMCONF_LIBS = @CLAMCONF_LIBS@
CLAMDSCAN_CPPFLAGS = @CLAMDSCAN_CPPFLAGS@
CLAMDSCAN_LIBS = @CLAMDSCAN_LIBS@
CLAMDTOP_CPPFLAGS = @CLAMDTOP_CPPFLAGS@
CLAMDTOP_LIBS = @CLAMDTOP_LIBS@
CLAMD_CPPFLAGS = @CLAMD_CPPFLAGS@
CLAMD_LIBS = @CLAMD_LIBS@
CLAMMEM_CPPFLAGS = @CLAMMEM_CPPFLAGS@
CLAMMEM_LIBS = @CLAMMEM_LIBS@
CLAMONACC_CPPFLAGS = @CLAMONACC_CPPFLAGS@
CLAMONACC_LIBS = @CLAMONACC_LIBS@
CLAMSCAN_CPPFLAGS = @CLAMSCAN_CPPFLAGS@
CLAMSCAN_LIBS = @CLAMSCAN_LIBS@
CLAMSUBMIT_CFLAGS = @CLAMSUBMIT_CFLAGS@
CLAMSUBMIT_LIBS = @CLAMSUBMIT_LIBS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CURL_CPPFLAGS = @CURL_CPPFLAGS@
CURL_LDFLAGS = @CURL_LDFLAGS@
CURL_LIBS = @CURL_LIBS@
CURSES_CPPFLAGS = @CURSES_CPPFLAGS@
CURSES_LIBS = @CURSES_LIBS@
CXX = @CXX@
CXXCPP = @CXXCPP@
CXXDEPMODE = @CXXDEPMODE@
CXXFLAGS = @CXXFLAGS@
CYGPATH_W = @CYGPATH_W@
DBDIR = @DBDIR@
DEFINE_SF32_PREFIX = @DEFINE_SF32_PREFIX@
DEFINE_SF64_PREFIX = @DEFINE_SF64_PREFIX@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
DLLTOOL = @DLLTOOL@
DSYMUTIL = @DSYMUTIL@
DUMPBIN = @DUMPBIN@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
FGREP = @FGREP@
FRESHCLAM_CPPFLAGS = @FRESHCLAM_CPPFLAGS@
FRESHCLAM_LIBS = @FRESHCLAM_LIBS@
GCOV = @GCOV@
GENERATE_WARNING = @GENERATE_WARNING@
GENHTML = @GENHTML@
GETENT = @GETENT@
GPERF = @GPERF@
GREP = @GREP@
HAVE_STRNI = @HAVE_STRNI@
HAVE_YARA = @HAVE_YARA@
INCLTDL = @INCLTDL@
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
INT16_DEF = @INT16_DEF@
INT32_DEF = @INT32_DEF@
INT64_DEF = @INT64_DEF@
INT8_DEF = @INT8_DEF@
INT_TYPES_HEADER = @INT_TYPES_HEADER@
JSON_CPPFLAGS = @JSON_CPPFLAGS@
JSON_LDFLAGS = @JSON_LDFLAGS@
JSON_LIBS = @JSON_LIBS@
LCOV = @LCOV@
LD = @LD@
LDFLAGS = @LDFLAGS@
LEX = @LEX@
LEXLIB = @LEXLIB@
LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@
LIBADD_DL = @LIBADD_DL@
LIBADD_DLD_LINK = @LIBADD_DLD_LINK@
LIBADD_DLOPEN = @LIBADD_DLOPEN@
LIBADD_SHL_LOAD = @LIBADD_SHL_LOAD@
LIBBZ2 = @LIBBZ2@
LIBBZ2_PREFIX = @LIBBZ2_PREFIX@
LIBCLAMAV_CPPFLAGS = @LIBCLAMAV_CPPFLAGS@
LIBCLAMAV_LIBS = @LIBCLAMAV_LIBS@
LIBCLAMAV_VERSION = @LIBCLAMAV_VERSION@
LIBCLAMAV_VERSION_NUM = @LIBCLAMAV_VERSION_NUM@
LIBCLAMSHARED_CPPFLAGS = @LIBCLAMSHARED_CPPFLAGS@
LIBFRESHCLAM_VERSION = @LIBFRESHCLAM_VERSION@
LIBFRESHCLAM_VERSION_NUM = @LIBFRESHCLAM_VERSION_NUM@
LIBICONV = @LIBICONV@
LIBLTDL = @LIBLTDL@
LIBM = @LIBM@
LIBMSPACK_CFLAGS = @LIBMSPACK_CFLAGS@
LIBMSPACK_LIBS = @LIBMSPACK_LIBS@
LIBOBJS = @LIBOBJS@
LIBPRELUDE_CFLAGS = @LIBPRELUDE_CFLAGS@
LIBPRELUDE_CONFIG = @LIBPRELUDE_CONFIG@
LIBPRELUDE_CONFIG_PREFIX = @LIBPRELUDE_CONFIG_PREFIX@
LIBPRELUDE_LDFLAGS = @LIBPRELUDE_LDFLAGS@
LIBPRELUDE_LIBS = @LIBPRELUDE_LIBS@
LIBPRELUDE_PREFIX = @LIBPRELUDE_PREFIX@
LIBPRELUDE_PTHREAD_CFLAGS = @LIBPRELUDE_PTHREAD_CFLAGS@
LIBS = $(top_builddir)/libclamav/libclamav.la $(top_builddir)/shared/libshared.la @THREAD_LIBS@ @CLAMSCAN_LIBS@
LIBTOOL = @LIBTOOL@
LIPO = @LIPO@
LN_S = @LN_S@
LTDLDEPS = @LTDLDEPS@
LTDLINCL = @LTDLINCL@
LTDLOPEN = @LTDLOPEN@
LTLIBBZ2 = @LTLIBBZ2@
LTLIBICONV = @LTLIBICONV@
LTLIBOBJS = @LTLIBOBJS@
LT_ARGZ_H = @LT_ARGZ_H@
LT_CONFIG_H = @LT_CONFIG_H@
LT_DLLOADERS = @LT_DLLOADERS@
LT_DLPREOPEN = @LT_DLPREOPEN@
LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
MAINT = @MAINT@
MAKEINFO = @MAKEINFO@
MANIFEST_TOOL = @MANIFEST_TOOL@
MKDIR_P = @MKDIR_P@
NCURSES_CFLAGS = @NCURSES_CFLAGS@
NCURSES_LIBS = @NCURSES_LIBS@
NM = @NM@
NMEDIT = @NMEDIT@
OBJC = @OBJC@
OBJCDEPMODE = @OBJCDEPMODE@
OBJCFLAGS = @OBJCFLAGS@
OBJDUMP = @OBJDUMP@
OBJEXT = @OBJEXT@
OTOOL = @OTOOL@
OTOOL64 = @OTOOL64@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_URL = @PACKAGE_URL@
PACKAGE_VERSION = @PACKAGE_VERSION@
PACKAGE_VERSION_NUM = @PACKAGE_VERSION_NUM@
PATH_SEPARATOR = @PATH_SEPARATOR@
PCRE_CFLAGS = @PCRE_CFLAGS@
PCRE_CPPFLAGS = @PCRE_CPPFLAGS@
PCRE_LIBS = @PCRE_LIBS@
PKG_CONFIG = @PKG_CONFIG@
PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@
PKG_CONFIG_PATH = @PKG_CONFIG_PATH@
RANLIB = @RANLIB@
SED = @SED@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
SIGTOOL_CPPFLAGS = @SIGTOOL_CPPFLAGS@
SSL_CPPFLAGS = @SSL_CPPFLAGS@
SSL_LDFLAGS = @SSL_LDFLAGS@
SSL_LIBS = @SSL_LIBS@
STRIP = @STRIP@
SYSTEMD_CFLAGS = @SYSTEMD_CFLAGS@
SYSTEMD_LIBS = @SYSTEMD_LIBS@
THREAD_LIBS = @THREAD_LIBS@
TH_SAFE = @TH_SAFE@
TOMSFASTMATH_CFLAGS = @TOMSFASTMATH_CFLAGS@
TOMSFASTMATH_LIBS = @TOMSFASTMATH_LIBS@
UINT16_DEF = @UINT16_DEF@
UINT32_DEF = @UINT32_DEF@
UINT64_DEF = @UINT64_DEF@
UINT8_DEF = @UINT8_DEF@
VERSION = @VERSION@
VERSIONSCRIPTFLAG = @VERSIONSCRIPTFLAG@
WERR_CFLAGS = @WERR_CFLAGS@
WERR_CFLAGS_MILTER = @WERR_CFLAGS_MILTER@
XML_CPPFLAGS = @XML_CPPFLAGS@
XML_LIBS = @XML_LIBS@
YACC = @YACC@
YFLAGS = @YFLAGS@
ZLIB_CFLAGS = @ZLIB_CFLAGS@
ZLIB_LIBS = @ZLIB_LIBS@
abs_builddir = @abs_builddir@
abs_srcdir = @abs_srcdir@
abs_top_builddir = @abs_top_builddir@
abs_top_srcdir = @abs_top_srcdir@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_CXX = @ac_ct_CXX@
ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
ac_ct_OBJC = @ac_ct_OBJC@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
builddir = @builddir@
curl_config = @curl_config@
datadir = @datadir@
datarootdir = @datarootdir@
docdir = @docdir@
dvidir = @dvidir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
htmldir = @htmldir@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
llvmconfig = @llvmconfig@
localedir = @localedir@
localstatedir = @localstatedir@
ltdl_LIBOBJS = @ltdl_LIBOBJS@
ltdl_LTLIBOBJS = @ltdl_LTLIBOBJS@
mandir = @mandir@
mkdir_p = @mkdir_p@
oldincludedir = @oldincludedir@
pcreconfig = @pcreconfig@
pdfdir = @pdfdir@
prefix = @prefix@
program_transform_name = @program_transform_name@
psdir = @psdir@
runstatedir = @runstatedir@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
srcdir = @srcdir@
subdirs = @subdirs@
sys_symbol_underscore = @sys_symbol_underscore@
sysconfdir = @sysconfdir@
systemdsystemunitdir = @systemdsystemunitdir@
target = @target@
target_alias = @target_alias@
target_cpu = @target_cpu@
target_os = @target_os@
target_vendor = @target_vendor@
top_build_prefix = @top_build_prefix@
top_builddir = @top_builddir@
top_srcdir = @top_srcdir@
xmlconfig = @xmlconfig@
clamscan_SOURCES = \
clamscan.c \
global.h \
manager.c \
manager.h
AM_CFLAGS = @WERR_CFLAGS@
AM_CPPFLAGS = -I$(top_srcdir) -I$(top_srcdir)/shared -I$(top_srcdir)/libclamav -I$(top_builddir)/libclamav -I$(top_srcdir)/libclamunrar_iface @SSL_CPPFLAGS@ @JSON_CPPFLAGS@ @PCRE_CPPFLAGS@ @CLAMSCAN_CPPFLAGS@
CLEANFILES = *.gcda *.gcno
all: all-am
.SUFFIXES:
.SUFFIXES: .c .lo .o .obj
$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign clamscan/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign clamscan/Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
install-binPROGRAMS: $(bin_PROGRAMS)
@$(NORMAL_INSTALL)
@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \
$(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \
fi; \
for p in $$list; do echo "$$p $$p"; done | \
sed 's/$(EXEEXT)$$//' | \
while read p p1; do if test -f $$p \
|| test -f $$p1 \
; then echo "$$p"; echo "$$p"; else :; fi; \
done | \
sed -e 'p;s,.*/,,;n;h' \
-e 's|.*|.|' \
-e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
sed 'N;N;N;s,\n, ,g' | \
$(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \
{ d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
if ($$2 == $$4) files[d] = files[d] " " $$1; \
else { print "f", $$3 "/" $$4, $$1; } } \
END { for (d in files) print "f", d, files[d] }' | \
while read type dir files; do \
if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
test -z "$$files" || { \
echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \
$(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
} \
; done
uninstall-binPROGRAMS:
@$(NORMAL_UNINSTALL)
@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
files=`for p in $$list; do echo "$$p"; done | \
sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
-e 's/$$/$(EXEEXT)/' \
`; \
test -n "$$list" || exit 0; \
echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
cd "$(DESTDIR)$(bindir)" && rm -f $$files
clean-binPROGRAMS:
@list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
echo " rm -f" $$list; \
rm -f $$list || exit $$?; \
test -n "$(EXEEXT)" || exit 0; \
list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
echo " rm -f" $$list; \
rm -f $$list
installcheck-binPROGRAMS: $(bin_PROGRAMS)
bad=0; pid=$$$$; list="$(bin_PROGRAMS)"; for p in $$list; do \
case ' $(AM_INSTALLCHECK_STD_OPTIONS_EXEMPT) ' in \
*" $$p "* | *" $(srcdir)/$$p "*) continue;; \
esac; \
f=`echo "$$p" | \
sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
for opt in --help --version; do \
if "$(DESTDIR)$(bindir)/$$f" $$opt >c$${pid}_.out \
2>c$${pid}_.err </dev/null \
&& test -n "`cat c$${pid}_.out`" \
&& test -z "`cat c$${pid}_.err`"; then :; \
else echo "$$f does not support $$opt" 1>&2; bad=1; fi; \
done; \
done; rm -f c$${pid}_.???; exit $$bad
clamscan$(EXEEXT): $(clamscan_OBJECTS) $(clamscan_DEPENDENCIES) $(EXTRA_clamscan_DEPENDENCIES)
@rm -f clamscan$(EXEEXT)
$(AM_V_CCLD)$(LINK) $(clamscan_OBJECTS) $(clamscan_LDADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
distclean-compile:
-rm -f *.tab.c
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/clamscan.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/manager.Po@am__quote@ # am--include-marker
$(am__depfiles_remade):
@$(MKDIR_P) $(@D)
@echo '# dummy' >$@-t && $(am__mv) $@-t $@
am--depfiles: $(am__depfiles_remade)
.c.o:
@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po
@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
.c.obj:
@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po
@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
.c.lo:
@am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
@am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo
@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
ID: $(am__tagged_files)
$(am__define_uniq_tagged_files); mkid -fID $$unique
tags: tags-am
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
$(am__define_uniq_tagged_files); \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: ctags-am
CTAGS: ctags
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
$(am__define_uniq_tagged_files); \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
cscopelist: cscopelist-am
cscopelist-am: $(am__tagged_files)
list='$(am__tagged_files)'; \
case "$(srcdir)" in \
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
*) sdir=$(subdir)/$(srcdir) ;; \
esac; \
for i in $$list; do \
if test -f "$$i"; then \
echo "$(subdir)/$$i"; \
else \
echo "$$sdir/$$i"; \
fi; \
done >> $(top_builddir)/cscope.files
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(BUILT_SOURCES)
$(MAKE) $(AM_MAKEFLAGS) distdir-am
distdir-am: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(PROGRAMS)
installdirs:
for dir in "$(DESTDIR)$(bindir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f ./$(DEPDIR)/clamscan.Po
-rm -f ./$(DEPDIR)/manager.Po
-rm -f Makefile
distclean-am: clean-am distclean-compile distclean-generic \
distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am:
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am: install-binPROGRAMS
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am: installcheck-binPROGRAMS
maintainer-clean: maintainer-clean-am
-rm -f ./$(DEPDIR)/clamscan.Po
-rm -f ./$(DEPDIR)/manager.Po
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-binPROGRAMS
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-am clean \
clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \
ctags ctags-am distclean distclean-compile distclean-generic \
distclean-libtool distclean-tags distdir dvi dvi-am html \
html-am info info-am install install-am install-binPROGRAMS \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installcheck-binPROGRAMS \
installdirs maintainer-clean maintainer-clean-generic \
mostlyclean mostlyclean-compile mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
uninstall-am uninstall-binPROGRAMS
.PRECIOUS: Makefile
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
+708
View File
@@ -0,0 +1,708 @@
/* clamav-config.h. Generated from clamav-config.h.in by configure. */
/* clamav-config.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* mmap flag for anonymous maps */
#define ANONYMOUS_MAP MAP_ANONYMOUS
/* enable bind8 compatibility */
/* #undef BIND_8_COMPAT */
/* use ClamAuth */
/* #undef CLAMAUTH */
/* name of the clamav group */
#define CLAMAVGROUP "clamav"
/* name of the clamav user */
#define CLAMAVUSER "clamav"
/* enable debugging */
/* #undef CL_DEBUG */
/* enable experimental code */
/* #undef CL_EXPERIMENTAL */
/* thread safe */
#define CL_THREAD_SAFE 1
/* where to look for the config file */
#define CONFDIR "/etc/clamav"
/* curses header location */
#define CURSES_INCLUDE <ncurses.h>
/* os is aix */
/* #undef C_AIX */
/* os is beos */
/* #undef C_BEOS */
/* Increase thread stack size. */
/* #undef C_BIGSTACK */
/* os is bsd flavor */
/* #undef C_BSD */
/* os is darwin */
/* #undef C_DARWIN */
/* target is gnu-hurd */
/* #undef C_GNU_HURD */
/* os is hpux */
/* #undef C_HPUX */
/* os is interix */
/* #undef C_INTERIX */
/* os is irix */
/* #undef C_IRIX */
/* target is kfreebsd-gnu */
/* #undef C_KFREEBSD_GNU */
/* target is linux */
#define C_LINUX 1
/* os is OS/2 */
/* #undef C_OS2 */
/* os is osf/tru64 */
/* #undef C_OSF */
/* os is QNX 6.x.x */
/* #undef C_QNX6 */
/* os is solaris */
/* #undef C_SOLARIS */
/* Path to virus database directory. */
#define DATADIR "/var/lib/clamav"
/* "default FD_SETSIZE value" */
#define DEFAULT_FD_SETSIZE 1024
/* whether _XOPEN_SOURCE needs to be defined for fd passing to work */
/* #undef FDPASS_NEED_XOPEN */
/* file i/o buffer size */
#define FILEBUFF 8192
/* enable workaround for broken DNS servers */
#define FRESHCLAM_DNS_FIX 1
/* use "Cache-Control: no-cache" in freshclam */
/* #undef FRESHCLAM_NO_CACHE */
/* Define to 1 if you have the `argz_add' function. */
#define HAVE_ARGZ_ADD 1
/* Define to 1 if you have the `argz_append' function. */
#define HAVE_ARGZ_APPEND 1
/* Define to 1 if you have the `argz_count' function. */
#define HAVE_ARGZ_COUNT 1
/* Define to 1 if you have the `argz_create_sep' function. */
#define HAVE_ARGZ_CREATE_SEP 1
/* Define to 1 if you have the <argz.h> header file. */
#define HAVE_ARGZ_H 1
/* Define to 1 if you have the `argz_insert' function. */
#define HAVE_ARGZ_INSERT 1
/* Define to 1 if you have the `argz_next' function. */
#define HAVE_ARGZ_NEXT 1
/* Define to 1 if you have the `argz_stringify' function. */
#define HAVE_ARGZ_STRINGIFY 1
/* attrib aligned */
#define HAVE_ATTRIB_ALIGNED 1
/* attrib packed */
#define HAVE_ATTRIB_PACKED 1
/* have bzip2 */
#define HAVE_BZLIB_H 1
/* Define to 1 if you have the `closedir' function. */
#define HAVE_CLOSEDIR 1
/* Define to 1 if you have the `ctime_r' function. */
#define HAVE_CTIME_R 1
/* ctime_r takes 2 arguments */
#define HAVE_CTIME_R_2 1
/* ctime_r takes 3 arguments */
/* #undef HAVE_CTIME_R_3 */
/* Define to 1 if you have the declaration of `cygwin_conv_path', and to 0 if
you don't. */
/* #undef HAVE_DECL_CYGWIN_CONV_PATH */
/* Define to 1 if you have a deprecated version of the 'libjson' library
(-ljson). */
/* #undef HAVE_DEPRECATED_JSON */
/* Define to 1 if you have the <dirent.h> header file. */
#define HAVE_DIRENT_H 1
/* Define if you have the GNU dld library. */
/* #undef HAVE_DLD */
/* Define to 1 if you have the <dld.h> header file. */
/* #undef HAVE_DLD_H */
/* Define to 1 if you have the `dlerror' function. */
#define HAVE_DLERROR 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <dl.h> header file. */
/* #undef HAVE_DL_H */
/* Define if you have the _dyld_func_lookup function. */
/* #undef HAVE_DYLD */
/* Define to 1 if you have the `enable_extended_FILE_stdio' function. */
/* #undef HAVE_ENABLE_EXTENDED_FILE_STDIO */
/* Define to 1 if the system has the type `error_t'. */
#define HAVE_ERROR_T 1
/* have working file descriptor passing support */
#define HAVE_FD_PASSING 1
/* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
#define HAVE_FSEEKO 1
/* have getaddrinfo() */
#define HAVE_GETADDRINFO 1
/* Define to 1 if you have the `getnameinfo' function. */
#define HAVE_GETNAMEINFO 1
/* Define to 1 if getpagesize() is available */
#define HAVE_GETPAGESIZE 1
/* Define to 1 if you have the <grp.h> header file. */
#define HAVE_GRP_H 1
/* Define if you have the iconv() function and it works. */
#define HAVE_ICONV 1
/* Define to 1 if you have the <iconv.h> header file. */
#define HAVE_ICONV_H 1
/* Define to 1 if you have the `inet_ntop' function. */
#define HAVE_INET_NTOP 1
/* Define to 1 if you have the `initgroups' function. */
#define HAVE_INITGROUPS 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* in_addr_t is defined */
#define HAVE_IN_ADDR_T 1
/* in_port_t is defined */
#define HAVE_IN_PORT_T 1
/* Define to 1 if you have the 'libjson' library (-ljson). */
#define HAVE_JSON 1
/* Define to 1 if you have the `charset' library (-lcharset). */
/* #undef HAVE_LIBCHARSET */
/* Define to '1' if you have the check.h library */
/* #undef HAVE_LIBCHECK */
/* Define if you have the libdl library or equivalent. */
#define HAVE_LIBDL 1
/* Define if libdlloader will be built on this platform */
#define HAVE_LIBDLLOADER 1
/* Define to 1 if you have the <libmilter/mfapi.h> header file. */
#define HAVE_LIBMILTER_MFAPI_H 1
/* Define to '1' if you have the ncurses.h library */
/* #undef HAVE_LIBNCURSES */
/* Define to '1' if you have the curses.h library */
/* #undef HAVE_LIBPDCURSES */
/* Define to 1 if you have the `ssl' library (-lssl). */
#define HAVE_LIBSSL 1
/* Define to 1 if you have the 'libxml2' library (-lxml2). */
#define HAVE_LIBXML2 1
/* Define to 1 if you have the `z' library (-lz). */
#define HAVE_LIBZ 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <localcharset.h> header file. */
/* #undef HAVE_LOCALCHARSET_H */
/* Define to 1 if you have the `locale_charset' function. */
/* #undef HAVE_LOCALE_CHARSET */
/* Define this if a modern libltdl is already installed */
#define HAVE_LTDL 1
/* Define to 1 if you have the <mach-o/dyld.h> header file. */
/* #undef HAVE_MACH_O_DYLD_H */
/* Define to 1 if you have the `madvise' function. */
#define HAVE_MADVISE 1
/* Define to 1 if you have the `mallinfo' function. */
#define HAVE_MALLINFO 1
/* Define to 1 if you have the <malloc.h> header file. */
#define HAVE_MALLOC_H 1
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `mkstemp' function. */
#define HAVE_MKSTEMP 1
/* Define to 1 if you have a working `mmap' system call that supports
MAP_PRIVATE. */
#define HAVE_MMAP 1
/* Define to 1 if you have the <ndir.h> header file. */
/* #undef HAVE_NDIR_H */
/* Define to 1 if you have the `opendir' function. */
#define HAVE_OPENDIR 1
/* Define to 1 if you have a pcre library (-lpcre). */
#define HAVE_PCRE 1
/* Define to 1 if you have the `poll' function. */
#define HAVE_POLL 1
/* Define to 1 if you have the <poll.h> header file. */
#define HAVE_POLL_H 1
/* "pragma pack" */
/* #undef HAVE_PRAGMA_PACK */
/* "pragma pack hppa/hp-ux style" */
/* #undef HAVE_PRAGMA_PACK_HPPA */
/* Define if libtool can extract symbol lists from object files. */
#define HAVE_PRELOADED_SYMBOLS 1
/* Define to 1 if you have the <pthread.h> header file */
#define HAVE_PTHREAD_H 1
/* Define to 1 if you have the `pthread_yield' function. */
#define HAVE_PTHREAD_YIELD 1
/* Define to 1 if you have the <pwd.h> header file. */
#define HAVE_PWD_H 1
/* Define to 1 if you have the `readdir' function. */
#define HAVE_READDIR 1
/* Define to 1 if you have the `recvmsg' function. */
#define HAVE_RECVMSG 1
/* have resolv.h */
#define HAVE_RESOLV_H 1
/* Define signed right shift implementation */
#define HAVE_SAR 1
/* Define to 1 if you have the `sched_yield' function. */
#define HAVE_SCHED_YIELD 1
/* Define to 1 if you have the `sendmsg' function. */
#define HAVE_SENDMSG 1
/* Define to 1 if you have the `setgroups' function. */
#define HAVE_SETGROUPS 1
/* Define to 1 if you have the `setsid' function. */
#define HAVE_SETSID 1
/* Define if you have the shl_load function. */
/* #undef HAVE_SHL_LOAD */
/* Define to 1 if you have the `snprintf' function. */
#define HAVE_SNPRINTF 1
/* enable stat64 */
#define HAVE_STAT64 1
/* Define to 1 if you have the <stdbool.h> header file. */
#define HAVE_STDBOOL_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strcasestr' function. */
#define HAVE_STRCASESTR 1
/* Define to 1 if you have the `strerror_r' function. */
#define HAVE_STRERROR_R 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strlcat' function. */
/* #undef HAVE_STRLCAT */
/* Define to 1 if you have the `strlcpy' function. */
/* #undef HAVE_STRLCPY */
/* Define to 1 if you have the `strndup' function. */
#define HAVE_STRNDUP 1
/* using internal strn functions */
/* #undef HAVE_STRNI */
/* Define to 1 if you have the `strnlen' function. */
#define HAVE_STRNLEN 1
/* Define to 1 if you have the `strnstr' function. */
/* #undef HAVE_STRNSTR */
/* Define to 1 if sysconf(_SC_PAGESIZE) is available */
#define HAVE_SYSCONF_SC_PAGESIZE 1
/* Define to 1 if you have the `sysctlbyname' function. */
/* #undef HAVE_SYSCTLBYNAME */
/* systemd is supported */
#define HAVE_SYSTEMD /**/
/* Use private fts() implementation which is LFS safe */
#define HAVE_SYSTEM_LFS_FTS 1
/* don't link against system-wide tomsfastmath library */
#define HAVE_SYSTEM_TOMSFASTMATH 1
/* Define to 1 if you have the <sys/cdefs.h> header file. */
#define HAVE_SYS_CDEFS_H 1
/* Define to 1 if you have the <sys/dl.h> header file. */
/* #undef HAVE_SYS_DL_H */
/* use fanotify */
#define HAVE_SYS_FANOTIFY_H 1
/* Define to 1 if you have the <sys/filio.h> header file. */
/* #undef HAVE_SYS_FILIO_H */
/* Define to 1 if you have the <sys/inttypes.h> header file. */
/* #undef HAVE_SYS_INTTYPES_H */
/* Define to 1 if you have the <sys/int_types.h> header file. */
/* #undef HAVE_SYS_INT_TYPES_H */
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/param.h> header file. */
#define HAVE_SYS_PARAM_H 1
/* Define to 1 if you have the <sys/queue.h> header file. */
#define HAVE_SYS_QUEUE_H 1
/* "have <sys/select.h>" */
#define HAVE_SYS_SELECT_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/times.h> header file. */
#define HAVE_SYS_TIMES_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/uio.h> header file. */
#define HAVE_SYS_UIO_H 1
/* Define to 1 if you have the <termios.h> header file. */
#define HAVE_TERMIOS_H 1
/* Define to 1 if you have the `timegm' function. */
#define HAVE_TIMEGM 1
/* Define this if uname(2) is POSIX */
#define HAVE_UNAME_SYSCALL 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if you have the `vsnprintf' function. */
#define HAVE_VSNPRINTF 1
/* This value is set to 1 to indicate that the system argz facility works */
#define HAVE_WORKING_ARGZ 1
/* yara sources are compiled in */
#define HAVE_YARA 1
/* Define to 1 if you have the <zlib.h> header file. */
#define HAVE_ZLIB_H 1
/* For internal use only - DO NOT DEFINE */
/* #undef HAVE__INTERNAL__SHA_COLLECT */
/* Define as const if the declaration of iconv() needs const. */
#define ICONV_CONST
/* "Full clamav library version number" */
#define LIBCLAMAV_FULLVER "9.0.5"
/* "Major clamav library version number" */
#define LIBCLAMAV_MAJORVER 9
/* "Full freshclam library version number" */
#define LIBFRESHCLAM_FULLVER "2.0.1"
/* "Major freshclam library version number" */
#define LIBFRESHCLAM_MAJORVER 2
/* Define if the OS needs help to load dependent libraries for dlopen(). */
/* #undef LTDL_DLOPEN_DEPLIBS */
/* Define to the system default library search path. */
#define LT_DLSEARCH_PATH "/lib:/usr/lib:/usr/lib/x86_64-linux-gnu/libfakeroot:/usr/local/lib:/opt/mysql/lib:/usr/local/lib/x86_64-linux-gnu:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/lib32:/usr/lib32:/libx32:/usr/libx32"
/* The archive extension */
#define LT_LIBEXT "a"
/* The archive prefix */
#define LT_LIBPREFIX "lib"
/* Define to the extension used for runtime loadable modules, say, ".so". */
#define LT_MODULE_EXT ".so"
/* Define to the name of the environment variable that determines the run-time
module search path. */
#define LT_MODULE_PATH_VAR "LD_LIBRARY_PATH"
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"
/* Define to the shared library suffix, say, ".dylib". */
/* #undef LT_SHARED_EXT */
/* Define to the shared archive member specification, say "(shr.o)". */
/* #undef LT_SHARED_LIB_MEMBER */
/* disable assertions */
#define NDEBUG 1
/* Define if dlsym() requires a leading underscore in symbol names. */
/* #undef NEED_USCORE */
/* bzip funtions do not have bz2 prefix */
/* #undef NOBZ2PREFIX */
/* "no fd_set" */
/* #undef NO_FD_SET */
/* Name of package */
#define PACKAGE PACKAGE_NAME
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "https://github.com/Cisco-Talos/clamav/issues"
/* Define to the full name of this package. */
#define PACKAGE_NAME "ClamAV"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "ClamAV 0.103.7"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "clamav"
/* Define to the home page for this package. */
#define PACKAGE_URL "https://www.clamav.net/"
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.103.7"
/* Libprelude support enabled */
/* #undef PRELUDE */
/* Define whether application use libtool >= 2.0 */
/* #undef PRELUDE_APPLICATION_USE_LIBTOOL2 */
/* scan buffer size */
#define SCANBUFF 131072
/* Define to 1 if the `setpgrp' function takes no argument. */
#define SETPGRP_VOID 1
/* The number of bytes in type int */
#define SIZEOF_INT 4
/* The number of bytes in type long */
#define SIZEOF_LONG 8
/* The number of bytes in type long long */
#define SIZEOF_LONG_LONG 8
/* The number of bytes in type short */
#define SIZEOF_SHORT 2
/* The number of bytes in type void * */
#define SIZEOF_VOID_P 8
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Support for IPv6 */
#define SUPPORT_IPv6 1
/* enable memory pools */
#define USE_MPOOL 1
/* use syslog */
#define USE_SYSLOG 1
/* Enable extensions on AIX 3, Interix. */
#ifndef _ALL_SOURCE
# define _ALL_SOURCE 1
#endif
/* Enable GNU extensions on systems that have them. */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
/* Enable threading extensions on Solaris. */
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS 1
#endif
/* Enable extensions on HP NonStop. */
#ifndef _TANDEM_SOURCE
# define _TANDEM_SOURCE 1
#endif
/* Enable general extensions on Solaris. */
#ifndef __EXTENSIONS__
# define __EXTENSIONS__ 1
#endif
/* Define to 1 if you using the pcre2 library. */
#define USING_PCRE2 1
/* Version number of package */
#define VERSION "0.103.7"
/* Version suffix for package */
#define VERSION_SUFFIX ""
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to 1 if `lex' declares `yytext' as a `char *' by default, not a
`char[]'. */
#define YYTEXT_POINTER 1
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
# define _DARWIN_USE_64_BIT_INODE 1
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
/* #undef _FILE_OFFSET_BITS */
/* Define to 1 to make fseeko visible on some hosts (e.g. glibc 2.2). */
/* #undef _LARGEFILE_SOURCE */
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define to 1 if on MINIX. */
/* #undef _MINIX */
/* Define to 2 if the system does not provide POSIX.1 features except with
this defined. */
/* #undef _POSIX_1_SOURCE */
/* POSIX compatibility */
/* #undef _POSIX_PII_SOCKET */
/* Define to 1 if you need to in order for `stat' and other things to work. */
/* #undef _POSIX_SOURCE */
/* thread safe */
#define _REENTRANT 1
/* thread safe */
/* #undef _THREAD_SAFE */
/* Define so that glibc/gnulib argp.h does not typedef error_t. */
/* #undef __error_t_defined */
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define to a type to use for 'error_t' if it is not otherwise available. */
/* #undef error_t */
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
/* #undef inline */
#endif
/* Define to `long int' if <sys/types.h> does not define. */
/* #undef off_t */
/* Define to the equivalent of the C99 'restrict' keyword, or to
nothing if this is not supported. Do not define if restrict is
supported directly. */
#define restrict __restrict
/* Work around a bug in Sun C++: it does not support _Restrict or
__restrict__, even though the corresponding Sun C compiler ends up with
"#define restrict _Restrict" or "#define restrict __restrict__" in the
previous line. Perhaps some future version of Sun C++ will work with
restrict; if so, hopefully it defines __RESTRICT like Sun C does. */
#if defined __SUNPRO_CC && !defined __RESTRICT
# define _Restrict
# define __restrict__
#endif
/* Define to "int" if <sys/socket.h> does not define. */
/* #undef socklen_t */
#include "platform.h"
+210
View File
@@ -0,0 +1,210 @@
#! /bin/bash
# clamscan - temporary wrapper script for .libs/clamscan
# Generated by libtool (GNU libtool) 2.4.6 Debian-2.4.6-15
#
# The clamscan program cannot be directly executed until all the libtool
# libraries that it depends on are installed.
#
# This wrapper script should never be moved out of the build directory.
# If it is, it will not operate correctly.
# Sed substitution that helps us do robust quoting. It backslashifies
# metacharacters that are still active within double-quoted strings.
sed_quote_subst='s|\([`"$\\]\)|\\\1|g'
# Be Bourne compatible
if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
emulate sh
NULLCMD=:
# Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
# is contrary to our usage. Disable this feature.
alias -g '${1+"$@"}'='"$@"'
setopt NO_GLOB_SUBST
else
case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
fi
BIN_SH=xpg4; export BIN_SH # for Tru64
DUALCASE=1; export DUALCASE # for MKS sh
# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
relink_command=""
# This environment variable determines our operation mode.
if test "$libtool_install_magic" = "%%%MAGIC variable%%%"; then
# install mode needs the following variables:
generated_by_libtool_version='2.4.6'
notinst_deplibs=' ../libclamav/libclamav.la'
else
# When we are sourced in execute mode, $file and $ECHO are already set.
if test "$libtool_execute_magic" != "%%%MAGIC variable%%%"; then
file="$0"
# A function that is used when there is no print builtin or printf.
func_fallback_echo ()
{
eval 'cat <<_LTECHO_EOF
$1
_LTECHO_EOF'
}
ECHO="printf %s\\n"
fi
# Very basic option parsing. These options are (a) specific to
# the libtool wrapper, (b) are identical between the wrapper
# /script/ and the wrapper /executable/ that is used only on
# windows platforms, and (c) all begin with the string --lt-
# (application programs are unlikely to have options that match
# this pattern).
#
# There are only two supported options: --lt-debug and
# --lt-dump-script. There is, deliberately, no --lt-help.
#
# The first argument to this parsing function should be the
# script's ../libtool value, followed by no.
lt_option_debug=
func_parse_lt_options ()
{
lt_script_arg0=$0
shift
for lt_opt
do
case "$lt_opt" in
--lt-debug) lt_option_debug=1 ;;
--lt-dump-script)
lt_dump_D=`$ECHO "X$lt_script_arg0" | /bin/sed -e 's/^X//' -e 's%/[^/]*$%%'`
test "X$lt_dump_D" = "X$lt_script_arg0" && lt_dump_D=.
lt_dump_F=`$ECHO "X$lt_script_arg0" | /bin/sed -e 's/^X//' -e 's%^.*/%%'`
cat "$lt_dump_D/$lt_dump_F"
exit 0
;;
--lt-*)
$ECHO "Unrecognized --lt- option: '$lt_opt'" 1>&2
exit 1
;;
esac
done
# Print the debug banner immediately:
if test -n "$lt_option_debug"; then
echo "clamscan:clamscan:$LINENO: libtool wrapper (GNU libtool) 2.4.6 Debian-2.4.6-15" 1>&2
fi
}
# Used when --lt-debug. Prints its arguments to stdout
# (redirection is the responsibility of the caller)
func_lt_dump_args ()
{
lt_dump_args_N=1;
for lt_arg
do
$ECHO "clamscan:clamscan:$LINENO: newargv[$lt_dump_args_N]: $lt_arg"
lt_dump_args_N=`expr $lt_dump_args_N + 1`
done
}
# Core function for launching the target application
func_exec_program_core ()
{
if test -n "$lt_option_debug"; then
$ECHO "clamscan:clamscan:$LINENO: newargv[0]: $progdir/$program" 1>&2
func_lt_dump_args ${1+"$@"} 1>&2
fi
exec "$progdir/$program" ${1+"$@"}
$ECHO "$0: cannot exec $program $*" 1>&2
exit 1
}
# A function to encapsulate launching the target application
# Strips options in the --lt-* namespace from $@ and
# launches target application with the remaining arguments.
func_exec_program ()
{
case " $* " in
*\ --lt-*)
for lt_wr_arg
do
case $lt_wr_arg in
--lt-*) ;;
*) set x "$@" "$lt_wr_arg"; shift;;
esac
shift
done ;;
esac
func_exec_program_core ${1+"$@"}
}
# Parse options
func_parse_lt_options "$0" ${1+"$@"}
# Find the directory that this script lives in.
thisdir=`$ECHO "$file" | /bin/sed 's%/[^/]*$%%'`
test "x$thisdir" = "x$file" && thisdir=.
# Follow symbolic links until we get to the real thisdir.
file=`ls -ld "$file" | /bin/sed -n 's/.*-> //p'`
while test -n "$file"; do
destdir=`$ECHO "$file" | /bin/sed 's%/[^/]*$%%'`
# If there was a directory component, then change thisdir.
if test "x$destdir" != "x$file"; then
case "$destdir" in
[\\/]* | [A-Za-z]:[\\/]*) thisdir="$destdir" ;;
*) thisdir="$thisdir/$destdir" ;;
esac
fi
file=`$ECHO "$file" | /bin/sed 's%^.*/%%'`
file=`ls -ld "$thisdir/$file" | /bin/sed -n 's/.*-> //p'`
done
# Usually 'no', except on cygwin/mingw when embedded into
# the cwrapper.
WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=no
if test "$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR" = "yes"; then
# special case for '.'
if test "$thisdir" = "."; then
thisdir=`pwd`
fi
# remove .libs from thisdir
case "$thisdir" in
*[\\/].libs ) thisdir=`$ECHO "$thisdir" | /bin/sed 's%[\\/][^\\/]*$%%'` ;;
.libs ) thisdir=. ;;
esac
fi
# Try to get the absolute directory name.
absdir=`cd "$thisdir" && pwd`
test -n "$absdir" && thisdir="$absdir"
program='clamscan'
progdir="$thisdir/.libs"
if test -f "$progdir/$program"; then
# Add our own library path to LD_LIBRARY_PATH
LD_LIBRARY_PATH="/root/clamav/clamav-0.103.7+dfsg/libclamav/.libs:$LD_LIBRARY_PATH"
# Some systems cannot cope with colon-terminated LD_LIBRARY_PATH
# The second colon is a workaround for a bug in BeOS R4 sed
LD_LIBRARY_PATH=`$ECHO "$LD_LIBRARY_PATH" | /bin/sed 's/::*$//'`
export LD_LIBRARY_PATH
if test "$libtool_execute_magic" != "%%%MAGIC variable%%%"; then
# Run the actual program with our arguments.
func_exec_program ${1+"$@"}
fi
else
# The program doesn't exist.
$ECHO "$0: error: '$progdir/$program' does not exist" 1>&2
$ECHO "This script is just a wrapper for $program." 1>&2
$ECHO "See the libtool documentation for more information." 1>&2
exit 1
fi
fi
+340
View File
@@ -0,0 +1,340 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Tomasz Kojm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <locale.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <time.h>
#ifdef C_LINUX
#include <sys/resource.h>
#endif
// libclamav
#include "clamav.h"
#include "others.h"
#include "str.h"
// shared
#include "misc.h"
#include "output.h"
#include "actions.h"
#include "optparser.h"
#include "global.h"
#include "manager.h"
void help(void);
struct s_info info;
short recursion = 0, bell = 0;
short printinfected = 0, printclean = 1;
int _clamscan(int argc, char **argv)
{
int ds, dms, ret;
double mb, rmb;
struct timeval t1, t2;
time_t date_start, date_end;
char buffer[26];
#ifndef _WIN32
sigset_t sigset;
#endif
struct optstruct *opts;
const struct optstruct *opt;
if (check_flevel())
exit(2);
#if !defined(_WIN32)
if (!setlocale(LC_CTYPE, "")) {
mprintf("^Failed to set locale\n");
}
#if !defined(C_BEOS)
sigemptyset(&sigset);
sigaddset(&sigset, SIGXFSZ);
sigprocmask(SIG_SETMASK, &sigset, NULL);
#endif /* !C_BEOS */
#endif /* !_WIN32 */
cl_initialize_crypto();
if ((opts = optparse(NULL, argc, argv, 1, OPT_CLAMSCAN, 0, NULL)) == NULL) {
mprintf("!Can't parse command line options\n");
return 2;
}
if (optget(opts, "verbose")->enabled) {
mprintf_verbose = 1;
logg_verbose = 1;
}
if (optget(opts, "quiet")->enabled)
mprintf_quiet = 1;
if (optget(opts, "stdout")->enabled)
mprintf_stdout = 1;
if (optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
/* njh@bandsman.co.uk: create a dump if needed */
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &rlim) < 0)
perror("setrlimit");
#endif
cl_debug(); /* enable debug messages */
}
if (optget(opts, "gen-mdb")->enabled) {
cl_always_gen_section_hash();
}
if (optget(opts, "version")->enabled) {
print_version(optget(opts, "database")->strarg);
optfree(opts);
return 0;
}
if (optget(opts, "help")->enabled) {
optfree(opts);
help();
return 0;
}
if (optget(opts, "recursive")->enabled)
recursion = 1;
if (optget(opts, "infected")->enabled)
printinfected = 1;
if (optget(opts, "suppress-ok-results")->enabled)
printclean = 0;
if (optget(opts, "bell")->enabled)
bell = 1;
/* initialize logger */
if ((opt = optget(opts, "log"))->enabled) {
logg_file = opt->strarg;
if (logg("#\n-------------------------------------------------------------------------------\n\n")) {
mprintf("!Problem with internal logger.\n");
optfree(opts);
return 2;
}
} else
logg_file = NULL;
if (actsetup(opts)) {
optfree(opts);
logg_close();
exit(2);
}
memset(&info, 0, sizeof(struct s_info));
date_start = time(NULL);
gettimeofday(&t1, NULL);
ret = scanmanager(opts);
if (!optget(opts, "no-summary")->enabled) {
struct tm tmp;
date_end = time(NULL);
gettimeofday(&t2, NULL);
ds = t2.tv_sec - t1.tv_sec;
dms = t2.tv_usec - t1.tv_usec;
ds -= (dms < 0) ? (1) : (0);
dms += (dms < 0) ? (1000000) : (0);
logg("\n----------- SCAN SUMMARY -----------\n");
logg("Known viruses: %u\n", info.sigs);
logg("Engine version: %s\n", get_version());
logg("Scanned directories: %u\n", info.dirs);
logg("Scanned files: %u\n", info.files);
logg("Infected files: %u\n", info.ifiles);
if (info.errors)
logg("Total errors: %u\n", info.errors);
if (notremoved) {
logg("Not removed: %u\n", notremoved);
}
if (notmoved) {
logg("Not %s: %u\n", optget(opts, "copy")->enabled ? "moved" : "copied", notmoved);
}
mb = info.blocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
logg("Data scanned: %2.2lf MB\n", mb);
rmb = info.rblocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
logg("Data read: %2.2lf MB (ratio %.2f:1)\n", rmb, info.rblocks ? (double)info.blocks / (double)info.rblocks : 0);
logg("Time: %u.%3.3u sec (%u m %u s)\n", ds, dms / 1000, ds / 60, ds % 60);
#ifdef _WIN32
if (0 != localtime_s(&tmp, &date_start)) {
#else
if (!localtime_r(&date_start, &tmp)) {
#endif
logg("!Failed to get local time for Start Date.\n");
}
strftime(buffer, sizeof(buffer), "%Y:%m:%d %H:%M:%S", &tmp);
logg("Start Date: %s\n", buffer);
#ifdef _WIN32
if (0 != localtime_s(&tmp, &date_end)) {
#else
if (!localtime_r(&date_end, &tmp)) {
#endif
logg("!Failed to get local time for End Date.\n");
}
strftime(buffer, sizeof(buffer), "%Y:%m:%d %H:%M:%S", &tmp);
logg("End Date: %s\n", buffer);
}
optfree(opts);
return ret;
}
void help(void)
{
mprintf_stdout = 1;
mprintf("\n");
mprintf(" Clam AntiVirus: Scanner %s\n", get_version());
printf(" By The ClamAV Team: https://www.clamav.net/about.html#credits\n");
printf(" (C) 2022 Cisco Systems, Inc.\n");
mprintf("\n");
mprintf(" clamscan [options] [file/directory/-]\n");
mprintf("\n");
mprintf(" --help -h Show this help\n");
mprintf(" --version -V Print version number\n");
mprintf(" --verbose -v Be verbose\n");
mprintf(" --archive-verbose -a Show filenames inside scanned archives\n");
mprintf(" --debug Enable libclamav's debug messages\n");
mprintf(" --quiet Only output error messages\n");
mprintf(" --stdout Write to stdout instead of stderr. Does not affect 'debug' messages.\n");
mprintf(" --no-summary Disable summary at end of scanning\n");
mprintf(" --infected -i Only print infected files\n");
mprintf(" --suppress-ok-results -o Skip printing OK files\n");
mprintf(" --bell Sound bell on virus detection\n");
mprintf("\n");
mprintf(" --tempdir=DIRECTORY Create temporary files in DIRECTORY\n");
mprintf(" --leave-temps[=yes/no(*)] Do not remove temporary files\n");
mprintf(" --gen-json[=yes/no(*)] Generate JSON description of scanned file(s). JSON will be printed and also-\n");
mprintf(" dropped to the temp directory if --leave-temps is enabled.\n");
mprintf(" --database=FILE/DIR -d FILE/DIR Load virus database from FILE or load all supported db files from DIR\n");
mprintf(" --official-db-only[=yes/no(*)] Only load official signatures\n");
mprintf(" --log=FILE -l FILE Save scan report to FILE\n");
mprintf(" --recursive[=yes/no(*)] -r Scan subdirectories recursively\n");
mprintf(" --allmatch[=yes/no(*)] -z Continue scanning within file after finding a match\n");
mprintf(" --cross-fs[=yes(*)/no] Scan files and directories on other filesystems\n");
mprintf(" --follow-dir-symlinks[=0/1(*)/2] Follow directory symlinks (0 = never, 1 = direct, 2 = always)\n");
mprintf(" --follow-file-symlinks[=0/1(*)/2] Follow file symlinks (0 = never, 1 = direct, 2 = always)\n");
mprintf(" --file-list=FILE -f FILE Scan files from FILE\n");
mprintf(" --remove[=yes/no(*)] Remove infected files. Be careful!\n");
mprintf(" --move=DIRECTORY Move infected files into DIRECTORY\n");
mprintf(" --copy=DIRECTORY Copy infected files into DIRECTORY\n");
mprintf(" --exclude=REGEX Don't scan file names matching REGEX\n");
mprintf(" --exclude-dir=REGEX Don't scan directories matching REGEX\n");
mprintf(" --include=REGEX Only scan file names matching REGEX\n");
mprintf(" --include-dir=REGEX Only scan directories matching REGEX\n");
mprintf("\n");
mprintf(" --bytecode[=yes(*)/no] Load bytecode from the database\n");
mprintf(" --bytecode-unsigned[=yes/no(*)] Load unsigned bytecode\n");
mprintf(" **Caution**: You should NEVER run bytecode signatures from untrusted sources.\n");
mprintf(" Doing so may result in arbitrary code execution.\n");
mprintf(" --bytecode-timeout=N Set bytecode timeout (in milliseconds)\n");
mprintf(" --statistics[=none(*)/bytecode/pcre] Collect and print execution statistics\n");
mprintf(" --detect-pua[=yes/no(*)] Detect Possibly Unwanted Applications\n");
mprintf(" --exclude-pua=CAT Skip PUA sigs of category CAT\n");
mprintf(" --include-pua=CAT Load PUA sigs of category CAT\n");
mprintf(" --detect-structured[=yes/no(*)] Detect structured data (SSN, Credit Card)\n");
mprintf(" --structured-ssn-format=X SSN format (0=normal,1=stripped,2=both)\n");
mprintf(" --structured-ssn-count=N Min SSN count to generate a detect\n");
mprintf(" --structured-cc-count=N Min CC count to generate a detect\n");
mprintf(" --structured-cc-mode=X CC mode (0=credit debit and private label, 1=credit cards only\n");
mprintf(" --scan-mail[=yes(*)/no] Scan mail files\n");
mprintf(" --phishing-sigs[=yes(*)/no] Enable email signature-based phishing detection\n");
mprintf(" --phishing-scan-urls[=yes(*)/no] Enable URL signature-based phishing detection\n");
mprintf(" --heuristic-alerts[=yes(*)/no] Heuristic alerts\n");
mprintf(" --heuristic-scan-precedence[=yes/no(*)] Stop scanning as soon as a heuristic match is found\n");
mprintf(" --normalize[=yes(*)/no] Normalize html, script, and text files. Use normalize=no for yara compatibility\n");
mprintf(" --scan-pe[=yes(*)/no] Scan PE files\n");
mprintf(" --scan-elf[=yes(*)/no] Scan ELF files\n");
mprintf(" --scan-ole2[=yes(*)/no] Scan OLE2 containers\n");
mprintf(" --scan-pdf[=yes(*)/no] Scan PDF files\n");
mprintf(" --scan-swf[=yes(*)/no] Scan SWF files\n");
mprintf(" --scan-html[=yes(*)/no] Scan HTML files\n");
mprintf(" --scan-xmldocs[=yes(*)/no] Scan xml-based document files\n");
mprintf(" --scan-hwp3[=yes(*)/no] Scan HWP3 files\n");
mprintf(" --scan-archive[=yes(*)/no] Scan archive files (supported by libclamav)\n");
mprintf(" --alert-broken[=yes/no(*)] Alert on broken executable files (PE & ELF)\n");
mprintf(" --alert-broken-media[=yes/no(*)] Alert on broken graphics files (JPEG, TIFF, PNG, GIF)\n");
mprintf(" --alert-encrypted[=yes/no(*)] Alert on encrypted archives and documents\n");
mprintf(" --alert-encrypted-archive[=yes/no(*)] Alert on encrypted archives\n");
mprintf(" --alert-encrypted-doc[=yes/no(*)] Alert on encrypted documents\n");
mprintf(" --alert-macros[=yes/no(*)] Alert on OLE2 files containing VBA macros\n");
mprintf(" --alert-exceeds-max[=yes/no(*)] Alert on files that exceed max file size, max scan size, or max recursion limit\n");
mprintf(" --alert-phishing-ssl[=yes/no(*)] Alert on emails containing SSL mismatches in URLs\n");
mprintf(" --alert-phishing-cloak[=yes/no(*)] Alert on emails containing cloaked URLs\n");
mprintf(" --alert-partition-intersection[=yes/no(*)] Alert on raw DMG image files containing partition intersections\n");
mprintf(" --nocerts Disable authenticode certificate chain verification in PE files\n");
mprintf(" --dumpcerts Dump authenticode certificate chain in PE files\n");
mprintf("\n");
mprintf(" --max-scantime=#n Scan time longer than this will be skipped and assumed clean (milliseconds)\n");
mprintf(" --max-filesize=#n Files larger than this will be skipped and assumed clean\n");
mprintf(" --max-scansize=#n The maximum amount of data to scan for each container file (**)\n");
mprintf(" --max-files=#n The maximum number of files to scan for each container file (**)\n");
mprintf(" --max-recursion=#n Maximum archive recursion level for container file (**)\n");
mprintf(" --max-dir-recursion=#n Maximum directory recursion level\n");
mprintf(" --max-embeddedpe=#n Maximum size file to check for embedded PE\n");
mprintf(" --max-htmlnormalize=#n Maximum size of HTML file to normalize\n");
mprintf(" --max-htmlnotags=#n Maximum size of normalized HTML file to scan\n");
mprintf(" --max-scriptnormalize=#n Maximum size of script file to normalize\n");
mprintf(" --max-ziptypercg=#n Maximum size zip to type reanalyze\n");
mprintf(" --max-partitions=#n Maximum number of partitions in disk image to be scanned\n");
mprintf(" --max-iconspe=#n Maximum number of icons in PE file to be scanned\n");
mprintf(" --max-rechwp3=#n Maximum recursive calls to HWP3 parsing function\n");
#if HAVE_PCRE
mprintf(" --pcre-match-limit=#n Maximum calls to the PCRE match function.\n");
mprintf(" --pcre-recmatch-limit=#n Maximum recursive calls to the PCRE match function.\n");
mprintf(" --pcre-max-filesize=#n Maximum size file to perform PCRE subsig matching.\n");
#endif /* HAVE_PCRE */
mprintf(" --disable-cache Disable caching and cache checks for hash sums of scanned files.\n");
mprintf("\n");
mprintf("Pass in - as the filename for stdin.\n");
mprintf("\n");
mprintf("(*) Default scan settings\n");
mprintf("(**) Certain files (e.g. documents, archives, etc.) may in turn contain other\n");
mprintf(" files inside. The above options ensure safe processing of this kind of data.\n\n");
}
Binary file not shown.
+39
View File
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Tomasz Kojm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __GLOBAL_H
#define __GLOBAL_H
struct s_info {
unsigned int sigs; /* number of signatures */
unsigned int dirs; /* number of scanned directories */
unsigned int files; /* number of scanned files */
unsigned int ifiles; /* number of infected files */
unsigned int errors; /* number of errors */
unsigned long int blocks; /* number of *scanned* 16kb blocks */
unsigned long int rblocks; /* number of *read* 16kb blocks */
};
extern struct s_info info;
extern short recursion, bell;
extern short printinfected, printclean;
#endif
+203
View File
@@ -0,0 +1,203 @@
/* 7z.h -- 7z interface
2010-03-11 : Igor Pavlov : Public domain */
#ifndef __7Z_H
#define __7Z_H
#include "7zBuf.h"
EXTERN_C_BEGIN
#define k7zStartHeaderSize 0x20
#define k7zSignatureSize 6
extern Byte k7zSignature[k7zSignatureSize];
#define k7zMajorVersion 0
enum EIdEnum
{
k7zIdEnd,
k7zIdHeader,
k7zIdArchiveProperties,
k7zIdAdditionalStreamsInfo,
k7zIdMainStreamsInfo,
k7zIdFilesInfo,
k7zIdPackInfo,
k7zIdUnpackInfo,
k7zIdSubStreamsInfo,
k7zIdSize,
k7zIdCRC,
k7zIdFolder,
k7zIdCodersUnpackSize,
k7zIdNumUnpackStream,
k7zIdEmptyStream,
k7zIdEmptyFile,
k7zIdAnti,
k7zIdName,
k7zIdCTime,
k7zIdATime,
k7zIdMTime,
k7zIdWinAttributes,
k7zIdComment,
k7zIdEncodedHeader,
k7zIdStartPos,
k7zIdDummy
};
typedef struct
{
UInt32 NumInStreams;
UInt32 NumOutStreams;
UInt64 MethodID;
CBuf Props;
} CSzCoderInfo;
void SzCoderInfo_Init(CSzCoderInfo *p);
void SzCoderInfo_Free(CSzCoderInfo *p, ISzAlloc *alloc);
typedef struct
{
UInt32 InIndex;
UInt32 OutIndex;
} CSzBindPair;
typedef struct
{
CSzCoderInfo *Coders;
CSzBindPair *BindPairs;
UInt32 *PackStreams;
UInt64 *UnpackSizes;
UInt32 NumCoders;
UInt32 NumBindPairs;
UInt32 NumPackStreams;
int UnpackCRCDefined;
UInt32 UnpackCRC;
UInt32 NumUnpackStreams;
} CSzFolder;
void SzFolder_Init(CSzFolder *p);
UInt64 SzFolder_GetUnpackSize(CSzFolder *p);
int SzFolder_FindBindPairForInStream(CSzFolder *p, UInt32 inStreamIndex);
UInt32 SzFolder_GetNumOutStreams(CSzFolder *p);
UInt64 SzFolder_GetUnpackSize(CSzFolder *p);
SRes SzFolder_Decode(const CSzFolder *folder, const UInt64 *packSizes,
ILookInStream *stream, UInt64 startPos,
Byte *outBuffer, size_t outSize, ISzAlloc *allocMain);
typedef struct
{
UInt32 Low;
UInt32 High;
} CNtfsFileTime;
typedef struct
{
CNtfsFileTime MTime;
UInt64 Size;
UInt32 Crc;
UInt32 Attrib;
Byte HasStream;
Byte IsDir;
Byte IsAnti;
Byte CrcDefined;
Byte MTimeDefined;
Byte AttribDefined;
} CSzFileItem;
void SzFile_Init(CSzFileItem *p);
typedef struct
{
UInt64 *PackSizes;
Byte *PackCRCsDefined;
UInt32 *PackCRCs;
CSzFolder *Folders;
CSzFileItem *Files;
UInt32 NumPackStreams;
UInt32 NumFolders;
UInt32 NumFiles;
} CSzAr;
void SzAr_Init(CSzAr *p);
void SzAr_Free(CSzAr *p, ISzAlloc *alloc);
/*
SzExtract extracts file from archive
*outBuffer must be 0 before first call for each new archive.
Extracting cache:
If you need to decompress more than one file, you can send
these values from previous call:
*blockIndex,
*outBuffer,
*outBufferSize
You can consider "*outBuffer" as cache of solid block. If your archive is solid,
it will increase decompression speed.
If you use external function, you can declare these 3 cache variables
(blockIndex, outBuffer, outBufferSize) as static in that external function.
Free *outBuffer and set *outBuffer to 0, if you want to flush cache.
*/
typedef struct
{
CSzAr db;
UInt64 startPosAfterHeader;
UInt64 dataPos;
UInt32 *FolderStartPackStreamIndex;
UInt64 *PackStreamStartPositions;
UInt32 *FolderStartFileIndex;
UInt32 *FileIndexToFolderIndexMap;
size_t *FileNameOffsets; /* in 2-byte steps */
CBuf FileNames; /* UTF-16-LE */
} CSzArEx;
void SzArEx_Init(CSzArEx *p);
void SzArEx_Free(CSzArEx *p, ISzAlloc *alloc);
UInt64 SzArEx_GetFolderStreamPos(const CSzArEx *p, UInt32 folderIndex, UInt32 indexInFolder);
int SzArEx_GetFolderFullPackSize(const CSzArEx *p, UInt32 folderIndex, UInt64 *resSize);
/*
if dest == NULL, the return value specifies the required size of the buffer,
in 16-bit characters, including the null-terminating character.
if dest != NULL, the return value specifies the number of 16-bit characters that
are written to the dest, including the null-terminating character. */
size_t SzArEx_GetFileNameUtf16(const CSzArEx *p, size_t fileIndex, UInt16 *dest);
SRes SzArEx_Extract(
const CSzArEx *db,
ILookInStream *inStream,
UInt32 fileIndex, /* index of file */
UInt32 *blockIndex, /* index of solid block */
Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */
size_t *outBufferSize, /* buffer size for output buffer */
size_t *offset, /* offset of stream for required file in *outBuffer */
size_t *outSizeProcessed, /* size of file in *outBuffer */
ISzAlloc *allocMain,
ISzAlloc *allocTemp);
/*
SzArEx_Open Errors:
SZ_ERROR_NO_ARCHIVE
SZ_ERROR_ARCHIVE
SZ_ERROR_UNSUPPORTED
SZ_ERROR_MEM
SZ_ERROR_CRC
SZ_ERROR_INPUT_EOF
SZ_ERROR_FAIL
*/
SRes SzArEx_Open(CSzArEx *p, ILookInStream *inStream, ISzAlloc *allocMain, ISzAlloc *allocTemp);
EXTERN_C_END
#endif
+82
View File
@@ -0,0 +1,82 @@
/* 7zAlloc.c -- Allocation functions
2010-10-29 : Igor Pavlov : Public domain */
#include "7zAlloc.h"
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
/* #define _SZ_ALLOC_DEBUG */
/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
#ifdef _SZ_ALLOC_DEBUG
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdio.h>
int g_allocCount = 0;
int g_allocCountTemp = 0;
#endif
#include "clamav.h"
void *SzAlloc(void *p, size_t size)
{
UNUSEDPARAM(p);
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc %10d bytes; count = %10d", size, g_allocCount);
g_allocCount++;
#endif
return malloc(size);
}
void SzFree(void *p, void *address)
{
UNUSEDPARAM(p);
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
{
g_allocCount--;
fprintf(stderr, "\nFree; count = %10d", g_allocCount);
}
#endif
free(address);
}
void *SzAllocTemp(void *p, size_t size)
{
UNUSEDPARAM(p);
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc_temp %10d bytes; count = %10d", size, g_allocCountTemp);
g_allocCountTemp++;
#ifdef _WIN32
return HeapAlloc(GetProcessHeap(), 0, size);
#endif
#endif
return malloc(size);
}
void SzFreeTemp(void *p, void *address)
{
UNUSEDPARAM(p);
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
{
g_allocCountTemp--;
fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp);
}
#ifdef _WIN32
HeapFree(GetProcessHeap(), 0, address);
return;
#endif
#endif
free(address);
}
+15
View File
@@ -0,0 +1,15 @@
/* 7zAlloc.h -- Allocation functions
2010-10-29 : Igor Pavlov : Public domain */
#ifndef __7Z_ALLOC_H
#define __7Z_ALLOC_H
#include <stdlib.h>
void *SzAlloc(void *p, size_t size);
void SzFree(void *p, void *address);
void *SzAllocTemp(void *p, size_t size);
void SzFreeTemp(void *p, void *address);
#endif
+36
View File
@@ -0,0 +1,36 @@
/* 7zBuf.c -- Byte Buffer
2008-03-28
Igor Pavlov
Public domain */
#include "7zBuf.h"
void Buf_Init(CBuf *p)
{
p->data = 0;
p->size = 0;
}
int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc)
{
p->size = 0;
if (size == 0)
{
p->data = 0;
return 1;
}
p->data = (Byte *)alloc->Alloc(alloc, size);
if (p->data != 0)
{
p->size = size;
return 1;
}
return 0;
}
void Buf_Free(CBuf *p, ISzAlloc *alloc)
{
alloc->Free(alloc, p->data);
p->data = 0;
p->size = 0;
}
+39
View File
@@ -0,0 +1,39 @@
/* 7zBuf.h -- Byte Buffer
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __7Z_BUF_H
#define __7Z_BUF_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
Byte *data;
size_t size;
} CBuf;
void Buf_Init(CBuf *p);
int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc);
void Buf_Free(CBuf *p, ISzAlloc *alloc);
typedef struct
{
Byte *data;
size_t size;
size_t pos;
} CDynBuf;
void DynBuf_Construct(CDynBuf *p);
void DynBuf_SeekToBeg(CDynBuf *p);
int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc);
void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc);
#ifdef __cplusplus
}
#endif
#endif
+51
View File
@@ -0,0 +1,51 @@
/* 7zBuf2.c -- Byte Buffer
2008-10-04 : Igor Pavlov : Public domain */
#include <string.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "7zBuf.h"
void DynBuf_Construct(CDynBuf *p)
{
p->data = 0;
p->size = 0;
p->pos = 0;
}
void DynBuf_SeekToBeg(CDynBuf *p)
{
p->pos = 0;
}
int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc)
{
if (size > p->size - p->pos)
{
size_t newSize = p->pos + size;
Byte *data;
newSize += newSize / 4;
data = (Byte *)alloc->Alloc(alloc, newSize);
if (data == 0)
return 0;
p->size = newSize;
memcpy(data, p->data, p->pos);
alloc->Free(alloc, p->data);
p->data = data;
}
memcpy(p->data + p->pos, buf, size);
p->pos += size;
return 1;
}
void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc)
{
alloc->Free(alloc, p->data);
p->data = 0;
p->size = 0;
p->pos = 0;
}
+27
View File
@@ -0,0 +1,27 @@
/* 7zCrc.c -- CRC32 calculation
2009-11-23 : Igor Pavlov : Public domain */
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "7zCrc.h"
#include "CpuArch.h"
const UInt32 g_CrcTable[256] = { 0x0, 0x77073096, 0xee0e612c, 0x990951ba, 0x76dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0xedb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x9b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x1db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x6b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0xf00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x86d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x3b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x4db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0xd6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0xa00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x26d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x5005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0xcb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0xbdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d };
#define CRC_UPDATE_BYTE_2(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size)
{
const Byte *p = (const Byte *)data;
for (; size > 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
return v;
}
UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size)
{
return CrcUpdate(CRC_INIT_VAL, data, size) ^ CRC_INIT_VAL;
}
+22
View File
@@ -0,0 +1,22 @@
/* 7zCrc.h -- CRC32 calculation
2009-11-21 : Igor Pavlov : Public domain */
#ifndef __7Z_CRC_H
#define __7Z_CRC_H
#include "Types.h"
EXTERN_C_BEGIN
extern const UInt32 g_CrcTable[];
#define CRC_INIT_VAL 0xFFFFFFFF
#define CRC_GET_DIGEST(crc) ((crc) ^ CRC_INIT_VAL)
#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size);
UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size);
EXTERN_C_END
#endif
+39
View File
@@ -0,0 +1,39 @@
/* 7zCrcOpt.c -- CRC32 calculation : optimized version
2009-11-23 : Igor Pavlov : Public domain */
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "CpuArch.h"
#ifdef MY_CPU_LE
#define CRC_UPDATE_BYTE_2(crc, b) (table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt32 MY_FAST_CALL CrcUpdateT4(UInt32 v, const void *data, size_t size, const UInt32 *table)
{
const Byte *p = (const Byte *)data;
for (; size > 0 && ((unsigned)(ptrdiff_t)p & 3) != 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
for (; size >= 4; size -= 4, p += 4)
{
v ^= *(const UInt32 *)p;
v =
table[0x300 + (v & 0xFF)] ^
table[0x200 + ((v >> 8) & 0xFF)] ^
table[0x100 + ((v >> 16) & 0xFF)] ^
table[0x000 + ((v >> 24))];
}
for (; size > 0; size--, p++)
v = CRC_UPDATE_BYTE_2(v, *p);
return v;
}
UInt32 MY_FAST_CALL CrcUpdateT8(UInt32 v, const void *data, size_t size, const UInt32 *table)
{
return CrcUpdateT4(v, data, size, table);
}
#endif
+481
View File
@@ -0,0 +1,481 @@
/* 7zDec.c -- Decoding from 7z folder
2010-11-02 : Igor Pavlov : Public domain */
#include <string.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#define _7ZIP_PPMD_SUPPPORT
#include "7z.h"
#include "Bcj2.h"
#include "Bra.h"
#include "CpuArch.h"
#include "LzmaDec.h"
#include "Lzma2Dec.h"
#ifdef _7ZIP_PPMD_SUPPPORT
#include "Ppmd7.h"
#endif
#define k_Copy 0
#define k_LZMA2 0x21
#define k_LZMA 0x30101
#define k_BCJ 0x03030103
#define k_PPC 0x03030205
#define k_ARM 0x03030501
#define k_ARMT 0x03030701
#define k_SPARC 0x03030805
#define k_BCJ2 0x0303011B
#ifdef _7ZIP_PPMD_SUPPPORT
#define k_PPMD 0x30401
typedef struct
{
IByteIn p;
const Byte *cur;
const Byte *end;
const Byte *begin;
UInt64 processed;
Bool extra;
SRes res;
ILookInStream *inStream;
} CByteInToLook;
static Byte ReadByte(void *pp)
{
CByteInToLook *p = (CByteInToLook *)pp;
if (p->cur != p->end)
return *p->cur++;
if (p->res == SZ_OK)
{
size_t size = p->cur - p->begin;
p->processed += size;
p->res = p->inStream->Skip(p->inStream, size);
size = (1 << 25);
p->res = p->inStream->Look(p->inStream, (const void **)&p->begin, &size);
p->cur = p->begin;
p->end = p->begin + size;
if (size != 0)
return *p->cur++;;
}
p->extra = True;
return 0;
}
static SRes SzDecodePpmd(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
{
CPpmd7 ppmd;
CByteInToLook s;
SRes res = SZ_OK;
s.p.Read = ReadByte;
s.inStream = inStream;
s.begin = s.end = s.cur = NULL;
s.extra = False;
s.res = SZ_OK;
s.processed = 0;
if (coder->Props.size != 5)
return SZ_ERROR_UNSUPPORTED;
{
unsigned order = coder->Props.data[0];
UInt32 memSize = GetUi32(coder->Props.data + 1);
if (order < PPMD7_MIN_ORDER ||
order > PPMD7_MAX_ORDER ||
memSize < PPMD7_MIN_MEM_SIZE ||
memSize > PPMD7_MAX_MEM_SIZE)
return SZ_ERROR_UNSUPPORTED;
Ppmd7_Construct(&ppmd);
if (!Ppmd7_Alloc(&ppmd, memSize, allocMain))
return SZ_ERROR_MEM;
Ppmd7_Init(&ppmd, order);
}
{
CPpmd7z_RangeDec rc;
Ppmd7z_RangeDec_CreateVTable(&rc);
rc.Stream = &s.p;
if (!Ppmd7z_RangeDec_Init(&rc))
res = SZ_ERROR_DATA;
else if (s.extra)
res = (s.res != SZ_OK ? s.res : SZ_ERROR_DATA);
else
{
SizeT i;
for (i = 0; i < outSize; i++)
{
int sym = Ppmd7_DecodeSymbol(&ppmd, &rc.p);
if (s.extra || sym < 0)
break;
outBuffer[i] = (Byte)sym;
}
if (i != outSize)
res = (s.res != SZ_OK ? s.res : SZ_ERROR_DATA);
else if (s.processed + (s.cur - s.begin) != inSize || !Ppmd7z_RangeDec_IsFinishedOK(&rc))
res = SZ_ERROR_DATA;
}
}
Ppmd7_Free(&ppmd, allocMain);
return res;
}
#endif
static SRes SzDecodeLzma(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
{
CLzmaDec state;
SRes res = SZ_OK;
LzmaDec_Construct(&state);
RINOK(LzmaDec_AllocateProbs(&state, coder->Props.data, (unsigned)coder->Props.size, allocMain));
state.dic = outBuffer;
state.dicBufSize = outSize;
LzmaDec_Init(&state);
for (;;)
{
Byte *inBuf = NULL;
size_t lookahead = (1 << 18);
if (lookahead > inSize)
lookahead = (size_t)inSize;
res = inStream->Look((void *)inStream, (const void **)&inBuf, &lookahead);
if (res != SZ_OK)
break;
{
SizeT inProcessed = (SizeT)lookahead, dicPos = state.dicPos;
ELzmaStatus status;
res = LzmaDec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
lookahead -= inProcessed;
inSize -= inProcessed;
if (res != SZ_OK)
break;
if (state.dicPos == state.dicBufSize || (inProcessed == 0 && dicPos == state.dicPos))
{
if (state.dicBufSize != outSize || lookahead != 0 ||
(status != LZMA_STATUS_FINISHED_WITH_MARK &&
status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK))
res = SZ_ERROR_DATA;
break;
}
res = inStream->Skip((void *)inStream, inProcessed);
if (res != SZ_OK)
break;
}
}
LzmaDec_FreeProbs(&state, allocMain);
return res;
}
static SRes SzDecodeLzma2(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
{
CLzma2Dec state;
SRes res = SZ_OK;
Lzma2Dec_Construct(&state);
if (coder->Props.size != 1)
return SZ_ERROR_DATA;
RINOK(Lzma2Dec_AllocateProbs(&state, coder->Props.data[0], allocMain));
state.decoder.dic = outBuffer;
state.decoder.dicBufSize = outSize;
Lzma2Dec_Init(&state);
for (;;)
{
Byte *inBuf = NULL;
size_t lookahead = (1 << 18);
if (lookahead > inSize)
lookahead = (size_t)inSize;
res = inStream->Look((void *)inStream, (const void **)&inBuf, &lookahead);
if (res != SZ_OK)
break;
{
SizeT inProcessed = (SizeT)lookahead, dicPos = state.decoder.dicPos;
ELzmaStatus status;
res = Lzma2Dec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
lookahead -= inProcessed;
inSize -= inProcessed;
if (res != SZ_OK)
break;
if (state.decoder.dicPos == state.decoder.dicBufSize || (inProcessed == 0 && dicPos == state.decoder.dicPos))
{
if (state.decoder.dicBufSize != outSize || lookahead != 0 ||
(status != LZMA_STATUS_FINISHED_WITH_MARK))
res = SZ_ERROR_DATA;
break;
}
res = inStream->Skip((void *)inStream, inProcessed);
if (res != SZ_OK)
break;
}
}
Lzma2Dec_FreeProbs(&state, allocMain);
return res;
}
static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer)
{
while (inSize > 0)
{
void *inBuf;
size_t curSize = (1 << 18);
if (curSize > inSize)
curSize = (size_t)inSize;
RINOK(inStream->Look((void *)inStream, (const void **)&inBuf, &curSize));
if (curSize == 0)
return SZ_ERROR_INPUT_EOF;
memcpy(outBuffer, inBuf, curSize);
outBuffer += curSize;
inSize -= curSize;
RINOK(inStream->Skip((void *)inStream, curSize));
}
return SZ_OK;
}
static Bool IS_MAIN_METHOD(UInt32 m)
{
switch(m)
{
case k_Copy:
case k_LZMA:
case k_LZMA2:
#ifdef _7ZIP_PPMD_SUPPPORT
case k_PPMD:
#endif
return True;
}
return False;
}
static Bool IS_SUPPORTED_CODER(const CSzCoderInfo *c)
{
return
c->NumInStreams == 1 &&
c->NumOutStreams == 1 &&
c->MethodID <= (UInt32)0xFFFFFFFF &&
IS_MAIN_METHOD((UInt32)c->MethodID);
}
#define IS_BCJ2(c) ((c)->MethodID == k_BCJ2 && (c)->NumInStreams == 4 && (c)->NumOutStreams == 1)
static SRes CheckSupportedFolder(const CSzFolder *f)
{
if (f->NumCoders < 1 || f->NumCoders > 4)
return SZ_ERROR_UNSUPPORTED;
if (f->Coders[0].MethodID == 0x06F10701) /* ACAB */
return SZ_ERROR_ENCRYPTED;
if (!IS_SUPPORTED_CODER(&f->Coders[0]))
return SZ_ERROR_UNSUPPORTED;
if (f->NumCoders == 1)
{
if (f->NumPackStreams != 1 || f->PackStreams[0] != 0 || f->NumBindPairs != 0)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
if (f->NumCoders == 2)
{
CSzCoderInfo *c = &f->Coders[1];
if (c->MethodID > (UInt32)0xFFFFFFFF ||
c->NumInStreams != 1 ||
c->NumOutStreams != 1 ||
f->NumPackStreams != 1 ||
f->PackStreams[0] != 0 ||
f->NumBindPairs != 1 ||
f->BindPairs[0].InIndex != 1 ||
f->BindPairs[0].OutIndex != 0)
return SZ_ERROR_UNSUPPORTED;
switch ((UInt32)c->MethodID)
{
case k_BCJ:
case k_ARM:
break;
default:
return SZ_ERROR_UNSUPPORTED;
}
return SZ_OK;
}
if (f->NumCoders == 4)
{
if (!IS_SUPPORTED_CODER(&f->Coders[1]) ||
!IS_SUPPORTED_CODER(&f->Coders[2]) ||
!IS_BCJ2(&f->Coders[3]))
return SZ_ERROR_UNSUPPORTED;
if (f->NumPackStreams != 4 ||
f->PackStreams[0] != 2 ||
f->PackStreams[1] != 6 ||
f->PackStreams[2] != 1 ||
f->PackStreams[3] != 0 ||
f->NumBindPairs != 3 ||
f->BindPairs[0].InIndex != 5 || f->BindPairs[0].OutIndex != 0 ||
f->BindPairs[1].InIndex != 4 || f->BindPairs[1].OutIndex != 1 ||
f->BindPairs[2].InIndex != 3 || f->BindPairs[2].OutIndex != 2)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
return SZ_ERROR_UNSUPPORTED;
}
static UInt64 GetSum(const UInt64 *values, UInt32 index)
{
UInt64 sum = 0;
UInt32 i;
for (i = 0; i < index; i++)
sum += values[i];
return sum;
}
#define CASE_BRA_CONV(isa) case k_ ## isa: isa ## _Convert(outBuffer, outSize, 0, 0); break;
static SRes SzFolder_Decode2(const CSzFolder *folder, const UInt64 *packSizes,
ILookInStream *inStream, UInt64 startPos,
Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain,
Byte *tempBuf[])
{
UInt32 ci;
SizeT tempSizes[3] = { 0, 0, 0};
SizeT tempSize3 = 0;
Byte *tempBuf3 = 0;
RINOK(CheckSupportedFolder(folder));
for (ci = 0; ci < folder->NumCoders; ci++)
{
CSzCoderInfo *coder = &folder->Coders[ci];
if (IS_MAIN_METHOD((UInt32)coder->MethodID))
{
UInt32 si = 0;
UInt64 offset;
UInt64 inSize;
Byte *outBufCur = outBuffer;
SizeT outSizeCur = outSize;
if (folder->NumCoders == 4)
{
UInt32 indices[] = { 3, 2, 0 };
UInt64 unpackSize = folder->UnpackSizes[ci];
si = indices[ci];
if (ci < 2)
{
Byte *temp;
outSizeCur = (SizeT)unpackSize;
if (outSizeCur != unpackSize)
return SZ_ERROR_MEM;
temp = (Byte *)IAlloc_Alloc(allocMain, outSizeCur);
if (temp == 0 && outSizeCur != 0)
return SZ_ERROR_MEM;
outBufCur = tempBuf[1 - ci] = temp;
tempSizes[1 - ci] = outSizeCur;
}
else if (ci == 2)
{
if (unpackSize > outSize) /* check it */
return SZ_ERROR_PARAM;
tempBuf3 = outBufCur = outBuffer + (outSize - (size_t)unpackSize);
tempSize3 = outSizeCur = (SizeT)unpackSize;
}
else
return SZ_ERROR_UNSUPPORTED;
}
if (!packSizes)
return SZ_ERROR_FAIL;
offset = GetSum(packSizes, si);
inSize = packSizes[si];
RINOK(LookInStream_SeekTo(inStream, startPos + offset));
if (coder->MethodID == k_Copy)
{
if (inSize != outSizeCur) /* check it */
return SZ_ERROR_DATA;
RINOK(SzDecodeCopy(inSize, inStream, outBufCur));
}
else if (coder->MethodID == k_LZMA)
{
RINOK(SzDecodeLzma(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
}
else if (coder->MethodID == k_LZMA2)
{
RINOK(SzDecodeLzma2(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
}
else
{
#ifdef _7ZIP_PPMD_SUPPPORT
RINOK(SzDecodePpmd(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
#else
return SZ_ERROR_UNSUPPORTED;
#endif
}
}
else if (coder->MethodID == k_BCJ2)
{
UInt64 offset = GetSum(packSizes, 1);
UInt64 s3Size = packSizes[1];
SRes res;
if (ci != 3)
return SZ_ERROR_UNSUPPORTED;
RINOK(LookInStream_SeekTo(inStream, startPos + offset));
tempSizes[2] = (SizeT)s3Size;
if (tempSizes[2] != s3Size)
return SZ_ERROR_MEM;
tempBuf[2] = (Byte *)IAlloc_Alloc(allocMain, tempSizes[2]);
if (tempBuf[2] == 0 && tempSizes[2] != 0)
return SZ_ERROR_MEM;
res = SzDecodeCopy(s3Size, inStream, tempBuf[2]);
RINOK(res)
res = Bcj2_Decode(
tempBuf3, tempSize3,
tempBuf[0], tempSizes[0],
tempBuf[1], tempSizes[1],
tempBuf[2], tempSizes[2],
outBuffer, outSize);
RINOK(res)
}
else
{
if (ci != 1)
return SZ_ERROR_UNSUPPORTED;
switch(coder->MethodID)
{
case k_BCJ:
{
UInt32 state;
x86_Convert_Init(state);
x86_Convert(outBuffer, outSize, 0, &state, 0);
break;
}
CASE_BRA_CONV(ARM)
default:
return SZ_ERROR_UNSUPPORTED;
}
}
}
return SZ_OK;
}
SRes SzFolder_Decode(const CSzFolder *folder, const UInt64 *packSizes,
ILookInStream *inStream, UInt64 startPos,
Byte *outBuffer, size_t outSize, ISzAlloc *allocMain)
{
Byte *tempBuf[3] = { 0, 0, 0};
int i;
SRes res = SzFolder_Decode2(folder, packSizes, inStream, startPos,
outBuffer, (SizeT)outSize, allocMain, tempBuf);
for (i = 0; i < 3; i++)
IAlloc_Free(allocMain, tempBuf[i]);
return res;
}
+258
View File
@@ -0,0 +1,258 @@
/* 7zFile.c -- File IO
2009-11-24 : Igor Pavlov : Public domain */
#include "7zFile.h"
#ifndef USE_WINDOWS_FILE
#ifndef UNDER_CE
#include <errno.h>
#endif
#else
/*
ReadFile and WriteFile functions in Windows have BUG:
If you Read or Write 64MB or more (probably min_failure_size = 64MB - 32KB + 1)
from/to Network file, it returns ERROR_NO_SYSTEM_RESOURCES
(Insufficient system resources exist to complete the requested service).
Probably in some version of Windows there are problems with other sizes:
for 32 MB (maybe also for 16 MB).
And message can be "Network connection was lost"
*/
#define kChunkSizeMax (1 << 22)
#endif
void File_Construct(CSzFile *p)
{
#ifdef USE_WINDOWS_FILE
p->handle = INVALID_HANDLE_VALUE;
#else
p->file = NULL;
#endif
}
#if !defined(UNDER_CE) || !defined(USE_WINDOWS_FILE)
static WRes File_Open(CSzFile *p, const char *name, int writeMode)
{
#ifdef USE_WINDOWS_FILE
p->handle = CreateFileA(name,
writeMode ? GENERIC_WRITE : GENERIC_READ,
FILE_SHARE_READ, NULL,
writeMode ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
return (p->handle != INVALID_HANDLE_VALUE) ? 0 : GetLastError();
#else
p->file = fopen(name, writeMode ? "wb+" : "rb");
return (p->file != 0) ? 0 :
#ifdef UNDER_CE
2; /* ENOENT */
#else
errno;
#endif
#endif
}
WRes InFile_Open(CSzFile *p, const char *name) { return File_Open(p, name, 0); }
WRes OutFile_Open(CSzFile *p, const char *name) { return File_Open(p, name, 1); }
#endif
#ifdef USE_WINDOWS_FILE
static WRes File_OpenW(CSzFile *p, const WCHAR *name, int writeMode)
{
p->handle = CreateFileW(name,
writeMode ? GENERIC_WRITE : GENERIC_READ,
FILE_SHARE_READ, NULL,
writeMode ? CREATE_ALWAYS : OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
return (p->handle != INVALID_HANDLE_VALUE) ? 0 : GetLastError();
}
WRes InFile_OpenW(CSzFile *p, const WCHAR *name) { return File_OpenW(p, name, 0); }
WRes OutFile_OpenW(CSzFile *p, const WCHAR *name) { return File_OpenW(p, name, 1); }
#endif
WRes File_Close(CSzFile *p)
{
#ifdef USE_WINDOWS_FILE
if (p->handle != INVALID_HANDLE_VALUE)
{
if (!CloseHandle(p->handle))
return GetLastError();
p->handle = INVALID_HANDLE_VALUE;
}
#else
if (p->file != NULL)
{
int res = fclose(p->file);
if (res != 0)
return res;
p->file = NULL;
}
#endif
return 0;
}
WRes File_Read(CSzFile *p, void *data, size_t *size)
{
size_t originalSize = *size;
if (originalSize == 0)
return 0;
#ifdef USE_WINDOWS_FILE
*size = 0;
do
{
DWORD curSize = (originalSize > kChunkSizeMax) ? kChunkSizeMax : (DWORD)originalSize;
DWORD processed = 0;
BOOL res = ReadFile(p->handle, data, curSize, &processed, NULL);
data = (void *)((Byte *)data + processed);
originalSize -= processed;
*size += processed;
if (!res)
return GetLastError();
if (processed == 0)
break;
}
while (originalSize > 0);
return 0;
#else
*size = fread(data, 1, originalSize, p->file);
if (*size == originalSize)
return 0;
return ferror(p->file);
#endif
}
WRes File_Write(CSzFile *p, const void *data, size_t *size)
{
size_t originalSize = *size;
if (originalSize == 0)
return 0;
#ifdef USE_WINDOWS_FILE
*size = 0;
do
{
DWORD curSize = (originalSize > kChunkSizeMax) ? kChunkSizeMax : (DWORD)originalSize;
DWORD processed = 0;
BOOL res = WriteFile(p->handle, data, curSize, &processed, NULL);
data = (void *)((Byte *)data + processed);
originalSize -= processed;
*size += processed;
if (!res)
return GetLastError();
if (processed == 0)
break;
}
while (originalSize > 0);
return 0;
#else
*size = fwrite(data, 1, originalSize, p->file);
if (*size == originalSize)
return 0;
return ferror(p->file);
#endif
}
WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin)
{
#ifdef USE_WINDOWS_FILE
LARGE_INTEGER value;
DWORD moveMethod;
value.LowPart = (DWORD)*pos;
value.HighPart = (LONG)((UInt64)*pos >> 16 >> 16); /* for case when UInt64 is 32-bit only */
switch (origin)
{
case SZ_SEEK_SET: moveMethod = FILE_BEGIN; break;
case SZ_SEEK_CUR: moveMethod = FILE_CURRENT; break;
case SZ_SEEK_END: moveMethod = FILE_END; break;
default: return ERROR_INVALID_PARAMETER;
}
value.LowPart = SetFilePointer(p->handle, value.LowPart, &value.HighPart, moveMethod);
if (value.LowPart == 0xFFFFFFFF)
{
WRes res = GetLastError();
if (res != NO_ERROR)
return res;
}
*pos = ((Int64)value.HighPart << 32) | value.LowPart;
return 0;
#else
int moveMethod;
int res;
switch (origin)
{
case SZ_SEEK_SET: moveMethod = SEEK_SET; break;
case SZ_SEEK_CUR: moveMethod = SEEK_CUR; break;
case SZ_SEEK_END: moveMethod = SEEK_END; break;
default: return 1;
}
res = fseek(p->file, (long)*pos, moveMethod);
*pos = ftell(p->file);
return res;
#endif
}
/* ---------- FileSeqInStream ---------- */
static SRes FileSeqInStream_Read(void *pp, void *buf, size_t *size)
{
CFileSeqInStream *p = (CFileSeqInStream *)pp;
return File_Read(&p->file, buf, size) == 0 ? SZ_OK : SZ_ERROR_READ;
}
void FileSeqInStream_CreateVTable(CFileSeqInStream *p)
{
p->s.Read = FileSeqInStream_Read;
}
/* ---------- FileInStream ---------- */
static SRes FileInStream_Read(void *pp, void *buf, size_t *size)
{
CFileInStream *p = (CFileInStream *)pp;
return (File_Read(&p->file, buf, size) == 0) ? SZ_OK : SZ_ERROR_READ;
}
static SRes FileInStream_Seek(void *pp, Int64 *pos, ESzSeek origin)
{
CFileInStream *p = (CFileInStream *)pp;
return File_Seek(&p->file, pos, origin);
}
void FileInStream_CreateVTable(CFileInStream *p)
{
p->s.Read = FileInStream_Read;
p->s.Seek = FileInStream_Seek;
}
/* ---------- FileOutStream ---------- */
static size_t FileOutStream_Write(void *pp, const void *data, size_t size)
{
CFileOutStream *p = (CFileOutStream *)pp;
File_Write(&p->file, data, &size);
return size;
}
void FileOutStream_CreateVTable(CFileOutStream *p)
{
p->s.Write = FileOutStream_Write;
}
+83
View File
@@ -0,0 +1,83 @@
/* 7zFile.h -- File IO
2009-11-24 : Igor Pavlov : Public domain */
#ifndef __7Z_FILE_H
#define __7Z_FILE_H
#ifdef _WIN32
#define USE_WINDOWS_FILE
#endif
#ifdef USE_WINDOWS_FILE
#include <windows.h>
#else
#include <stdio.h>
#endif
#include "Types.h"
EXTERN_C_BEGIN
/* ---------- File ---------- */
typedef struct
{
#ifdef USE_WINDOWS_FILE
HANDLE handle;
#else
FILE *file;
#endif
fmap_t *fmap;
} CSzFile;
void File_Construct(CSzFile *p);
#if !defined(UNDER_CE) || !defined(USE_WINDOWS_FILE)
WRes InFile_Open(CSzFile *p, const char *name);
WRes OutFile_Open(CSzFile *p, const char *name);
#endif
#ifdef USE_WINDOWS_FILE
WRes InFile_OpenW(CSzFile *p, const WCHAR *name);
WRes OutFile_OpenW(CSzFile *p, const WCHAR *name);
#endif
WRes File_Close(CSzFile *p);
/* reads max(*size, remain file's size) bytes */
WRes File_Read(CSzFile *p, void *data, size_t *size);
/* writes *size bytes */
WRes File_Write(CSzFile *p, const void *data, size_t *size);
WRes File_Seek(CSzFile *p, Int64 *pos, ESzSeek origin);
/* ---------- FileInStream ---------- */
typedef struct
{
ISeqInStream s;
CSzFile file;
} CFileSeqInStream;
void FileSeqInStream_CreateVTable(CFileSeqInStream *p);
typedef struct
{
ISeekInStream s;
CSzFile file;
} CFileInStream;
void FileInStream_CreateVTable(CFileInStream *p);
typedef struct
{
ISeqOutStream s;
CSzFile file;
} CFileOutStream;
void FileOutStream_CreateVTable(CFileOutStream *p);
EXTERN_C_END
#endif
File diff suppressed because it is too large Load Diff
+169
View File
@@ -0,0 +1,169 @@
/* 7zStream.c -- 7z Stream functions
2010-03-11 : Igor Pavlov : Public domain */
#include <string.h>
#include "Types.h"
SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType)
{
while (size != 0)
{
size_t processed = size;
RINOK(stream->Read(stream, buf, &processed));
if (processed == 0)
return errorType;
buf = (void *)((Byte *)buf + processed);
size -= processed;
}
return SZ_OK;
}
SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size)
{
return SeqInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
}
SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf)
{
size_t processed = 1;
RINOK(stream->Read(stream, buf, &processed));
return (processed == 1) ? SZ_OK : SZ_ERROR_INPUT_EOF;
}
SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset)
{
Int64 t = offset;
return stream->Seek(stream, &t, SZ_SEEK_SET);
}
SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size)
{
const void *lookBuf;
if (*size == 0)
return SZ_OK;
RINOK(stream->Look(stream, &lookBuf, size));
memcpy(buf, lookBuf, *size);
return stream->Skip(stream, *size);
}
SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType)
{
while (size != 0)
{
size_t processed = size;
RINOK(stream->Read(stream, buf, &processed));
if (processed == 0)
return errorType;
buf = (void *)((Byte *)buf + processed);
size -= processed;
}
return SZ_OK;
}
SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size)
{
return LookInStream_Read2(stream, buf, size, SZ_ERROR_INPUT_EOF);
}
static SRes LookToRead_Look_Lookahead(void *pp, const void **buf, size_t *size)
{
SRes res = SZ_OK;
CLookToRead *p = (CLookToRead *)pp;
size_t size2 = p->size - p->pos;
if (size2 == 0 && *size > 0)
{
p->pos = 0;
size2 = LookToRead_BUF_SIZE;
res = p->realStream->Read(p->realStream, p->buf, &size2);
p->size = size2;
}
if (size2 < *size)
*size = size2;
*buf = p->buf + p->pos;
return res;
}
static SRes LookToRead_Look_Exact(void *pp, const void **buf, size_t *size)
{
SRes res = SZ_OK;
CLookToRead *p = (CLookToRead *)pp;
size_t size2 = p->size - p->pos;
if (size2 == 0 && *size > 0)
{
p->pos = 0;
if (*size > LookToRead_BUF_SIZE)
*size = LookToRead_BUF_SIZE;
res = p->realStream->Read(p->realStream, p->buf, size);
size2 = p->size = *size;
}
if (size2 < *size)
*size = size2;
*buf = p->buf + p->pos;
return res;
}
static SRes LookToRead_Skip(void *pp, size_t offset)
{
CLookToRead *p = (CLookToRead *)pp;
p->pos += offset;
return SZ_OK;
}
static SRes LookToRead_Read(void *pp, void *buf, size_t *size)
{
CLookToRead *p = (CLookToRead *)pp;
size_t rem = p->size - p->pos;
if (rem == 0)
return p->realStream->Read(p->realStream, buf, size);
if (rem > *size)
rem = *size;
memcpy(buf, p->buf + p->pos, rem);
p->pos += rem;
*size = rem;
return SZ_OK;
}
static SRes LookToRead_Seek(void *pp, Int64 *pos, ESzSeek origin)
{
CLookToRead *p = (CLookToRead *)pp;
p->pos = p->size = 0;
return p->realStream->Seek(p->realStream, pos, origin);
}
void LookToRead_CreateVTable(CLookToRead *p, int lookahead)
{
p->s.Look = lookahead ?
LookToRead_Look_Lookahead :
LookToRead_Look_Exact;
p->s.Skip = LookToRead_Skip;
p->s.Read = LookToRead_Read;
p->s.Seek = LookToRead_Seek;
}
void LookToRead_Init(CLookToRead *p)
{
p->pos = p->size = 0;
}
static SRes SecToLook_Read(void *pp, void *buf, size_t *size)
{
CSecToLook *p = (CSecToLook *)pp;
return LookInStream_LookRead(p->realStream, buf, size);
}
void SecToLook_CreateVTable(CSecToLook *p)
{
p->s.Read = SecToLook_Read;
}
static SRes SecToRead_Read(void *pp, void *buf, size_t *size)
{
CSecToRead *p = (CSecToRead *)pp;
return p->realStream->Read(p->realStream, buf, size);
}
void SecToRead_CreateVTable(CSecToRead *p)
{
p->s.Read = SecToRead_Read;
}
+7
View File
@@ -0,0 +1,7 @@
#define MY_VER_MAJOR 9
#define MY_VER_MINOR 20
#define MY_VER_BUILD 0
#define MY_VERSION "9.20"
#define MY_DATE "2010-11-18"
#define MY_COPYRIGHT ": Igor Pavlov : Public domain"
#define MY_VERSION_COPYRIGHT_DATE MY_VERSION " " MY_COPYRIGHT " : " MY_DATE
+38
View File
@@ -0,0 +1,38 @@
/* Alloc.h -- Memory allocation functions
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __COMMON_ALLOC_H
#define __COMMON_ALLOC_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void *MyAlloc(size_t size);
void MyFree(void *address);
#ifdef _WIN32
void SetLargePageSize();
void *MidAlloc(size_t size);
void MidFree(void *address);
void *BigAlloc(size_t size);
void BigFree(void *address);
#else
#define MidAlloc(size) MyAlloc(size)
#define MidFree(address) MyFree(address)
#define BigAlloc(size) MyAlloc(size)
#define BigFree(address) MyFree(address)
#endif
#ifdef __cplusplus
}
#endif
#endif
+132
View File
@@ -0,0 +1,132 @@
/* Bcj2.c -- Converter for x86 code (BCJ2)
2008-10-04 : Igor Pavlov : Public domain */
#include "Bcj2.h"
#ifdef _LZMA_PROB32
#define CProb UInt32
#else
#define CProb UInt16
#endif
#define IsJcc(b0, b1) ((b0) == 0x0F && ((b1) & 0xF0) == 0x80)
#define IsJ(b0, b1) ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1))
#define kNumTopBits 24
#define kTopValue ((UInt32)1 << kNumTopBits)
#define kNumBitModelTotalBits 11
#define kBitModelTotal (1 << kNumBitModelTotalBits)
#define kNumMoveBits 5
#define RC_READ_BYTE (*buffer++)
#define RC_TEST { if (buffer == bufferLim) return SZ_ERROR_DATA; }
#define RC_INIT2 code = 0; range = 0xFFFFFFFF; \
{ int i; for (i = 0; i < 5; i++) { RC_TEST; code = (code << 8) | RC_READ_BYTE; }}
#define NORMALIZE if (range < kTopValue) { RC_TEST; range <<= 8; code = (code << 8) | RC_READ_BYTE; }
#define IF_BIT_0(p) ttt = *(p); bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound)
#define UPDATE_0(p) range = bound; *(p) = (CProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); NORMALIZE;
#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CProb)(ttt - (ttt >> kNumMoveBits)); NORMALIZE;
int Bcj2_Decode(
const Byte *buf0, SizeT size0,
const Byte *buf1, SizeT size1,
const Byte *buf2, SizeT size2,
const Byte *buf3, SizeT size3,
Byte *outBuf, SizeT outSize)
{
CProb p[256 + 2];
SizeT inPos = 0, outPos = 0;
const Byte *buffer, *bufferLim;
UInt32 range, code;
Byte prevByte = 0;
unsigned int i;
for (i = 0; i < sizeof(p) / sizeof(p[0]); i++)
p[i] = kBitModelTotal >> 1;
buffer = buf3;
bufferLim = buffer + size3;
RC_INIT2
if (outSize == 0)
return SZ_OK;
for (;;)
{
Byte b;
CProb *prob;
UInt32 bound;
UInt32 ttt;
SizeT limit = size0 - inPos;
if (outSize - outPos < limit)
limit = outSize - outPos;
while (limit != 0)
{
Byte b = buf0[inPos];
outBuf[outPos++] = b;
if (IsJ(prevByte, b))
break;
inPos++;
prevByte = b;
limit--;
}
if (limit == 0 || outPos == outSize)
break;
b = buf0[inPos++];
if (b == 0xE8)
prob = p + prevByte;
else if (b == 0xE9)
prob = p + 256;
else
prob = p + 257;
IF_BIT_0(prob)
{
UPDATE_0(prob)
prevByte = b;
}
else
{
UInt32 dest;
const Byte *v;
UPDATE_1(prob)
if (b == 0xE8)
{
v = buf1;
if (size1 < 4)
return SZ_ERROR_DATA;
buf1 += 4;
size1 -= 4;
}
else
{
v = buf2;
if (size2 < 4)
return SZ_ERROR_DATA;
buf2 += 4;
size2 -= 4;
}
dest = (((UInt32)v[0] << 24) | ((UInt32)v[1] << 16) |
((UInt32)v[2] << 8) | ((UInt32)v[3])) - ((UInt32)outPos + 4);
outBuf[outPos++] = (Byte)dest;
if (outPos == outSize)
break;
outBuf[outPos++] = (Byte)(dest >> 8);
if (outPos == outSize)
break;
outBuf[outPos++] = (Byte)(dest >> 16);
if (outPos == outSize)
break;
outBuf[outPos++] = prevByte = (Byte)(dest >> 24);
}
}
return (outPos == outSize) ? SZ_OK : SZ_ERROR_DATA;
}
+38
View File
@@ -0,0 +1,38 @@
/* Bcj2.h -- Converter for x86 code (BCJ2)
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __BCJ2_H
#define __BCJ2_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
Conditions:
outSize <= FullOutputSize,
where FullOutputSize is full size of output stream of x86_2 filter.
If buf0 overlaps outBuf, there are two required conditions:
1) (buf0 >= outBuf)
2) (buf0 + size0 >= outBuf + FullOutputSize).
Returns:
SZ_OK
SZ_ERROR_DATA - Data error
*/
int Bcj2_Decode(
const Byte *buf0, SizeT size0,
const Byte *buf1, SizeT size1,
const Byte *buf2, SizeT size2,
const Byte *buf3, SizeT size3,
Byte *outBuf, SizeT outSize);
#ifdef __cplusplus
}
#endif
#endif
+133
View File
@@ -0,0 +1,133 @@
/* Bra.c -- Converters for RISC code
2010-04-16 : Igor Pavlov : Public domain */
#include "Bra.h"
SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 4)
return 0;
size -= 4;
ip += 8;
for (i = 0; i <= size; i += 4)
{
if (data[i + 3] == 0xEB)
{
UInt32 dest;
UInt32 src = ((UInt32)data[i + 2] << 16) | ((UInt32)data[i + 1] << 8) | (data[i + 0]);
src <<= 2;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
dest >>= 2;
data[i + 2] = (Byte)(dest >> 16);
data[i + 1] = (Byte)(dest >> 8);
data[i + 0] = (Byte)dest;
}
}
return i;
}
SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 4)
return 0;
size -= 4;
ip += 4;
for (i = 0; i <= size; i += 2)
{
if ((data[i + 1] & 0xF8) == 0xF0 &&
(data[i + 3] & 0xF8) == 0xF8)
{
UInt32 dest;
UInt32 src =
(((UInt32)data[i + 1] & 0x7) << 19) |
((UInt32)data[i + 0] << 11) |
(((UInt32)data[i + 3] & 0x7) << 8) |
(data[i + 2]);
src <<= 1;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
dest >>= 1;
data[i + 1] = (Byte)(0xF0 | ((dest >> 19) & 0x7));
data[i + 0] = (Byte)(dest >> 11);
data[i + 3] = (Byte)(0xF8 | ((dest >> 8) & 0x7));
data[i + 2] = (Byte)dest;
i += 2;
}
}
return i;
}
SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 4)
return 0;
size -= 4;
for (i = 0; i <= size; i += 4)
{
if ((data[i] >> 2) == 0x12 && (data[i + 3] & 3) == 1)
{
UInt32 src = ((UInt32)(data[i + 0] & 3) << 24) |
((UInt32)data[i + 1] << 16) |
((UInt32)data[i + 2] << 8) |
((UInt32)data[i + 3] & (~3));
UInt32 dest;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
data[i + 0] = (Byte)(0x48 | ((dest >> 24) & 0x3));
data[i + 1] = (Byte)(dest >> 16);
data[i + 2] = (Byte)(dest >> 8);
data[i + 3] &= 0x3;
data[i + 3] |= dest;
}
}
return i;
}
SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
{
UInt32 i;
if (size < 4)
return 0;
size -= 4;
for (i = 0; i <= size; i += 4)
{
if ((data[i] == 0x40 && (data[i + 1] & 0xC0) == 0x00) ||
(data[i] == 0x7F && (data[i + 1] & 0xC0) == 0xC0))
{
UInt32 src =
((UInt32)data[i + 0] << 24) |
((UInt32)data[i + 1] << 16) |
((UInt32)data[i + 2] << 8) |
((UInt32)data[i + 3]);
UInt32 dest;
src <<= 2;
if (encoding)
dest = ip + i + src;
else
dest = src - (ip + i);
dest >>= 2;
dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000;
data[i + 0] = (Byte)(dest >> 24);
data[i + 1] = (Byte)(dest >> 16);
data[i + 2] = (Byte)(dest >> 8);
data[i + 3] = (Byte)dest;
}
}
return i;
}
+68
View File
@@ -0,0 +1,68 @@
/* Bra.h -- Branch converters for executables
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __BRA_H
#define __BRA_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
These functions convert relative addresses to absolute addresses
in CALL instructions to increase the compression ratio.
In:
data - data buffer
size - size of data
ip - current virtual Instruction Pinter (IP) value
state - state variable for x86 converter
encoding - 0 (for decoding), 1 (for encoding)
Out:
state - state variable for x86 converter
Returns:
The number of processed bytes. If you call these functions with multiple calls,
you must start next call with first byte after block of processed bytes.
Type Endian Alignment LookAhead
x86 little 1 4
ARMT little 2 2
ARM little 4 0
PPC big 4 0
SPARC big 4 0
IA64 little 16 0
size must be >= Alignment + LookAhead, if it's not last block.
If (size < Alignment + LookAhead), converter returns 0.
Example:
UInt32 ip = 0;
for ()
{
; size must be >= Alignment + LookAhead, if it's not last block
SizeT processed = Convert(data, size, ip, 1);
data += processed;
size -= processed;
ip += processed;
}
*/
#define x86_Convert_Init(state) { state = 0; }
SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding);
SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
#ifdef __cplusplus
}
#endif
#endif
+85
View File
@@ -0,0 +1,85 @@
/* Bra86.c -- Converter for x86 code (BCJ)
2008-10-04 : Igor Pavlov : Public domain */
#include "Bra.h"
#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
const Byte kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0};
const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3};
SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding)
{
SizeT bufferPos = 0, prevPosT;
UInt32 prevMask = *state & 0x7;
if (size < 5)
return 0;
ip += 5;
prevPosT = (SizeT)0 - 1;
for (;;)
{
Byte *p = data + bufferPos;
Byte *limit = data + size - 4;
for (; p < limit; p++)
if ((*p & 0xFE) == 0xE8)
break;
bufferPos = (SizeT)(p - data);
if (p >= limit)
break;
prevPosT = bufferPos - prevPosT;
if (prevPosT > 3)
prevMask = 0;
else
{
prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7;
if (prevMask != 0)
{
Byte b = p[4 - kMaskToBitNumber[prevMask]];
if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b))
{
prevPosT = bufferPos;
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
continue;
}
}
}
prevPosT = bufferPos;
if (Test86MSByte(p[4]))
{
UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]);
UInt32 dest;
for (;;)
{
Byte b;
int index;
if (encoding)
dest = (ip + (UInt32)bufferPos) + src;
else
dest = src - (ip + (UInt32)bufferPos);
if (prevMask == 0)
break;
index = kMaskToBitNumber[prevMask] * 8;
b = (Byte)(dest >> (24 - index));
if (!Test86MSByte(b))
break;
src = dest ^ ((1 << (32 - index)) - 1);
}
p[4] = (Byte)(~(((dest >> 24) & 1) - 1));
p[3] = (Byte)(dest >> 16);
p[2] = (Byte)(dest >> 8);
p[1] = (Byte)dest;
bufferPos += 5;
}
else
{
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
}
}
prevPosT = bufferPos - prevPosT;
*state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7));
return bufferPos;
}
+67
View File
@@ -0,0 +1,67 @@
/* BraIA64.c -- Converter for IA-64 code
2008-10-04 : Igor Pavlov : Public domain */
#include "Bra.h"
static const Byte kBranchTable[32] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 4, 6, 6, 0, 0, 7, 7,
4, 4, 0, 0, 4, 4, 0, 0
};
SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
{
SizeT i;
if (size < 16)
return 0;
size -= 16;
for (i = 0; i <= size; i += 16)
{
UInt32 instrTemplate = data[i] & 0x1F;
UInt32 mask = kBranchTable[instrTemplate];
UInt32 bitPos = 5;
int slot;
for (slot = 0; slot < 3; slot++, bitPos += 41)
{
UInt32 bytePos, bitRes;
UInt64 instruction, instNorm;
int j;
if (((mask >> slot) & 1) == 0)
continue;
bytePos = (bitPos >> 3);
bitRes = bitPos & 0x7;
instruction = 0;
for (j = 0; j < 6; j++)
instruction += (UInt64)data[i + j + bytePos] << (8 * j);
instNorm = instruction >> bitRes;
if (((instNorm >> 37) & 0xF) == 0x5 && ((instNorm >> 9) & 0x7) == 0)
{
UInt32 src = (UInt32)((instNorm >> 13) & 0xFFFFF);
UInt32 dest;
src |= ((UInt32)(instNorm >> 36) & 1) << 20;
src <<= 4;
if (encoding)
dest = ip + (UInt32)i + src;
else
dest = src - (ip + (UInt32)i);
dest >>= 4;
instNorm &= ~((UInt64)(0x8FFFFF) << 13);
instNorm |= ((UInt64)(dest & 0xFFFFF) << 13);
instNorm |= ((UInt64)(dest & 0x100000) << (36 - 20));
instruction &= (1 << bitRes) - 1;
instruction |= (instNorm << bitRes);
for (j = 0; j < 6; j++)
data[i + j + bytePos] = (Byte)(instruction >> (8 * j));
}
}
}
return i;
}
+173
View File
@@ -0,0 +1,173 @@
/* CpuArch.c -- CPU specific code
2010-10-26: Igor Pavlov : Public domain */
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "CpuArch.h"
#ifdef MY_CPU_X86_OR_AMD64
#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__)
#define USE_ASM
#endif
#if defined(USE_ASM) && !defined(MY_CPU_AMD64)
static UInt32 CheckFlag(UInt32 flag)
{
#ifdef _MSC_VER
__asm pushfd;
__asm pop EAX;
__asm mov EDX, EAX;
__asm xor EAX, flag;
__asm push EAX;
__asm popfd;
__asm pushfd;
__asm pop EAX;
__asm xor EAX, EDX;
__asm push EDX;
__asm popfd;
__asm and flag, EAX;
#else
__asm__ __volatile__ (
"pushf\n\t"
"pop %%EAX\n\t"
"movl %%EAX,%%EDX\n\t"
"xorl %0,%%EAX\n\t"
"push %%EAX\n\t"
"popf\n\t"
"pushf\n\t"
"pop %%EAX\n\t"
"xorl %%EDX,%%EAX\n\t"
"push %%EDX\n\t"
"popf\n\t"
"andl %%EAX, %0\n\t":
"=c" (flag) : "c" (flag));
#endif
return flag;
}
#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return False;
#else
#define CHECK_CPUID_IS_SUPPORTED
#endif
static void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d)
{
#ifdef USE_ASM
#ifdef _MSC_VER
UInt32 a2, b2, c2, d2;
__asm xor EBX, EBX;
__asm xor ECX, ECX;
__asm xor EDX, EDX;
__asm mov EAX, function;
__asm cpuid;
__asm mov a2, EAX;
__asm mov b2, EBX;
__asm mov c2, ECX;
__asm mov d2, EDX;
*a = a2;
*b = b2;
*c = c2;
*d = d2;
#else
__asm__ __volatile__ (
"cpuid"
: "=a" (*a) ,
"=b" (*b) ,
"=c" (*c) ,
"=d" (*d)
: "0" (function)) ;
#endif
#else
int CPUInfo[4];
__cpuid(CPUInfo, function);
*a = CPUInfo[0];
*b = CPUInfo[1];
*c = CPUInfo[2];
*d = CPUInfo[3];
#endif
}
Bool x86cpuid_CheckAndRead(Cx86cpuid *p)
{
CHECK_CPUID_IS_SUPPORTED
MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]);
MyCPUID(1, &p->ver, &p->b, &p->c, &p->d);
return True;
}
static UInt32 kVendors[][3] =
{
{ 0x756E6547, 0x49656E69, 0x6C65746E},
{ 0x68747541, 0x69746E65, 0x444D4163},
{ 0x746E6543, 0x48727561, 0x736C7561}
};
int x86cpuid_GetFirm(const Cx86cpuid *p)
{
unsigned i;
for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++)
{
const UInt32 *v = kVendors[i];
if (v[0] == p->vendor[0] &&
v[1] == p->vendor[1] &&
v[2] == p->vendor[2])
return (int)i;
}
return -1;
}
Bool CPU_Is_InOrder()
{
Cx86cpuid p;
int firm;
UInt32 family, model;
if (!x86cpuid_CheckAndRead(&p))
return True;
family = x86cpuid_GetFamily(&p);
model = x86cpuid_GetModel(&p);
firm = x86cpuid_GetFirm(&p);
switch (firm)
{
case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && model == 0x100C));
case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA)));
case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF));
}
return True;
}
#if !defined(MY_CPU_AMD64) && defined(_WIN32)
static Bool CPU_Sys_Is_SSE_Supported()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(vi);
if (!GetVersionEx(&vi))
return False;
return (vi.dwMajorVersion >= 5);
}
#define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False;
#else
#define CHECK_SYS_SSE_SUPPORT
#endif
Bool CPU_Is_Aes_Supported()
{
Cx86cpuid p;
CHECK_SYS_SSE_SUPPORT
if (!x86cpuid_CheckAndRead(&p))
return False;
return (p.c >> 25) & 1;
}
#endif
+37
View File
@@ -0,0 +1,37 @@
/* CpuArch.h -- CPU specific code
2010-10-26: Igor Pavlov : Public domain */
#ifndef __CPU_ARCH_H
#define __CPU_ARCH_H
#include "Types.h"
#include "others.h"
EXTERN_C_BEGIN
/*
MY_CPU_LE means that CPU is LITTLE ENDIAN.
If MY_CPU_LE is not defined, we don't know about that property of platform (it can be LITTLE ENDIAN).
MY_CPU_LE_UNALIGN means that CPU is LITTLE ENDIAN and CPU supports unaligned memory accesses.
If MY_CPU_LE_UNALIGN is not defined, we don't know about these properties of platform.
*/
#define GetUi16(p) (cli_readint16(p))
#define GetUi32(p) (cli_readint32(p))
#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32))
#define SetUi16(p, d) { UInt32 _x_ = (d); \
((Byte *)(p))[0] = (Byte)_x_; \
((Byte *)(p))[1] = (Byte)(_x_ >> 8); }
#define SetUi32(p, d) (cli_writeint32(p, d))
#define SetUi64(p, d) { UInt64 _x64_ = (d); \
SetUi32(p, (UInt32)_x64_); \
SetUi32(((Byte *)(p)) + 4, (UInt32)(_x64_ >> 32)); }
#define GetBe16(p) (((UInt16)((const Byte *)(p))[0] << 8) | ((const Byte *)(p))[1])
#endif
+62
View File
@@ -0,0 +1,62 @@
/* Delta.c -- Delta converter
2009-05-26 : Igor Pavlov : Public domain */
#include "Delta.h"
void Delta_Init(Byte *state)
{
unsigned i;
for (i = 0; i < DELTA_STATE_SIZE; i++)
state[i] = 0;
}
static void MyMemCpy(Byte *dest, const Byte *src, unsigned size)
{
unsigned i;
for (i = 0; i < size; i++)
dest[i] = src[i];
}
void Delta_Encode(Byte *state, unsigned delta, Byte *data, SizeT size)
{
Byte buf[DELTA_STATE_SIZE];
unsigned j = 0;
MyMemCpy(buf, state, delta);
{
SizeT i;
for (i = 0; i < size;)
{
for (j = 0; j < delta && i < size; i++, j++)
{
Byte b = data[i];
data[i] = (Byte)(b - buf[j]);
buf[j] = b;
}
}
}
if (j == delta)
j = 0;
MyMemCpy(state, buf + j, delta - j);
MyMemCpy(state + delta - j, buf, j);
}
void Delta_Decode(Byte *state, unsigned delta, Byte *data, SizeT size)
{
Byte buf[DELTA_STATE_SIZE];
unsigned j = 0;
MyMemCpy(buf, state, delta);
{
SizeT i;
for (i = 0; i < size;)
{
for (j = 0; j < delta && i < size; i++, j++)
{
buf[j] = data[i] = (Byte)(buf[j] + data[i]);
}
}
}
if (j == delta)
j = 0;
MyMemCpy(state, buf + j, delta - j);
MyMemCpy(state + delta - j, buf, j);
}
+23
View File
@@ -0,0 +1,23 @@
/* Delta.h -- Delta converter
2009-04-15 : Igor Pavlov : Public domain */
#ifndef __DELTA_H
#define __DELTA_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define DELTA_STATE_SIZE 256
void Delta_Init(Byte *state);
void Delta_Encode(Byte *state, unsigned delta, Byte *data, SizeT size);
void Delta_Decode(Byte *state, unsigned delta, Byte *data, SizeT size);
#ifdef __cplusplus
}
#endif
#endif
+356
View File
@@ -0,0 +1,356 @@
/* Lzma2Dec.c -- LZMA2 Decoder
2009-05-03 : Igor Pavlov : Public domain */
/* #define SHOW_DEBUG_INFO */
#ifdef SHOW_DEBUG_INFO
#include <stdio.h>
#endif
#include <string.h>
#include "Lzma2Dec.h"
/*
00000000 - EOS
00000001 U U - Uncompressed Reset Dic
00000010 U U - Uncompressed No Reset
100uuuuu U U P P - LZMA no reset
101uuuuu U U P P - LZMA reset state
110uuuuu U U P P S - LZMA reset state + new prop
111uuuuu U U P P S - LZMA reset state + new prop + reset dic
u, U - Unpack Size
P - Pack Size
S - Props
*/
#define LZMA2_CONTROL_LZMA (1 << 7)
#define LZMA2_CONTROL_COPY_NO_RESET 2
#define LZMA2_CONTROL_COPY_RESET_DIC 1
#define LZMA2_CONTROL_EOF 0
#define LZMA2_IS_UNCOMPRESSED_STATE(p) (((p)->control & LZMA2_CONTROL_LZMA) == 0)
#define LZMA2_GET_LZMA_MODE(p) (((p)->control >> 5) & 3)
#define LZMA2_IS_THERE_PROP(mode) ((mode) >= 2)
#define LZMA2_LCLP_MAX 4
#define LZMA2_DIC_SIZE_FROM_PROP(p) (((UInt32)2 | ((p) & 1)) << ((p) / 2 + 11))
#ifdef SHOW_DEBUG_INFO
#define PRF(x) x
#else
#define PRF(x)
#endif
typedef enum
{
LZMA2_STATE_CONTROL,
LZMA2_STATE_UNPACK0,
LZMA2_STATE_UNPACK1,
LZMA2_STATE_PACK0,
LZMA2_STATE_PACK1,
LZMA2_STATE_PROP,
LZMA2_STATE_DATA,
LZMA2_STATE_DATA_CONT,
LZMA2_STATE_FINISHED,
LZMA2_STATE_ERROR
} ELzma2State;
static SRes Lzma2Dec_GetOldProps(Byte prop, Byte *props)
{
UInt32 dicSize;
if (prop > 40)
return SZ_ERROR_UNSUPPORTED;
dicSize = (prop == 40) ? 0xFFFFFFFF : LZMA2_DIC_SIZE_FROM_PROP(prop);
props[0] = (Byte)LZMA2_LCLP_MAX;
props[1] = (Byte)(dicSize);
props[2] = (Byte)(dicSize >> 8);
props[3] = (Byte)(dicSize >> 16);
props[4] = (Byte)(dicSize >> 24);
return SZ_OK;
}
SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAlloc *alloc)
{
Byte props[LZMA_PROPS_SIZE];
RINOK(Lzma2Dec_GetOldProps(prop, props));
return LzmaDec_AllocateProbs(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
}
SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAlloc *alloc)
{
Byte props[LZMA_PROPS_SIZE];
RINOK(Lzma2Dec_GetOldProps(prop, props));
return LzmaDec_Allocate(&p->decoder, props, LZMA_PROPS_SIZE, alloc);
}
void Lzma2Dec_Init(CLzma2Dec *p)
{
p->state = LZMA2_STATE_CONTROL;
p->needInitDic = True;
p->needInitState = True;
p->needInitProp = True;
LzmaDec_Init(&p->decoder);
}
static ELzma2State Lzma2Dec_UpdateState(CLzma2Dec *p, Byte b)
{
switch(p->state)
{
case LZMA2_STATE_CONTROL:
p->control = b;
PRF(printf("\n %4X ", p->decoder.dicPos));
PRF(printf(" %2X", b));
if (p->control == 0)
return LZMA2_STATE_FINISHED;
if (LZMA2_IS_UNCOMPRESSED_STATE(p))
{
if ((p->control & 0x7F) > 2)
return LZMA2_STATE_ERROR;
p->unpackSize = 0;
}
else
p->unpackSize = (UInt32)(p->control & 0x1F) << 16;
return LZMA2_STATE_UNPACK0;
case LZMA2_STATE_UNPACK0:
p->unpackSize |= (UInt32)b << 8;
return LZMA2_STATE_UNPACK1;
case LZMA2_STATE_UNPACK1:
p->unpackSize |= (UInt32)b;
p->unpackSize++;
PRF(printf(" %8d", p->unpackSize));
return (LZMA2_IS_UNCOMPRESSED_STATE(p)) ? LZMA2_STATE_DATA : LZMA2_STATE_PACK0;
case LZMA2_STATE_PACK0:
p->packSize = (UInt32)b << 8;
return LZMA2_STATE_PACK1;
case LZMA2_STATE_PACK1:
p->packSize |= (UInt32)b;
p->packSize++;
PRF(printf(" %8d", p->packSize));
return LZMA2_IS_THERE_PROP(LZMA2_GET_LZMA_MODE(p)) ? LZMA2_STATE_PROP:
(p->needInitProp ? LZMA2_STATE_ERROR : LZMA2_STATE_DATA);
case LZMA2_STATE_PROP:
{
int lc, lp;
if (b >= (9 * 5 * 5))
return LZMA2_STATE_ERROR;
lc = b % 9;
b /= 9;
p->decoder.prop.pb = b / 5;
lp = b % 5;
if (lc + lp > LZMA2_LCLP_MAX)
return LZMA2_STATE_ERROR;
p->decoder.prop.lc = lc;
p->decoder.prop.lp = lp;
p->needInitProp = False;
return LZMA2_STATE_DATA;
}
}
return LZMA2_STATE_ERROR;
}
static void LzmaDec_UpdateWithUncompressed(CLzmaDec *p, const Byte *src, SizeT size)
{
memcpy(p->dic + p->dicPos, src, size);
p->dicPos += size;
if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= size)
p->checkDicSize = p->prop.dicSize;
p->processedPos += (UInt32)size;
}
void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState);
SRes Lzma2Dec_DecodeToDic(CLzma2Dec *p, SizeT dicLimit,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
{
SizeT inSize = *srcLen;
*srcLen = 0;
*status = LZMA_STATUS_NOT_SPECIFIED;
while (p->state != LZMA2_STATE_FINISHED)
{
SizeT dicPos = p->decoder.dicPos;
if (p->state == LZMA2_STATE_ERROR)
return SZ_ERROR_DATA;
if (dicPos == dicLimit && finishMode == LZMA_FINISH_ANY)
{
*status = LZMA_STATUS_NOT_FINISHED;
return SZ_OK;
}
if (p->state != LZMA2_STATE_DATA && p->state != LZMA2_STATE_DATA_CONT)
{
if (*srcLen == inSize)
{
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
(*srcLen)++;
p->state = Lzma2Dec_UpdateState(p, *src++);
continue;
}
{
SizeT destSizeCur = dicLimit - dicPos;
SizeT srcSizeCur = inSize - *srcLen;
ELzmaFinishMode curFinishMode = LZMA_FINISH_ANY;
if (p->unpackSize <= destSizeCur)
{
destSizeCur = (SizeT)p->unpackSize;
curFinishMode = LZMA_FINISH_END;
}
if (LZMA2_IS_UNCOMPRESSED_STATE(p))
{
if (*srcLen == inSize)
{
*status = LZMA_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
if (p->state == LZMA2_STATE_DATA)
{
Bool initDic = (p->control == LZMA2_CONTROL_COPY_RESET_DIC);
if (initDic)
p->needInitProp = p->needInitState = True;
else if (p->needInitDic)
return SZ_ERROR_DATA;
p->needInitDic = False;
LzmaDec_InitDicAndState(&p->decoder, initDic, False);
}
if (srcSizeCur > destSizeCur)
srcSizeCur = destSizeCur;
if (srcSizeCur == 0)
return SZ_ERROR_DATA;
LzmaDec_UpdateWithUncompressed(&p->decoder, src, srcSizeCur);
src += srcSizeCur;
*srcLen += srcSizeCur;
p->unpackSize -= (UInt32)srcSizeCur;
p->state = (p->unpackSize == 0) ? LZMA2_STATE_CONTROL : LZMA2_STATE_DATA_CONT;
}
else
{
SizeT outSizeProcessed;
SRes res;
if (p->state == LZMA2_STATE_DATA)
{
int mode = LZMA2_GET_LZMA_MODE(p);
Bool initDic = (mode == 3);
Bool initState = (mode > 0);
if ((!initDic && p->needInitDic) || (!initState && p->needInitState))
return SZ_ERROR_DATA;
LzmaDec_InitDicAndState(&p->decoder, initDic, initState);
p->needInitDic = False;
p->needInitState = False;
p->state = LZMA2_STATE_DATA_CONT;
}
if (srcSizeCur > p->packSize)
srcSizeCur = (SizeT)p->packSize;
res = LzmaDec_DecodeToDic(&p->decoder, dicPos + destSizeCur, src, &srcSizeCur, curFinishMode, status);
src += srcSizeCur;
*srcLen += srcSizeCur;
p->packSize -= (UInt32)srcSizeCur;
outSizeProcessed = p->decoder.dicPos - dicPos;
p->unpackSize -= (UInt32)outSizeProcessed;
RINOK(res);
if (*status == LZMA_STATUS_NEEDS_MORE_INPUT)
return res;
if (srcSizeCur == 0 && outSizeProcessed == 0)
{
if (*status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK ||
p->unpackSize != 0 || p->packSize != 0)
return SZ_ERROR_DATA;
p->state = LZMA2_STATE_CONTROL;
}
if (*status == LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK)
*status = LZMA_STATUS_NOT_FINISHED;
}
}
}
*status = LZMA_STATUS_FINISHED_WITH_MARK;
return SZ_OK;
}
SRes Lzma2Dec_DecodeToBuf(CLzma2Dec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status)
{
SizeT outSize = *destLen, inSize = *srcLen;
*srcLen = *destLen = 0;
for (;;)
{
SizeT srcSizeCur = inSize, outSizeCur, dicPos;
ELzmaFinishMode curFinishMode;
SRes res;
if (p->decoder.dicPos == p->decoder.dicBufSize)
p->decoder.dicPos = 0;
dicPos = p->decoder.dicPos;
if (outSize > p->decoder.dicBufSize - dicPos)
{
outSizeCur = p->decoder.dicBufSize;
curFinishMode = LZMA_FINISH_ANY;
}
else
{
outSizeCur = dicPos + outSize;
curFinishMode = finishMode;
}
res = Lzma2Dec_DecodeToDic(p, outSizeCur, src, &srcSizeCur, curFinishMode, status);
src += srcSizeCur;
inSize -= srcSizeCur;
*srcLen += srcSizeCur;
outSizeCur = p->decoder.dicPos - dicPos;
memcpy(dest, p->decoder.dic + dicPos, outSizeCur);
dest += outSizeCur;
outSize -= outSizeCur;
*destLen += outSizeCur;
if (res != 0)
return res;
if (outSizeCur == 0 || outSize == 0)
return SZ_OK;
}
}
SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
Byte prop, ELzmaFinishMode finishMode, ELzmaStatus *status, ISzAlloc *alloc)
{
CLzma2Dec decoder;
SRes res;
SizeT outSize = *destLen, inSize = *srcLen;
Byte props[LZMA_PROPS_SIZE];
Lzma2Dec_Construct(&decoder);
*destLen = *srcLen = 0;
*status = LZMA_STATUS_NOT_SPECIFIED;
decoder.decoder.dic = dest;
decoder.decoder.dicBufSize = outSize;
RINOK(Lzma2Dec_GetOldProps(prop, props));
RINOK(LzmaDec_AllocateProbs(&decoder.decoder, props, LZMA_PROPS_SIZE, alloc));
*srcLen = inSize;
res = Lzma2Dec_DecodeToDic(&decoder, outSize, src, srcLen, finishMode, status);
*destLen = decoder.decoder.dicPos;
if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT)
res = SZ_ERROR_INPUT_EOF;
LzmaDec_FreeProbs(&decoder.decoder, alloc);
return res;
}
+84
View File
@@ -0,0 +1,84 @@
/* Lzma2Dec.h -- LZMA2 Decoder
2009-05-03 : Igor Pavlov : Public domain */
#ifndef __LZMA2_DEC_H
#define __LZMA2_DEC_H
#include "LzmaDec.h"
#ifdef __cplusplus
extern "C" {
#endif
/* ---------- State Interface ---------- */
typedef struct
{
CLzmaDec decoder;
UInt32 packSize;
UInt32 unpackSize;
int state;
Byte control;
Bool needInitDic;
Bool needInitState;
Bool needInitProp;
} CLzma2Dec;
#define Lzma2Dec_Construct(p) LzmaDec_Construct(&(p)->decoder)
#define Lzma2Dec_FreeProbs(p, alloc) LzmaDec_FreeProbs(&(p)->decoder, alloc);
#define Lzma2Dec_Free(p, alloc) LzmaDec_Free(&(p)->decoder, alloc);
SRes Lzma2Dec_AllocateProbs(CLzma2Dec *p, Byte prop, ISzAlloc *alloc);
SRes Lzma2Dec_Allocate(CLzma2Dec *p, Byte prop, ISzAlloc *alloc);
void Lzma2Dec_Init(CLzma2Dec *p);
/*
finishMode:
It has meaning only if the decoding reaches output limit (*destLen or dicLimit).
LZMA_FINISH_ANY - use smallest number of input bytes
LZMA_FINISH_END - read EndOfStream marker after decoding
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_NEEDS_MORE_INPUT
SZ_ERROR_DATA - Data error
*/
SRes Lzma2Dec_DecodeToDic(CLzma2Dec *p, SizeT dicLimit,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
SRes Lzma2Dec_DecodeToBuf(CLzma2Dec *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
/* ---------- One Call Interface ---------- */
/*
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - use smallest number of input bytes
LZMA_FINISH_END - read EndOfStream marker after decoding
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
*/
SRes Lzma2Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
Byte prop, ELzmaFinishMode finishMode, ELzmaStatus *status, ISzAlloc *alloc);
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
+231
View File
@@ -0,0 +1,231 @@
/* LzmaDec.h -- LZMA Decoder
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __LZMA_DEC_H
#define __LZMA_DEC_H
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* #define _LZMA_PROB32 */
/* _LZMA_PROB32 can increase the speed on some CPUs,
but memory usage for CLzmaDec::probs will be doubled in that case */
#ifdef _LZMA_PROB32
#define CLzmaProb UInt32
#else
#define CLzmaProb UInt16
#endif
/* ---------- LZMA Properties ---------- */
#define LZMA_PROPS_SIZE 5
typedef struct _CLzmaProps
{
unsigned lc, lp, pb;
UInt32 dicSize;
} CLzmaProps;
/* LzmaProps_Decode - decodes properties
Returns:
SZ_OK
SZ_ERROR_UNSUPPORTED - Unsupported properties
*/
SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size);
/* ---------- LZMA Decoder state ---------- */
/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case.
Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */
#define LZMA_REQUIRED_INPUT_MAX 20
typedef struct
{
CLzmaProps prop;
CLzmaProb *probs;
Byte *dic;
const Byte *buf;
UInt32 range, code;
SizeT dicPos;
SizeT dicBufSize;
UInt32 processedPos;
UInt32 checkDicSize;
unsigned state;
UInt32 reps[4];
unsigned remainLen;
int needFlush;
int needInitState;
UInt32 numProbs;
unsigned tempBufSize;
Byte tempBuf[LZMA_REQUIRED_INPUT_MAX];
} CLzmaDec;
#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; }
void LzmaDec_Init(CLzmaDec *p);
/* There are two types of LZMA streams:
0) Stream with end mark. That end mark adds about 6 bytes to compressed size.
1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */
typedef enum
{
LZMA_FINISH_ANY, /* finish at any point */
LZMA_FINISH_END /* block must be finished at the end */
} ELzmaFinishMode;
/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!!
You must use LZMA_FINISH_END, when you know that current output buffer
covers last bytes of block. In other cases you must use LZMA_FINISH_ANY.
If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK,
and output value of destLen will be less than output buffer size limit.
You can check status result also.
You can use multiple checks to test data integrity after full decompression:
1) Check Result and "status" variable.
2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize.
3) Check that output(srcLen) = compressedSize, if you know real compressedSize.
You must use correct finish mode in that case. */
typedef enum
{
LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */
LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
LZMA_STATUS_NOT_FINISHED, /* stream was not finished */
LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */
} ELzmaStatus;
/* ELzmaStatus is used only as output value for function call */
/* ---------- Interfaces ---------- */
/* There are 3 levels of interfaces:
1) Dictionary Interface
2) Buffer Interface
3) One Call Interface
You can select any of these interfaces, but don't mix functions from different
groups for same object. */
/* There are two variants to allocate state for Dictionary Interface:
1) LzmaDec_Allocate / LzmaDec_Free
2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs
You can use variant 2, if you set dictionary buffer manually.
For Buffer Interface you must always use variant 1.
LzmaDec_Allocate* can return:
SZ_OK
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
*/
SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc);
void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc);
SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc);
void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc);
/* ---------- Dictionary Interface ---------- */
/* You can use it, if you want to eliminate the overhead for data copying from
dictionary to some other external buffer.
You must work with CLzmaDec variables directly in this interface.
STEPS:
LzmaDec_Constr()
LzmaDec_Allocate()
for (each new stream)
{
LzmaDec_Init()
while (it needs more decompression)
{
LzmaDec_DecodeToDic()
use data from CLzmaDec::dic and update CLzmaDec::dicPos
}
}
LzmaDec_Free()
*/
/* LzmaDec_DecodeToDic
The decoding to internal dictionary buffer (CLzmaDec::dic).
You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!!
finishMode:
It has meaning only if the decoding reaches output limit (dicLimit).
LZMA_FINISH_ANY - Decode just dicLimit bytes.
LZMA_FINISH_END - Stream must be finished after dicLimit.
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_NEEDS_MORE_INPUT
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
SZ_ERROR_DATA - Data error
*/
SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
/* ---------- Buffer Interface ---------- */
/* It's zlib-like interface.
See LzmaDec_DecodeToDic description for information about STEPS and return results,
but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need
to work with CLzmaDec variables manually.
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - Decode just destLen bytes.
LZMA_FINISH_END - Stream must be finished after (*destLen).
*/
SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status);
/* ---------- One Call Interface ---------- */
/* LzmaDecode
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - Decode just destLen bytes.
LZMA_FINISH_END - Stream must be finished after (*destLen).
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
*/
SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode,
ELzmaStatus *status, ISzAlloc *alloc);
#ifdef __cplusplus
}
#endif
#endif
+81
View File
@@ -0,0 +1,81 @@
/* Ppmd.h -- PPMD codec common code
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#ifndef __PPMD_H
#define __PPMD_H
#include "Types.h"
#include "CpuArch.h"
EXTERN_C_BEGIN
#ifdef MY_CPU_32BIT
#define PPMD_32BIT
#endif
#define PPMD_INT_BITS 7
#define PPMD_PERIOD_BITS 7
#define PPMD_BIN_SCALE (1 << (PPMD_INT_BITS + PPMD_PERIOD_BITS))
#define PPMD_GET_MEAN_SPEC(summ, shift, round) (((summ) + (1 << ((shift) - (round)))) >> (shift))
#define PPMD_GET_MEAN(summ) PPMD_GET_MEAN_SPEC((summ), PPMD_PERIOD_BITS, 2)
#define PPMD_UPDATE_PROB_0(prob) ((prob) + (1 << PPMD_INT_BITS) - PPMD_GET_MEAN(prob))
#define PPMD_UPDATE_PROB_1(prob) ((prob) - PPMD_GET_MEAN(prob))
#define PPMD_N1 4
#define PPMD_N2 4
#define PPMD_N3 4
#define PPMD_N4 ((128 + 3 - 1 * PPMD_N1 - 2 * PPMD_N2 - 3 * PPMD_N3) / 4)
#define PPMD_NUM_INDEXES (PPMD_N1 + PPMD_N2 + PPMD_N3 + PPMD_N4)
/* SEE-contexts for PPM-contexts with masked symbols */
typedef struct
{
UInt16 Summ; /* Freq */
Byte Shift; /* Speed of Freq change; low Shift is for fast change */
Byte Count; /* Count to next change of Shift */
} CPpmd_See;
#define Ppmd_See_Update(p) if ((p)->Shift < PPMD_PERIOD_BITS && --(p)->Count == 0) \
{ (p)->Summ <<= 1; (p)->Count = (Byte)(3 << (p)->Shift++); }
typedef struct
{
Byte Symbol;
Byte Freq;
UInt16 SuccessorLow;
UInt16 SuccessorHigh;
} CPpmd_State;
typedef
#ifdef PPMD_32BIT
CPpmd_State *
#else
UInt32
#endif
CPpmd_State_Ref;
typedef
#ifdef PPMD_32BIT
void *
#else
UInt32
#endif
CPpmd_Void_Ref;
typedef
#ifdef PPMD_32BIT
Byte *
#else
UInt32
#endif
CPpmd_Byte_Ref;
#define PPMD_SetAllBitsIn256Bytes(p) \
{ unsigned i; for (i = 0; i < 256 / sizeof(p[0]); i += 8) { \
p[i+7] = p[i+6] = p[i+5] = p[i+4] = p[i+3] = p[i+2] = p[i+1] = p[i+0] = ~(size_t)0; }}
EXTERN_C_END
#endif
+713
View File
@@ -0,0 +1,713 @@
/* Ppmd7.c -- PPMdH codec
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#include <memory.h>
#include "Ppmd7.h"
const Byte PPMD7_kExpEscape[16] = { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
static const UInt16 kInitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
#define MAX_FREQ 124
#define UNIT_SIZE 12
#define U2B(nu) ((UInt32)(nu) * UNIT_SIZE)
#define U2I(nu) (p->Units2Indx[(nu) - 1])
#define I2U(indx) (p->Indx2Units[indx])
#ifdef PPMD_32BIT
#define REF(ptr) (ptr)
#else
#define REF(ptr) ((UInt32)((Byte *)(ptr) - (p)->Base))
#endif
#define STATS_REF(ptr) ((CPpmd_State_Ref)REF(ptr))
#define CTX(ref) ((CPpmd7_Context *)Ppmd7_GetContext(p, ref))
#define STATS(ctx) Ppmd7_GetStats(p, ctx)
#define ONE_STATE(ctx) Ppmd7Context_OneState(ctx)
#define SUFFIX(ctx) CTX((ctx)->Suffix)
typedef CPpmd7_Context * CTX_PTR;
struct CPpmd7_Node_;
typedef
#ifdef PPMD_32BIT
struct CPpmd7_Node_ *
#else
UInt32
#endif
CPpmd7_Node_Ref;
typedef struct CPpmd7_Node_
{
UInt16 Stamp; /* must be at offset 0 as CPpmd7_Context::NumStats. Stamp=0 means free */
UInt16 NU;
CPpmd7_Node_Ref Next; /* must be at offset >= 4 */
CPpmd7_Node_Ref Prev;
} CPpmd7_Node;
union NodeOrRef {
CPpmd7_Node node;
CPpmd7_Node_Ref ref;
};
#ifdef PPMD_32BIT
#define NODE(ptr) (ptr)
#else
#define NODE(offs) ((CPpmd7_Node *)(p->Base + (offs)))
#endif
void Ppmd7_Construct(CPpmd7 *p)
{
unsigned i, k, m;
p->Base = 0;
for (i = 0, k = 0; i < PPMD_NUM_INDEXES; i++)
{
unsigned step = (i >= 12 ? 4 : (i >> 2) + 1);
do { p->Units2Indx[k++] = (Byte)i; } while(--step);
p->Indx2Units[i] = (Byte)k;
}
p->NS2BSIndx[0] = (0 << 1);
p->NS2BSIndx[1] = (1 << 1);
memset(p->NS2BSIndx + 2, (2 << 1), 9);
memset(p->NS2BSIndx + 11, (3 << 1), 256 - 11);
for (i = 0; i < 3; i++)
p->NS2Indx[i] = (Byte)i;
for (m = i, k = 1; i < 256; i++)
{
p->NS2Indx[i] = (Byte)m;
if (--k == 0)
k = (++m) - 2;
}
memset(p->HB2Flag, 0, 0x40);
memset(p->HB2Flag + 0x40, 8, 0x100 - 0x40);
}
void Ppmd7_Free(CPpmd7 *p, ISzAlloc *alloc)
{
alloc->Free(alloc, p->Base);
p->Size = 0;
p->Base = 0;
}
Bool Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAlloc *alloc)
{
if (p->Base == 0 || p->Size != size)
{
Ppmd7_Free(p, alloc);
p->AlignOffset =
#ifdef PPMD_32BIT
(4 - size) & 3;
#else
4 - (size & 3);
#endif
if ((p->Base = (Byte *)alloc->Alloc(alloc, p->AlignOffset + size
#ifndef PPMD_32BIT
+ UNIT_SIZE
#endif
)) == 0)
return False;
p->Size = size;
}
return True;
}
static void InsertNode(CPpmd7 *p, void *node, unsigned indx)
{
*((CPpmd_Void_Ref *)node) = p->FreeList[indx];
p->FreeList[indx] = REF(node);
}
static void *RemoveNode(CPpmd7 *p, unsigned indx)
{
CPpmd_Void_Ref *node = (CPpmd_Void_Ref *)Ppmd7_GetPtr(p, p->FreeList[indx]);
p->FreeList[indx] = *node;
return node;
}
static void SplitBlock(CPpmd7 *p, void *ptr, unsigned oldIndx, unsigned newIndx)
{
unsigned i, nu = I2U(oldIndx) - I2U(newIndx);
ptr = (Byte *)ptr + U2B(I2U(newIndx));
if (I2U(i = U2I(nu)) != nu)
{
unsigned k = I2U(--i);
InsertNode(p, ((Byte *)ptr) + U2B(k), nu - k - 1);
}
InsertNode(p, ptr, i);
}
static void GlueFreeBlocks(CPpmd7 *p)
{
#ifdef PPMD_32BIT
CPpmd7_Node headItem;
CPpmd7_Node_Ref head = &headItem;
#else
CPpmd7_Node_Ref head = p->AlignOffset + p->Size;
#endif
CPpmd7_Node_Ref n = head;
unsigned i;
p->GlueCount = 255;
/* create doubly-linked list of free blocks */
for (i = 0; i < PPMD_NUM_INDEXES; i++)
{
UInt16 nu = I2U(i);
CPpmd7_Node_Ref next = (CPpmd7_Node_Ref)p->FreeList[i];
p->FreeList[i] = 0;
while (next != 0)
{
CPpmd7_Node *node = NODE(next);
node->Next = n;
n = NODE(n)->Prev = next;
next = ((const union NodeOrRef *)node)->ref;
node->Stamp = 0;
node->NU = (UInt16)nu;
}
}
NODE(head)->Stamp = 1;
NODE(head)->Next = n;
NODE(n)->Prev = head;
if (p->LoUnit != p->HiUnit)
((CPpmd7_Node *)p->LoUnit)->Stamp = 1;
/* Glue free blocks */
while (n != head)
{
CPpmd7_Node *node = NODE(n);
UInt32 nu = (UInt32)node->NU;
for (;;)
{
CPpmd7_Node *node2 = NODE(n) + nu;
nu += node2->NU;
if (node2->Stamp != 0 || nu >= 0x10000)
break;
NODE(node2->Prev)->Next = node2->Next;
NODE(node2->Next)->Prev = node2->Prev;
node->NU = (UInt16)nu;
}
n = node->Next;
}
/* Fill lists of free blocks */
for (n = NODE(head)->Next; n != head;)
{
CPpmd7_Node *node = NODE(n);
unsigned nu;
CPpmd7_Node_Ref next = node->Next;
for (nu = node->NU; nu > 128; nu -= 128, node += 128)
InsertNode(p, node, PPMD_NUM_INDEXES - 1);
if (I2U(i = U2I(nu)) != nu)
{
unsigned k = I2U(--i);
InsertNode(p, node + k, nu - k - 1);
}
InsertNode(p, node, i);
n = next;
}
}
static void *AllocUnitsRare(CPpmd7 *p, unsigned indx)
{
unsigned i;
void *retVal;
if (p->GlueCount == 0)
{
GlueFreeBlocks(p);
if (p->FreeList[indx] != 0)
return RemoveNode(p, indx);
}
i = indx;
do
{
if (++i == PPMD_NUM_INDEXES)
{
UInt32 numBytes = U2B(I2U(indx));
p->GlueCount--;
return ((UInt32)(p->UnitsStart - p->Text) > numBytes) ? (p->UnitsStart -= numBytes) : (NULL);
}
}
while (p->FreeList[i] == 0);
retVal = RemoveNode(p, i);
SplitBlock(p, retVal, i, indx);
return retVal;
}
static void *AllocUnits(CPpmd7 *p, unsigned indx)
{
UInt32 numBytes;
if (p->FreeList[indx] != 0)
return RemoveNode(p, indx);
numBytes = U2B(I2U(indx));
if (numBytes <= (UInt32)(p->HiUnit - p->LoUnit))
{
void *retVal = p->LoUnit;
p->LoUnit += numBytes;
return retVal;
}
return AllocUnitsRare(p, indx);
}
#define MyMem12Cpy(dest, src, num) \
{ UInt32 *d = (UInt32 *)dest; const UInt32 *s = (const UInt32 *)src; UInt32 n = num; \
do { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; s += 3; d += 3; } while(--n); }
static void *ShrinkUnits(CPpmd7 *p, void *oldPtr, unsigned oldNU, unsigned newNU)
{
unsigned i0 = U2I(oldNU);
unsigned i1 = U2I(newNU);
if (i0 == i1)
return oldPtr;
if (p->FreeList[i1] != 0)
{
void *ptr = RemoveNode(p, i1);
MyMem12Cpy(ptr, oldPtr, newNU);
InsertNode(p, oldPtr, i0);
return ptr;
}
SplitBlock(p, oldPtr, i0, i1);
return oldPtr;
}
#define SUCCESSOR(p) ((CPpmd_Void_Ref)((p)->SuccessorLow | ((UInt32)(p)->SuccessorHigh << 16)))
static void SetSuccessor(CPpmd_State *p, CPpmd_Void_Ref v)
{
(p)->SuccessorLow = (UInt16)((UInt32)(v) & 0xFFFF);
(p)->SuccessorHigh = (UInt16)(((UInt32)(v) >> 16) & 0xFFFF);
}
static void RestartModel(CPpmd7 *p)
{
unsigned i, k, m;
memset(p->FreeList, 0, sizeof(p->FreeList));
p->Text = p->Base + p->AlignOffset;
p->HiUnit = p->Text + p->Size;
p->LoUnit = p->UnitsStart = p->HiUnit - p->Size / 8 / UNIT_SIZE * 7 * UNIT_SIZE;
p->GlueCount = 0;
p->OrderFall = p->MaxOrder;
p->RunLength = p->InitRL = -(Int32)((p->MaxOrder < 12) ? p->MaxOrder : 12) - 1;
p->PrevSuccess = 0;
p->MinContext = p->MaxContext = (CTX_PTR)(p->HiUnit -= UNIT_SIZE); /* AllocContext(p); */
p->MinContext->Suffix = 0;
p->MinContext->NumStats = 256;
p->MinContext->SummFreq = 256 + 1;
p->FoundState = (CPpmd_State *)p->LoUnit; /* AllocUnits(p, PPMD_NUM_INDEXES - 1); */
p->LoUnit += U2B(256 / 2);
p->MinContext->Stats = REF(p->FoundState);
for (i = 0; i < 256; i++)
{
CPpmd_State *s = &p->FoundState[i];
s->Symbol = (Byte)i;
s->Freq = 1;
SetSuccessor(s, 0);
}
for (i = 0; i < 128; i++)
for (k = 0; k < 8; k++)
{
UInt16 *dest = p->BinSumm[i] + k;
UInt16 val = (UInt16)(PPMD_BIN_SCALE - kInitBinEsc[k] / (i + 2));
for (m = 0; m < 64; m += 8)
dest[m] = val;
}
for (i = 0; i < 25; i++)
for (k = 0; k < 16; k++)
{
CPpmd_See *s = &p->See[i][k];
s->Summ = (UInt16)((5 * i + 10) << (s->Shift = PPMD_PERIOD_BITS - 4));
s->Count = 4;
}
}
void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder)
{
p->MaxOrder = maxOrder;
RestartModel(p);
p->DummySee.Shift = PPMD_PERIOD_BITS;
p->DummySee.Summ = 0; /* unused */
p->DummySee.Count = 64; /* unused */
}
static CTX_PTR CreateSuccessors(CPpmd7 *p, Bool skip)
{
CPpmd_State upState;
CTX_PTR c = p->MinContext;
CPpmd_Byte_Ref upBranch = (CPpmd_Byte_Ref)SUCCESSOR(p->FoundState);
CPpmd_State *ps[PPMD7_MAX_ORDER];
unsigned numPs = 0;
if (!skip)
ps[numPs++] = p->FoundState;
while (c->Suffix)
{
CPpmd_Void_Ref successor;
CPpmd_State *s;
c = SUFFIX(c);
if (c->NumStats != 1)
{
for (s = STATS(c); s->Symbol != p->FoundState->Symbol; s++);
}
else
s = ONE_STATE(c);
successor = SUCCESSOR(s);
if (successor != upBranch)
{
c = CTX(successor);
if (numPs == 0)
return c;
break;
}
ps[numPs++] = s;
}
upState.Symbol = *(const Byte *)Ppmd7_GetPtr(p, upBranch);
SetSuccessor(&upState, upBranch + 1);
if (c->NumStats == 1)
upState.Freq = ONE_STATE(c)->Freq;
else
{
UInt32 cf, s0;
CPpmd_State *s;
for (s = STATS(c); s->Symbol != upState.Symbol; s++);
cf = s->Freq - 1;
s0 = c->SummFreq - c->NumStats - cf;
upState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : ((2 * cf + 3 * s0 - 1) / (2 * s0))));
}
do
{
/* Create Child */
CTX_PTR c1; /* = AllocContext(p); */
if (p->HiUnit != p->LoUnit)
c1 = (CTX_PTR)(p->HiUnit -= UNIT_SIZE);
else if (p->FreeList[0] != 0)
c1 = (CTX_PTR)RemoveNode(p, 0);
else
{
c1 = (CTX_PTR)AllocUnitsRare(p, 0);
if (!c1)
return NULL;
}
c1->NumStats = 1;
*ONE_STATE(c1) = upState;
c1->Suffix = REF(c);
SetSuccessor(ps[--numPs], REF(c1));
c = c1;
}
while (numPs != 0);
return c;
}
static void SwapStates(CPpmd_State *t1, CPpmd_State *t2)
{
CPpmd_State tmp = *t1;
*t1 = *t2;
*t2 = tmp;
}
static void UpdateModel(CPpmd7 *p)
{
CPpmd_Void_Ref successor, fSuccessor = SUCCESSOR(p->FoundState);
CTX_PTR c;
unsigned s0, ns;
if (p->FoundState->Freq < MAX_FREQ / 4 && p->MinContext->Suffix != 0)
{
c = SUFFIX(p->MinContext);
if (c->NumStats == 1)
{
CPpmd_State *s = ONE_STATE(c);
if (s->Freq < 32)
s->Freq++;
}
else
{
CPpmd_State *s = STATS(c);
if (s->Symbol != p->FoundState->Symbol)
{
do { s++; } while (s->Symbol != p->FoundState->Symbol);
if (s[0].Freq >= s[-1].Freq)
{
SwapStates(&s[0], &s[-1]);
s--;
}
}
if (s->Freq < MAX_FREQ - 9)
{
s->Freq += 2;
c->SummFreq += 2;
}
}
}
if (p->OrderFall == 0)
{
p->MinContext = p->MaxContext = CreateSuccessors(p, True);
if (p->MinContext == 0)
{
RestartModel(p);
return;
}
SetSuccessor(p->FoundState, REF(p->MinContext));
return;
}
*p->Text++ = p->FoundState->Symbol;
successor = REF(p->Text);
if (p->Text >= p->UnitsStart)
{
RestartModel(p);
return;
}
if (fSuccessor)
{
if (fSuccessor <= successor)
{
CTX_PTR cs = CreateSuccessors(p, False);
if (cs == NULL)
{
RestartModel(p);
return;
}
fSuccessor = REF(cs);
}
if (--p->OrderFall == 0)
{
successor = fSuccessor;
p->Text -= (p->MaxContext != p->MinContext);
}
}
else
{
SetSuccessor(p->FoundState, successor);
fSuccessor = REF(p->MinContext);
}
s0 = p->MinContext->SummFreq - (ns = p->MinContext->NumStats) - (p->FoundState->Freq - 1);
for (c = p->MaxContext; c != p->MinContext; c = SUFFIX(c))
{
unsigned ns1;
UInt32 cf, sf;
if ((ns1 = c->NumStats) != 1)
{
if ((ns1 & 1) == 0)
{
/* Expand for one UNIT */
unsigned oldNU = ns1 >> 1;
unsigned i = U2I(oldNU);
if (i != U2I(oldNU + 1))
{
void *ptr = AllocUnits(p, i + 1);
void *oldPtr;
if (!ptr)
{
RestartModel(p);
return;
}
oldPtr = STATS(c);
MyMem12Cpy(ptr, oldPtr, oldNU);
InsertNode(p, oldPtr, i);
c->Stats = STATS_REF(ptr);
}
}
c->SummFreq = (UInt16)(c->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) & (c->SummFreq <= 8 * ns1)));
}
else
{
CPpmd_State *s = (CPpmd_State*)AllocUnits(p, 0);
if (!s)
{
RestartModel(p);
return;
}
*s = *ONE_STATE(c);
c->Stats = REF(s);
if (s->Freq < MAX_FREQ / 4 - 1)
s->Freq <<= 1;
else
s->Freq = MAX_FREQ - 4;
c->SummFreq = (UInt16)(s->Freq + p->InitEsc + (ns > 3));
}
cf = 2 * (UInt32)p->FoundState->Freq * (c->SummFreq + 6);
sf = (UInt32)s0 + c->SummFreq;
if (cf < 6 * sf)
{
cf = 1 + (cf > sf) + (cf >= 4 * sf);
c->SummFreq += 3;
}
else
{
cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf);
c->SummFreq = (UInt16)(c->SummFreq + cf);
}
{
CPpmd_State *s = STATS(c) + ns1;
SetSuccessor(s, successor);
s->Symbol = p->FoundState->Symbol;
s->Freq = (Byte)cf;
c->NumStats = (UInt16)(ns1 + 1);
}
}
p->MaxContext = p->MinContext = CTX(fSuccessor);
}
static void Rescale(CPpmd7 *p)
{
unsigned i, adder, sumFreq, escFreq;
CPpmd_State *stats = STATS(p->MinContext);
CPpmd_State *s = p->FoundState;
{
CPpmd_State tmp = *s;
for (; s != stats; s--)
s[0] = s[-1];
*s = tmp;
}
escFreq = p->MinContext->SummFreq - s->Freq;
s->Freq += 4;
adder = (p->OrderFall != 0);
s->Freq = (Byte)((s->Freq + adder) >> 1);
sumFreq = s->Freq;
i = p->MinContext->NumStats - 1;
do
{
escFreq -= (++s)->Freq;
s->Freq = (Byte)((s->Freq + adder) >> 1);
sumFreq += s->Freq;
if (s[0].Freq > s[-1].Freq)
{
CPpmd_State *s1 = s;
CPpmd_State tmp = *s1;
do
s1[0] = s1[-1];
while (--s1 != stats && tmp.Freq > s1[-1].Freq);
*s1 = tmp;
}
}
while (--i);
if (s->Freq == 0)
{
unsigned numStats = p->MinContext->NumStats;
unsigned n0, n1;
do { i++; } while ((--s)->Freq == 0);
escFreq += i;
p->MinContext->NumStats = (UInt16)(p->MinContext->NumStats - i);
if (p->MinContext->NumStats == 1)
{
CPpmd_State tmp = *stats;
do
{
tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1));
escFreq >>= 1;
}
while (escFreq > 1);
InsertNode(p, stats, U2I(((numStats + 1) >> 1)));
*(p->FoundState = ONE_STATE(p->MinContext)) = tmp;
return;
}
n0 = (numStats + 1) >> 1;
n1 = (p->MinContext->NumStats + 1) >> 1;
if (n0 != n1)
p->MinContext->Stats = STATS_REF(ShrinkUnits(p, stats, n0, n1));
}
p->MinContext->SummFreq = (UInt16)(sumFreq + escFreq - (escFreq >> 1));
p->FoundState = STATS(p->MinContext);
}
CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *escFreq)
{
CPpmd_See *see;
unsigned nonMasked = p->MinContext->NumStats - numMasked;
if (p->MinContext->NumStats != 256)
{
see = p->See[p->NS2Indx[nonMasked - 1]] +
(nonMasked < (unsigned)SUFFIX(p->MinContext)->NumStats - p->MinContext->NumStats) +
2 * (p->MinContext->SummFreq < 11 * p->MinContext->NumStats) +
4 * (numMasked > nonMasked) +
p->HiBitsFlag;
{
unsigned r = (see->Summ >> see->Shift);
see->Summ = (UInt16)(see->Summ - r);
*escFreq = r + (r == 0);
}
}
else
{
see = &p->DummySee;
*escFreq = 1;
}
return see;
}
static void NextContext(CPpmd7 *p)
{
CTX_PTR c = CTX(SUCCESSOR(p->FoundState));
if (p->OrderFall == 0 && (Byte *)c > p->Text)
p->MinContext = p->MaxContext = c;
else
UpdateModel(p);
}
void Ppmd7_Update1(CPpmd7 *p)
{
CPpmd_State *s = p->FoundState;
s->Freq += 4;
p->MinContext->SummFreq += 4;
if (s[0].Freq > s[-1].Freq)
{
SwapStates(&s[0], &s[-1]);
p->FoundState = --s;
if (s->Freq > MAX_FREQ)
Rescale(p);
}
NextContext(p);
}
void Ppmd7_Update1_0(CPpmd7 *p)
{
p->PrevSuccess = (2 * p->FoundState->Freq > p->MinContext->SummFreq);
p->RunLength += p->PrevSuccess;
p->MinContext->SummFreq += 4;
if ((p->FoundState->Freq += 4) > MAX_FREQ)
Rescale(p);
NextContext(p);
}
void Ppmd7_UpdateBin(CPpmd7 *p)
{
p->FoundState->Freq = (Byte)(p->FoundState->Freq + (p->FoundState->Freq < 128 ? 1: 0));
p->PrevSuccess = 1;
p->RunLength++;
NextContext(p);
}
void Ppmd7_Update2(CPpmd7 *p)
{
p->MinContext->SummFreq += 4;
if ((p->FoundState->Freq += 4) > MAX_FREQ)
Rescale(p);
p->RunLength = p->InitRL;
UpdateModel(p);
}
+140
View File
@@ -0,0 +1,140 @@
/* Ppmd7.h -- PPMdH compression codec
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
/* This code supports virtual RangeDecoder and includes the implementation
of RangeCoder from 7z, instead of RangeCoder from original PPMd var.H.
If you need the compatibility with original PPMd var.H, you can use external RangeDecoder */
#ifndef __PPMD7_H
#define __PPMD7_H
#include "Ppmd.h"
EXTERN_C_BEGIN
#define PPMD7_MIN_ORDER 2
#define PPMD7_MAX_ORDER 64
#define PPMD7_MIN_MEM_SIZE (1 << 11)
#define PPMD7_MAX_MEM_SIZE (0xFFFFFFFF - 12 * 3)
struct CPpmd7_Context_;
typedef
#ifdef PPMD_32BIT
struct CPpmd7_Context_ *
#else
UInt32
#endif
CPpmd7_Context_Ref;
typedef struct CPpmd7_Context_
{
UInt16 NumStats;
UInt16 SummFreq;
CPpmd_State_Ref Stats;
CPpmd7_Context_Ref Suffix;
} CPpmd7_Context;
#define Ppmd7Context_OneState(p) ((CPpmd_State *)&(p)->SummFreq)
typedef struct
{
CPpmd7_Context *MinContext, *MaxContext;
CPpmd_State *FoundState;
unsigned OrderFall, InitEsc, PrevSuccess, MaxOrder, HiBitsFlag;
Int32 RunLength, InitRL; /* must be 32-bit at least */
UInt32 Size;
UInt32 GlueCount;
Byte *Base, *LoUnit, *HiUnit, *Text, *UnitsStart;
UInt32 AlignOffset;
Byte Indx2Units[PPMD_NUM_INDEXES];
Byte Units2Indx[128];
CPpmd_Void_Ref FreeList[PPMD_NUM_INDEXES];
Byte NS2Indx[256], NS2BSIndx[256], HB2Flag[256];
CPpmd_See DummySee, See[25][16];
UInt16 BinSumm[128][64];
} CPpmd7;
void Ppmd7_Construct(CPpmd7 *p);
Bool Ppmd7_Alloc(CPpmd7 *p, UInt32 size, ISzAlloc *alloc);
void Ppmd7_Free(CPpmd7 *p, ISzAlloc *alloc);
void Ppmd7_Init(CPpmd7 *p, unsigned maxOrder);
#define Ppmd7_WasAllocated(p) ((p)->Base != NULL)
/* ---------- Internal Functions ---------- */
extern const Byte PPMD7_kExpEscape[16];
#ifdef PPMD_32BIT
#define Ppmd7_GetPtr(p, ptr) (ptr)
#define Ppmd7_GetContext(p, ptr) (ptr)
#define Ppmd7_GetStats(p, ctx) ((ctx)->Stats)
#else
#define Ppmd7_GetPtr(p, offs) ((void *)((p)->Base + (offs)))
#define Ppmd7_GetContext(p, offs) ((CPpmd7_Context *)Ppmd7_GetPtr((p), (offs)))
#define Ppmd7_GetStats(p, ctx) ((CPpmd_State *)Ppmd7_GetPtr((p), ((ctx)->Stats)))
#endif
void Ppmd7_Update1(CPpmd7 *p);
void Ppmd7_Update1_0(CPpmd7 *p);
void Ppmd7_Update2(CPpmd7 *p);
void Ppmd7_UpdateBin(CPpmd7 *p);
#define Ppmd7_GetBinSumm(p) \
&p->BinSumm[Ppmd7Context_OneState(p->MinContext)->Freq - 1][p->PrevSuccess + \
p->NS2BSIndx[Ppmd7_GetContext(p, p->MinContext->Suffix)->NumStats - 1] + \
(p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol]) + \
2 * p->HB2Flag[Ppmd7Context_OneState(p->MinContext)->Symbol] + \
((p->RunLength >> 26) & 0x20)]
CPpmd_See *Ppmd7_MakeEscFreq(CPpmd7 *p, unsigned numMasked, UInt32 *scale);
/* ---------- Decode ---------- */
typedef struct
{
UInt32 (*GetThreshold)(void *p, UInt32 total);
void (*Decode)(void *p, UInt32 start, UInt32 size);
UInt32 (*DecodeBit)(void *p, UInt32 size0);
} IPpmd7_RangeDec;
typedef struct
{
IPpmd7_RangeDec p;
UInt32 Range;
UInt32 Code;
IByteIn *Stream;
} CPpmd7z_RangeDec;
void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec *p);
Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec *p);
#define Ppmd7z_RangeDec_IsFinishedOK(p) ((p)->Code == 0)
int Ppmd7_DecodeSymbol(CPpmd7 *p, IPpmd7_RangeDec *rc);
/* ---------- Encode ---------- */
typedef struct
{
UInt64 Low;
UInt32 Range;
Byte Cache;
UInt64 CacheSize;
IByteOut *Stream;
} CPpmd7z_RangeEnc;
void Ppmd7z_RangeEnc_Init(CPpmd7z_RangeEnc *p);
void Ppmd7z_RangeEnc_FlushData(CPpmd7z_RangeEnc *p);
void Ppmd7_EncodeSymbol(CPpmd7 *p, CPpmd7z_RangeEnc *rc, int symbol);
EXTERN_C_END
#endif
+187
View File
@@ -0,0 +1,187 @@
/* Ppmd7Dec.c -- PPMdH Decoder
2010-03-12 : Igor Pavlov : Public domain
This code is based on PPMd var.H (2001): Dmitry Shkarin : Public domain */
#include "Ppmd7.h"
#define kTopValue (1 << 24)
Bool Ppmd7z_RangeDec_Init(CPpmd7z_RangeDec *p)
{
unsigned i;
p->Code = 0;
p->Range = 0xFFFFFFFF;
if (p->Stream->Read((void *)p->Stream) != 0)
return False;
for (i = 0; i < 4; i++)
p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream);
return (p->Code < 0xFFFFFFFF);
}
static UInt32 Range_GetThreshold(void *pp, UInt32 total)
{
CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp;
return (p->Code) / (p->Range /= total);
}
static void Range_Normalize(CPpmd7z_RangeDec *p)
{
if (p->Range < kTopValue)
{
p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream);
p->Range <<= 8;
if (p->Range < kTopValue)
{
p->Code = (p->Code << 8) | p->Stream->Read((void *)p->Stream);
p->Range <<= 8;
}
}
}
static void Range_Decode(void *pp, UInt32 start, UInt32 size)
{
CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp;
p->Code -= start * p->Range;
p->Range *= size;
Range_Normalize(p);
}
static UInt32 Range_DecodeBit(void *pp, UInt32 size0)
{
CPpmd7z_RangeDec *p = (CPpmd7z_RangeDec *)pp;
UInt32 newBound = (p->Range >> 14) * size0;
UInt32 symbol;
if (p->Code < newBound)
{
symbol = 0;
p->Range = newBound;
}
else
{
symbol = 1;
p->Code -= newBound;
p->Range -= newBound;
}
Range_Normalize(p);
return symbol;
}
void Ppmd7z_RangeDec_CreateVTable(CPpmd7z_RangeDec *p)
{
p->p.GetThreshold = Range_GetThreshold;
p->p.Decode = Range_Decode;
p->p.DecodeBit = Range_DecodeBit;
}
#define MASK(sym) ((signed char *)charMask)[sym]
int Ppmd7_DecodeSymbol(CPpmd7 *p, IPpmd7_RangeDec *rc)
{
size_t charMask[256 / sizeof(size_t)];
if (p->MinContext->NumStats != 1)
{
CPpmd_State *s = Ppmd7_GetStats(p, p->MinContext);
unsigned i;
UInt32 count, hiCnt;
if ((count = rc->GetThreshold(rc, p->MinContext->SummFreq)) < (hiCnt = s->Freq))
{
Byte symbol;
rc->Decode(rc, 0, s->Freq);
p->FoundState = s;
symbol = s->Symbol;
Ppmd7_Update1_0(p);
return symbol;
}
p->PrevSuccess = 0;
i = p->MinContext->NumStats - 1;
do
{
if ((hiCnt += (++s)->Freq) > count)
{
Byte symbol;
rc->Decode(rc, hiCnt - s->Freq, s->Freq);
p->FoundState = s;
symbol = s->Symbol;
Ppmd7_Update1(p);
return symbol;
}
}
while (--i);
if (count >= p->MinContext->SummFreq)
return -2;
p->HiBitsFlag = p->HB2Flag[p->FoundState->Symbol];
rc->Decode(rc, hiCnt, p->MinContext->SummFreq - hiCnt);
PPMD_SetAllBitsIn256Bytes(charMask);
MASK(s->Symbol) = 0;
i = p->MinContext->NumStats - 1;
do { MASK((--s)->Symbol) = 0; } while (--i);
}
else
{
UInt16 *prob = Ppmd7_GetBinSumm(p);
if (rc->DecodeBit(rc, *prob) == 0)
{
Byte symbol;
*prob = (UInt16)PPMD_UPDATE_PROB_0(*prob);
symbol = (p->FoundState = Ppmd7Context_OneState(p->MinContext))->Symbol;
Ppmd7_UpdateBin(p);
return symbol;
}
*prob = (UInt16)PPMD_UPDATE_PROB_1(*prob);
p->InitEsc = PPMD7_kExpEscape[*prob >> 10];
PPMD_SetAllBitsIn256Bytes(charMask);
MASK(Ppmd7Context_OneState(p->MinContext)->Symbol) = 0;
p->PrevSuccess = 0;
}
for (;;)
{
CPpmd_State *ps[256], *s;
UInt32 freqSum, count, hiCnt;
CPpmd_See *see;
unsigned i, num, numMasked = p->MinContext->NumStats;
do
{
p->OrderFall++;
if (!p->MinContext->Suffix)
return -1;
p->MinContext = Ppmd7_GetContext(p, p->MinContext->Suffix);
}
while (p->MinContext->NumStats == numMasked);
hiCnt = 0;
s = Ppmd7_GetStats(p, p->MinContext);
i = 0;
num = p->MinContext->NumStats - numMasked;
do
{
int k = (int)(MASK(s->Symbol));
hiCnt += (s->Freq & k);
ps[i] = s++;
i -= k;
}
while (i != num);
see = Ppmd7_MakeEscFreq(p, numMasked, &freqSum);
freqSum += hiCnt;
count = rc->GetThreshold(rc, freqSum);
if (count < hiCnt)
{
Byte symbol;
CPpmd_State **pps = ps;
for (hiCnt = 0; (hiCnt += (*pps)->Freq) <= count; pps++);
s = *pps;
rc->Decode(rc, hiCnt - s->Freq, s->Freq);
Ppmd_See_Update(see);
p->FoundState = s;
symbol = s->Symbol;
Ppmd7_Update2(p);
return symbol;
}
if (count >= freqSum)
return -2;
rc->Decode(rc, hiCnt, freqSum - hiCnt);
see->Summ = (UInt16)(see->Summ + freqSum);
do { MASK(ps[--i]->Symbol) = 0; } while (i != 0);
}
}
+20
View File
@@ -0,0 +1,20 @@
/* RotateDefs.h -- Rotate functions
2009-02-07 : Igor Pavlov : Public domain */
#ifndef __ROTATE_DEFS_H
#define __ROTATE_DEFS_H
#ifdef _MSC_VER
#include <stdlib.h>
#define rotlFixed(x, n) _rotl((x), (n))
#define rotrFixed(x, n) _rotr((x), (n))
#else
#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#endif
#endif
+262
View File
@@ -0,0 +1,262 @@
/* Types.h -- Basic types
2010-10-09 : Igor Pavlov : Public domain */
#ifndef __7Z_TYPES_H
#define __7Z_TYPES_H
#include <stddef.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <zconf.h>
#ifndef EXTERN_C_BEGIN
#ifdef __cplusplus
#define EXTERN_C_BEGIN extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C_BEGIN
#define EXTERN_C_END
#endif
#endif
EXTERN_C_BEGIN
#include "fmap.h"
#define SZ_OK 0
#define SZ_ERROR_DATA 1
#define SZ_ERROR_MEM 2
#define SZ_ERROR_CRC 3
#define SZ_ERROR_UNSUPPORTED 4
#define SZ_ERROR_PARAM 5
#define SZ_ERROR_INPUT_EOF 6
#define SZ_ERROR_OUTPUT_EOF 7
#define SZ_ERROR_READ 8
#define SZ_ERROR_WRITE 9
#define SZ_ERROR_PROGRESS 10
#define SZ_ERROR_FAIL 11
#define SZ_ERROR_THREAD 12
#define SZ_ERROR_ARCHIVE 16
#define SZ_ERROR_NO_ARCHIVE 17
/* ACAB */
#define SZ_ERROR_ENCRYPTED 18
typedef int SRes;
#ifdef _WIN32
typedef DWORD WRes;
#else
typedef int WRes;
#endif
#ifndef RINOK
#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; }
#endif
/* aCaB -- use Byte defined in zconf.h
typedef unsigned char Byte;
*/
typedef short Int16;
typedef unsigned short UInt16;
#ifdef _LZMA_UINT32_IS_ULONG
typedef long Int32;
typedef unsigned long UInt32;
#else
typedef int Int32;
typedef unsigned int UInt32;
#endif
#ifdef _SZ_NO_INT_64
/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers.
NOTES: Some code will work incorrectly in that case! */
typedef long Int64;
typedef unsigned long UInt64;
#else
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#define UINT64_CONST(n) n
#else
typedef long long int Int64;
typedef unsigned long long int UInt64;
#define UINT64_CONST(n) n ## ULL
#endif
#endif
#ifdef _LZMA_NO_SYSTEM_SIZE_T
typedef UInt32 SizeT;
#else
typedef size_t SizeT;
#endif
typedef int Bool;
#define True 1
#define False 0
#ifdef _WIN32
#define MY_STD_CALL __stdcall
#else
#define MY_STD_CALL
#endif
#ifdef _MSC_VER
#if _MSC_VER >= 1300
#define MY_NO_INLINE __declspec(noinline)
#else
#define MY_NO_INLINE
#endif
#define MY_CDECL __cdecl
#define MY_FAST_CALL __fastcall
#else
#define MY_CDECL
#define MY_FAST_CALL
#endif
/* The following interfaces use first parameter as pointer to structure */
typedef struct
{
Byte (*Read)(void *p); /* reads one byte, returns 0 in case of EOF or error */
} IByteIn;
typedef struct
{
void (*Write)(void *p, Byte b);
} IByteOut;
typedef struct
{
SRes (*Read)(void *p, void *buf, size_t *size);
/* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
(output(*size) < input(*size)) is allowed */
} ISeqInStream;
/* it can return SZ_ERROR_INPUT_EOF */
SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size);
SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType);
SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf);
typedef struct
{
size_t (*Write)(void *p, const void *buf, size_t size);
/* Returns: result - the number of actually written bytes.
(result < size) means error */
} ISeqOutStream;
typedef enum
{
SZ_SEEK_SET = 0,
SZ_SEEK_CUR = 1,
SZ_SEEK_END = 2
} ESzSeek;
typedef struct
{
SRes (*Read)(void *p, void *buf, size_t *size); /* same as ISeqInStream::Read */
SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin);
off_t curpos;
} ISeekInStream;
typedef struct
{
SRes (*Look)(void *p, const void **buf, size_t *size);
/* if (input(*size) != 0 && output(*size) == 0) means end_of_stream.
(output(*size) > input(*size)) is not allowed
(output(*size) < input(*size)) is allowed */
SRes (*Skip)(void *p, size_t offset);
/* offset must be <= output(*size) of Look */
SRes (*Read)(void *p, void *buf, size_t *size);
/* reads directly (without buffer). It's same as ISeqInStream::Read */
SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin);
} ILookInStream;
SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size);
SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset);
/* reads via ILookInStream::Read */
SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType);
SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size);
#define LookToRead_BUF_SIZE (1 << 14)
typedef struct
{
ILookInStream s;
ISeekInStream *realStream;
size_t pos;
size_t size;
Byte buf[LookToRead_BUF_SIZE];
} CLookToRead;
void LookToRead_CreateVTable(CLookToRead *p, int lookahead);
void LookToRead_Init(CLookToRead *p);
typedef struct
{
ISeqInStream s;
ILookInStream *realStream;
} CSecToLook;
void SecToLook_CreateVTable(CSecToLook *p);
typedef struct
{
ISeqInStream s;
ILookInStream *realStream;
} CSecToRead;
void SecToRead_CreateVTable(CSecToRead *p);
typedef struct
{
SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize);
/* Returns: result. (result != SZ_OK) means break.
Value (UInt64)(Int64)-1 for size means unknown value. */
} ICompressProgress;
typedef struct
{
void *(*Alloc)(void *p, size_t size);
void (*Free)(void *p, void *address); /* address can be 0 */
} ISzAlloc;
#define IAlloc_Alloc(p, size) (p)->Alloc((p), size)
#define IAlloc_Free(p, a) (p)->Free((p), a)
#ifdef _WIN32
#define CHAR_PATH_SEPARATOR '\\'
#define WCHAR_PATH_SEPARATOR L'\\'
#define STRING_PATH_SEPARATOR "\\"
#define WSTRING_PATH_SEPARATOR L"\\"
#else
#define CHAR_PATH_SEPARATOR '/'
#define WCHAR_PATH_SEPARATOR L'/'
#define STRING_PATH_SEPARATOR "/"
#define WSTRING_PATH_SEPARATOR L"/"
#endif
EXTERN_C_END
#endif
+102
View File
@@ -0,0 +1,102 @@
/* Xz.c - Xz
2009-04-15 : Igor Pavlov : Public domain */
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "7zCrc.h"
#include "CpuArch.h"
#include "Xz.h"
#include "XzCrc64.h"
Byte XZ_SIG[XZ_SIG_SIZE] = { 0xFD, '7', 'z', 'X', 'Z', 0 };
Byte XZ_FOOTER_SIG[XZ_FOOTER_SIG_SIZE] = { 'Y', 'Z' };
unsigned Xz_WriteVarInt(Byte *buf, UInt64 v)
{
unsigned i = 0;
do
{
buf[i++] = (Byte)((v & 0x7F) | 0x80);
v >>= 7;
}
while (v != 0);
buf[i - 1] &= 0x7F;
return i;
}
void Xz_Construct(CXzStream *p)
{
p->numBlocks = p->numBlocksAllocated = 0;
p->blocks = 0;
p->flags = 0;
}
void Xz_Free(CXzStream *p, ISzAlloc *alloc)
{
alloc->Free(alloc, p->blocks);
p->numBlocks = p->numBlocksAllocated = 0;
p->blocks = 0;
}
unsigned XzFlags_GetCheckSize(CXzStreamFlags f)
{
int t = XzFlags_GetCheckType(f);
return (t == 0) ? 0 : (4 << ((t - 1) / 3));
}
void XzCheck_Init(CXzCheck *p, int mode)
{
p->mode = mode;
switch (mode)
{
case XZ_CHECK_CRC32: p->crc = CRC_INIT_VAL; break;
case XZ_CHECK_CRC64: p->crc64 = CRC64_INIT_VAL; break;
case XZ_CHECK_SHA256:
p->sha = cl_hash_init("sha256");
break;
}
}
void XzCheck_Update(CXzCheck *p, const void *data, size_t size)
{
switch (p->mode)
{
case XZ_CHECK_CRC32: p->crc = CrcUpdate(p->crc, data, size); break;
case XZ_CHECK_CRC64: p->crc64 = Crc64Update(p->crc64, data, size); break;
case XZ_CHECK_SHA256:
if ((p->sha))
cl_update_hash(p->sha, (void *)data, size);
break;
}
}
int XzCheck_Final(CXzCheck *p, Byte *digest)
{
switch (p->mode)
{
case XZ_CHECK_CRC32:
SetUi32(digest, CRC_GET_DIGEST(p->crc));
break;
case XZ_CHECK_CRC64:
{
int i;
UInt64 v = CRC64_GET_DIGEST(p->crc64);
for (i = 0; i < 8; i++, v >>= 8)
digest[i] = (Byte)(v & 0xFF);
break;
}
case XZ_CHECK_SHA256:
if (!(p->sha))
return 0;
cl_finish_hash(p->sha, digest);
p->sha = NULL;
break;
default:
return 0;
}
return 1;
}
+254
View File
@@ -0,0 +1,254 @@
/* Xz.h - Xz interface
2010-09-17 : Igor Pavlov : Public domain */
#ifndef __XZ_H
#define __XZ_H
#include "Types.h"
#define SHA256_DIGEST_SIZE 32
EXTERN_C_BEGIN
#define XZ_ID_Subblock 1
#define XZ_ID_Delta 3
#define XZ_ID_X86 4
#define XZ_ID_PPC 5
#define XZ_ID_IA64 6
#define XZ_ID_ARM 7
#define XZ_ID_ARMT 8
#define XZ_ID_SPARC 9
#define XZ_ID_LZMA2 0x21
unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value);
unsigned Xz_WriteVarInt(Byte *buf, UInt64 v);
/* ---------- xz block ---------- */
#define XZ_BLOCK_HEADER_SIZE_MAX 1024
#define XZ_NUM_FILTERS_MAX 4
#define XZ_BF_NUM_FILTERS_MASK 3
#define XZ_BF_PACK_SIZE (1 << 6)
#define XZ_BF_UNPACK_SIZE (1 << 7)
#define XZ_FILTER_PROPS_SIZE_MAX 20
typedef struct
{
UInt64 id;
UInt32 propsSize;
Byte props[XZ_FILTER_PROPS_SIZE_MAX];
} CXzFilter;
typedef struct
{
UInt64 packSize;
UInt64 unpackSize;
Byte flags;
CXzFilter filters[XZ_NUM_FILTERS_MAX];
} CXzBlock;
#define XzBlock_GetNumFilters(p) (((p)->flags & XZ_BF_NUM_FILTERS_MASK) + 1)
#define XzBlock_HasPackSize(p) (((p)->flags & XZ_BF_PACK_SIZE) != 0)
#define XzBlock_HasUnpackSize(p) (((p)->flags & XZ_BF_UNPACK_SIZE) != 0)
SRes XzBlock_Parse(CXzBlock *p, const Byte *header);
SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, Bool *isIndex, UInt32 *headerSizeRes);
/* ---------- xz stream ---------- */
#define XZ_SIG_SIZE 6
#define XZ_FOOTER_SIG_SIZE 2
extern Byte XZ_SIG[XZ_SIG_SIZE];
extern Byte XZ_FOOTER_SIG[XZ_FOOTER_SIG_SIZE];
#define XZ_STREAM_FLAGS_SIZE 2
#define XZ_STREAM_CRC_SIZE 4
#define XZ_STREAM_HEADER_SIZE (XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE + XZ_STREAM_CRC_SIZE)
#define XZ_STREAM_FOOTER_SIZE (XZ_FOOTER_SIG_SIZE + XZ_STREAM_FLAGS_SIZE + XZ_STREAM_CRC_SIZE + 4)
#define XZ_CHECK_MASK 0xF
#define XZ_CHECK_NO 0
#define XZ_CHECK_CRC32 1
#define XZ_CHECK_CRC64 4
#define XZ_CHECK_SHA256 10
typedef struct
{
int mode;
UInt32 crc;
UInt64 crc64;
void *sha;
} CXzCheck;
void XzCheck_Init(CXzCheck *p, int mode);
void XzCheck_Update(CXzCheck *p, const void *data, size_t size);
int XzCheck_Final(CXzCheck *p, Byte *digest);
typedef UInt16 CXzStreamFlags;
#define XzFlags_IsSupported(f) ((f) <= XZ_CHECK_MASK)
#define XzFlags_GetCheckType(f) ((f) & XZ_CHECK_MASK)
#define XzFlags_HasDataCrc32(f) (Xz_GetCheckType(f) == XZ_CHECK_CRC32)
unsigned XzFlags_GetCheckSize(CXzStreamFlags f);
SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf);
SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream);
typedef struct
{
UInt64 unpackSize;
UInt64 totalSize;
} CXzBlockSizes;
typedef struct
{
CXzStreamFlags flags;
size_t numBlocks;
size_t numBlocksAllocated;
CXzBlockSizes *blocks;
UInt64 startOffset;
} CXzStream;
void Xz_Construct(CXzStream *p);
void Xz_Free(CXzStream *p, ISzAlloc *alloc);
#define XZ_SIZE_OVERFLOW ((UInt64)(Int64)-1)
UInt64 Xz_GetUnpackSize(const CXzStream *p);
UInt64 Xz_GetPackSize(const CXzStream *p);
typedef struct
{
size_t num;
size_t numAllocated;
CXzStream *streams;
} CXzs;
void Xzs_Construct(CXzs *p);
void Xzs_Free(CXzs *p, ISzAlloc *alloc);
SRes Xzs_ReadBackward(CXzs *p, ILookInStream *inStream, Int64 *startOffset, ICompressProgress *progress, ISzAlloc *alloc);
UInt64 Xzs_GetNumBlocks(const CXzs *p);
UInt64 Xzs_GetUnpackSize(const CXzs *p);
typedef enum
{
CODER_STATUS_NOT_SPECIFIED, /* use main error code instead */
CODER_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */
CODER_STATUS_NOT_FINISHED, /* stream was not finished */
CODER_STATUS_NEEDS_MORE_INPUT /* you must provide more input bytes */
} ECoderStatus;
typedef enum
{
CODER_FINISH_ANY, /* finish at any point */
CODER_FINISH_END /* block must be finished at the end */
} ECoderFinishMode;
typedef struct _IStateCoder
{
void *p;
void (*Free)(void *p, ISzAlloc *alloc);
SRes (*SetProps)(void *p, const Byte *props, size_t propSize, ISzAlloc *alloc);
void (*Init)(void *p);
SRes (*Code)(void *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished);
} IStateCoder;
#define MIXCODER_NUM_FILTERS_MAX 4
typedef struct
{
ISzAlloc *alloc;
Byte *buf;
int numCoders;
int finished[MIXCODER_NUM_FILTERS_MAX - 1];
size_t pos[MIXCODER_NUM_FILTERS_MAX - 1];
size_t size[MIXCODER_NUM_FILTERS_MAX - 1];
UInt64 ids[MIXCODER_NUM_FILTERS_MAX];
IStateCoder coders[MIXCODER_NUM_FILTERS_MAX];
} CMixCoder;
void MixCoder_Construct(CMixCoder *p, ISzAlloc *alloc);
void MixCoder_Free(CMixCoder *p);
void MixCoder_Init(CMixCoder *p);
SRes MixCoder_SetFromMethod(CMixCoder *p, int coderIndex, UInt64 methodId);
SRes MixCoder_Code(CMixCoder *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, int srcWasFinished,
ECoderFinishMode finishMode, ECoderStatus *status);
typedef enum
{
XZ_STATE_STREAM_HEADER,
XZ_STATE_STREAM_INDEX,
XZ_STATE_STREAM_INDEX_CRC,
XZ_STATE_STREAM_FOOTER,
XZ_STATE_STREAM_PADDING,
XZ_STATE_BLOCK_HEADER,
XZ_STATE_BLOCK,
XZ_STATE_BLOCK_FOOTER
} EXzState;
typedef struct
{
EXzState state;
UInt32 pos;
unsigned alignPos;
unsigned indexPreSize;
CXzStreamFlags streamFlags;
UInt32 blockHeaderSize;
UInt64 packSize;
UInt64 unpackSize;
UInt64 numBlocks;
UInt64 indexSize;
UInt64 indexPos;
UInt64 padSize;
UInt64 numStreams;
UInt32 crc;
CMixCoder decoder;
CXzBlock block;
CXzCheck check;
void *sha;
Byte shaDigest[SHA256_DIGEST_SIZE];
Byte buf[XZ_BLOCK_HEADER_SIZE_MAX];
} CXzUnpacker;
SRes XzUnpacker_Create(CXzUnpacker *p, ISzAlloc *alloc);
void XzUnpacker_Free(CXzUnpacker *p);
/*
finishMode:
It has meaning only if the decoding reaches output limit (*destLen).
LZMA_FINISH_ANY - use smallest number of input bytes
LZMA_FINISH_END - read EndOfStream marker after decoding
Returns:
SZ_OK
status:
LZMA_STATUS_FINISHED_WITH_MARK
LZMA_STATUS_NOT_FINISHED
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - Unsupported properties
SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src).
*/
SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, /* int srcWasFinished, */ int finishMode,
ECoderStatus *status);
Bool XzUnpacker_IsStreamWasFinished(CXzUnpacker *p);
EXTERN_C_END
#endif
+33
View File
@@ -0,0 +1,33 @@
/* XzCrc64.c -- CRC64 calculation
2010-04-16 : Igor Pavlov : Public domain */
#include "XzCrc64.h"
#define kCrc64Poly UINT64_CONST(0xC96C5795D7870F42)
UInt64 g_Crc64Table[256];
void MY_FAST_CALL Crc64GenerateTable(void)
{
UInt32 i;
for (i = 0; i < 256; i++)
{
UInt64 r = i;
int j;
for (j = 0; j < 8; j++)
r = (r >> 1) ^ ((UInt64)kCrc64Poly & ~((r & 1) - 1));
g_Crc64Table[i] = r;
}
}
UInt64 MY_FAST_CALL Crc64Update(UInt64 v, const void *data, size_t size)
{
const Byte *p = (const Byte *)data;
for (; size > 0 ; size--, p++)
v = CRC64_UPDATE_BYTE(v, *p);
return v;
}
UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size)
{
return CRC64_GET_DIGEST(Crc64Update(CRC64_INIT_VAL, data, size));
}
+26
View File
@@ -0,0 +1,26 @@
/* XzCrc64.h -- CRC64 calculation
2010-04-16 : Igor Pavlov : Public domain */
#ifndef __XZ_CRC64_H
#define __XZ_CRC64_H
#include <stddef.h>
#include "Types.h"
EXTERN_C_BEGIN
extern UInt64 g_Crc64Table[];
void MY_FAST_CALL Crc64GenerateTable(void);
#define CRC64_INIT_VAL UINT64_CONST(0xFFFFFFFFFFFFFFFF)
#define CRC64_GET_DIGEST(crc) ((crc) ^ CRC64_INIT_VAL)
#define CRC64_UPDATE_BYTE(crc, b) (g_Crc64Table[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt64 MY_FAST_CALL Crc64Update(UInt64 crc, const void *data, size_t size);
UInt64 MY_FAST_CALL Crc64Calc(const void *data, size_t size);
EXTERN_C_END
#endif
+905
View File
@@ -0,0 +1,905 @@
/* XzDec.c -- Xz Decode
2010-04-16 : Igor Pavlov : Public domain */
/* #define XZ_DUMP */
#ifdef XZ_DUMP
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "clamav.h"
#include "7zCrc.h"
#include "Alloc.h"
#include "Bra.h"
#include "CpuArch.h"
#include "Delta.h"
#include "Lzma2Dec.h"
#ifdef USE_SUBBLOCK
#include "SbDec.h"
#endif
#include "Xz.h"
#define XZ_CHECK_SIZE_MAX 64
#define CODER_BUF_SIZE (1 << 17)
void BraState_Free(void *pp, ISzAlloc *alloc);
SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc);
void BraState_Init(void *pp);
SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, ISzAlloc *alloc);
unsigned Xz_ReadVarInt(const Byte *p, size_t maxSize, UInt64 *value)
{
int i, limit;
*value = 0;
limit = (maxSize > 9) ? 9 : (int)maxSize;
for (i = 0; i < limit;)
{
Byte b = p[i];
*value |= (UInt64)(b & 0x7F) << (7 * i++);
if ((b & 0x80) == 0)
return (b == 0 && i != 1) ? 0 : i;
}
return 0;
}
/* ---------- BraState ---------- */
#define BRA_BUF_SIZE (1 << 14)
typedef struct
{
size_t bufPos;
size_t bufConv;
size_t bufTotal;
UInt32 methodId;
int encodeMode;
UInt32 delta;
UInt32 ip;
UInt32 x86State;
Byte deltaState[DELTA_STATE_SIZE];
Byte buf[BRA_BUF_SIZE];
} CBraState;
void BraState_Free(void *pp, ISzAlloc *alloc)
{
alloc->Free(alloc, pp);
}
SRes BraState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc)
{
CBraState *p = ((CBraState *)pp);
UNUSEDPARAM(alloc);
p->encodeMode = 0;
p->ip = 0;
if (p->methodId == XZ_ID_Delta)
{
if (propSize != 1)
return SZ_ERROR_UNSUPPORTED;
p->delta = (unsigned)props[0] + 1;
}
else
{
if (propSize == 4)
{
UInt32 v = GetUi32(props);
switch(p->methodId)
{
case XZ_ID_PPC:
case XZ_ID_ARM:
case XZ_ID_SPARC:
if ((v & 3) != 0)
return SZ_ERROR_UNSUPPORTED;
break;
case XZ_ID_ARMT:
if ((v & 1) != 0)
return SZ_ERROR_UNSUPPORTED;
break;
case XZ_ID_IA64:
if ((v & 0xF) != 0)
return SZ_ERROR_UNSUPPORTED;
break;
}
p->ip = v;
}
else if (propSize != 0)
return SZ_ERROR_UNSUPPORTED;
}
return SZ_OK;
}
void BraState_Init(void *pp)
{
CBraState *p = ((CBraState *)pp);
p->bufPos = p->bufConv = p->bufTotal = 0;
x86_Convert_Init(p->x86State);
if (p->methodId == XZ_ID_Delta)
Delta_Init(p->deltaState);
}
#define CASE_BRA_CONV(isa) case XZ_ID_ ## isa: p->bufConv = isa ## _Convert(p->buf, p->bufTotal, p->ip, p->encodeMode); break;
static SRes BraState_Code(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished)
{
CBraState *p = ((CBraState *)pp);
SizeT destLenOrig = *destLen;
SizeT srcLenOrig = *srcLen;
UNUSEDPARAM(finishMode);
*destLen = 0;
*srcLen = 0;
*wasFinished = 0;
while (destLenOrig > 0)
{
if (p->bufPos != p->bufConv)
{
size_t curSize = p->bufConv - p->bufPos;
if (curSize > destLenOrig)
curSize = destLenOrig;
memcpy(dest, p->buf + p->bufPos, curSize);
p->bufPos += curSize;
*destLen += curSize;
dest += curSize;
destLenOrig -= curSize;
continue;
}
p->bufTotal -= p->bufPos;
memmove(p->buf, p->buf + p->bufPos, p->bufTotal);
p->bufPos = 0;
p->bufConv = 0;
{
size_t curSize = BRA_BUF_SIZE - p->bufTotal;
if (curSize > srcLenOrig)
curSize = srcLenOrig;
memcpy(p->buf + p->bufTotal, src, curSize);
*srcLen += curSize;
src += curSize;
srcLenOrig -= curSize;
p->bufTotal += curSize;
}
if (p->bufTotal == 0)
break;
switch(p->methodId)
{
case XZ_ID_Delta:
if (p->encodeMode)
Delta_Encode(p->deltaState, p->delta, p->buf, p->bufTotal);
else
Delta_Decode(p->deltaState, p->delta, p->buf, p->bufTotal);
p->bufConv = p->bufTotal;
break;
case XZ_ID_X86:
p->bufConv = x86_Convert(p->buf, p->bufTotal, p->ip, &p->x86State, p->encodeMode);
break;
CASE_BRA_CONV(PPC)
CASE_BRA_CONV(IA64)
CASE_BRA_CONV(ARM)
CASE_BRA_CONV(ARMT)
CASE_BRA_CONV(SPARC)
default:
return SZ_ERROR_UNSUPPORTED;
}
p->ip += (UInt32)p->bufConv;
if (p->bufConv == 0)
{
if (!srcWasFinished)
break;
p->bufConv = p->bufTotal;
}
}
if (p->bufTotal == p->bufPos && srcLenOrig == 0 && srcWasFinished)
*wasFinished = 1;
return SZ_OK;
}
SRes BraState_SetFromMethod(IStateCoder *p, UInt64 id, ISzAlloc *alloc)
{
CBraState *decoder;
if (id != XZ_ID_Delta &&
id != XZ_ID_X86 &&
id != XZ_ID_PPC &&
id != XZ_ID_IA64 &&
id != XZ_ID_ARM &&
id != XZ_ID_ARMT &&
id != XZ_ID_SPARC)
return SZ_ERROR_UNSUPPORTED;
p->p = 0;
decoder = alloc->Alloc(alloc, sizeof(CBraState));
if (decoder == 0)
return SZ_ERROR_MEM;
decoder->methodId = (UInt32)id;
p->p = decoder;
p->Free = BraState_Free;
p->SetProps = BraState_SetProps;
p->Init = BraState_Init;
p->Code = BraState_Code;
return SZ_OK;
}
/* ---------- SbState ---------- */
#ifdef USE_SUBBLOCK
static void SbState_Free(void *pp, ISzAlloc *alloc)
{
CSubblockDec *p = (CSubblockDec *)pp;
SubblockDec_Free(p, alloc);
alloc->Free(alloc, pp);
}
static SRes SbState_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc)
{
pp = pp;
props = props;
alloc = alloc;
return (propSize == 0) ? SZ_OK : SZ_ERROR_UNSUPPORTED;
}
static void SbState_Init(void *pp)
{
SubblockDec_Init((CSubblockDec *)pp);
}
static SRes SbState_Code(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished)
{
ECoderStatus status;
SRes res = SubblockDec_Decode((CSubblockDec *)pp, dest, destLen, src, srcLen, finishMode, &status);
srcWasFinished = srcWasFinished;
*wasFinished = (status == LZMA_STATUS_FINISHED_WITH_MARK);
return res;
}
SRes SbState_SetFromMethod(IStateCoder *p, ISzAlloc *alloc)
{
CSubblockDec *decoder;
p->p = 0;
decoder = alloc->Alloc(alloc, sizeof(CSubblockDec));
if (decoder == 0)
return SZ_ERROR_MEM;
p->p = decoder;
p->Free = SbState_Free;
p->SetProps = SbState_SetProps;
p->Init = SbState_Init;
p->Code = SbState_Code;
SubblockDec_Construct(decoder);
return SZ_OK;
}
#endif
/* ---------- Lzma2State ---------- */
static void Lzma2State_Free(void *pp, ISzAlloc *alloc)
{
Lzma2Dec_Free((CLzma2Dec *)pp, alloc);
alloc->Free(alloc, pp);
}
static SRes Lzma2State_SetProps(void *pp, const Byte *props, size_t propSize, ISzAlloc *alloc)
{
if (propSize != 1)
return SZ_ERROR_UNSUPPORTED;
return Lzma2Dec_Allocate((CLzma2Dec *)pp, props[0], alloc);
}
static void Lzma2State_Init(void *pp)
{
Lzma2Dec_Init((CLzma2Dec *)pp);
}
static SRes Lzma2State_Code(void *pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen,
int srcWasFinished, ECoderFinishMode finishMode, int *wasFinished)
{
ELzmaStatus status;
/* ELzmaFinishMode fm = (finishMode == LZMA_FINISH_ANY) ? LZMA_FINISH_ANY : LZMA_FINISH_END; */
SRes res = Lzma2Dec_DecodeToBuf((CLzma2Dec *)pp, dest, destLen, src, srcLen, finishMode, &status);
UNUSEDPARAM(srcWasFinished);
*wasFinished = (status == LZMA_STATUS_FINISHED_WITH_MARK);
return res;
}
static SRes Lzma2State_SetFromMethod(IStateCoder *p, ISzAlloc *alloc)
{
CLzma2Dec *decoder = alloc->Alloc(alloc, sizeof(CLzma2Dec));
p->p = decoder;
if (decoder == 0)
return SZ_ERROR_MEM;
p->Free = Lzma2State_Free;
p->SetProps = Lzma2State_SetProps;
p->Init = Lzma2State_Init;
p->Code = Lzma2State_Code;
Lzma2Dec_Construct(decoder);
return SZ_OK;
}
void MixCoder_Construct(CMixCoder *p, ISzAlloc *alloc)
{
int i;
p->alloc = alloc;
p->buf = NULL;
p->numCoders = 0;
for (i = 0; i < MIXCODER_NUM_FILTERS_MAX; i++)
p->coders[i].p = NULL;
}
void MixCoder_Free(CMixCoder *p)
{
int i;
for (i = 0; i < p->numCoders; i++)
{
IStateCoder *sc = &p->coders[i];
if (p->alloc && sc->p)
sc->Free(sc->p, p->alloc);
}
p->numCoders = 0;
if (p->buf)
{
p->alloc->Free(p->alloc, p->buf);
p->buf = NULL; /* 9.31: the BUG was fixed */
}
}
void MixCoder_Init(CMixCoder *p)
{
int i;
for (i = 0; i < p->numCoders - 1; i++)
{
p->size[i] = 0;
p->pos[i] = 0;
p->finished[i] = 0;
}
for (i = 0; i < p->numCoders; i++)
{
IStateCoder *coder = &p->coders[i];
coder->Init(coder->p);
}
}
SRes MixCoder_SetFromMethod(CMixCoder *p, int coderIndex, UInt64 methodId)
{
IStateCoder *sc = &p->coders[coderIndex];
p->ids[coderIndex] = methodId;
switch(methodId)
{
case XZ_ID_LZMA2: return Lzma2State_SetFromMethod(sc, p->alloc);
#ifdef USE_SUBBLOCK
case XZ_ID_Subblock: return SbState_SetFromMethod(sc, p->alloc);
#endif
}
if (coderIndex == 0)
return SZ_ERROR_UNSUPPORTED;
return BraState_SetFromMethod(sc, methodId, p->alloc);
}
SRes MixCoder_Code(CMixCoder *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, int srcWasFinished,
ECoderFinishMode finishMode, ECoderStatus *status)
{
SizeT destLenOrig = *destLen;
SizeT srcLenOrig = *srcLen;
Bool allFinished = True;
*destLen = 0;
*srcLen = 0;
*status = CODER_STATUS_NOT_FINISHED;
if (p->buf == 0)
{
p->buf = p->alloc->Alloc(p->alloc, CODER_BUF_SIZE * (MIXCODER_NUM_FILTERS_MAX - 1));
if (p->buf == 0)
return SZ_ERROR_MEM;
}
if (p->numCoders != 1)
finishMode = CODER_FINISH_ANY;
for (;;)
{
Bool processed = False;
int i;
/*
if (p->numCoders == 1 && *destLen == destLenOrig && finishMode == LZMA_FINISH_ANY)
break;
*/
for (i = 0; i < p->numCoders; i++)
{
SRes res;
IStateCoder *coder = &p->coders[i];
Byte *destCur;
SizeT destLenCur, srcLenCur;
const Byte *srcCur;
int srcFinishedCur;
int encodingWasFinished;
if (i == 0)
{
srcCur = src;
srcLenCur = srcLenOrig - *srcLen;
srcFinishedCur = srcWasFinished;
}
else
{
srcCur = p->buf + (CODER_BUF_SIZE * (i - 1)) + p->pos[i - 1];
srcLenCur = p->size[i - 1] - p->pos[i - 1];
srcFinishedCur = p->finished[i - 1];
}
if (i == p->numCoders - 1)
{
destCur = dest;
destLenCur = destLenOrig - *destLen;
}
else
{
if (p->pos[i] != p->size[i])
continue;
destCur = p->buf + (CODER_BUF_SIZE * i);
destLenCur = CODER_BUF_SIZE;
}
res = coder->Code(coder->p, destCur, &destLenCur, srcCur, &srcLenCur, srcFinishedCur, finishMode, &encodingWasFinished);
if (!encodingWasFinished)
allFinished = False;
if (i == 0)
{
*srcLen += srcLenCur;
src += srcLenCur;
}
else
{
p->pos[i - 1] += srcLenCur;
}
if (i == p->numCoders - 1)
{
*destLen += destLenCur;
dest += destLenCur;
}
else
{
p->size[i] = destLenCur;
p->pos[i] = 0;
p->finished[i] = encodingWasFinished;
}
if (res != SZ_OK)
return res;
if (destLenCur != 0 || srcLenCur != 0)
processed = True;
}
if (!processed)
break;
}
if (allFinished)
*status = CODER_STATUS_FINISHED_WITH_MARK;
return SZ_OK;
}
SRes Xz_ParseHeader(CXzStreamFlags *p, const Byte *buf)
{
*p = (CXzStreamFlags)GetBe16(buf + XZ_SIG_SIZE);
if (CrcCalc(buf + XZ_SIG_SIZE, XZ_STREAM_FLAGS_SIZE) !=
GetUi32(buf + XZ_SIG_SIZE + XZ_STREAM_FLAGS_SIZE))
return SZ_ERROR_NO_ARCHIVE;
return XzFlags_IsSupported(*p) ? SZ_OK : SZ_ERROR_UNSUPPORTED;
}
static Bool Xz_CheckFooter(CXzStreamFlags flags, UInt64 indexSize, const Byte *buf)
{
return
indexSize == (((UInt64)GetUi32(buf + 4) + 1) << 2) &&
(GetUi32(buf) == CrcCalc(buf + 4, 6) &&
flags == GetBe16(buf + 8) &&
memcmp(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE) == 0);
}
#define READ_VARINT_AND_CHECK(buf, pos, size, res) \
{ unsigned s = Xz_ReadVarInt(buf + pos, size - pos, res); \
if (s == 0) return SZ_ERROR_ARCHIVE; pos += s; }
SRes XzBlock_Parse(CXzBlock *p, const Byte *header)
{
unsigned pos;
int numFilters, i;
UInt32 headerSize = (UInt32)header[0] << 2;
if (CrcCalc(header, headerSize) != GetUi32(header + headerSize))
return SZ_ERROR_ARCHIVE;
pos = 1;
if (pos == headerSize)
return SZ_ERROR_ARCHIVE;
p->flags = header[pos++];
if (XzBlock_HasPackSize(p))
{
READ_VARINT_AND_CHECK(header, pos, headerSize, &p->packSize);
if (p->packSize == 0 || p->packSize + headerSize >= (UInt64)1 << 63)
return SZ_ERROR_ARCHIVE;
}
if (XzBlock_HasUnpackSize(p))
READ_VARINT_AND_CHECK(header, pos, headerSize, &p->unpackSize);
numFilters = XzBlock_GetNumFilters(p);
for (i = 0; i < numFilters; i++)
{
CXzFilter *filter = p->filters + i;
UInt64 size;
READ_VARINT_AND_CHECK(header, pos, headerSize, &filter->id);
READ_VARINT_AND_CHECK(header, pos, headerSize, &size);
if (size > headerSize - pos || size > XZ_FILTER_PROPS_SIZE_MAX)
return SZ_ERROR_ARCHIVE;
filter->propsSize = (UInt32)size;
memcpy(filter->props, header + pos, (size_t)size);
pos += (unsigned)size;
#ifdef XZ_DUMP
printf("\nf[%d] = %2X: ", i, filter->id);
{
int i;
for (i = 0; i < size; i++)
printf(" %2X", filter->props[i]);
}
#endif
}
while (pos < headerSize)
if (header[pos++] != 0)
return SZ_ERROR_ARCHIVE;
return SZ_OK;
}
SRes XzDec_Init(CMixCoder *p, const CXzBlock *block)
{
int i;
Bool needReInit = True;
int numFilters = XzBlock_GetNumFilters(block);
if (numFilters == p->numCoders)
{
for (i = 0; i < numFilters; i++)
if (p->ids[i] != block->filters[numFilters - 1 - i].id)
break;
needReInit = (i != numFilters);
}
if (needReInit)
{
MixCoder_Free(p);
p->numCoders = numFilters;
for (i = 0; i < numFilters; i++)
{
const CXzFilter *f = &block->filters[numFilters - 1 - i];
RINOK(MixCoder_SetFromMethod(p, i, f->id));
}
}
for (i = 0; i < numFilters; i++)
{
const CXzFilter *f = &block->filters[numFilters - 1 - i];
IStateCoder *sc = &p->coders[i];
RINOK(sc->SetProps(sc->p, f->props, f->propsSize, p->alloc));
}
MixCoder_Init(p);
return SZ_OK;
}
SRes XzUnpacker_Create(CXzUnpacker *p, ISzAlloc *alloc)
{
MixCoder_Construct(&p->decoder, alloc);
p->state = XZ_STATE_STREAM_HEADER;
p->pos = 0;
p->numStreams = 0;
p->numBlocks = 0;
p->padSize = 0;
return SZ_OK;
}
void XzUnpacker_Free(CXzUnpacker *p)
{
if (!p)
return;
MixCoder_Free(&p->decoder);
cl_hash_destroy(p->check.sha);
cl_hash_destroy(p->sha);
p->sha = NULL;
}
SRes XzUnpacker_Code(CXzUnpacker *p, Byte *dest, SizeT *destLen,
const Byte *src, SizeT *srcLen, int finishMode, ECoderStatus *status)
{
SizeT destLenOrig = *destLen;
SizeT srcLenOrig = *srcLen;
*destLen = 0;
*srcLen = 0;
*status = CODER_STATUS_NOT_SPECIFIED;
for (;;)
{
SizeT srcRem = srcLenOrig - *srcLen;
if (p->state == XZ_STATE_BLOCK)
{
SizeT destLen2 = destLenOrig - *destLen;
SizeT srcLen2 = srcLenOrig - *srcLen;
SRes res;
if (srcLen2 == 0 && destLen2 == 0)
{
*status = CODER_STATUS_NOT_FINISHED;
return SZ_OK;
}
res = MixCoder_Code(&p->decoder, dest, &destLen2, src, &srcLen2, False, finishMode, status);
XzCheck_Update(&p->check, dest, destLen2);
(*srcLen) += srcLen2;
src += srcLen2;
p->packSize += srcLen2;
(*destLen) += destLen2;
dest += destLen2;
p->unpackSize += destLen2;
RINOK(res);
if (*status == CODER_STATUS_FINISHED_WITH_MARK)
{
Byte temp[32];
unsigned num = Xz_WriteVarInt(temp, p->packSize + p->blockHeaderSize + XzFlags_GetCheckSize(p->streamFlags));
num += Xz_WriteVarInt(temp + num, p->unpackSize);
if ((p->sha))
cl_update_hash(p->sha, temp, num);
p->indexSize += num;
p->numBlocks++;
p->state = XZ_STATE_BLOCK_FOOTER;
p->pos = 0;
p->alignPos = 0;
}
else if (srcLen2 == 0 && destLen2 == 0)
return SZ_OK;
continue;
}
if (srcRem == 0)
{
*status = CODER_STATUS_NEEDS_MORE_INPUT;
return SZ_OK;
}
switch(p->state)
{
case XZ_STATE_STREAM_HEADER:
{
if (p->pos < XZ_STREAM_HEADER_SIZE)
{
if (p->pos < XZ_SIG_SIZE && *src != XZ_SIG[p->pos])
return SZ_ERROR_NO_ARCHIVE;
p->buf[p->pos++] = *src++;
(*srcLen)++;
}
else
{
RINOK(Xz_ParseHeader(&p->streamFlags, p->buf));
p->state = XZ_STATE_BLOCK_HEADER;
p->sha = cl_hash_init("sha256");
p->indexSize = 0;
p->numBlocks = 0;
p->pos = 0;
}
break;
}
case XZ_STATE_BLOCK_HEADER:
{
if (p->pos == 0)
{
p->buf[p->pos++] = *src++;
(*srcLen)++;
if (p->buf[0] == 0)
{
p->indexPreSize = 1 + Xz_WriteVarInt(p->buf + 1, p->numBlocks);
p->indexPos = p->indexPreSize;
p->indexSize += p->indexPreSize;
if ((p->sha)) {
cl_finish_hash(p->sha, p->shaDigest);
p->sha = cl_hash_init("sha256");
}
p->crc = CrcUpdate(CRC_INIT_VAL, p->buf, p->indexPreSize);
p->state = XZ_STATE_STREAM_INDEX;
}
p->blockHeaderSize = ((UInt32)p->buf[0] << 2) + 4;
}
else if (p->pos != p->blockHeaderSize)
{
UInt32 cur = p->blockHeaderSize - p->pos;
if (cur > srcRem)
cur = (UInt32)srcRem;
memcpy(p->buf + p->pos, src, cur);
p->pos += cur;
(*srcLen) += cur;
src += cur;
}
else
{
RINOK(XzBlock_Parse(&p->block, p->buf));
p->state = XZ_STATE_BLOCK;
p->packSize = 0;
p->unpackSize = 0;
XzCheck_Init(&p->check, XzFlags_GetCheckType(p->streamFlags));
RINOK(XzDec_Init(&p->decoder, &p->block));
}
break;
}
case XZ_STATE_BLOCK_FOOTER:
{
if (((p->packSize + p->alignPos) & 3) != 0)
{
(*srcLen)++;
p->alignPos++;
if (*src++ != 0)
return SZ_ERROR_CRC;
}
else
{
UInt32 checkSize = XzFlags_GetCheckSize(p->streamFlags);
UInt32 cur = checkSize - p->pos;
if (cur != 0)
{
if (cur > srcRem)
cur = (UInt32)srcRem;
memcpy(p->buf + p->pos, src, cur);
p->pos += cur;
(*srcLen) += cur;
src += cur;
}
else
{
Byte digest[XZ_CHECK_SIZE_MAX];
p->state = XZ_STATE_BLOCK_HEADER;
p->pos = 0;
if (XzCheck_Final(&p->check, digest) && memcmp(digest, p->buf, checkSize) != 0)
return SZ_ERROR_CRC;
}
}
break;
}
case XZ_STATE_STREAM_INDEX:
{
if (p->pos < p->indexPreSize)
{
(*srcLen)++;
if (*src++ != p->buf[p->pos++])
return SZ_ERROR_CRC;
}
else
{
if (p->indexPos < p->indexSize)
{
UInt64 cur = p->indexSize - p->indexPos;
if (srcRem > cur)
srcRem = (SizeT)cur;
p->crc = CrcUpdate(p->crc, src, srcRem);
if ((p->sha))
cl_update_hash(p->sha, (void *)src, srcRem);
(*srcLen) += srcRem;
src += srcRem;
p->indexPos += srcRem;
}
else if ((p->indexPos & 3) != 0)
{
Byte b = *src++;
p->crc = CRC_UPDATE_BYTE(p->crc, b);
(*srcLen)++;
p->indexPos++;
p->indexSize++;
if (b != 0)
return SZ_ERROR_CRC;
}
else
{
Byte digest[SHA256_DIGEST_SIZE];
memset(&digest, 0, SHA256_DIGEST_SIZE);
p->state = XZ_STATE_STREAM_INDEX_CRC;
p->indexSize += 4;
p->pos = 0;
if ((p->sha)) {
cl_finish_hash(p->sha, digest);
p->sha = NULL;
}
if (memcmp(digest, p->shaDigest, SHA256_DIGEST_SIZE) != 0)
return SZ_ERROR_CRC;
}
}
break;
}
case XZ_STATE_STREAM_INDEX_CRC:
{
if (p->pos < 4)
{
(*srcLen)++;
p->buf[p->pos++] = *src++;
}
else
{
p->state = XZ_STATE_STREAM_FOOTER;
p->pos = 0;
if (CRC_GET_DIGEST(p->crc) != GetUi32(p->buf))
return SZ_ERROR_CRC;
}
break;
}
case XZ_STATE_STREAM_FOOTER:
{
UInt32 cur = XZ_STREAM_FOOTER_SIZE - p->pos;
if (cur > srcRem)
cur = (UInt32)srcRem;
memcpy(p->buf + p->pos, src, cur);
p->pos += cur;
(*srcLen) += cur;
src += cur;
if (p->pos == XZ_STREAM_FOOTER_SIZE)
{
p->state = XZ_STATE_STREAM_PADDING;
p->numStreams++;
p->padSize = 0;
if (!Xz_CheckFooter(p->streamFlags, p->indexSize, p->buf))
return SZ_ERROR_CRC;
}
break;
}
case XZ_STATE_STREAM_PADDING:
{
if (*src != 0)
{
if (((UInt32)p->padSize & 3) != 0)
return SZ_ERROR_NO_ARCHIVE;
p->pos = 0;
p->state = XZ_STATE_STREAM_HEADER;
}
else
{
(*srcLen)++;
src++;
p->padSize++;
}
break;
}
case XZ_STATE_BLOCK: break; /* to disable GCC warning */
}
}
/*
if (p->state == XZ_STATE_FINISHED)
*status = CODER_STATUS_FINISHED_WITH_MARK;
return SZ_OK;
*/
}
Bool XzUnpacker_IsStreamWasFinished(CXzUnpacker *p)
{
return (p->state == XZ_STATE_STREAM_PADDING) && (((UInt32)p->padSize & 3) == 0);
}
+312
View File
@@ -0,0 +1,312 @@
/* XzIn.c - Xz input
2009-06-19 : Igor Pavlov : Public domain */
#include <string.h>
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "clamav.h"
#include "7zCrc.h"
#include "CpuArch.h"
#include "Xz.h"
SRes Xz_ReadHeader(CXzStreamFlags *p, ISeqInStream *inStream)
{
Byte sig[XZ_STREAM_HEADER_SIZE];
RINOK(SeqInStream_Read2(inStream, sig, XZ_STREAM_HEADER_SIZE, SZ_ERROR_NO_ARCHIVE));
if (memcmp(sig, XZ_SIG, XZ_SIG_SIZE) != 0)
return SZ_ERROR_NO_ARCHIVE;
return Xz_ParseHeader(p, sig);
}
#define READ_VARINT_AND_CHECK(buf, pos, size, res) \
{ unsigned s = Xz_ReadVarInt(buf + pos, size - pos, res); \
if (s == 0) return SZ_ERROR_ARCHIVE; pos += s; }
SRes XzBlock_ReadHeader(CXzBlock *p, ISeqInStream *inStream, Bool *isIndex, UInt32 *headerSizeRes)
{
Byte header[XZ_BLOCK_HEADER_SIZE_MAX];
unsigned headerSize;
*headerSizeRes = 0;
RINOK(SeqInStream_ReadByte(inStream, &header[0]));
headerSize = ((unsigned)header[0] << 2) + 4;
if (headerSize == 0)
{
*headerSizeRes = 1;
*isIndex = True;
return SZ_OK;
}
*isIndex = False;
*headerSizeRes = headerSize;
RINOK(SeqInStream_Read(inStream, header + 1, headerSize - 1));
return XzBlock_Parse(p, header);
}
#define ADD_SIZE_CHECH(size, val) \
{ UInt64 newSize = size + (val); if (newSize < size) return XZ_SIZE_OVERFLOW; size = newSize; }
UInt64 Xz_GetUnpackSize(const CXzStream *p)
{
UInt64 size = 0;
size_t i;
for (i = 0; i < p->numBlocks; i++)
ADD_SIZE_CHECH(size, p->blocks[i].unpackSize);
return size;
}
UInt64 Xz_GetPackSize(const CXzStream *p)
{
UInt64 size = 0;
size_t i;
for (i = 0; i < p->numBlocks; i++)
ADD_SIZE_CHECH(size, (p->blocks[i].totalSize + 3) & ~(UInt64)3);
return size;
}
/*
SRes XzBlock_ReadFooter(CXzBlock *p, CXzStreamFlags f, ISeqInStream *inStream)
{
return SeqInStream_Read(inStream, p->check, XzFlags_GetCheckSize(f));
}
*/
static SRes Xz_ReadIndex2(CXzStream *p, const Byte *buf, size_t size, ISzAlloc *alloc)
{
size_t i, numBlocks, crcStartPos, pos = 1;
UInt32 crc;
if (size < 5 || buf[0] != 0)
return SZ_ERROR_ARCHIVE;
size -= 4;
crc = CrcCalc(buf, size);
if (crc != GetUi32(buf + size))
return SZ_ERROR_ARCHIVE;
{
UInt64 numBlocks64;
READ_VARINT_AND_CHECK(buf, pos, size, &numBlocks64);
numBlocks = (size_t)numBlocks64;
if (numBlocks != numBlocks64 || numBlocks * 2 > size)
return SZ_ERROR_ARCHIVE;
}
crcStartPos = pos;
Xz_Free(p, alloc);
if (numBlocks != 0)
{
p->numBlocks = numBlocks;
p->numBlocksAllocated = numBlocks;
p->blocks = alloc->Alloc(alloc, sizeof(CXzBlockSizes) * numBlocks);
if (p->blocks == 0)
return SZ_ERROR_MEM;
for (i = 0; i < numBlocks; i++)
{
CXzBlockSizes *block = &p->blocks[i];
READ_VARINT_AND_CHECK(buf, pos, size, &block->totalSize);
READ_VARINT_AND_CHECK(buf, pos, size, &block->unpackSize);
if (block->totalSize == 0)
return SZ_ERROR_ARCHIVE;
}
}
while ((pos & 3) != 0)
if (buf[pos++] != 0)
return SZ_ERROR_ARCHIVE;
return (pos == size) ? SZ_OK : SZ_ERROR_ARCHIVE;
}
static SRes Xz_ReadIndex(CXzStream *p, ILookInStream *stream, UInt64 indexSize, ISzAlloc *alloc)
{
SRes res;
size_t size;
Byte *buf;
if (indexSize > ((UInt32)1 << 31))
return SZ_ERROR_UNSUPPORTED;
size = (size_t)indexSize;
if (size != indexSize)
return SZ_ERROR_UNSUPPORTED;
buf = alloc->Alloc(alloc, size);
if (buf == 0)
return SZ_ERROR_MEM;
res = LookInStream_Read2(stream, buf, size, SZ_ERROR_UNSUPPORTED);
if (res == SZ_OK)
res = Xz_ReadIndex2(p, buf, size, alloc);
alloc->Free(alloc, buf);
return res;
}
static SRes SeekFromCur(ILookInStream *inStream, Int64 *res)
{
return inStream->Seek(inStream, res, SZ_SEEK_CUR);
}
static SRes Xz_ReadBackward(CXzStream *p, ILookInStream *stream, Int64 *startOffset, ISzAlloc *alloc)
{
UInt64 indexSize;
Byte buf[XZ_STREAM_FOOTER_SIZE];
if ((*startOffset & 3) != 0 || *startOffset < XZ_STREAM_FOOTER_SIZE)
return SZ_ERROR_NO_ARCHIVE;
*startOffset = -XZ_STREAM_FOOTER_SIZE;
RINOK(SeekFromCur(stream, startOffset));
RINOK(LookInStream_Read2(stream, buf, XZ_STREAM_FOOTER_SIZE, SZ_ERROR_NO_ARCHIVE));
if (memcmp(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE) != 0)
{
Int64 i = 0;
*startOffset += XZ_STREAM_FOOTER_SIZE;
for (;;)
{
int j;
size_t processedSize;
#define TEMP_BUF_SIZE (1 << 10)
Byte tempBuf[TEMP_BUF_SIZE];
if (*startOffset < XZ_STREAM_FOOTER_SIZE || i > (1 << 16))
return SZ_ERROR_NO_ARCHIVE;
processedSize = (*startOffset > TEMP_BUF_SIZE) ? TEMP_BUF_SIZE : (size_t)*startOffset;
i += processedSize;
*startOffset = -(Int64)processedSize;
RINOK(SeekFromCur(stream, startOffset));
RINOK(LookInStream_Read2(stream, tempBuf, processedSize, SZ_ERROR_NO_ARCHIVE));
for (j = (int)processedSize; j >= 0; j--)
if (tempBuf[j -1] != 0)
break;
if (j != 0)
{
if ((j & 3) != 0)
return SZ_ERROR_NO_ARCHIVE;
*startOffset += j;
if (*startOffset < XZ_STREAM_FOOTER_SIZE)
return SZ_ERROR_NO_ARCHIVE;
*startOffset -= XZ_STREAM_FOOTER_SIZE;
RINOK(stream->Seek(stream, startOffset, SZ_SEEK_SET));
RINOK(LookInStream_Read2(stream, buf, XZ_STREAM_FOOTER_SIZE, SZ_ERROR_NO_ARCHIVE));
if (memcmp(buf + 10, XZ_FOOTER_SIG, XZ_FOOTER_SIG_SIZE) != 0)
return SZ_ERROR_NO_ARCHIVE;
break;
}
}
}
p->flags = (CXzStreamFlags)GetBe16(buf + 8);
if (!XzFlags_IsSupported(p->flags))
return SZ_ERROR_UNSUPPORTED;
if (GetUi32(buf) != CrcCalc(buf + 4, 6))
return SZ_ERROR_ARCHIVE;
indexSize = ((UInt64)GetUi32(buf + 4) + 1) << 2;
*startOffset = -(Int64)(indexSize + XZ_STREAM_FOOTER_SIZE);
RINOK(SeekFromCur(stream, startOffset));
RINOK(Xz_ReadIndex(p, stream, indexSize, alloc));
{
UInt64 totalSize = Xz_GetPackSize(p);
UInt64 sum = XZ_STREAM_HEADER_SIZE + totalSize + indexSize;
if (totalSize == XZ_SIZE_OVERFLOW ||
sum >= ((UInt64)1 << 63) ||
totalSize >= ((UInt64)1 << 63))
return SZ_ERROR_ARCHIVE;
*startOffset = -(Int64)sum;
RINOK(SeekFromCur(stream, startOffset));
}
{
CXzStreamFlags headerFlags;
CSecToRead secToRead;
SecToRead_CreateVTable(&secToRead);
secToRead.realStream = stream;
RINOK(Xz_ReadHeader(&headerFlags, &secToRead.s));
return (p->flags == headerFlags) ? SZ_OK : SZ_ERROR_ARCHIVE;
}
}
/* ---------- Xz Streams ---------- */
void Xzs_Construct(CXzs *p)
{
p->num = p->numAllocated = 0;
p->streams = 0;
}
void Xzs_Free(CXzs *p, ISzAlloc *alloc)
{
size_t i;
for (i = 0; i < p->num; i++)
Xz_Free(&p->streams[i], alloc);
alloc->Free(alloc, p->streams);
p->num = p->numAllocated = 0;
p->streams = 0;
}
UInt64 Xzs_GetNumBlocks(const CXzs *p)
{
UInt64 num = 0;
size_t i;
for (i = 0; i < p->num; i++)
num += p->streams[i].numBlocks;
return num;
}
UInt64 Xzs_GetUnpackSize(const CXzs *p)
{
UInt64 size = 0;
size_t i;
for (i = 0; i < p->num; i++)
ADD_SIZE_CHECH(size, Xz_GetUnpackSize(&p->streams[i]));
return size;
}
/*
UInt64 Xzs_GetPackSize(const CXzs *p)
{
UInt64 size = 0;
size_t i;
for (i = 0; i < p->num; i++)
ADD_SIZE_CHECH(size, Xz_GetTotalSize(&p->streams[i]));
return size;
}
*/
SRes Xzs_ReadBackward(CXzs *p, ILookInStream *stream, Int64 *startOffset, ICompressProgress *progress, ISzAlloc *alloc)
{
Int64 endOffset = 0;
RINOK(stream->Seek(stream, &endOffset, SZ_SEEK_END));
*startOffset = endOffset;
for (;;)
{
CXzStream st;
SRes res;
Xz_Construct(&st);
res = Xz_ReadBackward(&st, stream, startOffset, alloc);
st.startOffset = *startOffset;
RINOK(res);
if (p->num == p->numAllocated)
{
size_t newNum = p->num + p->num / 4 + 1;
Byte *data = (Byte *)alloc->Alloc(alloc, newNum * sizeof(CXzStream));
if (data == 0)
return SZ_ERROR_MEM;
p->numAllocated = newNum;
memcpy(data, p->streams, p->num * sizeof(CXzStream));
alloc->Free(alloc, p->streams);
p->streams = (CXzStream *)data;
}
p->streams[p->num++] = st;
if (*startOffset == 0)
break;
RINOK(stream->Seek(stream, startOffset, SZ_SEEK_SET));
if (progress && progress->Progress(progress, endOffset - *startOffset, (UInt64)(Int64)-1) != SZ_OK)
return SZ_ERROR_PROGRESS;
}
return SZ_OK;
}
+228
View File
@@ -0,0 +1,228 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2011-2013 Sourcefire, Inc.
*
* Authors: aCaB
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if defined(_WIN32)
#include <WinSock2.h>
#include <Windows.h>
#endif
#include "clamav.h"
#include "7z_iface.h"
#include "lzma_iface.h"
#include "scanners.h"
#include "others.h"
#include "fmap.h"
#include "7z/7z.h"
#include "7z/7zAlloc.h"
#include "7z/7zFile.h"
static ISzAlloc allocImp = {__lzma_wrap_alloc, __lzma_wrap_free}, allocTempImp = {__lzma_wrap_alloc, __lzma_wrap_free};
static SRes FileInStream_fmap_Read(void *pp, void *buf, size_t *size)
{
CFileInStream *p = (CFileInStream *)pp;
size_t read_sz;
if (*size == 0)
return 0;
read_sz = fmap_readn(p->file.fmap, buf, p->s.curpos, *size);
if (read_sz == (size_t)-1) {
*size = 0;
return SZ_ERROR_READ;
}
p->s.curpos += read_sz;
*size = read_sz;
return SZ_OK;
}
static SRes FileInStream_fmap_Seek(void *pp, Int64 *pos, ESzSeek origin)
{
CFileInStream *p = (CFileInStream *)pp;
switch (origin) {
case SZ_SEEK_SET:
p->s.curpos = *pos;
break;
case SZ_SEEK_CUR:
p->s.curpos += *pos;
*pos = p->s.curpos;
break;
case SZ_SEEK_END:
p->s.curpos = p->file.fmap->len + *pos;
*pos = p->s.curpos;
break;
default:
return 1;
}
return 0;
}
#define UTFBUFSZ 256
int cli_7unz(cli_ctx *ctx, size_t offset)
{
CFileInStream archiveStream;
CLookToRead lookStream;
CSzArEx db;
SRes res;
UInt16 utf16buf[UTFBUFSZ], *utf16name = utf16buf;
int namelen = UTFBUFSZ;
cl_error_t found = CL_CLEAN;
Int64 begin_of_archive = offset;
UInt32 viruses_found = 0;
/* Replacement for
FileInStream_CreateVTable(&archiveStream); */
archiveStream.s.Read = FileInStream_fmap_Read;
archiveStream.s.Seek = FileInStream_fmap_Seek;
archiveStream.s.curpos = 0;
archiveStream.file.fmap = ctx->fmap;
LookToRead_CreateVTable(&lookStream, False);
if (archiveStream.s.Seek(&archiveStream.s, &begin_of_archive, SZ_SEEK_SET) != 0)
return CL_CLEAN;
lookStream.realStream = &archiveStream.s;
LookToRead_Init(&lookStream);
SzArEx_Init(&db);
res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
if (res == SZ_ERROR_ENCRYPTED && SCAN_HEURISTIC_ENCRYPTED_ARCHIVE) {
cli_dbgmsg("cli_7unz: Encrypted header found in archive.\n");
found = cli_append_virus(ctx, "Heuristics.Encrypted.7Zip");
} else if (res == SZ_OK) {
UInt32 i, blockIndex = 0xFFFFFFFF;
Byte *outBuffer = 0;
size_t outBufferSize = 0;
unsigned int encrypted = 0;
for (i = 0; i < db.db.NumFiles; i++) {
size_t offset = 0;
size_t outSizeProcessed = 0;
const CSzFileItem *f = db.db.Files + i;
char *name;
char *tmp_name;
size_t j;
int newnamelen, fd;
if ((found = cli_checklimits("7unz", ctx, 0, 0, 0)))
break;
if (f->IsDir)
continue;
if (cli_checklimits("7unz", ctx, f->Size, 0, 0))
continue;
if (!db.FileNameOffsets)
newnamelen = 0; /* no filename */
else {
newnamelen = SzArEx_GetFileNameUtf16(&db, i, NULL);
if (newnamelen > namelen) {
if (namelen > UTFBUFSZ)
free(utf16name);
utf16name = cli_malloc(newnamelen * 2);
if (!utf16name) {
found = CL_EMEM;
break;
}
namelen = newnamelen;
}
SzArEx_GetFileNameUtf16(&db, i, utf16name);
}
name = (char *)utf16name;
for (j = 0; j < (size_t)newnamelen; j++) /* FIXME */
name[j] = utf16name[j];
name[j] = 0;
cli_dbgmsg("cli_7unz: extracting %s\n", name);
res = SzArEx_Extract(&db, &lookStream.s, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &allocImp, &allocTempImp);
if (res == SZ_ERROR_ENCRYPTED) {
encrypted = 1;
if (SCAN_HEURISTIC_ENCRYPTED_ARCHIVE) {
cli_dbgmsg("cli_7unz: Encrypted files found in archive.\n");
found = cli_append_virus(ctx, "Heuristics.Encrypted.7Zip");
if (found != CL_CLEAN) {
if (found == CL_VIRUS) {
if (SCAN_ALLMATCHES)
viruses_found++;
} else
break;
}
}
}
if (cli_matchmeta(ctx, name, 0, f->Size, encrypted, i, f->CrcDefined ? f->Crc : 0, NULL)) {
found = CL_VIRUS;
viruses_found++;
if (!SCAN_ALLMATCHES)
break;
}
if (res != SZ_OK)
cli_dbgmsg("cli_unz: extraction failed with %d\n", res);
else if ((outBuffer == NULL) || (outSizeProcessed == 0)) {
cli_dbgmsg("cli_unz: extracted empty file\n");
} else {
if ((found = cli_gentempfd(ctx->sub_tmpdir, &tmp_name, &fd)))
break;
cli_dbgmsg("cli_7unz: Saving to %s\n", tmp_name);
if (cli_writen(fd, outBuffer + offset, outSizeProcessed) != outSizeProcessed)
found = CL_EWRITE;
else if ((found = cli_magic_scan_desc(fd, tmp_name, ctx, name)) == CL_VIRUS)
viruses_found++;
close(fd);
if (!ctx->engine->keeptmp && cli_unlink(tmp_name))
found = CL_EUNLINK;
free(tmp_name);
if (found != CL_CLEAN)
if (!(SCAN_ALLMATCHES && found == CL_VIRUS))
break;
}
}
IAlloc_Free(&allocImp, outBuffer);
}
SzArEx_Free(&db, &allocImp);
if (namelen > UTFBUFSZ)
free(utf16name);
if (res == SZ_OK)
cli_dbgmsg("cli_7unz: completed successfully\n");
else if (res == SZ_ERROR_UNSUPPORTED)
cli_dbgmsg("cli_7unz: unsupported\n");
else if (res == SZ_ERROR_MEM)
cli_dbgmsg("cli_7unz: oom\n");
else if (res == SZ_ERROR_CRC)
cli_dbgmsg("cli_7unz: crc mismatch\n");
else if (res == SZ_ERROR_ENCRYPTED)
cli_dbgmsg("cli_7unz: encrypted\n");
else
cli_dbgmsg("cli_7unz: error %d\n", res);
if (SCAN_ALLMATCHES && viruses_found)
return CL_VIRUS;
return found;
}
+33
View File
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2011-2013 Sourcefire, Inc.
*
* Authors: aCaB
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __7Z_IFACE_H
#define __7Z_IFACE_H
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include "others.h"
int cli_7unz(cli_ctx *, size_t);
#endif
+626
View File
@@ -0,0 +1,626 @@
# Copyright (C) 2020-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
cmake_minimum_required( VERSION 3.12...3.13 )
include_directories(
${LIBXML2_INCLUDE_DIR}
${OPENSSL_INCLUDE_DIR}
${ZLIB_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
$<TARGET_PROPERTY:ClamAV::libclamunrar_iface_iface,INTERFACE_INCLUDE_DIRECTORIES>
${CMAKE_CURRENT_SOURCE_DIR}/..
)
configure_file(version.h.in version.h)
if(WIN32)
add_definitions(-DWIN32_LEAN_AND_MEAN)
add_definitions(-DHAVE_STRUCT_TIMESPEC)
# Windows compatibility headers
include_directories(${CMAKE_SOURCE_DIR}/win32/compat)
endif()
# 3rd party libraries included in libclamav
add_library( regex OBJECT )
target_sources( regex
PRIVATE
regex/strlcpy.c
regex/regcomp.c
regex/regerror.c
regex/regexec.c
regex/regfree.c
PUBLIC
regex/cclass.h
regex/cname.h
regex/regex.h
regex/regex2.h
regex/utils.h )
target_include_directories( regex
PRIVATE ${CMAKE_BINARY_DIR}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} )
set_target_properties(regex PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
target_link_libraries( regex
PRIVATE
PCRE2::pcre2
JSONC::jsonc )
add_library( lzma_sdk OBJECT )
target_sources( lzma_sdk
PRIVATE
7z/7zAlloc.c
7z/7zBuf.c
7z/7zBuf2.c
7z/7zCrc.c
7z/7zCrcOpt.c
7z/7zDec.c
7z/7zFile.c
7z/7zIn.c
7z/7zStream.c
7z/Bcj2.c
7z/Bra.c
7z/Bra86.c
7z/BraIA64.c
7z/CpuArch.c
7z/Delta.c
7z/Lzma2Dec.c
7z/LzmaDec.c
7z/Ppmd7.c
7z/Ppmd7Dec.c
7z/Xz.c
7z/XzCrc64.c
7z/XzDec.c
7z/XzIn.c
PUBLIC
7z/7z.h
7z/Xz.h
7z/Alloc.h
7z/7zFile.h
7z/XzCrc64.h
7z/RotateDefs.h
7z/Types.h
7z/Ppmd7.h
7z/LzmaDec.h
7z/Ppmd.h
7z/Lzma2Dec.h
7z/Delta.h
7z/CpuArch.h
7z/CpuArch.h
7z/Bra.h
7z/Bcj2.h
7z/7zVersion.h
7z/7zCrc.h
7z/7zBuf.h
7z/7zAlloc.h )
target_include_directories( lzma_sdk
PRIVATE ${CMAKE_BINARY_DIR}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} )
set_target_properties(lzma_sdk PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
target_link_libraries( lzma_sdk
PRIVATE
PCRE2::pcre2
JSONC::jsonc )
if(MAINTAINER_MODE)
bison_target( yara_grammar
yara_grammar.y ${CMAKE_CURRENT_SOURCE_DIR}/yara_grammar.c )
flex_target( yara_lexer
yara_lexer.l ${CMAKE_CURRENT_SOURCE_DIR}/yara_lexer.c )
add_flex_bison_dependency(yara_lexer yara_grammar)
endif()
add_library( yara OBJECT )
target_sources( yara
PRIVATE
yara_compiler.c
yara_exec.c
yara_hash.c
yara_parser.c
yara_arena.c
${BISON_yara_grammar_OUTPUTS}
${FLEX_yara_lexer_OUTPUTS}
PUBLIC
yara_arena.h
yara_compiler.h
yara_clam.h
yara_hash.h
yara_exec.h
yara_parser.h )
if(MAINTAINER_MODE)
target_sources( yara
PRIVATE
${BISON_yara_grammar_OUTPUTS}
${FLEX_yara_lexer_OUTPUTS} )
else()
target_sources( yara
PRIVATE
yara_grammar.c
yara_lexer.c )
endif()
target_include_directories( yara
PRIVATE
${CMAKE_BINARY_DIR}
${CMAKE_CURRENT_BINARY_DIR}
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR} )
set_target_properties(yara PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
target_link_libraries( yara
PRIVATE
PCRE2::pcre2
JSONC::jsonc )
add_library( tomsfastmath OBJECT )
target_sources( tomsfastmath
PRIVATE
tomsfastmath/addsub/fp_add.c
tomsfastmath/addsub/fp_add_d.c
tomsfastmath/addsub/fp_addmod.c
tomsfastmath/addsub/fp_cmp.c
tomsfastmath/addsub/fp_cmp_d.c
tomsfastmath/addsub/fp_cmp_mag.c
tomsfastmath/addsub/fp_sub.c
tomsfastmath/addsub/fp_sub_d.c
tomsfastmath/addsub/fp_submod.c
tomsfastmath/addsub/s_fp_add.c
tomsfastmath/addsub/s_fp_sub.c
tomsfastmath/bin/fp_radix_size.c
tomsfastmath/bin/fp_read_radix.c
tomsfastmath/bin/fp_read_signed_bin.c
tomsfastmath/bin/fp_read_unsigned_bin.c
tomsfastmath/bin/fp_reverse.c
tomsfastmath/bin/fp_s_rmap.c
tomsfastmath/bin/fp_signed_bin_size.c
tomsfastmath/bin/fp_to_signed_bin.c
tomsfastmath/bin/fp_to_unsigned_bin.c
tomsfastmath/bin/fp_toradix.c
tomsfastmath/bin/fp_toradix_n.c
tomsfastmath/bin/fp_unsigned_bin_size.c
tomsfastmath/bit/fp_cnt_lsb.c
tomsfastmath/bit/fp_count_bits.c
tomsfastmath/bit/fp_div_2.c
tomsfastmath/bit/fp_div_2d.c
tomsfastmath/bit/fp_lshd.c
tomsfastmath/bit/fp_mod_2d.c
tomsfastmath/bit/fp_rshd.c
tomsfastmath/divide/fp_div.c
tomsfastmath/divide/fp_div_d.c
tomsfastmath/divide/fp_mod.c
tomsfastmath/divide/fp_mod_d.c
tomsfastmath/exptmod/fp_2expt.c
tomsfastmath/exptmod/fp_exptmod.c
tomsfastmath/misc/fp_ident.c
tomsfastmath/misc/fp_set.c
tomsfastmath/mont/fp_montgomery_calc_normalization.c
tomsfastmath/mont/fp_montgomery_reduce.c
tomsfastmath/mont/fp_montgomery_setup.c
tomsfastmath/mul/fp_mul.c
tomsfastmath/mul/fp_mul_comba.c
tomsfastmath/mul/fp_mul_2.c
tomsfastmath/mul/fp_mul_2d.c
tomsfastmath/mul/fp_mul_comba_12.c
tomsfastmath/mul/fp_mul_comba_17.c
tomsfastmath/mul/fp_mul_comba_20.c
tomsfastmath/mul/fp_mul_comba_24.c
tomsfastmath/mul/fp_mul_comba_28.c
tomsfastmath/mul/fp_mul_comba_3.c
tomsfastmath/mul/fp_mul_comba_32.c
tomsfastmath/mul/fp_mul_comba_4.c
tomsfastmath/mul/fp_mul_comba_48.c
tomsfastmath/mul/fp_mul_comba_6.c
tomsfastmath/mul/fp_mul_comba_64.c
tomsfastmath/mul/fp_mul_comba_7.c
tomsfastmath/mul/fp_mul_comba_8.c
tomsfastmath/mul/fp_mul_comba_9.c
tomsfastmath/mul/fp_mul_comba_small_set.c
tomsfastmath/mul/fp_mul_d.c
tomsfastmath/mul/fp_mulmod.c
tomsfastmath/numtheory/fp_invmod.c
tomsfastmath/sqr/fp_sqr.c
tomsfastmath/sqr/fp_sqr_comba_12.c
tomsfastmath/sqr/fp_sqr_comba_17.c
tomsfastmath/sqr/fp_sqr_comba_20.c
tomsfastmath/sqr/fp_sqr_comba_24.c
tomsfastmath/sqr/fp_sqr_comba_28.c
tomsfastmath/sqr/fp_sqr_comba_3.c
tomsfastmath/sqr/fp_sqr_comba_32.c
tomsfastmath/sqr/fp_sqr_comba_4.c
tomsfastmath/sqr/fp_sqr_comba_48.c
tomsfastmath/sqr/fp_sqr_comba_6.c
tomsfastmath/sqr/fp_sqr_comba_64.c
tomsfastmath/sqr/fp_sqr_comba_7.c
tomsfastmath/sqr/fp_sqr_comba_8.c
tomsfastmath/sqr/fp_sqr_comba_9.c
tomsfastmath/sqr/fp_sqr_comba_generic.c
tomsfastmath/sqr/fp_sqr_comba_small_set.c
tomsfastmath/sqr/fp_sqrmod.c
PUBLIC
bignum.h
bignum_fast.h )
target_include_directories( tomsfastmath
PRIVATE ${CMAKE_BINARY_DIR}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} )
set_target_properties(tomsfastmath PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
# Bytecode Runtime
add_library( bytecode_runtime OBJECT )
if(LLVM_FOUND)
target_sources( bytecode_runtime
PRIVATE
c++/detect.cpp
c++/ClamBCRTChecks.cpp
c++/bytecode2llvm.cpp
bytecode_priv.h
bytecode.h )
set_target_properties(bytecode_runtime PROPERTIES
COMPILE_FLAGS "${WARNCXXFLAGS} ${CXX1XCXXFLAGS}")
else()
target_sources( bytecode_runtime
PRIVATE
bytecode_nojit.c
bytecode_priv.h
bytecode.h )
set_target_properties(bytecode_runtime PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
endif()
target_include_directories( bytecode_runtime
PRIVATE ${CMAKE_BINARY_DIR}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} )
target_link_libraries( bytecode_runtime
PRIVATE
PCRE2::pcre2
JSONC::jsonc )
# clamav clamav_obj
add_library( clamav_obj OBJECT )
target_sources( clamav_obj
PRIVATE
# Utils
blob.c blob.h
conv.c conv.h
fpu.c fpu.h
hashtab.c hashtab.h
iowrap.c iowrap.h
json_api.c json_api.h
jsparse/textbuf.h
others_common.c others.h
qsort.c
sf_base64decode.c sf_base64decode.h
str.c str.h
strlcat.c
table.c table.h
text.c text.h
uniq.c uniq.h
www.c www.h
# Utils Disasm
disasm-common.h disasm.c disasm.h disasmpriv.h
# Matcher
filtering.c filtering.h
matcher-ac.c matcher-ac.h
matcher-bm.c matcher-bm.h
matcher-byte-comp.c matcher-byte-comp.h
matcher-hash.c matcher-hash.h
matcher-pcre.c matcher-pcre.h
matcher.c matcher.h
regex_pcre.c regex_pcre.h
# Database
cvd.c cvd.h
dconf.c dconf.h
dsig.c dsig.h
readdb.c readdb.h
# Core
cache.c cache.h
crtmgr.c crtmgr.h
crypto.c
default.h
filetypes_int.h filetypes.c filetypes.h
fmap.c fmap.h
mpool.c mpool.h
others.c
perflogging.c perflogging.h
scanners.c scanners.h
textdet.c textdet.h
version.c
# file normalization (for matching)
htmlnorm.c htmlnorm.h
jsparse/generated/keywords.h
jsparse/generated/operators.h
jsparse/js-norm.c
jsparse/js-norm.h
jsparse/lexglobal.h
textnorm.c textnorm.h
# heuristics (hardcoded exploit/malware detection)
partition_intersection.c partition_intersection.h
special.c special.h
# clamav statistics
hostid_internal.c hostid_internal.h
stats_json.c stats_json.h
stats.c stats.h
# clamav bytecode support
bcfeatures.h
builtin_bytecodes.h
bytecode_api_decl.c
bytecode_api_impl.h
bytecode_api.c bytecode_api.h
bytecode_detect.c bytecode_detect.h
bytecode_hooks.h
bytecode_priv.h
bytecode_vm.c
bytecode.c bytecode.h
events.c events.h
type_desc.h
# utils: compression
7z_iface.c 7z_iface.h
explode.c explode.h
inffixed64.h
inflate64_priv.h inflate64.c inflate64.h
lzma_iface.c lzma_iface.h
lzw/lzwdec.c lzw/lzwdec.h
xz_iface.c xz_iface.h
# utils: encryption
arc4.c arc4.h
rijndael.c rijndael.h
# utils: text conversion
encoding_aliases.h
entconv.c entconv.h
entitylist.h
# Data-Loss-Prevention
dlp.c dlp.h
#
# FILE PARSERS
#
# autoit
autoit.c autoit.h
# binhex
binhex.c binhex.h
# cpio
cpio.c cpio.h
# install shield
ishield.c ishield.h
# cab / chm
libmspack.c libmspack.h
# msszdd
msexpand.c msexpand.h
# nsis
nsis/bzlib_private.h
nsis/bzlib.c
nsis/infblock.c
nsis/nsis_bzlib.h
nsis/nsis_zconf.h
nsis/nsis_zlib.h
nsis/nsis_zutil.h
nsis/nulsft.c nsis/nulsft.h
# office docs
hwp.c hwp.h
msdoc.c msdoc.h
msxml_parser.c msxml_parser.h
msxml.c msxml.h
ole2_extract.c ole2_extract.h
xlm_extract.c xlm_extract.h
ooxml.c ooxml.h
rtf.c rtf.h
vba_extract.c vba_extract.h
# executables
asn1.c asn1.h
elf.c elf.h
execs.c execs.h
macho.c macho.h
pe_icons.c pe_icons.h
pe_structs.h
pe.c pe.h
rebuildpe.c rebuildpe.h
# executable unpackers
aspack.c aspack.h
fsg.c fsg.h
mew.c mew.h
packlibs.c packlibs.h
petite.c petite.h
spin.c spin.h
unsp.c unsp.h
upack.c upack.h
upx.c upx.h
wwunpack.c wwunpack.h
yc.c yc.h
# mail & phishing
iana_cctld.h
iana_tld.h
line.c line.h
mbox.c mbox.h
message.c message.h
phish_domaincheck_db.c phish_domaincheck_db.h
phish_whitelist.c phish_whitelist.h
phishcheck.c phishcheck.h
regex_list.c regex_list.h
regex_suffix.c regex_suffix.h
# sis
sis.c sis.h
# tnef
tnef.c tnef.h
# uuencode
uuencode.c uuencode.h
# swf (flash)
swf.c swf.h
# pdf
pdf.c pdf.h
pdfng.c
pdfdecode.c pdfdecode.h
# xdp
xdp.c xdp.h
# ARJ archive
unarj.c unarj.h
# TAR archive
is_tar.c is_tar.h
untar.c untar.h
# ZIP archive
unzip.c unzip.h
# DMG archive
adc.c adc.h
dmg.c dmg.h
# XAR archive
xar.c xar.h
# EGG archive
egg.c egg.h
# Master Boot Record partition
mbr.c mbr.h
# GUID Parition Table partition
gpt.c gpt.h
# Apple Partition Map partition
apm.c apm.h
# HFS+ partition
hfsplus.c hfsplus.h
# iso9660 partition
iso9660.c iso9660.h
# OpenIOC
openioc.c openioc.h
# JPEG image format checker
jpeg.c jpeg.h
# PNG image format checker
png.c png.h
# TIFF image format checker
tiff.c tiff.h
# GIF image format checker
gif.c gif.h
PUBLIC
clamav.h )
if(WIN32)
target_sources( clamav_obj PRIVATE libclamav_main.c )
endif()
target_include_directories( clamav_obj
PRIVATE ${CMAKE_BINARY_DIR} ${JSONC_INCLUDE_DIRS}
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
INTERFACE ${CMAKE_BINARY_DIR} )
target_link_libraries( clamav_obj
PUBLIC
regex
lzma_sdk
yara
tomsfastmath
bytecode_runtime
ClamAV::libmspack
ClamAV::libclamunrar_iface_iface
OpenSSL::SSL
OpenSSL::Crypto
ZLIB::ZLIB
BZip2::BZip2
PCRE2::pcre2
LibXml2::LibXml2
JSONC::jsonc )
if (WIN32)
target_link_libraries( clamav_obj
PUBLIC
PThreadW32::pthreadw32
ClamAV::win32_compat
wsock32 ws2_32 )
else()
target_link_libraries( clamav_obj
PUBLIC
Threads::Threads
Iconv::Iconv
${CMAKE_DL_LIBS}
m )
endif()
set_target_properties(clamav_obj PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
if(ENABLE_SHARED_LIB)
# The clamav shared library.
add_library( clamav SHARED )
set_target_properties(clamav PROPERTIES
VERSION ${LIBCLAMAV_VERSION}
SOVERSION ${LIBCLAMAV_SOVERSION})
target_sources( clamav
PUBLIC
clamav.h )
target_link_libraries( clamav
PUBLIC
clamav_obj
regex
lzma_sdk
yara
tomsfastmath
bytecode_runtime
ClamAV::libmspack
ClamAV::libclamunrar_iface_iface
OpenSSL::SSL
OpenSSL::Crypto
ZLIB::ZLIB
BZip2::BZip2
PCRE2::pcre2
LibXml2::LibXml2
JSONC::jsonc )
set_target_properties(clamav PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}"
VERSION ${LIBCLAMAV_VERSION} SOVERSION ${LIBCLAMAV_SOVERSION})
if(WIN32)
set_target_properties(clamav PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON)
else()
target_link_libraries( clamav PUBLIC Iconv::Iconv )
endif()
if(WIN32)
install(TARGETS clamav DESTINATION ${CMAKE_INSTALL_PREFIX})
else()
install(TARGETS clamav DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
if(LLVM_FOUND)
target_link_directories( clamav PRIVATE ${LLVM_LIBRARY_DIRS} )
target_link_libraries( clamav PRIVATE ${LLVM_LIBRARIES} )
endif()
add_library( ClamAV::libclamav ALIAS clamav )
endif()
if(ENABLE_STATIC_LIB)
# The clamav static library.
add_library(clamav_static STATIC)
target_sources(clamav_static
PUBLIC
clamav.h )
target_link_libraries(clamav_static
PUBLIC
clamav_obj
regex
lzma_sdk
yara
tomsfastmath
bytecode_runtime
ClamAV::libmspack
ClamAV::libclamunrar_iface_iface
OpenSSL::SSL
OpenSSL::Crypto
ZLIB::ZLIB
BZip2::BZip2
PCRE2::pcre2
LibXml2::LibXml2
JSONC::jsonc )
if(NOT WIN32)
target_link_libraries( clamav PUBLIC Iconv::Iconv )
endif()
set_target_properties(clamav_static PROPERTIES
ARCHIVE_OUTPUT_NAME clamav_static
COMPILE_FLAGS "${WARNCFLAGS}"
VERSION ${LIBCLAMAV_VERSION} SOVERSION ${LIBCLAMAV_SOVERSION})
target_compile_definitions(clamav_static PUBLIC clamav_staticLIB)
if(WIN32)
install(TARGETS clamav_static DESTINATION ${CMAKE_INSTALL_PREFIX})
else()
install(TARGETS clamav_static DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
add_library( ClamAV::libclamav_static ALIAS clamav_static )
endif()
install(
FILES
clamav.h
${CMAKE_BINARY_DIR}/clamav-types.h
${CMAKE_BINARY_DIR}/clamav-version.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
+732
View File
@@ -0,0 +1,732 @@
#
# Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
# Copyright (C) 2007-2013 Sourcefire, Inc.
# Copyright (C) 2002-2007 Tomasz Kojm <tkojm@clamav.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
AM_YFLAGS = -d
AM_LFLAGS = -d
AM_CPPFLAGS = -I$(top_srcdir) -I@srcdir@/nsis $(LTDLINCL)
AM_CFLAGS=@WERR_CFLAGS@
lib_LTLIBRARIES =
COMMON_CLEANFILES =
EXTRA_DIST = c++/Makefile.nollvm.in
if ENABLE_UNRAR
AM_CPPFLAGS += -DWARN_DLOPEN_FAIL
libclamunrar_la_CXXFLAGS = $(AM_CPPFLAGS) -DRARDLL -Wno-logical-op-parentheses -Wno-switch -Wno-dangling-else
libclamunrar_la_LDFLAGS = @TH_SAFE@ -version-info @LIBCLAMAV_VERSION@ -no-undefined
if VERSIONSCRIPT
libclamunrar_la_LDFLAGS += -Wl,@VERSIONSCRIPTFLAG@,@top_srcdir@/libclamunrar/libclamunrar.map
endif
libclamunrar_la_SOURCES = \
../libclamunrar/archive.cpp \
../libclamunrar/arcread.cpp \
../libclamunrar/blake2s.cpp \
../libclamunrar/cmddata.cpp \
../libclamunrar/consio.cpp \
../libclamunrar/crc.cpp \
../libclamunrar/crypt.cpp \
../libclamunrar/dll.cpp \
../libclamunrar/encname.cpp \
../libclamunrar/errhnd.cpp \
../libclamunrar/extinfo.cpp \
../libclamunrar/extract.cpp \
../libclamunrar/filcreat.cpp \
../libclamunrar/file.cpp \
../libclamunrar/filefn.cpp \
../libclamunrar/filestr.cpp \
../libclamunrar/find.cpp \
../libclamunrar/getbits.cpp \
../libclamunrar/global.cpp \
../libclamunrar/hash.cpp \
../libclamunrar/headers.cpp \
../libclamunrar/list.cpp \
../libclamunrar/match.cpp \
../libclamunrar/options.cpp \
../libclamunrar/pathfn.cpp \
../libclamunrar/qopen.cpp \
../libclamunrar/rar.cpp \
../libclamunrar/rarvm.cpp \
../libclamunrar/rawread.cpp \
../libclamunrar/rdwrfn.cpp \
../libclamunrar/recvol.cpp \
../libclamunrar/resource.cpp \
../libclamunrar/rijndael.cpp \
../libclamunrar/rs.cpp \
../libclamunrar/rs16.cpp \
../libclamunrar/scantree.cpp \
../libclamunrar/secpassword.cpp \
../libclamunrar/sha1.cpp \
../libclamunrar/sha256.cpp \
../libclamunrar/smallfn.cpp \
../libclamunrar/strfn.cpp \
../libclamunrar/strlist.cpp \
../libclamunrar/system.cpp \
../libclamunrar/threadpool.cpp \
../libclamunrar/timefn.cpp \
../libclamunrar/ui.cpp \
../libclamunrar/unicode.cpp \
../libclamunrar/unpack.cpp \
../libclamunrar/volume.cpp
lib_LTLIBRARIES += libclamunrar.la
EXTRA_DIST += @top_srcdir@/libclamunrar/libclamunrar.map
libclamunrar_iface_la_CXXFLAGS = $(AM_CPPFLAGS) -I@top_srcdir@/libclamunrar
libclamunrar_iface_la_LIBADD = libclamunrar.la
libclamunrar_iface_la_LDFLAGS = -module @TH_SAFE@ -version-info @LIBCLAMAV_VERSION@ -no-undefined
if VERSIONSCRIPT
libclamunrar_iface_la_LDFLAGS += -Wl,@VERSIONSCRIPTFLAG@,@top_srcdir@/libclamunrar_iface/libclamunrar_iface.map
endif
libclamunrar_iface_la_SOURCES = \
../libclamunrar_iface/unrar_iface.cpp \
../libclamunrar_iface/unrar_iface.h
lib_LTLIBRARIES += libclamunrar_iface.la
EXTRA_DIST += @top_srcdir@/libclamunrar_iface/libclamunrar_iface.map
IFACELIBADD = -dlopen libclamunrar_iface.la
IFACEDEP = libclamunrar_iface.la
endif
# We need libclamunrar_iface in the include path even if we don't build it,
# because we #include "unrar_iface.h"
# We still want to support unrar if it is later provided, which is why we don't
# just wrap all the unrar scanners code with #ifdefs.
IFACE_CFLAGS = -I@top_srcdir@/libclamunrar_iface
if USE_INTERNAL_MSPACK
# libmspack version: 0.8alpha (1:0:1)
LIBMSPACK_VERSION = 1:0:1
libclammspack_la_CFLAGS = -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -Wno-unused-parameter -I@top_srcdir@/libclammspack/mspack
libclammspack_la_LDFLAGS = -version-info $(LIBMSPACK_VERSION) -no-undefined -export-symbols-regex '^mspack_'
# if VERSIONSCRIPT
# libclammspack_la_LDFLAGS += -Wl,@VERSIONSCRIPTFLAG@,@top_srcdir@/libclammspack/libclammspack.map
# endif
libclammspack_la_SOURCES = \
../libclammspack/mspack/cab.h \
../libclammspack/mspack/cabc.c \
../libclammspack/mspack/cabd.c \
../libclammspack/mspack/chm.h \
../libclammspack/mspack/chmc.c \
../libclammspack/mspack/chmd.c \
../libclammspack/mspack/crc32.c \
../libclammspack/mspack/crc32.h \
../libclammspack/mspack/des.h \
../libclammspack/mspack/hlp.h \
../libclammspack/mspack/hlpc.c \
../libclammspack/mspack/hlpd.c \
../libclammspack/mspack/kwaj.h \
../libclammspack/mspack/kwajc.c \
../libclammspack/mspack/kwajd.c \
../libclammspack/mspack/lit.h \
../libclammspack/mspack/litc.c \
../libclammspack/mspack/litd.c \
../libclammspack/mspack/lzss.h \
../libclammspack/mspack/lzssd.c \
../libclammspack/mspack/lzx.h \
../libclammspack/mspack/lzxc.c \
../libclammspack/mspack/lzxd.c \
../libclammspack/mspack/mspack.h \
../libclammspack/mspack/mszip.h \
../libclammspack/mspack/mszipc.c \
../libclammspack/mspack/mszipd.c \
../libclammspack/mspack/oab.h \
../libclammspack/mspack/oabc.c \
../libclammspack/mspack/oabd.c \
../libclammspack/mspack/qtm.h \
../libclammspack/mspack/qtmd.c \
../libclammspack/mspack/readbits.h \
../libclammspack/mspack/readhuff.h \
../libclammspack/mspack/sha.h \
../libclammspack/mspack/system.c \
../libclammspack/mspack/system.h \
../libclammspack/mspack/szdd.h \
../libclammspack/mspack/szddc.c \
../libclammspack/mspack/szddd.c
lib_LTLIBRARIES += libclammspack.la
# EXTRA_DIST += @top_srcdir@/libclammspack/libclammspack.map
MSPACK_CFLAGS = -I@top_srcdir@/libclammspack/mspack -DHAVE_INTERNAL_MSPACK
MSPACKLIBADD = -lclammspack
MSPACKDEP = libclammspack.la
else
MSPACK_CFLAGS = $(LIBMSPACK_CFLAGS)
MSPACKLIBADD = $(LIBMSPACK_LIBS)
MSPACKDEP =
libmspack/Makefile:
.PHONY: distdir distclean maintainer-clean
distdir:
echo "make distdir requires --with-system-libmspack=no"
exit 1
# nothing to do here, rules must exist for distclean to succeed
distclean:
-rm -f Makefile
maintainer-clean:
distclean-recursive distdir maintainer-clean-recursive: libmspack/Makefile
endif
libclamav_internal_utils_la_SOURCES= \
conv.c \
conv.h \
crypto.c \
iowrap.c \
iowrap.h \
others_common.c \
others.h \
qsort.c \
regex/cclass.h \
regex/cname.h \
regex/regcomp.c \
regex/regerror.c \
regex/regex.h \
regex/regex2.h \
regex/regexec.c \
regex/regfree.c \
regex/strlcpy.c \
regex/utils.h \
str.c \
str.h \
strlcat.c
libclamav_internal_utils_la_LDFLAGS=-static @SSL_LDFLAGS@ @JSON_LDFLAGS@
libclamav_internal_utils_la_CFLAGS=$(AM_CFLAGS) $(IFACE_CFLAGS) -fPIC -DPIC @SSL_CPPFLAGS@ @JSON_CPPFLAGS@ @PCRE_CPPFLAGS@ @XML_CPPFLAGS@
libclamav_internal_utils_la_LIBADD=@SSL_LIBS@ @PCRE_LIBS@
SUBDIRS=
if ENABLE_LLVM
LLVMLIBADD=c++/libclamavcxx.la -lstdc++ -lm
LLVMDEP=c++/libclamavcxx.la
SUBDIRS+=c++
else
LLVMLIBADD=libclamav_nocxx.la
LLVMDEP=libclamav_nocxx.la
c++/Makefile: c++/Makefile.nollvm.in
$(AM_V_at) cp $< $@
distclean-recursive distdir maintainer-clean-recursive: c++/Makefile
endif
if ENABLE_YARA
YARA_CFLAGS=-DHAVE_YARA
endif
libclamav_nocxx_la_SOURCES = bytecode_nojit.c
libclamav_nocxx_la_CFLAGS=$(AM_CFLAGS) $(IFACE_CFLAGS) @SSL_CPPFLAGS@ @JSON_CPPFLAGS@ @ZLIB_CFLAGS@ @PCRE_CPPFLAGS@
libclamav_la_LIBADD = @SSL_LIBS@ @JSON_LIBS@ @PCRE_LIBS@ @LIBCLAMAV_LIBS@ @ZLIB_LIBS@ @LIBLTDL@ $(XML_LIBS) $(IFACELIBADD) $(MSPACKLIBADD) $(LLVMLIBADD) libclamav_internal_utils.la @THREAD_LIBS@ @LIBM@
libclamav_la_DEPENDENCIES = @LTDLDEPS@ $(IFACEDEP) $(LLVMDEP) $(MSPACKDEP) libclamav_internal_utils.la
libclamav_la_CFLAGS = $(IFACE_CFLAGS) $(MSPACK_CFLAGS) $(AM_CFLAGS) $(YARA_CFLAGS) -DSEARCH_LIBDIR=\"$(libdir)\" @LIBCLAMAV_CPPFLAGS@ @SSL_CPPFLAGS@ @JSON_CPPFLAGS@ @ZLIB_CFLAGS@ @PCRE_CPPFLAGS@ @XML_CPPFLAGS@
libclamav_la_LDFLAGS = @SSL_LDFLAGS@ @TH_SAFE@ @JSON_LDFLAGS@ @LIBICONV@ $(XML_LIBS) -version-info @LIBCLAMAV_VERSION@ -no-undefined
if VERSIONSCRIPT
libclamav_la_LDFLAGS += -Wl,@VERSIONSCRIPTFLAG@,@top_srcdir@/libclamav/libclamav.map
endif
include_HEADERS = clamav.h
libclamav_la_SOURCES = \
matcher-ac.c \
matcher-ac.h \
matcher-bm.c \
matcher-bm.h \
matcher-hash.c \
matcher-hash.h \
matcher.c \
matcher.h \
others.c \
others.h \
readdb.c \
readdb.h \
cvd.c \
cvd.h \
dsig.c \
dsig.h \
scanners.c \
scanners.h \
textdet.c \
textdet.h \
filetypes.c \
filetypes.h \
filetypes_int.h \
rtf.c \
rtf.h \
blob.c \
blob.h \
mbox.c \
mbox.h \
message.c \
message.h \
table.c \
table.h \
text.c \
text.h \
ole2_extract.c \
ole2_extract.h \
vba_extract.c \
vba_extract.h \
xlm_extract.c \
xlm_extract.h \
msexpand.c \
msexpand.h \
pe.c \
pe.h \
pe_icons.c \
pe_icons.h \
pe_structs.h \
disasm.c \
disasm.h \
disasm-common.h \
disasmpriv.h \
upx.c \
upx.h \
htmlnorm.c \
htmlnorm.h \
libmspack.c \
libmspack.h \
rebuildpe.c \
rebuildpe.h \
petite.c \
petite.h \
wwunpack.c \
wwunpack.h \
unsp.c \
unsp.h \
aspack.c \
aspack.h \
packlibs.c \
packlibs.h \
fsg.c \
fsg.h \
mew.c \
mew.h \
upack.c \
upack.h \
line.c \
line.h \
untar.c \
untar.h \
unzip.c \
unzip.h \
ooxml.c \
ooxml.h \
inflate64.c \
inflate64.h \
inffixed64.h \
inflate64_priv.h \
special.c \
special.h \
binhex.c \
binhex.h \
is_tar.c \
is_tar.h \
tnef.c \
tnef.h \
autoit.c \
autoit.h \
unarj.c \
unarj.h \
nsis/bzlib.c \
nsis/bzlib_private.h \
nsis/nsis_bzlib.h \
nsis/nulsft.c \
nsis/nulsft.h \
nsis/infblock.c \
nsis/nsis_zconf.h \
nsis/nsis_zlib.h \
nsis/nsis_zutil.h \
pdf.c \
pdf.h \
pdfng.c \
pdfdecode.c \
pdfdecode.h \
spin.c \
spin.h \
yc.c \
yc.h \
elf.c \
elf.h \
execs.h \
execs.c \
sis.c \
sis.h \
uuencode.c \
uuencode.h \
phishcheck.c \
phishcheck.h \
phish_domaincheck_db.c \
phish_domaincheck_db.h \
phish_whitelist.c \
phish_whitelist.h \
iana_cctld.h \
iana_tld.h \
regex_list.c \
regex_list.h \
regex_suffix.c \
regex_suffix.h \
entconv.c \
entconv.h \
entitylist.h \
encoding_aliases.h \
hashtab.c \
hashtab.h \
dconf.c \
dconf.h \
lzma_iface.c \
lzma_iface.h \
7z_iface.c \
7z_iface.h \
7z/7z.h \
7z/7zAlloc.c \
7z/7zAlloc.h \
7z/7zBuf.c \
7z/7zBuf.h \
7z/7zBuf2.c \
7z/7zCrc.c \
7z/7zCrc.h \
7z/7zDec.c \
7z/7zFile.c \
7z/7zFile.h \
7z/7zIn.c \
7z/7zStream.c \
7z/7zVersion.h \
7z/Bcj2.c \
7z/Bcj2.h \
7z/Bra.c \
7z/Bra.h \
7z/Bra86.c \
7z/CpuArch.h \
7z/Lzma2Dec.c \
7z/Lzma2Dec.h \
7z/LzmaDec.c \
7z/LzmaDec.h \
7z/Ppmd.h \
7z/Ppmd7.c \
7z/Ppmd7.h \
7z/Ppmd7Dec.c \
7z/Types.h \
7z/Xz.c \
7z/Xz.h \
7z/XzCrc64.c \
7z/XzCrc64.h \
7z/XzDec.c \
7z/XzIn.c \
7z/Delta.c \
7z/Delta.h \
7z/Alloc.h \
7z/BraIA64.c \
7z/CpuArch.c \
7z/CpuArch.h \
7z/7zCrcOpt.c \
7z/RotateDefs.h \
explode.c \
explode.h \
textnorm.c \
textnorm.h \
dlp.c \
dlp.h \
jsparse/js-norm.c \
jsparse/js-norm.h \
jsparse/lexglobal.h \
jsparse/textbuf.h \
uniq.c \
uniq.h \
version.c\
version.h\
mpool.c\
mpool.h \
filtering.h\
filtering.c\
fmap.c \
fmap.h \
perflogging.c\
perflogging.h\
default.h\
bytecode.c\
bytecode.h\
bytecode_vm.c\
bytecode_priv.h\
clambc.h \
cpio.c \
cpio.h \
macho.c \
macho.h \
ishield.c \
ishield.h \
type_desc.h \
bcfeatures.h \
bytecode_api.c \
bytecode_api_decl.c \
bytecode_api.h \
bytecode_api_impl.h \
bytecode_hooks.h \
cache.c \
cache.h \
bytecode_detect.c \
bytecode_detect.h\
builtin_bytecodes.h\
events.c\
events.h \
adc.c \
adc.h \
dmg.c \
dmg.h \
xar.c \
xar.h \
xdp.c \
xdp.h \
mbr.c \
mbr.h \
gpt.c \
gpt.h \
apm.c \
apm.h \
partition_intersection.c \
partition_intersection.h \
json_api.c\
json_api.h\
xz_iface.c \
xz_iface.h \
sf_base64decode.c \
sf_base64decode.h \
hfsplus.c \
hfsplus.h \
swf.c \
swf.h \
gif.c \
gif.h \
jpeg.c \
jpeg.h \
png.c \
png.h \
iso9660.c \
iso9660.h \
arc4.c \
arc4.h \
rijndael.c \
rijndael.h \
crtmgr.c \
crtmgr.h \
asn1.c \
asn1.h \
fpu.c \
fpu.h \
stats.c \
stats.h \
www.c \
www.h \
stats_json.c \
stats_json.h \
hostid_internal.c \
hostid_internal.h \
openioc.c \
openioc.h \
msdoc.c \
msdoc.h \
matcher-pcre.c \
matcher-pcre.h \
regex_pcre.c \
regex_pcre.h \
msxml.c \
msxml.h \
msxml_parser.c \
msxml_parser.h \
tiff.c \
tiff.h \
hwp.c \
hwp.h \
lzw/lzwdec.c \
lzw/lzwdec.h \
matcher-byte-comp.c \
matcher-byte-comp.h \
egg.c \
egg.h \
queue.h
if ENABLE_YARA
libclamav_la_SOURCES += yara_arena.c \
yara_arena.h \
yara_compiler.c \
yara_compiler.h \
yara_exec.c \
yara_exec.h \
yara_hash.c \
yara_hash.h \
yara_grammar.y \
yara_lexer.l \
yara_lexer.h \
yara_parser.c \
yara_parser.h \
yara_clam.h
endif
libclamav_la_SOURCES += bignum.h\
bignum_fast.h\
tomsfastmath/addsub/fp_add.c\
tomsfastmath/addsub/fp_add_d.c\
tomsfastmath/addsub/fp_addmod.c\
tomsfastmath/addsub/fp_cmp.c\
tomsfastmath/addsub/fp_cmp_d.c\
tomsfastmath/addsub/fp_cmp_mag.c\
tomsfastmath/addsub/fp_sub.c\
tomsfastmath/addsub/fp_sub_d.c\
tomsfastmath/addsub/fp_submod.c\
tomsfastmath/addsub/s_fp_add.c\
tomsfastmath/addsub/s_fp_sub.c\
tomsfastmath/bin/fp_radix_size.c\
tomsfastmath/bin/fp_read_radix.c\
tomsfastmath/bin/fp_read_signed_bin.c\
tomsfastmath/bin/fp_read_unsigned_bin.c\
tomsfastmath/bin/fp_reverse.c\
tomsfastmath/bin/fp_s_rmap.c\
tomsfastmath/bin/fp_signed_bin_size.c\
tomsfastmath/bin/fp_to_signed_bin.c\
tomsfastmath/bin/fp_to_unsigned_bin.c\
tomsfastmath/bin/fp_toradix.c\
tomsfastmath/bin/fp_toradix_n.c\
tomsfastmath/bin/fp_unsigned_bin_size.c\
tomsfastmath/bit/fp_cnt_lsb.c\
tomsfastmath/bit/fp_count_bits.c\
tomsfastmath/bit/fp_div_2.c\
tomsfastmath/bit/fp_div_2d.c\
tomsfastmath/bit/fp_lshd.c\
tomsfastmath/bit/fp_mod_2d.c\
tomsfastmath/bit/fp_rshd.c\
tomsfastmath/divide/fp_div.c\
tomsfastmath/divide/fp_div_d.c\
tomsfastmath/divide/fp_mod.c\
tomsfastmath/divide/fp_mod_d.c\
tomsfastmath/exptmod/fp_2expt.c\
tomsfastmath/exptmod/fp_exptmod.c\
tomsfastmath/misc/fp_ident.c\
tomsfastmath/misc/fp_set.c\
tomsfastmath/mont/fp_montgomery_calc_normalization.c\
tomsfastmath/mont/fp_montgomery_reduce.c\
tomsfastmath/mont/fp_montgomery_setup.c\
tomsfastmath/mul/fp_mul.c\
tomsfastmath/mul/fp_mul_comba.c\
tomsfastmath/mul/fp_mul_2.c\
tomsfastmath/mul/fp_mul_2d.c\
tomsfastmath/mul/fp_mul_comba_12.c\
tomsfastmath/mul/fp_mul_comba_17.c\
tomsfastmath/mul/fp_mul_comba_20.c\
tomsfastmath/mul/fp_mul_comba_24.c\
tomsfastmath/mul/fp_mul_comba_28.c\
tomsfastmath/mul/fp_mul_comba_3.c\
tomsfastmath/mul/fp_mul_comba_32.c\
tomsfastmath/mul/fp_mul_comba_4.c\
tomsfastmath/mul/fp_mul_comba_48.c\
tomsfastmath/mul/fp_mul_comba_6.c\
tomsfastmath/mul/fp_mul_comba_64.c\
tomsfastmath/mul/fp_mul_comba_7.c\
tomsfastmath/mul/fp_mul_comba_8.c\
tomsfastmath/mul/fp_mul_comba_9.c\
tomsfastmath/mul/fp_mul_comba_small_set.c\
tomsfastmath/mul/fp_mul_d.c\
tomsfastmath/mul/fp_mulmod.c\
tomsfastmath/numtheory/fp_invmod.c\
tomsfastmath/sqr/fp_sqr.c\
tomsfastmath/sqr/fp_sqr_comba_12.c\
tomsfastmath/sqr/fp_sqr_comba_17.c\
tomsfastmath/sqr/fp_sqr_comba_20.c\
tomsfastmath/sqr/fp_sqr_comba_24.c\
tomsfastmath/sqr/fp_sqr_comba_28.c\
tomsfastmath/sqr/fp_sqr_comba_3.c\
tomsfastmath/sqr/fp_sqr_comba_32.c\
tomsfastmath/sqr/fp_sqr_comba_4.c\
tomsfastmath/sqr/fp_sqr_comba_48.c\
tomsfastmath/sqr/fp_sqr_comba_6.c\
tomsfastmath/sqr/fp_sqr_comba_64.c\
tomsfastmath/sqr/fp_sqr_comba_7.c\
tomsfastmath/sqr/fp_sqr_comba_8.c\
tomsfastmath/sqr/fp_sqr_comba_9.c\
tomsfastmath/sqr/fp_sqr_comba_generic.c\
tomsfastmath/sqr/fp_sqr_comba_small_set.c\
tomsfastmath/sqr/fp_sqrmod.c
.PHONY2: version.h.tmp
version.c: version.h
version.h: version.h.tmp
$(AM_V_GEN) if test -f version.h.static; then\
cp version.h.static version.h;\
elif ! diff $@ version.h.tmp >/dev/null 2>/dev/null; then\
cp version.h.tmp $@;\
fi
version.h.tmp:
$(AM_V_GEN) test -f version.h || touch version.h;\
rm -f $@;\
REVISION="$$(LANG=C git --git-dir "$(top_srcdir)"/.git describe --always 2>/dev/null || echo "exported")";\
if test "$$REVISION" = "exported"; then\
REVISION="";\
fi;\
if test -n "$$REVISION"; then\
echo "#define REPO_VERSION \"devel-$$REVISION\"" >> $@;\
else\
touch version.h.tmp;\
fi
lib_LTLIBRARIES += libclamav.la
noinst_LTLIBRARIES = libclamav_internal_utils.la libclamav_nocxx.la
EXTRA_DIST += regex/engine.c tomsfastmath/sqr/fp_sqr_comba.c tomsfastmath/mul/fp_mul_comba.c libclamav.map libclamav_main.c \
jsparse/generated/operators.h jsparse/generated/keywords.h jsparse/future_reserved_words.list\
jsparse/keywords.list jsparse/special_keywords.list jsparse/operators.gperf version.h.in
COMMON_CLEANFILES+=version.h version.h.tmp *.gcda *.gcno
BUILT_SOURCES = yara_grammar.h
if MAINTAINER_MODE
BUILT_SOURCES += jsparse/generated/operators.h jsparse/generated/keywords.h jsparse-keywords.gperf
GPERF_FLAGS=-E -t -L ANSI-C -C -F ', TOK_ERROR' -c
jsparse-keywords.gperf: jsparse/keywords.list jsparse/future_reserved_words.list jsparse/special_keywords.list
echo -e "struct keyword { const char *name; int val; };\n%%" >keywords-g-tmp
for i in `cat @srcdir@/jsparse/keywords.list`; do j=`echo $$i |tr \[a-z\] \[A-Z\]`; echo "$$i, TOK_$$j" >>keywords-g-tmp; done
for i in `cat @srcdir@/jsparse/future_reserved_words.list`; do echo "$$i, TOK_FUTURE_RESERVED_WORD" >>keywords-g-tmp; done
cat @srcdir@/jsparse/special_keywords.list >>keywords-g-tmp
mv keywords-g-tmp $@
jsparse/generated/operators.h: jsparse/operators.gperf
$(GPERF) $(GPERF_FLAGS) -H op_hash -N in_op_set -W oplist $< >operators-tmp-g
grep -v '^#line' <operators-tmp-g | sed -e 's/^const struct/static const struct/' -e 's/register //g' >operators-tmp
rm operators-tmp-g
mv operators-tmp @srcdir@/jsparse/generated/operators.h
jsparse/generated/keywords.h: jsparse-keywords.gperf
$(GPERF) $(GPERF_FLAGS) $< >keywords-tmp-g
grep -v '^#line' <keywords-tmp-g | sed -e 's/^const struct/static const struct/' -e 's/register //g' >keywords-tmp
rm keywords-tmp-g
mv keywords-tmp @srcdir@/jsparse/generated/keywords.h
CLEANFILES=$(COMMON_CLEANFILES) @srcdir@/jsparse/generated/operators.h @srcdir@/jsparse/generated/keywords.h
else
CLEANFILES=$(COMMON_CLEANFILES)
endif
File diff suppressed because it is too large Load Diff
+286
View File
@@ -0,0 +1,286 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2013 Sourcefire, Inc.
*
* Authors: David Raynor <draynor@sourcefire.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <stdio.h>
#include <errno.h>
#if HAVE_STRING_H
#include <string.h>
#endif
#include "clamav.h"
#include "others.h"
#include "adc.h"
/* #define DEBUG_ADC */
#ifdef DEBUG_ADC
#define adc_dbgmsg(...) cli_dbgmsg(__VA_ARGS__)
#else
#define adc_dbgmsg(...) ;
#endif
/* Initialize values and collect buffer
* NOTE: buffer size must be larger than largest lookback offset */
int adc_decompressInit(adc_stream *strm)
{
if (strm == NULL) {
return ADC_IO_ERROR;
}
if (strm->state != ADC_STATE_UNINIT) {
return ADC_DATA_ERROR;
}
/* Have to buffer maximum backward lookup */
strm->buffer = (uint8_t *)calloc(ADC_BUFF_SIZE, 1);
if (strm->buffer == NULL) {
return ADC_MEM_ERROR;
}
strm->buffered = 0;
strm->state = ADC_STATE_GETTYPE;
strm->length = 0;
strm->offset = 0;
strm->curr = strm->buffer;
return ADC_OK;
}
/* Decompress routine
* NOTE: Reaching end of input buffer does not mean end of output.
* It may fill the output buffer but have more to output.
* It will only return ADC_STREAM_END if output buffer is not full.
* It will return ADC_DATA_ERROR if it ends in the middle of a phrase
* (i.e. in the middle of a lookback code or data run)
*/
int adc_decompress(adc_stream *strm)
{
uint8_t bData;
uint8_t didNothing = 1;
/* first, the error returns based on strm */
if ((strm == NULL) || (strm->next_in == NULL) || (strm->next_out == NULL)) {
return ADC_IO_ERROR;
}
if (strm->state == ADC_STATE_UNINIT) {
return ADC_DATA_ERROR;
}
cli_dbgmsg("adc_decompress: avail_in %llu avail_out %llu state %u\n",
(long long unsigned)strm->avail_in, (long long unsigned)strm->avail_out, strm->state);
while (strm->avail_out) {
/* Exit if needs more in bytes and none available */
int needsInput;
switch (strm->state) {
case ADC_STATE_SHORTLOOK:
case ADC_STATE_LONGLOOK:
needsInput = 0;
break;
default:
needsInput = 1;
break;
}
if (needsInput && (strm->avail_in == 0)) {
break;
} else {
didNothing = 0;
}
/* Find or execute statecode */
switch (strm->state) {
case ADC_STATE_GETTYPE: {
/* Grab action code */
bData = *(strm->next_in);
strm->next_in++;
strm->avail_in--;
if (bData & 0x80) {
strm->state = ADC_STATE_RAWDATA;
strm->offset = 0;
strm->length = (bData & 0x7F) + 1;
} else if (bData & 0x40) {
strm->state = ADC_STATE_LONGOP2;
strm->offset = 0;
strm->length = (bData & 0x3F) + 4;
} else {
strm->state = ADC_STATE_SHORTOP;
strm->offset = (bData & 0x3) * 0x100;
strm->length = ((bData & 0x3C) >> 2) + 3;
}
adc_dbgmsg("adc_decompress: GETTYPE bData %x state %u offset %u length %u\n",
bData, strm->state, strm->offset, strm->length);
break;
}
case ADC_STATE_LONGOP2: {
/* Grab first offset byte */
bData = *(strm->next_in);
strm->next_in++;
strm->avail_in--;
strm->offset = bData * 0x100;
strm->state = ADC_STATE_LONGOP1;
adc_dbgmsg("adc_decompress: LONGOP2 bData %x state %u offset %u length %u\n",
bData, strm->state, strm->offset, strm->length);
break;
}
case ADC_STATE_LONGOP1: {
/* Grab second offset byte */
bData = *(strm->next_in);
strm->next_in++;
strm->avail_in--;
strm->offset += bData + 1;
strm->state = ADC_STATE_LONGLOOK;
adc_dbgmsg("adc_decompress: LONGOP1 bData %x state %u offset %u length %u\n",
bData, strm->state, strm->offset, strm->length);
break;
}
case ADC_STATE_SHORTOP: {
/* Grab offset byte */
bData = *(strm->next_in);
strm->next_in++;
strm->avail_in--;
strm->offset += bData + 1;
strm->state = ADC_STATE_SHORTLOOK;
adc_dbgmsg("adc_decompress: SHORTOP bData %x state %u offset %u length %u\n",
bData, strm->state, strm->offset, strm->length);
break;
}
case ADC_STATE_RAWDATA: {
/* Grab data */
adc_dbgmsg("adc_decompress: RAWDATA offset %u length %u\n", strm->offset, strm->length);
while ((strm->avail_in > 0) && (strm->avail_out > 0) && (strm->length > 0)) {
bData = *(strm->next_in);
strm->next_in++;
strm->avail_in--;
/* store to output */
*(strm->next_out) = bData;
strm->next_out++;
strm->avail_out--;
/* store to buffer */
if (strm->curr >= (strm->buffer + ADC_BUFF_SIZE)) {
strm->curr = strm->buffer;
}
*(strm->curr) = bData;
strm->curr++;
if (strm->buffered < ADC_BUFF_SIZE) {
strm->buffered++;
}
strm->length--;
}
if (strm->length == 0) {
/* adc_dbgmsg("adc_decompress: RAWDATADONE buffered %u avail_in %u avail_out %u \n",
strm->buffered, strm->avail_in, strm->avail_out); */
strm->state = ADC_STATE_GETTYPE;
}
break;
}
case ADC_STATE_SHORTLOOK:
case ADC_STATE_LONGLOOK: {
/* Copy data */
adc_dbgmsg("adc_decompress: LOOKBACK offset %u length %u avail_in %u avail_out %u\n",
strm->offset, strm->length, strm->avail_in, strm->avail_out);
while ((strm->avail_out > 0) && (strm->length > 0)) {
/* state validation first */
if (strm->offset > 0x10000) {
cli_dbgmsg("adc_decompress: bad LOOKBACK offset %u\n", strm->offset);
return ADC_DATA_ERROR;
} else if ((strm->state == ADC_STATE_SHORTLOOK) && (strm->offset > 0x400)) {
cli_dbgmsg("adc_decompress: bad LOOKBACK offset %u\n", strm->offset);
return ADC_DATA_ERROR;
}
if (strm->offset > strm->buffered) {
cli_dbgmsg("adc_decompress: too large LOOKBACK offset %u\n", strm->offset);
return ADC_DATA_ERROR;
}
/* retrieve byte */
if (strm->curr >= (strm->buffer + ADC_BUFF_SIZE)) {
strm->curr = strm->buffer;
}
if (strm->curr >= (strm->buffer + strm->offset)) {
bData = *(uint8_t *)(strm->curr - strm->offset);
} else {
bData = *(uint8_t *)(strm->curr + ADC_BUFF_SIZE - strm->offset);
}
/* store to output */
*(strm->next_out) = bData;
strm->next_out++;
strm->avail_out--;
/* store to buffer */
*(strm->curr) = bData;
strm->curr++;
if (strm->buffered < ADC_BUFF_SIZE) {
strm->buffered++;
}
strm->length--;
}
if (strm->length == 0) {
strm->state = ADC_STATE_GETTYPE;
/* adc_dbgmsg("adc_decompress: LOOKBACKDONE buffered %u avail_in %u avail_out %u \n",
strm->buffered, strm->avail_in, strm->avail_out); */
}
break;
}
default: {
/* bad state */
cli_errmsg("adc_decompress: invalid state %u\n", strm->state);
return ADC_DATA_ERROR;
}
} /* end switch */
} /* end while */
/* There really isn't a terminator, just end of data */
if (didNothing && strm->avail_out) {
if (strm->state == ADC_STATE_GETTYPE) {
/* Nothing left to do */
return ADC_STREAM_END;
} else {
/* Ended mid phrase */
cli_dbgmsg("adc_decompress: stream ended mid-phrase, state %u\n", strm->state);
return ADC_DATA_ERROR;
}
}
return ADC_OK;
}
/* Cleanup routine, frees buffer */
int adc_decompressEnd(adc_stream *strm)
{
if (strm == NULL) {
return ADC_IO_ERROR;
}
if (strm->state == ADC_STATE_UNINIT) {
return ADC_DATA_ERROR;
}
if (strm->buffer != NULL) {
free(strm->buffer);
}
strm->buffered = 0;
strm->state = ADC_STATE_UNINIT;
strm->length = 0;
strm->offset = 0;
return ADC_OK;
}
+74
View File
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2013 Sourcefire, Inc.
*
* Authors: David Raynor <draynor@sourcefire.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef CLAM_ADC_H
#define CLAM_ADC_H
struct adc_stream {
uint8_t *next_in;
size_t avail_in;
size_t total_in;
uint8_t *next_out;
size_t avail_out;
size_t total_out;
/* internals */
uint8_t *buffer;
uint8_t *curr;
uint32_t buffered;
uint16_t state;
uint16_t length;
uint32_t offset;
};
typedef struct adc_stream adc_stream;
#define ADC_BUFF_SIZE 65536
#define ADC_MEM_ERROR -1
#define ADC_DATA_ERROR -2
#define ADC_IO_ERROR -3
#define ADC_OK 0
#define ADC_STREAM_END 1
enum adc_state {
ADC_STATE_UNINIT = 0,
ADC_STATE_GETTYPE = 1,
ADC_STATE_RAWDATA = 2,
ADC_STATE_SHORTOP = 3,
ADC_STATE_LONGOP2 = 4,
ADC_STATE_LONGOP1 = 5,
ADC_STATE_SHORTLOOK = 6,
ADC_STATE_LONGLOOK = 7
};
/* Compression phrases
* store phrase - 1 byte header + data, first byte 0x80-0xFF, max length 0x80 (7 bits + 1), no offset
* short phrase - 2 byte header + data, first byte 0x00-0x3F, max length 0x12 (4 bits + 3), max offset 0x3FF (10 bits)
* long phrase - 3 byte header + data, first byte 0x40-0x7F, max length 0x43 (6 bits + 4), max offset 0xFFFF (16 bits)
*/
int adc_decompressInit(adc_stream *strm);
int adc_decompress(adc_stream *strm);
int adc_decompressEnd(adc_stream *strm);
#endif
+315
View File
@@ -0,0 +1,315 @@
/*
* Copyright (C) 2014-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
*
* Authors: Kevin Lin <kevlin2@cisco.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <stdio.h>
#include <errno.h>
#if HAVE_STRING_H
#include <string.h>
#endif
#include <ctype.h>
#include <fcntl.h>
#include "clamav-types.h"
#include "others.h"
#include "apm.h"
#include "partition_intersection.h"
#include "scanners.h"
#include "dconf.h"
//#define DEBUG_APM_PARSE
#ifdef DEBUG_APM_PARSE
#define apm_parsemsg(...) cli_dbgmsg(__VA_ARGS__)
#else
#define apm_parsemsg(...) ;
#endif
static int apm_partition_intersection(cli_ctx *ctx, struct apm_partition_info *aptable, size_t sectorsize, int old_school);
int cli_scanapm(cli_ctx *ctx)
{
struct apm_driver_desc_map ddm;
struct apm_partition_info aptable, apentry;
int ret = CL_CLEAN, detection = CL_CLEAN, old_school = 0;
size_t sectorsize, maplen, partsize;
size_t pos = 0, partoff = 0;
unsigned i;
uint32_t max_prtns = 0;
if (!ctx || !ctx->fmap) {
cli_errmsg("cli_scanapm: Invalid context\n");
return CL_ENULLARG;
}
/* read driver description map at sector 0 */
if (fmap_readn(ctx->fmap, &ddm, pos, sizeof(ddm)) != sizeof(ddm)) {
cli_dbgmsg("cli_scanapm: Invalid Apple driver description map\n");
return CL_EFORMAT;
}
/* convert driver description map big-endian to host */
ddm.signature = be16_to_host(ddm.signature);
ddm.blockSize = be16_to_host(ddm.blockSize);
ddm.blockCount = be32_to_host(ddm.blockCount);
/* check DDM signature */
if (ddm.signature != DDM_SIGNATURE) {
cli_dbgmsg("cli_scanapm: Apple driver description map signature mismatch\n");
return CL_EFORMAT;
}
/* sector size is determined by the ddm */
sectorsize = ddm.blockSize;
/* size of total file must be described by the ddm */
maplen = ctx->fmap->len;
if ((ddm.blockSize * ddm.blockCount) != maplen) {
cli_dbgmsg("cli_scanapm: File described %u size does not match %lu actual size\n",
(ddm.blockSize * ddm.blockCount), (unsigned long)maplen);
return CL_EFORMAT;
}
/* check for old-school partition map */
if (sectorsize == 2048) {
if (fmap_readn(ctx->fmap, &aptable, APM_FALLBACK_SECTOR_SIZE, sizeof(aptable)) != sizeof(aptable)) {
cli_dbgmsg("cli_scanapm: Invalid Apple partition entry\n");
return CL_EFORMAT;
}
aptable.signature = be16_to_host(aptable.signature);
if (aptable.signature == APM_SIGNATURE) {
sectorsize = APM_FALLBACK_SECTOR_SIZE;
old_school = 1;
}
}
/* read partition table at sector 1 (or after the ddm if old-school) */
pos = APM_PTABLE_BLOCK * sectorsize;
if (fmap_readn(ctx->fmap, &aptable, pos, sizeof(aptable)) != sizeof(aptable)) {
cli_dbgmsg("cli_scanapm: Invalid Apple partition table\n");
return CL_EFORMAT;
}
/* convert partition table big endian to host */
aptable.signature = be16_to_host(aptable.signature);
aptable.numPartitions = be32_to_host(aptable.numPartitions);
aptable.pBlockStart = be32_to_host(aptable.pBlockStart);
aptable.pBlockCount = be32_to_host(aptable.pBlockCount);
/* check the partition entry signature */
if (aptable.signature != APM_SIGNATURE) {
cli_dbgmsg("cli_scanapm: Apple partition table signature mismatch\n");
return CL_EFORMAT;
}
/* check if partition table partition */
if (strncmp((char *)aptable.type, "Apple_Partition_Map", 32) &&
strncmp((char *)aptable.type, "Apple_partition_map", 32) &&
strncmp((char *)aptable.type, "Apple_patition_map", 32)) {
cli_dbgmsg("cli_scanapm: Initial Apple Partition Map partition is not detected\n");
return CL_EFORMAT;
}
/* check that the partition table fits in the space specified - HEURISTICS */
if (SCAN_HEURISTIC_PARTITION_INTXN && (ctx->dconf->other & OTHER_CONF_PRTNINTXN)) {
ret = apm_partition_intersection(ctx, &aptable, sectorsize, old_school);
if (ret != CL_CLEAN) {
if (SCAN_ALLMATCHES && (ret == CL_VIRUS))
detection = CL_VIRUS;
else
return ret;
}
}
/* print debugging info on partition tables */
cli_dbgmsg("APM Partition Table:\n");
cli_dbgmsg("Name: %s\n", (char *)aptable.name);
cli_dbgmsg("Type: %s\n", (char *)aptable.type);
cli_dbgmsg("Signature: %x\n", aptable.signature);
cli_dbgmsg("Partition Count: %u\n", aptable.numPartitions);
cli_dbgmsg("Blocks: [%u, +%u), ([%lu, +%lu))\n",
aptable.pBlockStart, aptable.pBlockCount,
(unsigned long)(aptable.pBlockStart * sectorsize),
(unsigned long)(aptable.pBlockCount * sectorsize));
/* check engine maxpartitions limit */
if (aptable.numPartitions < ctx->engine->maxpartitions) {
max_prtns = aptable.numPartitions;
} else {
max_prtns = ctx->engine->maxpartitions;
}
/* partition table is a partition [at index 1], so skip it */
for (i = 2; i <= max_prtns; ++i) {
/* read partition table entry */
pos = i * sectorsize;
if (fmap_readn(ctx->fmap, &apentry, pos, sizeof(apentry)) != sizeof(apentry)) {
cli_dbgmsg("cli_scanapm: Invalid Apple partition entry\n");
return CL_EFORMAT;
}
/* convert partition entry big endian to host */
apentry.signature = be16_to_host(apentry.signature);
apentry.reserved = be16_to_host(apentry.reserved);
apentry.numPartitions = be32_to_host(apentry.numPartitions);
apentry.pBlockStart = be32_to_host(apentry.pBlockStart);
apentry.pBlockCount = be32_to_host(apentry.pBlockCount);
/* check the partition entry signature */
if (aptable.signature != APM_SIGNATURE) {
cli_dbgmsg("cli_scanapm: Apple partition entry signature mismatch\n");
return CL_EFORMAT;
}
/* check if a out-of-order partition map */
if (!strncmp((char *)apentry.type, "Apple_Partition_Map", 32) ||
!strncmp((char *)apentry.type, "Apple_partition_map", 32) ||
!strncmp((char *)apentry.type, "Apple_patition_map", 32)) {
cli_dbgmsg("cli_scanapm: Out of order Apple Partition Map partition\n");
continue;
}
partoff = apentry.pBlockStart * sectorsize;
partsize = apentry.pBlockCount * sectorsize;
/* re-calculate if old_school and aligned [512 * 4 => 2048] */
if (old_school && ((i % 4) == 0)) {
if (!strncmp((char *)apentry.type, "Apple_Driver", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver43", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver43_CD", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver_ATA", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver_ATAPI", 32) ||
!strncmp((char *)apentry.type, "Apple_Patches", 32)) {
partsize = apentry.pBlockCount * 2048;
}
}
/* check if invalid partition */
if ((partoff == 0) || (partoff + partsize > maplen)) {
cli_dbgmsg("cli_scanapm: Detected invalid Apple partition entry\n");
continue;
}
/* print debugging info on partition */
cli_dbgmsg("APM Partition Entry %u:\n", i);
cli_dbgmsg("Name: %s\n", (char *)apentry.name);
cli_dbgmsg("Type: %s\n", (char *)apentry.type);
cli_dbgmsg("Signature: %x\n", apentry.signature);
cli_dbgmsg("Partition Count: %u\n", apentry.numPartitions);
cli_dbgmsg("Blocks: [%u, +%u), ([%zu, +%zu))\n",
apentry.pBlockStart, apentry.pBlockCount, partoff, partsize);
/* send the partition to cli_magic_scan_nested_fmap_type */
ret = cli_magic_scan_nested_fmap_type(ctx->fmap, partoff, partsize, ctx, CL_TYPE_PART_ANY, (const char *)apentry.name);
if (ret != CL_CLEAN) {
if (SCAN_ALLMATCHES && (ret == CL_VIRUS))
detection = CL_VIRUS;
else
return ret;
}
}
if (i >= ctx->engine->maxpartitions) {
cli_dbgmsg("cli_scanapm: max partitions reached\n");
}
return detection;
}
static int apm_partition_intersection(cli_ctx *ctx, struct apm_partition_info *aptable, size_t sectorsize, int old_school)
{
partition_intersection_list_t prtncheck;
struct apm_partition_info apentry;
unsigned i, pitxn;
int ret = CL_CLEAN, tmp = CL_CLEAN;
size_t pos;
uint32_t max_prtns = 0;
int virus_found = 0;
partition_intersection_list_init(&prtncheck);
/* check engine maxpartitions limit */
if (aptable->numPartitions < ctx->engine->maxpartitions) {
max_prtns = aptable->numPartitions;
} else {
max_prtns = ctx->engine->maxpartitions;
}
for (i = 1; i <= max_prtns; ++i) {
/* read partition table entry */
pos = i * sectorsize;
if (fmap_readn(ctx->fmap, &apentry, pos, sizeof(apentry)) != sizeof(apentry)) {
cli_dbgmsg("cli_scanapm: Invalid Apple partition entry\n");
partition_intersection_list_free(&prtncheck);
return CL_EFORMAT;
}
/* convert necessary info big endian to host */
apentry.pBlockStart = be32_to_host(apentry.pBlockStart);
apentry.pBlockCount = be32_to_host(apentry.pBlockCount);
/* re-calculate if old_school and aligned [512 * 4 => 2048] */
if (old_school && ((i % 4) == 0)) {
if (!strncmp((char *)apentry.type, "Apple_Driver", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver43", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver43_CD", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver_ATA", 32) ||
!strncmp((char *)apentry.type, "Apple_Driver_ATAPI", 32) ||
!strncmp((char *)apentry.type, "Apple_Patches", 32)) {
apentry.pBlockCount = apentry.pBlockCount * 4;
}
}
tmp = partition_intersection_list_check(&prtncheck, &pitxn, apentry.pBlockStart, apentry.pBlockCount);
if (tmp != CL_CLEAN) {
if (tmp == CL_VIRUS) {
apm_parsemsg("Name: %s\n", (char *)aptable.name);
apm_parsemsg("Type: %s\n", (char *)aptable.type);
cli_dbgmsg("cli_scanapm: detected intersection with partitions "
"[%u, %u]\n",
pitxn, i);
ret = cli_append_virus(ctx, PRTN_INTXN_DETECTION);
if (ret == CL_VIRUS)
virus_found = 1;
if (SCAN_ALLMATCHES || ret == CL_CLEAN)
tmp = 0;
else
goto leave;
} else {
ret = tmp;
goto leave;
}
}
pos += sectorsize;
}
leave:
partition_intersection_list_free(&prtncheck);
if (virus_found)
return CL_VIRUS;
return ret;
}
+117
View File
@@ -0,0 +1,117 @@
/*
* Copyright (C) 2014-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
*
* Authors: Kevin Lin <klin@sourcefire.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __APM_H
#define __APM_H
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include "clamav-types.h"
#include "others.h"
#define APM_FALLBACK_SECTOR_SIZE 512
#define APM_PTABLE_BLOCK 1
#define APM_STRUCT_SIZE 512
#define DDM_SIGNATURE 0x4552 /* driver description signature ('ER') */
#define APM_SIGNATURE 0x504D /* partition map signature ('PM') */
/* partition flags */
#define VALID 0x00000001
#define ALLOCATED 0x00000002
#define IN_USE 0x00000004
#define BOOTABLE 0x00000008
#define READABLE 0x00000010
#define WRITEABLE 0x00000020
#define POSINDEPENDENT 0x00000040
/* end of partition flags */
#ifndef HAVE_ATTRIB_PACKED
#define __attribute__(x)
#endif
#ifdef HAVE_PRAGMA_PACK
#pragma pack(1)
#endif
#ifdef HAVE_PRAGMA_PACK_HPPA
#pragma pack 1
#endif
/* 8-byte driver description entry for ddmap, big endian */
struct apm_driver_desc_entry {
uint32_t block __attribute__((packed));
uint16_t size __attribute__((packed));
uint16_t type __attribute__((packed));
}; //NOTE may need to be renamed
/* 512(82)-byte driver descriptor map (Block0), big endian */
struct apm_driver_desc_map {
uint16_t signature __attribute__((packed));
uint16_t blockSize __attribute__((packed));
uint32_t blockCount __attribute__((packed));
uint16_t deviceType __attribute__((packed));
uint16_t deviceID __attribute__((packed));
uint32_t driverData __attribute__((packed));
uint16_t driverCount __attribute__((packed));
struct apm_driver_desc_entry driverTable[8];
/* zeroes fill remainder of sector (430 bytes in 512 sector size) */
};
/* 512(136)-byte partition info, big endian;
* both the partition table and the individual partitions use this
* struct to describe their details
*/
struct apm_partition_info {
uint16_t signature __attribute__((packed));
uint16_t reserved __attribute__((packed));
uint32_t numPartitions __attribute__((packed));
uint32_t pBlockStart __attribute__((packed));
uint32_t pBlockCount __attribute__((packed));
uint8_t name[32];
uint8_t type[32];
uint32_t lBlockStart __attribute__((packed));
uint32_t lBlockCount __attribute__((packed));
uint32_t flags __attribute__((packed));
uint32_t bootBlockStart __attribute__((packed));
uint32_t bootSize __attribute__((packed));
uint32_t bootAddr __attribute__((packed));
uint32_t bootAddr2 __attribute__((packed));
uint32_t bootEntry __attribute__((packed));
uint32_t bootEntry2 __attribute__((packed));
uint32_t bootChecksum __attribute__((packed));
uint8_t processor[16];
/* zeroes fill remainder of sector (376 bytes in 512 sector size) */
};
#ifdef HAVE_PRAGMA_PACK
#pragma pack()
#endif
#ifdef HAVE_PRAGMA_PACK_HPPA
#pragma pack
#endif
int cli_scanapm(cli_ctx *ctx);
#endif
+111
View File
@@ -0,0 +1,111 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2011-2013 Sourcefire, Inc.
*
* Author: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include "clamav-types.h"
#include "arc4.h"
#include <string.h>
bool arc4_init(struct arc4_state *a, const uint8_t *key, unsigned keylength)
{
unsigned i;
uint8_t j;
uint32_t *S;
if (NULL == a || NULL == key || 0 == keylength)
return false;
S = &a->S[0];
for (i = 0; i < 256; i++)
S[i] = i;
for (i = 0, j = 0; i < 256; i++) {
uint8_t tmp = S[i];
j = j + S[i] + key[i % keylength];
S[i] = S[j];
S[j] = tmp;
}
a->i = a->j = 0;
return true;
}
void arc4_apply(struct arc4_state *s, uint8_t *data, unsigned len)
{
uint8_t i = s->i, j = s->j;
uint32_t *S = &s->S[0];
while (len-- > 0) {
uint32_t a, b;
i++;
a = S[i];
j += a;
b = S[i] = S[j];
b += a;
S[j] = a;
*data++ ^= S[b & 0xff];
}
s->i = i;
s->j = j;
}
#if 0
#include <sys/time.h>
static struct {
const char *key;
const char *plaintext;
const char *result;
} testdata[] = {
{"Key", "Plaintext", "\xBB\xF3\x16\xE8\xD9\x40\xAF\x0A\xD3"},
{"Wiki", "pedia", "\x10\x21\xBF\x04\x20"},
{"Secret", "Attack at dawn", "\x45\xA0\x1F\x64\x5F\xC3\x5B\x38\x35\x52\x54\x4B\x9B\xF5"}
};
static int data[10*1024*1024];
int main(void)
{
struct arc4_state a;
uint8_t data[32];
size_t i;
struct timeval tv0, tv1;
for (i=0;i<sizeof(testdata)/sizeof(testdata[0]);i++) {
unsigned len;
arc4_init(&a, (const uint8_t*)testdata[i].key, strlen(testdata[i].key));
len = strlen(testdata[i].plaintext);
memcpy(data, testdata[i].plaintext, len);
arc4_apply(&a, data, len);
if (memcmp(data, testdata[i].result, len)) {
printf("Bad result at %zu\n", i);
}
}
gettimeofday(&tv0, NULL);
for (i=0;i<1000000;i++)
arc4_apply(&a, data, sizeof(data));
gettimeofday(&tv1, NULL);
tv1.tv_sec -= tv0.tv_sec;
tv1.tv_usec -= tv0.tv_usec;
printf("Time: %f us\n", tv1.tv_sec*1000000.0 + tv1.tv_usec);
}
#endif
+32
View File
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2011-2013 Sourcefire, Inc.
*
* Author: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <stdbool.h>
#include "clamav-types.h"
struct arc4_state {
/* really just 8 bit, but it is faster if reads are aligned */
uint32_t S[256];
uint8_t i, j;
};
bool arc4_init(struct arc4_state *a, const uint8_t *key, unsigned keylength);
void arc4_apply(struct arc4_state *s, uint8_t *data, unsigned len);
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2011-2013 Sourcefire, Inc.
*
* Authors: aCaB
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __ASN1_H
#define __ASN1_H
#include "others.h"
#include "fmap.h"
struct cli_mapped_region {
unsigned int offset;
unsigned int size;
};
int asn1_load_mscat(fmap_t *map, struct cl_engine *engine);
cl_error_t asn1_check_mscat(struct cl_engine *engine, fmap_t *map, size_t offset, unsigned int size, struct cli_mapped_region *regions, uint32_t nregions, cli_ctx *ctx);
#endif
+503
View File
@@ -0,0 +1,503 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Luciano Giuseppe 'Pnluck', Alberto Wu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <string.h>
#include "clamav.h"
#include "execs.h"
#include "others.h"
#include "rebuildpe.h"
#include "aspack.h"
#define ASPACK_BLOCKS_OFFSET_212 0x57c
#define ASPACK_BLOCKS_OFFSET_OTHER 0x5d8
#define ASPACK_BLOCKS_OFFSET_242 0x5e4
#define ASPACK_STR_INIT_MLT_OFFSET_212 0x70e
#define ASPACK_STR_INIT_MLT_OFFSET_OTHER 0x76a
#define ASPACK_STR_INIT_MLT_OFFSET_242 0x776
#define ASPACK_COMP_BLOCK_OFFSET_212 0x6d6
#define ASPACK_COMP_BLOCK_OFFSET_OTHER 0x732
#define ASPACK_COMP_BLOCK_OFFSET_242 0x73e
#define ASPACK_WRKBUF_OFFSET_212 0x148
#define ASPACK_WRKBUF_OFFSET_OTHER 0x13a
#define ASPACK_WRKBUF_OFFSET_242 0x148
#define ASPACK_OEP_OFFSET_212 0x39b
#define ASPACK_OEP_OFFSET_OTHER 0x401
#define ASPACK_OEP_OFFSET_242 0x40d
struct DICT_HELPER {
uint32_t *starts;
uint8_t *ends;
uint32_t size;
};
struct ASPK {
uint32_t bitpos;
uint32_t hash;
uint32_t init_array[58];
struct DICT_HELPER dict_helper[4];
uint8_t *input;
uint8_t *iend;
uint8_t *decrypt_dict;
uint32_t decarray3[4][24];
uint32_t decarray4[4][24];
int dict_ok;
uint8_t array2[758];
uint8_t array1[19];
};
static inline int readstream(struct ASPK *stream)
{
while (stream->bitpos >= 8) {
if (stream->input >= stream->iend) return 0;
stream->hash = (stream->hash << 8) | *stream->input;
stream->input++;
stream->bitpos -= 8;
}
return 1;
}
static uint32_t getdec(struct ASPK *stream, uint8_t which, int *err)
{
uint32_t ret;
uint8_t pos;
uint32_t *d3 = stream->decarray3[which];
uint32_t *d4 = stream->decarray4[which];
*err = 1;
if (!readstream(stream)) return 0;
ret = (stream->hash >> (8 - stream->bitpos)) & 0xfffe00;
if (ret < d3[8]) {
if ((ret >> 16) >= 0x100) return 0;
if (!(pos = stream->dict_helper[which].ends[ret >> 16]) || pos >= 24) return 0; /* 0<pos<24 */
} else {
if (ret < d3[10]) {
if (ret < d3[9])
pos = 9;
else
pos = 10;
} else {
if (ret < d3[11])
pos = 11;
else {
if (ret < d3[12])
pos = 12;
else {
if (ret < d3[13])
pos = 13;
else {
if (ret < d3[14])
pos = 14;
else
pos = 15;
}
}
}
}
}
stream->bitpos += pos;
ret = ((ret - d3[pos - 1]) >> (24 - pos)) + d4[pos];
if (ret >= stream->dict_helper[which].size) return 0;
ret = stream->dict_helper[which].starts[ret];
*err = 0;
return ret;
}
static uint8_t build_decrypt_array(struct ASPK *stream, uint8_t *array, uint8_t which)
{
uint32_t sum = 0, counter = 23, i, endoff = 0, bus[18], dict[18];
uint32_t *d3 = stream->decarray3[which];
uint32_t *d4 = stream->decarray4[which];
memset(bus, 0, sizeof(bus));
memset(dict, 0, sizeof(dict));
for (i = 0; i < stream->dict_helper[which].size; i++) {
/* within bounds - see comments in build_decrypt_dictionaries */
if (array[i] > 17) return 0;
bus[array[i]]++;
}
d3[0] = 0;
d4[0] = 0;
i = 0;
while (counter >= 9) { /* 0<=i<=14 */
sum += (bus[i + 1] << counter);
if (sum > 0x1000000) return 0;
d3[i + 1] = sum;
d4[i + 1] = dict[i + 1] = bus[i] + d4[i];
if (counter >= 0x10) {
uint32_t old = endoff;
endoff = d3[i + 1] >> 0x10;
if (endoff - old) {
if (!CLI_ISCONTAINED(stream->dict_helper[which].ends, 0x100, stream->dict_helper[which].ends + old, endoff - old)) return 0;
memset((stream->dict_helper[which].ends + old), i + 1, endoff - old);
}
}
i++;
counter--;
}
if (sum != 0x1000000) return 0;
i = 0;
for (i = 0; i < stream->dict_helper[which].size; i++) {
if (array[i]) { /* within bounds - see above */
if (array[i] > 17) return 0;
if (dict[array[i]] >= stream->dict_helper[which].size) return 0;
stream->dict_helper[which].starts[dict[array[i]]] = i;
dict[array[i]]++;
}
}
return 1;
}
static uint8_t getbits(struct ASPK *stream, uint32_t num, int *err)
{
uint8_t retvalue;
if (!readstream(stream)) {
*err = 1;
return 0;
}
*err = 0;
retvalue = ((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (24 - num);
stream->bitpos += num;
return retvalue;
}
static int build_decrypt_dictionaries(struct ASPK *stream)
{
unsigned int counter;
uint32_t ret;
int oob;
if (!getbits(stream, 1, &oob)) memset(stream->decrypt_dict, 0, 0x2f5);
if (oob) return 0;
for (counter = 0; counter < 19; counter++) {
stream->array1[counter] = getbits(stream, 4, &oob);
if (oob) return 0;
}
if (!build_decrypt_array(stream, stream->array1, 3)) return 0; /* array1[19] - [3].size=19 */
counter = 0;
while (counter < 757) {
ret = getdec(stream, 3, &oob);
if (oob) return 0;
if (ret >= 16) {
if (ret != 16) {
if (ret == 17)
ret = 3 + getbits(stream, 3, &oob);
else
ret = 11 + getbits(stream, 7, &oob);
if (oob) return 0;
while (ret) {
if (counter >= 757) break;
stream->array2[1 + counter] = 0;
counter++;
ret--;
}
} else {
ret = 3 + getbits(stream, 2, &oob);
if (oob) return 0;
while (ret) {
if (counter >= 757) break;
stream->array2[1 + counter] = stream->array2[counter];
counter++;
ret--;
}
}
} else {
stream->array2[1 + counter] = (stream->decrypt_dict[counter] + ret) & 0xF;
counter++;
}
}
if (!build_decrypt_array(stream, &stream->array2[1], 0) /* array2[758-1=757] - [0].size=721 */ || !build_decrypt_array(stream, &stream->array2[722], 1) /* array2[758-722=36] - [1].size=28 */ || !build_decrypt_array(stream, &stream->array2[750], 2) /* array2[758-750=8] - [2].size=8 */) return 0;
stream->dict_ok = 0;
for (counter = 0; counter < 8; counter++) {
if (stream->array2[750 + counter] != 3) {
stream->dict_ok = 1;
break;
}
}
memcpy(stream->decrypt_dict, &stream->array2[1], 757);
return 1;
}
static int decrypt(struct ASPK *stream, uint8_t *stuff, uint32_t size, uint8_t *output)
{
/* ep+6d6 -> ep+748 = 0x72*/
uint32_t gen, backsize, backbytes, useold, counter = 0;
uint32_t hist[4] = {0, 0, 0, 0};
int oob;
cli_dbgmsg("Aspack: decrypt size:%x\n", size);
while (counter < size) {
gen = getdec(stream, 0, &oob);
if (oob) return 0;
if (gen < 256) { /* implied within bounds */
output[counter] = (uint8_t)gen;
counter++;
continue;
}
if (gen >= 720) {
if (!build_decrypt_dictionaries(stream)) return 0;
continue;
}
if ((backbytes = (gen - 256) >> 3) >= 58) return 0; /* checks init_array + stuff */
backsize = ((gen - 256) & 7) + 2;
if ((backsize - 2) == 7) {
uint8_t hlp;
gen = getdec(stream, 1, &oob);
if (oob || gen >= 0x56) return 0;
hlp = stuff[gen + 0x1c];
if (!readstream(stream)) return 0;
backsize += stuff[gen] + (((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (0x18 - hlp));
stream->bitpos += hlp;
}
useold = stream->init_array[backbytes];
gen = stuff[backbytes + 0x38];
if (!stream->dict_ok || gen < 3) {
if (!readstream(stream)) return 0;
useold += ((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (24 - gen);
stream->bitpos += gen;
} else {
gen -= 3;
if (!readstream(stream)) return 0;
useold += ((((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (24 - gen)) * 8);
stream->bitpos += gen;
useold += getdec(stream, 2, &oob);
if (oob) return 0;
}
if (useold < 3) {
backbytes = hist[useold];
if (useold != 0) {
hist[useold] = hist[0];
hist[0] = backbytes;
}
} else {
hist[2] = hist[1];
hist[1] = hist[0];
hist[0] = backbytes = useold - 3;
}
backbytes++;
if (!backbytes || backbytes > counter || backsize > size - counter) return 0;
while (backsize--) {
output[counter] = output[counter - backbytes];
counter++;
}
}
return 1;
}
static int decomp_block(struct ASPK *stream, uint32_t size, uint8_t *stuff, uint8_t *output)
{
memset(stream->decarray3, 0, sizeof(stream->decarray3));
memset(stream->decarray4, 0, sizeof(stream->decarray4));
memset(stream->decrypt_dict, 0, 757);
stream->bitpos = 0x20;
if (!build_decrypt_dictionaries(stream)) return 0;
return decrypt(stream, stuff, size, output);
}
#define INIT_DICT_HELPER(n, sz) \
stream.dict_helper[n].starts = (uint32_t *)wrkbuf; \
stream.dict_helper[n].ends = &wrkbuf[sz * sizeof(uint32_t)]; \
stream.dict_helper[n].size = sz; \
wrkbuf = &wrkbuf[sz * sizeof(uint32_t) + 0x100];
int unaspack(uint8_t *image, unsigned int size, struct cli_exe_section *sections, uint16_t sectcount, uint32_t ep, uint32_t base, int f, aspack_version_t version)
{
struct ASPK stream;
uint32_t i = 0, j = 0;
uint8_t *blocks = NULL, *wrkbuf;
uint32_t block_rva = 1, block_size;
struct cli_exe_section *outsects;
uint32_t blocks_offset, stream_init_multiplier_offset, comp_block_offset, wrkbuf_offset, oep_offset;
switch (version) {
case ASPACK_VER_212:
cli_dbgmsg("Aspack: Attempting to unpack Aspack 2.12.\n");
blocks_offset = ASPACK_BLOCKS_OFFSET_212;
stream_init_multiplier_offset = ASPACK_STR_INIT_MLT_OFFSET_212;
comp_block_offset = ASPACK_COMP_BLOCK_OFFSET_212;
wrkbuf_offset = ASPACK_WRKBUF_OFFSET_212;
oep_offset = ASPACK_OEP_OFFSET_212;
break;
case ASPACK_VER_OTHER:
cli_dbgmsg("Aspack: Attempting to unpack Aspack >2.12, <2.42.\n");
blocks_offset = ASPACK_BLOCKS_OFFSET_OTHER;
stream_init_multiplier_offset = ASPACK_STR_INIT_MLT_OFFSET_OTHER;
comp_block_offset = ASPACK_COMP_BLOCK_OFFSET_OTHER;
wrkbuf_offset = ASPACK_WRKBUF_OFFSET_OTHER;
oep_offset = ASPACK_OEP_OFFSET_OTHER;
break;
case ASPACK_VER_242:
cli_dbgmsg("Aspack: Attempting to unpack Aspack 2.42.\n");
blocks_offset = ASPACK_BLOCKS_OFFSET_242;
stream_init_multiplier_offset = ASPACK_STR_INIT_MLT_OFFSET_242;
comp_block_offset = ASPACK_COMP_BLOCK_OFFSET_242;
wrkbuf_offset = ASPACK_WRKBUF_OFFSET_242;
oep_offset = ASPACK_OEP_OFFSET_242;
break;
default:
cli_dbgmsg("Aspack: Unexpected/Unknown version number.\n");
return 0;
}
blocks = image + ep + blocks_offset;
if (!(wrkbuf = cli_calloc(0x1800, sizeof(uint8_t)))) {
cli_dbgmsg("Aspack: Unable to allocate dictionary\n");
return 0;
}
INIT_DICT_HELPER(0, 721); /* dictionary -> dictionary + b44 */
INIT_DICT_HELPER(1, 28); /* dictionary + c44 -> dictionary + cb4 */
INIT_DICT_HELPER(2, 8); /* dictionary + db4 -> dictionary + dd4 */
INIT_DICT_HELPER(3, 19); /* dictionary + ed4 -> dictionary + f20 */
stream.decrypt_dict = wrkbuf;
stream.hash = 0x10000;
for (i = 0; i < 58; i++) {
stream.init_array[i] = j;
if (ep + i + stream_init_multiplier_offset < size) {
j += (1 << image[ep + i + stream_init_multiplier_offset]);
}
}
memset(stream.array1, 0, sizeof(stream.array1));
memset(stream.array2, 0, sizeof(stream.array2));
i = 0;
while (CLI_ISCONTAINED(image, size, blocks, 8) && (block_rva = cli_readint32(blocks)) && (block_size = cli_readint32(blocks + 4)) && CLI_ISCONTAINED(image, size, image + block_rva, block_size)) {
cli_dbgmsg("Aspack: unpacking block rva:%x - sz:%x\n", block_rva, block_size);
wrkbuf = (uint8_t *)cli_calloc(block_size + 0x10e, sizeof(uint8_t));
if (!wrkbuf) {
cli_dbgmsg("Aspack: Null work buff\n");
break;
}
stream.input = wrkbuf;
stream.iend = &wrkbuf[block_size + 0x10e];
memcpy(wrkbuf, image + block_rva, block_size);
if (!decomp_block(&stream, block_size, &image[ep + comp_block_offset], image + block_rva)) {
cli_dbgmsg("Aspack: decomp_block failed\n");
free(wrkbuf);
break;
} else
cli_dbgmsg("Aspack: decomp block succeed\n");
free(wrkbuf);
if (i == 0 && block_size > 7) { /* first sect j/c unrolling */
while (i < block_size - 6) {
uint8_t curbyte = image[block_rva + i];
if (curbyte == 0xe8 || curbyte == 0xe9) {
wrkbuf = &image[block_rva + i + 1];
if (*wrkbuf == image[ep + wrkbuf_offset]) {
uint32_t target = cli_readint32(wrkbuf) & 0xffffff00;
CLI_ROL(target, 0x18);
cli_writeint32(wrkbuf, target - i);
i += 4;
}
}
i++;
}
}
if (version == ASPACK_VER_212) {
blocks += 8;
} else {
blocks += 12;
block_size = cli_readint32(blocks + 4);
while (!((block_size + 0x10e) & 0xffffffff)) {
blocks += 12;
block_size = cli_readint32(blocks + 4);
}
}
}
cli_dbgmsg("Aspack: leaving loop all uncompressed\n");
free(stream.dict_helper[0].starts);
if (block_rva) {
cli_dbgmsg("Aspack: unpacking failure\n");
return 0;
}
if (sectcount > 2 && ep == sections[sectcount - 2].rva && !sections[sectcount - 1].rsz) {
sectcount -= 2;
}
if (!(outsects = cli_malloc(sizeof(struct cli_exe_section) * sectcount))) {
cli_dbgmsg("Aspack: OOM - rebuild failed\n");
cli_writen(f, image, size);
return 1; /* No whatsoheader - won't infloop in pe.c */
}
memcpy(outsects, sections, sizeof(struct cli_exe_section) * sectcount);
for (i = 0; i < sectcount; i++) {
outsects[i].raw = outsects[i].rva;
outsects[i].rsz = outsects[i].vsz;
}
if (!cli_rebuildpe((char *)image, outsects, sectcount, base, cli_readint32(image + ep + oep_offset), 0, 0, f)) {
cli_dbgmsg("Aspack: rebuild failed\n");
cli_writen(f, image, size);
} else {
cli_dbgmsg("Aspack: successfully rebuilt\n");
}
free(outsects);
return 1;
}
+45
View File
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Luciano Giuseppe 'Pnluck', Alberto Wu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __ASPACK_H
#define __ASPACK_H
#include "clamav-types.h"
#include "execs.h"
#define ASPACK_EP_OFFSET_212 (58 + 0x70e)
#define ASPACK_EP_OFFSET_OTHER (58 + 0x76a)
#define ASPACK_EP_OFFSET_242 (58 + 0x776)
#define ASPACK_EPBUFF_OFFSET_212 (0x3b9)
#define ASPACK_EPBUFF_OFFSET_OTHER (0x41f)
#define ASPACK_EPBUFF_OFFSET_242 (0x42B)
typedef enum aspack_version_tag {
ASPACK_VER_NONE = 0,
ASPACK_VER_212,
ASPACK_VER_OTHER,
ASPACK_VER_242
} aspack_version_t;
int unaspack(uint8_t *image, unsigned int size, struct cli_exe_section *sections, uint16_t sectcount, uint32_t ep, uint32_t base, int f, aspack_version_t version);
#endif
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Alberto Wu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __AUTOIT_H
#define __AUTOIT_H
#include "others.h"
int cli_scanautoit(cli_ctx *ctx, off_t offset);
#endif
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
* Authors: Török Edvin
*
* 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 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 BC_FEATURES_H
#define BC_FEATURES_H
/* Compatibility for non-clang compilers */
#ifndef __has_feature
#define __has_feature(x) 0
#endif
#if __has_feature(attribute_bounds)
#define EBOUNDS(fieldname) __attribute__((bounds(fieldname)))
#else
#define EBOUNDS(x)
#endif
#endif
+28
View File
@@ -0,0 +1,28 @@
#ifndef BIGNUM_H_
#define BIGNUM_H_
#define TFM_CHECK
#include "bignum_fast.h"
typedef fp_int mp_int;
#define mp_cmp fp_cmp
#define mp_toradix_n(a, b, c, d) fp_toradix_n(a, b, c, d)
#define mp_init(a) (fp_init(a), 0)
#define mp_add fp_add
#define mp_init_multi(a, b, c, d) (mp_init(a), mp_init(b), mp_init(c), 0)
#define mp_read_unsigned_bin(a, b, c) (fp_read_unsigned_bin(a, b, c), 0)
#define mp_div fp_div
#define mp_clear_multi(...)
#define mp_copy(a, b) (fp_copy(a, b), 0)
#define mp_unsigned_bin_size fp_unsigned_bin_size
#define mp_to_unsigned_bin(a, b) (fp_to_unsigned_bin(a, b), 0)
#define mp_read_radix fp_read_radix
#define mp_exptmod fp_exptmod
#define mp_get_int(a) ((a)->used > 0 ? (a)->dp[0] : 0)
#define mp_set_int(a, b) fp_set(a, b)
#define mp_mul_2d fp_mul_2d
#define mp_clear(x)
#endif
+595
View File
@@ -0,0 +1,595 @@
/* TomsFastMath, a fast ISO C bignum library.
*
* This project is meant to fill in where LibTomMath
* falls short. That is speed ;-)
*
* This project is public domain and free for all purposes.
*
* Tom St Denis, tomstdenis@gmail.com
*/
/* Oct 1, 2013
* Adding clamav-config.h include here for size-checking on fall-through case
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#ifndef TFM_H_
#define TFM_H_
#if !defined(__GNUC__) || !defined(__x86_64__)
/* on i686 we run out of registers with -fPIC, and on ia64 we miscompile.
* Just enable this on x86-64 where we know it works */
#define TFM_NO_ASM
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#ifndef MIN
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#endif
#ifndef MAX
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#endif
/* externally define this symbol to ignore the default settings, useful for changing the build from the make process */
#ifndef TFM_ALREADY_SET
/* do we want the large set of small multiplications ?
Enable these if you are going to be doing a lot of small (<= 16 digit) multiplications say in ECC
Or if you're on a 64-bit machine doing RSA as a 1024-bit integer == 16 digits ;-)
*/
#define TFM_SMALL_SET
/* do we want huge code
Enable these if you are doing 20, 24, 28, 32, 48, 64 digit multiplications (useful for RSA)
Less important on 64-bit machines as 32 digits == 2048 bits
*/
#if 0
#define TFM_MUL3
#define TFM_MUL4
#define TFM_MUL6
#define TFM_MUL7
#define TFM_MUL8
#define TFM_MUL9
#define TFM_MUL12
#define TFM_MUL17
#endif
#define TFM_MUL20
#define TFM_MUL24
#define TFM_MUL28
#define TFM_MUL32
/*#define TFM_MUL48
#define TFM_MUL64*/
#if 0
#define TFM_SQR3
#define TFM_SQR4
#define TFM_SQR6
#define TFM_SQR7
#define TFM_SQR8
#define TFM_SQR9
#define TFM_SQR12
#define TFM_SQR17
#endif
#define TFM_SQR20
#define TFM_SQR24
#define TFM_SQR28
#define TFM_SQR32
/*#define TFM_SQR48
#define TFM_SQR64*/
/* do we want some overflow checks
Not required if you make sure your numbers are within range (e.g. by default a modulus for fp_exptmod() can only be upto 2048 bits long)
*/
#define TFM_CHECK
/* Is the target a P4 Prescott
*/
/* #define TFM_PRESCOTT */
/* Do we want timing resistant fp_exptmod() ?
* This makes it slower but also timing invariant with respect to the exponent
*/
/* #define TFM_TIMING_RESISTANT */
#endif
/* autodetect x86-64 and make sure we are using 64-bit digits with x86-64 asm */
#if defined(__x86_64__)
#if defined(TFM_X86) || defined(TFM_SSE2) || defined(TFM_ARM)
#error x86-64 detected, x86-32/SSE2/ARM optimizations are not valid!
#endif
#if !defined(TFM_X86_64) && !defined(TFM_NO_ASM)
#define TFM_X86_64
#endif
#endif
#if defined(TFM_X86_64)
#if !defined(FP_64BIT)
#define FP_64BIT
#endif
#endif
/* try to detect x86-32 */
#if defined(__i386__) && !defined(TFM_SSE2)
#if defined(TFM_X86_64) || defined(TFM_ARM)
#error x86-32 detected, x86-64/ARM optimizations are not valid!
#endif
#if !defined(TFM_X86) && !defined(TFM_NO_ASM)
#define TFM_X86
#endif
#endif
/* make sure we're 32-bit for x86-32/sse/arm/ppc32 */
#if (defined(TFM_X86) || defined(TFM_SSE2) || defined(TFM_ARM) || defined(TFM_PPC32)) && defined(FP_64BIT)
#warning x86-32, SSE2 and ARM, PPC32 optimizations require 32-bit digits (undefining)
#undef FP_64BIT
#endif
/* multi asms? */
#ifdef TFM_X86
#define TFM_ASM
#endif
#ifdef TFM_X86_64
#ifdef TFM_ASM
#error TFM_ASM already defined!
#endif
#define TFM_ASM
#endif
#ifdef TFM_SSE2
#ifdef TFM_ASM
#error TFM_ASM already defined!
#endif
#define TFM_ASM
#endif
#ifdef TFM_ARM
#ifdef TFM_ASM
#error TFM_ASM already defined!
#endif
#define TFM_ASM
#endif
#ifdef TFM_PPC32
#ifdef TFM_ASM
#error TFM_ASM already defined!
#endif
#define TFM_ASM
#endif
#ifdef TFM_PPC64
#ifdef TFM_ASM
#error TFM_ASM already defined!
#endif
#define TFM_ASM
#endif
#ifdef TFM_AVR32
#ifdef TFM_ASM
#error TFM_ASM already defined!
#endif
#define TFM_ASM
#endif
/* we want no asm? */
#ifdef TFM_NO_ASM
#undef TFM_X86
#undef TFM_X86_64
#undef TFM_SSE2
#undef TFM_ARM
#undef TFM_PPC32
#undef TFM_PPC64
#undef TFM_AVR32
#undef TFM_ASM
#endif
/* ECC helpers */
#ifdef TFM_ECC192
#ifdef FP_64BIT
#define TFM_MUL3
#define TFM_SQR3
#else
#define TFM_MUL6
#define TFM_SQR6
#endif
#endif
#ifdef TFM_ECC224
#ifdef FP_64BIT
#define TFM_MUL4
#define TFM_SQR4
#else
#define TFM_MUL7
#define TFM_SQR7
#endif
#endif
#ifdef TFM_ECC256
#ifdef FP_64BIT
#define TFM_MUL4
#define TFM_SQR4
#else
#define TFM_MUL8
#define TFM_SQR8
#endif
#endif
#ifdef TFM_ECC384
#ifdef FP_64BIT
#define TFM_MUL6
#define TFM_SQR6
#else
#define TFM_MUL12
#define TFM_SQR12
#endif
#endif
#ifdef TFM_ECC521
#ifdef FP_64BIT
#define TFM_MUL9
#define TFM_SQR9
#else
#define TFM_MUL17
#define TFM_SQR17
#endif
#endif
/* some default configurations.
*/
#if defined(FP_64BIT)
/* for GCC only on supported platforms */
#ifndef CRYPT
typedef unsigned long ulong64;
#endif
typedef ulong64 fp_digit;
typedef unsigned long fp_word __attribute__((mode(TI)));
#else
/* this is to make porting into LibTomCrypt easier :-) */
#ifndef CRYPT
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ulong64;
typedef signed __int64 long64;
#else
typedef unsigned long long ulong64;
typedef signed long long long64;
#endif
#endif
/* The code requires that fp_word be twice the size of fp_digit.
* Add size-checking for special case (both long and long long are 64) */
#if (SIZEOF_LONG == 8) && (SIZEOF_LONG_LONG == 8)
typedef unsigned int fp_digit;
#else
typedef unsigned long fp_digit;
#endif
typedef ulong64 fp_word;
#endif
/* # of digits this is */
#define DIGIT_BIT (int)((CHAR_BIT) * sizeof(fp_digit))
/* Max size of any number in bits. Basically the largest size you will be multiplying
* should be half [or smaller] of FP_MAX_SIZE-four_digit
*
* You can externally define this or it defaults to 4096-bits [allowing multiplications upto 2048x2048 bits ]
*/
#ifndef FP_MAX_SIZE
#define FP_MAX_SIZE (8192 + (8 * DIGIT_BIT))
#endif
/* will this lib work? */
#if (CHAR_BIT & 7)
#error CHAR_BIT must be a multiple of eight.
#endif
#define FP_MASK (fp_digit)(-1)
#define FP_SIZE (FP_MAX_SIZE / DIGIT_BIT)
/* signs */
#define FP_ZPOS 0
#define FP_NEG 1
/* return codes */
#define FP_OKAY 0
#define FP_VAL 1
#define FP_MEM 2
/* equalities */
#define FP_LT -1 /* less than */
#define FP_EQ 0 /* equal to */
#define FP_GT 1 /* greater than */
/* replies */
#define FP_YES 1 /* yes response */
#define FP_NO 0 /* no response */
/* a FP type */
typedef struct {
fp_digit dp[FP_SIZE];
int used,
sign;
} fp_int;
/* functions */
/* returns a TFM ident string useful for debugging... */
const char *fp_ident(void);
/* initialize [or zero] an fp int */
#define fp_init(a) (void)memset((a), 0, sizeof(fp_int))
#define fp_zero(a) fp_init(a)
/* zero/even/odd ? */
#define fp_iszero(a) (((a)->used == 0) ? FP_YES : FP_NO)
#define fp_iseven(a) (((a)->used >= 0 && (((a)->dp[0] & 1) == 0)) ? FP_YES : FP_NO)
#define fp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? FP_YES : FP_NO)
/* set to a small digit */
void fp_set(fp_int *a, fp_digit b);
/* copy from a to b */
#define fp_copy(a, b) (void)(((a) != (b)) && memcpy((b), (a), sizeof(fp_int)))
#define fp_init_copy(a, b) fp_copy(b, a)
/* clamp digits */
#define fp_clamp(a) \
{ \
while ((a)->used && (a)->dp[(a)->used - 1] == 0) --((a)->used); \
(a)->sign = (a)->used ? (a)->sign : FP_ZPOS; \
}
/* negate and absolute */
#define fp_neg(a, b) \
{ \
fp_copy(a, b); \
(b)->sign ^= 1; \
fp_clamp(b); \
}
#define fp_abs(a, b) \
{ \
fp_copy(a, b); \
(b)->sign = 0; \
}
/* right shift x digits */
void fp_rshd(fp_int *a, int x);
/* left shift x digits */
void fp_lshd(fp_int *a, int x);
/* signed comparison */
int fp_cmp(fp_int *a, fp_int *b);
/* unsigned comparison */
int fp_cmp_mag(fp_int *a, fp_int *b);
/* power of 2 operations */
void fp_div_2d(fp_int *a, int b, fp_int *c, fp_int *d);
void fp_mod_2d(fp_int *a, int b, fp_int *c);
void fp_mul_2d(fp_int *a, int b, fp_int *c);
void fp_2expt(fp_int *a, int b);
void fp_mul_2(fp_int *a, fp_int *c);
void fp_div_2(fp_int *a, fp_int *c);
/* Counts the number of lsbs which are zero before the first zero bit */
int fp_cnt_lsb(fp_int *a);
/* c = a + b */
void fp_add(fp_int *a, fp_int *b, fp_int *c);
/* c = a - b */
void fp_sub(fp_int *a, fp_int *b, fp_int *c);
/* c = a * b */
void fp_mul(fp_int *a, fp_int *b, fp_int *c);
/* b = a*a */
void fp_sqr(fp_int *a, fp_int *b);
/* a/b => cb + d == a */
int fp_div(fp_int *a, fp_int *b, fp_int *c, fp_int *d);
/* c = a mod b, 0 <= c < b */
int fp_mod(fp_int *a, fp_int *b, fp_int *c);
/* compare against a single digit */
int fp_cmp_d(fp_int *a, fp_digit b);
/* c = a + b */
void fp_add_d(fp_int *a, fp_digit b, fp_int *c);
/* c = a - b */
void fp_sub_d(fp_int *a, fp_digit b, fp_int *c);
/* c = a * b */
void fp_mul_d(fp_int *a, fp_digit b, fp_int *c);
/* a/b => cb + d == a */
int fp_div_d(fp_int *a, fp_digit b, fp_int *c, fp_digit *d);
/* c = a mod b, 0 <= c < b */
int fp_mod_d(fp_int *a, fp_digit b, fp_digit *c);
/* ---> number theory <--- */
/* d = a + b (mod c) */
int fp_addmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d);
/* d = a - b (mod c) */
int fp_submod(fp_int *a, fp_int *b, fp_int *c, fp_int *d);
/* d = a * b (mod c) */
int fp_mulmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d);
/* c = a * a (mod b) */
int fp_sqrmod(fp_int *a, fp_int *b, fp_int *c);
/* c = 1/a (mod b) */
int fp_invmod(fp_int *a, fp_int *b, fp_int *c);
/* c = (a, b) */
void fp_gcd(fp_int *a, fp_int *b, fp_int *c);
/* c = [a, b] */
void fp_lcm(fp_int *a, fp_int *b, fp_int *c);
/* setups the montgomery reduction */
int fp_montgomery_setup(fp_int *a, fp_digit *mp);
/* computes a = B**n mod b without division or multiplication useful for
* normalizing numbers in a Montgomery system.
*/
void fp_montgomery_calc_normalization(fp_int *a, fp_int *b);
/* computes x/R == x (mod N) via Montgomery Reduction */
void fp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp);
/* d = a**b (mod c) */
int fp_exptmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d);
/* primality stuff */
/* perform a Miller-Rabin test of a to the base b and store result in "result" */
void fp_prime_miller_rabin(fp_int *a, fp_int *b, int *result);
/* 256 trial divisions + 8 Miller-Rabins, returns FP_YES if probable prime */
int fp_isprime(fp_int *a);
/* Primality generation flags */
#define TFM_PRIME_BBS 0x0001 /* BBS style prime */
#define TFM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */
#define TFM_PRIME_2MSB_OFF 0x0004 /* force 2nd MSB to 0 */
#define TFM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */
/* callback for fp_prime_random, should fill dst with random bytes and return how many read [upto len] */
typedef int tfm_prime_callback(unsigned char *dst, int len, void *dat);
#define fp_prime_random(a, t, size, bbs, cb, dat) fp_prime_random_ex(a, t, ((size)*8) + 1, (bbs == 1) ? TFM_PRIME_BBS : 0, cb, dat)
int fp_prime_random_ex(fp_int *a, int t, int size, int flags, tfm_prime_callback cb, void *dat);
/* radix conversions */
int fp_count_bits(fp_int *a);
int fp_unsigned_bin_size(fp_int *a);
void fp_read_unsigned_bin(fp_int *a, const unsigned char *b, int c);
void fp_to_unsigned_bin(fp_int *a, unsigned char *b);
int fp_signed_bin_size(fp_int *a);
void fp_read_signed_bin(fp_int *a, unsigned char *b, int c);
void fp_to_signed_bin(fp_int *a, unsigned char *b);
int fp_read_radix(fp_int *a, const char *str, int radix);
int fp_toradix(fp_int *a, char *str, int radix);
int fp_toradix_n(fp_int *a, char *str, int radix, int maxlen);
/* VARIOUS LOW LEVEL STUFFS */
void s_fp_add(fp_int *a, fp_int *b, fp_int *c);
void s_fp_sub(fp_int *a, fp_int *b, fp_int *c);
void fp_reverse(unsigned char *s, int len);
void fp_mul_comba(fp_int *A, fp_int *B, fp_int *C);
#ifdef TFM_SMALL_SET
void fp_mul_comba_small(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL3
void fp_mul_comba3(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL4
void fp_mul_comba4(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL6
void fp_mul_comba6(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL7
void fp_mul_comba7(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL8
void fp_mul_comba8(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL9
void fp_mul_comba9(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL12
void fp_mul_comba12(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL17
void fp_mul_comba17(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL20
void fp_mul_comba20(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL24
void fp_mul_comba24(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL28
void fp_mul_comba28(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL32
void fp_mul_comba32(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL48
void fp_mul_comba48(fp_int *A, fp_int *B, fp_int *C);
#endif
#ifdef TFM_MUL64
void fp_mul_comba64(fp_int *A, fp_int *B, fp_int *C);
#endif
void fp_sqr_comba(fp_int *A, fp_int *B);
#ifdef TFM_SMALL_SET
void fp_sqr_comba_small(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR3
void fp_sqr_comba3(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR4
void fp_sqr_comba4(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR6
void fp_sqr_comba6(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR7
void fp_sqr_comba7(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR8
void fp_sqr_comba8(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR9
void fp_sqr_comba9(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR12
void fp_sqr_comba12(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR17
void fp_sqr_comba17(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR20
void fp_sqr_comba20(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR24
void fp_sqr_comba24(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR28
void fp_sqr_comba28(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR32
void fp_sqr_comba32(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR48
void fp_sqr_comba48(fp_int *A, fp_int *B);
#endif
#ifdef TFM_SQR64
void fp_sqr_comba64(fp_int *A, fp_int *B);
#endif
extern const char *fp_s_rmap;
#endif
/* $Source: /cvs/libtom/tomsfastmath/src/headers/tfm.h,v $ */
/* $Revision: 1.3 $ */
/* $Date: 2007/02/27 02:38:44 $ */
+274
View File
@@ -0,0 +1,274 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2010-2013 Sourcefire, Inc.
*
* Authors: aCaB <acab@clamav.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <string.h>
#include "scanners.h"
#include "others.h"
#include "clamav.h"
#include "fmap.h"
#include "binhex.h"
// clang-format off
static const uint8_t hqxtbl[] = {
/* 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */
/* 00-0f */ 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
/* 10-1f */ 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
/* 20-2f */ 0xff,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0xff,0xff,
/* 30-3f */ 0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0xff,0x14,0x15,0xff,0xff,0xff,0xff,0xff,0xff,
/* 40-4f */ 0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23,0x24,0xff,
/* 50-5f */ 0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0xff,0x2c,0x2d,0x2e,0x2f,0xff,0xff,0xff,0xff,
/* 60-6f */ 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0xff,0x37,0x38,0x39,0x3a,0x3b,0x3c,0xff,0xff,
/* 70-7f */ 0x3d,0x3e,0x3f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
};
// clang-format on
#define BH_FLUSH_SZ (BUFSIZ - 256)
int cli_binhex(cli_ctx *ctx)
{
fmap_t *map = ctx->fmap;
const uint8_t *encoded = NULL;
uint8_t decoded[BUFSIZ], spare_bits = 0, last_byte = 0, this_byte = 0, offset = 0;
size_t enc_done = 0, enc_todo = map->len;
unsigned int dec_done = 0, chunksz = 0, chunkoff = 0;
uint32_t datalen = 0, reslen = 0;
int in_data = 0, in_run = 0, datafd, resfd, ret = CL_CLEAN;
enum binhex_phase { IN_BANNER,
IN_HEADER,
IN_DATA,
IN_LIMBO1,
IN_LIMBO2,
IN_RES } write_phase = IN_BANNER;
char *dname, *rname;
cli_dbgmsg("in cli_binhex\n");
if (!map->len) return CL_CLEAN;
if ((ret = cli_gentempfd(ctx->sub_tmpdir, &dname, &datafd)) != CL_SUCCESS)
return ret;
if ((ret = cli_gentempfd(ctx->sub_tmpdir, &rname, &resfd)) != CL_SUCCESS) {
close(datafd);
if (cli_unlink(dname)) ret = CL_EUNLINK;
free(dname);
return ret;
}
memset(decoded, 0, 24);
while (1) {
uint8_t b;
if (!enc_todo || dec_done >= BH_FLUSH_SZ) {
if (write_phase == IN_HEADER) {
uint32_t namelen = (uint32_t)decoded[0], hdrlen = 1 + namelen + 1 + 4 + 4 + 2;
if (!dec_done) {
cli_dbgmsg("cli_binhex: file is empty\n");
break;
}
datalen = (decoded[hdrlen] << 24) | (decoded[hdrlen + 1] << 16) | (decoded[hdrlen + 2] << 8) | decoded[hdrlen + 3];
hdrlen += 4;
reslen = (decoded[hdrlen] << 24) | (decoded[hdrlen + 1] << 16) | (decoded[hdrlen + 2] << 8) | decoded[hdrlen + 3];
hdrlen += 4 + 2;
decoded[namelen + 1] = 0;
if (dec_done <= hdrlen) {
cli_dbgmsg("cli_binhex: file too short for header\n");
break;
}
if ((ret = cli_checklimits("cli_binhex(data)", ctx, datalen, 0, 0)) != CL_CLEAN)
break;
if (cli_checklimits("cli_binhex(resources)", ctx, reslen, 0, 0) != CL_CLEAN)
reslen = 0;
cli_dbgmsg("cli_binhex: decoding '%s' - %u bytes of data to %s - %u bytes or resources to %s\n", decoded + 1, datalen, dname, reslen, rname);
memmove(decoded, &decoded[hdrlen], dec_done - hdrlen);
dec_done -= hdrlen;
write_phase++;
}
if (dec_done && write_phase == IN_DATA) {
unsigned int todo = MIN(dec_done, datalen);
datalen -= todo;
dec_done -= todo;
if (cli_writen(datafd, decoded, todo) != todo) {
ret = CL_EWRITE;
break;
}
if (!datalen) {
write_phase++;
if (lseek(datafd, 0, SEEK_SET) == -1) {
cli_dbgmsg("cli_binhex: call to lseek() has failed\n");
ret = CL_ESEEK;
break;
}
ret = cli_magic_scan_desc(datafd, dname, ctx, NULL);
if (ret == CL_VIRUS) break;
}
if (dec_done)
memmove(decoded, &decoded[todo], dec_done);
}
if (dec_done && write_phase == IN_LIMBO1) {
if (dec_done > 1) {
if (reslen < 5) {
cli_dbgmsg("cli_binhex: skipping resources (too small)\n");
break;
}
dec_done -= 2;
write_phase += 2;
if (dec_done)
memmove(decoded, &decoded[2], dec_done);
} else {
dec_done--;
write_phase++;
if (dec_done)
memmove(decoded, &decoded[1], dec_done);
}
}
if (dec_done && write_phase == IN_LIMBO2) {
if (reslen < 5) {
cli_dbgmsg("cli_binhex: skipping resources (too small)\n");
break;
}
write_phase++;
if (--dec_done)
memmove(decoded, &decoded[1], dec_done);
}
if (dec_done && write_phase == IN_RES) {
unsigned int todo = MIN(dec_done, reslen);
reslen -= todo;
dec_done -= todo;
if (cli_writen(resfd, decoded, todo) != todo) {
ret = CL_EWRITE;
break;
}
if (!reslen) {
if (lseek(resfd, 0, SEEK_SET) == -1) {
cli_dbgmsg("cli_binhex: call to lseek() has failed\n");
ret = CL_ESEEK;
break;
}
ret = cli_magic_scan_desc(resfd, rname, ctx, NULL);
break;
}
}
if (!enc_todo) {
if (write_phase == IN_DATA) {
cli_dbgmsg("cli_binhex: scanning partially extracted data fork\n");
if (lseek(datafd, 0, SEEK_SET) == -1) {
cli_dbgmsg("cli_binhex: call to lseek() has failed\n");
ret = CL_ESEEK;
break;
}
ret = cli_magic_scan_desc(datafd, dname, ctx, NULL);
} else if (write_phase == IN_RES) {
cli_dbgmsg("cli_binhex: scanning partially extracted resource fork\n");
if (lseek(resfd, 0, SEEK_SET) == -1) {
cli_dbgmsg("cli_binhex: call to lseek() has failed\n");
ret = CL_ESEEK;
break;
}
ret = cli_magic_scan_desc(resfd, rname, ctx, NULL);
}
break;
}
}
// 'chunksz' must be 0 the first iteration,
// so that 'encoded' will be initialized before first dereference.
if (!chunksz) {
chunksz = MIN(enc_todo, map->pgsz);
encoded = fmap_need_off_once(map, enc_done, chunksz);
if (!encoded) {
ret = CL_EREAD;
break;
}
chunkoff = 0;
}
chunksz--;
b = encoded[chunkoff++];
enc_done++;
enc_todo--;
if ((char)b == '\r' || (char)b == '\n') {
in_data = 1;
continue;
}
if (!in_data) continue;
if (write_phase == IN_BANNER) {
if ((char)b != ':') {
cli_dbgmsg("cli_binhex: broken file (missing stream start identifier)\n");
break;
}
write_phase++;
}
if ((char)b == ':')
continue;
if (b > 0x7f || (b = hqxtbl[b]) == 0xff) {
cli_dbgmsg("cli_binhex: Invalid character (%02x)\n", encoded[chunkoff - 1]);
break;
}
switch ((offset++) & 3) { /* 6 bits per char */
case 0: /* left-6h */
spare_bits = b << 2;
continue;
case 1: /* left-2l + middle-4h */
this_byte = spare_bits | (b >> 4);
spare_bits = b << 4;
break;
case 2: /* middle-4l + right-2h */
this_byte = spare_bits | (b >> 2);
spare_bits = b << 6;
break;
case 3: /* right-6l */
this_byte = spare_bits | b;
}
if (in_run) {
in_run = 0;
if (!this_byte)
this_byte = 0x90;
else {
while (--this_byte)
decoded[dec_done++] = last_byte;
continue;
}
} else if (this_byte == 0x90) {
in_run = 1;
continue;
}
decoded[dec_done++] = this_byte;
last_byte = this_byte;
}
close(datafd);
close(resfd);
if (!ctx->engine->keeptmp) {
if (cli_unlink(dname) && ret != CL_VIRUS) ret = CL_EUNLINK;
if (cli_unlink(rname) && ret != CL_VIRUS) ret = CL_EUNLINK;
}
free(dname);
free(rname);
return ret;
}
+28
View File
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Nigel Horne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __BINHEX_H
#define __BINHEX_H
#include "others.h"
int cli_binhex(cli_ctx *ctx);
#endif
+695
View File
@@ -0,0 +1,695 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Nigel Horne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* for NAME_MAX */
#endif
#ifdef C_DARWIN
#include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "others.h"
#include "mbox.h"
#include "matcher.h"
#include "scanners.h"
#include "filetypes.h"
#include <assert.h>
/* Scheduled for rewrite in 0.94 (bb#804). Disabling for now */
/* #define MAX_SCAN_SIZE 20*1024 /\* */
/* * The performance benefit of scanning */
/* * early disappears on medium and */
/* * large sized files */
/* *\/ */
static const char *blobGetFilename(const blob *b);
blob *
blobCreate(void)
{
#ifdef CL_DEBUG
blob *b = (blob *)cli_calloc(1, sizeof(blob));
if (b)
b->magic = BLOBCLASS;
cli_dbgmsg("blobCreate\n");
return b;
#else
return (blob *)cli_calloc(1, sizeof(blob));
#endif
}
void blobDestroy(blob *b)
{
#ifdef CL_DEBUG
cli_dbgmsg("blobDestroy %d\n", b->magic);
#else
cli_dbgmsg("blobDestroy\n");
#endif
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
if (b->name)
free(b->name);
if (b->data)
free(b->data);
#ifdef CL_DEBUG
b->magic = INVALIDCLASS;
#endif
free(b);
}
void blobArrayDestroy(blob *blobList[], int n)
{
assert(blobList != NULL);
while (--n >= 0) {
cli_dbgmsg("blobArrayDestroy: %d\n", n);
if (blobList[n]) {
blobDestroy(blobList[n]);
blobList[n] = NULL;
}
}
}
/*
* No longer needed to be growable, so turn into a normal memory area which
* the caller must free. The passed blob is destroyed
*/
void *
blobToMem(blob *b)
{
void *ret;
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
if (!b->isClosed)
blobClose(b);
if (b->name)
free(b->name);
#ifdef CL_DEBUG
b->magic = INVALIDCLASS;
#endif
ret = (void *)b->data;
free(b);
return ret;
}
/*ARGSUSED*/
void blobSetFilename(blob *b, const char *dir, const char *filename)
{
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
assert(filename != NULL);
UNUSEDPARAM(dir);
cli_dbgmsg("blobSetFilename: %s\n", filename);
if (b->name)
free(b->name);
b->name = cli_strdup(filename);
if (b->name)
sanitiseName(b->name);
}
static const char *
blobGetFilename(const blob *b)
{
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
return b->name;
}
/*
* Returns <0 for failure
*/
int blobAddData(blob *b, const unsigned char *data, size_t len)
{
#if HAVE_CLI_GETPAGESIZE
static int pagesize = 0;
int growth;
#endif
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
assert(data != NULL);
if (len == 0)
return 0;
if (b->isClosed) {
/*
* Should be cli_dbgmsg, but I want to see them for now,
* and cli_dbgmsg doesn't support debug levels
*/
cli_warnmsg("Reopening closed blob\n");
b->isClosed = 0;
}
/*
* The payoff here is between reducing the number of calls to
* malloc/realloc and not overallocating memory. A lot of machines
* are more tight with memory than one may imagine which is why
* we don't just allocate a *huge* amount and be done with it. Closing
* the blob helps because that reclaims memory. If you know the maximum
* size of a blob before you start adding data, use blobGrow() that's
* the most optimum
*/
#if HAVE_CLI_GETPAGESIZE
if (pagesize == 0) {
pagesize = cli_getpagesize();
if (pagesize == 0)
pagesize = 4096;
}
growth = pagesize;
if (len >= (size_t)pagesize)
growth = ((len / pagesize) + 1) * pagesize;
/*cli_dbgmsg("blobGrow: b->size %lu, b->len %lu, len %lu, growth = %u\n",
b->size, b->len, len, growth);*/
if (b->data == NULL) {
assert(b->len == 0);
assert(b->size == 0);
b->size = growth;
b->data = cli_malloc(growth);
if (NULL == b->data) {
b->size = 0;
return -1;
}
} else if (b->size < b->len + (off_t)len) {
unsigned char *p = cli_realloc(b->data, b->size + growth);
if (p == NULL)
return -1;
b->size += growth;
b->data = p;
}
#else
if (b->data == NULL) {
assert(b->len == 0);
assert(b->size == 0);
b->size = (off_t)len * 4;
b->data = cli_malloc(b->size);
if (NULL == b->data) {
b->size = 0;
return -1;
}
} else if (b->size < b->len + (off_t)len) {
unsigned char *p = cli_realloc(b->data, b->size + (len * 4));
if (p == NULL)
return -1;
b->size += (off_t)len * 4;
b->data = p;
}
#endif
if (b->data) {
memcpy(&b->data[b->len], data, len);
b->len += (off_t)len;
} else {
b->size = 0;
return -1;
}
return 0;
}
unsigned char *
blobGetData(const blob *b)
{
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
if (b->len == 0)
return NULL;
return b->data;
}
size_t
blobGetDataSize(const blob *b)
{
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
return b->len;
}
void blobClose(blob *b)
{
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
if (b->isClosed) {
cli_warnmsg("Attempt to close a previously closed blob\n");
return;
}
/*
* Nothing more is going to be added to this blob. If it'll save more
* than a trivial amount (say 64 bytes) of memory, shrink the allocation
*/
if ((b->size - b->len) >= 64) {
if (b->len == 0) { /* Not likely */
free(b->data);
b->data = NULL;
cli_dbgmsg("blobClose: recovered all %lu bytes\n",
(unsigned long)b->size);
b->size = 0;
} else {
unsigned char *ptr = cli_realloc(b->data, b->len);
if (ptr == NULL) {
return;
}
cli_dbgmsg("blobClose: recovered %lu bytes from %lu\n",
(unsigned long)(b->size - b->len),
(unsigned long)b->size);
b->size = b->len;
b->data = ptr;
}
}
b->isClosed = 1;
}
/*
* Returns 0 if the blobs are the same
*/
int blobcmp(const blob *b1, const blob *b2)
{
size_t s1, s2;
assert(b1 != NULL);
assert(b2 != NULL);
if (b1 == b2)
return 0;
s1 = blobGetDataSize(b1);
s2 = blobGetDataSize(b2);
if (s1 != s2)
return 1;
if ((s1 == 0) && (s2 == 0))
return 0;
return memcmp(blobGetData(b1), blobGetData(b2), s1);
}
/*
* Return clamav return code
*/
int blobGrow(blob *b, size_t len)
{
assert(b != NULL);
#ifdef CL_DEBUG
assert(b->magic == BLOBCLASS);
#endif
if (len == 0)
return CL_SUCCESS;
if (b->isClosed) {
/*
* Should be cli_dbgmsg, but I want to see them for now,
* and cli_dbgmsg doesn't support debug levels
*/
cli_warnmsg("Growing closed blob\n");
b->isClosed = 0;
}
if (b->data == NULL) {
assert(b->len == 0);
assert(b->size == 0);
b->data = cli_malloc(len);
if (b->data)
b->size = (off_t)len;
} else {
unsigned char *ptr = cli_realloc(b->data, b->size + len);
if (ptr) {
b->size += (off_t)len;
b->data = ptr;
}
}
return (b->data) ? CL_SUCCESS : CL_EMEM;
}
fileblob *
fileblobCreate(void)
{
#ifdef CL_DEBUG
fileblob *fb = (fileblob *)cli_calloc(1, sizeof(fileblob));
if (fb)
fb->b.magic = BLOBCLASS;
cli_dbgmsg("blobCreate\n");
return fb;
#else
return (fileblob *)cli_calloc(1, sizeof(fileblob));
#endif
}
/*
* Returns CL_CLEAN or CL_VIRUS. Destroys the fileblob and removes the file
* if possible
*/
int fileblobScanAndDestroy(fileblob *fb)
{
switch (fileblobScan(fb)) {
case CL_VIRUS:
fileblobDestructiveDestroy(fb);
return CL_VIRUS;
case CL_BREAK:
fileblobDestructiveDestroy(fb);
return CL_CLEAN;
default:
fileblobDestroy(fb);
return CL_CLEAN;
}
}
/*
* Destroy the fileblob, and remove the file associated with it
*/
void fileblobDestructiveDestroy(fileblob *fb)
{
if (fb->fp && fb->fullname) {
fclose(fb->fp);
cli_dbgmsg("fileblobDestructiveDestroy: %s\n", fb->fullname);
if (!fb->ctx || !fb->ctx->engine->keeptmp)
cli_unlink(fb->fullname);
free(fb->fullname);
fb->fp = NULL;
fb->fullname = NULL;
}
if (fb->b.name) {
free(fb->b.name);
fb->b.name = NULL;
}
fileblobDestroy(fb);
}
/*
* Destroy the fileblob, and remove the file associated with it if that file is
* empty
*/
void fileblobDestroy(fileblob *fb)
{
assert(fb != NULL);
#ifdef CL_DEBUG
assert(fb->b.magic == BLOBCLASS);
#endif
if (fb->b.name && fb->fp) {
fclose(fb->fp);
if (fb->fullname) {
cli_dbgmsg("fileblobDestroy: %s\n", fb->fullname);
if (!fb->isNotEmpty) {
cli_dbgmsg("fileblobDestroy: not saving empty file\n");
cli_unlink(fb->fullname);
}
}
free(fb->b.name);
assert(fb->b.data == NULL);
} else if (fb->b.data) {
free(fb->b.data);
if (fb->b.name) {
cli_errmsg("fileblobDestroy: %s not saved: report to https://github.com/Cisco-Talos/clamav/issues\n",
(fb->fullname) ? fb->fullname : fb->b.name);
free(fb->b.name);
} else
cli_errmsg("fileblobDestroy: file not saved (%lu bytes): report to https://github.com/Cisco-Talos/clamav/issues\n",
(unsigned long)fb->b.len);
}
if (fb->fullname)
free(fb->fullname);
#ifdef CL_DEBUG
fb->b.magic = INVALIDCLASS;
#endif
free(fb);
}
void fileblobPartialSet(fileblob *fb, const char *fullname, const char *arg)
{
UNUSEDPARAM(arg);
if (fb->b.name)
return;
assert(fullname != NULL);
cli_dbgmsg("fileblobPartialSet: saving to %s\n", fullname);
fb->fd = open(fullname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_EXCL, 0600);
if (fb->fd < 0) {
cli_errmsg("fileblobPartialSet: unable to create file: %s\n", fullname);
return;
}
fb->fp = fdopen(fb->fd, "wb");
if (fb->fp == NULL) {
cli_errmsg("fileblobSetFilename: fdopen failed\n");
close(fb->fd);
return;
}
blobSetFilename(&fb->b, fb->ctx ? fb->ctx->sub_tmpdir : NULL, fullname);
if (fb->b.data)
if (fileblobAddData(fb, fb->b.data, fb->b.len) == 0) {
free(fb->b.data);
fb->b.data = NULL;
fb->b.len = fb->b.size = 0;
fb->isNotEmpty = 1;
}
fb->fullname = cli_strdup(fullname);
}
void fileblobSetFilename(fileblob *fb, const char *dir, const char *filename)
{
char *fullname;
if (fb->b.name)
return;
assert(filename != NULL);
assert(dir != NULL);
blobSetFilename(&fb->b, dir, filename);
/*
* Reload the filename, it may be different from the one we've
* asked for, e.g. '/'s taken out
*/
filename = blobGetFilename(&fb->b);
assert(filename != NULL);
if (cli_gentempfd(dir, &fullname, &fb->fd) != CL_SUCCESS) return;
cli_dbgmsg("fileblobSetFilename: file %s saved to %s\n", filename, fullname);
fb->fp = fdopen(fb->fd, "wb");
if (fb->fp == NULL) {
cli_errmsg("fileblobSetFilename: fdopen failed\n");
close(fb->fd);
free(fullname);
return;
}
if (fb->b.data)
if (fileblobAddData(fb, fb->b.data, fb->b.len) == 0) {
free(fb->b.data);
fb->b.data = NULL;
fb->b.len = fb->b.size = 0;
fb->isNotEmpty = 1;
}
fb->fullname = fullname;
}
int fileblobAddData(fileblob *fb, const unsigned char *data, size_t len)
{
if (len == 0)
return 0;
assert(data != NULL);
if (fb->fp) {
#if defined(MAX_SCAN_SIZE) && (MAX_SCAN_SIZE > 0)
const cli_ctx *ctx = fb->ctx;
if (fb->isInfected) /* pretend all was written */
return 0;
if (ctx) {
int do_scan = 1;
if (cli_checklimits("fileblobAddData", ctx, fb->bytes_scanned, 0, 0) != CL_CLEAN)
do_scan = 0;
if (fb->bytes_scanned > MAX_SCAN_SIZE)
do_scan = 0;
if (do_scan) {
if (ctx->scanned)
*ctx->scanned += (unsigned long)len / CL_COUNT_PRECISION;
fb->bytes_scanned += (unsigned long)len;
if ((len > 5) && cli_updatelimits(ctx, len) == CL_CLEAN && (cli_scan_buff(data, (unsigned int)len, 0, ctx->virname, ctx->engine, CL_TYPE_BINARY_DATA, NULL) == CL_VIRUS)) {
cli_dbgmsg("fileblobAddData: found %s\n", cli_get_last_virus_str(ctx->virname));
fb->isInfected = 1;
}
}
}
#endif
if (fwrite(data, len, 1, fb->fp) != 1) {
cli_errmsg("fileblobAddData: Can't write %lu bytes to temporary file %s\n",
(unsigned long)len, fb->b.name);
return -1;
}
fb->isNotEmpty = 1;
return 0;
}
return blobAddData(&(fb->b), data, len);
}
const char *
fileblobGetFilename(const fileblob *fb)
{
return blobGetFilename(&(fb->b));
}
void fileblobSetCTX(fileblob *fb, cli_ctx *ctx)
{
fb->ctx = ctx;
}
/*
* Performs a full scan on the fileblob, returning ClamAV status:
* CL_BREAK means clean
* CL_CLEAN means unknown
* CL_VIRUS means infected
*/
int fileblobScan(const fileblob *fb)
{
int rc;
cli_ctx *ctx = fb->ctx;
STATBUF sb;
int virus_found = 0;
if (fb->isInfected)
return CL_VIRUS;
if (fb->fp == NULL || fb->fullname == NULL) {
/* shouldn't happen, scan called before fileblobSetFilename */
cli_warnmsg("fileblobScan, fullname == NULL\n");
return CL_ENULLARG; /* there is no CL_UNKNOWN */
}
if (fb->ctx == NULL) {
/* fileblobSetCTX hasn't been called */
cli_dbgmsg("fileblobScan, ctx == NULL\n");
return CL_CLEAN; /* there is no CL_UNKNOWN */
}
fflush(fb->fp);
lseek(fb->fd, 0, SEEK_SET);
FSTAT(fb->fd, &sb);
if (cli_matchmeta(fb->ctx, fb->b.name, sb.st_size, sb.st_size, 0, 0, 0, NULL) == CL_VIRUS) {
if (!SCAN_ALLMATCHES)
return CL_VIRUS;
virus_found = 1;
}
rc = cli_magic_scan_desc(fb->fd, fb->fullname, fb->ctx, fb->b.name);
if (rc == CL_VIRUS || virus_found != 0) {
cli_dbgmsg("%s is infected\n", fb->fullname);
return CL_VIRUS;
}
cli_dbgmsg("%s is clean\n", fb->fullname);
return CL_BREAK;
}
/*
* Doesn't perform a full scan just lets the caller know if something suspicious has
* been seen yet
*/
int fileblobInfected(const fileblob *fb)
{
return fb->isInfected;
}
/*
* Different operating systems allow different characters in their filenames
* FIXME: What does QNX want? There is no #ifdef C_QNX, but if there were
* it may be best to treat it like MSDOS
*/
void sanitiseName(char *name)
{
char c;
while ((c = *name)) {
if (c != '.' && c != '_' && (c > 'z' || c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a')))
*name = '_';
name++;
}
}
+81
View File
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Nigel Horne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef __BLOB_H
#define __BLOB_H
/*
* Resizable chunk of memory
*/
typedef struct blob {
char *name; /* filename */
unsigned char *data; /* the stuff itself */
off_t len; /* number of bytes of data so far */
off_t size; /* number of bytes allocated to data so far */
int isClosed;
#ifdef CL_DEBUG
object_type magic; /* verify that this is a blob */
#endif
} blob;
blob *blobCreate(void);
void blobDestroy(blob *b);
void blobArrayDestroy(blob *b[], int n);
void *blobToMem(blob *b);
void blobSetFilename(blob *b, const char *dir, const char *filename);
int blobAddData(blob *b, const unsigned char *data, size_t len);
unsigned char *blobGetData(const blob *b);
size_t blobGetDataSize(const blob *b);
void blobClose(blob *b);
int blobcmp(const blob *b1, const blob *b2);
int blobGrow(blob *b, size_t len);
/*
* Like a blob, but associated with a file stored in the temporary directory
*/
typedef struct fileblob {
FILE *fp;
int fd;
blob b; /*
* b.name is the name of the attachment as stored in the
* email, not the full path name of the temporary file
*/
char *fullname; /* full pathname of the file */
cli_ctx *ctx; /* When set we can scan the blob, otherwise NULL */
unsigned long bytes_scanned;
unsigned int isNotEmpty : 1;
unsigned int isInfected : 1;
} fileblob;
fileblob *fileblobCreate(void);
int fileblobScanAndDestroy(fileblob *fb);
void fileblobDestructiveDestroy(fileblob *fb);
void fileblobDestroy(fileblob *fb);
void fileblobSetFilename(fileblob *fb, const char *dir, const char *filename);
void fileblobPartialSet(fileblob *fb, const char *fullname, const char *arg);
const char *fileblobGetFilename(const fileblob *fb);
void fileblobSetCTX(fileblob *fb, cli_ctx *ctx);
int fileblobAddData(fileblob *fb, const unsigned char *data, size_t len);
int fileblobScan(const fileblob *fb);
int fileblobInfected(const fileblob *fb);
void sanitiseName(char *name);
#endif /*_BLOB_H*/
+227
View File
@@ -0,0 +1,227 @@
/*
* Builtin ClamAV bytecodes.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2010-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef BUILTIN_BYTECODES_H
#define BUILTIN_BYTECODES_H
/* bytecode run on startup with interpreter to determine if JIT/bytecode should
* be disabled. It also runs a minimal self-check.
* There can only be one such bytecode, if there is none this is used as
* fallback.
* Usually bytecode.cvd will contain this bytecode */
static const char* builtin_bc_startup =
"ClamBCafhhbfkjmld|afefdfggifnf```aa```|biacflfafmfbfcfmb`cnbacacmbachcccmbgfbfcc`ccchcbfdf``bgcaap`clamcoincidencejb:4096\n"
"\n"
"Teddaaahdabahdacahdadahdaeahdafahdagahebfgebidebegebdgebgdebkdebcgebbgebageb`gebofebnfebmfebedeblfebkfebjfebadcbgab`bb`bb`bb`bb`bb`bb`bbifbifbifbifbifbifbifahahahahahahahahahebneebifaaaaaaaab`baabb`bb`baacb`bbadb`baacb`bboeb`baacb`bb`bb`baadb`bbadb`bb`baadb`bbadbadb`bdbadahdbkaahdbbcahdbibahdb`eahdbddahdbodahdbdaahdaiahdakahdamahdahahdbncahdbnbah\n"
"Ebjdaibcdbbf|bcaefnfgfifnfefoedfcfofnfffoelfeffgeflf``bbdbbf|bkaefnfgfifnfefoeffegnfcfdgifofnfaflfifdgigoelfeffgeflf``agbcf|baadfefbfeggfoe`gbgifnfdgoeegifnfdg``bcabcf|afdgefcgdgbc``afbdf|b`adfefbfeggfoe`gbgifnfdgoecgdgbg``bhdbef|b`agfefdgoeefnffgifbgofnfmfefnfdg``aabff|afdgefcgdgac``bidbgf|bdadfifcgafbflfefoebfigdgefcfofdfefoeifff``bjdbgf|aodfifcgafbflfefoejfifdgoeifff``\n"
"G`b`c`@`b`aAa`bfgBifBkeBccBdcBmeBhcBfcB`bBdfBefBdgBefBcfBdgBefBdfBlbB`bBjdBidBdeB`bBnfBefBefBdfBcgB`bB`gBefBnfBdgBifBegBmfB`bBofBbgB`bBbfBefBdgBdgBefBbg@`bidBifBccBhcBfc@`bidBifBdcBhcBfc@`begBcdB`eBeeB`bBdfBofBefBcgBnfBgbBdgB`bBcgBegB`gB`gBofBbgBdgB`bBcdBmdBodBfeBlbB`bBggBofBegBlfBdfB`bBnfBefBefBdfB`bB`cBnbBicBgcB`bBhbBldBldBfeBmdB`bBbcBnbBhcBibB`bBdgBofB`bBggBofBbgBkfBab@`bidBifBecBhcBfc@`bdgB`gBefBnfBdgBifBegBmf@`bidBifBfcBhcBfc@`bgdBkfBfc@`bidBkfBfcBmbBbc@`bidBkfBfcBmbBcc@`bkdBafBdgBhfBlfBofBnf@`bcgBafBdgBhfBlfBofBnfBmbBdgBbfBifBbgBdf@`bbgBggBifBnfBcfBhfBifB`gBmbBcfBfc@`bagBggBifBnfBcfBhfBifB`gBbc@`bgdBcfBcc@`b`gBbeBgeBheB`bBmfBafB`gB`gBifBnfBgfB`bBdfBefBnfBifBefBdfBnb@`bofBneBceBedBldBifBnfBegBhgB`bBifBcgB`bB`gBbgBefBfgBefBnfBdgBifBnfBgfB`bBgbBefBhgBefBcfBmfBefBmfBgbB`bBafBcfBcfBefBcgBcgBnbAjBbeBegBnfB`bB`bBgbBcgBefBdgBcgBefBbfBofBofBlfB`bBmbB`eB`bBcfBlfBafBmfBdfBoeBegBcgBefBoeBjfBifBdgB`bBofBnfBgbBnb@`bnfBneB`eBafBheB`bBifBcgB`bB`gBbgBefBfgBefBnfBdgBifBnfBgfB`bBgbBmfB`gBbgBofBdgBefBcfBdgBgbB`bBafBcfBcfBefBcgBcgBnbAjBbeBegBnfB`bBgbB`gBafBhgBcfBdgBlfB`bBmbBcfBmfB`bBlcBefBhgBefBcfBegBdgBafBbfBlfBefBncBgb@`bmfBneBbeBgeBheB`bBmfBafB`gB`gBifBnfBgfB`bBdfBefBnfBifBefBdfB`bBffBofBbgB`bBegBnfBkfBnfBofBggBnfB`bBbgBefBafBcgBofBnfBnbB`eBlfBefBafBcgBefB`bBbgBefB`gBofBbgBdgB`bBdgBofB`bBhfBdgBdgB`gBjcBobBobBbfBegBgfBcgBnbBcfBlfBafBmfBafBfgBnbBnfBefBdgAj@`bed@`blfBcgBdgBafBbgBdgBegB`gBjcB`bBbfBigBdgBefBcfBofBdfBefB`bBefBhgBefBcfBegBdgBifBofBnfB`bBifBnfB`bBafBegBdgBofB`bBmfBofBdfBef@`bkfBcgBdgBafBbgBdgBegB`gBjcB`bBbfBigBdgBefBcfBofBdfBefB`bBefBhgBefBcfBegBdgBifBofBnfB`bBggBifBdgBhfB`bBifBnfBdgBefBbgB`gBbgBefBdgBefBbgB`bBofBnfBlfBig@`bjfBcgBdgBafBbgBdgBegB`gBjcB`bBbfBigBdgBefBcfBofBdfBefB`bBdfBifBcgBafBbfBlfBefBdf@`bad@Ab`bad@Ac`bad@Ad`bad@Ae`bad@Af`bad@Ag`bad@Ah`bad@Ai`bad@Aj`bad@Ak`bad@Al`bad@Am`bad@An`bad@Ao`bad@B`a`bad@Baa`bad@Bba`bad@Bca`bad@Bda`bad@Bea`bad@Bfa`bad@Bga`bad@Bha`\n"
"A`b`bLblib`bab`b`b`b`bneab`b`bad`ah`aa`bad`ah`aa`b`f`bad`b`b`aa`b`b`aa`b`b`b`b`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`aa`b`b`b`b`bad`ah`b`b`b`b`aa`b`b`bad`ah`aa`ah`b`b`b`b`aa`b`b`b`b`aa`b`b`b`b`bad`ah`aa`bad`ah`aa`b`b`aa`b`b`b`b`aa`aa`aa`aa`aa`b`b`b`b`b`b`ah`aa`bcd`b`b`aa`bcd`b`b`bcd`b`b`aa`b`b`aa`b`b`b`b`aa`bad`ah`b`b`aa`b`b`aa`bad`ah`b`b`b`b`bad`ah`b`b`b`b`bad`ah`b`b`b`b`b`b`b`b`b`b`b`b`b`b`b`b`b`b`b`b`bad`ah`b`b`b`b`bcd`b`b`b`b`b`b`bad`ah`b`b`b`b`bcd`b`b`b`b`bcd`b`b`aa`b`b`bcd`b`b`aa`b`b`bcd`b`b`aa`b`b`b`b`aa`b`b`b`b`aa`b`b`b`b`Fbbnbec\n"
"Bb`badabbbhdacClnadbadaedbboeacBdadahafgbaeaaageaahaf@aTaaagblaaa\n"
"BbadahdbboeacB`adahaigbahaaajeaahaiAaaTaaajabbaa\n"
"Bb`fakdbboeacAidbadaldbb`fak@db`bamkbalBja`Aedaaaneab`bam@db`b`bbAadabTaaanadac\n"
"Bb`baokbalBka`Aedaab`aeab`bao@db`bab`ab`ab`b`bbababTbaad\n"
"Bb`bbaabbabbaab`bbbaabcbjdBia`@dbaab`bbcaab`bbdaabdaiab`bbcaBicdTaabdaaebaa\n"
"Bb`bbeakbalBma`Aedaabfaeab`bbea@db`b`bbAadaaTaabfab`aaf\n"
"Bb`bbgakbalBna`Ahdaabhaeab`bbga@db`b`bbAadaaTaabhab`aag\n"
"Bb`bbiakbalBoa`Aedaabjaeab`bbia@db`b`bbAadaaTaabjab`aah\n"
"Bb`bbkakbalB`b`Acdaablaeab`bbka@db`b`bbAadaaTaablab`aai\n"
"Bb`bbmakbalBab`Aedaabnaeab`bbma@db`b`bbAadaaTaabnab`aaj\n"
"Bb`bboakbalBbb`Aedaab`beab`bboa@db`b`bbAadaaTaab`bb`aak\n"
"Bb`bbabkbalBcb`Agdaabbbeab`bbab@db`b`bbAadaaTaabbbb`aal\n"
"Bb`bbcbkbalBdb`Amdaabdbeab`bbcb@db`b`bbAadaaTaabdbb`aam\n"
"Bb`bbebkbalBeb`Akdaabfbeab`bbeb@db`b`bbAadaaTaabfbb`aan\n"
"Bb`bbgbkbalBfb`Aidaabhbeab`bbgb@db`b`bbAadaaTaabhbb`aao\n"
"Bb`bbibkbalBgb`Acdaabjbeab`bbib@db`baa`abjbb`b`bbaaaaTbab`a\n"
"Bb`bbkbbbaabkbb`bblbabcbjdBla`@dbkbTbabaa\n"
"BbadbmbdbboeacBeadahbnbgbbmbb`bbob`abnbb`bb`ck`bobAadaabaceab`bb`c@dTaabacbbabha\n"
"Bb`bbbcabcbjdBhb`@dAadbadbccdbboeacBaadahbdcgbbccaabeceaahbdcAjaTaabecbcabla\n"
"Bahbfcgbbmbb`bbgc`abfcb`bbhck`bgcAbdaabiceab`bbhc@dTaabicbeabda\n"
"Bb`bbjcabcbjdBib`@dAadTbabla\n"
"Bb`bbkck`bgcAhdaablceab`bbkc@dTaablcbgabfa\n"
"Bb`bbmcabcbjdBjb`@dAadTbabla\n"
"Bb`bbncabcbjdBkb`@dAadTbabla\n"
"BbadbocdbboeacBaadahb`dgbbocaabadeaahb`dAjaTaabadbjabia\n"
"BbadbbddbboeacBbadahbcdgbbbdaabddeaahbcdAfaTaabddbjabla\n"
"Bb`bbedk`bobB`adaabfdeab`bbed@dTaabfdblabka\n"
"Bb`bbgdabcbjdBjb`@dAadTbabla\n"
"Bb`bbhdabcbidBlb`@d@daabidnab`bbhdAadTaabidb`bbma\n"
"Baabjdnab`bbhdAbdTaabjdboabna\n"
"Baabkdeab`bbhdAbdTaabkdbcbbdb\n"
"Baabldeab`bbhdAadTaabldbbbbdb\n"
"Baabmdeab`bbhd@dTaabmdbabbdb\n"
"Bb`bbndabbafBmb`@dTbabdb\n"
"Bb`bbodabbafBnb`@dTbabdb\n"
"Bb`bb`eabbafBob`@dTbabdb\n"
"Bahbaegbaeaabbeeaahbae@aTaabbebfbbeb\n"
"BbcdbcedbboeacAddb`bbdegbbceaabeeeab`bbde@db`b`bbEamjnmd`Taabeebdcbfb\n"
"BbcdbfedbboeacAfdb`bbgegbbfebcdbhedbboeacAedb`bbiegbbheaabjeiab`bbgebieb`b`bbEbmjnmd`Taabjebdcbgb\n"
"Bb`bbkeab`bbdaableeab`bbiebkeb`b`bbEcmjnmd`Taablebhbbdc\n"
"Bb`bbmegbbfeb`bbneab`bcdaaboeeab`bbmebneb`b`bbEdmjnmd`Taaboebibbdc\n"
"Bbadb`fdbboeacAndahbafgbb`fb`bbbf`abafaabcflbb`bbdf`abcfaabefeab`bbbfbdfb`b`bbEemjnmd`Taabefbjbbdc\n"
"BbadbffdbboeacBaadahbgfgbbffb`bbhf`abgfb`bbifh`bhfBhadbadbjfdbboeacB`adahbkfgbbjfb`bblf`abkfb`bbmfh`blfBdadbadbnfdbboeacBcadahbofgbbnfb`bb`g`abofb`bbagh`b`gB`adb`bbbggbbheb`bbcgh`bbgAhdb`bbdggbbfeb`bbegl`bmfbifb`bbfgl`begbcgb`bbggl`bfgbdgb`bbhgl`bggbagb`bbigh`bbfBladbadbjgdbboeacAodahbkggbbjgb`bblg`abkgb`bbmgh`blgBhadbcdbngdbboeacAddb`bboggbbngb`bb`hl`bogbigb`bbahl`b`hbmgbadbbhdbboeacBeadahbchgbbbhb`bbdh`abchb`bbehh`bdhBhadbcdbfhdbboeacAcdb`bbghgbbfhb`bbhhl`behbghbcdbihdbboeac@db`bbjhgbbihaabkheab`bbhgbjhTaabkhblbbkb\n"
"Bb`bblhabaagbhgTcab`bEfmjnmd\n"
"BbcdbmhdbboeacAadb`bbnhgbbmhaaboheab`bbahbnhTaabohbnbbmb\n"
"Bb`bb`iabaagbahTcab`bEgmjnmd\n"
"BbcdbaidbboeacAbdb`bbbigbbaiaabcieab`bbhhbbiTaabcib`cbob\n"
"Bb`bbdiabaagbhhTcab`bEhmjnmd\n"
"Bb`bbeiabbaaHonnkm``odHm``oonnkdaabfieab`bbeiHhgfedcbadTaabfibbcbac\n"
"Bb`bbgiabaagbeiTcab`bEimjnmd\n"
"Bb`bbhiababcaDm``odaabiieab`bbhiDo``mdb`b`bbHnejkjgjmd`Taabiibdcbcc\n"
"Bb`bbjiabaagbhiTcab`bF`amjnmd\n"
"Bb`bbkibb`bkiTcab`bbkiE\n";
/* source-code for builtin_bc_startup: */
#if 0
const uint16_t __clambc_kind = BC_STARTUP;
int entrypoint()
{
// Whole platform specific bugs can be disabled with check_platform,
// see clamscan --debug for meaning of bits.
// For example:
//disable_jit_if("Pax mprotect on, with RWX", 0,
// check_platform(0x0affffff, 0xffffffff, 0x19));
struct cli_environment env;
get_environment(&env, sizeof(env));
if (env.has_jit_compiled) {
/* CPU checks */
switch (env.arch) {
case arch_i386:
disable_jit_if("i[34]86 detected, JIT needs pentium or better",0,
!memcmp(env.cpu,"i386",5) ||
!memcmp(env.cpu,"i486",5));
if (engine_functionality_level() < FUNC_LEVEL_097) {
/* LLVM 2.7 bug, fixed in 2.8, but only 0.97 has 2.8 */
/* bug is using CMOV instr, when CPU doesn't support it, 2.8 correctly
* handles this, 2.7 doesn't */
disable_jit_if("CPU doesn't support CMOV, would need 0.97 (LLVM 2.8) to work!",0,
!memcmp(env.cpu,"i586",5) ||
!memcmp(env.cpu,"pentium",8) ||
!memcmp(env.cpu,"i686",5) ||
!memcmp(env.cpu,"k6",3) ||
!memcmp(env.cpu,"k6-2",5) ||
!memcmp(env.cpu,"k6-3",5) ||
!memcmp(env.cpu,"athlon",7) ||
!memcmp(env.cpu,"athlon-tbird",13) ||
!memcmp(env.cpu,"winchip-c6",11) ||
!memcmp(env.cpu,"winchip2",9) ||
!memcmp(env.cpu,"c3",3));
}
break;
default:
break;
}
/* RWX checks */
if (!(env.os_features & (1 << feature_map_rwx))) {
disable_jit_if("RWX mapping denied.", 0, 1);
if (env.os_category == os_linux) {
if (env.os_features & (1 << feature_selinux))
/* all SELinux versions deny RWX mapping when policy says so */
disable_jit_if("^SELinux is preventing 'execmem' access.\n"
"Run 'setsebool -P clamd_use_jit on'.", 0, 1);
else if (env.os_features & (1 << feature_pax))
/* recent versions of PaX deny RWX mapping */
disable_jit_if("^PaX is preventing 'mprotect' access.\n"
"Run 'paxctl -cm <executable>'", 0, 1);
else
/* RWX mapping got denied but apparently not due to SELinux/PaX */
disable_jit_if("^RWX mapping denied for unknown reason."
"Please report to https://github.com/Cisco-Talos/clamav/issues\n", 0, 1);
}
} else {
if ((env.os_category == os_linux || env.os == llvm_os_Linux) &&
(env.os_features & (1 << feature_pax_mprotect))) {
/* older versions of PaX allow RWX mapping but silently degrade it to RW
* mapping and kill the program if it tries to execute. */
disable_jit_if("^PaX is preventing 'mprotect' access.\n"
"Run 'paxctl -cm <executable>'", 0, 1);
}
}
}
int s = disable_bytecode_if("",0,0);
switch (s) {
case 0:
debug("startup: bytecode execution in auto mode");
break;
case 1:
debug("startup: bytecode execution with interpreter only");
break;
case 2:
debug("startup: bytecode disabled");
break;
}
/* check that the OS information is consistent */
/* JIT == C++ code compiled */
if (env.has_jit_compiled && !env.cpp_version) {
return 0xdead1;
}
if (env.dconf_level < env.functionality_level) {
return 0xdead2;
}
if (env.functionality_level != engine_functionality_level()) {
return 0xdead3;
}
if (env.dconf_level != engine_dconf_level()) {
return 0xdead4;
}
if (env.big_endian != __is_bigendian()) {
return 0xdead5;
}
uint32_t a = (env.os_category << 24) | (env.arch << 20) |
(env.compiler << 16) | (env.functionality_level << 8) |
(env.dconf_level);
uint32_t b = (env.big_endian << 28) | (env.sizeof_ptr << 24) |
env.cpp_version;
uint32_t c = (env.os_features << 24) | env.c_version;
if (a != env.platform_id_a) {
debug_print_uint(a);
return 0xdead6;
}
if (b != env.platform_id_b) {
debug_print_uint(b);
return 0xdead7;
}
if (c != env.platform_id_c) {
debug_print_uint(c);
return 0xdead8;
}
c = test1(0xf00dbeef, 0xbeeff00d);
if (c != 0x12345678) {
debug_print_uint(c);
return 0xdead9;
}
c = test2(0xf00d);
if (c != 0xd00f) {
debug_print_uint(c);
return 0xdead10;
}
/* magic number to tell libclamav that selftest succeeded */
return 0xda7aba5e;
}
#endif
#endif
File diff suppressed because it is too large Load Diff
+160
View File
@@ -0,0 +1,160 @@
/*
* Load, verify and execute ClamAV bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef BYTECODE_H
#define BYTECODE_H
#include "clamav-types.h"
#include "clambc.h"
#include <stdio.h>
#include "fmap.h"
#include "bytecode_detect.h"
#include "platform.h"
struct cli_dbio;
struct cli_bc_ctx;
struct cli_bc_func;
struct cli_bc_value;
struct cli_bc_inst;
struct cli_bc_type;
struct cli_bc_engine;
struct cli_bc_dbgnode;
struct bitset_tag;
struct cl_engine;
enum bc_state {
bc_skip,
bc_loaded,
bc_jit,
bc_interp,
bc_disabled
};
struct cli_bc {
struct bytecode_metadata metadata;
unsigned id;
unsigned kind;
unsigned num_types;
unsigned num_func;
struct cli_bc_func *funcs;
struct cli_bc_type *types;
uint64_t **globals;
uint16_t *globaltys;
size_t num_globals;
enum bc_state state;
struct bitset_tag *uses_apis;
char *lsig;
char *vnameprefix;
char **vnames;
unsigned vnames_cnt;
uint16_t start_tid;
struct cli_bc_dbgnode *dbgnodes;
unsigned dbgnode_cnt;
unsigned hook_lsig_id;
unsigned trusted;
uint32_t numGlobalBytes;
uint8_t *globalBytes;
uint32_t sigtime_id, sigmatch_id;
char *hook_name;
};
struct cli_all_bc {
struct cli_bc *all_bcs;
unsigned count;
struct cli_bcengine *engine;
struct cli_environment env;
int inited;
};
struct cli_pe_hook_data;
struct cli_exe_section;
struct pdf_obj;
struct cli_bc_ctx *cli_bytecode_context_alloc(void);
/* FIXME: we can't include others.h because others.h includes us...*/
void cli_bytecode_context_setctx(struct cli_bc_ctx *ctx, void *cctx);
int cli_bytecode_context_setfuncid(struct cli_bc_ctx *ctx, const struct cli_bc *bc, unsigned funcid);
int cli_bytecode_context_setparam_int(struct cli_bc_ctx *ctx, unsigned i, uint64_t c);
int cli_bytecode_context_setparam_ptr(struct cli_bc_ctx *ctx, unsigned i, void *data, unsigned datalen);
int cli_bytecode_context_setfile(struct cli_bc_ctx *ctx, fmap_t *map);
int cli_bytecode_context_setpe(struct cli_bc_ctx *ctx, const struct cli_pe_hook_data *data, const struct cli_exe_section *sections);
int cli_bytecode_context_setpdf(struct cli_bc_ctx *ctx, unsigned phase, unsigned nobjs, struct pdf_obj **objs, uint32_t *pdf_flags, uint32_t pdfsize, uint32_t pdfstartoff);
int cli_bytecode_context_clear(struct cli_bc_ctx *ctx);
/* returns file descriptor, sets tempfile. Caller takes ownership, and is
* responsible for freeing/unlinking */
int cli_bytecode_context_getresult_file(struct cli_bc_ctx *ctx, char **tempfilename);
uint64_t cli_bytecode_context_getresult_int(struct cli_bc_ctx *ctx);
void cli_bytecode_context_destroy(struct cli_bc_ctx *ctx);
#ifdef __cplusplus
extern "C" {
#endif
extern LIBCLAMAV_EXPORT int have_clamjit;
#ifdef __cplusplus
}
#endif
int cli_bytecode_init(struct cli_all_bc *allbc);
int cli_bytecode_load(struct cli_bc *bc, FILE *f, struct cli_dbio *dbio, int security, int sigperf);
int cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *allbc, unsigned dconfmask);
int cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *bc, struct cli_bc_ctx *ctx);
void cli_bytecode_destroy(struct cli_bc *bc);
int cli_bytecode_done(struct cli_all_bc *allbc);
/* Bytecode IR descriptions */
void cli_bytecode_describe(const struct cli_bc *bc);
void cli_bytetype_describe(const struct cli_bc *bc);
void cli_bytevalue_describe(const struct cli_bc *bc, unsigned funcid);
void cli_byteinst_describe(const struct cli_bc_inst *inst, unsigned *bbnum);
void cli_bytefunc_describe(const struct cli_bc *bc, unsigned funcid);
/* Hooks */
struct cli_exe_info;
struct cli_ctx_tag;
struct cli_target_info;
int cli_bytecode_runlsig(struct cli_ctx_tag *ctx, struct cli_target_info *info, const struct cli_all_bc *bcs, unsigned bc_idx, const uint32_t *lsigcnt, const uint32_t *lsigsuboff, fmap_t *map);
int cli_bytecode_runhook(struct cli_ctx_tag *cctx, const struct cl_engine *engine, struct cli_bc_ctx *ctx, unsigned id, fmap_t *map);
#ifdef __cplusplus
extern "C" {
#endif
int bytecode_init(void);
/* Bytecode internal debug API */
void cli_bytecode_debug(int argc, char **argv);
void cli_bytecode_printversion(void);
void cli_bytecode_debug_printsrc(const struct cli_bc_ctx *ctx);
void cli_printcxxver(void);
typedef void (*bc_dbg_callback_trace)(struct cli_bc_ctx *, unsigned event);
typedef void (*bc_dbg_callback_trace_op)(struct cli_bc_ctx *, const char *op);
typedef void (*bc_dbg_callback_trace_val)(struct cli_bc_ctx *, const char *name, uint32_t value);
typedef void (*bc_dbg_callback_trace_ptr)(struct cli_bc_ctx *, const void *val);
void cli_bytecode_context_set_trace(struct cli_bc_ctx *, unsigned level,
bc_dbg_callback_trace,
bc_dbg_callback_trace_op,
bc_dbg_callback_trace_val,
bc_dbg_callback_trace_ptr);
void cli_sigperf_print(void);
void cli_sigperf_events_destroy(void);
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+466
View File
@@ -0,0 +1,466 @@
/*
* ClamAV bytecode internal API
* This is an automatically generated file!
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* 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 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
*/
#include "clamav-types.h"
#include "type_desc.h"
#include "bytecode_api.h"
#include "bytecode_api_impl.h"
#include "bytecode_priv.h"
#include <stdlib.h>
uint32_t cli_bcapi_test1(struct cli_bc_ctx *ctx , uint32_t, uint32_t);
int32_t cli_bcapi_read(struct cli_bc_ctx *ctx , uint8_t*, int32_t);
int32_t cli_bcapi_write(struct cli_bc_ctx *ctx , uint8_t*, int32_t);
int32_t cli_bcapi_seek(struct cli_bc_ctx *ctx , int32_t, uint32_t);
uint32_t cli_bcapi_setvirusname(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_debug_print_str(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_debug_print_uint(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_disasm_x86(struct cli_bc_ctx *ctx , struct DISASM_RESULT*, uint32_t);
uint32_t cli_bcapi_trace_directory(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_scope(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_source(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_op(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_value(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_ptr(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_pe_rawaddr(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_file_find(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
int32_t cli_bcapi_file_byteat(struct cli_bc_ctx *ctx , uint32_t);
uint8_t* cli_bcapi_malloc(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_test2(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_get_pe_section(struct cli_bc_ctx *ctx , struct cli_exe_section*, uint32_t);
int32_t cli_bcapi_fill_buffer(struct cli_bc_ctx *ctx , uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t);
int32_t cli_bcapi_extract_new(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_read_number(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_hashset_new(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_hashset_add(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_hashset_remove(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_hashset_contains(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_hashset_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_hashset_empty(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_buffer_pipe_new(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_buffer_pipe_new_fromfile(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_buffer_pipe_read_avail(struct cli_bc_ctx *ctx , int32_t);
const uint8_t* cli_bcapi_buffer_pipe_read_get(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_buffer_pipe_read_stopped(struct cli_bc_ctx *ctx , int32_t, uint32_t);
uint32_t cli_bcapi_buffer_pipe_write_avail(struct cli_bc_ctx *ctx , int32_t);
uint8_t* cli_bcapi_buffer_pipe_write_get(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_buffer_pipe_write_stopped(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_buffer_pipe_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_inflate_init(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_inflate_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_inflate_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_bytecode_rt_error(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_jsnorm_init(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_jsnorm_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_jsnorm_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_ilog2(struct cli_bc_ctx *ctx , uint32_t, uint32_t);
int32_t cli_bcapi_ipow(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
uint32_t cli_bcapi_iexp(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_isin(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_icos(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_memstr(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, const uint8_t*, int32_t);
int32_t cli_bcapi_hex2ui(struct cli_bc_ctx *ctx , uint32_t, uint32_t);
int32_t cli_bcapi_atoi(struct cli_bc_ctx *ctx , const uint8_t*, int32_t);
uint32_t cli_bcapi_debug_print_str_start(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_debug_print_str_nonl(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_entropy_buffer(struct cli_bc_ctx *ctx , uint8_t*, int32_t);
int32_t cli_bcapi_map_new(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_map_addkey(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_setvalue(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_remove(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_find(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_getvaluesize(struct cli_bc_ctx *ctx , int32_t);
uint8_t* cli_bcapi_map_getvalue(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_map_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_file_find_limit(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t, int32_t);
uint32_t cli_bcapi_engine_functionality_level(struct cli_bc_ctx *ctx );
uint32_t cli_bcapi_engine_dconf_level(struct cli_bc_ctx *ctx );
uint32_t cli_bcapi_engine_scan_options(struct cli_bc_ctx *ctx );
uint32_t cli_bcapi_engine_db_options(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_extract_set_container(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_input_switch(struct cli_bc_ctx *ctx , int32_t);
uint32_t cli_bcapi_get_environment(struct cli_bc_ctx *ctx , struct cli_environment*, uint32_t);
uint32_t cli_bcapi_disable_bytecode_if(struct cli_bc_ctx *ctx , const int8_t*, uint32_t, uint32_t);
uint32_t cli_bcapi_disable_jit_if(struct cli_bc_ctx *ctx , const int8_t*, uint32_t, uint32_t);
int32_t cli_bcapi_version_compare(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t, const uint8_t*, uint32_t);
uint32_t cli_bcapi_check_platform(struct cli_bc_ctx *ctx , uint32_t, uint32_t, uint32_t);
int32_t cli_bcapi_pdf_get_obj_num(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_pdf_get_flags(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_pdf_set_flags(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_lookupobj(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_pdf_getobjsize(struct cli_bc_ctx *ctx , int32_t);
const uint8_t* cli_bcapi_pdf_getobj(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_pdf_getobjid(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_getobjflags(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_setobjflags(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_pdf_get_offset(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_get_phase(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_pdf_get_dumpedobjid(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_matchicon(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, const uint8_t*, int32_t);
int32_t cli_bcapi_running_on_jit(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_get_file_reliability(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_json_is_active(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_json_get_object(struct cli_bc_ctx *ctx , const int8_t*, int32_t, int32_t);
int32_t cli_bcapi_json_get_type(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_array_length(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_array_idx(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_json_get_string_length(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_string(struct cli_bc_ctx *ctx , int8_t*, int32_t, int32_t);
int32_t cli_bcapi_json_get_boolean(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_int(struct cli_bc_ctx *ctx , int32_t);
uint32_t cli_bcapi_engine_scan_options_ex(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
int32_t cli_bcapi_lzma_init(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_lzma_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_lzma_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_bzip2_init(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_bzip2_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_bzip2_done(struct cli_bc_ctx *ctx , int32_t);
const struct cli_apiglobal cli_globals[] = {
/* Bytecode globals BEGIN */
{"__clambc_match_offsets", GLOBAL_MATCH_OFFSETS, 76,
((char*)&((struct cli_bc_ctx*)0)->hooks.match_offsets - (char*)NULL)},
{"__clambc_kind", GLOBAL_KIND, 16,
((char*)&((struct cli_bc_ctx*)0)->hooks.kind - (char*)NULL)},
{"__clambc_match_counts", GLOBAL_MATCH_COUNTS, 76,
((char*)&((struct cli_bc_ctx*)0)->hooks.match_counts - (char*)NULL)},
{"__clambc_filesize", GLOBAL_FILESIZE, 75,
((char*)&((struct cli_bc_ctx*)0)->hooks.filesize - (char*)NULL)},
{"__clambc_pedata", GLOBAL_PEDATA, 69,
((char*)&((struct cli_bc_ctx*)0)->hooks.pedata - (char*)NULL)}
/* Bytecode globals END */
};
const unsigned cli_apicall_maxglobal = _LAST_GLOBAL-1;
static uint16_t cli_tmp0[]={32, 32, 16, 16, 74, 73, 70, 32, 72, 70, 70, 32, 32, 32, 32};
static uint16_t cli_tmp1[]={71};
static uint16_t cli_tmp2[]={32, 32};
static uint16_t cli_tmp3[]={16, 8, 8, 32, 32, 32, 32, 32, 64, 32, 32, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 16, 16, 64, 64, 64, 64, 32, 32};
static uint16_t cli_tmp4[]={16, 8, 8, 32, 32, 32, 32, 32, 32, 32, 32, 32, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 16, 16, 32, 32, 32, 32, 32, 32};
static uint16_t cli_tmp5[]={32, 16, 16, 32, 32, 32, 16, 16};
static uint16_t cli_tmp6[]={32};
static uint16_t cli_tmp7[]={32};
static uint16_t cli_tmp8[]={32, 32};
static uint16_t cli_tmp9[]={32, 32, 32};
static uint16_t cli_tmp10[]={32, 65, 32};
static uint16_t cli_tmp11[]={32, 65, 32, 32};
static uint16_t cli_tmp12[]={32};
static uint16_t cli_tmp13[]={32, 65, 32, 65, 32};
static uint16_t cli_tmp14[]={65, 32, 32};
static uint16_t cli_tmp15[]={32, 32, 32, 32};
static uint16_t cli_tmp16[]={32, 86, 32};
static uint16_t cli_tmp17[]={87};
static uint16_t cli_tmp18[]={32, 32, 32, 32, 32, 32, 32, 88, 88, 88, 88, 88, 88, 88, 8, 8, 8, 8, 8, 8, 8, 8, 8};
static uint16_t cli_tmp19[]={8};
static uint16_t cli_tmp20[]={32, 65, 32, 32, 32, 32};
static uint16_t cli_tmp21[]={32, 91, 32};
static uint16_t cli_tmp22[]={92};
static uint16_t cli_tmp23[]={32, 32, 32, 32, 32, 32, 32, 32, 32};
static uint16_t cli_tmp24[]={65, 32};
static uint16_t cli_tmp25[]={32, 95, 32};
static uint16_t cli_tmp26[]={96};
static uint16_t cli_tmp27[]={16, 8, 8, 8, 98, 97};
static uint16_t cli_tmp28[]={8};
static uint16_t cli_tmp29[]={99};
static uint16_t cli_tmp30[]={8};
const struct cli_bc_type cli_apicall_types[]={
{DStructType, cli_tmp0, 15, 0, 0},
{DArrayType, cli_tmp1, 16, 0, 0},
{DStructType, cli_tmp2, 2, 0, 0},
{DStructType, cli_tmp3, 29, 0, 0},
{DStructType, cli_tmp4, 30, 0, 0},
{DStructType, cli_tmp5, 8, 0, 0},
{DArrayType, cli_tmp6, 1, 0, 0},
{DArrayType, cli_tmp7, 64, 0, 0},
{DFunctionType, cli_tmp8, 2, 0, 0},
{DFunctionType, cli_tmp9, 3, 0, 0},
{DFunctionType, cli_tmp10, 3, 0, 0},
{DFunctionType, cli_tmp11, 4, 0, 0},
{DFunctionType, cli_tmp12, 1, 0, 0},
{DFunctionType, cli_tmp13, 5, 0, 0},
{DFunctionType, cli_tmp14, 3, 0, 0},
{DFunctionType, cli_tmp15, 4, 0, 0},
{DFunctionType, cli_tmp16, 3, 0, 0},
{DPointerType, cli_tmp17, 1, 0, 0},
{DStructType, cli_tmp18, 23, 0, 0},
{DArrayType, cli_tmp19, 65, 0, 0},
{DFunctionType, cli_tmp20, 6, 0, 0},
{DFunctionType, cli_tmp21, 3, 0, 0},
{DPointerType, cli_tmp22, 1, 0, 0},
{DStructType, cli_tmp23, 9, 0, 0},
{DFunctionType, cli_tmp24, 2, 0, 0},
{DFunctionType, cli_tmp25, 3, 0, 0},
{DPointerType, cli_tmp26, 1, 0, 0},
{DStructType, cli_tmp27, 6, 0, 0},
{DArrayType, cli_tmp28, 29, 0, 0},
{DArrayType, cli_tmp29, 3, 0, 0},
{DArrayType, cli_tmp30, 10, 0, 0}
};
const unsigned cli_apicall_maxtypes=sizeof(cli_apicall_types)/sizeof(cli_apicall_types[0]);
const struct cli_apicall cli_apicalls[]={
/* Bytecode APIcalls BEGIN */
{"test1", 9, 0, 0},
{"read", 10, 0, 1},
{"write", 10, 1, 1},
{"seek", 9, 1, 0},
{"setvirusname", 10, 2, 1},
{"debug_print_str", 10, 3, 1},
{"debug_print_uint", 8, 0, 2},
{"disasm_x86", 25, 4, 1},
{"trace_directory", 10, 5, 1},
{"trace_scope", 10, 6, 1},
{"trace_source", 10, 7, 1},
{"trace_op", 10, 8, 1},
{"trace_value", 10, 9, 1},
{"trace_ptr", 10, 10, 1},
{"pe_rawaddr", 8, 1, 2},
{"file_find", 10, 11, 1},
{"file_byteat", 8, 2, 2},
{"malloc", 24, 0, 3},
{"test2", 8, 3, 2},
{"get_pe_section", 21, 12, 1},
{"fill_buffer", 20, 0, 4},
{"extract_new", 8, 4, 2},
{"read_number", 8, 5, 2},
{"hashset_new", 12, 0, 5},
{"hashset_add", 9, 2, 0},
{"hashset_remove", 9, 3, 0},
{"hashset_contains", 9, 4, 0},
{"hashset_done", 8, 6, 2},
{"hashset_empty", 8, 7, 2},
{"buffer_pipe_new", 8, 8, 2},
{"buffer_pipe_new_fromfile", 8, 9, 2},
{"buffer_pipe_read_avail", 8, 10, 2},
{"buffer_pipe_read_get", 14, 0, 6},
{"buffer_pipe_read_stopped", 9, 5, 0},
{"buffer_pipe_write_avail", 8, 11, 2},
{"buffer_pipe_write_get", 14, 1, 6},
{"buffer_pipe_write_stopped", 9, 6, 0},
{"buffer_pipe_done", 8, 12, 2},
{"inflate_init", 15, 0, 7},
{"inflate_process", 8, 13, 2},
{"inflate_done", 8, 14, 2},
{"bytecode_rt_error", 8, 15, 2},
{"jsnorm_init", 8, 16, 2},
{"jsnorm_process", 8, 17, 2},
{"jsnorm_done", 8, 18, 2},
{"ilog2", 9, 7, 0},
{"ipow", 15, 1, 7},
{"iexp", 15, 2, 7},
{"isin", 15, 3, 7},
{"icos", 15, 4, 7},
{"memstr", 13, 0, 8},
{"hex2ui", 9, 8, 0},
{"atoi", 10, 13, 1},
{"debug_print_str_start", 10, 14, 1},
{"debug_print_str_nonl", 10, 15, 1},
{"entropy_buffer", 10, 16, 1},
{"map_new", 9, 9, 0},
{"map_addkey", 11, 0, 9},
{"map_setvalue", 11, 1, 9},
{"map_remove", 11, 2, 9},
{"map_find", 11, 3, 9},
{"map_getvaluesize", 8, 19, 2},
{"map_getvalue", 14, 2, 6},
{"map_done", 8, 20, 2},
{"file_find_limit", 11, 4, 9},
{"engine_functionality_level", 12, 1, 5},
{"engine_dconf_level", 12, 2, 5},
{"engine_scan_options", 12, 3, 5},
{"engine_db_options", 12, 4, 5},
{"extract_set_container", 8, 21, 2},
{"input_switch", 8, 22, 2},
{"get_environment", 16, 17, 1},
{"disable_bytecode_if", 11, 5, 9},
{"disable_jit_if", 11, 6, 9},
{"version_compare", 13, 1, 8},
{"check_platform", 15, 5, 7},
{"pdf_get_obj_num", 12, 5, 5},
{"pdf_get_flags", 12, 6, 5},
{"pdf_set_flags", 8, 23, 2},
{"pdf_lookupobj", 8, 24, 2},
{"pdf_getobjsize", 8, 25, 2},
{"pdf_getobj", 14, 3, 6},
{"pdf_getobjid", 8, 26, 2},
{"pdf_getobjflags", 8, 27, 2},
{"pdf_setobjflags", 9, 10, 0},
{"pdf_get_offset", 8, 28, 2},
{"pdf_get_phase", 12, 7, 5},
{"pdf_get_dumpedobjid", 12, 8, 5},
{"matchicon", 13, 2, 8},
{"running_on_jit", 12, 9, 5},
{"get_file_reliability", 12, 10, 5},
{"json_is_active", 12, 11, 5},
{"json_get_object", 11, 7, 9},
{"json_get_type", 8, 29, 2},
{"json_get_array_length", 8, 30, 2},
{"json_get_array_idx", 9, 11, 0},
{"json_get_string_length", 8, 31, 2},
{"json_get_string", 11, 8, 9},
{"json_get_boolean", 8, 32, 2},
{"json_get_int", 8, 33, 2},
{"engine_scan_options_ex", 10, 18, 1},
{"lzma_init", 9, 12, 0},
{"lzma_process", 8, 34, 2},
{"lzma_done", 8, 35, 2},
{"bzip2_init", 9, 13, 0},
{"bzip2_process", 8, 36, 2},
{"bzip2_done", 8, 37, 2}
/* Bytecode APIcalls END */
};
const unsigned cli_numapicalls=sizeof(cli_apicalls)/sizeof(cli_apicalls[0]);
const cli_apicall_int2 cli_apicalls0[] = {
(cli_apicall_int2)cli_bcapi_test1,
(cli_apicall_int2)cli_bcapi_seek,
(cli_apicall_int2)cli_bcapi_hashset_add,
(cli_apicall_int2)cli_bcapi_hashset_remove,
(cli_apicall_int2)cli_bcapi_hashset_contains,
(cli_apicall_int2)cli_bcapi_buffer_pipe_read_stopped,
(cli_apicall_int2)cli_bcapi_buffer_pipe_write_stopped,
(cli_apicall_int2)cli_bcapi_ilog2,
(cli_apicall_int2)cli_bcapi_hex2ui,
(cli_apicall_int2)cli_bcapi_map_new,
(cli_apicall_int2)cli_bcapi_pdf_setobjflags,
(cli_apicall_int2)cli_bcapi_json_get_array_idx,
(cli_apicall_int2)cli_bcapi_lzma_init,
(cli_apicall_int2)cli_bcapi_bzip2_init
};
const cli_apicall_pointer cli_apicalls1[] = {
(cli_apicall_pointer)cli_bcapi_read,
(cli_apicall_pointer)cli_bcapi_write,
(cli_apicall_pointer)cli_bcapi_setvirusname,
(cli_apicall_pointer)cli_bcapi_debug_print_str,
(cli_apicall_pointer)cli_bcapi_disasm_x86,
(cli_apicall_pointer)cli_bcapi_trace_directory,
(cli_apicall_pointer)cli_bcapi_trace_scope,
(cli_apicall_pointer)cli_bcapi_trace_source,
(cli_apicall_pointer)cli_bcapi_trace_op,
(cli_apicall_pointer)cli_bcapi_trace_value,
(cli_apicall_pointer)cli_bcapi_trace_ptr,
(cli_apicall_pointer)cli_bcapi_file_find,
(cli_apicall_pointer)cli_bcapi_get_pe_section,
(cli_apicall_pointer)cli_bcapi_atoi,
(cli_apicall_pointer)cli_bcapi_debug_print_str_start,
(cli_apicall_pointer)cli_bcapi_debug_print_str_nonl,
(cli_apicall_pointer)cli_bcapi_entropy_buffer,
(cli_apicall_pointer)cli_bcapi_get_environment,
(cli_apicall_pointer)cli_bcapi_engine_scan_options_ex
};
const cli_apicall_int1 cli_apicalls2[] = {
(cli_apicall_int1)cli_bcapi_debug_print_uint,
(cli_apicall_int1)cli_bcapi_pe_rawaddr,
(cli_apicall_int1)cli_bcapi_file_byteat,
(cli_apicall_int1)cli_bcapi_test2,
(cli_apicall_int1)cli_bcapi_extract_new,
(cli_apicall_int1)cli_bcapi_read_number,
(cli_apicall_int1)cli_bcapi_hashset_done,
(cli_apicall_int1)cli_bcapi_hashset_empty,
(cli_apicall_int1)cli_bcapi_buffer_pipe_new,
(cli_apicall_int1)cli_bcapi_buffer_pipe_new_fromfile,
(cli_apicall_int1)cli_bcapi_buffer_pipe_read_avail,
(cli_apicall_int1)cli_bcapi_buffer_pipe_write_avail,
(cli_apicall_int1)cli_bcapi_buffer_pipe_done,
(cli_apicall_int1)cli_bcapi_inflate_process,
(cli_apicall_int1)cli_bcapi_inflate_done,
(cli_apicall_int1)cli_bcapi_bytecode_rt_error,
(cli_apicall_int1)cli_bcapi_jsnorm_init,
(cli_apicall_int1)cli_bcapi_jsnorm_process,
(cli_apicall_int1)cli_bcapi_jsnorm_done,
(cli_apicall_int1)cli_bcapi_map_getvaluesize,
(cli_apicall_int1)cli_bcapi_map_done,
(cli_apicall_int1)cli_bcapi_extract_set_container,
(cli_apicall_int1)cli_bcapi_input_switch,
(cli_apicall_int1)cli_bcapi_pdf_set_flags,
(cli_apicall_int1)cli_bcapi_pdf_lookupobj,
(cli_apicall_int1)cli_bcapi_pdf_getobjsize,
(cli_apicall_int1)cli_bcapi_pdf_getobjid,
(cli_apicall_int1)cli_bcapi_pdf_getobjflags,
(cli_apicall_int1)cli_bcapi_pdf_get_offset,
(cli_apicall_int1)cli_bcapi_json_get_type,
(cli_apicall_int1)cli_bcapi_json_get_array_length,
(cli_apicall_int1)cli_bcapi_json_get_string_length,
(cli_apicall_int1)cli_bcapi_json_get_boolean,
(cli_apicall_int1)cli_bcapi_json_get_int,
(cli_apicall_int1)cli_bcapi_lzma_process,
(cli_apicall_int1)cli_bcapi_lzma_done,
(cli_apicall_int1)cli_bcapi_bzip2_process,
(cli_apicall_int1)cli_bcapi_bzip2_done
};
const cli_apicall_malloclike cli_apicalls3[] = {
(cli_apicall_malloclike)cli_bcapi_malloc
};
const cli_apicall_ptrbuffdata cli_apicalls4[] = {
(cli_apicall_ptrbuffdata)cli_bcapi_fill_buffer
};
const cli_apicall_allocobj cli_apicalls5[] = {
(cli_apicall_allocobj)cli_bcapi_hashset_new,
(cli_apicall_allocobj)cli_bcapi_engine_functionality_level,
(cli_apicall_allocobj)cli_bcapi_engine_dconf_level,
(cli_apicall_allocobj)cli_bcapi_engine_scan_options,
(cli_apicall_allocobj)cli_bcapi_engine_db_options,
(cli_apicall_allocobj)cli_bcapi_pdf_get_obj_num,
(cli_apicall_allocobj)cli_bcapi_pdf_get_flags,
(cli_apicall_allocobj)cli_bcapi_pdf_get_phase,
(cli_apicall_allocobj)cli_bcapi_pdf_get_dumpedobjid,
(cli_apicall_allocobj)cli_bcapi_running_on_jit,
(cli_apicall_allocobj)cli_bcapi_get_file_reliability,
(cli_apicall_allocobj)cli_bcapi_json_is_active
};
const cli_apicall_bufget cli_apicalls6[] = {
(cli_apicall_bufget)cli_bcapi_buffer_pipe_read_get,
(cli_apicall_bufget)cli_bcapi_buffer_pipe_write_get,
(cli_apicall_bufget)cli_bcapi_map_getvalue,
(cli_apicall_bufget)cli_bcapi_pdf_getobj
};
const cli_apicall_int3 cli_apicalls7[] = {
(cli_apicall_int3)cli_bcapi_inflate_init,
(cli_apicall_int3)cli_bcapi_ipow,
(cli_apicall_int3)cli_bcapi_iexp,
(cli_apicall_int3)cli_bcapi_isin,
(cli_apicall_int3)cli_bcapi_icos,
(cli_apicall_int3)cli_bcapi_check_platform
};
const cli_apicall_2bufs cli_apicalls8[] = {
(cli_apicall_2bufs)cli_bcapi_memstr,
(cli_apicall_2bufs)cli_bcapi_version_compare,
(cli_apicall_2bufs)cli_bcapi_matchicon
};
const cli_apicall_ptrbufid cli_apicalls9[] = {
(cli_apicall_ptrbufid)cli_bcapi_map_addkey,
(cli_apicall_ptrbufid)cli_bcapi_map_setvalue,
(cli_apicall_ptrbufid)cli_bcapi_map_remove,
(cli_apicall_ptrbufid)cli_bcapi_map_find,
(cli_apicall_ptrbufid)cli_bcapi_file_find_limit,
(cli_apicall_ptrbufid)cli_bcapi_disable_bytecode_if,
(cli_apicall_ptrbufid)cli_bcapi_disable_jit_if,
(cli_apicall_ptrbufid)cli_bcapi_json_get_object,
(cli_apicall_ptrbufid)cli_bcapi_json_get_string
};
const unsigned cli_apicall_maxapi = sizeof(cli_apicalls)/sizeof(cli_apicalls[0]);
+142
View File
@@ -0,0 +1,142 @@
/*
* ClamAV bytecode internal API
* This is an automatically generated file!
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* 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 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 BYTECODE_API_IMPL_H
#define BYTECODE_API_IMPL_H
struct cli_bc_bctx;
struct cli_environment;
uint32_t cli_bcapi_test1(struct cli_bc_ctx *ctx , uint32_t, uint32_t);
int32_t cli_bcapi_read(struct cli_bc_ctx *ctx , uint8_t*, int32_t);
int32_t cli_bcapi_write(struct cli_bc_ctx *ctx , uint8_t*, int32_t);
int32_t cli_bcapi_seek(struct cli_bc_ctx *ctx , int32_t, uint32_t);
uint32_t cli_bcapi_setvirusname(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_debug_print_str(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_debug_print_uint(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_disasm_x86(struct cli_bc_ctx *ctx , struct DISASM_RESULT*, uint32_t);
uint32_t cli_bcapi_trace_directory(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_scope(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_source(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_op(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_value(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_trace_ptr(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_pe_rawaddr(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_file_find(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
int32_t cli_bcapi_file_byteat(struct cli_bc_ctx *ctx , uint32_t);
uint8_t* cli_bcapi_malloc(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_test2(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_get_pe_section(struct cli_bc_ctx *ctx , struct cli_exe_section*, uint32_t);
int32_t cli_bcapi_fill_buffer(struct cli_bc_ctx *ctx , uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t);
int32_t cli_bcapi_extract_new(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_read_number(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_hashset_new(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_hashset_add(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_hashset_remove(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_hashset_contains(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_hashset_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_hashset_empty(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_buffer_pipe_new(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_buffer_pipe_new_fromfile(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_buffer_pipe_read_avail(struct cli_bc_ctx *ctx , int32_t);
const uint8_t* cli_bcapi_buffer_pipe_read_get(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_buffer_pipe_read_stopped(struct cli_bc_ctx *ctx , int32_t, uint32_t);
uint32_t cli_bcapi_buffer_pipe_write_avail(struct cli_bc_ctx *ctx , int32_t);
uint8_t* cli_bcapi_buffer_pipe_write_get(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_buffer_pipe_write_stopped(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_buffer_pipe_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_inflate_init(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_inflate_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_inflate_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_bytecode_rt_error(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_jsnorm_init(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_jsnorm_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_jsnorm_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_ilog2(struct cli_bc_ctx *ctx , uint32_t, uint32_t);
int32_t cli_bcapi_ipow(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
uint32_t cli_bcapi_iexp(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_isin(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_icos(struct cli_bc_ctx *ctx , int32_t, int32_t, int32_t);
int32_t cli_bcapi_memstr(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, const uint8_t*, int32_t);
int32_t cli_bcapi_hex2ui(struct cli_bc_ctx *ctx , uint32_t, uint32_t);
int32_t cli_bcapi_atoi(struct cli_bc_ctx *ctx , const uint8_t*, int32_t);
uint32_t cli_bcapi_debug_print_str_start(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_debug_print_str_nonl(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
uint32_t cli_bcapi_entropy_buffer(struct cli_bc_ctx *ctx , uint8_t*, int32_t);
int32_t cli_bcapi_map_new(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_map_addkey(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_setvalue(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_remove(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_find(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, int32_t);
int32_t cli_bcapi_map_getvaluesize(struct cli_bc_ctx *ctx , int32_t);
uint8_t* cli_bcapi_map_getvalue(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_map_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_file_find_limit(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t, int32_t);
uint32_t cli_bcapi_engine_functionality_level(struct cli_bc_ctx *ctx );
uint32_t cli_bcapi_engine_dconf_level(struct cli_bc_ctx *ctx );
uint32_t cli_bcapi_engine_scan_options(struct cli_bc_ctx *ctx );
uint32_t cli_bcapi_engine_db_options(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_extract_set_container(struct cli_bc_ctx *ctx , uint32_t);
int32_t cli_bcapi_input_switch(struct cli_bc_ctx *ctx , int32_t);
uint32_t cli_bcapi_get_environment(struct cli_bc_ctx *ctx , struct cli_environment*, uint32_t);
uint32_t cli_bcapi_disable_bytecode_if(struct cli_bc_ctx *ctx , const int8_t*, uint32_t, uint32_t);
uint32_t cli_bcapi_disable_jit_if(struct cli_bc_ctx *ctx , const int8_t*, uint32_t, uint32_t);
int32_t cli_bcapi_version_compare(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t, const uint8_t*, uint32_t);
uint32_t cli_bcapi_check_platform(struct cli_bc_ctx *ctx , uint32_t, uint32_t, uint32_t);
int32_t cli_bcapi_pdf_get_obj_num(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_pdf_get_flags(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_pdf_set_flags(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_lookupobj(struct cli_bc_ctx *ctx , uint32_t);
uint32_t cli_bcapi_pdf_getobjsize(struct cli_bc_ctx *ctx , int32_t);
const uint8_t* cli_bcapi_pdf_getobj(struct cli_bc_ctx *ctx , int32_t, uint32_t);
int32_t cli_bcapi_pdf_getobjid(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_getobjflags(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_setobjflags(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_pdf_get_offset(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_pdf_get_phase(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_pdf_get_dumpedobjid(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_matchicon(struct cli_bc_ctx *ctx , const uint8_t*, int32_t, const uint8_t*, int32_t);
int32_t cli_bcapi_running_on_jit(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_get_file_reliability(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_json_is_active(struct cli_bc_ctx *ctx );
int32_t cli_bcapi_json_get_object(struct cli_bc_ctx *ctx , const int8_t*, int32_t, int32_t);
int32_t cli_bcapi_json_get_type(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_array_length(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_array_idx(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_json_get_string_length(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_string(struct cli_bc_ctx *ctx , int8_t*, int32_t, int32_t);
int32_t cli_bcapi_json_get_boolean(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_json_get_int(struct cli_bc_ctx *ctx , int32_t);
uint32_t cli_bcapi_engine_scan_options_ex(struct cli_bc_ctx *ctx , const uint8_t*, uint32_t);
int32_t cli_bcapi_lzma_init(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_lzma_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_lzma_done(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_bzip2_init(struct cli_bc_ctx *ctx , int32_t, int32_t);
int32_t cli_bcapi_bzip2_process(struct cli_bc_ctx *ctx , int32_t);
int32_t cli_bcapi_bzip2_done(struct cli_bc_ctx *ctx , int32_t);
#endif
+328
View File
@@ -0,0 +1,328 @@
/*
* Detect environment for bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include "clamav.h"
#include "target.h"
#include "bytecode_detect.h"
#include "others.h"
#include <string.h>
#include <stdio.h>
#include <errno.h>
#ifdef HAVE_UNAME_SYSCALL
#include <sys/utsname.h>
#endif
#define CHECK_ARCH(a) \
if (!strcmp(TARGET_ARCH_TYPE, #a)) env->arch = arch_##a
extern int have_clamjit;
static void cli_print_environment(struct cli_environment *env)
{
uint32_t id_a = env->platform_id_a;
uint32_t id_b = env->platform_id_b;
uint32_t id_c = env->platform_id_c;
/* the bytecode instruction that exactly identifies this platform */
/* the space separated groups can be a concrete value, or 0xff for ANY */
cli_dbgmsg("environment detected:\n");
cli_dbgmsg("check_platform(0x%08x, 0x%08x, 0x%08x)\n",
id_a, id_b, id_c);
cli_dbgmsg("check_platform(0x%02x %01x %01x %02x %02x,"
"0x%01x %01x %02x %02x %02x,"
"0x%02x %02x %02x %02x)\n",
env->os_category, env->arch, env->compiler,
env->functionality_level,
env->dconf_level,
env->big_endian,
env->sizeof_ptr,
(env->cpp_version >> 16) & 0xff,
(env->cpp_version >> 8) & 0xff,
env->cpp_version & 0xff,
env->os_features,
(env->c_version >> 16) & 0xff,
(env->c_version >> 8) & 0xff,
env->c_version & 0xff);
cli_dbgmsg("check_platform( OS CPU COM FL DCONF,BE PTR CXX VV.VV.VV, FLG CC VV.VV.VV)\n");
cli_dbgmsg("Engine version: %s\n", env->engine_version);
cli_dbgmsg("Host triple: %s\n", env->triple);
cli_dbgmsg("Host CPU: %s\n", env->cpu);
cli_dbgmsg("OS: %s\n", env->sysname);
cli_dbgmsg("OS release: %s\n", env->release);
cli_dbgmsg("OS version: %s\n", env->version);
cli_dbgmsg("OS hardware: %s\n", env->machine);
cli_dbgmsg("OS LLVM category: %d\n", env->os);
cli_dbgmsg("Has JIT compiled: %d\n", env->has_jit_compiled);
cli_dbgmsg("------------------------------------------------------\n");
}
#ifdef __linux__
static int detect_PaX(void)
{
char line[128];
int pax = 0;
FILE *f = fopen("/proc/self/status", "r");
if (!f)
return 0;
while (fgets(line, sizeof(line), f)) {
if (!memcmp(line, "PaX:", 4)) {
pax = 1;
if (!strchr(line, 'm'))
pax = 2;
break;
}
}
fclose(f);
return pax;
}
static int detect_SELinux(void)
{
char line[128];
int selinux = 0;
int enforce = 0;
FILE *f = fopen("/proc/filesystems", "r");
if (!f) {
f = fopen("/selinux/enforce", "r");
if (!f && errno == EACCES)
return 2;
if (f) {
if (fscanf(f, "%d", &enforce) == 1)
selinux = 2;
fclose(f);
}
return selinux;
}
while (fgets(line, sizeof(line), f)) {
if (strstr(line, "selinuxfs\n")) {
selinux = 1;
break;
}
}
fclose(f);
if (!selinux)
return 0;
f = fopen("/selinux/enforce", "r");
if (f) {
if (fscanf(f, "%d", &enforce) == 1) {
if (enforce == 1)
selinux = 2;
if (enforce == -1)
selinux = 0;
}
fclose(f);
}
return selinux;
}
static void detect_os_features(uint8_t *os_features)
{
int features = 0;
switch (detect_PaX()) {
case 2:
features |= 1 << feature_pax_mprotect;
/* fall through */
case 1:
features |= 1 << feature_pax;
break;
default:
break;
}
switch (detect_SELinux()) {
case 2:
features |= 1 << feature_selinux_enforcing;
/* fall through */
case 1:
features |= 1 << feature_selinux;
break;
default:
break;
}
*os_features = features;
}
#else
static void detect_os_features(uint8_t *os_features)
{
*os_features = 0;
}
#endif
/* OS features :
* Linux: PaX << 2| SELinux << 1| mmap-RWX
* Other: mmap-RWX */
void cli_detect_environment(struct cli_environment *env)
{
memset(env, 0, sizeof(*env));
#if WORDS_BIGENDIAN == 0
env->big_endian = 0;
#else
env->big_endian = 1;
#endif
env->sizeof_ptr = sizeof(void *);
/* -- Detect arch -- */
CHECK_ARCH(i386);
else CHECK_ARCH(x86_64);
else if (!strcmp(TARGET_ARCH_TYPE, "amd64")) env->arch = arch_x86_64;
else if (!strcmp(TARGET_ARCH_TYPE, "ppc")) env->arch = arch_ppc32; /* llvm will fix ppc64 */
else CHECK_ARCH(arm);
else CHECK_ARCH(sparc);
else CHECK_ARCH(sparc64);
else CHECK_ARCH(mips);
else CHECK_ARCH(mips64);
else CHECK_ARCH(alpha);
else CHECK_ARCH(hppa1);
else CHECK_ARCH(hppa2);
else CHECK_ARCH(m68k);
else env->arch = arch_unknown;
/* -- Detect OS -- */
#ifdef C_AIX
env->os_category = os_aix;
#elif defined(C_BEOS)
env->os_category = os_beos;
/* DARWIN must come before BSD since it defines both */
#elif defined(C_DARWIN)
env->os_category = os_darwin;
#elif defined(C_BSD)
env->os_category = os_bsd;
#elif defined(C_GNU_HURD)
env->os_category = os_gnu_hurd;
#elif defined(C_HPUX)
env->os_category = os_hpux;
#elif defined(C_INTERIX)
env->os_category = os_interix;
#elif defined(C_IRIX)
env->os_category = os_irix;
#elif defined(C_KFREEBSD_GNU)
env->os_category = os_kfreebsd_gnu;
#elif defined(C_LINUX)
env->os_category = os_linux;
#elif defined(C_OS2)
env->os_category = os_os2;
#elif defined(C_OSF)
env->os_category = os_osf;
#elif defined(C_QNX6)
env->os_category = os_qnx6;
#elif defined(C_SOLARIS)
env->os_category = os_solaris;
#elif defined(_WIN64)
env->os_category = os_win64;
#elif defined(_WIN32)
env->os_category = os_win32;
#else
env->os_category = os_generic;
#endif
env->os = llvm_os_UnknownOS;
/* -- Detect compiler -- */
/* check GNUC last, because some other compilers might define it */
#ifdef __INTEL_COMPILER
env->compiler = compiler_intel;
env->c_version = __INTEL_COMPILER;
#elif defined(_MSC_VER)
env->compiler = compiler_msc;
env->c_version = _MSC_VER;
#elif defined(__SUNPRO_C)
env->compiler = compiler_sun;
env->c_version = __SUNPRO_C;
#elif defined(__GNUC__)
#ifdef __clang__
env->compiler = compiler_clang;
#elif defined(__llvm__)
env->compiler = compiler_llvm;
#else
env->compiler = compiler_gnuc;
#endif
env->c_version =
MAKE_VERSION(0, __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#else
env->compiler = compiler_other;
env->c_version = 0;
#endif
env->cpp_version = 0;
env->has_jit_compiled = have_clamjit;
/* engine */
env->functionality_level = cl_retflevel();
env->dconf_level = CL_FLEVEL_DCONF;
INIT_STRFIELD(env->engine_version, cl_retver());
#ifdef HAVE_UNAME_SYSCALL
{
struct utsname name;
if (uname(&name) == 0) {
INIT_STRFIELD(env->sysname, name.sysname);
INIT_STRFIELD(env->release, name.release);
INIT_STRFIELD(env->version, name.version);
INIT_STRFIELD(env->machine, name.machine);
}
}
#endif
#ifdef _WIN32
{
OSVERSIONINFOEX info;
info.dwOSVersionInfoSize = sizeof(info);
if (GetVersionEx((OSVERSIONINFO *)&info) != 0 && info.dwPlatformId == VER_PLATFORM_WIN32_NT) {
if (info.wProductType == VER_NT_WORKSTATION)
INIT_STRFIELD(env->sysname, "Microsoft Windows");
else
INIT_STRFIELD(env->sysname, "Microsoft Windows Server");
snprintf((char *)env->release, sizeof(env->release), "%d.%d SP%d.%d",
info.dwMajorVersion, info.dwMinorVersion,
info.wServicePackMajor, info.wServicePackMinor);
snprintf((char *)env->version, sizeof(env->version), "Build %d",
info.dwBuildNumber);
}
}
#endif
if (!env->sysname[0]) {
INIT_STRFIELD(env->sysname, TARGET_OS_TYPE);
}
detect_os_features(&env->os_features);
cli_detect_env_jit(env);
env->platform_id_a = (env->os_category << 24) | (env->arch << 20) |
(env->compiler << 16) | (env->functionality_level << 8) |
(env->dconf_level);
env->platform_id_b = (env->big_endian << 28) | (env->sizeof_ptr << 24) |
env->cpp_version;
env->platform_id_c = (env->os_features << 24) | env->c_version;
cli_print_environment(env);
}
+159
View File
@@ -0,0 +1,159 @@
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* 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 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 BYTECODE_DETECT_H
#define BYTECODE_DETECT_H
/* mostly from m4/acinclude.m4 */
enum arch_list {
arch_unknown = 0,
arch_i386,
arch_x86_64,
arch_ppc32,
arch_ppc64,
arch_arm,
arch_sparc,
arch_sparc64,
arch_mips,
arch_mips64,
arch_alpha,
arch_hppa1,
arch_hppa2,
arch_m68k,
arch_ANY = 0xf
};
/* from ClamAV's configure.in */
enum os_kind_conf {
os_unknown = 0,
os_aix,
os_beos,
os_bsd,
os_darwin,
os_gnu_hurd,
os_hpux,
os_interix,
os_irix,
os_kfreebsd_gnu,
os_linux,
os_os2,
os_osf,
os_qnx6,
os_solaris,
os_win32,
os_win64,
os_generic,
os_ANY = 0xff
};
enum os_kind_llvm {
llvm_os_UnknownOS = 0,
llvm_os_AuroraUX,
llvm_os_Cygwin,
llvm_os_Darwin,
llvm_os_DragonFly,
llvm_os_FreeBSD,
llvm_os_Linux,
llvm_os_Lv2,
llvm_os_MinGW32,
llvm_os_MinGW64,
llvm_os_NetBSD,
llvm_os_OpenBSD,
llvm_os_Psp,
llvm_os_Solaris,
llvm_os_Win32,
llvm_os_Haiku,
llvm_os_Minix,
llvm_os_ANY = 0xff
};
/* the ones from clamconf */
enum compiler_list {
compiler_unknown = 0,
compiler_gnuc,
compiler_llvm,
compiler_clang,
compiler_intel,
compiler_msc,
compiler_sun,
compiler_other,
compiler_ANY = 0xf
};
enum endian_list {
endian_little = 0,
endian_big = 1,
endian_ANY = 0xf
};
enum os_feature_bits {
feature_map_rwx = 0,
feature_selinux = 1,
feature_selinux_enforcing = 2,
feature_pax = 3,
feature_pax_mprotect = 4
};
struct cli_environment {
uint32_t platform_id_a;
uint32_t platform_id_b;
uint32_t platform_id_c;
uint32_t c_version;
uint32_t cpp_version; /* LLVM only */
/* engine */
uint32_t functionality_level;
uint32_t dconf_level;
int8_t engine_version[65];
/* detailed runtime info */
int8_t triple[65]; /* LLVM only */
int8_t cpu[65]; /* LLVM only */
/* uname */
int8_t sysname[65];
int8_t release[65];
int8_t version[65];
int8_t machine[65];
/* build time */
uint8_t big_endian;
uint8_t sizeof_ptr;
uint8_t arch;
uint8_t os_category; /* from configure */
uint8_t os; /* from LLVM if available */
uint8_t compiler;
uint8_t has_jit_compiled;
uint8_t os_features;
uint8_t reserved0;
};
#ifndef __CLAMBC__
#define MAKE_VERSION(a, b, c, d) ((a << 24) | (b << 16) | (c << 8) | d)
#define INIT_STRFIELD(field, value) \
do { \
strncpy((char *)(field), (value), sizeof(field) - 1); \
(field)[sizeof(field) - 1] = 0; \
} while (0)
#endif
void cli_detect_env_jit(struct cli_environment *env);
void cli_detect_environment(struct cli_environment *env);
#endif
+39
View File
@@ -0,0 +1,39 @@
/*
* ClamAV bytecode internal API
* This is an automatically generated file!
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* 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 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 BYTECODE_HOOKS_H
#define BYTECODE_HOOKS_H
struct cli_bc_hooks {
const uint32_t* match_offsets;
const uint16_t* kind;
const uint32_t* match_counts;
const uint32_t* filesize;
const struct cli_pe_hook_data* pedata;
};
#endif
+100
View File
@@ -0,0 +1,100 @@
/*
* Load, and verify ClamAV bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include "bytecode.h"
#include "bytecode_priv.h"
#include "clamav.h"
#include "others.h"
int cli_bytecode_prepare_jit(struct cli_all_bc *bcs)
{
unsigned i;
for (i = 0; i < bcs->count; i++) {
if (bcs->all_bcs[i].state == bc_skip)
continue;
if (bcs->all_bcs[i].state != bc_loaded &&
bcs->all_bcs[i].kind != BC_STARTUP) {
cli_warnmsg("Cannot prepare for JIT, because it has already been converted to interpreter\n");
return CL_EBYTECODE;
}
}
cli_dbgmsg("Cannot prepare for JIT, LLVM is not compiled or not linked\n");
return CL_EBYTECODE;
}
int cli_vm_execute_jit(const struct cli_all_bc *bcs, struct cli_bc_ctx *ctx, const struct cli_bc_func *func)
{
UNUSEDPARAM(bcs);
UNUSEDPARAM(ctx);
UNUSEDPARAM(func);
return CL_EBYTECODE;
}
int cli_bytecode_init_jit(struct cli_all_bc *allbc, unsigned dconfmask)
{
UNUSEDPARAM(allbc);
UNUSEDPARAM(dconfmask);
return CL_SUCCESS;
}
int cli_bytecode_done_jit(struct cli_all_bc *allbc, int partial)
{
UNUSEDPARAM(allbc);
UNUSEDPARAM(partial);
return CL_SUCCESS;
}
void cli_bytecode_debug(int argc, char **argv)
{
/* Empty */
UNUSEDPARAM(argc);
UNUSEDPARAM(argv);
}
int bytecode_init(void)
{
return 0;
}
void cli_bytecode_debug_printsrc(const struct cli_bc_ctx *ctx)
{
/* Empty */
UNUSEDPARAM(ctx);
}
void cli_bytecode_printversion(void)
{
printf("LLVM is not compiled or not linked\n");
}
int have_clamjit = 0;
void cli_printcxxver()
{
/* Empty */
}
void cli_detect_env_jit(struct cli_environment *env)
{
/* Empty */
UNUSEDPARAM(env);
}
+259
View File
@@ -0,0 +1,259 @@
/*
* Load, verify and execute ClamAV bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifndef BYTECODE_PRIV_H
#define BYTECODE_PRIV_H
#include <zlib.h>
#include "bytecode.h"
#include "type_desc.h"
#include "execs.h"
#include "bytecode_hooks.h"
#include "fmap.h"
#include "mpool.h"
#include "hashtab.h"
#include "events.h"
typedef uint32_t operand_t;
typedef uint16_t bbid_t;
typedef uint16_t funcid_t;
struct cli_bc_callop {
operand_t *ops;
uint16_t *opsizes;
funcid_t funcid;
uint8_t numOps;
};
struct branch {
operand_t condition;
bbid_t br_true;
bbid_t br_false;
};
struct cli_bc_cast {
uint64_t mask;
operand_t source;
uint8_t size; /* 0: 1-bit, 1: 8b, 2: 16b, 3: 32b, 4: 64b */
};
typedef uint8_t interp_op_t;
struct cli_bc_inst {
enum bc_opcode opcode;
uint16_t type;
operand_t dest;
interp_op_t interp_op; /* opcode for interpreter */
union {
operand_t unaryop;
struct cli_bc_cast cast;
operand_t binop[2];
operand_t three[3];
struct cli_bc_callop ops;
struct branch branch;
bbid_t jump;
} u;
};
struct cli_bc_bb {
unsigned numInsts;
struct cli_bc_inst *insts;
};
struct cli_bc_func {
uint8_t numArgs;
uint16_t numLocals;
uint32_t numInsts;
uint32_t numValues; /* without constants */
uint32_t numConstants;
uint32_t numBytes; /* stack size */
uint16_t numBB;
uint16_t returnType;
uint16_t *types;
uint32_t insn_idx;
struct cli_bc_bb *BB;
struct cli_bc_inst *allinsts;
uint64_t *constants;
unsigned *dbgnodes;
};
struct cli_bc_dbgnode_element {
unsigned nodeid;
unsigned len;
char *string;
uint64_t constant;
};
struct cli_bc_dbgnode {
unsigned numelements;
struct cli_bc_dbgnode_element *elements;
};
#define MAX_OP ~0u
enum trace_level {
trace_none = 0,
trace_func,
trace_param,
trace_scope,
trace_line,
trace_col,
trace_op,
trace_val
};
struct bc_buffer {
unsigned char *data;
unsigned size;
unsigned write_cursor;
unsigned read_cursor;
};
struct bc_inflate {
z_stream stream;
int32_t from;
int32_t to;
int8_t needSync;
};
struct bc_jsnorm {
struct parser_state *state;
int32_t from;
};
enum bc_events {
BCEV_VIRUSNAME,
BCEV_EXEC_RETURNVALUE,
BCEV_WRITE,
BCEV_OFFSET,
BCEV_READ,
BCEV_DBG_STR,
BCEV_DBG_INT,
BCEV_MEM_1,
BCEV_MEM_2,
BCEV_FIND,
BCEV_EXTRACTED,
BCEV_EXEC_TIME,
/* API failures (that are not serious), count must be 0 for testmode */
BCEV_API_WARN_BEGIN,
BCEV_READ_ERR,
BCEV_DISASM_FAIL,
BCEV_API_WARN_END,
/* real errors (write failure) are reported via cli_event_error_str */
BCEV_LASTEVENT
};
struct cli_bc_ctx {
uint8_t timeout; /* must be first byte in struct! */
uint16_t funcid;
unsigned numParams;
/* id and params of toplevel function called */
const struct cli_bc *bc;
const struct cli_bc_func *func;
uint32_t bytecode_timeout;
unsigned bytes;
uint16_t *opsizes;
char *values;
operand_t *operands;
uint32_t file_size;
int outfd;
off_t off;
fmap_t *fmap;
fmap_t *save_map;
const char *virname;
struct cli_bc_hooks hooks;
struct cli_exe_info exeinfo;
uint32_t lsigcnt[64];
uint32_t lsigoff[64];
uint32_t pdf_nobjs;
struct pdf_obj **pdf_objs;
uint32_t *pdf_flags;
uint32_t pdf_size;
uint32_t pdf_startoff;
unsigned pdf_phase;
int32_t pdf_dumpedid;
const struct cli_exe_section *sections;
uint32_t resaddr;
char *tempfile;
void *ctx;
unsigned written;
unsigned filewritten;
unsigned found;
unsigned ninflates;
unsigned nlzmas;
#if HAVE_BZLIB_H
unsigned nbzip2s;
#endif
bc_dbg_callback_trace trace;
bc_dbg_callback_trace_op trace_op;
bc_dbg_callback_trace_val trace_val;
bc_dbg_callback_trace_ptr trace_ptr;
const char *directory;
const char *file;
const char *scope;
unsigned trace_level;
uint32_t scopeid;
unsigned line;
unsigned col;
mpool_t *mpool;
struct bc_inflate *inflates;
struct bc_lzma *lzmas;
#if HAVE_BZLIB_H
struct bc_bzip2 *bzip2s;
#endif
struct bc_buffer *buffers;
unsigned nbuffers;
unsigned nhashsets;
unsigned njsnorms;
unsigned jsnormwritten;
struct cli_hashset *hashsets;
struct bc_jsnorm *jsnorms;
char *jsnormdir;
struct cli_map *maps;
unsigned nmaps;
unsigned containertype;
unsigned extracted_file_input;
const struct cli_environment *env;
unsigned bytecode_disable_status;
cli_events_t *bc_events;
int on_jit;
int no_diff;
#if HAVE_JSON
void **jsonobjs;
unsigned njsonobjs;
#endif
};
struct cli_all_bc;
int cli_vm_execute(const struct cli_bc *bc, struct cli_bc_ctx *ctx, const struct cli_bc_func *func, const struct cli_bc_inst *inst);
#ifdef __cplusplus
extern "C" {
#endif
int cli_vm_execute_jit(const struct cli_all_bc *bcs, struct cli_bc_ctx *ctx, const struct cli_bc_func *func);
int cli_bytecode_prepare_jit(struct cli_all_bc *bc);
int cli_bytecode_init_jit(struct cli_all_bc *bc, unsigned dconfmask);
int cli_bytecode_done_jit(struct cli_all_bc *bc, int partial);
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
/*
* Compile LLVM bytecode to ClamAV bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2010-2013 Sourcefire, Inc.
*
* Authors: Török Edvin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
namespace llvm
{
class Value;
}
// match the prototype used in the bytecode compiler
void printValue(llvm::Value *V, bool a = false, bool b = false);
void printLocation(llvm::Instruction *I, bool a = false, bool b = false);
+10
View File
@@ -0,0 +1,10 @@
#include "llvm/Support/raw_ostream.h"
namespace llvm {
class Function;
class Instruction;
class Pass;
}
namespace ClamBCModule {
void stop(const char *msg, llvm::Function* F, llvm::Instruction* I=0);
}
llvm::Pass *createClamBCRTChecks();
+971
View File
@@ -0,0 +1,971 @@
/*
* Compile LLVM bytecode to ClamAV bytecode.
*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Török Edvin, Kevin Lin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#define DEBUG_TYPE "clambc-rtcheck"
#include "ClamBCModule.h"
#include "ClamBCDiagnostics.h"
#include "llvm30_compat.h" /* libclamav-specific */
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/Analysis/CallGraph.h"
#if LLVM_VERSION < 32
#include "llvm/Analysis/DebugInfo.h"
#elif LLVM_VERSION < 35
#include "llvm/DebugInfo.h"
#else
#include "llvm/IR/DebugInfo.h"
#endif
#if LLVM_VERSION < 35
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/Verifier.h"
#else
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Verifier.h"
#endif
#include "llvm/Analysis/ConstantFolding.h"
#if LLVM_VERSION < 29
//#include "llvm/Analysis/LiveValues.h" (unused)
#include "llvm/Analysis/PointerTracking.h"
#else
#include "llvm/Analysis/ValueTracking.h"
#include "PointerTracking.h" /* included from old LLVM source */
#endif
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/ScalarEvolutionExpander.h"
#include "llvm/Config/config.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#if LLVM_VERSION < 35
#include "llvm/Support/DataFlow.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#else
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#endif
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Support/Debug.h"
#if LLVM_VERSION < 32
#include "llvm/Target/TargetData.h"
#elif LLVM_VERSION < 33
#include "llvm/DataLayout.h"
#else
#include "llvm/IR/DataLayout.h"
#endif
#if LLVM_VERSION < 33
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Intrinsics.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#else
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#endif
#if LLVM_VERSION < 33
#include "llvm/Support/InstVisitor.h"
#elif LLVM_VERSION < 35
#include "llvm/InstVisitor.h"
#else
#include "llvm/IR/InstVisitor.h"
#endif
#define DEFINEPASS(passname) passname() : FunctionPass(ID)
using namespace llvm;
#if LLVM_VERSION < 29
/* function is succeeded in later LLVM with LLVM corresponding standalone */
static Value *GetUnderlyingObject(Value *P, TargetData *TD)
{
return P->getUnderlyingObject();
}
#endif
namespace llvm {
class PtrVerifier;
#if LLVM_VERSION >= 29
void initializePtrVerifierPass(PassRegistry&);
#endif
class PtrVerifier : public FunctionPass {
private:
DenseSet<Function*> badFunctions;
std::vector<Instruction*> delInst;
#if LLVM_VERSION < 35
CallGraphNode *rootNode;
#else
CallGraph *CG;
#endif
public:
static char ID;
#if LLVM_VERSION < 35
DEFINEPASS(PtrVerifier), rootNode(0), PT(), TD(), SE(), expander(),
#else
DEFINEPASS(PtrVerifier), CG(0), PT(), TD(), SE(), expander(),
#endif
DT(), AbrtBB(), Changed(false), valid(false), EP() {
#if LLVM_VERSION >= 29
initializePtrVerifierPass(*PassRegistry::getPassRegistry());
#endif
}
virtual bool runOnFunction(Function &F) {
/*
#ifndef CLAMBC_COMPILER
// Bytecode was already verified and had stack protector applied.
// We get called again because ALL bytecode functions loaded are part of
// the same module.
if (F.hasFnAttr(Attribute::StackProtectReq))
return false;
#endif
*/
DEBUG(errs() << "Running on " << F.getName() << "\n");
DEBUG(F.dump());
Changed = false;
BaseMap.clear();
BoundsMap.clear();
delInst.clear();
AbrtBB = 0;
valid = true;
#if LLVM_VERSION < 35
if (!rootNode) {
rootNode = getAnalysis<CallGraph>().getRoot();
#else
if (!CG) {
CG = &getAnalysis<CallGraphWrapperPass>().getCallGraph();
#endif
// No recursive functions for now.
// In the future we may insert runtime checks for stack depth.
#if LLVM_VERSION < 35
for (scc_iterator<CallGraphNode*> SCCI = scc_begin(rootNode),
E = scc_end(rootNode); SCCI != E; ++SCCI) {
#else
for (scc_iterator<CallGraph*> SCCI = scc_begin(CG); !SCCI.isAtEnd(); ++SCCI) {
#endif
const std::vector<CallGraphNode*> &nextSCC = *SCCI;
if (nextSCC.size() > 1 || SCCI.hasLoop()) {
errs() << "INVALID: Recursion detected, callgraph SCC components: ";
for (std::vector<CallGraphNode*>::const_iterator I = nextSCC.begin(),
E = nextSCC.end(); I != E; ++I) {
Function *FF = (*I)->getFunction();
if (FF) {
errs() << FF->getName() << ", ";
badFunctions.insert(FF);
}
}
if (SCCI.hasLoop())
errs() << "(self-loop)";
errs() << "\n";
}
// we could also have recursion via function pointers, but we don't
// allow calls to unknown functions, see runOnFunction() below
}
}
BasicBlock::iterator It = F.getEntryBlock().begin();
while (isa<AllocaInst>(It) || isa<PHINode>(It)) ++It;
EP = &*It;
#if LLVM_VERSION < 32
TD = &getAnalysis<TargetData>();
#elif LLVM_VERSION < 35
TD = &getAnalysis<DataLayout>();
#else
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
TD = DLP ? &DLP->getDataLayout() : 0;
#endif
SE = &getAnalysis<ScalarEvolution>();
PT = &getAnalysis<PointerTracking>();
#if LLVM_VERSION < 35
DT = &getAnalysis<DominatorTree>();
#else
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
#endif
expander = new SCEVExpander(*SE OPT("SCEVexpander"));
std::vector<Instruction*> insns;
BasicBlock *LastBB = 0;
for (inst_iterator I=inst_begin(F),E=inst_end(F); I != E;++I) {
Instruction *II = &*I;
/* only appears in the libclamav version */
if (II->getParent() != LastBB) {
LastBB = II->getParent();
if (DT->getNode(LastBB) == 0)
continue;
}
/* end-block */
if (isa<LoadInst>(II) || isa<StoreInst>(II) || isa<MemIntrinsic>(II))
insns.push_back(II);
else if (CallInst *CI = dyn_cast<CallInst>(II)) {
Value *V = CI->getCalledValue()->stripPointerCasts();
Function *F = dyn_cast<Function>(V);
if (!F) {
printLocation(CI, true);
errs() << "Could not determine call target\n";
valid = 0;
continue;
}
// this statement disable checks on user-defined CallInst
//if (!F->isDeclaration())
//continue;
insns.push_back(CI);
}
}
for (unsigned Idx = 0; Idx < insns.size(); ++Idx) {
Instruction *II = insns[Idx];
DEBUG(dbgs() << "checking " << *II << "\n");
if (LoadInst *LI = dyn_cast<LoadInst>(II)) {
constType *Ty = LI->getType();
valid &= validateAccess(LI->getPointerOperand(),
TD->getTypeAllocSize(Ty), LI);
} else if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
constType *Ty = SI->getOperand(0)->getType();
valid &= validateAccess(SI->getPointerOperand(),
TD->getTypeAllocSize(Ty), SI);
} else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
valid &= validateAccess(MI->getDest(), MI->getLength(), MI);
if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
valid &= validateAccess(MTI->getSource(), MI->getLength(), MI);
}
} else if (CallInst *CI = dyn_cast<CallInst>(II)) {
Value *V = CI->getCalledValue()->stripPointerCasts();
Function *F = cast<Function>(V);
constFunctionType *FTy = F->getFunctionType();
CallSite CS(CI);
if (F->getName().equals("memcmp") && FTy->getNumParams() == 3) {
valid &= validateAccess(CS.getArgument(0), CS.getArgument(2), CI);
valid &= validateAccess(CS.getArgument(1), CS.getArgument(2), CI);
continue;
}
unsigned i;
#ifdef CLAMBC_COMPILER
i = 0;
#else
i = 1;// skip hidden ctx*
#endif
for (;i<FTy->getNumParams();i++) {
if (isa<PointerType>(FTy->getParamType(i))) {
Value *Ptr = CS.getArgument(i);
if (i+1 >= FTy->getNumParams()) {
printLocation(CI, false);
errs() << "Call to external function with pointer parameter last"
" cannot be analyzed\n";
errs() << *CI << "\n";
valid = 0;
break;
}
Value *Size = CS.getArgument(i+1);
if (!Size->getType()->isIntegerTy()) {
printLocation(CI, false);
errs() << "Pointer argument must be followed by integer argument"
" representing its size\n";
errs() << *CI << "\n";
valid = 0;
break;
}
valid &= validateAccess(Ptr, Size, CI);
}
}
}
}
if (badFunctions.count(&F))
valid = 0;
if (!valid) {
DEBUG(F.dump());
ClamBCModule::stop("Verification found errors!", &F);
// replace function with call to abort
std::vector<constType*>args;
FunctionType* abrtTy = FunctionType::get(Type::getVoidTy(F.getContext()),args,false);
Constant *func_abort = F.getParent()->getOrInsertFunction("abort", abrtTy);
BasicBlock *BB = &F.getEntryBlock();
Instruction *I = &*BB->begin();
Instruction *UI = new UnreachableInst(F.getContext(), I);
CallInst *AbrtC = CallInst::Create(func_abort, "", UI);
AbrtC->setCallingConv(CallingConv::C);
AbrtC->setTailCall(true);
#if LLVM_VERSION < 32
AbrtC->setDoesNotReturn(true);
AbrtC->setDoesNotThrow(true);
#else
AbrtC->setDoesNotReturn();
AbrtC->setDoesNotThrow();
#endif
// remove all instructions from entry
BasicBlock::iterator BBI = I, BBE=BB->end();
while (BBI != BBE) {
if (!BBI->use_empty())
BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
BB->getInstList().erase(BBI++);
}
}
// bb#9967 - deleting obsolete termination instructions
for (unsigned i = 0; i < delInst.size(); ++i)
delInst[i]->eraseFromParent();
delete expander;
return Changed;
}
virtual void releaseMemory() {
badFunctions.clear();
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
#if LLVM_VERSION < 32
AU.addRequired<TargetData>();
#elif LLVM_VERSION < 35
AU.addRequired<DataLayout>();
#else
AU.addRequired<DataLayoutPass>();
#endif
#if LLVM_VERSION < 35
AU.addRequired<DominatorTree>();
#else
AU.addRequired<DominatorTreeWrapperPass>();
#endif
AU.addRequired<ScalarEvolution>();
AU.addRequired<PointerTracking>();
#if LLVM_VERSION < 35
AU.addRequired<CallGraph>();
#else
AU.addRequired<CallGraphWrapperPass>();
#endif
}
bool isValid() const { return valid; }
private:
PointerTracking *PT;
#if LLVM_VERSION < 32
TargetData *TD;
#elif LLVM_VERSION < 35
DataLayout *TD;
#else
const DataLayout *TD;
#endif
ScalarEvolution *SE;
SCEVExpander *expander;
DominatorTree *DT;
DenseMap<Value*, Value*> BaseMap;
DenseMap<Value*, Value*> BoundsMap;
BasicBlock *AbrtBB;
bool Changed;
bool valid;
Instruction *EP;
Instruction *getInsertPoint(Value *V)
{
BasicBlock::iterator It = EP;
if (Instruction *I = dyn_cast<Instruction>(V)) {
It = I;
++It;
}
return &*It;
}
Value *getPointerBase(Value *Ptr)
{
if (BaseMap.count(Ptr))
return BaseMap[Ptr];
Value *P = Ptr->stripPointerCasts();
if (BaseMap.count(P)) {
return BaseMap[Ptr] = BaseMap[P];
}
Value *P2 = GetUnderlyingObject(P, TD);
if (P2 != P) {
Value *V = getPointerBase(P2);
return BaseMap[Ptr] = V;
}
constType *P8Ty =
PointerType::getUnqual(Type::getInt8Ty(Ptr->getContext()));
if (PHINode *PN = dyn_cast<PHINode>(Ptr)) {
BasicBlock::iterator It = PN;
++It;
PHINode *newPN = PHINode::Create(P8Ty, HINT(PN->getNumIncomingValues()) ".verif.base", &*It);
Changed = true;
BaseMap[Ptr] = newPN;
for (unsigned i=0;i<PN->getNumIncomingValues();i++) {
Value *Inc = PN->getIncomingValue(i);
Value *V = getPointerBase(Inc);
newPN->addIncoming(V, PN->getIncomingBlock(i));
}
return newPN;
}
if (SelectInst *SI = dyn_cast<SelectInst>(Ptr)) {
BasicBlock::iterator It = SI;
++It;
Value *TrueB = getPointerBase(SI->getTrueValue());
Value *FalseB = getPointerBase(SI->getFalseValue());
if (TrueB && FalseB) {
SelectInst *NewSI = SelectInst::Create(SI->getCondition(), TrueB,
FalseB, ".select.base", &*It);
Changed = true;
return BaseMap[Ptr] = NewSI;
}
}
if (Ptr->getType() != P8Ty) {
if (Constant *C = dyn_cast<Constant>(Ptr))
Ptr = ConstantExpr::getPointerCast(C, P8Ty);
else {
Instruction *I = getInsertPoint(Ptr);
Ptr = new BitCastInst(Ptr, P8Ty, "", I);
}
}
return BaseMap[Ptr] = Ptr;
}
Value* getValAtIdx(Function *F, unsigned Idx) {
Value *Val= NULL;
// check if accessed Idx is within function parameter list
if (Idx < F->arg_size()) {
Function::arg_iterator It = F->arg_begin();
Function::arg_iterator ItEnd = F->arg_end();
for (unsigned i = 0; i < Idx; ++i, ++It) {
// redundant check, should not be possible
if (It == ItEnd) {
// Houston, the impossible has become possible
//printDiagnostic("Idx is outside of Function parameters", F);
errs() << "Idx is outside of Function parameters\n";
errs() << *F << "\n";
//valid = 0;
break;
}
}
// retrieve value ptr of argument of F at Idx
Val = &(*It);
}
else {
// Idx is outside function parameter list
//printDiagnostic("Idx is outside of Function parameters", F);
errs() << "Idx is outside of Function parameters\n";
errs() << *F << "\n";
//valid = 0;
}
return Val;
}
Value* getPointerBounds(Value *Base) {
if (BoundsMap.count(Base))
return BoundsMap[Base];
constType *I64Ty =
Type::getInt64Ty(Base->getContext());
#ifndef CLAMBC_COMPILER
// first arg is hidden ctx
if (Argument *A = dyn_cast<Argument>(Base)) {
if (A->getArgNo() == 0) {
constType *Ty = cast<PointerType>(A->getType())->getElementType();
return ConstantInt::get(I64Ty, TD->getTypeAllocSize(Ty));
} else if (Base->getType()->isPointerTy()) {
Function *F = A->getParent();
const FunctionType *FT = F->getFunctionType();
bool checks = true;
// last argument check
if (A->getArgNo() == (FT->getNumParams()-1)) {
//printDiagnostic("pointer argument cannot be last argument", F);
errs() << "pointer argument cannot be last argument\n";
errs() << *F << "\n";
checks = false;
}
// argument after pointer MUST be a integer (unsigned probably too)
if (checks && !FT->getParamType(A->getArgNo()+1)->isIntegerTy()) {
//printDiagnostic("argument following pointer argument is not an integer", F);
errs() << "argument following pointer argument is not an integer\n";
errs() << *F << "\n";
checks = false;
}
if (checks)
return BoundsMap[Base] = getValAtIdx(F, A->getArgNo()+1);
}
}
if (LoadInst *LI = dyn_cast<LoadInst>(Base)) {
Value *V = GetUnderlyingObject(LI->getPointerOperand()->stripPointerCasts(), TD);
if (Argument *A = dyn_cast<Argument>(V)) {
if (A->getArgNo() == 0) {
// pointers from hidden ctx are trusted to be at least the
// size they say they are
constType *Ty = cast<PointerType>(LI->getType())->getElementType();
return ConstantInt::get(I64Ty, TD->getTypeAllocSize(Ty));
}
}
}
#else
if (Base->getType()->isPointerTy()) {
if (Argument *A = dyn_cast<Argument>(Base)) {
Function *F = A->getParent();
const FunctionType *FT = F->getFunctionType();
bool checks = true;
// last argument check
if (A->getArgNo() == (FT->getNumParams()-1)) {
//printDiagnostic("pointer argument cannot be last argument", F);
errs() << "pointer argument cannot be last argument\n";
errs() << *F << "\n";
checks = false;
}
// argument after pointer MUST be a integer (unsigned probably too)
if (checks && !FT->getParamType(A->getArgNo()+1)->isIntegerTy()) {
//printDiagnostic("argument following pointer argument is not an integer", F);
errs() << "argument following pointer argument is not an integer\n";
errs() << *F << "\n";
checks = false;
}
if (checks)
return BoundsMap[Base] = getValAtIdx(F, A->getArgNo()+1);
}
}
#endif
if (PHINode *PN = dyn_cast<PHINode>(Base)) {
BasicBlock::iterator It = PN;
++It;
PHINode *newPN = PHINode::Create(I64Ty, HINT(PN->getNumIncomingValues()) ".verif.bounds", &*It);
Changed = true;
BoundsMap[Base] = newPN;
bool good = true;
for (unsigned i=0;i<PN->getNumIncomingValues();i++) {
Value *Inc = PN->getIncomingValue(i);
Value *B = getPointerBounds(Inc);
if (!B) {
good = false;
B = ConstantInt::get(newPN->getType(), 0);
DEBUG(dbgs() << "bounds not found while solving phi node: " << *Inc
<< "\n");
}
newPN->addIncoming(B, PN->getIncomingBlock(i));
}
if (!good)
newPN = 0;
return BoundsMap[Base] = newPN;
}
if (SelectInst *SI = dyn_cast<SelectInst>(Base)) {
BasicBlock::iterator It = SI;
++It;
Value *TrueB = getPointerBounds(SI->getTrueValue());
Value *FalseB = getPointerBounds(SI->getFalseValue());
if (TrueB && FalseB) {
SelectInst *NewSI = SelectInst::Create(SI->getCondition(), TrueB,
FalseB, ".select.bounds", &*It);
Changed = true;
return BoundsMap[Base] = NewSI;
}
}
constType *Ty;
Value *V = PT->computeAllocationCountValue(Base, Ty);
if (!V) {
Base = Base->stripPointerCasts();
if (CallInst *CI = dyn_cast<CallInst>(Base)) {
Function *F = CI->getCalledFunction();
constFunctionType *FTy = F->getFunctionType();
// last operand is always size for this API call kind
if (F->isDeclaration() && FTy->getNumParams() > 0) {
CallSite CS(CI);
if (FTy->getParamType(FTy->getNumParams()-1)->isIntegerTy())
V = CS.getArgument(FTy->getNumParams()-1);
}
}
if (!V)
return BoundsMap[Base] = 0;
} else {
unsigned size = TD->getTypeAllocSize(Ty);
if (size > 1) {
Constant *C = cast<Constant>(V);
C = ConstantExpr::getMul(C,
ConstantInt::get(Type::getInt32Ty(C->getContext()),
size));
V = C;
}
}
if (V->getType() != I64Ty) {
if (Constant *C = dyn_cast<Constant>(V))
V = ConstantExpr::getZExt(C, I64Ty);
else {
Instruction *I = getInsertPoint(V);
V = new ZExtInst(V, I64Ty, "", I);
}
}
return BoundsMap[Base] = V;
}
MDNode *getLocation(Instruction *I, bool &Approximate, unsigned MDDbgKind)
{
Approximate = false;
if (MDNode *Dbg = I->getMetadata(MDDbgKind))
return Dbg;
if (!MDDbgKind)
return 0;
Approximate = true;
BasicBlock::iterator It = I;
while (It != I->getParent()->begin()) {
--It;
if (MDNode *Dbg = It->getMetadata(MDDbgKind))
return Dbg;
}
BasicBlock *BB = I->getParent();
while ((BB = BB->getUniquePredecessor())) {
It = BB->end();
while (It != BB->begin()) {
--It;
if (MDNode *Dbg = It->getMetadata(MDDbgKind))
return Dbg;
}
}
return 0;
}
bool insertCheck(const SCEV *Idx, const SCEV *Limit, Instruction *I,
bool strict)
{
if (isa<SCEVCouldNotCompute>(Idx) && isa<SCEVCouldNotCompute>(Limit)) {
errs() << "Could not compute the index and the limit!: \n" << *I << "\n";
return false;
}
if (isa<SCEVCouldNotCompute>(Idx)) {
errs() << "Could not compute index: \n" << *I << "\n";
return false;
}
if (isa<SCEVCouldNotCompute>(Limit)) {
errs() << "Could not compute limit: " << *I << "\n";
return false;
}
BasicBlock *BB = I->getParent();
BasicBlock::iterator It = I;
BasicBlock *newBB = SplitBlock(BB, &*It, this);
PHINode *PN;
unsigned MDDbgKind = I->getContext().getMDKindID("dbg");
//verifyFunction(*BB->getParent());
if (!AbrtBB) {
std::vector<constType*>args;
FunctionType* abrtTy = FunctionType::get(Type::getVoidTy(BB->getContext()),args,false);
args.push_back(Type::getInt32Ty(BB->getContext()));
FunctionType* rterrTy = FunctionType::get(Type::getInt32Ty(BB->getContext()),args,false);
Constant *func_abort = BB->getParent()->getParent()->getOrInsertFunction("abort", abrtTy);
Constant *func_rterr = BB->getParent()->getParent()->getOrInsertFunction("bytecode_rt_error",
rterrTy);
AbrtBB = BasicBlock::Create(BB->getContext(), "rterr.trig", BB->getParent());
PN = PHINode::Create(Type::getInt32Ty(BB->getContext()),HINT(1) "",
AbrtBB);
if (MDDbgKind) {
CallInst *RtErrCall = CallInst::Create(func_rterr, PN, "", AbrtBB);
RtErrCall->setCallingConv(CallingConv::C);
RtErrCall->setTailCall(true);
#if LLVM_VERSION < 32
RtErrCall->setDoesNotThrow(true);
#else
RtErrCall->setDoesNotThrow();
#endif
}
CallInst* AbrtC = CallInst::Create(func_abort, "", AbrtBB);
AbrtC->setCallingConv(CallingConv::C);
AbrtC->setTailCall(true);
#if LLVM_VERSION < 32
AbrtC->setDoesNotReturn(true);
AbrtC->setDoesNotThrow(true);
#else
AbrtC->setDoesNotReturn();
AbrtC->setDoesNotThrow();
#endif
new UnreachableInst(BB->getContext(), AbrtBB);
DT->addNewBlock(AbrtBB, BB);
//verifyFunction(*BB->getParent());
} else {
PN = cast<PHINode>(AbrtBB->begin());
}
unsigned locationid = 0;
bool Approximate;
if (MDNode *Dbg = getLocation(I, Approximate, MDDbgKind)) {
DILocation Loc(Dbg);
locationid = Loc.getLineNumber() << 8;
unsigned col = Loc.getColumnNumber();
if (col > 254)
col = 254;
if (Approximate)
col = 255;
locationid |= col;
}
PN->addIncoming(ConstantInt::get(Type::getInt32Ty(BB->getContext()),
locationid), BB);
TerminatorInst *TI = BB->getTerminator();
Value *IdxV = expander->expandCodeFor(Idx, Limit->getType(), TI);
Value *LimitV = expander->expandCodeFor(Limit, Limit->getType(), TI);
if (isa<Instruction>(IdxV) &&
!DT->dominates(cast<Instruction>(IdxV)->getParent(),I->getParent())) {
printLocation(I, true);
errs() << "basic block with value [ " << IdxV->getName();
errs() << " ] with limit [ " << LimitV->getName();
errs() << " ] does not dominate" << *I << "\n";
return false;
}
if (isa<Instruction>(LimitV) &&
!DT->dominates(cast<Instruction>(LimitV)->getParent(),I->getParent())) {
printLocation(I, true);
errs() << "basic block with limit [" << LimitV->getName();
errs() << " ] on value [ " << IdxV->getName();
errs() << " ] does not dominate" << *I << "\n";
return false;
}
Value *Cond = new ICmpInst(TI, strict ?
ICmpInst::ICMP_ULT :
ICmpInst::ICMP_ULE, IdxV, LimitV);
BranchInst::Create(newBB, AbrtBB, Cond, TI);
//TI->eraseFromParent();
delInst.push_back(TI);
// Update dominator info
BasicBlock *DomBB =
DT->findNearestCommonDominator(BB, DT->getNode(AbrtBB)->getIDom()->getBlock());
DT->changeImmediateDominator(AbrtBB, DomBB);
return true;
}
static void MakeCompatible(ScalarEvolution *SE, const SCEV*& LHS, const SCEV*& RHS)
{
if (const SCEVZeroExtendExpr *ZL = dyn_cast<SCEVZeroExtendExpr>(LHS))
LHS = ZL->getOperand();
if (const SCEVZeroExtendExpr *ZR = dyn_cast<SCEVZeroExtendExpr>(RHS))
RHS = ZR->getOperand();
constType* LTy = SE->getEffectiveSCEVType(LHS->getType());
constType *RTy = SE->getEffectiveSCEVType(RHS->getType());
if (SE->getTypeSizeInBits(RTy) > SE->getTypeSizeInBits(LTy))
LTy = RTy;
LHS = SE->getNoopOrZeroExtend(LHS, LTy);
RHS = SE->getNoopOrZeroExtend(RHS, LTy);
}
bool checkCond(Instruction *ICI, Instruction *I, bool equal)
{
#if LLVM_VERSION < 35
for (Value::use_iterator JU=ICI->use_begin(),JUE=ICI->use_end();
JU != JUE; ++JU) {
#else
for (Value::user_iterator JU=ICI->user_begin(),JUE=ICI->user_end();
JU != JUE; ++JU) {
#endif
Value *JU_V = *JU;
if (BranchInst *BI = dyn_cast<BranchInst>(JU_V)) {
if (!BI->isConditional())
continue;
BasicBlock *S = BI->getSuccessor(equal);
if (DT->dominates(S, I->getParent()))
return true;
}
if (BinaryOperator *BI = dyn_cast<BinaryOperator>(JU_V)) {
if (BI->getOpcode() == Instruction::Or &&
checkCond(BI, I, equal))
return true;
if (BI->getOpcode() == Instruction::And &&
checkCond(BI, I, !equal))
return true;
}
}
return false;
}
bool checkCondition(Instruction *CI, Instruction *I)
{
#if LLVM_VERSION < 35
for (Value::use_iterator U=CI->use_begin(),UE=CI->use_end();
U != UE; ++U) {
#else
for (Value::user_iterator U=CI->user_begin(),UE=CI->user_end();
U != UE; ++U) {
#endif
Value *U_V = *U;
if (ICmpInst *ICI = dyn_cast<ICmpInst>(U_V)) {
if (ICI->getOperand(0)->stripPointerCasts() == CI &&
isa<ConstantPointerNull>(ICI->getOperand(1))) {
if (checkCond(ICI, I, ICI->getPredicate() == ICmpInst::ICMP_EQ))
return true;
}
}
}
return false;
}
bool validateAccess(Value *Pointer, Value *Length, Instruction *I)
{
// get base
Value *Base = getPointerBase(Pointer);
Value *SBase = Base->stripPointerCasts();
// get bounds
Value *Bounds = getPointerBounds(SBase);
if (!Bounds) {
printLocation(I, true);
errs() << "no bounds for base ";
printValue(SBase);
errs() << " while checking access to ";
printValue(Pointer);
errs() << " of length ";
printValue(Length);
errs() << "\n";
return false;
}
// checks if a NULL pointer check (returned from function) is made:
if (CallInst *CI = dyn_cast<CallInst>(Base->stripPointerCasts())) {
// by checking if use is in the same block (i.e. no branching decisions)
if (I->getParent() == CI->getParent()) {
printLocation(I, true);
errs() << "no null pointer check of pointer ";
printValue(Base, false, true);
errs() << " obtained by function call";
errs() << " before use in same block\n";
return false;
}
// by checking if a conditional contains the values in question somewhere
// between their usage
if (!checkCondition(CI, I)) {
printLocation(I, true);
errs() << "no null pointer check of pointer ";
printValue(Base, false, true);
errs() << " obtained by function call";
errs() << " before use\n";
return false;
}
}
constType *I64Ty =
Type::getInt64Ty(Base->getContext());
const SCEV *SLen = SE->getSCEV(Length);
const SCEV *OffsetP = SE->getMinusSCEV(SE->getSCEV(Pointer),
SE->getSCEV(Base));
SLen = SE->getNoopOrZeroExtend(SLen, I64Ty);
OffsetP = SE->getNoopOrZeroExtend(OffsetP, I64Ty);
const SCEV *Limit = SE->getSCEV(Bounds);
Limit = SE->getNoopOrZeroExtend(Limit, I64Ty);
DEBUG(dbgs() << "Checking access to " << *Pointer << " of length " <<
*Length << "\n");
if (OffsetP == Limit) {
printLocation(I, true);
errs() << "OffsetP == Limit: " << *OffsetP << "\n";
errs() << " while checking access to ";
printValue(Pointer);
errs() << " of length ";
printValue(Length);
errs() << "\n";
return false;
}
if (SLen == Limit) {
if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OffsetP)) {
if (SC->isZero())
return true;
}
errs() << "SLen == Limit: " << *SLen << "\n";
errs() << " while checking access to " << *Pointer << " of length "
<< *Length << " at " << *I << "\n";
return false;
}
bool valid = true;
SLen = SE->getAddExpr(OffsetP, SLen);
// check that offset + slen <= limit;
// umax(offset+slen, limit) == limit is a sufficient (but not necessary
// condition)
const SCEV *MaxL = SE->getUMaxExpr(SLen, Limit);
if (MaxL != Limit) {
DEBUG(dbgs() << "MaxL != Limit: " << *MaxL << ", " << *Limit << "\n");
valid &= insertCheck(SLen, Limit, I, false);
}
//TODO: nullpointer check
const SCEV *Max = SE->getUMaxExpr(OffsetP, Limit);
if (Max == Limit)
return valid;
DEBUG(dbgs() << "Max != Limit: " << *Max << ", " << *Limit << "\n");
// check that offset < limit
valid &= insertCheck(OffsetP, Limit, I, true);
return valid;
}
bool validateAccess(Value *Pointer, unsigned size, Instruction *I)
{
return validateAccess(Pointer,
ConstantInt::get(Type::getInt32Ty(Pointer->getContext()),
size), I);
}
};
char PtrVerifier::ID;
} /* end namespace llvm */
#if LLVM_VERSION >= 29
INITIALIZE_PASS_BEGIN(PtrVerifier, "", "", false, false)
#if LLVM_VERSION < 32
INITIALIZE_PASS_DEPENDENCY(TargetData)
#elif LLVM_VERSION < 35
INITIALIZE_PASS_DEPENDENCY(DataLayout)
#else
INITIALIZE_PASS_DEPENDENCY(DataLayoutPass)
#endif
#if LLVM_VERSION < 35
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
#else
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
#endif
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
#if LLVM_VERSION < 34
INITIALIZE_AG_DEPENDENCY(CallGraph)
#elif LLVM_VERSION < 35
INITIALIZE_PASS_DEPENDENCY(CallGraph)
#else
INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
#endif
INITIALIZE_PASS_DEPENDENCY(PointerTracking)
INITIALIZE_PASS_END(PtrVerifier, "clambc-rtchecks", "ClamBC RTchecks", false, false)
#endif
llvm::Pass *createClamBCRTChecks()
{
return new PtrVerifier();
}
+614
View File
@@ -0,0 +1,614 @@
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
LLVM_INCLUDES=-I$(top_srcdir)/llvm/include -I$(top_builddir)/llvm/include
# TODO: _DEBUG should be defined for --enable-debug, and NDEBUG otherwise, but
# keep it like this while I'm testing LLVM
# TODO: HP-UX should have -D_REENTRANT -D_HPUX_SOURCE
LLVM_DEFS=-D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS -D_DEBUG -D_GNU_SOURCE
AM_CPPFLAGS = @SSL_CPPFLAGS@ -I$(top_srcdir)/../.. -I$(top_srcdir)/.. -I$(top_builddir)/../../
AM_CXXFLAGS = $(LLVM_CXXFLAGS) -fno-exceptions
ACLOCAL_AMFLAGS=-I m4
libclamavcxx_la_SOURCES = bytecode2llvm.cpp\
ClamBCRTChecks.cpp\
ClamBCModule.h\
ClamBCDiagnostics.h\
detect.cpp\
llvm30_compat.h
if BUILD_EXTERNAL_LLVM
#$(LLVM_CONFIG): build-llvm
# we know this will be built with GNU make, so its safe to use GNU make specific
# $(shell ...)
#LLVM_DEPS=$(shell $(LLVM_CONFIG) --libfiles jit nativecodegen)
libclamavcxx_la_CXXFLAGS = $(AM_CPPFLAGS) @LLVMCONFIG_CXXFLAGS@ -fexceptions -DLLVM_VERSION=${LLVM_VERSION}
libclamavcxx_la_LDFLAGS = @LLVMCONFIG_LDFLAGS@ @LLVMCONFIG_LIBS@ @LLVMCONFIG_LDFLAGS@
libclamavcxx_la_DEPENDENCIES = @LLVMCONFIG_LIBFILES@
noinst_LTLIBRARIES = libclamavcxx.la
libclamavcxx_la_SOURCES += PointerTracking.cpp
libclamavcxx_la_SOURCES += PointerTracking.h
else
AM_CPPFLAGS += $(LLVM_INCLUDES) $(LLVM_DEFS)
noinst_LTLIBRARIES = libclamavcxx.la libllvmsystem.la\
libllvmcodegen.la libllvmjit.la
libclamavcxx_la_LIBADD = libllvmjit.la
libclamavcxx_la_DEPENDENCIES = libllvmjit.la libllvmcodegen.la libllvmsystem.la
libclamavcxx_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined
libclamavcxx_la_CXXFLAGS = $(LLVM_CXXFLAGS) -DLLVM_VERSION=${LLVM_VERSION}
if BUILD_X86
libclamavcxx_la_LIBADD+=libllvmx86codegen.la
libclamavcxx_la_DEPENDENCIES+=libllvmx86codegen.la
noinst_LTLIBRARIES+=libllvmx86codegen.la
endif
if BUILD_PPC
libclamavcxx_la_LIBADD+=libllvmpowerpccodegen.la
libclamavcxx_la_DEPENDENCIES+=libllvmpowerpccodegen.la
noinst_LTLIBRARIES+=libllvmpowerpccodegen.la
endif
libclamavcxx_la_LIBADD+=libllvmcodegen.la libllvmsystem.la
# crdaviso@cisco.com - Removed -pedantic from the following line to allow
# building on CentOS 5 (g++ 4.1.2). An openssl header file is included that
# includes a comma at the end of an enumerator list, which is valid in C99 but
# not C++98, so -pedantic produces an error and the build fails.
LLVM_CXXFLAGS=-Woverloaded-virtual -Wno-long-long -Wall -W -Wno-unused-parameter -Wwrite-strings
unittest_CXXFLAGS=@NO_VARIADIC_MACROS@ @NO_MISSING_FIELD_INITIALIZERS@ -DGTEST_HAS_TR1_TUPLE=0
TBLGENFILES=llvm/include/llvm/Intrinsics.gen X86GenRegisterInfo.h.inc X86GenRegisterNames.inc X86GenRegisterInfo.inc X86GenInstrNames.inc X86GenInstrInfo.inc\
X86GenDAGISel.inc X86GenFastISel.inc X86GenCallingConv.inc\
X86GenSubtarget.inc PPCGenInstrNames.inc PPCGenRegisterNames.inc PPCGenCodeEmitter.inc PPCGenRegisterInfo.h.inc PPCGenRegisterInfo.inc\
PPCGenInstrInfo.inc PPCGenDAGISel.inc PPCGenCallingConv.inc PPCGenSubtarget.inc
BUILT_SOURCES=
EXTRA_DIST=$(top_srcdir)/llvm llvmcheck.sh $(TBLGENFILES)
libllvmsystem_la_LDFLAGS=@THREAD_LIBS@
libllvmsystem_la_LIBADD=
libllvmsystem_la_SOURCES=\
llvm/lib/System/Alarm.cpp\
llvm/lib/System/Atomic.cpp\
llvm/lib/System/Disassembler.cpp\
llvm/lib/System/DynamicLibrary.cpp\
llvm/lib/System/Errno.cpp\
llvm/lib/System/Host.cpp\
llvm/lib/System/IncludeFile.cpp\
llvm/lib/System/Memory.cpp\
llvm/lib/System/Mutex.cpp\
llvm/lib/System/Path.cpp\
llvm/lib/System/Process.cpp\
llvm/lib/System/Program.cpp\
llvm/lib/System/RWMutex.cpp\
llvm/lib/System/Signals.cpp\
llvm/lib/System/ThreadLocal.cpp\
llvm/lib/System/Threading.cpp\
llvm/lib/System/TimeValue.cpp\
llvm/lib/System/Valgrind.cpp
if MAINTAINER_MODE
BUILT_SOURCES+=$(TBLGENFILES)
noinst_PROGRAMS = tblgen
tblgen_CXXFLAGS=$(LLVM_CXXFLAGS)
tblgen_CFLAGS=
#TODO: if VERSIONSCRIPT
tblgen_LDFLAGS=@THREAD_LIBS@ -Wl,--version-script,@top_srcdir@/llvm/autoconf/ExportMap.map
# tblgen needs rtti (for now), and we build everything else with -fno-rtti
# since tblgen is only a maintainer-mode tool, build these files twice (once for
# libllvmsupport.la -fno-rtti, and once here, with defaults (rtti)).
tblgen_SOURCES=\
llvm/utils/TableGen/ARMDecoderEmitter.cpp\
llvm/utils/TableGen/AsmMatcherEmitter.cpp\
llvm/utils/TableGen/AsmWriterInst.cpp\
llvm/utils/TableGen/CallingConvEmitter.cpp\
llvm/utils/TableGen/ClangASTNodesEmitter.cpp\
llvm/utils/TableGen/ClangAttrEmitter.cpp\
llvm/utils/TableGen/ClangDiagnosticsEmitter.cpp\
llvm/utils/TableGen/CodeEmitterGen.cpp\
llvm/utils/TableGen/CodeGenDAGPatterns.cpp\
llvm/utils/TableGen/CodeGenInstruction.cpp\
llvm/utils/TableGen/CodeGenTarget.cpp\
llvm/utils/TableGen/DAGISelEmitter.cpp\
llvm/utils/TableGen/DAGISelMatcher.cpp\
llvm/utils/TableGen/DAGISelMatcherEmitter.cpp\
llvm/utils/TableGen/DAGISelMatcherGen.cpp\
llvm/utils/TableGen/DAGISelMatcherOpt.cpp\
llvm/utils/TableGen/EDEmitter.cpp\
llvm/utils/TableGen/FastISelEmitter.cpp\
llvm/utils/TableGen/InstrEnumEmitter.cpp\
llvm/utils/TableGen/InstrInfoEmitter.cpp\
llvm/utils/TableGen/IntrinsicEmitter.cpp\
llvm/utils/TableGen/LLVMCConfigurationEmitter.cpp\
llvm/utils/TableGen/NeonEmitter.cpp\
llvm/utils/TableGen/OptParserEmitter.cpp\
llvm/utils/TableGen/Record.cpp\
llvm/utils/TableGen/RegisterInfoEmitter.cpp\
llvm/utils/TableGen/SubtargetEmitter.cpp\
llvm/utils/TableGen/TableGenBackend.cpp\
llvm/utils/TableGen/TableGen.cpp\
llvm/utils/TableGen/TGLexer.cpp\
llvm/utils/TableGen/TGParser.cpp\
llvm/utils/TableGen/TGValueTypes.cpp\
llvm/lib/System/Alarm.cpp\
llvm/lib/System/Atomic.cpp\
llvm/lib/System/Disassembler.cpp\
llvm/lib/System/DynamicLibrary.cpp\
llvm/lib/System/Errno.cpp\
llvm/lib/System/Host.cpp\
llvm/lib/System/IncludeFile.cpp\
llvm/lib/System/Memory.cpp\
llvm/lib/System/Mutex.cpp\
llvm/lib/System/Path.cpp\
llvm/lib/System/Process.cpp\
llvm/lib/System/Program.cpp\
llvm/lib/System/RWMutex.cpp\
llvm/lib/System/Signals.cpp\
llvm/lib/System/ThreadLocal.cpp\
llvm/lib/System/Threading.cpp\
llvm/lib/System/TimeValue.cpp\
llvm/lib/System/Valgrind.cpp\
llvm/lib/Support/APFloat.cpp\
llvm/lib/Support/APInt.cpp\
llvm/lib/Support/APSInt.cpp\
llvm/lib/Support/Allocator.cpp\
llvm/lib/Support/CommandLine.cpp\
llvm/lib/Support/ConstantRange.cpp\
llvm/lib/Support/Debug.cpp\
llvm/lib/Support/DeltaAlgorithm.cpp\
llvm/lib/Support/Dwarf.cpp\
llvm/lib/Support/ErrorHandling.cpp\
llvm/lib/Support/FileUtilities.cpp\
llvm/lib/Support/FoldingSet.cpp\
llvm/lib/Support/FormattedStream.cpp\
llvm/lib/Support/GraphWriter.cpp\
llvm/lib/Support/IsInf.cpp\
llvm/lib/Support/IsNAN.cpp\
llvm/lib/Support/ManagedStatic.cpp\
llvm/lib/Support/MemoryBuffer.cpp\
llvm/lib/Support/MemoryObject.cpp\
llvm/lib/Support/PluginLoader.cpp\
llvm/lib/Support/PrettyStackTrace.cpp\
llvm/lib/Support/Regex.cpp\
llvm/lib/Support/SmallPtrSet.cpp\
llvm/lib/Support/SmallVector.cpp\
llvm/lib/Support/SourceMgr.cpp\
llvm/lib/Support/Statistic.cpp\
llvm/lib/Support/StringExtras.cpp\
llvm/lib/Support/StringMap.cpp\
llvm/lib/Support/StringPool.cpp\
llvm/lib/Support/StringRef.cpp\
llvm/lib/Support/SystemUtils.cpp\
llvm/lib/Support/TargetRegistry.cpp\
llvm/lib/Support/Timer.cpp\
llvm/lib/Support/Triple.cpp\
llvm/lib/Support/Twine.cpp\
llvm/lib/Support/circular_raw_ostream.cpp\
llvm/lib/Support/raw_os_ostream.cpp\
llvm/lib/Support/raw_ostream.cpp\
llvm/lib/Support/regcomp.c\
llvm/lib/Support/regerror.c\
llvm/lib/Support/regexec.c\
llvm/lib/Support/regfree.c\
llvm/lib/Support/regstrlcpy.c
TBLGEN=$(top_builddir)/tblgen
TBLGEN_V=$(AM_V_GEN)$(TBLGEN)
TBLGEN_FLAGS=-I$(top_srcdir)/llvm/include -I$(top_srcdir)/llvm/lib/Target -omit-comments
llvm/include/llvm/Intrinsics.gen: llvm/include/llvm/Intrinsics.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS) -gen-intrinsic -o $@ $<
# X86 Target
TBLGEN_FLAGS_X86= $(TBLGEN_FLAGS) -I$(top_srcdir)/llvm/lib/Target/X86
X86GenRegisterInfo.h.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-register-desc-header -o $@ $<
X86GenRegisterNames.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-register-enums -o $@ $<
X86GenRegisterInfo.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-register-desc -o $@ $<
X86GenInstrNames.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-instr-enums -o $@ $<
X86GenInstrInfo.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-instr-desc -o $@ $<
X86GenDAGISel.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-dag-isel -o $@ $<
X86GenFastISel.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-fast-isel -o $@ $<
X86GenCallingConv.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-callingconv -o $@ $<
X86GenSubtarget.inc: llvm/lib/Target/X86/X86.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_X86) -gen-subtarget -o $@ $<
# PPC Target
TBLGEN_FLAGS_PPC= $(TBLGEN_FLAGS) -I$(top_srcdir)/llvm/lib/Target/PowerPC
PPCGenInstrNames.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-instr-enums -o $@ $<
PPCGenRegisterNames.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-register-enums -o $@ $<
PPCGenCodeEmitter.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-emitter -o $@ $<
PPCRegisterInfo.h.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-register-desc-header -o $@ $<
PPCGenRegisterInfo.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-register-desc -o $@ $<
PPCGenRegisterInfo.h.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-register-desc-header -o $@ $<
PPCGenInstrInfo.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-instr-desc -o $@ $<
PPCGenDAGISel.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-dag-isel -o $@ $<
PPCGenCallingConv.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-callingconv -o $@ $<
PPCGenSubtarget.inc: llvm/lib/Target/PowerPC/PPC.td $(TBLGEN)
$(TBLGEN_V) $(TBLGEN_FLAGS_PPC) -gen-subtarget -o $@ $<
endif
if BUILD_X86
libllvmx86codegen_la_CPPFLAGS=$(LLVM_INCLUDES) $(LLVM_DEFS) -I$(top_builddir) -I$(top_srcdir)/llvm/lib/Target/X86
libllvmx86codegen_la_SOURCES=\
llvm/lib/MC/ELFObjectWriter.cpp\
llvm/lib/MC/MCAsmInfoCOFF.cpp\
llvm/lib/MC/MCCodeEmitter.cpp\
llvm/lib/MC/MCELFStreamer.cpp\
llvm/lib/MC/MCMachOStreamer.cpp\
llvm/lib/MC/MCObjectStreamer.cpp\
llvm/lib/MC/MCObjectWriter.cpp\
llvm/lib/MC/MachObjectWriter.cpp\
llvm/lib/MC/TargetAsmBackend.cpp\
llvm/lib/MC/WinCOFFObjectWriter.cpp\
llvm/lib/MC/WinCOFFStreamer.cpp\
llvm/lib/Target/TargetELFWriterInfo.cpp\
llvm/lib/Target/X86/SSEDomainFix.cpp\
llvm/lib/Target/X86/TargetInfo/X86TargetInfo.cpp\
llvm/lib/Target/X86/X86AsmBackend.cpp\
llvm/lib/Target/X86/X86COFFMachineModuleInfo.cpp\
llvm/lib/Target/X86/X86CodeEmitter.cpp\
llvm/lib/Target/X86/X86ELFWriterInfo.cpp\
llvm/lib/Target/X86/X86FastISel.cpp\
llvm/lib/Target/X86/X86FloatingPoint.cpp\
llvm/lib/Target/X86/X86ISelDAGToDAG.cpp\
llvm/lib/Target/X86/X86ISelLowering.cpp\
llvm/lib/Target/X86/X86InstrInfo.cpp\
llvm/lib/Target/X86/X86JITInfo.cpp\
llvm/lib/Target/X86/X86MCAsmInfo.cpp\
llvm/lib/Target/X86/X86MCCodeEmitter.cpp\
llvm/lib/Target/X86/X86RegisterInfo.cpp\
llvm/lib/Target/X86/X86SelectionDAGInfo.cpp\
llvm/lib/Target/X86/X86Subtarget.cpp\
llvm/lib/Target/X86/X86TargetMachine.cpp\
llvm/lib/Target/X86/X86TargetObjectFile.cpp
endif
if BUILD_PPC
libllvmpowerpccodegen_la_CPPFLAGS=$(LLVM_INCLUDES) $(LLVM_DEFS) -I$(top_builddir) -I$(top_srcdir)/llvm/lib/Target/PowerPC
libllvmpowerpccodegen_la_SOURCES=\
llvm/lib/Target/PowerPC/PPCBranchSelector.cpp\
llvm/lib/Target/PowerPC/PPCCodeEmitter.cpp\
llvm/lib/Target/PowerPC/PPCHazardRecognizers.cpp\
llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp\
llvm/lib/Target/PowerPC/PPCISelLowering.cpp\
llvm/lib/Target/PowerPC/PPCInstrInfo.cpp\
llvm/lib/Target/PowerPC/PPCJITInfo.cpp\
llvm/lib/Target/PowerPC/PPCMCAsmInfo.cpp\
llvm/lib/Target/PowerPC/PPCPredicates.cpp\
llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp\
llvm/lib/Target/PowerPC/PPCSelectionDAGInfo.cpp\
llvm/lib/Target/PowerPC/PPCSubtarget.cpp\
llvm/lib/Target/PowerPC/PPCTargetMachine.cpp\
llvm/lib/Target/PowerPC/TargetInfo/PowerPCTargetInfo.cpp
endif
# End of Targets
libllvmjit_la_SOURCES=\
llvm/lib/Analysis/AliasAnalysis.cpp\
llvm/lib/Analysis/AliasSetTracker.cpp\
llvm/lib/Analysis/BasicAliasAnalysis.cpp\
llvm/lib/Analysis/CaptureTracking.cpp\
llvm/lib/Analysis/DebugInfo.cpp\
llvm/lib/Analysis/IPA/CallGraph.cpp\
llvm/lib/Analysis/MemoryBuiltins.cpp\
llvm/lib/Analysis/PointerTracking.cpp\
llvm/lib/Analysis/ProfileInfo.cpp\
llvm/lib/Analysis/ValueTracking.cpp\
llvm/lib/CodeGen/ELFCodeEmitter.cpp\
llvm/lib/CodeGen/ELFWriter.cpp\
llvm/lib/CodeGen/LiveVariables.cpp\
llvm/lib/CodeGen/MachineBasicBlock.cpp\
llvm/lib/CodeGen/MachineDominators.cpp\
llvm/lib/CodeGen/MachineFunction.cpp\
llvm/lib/CodeGen/MachineFunctionAnalysis.cpp\
llvm/lib/CodeGen/MachineFunctionPass.cpp\
llvm/lib/CodeGen/MachineFunctionPrinterPass.cpp\
llvm/lib/CodeGen/MachineInstr.cpp\
llvm/lib/CodeGen/MachineLoopInfo.cpp\
llvm/lib/CodeGen/MachineModuleInfo.cpp\
llvm/lib/CodeGen/MachineRegisterInfo.cpp\
llvm/lib/CodeGen/ObjectCodeEmitter.cpp\
llvm/lib/CodeGen/PostRAHazardRecognizer.cpp\
llvm/lib/CodeGen/PseudoSourceValue.cpp\
llvm/lib/CodeGen/ScheduleDAG.cpp\
llvm/lib/CodeGen/TargetInstrInfoImpl.cpp\
llvm/lib/CodeGen/UnreachableBlockElim.cpp\
llvm/lib/ExecutionEngine/ExecutionEngine.cpp\
llvm/lib/ExecutionEngine/JIT/Intercept.cpp\
llvm/lib/ExecutionEngine/JIT/JIT.cpp\
llvm/lib/ExecutionEngine/JIT/JITDebugRegisterer.cpp\
llvm/lib/ExecutionEngine/JIT/JITDwarfEmitter.cpp\
llvm/lib/ExecutionEngine/JIT/JITEmitter.cpp\
llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp\
llvm/lib/ExecutionEngine/JIT/OProfileJITEventListener.cpp\
llvm/lib/ExecutionEngine/JIT/TargetSelect.cpp\
llvm/lib/MC/MCAsmInfo.cpp\
llvm/lib/MC/MCAssembler.cpp\
llvm/lib/MC/MCContext.cpp\
llvm/lib/MC/MCExpr.cpp\
llvm/lib/MC/MCInst.cpp\
llvm/lib/MC/MCSection.cpp\
llvm/lib/MC/MCSectionCOFF.cpp\
llvm/lib/MC/MCSectionELF.cpp\
llvm/lib/MC/MCSectionMachO.cpp\
llvm/lib/MC/MCSymbol.cpp\
llvm/lib/Support/APFloat.cpp\
llvm/lib/Support/APInt.cpp\
llvm/lib/Support/Allocator.cpp\
llvm/lib/Support/CommandLine.cpp\
llvm/lib/Support/ConstantRange.cpp\
llvm/lib/Support/Debug.cpp\
llvm/lib/Support/Dwarf.cpp\
llvm/lib/Support/ErrorHandling.cpp\
llvm/lib/Support/FoldingSet.cpp\
llvm/lib/Support/FormattedStream.cpp\
llvm/lib/Support/ManagedStatic.cpp\
llvm/lib/Support/MemoryBuffer.cpp\
llvm/lib/Support/PrettyStackTrace.cpp\
llvm/lib/Support/SmallPtrSet.cpp\
llvm/lib/Support/SmallVector.cpp\
llvm/lib/Support/SourceMgr.cpp\
llvm/lib/Support/Statistic.cpp\
llvm/lib/Support/StringExtras.cpp\
llvm/lib/Support/StringMap.cpp\
llvm/lib/Support/StringPool.cpp\
llvm/lib/Support/StringRef.cpp\
llvm/lib/Support/TargetRegistry.cpp\
llvm/lib/Support/Timer.cpp\
llvm/lib/Support/Triple.cpp\
llvm/lib/Support/Twine.cpp\
llvm/lib/Support/raw_ostream.cpp\
llvm/lib/Support/circular_raw_ostream.cpp\
llvm/lib/Target/Mangler.cpp\
llvm/lib/Target/SubtargetFeature.cpp\
llvm/lib/Target/TargetData.cpp\
llvm/lib/Target/TargetInstrInfo.cpp\
llvm/lib/Target/TargetLoweringObjectFile.cpp\
llvm/lib/Target/TargetMachine.cpp\
llvm/lib/Target/TargetRegisterInfo.cpp\
llvm/lib/Transforms/Scalar/DCE.cpp\
llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp\
llvm/lib/VMCore/AsmWriter.cpp\
llvm/lib/VMCore/Attributes.cpp\
llvm/lib/VMCore/AutoUpgrade.cpp\
llvm/lib/VMCore/BasicBlock.cpp\
llvm/lib/VMCore/ConstantFold.cpp\
llvm/lib/VMCore/Constants.cpp\
llvm/lib/VMCore/Core.cpp\
llvm/lib/VMCore/DebugLoc.cpp\
llvm/lib/VMCore/Dominators.cpp\
llvm/lib/VMCore/Function.cpp\
llvm/lib/VMCore/GVMaterializer.cpp\
llvm/lib/VMCore/Globals.cpp\
llvm/lib/VMCore/IRBuilder.cpp\
llvm/lib/VMCore/InlineAsm.cpp\
llvm/lib/VMCore/Instruction.cpp\
llvm/lib/VMCore/Instructions.cpp\
llvm/lib/VMCore/IntrinsicInst.cpp\
llvm/lib/VMCore/LLVMContext.cpp\
llvm/lib/VMCore/LLVMContextImpl.cpp\
llvm/lib/VMCore/LeakDetector.cpp\
llvm/lib/VMCore/Metadata.cpp\
llvm/lib/VMCore/Module.cpp\
llvm/lib/VMCore/Pass.cpp\
llvm/lib/VMCore/PassManager.cpp\
llvm/lib/VMCore/PassRegistry.cpp\
llvm/lib/VMCore/PrintModulePass.cpp\
llvm/lib/VMCore/Type.cpp\
llvm/lib/VMCore/TypeSymbolTable.cpp\
llvm/lib/VMCore/Use.cpp\
llvm/lib/VMCore/Value.cpp\
llvm/lib/VMCore/ValueSymbolTable.cpp\
llvm/lib/VMCore/ValueTypes.cpp\
llvm/lib/VMCore/Verifier.cpp
libllvmcodegen_la_SOURCES=\
llvm/lib/Analysis/ConstantFolding.cpp\
llvm/lib/Analysis/IVUsers.cpp\
llvm/lib/Analysis/InstructionSimplify.cpp\
llvm/lib/Analysis/Loads.cpp\
llvm/lib/Analysis/LoopInfo.cpp\
llvm/lib/Analysis/LoopPass.cpp\
llvm/lib/Analysis/MemoryDependenceAnalysis.cpp\
llvm/lib/Analysis/PHITransAddr.cpp\
llvm/lib/Analysis/ScalarEvolution.cpp\
llvm/lib/Analysis/ScalarEvolutionExpander.cpp\
llvm/lib/Analysis/ScalarEvolutionNormalization.cpp\
llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp\
llvm/lib/CodeGen/Analysis.cpp\
llvm/lib/CodeGen/BranchFolding.cpp\
llvm/lib/CodeGen/CalcSpillWeights.cpp\
llvm/lib/CodeGen/CallingConvLower.cpp\
llvm/lib/CodeGen/CodePlacementOpt.cpp\
llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp\
llvm/lib/CodeGen/DeadMachineInstructionElim.cpp\
llvm/lib/CodeGen/DwarfEHPrepare.cpp\
llvm/lib/CodeGen/GCMetadata.cpp\
llvm/lib/CodeGen/GCStrategy.cpp\
llvm/lib/CodeGen/InlineSpiller.cpp\
llvm/lib/CodeGen/LLVMTargetMachine.cpp\
llvm/lib/CodeGen/LatencyPriorityQueue.cpp\
llvm/lib/CodeGen/LiveInterval.cpp\
llvm/lib/CodeGen/LiveIntervalAnalysis.cpp\
llvm/lib/CodeGen/LiveStackAnalysis.cpp\
llvm/lib/CodeGen/LocalStackSlotAllocation.cpp\
llvm/lib/CodeGen/LowerSubregs.cpp\
llvm/lib/CodeGen/MachineCSE.cpp\
llvm/lib/CodeGen/MachineLICM.cpp\
llvm/lib/CodeGen/MachineModuleInfoImpls.cpp\
llvm/lib/CodeGen/MachinePassRegistry.cpp\
llvm/lib/CodeGen/MachineSSAUpdater.cpp\
llvm/lib/CodeGen/MachineSink.cpp\
llvm/lib/CodeGen/MachineVerifier.cpp\
llvm/lib/CodeGen/OptimizePHIs.cpp\
llvm/lib/CodeGen/PHIElimination.cpp\
llvm/lib/CodeGen/Passes.cpp\
llvm/lib/CodeGen/PeepholeOptimizer.cpp\
llvm/lib/CodeGen/PostRASchedulerList.cpp\
llvm/lib/CodeGen/PreAllocSplitting.cpp\
llvm/lib/CodeGen/ProcessImplicitDefs.cpp\
llvm/lib/CodeGen/PrologEpilogInserter.cpp\
llvm/lib/CodeGen/RegAllocFast.cpp\
llvm/lib/CodeGen/RegAllocLinearScan.cpp\
llvm/lib/CodeGen/RegisterCoalescer.cpp\
llvm/lib/CodeGen/RegisterScavenging.cpp\
llvm/lib/CodeGen/ScheduleDAGEmit.cpp\
llvm/lib/CodeGen/ScheduleDAGInstrs.cpp\
llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp\
llvm/lib/CodeGen/SelectionDAG/FastISel.cpp\
llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp\
llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp\
llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp\
llvm/lib/CodeGen/SelectionDAG/ScheduleDAGList.cpp\
llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp\
llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp\
llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp\
llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp\
llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp\
llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp\
llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp\
llvm/lib/CodeGen/SelectionDAG/TargetSelectionDAGInfo.cpp\
llvm/lib/CodeGen/ScheduleDAGPrinter.cpp\
llvm/lib/CodeGen/ShrinkWrapping.cpp\
llvm/lib/CodeGen/SimpleRegisterCoalescing.cpp\
llvm/lib/CodeGen/SjLjEHPrepare.cpp\
llvm/lib/CodeGen/SlotIndexes.cpp\
llvm/lib/CodeGen/Spiller.cpp\
llvm/lib/CodeGen/SplitKit.cpp\
llvm/lib/CodeGen/StackProtector.cpp\
llvm/lib/CodeGen/StackSlotColoring.cpp\
llvm/lib/CodeGen/StrongPHIElimination.cpp\
llvm/lib/CodeGen/TailDuplication.cpp\
llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp\
llvm/lib/CodeGen/TwoAddressInstructionPass.cpp\
llvm/lib/CodeGen/VirtRegMap.cpp\
llvm/lib/CodeGen/VirtRegRewriter.cpp\
llvm/lib/MC/MCAsmInfoDarwin.cpp\
llvm/lib/MC/MCAsmStreamer.cpp\
llvm/lib/MC/MCInstPrinter.cpp\
llvm/lib/MC/MCLoggingStreamer.cpp\
llvm/lib/MC/MCNullStreamer.cpp\
llvm/lib/MC/MCStreamer.cpp\
llvm/lib/Support/GraphWriter.cpp\
llvm/lib/Target/TargetFrameInfo.cpp\
llvm/lib/Target/TargetSubtarget.cpp\
llvm/lib/Transforms/IPO/ConstantMerge.cpp\
llvm/lib/Transforms/IPO/GlobalOpt.cpp\
llvm/lib/Transforms/Scalar/CodeGenPrepare.cpp\
llvm/lib/Transforms/Scalar/GEPSplitter.cpp\
llvm/lib/Transforms/Scalar/GVN.cpp\
llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp\
llvm/lib/Transforms/Scalar/SCCP.cpp\
llvm/lib/Transforms/Utils/AddrModeMatcher.cpp\
llvm/lib/Transforms/Utils/BasicBlockUtils.cpp\
llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp\
llvm/lib/Transforms/Utils/BuildLibCalls.cpp\
llvm/lib/Transforms/Utils/DemoteRegToStack.cpp\
llvm/lib/Transforms/Utils/LCSSA.cpp\
llvm/lib/Transforms/Utils/Local.cpp\
llvm/lib/Transforms/Utils/LoopSimplify.cpp\
llvm/lib/Transforms/Utils/LowerInvoke.cpp\
llvm/lib/Transforms/Utils/LowerSwitch.cpp\
llvm/lib/Transforms/Utils/Mem2Reg.cpp\
llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp\
llvm/lib/Transforms/Utils/SSAUpdater.cpp\
llvm/lib/Transforms/Utils/SimplifyCFG.cpp\
llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp
# Don't use make -C here, otherwise there's a racecondition between distclean
# and clean (distclean removes all Makefiles in llvm/)
clean-local:
rm -rf `find llvm/test -name Output -type d -print`
rm -rf llvm/Release llvm/Debug
if MAINTAINER_MODE
rm -f *.inc
rm -f llvm/include/llvm/Intrinsics.gen
endif
rm -f llvm/test/site.exp llvm/test/site.bak llvm/test/*.out llvm/test/*.sum llvm/test/*.log
rm -f $(top_srcdir)/llvm/utils/lit/lit/*.pyc
distclean-local:
rm -f llvm/docs/doxygen.cfg llvm/test/Unit/.dir llvm/test/Unit/lit.site.cfg
rm -f llvm/test/lit.site.cfg llvm/config.status
rm -f llvm/mklib llvm/tools/llvmc/llvm-config.in
rm -f llvm/Makefile.config llvm/config.log
rm -f llvm/llvm.spec llvm/include/llvm/Config/AsmPrinters.def llvm/include/llvm/Config/config.h
rm -f llvm/include/llvm/Config/Disassemblers.def llvm/include/llvm/Config/llvm-config.h
rm -f llvm/include/llvm/System/DataTypes.h llvm/include/llvm/Config/Targets.def
rm -f llvm/tools/llvmc/plugins/Base/Base.td llvm/tools/llvm-config/llvm-config.in
rm -f llvm/include/llvm/Config/AsmParsers.def
if test $(abs_srcdir) != $(abs_builddir); then\
rm -f llvm/Makefile llvm/lib/Makefile llvm/test/Makefile\
llvm/test/Makefile.tests llvm/tools/Makefile llvm/utils/Makefile\
llvm/Makefile.common llvm/unittests/Makefile;\
fi
# Rule to rerun LLVM's configure if it changed, before building anything else
# LLVM
BUILT_SOURCES += llvm/config.status
libllvmsystem_la_SOURCES += llvm/config.status
$(top_builddir)/llvm/config.status: llvm/configure
(cd llvm; ./config.status --recheck; ./config.status)
endif
# rm configure generated files
dist-hook: clean-local
$(MAKE) -C llvm dist-hook
rm -f $(distdir)/llvm/include/llvm/Config/*.h $(distdir)/llvm/include/llvm/Config/*.def $(distdir)/llvm/Makefile.config $(distdir)/llvm/llvm.spec
rm -f $(distdir)/llvm/docs/doxygen.cfg $(distdir)/llvm/tools/llvmc/plugins/Base/Base.td $(distdir)/llvm/tools/llvm-config/llvm-config.in
rm -f $(distdir)/llvm/include/llvm/System/DataTypes.h $(distdir)/llvm/config.log $(distdir)/llvm/config.status
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,9 @@
.PHONY: distdir distclean maintainer-clean
distdir:
echo "make distdir requires --enable-llvm"
exit 1
# nothing to do here, rules must exist for distclean to succeed
distclean:
-rm -f Makefile
maintainer-clean:
@@ -0,0 +1,202 @@
//===- TableGen'erated file -------------------------------------*- C++ -*-===//
//
// Calling Convention Implementation Fragment
//
// Automatically generated file, do not edit!
//
//===----------------------------------------------------------------------===//
static bool CC_PPC_SVR4(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool CC_PPC_SVR4_ByVal(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool CC_PPC_SVR4_Common(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool CC_PPC_SVR4_VarArg(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool RetCC_PPC(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State);
static bool CC_PPC_SVR4(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (LocVT == MVT::v16i8 ||
LocVT == MVT::v8i16 ||
LocVT == MVT::v4i32 ||
LocVT == MVT::v4f32) {
static const unsigned RegList1[] = {
PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
};
if (unsigned Reg = State.AllocateReg(RegList1, 12)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (!CC_PPC_SVR4_Common(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
return true; // CC didn't match.
}
static bool CC_PPC_SVR4_ByVal(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (ArgFlags.isByVal()) {
State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, 4, 4, ArgFlags);
return false;
}
if (CC_PPC_SVR4_Custom_Dummy(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
return true; // CC didn't match.
}
static bool CC_PPC_SVR4_Common(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (LocVT == MVT::i32) {
if (ArgFlags.isSplit()) {
if (CC_PPC_SVR4_Custom_AlignArgRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
}
}
if (LocVT == MVT::i32) {
static const unsigned RegList1[] = {
PPC::R3, PPC::R4, PPC::R5, PPC::R6, PPC::R7, PPC::R8, PPC::R9, PPC::R10
};
if (unsigned Reg = State.AllocateReg(RegList1, 8)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::f64) {
if (ArgFlags.isSplit()) {
if (CC_PPC_SVR4_Custom_AlignFPArgRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
}
}
if (LocVT == MVT::f32 ||
LocVT == MVT::f64) {
static const unsigned RegList2[] = {
PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, PPC::F8
};
if (unsigned Reg = State.AllocateReg(RegList2, 8)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::i32) {
if (ArgFlags.isSplit()) {
unsigned Offset3 = State.AllocateStack(4, 8);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset3, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::i32) {
unsigned Offset4 = State.AllocateStack(4, 4);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
return false;
}
if (LocVT == MVT::f32 ||
LocVT == MVT::f64) {
unsigned Offset5 = State.AllocateStack(8, 8);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
return false;
}
if (LocVT == MVT::v16i8 ||
LocVT == MVT::v8i16 ||
LocVT == MVT::v4i32 ||
LocVT == MVT::v4f32) {
unsigned Offset6 = State.AllocateStack(16, 16);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset6, LocVT, LocInfo));
return false;
}
return true; // CC didn't match.
}
static bool CC_PPC_SVR4_VarArg(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (!CC_PPC_SVR4_Common(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
return false;
return true; // CC didn't match.
}
static bool RetCC_PPC(unsigned ValNo, EVT ValVT,
EVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
if (LocVT == MVT::i32) {
static const unsigned RegList1[] = {
PPC::R3, PPC::R4, PPC::R5, PPC::R6, PPC::R7, PPC::R8, PPC::R9, PPC::R10
};
if (unsigned Reg = State.AllocateReg(RegList1, 8)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::i64) {
static const unsigned RegList2[] = {
PPC::X3, PPC::X4, PPC::X5, PPC::X6
};
if (unsigned Reg = State.AllocateReg(RegList2, 4)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::f32) {
if (unsigned Reg = State.AllocateReg(PPC::F1)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::f64) {
static const unsigned RegList3[] = {
PPC::F1, PPC::F2
};
if (unsigned Reg = State.AllocateReg(RegList3, 2)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
if (LocVT == MVT::v16i8 ||
LocVT == MVT::v8i16 ||
LocVT == MVT::v4i32 ||
LocVT == MVT::v4f32) {
if (unsigned Reg = State.AllocateReg(PPC::V2)) {
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
}
return true; // CC didn't match.
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

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