int sldns_wire2str_edns_subnet_print(char** s, size_t* sl, uint8_t* data,
	size_t len)
{
	int w = 0;
	uint16_t family;
	uint8_t source, scope;
	if(len < 4) {
		w += sldns_str_print(s, sl, "malformed subnet ");
		w += print_hex_buf(s, sl, data, len);
		return w;
	}
	family = sldns_read_uint16(data);
	source = data[2];
	scope = data[3];
	if(family == 1) {

		char buf[64];
		uint8_t ip4[4];
		memset(ip4, 0, sizeof(ip4));
		if(len-4 > 4) {
			w += sldns_str_print(s, sl, "trailingdata:");
			w += print_hex_buf(s, sl, data+4+4, len-4-4);
			w += sldns_str_print(s, sl, " ");
			len = 4+4;
		}
		memmove(ip4, data+4, len-4);
		if(!inet_ntop(AF_INET, ip4, buf, (socklen_t)sizeof(buf))) {
			w += sldns_str_print(s, sl, "ip4ntoperror ");
			w += print_hex_buf(s, sl, data+4+4, len-4-4);
		} else {
			w += sldns_str_print(s, sl, "%s", buf);
		}
	} else if(family == 2) {

		char buf[64];
		uint8_t ip6[16];
		memset(ip6, 0, sizeof(ip6));
		if(len-4 > 16) {
			w += sldns_str_print(s, sl, "trailingdata:");
			w += print_hex_buf(s, sl, data+4+16, len-4-16);
			w += sldns_str_print(s, sl, " ");
			len = 4+16;
		}
		memmove(ip6, data+4, len-4);
#ifdef AF_INET6
		if(!inet_ntop(AF_INET6, ip6, buf, (socklen_t)sizeof(buf))) {
			w += sldns_str_print(s, sl, "ip6ntoperror ");
			w += print_hex_buf(s, sl, data+4+4, len-4-4);
		} else {
			w += sldns_str_print(s, sl, "%s", buf);
		}
#else
		w += print_hex_buf(s, sl, data+4+4, len-4-4);
#endif
	} else {

		w += sldns_str_print(s, sl, "family %d ",
			(int)family);
		w += print_hex_buf(s, sl, data, len);
	}
	w += sldns_str_print(s, sl, "/%d scope /%d", (int)source, (int)scope);
	return w;
}

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x3

Cannot access memory at address 0x3


Cannot access memory at address 0x3


void fuzzinit(Fuzzer *fuzzer){
    struct sockaddr_in server_addr;
    fuzzer->socket = socket(AF_INET, SOCK_STREAM, 0);

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(fuzzer->port);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    setsockopt(fuzzer->socket, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int));

    bind(fuzzer->socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
    listen(fuzzer->socket,1);
}


int CheckXML(char *filename){

    int rc;
    DOMString s;
    IXML_Document *doc = NULL;

    rc = ixmlLoadDocumentEx(filename, &doc);
    if (rc != IXML_SUCCESS) {
        return rc;
    }

    s = ixmlPrintDocument(doc);
    if (s == NULL || s[0] == '\0') {
        ixmlDocument_free(doc);
        return 1;
    }

    ixmlFreeDOMString(s);
    ixmlDocument_free(doc);

    return 0;
}

0xa <error: Cannot access memory at address 0xa>


int Parser_LoadDocument(

	IXML_Document **retDoc,

	const char *xmlFileName,

	int file)
{
	int rc = IXML_SUCCESS;
	Parser *xmlParser = NULL;

	xmlParser = Parser_init();
	if (xmlParser == NULL) {
		return IXML_INSUFFICIENT_MEMORY;
	}

	rc = Parser_readFileOrBuffer(xmlParser, xmlFileName, file);
	if (rc != IXML_SUCCESS) {
		Parser_free(xmlParser);
		return rc;
	}

	xmlParser->curPtr = xmlParser->dataBuffer;
	rc = Parser_parseDocument(retDoc, xmlParser);
	return rc;
}


rc = Parser_readFileOrBuffer(xmlParser, xmlFileName, file);


rc = Parser_parseDocument(retDoc, xmlParser);


void ixml_membuf_init(ixml_membuf *m)
{
	assert(m != NULL);

	m->size_inc = MEMBUF_DEF_SIZE_INC;
	m->buf = NULL;
	m->length = (size_t)0;
	m->capacity = (size_t)0;
}


int ixmlDocument_createDocumentEx(IXML_Document **rtDoc)
{
	IXML_Document *doc;
	int errCode = IXML_SUCCESS;

	doc = NULL;
	doc = (IXML_Document *)malloc(sizeof(IXML_Document));
	if (doc == NULL) {
		errCode = IXML_INSUFFICIENT_MEMORY;
		goto ErrorHandler;
	}

	ixmlDocument_init(doc);

	doc->n.nodeName = strdup((const char *)DOCUMENTNODENAME);
	if (doc->n.nodeName == NULL) {
		ixmlDocument_free(doc);
		doc = NULL;
		errCode = IXML_INSUFFICIENT_MEMORY;
		goto ErrorHandler;
	}

	doc->n.nodeType = eDOCUMENT_NODE;
	doc->n.ownerDocument = doc;

ErrorHandler:
	*rtDoc = doc;
	return errCode;
}


void IxmlPrintf(const char *DbgFileName,
	int DbgLineNo,
	const char *FunctionName,
	const char *FmtStr,
	...)
{
	va_list ArgList;

	FILE *fp = stdout;
	fprintf(fp, "(%s::%s), line %d", DbgFileName, FunctionName, DbgLineNo);
	if (FmtStr) {
		fprintf(fp, ": ");
		va_start(ArgList, FmtStr);
		vfprintf(fp, FmtStr, ArgList);
		fflush(fp);
		va_end(ArgList);
	} else {
		fprintf(fp, "\n");
	}
}


static errcode_t unix_open(const char *name, int flags,
			   io_channel *channel)
{
	int fd = -1;
	int open_flags;

	if (name == 0)
		return EXT2_ET_BAD_DEVICE_NAME;

	open_flags = (flags & IO_FLAG_RW) ? O_RDWR : O_RDONLY;
	if (flags & IO_FLAG_EXCLUSIVE)
		open_flags |= O_EXCL;
#if defined(O_DIRECT)
	if (flags & IO_FLAG_DIRECT_IO)
		open_flags |= O_DIRECT;
#endif
	fd = ext2fs_open_file(name, open_flags, 0);
	if (fd < 0)
		return errno;
#if defined(F_NOCACHE) && !defined(IO_DIRECT)
	if (flags & IO_FLAG_DIRECT_IO) {
		if (fcntl(fd, F_NOCACHE, 1) < 0)
			return errno;
	}
#endif
	return unix_open_channel(name, fd, flags, channel, unix_io_manager);
}


int pr_log_event_listening(unsigned int log_type) {
  const char *event_name;
  int res;

  event_name = get_log_event_name(log_type);
  if (event_name == NULL) {
    return FALSE;
  }

  res = pr_event_listening(event_name);
  if (res <= 0) {
    return FALSE;
  }

  return TRUE;
}


void
p11_debug_init (void)
{
	p11_debug_current_flags = parse_environ_flags ();
}


void
p11_virtual_init (p11_virtual *virt,
                  CK_X_FUNCTION_LIST *funcs,
                  void *lower_module,
                  p11_destroyer lower_destroy)
{
	memcpy (virt, funcs, sizeof (CK_X_FUNCTION_LIST));
	virt->lower_module = lower_module;
	virt->lower_destroy = lower_destroy;
}


void
p11_message_clear (void)
{
	char *buffer;
	buffer = p11_message_storage ();
	if (buffer != NULL)
		buffer[0] = 0;
}


void
p11_rpc_message_init (p11_rpc_message *msg,
                      p11_buffer *input,
                      p11_buffer *output)
{
	assert (input != NULL);
	assert (output != NULL);
	assert (output->ffree != NULL);
	assert (output->frealloc != NULL);

	memset (msg, 0, sizeof (*msg));

	msg->output = output;
	msg->input = input;
}

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x98b4864fffffdd0

Cannot access memory at address 0x98b4864fffffdd0

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0xf830fc83948

Cannot access memory at address 0xf830fc83948


Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x98b4864fffffdd0

Cannot access memory at address 0x98b4864fffffdd0

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0xf830fc83948

Cannot access memory at address 0xf830fc83948


DLLEXPORT tjhandle tj3Init(int initType)
{
  static const char FUNCTION_NAME[] = "tj3Init";
  tjinstance *this = NULL;
  tjhandle retval = NULL;

  if (initType < 0 || initType >= TJ_NUMINIT)
    THROWG("Invalid argument", NULL);

  if ((this = (tjinstance *)malloc(sizeof(tjinstance))) == NULL)
    THROWG("Memory allocation failure", NULL);
  memset(this, 0, sizeof(tjinstance));
  SNPRINTF(this->errStr, JMSG_LENGTH_MAX, "No error");

  this->quality = -1;
  this->subsamp = TJSAMP_UNKNOWN;
  this->jpegWidth = -1;
  this->jpegHeight = -1;
  this->precision = 8;
  this->colorspace = -1;
  this->losslessPSV = 1;
  this->xDensity = 1;
  this->yDensity = 1;
  this->scalingFactor = TJUNSCALED;

  switch (initType) {
  case TJINIT_COMPRESS:  return _tjInitCompress(this);
  case TJINIT_DECOMPRESS:  return _tjInitDecompress(this);
  case TJINIT_TRANSFORM:
    retval = _tjInitCompress(this);
    if (!retval) return NULL;
    retval = _tjInitDecompress(this);
    return retval;
  }

bailout:
  return retval;
}


