2011-02-17 16:10:53 +08:00
|
|
|
#include <string.h>
|
|
|
|
#include <jansson.h>
|
|
|
|
|
|
|
|
#include "util.h"
|
|
|
|
|
|
|
|
static int malloc_called = 0;
|
|
|
|
static int free_called = 0;
|
|
|
|
|
|
|
|
/* helper */
|
|
|
|
static void create_and_free_complex_object()
|
|
|
|
{
|
|
|
|
json_t *obj;
|
|
|
|
|
2015-08-13 15:44:31 +08:00
|
|
|
obj = json_pack("{s:i,s:n,s:b,s:b,s:{s:s},s:[i,i,i]}",
|
2011-02-17 16:10:53 +08:00
|
|
|
"foo", 42,
|
|
|
|
"bar",
|
|
|
|
"baz", 1,
|
|
|
|
"qux", 0,
|
|
|
|
"alice", "bar", "baz",
|
|
|
|
"bob", 9, 8, 7);
|
|
|
|
|
|
|
|
json_decref(obj);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void *my_malloc(size_t size)
|
|
|
|
{
|
2014-01-14 17:16:39 +08:00
|
|
|
malloc_called = 1;
|
2011-02-17 16:10:53 +08:00
|
|
|
return malloc(size);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void my_free(void *ptr)
|
|
|
|
{
|
2014-01-14 17:16:39 +08:00
|
|
|
free_called = 1;
|
2011-02-17 16:10:53 +08:00
|
|
|
free(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void test_simple()
|
|
|
|
{
|
2015-12-22 00:46:32 +08:00
|
|
|
json_malloc_t mfunc = NULL;
|
|
|
|
json_free_t ffunc = NULL;
|
|
|
|
|
2011-02-17 16:10:53 +08:00
|
|
|
json_set_alloc_funcs(my_malloc, my_free);
|
2015-12-22 00:46:32 +08:00
|
|
|
json_get_alloc_funcs(&mfunc, &ffunc);
|
2011-02-17 16:10:53 +08:00
|
|
|
create_and_free_complex_object();
|
|
|
|
|
2015-12-22 00:46:32 +08:00
|
|
|
if (malloc_called != 1 || free_called != 1
|
|
|
|
|| mfunc != my_malloc || ffunc != my_free)
|
2011-02-17 16:10:53 +08:00
|
|
|
fail("Custom allocation failed");
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
Test the secure memory functions code given in the API reference
|
|
|
|
documentation, but by using plain memset instead of
|
|
|
|
guaranteed_memset().
|
|
|
|
*/
|
|
|
|
|
|
|
|
static void *secure_malloc(size_t size)
|
|
|
|
{
|
|
|
|
/* Store the memory area size in the beginning of the block */
|
|
|
|
void *ptr = malloc(size + 8);
|
|
|
|
*((size_t *)ptr) = size;
|
2012-06-04 02:17:29 +08:00
|
|
|
return (char *)ptr + 8;
|
2011-02-17 16:10:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static void secure_free(void *ptr)
|
|
|
|
{
|
|
|
|
size_t size;
|
|
|
|
|
2012-06-04 02:17:29 +08:00
|
|
|
ptr = (char *)ptr - 8;
|
2011-02-17 16:10:53 +08:00
|
|
|
size = *((size_t *)ptr);
|
|
|
|
|
2013-11-14 14:49:16 +08:00
|
|
|
/*guaranteed_*/memset(ptr, 0, size + 8);
|
2011-02-17 16:10:53 +08:00
|
|
|
free(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void test_secure_funcs(void)
|
|
|
|
{
|
|
|
|
json_set_alloc_funcs(secure_malloc, secure_free);
|
|
|
|
create_and_free_complex_object();
|
|
|
|
}
|
|
|
|
|
2011-10-03 02:27:53 +08:00
|
|
|
static void run_tests()
|
2011-02-17 16:10:53 +08:00
|
|
|
{
|
|
|
|
test_simple();
|
|
|
|
test_secure_funcs();
|
|
|
|
}
|