removed unused test files (#4648)

This commit is contained in:
Oliver Stöneberg 2022-12-18 19:36:37 +01:00 committed by GitHub
parent 98b3d66684
commit 0ed98c8f29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
124 changed files with 5 additions and 81625 deletions

View File

@ -7,4 +7,3 @@ exclude_paths:
- test/test.cxx
- test/cfg/*.c
- test/cfg/*.cpp
- test/synthetic/*.c

View File

@ -366,7 +366,7 @@ man/cppcheck.1: $(MAN_SOURCE)
$(XP) $(DB2MAN) $(MAN_SOURCE)
tags:
ctags -R --exclude=doxyoutput --exclude=test/cfg --exclude=test/synthetic cli externals gui lib test
ctags -R --exclude=doxyoutput --exclude=test/cfg cli externals gui lib test
install: cppcheck
install -d ${BIN}

View File

@ -1,22 +0,0 @@
==========
Benchmarks
==========
In this file we can document some good code repos / code samples to use when working on optimisations.
Trac tickets
------------
http://trac.cppcheck.net/ticket/2435 -- Tokenizer::simplifyTypedef
http://trac.cppcheck.net/ticket/8355 -- TokenList::createAst
http://trac.cppcheck.net/ticket/9007 -- Unused types
Repos
-----
Small C++ library with lots of templates:
https://framagit.org/dtschump/CImg
Just check the file examples/use_tinymatwriter.cpp

View File

@ -1,16 +0,0 @@
// Reduced source code. Inspired by this fix:
// https://github.com/EOSIO/eos/pull/4112/commits/ef62761c5e388880e8bb1bb41e8b512a5187f255
#include <set>
class C
{
std::set<int> typedefs;
bool is_type(int type) const
{
if (typedefs.find(type) != typedefs.end())
return is_type(type); // BUG: endless recursion
return false;
}
};

View File

@ -1,15 +0,0 @@
// CVE: CVE-2018-6836
// This is a simplified code example based on CVE-2018-11360.
void *malloc(unsigned long);
void free(void *);
void f(int size)
{
char *ia5_string = malloc(size); // Hint: Off by one
for (int i = 0; i <= size; i++)
ia5_string[i]=0; // BUG
free(ia5_string);
}

View File

@ -1,9 +0,0 @@
// CVE-2018-5334
#define LEN 100
void f(const int *m_ptr, int sig_off, int rec_size)
{
if (m_ptr[sig_off] == 0xdd && (sig_off + 15 <= (rec_size - LEN))) {}
}

View File

@ -1,30 +0,0 @@
// Bug: free uninitialized pointer
// Fix: https://code.wireshark.org/review/gitweb?p=wireshark.git;a=commit;h=28960d79cca262ac6b974f339697b299a1e28fef
void *malloc(unsigned long);
void free(void *);
struct comment {
int *data;
};
struct table {
struct comment *com;
};
void destroy_table(struct table *comment_table)
{
free(comment_table->com->data);
free(comment_table->com);
free(comment_table);
}
void f()
{
struct table *comment_table = (struct table *)malloc(sizeof(struct table));
struct comment *comment_rec = (struct comment *)malloc(sizeof(struct comment));
comment_table->com = comment_rec;
destroy_table(comment_table);
}

View File

@ -1,31 +0,0 @@
#!/bin/bash
# Fetch CVE issues that are interesting to look at
echo "CVE" > cve.txt
for i in $(seq 1 20);
do
echo "page $i"
# CVE 119 issues:
# https://www.cvedetails.com/vulnerability-list/cweid-119/vulnerabilities.html
# Use curl to get page $i:
curl -s "https://www.cvedetails.com/vulnerability-list.php?vendor_id=0&product_id=0&version_id=0&page=$i&hasexp=0&opdos=0&opec=0&opov=0&opcsrf=0&opgpriv=0&opsqli=0&opxss=0&opdirt=0&opmemc=0&ophttprs=0&opbyp=0&opfileinc=0&opginf=0&cvssscoremin=0&cvssscoremax=0&year=0&month=0&cweid=119&order=1&trc=11185&sha=a76f56dbb935840fc028b135d550322223547356" > v.html
# for each cve:
for cve in $(grep /cve/CVE-2018- v.html | sed 's|.*/cve/CVE-2018-\([0-9]*\).*|CVE-2018-\1|'); do
echo "$cve" >> cve.txt
curl -s "https://www.cvedetails.com/cve/$cve/" > download-cve
# cve type
cat download-cve | grep '>Overflow<' >> cve.txt
# is there a code reference?
cat download-cve | grep 'https*://.*[a-f0-9]\{30,50\}' | sed 's|.*\(https*://[^ ]*[a-f0-9]\{30,\}\).*|\1|' >> cve.txt
# is there a pull request reference?
cat download-cve | grep 'https*://github.com/[^ ]*/pull/' | sed 's|.*\(https*://github.com/[^ ]*\).*|\1|' >> cve.txt
done
done
rm v.html
rm download-cve

View File

@ -1,22 +0,0 @@
Background
==========
The CVE database contains known vulnerabilities in various source code projects. For instance, to list known "overflow" vulnerabilities, this link can be used:
https://www.cvedetails.com/vulnerability-list/cweid-119/vulnerabilities.html
Many issues in the CVE database are "out of reach" for static analysis because of required domain knowledge etc.
However there are also issues that could be "possible" to detect with static analysis.
For each such issue that we see that we think is "possible" to detect with static analysis, we can create a file in this folder. The filename is the CVE id. The contents of the file should contain this info:
* Recommended: URL that can be used to download source code, file with bug
* Description
* Reduced example code. The code should be plain C/C++ without dependencies.
Possible usages:
================
The test cases can inspire future Cppcheck development.
These files could be used for a quick and easy tool evaluation. For Cppcheck and other tools. Because only plain C/C++ is used, tools should have all info they need, so hopefully no extra configuration is needed.
An extended tool evaluation can use the real source code. It's possible to lookup the real source code using the CWE id. However in such tool evaluation, the tools must be configured properly.

View File

@ -1,4 +1,3 @@
add_subdirectory(benchmark)
add_subdirectory(cppchecklibrarydata)
add_subdirectory(filelist)
add_subdirectory(projectfile)

View File

@ -1 +0,0 @@
add_subdirectory(simple)

View File

@ -1,4 +0,0 @@
CONFIG += ordered
TEMPLATE = subdirs
SUBDIRS = simple

View File

@ -1,30 +0,0 @@
qt_wrap_cpp(test-benchmark-simple_SRC benchmarksimple.h)
add_custom_target(build-testbenchmark-simple-deps SOURCES ${test-benchmark-simple_SRC})
add_dependencies(gui-build-deps build-testbenchmark-simple-deps)
if(USE_BUNDLED_TINYXML2)
list(APPEND test-benchmark-simple_SRC $<TARGET_OBJECTS:tinyxml2_objs>)
endif()
add_executable(benchmark-simple
${test-benchmark-simple_SRC}
benchmarksimple.cpp
$<TARGET_OBJECTS:lib_objs>
$<TARGET_OBJECTS:simplecpp_objs>
)
target_include_directories(benchmark-simple PRIVATE ${CMAKE_SOURCE_DIR}/lib)
target_compile_definitions(benchmark-simple PRIVATE SRCDIR="${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(benchmark-simple ${QT_CORE_LIB} ${QT_TEST_LIB})
if (HAVE_RULES)
target_link_libraries(benchmark-simple ${PCRE_LIBRARY})
endif()
if(tinyxml2_FOUND AND NOT USE_BUNDLED_TINYXML2)
target_link_libraries(benchmark-simple ${tinyxml2_LIBRARIES})
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14)
# false positive in up to CLang 13 - caused by QBENCHMARK macro
set_source_files_properties(benchmarksimple.cpp PROPERTIES COMPILE_FLAGS -Wno-reserved-identifier)
endif()
# caused by Q_UNUSED macro
set_source_files_properties(moc_benchmarksimple.cpp PROPERTIES COMPILE_FLAGS -Wno-extra-semi-stmt)
endif()

View File

@ -1,47 +0,0 @@
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "benchmarksimple.h"
#include "settings.h"
#include "tokenize.h"
#include <sstream>
#include <QByteArray>
#include <QFile>
#include <QString>
#include <QtTest>
void BenchmarkSimple::tokenize()
{
QFile file(QString(SRCDIR) + "/../../data/benchmark/simple.cpp");
QByteArray data = file.readAll();
Settings settings;
settings.debugwarnings = true;
// tokenize..
Tokenizer tokenizer(&settings, this);
std::istringstream istr(data.constData());
QBENCHMARK {
tokenizer.tokenize(istr, "test.cpp");
}
}
QTEST_MAIN(BenchmarkSimple)

View File

@ -1,37 +0,0 @@
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "color.h"
#include "errorlogger.h"
#include <string>
#include <QObject>
class BenchmarkSimple : public QObject, public ErrorLogger {
Q_OBJECT
private slots:
void tokenize();
private:
// Empty implementations of ErrorLogger methods.
// We don't care about the output in the benchmark tests.
void reportOut(const std::string & /*outmsg*/, Color /*c*/ = Color::Reset) override {}
void reportErr(const ErrorMessage & /*msg*/) override {}
};

View File

@ -1,15 +0,0 @@
TEMPLATE = app
TARGET = benchmark-simple
DEPENDPATH += .
INCLUDEPATH += .
OBJECTS_DIR = ../../../temp
MOC_DIR = ../../temp
include(../../common.pri)
DEFINES += SRCDIR=\\\"$$PWD\\\"
# tests
SOURCES += benchmarksimple.cpp
HEADERS += benchmarksimple.h

View File

@ -1,4 +1,4 @@
GUI tests + benchmark tests
GUI tests
===========================
As the GUI uses Qt framework, the GUI tests also use Qt's Testlib. This is

View File

@ -40,7 +40,7 @@ validate_html "$INDEX_HTML"
validate_html "$STATS_HTML"
../cppcheck ../test/synthetic --enable=all --inconclusive --xml-version=2 2> "$GUI_TEST_XML"
../cppcheck ../samples --enable=all --inconclusive --xml-version=2 2> "$GUI_TEST_XML"
xmllint --noout "$GUI_TEST_XML"
$PYTHON cppcheck-htmlreport --file "$GUI_TEST_XML" --title "xml2 + inconclusive test" --report-dir "$REPORT_DIR"
echo ""
@ -49,7 +49,7 @@ validate_html "$INDEX_HTML"
validate_html "$STATS_HTML"
../cppcheck ../test/synthetic --enable=all --inconclusive --verbose --xml-version=2 2> "$GUI_TEST_XML"
../cppcheck ../samples --enable=all --inconclusive --verbose --xml-version=2 2> "$GUI_TEST_XML"
xmllint --noout "$GUI_TEST_XML"
$PYTHON cppcheck-htmlreport --file "$GUI_TEST_XML" --title "xml2 + inconclusive + verbose test" --report-dir "$REPORT_DIR"
echo -e "\n"

View File

@ -1,73 +0,0 @@
# Test if --bug-hunting works using cve tests
import glob
import logging
import os
import sys
import subprocess
if sys.argv[0] in ('test/bug-hunting/cve.py', './test/bug-hunting/cve.py'):
CPPCHECK_PATH = './cppcheck'
TEST_SUITE = 'test/bug-hunting/cve'
else:
CPPCHECK_PATH = '../../cppcheck'
TEST_SUITE = 'cve'
slow = '--slow' in sys.argv
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S')
def test(test_folder):
logging.info(test_folder)
cmd_file = os.path.join(test_folder, 'cmd.txt')
expected_file = os.path.join(test_folder, 'expected.txt')
cmd = ['nice',
CPPCHECK_PATH,
'-D__GNUC__',
'--bug-hunting',
'--inconclusive',
'--platform=unix64',
'--template={file}:{line}:{id}',
'-rp=' + test_folder]
if os.path.isfile(cmd_file):
for line in open(cmd_file, 'rt'):
if len(line) > 1:
cmd.append(line.strip())
cmd.append(test_folder)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
comm = p.communicate()
stdout = comm[0].decode(encoding='utf-8', errors='ignore')
stderr = comm[1].decode(encoding='utf-8', errors='ignore')
with open(expected_file, 'rt') as f:
for expected in f.readlines():
if expected.strip() not in stderr.split('\n'):
print('FAILED. Expected result not found: ' + expected)
print('Command:')
print(' '.join(cmd))
print('Output:')
print(stderr)
sys.exit(1)
if (slow is False) and len(sys.argv) > 1:
test(sys.argv[1])
sys.exit(0)
SLOW = []
for test_folder in sorted(glob.glob(TEST_SUITE + '/CVE*')):
if slow is False:
check = False
for s in SLOW:
if s in test_folder:
check = True
if check is True:
logging.info('skipping %s', test_folder)
continue
test(test_folder)

View File

@ -1,6 +0,0 @@
Project:
Qt
Details:
https://nvd.nist.gov/vuln/detail/CVE-2018-19872

View File

@ -1,2 +0,0 @@
qppmhandler.cpp:223:bughuntingDivByZero
qppmhandler.cpp:255:bughuntingDivByZero

View File

@ -1,579 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "private/qppmhandler_p.h"
#ifndef QT_NO_IMAGEFORMAT_PPM
#include <qimage.h>
#include <qvariant.h>
#include <qvector.h>
#include <ctype.h>
#include <qrgba64.h>
QT_BEGIN_NAMESPACE
/*****************************************************************************
PBM/PGM/PPM (ASCII and RAW) image read/write functions
*****************************************************************************/
static void discard_pbm_line(QIODevice *d)
{
const int buflen = 100;
char buf[buflen];
int res = 0;
do {
res = d->readLine(buf, buflen);
} while (res > 0 && buf[res-1] != '\n');
}
static int read_pbm_int(QIODevice *d)
{
char c;
int val = -1;
bool digit;
for (;;) {
if (!d->getChar(&c)) // end of file
break;
digit = isdigit((uchar) c);
if (val != -1) {
if (digit) {
val = 10*val + c - '0';
continue;
} else {
if (c == '#') // comment
discard_pbm_line(d);
break;
}
}
if (digit) // first digit
val = c - '0';
else if (isspace((uchar) c))
continue;
else if (c == '#')
discard_pbm_line(d);
else
break;
}
return val;
}
static bool read_pbm_header(QIODevice *device, char& type, int& w, int& h, int& mcc)
{
char buf[3];
if (device->read(buf, 3) != 3) // read P[1-6]<white-space>
return false;
if (!(buf[0] == 'P' && isdigit((uchar) buf[1]) && isspace((uchar) buf[2])))
return false;
type = buf[1];
if (type < '1' || type > '6')
return false;
w = read_pbm_int(device); // get image width
h = read_pbm_int(device); // get image height
if (type == '1' || type == '4')
mcc = 1; // ignore max color component
else
mcc = read_pbm_int(device); // get max color component
if (w <= 0 || w > 32767 || h <= 0 || h > 32767 || mcc <= 0)
return false; // weird P.M image
return true;
}
static inline QRgb scale_pbm_color(quint16 mx, quint16 rv, quint16 gv, quint16 bv)
{
return QRgba64::fromRgba64((rv * 0xffff) / mx, (gv * 0xffff) / mx, (bv * 0xffff) / mx, 0xffff).toArgb32();
}
static bool read_pbm_body(QIODevice *device, char type, int w, int h, int mcc, QImage *outImage)
{
int nbits, y;
int pbm_bpl;
bool raw;
QImage::Format format;
switch (type) {
case '1': // ascii PBM
case '4': // raw PBM
nbits = 1;
format = QImage::Format_Mono;
break;
case '2': // ascii PGM
case '5': // raw PGM
nbits = 8;
format = QImage::Format_Grayscale8;
break;
case '3': // ascii PPM
case '6': // raw PPM
nbits = 32;
format = QImage::Format_RGB32;
break;
default:
return false;
}
raw = type >= '4';
if (outImage->size() != QSize(w, h) || outImage->format() != format) {
*outImage = QImage(w, h, format);
if (outImage->isNull())
return false;
}
pbm_bpl = (nbits*w+7)/8; // bytes per scanline in PBM
if (raw) { // read raw data
if (nbits == 32) { // type 6
pbm_bpl = mcc < 256 ? 3*w : 6*w;
uchar *buf24 = new uchar[pbm_bpl], *b;
QRgb *p;
QRgb *end;
for (y=0; y<h; y++) {
if (device->read((char *)buf24, pbm_bpl) != pbm_bpl) {
delete[] buf24;
return false;
}
p = (QRgb *)outImage->scanLine(y);
end = p + w;
b = buf24;
while (p < end) {
if (mcc < 256) {
if (mcc == 255)
*p++ = qRgb(b[0],b[1],b[2]);
else
*p++ = scale_pbm_color(mcc, b[0], b[1], b[2]);
b += 3;
} else {
quint16 rv = b[0] << 8 | b[1];
quint16 gv = b[2] << 8 | b[3];
quint16 bv = b[4] << 8 | b[5];
if (mcc == 0xffff)
*p++ = QRgba64::fromRgba64(rv, gv, bv, 0xffff).toArgb32();
else
*p++ = scale_pbm_color(mcc, rv, gv, bv);
b += 6;
}
}
}
delete[] buf24;
} else if (nbits == 8 && mcc > 255) { // type 5 16bit
pbm_bpl = 2*w;
uchar *buf16 = new uchar[pbm_bpl];
for (y=0; y<h; y++) {
if (device->read((char *)buf16, pbm_bpl) != pbm_bpl) {
delete[] buf16;
return false;
}
uchar *p = outImage->scanLine(y);
uchar *end = p + w;
uchar *b = buf16;
while (p < end) {
*p++ = (b[0] << 8 | b[1]) * 255 / mcc;
b += 2;
}
}
delete[] buf16;
} else { // type 4,5
for (y=0; y<h; y++) {
uchar *p = outImage->scanLine(y);
if (device->read((char *)p, pbm_bpl) != pbm_bpl)
return false;
if (nbits == 8 && mcc < 255) {
for (int i = 0; i < pbm_bpl; i++)
p[i] = (p[i] * 255) / mcc;
}
}
}
} else { // read ascii data
uchar *p;
int n;
char buf;
for (y = 0; (y < h) && (device->peek(&buf, 1) == 1); y++) {
p = outImage->scanLine(y);
n = pbm_bpl;
if (nbits == 1) {
int b;
int bitsLeft = w;
while (n--) {
b = 0;
for (int i=0; i<8; i++) {
if (i < bitsLeft)
b = (b << 1) | (read_pbm_int(device) & 1);
else
b = (b << 1) | (0 & 1); // pad it our self if we need to
}
bitsLeft -= 8;
*p++ = b;
}
} else if (nbits == 8) {
if (mcc == 255) {
while (n--) {
*p++ = read_pbm_int(device);
}
} else {
while (n--) {
*p++ = read_pbm_int(device) * 255 / mcc;
}
}
} else { // 32 bits
n /= 4;
int r, g, b;
if (mcc == 255) {
while (n--) {
r = read_pbm_int(device);
g = read_pbm_int(device);
b = read_pbm_int(device);
*((QRgb*)p) = qRgb(r, g, b);
p += 4;
}
} else {
while (n--) {
r = read_pbm_int(device);
g = read_pbm_int(device);
b = read_pbm_int(device);
*((QRgb*)p) = scale_pbm_color(mcc, r, g, b);
p += 4;
}
}
}
}
}
if (format == QImage::Format_Mono) {
outImage->setColorCount(2);
outImage->setColor(0, qRgb(255,255,255)); // white
outImage->setColor(1, qRgb(0,0,0)); // black
}
return true;
}
static bool write_pbm_image(QIODevice *out, const QImage &sourceImage, const QByteArray &sourceFormat)
{
QByteArray str;
QImage image = sourceImage;
QByteArray format = sourceFormat;
format = format.left(3); // ignore RAW part
bool gray = format == "pgm";
if (format == "pbm") {
image = image.convertToFormat(QImage::Format_Mono);
} else if (gray) {
image = image.convertToFormat(QImage::Format_Grayscale8);
} else {
switch (image.format()) {
case QImage::Format_Mono:
case QImage::Format_MonoLSB:
image = image.convertToFormat(QImage::Format_Indexed8);
break;
case QImage::Format_Indexed8:
case QImage::Format_RGB32:
case QImage::Format_ARGB32:
break;
default:
if (image.hasAlphaChannel())
image = image.convertToFormat(QImage::Format_ARGB32);
else
image = image.convertToFormat(QImage::Format_RGB32);
break;
}
}
if (image.depth() == 1 && image.colorCount() == 2) {
if (qGray(image.color(0)) < qGray(image.color(1))) {
// 0=dark/black, 1=light/white - invert
image.detach();
for (int y=0; y<image.height(); y++) {
uchar *p = image.scanLine(y);
uchar *end = p + image.bytesPerLine();
while (p < end)
*p++ ^= 0xff;
}
}
}
uint w = image.width();
uint h = image.height();
str = "P\n";
str += QByteArray::number(w);
str += ' ';
str += QByteArray::number(h);
str += '\n';
switch (image.depth()) {
case 1: {
str.insert(1, '4');
if (out->write(str, str.length()) != str.length())
return false;
w = (w+7)/8;
for (uint y=0; y<h; y++) {
uchar* line = image.scanLine(y);
if (w != (uint)out->write((char*)line, w))
return false;
}
}
break;
case 8: {
str.insert(1, gray ? '5' : '6');
str.append("255\n");
if (out->write(str, str.length()) != str.length())
return false;
uint bpl = w * (gray ? 1 : 3);
uchar *buf = new uchar[bpl];
if (image.format() == QImage::Format_Indexed8) {
QVector<QRgb> color = image.colorTable();
for (uint y=0; y<h; y++) {
const uchar *b = image.constScanLine(y);
uchar *p = buf;
uchar *end = buf+bpl;
if (gray) {
while (p < end) {
uchar g = (uchar)qGray(color[*b++]);
*p++ = g;
}
} else {
while (p < end) {
QRgb rgb = color[*b++];
*p++ = qRed(rgb);
*p++ = qGreen(rgb);
*p++ = qBlue(rgb);
}
}
if (bpl != (uint)out->write((char*)buf, bpl))
return false;
}
} else {
for (uint y=0; y<h; y++) {
const uchar *b = image.constScanLine(y);
uchar *p = buf;
uchar *end = buf + bpl;
if (gray) {
while (p < end)
*p++ = *b++;
} else {
while (p < end) {
uchar color = *b++;
*p++ = color;
*p++ = color;
*p++ = color;
}
}
if (bpl != (uint)out->write((char*)buf, bpl))
return false;
}
}
delete[] buf;
break;
}
case 32: {
str.insert(1, '6');
str.append("255\n");
if (out->write(str, str.length()) != str.length())
return false;
uint bpl = w * 3;
uchar *buf = new uchar[bpl];
for (uint y=0; y<h; y++) {
const QRgb *b = reinterpret_cast<const QRgb *>(image.constScanLine(y));
uchar *p = buf;
uchar *end = buf+bpl;
while (p < end) {
QRgb rgb = *b++;
*p++ = qRed(rgb);
*p++ = qGreen(rgb);
*p++ = qBlue(rgb);
}
if (bpl != (uint)out->write((char*)buf, bpl))
return false;
}
delete[] buf;
break;
}
default:
return false;
}
return true;
}
QPpmHandler::QPpmHandler()
: state(Ready)
{}
bool QPpmHandler::readHeader()
{
state = Error;
if (!read_pbm_header(device(), type, width, height, mcc))
return false;
state = ReadHeader;
return true;
}
bool QPpmHandler::canRead() const
{
if (state == Ready && !canRead(device(), &subType))
return false;
if (state != Error) {
setFormat(subType);
return true;
}
return false;
}
bool QPpmHandler::canRead(QIODevice *device, QByteArray *subType)
{
if (!device) {
qWarning("QPpmHandler::canRead() called with no device");
return false;
}
char head[2];
if (device->peek(head, sizeof(head)) != sizeof(head))
return false;
if (head[0] != 'P')
return false;
if (head[1] == '1' || head[1] == '4') {
if (subType)
*subType = "pbm";
} else if (head[1] == '2' || head[1] == '5') {
if (subType)
*subType = "pgm";
} else if (head[1] == '3' || head[1] == '6') {
if (subType)
*subType = "ppm";
} else {
return false;
}
return true;
}
bool QPpmHandler::read(QImage *image)
{
if (state == Error)
return false;
if (state == Ready && !readHeader()) {
state = Error;
return false;
}
if (!read_pbm_body(device(), type, width, height, mcc, image)) {
state = Error;
return false;
}
state = Ready;
return true;
}
bool QPpmHandler::write(const QImage &image)
{
return write_pbm_image(device(), image, subType);
}
bool QPpmHandler::supportsOption(ImageOption option) const
{
return option == SubType
|| option == Size
|| option == ImageFormat;
}
QVariant QPpmHandler::option(ImageOption option) const
{
if (option == SubType) {
return subType;
} else if (option == Size) {
if (state == Error)
return QVariant();
if (state == Ready && !const_cast<QPpmHandler*>(this)->readHeader())
return QVariant();
return QSize(width, height);
} else if (option == ImageFormat) {
if (state == Error)
return QVariant();
if (state == Ready && !const_cast<QPpmHandler*>(this)->readHeader())
return QVariant();
QImage::Format format = QImage::Format_Invalid;
switch (type) {
case '1': // ascii PBM
case '4': // raw PBM
format = QImage::Format_Mono;
break;
case '2': // ascii PGM
case '5': // raw PGM
format = QImage::Format_Grayscale8;
break;
case '3': // ascii PPM
case '6': // raw PPM
format = QImage::Format_RGB32;
break;
default:
break;
}
return format;
}
return QVariant();
}
void QPpmHandler::setOption(ImageOption option, const QVariant &value)
{
if (option == SubType)
subType = value.toByteArray().toLower();
}
QByteArray QPpmHandler::name() const
{
return subType.isEmpty() ? QByteArray("ppm") : subType;
}
QT_END_NAMESPACE
#endif // QT_NO_IMAGEFORMAT_PPM

View File

@ -1,3 +0,0 @@
pi.c:426:bughuntingDivByZero
pi.c:430:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,310 +0,0 @@
//========================================================================
//
// Function.h
//
// Copyright 2001-2003 Glyph & Cog, LLC
//
//========================================================================
#ifndef FUNCTION_H
#define FUNCTION_H
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include "gtypes.h"
#include "Object.h"
class GList;
class Dict;
class Stream;
struct PSCode;
//------------------------------------------------------------------------
// Function
//------------------------------------------------------------------------
#define funcMaxInputs 32
#define funcMaxOutputs 32
#define sampledFuncMaxInputs 16
class Function {
public:
Function();
virtual ~Function();
// Construct a function. Returns NULL if unsuccessful.
static Function *parse(Object *funcObj, int recursion = 0);
// Initialize the entries common to all function types.
GBool init(Dict *dict);
virtual Function *copy() = 0;
// Return the function type:
// -1 : identity
// 0 : sampled
// 2 : exponential
// 3 : stitching
// 4 : PostScript
virtual int getType() = 0;
// Return size of input and output tuples.
int getInputSize() {
return m;
}
int getOutputSize() {
return n;
}
double getDomainMin(int i) {
return domain[i][0];
}
double getDomainMax(int i) {
return domain[i][1];
}
double getRangeMin(int i) {
return range[i][0];
}
double getRangeMax(int i) {
return range[i][1];
}
GBool getHasRange() {
return hasRange;
}
// Transform an input tuple into an output tuple.
virtual void transform(double *in, double *out) = 0;
virtual GBool isOk() = 0;
protected:
int m, n; // size of input and output tuples
double // min and max values for function domain
domain[funcMaxInputs][2];
double // min and max values for function range
range[funcMaxOutputs][2];
GBool hasRange; // set if range is defined
};
//------------------------------------------------------------------------
// IdentityFunction
//------------------------------------------------------------------------
class IdentityFunction : public Function {
public:
IdentityFunction();
virtual ~IdentityFunction();
virtual Function *copy() {
return new IdentityFunction();
}
virtual int getType() {
return -1;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return gTrue;
}
private:
};
//------------------------------------------------------------------------
// SampledFunction
//------------------------------------------------------------------------
class SampledFunction : public Function {
public:
SampledFunction(Object *funcObj, Dict *dict);
virtual ~SampledFunction();
virtual Function *copy() {
return new SampledFunction(this);
}
virtual int getType() {
return 0;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
int getSampleSize(int i) {
return sampleSize[i];
}
double getEncodeMin(int i) {
return encode[i][0];
}
double getEncodeMax(int i) {
return encode[i][1];
}
double getDecodeMin(int i) {
return decode[i][0];
}
double getDecodeMax(int i) {
return decode[i][1];
}
double *getSamples() {
return samples;
}
private:
SampledFunction(SampledFunction *func);
int // number of samples for each domain element
sampleSize[funcMaxInputs];
double // min and max values for domain encoder
encode[funcMaxInputs][2];
double // min and max values for range decoder
decode[funcMaxOutputs][2];
double // input multipliers
inputMul[funcMaxInputs];
int *idxOffset;
double *samples; // the samples
int nSamples; // size of the samples array
double *sBuf; // buffer for the transform function
double cacheIn[funcMaxInputs];
double cacheOut[funcMaxOutputs];
GBool ok;
};
//------------------------------------------------------------------------
// ExponentialFunction
//------------------------------------------------------------------------
class ExponentialFunction : public Function {
public:
ExponentialFunction(Object *funcObj, Dict *dict);
virtual ~ExponentialFunction();
virtual Function *copy() {
return new ExponentialFunction(this);
}
virtual int getType() {
return 2;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
double *getC0() {
return c0;
}
double *getC1() {
return c1;
}
double getE() {
return e;
}
private:
ExponentialFunction(ExponentialFunction *func);
double c0[funcMaxOutputs];
double c1[funcMaxOutputs];
double e;
GBool ok;
};
//------------------------------------------------------------------------
// StitchingFunction
//------------------------------------------------------------------------
class StitchingFunction : public Function {
public:
StitchingFunction(Object *funcObj, Dict *dict, int recursion);
virtual ~StitchingFunction();
virtual Function *copy() {
return new StitchingFunction(this);
}
virtual int getType() {
return 3;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
int getNumFuncs() {
return k;
}
Function *getFunc(int i) {
return funcs[i];
}
double *getBounds() {
return bounds;
}
double *getEncode() {
return encode;
}
double *getScale() {
return scale;
}
private:
StitchingFunction(StitchingFunction *func);
int k;
Function **funcs;
double *bounds;
double *encode;
double *scale;
GBool ok;
};
//------------------------------------------------------------------------
// PostScriptFunction
//------------------------------------------------------------------------
class PostScriptFunction : public Function {
public:
PostScriptFunction(Object *funcObj, Dict *dict);
virtual ~PostScriptFunction();
virtual Function *copy() {
return new PostScriptFunction(this);
}
virtual int getType() {
return 4;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
GString *getCodeString() {
return codeString;
}
private:
PostScriptFunction(PostScriptFunction *func);
GBool parseCode(GList *tokens, int *tokPtr, int *codePtr);
void addCode(int *codePtr, int op);
void addCodeI(int *codePtr, int op, int x);
void addCodeD(int *codePtr, int op, double x);
GString *getToken(Stream *str);
int exec(double *stack, int sp0);
GString *codeString;
PSCode *code;
int codeLen;
int codeSize;
double cacheIn[funcMaxInputs];
double cacheOut[funcMaxOutputs];
GBool ok;
};
#endif

View File

@ -1,2 +0,0 @@
Function.cc:1374:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,539 +0,0 @@
//========================================================================
//
// PSOutputDev.h
//
// Copyright 1996-2003 Glyph & Cog, LLC
//
//========================================================================
#ifndef PSOUTPUTDEV_H
#define PSOUTPUTDEV_H
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include <stddef.h>
#include "config.h"
#include "Object.h"
#include "GlobalParams.h"
#include "OutputDev.h"
class GHash;
class PDFDoc;
class XRef;
class Function;
class GfxPath;
class GfxFont;
class GfxColorSpace;
class GfxDeviceGrayColorSpace;
class GfxCalGrayColorSpace;
class GfxDeviceRGBColorSpace;
class GfxCalRGBColorSpace;
class GfxDeviceCMYKColorSpace;
class GfxLabColorSpace;
class GfxICCBasedColorSpace;
class GfxIndexedColorSpace;
class GfxSeparationColorSpace;
class GfxDeviceNColorSpace;
class PDFRectangle;
class PSOutCustomColor;
class PSOutputDev;
class PSFontFileInfo;
//------------------------------------------------------------------------
// PSOutputDev
//------------------------------------------------------------------------
enum PSOutMode {
psModePS,
psModeEPS,
psModeForm
};
enum PSFileType {
psFile, // write to file
psPipe, // write to pipe
psStdout, // write to stdout
psGeneric // write to a generic stream
};
enum PSOutCustomCodeLocation {
psOutCustomDocSetup,
psOutCustomPageSetup
};
typedef void (*PSOutputFunc)(void *stream, const char *data, int len);
typedef GString *(*PSOutCustomCodeCbk)(PSOutputDev *psOut,
PSOutCustomCodeLocation loc, int n,
void *data);
class PSOutputDev : public OutputDev {
public:
// Open a PostScript output file, and write the prolog.
PSOutputDev(char *fileName, PDFDoc *docA,
int firstPageA, int lastPageA, PSOutMode modeA,
int imgLLXA = 0, int imgLLYA = 0,
int imgURXA = 0, int imgURYA = 0,
GBool manualCtrlA = gFalse,
PSOutCustomCodeCbk customCodeCbkA = NULL,
void *customCodeCbkDataA = NULL,
GBool honorUserUnitA = gFalse);
// Open a PSOutputDev that will write to a generic stream.
PSOutputDev(PSOutputFunc outputFuncA, void *outputStreamA,
PDFDoc *docA,
int firstPageA, int lastPageA, PSOutMode modeA,
int imgLLXA = 0, int imgLLYA = 0,
int imgURXA = 0, int imgURYA = 0,
GBool manualCtrlA = gFalse,
PSOutCustomCodeCbk customCodeCbkA = NULL,
void *customCodeCbkDataA = NULL,
GBool honorUserUnitA = gFalse);
// Destructor -- writes the trailer and closes the file.
virtual ~PSOutputDev();
// Check if file was successfully created.
virtual GBool isOk() {
return ok;
}
// Returns false if there have been any errors on the output stream.
GBool checkIO();
//---- get info about output device
// Does this device use upside-down coordinates?
// (Upside-down means (0,0) is the top left corner of the page.)
virtual GBool upsideDown() {
return gFalse;
}
// Does this device use drawChar() or drawString()?
virtual GBool useDrawChar() {
return gFalse;
}
// Does this device use tilingPatternFill()? If this returns false,
// tiling pattern fills will be reduced to a series of other drawing
// operations.
virtual GBool useTilingPatternFill() {
return gTrue;
}
// Does this device use functionShadedFill(), axialShadedFill(), and
// radialShadedFill()? If this returns false, these shaded fills
// will be reduced to a series of other drawing operations.
virtual GBool useShadedFills()
{
return level == psLevel2 || level == psLevel2Sep ||
level == psLevel3 || level == psLevel3Sep;
}
// Does this device use drawForm()? If this returns false,
// form-type XObjects will be interpreted (i.e., unrolled).
virtual GBool useDrawForm() {
return preload;
}
// Does this device use beginType3Char/endType3Char? Otherwise,
// text in Type 3 fonts will be drawn with drawChar/drawString.
virtual GBool interpretType3Chars() {
return gFalse;
}
//----- header/trailer (used only if manualCtrl is true)
// Write the document-level header.
void writeHeader(PDFRectangle *mediaBox, PDFRectangle *cropBox,
int pageRotate);
// Write the Xpdf procset.
void writeXpdfProcset();
// Write the document-level setup.
void writeDocSetup(Catalog *catalog);
// Write the trailer for the current page.
void writePageTrailer();
// Write the document trailer.
void writeTrailer();
//----- initialization and control
// Check to see if a page slice should be displayed. If this
// returns false, the page display is aborted. Typically, an
// OutputDev will use some alternate means to display the page
// before returning false.
virtual GBool checkPageSlice(Page *page, double hDPI, double vDPI,
int rotate, GBool useMediaBox, GBool crop,
int sliceX, int sliceY, int sliceW, int sliceH,
GBool printing,
GBool (*abortCheckCbk)(void *data) = NULL,
void *abortCheckCbkData = NULL);
// Start a page.
virtual void startPage(int pageNum, GfxState *state);
// End a page.
virtual void endPage();
//----- save/restore graphics state
virtual void saveState(GfxState *state);
virtual void restoreState(GfxState *state);
//----- update graphics state
virtual void updateCTM(GfxState *state, double m11, double m12,
double m21, double m22, double m31, double m32);
virtual void updateLineDash(GfxState *state);
virtual void updateFlatness(GfxState *state);
virtual void updateLineJoin(GfxState *state);
virtual void updateLineCap(GfxState *state);
virtual void updateMiterLimit(GfxState *state);
virtual void updateLineWidth(GfxState *state);
virtual void updateFillColorSpace(GfxState *state);
virtual void updateStrokeColorSpace(GfxState *state);
virtual void updateFillColor(GfxState *state);
virtual void updateStrokeColor(GfxState *state);
virtual void updateFillOverprint(GfxState *state);
virtual void updateStrokeOverprint(GfxState *state);
virtual void updateOverprintMode(GfxState *state);
virtual void updateTransfer(GfxState *state);
//----- update text state
virtual void updateFont(GfxState *state);
virtual void updateTextMat(GfxState *state);
virtual void updateCharSpace(GfxState *state);
virtual void updateRender(GfxState *state);
virtual void updateRise(GfxState *state);
virtual void updateWordSpace(GfxState *state);
virtual void updateHorizScaling(GfxState *state);
virtual void updateTextPos(GfxState *state);
virtual void updateTextShift(GfxState *state, double shift);
virtual void saveTextPos(GfxState *state);
virtual void restoreTextPos(GfxState *state);
//----- path painting
virtual void stroke(GfxState *state);
virtual void fill(GfxState *state);
virtual void eoFill(GfxState *state);
virtual void tilingPatternFill(GfxState *state, Gfx *gfx, Object *strRef,
int paintType, int tilingType, Dict *resDict,
double *mat, double *bbox,
int x0, int y0, int x1, int y1,
double xStep, double yStep);
virtual GBool functionShadedFill(GfxState *state,
GfxFunctionShading *shading);
virtual GBool axialShadedFill(GfxState *state, GfxAxialShading *shading);
virtual GBool radialShadedFill(GfxState *state, GfxRadialShading *shading);
//----- path clipping
virtual void clip(GfxState *state);
virtual void eoClip(GfxState *state);
virtual void clipToStrokePath(GfxState *state);
//----- text drawing
virtual void drawString(GfxState *state, GString *s);
virtual void endTextObject(GfxState *state);
//----- image drawing
virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
int width, int height, GBool invert,
GBool inlineImg, GBool interpolate);
virtual void drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height, GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg, GBool interpolate);
virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr, int maskWidth, int maskHeight,
GBool maskInvert, GBool interpolate);
#if OPI_SUPPORT
//----- OPI functions
virtual void opiBegin(GfxState *state, Dict *opiDict);
virtual void opiEnd(GfxState *state, Dict *opiDict);
#endif
//----- Type 3 font operators
virtual void type3D0(GfxState *state, double wx, double wy);
virtual void type3D1(GfxState *state, double wx, double wy,
double llx, double lly, double urx, double ury);
//----- form XObjects
virtual void drawForm(Ref ref);
//----- PostScript XObjects
virtual void psXObject(Stream *psStream, Stream *level1Stream);
//----- miscellaneous
void setImageableArea(int imgLLXA, int imgLLYA, int imgURXA, int imgURYA)
{
imgLLX = imgLLXA; imgLLY = imgLLYA; imgURX = imgURXA; imgURY = imgURYA;
}
void setOffset(double x, double y)
{
tx0 = x; ty0 = y;
}
void setScale(double x, double y)
{
xScale0 = x; yScale0 = y;
}
void setRotate(int rotateA)
{
rotate0 = rotateA;
}
void setClip(double llx, double lly, double urx, double ury)
{
clipLLX0 = llx; clipLLY0 = lly; clipURX0 = urx; clipURY0 = ury;
}
void setUnderlayCbk(void (*cbk)(PSOutputDev *psOut, void *data),
void *data)
{
underlayCbk = cbk; underlayCbkData = data;
}
void setOverlayCbk(void (*cbk)(PSOutputDev *psOut, void *data),
void *data)
{
overlayCbk = cbk; overlayCbkData = data;
}
void writePSChar(char c);
void writePSBlock(char *s, int len);
void writePS(const char *s);
void writePSFmt(const char *fmt, ...);
void writePSString(GString *s);
void writePSName(const char *s);
private:
void init(PSOutputFunc outputFuncA, void *outputStreamA,
PSFileType fileTypeA, PDFDoc *docA,
int firstPageA, int lastPageA, PSOutMode modeA,
int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
GBool manualCtrlA, GBool honorUserUnitA);
GBool checkIfPageNeedsToBeRasterized(int pg);
void setupResources(Dict *resDict);
void setupFonts(Dict *resDict);
void setupFont(GfxFont *font, Dict *parentResDict);
PSFontFileInfo *setupEmbeddedType1Font(GfxFont *font, Ref *id);
PSFontFileInfo *setupExternalType1Font(GfxFont *font, GString *fileName);
PSFontFileInfo *setupEmbeddedType1CFont(GfxFont *font, Ref *id);
PSFontFileInfo *setupEmbeddedOpenTypeT1CFont(GfxFont *font, Ref *id);
PSFontFileInfo *setupEmbeddedTrueTypeFont(GfxFont *font, Ref *id);
PSFontFileInfo *setupExternalTrueTypeFont(GfxFont *font, GString *fileName,
int fontNum);
PSFontFileInfo *setupEmbeddedCIDType0Font(GfxFont *font, Ref *id);
PSFontFileInfo *setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
GBool needVerticalMetrics);
PSFontFileInfo *setupExternalCIDTrueTypeFont(GfxFont *font,
GString *fileName,
int fontNum,
GBool needVerticalMetrics);
PSFontFileInfo *setupEmbeddedOpenTypeCFFFont(GfxFont *font, Ref *id);
PSFontFileInfo *setupExternalOpenTypeCFFFont(GfxFont *font,
GString *fileName);
PSFontFileInfo *setupType3Font(GfxFont *font, Dict *parentResDict);
GString *makePSFontName(GfxFont *font, Ref *id);
GString *fixType1Font(GString *font, int length1, int length2);
GBool splitType1PFA(Guchar *font, int fontSize,
int length1, int length2,
GString *textSection, GString *binSection);
GBool splitType1PFB(Guchar *font, int fontSize,
GString *textSection, GString *binSection);
GString *asciiHexDecodeType1EexecSection(GString *in);
GBool fixType1EexecSection(GString *binSection, GString *out);
GString *copyType1PFA(Guchar *font, int fontSize);
GString *copyType1PFB(Guchar *font, int fontSize);
void renameType1Font(GString *font, GString *name);
void setupDefaultFont();
void setupImages(Dict *resDict);
void setupImage(Ref id, Stream *str, GBool mask, Array *colorKeyMask);
void setupForms(Dict *resDict);
void setupForm(Object *strRef, Object *strObj);
void addProcessColor(double c, double m, double y, double k);
void addCustomColor(GfxState *state, GfxSeparationColorSpace *sepCS);
void addCustomColors(GfxState *state, GfxDeviceNColorSpace *devnCS);
void tilingPatternFillL1(GfxState *state, Gfx *gfx, Object *strRef,
int paintType, int tilingType, Dict *resDict,
double *mat, double *bbox,
int x0, int y0, int x1, int y1,
double xStep, double yStep);
void tilingPatternFillL2(GfxState *state, Gfx *gfx, Object *strRef,
int paintType, int tilingType, Dict *resDict,
double *mat, double *bbox,
int x0, int y0, int x1, int y1,
double xStep, double yStep);
void doPath(GfxPath *path);
void doImageL1(Object *ref, GfxState *state,
GfxImageColorMap *colorMap,
GBool invert, GBool inlineImg,
Stream *str, int width, int height, int len);
void doImageL1Sep(GfxState *state, GfxImageColorMap *colorMap,
GBool invert, GBool inlineImg,
Stream *str, int width, int height, int len);
void doImageL2(Object *ref, GfxState *state,
GfxImageColorMap *colorMap,
GBool invert, GBool inlineImg,
Stream *str, int width, int height, int len,
int *maskColors, Stream *maskStr,
int maskWidth, int maskHeight, GBool maskInvert);
void convertColorKeyMaskToClipRects(GfxImageColorMap *colorMap,
Stream *str,
int width, int height,
int *maskColors);
void convertExplicitMaskToClipRects(Stream *maskStr,
int maskWidth, int maskHeight,
GBool maskInvert);
void doImageL3(Object *ref, GfxState *state,
GfxImageColorMap *colorMap,
GBool invert, GBool inlineImg,
Stream *str, int width, int height, int len,
int *maskColors, Stream *maskStr,
int maskWidth, int maskHeight, GBool maskInvert);
void dumpColorSpaceL2(GfxState *state, GfxColorSpace *colorSpace,
GBool genXform, GBool updateColors,
GBool map01);
void dumpDeviceGrayColorSpace(GfxDeviceGrayColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpCalGrayColorSpace(GfxCalGrayColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpDeviceRGBColorSpace(GfxDeviceRGBColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpCalRGBColorSpace(GfxCalRGBColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpDeviceCMYKColorSpace(GfxDeviceCMYKColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpLabColorSpace(GfxLabColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpICCBasedColorSpace(GfxState *state, GfxICCBasedColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpIndexedColorSpace(GfxState *state,
GfxIndexedColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpSeparationColorSpace(GfxState *state,
GfxSeparationColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpDeviceNColorSpaceL2(GfxState *state, GfxDeviceNColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
void dumpDeviceNColorSpaceL3(GfxState *state, GfxDeviceNColorSpace *cs,
GBool genXform, GBool updateColors,
GBool map01);
GString *createDeviceNTintFunc(GfxDeviceNColorSpace *cs);
#if OPI_SUPPORT
void opiBegin20(GfxState *state, Dict *dict);
void opiBegin13(GfxState *state, Dict *dict);
void opiTransform(GfxState *state, double x0, double y0,
double *x1, double *y1);
GBool getFileSpec(Object *fileSpec, Object *fileName);
#endif
void cvtFunction(Function *func);
GString *filterPSName(GString *name);
void writePSTextLine(GString *s);
PSLevel level; // PostScript level
PSOutMode mode; // PostScript mode (PS, EPS, form)
int paperWidth; // width of paper, in pts
int paperHeight; // height of paper, in pts
GBool paperMatch; // true if paper size is set to match each page
int imgLLX, imgLLY, // imageable area, in pts
imgURX, imgURY;
GBool preload; // load all images into memory, and
// predefine forms
PSOutputFunc outputFunc;
void *outputStream;
PSFileType fileType; // file / pipe / stdout
GBool manualCtrl;
int seqPage; // current sequential page number
void (*underlayCbk)(PSOutputDev *psOut, void *data);
void *underlayCbkData;
void (*overlayCbk)(PSOutputDev *psOut, void *data);
void *overlayCbkData;
GString *(*customCodeCbk)(PSOutputDev *psOut,
PSOutCustomCodeLocation loc, int n,
void *data);
void *customCodeCbkData;
GBool honorUserUnit;
PDFDoc *doc;
XRef *xref; // the xref table for this PDF file
int firstPage; // first output page
int lastPage; // last output page
char *rasterizePage; // boolean for each page - true if page
// needs to be rasterized
GList *fontInfo; // info for each font [PSFontInfo]
GHash *fontFileInfo; // info for each font file [PSFontFileInfo]
Ref *imgIDs; // list of image IDs for in-memory images
int imgIDLen; // number of entries in imgIDs array
int imgIDSize; // size of imgIDs array
Ref *formIDs; // list of IDs for predefined forms
int formIDLen; // number of entries in formIDs array
int formIDSize; // size of formIDs array
char *visitedResources; // vector of resource objects already visited
GBool noStateChanges; // true if there have been no state changes
// since the last save
GList *saveStack; // "no state changes" flag for each
// pending save
int numTilingPatterns; // current number of nested tiling patterns
int nextFunc; // next unique number to use for a function
GList *paperSizes; // list of used paper sizes, if paperMatch
// is true [PSOutPaperSize]
double tx0, ty0; // global translation
double xScale0, yScale0; // global scaling
int rotate0; // rotation angle (0, 90, 180, 270)
double clipLLX0, clipLLY0,
clipURX0, clipURY0;
double tx, ty; // global translation for current page
double xScale, yScale; // global scaling for current page
int rotate; // rotation angle for current page
double epsX1, epsY1, // EPS bounding box (unrotated)
epsX2, epsY2;
GString *embFontList; // resource comments for embedded fonts
int processColors; // used process colors
PSOutCustomColor // used custom colors
*customColors;
GBool haveTextClip; // set if text has been drawn with a
// clipping render mode
GBool inType3Char; // inside a Type 3 CharProc
GString *t3String; // Type 3 content string
double t3WX, t3WY, // Type 3 character parameters
t3LLX, t3LLY, t3URX, t3URY;
GBool t3FillColorOnly; // operators should only use the fill color
GBool t3Cacheable; // cleared if char is not cacheable
GBool t3NeedsRestore; // set if a 'q' operator was issued
#if OPI_SUPPORT
int opi13Nest; // nesting level of OPI 1.3 objects
int opi20Nest; // nesting level of OPI 2.0 objects
#endif
GBool ok; // set up ok?
friend class WinPDFPrinter;
};
#endif

View File

@ -1 +0,0 @@
-DHAVE_SPLASH=1

View File

@ -1 +0,0 @@
PSOutputDev.cc:4198:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,449 +0,0 @@
//========================================================================
//
// Splash.h
//
// Copyright 2003-2013 Glyph & Cog, LLC
//
//========================================================================
#ifndef SPLASH_H
#define SPLASH_H
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include "SplashTypes.h"
#include "SplashClip.h"
class Splash;
class SplashBitmap;
struct SplashGlyphBitmap;
class SplashState;
class SplashPattern;
class SplashScreen;
class SplashPath;
class SplashXPath;
class SplashFont;
struct SplashPipe;
//------------------------------------------------------------------------
// Retrieves the next line of pixels in an image mask. Normally,
// fills in *<line> and returns true. If the image stream is
// exhausted, returns false.
typedef GBool (*SplashImageMaskSource)(void *data, Guchar *pixel);
// Retrieves the next line of pixels in an image. Normally, fills in
// *<line> and returns true. If the image stream is exhausted,
// returns false.
typedef GBool (*SplashImageSource)(void *data, SplashColorPtr colorLine,
Guchar *alphaLine);
//------------------------------------------------------------------------
enum SplashPipeResultColorCtrl {
splashPipeResultColorNoAlphaBlendMono,
splashPipeResultColorNoAlphaBlendRGB,
#if SPLASH_CMYK
splashPipeResultColorNoAlphaBlendCMYK,
#endif
splashPipeResultColorAlphaNoBlendMono,
splashPipeResultColorAlphaNoBlendRGB,
#if SPLASH_CMYK
splashPipeResultColorAlphaNoBlendCMYK,
#endif
splashPipeResultColorAlphaBlendMono,
splashPipeResultColorAlphaBlendRGB
#if SPLASH_CMYK
,
splashPipeResultColorAlphaBlendCMYK
#endif
};
//------------------------------------------------------------------------
// Splash
//------------------------------------------------------------------------
class Splash {
public:
// Create a new rasterizer object.
Splash(SplashBitmap *bitmapA, GBool vectorAntialiasA,
SplashScreenParams *screenParams = NULL);
Splash(SplashBitmap *bitmapA, GBool vectorAntialiasA,
SplashScreen *screenA);
~Splash();
//----- state read
SplashCoord *getMatrix();
SplashPattern *getStrokePattern();
SplashPattern *getFillPattern();
SplashScreen *getScreen();
SplashBlendFunc getBlendFunc();
SplashCoord getStrokeAlpha();
SplashCoord getFillAlpha();
SplashCoord getLineWidth();
int getLineCap();
int getLineJoin();
SplashCoord getMiterLimit();
SplashCoord getFlatness();
SplashCoord *getLineDash();
int getLineDashLength();
SplashCoord getLineDashPhase();
SplashStrokeAdjustMode getStrokeAdjust();
SplashClip *getClip();
SplashBitmap *getSoftMask();
GBool getInNonIsolatedGroup();
GBool getInKnockoutGroup();
//----- state write
void setMatrix(SplashCoord *matrix);
void setStrokePattern(SplashPattern *strokeColor);
void setFillPattern(SplashPattern *fillColor);
void setScreen(SplashScreen *screen);
void setBlendFunc(SplashBlendFunc func);
void setStrokeAlpha(SplashCoord alpha);
void setFillAlpha(SplashCoord alpha);
void setLineWidth(SplashCoord lineWidth);
void setLineCap(int lineCap);
void setLineJoin(int lineJoin);
void setMiterLimit(SplashCoord miterLimit);
void setFlatness(SplashCoord flatness);
// the <lineDash> array will be copied
void setLineDash(SplashCoord *lineDash, int lineDashLength,
SplashCoord lineDashPhase);
void setStrokeAdjust(SplashStrokeAdjustMode strokeAdjust);
// NB: uses transformed coordinates.
void clipResetToRect(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1);
// NB: uses transformed coordinates.
SplashError clipToRect(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1);
// NB: uses untransformed coordinates.
SplashError clipToPath(SplashPath *path, GBool eo);
void setSoftMask(SplashBitmap *softMask);
void setInTransparencyGroup(SplashBitmap *groupBackBitmapA,
int groupBackXA, int groupBackYA,
GBool nonIsolated, GBool knockout);
void setTransfer(Guchar *red, Guchar *green, Guchar *blue, Guchar *gray);
void setOverprintMask(Guint overprintMask);
void setEnablePathSimplification(GBool en);
//----- state save/restore
void saveState();
SplashError restoreState();
//----- drawing operations
// Fill the bitmap with <color>. This is not subject to clipping.
void clear(SplashColorPtr color, Guchar alpha = 0x00);
// Stroke a path using the current stroke pattern.
SplashError stroke(SplashPath *path);
// Fill a path using the current fill pattern.
SplashError fill(SplashPath *path, GBool eo);
// Draw a character, using the current fill pattern.
SplashError fillChar(SplashCoord x, SplashCoord y, int c, SplashFont *font);
// Draw a glyph, using the current fill pattern. This function does
// not free any data, i.e., it ignores glyph->freeData.
SplashError fillGlyph(SplashCoord x, SplashCoord y,
SplashGlyphBitmap *glyph);
// Draws an image mask using the fill color. This will read <h>
// lines of <w> pixels from <src>, starting with the top line. "1"
// pixels will be drawn with the current fill color; "0" pixels are
// transparent. The matrix:
// [ mat[0] mat[1] 0 ]
// [ mat[2] mat[3] 0 ]
// [ mat[4] mat[5] 1 ]
// maps a unit square to the desired destination for the image, in
// PostScript style:
// [x' y' 1] = [x y 1] * mat
// Note that the Splash y axis points downward, and the image source
// is assumed to produce pixels in raster order, starting from the
// top line.
SplashError fillImageMask(SplashImageMaskSource src, void *srcData,
int w, int h, SplashCoord *mat,
GBool glyphMode, GBool interpolate);
// Draw an image. This will read <h> lines of <w> pixels from
// <src>, starting with the top line. These pixels are assumed to
// be in the source mode, <srcMode>. If <srcAlpha> is true, the
// alpha values returned by <src> are used; otherwise they are
// ignored. The following combinations of source and target modes
// are supported:
// source target
// ------ ------
// Mono8 Mono1 -- with dithering
// Mono8 Mono8
// RGB8 RGB8
// BGR8 RGB8
// CMYK8 CMYK8
// The matrix behaves as for fillImageMask.
SplashError drawImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, GBool srcAlpha,
int w, int h, SplashCoord *mat,
GBool interpolate);
// Composite a rectangular region from <src> onto this Splash
// object.
SplashError composite(SplashBitmap *src, int xSrc, int ySrc,
int xDest, int yDest, int w, int h,
GBool noClip, GBool nonIsolated);
// Composite this Splash object onto a background color. The
// background alpha is assumed to be 1.
void compositeBackground(SplashColorPtr color);
// Copy a rectangular region from <src> onto the bitmap belonging to
// this Splash object. The destination alpha values are all set to
// zero.
SplashError blitTransparent(SplashBitmap *src, int xSrc, int ySrc,
int xDest, int yDest, int w, int h);
// Copy a rectangular region from the bitmap belonging to this
// Splash object to <dest>. The alpha values are corrected for a
// non-isolated group.
SplashError blitCorrectedAlpha(SplashBitmap *dest, int xSrc, int ySrc,
int xDest, int yDest, int w, int h);
//----- misc
// Construct a path for a stroke, given the path to be stroked and
// the line width <w>. All other stroke parameters are taken from
// the current state. If <flatten> is true, this function will
// first flatten the path and handle the linedash.
SplashPath *makeStrokePath(SplashPath *path, SplashCoord w,
int lineCap, int lineJoin,
GBool flatten = gTrue);
// Reduce the size of a rectangle as much as possible by moving any
// edges that are completely outside the clip region. Returns the
// clipping status of the resulting rectangle.
SplashClipResult limitRectToClipRect(int *xMin, int *yMin,
int *xMax, int *yMax);
// Return the associated bitmap.
SplashBitmap *getBitmap() {
return bitmap;
}
// Set the minimum line width.
void setMinLineWidth(SplashCoord w) {
minLineWidth = w;
}
// Get a bounding box which includes all modifications since the
// last call to clearModRegion.
void getModRegion(int *xMin, int *yMin, int *xMax, int *yMax)
{
*xMin = modXMin; *yMin = modYMin; *xMax = modXMax; *yMax = modYMax;
}
// Clear the modified region bounding box.
void clearModRegion();
// Get clipping status for the last drawing operation subject to
// clipping.
SplashClipResult getClipRes() {
return opClipRes;
}
// Toggle debug mode on or off.
void setDebugMode(GBool debugModeA) {
debugMode = debugModeA;
}
#if 1 //~tmp: turn off anti-aliasing temporarily
void setInShading(GBool sh) {
inShading = sh;
}
#endif
private:
void pipeInit(SplashPipe *pipe, SplashPattern *pattern,
Guchar aInput, GBool usesShape,
GBool nonIsolatedGroup);
void pipeRun(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleMono1(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleMono8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleRGB8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleBGR8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#if SPLASH_CMYK
void pipeRunSimpleCMYK8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#endif
void pipeRunShapeMono1(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunShapeMono8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunShapeRGB8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunShapeBGR8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#if SPLASH_CMYK
void pipeRunShapeCMYK8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#endif
void pipeRunAAMono1(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunAAMono8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunAARGB8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunAABGR8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#if SPLASH_CMYK
void pipeRunAACMYK8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#endif
void transform(SplashCoord *matrix, SplashCoord xi, SplashCoord yi,
SplashCoord *xo, SplashCoord *yo);
void updateModX(int x);
void updateModY(int y);
void strokeNarrow(SplashPath *path);
void drawStrokeSpan(SplashPipe *pipe, int x0, int x1, int y, GBool noClip);
void strokeWide(SplashPath *path, SplashCoord w,
int lineCap, int lineJoin);
SplashPath *flattenPath(SplashPath *path, SplashCoord *matrix,
SplashCoord flatness);
void flattenCurve(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1,
SplashCoord x2, SplashCoord y2,
SplashCoord x3, SplashCoord y3,
SplashCoord *matrix, SplashCoord flatness2,
SplashPath *fPath);
SplashPath *makeDashedPath(SplashPath *xPath);
SplashError fillWithPattern(SplashPath *path, GBool eo,
SplashPattern *pattern, SplashCoord alpha);
SplashPath *tweakFillPath(SplashPath *path);
GBool pathAllOutside(SplashPath *path);
SplashError fillGlyph2(int x0, int y0, SplashGlyphBitmap *glyph);
void getImageBounds(SplashCoord xyMin, SplashCoord xyMax,
int *xyMinI, int *xyMaxI);
void upscaleMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode,
GBool interpolate);
void arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode,
GBool interpolate);
SplashBitmap *scaleMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
GBool interpolate);
void scaleMaskYdXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYdXu(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYuXu(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYuXuI(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void blitMask(SplashBitmap *src, int xDest, int yDest,
SplashClipResult clipRes);
void upscaleImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
SplashCoord *mat, GBool interpolate);
void arbitraryTransformImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool interpolate);
SplashBitmap *scaleImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
GBool interpolate);
void scaleImageYdXd(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYdXu(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYuXd(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYuXu(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYuXuI(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void vertFlipImage(SplashBitmap *img, int width, int height,
int nComps);
void horizFlipImage(SplashBitmap *img, int width, int height,
int nComps);
void blitImage(SplashBitmap *src, GBool srcAlpha, int xDest, int yDest,
SplashClipResult clipRes);
void blitImageClipped(SplashBitmap *src, GBool srcAlpha,
int xSrc, int ySrc, int xDest, int yDest,
int w, int h);
void dumpPath(SplashPath *path);
void dumpXPath(SplashXPath *path);
static SplashPipeResultColorCtrl pipeResultColorNoAlphaBlend[];
static SplashPipeResultColorCtrl pipeResultColorAlphaNoBlend[];
static SplashPipeResultColorCtrl pipeResultColorAlphaBlend[];
static int pipeNonIsoGroupCorrection[];
SplashBitmap *bitmap;
int bitmapComps;
SplashState *state;
Guchar *scanBuf;
Guchar *scanBuf2;
SplashBitmap // for transparency groups, this is the bitmap
*groupBackBitmap; // containing the alpha0/color0 values
int groupBackX, groupBackY; // offset within groupBackBitmap
SplashCoord minLineWidth;
int modXMin, modYMin, modXMax, modYMax;
SplashClipResult opClipRes;
GBool vectorAntialias;
GBool inShading;
GBool debugMode;
};
#endif

View File

@ -1,2 +0,0 @@
Splash.cc:5559:bughuntingDivByZero
Splash.cc:5560:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
Stream.cc:359:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,310 +0,0 @@
//========================================================================
//
// Function.h
//
// Copyright 2001-2003 Glyph & Cog, LLC
//
//========================================================================
#ifndef FUNCTION_H
#define FUNCTION_H
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include "gtypes.h"
#include "Object.h"
class GList;
class Dict;
class Stream;
struct PSCode;
//------------------------------------------------------------------------
// Function
//------------------------------------------------------------------------
#define funcMaxInputs 32
#define funcMaxOutputs 32
#define sampledFuncMaxInputs 16
class Function {
public:
Function();
virtual ~Function();
// Construct a function. Returns NULL if unsuccessful.
static Function *parse(Object *funcObj, int recursion = 0);
// Initialize the entries common to all function types.
GBool init(Dict *dict);
virtual Function *copy() = 0;
// Return the function type:
// -1 : identity
// 0 : sampled
// 2 : exponential
// 3 : stitching
// 4 : PostScript
virtual int getType() = 0;
// Return size of input and output tuples.
int getInputSize() {
return m;
}
int getOutputSize() {
return n;
}
double getDomainMin(int i) {
return domain[i][0];
}
double getDomainMax(int i) {
return domain[i][1];
}
double getRangeMin(int i) {
return range[i][0];
}
double getRangeMax(int i) {
return range[i][1];
}
GBool getHasRange() {
return hasRange;
}
// Transform an input tuple into an output tuple.
virtual void transform(double *in, double *out) = 0;
virtual GBool isOk() = 0;
protected:
int m, n; // size of input and output tuples
double // min and max values for function domain
domain[funcMaxInputs][2];
double // min and max values for function range
range[funcMaxOutputs][2];
GBool hasRange; // set if range is defined
};
//------------------------------------------------------------------------
// IdentityFunction
//------------------------------------------------------------------------
class IdentityFunction : public Function {
public:
IdentityFunction();
virtual ~IdentityFunction();
virtual Function *copy() {
return new IdentityFunction();
}
virtual int getType() {
return -1;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return gTrue;
}
private:
};
//------------------------------------------------------------------------
// SampledFunction
//------------------------------------------------------------------------
class SampledFunction : public Function {
public:
SampledFunction(Object *funcObj, Dict *dict);
virtual ~SampledFunction();
virtual Function *copy() {
return new SampledFunction(this);
}
virtual int getType() {
return 0;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
int getSampleSize(int i) {
return sampleSize[i];
}
double getEncodeMin(int i) {
return encode[i][0];
}
double getEncodeMax(int i) {
return encode[i][1];
}
double getDecodeMin(int i) {
return decode[i][0];
}
double getDecodeMax(int i) {
return decode[i][1];
}
double *getSamples() {
return samples;
}
private:
SampledFunction(SampledFunction *func);
int // number of samples for each domain element
sampleSize[funcMaxInputs];
double // min and max values for domain encoder
encode[funcMaxInputs][2];
double // min and max values for range decoder
decode[funcMaxOutputs][2];
double // input multipliers
inputMul[funcMaxInputs];
int *idxOffset;
double *samples; // the samples
int nSamples; // size of the samples array
double *sBuf; // buffer for the transform function
double cacheIn[funcMaxInputs];
double cacheOut[funcMaxOutputs];
GBool ok;
};
//------------------------------------------------------------------------
// ExponentialFunction
//------------------------------------------------------------------------
class ExponentialFunction : public Function {
public:
ExponentialFunction(Object *funcObj, Dict *dict);
virtual ~ExponentialFunction();
virtual Function *copy() {
return new ExponentialFunction(this);
}
virtual int getType() {
return 2;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
double *getC0() {
return c0;
}
double *getC1() {
return c1;
}
double getE() {
return e;
}
private:
ExponentialFunction(ExponentialFunction *func);
double c0[funcMaxOutputs];
double c1[funcMaxOutputs];
double e;
GBool ok;
};
//------------------------------------------------------------------------
// StitchingFunction
//------------------------------------------------------------------------
class StitchingFunction : public Function {
public:
StitchingFunction(Object *funcObj, Dict *dict, int recursion);
virtual ~StitchingFunction();
virtual Function *copy() {
return new StitchingFunction(this);
}
virtual int getType() {
return 3;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
int getNumFuncs() {
return k;
}
Function *getFunc(int i) {
return funcs[i];
}
double *getBounds() {
return bounds;
}
double *getEncode() {
return encode;
}
double *getScale() {
return scale;
}
private:
StitchingFunction(StitchingFunction *func);
int k;
Function **funcs;
double *bounds;
double *encode;
double *scale;
GBool ok;
};
//------------------------------------------------------------------------
// PostScriptFunction
//------------------------------------------------------------------------
class PostScriptFunction : public Function {
public:
PostScriptFunction(Object *funcObj, Dict *dict);
virtual ~PostScriptFunction();
virtual Function *copy() {
return new PostScriptFunction(this);
}
virtual int getType() {
return 4;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
GString *getCodeString() {
return codeString;
}
private:
PostScriptFunction(PostScriptFunction *func);
GBool parseCode(GList *tokens, int *tokPtr, int *codePtr);
void addCode(int *codePtr, int op);
void addCodeI(int *codePtr, int op, int x);
void addCodeD(int *codePtr, int op, double x);
GString *getToken(Stream *str);
int exec(double *stack, int sp0);
GString *codeString;
PSCode *code;
int codeLen;
int codeSize;
double cacheIn[funcMaxInputs];
double cacheOut[funcMaxOutputs];
GBool ok;
};
#endif

View File

@ -1 +0,0 @@
Function.cc:1420:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,449 +0,0 @@
//========================================================================
//
// Splash.h
//
// Copyright 2003-2013 Glyph & Cog, LLC
//
//========================================================================
#ifndef SPLASH_H
#define SPLASH_H
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include "SplashTypes.h"
#include "SplashClip.h"
class Splash;
class SplashBitmap;
struct SplashGlyphBitmap;
class SplashState;
class SplashPattern;
class SplashScreen;
class SplashPath;
class SplashXPath;
class SplashFont;
struct SplashPipe;
//------------------------------------------------------------------------
// Retrieves the next line of pixels in an image mask. Normally,
// fills in *<line> and returns true. If the image stream is
// exhausted, returns false.
typedef GBool (*SplashImageMaskSource)(void *data, Guchar *pixel);
// Retrieves the next line of pixels in an image. Normally, fills in
// *<line> and returns true. If the image stream is exhausted,
// returns false.
typedef GBool (*SplashImageSource)(void *data, SplashColorPtr colorLine,
Guchar *alphaLine);
//------------------------------------------------------------------------
enum SplashPipeResultColorCtrl {
splashPipeResultColorNoAlphaBlendMono,
splashPipeResultColorNoAlphaBlendRGB,
#if SPLASH_CMYK
splashPipeResultColorNoAlphaBlendCMYK,
#endif
splashPipeResultColorAlphaNoBlendMono,
splashPipeResultColorAlphaNoBlendRGB,
#if SPLASH_CMYK
splashPipeResultColorAlphaNoBlendCMYK,
#endif
splashPipeResultColorAlphaBlendMono,
splashPipeResultColorAlphaBlendRGB
#if SPLASH_CMYK
,
splashPipeResultColorAlphaBlendCMYK
#endif
};
//------------------------------------------------------------------------
// Splash
//------------------------------------------------------------------------
class Splash {
public:
// Create a new rasterizer object.
Splash(SplashBitmap *bitmapA, GBool vectorAntialiasA,
SplashScreenParams *screenParams = NULL);
Splash(SplashBitmap *bitmapA, GBool vectorAntialiasA,
SplashScreen *screenA);
~Splash();
//----- state read
SplashCoord *getMatrix();
SplashPattern *getStrokePattern();
SplashPattern *getFillPattern();
SplashScreen *getScreen();
SplashBlendFunc getBlendFunc();
SplashCoord getStrokeAlpha();
SplashCoord getFillAlpha();
SplashCoord getLineWidth();
int getLineCap();
int getLineJoin();
SplashCoord getMiterLimit();
SplashCoord getFlatness();
SplashCoord *getLineDash();
int getLineDashLength();
SplashCoord getLineDashPhase();
SplashStrokeAdjustMode getStrokeAdjust();
SplashClip *getClip();
SplashBitmap *getSoftMask();
GBool getInNonIsolatedGroup();
GBool getInKnockoutGroup();
//----- state write
void setMatrix(SplashCoord *matrix);
void setStrokePattern(SplashPattern *strokeColor);
void setFillPattern(SplashPattern *fillColor);
void setScreen(SplashScreen *screen);
void setBlendFunc(SplashBlendFunc func);
void setStrokeAlpha(SplashCoord alpha);
void setFillAlpha(SplashCoord alpha);
void setLineWidth(SplashCoord lineWidth);
void setLineCap(int lineCap);
void setLineJoin(int lineJoin);
void setMiterLimit(SplashCoord miterLimit);
void setFlatness(SplashCoord flatness);
// the <lineDash> array will be copied
void setLineDash(SplashCoord *lineDash, int lineDashLength,
SplashCoord lineDashPhase);
void setStrokeAdjust(SplashStrokeAdjustMode strokeAdjust);
// NB: uses transformed coordinates.
void clipResetToRect(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1);
// NB: uses transformed coordinates.
SplashError clipToRect(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1);
// NB: uses untransformed coordinates.
SplashError clipToPath(SplashPath *path, GBool eo);
void setSoftMask(SplashBitmap *softMask);
void setInTransparencyGroup(SplashBitmap *groupBackBitmapA,
int groupBackXA, int groupBackYA,
GBool nonIsolated, GBool knockout);
void setTransfer(Guchar *red, Guchar *green, Guchar *blue, Guchar *gray);
void setOverprintMask(Guint overprintMask);
void setEnablePathSimplification(GBool en);
//----- state save/restore
void saveState();
SplashError restoreState();
//----- drawing operations
// Fill the bitmap with <color>. This is not subject to clipping.
void clear(SplashColorPtr color, Guchar alpha = 0x00);
// Stroke a path using the current stroke pattern.
SplashError stroke(SplashPath *path);
// Fill a path using the current fill pattern.
SplashError fill(SplashPath *path, GBool eo);
// Draw a character, using the current fill pattern.
SplashError fillChar(SplashCoord x, SplashCoord y, int c, SplashFont *font);
// Draw a glyph, using the current fill pattern. This function does
// not free any data, i.e., it ignores glyph->freeData.
SplashError fillGlyph(SplashCoord x, SplashCoord y,
SplashGlyphBitmap *glyph);
// Draws an image mask using the fill color. This will read <h>
// lines of <w> pixels from <src>, starting with the top line. "1"
// pixels will be drawn with the current fill color; "0" pixels are
// transparent. The matrix:
// [ mat[0] mat[1] 0 ]
// [ mat[2] mat[3] 0 ]
// [ mat[4] mat[5] 1 ]
// maps a unit square to the desired destination for the image, in
// PostScript style:
// [x' y' 1] = [x y 1] * mat
// Note that the Splash y axis points downward, and the image source
// is assumed to produce pixels in raster order, starting from the
// top line.
SplashError fillImageMask(SplashImageMaskSource src, void *srcData,
int w, int h, SplashCoord *mat,
GBool glyphMode, GBool interpolate);
// Draw an image. This will read <h> lines of <w> pixels from
// <src>, starting with the top line. These pixels are assumed to
// be in the source mode, <srcMode>. If <srcAlpha> is true, the
// alpha values returned by <src> are used; otherwise they are
// ignored. The following combinations of source and target modes
// are supported:
// source target
// ------ ------
// Mono8 Mono1 -- with dithering
// Mono8 Mono8
// RGB8 RGB8
// BGR8 RGB8
// CMYK8 CMYK8
// The matrix behaves as for fillImageMask.
SplashError drawImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, GBool srcAlpha,
int w, int h, SplashCoord *mat,
GBool interpolate);
// Composite a rectangular region from <src> onto this Splash
// object.
SplashError composite(SplashBitmap *src, int xSrc, int ySrc,
int xDest, int yDest, int w, int h,
GBool noClip, GBool nonIsolated);
// Composite this Splash object onto a background color. The
// background alpha is assumed to be 1.
void compositeBackground(SplashColorPtr color);
// Copy a rectangular region from <src> onto the bitmap belonging to
// this Splash object. The destination alpha values are all set to
// zero.
SplashError blitTransparent(SplashBitmap *src, int xSrc, int ySrc,
int xDest, int yDest, int w, int h);
// Copy a rectangular region from the bitmap belonging to this
// Splash object to <dest>. The alpha values are corrected for a
// non-isolated group.
SplashError blitCorrectedAlpha(SplashBitmap *dest, int xSrc, int ySrc,
int xDest, int yDest, int w, int h);
//----- misc
// Construct a path for a stroke, given the path to be stroked and
// the line width <w>. All other stroke parameters are taken from
// the current state. If <flatten> is true, this function will
// first flatten the path and handle the linedash.
SplashPath *makeStrokePath(SplashPath *path, SplashCoord w,
int lineCap, int lineJoin,
GBool flatten = gTrue);
// Reduce the size of a rectangle as much as possible by moving any
// edges that are completely outside the clip region. Returns the
// clipping status of the resulting rectangle.
SplashClipResult limitRectToClipRect(int *xMin, int *yMin,
int *xMax, int *yMax);
// Return the associated bitmap.
SplashBitmap *getBitmap() {
return bitmap;
}
// Set the minimum line width.
void setMinLineWidth(SplashCoord w) {
minLineWidth = w;
}
// Get a bounding box which includes all modifications since the
// last call to clearModRegion.
void getModRegion(int *xMin, int *yMin, int *xMax, int *yMax)
{
*xMin = modXMin; *yMin = modYMin; *xMax = modXMax; *yMax = modYMax;
}
// Clear the modified region bounding box.
void clearModRegion();
// Get clipping status for the last drawing operation subject to
// clipping.
SplashClipResult getClipRes() {
return opClipRes;
}
// Toggle debug mode on or off.
void setDebugMode(GBool debugModeA) {
debugMode = debugModeA;
}
#if 1 //~tmp: turn off anti-aliasing temporarily
void setInShading(GBool sh) {
inShading = sh;
}
#endif
private:
void pipeInit(SplashPipe *pipe, SplashPattern *pattern,
Guchar aInput, GBool usesShape,
GBool nonIsolatedGroup);
void pipeRun(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleMono1(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleMono8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleRGB8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunSimpleBGR8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#if SPLASH_CMYK
void pipeRunSimpleCMYK8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#endif
void pipeRunShapeMono1(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunShapeMono8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunShapeRGB8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunShapeBGR8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#if SPLASH_CMYK
void pipeRunShapeCMYK8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#endif
void pipeRunAAMono1(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunAAMono8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunAARGB8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
void pipeRunAABGR8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#if SPLASH_CMYK
void pipeRunAACMYK8(SplashPipe *pipe, int x0, int x1, int y,
Guchar *shapePtr, SplashColorPtr cSrcPtr);
#endif
void transform(SplashCoord *matrix, SplashCoord xi, SplashCoord yi,
SplashCoord *xo, SplashCoord *yo);
void updateModX(int x);
void updateModY(int y);
void strokeNarrow(SplashPath *path);
void drawStrokeSpan(SplashPipe *pipe, int x0, int x1, int y, GBool noClip);
void strokeWide(SplashPath *path, SplashCoord w,
int lineCap, int lineJoin);
SplashPath *flattenPath(SplashPath *path, SplashCoord *matrix,
SplashCoord flatness);
void flattenCurve(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1,
SplashCoord x2, SplashCoord y2,
SplashCoord x3, SplashCoord y3,
SplashCoord *matrix, SplashCoord flatness2,
SplashPath *fPath);
SplashPath *makeDashedPath(SplashPath *xPath);
SplashError fillWithPattern(SplashPath *path, GBool eo,
SplashPattern *pattern, SplashCoord alpha);
SplashPath *tweakFillPath(SplashPath *path);
GBool pathAllOutside(SplashPath *path);
SplashError fillGlyph2(int x0, int y0, SplashGlyphBitmap *glyph);
void getImageBounds(SplashCoord xyMin, SplashCoord xyMax,
int *xyMinI, int *xyMaxI);
void upscaleMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode,
GBool interpolate);
void arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode,
GBool interpolate);
SplashBitmap *scaleMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
GBool interpolate);
void scaleMaskYdXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYdXu(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYuXu(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleMaskYuXuI(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void blitMask(SplashBitmap *src, int xDest, int yDest,
SplashClipResult clipRes);
void upscaleImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
SplashCoord *mat, GBool interpolate);
void arbitraryTransformImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool interpolate);
SplashBitmap *scaleImage(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
GBool interpolate);
void scaleImageYdXd(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYdXu(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYuXd(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYuXu(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void scaleImageYuXuI(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest);
void vertFlipImage(SplashBitmap *img, int width, int height,
int nComps);
void horizFlipImage(SplashBitmap *img, int width, int height,
int nComps);
void blitImage(SplashBitmap *src, GBool srcAlpha, int xDest, int yDest,
SplashClipResult clipRes);
void blitImageClipped(SplashBitmap *src, GBool srcAlpha,
int xSrc, int ySrc, int xDest, int yDest,
int w, int h);
void dumpPath(SplashPath *path);
void dumpXPath(SplashXPath *path);
static SplashPipeResultColorCtrl pipeResultColorNoAlphaBlend[];
static SplashPipeResultColorCtrl pipeResultColorAlphaNoBlend[];
static SplashPipeResultColorCtrl pipeResultColorAlphaBlend[];
static int pipeNonIsoGroupCorrection[];
SplashBitmap *bitmap;
int bitmapComps;
SplashState *state;
Guchar *scanBuf;
Guchar *scanBuf2;
SplashBitmap // for transparency groups, this is the bitmap
*groupBackBitmap; // containing the alpha0/color0 values
int groupBackX, groupBackY; // offset within groupBackBitmap
SplashCoord minLineWidth;
int modXMin, modYMin, modXMax, modYMax;
SplashClipResult opClipRes;
GBool vectorAntialias;
GBool inShading;
GBool debugMode;
};
#endif

View File

@ -1,3 +0,0 @@
Splash.cc:5555:bughuntingDivByZero
Splash.cc:5556:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
Stream.cc:360:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,310 +0,0 @@
//========================================================================
//
// Function.h
//
// Copyright 2001-2003 Glyph & Cog, LLC
//
//========================================================================
#ifndef FUNCTION_H
#define FUNCTION_H
#include <aconf.h>
#ifdef USE_GCC_PRAGMAS
#pragma interface
#endif
#include "gtypes.h"
#include "Object.h"
class GList;
class Dict;
class Stream;
struct PSCode;
//------------------------------------------------------------------------
// Function
//------------------------------------------------------------------------
#define funcMaxInputs 32
#define funcMaxOutputs 32
#define sampledFuncMaxInputs 16
class Function {
public:
Function();
virtual ~Function();
// Construct a function. Returns NULL if unsuccessful.
static Function *parse(Object *funcObj, int recursion = 0);
// Initialize the entries common to all function types.
GBool init(Dict *dict);
virtual Function *copy() = 0;
// Return the function type:
// -1 : identity
// 0 : sampled
// 2 : exponential
// 3 : stitching
// 4 : PostScript
virtual int getType() = 0;
// Return size of input and output tuples.
int getInputSize() {
return m;
}
int getOutputSize() {
return n;
}
double getDomainMin(int i) {
return domain[i][0];
}
double getDomainMax(int i) {
return domain[i][1];
}
double getRangeMin(int i) {
return range[i][0];
}
double getRangeMax(int i) {
return range[i][1];
}
GBool getHasRange() {
return hasRange;
}
// Transform an input tuple into an output tuple.
virtual void transform(double *in, double *out) = 0;
virtual GBool isOk() = 0;
protected:
int m, n; // size of input and output tuples
double // min and max values for function domain
domain[funcMaxInputs][2];
double // min and max values for function range
range[funcMaxOutputs][2];
GBool hasRange; // set if range is defined
};
//------------------------------------------------------------------------
// IdentityFunction
//------------------------------------------------------------------------
class IdentityFunction : public Function {
public:
IdentityFunction();
virtual ~IdentityFunction();
virtual Function *copy() {
return new IdentityFunction();
}
virtual int getType() {
return -1;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return gTrue;
}
private:
};
//------------------------------------------------------------------------
// SampledFunction
//------------------------------------------------------------------------
class SampledFunction : public Function {
public:
SampledFunction(Object *funcObj, Dict *dict);
virtual ~SampledFunction();
virtual Function *copy() {
return new SampledFunction(this);
}
virtual int getType() {
return 0;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
int getSampleSize(int i) {
return sampleSize[i];
}
double getEncodeMin(int i) {
return encode[i][0];
}
double getEncodeMax(int i) {
return encode[i][1];
}
double getDecodeMin(int i) {
return decode[i][0];
}
double getDecodeMax(int i) {
return decode[i][1];
}
double *getSamples() {
return samples;
}
private:
SampledFunction(SampledFunction *func);
int // number of samples for each domain element
sampleSize[funcMaxInputs];
double // min and max values for domain encoder
encode[funcMaxInputs][2];
double // min and max values for range decoder
decode[funcMaxOutputs][2];
double // input multipliers
inputMul[funcMaxInputs];
int *idxOffset;
double *samples; // the samples
int nSamples; // size of the samples array
double *sBuf; // buffer for the transform function
double cacheIn[funcMaxInputs];
double cacheOut[funcMaxOutputs];
GBool ok;
};
//------------------------------------------------------------------------
// ExponentialFunction
//------------------------------------------------------------------------
class ExponentialFunction : public Function {
public:
ExponentialFunction(Object *funcObj, Dict *dict);
virtual ~ExponentialFunction();
virtual Function *copy() {
return new ExponentialFunction(this);
}
virtual int getType() {
return 2;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
double *getC0() {
return c0;
}
double *getC1() {
return c1;
}
double getE() {
return e;
}
private:
ExponentialFunction(ExponentialFunction *func);
double c0[funcMaxOutputs];
double c1[funcMaxOutputs];
double e;
GBool ok;
};
//------------------------------------------------------------------------
// StitchingFunction
//------------------------------------------------------------------------
class StitchingFunction : public Function {
public:
StitchingFunction(Object *funcObj, Dict *dict, int recursion);
virtual ~StitchingFunction();
virtual Function *copy() {
return new StitchingFunction(this);
}
virtual int getType() {
return 3;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
int getNumFuncs() {
return k;
}
Function *getFunc(int i) {
return funcs[i];
}
double *getBounds() {
return bounds;
}
double *getEncode() {
return encode;
}
double *getScale() {
return scale;
}
private:
StitchingFunction(StitchingFunction *func);
int k;
Function **funcs;
double *bounds;
double *encode;
double *scale;
GBool ok;
};
//------------------------------------------------------------------------
// PostScriptFunction
//------------------------------------------------------------------------
class PostScriptFunction : public Function {
public:
PostScriptFunction(Object *funcObj, Dict *dict);
virtual ~PostScriptFunction();
virtual Function *copy() {
return new PostScriptFunction(this);
}
virtual int getType() {
return 4;
}
virtual void transform(double *in, double *out);
virtual GBool isOk() {
return ok;
}
GString *getCodeString() {
return codeString;
}
private:
PostScriptFunction(PostScriptFunction *func);
GBool parseCode(GList *tokens, int *tokPtr, int *codePtr);
void addCode(int *codePtr, int op);
void addCodeI(int *codePtr, int op, int x);
void addCodeD(int *codePtr, int op, double x);
GString *getToken(Stream *str);
int exec(double *stack, int sp0);
GString *codeString;
PSCode *code;
int codeLen;
int codeSize;
double cacheIn[funcMaxInputs];
double cacheOut[funcMaxOutputs];
GBool ok;
};
#endif

View File

@ -1,3 +0,0 @@
Details:
https://nvd.nist.gov/vuln/detail/CVE-2019-10026

View File

@ -1,4 +0,0 @@
Function.cc:1475:bughuntingDivByZero
Function.cc:1477:bughuntingDivByZero
Function.cc:1486:bughuntingDivByZero

View File

@ -1,443 +0,0 @@
////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2019 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// dsdiff.c
// This module is a helper to the WavPack command-line programs to support DFF files.
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <ctype.h>
#include "wavpack.h"
#include "utils.h"
#include "md5.h"
#ifdef _WIN32
#define strdup(x) _strdup(x)
#endif
#define WAVPACK_NO_ERROR 0
#define WAVPACK_SOFT_ERROR 1
#define WAVPACK_HARD_ERROR 2
extern int debug_logging_mode;
#pragma pack(push,2)
typedef struct {
char ckID[4];
int64_t ckDataSize;
} DFFChunkHeader;
typedef struct {
char ckID[4];
int64_t ckDataSize;
char formType[4];
} DFFFileHeader;
typedef struct {
char ckID[4];
int64_t ckDataSize;
uint32_t version;
} DFFVersionChunk;
typedef struct {
char ckID[4];
int64_t ckDataSize;
uint32_t sampleRate;
} DFFSampleRateChunk;
typedef struct {
char ckID[4];
int64_t ckDataSize;
uint16_t numChannels;
} DFFChannelsHeader;
typedef struct {
char ckID[4];
int64_t ckDataSize;
char compressionType[4];
} DFFCompressionHeader;
#pragma pack(pop)
#define DFFChunkHeaderFormat "4D"
#define DFFFileHeaderFormat "4D4"
#define DFFVersionChunkFormat "4DL"
#define DFFSampleRateChunkFormat "4DL"
#define DFFChannelsHeaderFormat "4DS"
#define DFFCompressionHeaderFormat "4D4"
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
// loop through all elements of the DSDIFF header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk;
if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize);
prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
if (numChannels < chansSpecified || numChannels < 1) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
uint32_t chan_mask = WavpackGetChannelMask (wpc);
int num_channels = WavpackGetNumChannels (wpc);
DFFFileHeader file_header, prop_header;
DFFChunkHeader data_header;
DFFVersionChunk ver_chunk;
DFFSampleRateChunk fs_chunk;
DFFChannelsHeader chan_header;
DFFCompressionHeader cmpr_header;
char *cmpr_name = "\016not compressed", *chan_ids;
int64_t file_size, prop_chunk_size, data_size;
int cmpr_name_size, chan_ids_size;
uint32_t bcount;
if (debug_logging_mode)
error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n",
(long long) total_samples, qmode);
cmpr_name_size = (strlen (cmpr_name) + 1) & ~1;
chan_ids_size = num_channels * 4;
chan_ids = malloc (chan_ids_size);
if (chan_ids) {
uint32_t scan_mask = 0x1;
char *cptr = chan_ids;
int ci, uci = 0;
for (ci = 0; ci < num_channels; ++ci) {
while (scan_mask && !(scan_mask & chan_mask))
scan_mask <<= 1;
if (scan_mask & 0x1)
memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4);
else if (scan_mask & 0x2)
memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4);
else if (scan_mask & 0x4)
memcpy (cptr, "C ", 4);
else if (scan_mask & 0x8)
memcpy (cptr, "LFE ", 4);
else if (scan_mask & 0x10)
memcpy (cptr, "LS ", 4);
else if (scan_mask & 0x20)
memcpy (cptr, "RS ", 4);
else {
cptr [0] = 'C';
cptr [1] = (uci / 100) + '0';
cptr [2] = ((uci % 100) / 10) + '0';
cptr [3] = (uci % 10) + '0';
uci++;
}
scan_mask <<= 1;
cptr += 4;
}
}
else {
error_line ("can't allocate memory!");
return FALSE;
}
data_size = total_samples * num_channels;
prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size;
file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1);
memcpy (file_header.ckID, "FRM8", 4);
file_header.ckDataSize = file_size - 12;
memcpy (file_header.formType, "DSD ", 4);
memcpy (prop_header.ckID, "PROP", 4);
prop_header.ckDataSize = prop_chunk_size - 12;
memcpy (prop_header.formType, "SND ", 4);
memcpy (ver_chunk.ckID, "FVER", 4);
ver_chunk.ckDataSize = sizeof (ver_chunk) - 12;
ver_chunk.version = 0x01050000;
memcpy (fs_chunk.ckID, "FS ", 4);
fs_chunk.ckDataSize = sizeof (fs_chunk) - 12;
fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8;
memcpy (chan_header.ckID, "CHNL", 4);
chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12;
chan_header.numChannels = num_channels;
memcpy (cmpr_header.ckID, "CMPR", 4);
cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12;
memcpy (cmpr_header.compressionType, "DSD ", 4);
memcpy (data_header.ckID, "DSD ", 4);
data_header.ckDataSize = data_size;
WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat);
WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat);
WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat);
WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat);
WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat);
WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat);
WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat);
if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) ||
!DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) ||
!DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) ||
!DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) ||
!DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) ||
!DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size ||
!DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) ||
!DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size ||
!DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) {
error_line ("can't write .DSF data, disk probably full!");
free (chan_ids);
return FALSE;
}
free (chan_ids);
return TRUE;
}

View File

@ -1 +0,0 @@
dsdiff.c:282:bughuntingDivByZero

View File

@ -1,2 +0,0 @@
-DMAGICKCORE_LIBOPENJP2_DELEGATE

View File

@ -1 +0,0 @@
jp2.c:865:bughuntingUninit

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +0,0 @@
Details:
https://nvd.nist.gov/vuln/detail/CVE-2019-13390

View File

@ -1 +0,0 @@
-DCONFIG_ADX_MUXER=1

View File

@ -1 +0,0 @@
libavformat_rawenc.c:70:bughuntingDivByZero

View File

@ -1,505 +0,0 @@
/*
* RAW muxers
* Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2005 Alex Beregszaszi
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/intreadwrite.h"
#include "avformat.h"
#include "rawenc.h"
#include "internal.h"
int ff_raw_write_packet(AVFormatContext *s, AVPacket *pkt)
{
avio_write(s->pb, pkt->data, pkt->size);
return 0;
}
static int force_one_stream(AVFormatContext *s)
{
if (s->nb_streams != 1) {
av_log(s, AV_LOG_ERROR, "%s files have exactly one stream\n",
s->oformat->name);
return AVERROR(EINVAL);
}
return 0;
}
/* Note: Do not forget to add new entries to the Makefile as well. */
#if CONFIG_AC3_MUXER
AVOutputFormat ff_ac3_muxer = {
.name = "ac3",
.long_name = NULL_IF_CONFIG_SMALL("raw AC-3"),
.mime_type = "audio/x-ac3",
.extensions = "ac3",
.audio_codec = AV_CODEC_ID_AC3,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_ADX_MUXER
static int adx_write_trailer(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
AVCodecParameters *par = s->streams[0]->codecpar;
if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
int64_t file_size = avio_tell(pb);
uint64_t sample_count = (file_size - 36) / par->channels / 18 * 32;
if (sample_count <= UINT32_MAX) {
avio_seek(pb, 12, SEEK_SET);
avio_wb32(pb, sample_count);
avio_seek(pb, file_size, SEEK_SET);
}
}
return 0;
}
AVOutputFormat ff_adx_muxer = {
.name = "adx",
.long_name = NULL_IF_CONFIG_SMALL("CRI ADX"),
.extensions = "adx",
.audio_codec = AV_CODEC_ID_ADPCM_ADX,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.write_trailer = adx_write_trailer,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_APTX_MUXER
AVOutputFormat ff_aptx_muxer = {
.name = "aptx",
.long_name = NULL_IF_CONFIG_SMALL("raw aptX (Audio Processing Technology for Bluetooth)"),
.extensions = "aptx",
.audio_codec = AV_CODEC_ID_APTX,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_APTX_HD_MUXER
AVOutputFormat ff_aptx_hd_muxer = {
.name = "aptx_hd",
.long_name = NULL_IF_CONFIG_SMALL("raw aptX HD (Audio Processing Technology for Bluetooth)"),
.extensions = "aptxhd",
.audio_codec = AV_CODEC_ID_APTX_HD,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_AVS2_MUXER
AVOutputFormat ff_avs2_muxer = {
.name = "avs2",
.long_name = NULL_IF_CONFIG_SMALL("raw AVS2-P2/IEEE1857.4 video"),
.extensions = "avs,avs2",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_AVS2,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_CAVSVIDEO_MUXER
AVOutputFormat ff_cavsvideo_muxer = {
.name = "cavsvideo",
.long_name = NULL_IF_CONFIG_SMALL("raw Chinese AVS (Audio Video Standard) video"),
.extensions = "cavs",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_CAVS,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_CODEC2RAW_MUXER
AVOutputFormat ff_codec2raw_muxer = {
.name = "codec2raw",
.long_name = NULL_IF_CONFIG_SMALL("raw codec2 muxer"),
.audio_codec = AV_CODEC_ID_CODEC2,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_DATA_MUXER
AVOutputFormat ff_data_muxer = {
.name = "data",
.long_name = NULL_IF_CONFIG_SMALL("raw data"),
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_DIRAC_MUXER
AVOutputFormat ff_dirac_muxer = {
.name = "dirac",
.long_name = NULL_IF_CONFIG_SMALL("raw Dirac"),
.extensions = "drc,vc2",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_DIRAC,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_DNXHD_MUXER
AVOutputFormat ff_dnxhd_muxer = {
.name = "dnxhd",
.long_name = NULL_IF_CONFIG_SMALL("raw DNxHD (SMPTE VC-3)"),
.extensions = "dnxhd,dnxhr",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_DNXHD,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_DTS_MUXER
AVOutputFormat ff_dts_muxer = {
.name = "dts",
.long_name = NULL_IF_CONFIG_SMALL("raw DTS"),
.mime_type = "audio/x-dca",
.extensions = "dts",
.audio_codec = AV_CODEC_ID_DTS,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_EAC3_MUXER
AVOutputFormat ff_eac3_muxer = {
.name = "eac3",
.long_name = NULL_IF_CONFIG_SMALL("raw E-AC-3"),
.mime_type = "audio/x-eac3",
.extensions = "eac3",
.audio_codec = AV_CODEC_ID_EAC3,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_G722_MUXER
AVOutputFormat ff_g722_muxer = {
.name = "g722",
.long_name = NULL_IF_CONFIG_SMALL("raw G.722"),
.mime_type = "audio/G722",
.extensions = "g722",
.audio_codec = AV_CODEC_ID_ADPCM_G722,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_G723_1_MUXER
AVOutputFormat ff_g723_1_muxer = {
.name = "g723_1",
.long_name = NULL_IF_CONFIG_SMALL("raw G.723.1"),
.mime_type = "audio/g723",
.extensions = "tco,rco",
.audio_codec = AV_CODEC_ID_G723_1,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_G726_MUXER
AVOutputFormat ff_g726_muxer = {
.name = "g726",
.long_name = NULL_IF_CONFIG_SMALL("raw big-endian G.726 (\"left-justified\")"),
.audio_codec = AV_CODEC_ID_ADPCM_G726,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_G726LE_MUXER
AVOutputFormat ff_g726le_muxer = {
.name = "g726le",
.long_name = NULL_IF_CONFIG_SMALL("raw little-endian G.726 (\"right-justified\")"),
.audio_codec = AV_CODEC_ID_ADPCM_G726LE,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_GSM_MUXER
AVOutputFormat ff_gsm_muxer = {
.name = "gsm",
.long_name = NULL_IF_CONFIG_SMALL("raw GSM"),
.mime_type = "audio/x-gsm",
.extensions = "gsm",
.audio_codec = AV_CODEC_ID_GSM,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_H261_MUXER
AVOutputFormat ff_h261_muxer = {
.name = "h261",
.long_name = NULL_IF_CONFIG_SMALL("raw H.261"),
.mime_type = "video/x-h261",
.extensions = "h261",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_H261,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_H263_MUXER
AVOutputFormat ff_h263_muxer = {
.name = "h263",
.long_name = NULL_IF_CONFIG_SMALL("raw H.263"),
.mime_type = "video/x-h263",
.extensions = "h263",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_H263,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_H264_MUXER
static int h264_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
{
AVStream *st = s->streams[0];
if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
AV_RB24(pkt->data) != 0x000001)
return ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL);
return 1;
}
AVOutputFormat ff_h264_muxer = {
.name = "h264",
.long_name = NULL_IF_CONFIG_SMALL("raw H.264 video"),
.extensions = "h264,264",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_H264,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.check_bitstream = h264_check_bitstream,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_HEVC_MUXER
static int hevc_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
{
AVStream *st = s->streams[0];
if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
AV_RB24(pkt->data) != 0x000001)
return ff_stream_add_bitstream_filter(st, "hevc_mp4toannexb", NULL);
return 1;
}
AVOutputFormat ff_hevc_muxer = {
.name = "hevc",
.long_name = NULL_IF_CONFIG_SMALL("raw HEVC video"),
.extensions = "hevc,h265,265",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_HEVC,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.check_bitstream = hevc_check_bitstream,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_M4V_MUXER
AVOutputFormat ff_m4v_muxer = {
.name = "m4v",
.long_name = NULL_IF_CONFIG_SMALL("raw MPEG-4 video"),
.extensions = "m4v",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_MPEG4,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_MJPEG_MUXER
AVOutputFormat ff_mjpeg_muxer = {
.name = "mjpeg",
.long_name = NULL_IF_CONFIG_SMALL("raw MJPEG video"),
.mime_type = "video/x-mjpeg",
.extensions = "mjpg,mjpeg",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_MJPEG,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_SINGLEJPEG_MUXER
AVOutputFormat ff_singlejpeg_muxer = {
.name = "singlejpeg",
.long_name = NULL_IF_CONFIG_SMALL("JPEG single image"),
.mime_type = "image/jpeg",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_MJPEG,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
.write_header = force_one_stream,
};
#endif
#if CONFIG_MLP_MUXER
AVOutputFormat ff_mlp_muxer = {
.name = "mlp",
.long_name = NULL_IF_CONFIG_SMALL("raw MLP"),
.extensions = "mlp",
.audio_codec = AV_CODEC_ID_MLP,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_MP2_MUXER
AVOutputFormat ff_mp2_muxer = {
.name = "mp2",
.long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
.mime_type = "audio/mpeg",
.extensions = "mp2,m2a,mpa",
.audio_codec = AV_CODEC_ID_MP2,
.video_codec = AV_CODEC_ID_NONE,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_MPEG1VIDEO_MUXER
AVOutputFormat ff_mpeg1video_muxer = {
.name = "mpeg1video",
.long_name = NULL_IF_CONFIG_SMALL("raw MPEG-1 video"),
.mime_type = "video/mpeg",
.extensions = "mpg,mpeg,m1v",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_MPEG1VIDEO,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_MPEG2VIDEO_MUXER
AVOutputFormat ff_mpeg2video_muxer = {
.name = "mpeg2video",
.long_name = NULL_IF_CONFIG_SMALL("raw MPEG-2 video"),
.extensions = "m2v",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_MPEG2VIDEO,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_RAWVIDEO_MUXER
AVOutputFormat ff_rawvideo_muxer = {
.name = "rawvideo",
.long_name = NULL_IF_CONFIG_SMALL("raw video"),
.extensions = "yuv,rgb",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_RAWVIDEO,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_SBC_MUXER
AVOutputFormat ff_sbc_muxer = {
.name = "sbc",
.long_name = NULL_IF_CONFIG_SMALL("raw SBC"),
.mime_type = "audio/x-sbc",
.extensions = "sbc,msbc",
.audio_codec = AV_CODEC_ID_SBC,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_TRUEHD_MUXER
AVOutputFormat ff_truehd_muxer = {
.name = "truehd",
.long_name = NULL_IF_CONFIG_SMALL("raw TrueHD"),
.extensions = "thd",
.audio_codec = AV_CODEC_ID_TRUEHD,
.video_codec = AV_CODEC_ID_NONE,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif
#if CONFIG_VC1_MUXER
AVOutputFormat ff_vc1_muxer = {
.name = "vc1",
.long_name = NULL_IF_CONFIG_SMALL("raw VC-1 video"),
.extensions = "vc1",
.audio_codec = AV_CODEC_ID_NONE,
.video_codec = AV_CODEC_ID_VC1,
.write_header = force_one_stream,
.write_packet = ff_raw_write_packet,
.flags = AVFMT_NOTIMESTAMPS,
};
#endif

View File

@ -1,3 +0,0 @@
layer.c:1616:bughuntingDivByZero
layer.c:1617:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +0,0 @@
Division by zero
Details:
https://nvd.nist.gov/vuln/detail/CVE-2019-14249
Fix:
https://sourceforge.net/p/libdwarf/code/ci/cb7198abde46c2ae29957ad460da6886eaa606ba/tree/libdwarf/dwarf_elf_load_headers.c?diff=99e77c3894877a1dd80b82808d8309eded4e5599

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
dwarf_elf_load_headers.c:1838:bughuntingDivByZero

View File

@ -1,5 +0,0 @@
Details:
https://nvd.nist.gov/vuln/detail/CVE-2019-14284

View File

@ -1 +0,0 @@
floppy.c:2131:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +0,0 @@
Project:
Poppler
Details:
https://nvd.nist.gov/vuln/detail/CVE-2019-14494

File diff suppressed because it is too large Load Diff

View File

@ -1,533 +0,0 @@
//========================================================================
//
// SplashOutputDev.h
//
// Copyright 2003 Glyph & Cog, LLC
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2005 Takashi Iwai <tiwai@suse.de>
// Copyright (C) 2009-2016 Thomas Freitag <Thomas.Freitag@alfa.de>
// Copyright (C) 2009 Carlos Garcia Campos <carlosgc@gnome.org>
// Copyright (C) 2010 Christian Feuersänger <cfeuersaenger@googlemail.com>
// Copyright (C) 2011 Andreas Hartmetz <ahartmetz@gmail.com>
// Copyright (C) 2011 Andrea Canciani <ranma42@gmail.com>
// Copyright (C) 2011, 2017 Adrian Johnson <ajohnson@redneon.com>
// Copyright (C) 2012, 2015, 2018 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2015, 2016 William Bader <williambader@hotmail.com>
// Copyright (C) 2018 Stefan Brüns <stefan.bruens@rwth-aachen.de>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#ifndef SPLASHOUTPUTDEV_H
#define SPLASHOUTPUTDEV_H
#include "splash/SplashTypes.h"
#include "splash/SplashPattern.h"
#include "poppler-config.h"
#include "OutputDev.h"
#include "GfxState.h"
#include "GlobalParams.h"
class PDFDoc;
class Gfx8BitFont;
class SplashBitmap;
class Splash;
class SplashPath;
class SplashFontEngine;
class SplashFont;
class T3FontCache;
struct T3FontCacheTag;
struct T3GlyphStack;
struct SplashTransparencyGroup;
//------------------------------------------------------------------------
// Splash dynamic pattern
//------------------------------------------------------------------------
class SplashFunctionPattern : public SplashPattern {
public:
SplashFunctionPattern(SplashColorMode colorMode, GfxState *state, GfxFunctionShading *shading);
SplashPattern *copy() override {
return new SplashFunctionPattern(colorMode, state, (GfxFunctionShading *) shading);
}
~SplashFunctionPattern();
bool testPosition(int x, int y) override {
return true;
}
bool isStatic() override {
return false;
}
bool getColor(int x, int y, SplashColorPtr c) override;
virtual GfxFunctionShading *getShading() {
return shading;
}
bool isCMYK() override {
return gfxMode == csDeviceCMYK;
}
protected:
Matrix ictm;
double xMin, yMin, xMax, yMax;
GfxFunctionShading *shading;
GfxState *state;
SplashColorMode colorMode;
GfxColorSpaceMode gfxMode;
};
class SplashUnivariatePattern : public SplashPattern {
public:
SplashUnivariatePattern(SplashColorMode colorMode, GfxState *state, GfxUnivariateShading *shading);
~SplashUnivariatePattern();
bool getColor(int x, int y, SplashColorPtr c) override;
bool testPosition(int x, int y) override;
bool isStatic() override {
return false;
}
virtual bool getParameter(double xs, double ys, double *t) = 0;
virtual GfxUnivariateShading *getShading() {
return shading;
}
bool isCMYK() override {
return gfxMode == csDeviceCMYK;
}
protected:
Matrix ictm;
double t0, t1, dt;
GfxUnivariateShading *shading;
GfxState *state;
SplashColorMode colorMode;
GfxColorSpaceMode gfxMode;
};
class SplashAxialPattern : public SplashUnivariatePattern {
public:
SplashAxialPattern(SplashColorMode colorMode, GfxState *state, GfxAxialShading *shading);
SplashPattern *copy() override {
return new SplashAxialPattern(colorMode, state, (GfxAxialShading *) shading);
}
~SplashAxialPattern();
bool getParameter(double xs, double ys, double *t) override;
private:
double x0, y0, x1, y1;
double dx, dy, mul;
};
// see GfxState.h, GfxGouraudTriangleShading
class SplashGouraudPattern : public SplashGouraudColor {
public:
SplashGouraudPattern(bool bDirectColorTranslation, GfxState *state, GfxGouraudTriangleShading *shading);
SplashPattern *copy() override {
return new SplashGouraudPattern(bDirectColorTranslation, state, shading);
}
~SplashGouraudPattern();
bool getColor(int x, int y, SplashColorPtr c) override {
return false;
}
bool testPosition(int x, int y) override {
return false;
}
bool isStatic() override {
return false;
}
bool isCMYK() override {
return gfxMode == csDeviceCMYK;
}
bool isParameterized() override {
return shading->isParameterized();
}
int getNTriangles() override {
return shading->getNTriangles();
}
void getTriangle(int i, double *x0, double *y0, double *color0,
double *x1, double *y1, double *color1,
double *x2, double *y2, double *color2) override
{
shading->getTriangle(i, x0, y0, color0, x1, y1, color1, x2, y2, color2);
}
void getParameterizedColor(double t, SplashColorMode mode, SplashColorPtr c) override;
private:
GfxGouraudTriangleShading *shading;
GfxState *state;
bool bDirectColorTranslation;
GfxColorSpaceMode gfxMode;
};
// see GfxState.h, GfxRadialShading
class SplashRadialPattern : public SplashUnivariatePattern {
public:
SplashRadialPattern(SplashColorMode colorMode, GfxState *state, GfxRadialShading *shading);
SplashPattern *copy() override {
return new SplashRadialPattern(colorMode, state, (GfxRadialShading *) shading);
}
~SplashRadialPattern();
bool getParameter(double xs, double ys, double *t) override;
private:
double x0, y0, r0, dx, dy, dr;
double a, inva;
};
//------------------------------------------------------------------------
// number of Type 3 fonts to cache
#define splashOutT3FontCacheSize 8
//------------------------------------------------------------------------
// SplashOutputDev
//------------------------------------------------------------------------
class SplashOutputDev : public OutputDev {
public:
// Constructor.
SplashOutputDev(SplashColorMode colorModeA, int bitmapRowPadA,
bool reverseVideoA, SplashColorPtr paperColorA,
bool bitmapTopDownA = true,
SplashThinLineMode thinLineMode = splashThinLineDefault,
bool overprintPreviewA = globalParams->getOverprintPreview());
// Destructor.
~SplashOutputDev();
//----- get info about output device
// Does this device use tilingPatternFill()? If this returns false,
// tiling pattern fills will be reduced to a series of other drawing
// operations.
bool useTilingPatternFill() override {
return true;
}
// Does this device use functionShadedFill(), axialShadedFill(), and
// radialShadedFill()? If this returns false, these shaded fills
// will be reduced to a series of other drawing operations.
bool useShadedFills(int type) override
{
return (type >= 1 && type <= 5) ? true : false;
}
// Does this device use upside-down coordinates?
// (Upside-down means (0,0) is the top left corner of the page.)
bool upsideDown() override {
return bitmapTopDown ^ bitmapUpsideDown;
}
// Does this device use drawChar() or drawString()?
bool useDrawChar() override {
return true;
}
// Does this device use beginType3Char/endType3Char? Otherwise,
// text in Type 3 fonts will be drawn with drawChar/drawString.
bool interpretType3Chars() override {
return true;
}
//----- initialization and control
// Start a page.
void startPage(int pageNum, GfxState *state, XRef *xref) override;
// End a page.
void endPage() override;
//----- save/restore graphics state
void saveState(GfxState *state) override;
void restoreState(GfxState *state) override;
//----- update graphics state
void updateAll(GfxState *state) override;
void updateCTM(GfxState *state, double m11, double m12,
double m21, double m22, double m31, double m32) override;
void updateLineDash(GfxState *state) override;
void updateFlatness(GfxState *state) override;
void updateLineJoin(GfxState *state) override;
void updateLineCap(GfxState *state) override;
void updateMiterLimit(GfxState *state) override;
void updateLineWidth(GfxState *state) override;
void updateStrokeAdjust(GfxState *state) override;
void updateFillColorSpace(GfxState *state) override;
void updateStrokeColorSpace(GfxState *state) override;
void updateFillColor(GfxState *state) override;
void updateStrokeColor(GfxState *state) override;
void updateBlendMode(GfxState *state) override;
void updateFillOpacity(GfxState *state) override;
void updateStrokeOpacity(GfxState *state) override;
void updatePatternOpacity(GfxState *state) override;
void clearPatternOpacity(GfxState *state) override;
void updateFillOverprint(GfxState *state) override;
void updateStrokeOverprint(GfxState *state) override;
void updateOverprintMode(GfxState *state) override;
void updateTransfer(GfxState *state) override;
//----- update text state
void updateFont(GfxState *state) override;
//----- path painting
void stroke(GfxState *state) override;
void fill(GfxState *state) override;
void eoFill(GfxState *state) override;
bool tilingPatternFill(GfxState *state, Gfx *gfx, Catalog *catalog, Object *str,
const double *pmat, int paintType, int tilingType, Dict *resDict,
const double *mat, const double *bbox,
int x0, int y0, int x1, int y1,
double xStep, double yStep) override;
bool functionShadedFill(GfxState *state, GfxFunctionShading *shading) override;
bool axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax) override;
bool radialShadedFill(GfxState *state, GfxRadialShading *shading, double tMin, double tMax) override;
bool gouraudTriangleShadedFill(GfxState *state, GfxGouraudTriangleShading *shading) override;
//----- path clipping
void clip(GfxState *state) override;
void eoClip(GfxState *state) override;
void clipToStrokePath(GfxState *state) override;
//----- text drawing
void drawChar(GfxState *state, double x, double y,
double dx, double dy,
double originX, double originY,
CharCode code, int nBytes, Unicode *u, int uLen) override;
bool beginType3Char(GfxState *state, double x, double y,
double dx, double dy,
CharCode code, Unicode *u, int uLen) override;
void endType3Char(GfxState *state) override;
void beginTextObject(GfxState *state) override;
void endTextObject(GfxState *state) override;
//----- image drawing
void drawImageMask(GfxState *state, Object *ref, Stream *str,
int width, int height, bool invert,
bool interpolate, bool inlineImg) override;
void setSoftMaskFromImageMask(GfxState *state,
Object *ref, Stream *str,
int width, int height, bool invert,
bool inlineImg, double *baseMatrix) override;
void unsetSoftMaskFromImageMask(GfxState *state, double *baseMatrix) override;
void drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height, GfxImageColorMap *colorMap,
bool interpolate, int *maskColors, bool inlineImg) override;
void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
bool interpolate,
Stream *maskStr, int maskWidth, int maskHeight,
bool maskInvert, bool maskInterpolate) override;
void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
bool interpolate,
Stream *maskStr,
int maskWidth, int maskHeight,
GfxImageColorMap *maskColorMap,
bool maskInterpolate) override;
//----- Type 3 font operators
void type3D0(GfxState *state, double wx, double wy) override;
void type3D1(GfxState *state, double wx, double wy,
double llx, double lly, double urx, double ury) override;
//----- transparency groups and soft masks
bool checkTransparencyGroup(GfxState *state, bool knockout) override;
void beginTransparencyGroup(GfxState *state, const double *bbox,
GfxColorSpace *blendingColorSpace,
bool isolated, bool knockout,
bool forSoftMask) override;
void endTransparencyGroup(GfxState *state) override;
void paintTransparencyGroup(GfxState *state, const double *bbox) override;
void setSoftMask(GfxState *state, const double *bbox, bool alpha,
Function *transferFunc, GfxColor *backdropColor) override;
void clearSoftMask(GfxState *state) override;
//----- special access
// Called to indicate that a new PDF document has been loaded.
void startDoc(PDFDoc *docA);
void setPaperColor(SplashColorPtr paperColorA);
bool isReverseVideo() {
return reverseVideo;
}
void setReverseVideo(bool reverseVideoA) {
reverseVideo = reverseVideoA;
}
// Get the bitmap and its size.
SplashBitmap *getBitmap() {
return bitmap;
}
int getBitmapWidth();
int getBitmapHeight();
// Returns the last rasterized bitmap, transferring ownership to the
// caller.
SplashBitmap *takeBitmap();
// Set this flag to true to generate an upside-down bitmap (useful
// for Windows BMP files).
void setBitmapUpsideDown(bool f) {
bitmapUpsideDown = f;
}
// Get the Splash object.
Splash *getSplash() {
return splash;
}
// Get the modified region.
void getModRegion(int *xMin, int *yMin, int *xMax, int *yMax);
// Clear the modified region.
void clearModRegion();
SplashFont *getCurrentFont() {
return font;
}
// If <skipTextA> is true, don't draw horizontal text.
// If <skipRotatedTextA> is true, don't draw rotated (non-horizontal) text.
void setSkipText(bool skipHorizTextA, bool skipRotatedTextA)
{
skipHorizText = skipHorizTextA; skipRotatedText = skipRotatedTextA;
}
int getNestCount() {
return nestCount;
}
#if 1 //~tmp: turn off anti-aliasing temporarily
bool getVectorAntialias() override;
void setVectorAntialias(bool vaa) override;
#endif
bool getFontAntialias() {
return fontAntialias;
}
void setFontAntialias(bool anti) {
fontAntialias = anti;
}
void setFreeTypeHinting(bool enable, bool enableSlightHinting);
protected:
void doUpdateFont(GfxState *state);
private:
bool univariateShadedFill(GfxState *state, SplashUnivariatePattern *pattern, double tMin, double tMax);
void setupScreenParams(double hDPI, double vDPI);
SplashPattern *getColor(GfxGray gray);
SplashPattern *getColor(GfxRGB *rgb);
#ifdef SPLASH_CMYK
SplashPattern *getColor(GfxCMYK *cmyk);
SplashPattern *getColor(GfxColor *deviceN);
#endif
static void getMatteColor( SplashColorMode colorMode, GfxImageColorMap *colorMap, const GfxColor * matteColor, SplashColor splashMatteColor);
void setOverprintMask(GfxColorSpace *colorSpace, bool overprintFlag,
int overprintMode, const GfxColor *singleColor, bool grayIndexed = false);
SplashPath convertPath(GfxState *state, GfxPath *path,
bool dropEmptySubpaths);
void drawType3Glyph(GfxState *state, T3FontCache *t3Font,
T3FontCacheTag *tag, unsigned char *data);
#ifdef USE_CMS
bool useIccImageSrc(void *data);
static void iccTransform(void *data, SplashBitmap *bitmap);
static bool iccImageSrc(void *data, SplashColorPtr colorLine,
unsigned char *alphaLine);
#endif
static bool imageMaskSrc(void *data, SplashColorPtr line);
static bool imageSrc(void *data, SplashColorPtr colorLine,
unsigned char *alphaLine);
static bool alphaImageSrc(void *data, SplashColorPtr line,
unsigned char *alphaLine);
static bool maskedImageSrc(void *data, SplashColorPtr line,
unsigned char *alphaLine);
static bool tilingBitmapSrc(void *data, SplashColorPtr line,
unsigned char *alphaLine);
bool keepAlphaChannel; // don't fill with paper color, keep alpha channel
SplashColorMode colorMode;
int bitmapRowPad;
bool bitmapTopDown;
bool bitmapUpsideDown;
bool fontAntialias;
bool vectorAntialias;
bool overprintPreview;
bool enableFreeTypeHinting;
bool enableSlightHinting;
bool reverseVideo; // reverse video mode
SplashColor paperColor; // paper color
SplashScreenParams screenParams;
bool skipHorizText;
bool skipRotatedText;
PDFDoc *doc; // the current document
XRef *xref; // the xref of the current document
SplashBitmap *bitmap;
Splash *splash;
SplashFontEngine *fontEngine;
T3FontCache * // Type 3 font cache
t3FontCache[splashOutT3FontCacheSize];
int nT3Fonts; // number of valid entries in t3FontCache
T3GlyphStack *t3GlyphStack; // Type 3 glyph context stack
SplashFont *font; // current font
bool needFontUpdate; // set when the font needs to be updated
SplashPath *textClipPath; // clipping path built with text object
SplashTransparencyGroup * // transparency group stack
transpGroupStack;
int nestCount;
};
#endif

View File

@ -1,3 +0,0 @@
SplashOutputDev.cc:4584:bughuntingDivByZero
SplashOutputDev.cc:4585:bughuntingDivByZero

View File

@ -1 +0,0 @@
feature.c:2291:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
-DCV_EXPORTS_W=
-DCV_EXPORTS=

View File

@ -1,5 +0,0 @@
hog.cpp:92:bughuntingDivByZero
hog.cpp:93:bughuntingDivByZero
hog.cpp:94:bughuntingDivByZero
hog.cpp:95:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1,753 +0,0 @@
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef OPENCV_OBJDETECT_HPP
#define OPENCV_OBJDETECT_HPP
#include "opencv2/core.hpp"
/**
@defgroup objdetect Object Detection
Haar Feature-based Cascade Classifier for Object Detection
----------------------------------------------------------
The object detector described below has been initially proposed by Paul Viola @cite Viola01 and
improved by Rainer Lienhart @cite Lienhart02 .
First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is
trained with a few hundred sample views of a particular object (i.e., a face or a car), called
positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary
images of the same size.
After a classifier is trained, it can be applied to a region of interest (of the same size as used
during the training) in an input image. The classifier outputs a "1" if the region is likely to show
the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can
move the search window across the image and check every location using the classifier. The
classifier is designed so that it can be easily "resized" in order to be able to find the objects of
interest at different sizes, which is more efficient than resizing the image itself. So, to find an
object of an unknown size in the image the scan procedure should be done several times at different
scales.
The word "cascade" in the classifier name means that the resultant classifier consists of several
simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some
stage the candidate is rejected or all the stages are passed. The word "boosted" means that the
classifiers at every stage of the cascade are complex themselves and they are built out of basic
classifiers using one of four different boosting techniques (weighted voting). Currently Discrete
Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are
decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic
classifiers, and are calculated as described below. The current algorithm uses the following
Haar-like features:
![image](pics/haarfeatures.png)
The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within
the region of interest and the scale (this scale is not the same as the scale used at the detection
stage, though these two scales are multiplied). For example, in the case of the third line feature
(2c) the response is calculated as the difference between the sum of image pixels under the
rectangle covering the whole feature (including the two white stripes and the black stripe in the
middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to
compensate for the differences in the size of areas. The sums of pixel values over a rectangular
regions are calculated rapidly using integral images (see below and the integral description).
To see the object detector at work, have a look at the facedetect demo:
<https://github.com/opencv/opencv/tree/master/samples/cpp/dbt_face_detection.cpp>
The following reference is for the detection part only. There is a separate application called
opencv_traincascade that can train a cascade of boosted classifiers from a set of samples.
@note In the new C++ interface it is also possible to use LBP (local binary pattern) features in
addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection
using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at
<http://research.microsoft.com/en-us/um/people/viola/Pubs/Detect/violaJones_CVPR2001.pdf>
@{
@defgroup objdetect_c C API
@}
*/
typedef struct CvHaarClassifierCascade CvHaarClassifierCascade;
namespace cv
{
//! @addtogroup objdetect
//! @{
///////////////////////////// Object Detection ////////////////////////////
//! class for grouping object candidates, detected by Cascade Classifier, HOG etc.
//! instance of the class is to be passed to cv::partition (see cxoperations.hpp)
class CV_EXPORTS SimilarRects
{
public:
SimilarRects(double _eps) : eps(_eps) {}
inline bool operator()(const Rect& r1, const Rect& r2) const
{
double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5;
return std::abs(r1.x - r2.x) <= delta &&
std::abs(r1.y - r2.y) <= delta &&
std::abs(r1.x + r1.width - r2.x - r2.width) <= delta &&
std::abs(r1.y + r1.height - r2.y - r2.height) <= delta;
}
double eps;
};
/** @brief Groups the object candidate rectangles.
@param rectList Input/output vector of rectangles. Output vector includes retained and grouped
rectangles. (The Python list is not modified in place.)
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a
group of rectangles to retain it.
@param eps Relative difference between sides of the rectangles to merge them into a group.
The function is a wrapper for the generic function partition . It clusters all the input rectangles
using the rectangle equivalence criteria that combines rectangles with similar sizes and similar
locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If
\f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small
clusters containing less than or equal to groupThreshold rectangles are rejected. In each other
cluster, the average rectangle is computed and put into the output rectangle list.
*/
CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, int groupThreshold, double eps = 0.2);
/** @overload */
CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector<Rect>& rectList, CV_OUT std::vector<int>& weights,
int groupThreshold, double eps = 0.2);
/** @overload */
CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, int groupThreshold,
double eps, std::vector<int>* weights, std::vector<double>* levelWeights );
/** @overload */
CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, std::vector<int>& rejectLevels,
std::vector<double>& levelWeights, int groupThreshold, double eps = 0.2);
/** @overload */
CV_EXPORTS void groupRectangles_meanshift(std::vector<Rect>& rectList, std::vector<double>& foundWeights,
std::vector<double>& foundScales,
double detectThreshold = 0.0, Size winDetSize = Size(64, 128));
template<> struct DefaultDeleter<CvHaarClassifierCascade>{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; };
enum { CASCADE_DO_CANNY_PRUNING = 1,
CASCADE_SCALE_IMAGE = 2,
CASCADE_FIND_BIGGEST_OBJECT = 4,
CASCADE_DO_ROUGH_SEARCH = 8
};
class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm
{
public:
virtual ~BaseCascadeClassifier();
virtual bool empty() const CV_OVERRIDE = 0;
virtual bool load( const String& filename ) = 0;
virtual void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
double scaleFactor,
int minNeighbors, int flags,
Size minSize, Size maxSize ) = 0;
virtual void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& numDetections,
double scaleFactor,
int minNeighbors, int flags,
Size minSize, Size maxSize ) = 0;
virtual void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& rejectLevels,
CV_OUT std::vector<double>& levelWeights,
double scaleFactor,
int minNeighbors, int flags,
Size minSize, Size maxSize,
bool outputRejectLevels ) = 0;
virtual bool isOldFormatCascade() const = 0;
virtual Size getOriginalWindowSize() const = 0;
virtual int getFeatureType() const = 0;
virtual void* getOldCascade() = 0;
class CV_EXPORTS MaskGenerator
{
public:
virtual ~MaskGenerator() {}
virtual Mat generateMask(const Mat& src)=0;
virtual void initializeMask(const Mat& /*src*/) { }
};
virtual void setMaskGenerator(const Ptr<MaskGenerator>& maskGenerator) = 0;
virtual Ptr<MaskGenerator> getMaskGenerator() = 0;
};
/** @example samples/cpp/facedetect.cpp
This program demonstrates usage of the Cascade classifier class
\image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254
*/
/** @brief Cascade classifier class for object detection.
*/
class CV_EXPORTS_W CascadeClassifier
{
public:
CV_WRAP CascadeClassifier();
/** @brief Loads a classifier from a file.
@param filename Name of the file from which the classifier is loaded.
*/
CV_WRAP CascadeClassifier(const String& filename);
~CascadeClassifier();
/** @brief Checks whether the classifier has been loaded.
*/
CV_WRAP bool empty() const;
/** @brief Loads a classifier from a file.
@param filename Name of the file from which the classifier is loaded. The file may contain an old
HAAR classifier trained by the haartraining application or a new cascade classifier trained by the
traincascade application.
*/
CV_WRAP bool load( const String& filename );
/** @brief Reads a classifier from a FileStorage node.
@note The file may contain a new cascade classifier (trained traincascade application) only.
*/
CV_WRAP bool read( const FileNode& node );
/** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
of rectangles.
@param image Matrix of the type CV_8U containing an image where objects are detected.
@param objects Vector of rectangles where each rectangle contains the detected object, the
rectangles may be partially outside the original image.
@param scaleFactor Parameter specifying how much the image size is reduced at each image scale.
@param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have
to retain it.
@param flags Parameter with the same meaning for an old cascade as in the function
cvHaarDetectObjects. It is not used for a new cascade.
@param minSize Minimum possible object size. Objects smaller than that are ignored.
@param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale.
The function is parallelized with the TBB library.
@note
- (Python) A face detection example using cascade classifiers can be found at
opencv_source_code/samples/python/facedetect.py
*/
CV_WRAP void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
double scaleFactor = 1.1,
int minNeighbors = 3, int flags = 0,
Size minSize = Size(),
Size maxSize = Size() );
/** @overload
@param image Matrix of the type CV_8U containing an image where objects are detected.
@param objects Vector of rectangles where each rectangle contains the detected object, the
rectangles may be partially outside the original image.
@param numDetections Vector of detection numbers for the corresponding objects. An object's number
of detections is the number of neighboring positively classified rectangles that were joined
together to form the object.
@param scaleFactor Parameter specifying how much the image size is reduced at each image scale.
@param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have
to retain it.
@param flags Parameter with the same meaning for an old cascade as in the function
cvHaarDetectObjects. It is not used for a new cascade.
@param minSize Minimum possible object size. Objects smaller than that are ignored.
@param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale.
*/
CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& numDetections,
double scaleFactor=1.1,
int minNeighbors=3, int flags=0,
Size minSize=Size(),
Size maxSize=Size() );
/** @overload
This function allows you to retrieve the final stage decision certainty of classification.
For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter.
For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage.
This value can then be used to separate strong from weaker classifications.
A code sample on how to use it efficiently can be found below:
@code
Mat img;
vector<double> weights;
vector<int> levels;
vector<Rect> detections;
CascadeClassifier model("/path/to/your/model.xml");
model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true);
cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl;
@endcode
*/
CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& rejectLevels,
CV_OUT std::vector<double>& levelWeights,
double scaleFactor = 1.1,
int minNeighbors = 3, int flags = 0,
Size minSize = Size(),
Size maxSize = Size(),
bool outputRejectLevels = false );
CV_WRAP bool isOldFormatCascade() const;
CV_WRAP Size getOriginalWindowSize() const;
CV_WRAP int getFeatureType() const;
void* getOldCascade();
CV_WRAP static bool convert(const String& oldcascade, const String& newcascade);
void setMaskGenerator(const Ptr<BaseCascadeClassifier::MaskGenerator>& maskGenerator);
Ptr<BaseCascadeClassifier::MaskGenerator> getMaskGenerator();
Ptr<BaseCascadeClassifier> cc;
};
CV_EXPORTS Ptr<BaseCascadeClassifier::MaskGenerator> createFaceDetectionMaskGenerator();
//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
//! struct for detection region of interest (ROI)
struct DetectionROI
{
//! scale(size) of the bounding box
double scale;
//! set of requested locations to be evaluated
std::vector<cv::Point> locations;
//! vector that will contain confidence values for each location
std::vector<double> confidences;
};
/**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector.
the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 .
useful links:
https://hal.inria.fr/inria-00548512/document/
https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients
https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor
http://www.learnopencv.com/histogram-of-oriented-gradients
http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial
*/
struct CV_EXPORTS_W HOGDescriptor
{
public:
enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType
};
enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value.
};
enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW };
/**@brief Creates the HOG descriptor and detector with default params.
aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 )
*/
CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8),
cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1),
histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true),
free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false)
{}
/** @overload
@param _winSize sets winSize with given value.
@param _blockSize sets blockSize with given value.
@param _blockStride sets blockStride with given value.
@param _cellSize sets cellSize with given value.
@param _nbins sets nbins with given value.
@param _derivAperture sets derivAperture with given value.
@param _winSigma sets winSigma with given value.
@param _histogramNormType sets histogramNormType with given value.
@param _L2HysThreshold sets L2HysThreshold with given value.
@param _gammaCorrection sets gammaCorrection with given value.
@param _nlevels sets nlevels with given value.
@param _signedGradient sets signedGradient with given value.
*/
CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride,
Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1,
HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys,
double _L2HysThreshold=0.2, bool _gammaCorrection=false,
int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false)
: winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize),
nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma),
histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold),
gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient)
{}
/** @overload
@param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier.
*/
CV_WRAP HOGDescriptor(const String& filename)
{
load(filename);
}
/** @overload
@param d the HOGDescriptor which cloned to create a new one.
*/
HOGDescriptor(const HOGDescriptor& d)
{
d.copyTo(*this);
}
/**@brief Default destructor.
*/
virtual ~HOGDescriptor() {}
/**@brief Returns the number of coefficients required for the classification.
*/
CV_WRAP size_t getDescriptorSize() const;
/** @brief Checks if detector size equal to descriptor size.
*/
CV_WRAP bool checkDetectorSize() const;
/** @brief Returns winSigma value
*/
CV_WRAP double getWinSigma() const;
/**@example samples/cpp/peopledetect.cpp
*/
/**@brief Sets coefficients for the linear SVM classifier.
@param svmdetector coefficients for the linear SVM classifier.
*/
CV_WRAP virtual void setSVMDetector(InputArray svmdetector);
/** @brief Reads HOGDescriptor parameters from a cv::FileNode.
@param fn File node
*/
virtual bool read(FileNode& fn);
/** @brief Stores HOGDescriptor parameters in a cv::FileStorage.
@param fs File storage
@param objname Object name
*/
virtual void write(FileStorage& fs, const String& objname) const;
/** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file.
@param filename Path of the file to read.
@param objname The optional name of the node to read (if empty, the first top-level node will be used).
*/
CV_WRAP virtual bool load(const String& filename, const String& objname = String());
/** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file
@param filename File name
@param objname Object name
*/
CV_WRAP virtual void save(const String& filename, const String& objname = String()) const;
/** @brief clones the HOGDescriptor
@param c cloned HOGDescriptor
*/
virtual void copyTo(HOGDescriptor& c) const;
/**@example samples/cpp/train_HOG.cpp
*/
/** @brief Computes HOG descriptors of given image.
@param img Matrix of the type CV_8U containing an image where HOG features will be calculated.
@param descriptors Matrix of the type CV_32F
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param locations Vector of Point
*/
CV_WRAP virtual void compute(InputArray img,
CV_OUT std::vector<float>& descriptors,
Size winStride = Size(), Size padding = Size(),
const std::vector<Point>& locations = std::vector<Point>()) const;
/** @brief Performs object detection without a multi-scale window.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries.
@param weights Vector that will contain confidence values for each detected object.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param searchLocations Vector of Point includes set of requested locations to be evaluated.
*/
CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector<Point>& foundLocations,
CV_OUT std::vector<double>& weights,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(),
const std::vector<Point>& searchLocations = std::vector<Point>()) const;
/** @brief Performs object detection without a multi-scale window.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param searchLocations Vector of Point includes locations to search.
*/
virtual void detect(InputArray img, CV_OUT std::vector<Point>& foundLocations,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(),
const std::vector<Point>& searchLocations=std::vector<Point>()) const;
/** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
of rectangles.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of rectangles where each rectangle contains the detected object.
@param foundWeights Vector that will contain confidence values for each detected object.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param scale Coefficient of the detection window increase.
@param finalThreshold Final threshold
@param useMeanshiftGrouping indicates grouping algorithm
*/
CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector<Rect>& foundLocations,
CV_OUT std::vector<double>& foundWeights, double hitThreshold = 0,
Size winStride = Size(), Size padding = Size(), double scale = 1.05,
double finalThreshold = 2.0,bool useMeanshiftGrouping = false) const;
/** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
of rectangles.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of rectangles where each rectangle contains the detected object.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param scale Coefficient of the detection window increase.
@param finalThreshold Final threshold
@param useMeanshiftGrouping indicates grouping algorithm
*/
virtual void detectMultiScale(InputArray img, CV_OUT std::vector<Rect>& foundLocations,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(), double scale = 1.05,
double finalThreshold = 2.0, bool useMeanshiftGrouping = false) const;
/** @brief Computes gradients and quantized gradient orientations.
@param img Matrix contains the image to be computed
@param grad Matrix of type CV_32FC2 contains computed gradients
@param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations
@param paddingTL Padding from top-left
@param paddingBR Padding from bottom-right
*/
CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs,
Size paddingTL = Size(), Size paddingBR = Size()) const;
/** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows).
*/
CV_WRAP static std::vector<float> getDefaultPeopleDetector();
/**@example samples/tapi/hog.cpp
*/
/** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows).
*/
CV_WRAP static std::vector<float> getDaimlerPeopleDetector();
//! Detection window size. Align to block size and block stride. Default value is Size(64,128).
CV_PROP Size winSize;
//! Block size in pixels. Align to cell size. Default value is Size(16,16).
CV_PROP Size blockSize;
//! Block stride. It must be a multiple of cell size. Default value is Size(8,8).
CV_PROP Size blockStride;
//! Cell size. Default value is Size(8,8).
CV_PROP Size cellSize;
//! Number of bins used in the calculation of histogram of gradients. Default value is 9.
CV_PROP int nbins;
//! not documented
CV_PROP int derivAperture;
//! Gaussian smoothing window parameter.
CV_PROP double winSigma;
//! histogramNormType
CV_PROP HOGDescriptor::HistogramNormType histogramNormType;
//! L2-Hys normalization method shrinkage.
CV_PROP double L2HysThreshold;
//! Flag to specify whether the gamma correction preprocessing is required or not.
CV_PROP bool gammaCorrection;
//! coefficients for the linear SVM classifier.
CV_PROP std::vector<float> svmDetector;
//! coefficients for the linear SVM classifier used when OpenCL is enabled
UMat oclSvmDetector;
//! not documented
float free_coef;
//! Maximum number of detection window increases. Default value is 64
CV_PROP int nlevels;
//! Indicates signed gradient will be used or not
CV_PROP bool signedGradient;
/** @brief evaluate specified ROI and return confidence value for each location
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param locations Vector of Point
@param foundLocations Vector of Point where each Point is detected object's top-left point.
@param confidences confidences
@param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually
it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if
the free coefficient is omitted (which is allowed), you can specify it manually here
@param winStride winStride
@param padding padding
*/
virtual void detectROI(InputArray img, const std::vector<cv::Point> &locations,
CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
double hitThreshold = 0, cv::Size winStride = Size(),
cv::Size padding = Size()) const;
/** @brief evaluate specified ROI and return confidence value for each location in multiple scales
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of rectangles where each rectangle contains the detected object.
@param locations Vector of DetectionROI
@param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified
in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
*/
virtual void detectMultiScaleROI(InputArray img,
CV_OUT std::vector<cv::Rect>& foundLocations,
std::vector<DetectionROI>& locations,
double hitThreshold = 0,
int groupThreshold = 0) const;
/** @brief Groups the object candidate rectangles.
@param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.)
@param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.)
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
@param eps Relative difference between sides of the rectangles to merge them into a group.
*/
void groupRectangles(std::vector<cv::Rect>& rectList, std::vector<double>& weights, int groupThreshold, double eps) const;
};
class CV_EXPORTS_W QRCodeDetector
{
public:
CV_WRAP QRCodeDetector();
~QRCodeDetector();
/** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection.
@param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern
of the scheme 1:1:3:1:1 according to QR code standard.
*/
CV_WRAP void setEpsX(double epsX);
/** @brief sets the epsilon used during the vertical scan of QR code stop marker detection.
@param epsY Epsilon neighborhood, which allows you to determine the vertical pattern
of the scheme 1:1:3:1:1 according to QR code standard.
*/
CV_WRAP void setEpsY(double epsY);
/** @brief Detects QR code in image and returns the quadrangle containing the code.
@param img grayscale or color (BGR) image containing (or not) QR code.
@param points Output vector of vertices of the minimum-area quadrangle containing the code.
*/
CV_WRAP bool detect(InputArray img, OutputArray points) const;
/** @brief Decodes QR code in image once it's found by the detect() method.
Returns UTF8-encoded output string or empty string if the code cannot be decoded.
@param img grayscale or color (BGR) image containing QR code.
@param points Quadrangle vertices found by detect() method (or some other algorithm).
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
/** @brief Both detects and decodes QR code
@param img grayscale or color (BGR) image containing QR code.
@param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points=noArray(),
OutputArray straight_qrcode = noArray());
/** @brief Detects QR codes in image and returns the vector of the quadrangles containing the codes.
@param img grayscale or color (BGR) image containing (or not) QR codes.
@param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes.
*/
CV_WRAP
bool detectMulti(InputArray img, OutputArray points) const;
/** @brief Decodes QR codes in image once it's found by the detect() method.
@param img grayscale or color (BGR) image containing QR codes.
@param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
@param points vector of Quadrangle vertices found by detect() method (or some other algorithm).
@param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
*/
CV_WRAP
bool decodeMulti(
InputArray img, InputArray points,
CV_OUT std::vector<std::string>& decoded_info,
OutputArrayOfArrays straight_qrcode = noArray()
) const;
/** @brief Both detects and decodes QR codes
@param img grayscale or color (BGR) image containing QR codes.
@param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
@param points optional output vector of vertices of the found QR code quadrangles. Will be empty if not found.
@param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
*/
CV_WRAP
bool detectAndDecodeMulti(
InputArray img, CV_OUT std::vector<std::string>& decoded_info,
OutputArray points = noArray(),
OutputArrayOfArrays straight_qrcode = noArray()
) const;
protected:
struct Impl;
Ptr<Impl> p;
};
//! @} objdetect
}
#include "opencv2/objdetect/detection_based_tracker.hpp"
#endif

View File

@ -1,53 +0,0 @@
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
#include "opencv2/objdetect.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/core/private.hpp"
#endif

View File

@ -1 +0,0 @@
where.c:2673:bughuntingDivByZero

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
-DLY_CHECK_ERR_RETURN(A,B,C)=

View File

@ -1,3 +0,0 @@
parser.c:1024:bughuntingBufferOverflow
parser.c:1026:bughuntingBufferOverflow

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
jfif.c:430:bughuntingDivByZero

View File

@ -1,862 +0,0 @@
/* 包含头文件 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stdefine.h"
#include "bitstr.h"
#include "huffman.h"
#include "quant.h"
#include "zigzag.h"
#include "dct.h"
#include "bmp.h"
#include "color.h"
#include "jfif.h"
// 预编译开关
#define DEBUG_JFIF 0
// 内部类型定义
typedef struct {
// width & height
int width;
int height;
// quantization table
int *pqtab[16];
// huffman codec ac
HUFCODEC *phcac[16];
// huffman codec dc
HUFCODEC *phcdc[16];
// components
int comp_num;
struct {
int id;
int samp_factor_v;
int samp_factor_h;
int qtab_idx;
int htab_idx_ac;
int htab_idx_dc;
} comp_info[4];
int datalen;
BYTE *databuf;
} JFIF;
/* 内部函数实现 */
#if DEBUG_JFIF
static void jfif_dump(JFIF *jfif)
{
int i, j;
printf("++ jfif dump ++\n");
printf("width : %d\n", jfif->width );
printf("height: %d\n", jfif->height);
printf("\n");
for (i=0; i<16; i++) {
if (!jfif->pqtab[i]) continue;
printf("qtab%d\n", i);
for (j=0; j<64; j++) {
printf("%3d,%c", jfif->pqtab[i][j], j%8 == 7 ? '\n' : ' ');
}
printf("\n");
}
for (i=0; i<16; i++) {
int size = 16;
if (!jfif->phcac[i]) continue;
printf("htabac%d\n", i);
for (j=0; j<16; j++) {
size += jfif->phcac[i]->huftab[j];
}
for (j=0; j<size; j++) {
printf("%3d,%c", jfif->phcac[i]->huftab[j], j%16 == 15 ? '\n' : ' ');
}
printf("\n\n");
}
for (i=0; i<16; i++) {
int size = 16;
if (!jfif->phcdc[i]) continue;
printf("htabdc%d\n", i);
for (j=0; j<16; j++) {
size += jfif->phcdc[i]->huftab[j];
}
for (j=0; j<size; j++) {
printf("%3d,%c", jfif->phcdc[i]->huftab[j], j%16 == 15 ? '\n' : ' ');
}
printf("\n\n");
}
printf("comp_num : %d\n", jfif->comp_num);
for (i=0; i<jfif->comp_num; i++) {
printf("id:%d samp_factor_v:%d samp_factor_h:%d qtab_idx:%d htab_idx_ac:%d htab_idx_dc:%d\n",
jfif->comp_info[i].id,
jfif->comp_info[i].samp_factor_v,
jfif->comp_info[i].samp_factor_h,
jfif->comp_info[i].qtab_idx,
jfif->comp_info[i].htab_idx_ac,
jfif->comp_info[i].htab_idx_dc);
}
printf("\n");
printf("datalen : %d\n", jfif->datalen);
printf("-- jfif dump --\n");
}
static void dump_du(int *du)
{
int i;
for (i=0; i<64; i++) {
printf("%3d%c", du[i], i % 8 == 7 ? '\n' : ' ');
}
printf("\n");
}
#endif
static int ALIGN(int x, int y) {
// y must be a power of 2.
return (x + y - 1) & ~(y - 1);
}
static void category_encode(int *code, int *size)
{
unsigned absc = abs(*code);
unsigned mask = (1 << 15);
int i = 15;
if (absc == 0) { *size = 0; return; }
while (i && !(absc & mask)) { mask >>= 1; i--; }
*size = i + 1;
if (*code < 0) *code = (1 << *size) - absc - 1;
}
static int category_decode(int code, int size)
{
return code >= (1 << (size - 1)) ? code : code - (1 << size) + 1;
}
/* 函数实现 */
void* jfif_load(char *file)
{
JFIF *jfif = NULL;
FILE *fp = NULL;
int header = 0;
int type = 0;
WORD size = 0;
BYTE *buf = NULL;
BYTE *end = NULL;
BYTE *dqt, *dht;
int ret =-1;
long offset = 0;
int i;
jfif = calloc(1, sizeof(JFIF));
buf = calloc(1, 0x10000);
end = buf + 0x10000;
if (!jfif || !buf) goto done;
fp = fopen(file, "rb");
if (!fp) goto done;
while (1) {
do { header = fgetc(fp); } while (header != EOF && header != 0xff); // get header
do { type = fgetc(fp); } while (type != EOF && type == 0xff); // get type
if (header == EOF || type == EOF) {
printf("file eof !\n");
break;
}
if ((type == 0xd8) || (type == 0xd9) || (type == 0x01) || (type >= 0xd0 && type <= 0xd7)) {
size = 0;
} else {
size = fgetc(fp) << 8;
size |= fgetc(fp) << 0;
size -= 2;
}
size = fread(buf, 1, size, fp);
switch (type) {
case 0xc0: // SOF0
jfif->width = (buf[3] << 8) | (buf[4] << 0);
jfif->height = (buf[1] << 8) | (buf[2] << 0);
jfif->comp_num = buf[5] < 4 ? buf[5] : 4;
for (i=0; i<jfif->comp_num; i++) {
jfif->comp_info[i].id = buf[6 + i * 3];
jfif->comp_info[i].samp_factor_v = (buf[7 + i * 3] >> 0) & 0x0f;
jfif->comp_info[i].samp_factor_h = (buf[7 + i * 3] >> 4) & 0x0f;
jfif->comp_info[i].qtab_idx = buf[8 + i * 3] & 0x0f;
}
break;
case 0xda: // SOS
jfif->comp_num = buf[0] < 4 ? buf[0] : 4;
for (i=0; i<jfif->comp_num; i++) {
jfif->comp_info[i].id = buf[1 + i * 2];
jfif->comp_info[i].htab_idx_ac = (buf[2 + i * 2] >> 0) & 0x0f;
jfif->comp_info[i].htab_idx_dc = (buf[2 + i * 2] >> 4) & 0x0f;
}
offset = ftell(fp);
ret = 0;
goto read_data;
case 0xdb: // DQT
dqt = buf;
while (size > 0 && dqt < end) {
int idx = dqt[0] & 0x0f;
int f16 = dqt[0] & 0xf0;
if (!jfif->pqtab[idx]) jfif->pqtab[idx] = malloc(64 * sizeof(int));
if (!jfif->pqtab[idx]) break;
if (dqt + 1 + 64 + (f16 ? 64 : 0) < end) {
for (i=0; i<64; i++) {
jfif->pqtab[idx][ZIGZAG[i]] = f16 ? ((dqt[1 + i * 2] << 8) | (dqt[2 + i * 2] << 0)) : dqt[1 + i];
}
}
dqt += 1 + 64 + (f16 ? 64 : 0);
size-= 1 + 64 + (f16 ? 64 : 0);
}
break;
case 0xc4: // DHT
dht = buf;
while (size > 0 && dht + 17 < end) {
int idx = dht[0] & 0x0f;
int fac = dht[0] & 0xf0;
int len = 0;
for (i=1; i<1+16; i++) len += dht[i];
if (len > end - dht - 17) len = end - dht - 17;
if (len > 256) len = 256;
if (fac) {
if (!jfif->phcac[idx]) jfif->phcac[idx] = calloc(1, sizeof(HUFCODEC));
if (jfif->phcac[idx]) memcpy(jfif->phcac[idx]->huftab, &dht[1], 16 + len);
} else {
if (!jfif->phcdc[idx]) jfif->phcdc[idx] = calloc(1, sizeof(HUFCODEC));
if (jfif->phcdc[idx]) memcpy(jfif->phcdc[idx]->huftab, &dht[1], 16 + len);
}
dht += 17 + len;
size-= 17 + len;
}
break;
}
}
read_data:
fseek(fp, 0, SEEK_END);
jfif->datalen = ftell(fp) - offset;
jfif->databuf = malloc(jfif->datalen);
if (jfif->databuf) {
fseek(fp, offset, SEEK_SET);
fread(jfif->databuf, 1, jfif->datalen, fp);
}
done:
if (buf) free (buf);
if (fp) fclose(fp );
if (ret == -1) {
jfif_free(jfif);
jfif = NULL;
}
return jfif;
}
int jfif_save(void *ctxt, char *file)
{
JFIF *jfif = (JFIF*)ctxt;
FILE *fp = NULL;
int len = 0;
int i, j;
int ret = -1;
fp = fopen(file, "wb");
if (!fp) goto done;
// output SOI
fputc(0xff, fp);
fputc(0xd8, fp);
// output DQT
for (i=0; i<16; i++) {
if (!jfif->pqtab[i]) continue;
len = 2 + 1 + 64;
fputc(0xff, fp);
fputc(0xdb, fp);
fputc(len >> 8, fp);
fputc(len >> 0, fp);
fputc(i, fp);
for (j=0; j<64; j++) {
fputc(jfif->pqtab[i][ZIGZAG[j]], fp);
}
}
// output SOF0
len = 2 + 1 + 2 + 2 + 1 + 3 * jfif->comp_num;
fputc(0xff, fp);
fputc(0xc0, fp);
fputc(len >> 8, fp);
fputc(len >> 0, fp);
fputc(8, fp); // precision 8bit
fputc(jfif->height >> 8, fp); // height
fputc(jfif->height >> 0, fp); // height
fputc(jfif->width >> 8, fp); // width
fputc(jfif->width >> 0, fp); // width
fputc(jfif->comp_num, fp);
for (i=0; i<jfif->comp_num; i++) {
fputc(jfif->comp_info[i].id, fp);
fputc((jfif->comp_info[i].samp_factor_v << 0)|(jfif->comp_info[i].samp_factor_h << 4), fp);
fputc(jfif->comp_info[i].qtab_idx, fp);
}
// output DHT AC
for (i=0; i<16; i++) {
if (!jfif->phcac[i]) continue;
fputc(0xff, fp);
fputc(0xc4, fp);
len = 2 + 1 + 16;
for (j=0; j<16; j++) len += jfif->phcac[i]->huftab[j];
fputc(len >> 8, fp);
fputc(len >> 0, fp);
fputc(i + 0x10, fp);
fwrite(jfif->phcac[i]->huftab, len - 3, 1, fp);
}
// output DHT DC
for (i=0; i<16; i++) {
if (!jfif->phcdc[i]) continue;
fputc(0xff, fp);
fputc(0xc4, fp);
len = 2 + 1 + 16;
for (j=0; j<16; j++) len += jfif->phcdc[i]->huftab[j];
fputc(len >> 8, fp);
fputc(len >> 0, fp);
fputc(i + 0x00, fp);
fwrite(jfif->phcdc[i]->huftab, len - 3, 1, fp);
}
// output SOS
len = 2 + 1 + 2 * jfif->comp_num + 3;
fputc(0xff, fp);
fputc(0xda, fp);
fputc(len >> 8, fp);
fputc(len >> 0, fp);
fputc(jfif->comp_num, fp);
for (i=0; i<jfif->comp_num; i++) {
fputc(jfif->comp_info[i].id, fp);
fputc((jfif->comp_info[i].htab_idx_ac << 0)|(jfif->comp_info[i].htab_idx_dc << 4), fp);
}
fputc(0x00, fp);
fputc(0x00, fp);
fputc(0x00, fp);
// output data
if (jfif->databuf) {
fwrite(jfif->databuf, jfif->datalen, 1, fp);
}
ret = 0;
done:
if (fp) fclose(fp);
return ret;
}
void jfif_free(void *ctxt)
{
JFIF *jfif = (JFIF*)ctxt;
int i;
if (!jfif) return;
for (i=0; i<16; i++) {
if (jfif->pqtab[i]) free(jfif->pqtab[i]);
if (jfif->phcac[i]) free(jfif->phcac[i]);
if (jfif->phcdc[i]) free(jfif->phcdc[i]);
}
if (jfif->databuf) free(jfif->databuf);
free(jfif);
}
int jfif_decode(void *ctxt, BMP *pb)
{
JFIF *jfif = (JFIF*)ctxt;
void *bs = NULL;
int *ftab[16]= {0};
int dc[4] = {0};
int mcuw, mcuh, mcuc, mcur, mcui, jw, jh;
int i, j, c, h, v, x, y;
int sfh_max = 0;
int sfv_max = 0;
int yuv_stride[3] = {0};
int yuv_height[3] = {0};
int *yuv_datbuf[3] = {0};
int *idst, *isrc;
int *ysrc, *usrc, *vsrc;
BYTE *bdst;
int ret = -1;
if (!ctxt || !pb) {
printf("invalid input params !\n");
return -1;
}
// init dct module
init_dct_module();
//++ init ftab
for (i=0; i<16; i++) {
if (jfif->pqtab[i]) {
ftab[i] = malloc(64 * sizeof(int));
if (ftab[i]) {
init_idct_ftab(ftab[i], jfif->pqtab[i]);
} else {
goto done;
}
}
}
//-- init ftab
//++ calculate mcu info
for (c=0; c<jfif->comp_num; c++) {
if (sfh_max < jfif->comp_info[c].samp_factor_h) {
sfh_max = jfif->comp_info[c].samp_factor_h;
}
if (sfv_max < jfif->comp_info[c].samp_factor_v) {
sfv_max = jfif->comp_info[c].samp_factor_v;
}
}
mcuw = sfh_max * 8;
mcuh = sfv_max * 8;
jw = ALIGN(jfif->width, mcuw);
jh = ALIGN(jfif->height, mcuh);
mcuc = jw / mcuw;
mcur = jh / mcuh;
//-- calculate mcu info
// create yuv buffer for decoding
yuv_stride[0] = jw;
yuv_stride[1] = jw * jfif->comp_info[1].samp_factor_h / sfh_max;
yuv_stride[2] = jw * jfif->comp_info[2].samp_factor_h / sfh_max;
yuv_height[0] = jh;
yuv_height[1] = jh * jfif->comp_info[1].samp_factor_v / sfv_max;
yuv_height[2] = jh * jfif->comp_info[2].samp_factor_v / sfv_max;
yuv_datbuf[0] = malloc(yuv_stride[0] * yuv_height[0] * sizeof(int));
yuv_datbuf[1] = malloc(yuv_stride[1] * yuv_height[1] * sizeof(int));
yuv_datbuf[2] = malloc(yuv_stride[2] * yuv_height[2] * sizeof(int));
if (!yuv_datbuf[0] || !yuv_datbuf[1] || !yuv_datbuf[2]) {
goto done;
}
// open bit stream
bs = bitstr_open(jfif->databuf, "mem", jfif->datalen);
if (!bs) {
printf("failed to open bitstr for jfif_decode !");
return -1;
}
// init huffman codec
for (i=0; i<16; i++) {
if (jfif->phcac[i]) {
jfif->phcac[i]->input = bs;
huffman_decode_init(jfif->phcac[i]);
}
if (jfif->phcdc[i]) {
jfif->phcdc[i]->input = bs;
huffman_decode_init(jfif->phcdc[i]);
}
}
for (mcui=0; mcui<mcuc*mcur; mcui++) {
for (c=0; c<jfif->comp_num; c++) {
for (v=0; v<jfif->comp_info[c].samp_factor_v; v++) {
for (h=0; h<jfif->comp_info[c].samp_factor_h; h++) {
HUFCODEC *hcac = jfif->phcac[jfif->comp_info[c].htab_idx_ac];
HUFCODEC *hcdc = jfif->phcdc[jfif->comp_info[c].htab_idx_dc];
int fidx = jfif->comp_info[c].qtab_idx;
int size, znum, code;
int du[64] = {0};
//+ decode dc
size = huffman_decode_step(hcdc) & 0xf;
if (size) {
code = bitstr_get_bits(bs, size);
code = category_decode(code, size);
}
else {
code = 0;
}
dc[c] += code;
du[0] = dc[c];
//- decode dc
//+ decode ac
for (i=1; i<64;) {
code = huffman_decode_step(hcac);
if (code <= 0) break;
size = (code >> 0) & 0xf;
znum = (code >> 4) & 0xf;
i += znum;
code = bitstr_get_bits(bs, size);
code = category_decode(code, size);
if (i < 64) du[i++] = code;
}
//- decode ac
// de-zigzag
zigzag_decode(du);
// idct
idct2d8x8(du, ftab[fidx]);
// copy du to yuv buffer
x = ((mcui % mcuc) * mcuw + h * 8) * jfif->comp_info[c].samp_factor_h / sfh_max;
y = ((mcui / mcuc) * mcuh + v * 8) * jfif->comp_info[c].samp_factor_v / sfv_max;
idst = yuv_datbuf[c] + y * yuv_stride[c] + x;
isrc = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
idst += yuv_stride[c];
isrc += 8;
}
}
}
}
}
// close huffman codec
for (i=0; i<16; i++) {
if (jfif->phcac[i]) huffman_decode_done(jfif->phcac[i]);
if (jfif->phcdc[i]) huffman_decode_done(jfif->phcdc[i]);
}
// close bit stream
bitstr_close(bs);
// create bitmap, and convert yuv to rgb
bmp_create(pb, jfif->width, jfif->height);
bdst = (BYTE*)pb->pdata;
ysrc = yuv_datbuf[0];
for (i=0; i<jfif->height; i++) {
int uy = i * jfif->comp_info[1].samp_factor_v / sfv_max;
int vy = i * jfif->comp_info[2].samp_factor_v / sfv_max;
for (j=0; j<jfif->width; j++) {
int ux = j * jfif->comp_info[1].samp_factor_h / sfh_max;
int vx = j * jfif->comp_info[2].samp_factor_h / sfh_max;
usrc = yuv_datbuf[2] + uy * yuv_stride[2] + ux;
vsrc = yuv_datbuf[1] + vy * yuv_stride[1] + vx;
yuv_to_rgb(*ysrc, *vsrc, *usrc, bdst + 2, bdst + 1, bdst + 0);
bdst += 3;
ysrc += 1;
}
bdst -= jfif->width * 3;
bdst += pb->stride;
ysrc -= jfif->width * 1;
ysrc += yuv_stride[0];
}
// success
ret = 0;
done:
if (yuv_datbuf[0]) free(yuv_datbuf[0]);
if (yuv_datbuf[1]) free(yuv_datbuf[1]);
if (yuv_datbuf[2]) free(yuv_datbuf[2]);
//++ free ftab
for (i=0; i<16; i++) {
if (ftab[i]) {
free(ftab[i]);
}
}
//-- free ftab
return ret;
}
#define DU_TYPE_LUMIN 0
#define DU_TYPE_CHROM 1
typedef struct {
unsigned runlen : 4;
unsigned codesize : 4;
unsigned codedata : 16;
} RLEITEM;
static void jfif_encode_du(JFIF *jfif, int type, int du[64], int *dc)
{
HUFCODEC *hfcac = jfif->phcac[type];
HUFCODEC *hfcdc = jfif->phcdc[type];
int *pqtab = jfif->pqtab[type];
void *bs = hfcac->output;
int diff, code, size;
RLEITEM rlelist[63];
int i, j, n, eob;
// fdct
fdct2d8x8(du, NULL);
// quant
quant_encode(du, pqtab);
// zigzag
zigzag_encode(du);
// dc
diff = du[0] - *dc;
*dc = du[0];
// category encode for dc
code = diff;
category_encode(&code, &size);
// huffman encode for dc
huffman_encode_step(hfcdc, size);
bitstr_put_bits(bs, code, size);
// rle encode for ac
for (i=1, j=0, n=0, eob=0; i<64 && j<63; i++) {
if (du[i] == 0 && n < 15) {
n++;
} else {
code = du[i]; size = 0;
category_encode(&code, &size);
rlelist[j].runlen = n;
rlelist[j].codesize = size;
rlelist[j].codedata = code;
n = 0;
j++;
if (size != 0) eob = j;
}
}
// set eob
if (du[63] == 0) {
rlelist[eob].runlen = 0;
rlelist[eob].codesize = 0;
rlelist[eob].codedata = 0;
j = eob + 1;
}
// huffman encode for ac
for (i=0; i<j; i++) {
huffman_encode_step(hfcac, (rlelist[i].runlen << 4) | (rlelist[i].codesize << 0));
bitstr_put_bits(bs, rlelist[i].codedata, rlelist[i].codesize);
}
}
void* jfif_encode(BMP *pb)
{
JFIF *jfif = NULL;
void *bs = NULL;
int jw, jh;
int *yuv_datbuf[3] = {0};
int *ydst, *udst, *vdst;
int *isrc, *idst;
BYTE *bsrc;
int du[64]= {0};
int dc[4]= {0};
int i, j, m, n;
int failed = 1;
// check input params
if (!pb) {
printf("invalid input params !\n");
return NULL;
}
// allocate jfif context
jfif = calloc(1, sizeof(JFIF));
if (!jfif) return NULL;
// init dct module
init_dct_module();
// init jfif context
jfif->width = pb->width;
jfif->height = pb->height;
jfif->pqtab[0] = malloc(64*sizeof(int));
jfif->pqtab[1] = malloc(64*sizeof(int));
jfif->phcac[0] = calloc(1, sizeof(HUFCODEC));
jfif->phcac[1] = calloc(1, sizeof(HUFCODEC));
jfif->phcdc[0] = calloc(1, sizeof(HUFCODEC));
jfif->phcdc[1] = calloc(1, sizeof(HUFCODEC));
jfif->datalen = jfif->width * jfif->height * 2;
jfif->databuf = malloc(jfif->datalen);
if (!jfif->pqtab[0] || !jfif->pqtab[1]
|| !jfif->phcac[0] || !jfif->phcac[1]
|| !jfif->phcdc[0] || !jfif->phcdc[1]
|| !jfif->databuf) {
goto done;
}
// init qtab
memcpy(jfif->pqtab[0], STD_QUANT_TAB_LUMIN, 64*sizeof(int));
memcpy(jfif->pqtab[1], STD_QUANT_TAB_CHROM, 64*sizeof(int));
// open bit stream
bs = bitstr_open(jfif->databuf, "mem", jfif->datalen);
if (!bs) {
printf("failed to open bitstr for jfif_decode !");
goto done;
}
// init huffman codec
memcpy(jfif->phcac[0]->huftab, STD_HUFTAB_LUMIN_AC, MAX_HUFFMAN_CODE_LEN + 256);
memcpy(jfif->phcac[1]->huftab, STD_HUFTAB_CHROM_AC, MAX_HUFFMAN_CODE_LEN + 256);
memcpy(jfif->phcdc[0]->huftab, STD_HUFTAB_LUMIN_DC, MAX_HUFFMAN_CODE_LEN + 256);
memcpy(jfif->phcdc[1]->huftab, STD_HUFTAB_CHROM_DC, MAX_HUFFMAN_CODE_LEN + 256);
jfif->phcac[0]->output = bs; huffman_encode_init(jfif->phcac[0], 1);
jfif->phcac[1]->output = bs; huffman_encode_init(jfif->phcac[1], 1);
jfif->phcdc[0]->output = bs; huffman_encode_init(jfif->phcdc[0], 1);
jfif->phcdc[1]->output = bs; huffman_encode_init(jfif->phcdc[1], 1);
// init comp_num & comp_info
jfif->comp_num = 3;
jfif->comp_info[0].id = 1;
jfif->comp_info[0].samp_factor_v = 2;
jfif->comp_info[0].samp_factor_h = 2;
jfif->comp_info[0].qtab_idx = 0;
jfif->comp_info[0].htab_idx_ac = 0;
jfif->comp_info[0].htab_idx_dc = 0;
jfif->comp_info[1].id = 2;
jfif->comp_info[1].samp_factor_v = 1;
jfif->comp_info[1].samp_factor_h = 1;
jfif->comp_info[1].qtab_idx = 1;
jfif->comp_info[1].htab_idx_ac = 1;
jfif->comp_info[1].htab_idx_dc = 1;
jfif->comp_info[2].id = 3;
jfif->comp_info[2].samp_factor_v = 1;
jfif->comp_info[2].samp_factor_h = 1;
jfif->comp_info[2].qtab_idx = 1;
jfif->comp_info[2].htab_idx_ac = 1;
jfif->comp_info[2].htab_idx_dc = 1;
// init jw & jw, init yuv data buffer
jw = ALIGN(pb->width, 16);
jh = ALIGN(pb->height, 16);
yuv_datbuf[0] = calloc(1, jw * jh / 1 * sizeof(int));
yuv_datbuf[1] = calloc(1, jw * jh / 4 * sizeof(int));
yuv_datbuf[2] = calloc(1, jw * jh / 4 * sizeof(int));
if (!yuv_datbuf[0] || !yuv_datbuf[1] || !yuv_datbuf[2]) {
goto done;
}
// convert rgb to yuv
bsrc = pb->pdata;
ydst = yuv_datbuf[0];
udst = yuv_datbuf[1];
vdst = yuv_datbuf[2];
for (i=0; i<pb->height; i++) {
for (j=0; j<pb->width; j++) {
rgb_to_yuv(bsrc[2], bsrc[1], bsrc[0], ydst, udst, vdst);
bsrc += 3;
ydst += 1;
if (j & 1) {
udst += 1;
vdst += 1;
}
}
bsrc -= pb->width * 3; bsrc += pb->stride;
ydst -= pb->width * 1; ydst += jw;
udst -= pb->width / 2;
vdst -= pb->width / 2;
if (i & 1) {
udst += jw / 2;
vdst += jw / 2;
}
}
for (m=0; m<jh/16; m++) {
for (n=0; n<jw/16; n++) {
//++ encode mcu, yuv 4:2:0
//+ y du0
isrc = yuv_datbuf[0] + (m * 16 + 0) * jw + n * 16 + 0;
idst = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
isrc += jw; idst += 8;
}
jfif_encode_du(jfif, DU_TYPE_LUMIN, du, &(dc[0]));
//- y du0
//+ y du1
isrc = yuv_datbuf[0] + (m * 16 + 0) * jw + n * 16 + 8;
idst = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
isrc += jw; idst += 8;
}
jfif_encode_du(jfif, DU_TYPE_LUMIN, du, &(dc[0]));
//- y du1
//+ y du2
isrc = yuv_datbuf[0] + (m * 16 + 8) * jw + n * 16 + 0;
idst = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
isrc += jw; idst += 8;
}
jfif_encode_du(jfif, DU_TYPE_LUMIN, du, &(dc[0]));
//- y du2
//+ y du3
isrc = yuv_datbuf[0] + (m * 16 + 8) * jw + n * 16 + 8;
idst = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
isrc += jw; idst += 8;
}
jfif_encode_du(jfif, DU_TYPE_LUMIN, du, &(dc[0]));
//- y du3
//+ u du
isrc = yuv_datbuf[1] + m * 8 * (jw/2) + n * 8;
idst = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
isrc += jw/2; idst += 8;
}
jfif_encode_du(jfif, DU_TYPE_CHROM, du, &(dc[1]));
//- u du
//+ v du
isrc = yuv_datbuf[2] + m * 8 * (jw/2) + n * 8;
idst = du;
for (i=0; i<8; i++) {
memcpy(idst, isrc, 8 * sizeof(int));
isrc += jw/2; idst += 8;
}
jfif_encode_du(jfif, DU_TYPE_CHROM, du, &(dc[2]));
//- v du
//-- encode mcu, yuv 4:2:0
}
}
failed = 0;
done:
// free yuv data buffer
if (yuv_datbuf[0]) free(yuv_datbuf[0]);
if (yuv_datbuf[1]) free(yuv_datbuf[1]);
if (yuv_datbuf[2]) free(yuv_datbuf[2]);
// close huffman codec
huffman_encode_done(jfif->phcac[0]);
huffman_encode_done(jfif->phcac[1]);
huffman_encode_done(jfif->phcdc[0]);
huffman_encode_done(jfif->phcdc[1]);
jfif->datalen = bitstr_tell(bs);
// close bit stream
bitstr_close(bs);
// if failed free context
if (failed) {
jfif_free(jfif);
jfif = NULL;
}
// return context
return jfif;
}