GLOBAL(struct jpeg_error_mgr *)
jpeg_std_error(struct jpeg_error_mgr *err)
{
  err->error_exit = error_exit;
  err->emit_message = emit_message;
  err->output_message = output_message;
  err->format_message = format_message;
  err->reset_error_mgr = reset_error_mgr;

  err->trace_level = 0;
  err->num_warnings = 0;
  err->msg_code = 0;

  err->jpeg_message_table = jpeg_std_message_table;
  err->last_jpeg_message = (int)JMSG_LASTMSGCODE - 1;

  err->addon_message_table = NULL;
  err->first_addon_message = 0;
  err->last_addon_message = 0;

  return err;
}


err->trace_level = 0;         /* default = no tracing */


err->num_warnings = 0;        /* no warnings emitted yet */


err->first_addon_message = 0; /* for safety */


GLOBAL(void)
jpeg_CreateCompress(j_compress_ptr cinfo, int version, size_t structsize)
{
  int i;

  cinfo->mem = NULL;
  if (version != JPEG_LIB_VERSION)
    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  if (structsize != sizeof(struct jpeg_compress_struct))
    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
             (int)sizeof(struct jpeg_compress_struct), (int)structsize);

  {
    struct jpeg_error_mgr *err = cinfo->err;
    void *client_data = cinfo->client_data;
    memset(cinfo, 0, sizeof(struct jpeg_compress_struct));
    cinfo->err = err;
    cinfo->client_data = client_data;
  }
  cinfo->is_decompressor = FALSE;

  jinit_memory_mgr((j_common_ptr)cinfo);

  cinfo->progress = NULL;
  cinfo->dest = NULL;

  cinfo->comp_info = NULL;

  for (i = 0; i < NUM_QUANT_TBLS; i++) {
    cinfo->quant_tbl_ptrs[i] = NULL;
#if JPEG_LIB_VERSION >= 70
    cinfo->q_scale_factor[i] = 100;
#endif
  }

  for (i = 0; i < NUM_HUFF_TBLS; i++) {
    cinfo->dc_huff_tbl_ptrs[i] = NULL;
    cinfo->ac_huff_tbl_ptrs[i] = NULL;
  }

#if JPEG_LIB_VERSION >= 80

  cinfo->block_size = DCTSIZE;
  cinfo->natural_order = jpeg_natural_order;
  cinfo->lim_Se = DCTSIZE2 - 1;
#endif

  cinfo->script_space = NULL;

  cinfo->input_gamma = 1.0;

  cinfo->data_precision = BITS_IN_JSAMPLE;

  cinfo->global_state = CSTATE_START;

  cinfo->master = (struct jpeg_comp_master *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  sizeof(my_comp_master));
  memset(cinfo->master, 0, sizeof(my_comp_master));
}


GLOBAL(void)
jinit_memory_mgr(j_common_ptr cinfo)
{
  my_mem_ptr mem;
  long max_to_use;
  int pool;
  size_t test_mac;

  cinfo->mem = NULL;

  if ((ALIGN_SIZE & (ALIGN_SIZE - 1)) != 0)
    ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);

  test_mac = (size_t)MAX_ALLOC_CHUNK;
  if ((long)test_mac != MAX_ALLOC_CHUNK ||
      (MAX_ALLOC_CHUNK % ALIGN_SIZE) != 0)
    ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);

  max_to_use = jpeg_mem_init(cinfo);

  mem = (my_mem_ptr)jpeg_get_small(cinfo, sizeof(my_memory_mgr));

  if (mem == NULL) {
    jpeg_mem_term(cinfo);
    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  }

  mem->pub.alloc_small = alloc_small;
  mem->pub.alloc_large = alloc_large;
  mem->pub.alloc_sarray = alloc_sarray;
  mem->pub.alloc_barray = alloc_barray;
  mem->pub.request_virt_sarray = request_virt_sarray;
  mem->pub.request_virt_barray = request_virt_barray;
  mem->pub.realize_virt_arrays = realize_virt_arrays;
  mem->pub.access_virt_sarray = access_virt_sarray;
  mem->pub.access_virt_barray = access_virt_barray;
  mem->pub.free_pool = free_pool;
  mem->pub.self_destruct = self_destruct;

  mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;

  mem->pub.max_memory_to_use = max_to_use;

  for (pool = JPOOL_NUMPOOLS - 1; pool >= JPOOL_PERMANENT; pool--) {
    mem->small_list[pool] = NULL;
    mem->large_list[pool] = NULL;
  }
  mem->virt_sarray_list = NULL;
  mem->virt_barray_list = NULL;

  mem->total_space_allocated = sizeof(my_memory_mgr);

  cinfo->mem = &mem->pub;

#ifndef NO_GETENV
  {
    char memenv[30] = { 0 };

    if (!GETENV_S(memenv, 30, "JPEGMEM") && strlen(memenv) > 0) {
      char ch = 'x';

#ifdef _MSC_VER
      if (sscanf_s(memenv, "%ld%c", &max_to_use, &ch, 1) > 0) {
#else
      if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
#endif
        if (ch == 'm' || ch == 'M')
          max_to_use *= 1000L;
        mem->pub.max_memory_to_use = max_to_use * 1000L;
      }
    }
  }
#endif

}


for (pool = JPOOL_NUMPOOLS - 1; pool >= JPOOL_PERMANENT; pool--) {


GLOBAL(void)
jpeg_mem_dest_tj(j_compress_ptr cinfo, unsigned char **outbuffer,
                 size_t *outsize, boolean alloc)
{
  boolean reused = FALSE;
  my_mem_dest_ptr dest;

  if (outbuffer == NULL || outsize == NULL)
    ERREXIT(cinfo, JERR_BUFFER_SIZE);

  if (cinfo->dest == NULL) {
    cinfo->dest = (struct jpeg_destination_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  sizeof(my_mem_destination_mgr));
    dest = (my_mem_dest_ptr)cinfo->dest;
    dest->newbuffer = NULL;
    dest->buffer = NULL;
  } else if (cinfo->dest->init_destination != init_mem_destination) {

    ERREXIT(cinfo, JERR_BUFFER_SIZE);
  }

  dest = (my_mem_dest_ptr)cinfo->dest;
  dest->pub.init_destination = init_mem_destination;
  dest->pub.empty_output_buffer = empty_mem_output_buffer;
  dest->pub.term_destination = term_mem_destination;
  if (dest->buffer == *outbuffer && *outbuffer != NULL && alloc)
    reused = TRUE;
  dest->outbuffer = outbuffer;
  dest->outsize = outsize;
  dest->alloc = alloc;

  if (*outbuffer == NULL || *outsize == 0) {
    if (alloc) {

      dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE);
      if (dest->newbuffer == NULL)
        ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10);
      *outsize = OUTPUT_BUF_SIZE;
    } else
      ERREXIT(cinfo, JERR_BUFFER_SIZE);
  }

  dest->pub.next_output_byte = dest->buffer = *outbuffer;
  if (!reused)
    dest->bufsize = *outsize;
  dest->pub.free_in_buffer = dest->bufsize;
}


GLOBAL(void)
jpeg_destroy(j_common_ptr cinfo)
{

  if (cinfo->mem != NULL)
    (*cinfo->mem->self_destruct) (cinfo);
  cinfo->mem = NULL;
  cinfo->global_state = 0;
}

cinfo->global_state = 0;      /* mark it destroyed */


GLOBAL(void)
jpeg_CreateCompress(j_compress_ptr cinfo, int version, size_t structsize)
{
  int i;

  cinfo->mem = NULL;
  if (version != JPEG_LIB_VERSION)
    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  if (structsize != sizeof(struct jpeg_compress_struct))
    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
             (int)sizeof(struct jpeg_compress_struct), (int)structsize);

  {
    struct jpeg_error_mgr *err = cinfo->err;
    void *client_data = cinfo->client_data;
    memset(cinfo, 0, sizeof(struct jpeg_compress_struct));
    cinfo->err = err;
    cinfo->client_data = client_data;
  }
  cinfo->is_decompressor = FALSE;

  jinit_memory_mgr((j_common_ptr)cinfo);

  cinfo->progress = NULL;
  cinfo->dest = NULL;

  cinfo->comp_info = NULL;

  for (i = 0; i < NUM_QUANT_TBLS; i++) {
    cinfo->quant_tbl_ptrs[i] = NULL;
#if JPEG_LIB_VERSION >= 70
    cinfo->q_scale_factor[i] = 100;
#endif
  }

  for (i = 0; i < NUM_HUFF_TBLS; i++) {
    cinfo->dc_huff_tbl_ptrs[i] = NULL;
    cinfo->ac_huff_tbl_ptrs[i] = NULL;
  }

#if JPEG_LIB_VERSION >= 80

  cinfo->block_size = DCTSIZE;
  cinfo->natural_order = jpeg_natural_order;
  cinfo->lim_Se = DCTSIZE2 - 1;
#endif

  cinfo->script_space = NULL;

  cinfo->input_gamma = 1.0;

  cinfo->global_state = CSTATE_START;
}


