Coverage Report

Created: 2024-04-23 06:32

/src/testdir/tests/capi/lua_load_test.cc
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * SPDX-License-Identifier: ISC
3
 *
4
 * Copyright 2023, Sergey Bronnikov.
5
 */
6
7
#include <assert.h>
8
#include <string.h>
9
10
#if defined(__cplusplus)
11
extern "C" {
12
#endif /* defined(__cplusplus) */
13
14
#include "lua.h"
15
#include "lualib.h"
16
#include "lauxlib.h"
17
18
#if defined(__cplusplus)
19
} /* extern "C" */
20
#endif /* defined(__cplusplus) */
21
22
#include <fuzzer/FuzzedDataProvider.h>
23
24
typedef struct {
25
  FuzzedDataProvider *fdp;
26
} dt;
27
28
static const char *
29
Reader(lua_State *L, void *data, size_t *size)
30
1.15M
{
31
1.15M
  dt *test_data = (dt *)data;
32
1.15M
  static char *buf = NULL;
33
34
1.15M
  FuzzedDataProvider *fdp = test_data->fdp;
35
1.15M
  uint8_t max_str_size = fdp->ConsumeIntegral<uint8_t>();
36
1.15M
  if (fdp->remaining_bytes() < max_str_size)
37
1.78k
    return NULL;
38
1.14M
  auto str = fdp->ConsumeRandomLengthString(max_str_size);
39
1.14M
  *size = str.size();
40
41
1.14M
  free(buf);
42
1.14M
  buf = (char *)malloc(*size);
43
1.14M
  assert(buf);
44
0
  memcpy(buf, str.c_str(), *size);
45
46
1.14M
  return buf;
47
1.15M
}
48
49
extern "C" int
50
LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
51
2.48k
{
52
2.48k
  lua_State *L = luaL_newstate();
53
2.48k
  if (L == NULL)
54
0
    return 0;
55
56
2.48k
  luaL_openlibs(L);
57
58
2.48k
  FuzzedDataProvider fdp(data, size);
59
2.48k
  dt test_data;
60
2.48k
  test_data.fdp = &fdp;
61
62
2.48k
  const char *mode = "t";
63
#if LUA_VERSION_NUM == 501
64
  int res = lua_load(L, Reader, &test_data, "libFuzzer");
65
#else /* Lua 5.3+ */
66
2.48k
  int res = lua_load(L, Reader, &test_data, "libFuzzer", mode);
67
2.48k
#endif /* LUA_VERSION_NUM */
68
2.48k
  if (res == LUA_OK) {
69
1.98k
    lua_pcall(L, 0, 0, 0);
70
1.98k
  }
71
72
2.48k
  lua_settop(L, 0);
73
2.48k
  lua_close(L);
74
75
2.48k
  return 0;
76
2.48k
}