View File

@ -1,4 +0,0 @@
ole.c:398:bughuntingDivByZero
ole.c:399:bughuntingDivByZero
ole.c:400:bughuntingDivByZero

View File

@ -1,605 +0,0 @@
/**
* @file ole.c
* @author Alex Ott, Victor B Wagner
* @date Wed Jun 11 12:33:01 2003
* Version: $Id: ole.c,v 1.2 2006/02/25 15:28:14 vitus Exp $
* Copyright: Victor B Wagner, 1996-2003 Alex Ott, 2003
*
* @brief Parsing structure of MS Office compound document
*
* This file is part of catdoc project
* and distributed under GNU Public License
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "catdoc.h"
#define min(a,b) ((a) < (b) ? (a) : (b))
const static unsigned char ole_sign[]={0xD0,0xCF,0x11,0xE0,0xA1,0xB1,0x1A,0xE1,0};
/**
* Initializes ole structure
*
* @param f (FILE *) compound document file, positioned at bufSize
* byte. Might be pipe or socket
* @param buffer (void *) bytes already read from f
* @param bufSize number of bytes already read from f should be less
* than 512
*
* @return
*/
FILE* ole_init(FILE *f, void *buffer, size_t bufSize, struct ole_params_t *ole_params) {
unsigned char oleBuf[BBD_BLOCK_SIZE];
unsigned char *tmpBuf;
FILE *newfile;
int ret=0, i;
long int sbdMaxLen, sbdCurrent, propMaxLen, propCurrent, mblock, msat_size;
oleEntry *tEntry;
long int sectorSize;
long int shortSectorSize;
long int bbdNumBlocks;
/* deleting old data (if it was allocated) */
ole_finish(ole_params);
if (fseek(f,0,SEEK_SET) == -1) {
if (errno == ESPIPE) {
/* We got non-seekable file, create temp file */
if ((newfile=tmpfile()) == NULL) {
return NULL;
}
if (bufSize > 0) {
ret=fwrite(buffer, 1, bufSize, newfile);
if (ret != bufSize) {
return NULL;
}
}
while (!feof(f)) {
ret=fread(oleBuf,1,BBD_BLOCK_SIZE,f);
fwrite(oleBuf, 1, ret, newfile);
}
fseek(newfile,0,SEEK_SET);
} else {
return NULL;
}
} else {
newfile=f;
}
fseek(newfile,0,SEEK_END);
ole_params->fileLength=ftell(newfile);
fseek(newfile,0,SEEK_SET);
ret=fread(oleBuf,1,BBD_BLOCK_SIZE,newfile);
if (ret != BBD_BLOCK_SIZE) {
return NULL;
}
if (strncmp(oleBuf,ole_sign,8) != 0) {
return NULL;
}
ole_params->sectorSize = 1<<getshort(oleBuf,0x1e);
if (ole_params->sectorSize == 0) {
return NULL;
}
sectorSize = ole_params->sectorSize;
ole_params->shortSectorSize = 1<<getshort(oleBuf,0x20);
shortSectorSize= ole_params->shortSectorSize;
if (shortSectorSize > sectorSize) {
return NULL;
}
/* Read BBD into memory */
ole_params->bbdNumBlocks = getulong(oleBuf,0x2c);
bbdNumBlocks = ole_params->bbdNumBlocks;
if ((ole_params->BBD=malloc(bbdNumBlocks*sectorSize)) == NULL) {
return NULL;
}
if ((tmpBuf=malloc(MSAT_ORIG_SIZE)) == NULL) {
return NULL;
}
memcpy(tmpBuf,oleBuf+0x4c,MSAT_ORIG_SIZE);
mblock=getlong(oleBuf,0x44);
msat_size=getlong(oleBuf,0x48);
/* fprintf(stderr, "msat_size=%ld\n", msat_size); */
i=0;
while ((mblock >= 0) && (i < msat_size)) {
unsigned char *newbuf;
/* fprintf(stderr, "i=%d mblock=%ld\n", i, mblock); */
if ((newbuf=realloc(tmpBuf, sectorSize*(i+1)+MSAT_ORIG_SIZE)) != NULL) {
tmpBuf=newbuf;
} else {
free(tmpBuf);
ole_finish(ole_params);
return NULL;
}
fseek(newfile, 512+mblock*sectorSize, SEEK_SET);
if (fread(tmpBuf+MSAT_ORIG_SIZE+(sectorSize-4)*i,
1, sectorSize, newfile) != sectorSize) {
ole_finish(ole_params);
return NULL;
}
i++;
mblock=getlong(tmpBuf, MSAT_ORIG_SIZE+(sectorSize-4)*i);
}
/* fprintf(stderr, "bbdNumBlocks=%ld\n", bbdNumBlocks); */
for (i=0; i< bbdNumBlocks; i++) {
long int bbdSector=getlong(tmpBuf,4*i);
if (bbdSector >= ole_params->fileLength/sectorSize || bbdSector < 0) {
errno = EINVAL;
ole_finish(ole_params);
return NULL;
}
fseek(newfile, 512+bbdSector*sectorSize, SEEK_SET);
if (fread(ole_params->BBD+i*sectorSize, 1, sectorSize, newfile) != sectorSize) {
free(tmpBuf);
ole_finish(ole_params);
return NULL;
}
}
free(tmpBuf);
/* Read SBD into memory */
ole_params->sbdLen=0;
sbdMaxLen=10;
sbdCurrent = ole_params->sbdStart = getlong(oleBuf,0x3c);
if (ole_params->sbdStart > 0) {
if ((ole_params->SBD=malloc(sectorSize*sbdMaxLen)) == NULL) {
ole_finish(ole_params);
return NULL;
}
while (1) {
fseek(newfile, 512+sbdCurrent*sectorSize, SEEK_SET);
fread(ole_params->SBD+ole_params->sbdLen*sectorSize, 1, sectorSize, newfile);
ole_params->sbdLen++;
if (ole_params->sbdLen >= sbdMaxLen) {
unsigned char *newSBD;
sbdMaxLen+=5;
if ((newSBD=realloc(ole_params->SBD, sectorSize*sbdMaxLen)) != NULL) {
ole_params->SBD=newSBD;
} else {
ole_finish(ole_params);
return NULL;
}
}
if (sbdCurrent < 0 || sbdCurrent * 4 >= bbdNumBlocks * sectorSize)
{
break;
}
sbdCurrent = getlong(ole_params->BBD, sbdCurrent*4);
if (sbdCurrent < 0 ||
sbdCurrent >= ole_params->fileLength/sectorSize)
break;
}
ole_params->sbdNumber = (ole_params->sbdLen*sectorSize)/shortSectorSize;
} else {
ole_params->SBD=NULL;
}
/* Read property catalog into memory */
ole_params->propLen = 0;
propMaxLen = 5;
propCurrent = ole_params->propStart = getlong(oleBuf,0x30);
if (ole_params->propStart >= 0) {
if ((ole_params->properties=malloc(propMaxLen*sectorSize)) == NULL) {
ole_finish(ole_params);
return NULL;
}
while (1) {
/* fprintf(stderr, "propCurrent=%ld\n",propCurrent); */
fseek(newfile, 512+propCurrent*sectorSize, SEEK_SET);
fread(ole_params->properties+ole_params->propLen*sectorSize,
1, sectorSize, newfile);
(ole_params->propLen)++;
if (ole_params->propLen >= propMaxLen) {
unsigned char *newProp;
propMaxLen+=5;
if ((newProp=realloc(ole_params->properties, propMaxLen*sectorSize)) != NULL)
ole_params->properties=newProp;
else {
ole_finish(ole_params);
return NULL;
}
}
propCurrent = getlong(ole_params->BBD, propCurrent*4);
if (propCurrent < 0 ||
propCurrent >= ole_params->fileLength/sectorSize) {
break;
}
}
ole_params->propNumber = (ole_params->propLen*sectorSize)/PROP_BLOCK_SIZE;
ole_params->propCurNumber = 0;
} else {
ole_finish(ole_params);
ole_params->properties = NULL;
return NULL;
}
/* Find Root Entry */
while ((tEntry=(oleEntry*)ole_readdir(newfile, ole_params)) != NULL) {
if (tEntry->type == oleRootDir) {
ole_params->rootEntry=tEntry;
break;
}
ole_close((FILE*)tEntry);
}
ole_params->propCurNumber = 0;
fseek(newfile, 0, SEEK_SET);
if (!ole_params->rootEntry) {
errno = EINVAL;
ole_finish(ole_params);
return NULL;
}
return newfile;
}
/**
*
*
* @param oleBuf
*
* @return
*/
int rightOleType(unsigned char *oleBuf) {
return (oleBuf[0x42] == 1 || oleBuf[0x42] == 2 ||
oleBuf[0x42] == 3 || oleBuf[0x42] == 5);
}
/**
*
*
* @param oleBuf
*
* @return
*/
oleType getOleType(unsigned char *oleBuf) {
return (oleType)((unsigned char)oleBuf[0x42]);
}
/**
* Reads next directory entry from file
*
* @param name buffer for name converted to us-ascii should be at least 33 chars long
* @param size size of file
*
* @return 0 if everything is ok -1 on error
*/
FILE *ole_readdir(FILE *f, struct ole_params_t *ole_params) {
int i, nLen;
unsigned char *oleBuf;
oleEntry *e=NULL;
long int chainMaxLen, chainCurrent;
if (ole_params->properties == NULL || ole_params->propCurNumber >= ole_params->propNumber || f == NULL)
return NULL;
oleBuf=ole_params->properties + ole_params->propCurNumber*PROP_BLOCK_SIZE;
if (!rightOleType(oleBuf))
return NULL;
if ((e = (oleEntry*)malloc(sizeof(oleEntry))) == NULL) {
return NULL;
}
e->dirPos=oleBuf;
e->type=getOleType(oleBuf);
e->file=f;
e->startBlock=getlong(oleBuf,0x74);
e->blocks=NULL;
nLen=getshort(oleBuf,0x40);
for (i=0; i < nLen/2 && i < OLENAMELENGHT; i++)
e->name[i]=(char)oleBuf[i*2];
e->name[i]='\0';
(ole_params->propCurNumber)++;
e->length=getulong(oleBuf,0x78);
/* Read sector chain for object */
chainMaxLen = 25;
e->numOfBlocks = 0;
chainCurrent = e->startBlock;
e->isBigBlock = (e->length >= 0x1000) || !strcmp(e->name, "Root Entry");
/* fprintf(stderr, "e->name=%s e->length=%ld\n", e->name, e->length); */
/* fprintf(stderr, "e->startBlock=%ld BBD=%p\n", e->startBlock, BBD); */
if (e->startBlock >= 0 &&
e->length >= 0 &&
(e->startBlock <=
ole_params->fileLength/(e->isBigBlock ? ole_params->sectorSize : ole_params->shortSectorSize))) {
if ((e->blocks=malloc(chainMaxLen*sizeof(long int))) == NULL) {
return NULL;
}
while (1) {
/* fprintf(stderr, "chainCurrent=%ld\n", chainCurrent); */
e->blocks[e->numOfBlocks++] = chainCurrent;
if (e->numOfBlocks >= chainMaxLen) {
long int *newChain;
chainMaxLen+=25;
if ((newChain=realloc(e->blocks,
chainMaxLen*sizeof(long int))) != NULL)
e->blocks=newChain;
else {
free(e->blocks);
e->blocks=NULL;
return NULL;
}
}
if (e->isBigBlock) {
chainCurrent = getlong(ole_params->BBD, chainCurrent*4);
} else if (ole_params->SBD != NULL) {
chainCurrent = getlong(ole_params->SBD, chainCurrent*4);
} else {
chainCurrent=-1;
}
if (chainCurrent <= 0 ||
chainCurrent >= (e->isBigBlock ?
((ole_params->bbdNumBlocks*ole_params->sectorSize)/4)
: ((ole_params->sbdNumber*ole_params->shortSectorSize)/4)) ||
(e->numOfBlocks >
e->length/(e->isBigBlock ? ole_params->sectorSize : ole_params->shortSectorSize))) {
/* fprintf(stderr, "chain End=%ld\n", chainCurrent); */
break;
}
}
}
if (e->length > (e->isBigBlock ? ole_params->sectorSize : ole_params->shortSectorSize)*e->numOfBlocks)
e->length = (e->isBigBlock ? ole_params->sectorSize : ole_params->shortSectorSize)*e->numOfBlocks;
/* fprintf(stderr, "READDIR: e->name=%s e->numOfBlocks=%ld length=%ld\n", */
/* e->name, e->numOfBlocks, e->length); */
return (FILE*)e;
}
/**
* Open stream, which correspond to directory entry last read by
* ole_readdir
*
*
* @return opaque pointer to pass to ole_read, casted to (FILE *)
*/
int ole_open(FILE *stream) {
oleEntry *e=(oleEntry *)stream;
if (e->type != oleStream)
return -2;
e->ole_offset=0;
e->file_offset= ftell(e->file);
return 0;
}
/**
*
*
* @param e
* @param blk
*
* @return
*/
long int calcFileBlockOffset(oleEntry *e, long int blk, struct ole_params_t *ole_params) {
long int res;
if (e->isBigBlock) {
res=512+e->blocks[blk]*ole_params->sectorSize;
} else {
long int sbdPerSector=(ole_params->sectorSize)/(ole_params->shortSectorSize);
long int sbdSecNum=e->blocks[blk]/sbdPerSector;
long int sbdSecMod=e->blocks[blk]%sbdPerSector;
res=512 + ole_params->rootEntry->blocks[sbdSecNum]*ole_params->sectorSize + sbdSecMod*ole_params->shortSectorSize;
}
return res;
}
/**
* Reads block from open ole stream interface-compatible with fread
*
* @param ptr pointer to buffer for read to
* @param size size of block
* @param nmemb size in blocks
* @param stream pointer to FILE* structure
*
* @return number of readed blocks
*/
size_t ole_read(void *ptr, size_t size, size_t nmemb, FILE *stream, struct ole_params_t *ole_params) {
oleEntry *e = (oleEntry*)stream;
long int llen = size*nmemb, rread=0, i;
long int blockNumber, modBlock, toReadBlocks, toReadBytes, bytesInBlock;
long int ssize; /**< Size of block */
long int newoffset;
unsigned char *cptr = ptr;
if (e->ole_offset+llen > e->length)
llen= e->length - e->ole_offset;
ssize = (e->isBigBlock ? ole_params->sectorSize : ole_params->shortSectorSize);
blockNumber=e->ole_offset/ssize;
/* fprintf(stderr, "blockNumber=%ld e->numOfBlocks=%ld llen=%ld\n", */
/* blockNumber, e->numOfBlocks, llen); */
if (blockNumber >= e->numOfBlocks || llen <=0)
return 0;
modBlock=e->ole_offset%ssize;
bytesInBlock = ssize - modBlock;
if (bytesInBlock < llen) {
toReadBlocks = (llen-bytesInBlock)/ssize;
toReadBytes = (llen-bytesInBlock)%ssize;
} else {
toReadBlocks = toReadBytes = 0;
}
/* fprintf(stderr, "llen=%ld toReadBlocks=%ld toReadBytes=%ld bytesInBlock=%ld blockNumber=%ld modBlock=%ld\n", */
/* llen, toReadBlocks, toReadBytes, bytesInBlock, blockNumber, modBlock); */
newoffset = calcFileBlockOffset(e,blockNumber, ole_params)+modBlock;
if (e->file_offset != newoffset) {
fseek(e->file, e->file_offset=newoffset, SEEK_SET);
}
rread=fread(ptr, 1, min(llen,bytesInBlock), e->file);
e->file_offset += rread;
for (i=0; i<toReadBlocks; i++) {
int readbytes;
blockNumber++;
newoffset = calcFileBlockOffset(e,blockNumber, ole_params);
if (newoffset != e->file_offset);
fseek(e->file, e->file_offset=newoffset, SEEK_SET);
readbytes=fread(cptr+rread, 1, min(llen-rread, ssize), e->file);
rread +=readbytes;
e->file_offset +=readbytes;
}
if (toReadBytes > 0) {
int readbytes;
blockNumber++;
newoffset = calcFileBlockOffset(e,blockNumber, ole_params);
fseek(e->file, e->file_offset=newoffset, SEEK_SET);
readbytes=fread(cptr+rread, 1, toReadBytes,e->file);
rread +=readbytes;
e->file_offset +=readbytes;
}
/* fprintf(stderr, "ole_offset=%ld rread=%ld llen=%ld\n",
e->ole_offset, rread, llen);*/
e->ole_offset+=rread;
return rread;
}
/**
*
*
* @param stream
*
* @return
*/
int ole_eof(FILE *stream) {
oleEntry *e=(oleEntry*)stream;
/* fprintf(stderr, "EOF: e->ole_offset=%ld e->length=%ld\n",
e->ole_offset, e->length);*/
return (e->ole_offset >= e->length);
}
/**
*
*
*/
void ole_finish(struct ole_params_t *ole_params) {
if (ole_params->BBD != NULL) free(ole_params->BBD);
if (ole_params->SBD != NULL) free(ole_params->SBD);
if (ole_params->properties != NULL) free(ole_params->properties);
if (ole_params->rootEntry != NULL) ole_close((FILE*)(ole_params->rootEntry));
ole_params->properties = ole_params->SBD = ole_params->BBD = NULL;
ole_params->rootEntry = NULL;
}
/**
*
*
* @param stream
*
* @return
*/
int ole_close(FILE *stream) {
oleEntry *e=(oleEntry*)stream;
if (e == NULL)
return -1;
if (e->blocks != NULL)
free(e->blocks);
free(e);
return 0;
}
/**
*
*
* @param stream pointer to OLE stream structure
* @param offset
* @param whence
*
* @return
*/
int ole_seek(FILE *stream, long offset, int whence, struct ole_params_t *ole_params) {
oleEntry *e=(oleEntry*)stream;
long int new_ole_offset=0, new_file_offset;
int ssize, modBlock, blockNumber;
switch (whence) {
case SEEK_SET:
new_ole_offset=offset;
break;
case SEEK_CUR:
new_ole_offset=e->ole_offset+offset;
break;
case SEEK_END:
new_ole_offset=e->length+offset;
break;
default:
errno=EINVAL;
return -1;
}
if (new_ole_offset<0)
new_ole_offset=0;
if (new_ole_offset >= e->length)
new_ole_offset=e->length;
ssize = (e->isBigBlock ? ole_params->sectorSize : ole_params->shortSectorSize);
blockNumber=new_ole_offset/ssize;
if (blockNumber >= e->numOfBlocks)
return -1;
modBlock=new_ole_offset%ssize;
new_file_offset = calcFileBlockOffset(e,blockNumber, ole_params)+modBlock;
fseek(e->file, e->file_offset=new_file_offset, SEEK_SET);
e->ole_offset=new_ole_offset;
return 0;
}
/**
* Tell position inside OLE stream
*
* @param stream pointer to OLE stream
*
* @return current position inside OLE stream
*/
long ole_tell(FILE *stream) {
oleEntry *e=(oleEntry*)stream;
return e->ole_offset;
}
void set_ole_func(struct io_funcs_t *io_funcs) {
io_funcs->catdoc_read=ole_read;
io_funcs->catdoc_eof=ole_eof;
io_funcs->catdoc_seek=ole_seek;
io_funcs->catdoc_tell=ole_tell;
}
size_t my_fread(void *ptr, size_t size, size_t nmemb, FILE *stream, struct ole_params_t *ole_params)
{
return fread(ptr, size, nmemb, stream);
}
int my_fseek(FILE *stream, long offset, int whence, struct ole_params_t *ole_params)
{
return fseek(stream, offset, whence);
}
void set_std_func(struct io_funcs_t *io_funcs) {
io_funcs->catdoc_read=my_fread;
io_funcs->catdoc_eof=feof;
io_funcs->catdoc_seek=my_fseek;
io_funcs->catdoc_tell=ftell;
}