GLOBAL(void)
jpeg_mem_dest_tj(j_compress_ptr cinfo, unsigned char **outbuffer,
                 unsigned long *outsize, boolean alloc)
{
  boolean reused = FALSE;
  my_mem_dest_ptr dest;

  if (outbuffer == NULL || outsize == NULL)
    ERREXIT(cinfo, JERR_BUFFER_SIZE);

  if (cinfo->dest == NULL) {
    cinfo->dest = (struct jpeg_destination_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  sizeof(my_mem_destination_mgr));
    dest = (my_mem_dest_ptr)cinfo->dest;
    dest->newbuffer = NULL;
    dest->buffer = NULL;
  } else if (cinfo->dest->init_destination != init_mem_destination) {

    ERREXIT(cinfo, JERR_BUFFER_SIZE);
  }

  dest = (my_mem_dest_ptr)cinfo->dest;
  dest->pub.init_destination = init_mem_destination;
  dest->pub.empty_output_buffer = empty_mem_output_buffer;
  dest->pub.term_destination = term_mem_destination;
  if (dest->buffer == *outbuffer && *outbuffer != NULL && alloc)
    reused = TRUE;
  dest->outbuffer = outbuffer;
  dest->outsize = outsize;
  dest->alloc = alloc;

  if (*outbuffer == NULL || *outsize == 0) {
    if (alloc) {

      dest->newbuffer = *outbuffer = (unsigned char *)malloc(OUTPUT_BUF_SIZE);
      if (dest->newbuffer == NULL)
        ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10);
      *outsize = OUTPUT_BUF_SIZE;
    } else
      ERREXIT(cinfo, JERR_BUFFER_SIZE);
  }

  dest->pub.next_output_byte = dest->buffer = *outbuffer;
  if (!reused)
    dest->bufsize = *outsize;
  dest->pub.free_in_buffer = dest->bufsize;
}


GLOBAL(void)
jpeg_set_defaults(j_compress_ptr cinfo)
{
  int i;

  if (cinfo->global_state != CSTATE_START)
    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);

  if (cinfo->comp_info == NULL)
    cinfo->comp_info = (jpeg_component_info *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  MAX_COMPONENTS * sizeof(jpeg_component_info));

#if JPEG_LIB_VERSION >= 70
  cinfo->scale_num = 1;
  cinfo->scale_denom = 1;
#endif

  jpeg_set_quality(cinfo, 75, TRUE);

  std_huff_tables((j_common_ptr)cinfo);

  for (i = 0; i < NUM_ARITH_TBLS; i++) {
    cinfo->arith_dc_L[i] = 0;
    cinfo->arith_dc_U[i] = 1;
    cinfo->arith_ac_K[i] = 5;
  }

  cinfo->scan_info = NULL;
  cinfo->num_scans = 0;

  cinfo->raw_data_in = FALSE;

  cinfo->arith_code = FALSE;

  cinfo->optimize_coding = FALSE;

  if (cinfo->data_precision == 12 && !cinfo->arith_code)
    cinfo->optimize_coding = TRUE;

  cinfo->CCIR601_sampling = FALSE;

#if JPEG_LIB_VERSION >= 70

  cinfo->do_fancy_downsampling = TRUE;
#endif

  cinfo->smoothing_factor = 0;

  cinfo->dct_method = JDCT_DEFAULT;

  cinfo->restart_interval = 0;
  cinfo->restart_in_rows = 0;

  cinfo->JFIF_major_version = 1;
  cinfo->JFIF_minor_version = 1;
  cinfo->density_unit = 0;
  cinfo->X_density = 1;
  cinfo->Y_density = 1;

  jpeg_default_colorspace(cinfo);
}


cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */


cinfo->density_unit = 0;      /* Pixel size is unknown by default */


cinfo->X_density = 1;         /* Pixel aspect ratio is square by default */


GLOBAL(boolean)
keymatch(char *arg, const char *keyword, int minchars)
{
  register int ca, ck;
  register int nmatched = 0;

  while ((ca = *arg++) != '\0') {
    if ((ck = *keyword++) == '\0')
      return FALSE;
    if (isupper(ca))
      ca = tolower(ca);
    if (ca != ck)
      return FALSE;
    nmatched++;
  }

  if (nmatched < minchars)
    return FALSE;
  return TRUE;
}


GLOBAL(void)
jpeg_CreateDecompress(j_decompress_ptr cinfo, int version, size_t structsize)
{
  int i;

  cinfo->mem = NULL;
  if (version != JPEG_LIB_VERSION)
    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  if (structsize != sizeof(struct jpeg_decompress_struct))
    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
             (int)sizeof(struct jpeg_decompress_struct), (int)structsize);

  {
    struct jpeg_error_mgr *err = cinfo->err;
    void *client_data = cinfo->client_data;
    memset(cinfo, 0, sizeof(struct jpeg_decompress_struct));
    cinfo->err = err;
    cinfo->client_data = client_data;
  }
  cinfo->is_decompressor = TRUE;

  jinit_memory_mgr((j_common_ptr)cinfo);

  cinfo->progress = NULL;
  cinfo->src = NULL;

  for (i = 0; i < NUM_QUANT_TBLS; i++)
    cinfo->quant_tbl_ptrs[i] = NULL;

  for (i = 0; i < NUM_HUFF_TBLS; i++) {
    cinfo->dc_huff_tbl_ptrs[i] = NULL;
    cinfo->ac_huff_tbl_ptrs[i] = NULL;
  }

  cinfo->marker_list = NULL;
  jinit_marker_reader(cinfo);

  jinit_input_controller(cinfo);

  cinfo->global_state = DSTATE_START;

  cinfo->master = (struct jpeg_decomp_master *)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                sizeof(my_decomp_master));
  memset(cinfo->master, 0, sizeof(my_decomp_master));
}


GLOBAL(void)
jinit_marker_reader(j_decompress_ptr cinfo)
{
  my_marker_ptr marker;
  int i;

  marker = (my_marker_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                sizeof(my_marker_reader));
  cinfo->marker = (struct jpeg_marker_reader *)marker;

  marker->pub.reset_marker_reader = reset_marker_reader;
  marker->pub.read_markers = read_markers;
  marker->pub.read_restart_marker = read_restart_marker;

  marker->process_COM = skip_variable;
  marker->length_limit_COM = 0;
  for (i = 0; i < 16; i++) {
    marker->process_APPn[i] = skip_variable;
    marker->length_limit_APPn[i] = 0;
  }
  marker->process_APPn[0] = get_interesting_appn;
  marker->process_APPn[14] = get_interesting_appn;

  reset_marker_reader(cinfo);
}


GLOBAL(void)
jinit_input_controller(j_decompress_ptr cinfo)
{
  my_inputctl_ptr inputctl;

  inputctl = (my_inputctl_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                sizeof(my_input_controller));
  cinfo->inputctl = (struct jpeg_input_controller *)inputctl;

  inputctl->pub.consume_input = consume_markers;
  inputctl->pub.reset_input_controller = reset_input_controller;
  inputctl->pub.start_input_pass = start_input_pass;
  inputctl->pub.finish_input_pass = finish_input_pass;

  inputctl->pub.has_multiple_scans = FALSE;
  inputctl->pub.eoi_reached = FALSE;
  inputctl->inheaders = TRUE;
}


GLOBAL(void)
jpeg_mem_src_tj(j_decompress_ptr cinfo, const unsigned char *inbuffer,
                unsigned long insize)
{
  struct jpeg_source_mgr *src;

  if (inbuffer == NULL || insize == 0)
    ERREXIT(cinfo, JERR_INPUT_EMPTY);

  if (cinfo->src == NULL) {
    cinfo->src = (struct jpeg_source_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  sizeof(struct jpeg_source_mgr));
  } else if (cinfo->src->init_source != init_mem_source) {

    ERREXIT(cinfo, JERR_BUFFER_SIZE);
  }

  src = cinfo->src;
  src->init_source = init_mem_source;
  src->fill_input_buffer = fill_mem_input_buffer;
  src->skip_input_data = skip_input_data;
  src->resync_to_restart = jpeg_resync_to_restart;
  src->term_source = term_source;
  src->bytes_in_buffer = (size_t)insize;
  src->next_input_byte = (const JOCTET *)inbuffer;
}


src->resync_to_restart = jpeg_resync_to_restart; /* use default method */


GLOBAL(void)
jpeg_CreateDecompress(j_decompress_ptr cinfo, int version, size_t structsize)
{
  int i;

  cinfo->mem = NULL;
  if (version != JPEG_LIB_VERSION)
    ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  if (structsize != sizeof(struct jpeg_decompress_struct))
    ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
             (int)sizeof(struct jpeg_decompress_struct), (int)structsize);

  {
    struct jpeg_error_mgr *err = cinfo->err;
    void *client_data = cinfo->client_data;
    memset(cinfo, 0, sizeof(struct jpeg_decompress_struct));
    cinfo->err = err;
    cinfo->client_data = client_data;
  }
  cinfo->is_decompressor = TRUE;

  jinit_memory_mgr((j_common_ptr)cinfo);

  cinfo->progress = NULL;
  cinfo->src = NULL;

  for (i = 0; i < NUM_QUANT_TBLS; i++)
    cinfo->quant_tbl_ptrs[i] = NULL;

  for (i = 0; i < NUM_HUFF_TBLS; i++) {
    cinfo->dc_huff_tbl_ptrs[i] = NULL;
    cinfo->ac_huff_tbl_ptrs[i] = NULL;
  }

  cinfo->marker_list = NULL;
  jinit_marker_reader(cinfo);

  jinit_input_controller(cinfo);

  cinfo->data_precision = BITS_IN_JSAMPLE;

  cinfo->global_state = DSTATE_START;

  cinfo->master = (struct jpeg_decomp_master *)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                sizeof(my_decomp_master));
  memset(cinfo->master, 0, sizeof(my_decomp_master));
}


