Skip to content

Commit e9b72d8

Browse files
guidovrankenstweil
authored andcommitted
Add API fuzzer
1 parent aa78a72 commit e9b72d8

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

fuzzer-api.cpp

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#include "baseapi.h"
2+
#include "leptonica/allheaders.h"
3+
4+
#include <stdint.h>
5+
#include <stddef.h>
6+
#include <stdlib.h>
7+
8+
class BitReader {
9+
private:
10+
uint8_t const* data;
11+
size_t size;
12+
size_t shift;
13+
public:
14+
BitReader(const uint8_t* data, size_t size) :
15+
data(data), size(size), shift(0)
16+
{ }
17+
18+
int Read(void) {
19+
if ( size == 0 ) {
20+
return 0;
21+
}
22+
23+
const int ret = ((*data) >> shift) & 1;
24+
25+
shift++;
26+
if ( shift >= 8 ) {
27+
shift = 0;
28+
data++;
29+
size--;
30+
}
31+
32+
return ret;
33+
}
34+
};
35+
36+
tesseract::TessBaseAPI *api = nullptr;
37+
38+
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv)
39+
{
40+
(void)argc;
41+
(void)argv;
42+
43+
44+
#ifndef TESSDATA_PREFIX
45+
#error TESSDATA_PREFIX must be defined
46+
#else
47+
if ( setenv("TESSDATA_PREFIX", TESSDATA_PREFIX, 1) != 0 ) {
48+
printf("Setenv failed\n");
49+
abort();
50+
}
51+
#endif
52+
53+
api = new tesseract::TessBaseAPI();
54+
if ( api->Init(nullptr, "eng") != 0 ) {
55+
printf("Cannot initialize API\n");
56+
abort();
57+
}
58+
59+
/* Silence output */
60+
api->SetVariable("debug_file", "/dev/null");
61+
62+
return 0;
63+
}
64+
65+
66+
static PIX* createPix(BitReader& BR, const size_t width, const size_t height) {
67+
Pix* pix = pixCreate(width, height, 1);
68+
69+
if ( pix == nullptr ) {
70+
printf("pix creation failed\n");
71+
abort();
72+
}
73+
74+
for (size_t i = 0; i < width; i++) {
75+
for (size_t j = 0; j < height; j++) {
76+
pixSetPixel(pix, i, j, BR.Read());
77+
}
78+
}
79+
80+
return pix;
81+
}
82+
83+
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
84+
{
85+
BitReader BR(data, size);
86+
87+
auto pix = createPix(BR, 100, 100);
88+
89+
api->SetImage(pix);
90+
91+
char* outText = api->GetUTF8Text();
92+
93+
pixDestroy(&pix);
94+
delete[] outText;
95+
96+
return 0;
97+
}

0 commit comments

Comments
 (0)