View File

@ -1,91 +0,0 @@
# Test if --bug-hunting works using the itc testsuite
# The itc test suite can be downloaded here:
# https://github.com/regehr/itc-benchmarks
import os
import re
import shutil
import sys
import subprocess
if sys.argv[0] in ('test/bug-hunting/itc.py', './test/bug-hunting/itc.py'):
CPPCHECK_PATH = './cppcheck'
else:
CPPCHECK_PATH = '../../cppcheck'
if len(sys.argv) >= 2 and sys.argv[-1] != '--clang':
TESTFILES = [sys.argv[-1]]
else:
TESTFILES = [os.path.expanduser('~/itc/01.w_Defects/zero_division.c'),
os.path.expanduser('~/itc/01.w_Defects/uninit_var.c')]
if not os.path.isfile(TESTFILES[0]):
print('ERROR: %s is not a file' % TESTFILES[0])
sys.exit(1)
RUN_CLANG = ('--clang' in sys.argv)
def get_error_lines(filename):
ret = []
f = open(filename, 'rt')
lines = f.readlines()
for linenr, line in enumerate(lines):
if line.find('/* ERROR:') > 0 or line.find('/*ERROR:') > 0:
linenr += 1
if testfile.find('uninit_') >= 0:
if linenr == 177:
linenr = 176
elif linenr == 241:
linenr = 242 # warn about usage
ret.append(linenr)
return ret
def check(filename):
cmd = [CPPCHECK_PATH,
'--bug-hunting',
'--bug-hunting-check-function-max-time=10'
'--platform=unix64',
filename]
if RUN_CLANG:
cmd.append('--clang')
print(' '.join(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
comm = p.communicate()
stdout = comm[0].decode(encoding='utf-8', errors='ignore')
stderr = comm[1].decode(encoding='utf-8', errors='ignore')
if RUN_CLANG:
shutil.rmtree('itc-build-dir')
if filename.find('zero_division.c') >= 0:
w = r'.*zero_division.c:([0-9]+):[0-9]+: error: There is division.*'
elif filename.find('uninit_') >= 0:
w = r'.*c:([0-9]+):[0-9]+: error: .*bughuntingUninit.*'
else:
w = r'.*c:([0-9]+):[0-9]+: error: .*bughunting.*'
ret = []
for line in stderr.split('\n'):
res = re.match(w, line)
if res is None:
continue
linenr = int(res.group(1))
if linenr not in ret:
ret.append(linenr)
return ret
for testfile in TESTFILES:
wanted = get_error_lines(testfile)
actual = check(testfile)
missing = []
for w in wanted:
if w not in actual:
missing.append(w)
if len(missing) > 0:
print('wanted:' + str(wanted))
print('actual:' + str(actual))
print('missing:' + str(missing))
sys.exit(1)

View File

@ -1,77 +0,0 @@
# Test if --bug-hunting works using the juliet testsuite
# The Juliet test suite can be downloaded from:
# https://samate.nist.gov/SRD/testsuite.php
import glob
import os
import re
import shutil
import sys
import subprocess
JULIET_PATH = os.path.expanduser('~/juliet')
if sys.argv[0] in ('test/bug-hunting/juliet.py', './test/bug-hunting/juliet.py'):
CPPCHECK_PATH = './cppcheck'
else:
CPPCHECK_PATH = '../../cppcheck'
RUN_CLANG = ('--clang' in sys.argv)
def get_files(juliet_path:str, test_cases:str):
ret = []
g = os.path.join(juliet_path, test_cases)
print(g)
for f in sorted(glob.glob(g)):
res = re.match(r'(.*[0-9][0-9])[a-x]?.(cp*)$', f)
if res is None:
print('Non-match!! ' + f)
sys.exit(1)
f = res.group(1) + '*.' + res.group(2)
if f not in ret:
ret.append(f)
return ret
def check(tc:str, warning_id:str):
num_ok = 0
num_failed = 0
for f in get_files(JULIET_PATH, tc):
cmd = [CPPCHECK_PATH,
'-I' + os.path.join(JULIET_PATH, 'C/testcasesupport'),
'-DOMIT_GOOD',
'-DAF_INET=1',
'-DINADDR_ANY=1',
'--library=posix',
'--bug-hunting',
'--platform=unix64']
if RUN_CLANG:
cmd += ['--clang', '--cppcheck-build-dir=juliet-build-dir']
if not os.path.isdir('juliet-build-dir'):
os.mkdir('juliet-build-dir')
cmd += glob.glob(f)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
comm = p.communicate()
stdout = comm[0].decode(encoding='utf-8', errors='ignore')
stderr = comm[1].decode(encoding='utf-8', errors='ignore')
if RUN_CLANG:
shutil.rmtree('juliet-build-dir')
if warning_id in stderr:
num_ok += 1
else:
print('fail: ' + ' '.join(cmd))
num_failed += 1
cwepos = tc.find('CWE')
cwe = tc[cwepos:cwepos+6]
print('%s ok:%i, fail:%i' % (cwe, num_ok, num_failed))
if num_failed != 0:
sys.exit(1)
check('C/testcases/CWE369_Divide_by_Zero/s*/*.c', 'bughuntingDivByZero')
#check('C/testcases/CWE457_Use_of_Uninitialized_Variable/s*/*.c', 'bughuntingUninit')

View File

@ -1,20 +0,0 @@
ifndef CC
CC=gcc
endif
all: controlflow.o data.o functions.o ub.o
controlflow.o: controlflow.c
$(CC) -c controlflow.c
data.o: data.c
$(CC) -c data.c
functions.o: functions.c
$(CC) -c functions.c
ub.o: ub.c
$(CC) -c ub.c
clean:
rm -rf controlflow.o data.o functions.o ub.o

View File

@ -1,73 +0,0 @@
//////////////////////////////
// control flow analysis
//////////////////////////////
int buf[2];
void in_if(int a) {
if (a==100)
buf[a] = 0; // BUG
}
void before_if(int a) {
buf[a] = 0; // WARNING
if (a==100) {}
}
void after_if(int a) {
if (a==100) {}
buf[a] = 0; // WARNING
}
void in_for(void) {
int x;
for (x = 0; x<100; x++) {
buf[x] = 0; // BUG
}
}
void after_for(void) {
int x;
for (x = 0; x<100; x++) {}
buf[x] = 0; // BUG
}
void in_switch(int x) {
switch (x) {
case 100:
buf[x] = 0; // BUG
break;
}
}
void before_switch(int x) {
buf[x] = 0; // WARNING
switch (x) {
case 100:
break;
}
}
void after_switch(int x) {
switch (x) {
case 100:
break;
}
buf[x] = 0; // WARNING
}
void in_while(void) {
int x = 0;
while (x<100) {
buf[x] = 0; // BUG
x++;
}
}
void after_while(void) {
int x = 0;
while (x<100)
x++;
buf[x] = 0; // BUG
}

View File

@ -1,68 +0,0 @@
int TestData[10];
int g;
void global() {
g = 1000;
TestData[g] = 0; // BUG
}
int garr[10];
void global_array() {
garr[3] = 1000;
TestData[garr[3]] = 0; // BUG
}
int *gp;
void global_pointer() {
*gp = 1000;
TestData[*gp] = 0; // BUG
}
void local() {
int x;
x = 1000;
TestData[x] = 0; // BUG
}
void local_array() {
int arr[10];
arr[3] = 1000;
TestData[arr[3]] = 0; // BUG
}
void local_alias_1() {
int x;
int *p = &x;
*p = 1000;
TestData[*p] = 0; // BUG
}
void local_alias_2() {
int x;
int *p = &x;
x = 1000;
TestData[*p] = 0; // BUG
}
struct ABC {
int a;
int b[10];
int c;
};
void struct_member_init() {
struct ABC abc = {1000,{0},3};
TestData[abc.a] = 0; // BUG
}
void struct_member_assign(struct ABC *abc) {
abc->a = 1000;
TestData[abc->a] = 0; // BUG
}
void struct_arraymember(struct ABC *abc) {
abc->b[3] = 1000;
TestData[abc->b[3]] = 0; // BUG
}

View File

@ -1,24 +0,0 @@
int TestData[100];
void par_not_dependant(int par) {
TestData[par] = 0; // BUG
}
void par_dependant(int x, int y) {
if (x < 10)
TestData[y] = 0; // BUG
}
void call(int x) {
par_not_dependant(1000);
par_dependant(0, 1000);
}
int getLargeIndex() {
return 1000;
}
void return_value() {
TestData[getLargeIndex()] = 0; // BUG
}

View File

@ -1,57 +0,0 @@
#!/usr/bin/env python3
import os
import re
def hasresult(filename, result):
if not os.path.isfile(filename):
return False
for line in open(filename, 'rt'):
if result in line:
return True
return False
def parsefile(filename):
ret = []
linenr = 0
functionName = None
for line in open(filename, 'rt'):
linenr = linenr + 1
res = re.match('^[a-z]+[ *]+([a-z0-9_]+)[(]', line)
if res:
functionName = res.group(1)
if line.startswith('}'):
functionName = ''
elif 'BUG' in line or 'WARN' in line or filename == 'ub.c':
spaces = ' ' * 100
s = filename + spaces
s = s[:15] + str(linenr) + spaces
s = s[:20] + functionName + spaces
s = s[:50]
if hasresult('cppcheck.txt', '[' + filename + ':' + str(linenr) + ']'):
s = s + ' X'
else:
s = s + ' '
if hasresult('clang.txt', filename + ':' + str(linenr)):
s = s + ' X'
else:
s = s + ' '
if hasresult('lint.txt', filename + ' ' + str(linenr)):
s = s + ' X'
else:
s = s + ' '
if hasresult('cov.txt', filename + ':' + str(linenr)):
s = s + ' X'
else:
s = s + ' '
ret.append(s)
return ret
bugs = []
bugs.extend(parsefile('controlflow.c'))
bugs.extend(parsefile('data.c'))
bugs.extend(parsefile('functions.c'))
bugs.extend(parsefile('ub.c'))
for bug in bugs:
print(bug)

View File

@ -1,4 +0,0 @@
#!/bin/bash
~/llvm/build/bin/clang -cc1 -analyze -analyzer-checker=alpha.security controlflow.c data.c functions.c 2>&1 /dev/null | grep warning
~/llvm/build/bin/clang -cc1 -analyze -analyzer-checker=alpha.security,core ub.c 2>&1 /dev/null | grep warning

View File

@ -1,4 +0,0 @@
\lint\lint-nt.exe -e526 -e529 -e550 -e552 -e714 -e744 -e765 -e830 -e831 -e843 -h1 controlflow.c
\lint\lint-nt.exe -e526 -e529 -e550 -e552 -e714 -e744 -e765 -e830 -e831 -e843 -h1 data.c
\lint\lint-nt.exe -e526 -e529 -e550 -e552 -e714 -e744 -e765 -e830 -e831 -e843 -h1 functions.c
\lint\lint-nt.exe -e526 -e529 -e550 -e552 -e714 -e744 -e765 -e830 -e831 -e843 -h1 ub.c

View File

@ -1,49 +0,0 @@
void alias() {
int x; int *ip=&x; float *fp = (float *)ip;
}
int buffer_overflow() {
int x[10]={0}; return x[100];
}
int dead_pointer(int a) {
int *p=&a; if (a) { int x=0; p = &x; } return *p;
}
int division_by_zero() {
return 100 / 0;
}
int float_to_int() {
double d=1E100; return (int)d;
}
void negative_size(int sz) {
if (sz < 0) { int buf[sz]; }
}
int no_return() {}
int null_pointer() {
int *p = 0; return *p;
}
int *pointer_arithmetic() {
static int buf[10]; return buf + 100;
}
unsigned char pointer_to_u8() {
static int buf[10]; return (int*)buf;
}
int pointer_subtraction() {
char a[10]; char b[10]; return b-a;
}
int pointer_comparison() {
char a[10]; char b[10]; return b<a;
}
int shift_overrun(int x) {
return x << 123;
}
int shift_negative() {
return -1 << 1;
}
int int_overflow() {
int intmax = (~0U) >> 1; return intmax * 2;
}
void string_literal() {
*((char *)"hello") = 0;
}
int uninit() {
int x; return x + 2;
}

View File

@ -1,128 +0,0 @@
// RUN: %clang_analyze_cc1 -Wno-array-bounds -analyzer-store=region -verify %s \
// RUN: -analyzer-checker=core \
// RUN: -analyzer-checker=unix \
// RUN: -analyzer-checker=alpha.security.ArrayBound \
// RUN: -analyzer-config unix.DynamicMemoryModeling:Optimistic=true
typedef __typeof(sizeof(int)) size_t;
void *malloc(size_t);
void *calloc(size_t, size_t);
char f1() {
char* s = "abcd";
char c = s[4]; // no-warning
return s[5] + c; // expected-warning{{Access out-of-bound array element (buffer overflow)}}
}
void f2() {
int *p = malloc(12);
p[3] = 4; // expected-warning{{Access out-of-bound array element (buffer overflow)}}
}
struct three_words {
int c[3];
};
struct seven_words {
int c[7];
};
void f3() {
struct three_words a, *p;
p = &a;
p[0] = a; // no-warning
p[1] = a; // expected-warning{{Access out-of-bound array element (buffer overflow)}}
}
void f4() {
struct seven_words c;
struct three_words a, *p = (struct three_words *)&c;
p[0] = a; // no-warning
p[1] = a; // no-warning
p[2] = a; // expected-warning{{Access out-of-bound array element (buffer overflow)}}
}
void f5() {
char *p = calloc(2,2);
p[3] = '.'; // no-warning
p[4] = '!'; // expected-warning{{out-of-bound}}
}
void f6() {
char a[2];
int *b = (int*)a;
b[1] = 3; // expected-warning{{out-of-bound}}
}
void f7() {
struct three_words a;
a.c[3] = 1; // expected-warning{{out-of-bound}}
}
void vla(int a) {
if (a == 5) {
int x[a];
x[4] = 4; // no-warning
x[5] = 5; // expected-warning{{out-of-bound}}
}
}
void alloca_region(int a) {
if (a == 5) {
char *x = __builtin_alloca(a);
x[4] = 4; // no-warning
x[5] = 5; // expected-warning{{out-of-bound}}
}
}
int symbolic_index(int a) {
int x[2] = {1, 2};
if (a == 2) {
return x[a]; // expected-warning{{out-of-bound}}
}
return 0;
}
int symbolic_index2(int a) {
int x[2] = {1, 2};
if (a < 0) {
return x[a]; // expected-warning{{out-of-bound}}
}
return 0;
}
int overflow_binary_search(double in) {
int eee = 16;
if (in < 1e-8 || in > 1e23) {
return 0;
} else {
static const double ins[] = {1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1,
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7,
1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22};
if (in < ins[eee]) {
eee -= 8;
} else {
eee += 8;
}
if (in < ins[eee]) {
eee -= 4;
} else {
eee += 4;
}
if (in < ins[eee]) {
eee -= 2;
} else {
eee += 2;
}
if (in < ins[eee]) {
eee -= 1;
} else {
eee += 1;
}
if (in < ins[eee]) { // expected-warning {{Access out-of-bound array element (buffer overflow)}}
eee -= 1;
}
}
return eee;
}

View File

@ -1,3 +0,0 @@
arrayIndexOutOfBounds:
~/llvm/tools/clang/test/Analysis/outofbound.c

View File

@ -1,79 +0,0 @@
// make USE_Z3=yes
// ./cppcheck --verify --inline-suppr --enable=information test/testsuites/danmar-verify/divbyzero.cpp
#include <stdio.h>
#include <map>
struct S { int x; };
int globalvar;
void dostuff();
int callfunc1() {
int x = 16;
scanf("%i\n", &x);
// cppcheck-suppress verificationDivByZero
return 100000 / x;
}
int float1(float f) {
// cppcheck-suppress verificationDivByZero
return 100000 / (int)f;
}
float float2(float f) {
// cppcheck-suppress verificationDivByZeroFloat
return 100000 / f;
}
int functionCall() {
#ifdef __clang__
return 0;
#else
// cppcheck-suppress verificationDivByZero
return 100000 / unknown_function();
#endif
}
int globalVar1() {
// cppcheck-suppress verificationDivByZero
return 100000 / globalvar;
}
int globalVar2() {
globalvar = 123;
dostuff();
// cppcheck-suppress verificationDivByZero
return 100000 / globalvar;
}
int pointer1(int *p) {
// cppcheck-suppress verificationDivByZero
return 100000 / *p;
}
int pointer2(int *p) {
// cppcheck-suppress verificationDivByZero
return 100000 / p[32];
}
int stdmap(std::map<int,int> &data) {
// cppcheck-suppress verificationDivByZero
return 100000 / data[43];
}
int struct1(struct S *s) {
// cppcheck-suppress verificationDivByZero
return 100000 / s->x;
}
int trycatch() {
int x = 0;
try {
dostuff();
x = 1;
} catch (...) {}
// cppcheck-suppress verificationDivByZero
return 100000 / x;
}

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