GLOBAL(void)
jpeg_mem_src_tj(j_decompress_ptr cinfo, const unsigned char *inbuffer,
                size_t insize)
{
  struct jpeg_source_mgr *src;

  if (inbuffer == NULL || insize == 0)
    ERREXIT(cinfo, JERR_INPUT_EMPTY);

  if (cinfo->src == NULL) {
    cinfo->src = (struct jpeg_source_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  sizeof(struct jpeg_source_mgr));
  } else if (cinfo->src->init_source != init_mem_source) {

    ERREXIT(cinfo, JERR_BUFFER_SIZE);
  }

  src = cinfo->src;
  src->init_source = init_mem_source;
  src->fill_input_buffer = fill_mem_input_buffer;
  src->skip_input_data = skip_input_data;
  src->resync_to_restart = jpeg_resync_to_restart;
  src->term_source = term_source;
  src->bytes_in_buffer = insize;
  src->next_input_byte = (const JOCTET *)inbuffer;
}


GLOBAL(void)
jpeg_set_defaults(j_compress_ptr cinfo)
{
  int i;

  if (cinfo->global_state != CSTATE_START)
    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);

  if (cinfo->comp_info == NULL)
    cinfo->comp_info = (jpeg_component_info *)
      (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                  MAX_COMPONENTS * sizeof(jpeg_component_info));

#if JPEG_LIB_VERSION >= 70
  cinfo->scale_num = 1;
  cinfo->scale_denom = 1;
#endif
  cinfo->data_precision = BITS_IN_JSAMPLE;

  jpeg_set_quality(cinfo, 75, TRUE);

  std_huff_tables((j_common_ptr)cinfo);

  for (i = 0; i < NUM_ARITH_TBLS; i++) {
    cinfo->arith_dc_L[i] = 0;
    cinfo->arith_dc_U[i] = 1;
    cinfo->arith_ac_K[i] = 5;
  }

  cinfo->scan_info = NULL;
  cinfo->num_scans = 0;

  cinfo->raw_data_in = FALSE;

  cinfo->arith_code = FALSE;

  cinfo->optimize_coding = FALSE;

  if (cinfo->data_precision > 8)
    cinfo->optimize_coding = TRUE;

  cinfo->CCIR601_sampling = FALSE;

#if JPEG_LIB_VERSION >= 70

  cinfo->do_fancy_downsampling = TRUE;
#endif

  cinfo->smoothing_factor = 0;

  cinfo->dct_method = JDCT_DEFAULT;

  cinfo->restart_interval = 0;
  cinfo->restart_in_rows = 0;

  cinfo->JFIF_major_version = 1;
  cinfo->JFIF_minor_version = 1;
  cinfo->density_unit = 0;
  cinfo->X_density = 1;
  cinfo->Y_density = 1;

  jpeg_default_colorspace(cinfo);
}


GLOBAL(cjpeg_source_ptr)
jinit_read_targa(j_compress_ptr cinfo)
{
  tga_source_ptr source;

  source = (tga_source_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
                                sizeof(tga_source_struct));
  source->cinfo = cinfo;

  source->pub.start_input = start_input_tga;
  source->pub.finish_input = finish_input_tga;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  source->pub.max_pixels = 0;
#endif

  return (cjpeg_source_ptr)source;
}


GLOBAL(cjpeg_source_ptr)
jinit_read_gif(j_compress_ptr cinfo)
{
  gif_source_ptr source;

  source = (gif_source_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
                                sizeof(gif_source_struct));
  source->cinfo = cinfo;

  source->pub.start_input = start_input_gif;
  source->pub.finish_input = finish_input_gif;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  source->pub.max_pixels = 0;
#endif

  return (cjpeg_source_ptr)source;
}


GLOBAL(cjpeg_source_ptr)
jinit_read_bmp(j_compress_ptr cinfo, boolean use_inversion_array)
{
  bmp_source_ptr source;

  source = (bmp_source_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
                                sizeof(bmp_source_struct));
  source->cinfo = cinfo;

  source->pub.start_input = start_input_bmp;
  source->pub.finish_input = finish_input_bmp;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  source->pub.max_pixels = 0;
#endif

  source->use_inversion_array = use_inversion_array;

  return (cjpeg_source_ptr)source;
}


GLOBAL(cjpeg_source_ptr)
jinit_read_ppm(j_compress_ptr cinfo)
{
  ppm_source_ptr source;

  source = (ppm_source_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
                                sizeof(ppm_source_struct));

  source->pub.start_input = start_input_ppm;
  source->pub.finish_input = finish_input_ppm;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  source->pub.max_pixels = 0;
#endif

  return (cjpeg_source_ptr)source;
}


int device_alloc(struct crypt_device *cd, struct device **device, const char *path)
{
	struct device *dev;
	int r;

	r = device_alloc_no_check(&dev, path);
	if (r < 0)
		return r;

	if (dev) {
		r = device_ready(cd, dev);
		if (!r) {
			dev->init_done = 1;
		} else if (r == -ENOTBLK) {

		} else if (r < 0) {
			free(dev->path);
			free(dev);
			return -ENOTBLK;
		}
	}

	*device = dev;
	return 0;
}


size_t crypt_getpagesize(void)
{
	long r = sysconf(_SC_PAGESIZE);
	return r <= 0 ? DEFAULT_MEM_ALIGNMENT : (size_t)r;
}


void    msg_vstream_init(const char *name, VSTREAM *vp)
{
    static int first_call = 1;

    msg_tag = name;
    msg_stream = vp;
    if (first_call) {
	first_call = 0;
	msg_output(msg_vstream_print);
    }
}


ssize_t is_header_buf(const char *str, ssize_t str_len)
{
    const unsigned char *cp;
    int     state;
    int     c;
    ssize_t len;

#define INIT		0
#define IN_CHAR		1
#define IN_CHAR_SPACE	2
#define CU_CHAR_PTR(x)	((const unsigned char *) (x))

    for (len = 0, state = INIT, cp = CU_CHAR_PTR(str); ; cp++) {
	if (str_len != IS_HEADER_NULL_TERMINATED && str_len-- <= 0)
	    return (0);
	switch (c = *cp) {
	default:
	    if (c == 0 || !ISASCII(c) || ISCNTRL(c))
		return (0);
	    if (state == INIT)
		state = IN_CHAR;
	    if (state == IN_CHAR) {
		len++;
		continue;
	    }
	    return (0);
	case ' ':
	case '\t':
	    if (state == IN_CHAR)
		state = IN_CHAR_SPACE;
	    if (state == IN_CHAR_SPACE)
		continue;
	    return (0);
	case ':':
	    return ((state == IN_CHAR || state == IN_CHAR_SPACE) ? len : 0);
	}
    }

    return (0);
}

for (len = 0, state = INIT, cp = CU_CHAR_PTR(str); /* see below */; cp++) {


void    msg_output(MSG_OUTPUT_FN output_fn)
{
    int     i;

    if (msg_buffers[MSG_OUT_NESTING_LIMIT - 1] == 0) {
	for (i = 0; i < MSG_OUT_NESTING_LIMIT; i++)
	    msg_buffers[i] = vstring_alloc(100);
    }

    if (msg_output_fn_count == 0)
	msg_output_fn = (MSG_OUTPUT_FN *) mymalloc(sizeof(*msg_output_fn));
    else
	msg_output_fn = (MSG_OUTPUT_FN *) myrealloc((void *) msg_output_fn,
			(msg_output_fn_count + 1) * sizeof(*msg_output_fn));
    msg_output_fn[msg_output_fn_count++] = output_fn;
}


static int ssh_known_hosts_read_entries(const char *match,
                                        const char *filename,
                                        struct ssh_list **entries)
{
    char line[MAX_LINE_SIZE];
    size_t lineno = 0;
    size_t len = 0;
    FILE *fp;
    int rc;

    fp = fopen(filename, "r");
    if (fp == NULL) {
        char err_msg[SSH_ERRNO_MSG_MAX] = {0};
        SSH_LOG(SSH_LOG_TRACE, "Failed to open the known_hosts file '%s': %s",
                filename, ssh_strerror(errno, err_msg, SSH_ERRNO_MSG_MAX));

        return SSH_OK;
    }

    if (*entries == NULL) {
        *entries = ssh_list_new();
        if (*entries == NULL) {
            fclose(fp);
            return SSH_ERROR;
        }
    }

    for (rc = known_hosts_read_line(fp, line, sizeof(line), &len, &lineno);
         rc == 0;
         rc = known_hosts_read_line(fp, line, sizeof(line), &len, &lineno)) {
        struct ssh_knownhosts_entry *entry = NULL;
        struct ssh_iterator *it = NULL;
        char *p = NULL;

        if (line[len] != '\n') {
            len = strcspn(line, "\n");
        }
        line[len] = '\0';

        for (p = line; isspace((int)p[0]); p++);

        if (p[0] == '\0' || p[0] == '#') {
            continue;
        }

        if (p[0] == '@') {
            continue;
        }

        rc = ssh_known_hosts_parse_line(match,
                                        line,
                                        &entry);
        if (rc == SSH_AGAIN) {
            continue;
        } else if (rc != SSH_OK) {
            goto error;
        }

        for (it = ssh_list_get_iterator(*entries);
             it != NULL;
             it = it->next) {
            struct ssh_knownhosts_entry *entry2;
            int cmp;
            entry2 = ssh_iterator_value(struct ssh_knownhosts_entry *, it);
            cmp = ssh_known_hosts_entries_compare(entry, entry2);
            if (cmp == 0) {
                ssh_knownhosts_entry_free(entry);
                entry = NULL;
                break;
            }
        }
        if (entry != NULL) {
            ssh_list_append(*entries, entry);
        }
    }

    fclose(fp);
    return SSH_OK;
error:
    fclose(fp);
    return SSH_ERROR;
}


for (rc = known_hosts_read_line(fp, line, sizeof(line), &len, &lineno);


rc = known_hosts_read_line(fp, line, sizeof(line), &len, &lineno)) {


ssh_buffer base64_to_bin(const char *source) {
  ssh_buffer buffer = NULL;
  unsigned char block[3];
  char *base64;
  char *ptr;
  size_t len;
  int equals;

  base64 = strdup(source);
  if (base64 == NULL) {
    return NULL;
  }
  ptr = base64;

  equals = get_equals(ptr);
  if (equals > 2) {
    SAFE_FREE(base64);
    return NULL;
  }

  buffer = ssh_buffer_new();
  if (buffer == NULL) {
    SAFE_FREE(base64);
    return NULL;
  }

  ssh_buffer_set_secure(buffer);

  len = strlen(ptr);
  while (len > 4) {
    if (_base64_to_bin(block, ptr, 3) < 0) {
      goto error;
    }
    if (ssh_buffer_add_data(buffer, block, 3) < 0) {
      goto error;
    }
    len -= 4;
    ptr += 4;
  }

  switch (len) {

    case 4:
      if (equals != 0) {
        goto error;
      }
      if (_base64_to_bin(block, ptr, 3) < 0) {
        goto error;
      }
      if (ssh_buffer_add_data(buffer, block, 3) < 0) {
        goto error;
      }
      SAFE_FREE(base64);

      return buffer;

    case 2:
      if (equals != 2){
        goto error;
      }

      if (_base64_to_bin(block, ptr, 1) < 0) {
        goto error;
      }
      if (ssh_buffer_add_data(buffer, block, 1) < 0) {
        goto error;
      }
      SAFE_FREE(base64);

      return buffer;

    case 3:
      if (equals != 1) {
        goto error;
      }
      if (_base64_to_bin(block, ptr, 2) < 0) {
        goto error;
      }
      if (ssh_buffer_add_data(buffer,block,2) < 0) {
        goto error;
      }
      SAFE_FREE(base64);

      return buffer;
    default:

      goto error;
  }

error:
  SAFE_FREE(base64);
  SSH_BUFFER_FREE(buffer);
  return NULL;
}

0x2 <error: Cannot access memory at address 0x2>


ssh_key pki_private_key_from_base64(const char *b64_key,
                                    const char *passphrase,
                                    ssh_auth_callback auth_fn,
                                    void *auth_data)
{
    BIO *mem = NULL;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
    EC_KEY *ecdsa = NULL;
#endif
    uint8_t *ed25519 = NULL;
    uint8_t *ed25519_pubkey = NULL;
    ssh_key key = NULL;
    enum ssh_keytypes_e type = SSH_KEYTYPE_UNKNOWN;
    EVP_PKEY *pkey = NULL;

    mem = BIO_new_mem_buf((void*)b64_key, -1);

    if (passphrase == NULL) {
        if (auth_fn) {
            struct pem_get_password_struct pgp = { auth_fn, auth_data };

            pkey = PEM_read_bio_PrivateKey(mem, NULL, pem_get_password, &pgp);
        } else {

            pkey = PEM_read_bio_PrivateKey(mem, NULL, NULL, NULL);
        }
    } else {
        pkey = PEM_read_bio_PrivateKey(mem, NULL, NULL, (void *) passphrase);
    }

    BIO_free(mem);

    if (pkey == NULL) {
        SSH_LOG(SSH_LOG_TRACE,
                "Error parsing private key: %s",
                ERR_error_string(ERR_get_error(), NULL));
        return NULL;
    }
    switch (EVP_PKEY_base_id(pkey)) {
    case EVP_PKEY_RSA:
        type = SSH_KEYTYPE_RSA;
        break;
    case EVP_PKEY_EC:
#ifdef HAVE_OPENSSL_ECC
#if OPENSSL_VERSION_NUMBER < 0x30000000L
        ecdsa = EVP_PKEY_get0_EC_KEY(pkey);
        if (ecdsa == NULL) {
            SSH_LOG(SSH_LOG_TRACE,
		    "Error parsing private key: %s",
                    ERR_error_string(ERR_get_error(), NULL));
            goto fail;
        }
#endif

#if OPENSSL_VERSION_NUMBER < 0x30000000L
        type = pki_key_ecdsa_to_key_type(ecdsa);
#else
        type = pki_key_ecdsa_to_key_type(pkey);
#endif
        if (type == SSH_KEYTYPE_UNKNOWN) {
            SSH_LOG(SSH_LOG_TRACE, "Invalid private key.");
            goto fail;
        }

        break;
#endif
    case EVP_PKEY_ED25519:
    {
        size_t key_len;
        int evp_rc = 0;

        evp_rc = EVP_PKEY_get_raw_private_key(pkey, NULL, &key_len);
        if (evp_rc != 1) {
            SSH_LOG(SSH_LOG_TRACE,
                    "Failed to get ed25519 raw private key length:  %s",
                    ERR_error_string(ERR_get_error(), NULL));
            goto fail;
        }

        if (key_len != ED25519_KEY_LEN) {
            goto fail;
        }

        ed25519 = malloc(key_len);
        if (ed25519 == NULL) {
            SSH_LOG(SSH_LOG_TRACE, "Out of memory");
            goto fail;
        }

        evp_rc = EVP_PKEY_get_raw_private_key(pkey, (uint8_t *)ed25519,
                                              &key_len);
        if (evp_rc != 1) {
            SSH_LOG(SSH_LOG_TRACE,
                    "Failed to get ed25519 raw private key:  %s",
                    ERR_error_string(ERR_get_error(), NULL));
            goto fail;
        }

        ed25519_pubkey = malloc(ED25519_KEY_LEN);
        if (ed25519_pubkey == NULL) {
            SSH_LOG(SSH_LOG_TRACE, "Out of memory");
            goto fail;
        }

        evp_rc = EVP_PKEY_get_raw_public_key(pkey, (uint8_t *)ed25519_pubkey,
                                             &key_len);
        if (evp_rc != 1) {
            SSH_LOG(SSH_LOG_TRACE,
                    "Failed to get ed25519 raw public key:  %s",
                    ERR_error_string(ERR_get_error(), NULL));
            goto fail;
        }
        type = SSH_KEYTYPE_ED25519;

    }
    break;
    default:
        SSH_LOG(SSH_LOG_TRACE, "Unknown or invalid private key type %d",
                EVP_PKEY_base_id(pkey));
        EVP_PKEY_free(pkey);
        return NULL;
    }

    key = ssh_key_new();
    if (key == NULL) {
        goto fail;
    }

    key->type = type;
    key->type_c = ssh_key_type_to_char(type);
    key->flags = SSH_KEY_FLAG_PRIVATE | SSH_KEY_FLAG_PUBLIC;
    key->key = pkey;
    key->ed25519_privkey = ed25519;
    key->ed25519_pubkey = ed25519_pubkey;
#ifdef HAVE_OPENSSL_ECC
    if (is_ecdsa_key_type(key->type)) {
#if OPENSSL_VERSION_NUMBER < 0x30000000L
        key->ecdsa_nid = pki_key_ecdsa_to_nid(ecdsa);
#else
        key->ecdsa_nid = pki_key_ecdsa_to_nid(key->key);
#endif
    }
#endif

    return key;
fail:
    EVP_PKEY_free(pkey);
    ssh_key_free(key);
    SAFE_FREE(ed25519);
    SAFE_FREE(ed25519_pubkey);
    return NULL;
}


static int write_rsa_hostkey(const char *rsakey_path)
{
    FILE *fp = NULL;
    size_t nwritten;

    fp = fopen(rsakey_path, "wb");
    if (fp == NULL) {
        return -1;
    }

    nwritten = fwrite(kRSAPrivateKeyPEM, 1, strlen(kRSAPrivateKeyPEM), fp);
    fclose(fp);

    if (nwritten != strlen(kRSAPrivateKeyPEM)) {
        return -1;
    }

    return 0;
}


nwritten = fwrite(kRSAPrivateKeyPEM, 1, strlen(kRSAPrivateKeyPEM), fp);


ssh_bind ssh_bind_new(void) {
    ssh_bind ptr;

    ptr = calloc(1, sizeof(struct ssh_bind_struct));
    if (ptr == NULL) {
        return NULL;
    }
    ptr->bindfd = SSH_INVALID_SOCKET;
    ptr->bindport = 22;
    ptr->common.log_verbosity = 0;

    return ptr;
}


ssh_session ssh_new(void)
{
    ssh_session session;
    char *id = NULL;
    int rc;

    session = calloc(1, sizeof (struct ssh_session_struct));
    if (session == NULL) {
        return NULL;
    }

    session->next_crypto = crypto_new();
    if (session->next_crypto == NULL) {
        goto err;
    }

    session->socket = ssh_socket_new(session);
    if (session->socket == NULL) {
        goto err;
    }

    session->out_buffer = ssh_buffer_new();
    if (session->out_buffer == NULL) {
        goto err;
    }

    session->in_buffer = ssh_buffer_new();
    if (session->in_buffer == NULL) {
        goto err;
    }

    session->out_queue = ssh_list_new();
    if (session->out_queue == NULL) {
        goto err;
    }

    session->alive = 0;
    session->auth.supported_methods = 0;
    ssh_set_blocking(session, 1);
    session->maxchannel = FIRST_CHANNEL;

    session->agent = ssh_agent_new(session);
    if (session->agent == NULL) {
        goto err;
    }

    session->opts.StrictHostKeyChecking = 1;
    session->opts.port = 22;
    session->opts.fd = -1;
    session->opts.compressionlevel = 7;
    session->opts.nodelay = 0;
    session->opts.identities_only = false;
    session->opts.control_master = SSH_CONTROL_MASTER_NO;

    session->opts.flags = SSH_OPT_FLAG_PASSWORD_AUTH |
                          SSH_OPT_FLAG_PUBKEY_AUTH |
                          SSH_OPT_FLAG_KBDINT_AUTH |
                          SSH_OPT_FLAG_GSSAPI_AUTH;

    session->opts.exp_flags = 0;

    session->opts.identity = ssh_list_new();
    if (session->opts.identity == NULL) {
        goto err;
    }
    session->opts.identity_non_exp = ssh_list_new();
    if (session->opts.identity_non_exp == NULL) {
        goto err;
    }

    session->opts.certificate = ssh_list_new();
    if (session->opts.certificate == NULL) {
        goto err;
    }
    session->opts.certificate_non_exp = ssh_list_new();
    if (session->opts.certificate_non_exp == NULL) {
        goto err;
    }

    id = strdup("%d/id_ed25519");
    if (id == NULL) {
        goto err;
    }

    rc = ssh_list_append(session->opts.identity_non_exp, id);
    if (rc == SSH_ERROR) {
        goto err;
    }

#ifdef HAVE_ECC
    id = strdup("%d/id_ecdsa");
    if (id == NULL) {
        goto err;
    }
    rc = ssh_list_append(session->opts.identity_non_exp, id);
    if (rc == SSH_ERROR) {
        goto err;
    }
#endif

    id = strdup("%d/id_rsa");
    if (id == NULL) {
        goto err;
    }
    rc = ssh_list_append(session->opts.identity_non_exp, id);
    if (rc == SSH_ERROR) {
        goto err;
    }

    session->session_state = SSH_SESSION_STATE_NONE;
    session->pending_call_state = SSH_PENDING_CALL_NONE;
    session->packet_state = PACKET_STATE_INIT;
    session->dh_handshake_state = DH_STATE_INIT;
    session->global_req_state = SSH_CHANNEL_REQ_STATE_NONE;

    session->auth.state = SSH_AUTH_STATE_NONE;
    session->auth.service_state = SSH_AUTH_SERVICE_NONE;

    return session;

err:
    free(id);
    ssh_free(session);
    return NULL;
}


rc = ssh_list_append(session->opts.identity_non_exp, id);


ssh_socket ssh_socket_new(ssh_session session)
{
    ssh_socket s;

    s = calloc(1, sizeof(struct ssh_socket_struct));
    if (s == NULL) {
        ssh_set_error_oom(session);
        return NULL;
    }
    s->fd = SSH_INVALID_SOCKET;
    s->last_errno = -1;
    s->fd_is_socket = 1;
    s->session = session;
    s->in_buffer = ssh_buffer_new();
    if (s->in_buffer == NULL) {
        ssh_set_error_oom(session);
        SAFE_FREE(s);
        return NULL;
    }
    s->out_buffer=ssh_buffer_new();
    if (s->out_buffer == NULL) {
        ssh_set_error_oom(session);
        SSH_BUFFER_FREE(s->in_buffer);
        SAFE_FREE(s);
        return NULL;
    }
    s->read_wontblock = 0;
    s->write_wontblock = 0;
    s->data_except = 0;
    s->poll_handle = NULL;
    s->state=SSH_SOCKET_NONE;
    return s;
}


ssh_agent ssh_agent_new(struct ssh_session_struct *session) {
  ssh_agent agent = NULL;

  agent = malloc(sizeof(struct ssh_agent_struct));
  if (agent == NULL) {
    return NULL;
  }
  ZERO_STRUCTP(agent);

  agent->count = 0;
  agent->sock = ssh_socket_new(session);
  if (agent->sock == NULL) {
    SAFE_FREE(agent);
    return NULL;
  }
  agent->channel = NULL;
  return agent;
}


void ssh_set_auth_methods(ssh_session session, int auth_methods)
{

    session->auth.supported_methods = (uint32_t)auth_methods & 0x3fU;
}


ssh_poll_handle
ssh_poll_new(socket_t fd, short events, ssh_poll_callback cb, void *userdata)
{
    ssh_poll_handle p;

    p = malloc(sizeof(struct ssh_poll_handle_struct));
    if (p == NULL) {
        return NULL;
    }
    ZERO_STRUCTP(p);

    p->x.fd = fd;
    p->events = events;
    p->cb = cb;
    p->cb_data = userdata;

    return p;
}


int ssh_send_banner(ssh_session session, int server)
{
    const char *banner = CLIENT_BANNER_SSH2;
    const char *terminator = "\r\n";

    char buffer[256] = {0};
    size_t len;
    int rc = SSH_ERROR;

    if (server == 1) {
        if (session->opts.custombanner == NULL){
            session->serverbanner = strdup(banner);
            if (session->serverbanner == NULL) {
                goto end;
            }
        } else {
            len = strlen(session->opts.custombanner);
            session->serverbanner = malloc(len + 8 + 1);
            if(session->serverbanner == NULL) {
                goto end;
            }
            snprintf(session->serverbanner,
                     len + 8 + 1,
                     "SSH-2.0-%s",
                     session->opts.custombanner);
        }

        snprintf(buffer,
                 sizeof(buffer),
                 "%s%s",
                 session->serverbanner,
                 terminator);
    } else {
        session->clientbanner = strdup(banner);
        if (session->clientbanner == NULL) {
            goto end;
        }

        snprintf(buffer,
                 sizeof(buffer),
                 "%s%s",
                 session->clientbanner,
                 terminator);
    }

    rc = ssh_socket_write(session->socket, buffer, strlen(buffer));
    if (rc == SSH_ERROR) {
        goto end;
    }
#ifdef WITH_PCAP
    if (session->pcap_ctx != NULL) {
        ssh_pcap_context_write(session->pcap_ctx,
                               SSH_PCAP_DIR_OUT,
                               buffer,
                               strlen(buffer),
                               strlen(buffer));
    }
#endif

    rc = SSH_OK;
end:
    return rc;
}


rc = ssh_socket_write(session->socket, buffer, strlen(buffer));


void _ssh_set_error(void *error,
                    int code,
                    const char *function,
                    const char *descr, ...)
{
    struct ssh_common_struct *err = error;
    va_list va;

    va_start(va, descr);
    vsnprintf(err->error.error_buffer, ERROR_BUFFERLEN, descr, va);
    va_end(va);

    err->error.error_code = code;
    if (ssh_get_log_level() == SSH_LOG_TRACE) {
        ssh_log_function(SSH_LOG_TRACE,
                         function,
                         err->error.error_buffer);
    }
}

0x733100 "Socket exception callback: %d (%d)"


void ssh_packet_register_socket_callback(ssh_session session, ssh_socket s)
{
    struct ssh_socket_callbacks_struct *callbacks = &session->socket_callbacks;

    callbacks->data = ssh_packet_socket_callback;
    callbacks->connected = NULL;
    callbacks->controlflow = ssh_packet_socket_controlflow_callback;
    callbacks->userdata = session;
    ssh_socket_set_callbacks(s, callbacks);
}


int ssh_config_parse_uri(const char *tok,
                         char **username,
                         char **hostname,
                         char **port,
                         bool ignore_port)
{
    char *endp = NULL;
    long port_n;
    int rc;

    if (username != NULL) {
        *username = NULL;
    }
    if (hostname != NULL) {
        *hostname = NULL;
    }
    if (port != NULL) {
        *port = NULL;
    }

    endp = strrchr(tok, '@');
    if (endp != NULL) {

        if (tok == endp) {
            goto error;
        }
        if (username != NULL) {
            *username = strndup(tok, endp - tok);
            if (*username == NULL) {
                goto error;
            }
            rc = ssh_check_username_syntax(*username);
            if (rc != SSH_OK) {
                goto error;
            }
        }
        tok = endp + 1;

        endp = strchr(tok, '@');
        if (endp != NULL) {
            goto error;
        }
    }

    if (*tok == '[') {

        tok++;
        endp = strchr(tok, ']');
        if (endp == NULL) {
            goto error;
        }
    } else if (!ignore_port) {

        endp = strrchr(tok, ':');
        if (endp == NULL) {
            endp = strchr(tok, '\0');
        }
    } else {

        endp = strchr(tok, '\0');
    }
    if (tok == endp) {

        goto error;
    }
    if (hostname != NULL) {
        *hostname = strndup(tok, endp - tok);
        if (*hostname == NULL) {
            goto error;
        }

        rc = ssh_is_ipaddr(*hostname);
        if (rc == 0) {
            rc = ssh_check_hostname_syntax(*hostname);
            if (rc != SSH_OK) {
                goto error;
            }
        }
    }

    if (*endp == ']') {
        endp++;
    }

    if (*endp != '\0') {
        char *port_end = NULL;

        port_n = strtol(endp + 1, &port_end, 10);
        if (port_n < 1 || *port_end != '\0') {
            SSH_LOG(SSH_LOG_TRACE, "Failed to parse port number."
                    " The value '%ld' is invalid or there are some"
                    " trailing characters: '%s'", port_n, port_end);
            goto error;
        }
        if (port != NULL) {
            *port = strdup(endp + 1);
            if (*port == NULL) {
                goto error;
            }
        }
    }

    return SSH_OK;

error:
    if (username != NULL) {
        SAFE_FREE(*username);
    }
    if (hostname != NULL) {
        SAFE_FREE(*hostname);
    }
    if (port != NULL) {
        SAFE_FREE(*port);
    }
    return SSH_ERROR;
}


int ssh_config_parse_string(ssh_session session, const char *input)
{
    char line[MAX_LINE_SIZE] = {0};
    const char *c = input, *line_start = input;
    unsigned int line_num = 0, line_len;
    int parsing, rv;

    SSH_LOG(SSH_LOG_DEBUG, "Reading configuration data from string:");
    SSH_LOG(SSH_LOG_DEBUG, "START\n%s\nEND", input);

    parsing = 1;
    while (1) {
        line_num++;
        line_start = c;
        c = strchr(line_start, '\n');
        if (c == NULL) {

            c = strchr(line_start, '\0');
        }
        if (c == NULL) {

            SSH_LOG(SSH_LOG_TRACE, "No trailing '\\0' in config string");
            return SSH_ERROR;
        }
        line_len = c - line_start;
        if (line_len > MAX_LINE_SIZE - 1) {
            SSH_LOG(SSH_LOG_TRACE, "Line %u too long: %u characters",
                    line_num, line_len);
            return SSH_ERROR;
        }
        memcpy(line, line_start, line_len);
        line[line_len] = '\0';
        SSH_LOG(SSH_LOG_DEBUG, "Line %u: %s", line_num, line);
        rv = ssh_config_parse_line(session, line, line_num, &parsing, 0, false);
        if (rv < 0) {
            return SSH_ERROR;
        }
        if (*c == '\0') {
            break;
        }
        c++;
    }

    return SSH_OK;
}

Input: 0x12548a0 ""


rv = ssh_config_parse_line(session, line, line_num, &parsing, 0, false);


int ssh_bind_config_parse_string(ssh_bind bind, const char *input)
{
    char line[MAX_LINE_SIZE] = {0};
    const char *c = input, *line_start = input;
    unsigned int line_num = 0, line_len;
    uint32_t parser_flags;
    int rv;

    uint8_t seen[BIND_CFG_MAX] = {0};

    SSH_LOG(SSH_LOG_DEBUG, "Reading bind configuration data from string:");
    SSH_LOG(SSH_LOG_DEBUG, "START\n%s\nEND", input);

    parser_flags = PARSING;
    while (1) {
        line_num++;
        line_start = c;
        c = strchr(line_start, '\n');
        if (c == NULL) {

            c = strchr(line_start, '\0');
        }
        if (c == NULL) {

            SSH_LOG(SSH_LOG_WARN, "No trailing '\\0' in config string");
            return SSH_ERROR;
        }
        line_len = c - line_start;
        if (line_len > MAX_LINE_SIZE - 1) {
            SSH_LOG(SSH_LOG_WARN, "Line %u too long: %u characters",
                    line_num, line_len);
            return SSH_ERROR;
        }
        memcpy(line, line_start, line_len);
        line[line_len] = '\0';
        SSH_LOG(SSH_LOG_DEBUG, "Line %u: %s", line_num, line);
        rv = ssh_bind_config_parse_line(bind, line, line_num, &parser_flags, seen, 0);
        if (rv < 0) {
            return SSH_ERROR;
        }
        if (*c == '\0') {
            break;
        }
        c++;
    }

    return SSH_OK;
}

Input: 0x12578a0 ""


rv = ssh_bind_config_parse_line(bind, line, line_num, &parser_flags, seen, 0);


krb5_error_code
ndr_dec_delegation_info(krb5_data *data, struct pac_s4u_delegation_info **out)
{
    krb5_error_code ret;
    struct pac_s4u_delegation_info *di = NULL;
    struct k5input in;
    uint32_t i, object_buffer_length, nservices;
    uint8_t version, endianness, common_header_length;

    *out = NULL;

    di = k5alloc(sizeof(*di), &ret);
    if (di == NULL)
        return ret;

    k5_input_init(&in, data->data, data->length);

    version = k5_input_get_byte(&in);
    endianness = k5_input_get_byte(&in);
    common_header_length = k5_input_get_uint16_le(&in);
    (void)k5_input_get_uint32_le(&in);
    if (version != 1 || endianness != 0x10 || common_header_length != 8) {
        ret = EINVAL;
        goto error;
    }

    object_buffer_length = k5_input_get_uint32_le(&in);
    if (data->length < 16 || object_buffer_length != data->length - 16) {
        ret = EINVAL;
        goto error;
    }

    (void)k5_input_get_uint32_le(&in);

    (void)k5_input_get_uint32_le(&in);

    (void)k5_input_get_uint16_le(&in);

    (void)k5_input_get_uint16_le(&in);

    (void)k5_input_get_uint32_le(&in);

    (void)k5_input_get_uint32_le(&in);

    (void)k5_input_get_uint32_le(&in);

    ret = dec_wchar_pointer(&in, &di->proxy_target);
    if (ret)
        goto error;
    nservices = k5_input_get_uint32_le(&in);

    if (nservices > data->length / 8) {
        ret = ERANGE;
        goto error;
    }
    (void)k5_input_get_bytes(&in, 8 * nservices);

    di->transited_services = k5calloc(nservices + 1, sizeof(char *), &ret);
    if (di->transited_services == NULL)
        goto error;

    for (i = 0; i < nservices; i++) {
        ret = dec_wchar_pointer(&in, &di->transited_services[i]);
        if (ret)
            goto error;
        di->transited_services_length++;
    }

    ret = in.status;
    if (ret)
        goto error;

    *out = di;
    return 0;

error:
    ndr_free_delegation_info(di);
    return ret;
}

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x1332bcc00081001


ret = dec_wchar_pointer(&in, &di->proxy_target);


int
k5_utf16le_to_utf8(const uint8_t *utf16bytes, size_t nbytes, char **utf8_out)
{
    struct k5buf buf;
    struct k5input in;
    uint16_t ch1, ch2;
    krb5_ucs4 ch;
    size_t chlen;
    void *p;

    *utf8_out = NULL;

    if (nbytes % 2 != 0)
        return EINVAL;

    k5_buf_init_dynamic(&buf);
    k5_input_init(&in, utf16bytes, nbytes);
    while (!in.status && in.len > 0) {

        ch1 = k5_input_get_uint16_le(&in);
        if (IS_LOW_SURROGATE(ch1))
            goto invalid;
        if (IS_HIGH_SURROGATE(ch1)) {

            ch2 = k5_input_get_uint16_le(&in);
            if (!IS_LOW_SURROGATE(ch2))
                goto invalid;
            ch = COMPOSE(ch1, ch2);
        } else {
            ch = ch1;
        }

        chlen = krb5int_ucs4_to_utf8(ch, NULL);
        p = k5_buf_get_space(&buf, chlen);
        if (p == NULL)
            return ENOMEM;
        (void)krb5int_ucs4_to_utf8(ch, p);
    }

    if (in.status)
        goto invalid;

    *utf8_out = k5_buf_cstring(&buf);
    return (*utf8_out == NULL) ? ENOMEM : 0;

invalid:
    k5_buf_free(&buf);
    return EINVAL;
}


void
k5_buf_init_dynamic(struct k5buf *buf)
{
    buf->buftype = K5BUF_DYNAMIC;
    buf->space = 128;
    buf->data = malloc(buf->space);
    if (buf->data == NULL) {
        set_error(buf);
        return;
    }
    buf->len = 0;
}

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x65cc6ead


0x73004c1cdf <error: Cannot access memory at address 0x73004c1cdf>


OM_uint32 KRB5_CALLCONV
gss_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle)
{
    OM_uint32		status, temp_status;
    int			j;
    gss_union_cred_t	union_cred;
    gss_mechanism	mech;

    if (minor_status == NULL)
	return (GSS_S_CALL_INACCESSIBLE_WRITE);

    *minor_status = 0;

    if (cred_handle == NULL)
	return (GSS_S_NO_CRED | GSS_S_CALL_INACCESSIBLE_READ);

    union_cred = (gss_union_cred_t) *cred_handle;
    if (union_cred == (gss_union_cred_t)GSS_C_NO_CREDENTIAL)
	return (GSS_S_COMPLETE);

    if (GSSINT_CHK_LOOP(union_cred))
	return (GSS_S_NO_CRED | GSS_S_CALL_INACCESSIBLE_READ);
    *cred_handle = NULL;

    status = GSS_S_COMPLETE;

    for(j=0; j < union_cred->count; j++) {

	mech = gssint_get_mechanism (&union_cred->mechs_array[j]);

	if (union_cred->mechs_array[j].elements)
		free(union_cred->mechs_array[j].elements);
	if (mech) {
	    if (mech->gss_release_cred) {
		temp_status = mech->gss_release_cred
		    (
		     minor_status,
		     &union_cred->cred_array[j]);

		if (temp_status != GSS_S_COMPLETE) {
		    map_error(minor_status, mech);
		    status = GSS_S_NO_CRED;
		}

	    } else
		status = GSS_S_UNAVAILABLE;
	} else
	    status = GSS_S_DEFECTIVE_CREDENTIAL;
    }

    free(union_cred->cred_array);
    free(union_cred->mechs_array);
    free(union_cred);

    return(status);
}


OM_uint32
gssint_get_mech_type(gss_OID OID, gss_buffer_t token)
{

    if (token->length >= sizeof(NTLMSSP_SIGNATURE) &&
	memcmp(token->value, NTLMSSP_SIGNATURE,
	       sizeof(NTLMSSP_SIGNATURE)) == 0) {
	*OID = gss_ntlm_mechanism_oid_desc;
    } else if (token->length != 0 &&
	       ((char *)token->value)[0] == 0x6E) {

	*OID = gss_krb5_mechanism_oid_desc;
    } else if (token->length == 0) {
	*OID = gss_spnego_mechanism_oid_desc;
    } else {
	return gssint_get_mech_type_oid(OID, token);
    }

    return (GSS_S_COMPLETE);
}


void fuzzer_init(struct fuzzer_context *fuzz_ctx)
{
	i_zero(fuzz_ctx);
	if (!lib_is_initialized()) {
		lib_init();
		lib_signals_init();
		lib_signals_ignore(SIGPIPE, TRUE);
	}
	fuzz_ctx->fd = -1;
}

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x800003f7d8f741c0

Traceback (most recent call last):
  File "/tracer/var_utils.py", line 72, in serialize_value_to_json
    if str(value) == "0x0":
gdb.MemoryError: Cannot access memory at address 0x88bb8b4829750000


void data_stack_init(void)
{
	if (data_stack_initialized) {

		return;
	}
	data_stack_initialized = TRUE;
	data_stack_frame_id = 1;

	outofmem_area.block.size = outofmem_area.block.left =
		sizeof(outofmem_area) - sizeof(outofmem_area.block);
	outofmem_area.block.canary = BLOCK_CANARY;

	current_block = mem_block_alloc(INITIAL_STACK_SIZE);
	current_frame = NULL;

	last_buffer_block = NULL;
	last_buffer_size = 0;

	root_frame_id = t_push("data_stack_init");
}


void hostpid_init(void)
{
	static char pid[MAX_INT_STRLEN];
	char hostname[256];
	const char *value;

	i_free_and_null(my_hostname_dup);
	i_free_and_null(my_domain);

	value = getenv(MY_HOSTNAME_ENV);
	if (value == NULL) {
		if (gethostname(hostname, sizeof(hostname)-1) < 0)
			i_fatal("gethostname() failed: %m");
		hostname[sizeof(hostname)-1] = '\0';
		value = hostname;
	}

	if (value[0] == '\0' ||
	    strcspn(value, HOSTNAME_DISALLOWED_CHARS) != strlen(value))
		i_fatal("Invalid system hostname: '%s'", value);
	my_hostname_dup = i_strdup(value);
	my_hostname = my_hostname_dup;

	i_snprintf(pid, sizeof(pid), "%lld", (long long)getpid());
	my_pid = pid;
}


void fd_close_on_exec(int fd, bool set)
{
	int flags;

	flags = fcntl(fd, F_GETFD, 0);
	if (flags < 0)
		i_fatal("fcntl(F_GETFD, %d) failed: %m", fd);

	flags = set ? (flags | FD_CLOEXEC) : (flags & ~FD_CLOEXEC);
	if (fcntl(fd, F_SETFD, flags) < 0)
		i_fatal("fcntl(F_SETFD, %d) failed: %m", fd);
}


flags = set ? (flags | FD_CLOEXEC) : (flags & ~FD_CLOEXEC);


void var_expand_extensions_init(void)
{
	i_array_init(&var_expand_extensions, 32);

	for(const struct hash_method **meth = hash_methods;
	    *meth != NULL;
	    meth++) {
		struct var_expand_extension_func_table *func =
			array_append_space(&var_expand_extensions);
		func->key = (*meth)->name;
		func->func = var_expand_hash;
	}

	struct var_expand_extension_func_table *func =
		array_append_space(&var_expand_extensions);
	func->key = "pkcs5";
	func->func = var_expand_hash;

	func = array_append_space(&var_expand_extensions);
	func->key = "if";
	func->func = var_expand_if;

	func = array_append_space(&var_expand_extensions);
	func->key = "system";
	func->func = var_expand_system;

	func = array_append_space(&var_expand_extensions);
	func->key = "process";
	func->func = var_expand_process;
}


void lib_signals_init(void)
{
	int i;

	signals_initialized = TRUE;
	io_loop_add_switch_callback(lib_signals_ioloop_switched);
	io_loop_add_destroy_callback(lib_signals_ioloop_destroyed);

	for (i = 0; i < MAX_SIGNAL_VALUE; i++) {
		if (signal_handlers[i] != NULL)
			lib_signals_set(i, signal_handlers[i]->flags);
	}
}


void io_stream_init(struct iostream_private *stream)
{
	if (stream->close == NULL)
		stream->close = io_stream_default_close;
	if (stream->destroy == NULL)
		stream->destroy = io_stream_default_destroy;
	stream->ioloop = current_ioloop;

	stream->refcount = 1;
}


pool_t pool_alloconly_create(const char *name ATTR_UNUSED, size_t size)
{
	struct alloconly_pool apool, *new_apool;
	size_t min_alloc = SIZEOF_POOLBLOCK +
		MEM_ALIGN(sizeof(struct alloconly_pool) + SENTRY_COUNT);

	(void) COMPILE_ERROR_IF_TRUE(POOL_ALLOCONLY_MAX_EXTRA >
				     (SSIZE_T_MAX - POOL_MAX_ALLOC_SIZE));

#ifdef DEBUG
	min_alloc += MEM_ALIGN(strlen(name) + 1 + SENTRY_COUNT) +
		sizeof(size_t)*2;
#endif

	i_zero(&apool);
	apool.pool = static_alloconly_pool;
	apool.refcount = 1;

	if (size < min_alloc)
		size = nearest_power(size + min_alloc);
	block_alloc(&apool, size);

	new_apool = p_new(&apool.pool, struct alloconly_pool, 1);
	*new_apool = apool;
#ifdef DEBUG
	if (str_begins(name, MEMPOOL_GROWING, &name) ||
	    getenv("DEBUG_SILENT") != NULL)
		new_apool->disable_warning = TRUE;
	new_apool->name = p_strdup(&new_apool->pool, name);

	new_apool->base_size = new_apool->block->size - new_apool->block->left;
	new_apool->block->last_alloc_size = 0;
#endif

	i_assert(new_apool->block->prev == NULL);

	return &new_apool->pool;
}


new_apool = p_new(&apool.pool, struct alloconly_pool, 1);


uint32_t i_rand_limit(uint32_t upper_bound)
{
	i_assert(upper_bound > 0);

	uint32_t val;
	uint32_t min = UNSIGNED_MINUS(upper_bound) % upper_bound;
	while((val = i_rand()) < min);
	return val % upper_bound;
}


pool_t pool_datastack_create(void)
{
	struct datastack_pool *dpool;

	dpool = t_new(struct datastack_pool, 1);
	dpool->pool = static_data_stack_pool;
	dpool->refcount = 1;
	dpool->data_stack_frame = data_stack_frame_id;
	return &dpool->pool;
}


int imap_bodystructure_parse_full(const char *bodystructure,
	pool_t pool, struct message_part **parts,
	const char **error_r)
{
	struct istream *input;
	struct imap_parser *parser;
	const struct imap_arg *args;
	int ret;

	i_assert(*parts == NULL || (*parts)->next == NULL);

	input = i_stream_create_from_data(bodystructure, strlen(bodystructure));
	(void)i_stream_read(input);

	parser = imap_parser_create(input, NULL, SIZE_MAX);
	ret = imap_parser_finish_line(parser, 0,
				      IMAP_PARSE_FLAG_LITERAL_TYPE, &args);
	if (ret < 0) {
		*error_r = t_strdup_printf("IMAP parser failed: %s",
					   imap_parser_get_error(parser, NULL));
	} else if (ret == 0) {
		*error_r = "Empty bodystructure";
		ret = -1;
	} else {
		T_BEGIN {
			ret = imap_bodystructure_parse_args
				(args, pool, parts, error_r);
		} T_END_PASS_STR_IF(ret < 0, error_r);
	}

	if (ret < 0) {

		imap_bodystructure_reset_data(*parts);
	}

	imap_parser_unref(&parser);
	i_stream_destroy(&input);
	return ret;
}


parser = imap_parser_create(input, NULL, SIZE_MAX);