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);
}


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;
}


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;
}


static inline void
quota_init(struct quota *quota, size_t total)
{
	uint64_t new_total = (total + (QUOTA_UNIT_SIZE - 1)) /
				QUOTA_UNIT_SIZE;
	quota->value = new_total << 32;
}


void
mempool_create_with_order(struct mempool *pool, struct slab_cache *cache,
			  uint32_t objsize, uint8_t order)
{
	assert(order <= cache->order_max);
	pool->cache = cache;
	slab_list_create(&pool->slabs);
	mslab_tree_new(&pool->hot_slabs);
	pool->first_hot_slab = NULL;
	rlist_create(&pool->cold_slabs);
	pool->spare = NULL;
	pool->objsize = objsize;
	pool->slab_order = order;

	uint32_t slab_size = slab_order_size(pool->cache, pool->slab_order);

	pool->objcount = (slab_size - mslab_sizeof()) / objsize;
	assert(pool->objcount);
	pool->offset = slab_size - pool->objcount * pool->objsize;
	pool->slab_ptr_mask = ~(slab_order_size(cache, order) - 1);
	pool->small_mempool = NULL;
}


MemoryContext
AllocSetContextCreateInternal(MemoryContext parent,
							  const char *name,
							  Size minContextSize,
							  Size initBlockSize,
							  Size maxBlockSize)
{
	int			freeListIndex;
	Size		firstBlockSize;
	AllocSet	set;
	AllocBlock	block;

	StaticAssertDecl(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ),
					 "sizeof(MemoryChunk) is not maxaligned");

	StaticAssertDecl(sizeof(AllocFreeListLink) <= (1 << ALLOC_MINBITS),
					 "sizeof(AllocFreeListLink) larger than minimum allocation size");

	Assert(initBlockSize == MAXALIGN(initBlockSize) &&
		   initBlockSize >= 1024);
	Assert(maxBlockSize == MAXALIGN(maxBlockSize) &&
		   maxBlockSize >= initBlockSize &&
		   AllocHugeSizeIsValid(maxBlockSize));
	Assert(minContextSize == 0 ||
		   (minContextSize == MAXALIGN(minContextSize) &&
			minContextSize >= 1024 &&
			minContextSize <= maxBlockSize));
	Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET);

	if (minContextSize == ALLOCSET_DEFAULT_MINSIZE &&
		initBlockSize == ALLOCSET_DEFAULT_INITSIZE)
		freeListIndex = 0;
	else if (minContextSize == ALLOCSET_SMALL_MINSIZE &&
			 initBlockSize == ALLOCSET_SMALL_INITSIZE)
		freeListIndex = 1;
	else
		freeListIndex = -1;

	if (freeListIndex >= 0)
	{
		AllocSetFreeList *freelist = &context_freelists[freeListIndex];

		if (freelist->first_free != NULL)
		{

			set = freelist->first_free;
			freelist->first_free = (AllocSet) set->header.nextchild;
			freelist->num_free--;

			set->maxBlockSize = maxBlockSize;

			MemoryContextCreate((MemoryContext) set,
								T_AllocSetContext,
								MCTX_ASET_ID,
								parent,
								name);

			((MemoryContext) set)->mem_allocated =
				set->keeper->endptr - ((char *) set);

			return (MemoryContext) set;
		}
	}

	firstBlockSize = MAXALIGN(sizeof(AllocSetContext)) +
		ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ;
	if (minContextSize != 0)
		firstBlockSize = Max(firstBlockSize, minContextSize);
	else
		firstBlockSize = Max(firstBlockSize, initBlockSize);

	set = (AllocSet) malloc(firstBlockSize);
	if (set == NULL)
	{
		if (TopMemoryContext)
			MemoryContextStats(TopMemoryContext);
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of memory"),
				 errdetail("Failed while creating memory context \"%s\".",
						   name)));
	}

	block = (AllocBlock) (((char *) set) + MAXALIGN(sizeof(AllocSetContext)));
	block->aset = set;
	block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ;
	block->endptr = ((char *) set) + firstBlockSize;
	block->prev = NULL;
	block->next = NULL;

	VALGRIND_MAKE_MEM_NOACCESS(block->freeptr, block->endptr - block->freeptr);

	set->blocks = block;

	set->keeper = block;

	MemSetAligned(set->freelist, 0, sizeof(set->freelist));

	set->initBlockSize = initBlockSize;
	set->maxBlockSize = maxBlockSize;
	set->nextBlockSize = initBlockSize;
	set->freeListIndex = freeListIndex;

	StaticAssertStmt(ALLOC_CHUNK_LIMIT == ALLOCSET_SEPARATE_THRESHOLD,
					 "ALLOC_CHUNK_LIMIT != ALLOCSET_SEPARATE_THRESHOLD");

	set->allocChunkLimit = ALLOC_CHUNK_LIMIT;
	while ((Size) (set->allocChunkLimit + ALLOC_CHUNKHDRSZ) >
		   (Size) ((maxBlockSize - ALLOC_BLOCKHDRSZ) / ALLOC_CHUNK_FRACTION))
		set->allocChunkLimit >>= 1;

	MemoryContextCreate((MemoryContext) set,
						T_AllocSetContext,
						MCTX_ASET_ID,
						parent,
						name);

	((MemoryContext) set)->mem_allocated = firstBlockSize;

	return (MemoryContext) set;
}


int
pg_vsnprintf(char *str, size_t count, const char *fmt, va_list args)
{
	PrintfTarget target;
	char		onebyte[1];

	if (count == 0)
	{
		str = onebyte;
		count = 1;
	}
	target.bufstart = target.bufptr = str;
	target.bufend = str + count - 1;
	target.stream = NULL;
	target.nchars = 0;
	target.failed = false;
	dopr(&target, fmt, args);
	*(target.bufptr) = '\0';
	return target.failed ? -1 : (target.bufptr - target.bufstart
								 + target.nchars);
}


APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr,
                                              char **scope_id,
                                              apr_port_t *port,
                                              const char *str,
                                              apr_pool_t *p)
{
    const char *ch, *lastchar;
    int big_port;
    apr_size_t addrlen;

    *addr = NULL;
    *scope_id = NULL;
    *port = 0;

    ch = lastchar = str + strlen(str) - 1;
    while (ch >= str && apr_isdigit(*ch)) {
        --ch;
    }

    if (ch < str) {
        big_port = atoi(str);
        if (big_port < 1 || big_port > 65535) {
            return APR_EINVAL;
        }
        *port = big_port;
        return APR_SUCCESS;
    }

    if (*ch == ':' && ch < lastchar) {
        if (ch == str) {
            return APR_EINVAL;
        }
        big_port = atoi(ch + 1);
        if (big_port < 1 || big_port > 65535) {
            return APR_EINVAL;
        }
        *port = big_port;
        lastchar = ch - 1;
    }

    addrlen = lastchar - str + 1;

#if APR_HAVE_IPV6
    if (*str == '[') {
        const char *end_bracket = memchr(str, ']', addrlen);
        struct in6_addr ipaddr;
        const char *scope_delim;

        if (!end_bracket || end_bracket != lastchar) {
            *port = 0;
            return APR_EINVAL;
        }

        scope_delim = memchr(str, '%', addrlen);
        if (scope_delim) {
            if (scope_delim == end_bracket - 1) {
                *port = 0;
                return APR_EINVAL;
            }
            addrlen = scope_delim - str - 1;
            *scope_id = apr_pstrmemdup(p, scope_delim + 1, end_bracket - scope_delim - 1);
        }
        else {
            addrlen = addrlen - 2;
        }

        *addr = apr_pstrmemdup(p, str + 1, addrlen);
        if (apr_inet_pton(AF_INET6, *addr, &ipaddr) != 1) {
            *addr = NULL;
            *scope_id = NULL;
            *port = 0;
            return APR_EINVAL;
        }
    }
    else
#endif
    {

        *addr = apr_pstrmemdup(p, str, addrlen);
    }
    return APR_SUCCESS;
}


void
nxt_monotonic_time(nxt_monotonic_time_t *now)
{
    nxt_nsec_t      current;
    nxt_nsec_int_t  delta;
    struct timeval  tv;

    (void) gettimeofday(&tv, NULL);

    now->realtime.sec = (nxt_time_t) tv.tv_sec;
    now->realtime.nsec = tv.tv_usec * 1000;

    current = (nxt_nsec_t) tv.tv_sec * 1000000000 + tv.tv_usec * 1000;
    delta = current - now->previous;
    now->previous = current;

    if (delta > 0) {
        now->monotonic += delta;

    } else {

        now->monotonic++;
    }

    now->update = now->monotonic + 1;
}

now->monotonic = (nxt_nsec_t) ts.tv_sec * 1000000000 + ts.tv_nsec;


int
utf8_isvalid(const char *s)
{
	struct utf8_data ud;
	const char	*end;
	enum utf8_state	 more;

	end = s + strlen(s);
	while (s < end) {
		if ((more = utf8_open(&ud, *s)) == UTF8_MORE) {
			while (++s < end && more == UTF8_MORE)
				more = utf8_append(&ud, *s);
			if (more == UTF8_DONE)
				continue;
			return (0);
		}
		if (*s < 0x20 || *s > 0x7e)
			return (0);
		s++;
	}
	return (1);
}


extern int
onig_detect_can_be_slow_pattern(const UChar* pattern,
  const UChar* pattern_end, OnigOptionType option, OnigEncoding enc,
  OnigSyntaxType* syntax)
{
  int r;
  regex_t* reg;
  Node* root;
  ParseEnv scan_env;
  SlowElementCount count;
  int calls[MAX_CALLS_IN_DETECT];
#ifdef USE_CALL
  UnsetAddrList  uslist = {0};
#endif

  reg = (regex_t* )xmalloc(sizeof(regex_t));
  if (IS_NULL(reg)) return ONIGERR_MEMORY;

  r = onig_reg_init(reg, option, ONIGENC_CASE_FOLD_DEFAULT, enc, syntax);
  if (r != 0) {
    xfree(reg);
    return r;
  }

  r = parse_and_tune(reg, pattern, pattern_end, &scan_env, &root, NULL
#ifdef USE_CALL
                     , &uslist
#endif
                    );
  if (r != 0) goto err;

#ifdef USE_CALL
  if (scan_env.num_call > 0) {
    unset_addr_list_end(&uslist);
  }
#endif

  count.prec_read          = 0;
  count.look_behind        = 0;
  count.backref            = 0;
  count.backref_with_level = 0;
  count.call               = 0;
  count.is_keep            = FALSE;
  count.anychar_reluctant_many     = 0;
  count.empty_check_nest_level     = 0;
  count.max_empty_check_nest_level = 0;
  count.heavy_element = 0;

  r = detect_can_be_slow(root, &count, 0, calls);
  if (r == 0) {
    int n;

    n = count.prec_read + count.look_behind
      + count.backref + count.backref_with_level + count.call
      + count.anychar_reluctant_many;

    if (count.is_keep) count.max_empty_check_nest_level++;

    if (count.max_empty_check_nest_level > 2)
      n += count.max_empty_check_nest_level - 2;
    if (count.heavy_element != 0) {
      if (count.heavy_element < 0x10000)
        n += count.heavy_element << 8;
      else
        n += count.heavy_element;
    }

    r = n;

#ifdef ONIG_DEBUG_PARSE
    fprintf(DBGFP, "-- detect can be slow --\n");
    fprintf(DBGFP, "  prec_read:          %d\n", count.prec_read);
    fprintf(DBGFP, "  look_behind:        %d\n", count.look_behind);
    fprintf(DBGFP, "  backref:            %d\n", count.backref);
    fprintf(DBGFP, "  backref_with_level: %d\n", count.backref_with_level);
    fprintf(DBGFP, "  call:               %d\n", count.call);
    fprintf(DBGFP, "  is_keep:            %d\n", count.is_keep);
    fprintf(DBGFP, "  any_reluctant_many: %d\n", count.anychar_reluctant_many);
    fprintf(DBGFP, "  max_empty_check_nest_level: %d\n", count.max_empty_check_nest_level);
    fprintf(DBGFP, "  heavy_element:      %d\n", count.heavy_element);
    fprintf(DBGFP, "  r:                  %d\n", r);
    fprintf(DBGFP, "\n");
#endif
  }

  if (IS_NOT_NULL(scan_env.mem_env_dynamic))
    xfree(scan_env.mem_env_dynamic);

 err:
  onig_node_free(root);
  onig_free(reg);
  return r;
}


static int
init(void)
{
#ifdef USE_CALLOUT

    int id;
    OnigEncoding enc;
    char* name;
    unsigned int args[4];
    OnigValue    opts[4];

    enc = ONIG_ENCODING_ASCII;

    name = "FAIL";        BC0_P(name, fail);
    name = "MISMATCH";    BC0_P(name, mismatch);

    name = "MAX";
    args[0] = ONIG_TYPE_TAG | ONIG_TYPE_LONG;
    args[1] = ONIG_TYPE_CHAR;
    opts[0].c = 'X';
    BC_B_O(name, max, 2, args, 1, opts);

    name = "ERROR";
    args[0] = ONIG_TYPE_LONG; opts[0].l = ONIG_ABORT;
    BC_P_O(name, error, 1, args, 1, opts);

    name = "COUNT";
    args[0] = ONIG_TYPE_CHAR; opts[0].c = '>';
    BC_B_O(name, count, 1, args, 1, opts);

    name = "TOTAL_COUNT";
    args[0] = ONIG_TYPE_CHAR; opts[0].c = '>';
    BC_B_O(name, total_count, 1, args, 1, opts);

    name = "CMP";
    args[0] = ONIG_TYPE_TAG | ONIG_TYPE_LONG;
    args[1] = ONIG_TYPE_STRING;
    args[2] = ONIG_TYPE_TAG | ONIG_TYPE_LONG;
    BC_P(name, cmp, 3, args);

#endif

  return ONIG_NORMAL;
}


extern int
onig_set_callout_of_name(OnigEncoding enc, OnigCalloutType callout_type,
                         UChar* name, UChar* name_end, int in,
                         OnigCalloutFunc start_func,
                         OnigCalloutFunc end_func,
                         int arg_num, unsigned int arg_types[],
                         int opt_arg_num, OnigValue opt_defaults[])
{
  int r;
  int i;
  int j;
  int id;
  int is_not_single;
  CalloutNameEntry* e;
  CalloutNameListEntry* fe;

  if (callout_type != ONIG_CALLOUT_TYPE_SINGLE)
    return ONIGERR_INVALID_ARGUMENT;

  if (arg_num < 0 || arg_num > ONIG_CALLOUT_MAX_ARGS_NUM)
    return ONIGERR_INVALID_CALLOUT_ARG;

  if (opt_arg_num < 0 || opt_arg_num > arg_num)
    return ONIGERR_INVALID_CALLOUT_ARG;

  if (start_func == 0 && end_func == 0)
    return ONIGERR_INVALID_CALLOUT_ARG;

  if ((in & ONIG_CALLOUT_IN_PROGRESS) == 0 && (in & ONIG_CALLOUT_IN_RETRACTION) == 0)
    return ONIGERR_INVALID_CALLOUT_ARG;

  for (i = 0; i < arg_num; i++) {
    unsigned int t = arg_types[i];
    if (t == ONIG_TYPE_VOID)
      return ONIGERR_INVALID_CALLOUT_ARG;
    else {
      if (i >= arg_num - opt_arg_num) {
        if (t != ONIG_TYPE_LONG && t != ONIG_TYPE_CHAR && t != ONIG_TYPE_STRING &&
            t != ONIG_TYPE_TAG)
          return ONIGERR_INVALID_CALLOUT_ARG;
      }
      else {
        if (t != ONIG_TYPE_LONG) {
          t = t & ~ONIG_TYPE_LONG;
          if (t != ONIG_TYPE_CHAR && t != ONIG_TYPE_STRING && t != ONIG_TYPE_TAG)
            return ONIGERR_INVALID_CALLOUT_ARG;
        }
      }
    }
  }

  if (! is_allowed_callout_name(enc, name, name_end)) {
    return ONIGERR_INVALID_CALLOUT_NAME;
  }

  is_not_single = (callout_type != ONIG_CALLOUT_TYPE_SINGLE);
  id = callout_name_entry(&e, enc, is_not_single, name, name_end);
  if (id < 0) return id;

  r = ONIG_NORMAL;
  if (IS_NULL(GlobalCalloutNameList)) {
    r = make_callout_func_list(&GlobalCalloutNameList, 10);
    if (r != ONIG_NORMAL) return r;
  }

  while (id >= GlobalCalloutNameList->n) {
    int rid;
    r = callout_func_list_add(GlobalCalloutNameList, &rid);
    if (r != ONIG_NORMAL) return r;
  }

  fe = GlobalCalloutNameList->v + id;
  fe->type         = callout_type;
  fe->in           = in;
  fe->start_func   = start_func;
  fe->end_func     = end_func;
  fe->arg_num      = arg_num;
  fe->opt_arg_num  = opt_arg_num;
  fe->name         = e->name;

  for (i = 0; i < arg_num; i++) {
    fe->arg_types[i] = arg_types[i];
  }
  for (i = arg_num - opt_arg_num, j = 0; i < arg_num; i++, j++) {
    if (IS_NULL(opt_defaults)) return ONIGERR_INVALID_ARGUMENT;
    if (fe->arg_types[i] == ONIG_TYPE_STRING) {
      OnigValue* val;
      UChar* ds;

      val = opt_defaults + j;
      ds = onigenc_strdup(enc, val->s.start, val->s.end);
      CHECK_NULL_RETURN_MEMERR(ds);

      fe->opt_defaults[i].s.start = ds;
      fe->opt_defaults[i].s.end   = ds + (val->s.end - val->s.start);
    }
    else {
      fe->opt_defaults[i] = opt_defaults[j];
    }
  }

  r = id;
  return r;
}


int parse_msg(
		char *const buf, const unsigned int len, struct sip_msg *const msg)
{

	char *tmp;
	char *rest;
	struct msg_start *fl;
	int offset;
	hdr_flags_t flags;

	for(tmp = buf; (tmp - buf < len)
				   && (*tmp == '\n' || *tmp == '\r' || *tmp == '\0'
						   || *tmp == '\t' || *tmp == ' ');
			tmp++)
		;
	offset = tmp - buf;
	fl = &(msg->first_line);
	rest = parse_first_line(tmp, len - offset, fl);
	offset += rest - tmp;
	tmp = rest;
	switch(fl->type) {
		case SIP_INVALID:
			DBG("invalid message\n");
			goto error;
			break;
		case SIP_REQUEST:
			DBG("SIP Request:\n");
			DBG(" method:  <%.*s>\n", fl->u.request.method.len,
					ZSW(fl->u.request.method.s));
			DBG(" uri:     <%.*s>\n", fl->u.request.uri.len,
					ZSW(fl->u.request.uri.s));
			DBG(" version: <%.*s>\n", fl->u.request.version.len,
					ZSW(fl->u.request.version.s));
			flags = HDR_VIA_F;
			break;
		case SIP_REPLY:
			DBG("SIP Reply  (status):\n");
			DBG(" version: <%.*s>\n", fl->u.reply.version.len,
					ZSW(fl->u.reply.version.s));
			DBG(" status:  <%.*s>\n", fl->u.reply.status.len,
					ZSW(fl->u.reply.status.s));
			DBG(" reason:  <%.*s>\n", fl->u.reply.reason.len,
					ZSW(fl->u.reply.reason.s));

			flags = HDR_VIA_F;
			break;
		default:
			DBG("unknown type %d\n", fl->type);
			goto error;
	}
	msg->unparsed = tmp;

	if(parse_headers(msg, flags, 0) == -1)
		goto error;

#ifdef EXTRA_DEBUG

	if(msg->via1) {
		DBG("first via: <%.*s/%.*s/%.*s> <%.*s:%.*s(%d)>", msg->via1->name.len,
				ZSW(msg->via1->name.s), msg->via1->version.len,
				ZSW(msg->via1->version.s), msg->via1->transport.len,
				ZSW(msg->via1->transport.s), msg->via1->host.len,
				ZSW(msg->via1->host.s), msg->via1->port_str.len,
				ZSW(msg->via1->port_str.s), msg->via1->port);
		if(msg->via1->params.s)
			DBG(";<%.*s>", msg->via1->params.len, ZSW(msg->via1->params.s));
		if(msg->via1->comment.s)
			DBG(" <%.*s>", msg->via1->comment.len, ZSW(msg->via1->comment.s));
		DBG("\n");
	}
	if(msg->via2) {
		DBG("second via: <%.*s/%.*s/%.*s> <%.*s:%.*s(%d)>", msg->via2->name.len,
				ZSW(msg->via2->name.s), msg->via2->version.len,
				ZSW(msg->via2->version.s), msg->via2->transport.len,
				ZSW(msg->via2->transport.s), msg->via2->host.len,
				ZSW(msg->via2->host.s), msg->via2->port_str.len,
				ZSW(msg->via2->port_str.s), msg->via2->port);
		if(msg->via2->params.s)
			DBG(";<%.*s>", msg->via2->params.len, ZSW(msg->via2->params.s));
		if(msg->via2->comment.s)
			DBG(" <%.*s>", msg->via2->comment.len, ZSW(msg->via2->comment.s));
		DBG("\n");
	}
#endif

#ifdef EXTRA_DEBUG
	DBG("exiting parse_msg\n");
#endif

	return 0;

error:

	LOG(cfg_get(core, core_cfg, sip_parser_log),
			"ERROR: parse_msg: message=<%.*s>\n", (int)msg->len,
			ZSW(ksr_buf_oneline(msg->buf, (int)msg->len)));
	return -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 0xffff00001f80


int libesedb_checksum_calculate_little_endian_xor32(
     uint32_t *checksum_value,
     const uint8_t *buffer,
     size_t size,
     uint32_t initial_value,
     libcerror_error_t **error )
{
	libesedb_aligned_t *aligned_buffer_iterator = NULL;
	uint8_t *buffer_iterator                    = NULL;
	static char *function                       = "libesedb_checksum_calculate_little_endian_xor32";
	libesedb_aligned_t value_aligned            = 0;
	uint32_t big_endian_value_32bit             = 0;
	uint32_t safe_checksum_value                = 0;
	uint32_t value_32bit                        = 0;
	uint8_t alignment_count                     = 0;
	uint8_t alignment_size                      = 0;
	uint8_t byte_count                          = 0;
	uint8_t byte_order                          = 0;
	uint8_t byte_size                           = 0;

	if( checksum_value == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid checksum value.",
		 function );

		return( -1 );
	}
	if( buffer == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid buffer.",
		 function );

		return( -1 );
	}
	if( size > (size_t) SSIZE_MAX )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
		 "%s: invalid size value exceeds maximum.",
		 function );

		return( -1 );
	}
	safe_checksum_value = initial_value;

	buffer_iterator = (uint8_t *) buffer;

	if( ( ( sizeof( libesedb_aligned_t ) % 4 ) == 0 )
	 && ( size > ( 2 * sizeof( libesedb_aligned_t ) ) ) )
	{

		alignment_size = (uint8_t) ( (intptr_t) buffer_iterator % sizeof( libesedb_aligned_t ) );

		if( alignment_size > 0 )
		{
			byte_size = sizeof( libesedb_aligned_t ) - alignment_size;

			while( byte_size != 0 )
			{
				value_32bit = 0;
				byte_count  = 1;

				if( byte_size >= 4 )
				{
					value_32bit |= buffer_iterator[ 3 ];
					value_32bit <<= 8;

					byte_count++;
				}
				if( byte_size >= 3 )
				{
					value_32bit |= buffer_iterator[ 2 ];
					value_32bit <<= 8;

					byte_count++;
				}
				if( byte_size >= 2 )
				{
					value_32bit |= buffer_iterator[ 1 ];
					value_32bit <<= 8;

					byte_count++;
				}
				value_32bit |= buffer_iterator[ 0 ];

				buffer_iterator += byte_count;
				byte_size       -= byte_count;

				safe_checksum_value ^= value_32bit;
			}
			size -= byte_count;
		}
		aligned_buffer_iterator = (libesedb_aligned_t *) buffer_iterator;

		if( *buffer_iterator != (uint8_t) ( *aligned_buffer_iterator & 0xff ) )
		{
			byte_order = _BYTE_STREAM_ENDIAN_BIG;
		}
		else
		{
			byte_order = _BYTE_STREAM_ENDIAN_LITTLE;
		}

		while( size > sizeof( libesedb_aligned_t ) )
		{
			value_aligned ^= *aligned_buffer_iterator;

			aligned_buffer_iterator++;

			size -= sizeof( libesedb_aligned_t );
		}

		if( alignment_size > 0 )
		{
			byte_count      = ( alignment_size % 4 ) * 8;
			alignment_count = ( sizeof( libesedb_aligned_t ) - alignment_size ) * 8;

			if( byte_order == _BYTE_STREAM_ENDIAN_BIG )
			{

				big_endian_value_32bit = (uint32_t) ( ( value_aligned >> alignment_count ) << byte_count );

				value_32bit = ( ( big_endian_value_32bit & 0x000000ffUL ) << 24 )
				            | ( ( big_endian_value_32bit & 0x0000ff00UL ) << 8 )
				            | ( ( big_endian_value_32bit >> 8 ) & 0x0000ff00UL )
				            | ( ( big_endian_value_32bit >> 24 ) & 0x000000ffUL );

				value_aligned <<= alignment_count;
			}
			else if( byte_order == _BYTE_STREAM_ENDIAN_LITTLE )
			{
				value_32bit = (uint32_t) ( value_aligned << byte_count );

				value_aligned >>= alignment_count;
			}
			safe_checksum_value ^= value_32bit;
		}

		byte_size = (uint8_t) sizeof( libesedb_aligned_t );

		while( byte_size != 0 )
		{
			byte_count = ( ( byte_size / 4 ) - 1 ) * 32;

			if( byte_order == _BYTE_STREAM_ENDIAN_BIG )
			{
				big_endian_value_32bit = (uint32_t) ( ( value_aligned >> byte_count ) & 0xffffffffUL );

				value_32bit = ( ( big_endian_value_32bit & 0x000000ffUL ) << 24 )
				            | ( ( big_endian_value_32bit & 0x0000ff00UL ) << 8 )
				            | ( ( big_endian_value_32bit >> 8 ) & 0x0000ff00UL )
				            | ( ( big_endian_value_32bit >> 24 ) & 0x000000ffUL );
			}
			else if( byte_order == _BYTE_STREAM_ENDIAN_LITTLE )
			{
				value_32bit = (uint32_t) value_aligned;

				value_aligned >>= byte_count;
			}
			byte_size -= 4;

			safe_checksum_value ^= value_32bit;
		}

		buffer_iterator = (uint8_t *) aligned_buffer_iterator;

		byte_size = 4 - ( alignment_size % 4 );

		if( byte_size != 4 )
		{
			value_32bit   = buffer_iterator[ 0 ];
			value_32bit <<= 8;

			if( byte_size >= 2 )
			{
				value_32bit |= buffer_iterator[ 1 ];
			}
			value_32bit <<= 8;

			if( byte_size >= 3 )
			{
				value_32bit |= buffer_iterator[ 2 ];
			}
			value_32bit <<= 8;

			buffer_iterator += byte_size;
			size            -= byte_size;

			safe_checksum_value ^= value_32bit;
		}
	}
	while( size > 0 )
	{
		value_32bit = 0;
		byte_count  = 1;

		if( size >= 4 )
		{
			value_32bit |= buffer_iterator[ 3 ];
			value_32bit <<= 8;

			byte_count++;
		}
		if( size >= 3 )
		{
			value_32bit |= buffer_iterator[ 2 ];
			value_32bit <<= 8;

			byte_count++;
		}
		if( size >= 2 )
		{
			value_32bit |= buffer_iterator[ 1 ];
			value_32bit <<= 8;

			byte_count++;
		}
		value_32bit |= buffer_iterator[ 0 ];

		buffer_iterator += byte_count;
		size            -= byte_count;

		safe_checksum_value ^= value_32bit;
	}
	*checksum_value = safe_checksum_value;

	return( 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 0x29c

Cannot access memory at address 0x29c


int libfsfat_block_tree_node_initialize(
     libfsfat_block_tree_node_t **block_tree_node,
     off64_t offset,
     size64_t size,
     size64_t leaf_value_size,
     libcerror_error_t **error )
{
	static char *function  = "libfsfat_block_tree_node_initialize";
	size64_t sub_node_size = 0;

	if( block_tree_node == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid block tree node.",
		 function );

		return( -1 );
	}
	if( *block_tree_node != NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
		 "%s: invalid block tree node value already set.",
		 function );

		return( -1 );
	}
	if( offset < 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_OUT_OF_BOUNDS,
		 "%s: invalid offset value out of bounds.",
		 function );

		return( -1 );
	}
	if( ( size == 0 )
	 || ( size > (size64_t) ( INT64_MAX - offset ) ) )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_OUT_OF_BOUNDS,
		 "%s: invalid size value out of bounds.",
		 function );

		return( -1 );
	}
	if( leaf_value_size == 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_VALUE_OUT_OF_BOUNDS,
		 "%s: invalid leaf value size value out of bounds.",
		 function );

		return( -1 );
	}
	*block_tree_node = memory_allocate_structure(
	                    libfsfat_block_tree_node_t );

	if( *block_tree_node == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
		 "%s: unable to create block tree node.",
		 function );

		goto on_error;
	}
	if( memory_set(
	     *block_tree_node,
	     0,
	     sizeof( libfsfat_block_tree_node_t ) ) == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_SET_FAILED,
		 "%s: unable to clear block tree node.",
		 function );

		memory_free(
		 *block_tree_node );

		*block_tree_node = NULL;

		return( -1 );
	}
	if( libcdata_array_initialize(
	     &( ( *block_tree_node )->sub_nodes_array ),
	     LIBFSFAT_BLOCK_TREE_NUMBER_OF_SUB_NODES,
	     error ) != 1 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
		 "%s: unable to create sub nodes array.",
		 function );

		goto on_error;
	}
	sub_node_size = leaf_value_size;

	while( ( size / sub_node_size ) > LIBFSFAT_BLOCK_TREE_NUMBER_OF_SUB_NODES )
	{
		sub_node_size *= LIBFSFAT_BLOCK_TREE_NUMBER_OF_SUB_NODES;
	}
	( *block_tree_node )->start_offset  = offset;
	( *block_tree_node )->end_offset    = offset + size;
	( *block_tree_node )->size          = size;
	( *block_tree_node )->sub_node_size = sub_node_size;

	if( sub_node_size == leaf_value_size )
	{
		( *block_tree_node )->is_leaf_node = 1;
	}
	return( 1 );

on_error:
	if( *block_tree_node != NULL )
	{
		memory_free(
		 *block_tree_node );

		*block_tree_node = NULL;
	}
	return( -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 0x204

Cannot access memory at address 0x204


size_t
dns_qpkey_fromname(dns_qpkey_t key, const dns_name_t *name) {
	size_t len, label;
	dns_fixedname_t fixed;

	REQUIRE(ISC_MAGIC_VALID(name, DNS_NAME_MAGIC));

	if (name->labels == 0) {
		key[0] = SHIFT_NOBYTE;
		return (0);
	}

	if (name->offsets == NULL) {
		dns_name_t *clone = dns_fixedname_initname(&fixed);
		dns_name_clone(name, clone);
		name = clone;
	}

	len = 0;
	label = name->labels;
	while (label-- > 0) {
		const uint8_t *ldata = name->ndata + name->offsets[label];
		size_t label_len = *ldata++;
		while (label_len-- > 0) {
			uint16_t bits = dns_qp_bits_for_byte[*ldata++];
			key[len++] = bits & 0xFF;
			if ((bits >> 8) != 0) {
				key[len++] = bits >> 8;
			}
		}

		key[len++] = SHIFT_NOBYTE;
	}

	key[len] = SHIFT_NOBYTE;
	ENSURE(len < sizeof(dns_qpkey_t));
	return (len);
}


int
_dwarf_object_read_random(int fd, char *buf, Dwarf_Unsigned loc,
    Dwarf_Unsigned size, Dwarf_Unsigned filesize, int *errc)
{
    Dwarf_Unsigned endpoint = 0;
    int res = 0;

    if (loc >= filesize) {

        *errc = DW_DLE_SEEK_OFF_END;
        return DW_DLV_ERROR;
    }
    endpoint = loc+size;
    if (endpoint < loc) {

        *errc = DW_DLE_READ_OFF_END;
        return DW_DLV_ERROR;
    }
    if (endpoint > filesize) {

        *errc = DW_DLE_READ_OFF_END;
        return DW_DLV_ERROR;
    }
    res = _dwarf_seekr(fd,loc,SEEK_SET,0);
    if (res != DW_DLV_OK) {
        *errc = DW_DLE_SEEK_ERROR;
        return DW_DLV_ERROR;
    }
    res = _dwarf_readr(fd,buf,size,0);
    if (res != DW_DLV_OK) {
        *errc = DW_DLE_READ_ERROR;
        return DW_DLV_ERROR;
    }
    return DW_DLV_OK;
}

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


unsigned int luaO_codeparam (unsigned int p) {
  if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u)
    return 0xFF;
  else {
    p = (cast(l_uint32, p) * 128 + 99) / 100;
    if (p < 0x10)
      return p;
    else {
      int log = luaO_ceillog2(p + 1) - 5;
      return ((p >> log) - 0x10) | ((log + 1) << 4);
    }
  }
}

int log = luaO_ceillog2(p + 1) - 5;  /* preserve 5 bits */


float
float32_le_read (const unsigned char *cptr)
{	int		exponent, mantissa, negative ;
	float	fvalue ;

	negative = cptr [3] & 0x80 ;
	exponent = ((cptr [3] & 0x7F) << 1) | ((cptr [2] & 0x80) ? 1 : 0) ;
	mantissa = ((cptr [2] & 0x7F) << 16) | (cptr [1] << 8) | (cptr [0]) ;

	if (! (exponent || mantissa))
		return 0.0 ;

	mantissa |= 0x800000 ;
	exponent = exponent ? exponent - 127 : 0 ;

	fvalue = mantissa ? ((float) mantissa) / ((float) 0x800000) : 0.0 ;

	if (negative)
		fvalue *= -1 ;

	if (exponent > 0)
		fvalue *= pow (2.0, exponent) ;
	else if (exponent < 0)
		fvalue /= pow (2.0, abs (exponent)) ;

	return fvalue ;
}


void ssh_set_auth_methods(ssh_session session, int auth_methods)
{

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


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;
}


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;
}


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);
}


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;
}


static inline size_t
small_round(size_t size)
{
	if (size < 2)
		return size;
	assert(size <= SIZE_MAX / 2 + 1);
	assert(size - 1 <= ULONG_MAX);
	size_t r = 1;
	return r << (sizeof(unsigned long) * CHAR_BIT -
		     __builtin_clzl((unsigned long) (size - 1)));
}


void
clock_lowres_signal_init(void)
{
#ifndef NDEBUG
	owner = pthread_self();
#endif
	clock_lowres_monotonic_clock_value = clock_monotonic();
	struct sigaction sa;
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = clock_lowres_tick;
	sa.sa_flags = SA_RESTART;
	if (tt_sigaction(SIGALRM, &sa, NULL) == -1)
		panic_syserror("cannot set low resolution clock timer signal");

	struct itimerval timer;
	timer.it_interval = resolution;
	timer.it_value = resolution;
	if (setitimer(ITIMER_REAL, &timer, NULL) == -1)
		panic_syserror("cannot set low resolution clock timer");
}


int
tt_sigaction(int signum, struct sigaction *sa, struct sigaction *osa)
{
	assert(signum < SIGMAX);
	assert(sa != NULL);

	if (!main_thread_initialized) {
		main_thread_id = pthread_self();
		main_thread_initialized = true;
	}

	void (*old_handler)(int) = sighandlers[signum];
	if (sa->sa_handler == SIG_DFL || sa->sa_handler == SIG_IGN) {
		sighandlers[signum] = NULL;
	} else {
		sighandlers[signum] = sa->sa_handler;
		sa->sa_handler = sighandler_dispatcher;
	}
	int rc = sigaction(signum, sa, osa);
	if (osa != NULL && old_handler != NULL)
		osa->sa_handler = old_handler;
	return rc;
}


if (sa->sa_handler == SIG_DFL || sa->sa_handler == SIG_IGN)


ssize_t
datetime_parse_full(struct datetime *date, const char *str, size_t len,
		    const char *tzsuffix, int32_t offset)
{
	size_t n;
	dt_t dt;
	const char *svp = str;
	char c;
	int sec_of_day = 0, nanosecond = 0;
	int16_t tzindex = 0;

	n = dt_parse_iso_date(str, len, &dt);
	if (n == 0)
		return 0;

	str += n;
	len -= n;
	if (len <= 0)
		goto exit;

	c = *str++;
	if (c != 'T' && c != 't' && c != ' ')
		return 0;
	len--;
	if (len <= 0)
		goto exit;

	n = dt_parse_iso_time(str, len, &sec_of_day, &nanosecond);
	if (n == 0)
		return 0;

	str += n;
	len -= n;
	if (len <= 0)
		goto exit;

	time_t base = dt_epoch(dt) + sec_of_day - offset * 60;
	ssize_t l;
	if (tzsuffix != NULL) {
		l = parse_tz_suffix(tzsuffix, strlen(tzsuffix), base,
				    &tzindex, &offset);
		if (l < 0)
			return l;
		goto exit;
	}

	if (*str == ' ') {
		str++;
		len--;
	}
	if (len <= 0)
		goto exit;

	l = parse_tz_suffix(str, len, base, &tzindex, &offset);
	if (l < 0)
		return l;
	str += l;

exit:
	date->epoch = dt_epoch(dt) + sec_of_day - offset * 60;
	date->nsec = nanosecond;
	date->tzoffset = offset;
	date->tzindex = tzindex;

	return str - svp;
}


static int
LLVMFuzzerTestOneInput_RESPONSE(const uint8_t *data, size_t size)
{
	if (call_count == 0) {
		mock_server_init();
	}
	call_count++;

	if (size > sizeof(RESPONSE.data)) {
		return 1;
	}

	memcpy(RESPONSE.data, data, size);
	RESPONSE.size = size;

	char errbuf[256];

	struct mg_connection *conn = mg_connect_client(
	    "127.0.0.1", PORT_NUM_HTTP, 0, errbuf, sizeof(errbuf));
	if (!conn) {
		printf("Connect error: %s\n", errbuf);
		test_sleep(1);
		return 1;
	}
	mg_printf(conn, "GET / HTTP/1.0\r\n\r\n");

	int r = mg_get_response(conn, errbuf, sizeof(errbuf), 1000);
	const struct mg_response_info *ri = mg_get_response_info(conn);

	(void)r;
	(void)ri;

	mg_close_connection(conn);

	return 0;
}


size_t
pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
{
	int			nprinted;

	nprinted = vsnprintf(buf, len, fmt, args);

	if (unlikely(nprinted < 0))
	{
#ifndef FRONTEND
		elog(ERROR, "vsnprintf failed: %m with format string \"%s\"", fmt);
#else
		fprintf(stderr, "vsnprintf failed: %s with format string \"%s\"\n",
				strerror(errno), fmt);
		exit(EXIT_FAILURE);
#endif
	}

	if ((size_t) nprinted < len)
	{

		return (size_t) nprinted;
	}

	if (unlikely((size_t) nprinted > MaxAllocSize - 1))
	{
#ifndef FRONTEND
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("out of memory")));
#else
		fprintf(stderr, _("out of memory\n"));
		exit(EXIT_FAILURE);
#endif
	}

	return nprinted + 1;
}


if (unlikely((size_t) nprinted > MaxAllocSize - 1))


static int process_file(const char *name)
{
    int rc = -1;
    blkid_probe pr = blkid_new_probe_from_filename(name);
    if (pr != NULL) {
        blkid_probe_enable_partitions(pr, TRUE);
        blkid_probe_set_partitions_flags(pr, FALSE);
        blkid_probe_enable_superblocks(pr, TRUE);
        blkid_probe_set_superblocks_flags(pr, BLKID_SUBLKS_DEFAULT | BLKID_SUBLKS_FSINFO | BLKID_SUBLKS_MAGIC | BLKID_SUBLKS_VERSION | BLKID_SUBLKS_BADCSUM);
        rc = blkid_do_safeprobe(pr) == -1 ? -1 : 0;
    }
    blkid_free_probe(pr);
    return rc;
}


int mnt_table_parse_stream(struct libmnt_table *tb, FILE *f, const char *filename)
{
	int rc = -1;
	int flags = 0;
	pid_t tid = -1;
	struct libmnt_parser pa = { .line = 0 };

	assert(tb);
	assert(f);
	assert(filename);

	DBG(TAB, ul_debugobj(tb, "%s: start parsing [entries=%d, filter=%s]",
				filename, mnt_table_get_nents(tb),
				tb->fltrcb ? "yes" : "not"));

	pa.filename = filename;
	pa.f = f;

	if (tb->fmt == MNT_FMT_SWAPS)
		flags = MNT_FS_SWAP;
	else if (filename && strcmp(filename, _PATH_PROC_MOUNTS) == 0)
		flags = MNT_FS_KERNEL;

	do {
		struct libmnt_fs *fs;

		if (feof(f)) {
			DBG(TAB, ul_debugobj(tb, "end-of-file"));
			break;
		}
		fs = mnt_new_fs();
		if (!fs)
			goto err;

		rc = mnt_table_parse_next(&pa, tb, fs);

		if (rc == 0 && tb->fltrcb && tb->fltrcb(fs, tb->fltrcb_data))
			rc = 1;

		if (rc == 0 && mnt_table_is_noautofs(tb)) {
			const char *fstype = mnt_fs_get_fstype(fs);

			if (fstype && strcmp(fstype, "autofs") == 0 &&
			    mnt_fs_get_option(fs, "ignore", NULL, NULL) == 0)
				rc = 1;
		}

		if (rc == 0) {
			rc = mnt_table_add_fs(tb, fs);
			fs->flags |= flags;

			if (rc == 0 && tb->fmt == MNT_FMT_MOUNTINFO) {
				rc = kernel_fs_postparse(&pa, tb, fs, &tid);
				if (rc)
					mnt_table_remove_fs(tb, fs);
			}
		}

		mnt_unref_fs(fs);

		if (rc > 0) {
			DBG(TAB, ul_debugobj(tb, "recoverable error (continue)"));
			continue;
		}

		if (rc < 0 && !feof(f)) {
			DBG(TAB, ul_debugobj(tb, "fatal error"));
			goto err;
		}
	} while (1);

	DBG(TAB, ul_debugobj(tb, "%s: stop parsing (%d entries)",
				filename, mnt_table_get_nents(tb)));
	parser_cleanup(&pa);
	return 0;
err:
	DBG(TAB, ul_debugobj(tb, "%s: parse error (rc=%d)", filename, rc));
	parser_cleanup(&pa);
	return rc;
}


int blkid_parse_tag_string(const char *token, char **ret_type, char **ret_val)
{
	char *name, *value, *cp;

	DBG(TAG, ul_debug("trying to parse '%s' as a tag", token));

	if (!token || !(cp = strchr(token, '=')))
		return -1;

	name = strdup(token);
	if (!name)
		return -1;
	value = name + (cp - token);
	*value++ = '\0';
	if (*value == '"' || *value == '\'') {
		char c = *value++;
		if (!(cp = strrchr(value, c)))
			goto errout;
		*cp = '\0';
	}

	if (ret_val) {
		value = *value ? strdup(value) : NULL;
		if (!value)
			goto errout;
		*ret_val = value;
	}

	if (ret_type)
		*ret_type = name;
	else
		free(name);

	return 0;

errout:
	DBG(TAG, ul_debug("parse error: '%s'", token));
	free(name);
	return -1;
}


if (!token || !(cp = strchr(token, '=')))


int strappend(char **a, const char *b)
{
	size_t al, bl;
	char *tmp;

	if (!a)
		return -EINVAL;
	if (!b || !*b)
		return 0;
	if (!*a) {
		*a = strdup(b);
		return !*a ? -ENOMEM : 0;
	}

	al = strlen(*a);
	bl = strlen(b);

	tmp = realloc(*a, al + bl + 1);
	if (!tmp)
		return -ENOMEM;
	*a = tmp;
	memcpy((*a) + al, b, bl + 1);
	return 0;
}


APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str,
                                            char ***argv_out,
                                            apr_pool_t *token_context)
{
    const char *cp;
    const char *ct;
    char *cleaned, *dirty;
    int escaped;
    int isquoted, numargs = 0, argnum;

#define SKIP_WHITESPACE(cp) \
    for ( ; *cp == ' ' || *cp == '\t'; ) { \
        cp++; \
    };

#define CHECK_QUOTATION(cp,isquoted) \
    isquoted = 0; \
    if (*cp == '"') { \
        isquoted = 1; \
        cp++; \
    } \
    else if (*cp == '\'') { \
        isquoted = 2; \
        cp++; \
    }

#define DETERMINE_NEXTSTRING(cp,isquoted) \
    for ( ; *cp != '\0'; cp++) { \
        if (   (*cp == '\\' && (*(cp+1) == ' ' || *(cp+1) == '\t' || \
                                *(cp+1) == '"' || *(cp+1) == '\''))) { \
            cp++; \
            continue; \
        } \
        if (   (!isquoted && (*cp == ' ' || *cp == '\t')) \
            || (isquoted == 1 && *cp == '"') \
            || (isquoted == 2 && *cp == '\'')                 ) { \
            break; \
        } \
    }

#define REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped) \
    escaped = 0; \
    while(*dirty) { \
        if (!escaped && *dirty == '\\') { \
            escaped = 1; \
        } \
        else { \
            escaped = 0; \
            *cleaned++ = *dirty; \
        } \
        ++dirty; \
    } \
    *cleaned = 0;

    cp = arg_str;
    SKIP_WHITESPACE(cp);
    ct = cp;

    numargs = 1;
    while (*ct != '\0') {
        CHECK_QUOTATION(ct, isquoted);
        DETERMINE_NEXTSTRING(ct, isquoted);
        if (*ct != '\0') {
            ct++;
        }
        numargs++;
        SKIP_WHITESPACE(ct);
    }
    *argv_out = apr_palloc(token_context, numargs * sizeof(char*));

    for (argnum = 0; argnum < (numargs-1); argnum++) {
        SKIP_WHITESPACE(cp);
        CHECK_QUOTATION(cp, isquoted);
        ct = cp;
        DETERMINE_NEXTSTRING(cp, isquoted);
        cp++;
        (*argv_out)[argnum] = apr_palloc(token_context, cp - ct);
        apr_cpystrn((*argv_out)[argnum], ct, cp - ct);
        cleaned = dirty = (*argv_out)[argnum];
        REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped);
    }
    (*argv_out)[argnum] = NULL;

    return APR_SUCCESS;
}


APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr,
                                              char **scope_id,
                                              apr_port_t *port,
                                              const char *str,
                                              apr_pool_t *p)
{
    const char *ch, *lastchar;
    int big_port;
    apr_size_t addrlen;

    *addr = NULL;
    *scope_id = NULL;
    *port = 0;

    ch = lastchar = str + strlen(str) - 1;
    while (ch >= str && apr_isdigit(*ch)) {
        --ch;
    }

    if (ch < str) {
        big_port = atoi(str);
        if (big_port < 1 || big_port > 65535) {
            return APR_EINVAL;
        }
        *port = big_port;
        return APR_SUCCESS;
    }

    if (*ch == ':' && ch < lastchar) {
        if (ch == str) {
            return APR_EINVAL;
        }
        big_port = atoi(ch + 1);
        if (big_port < 1 || big_port > 65535) {
            return APR_EINVAL;
        }
        *port = big_port;
        lastchar = ch - 1;
    }

    addrlen = lastchar - str + 1;

#if APR_HAVE_IPV6
    if (*str == '[') {
        const char *end_bracket = memchr(str, ']', addrlen);
        struct in6_addr ipaddr;
        const char *scope_delim;

        if (!end_bracket || end_bracket != lastchar) {
            *port = 0;
            return APR_EINVAL;
        }

        scope_delim = memchr(str, '%', addrlen);
        if (scope_delim) {
            if (scope_delim == end_bracket - 1) {
                *port = 0;
                return APR_EINVAL;
            }
            addrlen = scope_delim - str - 1;
            *scope_id = apr_pstrmemdup(p, scope_delim + 1, end_bracket - scope_delim - 1);
        }
        else {
            addrlen = addrlen - 2;
        }

        *addr = apr_pstrmemdup(p, str + 1, addrlen);
        if (apr_inet_pton(AF_INET6, *addr, &ipaddr) != 1) {
            *addr = NULL;
            *scope_id = NULL;
            *port = 0;
            return APR_EINVAL;
        }
    }
    else
#endif
    {

        *addr = apr_pstrmemdup(p, str, addrlen);
    }
    return APR_SUCCESS;
}


void nxt_cdecl
nxt_log_handler(nxt_uint_t level, nxt_log_t *log, const char *fmt, ...)
{
    u_char   *p, *end;
#if 0
    u_char   *syslogmsg;
#endif
    va_list  args;
    u_char   msg[NXT_MAX_ERROR_STR];

    p = msg;
    end = msg + NXT_MAX_ERROR_STR;

    if (nxt_log_prefix != NULL) {
        p = nxt_cpystrn(p, nxt_log_prefix, end - p);
        *p++ = ':';
        *p++ = ' ';
    }

#if 0
    syslogmsg = p;
#endif

    p = nxt_sprintf(p, end, (log->ident != 0) ? "[%V] *%D " : "[%V] ",
                    &nxt_log_levels[level], log->ident);

    va_start(args, fmt);
    p = nxt_vsprintf(p, end, fmt, args);
    va_end(args);

    if (level != NXT_LOG_DEBUG && log->ctx_handler != NULL) {
        p = log->ctx_handler(log->ctx, p, end);
    }

    if (p > end - nxt_length("\n")) {
        p = end - nxt_length("\n");
    }

    *p++ = '\n';

    (void) nxt_write_console(nxt_stderr, msg, p - msg);

#if 0
    if (level == NXT_LOG_ALERT) {
        *(p - nxt_length("\n")) = '\0';

        nxt_write_syslog(LOG_ALERT, syslogmsg);
    }
#endif
}


if (level != NXT_LOG_DEBUG && log->ctx_handler != NULL)


nxt_int_t
nxt_lib_start(const char *app, char **argv, char ***envp)
{
    int           n;
    nxt_int_t     flags;
    nxt_bool_t    update;
    nxt_thread_t  *thread;

    flags = nxt_stderr_start();

    nxt_log_start(app);

    nxt_pid = getpid();
    nxt_ppid = getppid();
    nxt_euid = geteuid();
    nxt_egid = getegid();

#if (NXT_DEBUG)

    nxt_main_log.level = NXT_LOG_DEBUG;

#if (NXT_HAVE_MALLOPT)

    mallopt(M_PERTURB, 0x55);
#endif

#if (NXT_MACOSX)

    setenv("MallocScribble", "1", 0);
#endif

#endif

    nxt_thread_init_data(nxt_thread_context);
    thread = nxt_thread();
    thread->log = &nxt_main_log;

    thread->handle = nxt_thread_handle();
    thread->time.signal = -1;
    nxt_thread_time_update(thread);

    nxt_main_task.thread = thread;
    nxt_main_task.log = thread->log;
    nxt_main_task.ident = nxt_task_next_ident();

    if (nxt_strerror_start() != NXT_OK) {
        return NXT_ERROR;
    }

    if (flags != -1) {
        nxt_debug(&nxt_main_task, "stderr flags: 0x%04Xd", flags);
    }

#ifdef _SC_NPROCESSORS_ONLN

    n = sysconf(_SC_NPROCESSORS_ONLN);

#elif (NXT_HPUX)
    n = mpctl(MPC_GETNUMSPUS, NULL, NULL);

#else
    n = 0;

#endif

    nxt_debug(&nxt_main_task, "ncpu: %d", n);

    if (n > 1) {
        nxt_ncpu = n;
    }

    nxt_thread_spin_init(nxt_ncpu, 0);

    nxt_random_init(&thread->random);

    nxt_pagesize = getpagesize();

    nxt_debug(&nxt_main_task, "pagesize: %ui", nxt_pagesize);

    if (argv != NULL) {
        update = (argv[0] == app);

        nxt_process_arguments(&nxt_main_task, argv, envp);

        if (update) {
            nxt_log_start(nxt_process_argv[0]);
        }
    }

    return NXT_OK;
}

0x622e00 <vtable for std::__Fuzzer::ios_base::failure+8> "\260.b"

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


nxt_int_t
nxt_strerror_start(void)
{
    char        *msg;
    u_char      *p;
    size_t      size, length, n;
    nxt_uint_t  err, invalid;

    size = nxt_length("Unknown error");

    for (invalid = 0; invalid < 100 && nxt_sys_nerr < 65536; nxt_sys_nerr++) {

        nxt_set_errno(0);
        msg = strerror((int) nxt_sys_nerr);

        if (msg == NULL) {
            invalid++;
            continue;
        }

        length = nxt_strlen(msg);
        size += length;

        if (length == 0
            || nxt_errno == NXT_EINVAL
            || memcmp(msg, "Unknown error", 13) == 0)
        {
            invalid++;
            continue;
        }

#if (NXT_AIX)

        if (memcmp(msg, "Error ", 6) == 0
            && memcmp(msg + length - 10, " occurred.", 9) == 0)
        {
            invalid++;
            continue;
        }

#endif
    }

    nxt_sys_nerr -= invalid;

    nxt_main_log_debug("sys_nerr: %d", nxt_sys_nerr);

    n = (nxt_sys_nerr + 1) * sizeof(nxt_str_t);

    nxt_sys_errlist = nxt_malloc(n + size);
    if (nxt_sys_errlist == NULL) {
        return NXT_ERROR;
    }

    p = nxt_pointer_to(nxt_sys_errlist, n);

    for (err = 0; err < nxt_sys_nerr; err++) {
        msg = strerror((int) err);
        length = nxt_strlen(msg);

        nxt_sys_errlist[err].length = length;
        nxt_sys_errlist[err].start = p;

        p = nxt_cpymem(p, msg, length);
    }

    nxt_sys_errlist[err].length = 13;
    nxt_sys_errlist[err].start = p;
    nxt_memcpy(p, "Unknown error", 13);

    nxt_strerror = nxt_runtime_strerror;

    return NXT_OK;
}

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


nxt_int_t nxt_http_parse_fuzz(nxt_str_t *request, nxt_lvlhsh_t *hash){

    nxt_mp_t                  *mp;
    nxt_buf_mem_t             buf;
    nxt_http_request_parse_t  rp;

    buf.start = request->start;
    buf.end = request->start + request->length;

    nxt_memzero(&rp, sizeof(nxt_http_request_parse_t));

    mp = nxt_mp_create(1024, 128, 256, 32);

    nxt_http_parse_request_init(&rp, mp);

    buf.pos = buf.start;
    buf.free = buf.end;

    if (nxt_slow_path(nxt_http_parse_request(&rp, &buf) == NXT_DONE)) {
        nxt_http_fields_process(rp.fields, hash, NULL);
    }

    nxt_mp_destroy(mp);

    return NXT_OK;
}


int stun_is_command_message_str(const uint8_t *buf, size_t blen) {
  if (buf && blen >= STUN_HEADER_LENGTH) {
    if (!STUN_VALID_CHANNEL(nswap16(((const uint16_t *)buf)[0]))) {
      if ((((uint8_t)buf[0]) & ((uint8_t)(0xC0))) == 0) {
        if (nswap32(((const uint32_t *)(buf))[1]) == STUN_MAGIC_COOKIE) {
          uint16_t len = nswap16(((const uint16_t *)(buf))[1]);
          if ((len & 0x0003) == 0) {
            if ((size_t)(len + STUN_HEADER_LENGTH) == blen) {
              return 1;
            }
          }
        }
      }
    }
  }
  return 0;
}


if (nswap32(((const uint32_t *)(buf))[1]) == STUN_MAGIC_COOKIE)


extern int
onig_set_callout_of_name(OnigEncoding enc, OnigCalloutType callout_type,
                         UChar* name, UChar* name_end, int in,
                         OnigCalloutFunc start_func,
                         OnigCalloutFunc end_func,
                         int arg_num, unsigned int arg_types[],
                         int opt_arg_num, OnigValue opt_defaults[])
{
  int r;
  int i;
  int j;
  int id;
  int is_not_single;
  CalloutNameEntry* e;
  CalloutNameListEntry* fe;

  if (callout_type != ONIG_CALLOUT_TYPE_SINGLE)
    return ONIGERR_INVALID_ARGUMENT;

  if (arg_num < 0 || arg_num > ONIG_CALLOUT_MAX_ARGS_NUM)
    return ONIGERR_INVALID_CALLOUT_ARG;

  if (opt_arg_num < 0 || opt_arg_num > arg_num)
    return ONIGERR_INVALID_CALLOUT_ARG;

  if (start_func == 0 && end_func == 0)
    return ONIGERR_INVALID_CALLOUT_ARG;

  if ((in & ONIG_CALLOUT_IN_PROGRESS) == 0 && (in & ONIG_CALLOUT_IN_RETRACTION) == 0)
    return ONIGERR_INVALID_CALLOUT_ARG;

  for (i = 0; i < arg_num; i++) {
    unsigned int t = arg_types[i];
    if (t == ONIG_TYPE_VOID)
      return ONIGERR_INVALID_CALLOUT_ARG;
    else {
      if (i >= arg_num - opt_arg_num) {
        if (t != ONIG_TYPE_LONG && t != ONIG_TYPE_CHAR && t != ONIG_TYPE_STRING &&
            t != ONIG_TYPE_TAG)
          return ONIGERR_INVALID_CALLOUT_ARG;
      }
      else {
        if (t != ONIG_TYPE_LONG) {
          t = t & ~ONIG_TYPE_LONG;
          if (t != ONIG_TYPE_CHAR && t != ONIG_TYPE_STRING && t != ONIG_TYPE_TAG)
            return ONIGERR_INVALID_CALLOUT_ARG;
        }
      }
    }
  }

  if (! is_allowed_callout_name(enc, name, name_end)) {
    return ONIGERR_INVALID_CALLOUT_NAME;
  }

  is_not_single = (callout_type != ONIG_CALLOUT_TYPE_SINGLE);
  id = callout_name_entry(&e, enc, is_not_single, name, name_end);
  if (id < 0) return id;

  r = ONIG_NORMAL;
  if (IS_NULL(GlobalCalloutNameList)) {
    r = make_callout_func_list(&GlobalCalloutNameList, 10);
    if (r != ONIG_NORMAL) return r;
  }

  while (id >= GlobalCalloutNameList->n) {
    int rid;
    r = callout_func_list_add(GlobalCalloutNameList, &rid);
    if (r != ONIG_NORMAL) return r;
  }

  fe = GlobalCalloutNameList->v + id;
  fe->type         = callout_type;
  fe->in           = in;
  fe->start_func   = start_func;
  fe->end_func     = end_func;
  fe->arg_num      = arg_num;
  fe->opt_arg_num  = opt_arg_num;
  fe->name         = e->name;

  for (i = 0; i < arg_num; i++) {
    fe->arg_types[i] = arg_types[i];
  }
  for (i = arg_num - opt_arg_num, j = 0; i < arg_num; i++, j++) {
    if (IS_NULL(opt_defaults)) return ONIGERR_INVALID_ARGUMENT;
    if (fe->arg_types[i] == ONIG_TYPE_STRING) {
      OnigValue* val;
      UChar* ds;

      val = opt_defaults + j;
      ds = onigenc_strdup(enc, val->s.start, val->s.end);
      CHECK_NULL_RETURN_MEMERR(ds);

      fe->opt_defaults[i].s.start = ds;
      fe->opt_defaults[i].s.end   = ds + (val->s.end - val->s.start);
    }
    else {
      fe->opt_defaults[i] = opt_defaults[j];
    }
  }

  r = id;
  return r;
}


static int
is_valid_mbc_string(const UChar* p, const UChar* end)
{
  while (p < end) {
    if (*p < 0x80) {
      p++;
    }
    else if (*p > 0xa0) {
      if (*p == 0xff) return FALSE;
      p++;
      if (p >= end) return FALSE;
      if (*p < 0xa1 || *p == 0xff) return FALSE;
      p++;
    }
    else if (*p == 0x8e) {
      p++;
      if (p >= end) return FALSE;
      if (*p < 0xa1 || *p > 0xdf) return FALSE;
      p++;
    }
    else if (*p == 0x8f) {
      p++;
      if (p >= end) return FALSE;
      if (*p < 0xa1 || *p == 0xff) return FALSE;
      p++;
      if (p >= end) return FALSE;
      if (*p < 0xa1 || *p == 0xff) return FALSE;
      p++;
    }
    else
      return FALSE;
  }

  return TRUE;
}


void ddsi_iid_init (void)
{
  union { uint64_t u64; uint32_t u32[2]; } tmp;
  ddsrt_prng_seed_t seed;
  DDSRT_STATIC_ASSERT (sizeof (seed.key) >= sizeof (ddsi_iid.key));

  if (ddsrt_prng_makeseed (&seed))
    memcpy (ddsi_iid.key, seed.key, sizeof (ddsi_iid.key));
  else
  {
    for (size_t i = 0; i < sizeof (ddsi_iid.key) / sizeof (ddsi_iid.key[0]); i++)
      ddsi_iid.key[i] = ddsrt_random ();
  }
  tmp.u64 = 0;
  dds_tea_decrypt (tmp.u32, ddsi_iid.key);
  ddsrt_atomic_st64 (&ddsi_iid.counter, tmp.u64);
}


bool ddsrt_prng_makeseed (struct ddsrt_prng_seed *seed)
{
  FILE *rndfile;
  memset (seed->key, 0, sizeof (seed->key));
  if ((rndfile = fopen ("/dev/urandom", "rb")) == NULL)
    return false;
  else
  {
    size_t n = fread (seed->key, sizeof (seed->key), 1, rndfile);
    fclose (rndfile);
    return (n == 1);
  }
}


void
WS_Rollback(struct ws *ws, uintptr_t pp)
{

	WS_Assert(ws);

	if (pp == 0)
		pp = (uintptr_t)ws->s;
	ws_ClearOverflow(ws);
	WS_Reset(ws, pp);
}


void
CxPlatSystemLoad(
    void
    )
{
#if defined(CX_PLATFORM_DARWIN)

    CxPlatProcessorCount = 1;
#else
    CxPlatProcessorCount = (uint32_t)sysconf(_SC_NPROCESSORS_ONLN);
#endif

#ifdef CXPLAT_NUMA_AWARE
    if (numa_available() >= 0) {
        CxPlatNumaNodeCount = (uint32_t)numa_num_configured_nodes();
        CxPlatNumaNodeMasks =
            CXPLAT_ALLOC_NONPAGED(sizeof(cpu_set_t) * CxPlatNumaNodeCount, QUIC_POOL_PLATFORM_PROC);
        CXPLAT_FRE_ASSERT(CxPlatNumaNodeMasks);
        for (uint32_t n = 0; n < CxPlatNumaNodeCount; ++n) {
            CPU_ZERO(&CxPlatNumaNodeMasks[n]);
            CXPLAT_FRE_ASSERT(numa_node_to_cpus_compat((int)n, CxPlatNumaNodeMasks[n].__bits, sizeof(cpu_set_t)) >= 0);
        }
    } else {
        CxPlatNumaNodeCount = 0;
    }
#endif

#ifdef DEBUG
    CxPlatform.AllocFailDenominator = 0;
    CxPlatform.AllocCounter = 0;
#endif

    long ShouldLoad = 1;

    char *DisableValue = getenv("QUIC_LTTng");
    if (DisableValue != NULL) {
        ShouldLoad = strtol(DisableValue, NULL, 10);
    }

    if (!ShouldLoad) {
        goto Exit;
    }

    Dl_info Info;
    int Succeeded = dladdr((void *)CxPlatSystemLoad, &Info);
    if (!Succeeded) {
        goto Exit;
    }

    size_t PathLen = strlen(Info.dli_fname);

    int LastTrailingSlashLen = -1;
    for (int i = PathLen; i >= 0; i--) {
        if (Info.dli_fname[i] == '/') {
            LastTrailingSlashLen = i + 1;
            break;
        }
    }

    if (LastTrailingSlashLen == -1) {
        goto Exit;
    }

    size_t TpLibNameLen = strlen(TpLibName);
    size_t ProviderFullPathLength = TpLibNameLen + LastTrailingSlashLen + 1;

    char* ProviderFullPath = CXPLAT_ALLOC_PAGED(ProviderFullPathLength, QUIC_POOL_PLATFORM_TMP_ALLOC);
    if (ProviderFullPath == NULL) {
        goto Exit;
    }

    CxPlatCopyMemory(ProviderFullPath, Info.dli_fname, LastTrailingSlashLen);
    CxPlatCopyMemory(ProviderFullPath + LastTrailingSlashLen, TpLibName, TpLibNameLen);
    ProviderFullPath[LastTrailingSlashLen + TpLibNameLen] = '\0';

    dlopen(ProviderFullPath, RTLD_NOW | RTLD_GLOBAL);

    CXPLAT_FREE(ProviderFullPath, QUIC_POOL_PLATFORM_TMP_ALLOC);

Exit:

    QuicTraceLogInfo(
        PosixLoaded,
        "[ dso] Loaded");
}


uint64_t
CGroupGetMemoryLimit()
{
    uint64_t PhysicalMemoryLimit = 0;
    uint64_t RestrictedMemoryLimit = 0;

    CGroupInitialize();

    PhysicalMemoryLimit = GetPhysicalMemoryLimit();

    if (!GetCGroupRestrictedMemoryLimit(&RestrictedMemoryLimit)) {
        goto Done;
    }

    if (RestrictedMemoryLimit > 0x7FFFFFFF00000000) {
        goto Done;
    }

    struct rlimit CurrRlimit;
    size_t RlimitSoftLimit = (size_t)RLIM_INFINITY;
    if (getrlimit(RLIMIT_AS, &CurrRlimit) == 0) {
        RlimitSoftLimit = CurrRlimit.rlim_cur;
    }
    RestrictedMemoryLimit = (RestrictedMemoryLimit < RlimitSoftLimit) ?
                             RestrictedMemoryLimit : RlimitSoftLimit;

    PhysicalMemoryLimit = (RestrictedMemoryLimit < PhysicalMemoryLimit) ?
                             RestrictedMemoryLimit : PhysicalMemoryLimit;

    if (PhysicalMemoryLimit > SIZE_T_MAX)
    {

        PhysicalMemoryLimit = SIZE_T_MAX;
    }

Done:

    CGroupCleanup();

    if (PhysicalMemoryLimit == 0) {
        PhysicalMemoryLimit = 0x40000000;
    }

    return PhysicalMemoryLimit;
}


int
sonmp_decode(struct lldpd *cfg, char *frame, int s, struct lldpd_hardware *hardware,
    struct lldpd_chassis **newchassis, struct lldpd_port **newport)
{
	const u_int8_t mcastaddr[] = SONMP_MULTICAST_ADDR;
	struct lldpd_chassis *chassis;
	struct lldpd_port *port;
	struct lldpd_mgmt *mgmt;
	int length, i;
	u_int8_t *pos;
	u_int8_t seg[3], rchassis;
	struct in_addr address;

	log_debug("sonmp", "decode SONMP PDU from %s", hardware->h_ifname);

	if ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) {
		log_warn("sonmp", "failed to allocate remote chassis");
		return -1;
	}
	TAILQ_INIT(&chassis->c_mgmt);
	if ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) {
		log_warn("sonmp", "failed to allocate remote port");
		free(chassis);
		return -1;
	}
#  ifdef ENABLE_DOT1
	TAILQ_INIT(&port->p_vlans);
#  endif

	length = s;
	pos = (u_int8_t *)frame;
	if (length < SONMP_SIZE + 2 * ETHER_ADDR_LEN + sizeof(u_int16_t)) {
		log_warnx("sonmp", "too short SONMP frame received on %s",
		    hardware->h_ifname);
		goto malformed;
	}
	if (PEEK_CMP(mcastaddr, sizeof(mcastaddr)) != 0)

		goto malformed;

	PEEK_DISCARD(ETHER_ADDR_LEN);
	PEEK_DISCARD_UINT16;
	PEEK_DISCARD(6);
	if (PEEK_UINT16 != LLC_PID_SONMP_HELLO) {
		log_debug("sonmp", "incorrect LLC protocol ID received for SONMP on %s",
		    hardware->h_ifname);
		goto malformed;
	}

	chassis->c_id_subtype = LLDP_CHASSISID_SUBTYPE_ADDR;
	if ((chassis->c_id = calloc(1, sizeof(struct in_addr) + 1)) == NULL) {
		log_warn("sonmp", "unable to allocate memory for chassis id on %s",
		    hardware->h_ifname);
		goto malformed;
	}
	chassis->c_id_len = sizeof(struct in_addr) + 1;
	chassis->c_id[0] = 1;
	PEEK_BYTES(&address, sizeof(struct in_addr));
	memcpy(chassis->c_id + 1, &address, sizeof(struct in_addr));
	if (asprintf(&chassis->c_name, "%s", inet_ntoa(address)) == -1) {
		log_warnx("sonmp", "unable to write chassis name for %s",
		    hardware->h_ifname);
		goto malformed;
	}
	PEEK_BYTES(seg, sizeof(seg));
	rchassis = PEEK_UINT8;
	for (i = 0; sonmp_chassis_types[i].type != 0; i++) {
		if (sonmp_chassis_types[i].type == rchassis) break;
	}
	if (asprintf(&chassis->c_descr, "%s", sonmp_chassis_types[i].description) ==
	    -1) {
		log_warnx("sonmp", "unable to write chassis description for %s",
		    hardware->h_ifname);
		goto malformed;
	}
	mgmt = lldpd_alloc_mgmt(LLDPD_AF_IPV4, &address, sizeof(struct in_addr), 0);
	if (mgmt == NULL) {
		if (errno == ENOMEM)
			log_warn("sonmp",
			    "unable to allocate memory for management address");
		else
			log_warn("sonmp", "too large management address received on %s",
			    hardware->h_ifname);
		goto malformed;
	}
	TAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries);
	port->p_ttl =
	    cfg ? (cfg->g_config.c_tx_interval * cfg->g_config.c_tx_hold) : LLDPD_TTL;
	port->p_ttl = (port->p_ttl + 999) / 1000;

	port->p_id_subtype = LLDP_PORTID_SUBTYPE_LOCAL;

	port->p_id_len =
	    asprintf(&port->p_id, "%02x-%02x-%02x", seg[0], seg[1], seg[2]);
	if (port->p_id_len == -1) {
		log_warn("sonmp", "unable to allocate memory for port id on %s",
		    hardware->h_ifname);
		goto malformed;
	}

	if ((seg[0] == 0) && (seg[1] == 0)) {
		if (asprintf(&port->p_descr, "port %d", seg[2]) == -1) {
			log_warnx("sonmp", "unable to write port description for %s",
			    hardware->h_ifname);
			goto malformed;
		}
	} else if (seg[0] == 0) {
		if (asprintf(&port->p_descr, "port %d/%d", seg[1], seg[2]) == -1) {
			log_warnx("sonmp", "unable to write port description for %s",
			    hardware->h_ifname);
			goto malformed;
		}
	} else {
		if (asprintf(&port->p_descr, "port %x:%x:%x", seg[0], seg[1], seg[2]) ==
		    -1) {
			log_warnx("sonmp", "unable to write port description for %s",
			    hardware->h_ifname);
			goto malformed;
		}
	}
	*newchassis = chassis;
	*newport = port;
	return 1;

malformed:
	lldpd_chassis_cleanup(chassis, 1);
	lldpd_port_cleanup(port, 1);
	free(port);
	return -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 0x18

Cannot access memory at address 0x18


Cannot access memory at address 0x18


void
lldpd_port_cleanup(struct lldpd_port *port, int all)
{
#ifdef ENABLE_LLDPMED
	int i;
	if (all)
		for (i = 0; i < LLDP_MED_LOCFORMAT_LAST; i++)
			free(port->p_med_location[i].data);
#endif
#ifdef ENABLE_DOT1
	lldpd_vlan_cleanup(port);
	lldpd_ppvid_cleanup(port);
	lldpd_pi_cleanup(port);
#endif

	if (all) {
		free(port->p_id);
		port->p_id = NULL;
		free(port->p_descr);
		port->p_descr = NULL;
		free(port->p_lastframe);
		if (port->p_chassis) {
			port->p_chassis->c_refcount--;
			port->p_chassis = NULL;
		}
#ifdef ENABLE_CUSTOM
		lldpd_custom_list_cleanup(port);
#endif
	}
}


int symtab_init(symtab_t * s, unsigned int size)
{
	s->table = hashtab_create(symhash, symcmp, size);
	if (!s->table)
		return -1;
	s->nprim = 0;
	return 0;
}


void sepol_policydb_free(sepol_policydb_t * p)
{
	if (!p)
		return;
	policydb_destroy(&p->p);
	free(p);
}


int add_i_to_a(uint32_t i, uint32_t * cnt, uint32_t ** a)
{
	uint32_t *new;

	if (cnt == NULL || *cnt == UINT32_MAX || a == NULL)
		return -1;

	if (*a != NULL)
		new = (uint32_t *) reallocarray(*a, *cnt + 1, sizeof(uint32_t));
	else {

		*cnt = 0;
		new = (uint32_t *) malloc(sizeof(uint32_t));
	}
	if (new == NULL) {
		return -1;
	}
	new[*cnt] = i;
	(*cnt)++;
	*a = new;
	return 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 0x725f7463656a626f


static int read_source_policy(policydb_t *p, const uint8_t *data, size_t size)
{
	int fd, rc;
	ssize_t wr;

	fd = memfd_create("fuzz-input", MFD_CLOEXEC);
	if (fd < 0)
		return -1;

	wr = full_write(fd, data, size);
	if (wr < 0 || (size_t)wr != size) {
		close(fd);
		return -1;
	}

	fsync(fd);

	yynerrs = 0;

	yyin = fdopen(fd, "r");
	if (!yyin) {
		close(fd);
		return -1;
	}

	rewind(yyin);

	set_source_file("fuzz-input");

	id_queue = queue_create();
	if (id_queue == NULL) {
		fclose(yyin);
		yylex_destroy();
		return -1;
	}

	policydbp = p;
	mlspol = p->mls;

	init_parser(1);

	if (!setjmp(fuzzing_pre_parse_stack_state)) {
		queue_destroy(id_queue);
		fclose(yyin);
		yylex_destroy();
		return -1;
	}

	rc = yyparse();

	assert(rc || !policydb_errors);
	if (rc || policydb_errors) {
		queue_destroy(id_queue);
		fclose(yyin);
		yylex_destroy();
		return -1;
	}

	rewind(yyin);
	init_parser(2);
	set_source_file("fuzz-input");
	yyrestart(yyin);

	rc = yyparse();
	assert(rc || !policydb_errors);
	if (rc || policydb_errors) {
		queue_destroy(id_queue);
		fclose(yyin);
		yylex_destroy();
		return -1;
	}

	queue_destroy(id_queue);
	fclose(yyin);
	yylex_destroy();

	return 0;
}


void sepol_sidtab_destroy(sidtab_t * s)
{
	int i;
	sidtab_ptr_t cur, temp;

	if (!s || !s->htable)
		return;

	for (i = 0; i < SIDTAB_SIZE; i++) {
		cur = s->htable[i];
		while (cur != NULL) {
			temp = cur;
			cur = cur->next;
			context_destroy(&temp->context);
			free(temp);
		}
		s->htable[i] = NULL;
	}
	free(s->htable);
	s->htable = NULL;
	s->nel = 0;
	s->next_sid = 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 0xffffffff00000000


void ebitmap_destroy(ebitmap_t * e)
{
	ebitmap_node_t *n, *temp;

	if (!e)
		return;

	n = e->node;
	while (n) {
		temp = n;
		n = n->next;
		free(temp);
	}

	e->highbit = 0;
	e->node = 0;
	return;
}


int next_entry(void *buf, struct policy_file *fp, size_t bytes)
{
	size_t nread;

	switch (fp->type) {
	case PF_USE_STDIO:
		nread = fread(buf, bytes, 1, fp->fp);

		if (nread != 1)
			return -1;
		break;
	case PF_USE_MEMORY:
		if (bytes > fp->len) {
			errno = EOVERFLOW;
			return -1;
		}
		memcpy(buf, fp->data, bytes);
		fp->data += bytes;
		fp->len -= bytes;
		break;
	default:
		errno = EINVAL;
		return -1;
	}
	return 0;
}


int shm_address_in(void *p)
{
	int i;

	for(i = 0; i < _shm_core_pools_num; i++) {
		if(_shm_core_pools_mem[i] == (void *)-1) {
			continue;
		}
		if(((char *)p >= (char *)_shm_core_pools_mem[i])
				&& ((char *)p
						< ((char *)_shm_core_pools_mem[i]) + shm_mem_size)) {

			return 1;
		}
	}

	return 0;
}

if (_shm_core_pools_mem[i] == (void *)-1)


int mdb_set_default_backend(MdbHandle *mdb, const char *backend_name)
{
	MdbBackend *backend;

    if (!mdb->backends) {
        mdb_init_backends(mdb);
    }
	backend = (MdbBackend *) g_hash_table_lookup(mdb->backends, backend_name);
	if (backend) {
		mdb->default_backend = backend;
		g_free(mdb->backend_name);
		mdb->backend_name = (char *) g_strdup(backend_name);
		mdb->relationships_table = NULL;
		if (backend->date_fmt) {
			mdb_set_date_fmt(mdb, backend->date_fmt);
		} else {
			mdb_set_date_fmt(mdb, "%x %X");
		}
		if (backend->shortdate_fmt) {
			mdb_set_shortdate_fmt(mdb, backend->shortdate_fmt);
		} else {
			mdb_set_shortdate_fmt(mdb, "%x");
		}
	}
	return (backend != NULL);
}

0x52f2b7 "-- That file uses encoding %s\n"

{gchar *(const gchar *, const gchar *)} 0x4caac0 <quote_schema_name_bracket_merge>

{gchar *(const gchar *)} 0x4cb1a0 <passthrough_unchanged>


void mdb_iconv_init(MdbHandle *mdb)
{
	const char *iconv_code;

	if (!(iconv_code=getenv("MDBICONV"))) {
		iconv_code="UTF-8";
	}

#ifdef HAVE_ICONV
	if (!IS_JET3(mdb)) {
		mdb->iconv_out = iconv_open("UCS-2LE", iconv_code);
		mdb->iconv_in = iconv_open(iconv_code, "UCS-2LE");
	} else {

		const char *jet3_iconv_code = getenv("MDB_JET3_CHARSET");

		if (!jet3_iconv_code) {

			jet3_iconv_code = mdb_iconv_name_from_code_page(mdb->f->code_page);
		}
		if (!jet3_iconv_code) {
			jet3_iconv_code = "CP1252";
		}

		mdb->iconv_out = iconv_open(jet3_iconv_code, iconv_code);
		mdb->iconv_in = iconv_open(iconv_code, jet3_iconv_code);
	}
#elif defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64) || defined(WINDOWS)
    mdb->locale = _create_locale(LC_CTYPE, ".65001");
#else
    mdb->locale = newlocale(LC_CTYPE_MASK, "C.UTF-8", NULL);
#endif
}


static int
enforce_null_termination (Bit_Chain *dat, bool enforce)
{
  unsigned char *copy;
  unsigned char c;
  if (!dat->size)
    return 0;
  c = dat->chain[dat->size - 1];

  if (!enforce && ((c == '\n' && c + 1 == '\0') || c == '\0'))
    return 0;
#ifdef STANDALONE
  fprintf (stderr,
           "llvmfuzz_standalone: enforce libfuzzer buffer NULL termination\n");
#endif
  copy = malloc (dat->size + 1);
  memcpy (copy, dat->chain, dat->size);
  copy[dat->size] = '\0';
  dat->chain = copy;
  return 1;
}


void
dwg_free (Dwg_Data *dwg)
{
  BITCODE_BL i;
  if (dwg)
    {
      pdat.version = dwg->header.version;
      pdat.from_version = dwg->header.from_version;
      if (dwg->opts)
        {
          loglevel = dwg->opts & DWG_OPTS_LOGLEVEL;
          pdat.opts = dwg->opts;
        }
#ifdef USE_TRACING

      if (!env_var_checked_p)
        {
          char *probe = getenv ("LIBREDWG_TRACE");
          if (probe)
            loglevel = atoi (probe);
          env_var_checked_p = 1;
        }
#endif
      LOG_INFO ("\n============\ndwg_free\n")

      for (i = 0; i < dwg->num_objects; ++i)
        {
          if (!dwg_obj_is_control (&dwg->object[i]))
            dwg_free_object (&dwg->object[i]);
        }
      if (dwg->header.version < R_13b1)
        dwg_free_preR13_header_vars (dwg);
      else
        dwg_free_header_vars (dwg);
      dwg_free_summaryinfo (dwg);
      if (dwg->header.section_infohdr.num_desc)
        {
          for (i = 0; i < dwg->header.section_infohdr.num_desc; ++i)
            FREE_IF (dwg->header.section_info[i].sections);
          FREE_IF (dwg->header.section_info);
        }
      dwg_free_appinfo (dwg);
      dwg_free_filedeplist (dwg);
      dwg_free_security (dwg);
      dwg_free_acds (dwg);

      FREE_IF (dwg->thumbnail.chain);
      FREE_IF (dwg->vbaproject.unknown_bits);
      FREE_IF (dwg->revhistory.histories);
      FREE_IF (dwg->appinfohistory.unknown_bits);

      FREE_IF (dwg->Template.description);
      FREE_IF (dwg->header.section);
      FREE_IF (dwg->auxheader.R11_HANDSEED);

      for (i = 0; i < dwg->num_objects; ++i)
        {
          if (dwg_obj_is_control (&dwg->object[i]))
            dwg_free_object (&dwg->object[i]);
        }
      if (dwg->num_classes && dwg->dwg_class)
        {
          for (i = 0; i < dwg->num_classes; ++i)
            {
              FREE_IF (dwg->dwg_class[i].appname);
              FREE_IF (dwg->dwg_class[i].cppname);
              FREE_IF (dwg->dwg_class[i].dxfname);
              if (dwg->header.from_version >= R_2007)
                FREE_IF (dwg->dwg_class[i].dxfname_u);
            }
        }
      FREE_IF (dwg->dwg_class);
      if (dwg->object_ref)
        {
          LOG_HANDLE ("free %d global refs\n", dwg->num_object_refs)
          for (i = 0; i < dwg->num_object_refs; ++i)
            {
              LOG_INSANE ("free ref %d\n", i)
              FREE_IF (dwg->object_ref[i]);
            }
        }
      FREE_IF (dwg->object_ref);
      for (i = 0; i < dwg->num_acis_sab_hdl; ++i)
        {
          FREE_IF (dwg->acis_sab_hdl[i]);
        }
      FREE_IF (dwg->acis_sab_hdl);
      FREE_IF (dwg->object);
      if (dwg->object_map)
        {
          hash_free (dwg->object_map);
          dwg->object_map = NULL;
        }
      dwg->num_objects = dwg->num_classes = dwg->num_object_refs = 0;
#undef FREE_IF
    }
}


size_t
strlcpy(char *dst, const char *src, size_t size) {
	char *d = dst;
	const char *s = src;
	size_t n = size;

	if (n != 0U && --n != 0U) {
		do {
			if ((*d++ = *s++) == 0) {
				break;
			}
		} while (--n != 0U);
	}

	if (n == 0U) {
		if (size != 0U) {
			*d = '\0';
		}
		while (*s++) {
		}
	}

	return (s - src - 1);
}


void
dns_message_create(isc_mem_t *mctx, isc_mempool_t *namepool,
		   isc_mempool_t *rdspool, dns_message_intent_t intent,
		   dns_message_t **msgp) {
	REQUIRE(mctx != NULL);
	REQUIRE(msgp != NULL);
	REQUIRE(*msgp == NULL);
	REQUIRE(intent == DNS_MESSAGE_INTENTPARSE ||
		intent == DNS_MESSAGE_INTENTRENDER);
	REQUIRE((namepool != NULL && rdspool != NULL) ||
		(namepool == NULL && rdspool == NULL));

	dns_message_t *msg = isc_mem_get(mctx, sizeof(dns_message_t));
	*msg = (dns_message_t){
		.from_to_wire = intent,
		.references = ISC_REFCOUNT_INITIALIZER(1),
		.scratchpad = ISC_LIST_INITIALIZER,
		.cleanup = ISC_LIST_INITIALIZER,
		.rdatas = ISC_LIST_INITIALIZER,
		.rdatalists = ISC_LIST_INITIALIZER,
		.offsets = ISC_LIST_INITIALIZER,
		.freerdata = ISC_LIST_INITIALIZER,
		.freerdatalist = ISC_LIST_INITIALIZER,
		.magic = DNS_MESSAGE_MAGIC,
		.namepool = namepool,
		.rdspool = rdspool,
		.free_pools = (namepool == NULL && rdspool == NULL),
	};

	isc_mem_attach(mctx, &msg->mctx);

	if (msg->free_pools) {
		dns_message_createpools(mctx, &msg->namepool, &msg->rdspool);
	}

	msginit(msg);

	for (size_t i = 0; i < DNS_SECTION_MAX; i++) {
		ISC_LIST_INIT(msg->sections[i]);
	}

	isc_buffer_t *dynbuf = NULL;
	isc_buffer_allocate(mctx, &dynbuf, SCRATCHPAD_SIZE);
	ISC_LIST_APPEND(msg->scratchpad, dynbuf, link);

	*msgp = msg;
}


isc_result_t
isc_parse_uint32(uint32_t *uip, const char *string, int base) {
	unsigned long n;
	uint32_t r;
	char *e;
	if (!isalnum((unsigned char)(string[0]))) {
		return (ISC_R_BADNUMBER);
	}
	errno = 0;
	n = strtoul(string, &e, base);
	if (*e != '\0') {
		return (ISC_R_BADNUMBER);
	}

	r = (uint32_t)n;
	if ((n == ULONG_MAX && errno == ERANGE) || (n != (unsigned long)r)) {
		return (ISC_R_RANGE);
	}
	*uip = r;
	return (ISC_R_SUCCESS);
}


int
dwarf_init_b(int fd,
    unsigned        group_number,
    Dwarf_Handler   errhand,
    Dwarf_Ptr       errarg,
    Dwarf_Debug *   ret_dbg,
    Dwarf_Error *   error)
{
    unsigned ftype = 0;
    unsigned endian = 0;
    unsigned offsetsize = 0;
    unsigned universalnumber = 0;
    Dwarf_Unsigned   filesize = 0;
    int res = 0;
    int errcode = 0;

    if (!ret_dbg) {
        DWARF_DBG_ERROR(NULL,DW_DLE_DWARF_INIT_DBG_NULL,DW_DLV_ERROR);
    }

    *ret_dbg = 0;
    res = dwarf_object_detector_fd(fd, &ftype,
        &endian,&offsetsize,&filesize,&errcode);
    if (res == DW_DLV_NO_ENTRY) {
        return res;
    }
    if (res == DW_DLV_ERROR) {

        DWARF_DBG_ERROR(NULL, DW_DLE_FILE_WRONG_TYPE, DW_DLV_ERROR);
    }
    switch(ftype) {
    case DW_FTYPE_ELF: {
        int res2 = 0;

        res2 = _dwarf_elf_nlsetup(fd,"",
            ftype,endian,offsetsize,filesize,
            group_number,errhand,errarg,ret_dbg,error);
        if (res2 != DW_DLV_OK) {
            return res2;
        }
        set_global_paths_init(*ret_dbg,error);
        return res2;
        }
    case DW_FTYPE_APPLEUNIVERSAL:
    case DW_FTYPE_MACH_O: {
        int resm = 0;

        resm = _dwarf_macho_setup(fd,"",
            universalnumber,
            ftype,endian,offsetsize,filesize,
            group_number,errhand,errarg,ret_dbg,error);
        if (resm != DW_DLV_OK) {
            return resm;
        }
        set_global_paths_init(*ret_dbg,error);
        return resm;
        }

    case DW_FTYPE_PE: {
        int resp = 0;

        resp = _dwarf_pe_setup(fd,
            "",
            ftype,endian,offsetsize,filesize,
            group_number,errhand,errarg,ret_dbg,error);
        if (resp != DW_DLV_OK) {
            return resp;
        }
        set_global_paths_init(*ret_dbg,error);
        return resp;
        }
    default: break;
    }
    DWARF_DBG_ERROR(NULL, DW_DLE_FILE_WRONG_TYPE, DW_DLV_ERROR);

}

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 0xfe02dd63e9f26600


int
_dwarf_seekr(int fd,
    Dwarf_Unsigned loc,
    int seektype,
    Dwarf_Unsigned *out_loc)
{
    Dwarf_Signed fsize = 0;
    Dwarf_Signed sloc = 0;

    sloc = (Dwarf_Signed)loc;
    if (sloc < 0) {
        return DW_DLV_ERROR;
    }
#ifdef _WIN64
    fsize = (Dwarf_Signed)lseek(fd,(__int64)loc,seektype);
#elif defined(_WIN32)
    fsize = (Dwarf_Signed)lseek(fd,(off_t)loc,seektype);
#else
    fsize = (Dwarf_Signed)lseek(fd,(off_t)loc,seektype);
#endif
    if (fsize < 0) {
        return DW_DLV_ERROR;
    }
    if (out_loc) {
        *out_loc = (Dwarf_Unsigned)fsize;
    }
    return DW_DLV_OK;
}


int
_dwarf_macho_setup(int fd,
    char *true_path,
    unsigned universalnumber,
    unsigned ftype,
    unsigned endian,
    unsigned offsetsize,
    Dwarf_Unsigned filesize,
    unsigned groupnumber,
    Dwarf_Handler errhand,
    Dwarf_Ptr errarg,
    Dwarf_Debug *dbg,Dwarf_Error *error)
{
    Dwarf_Obj_Access_Interface_a *binary_interface = 0;
    dwarf_macho_object_access_internals_t *intfc = 0;
    int res = DW_DLV_OK;
    int localerrnum = 0;
    unsigned universalbinary_count = 0;

    res = _dwarf_macho_object_access_init(
        fd,
        universalnumber,
        ftype,endian,offsetsize,
        &universalbinary_count,
        filesize,
        &binary_interface,
        &localerrnum);
    if (res != DW_DLV_OK) {
        if (res == DW_DLV_NO_ENTRY) {
            return res;
        }
        _dwarf_error(NULL, error, localerrnum);
        return DW_DLV_ERROR;
    }

    res = dwarf_object_init_b(binary_interface, errhand, errarg,
        groupnumber, dbg, error);
    if (res != DW_DLV_OK){
        _dwarf_destruct_macho_access(binary_interface);
        return res;
    }
    intfc = binary_interface->ai_object;
    intfc->mo_path = strdup(true_path);
    (*dbg)->de_obj_flags = intfc->mo_flags;
    (*dbg)->de_obj_machine = intfc->mo_machine;
    (*dbg)->de_universalbinary_index = universalnumber;
    (*dbg)->de_universalbinary_count = universalbinary_count;
    return res;
}


int
_dwarf_object_read_random(int fd, char *buf, Dwarf_Unsigned loc,
    Dwarf_Unsigned size, Dwarf_Unsigned filesize, int *errc)
{
    Dwarf_Unsigned endpoint = 0;
    int res = 0;

    if (loc >= filesize) {

        *errc = DW_DLE_SEEK_OFF_END;
        return DW_DLV_ERROR;
    }
    endpoint = loc+size;
    if (endpoint < loc) {

        *errc = DW_DLE_READ_OFF_END;
        return DW_DLV_ERROR;
    }
    if (endpoint > filesize) {

        *errc = DW_DLE_READ_OFF_END;
        return DW_DLV_ERROR;
    }
    res = _dwarf_seekr(fd,loc,SEEK_SET,0);
    if (res != DW_DLV_OK) {
        *errc = DW_DLE_SEEK_ERROR;
        return DW_DLV_ERROR;
    }
    res = _dwarf_readr(fd,buf,size,0);
    if (res != DW_DLV_OK) {
        *errc = DW_DLE_READ_ERROR;
        return DW_DLV_ERROR;
    }
    return DW_DLV_OK;
}


int
_dwarf_elf_nlsetup(int fd,
    char *true_path,
    unsigned ftype,
    unsigned endian,
    unsigned offsetsize,
    size_t filesize,
    unsigned groupnumber,
    Dwarf_Handler errhand,
    Dwarf_Ptr errarg,
    Dwarf_Debug *dbg,Dwarf_Error *error)
{
    Dwarf_Obj_Access_Interface_a *binary_interface = 0;
    dwarf_elf_object_access_internals_t *intfc = 0;
    int res = DW_DLV_OK;
    int localerrnum = 0;

    res = _dwarf_elf_object_access_init(
        fd,
        ftype,endian,offsetsize,filesize,
        &binary_interface,
        &localerrnum);
    if (res != DW_DLV_OK) {
        if (res == DW_DLV_NO_ENTRY) {
            return res;
        }
        _dwarf_error(NULL, error, localerrnum);
        return DW_DLV_ERROR;
    }

    res = dwarf_object_init_b(binary_interface, errhand, errarg,
        groupnumber, dbg, error);
    if (res != DW_DLV_OK){
        _dwarf_destruct_elf_nlaccess(binary_interface);
        return res;
    }
    intfc = binary_interface->ai_object;
    intfc->f_path = strdup(true_path);
    (*dbg)->de_obj_machine = intfc->f_machine;
    (*dbg)->de_obj_flags = intfc->f_flags;
    return res;
}


int
dwarf_crc32 (Dwarf_Debug dbg,unsigned char *crcbuf,
    Dwarf_Error *error)
{

    Dwarf_Unsigned   fsize = 0;

    Dwarf_Unsigned  readlenu = 10000;
    Dwarf_Unsigned  size_left = 0;
    const unsigned char *readbuf = 0;
    unsigned int   tcrc = 0;
    unsigned int   init = 0;
    int            fd = -1;
    Dwarf_Unsigned   sz = 0;
    int            res = 0;

    CHECK_DBG(dbg,error,"dwarf_crc32()");
    if (!crcbuf) {
        return DW_DLV_NO_ENTRY;
    }
    if (!dbg->de_owns_fd) {
        return DW_DLV_NO_ENTRY;
    }
    fd = dbg->de_fd;
    if (fd < 0) {
        return DW_DLV_NO_ENTRY;
    }
    fd = dbg->de_fd;
    if (dbg->de_filesize) {
        fsize = (size_t)dbg->de_filesize;
    } else {
        res = _dwarf_seekr(fd,0,SEEK_END,&sz);
        if (res != DW_DLV_OK) {
            _dwarf_error_string(dbg,error,DW_DLE_SEEK_ERROR,
                "DW_DLE_SEEK_ERROR: dwarf_crc32 seek "
                "to end fails");
            return DW_DLV_ERROR;
        }
        fsize = sz;
    }
    if (fsize <= (Dwarf_Unsigned)500) {

        return DW_DLV_NO_ENTRY;
    }
    size_left = fsize;
    res = _dwarf_seekr(fd,0,SEEK_SET,0);
    if (res != DW_DLV_OK) {
        _dwarf_error_string(dbg,error,DW_DLE_SEEK_ERROR,
            "DW_DLE_SEEK_ERROR: dwarf_crc32 seek "
            "to start fails");
        return DW_DLV_ERROR;
    }
    readbuf = (unsigned char *)malloc(readlenu);
    if (!readbuf) {
        _dwarf_error_string(dbg,error,DW_DLE_ALLOC_FAIL,
            "DW_DLE_ALLOC_FAIL: dwarf_crc32 read buffer"
            " alloc fails");
        return DW_DLV_ERROR;
    }
    while (size_left > 0) {
        if (size_left < readlenu) {
            readlenu = size_left;
        }
        res = _dwarf_readr(fd,(char *)readbuf,readlenu,0);
        if (res != DW_DLV_OK) {
            _dwarf_error_string(dbg,error,DW_DLE_READ_ERROR,
                "DW_DLE_READ_ERROR: dwarf_crc32 read fails ");
            free((unsigned char*)readbuf);
            return DW_DLV_ERROR;
        }

        tcrc = (unsigned int)dwarf_basic_crc32(readbuf,
            (unsigned long)readlenu,
            (unsigned long)init);
        init = tcrc;
        size_left -= readlenu;
    }

    free((unsigned char*)readbuf);
    memcpy(crcbuf,(void *)&tcrc,4);
    return DW_DLV_OK;
}

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 0x100000003


int
dwarf_get_debugfission_for_key(Dwarf_Debug dbg,
    Dwarf_Sig8  *key  ,
    const char  *key_type  ,
    Dwarf_Debug_Fission_Per_CU *  percu_out,
    Dwarf_Error *error)
{
    int sres = 0;
    Dwarf_Unsigned percu_index = 0;
    Dwarf_Xu_Index_Header xuhdr = 0;

    CHECK_DBG(dbg,error,"dwarf_get_debugfission_for_key()");
    if (!key || !key_type || !percu_out) {
        _dwarf_error_string(0,error,DW_DLE_XU_TYPE_ARG_ERROR,
            "DW_DLE_XU_TYPE_ARG_ERROR: dw_key, dw_keytype, or "
            "Dwarf_Debug_Fission_Per_CU pointer* to return "
            "is not valid");
        return DW_DLV_ERROR;
    }

    sres = _dwarf_load_debug_info(dbg,error);
    if (sres == DW_DLV_ERROR) {
        return sres;
    }
    sres = _dwarf_load_debug_types(dbg,error);
    if (sres == DW_DLV_ERROR) {
        return sres;
    }

    sres = _dwarf_get_xuhdr(dbg,key_type, &xuhdr,error);
    if (sres != DW_DLV_OK) {
        return sres;
    }

    sres = _dwarf_search_fission_for_key(dbg,
        xuhdr,key,&percu_index,error);
    if (sres != DW_DLV_OK) {
        return sres;
    }
    sres = transform_xu_to_dfp(xuhdr,percu_index,key,
        key_type,percu_out,error);
    return sres;
}


int
dwarf_formaddr(Dwarf_Attribute attr,
    Dwarf_Addr * return_addr, Dwarf_Error * error)
{
    Dwarf_Debug dbg = 0;
    Dwarf_Addr ret_addr = 0;
    Dwarf_CU_Context cu_context = 0;
    Dwarf_Half attrform = 0;
    int res = 0;

    res  = get_attr_dbg(&dbg,&cu_context,attr,error);
    if (res != DW_DLV_OK) {
        return res;
    }
    attrform = attr->ar_attribute_form;
    if (dwarf_addr_form_is_indexed(attrform)) {
        res = _dwarf_look_in_local_and_tied(
            attrform,
            cu_context,
            attr->ar_debug_ptr,
            return_addr,
            error);
        return res;
    }
    if (attrform == DW_FORM_addr ||
        (cu_context->cc_producer == CC_PROD_METROWERKS &&
        attrform == DW_FORM_ref_addr)

        ) {
        Dwarf_Small *section_end =
            _dwarf_calculate_info_section_end_ptr(cu_context);

        READ_UNALIGNED_CK(dbg, ret_addr, Dwarf_Addr,
            attr->ar_debug_ptr,
            cu_context->cc_address_size,
            error,section_end);
        *return_addr = ret_addr;
        return DW_DLV_OK;
    }
    generate_form_error(dbg,error,attrform,
        DW_DLE_ATTR_FORM_BAD,
        "DW_DLE_ATTR_FORM_BAD",
        "dwarf_formaddr");
    return DW_DLV_ERROR;
}


static int look_for_our_target(Dwarf_Debug dbg, struct target_data_s *td,
                               Dwarf_Error *errp) {
  Dwarf_Unsigned cu_header_length = 0;
  Dwarf_Unsigned abbrev_offset = 0;
  Dwarf_Half address_size = 0;
  Dwarf_Half version_stamp = 0;
  Dwarf_Half offset_size = 0;
  Dwarf_Half extension_size = 0;
  Dwarf_Unsigned typeoffset = 0;
  Dwarf_Half header_cu_type = unittype;
  Dwarf_Bool is_info = g_is_info;
  int cu_number = 0;

  for (;; ++cu_number) {
    Dwarf_Die no_die = 0;
    Dwarf_Die cu_die = 0;
    int res = DW_DLV_ERROR;
    Dwarf_Sig8 signature;

    memset(&signature, 0, sizeof(signature));
    res = dwarf_next_cu_header_d(dbg, is_info, &cu_header_length,
                                 &version_stamp, &abbrev_offset, &address_size,
                                 &offset_size, &extension_size, &signature,
                                 &typeoffset, 0, &header_cu_type, errp);
    if (res == DW_DLV_ERROR) {
      if (errp) {
        char *em = dwarf_errmsg(*errp);
      }
      return DW_DLV_NO_ENTRY;
    }
    if (res == DW_DLV_NO_ENTRY) {
      return DW_DLV_NO_ENTRY;
    }
    cu_version_stamp = version_stamp;
    cu_offset_size = offset_size;
    res = dwarf_siblingof_b(dbg, no_die, is_info, &cu_die, errp);
    if (res == DW_DLV_ERROR) {
      if (errp) {
        char *em = dwarf_errmsg(*errp);
      }
      return res;
    }
    if (res == DW_DLV_NO_ENTRY) {
      return res;
    }

    td->td_cu_die = cu_die;
    res = get_die_and_siblings(dbg, cu_die, is_info, 0, cu_number, td, errp);
    if (res == FOUND_SUBPROG) {
      read_line_data(dbg, td, errp);
      if (td->td_reportallfound) {
        return res;
      }
      return res;
    } else if (res == IN_THIS_CU) {
      if (errp) {
          char *em = dwarf_errmsg(*errp);
      }
      return res;
    } else if (res == DW_DLV_ERROR) {
      if (errp) {
        char *em = dwarf_errmsg(*errp);
      }
      return DW_DLV_ERROR;
    }
    return DW_DLV_NO_ENTRY;
  }
}


int EXPORT_CALL
lou_compileString(const char *tableList, const char *inString) {
	TranslationTableHeader *table;
	DisplayTableHeader *displayTable;
	getTable(tableList, tableList, &table, &displayTable);
	if (!table) return 0;
	if (!compileString(inString, &table, &displayTable)) return 0;
	return 1;
}


if (!compileString(inString, &table, &displayTable))


int burl_normalize (buffer *b, buffer *t, int flags)
{
    int qs;

  #if defined(_WIN32) || defined(__CYGWIN__)

    if (flags & HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS) {
        for (char *p = b->ptr; *p != '?' && *p != '\0'; ++p) {
            if (*p == '\\') *p = '/';
        }
    }
  #endif

    qs = (flags & HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED)
      ? burl_normalize_basic_required(b, t)
      : burl_normalize_basic_unreserved(b, t);
    if (-2 == qs) {
        if (flags & HTTP_PARSEOPT_URL_NORMALIZE_INVALID_UTF8_REJECT) return -2;
        qs = burl_scan_qmark(b);
    }

    if (flags & HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT) {
        if (burl_contains_ctrls(b)) return -2;
    }

    if (flags & (HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
                |HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT)) {
        qs = burl_normalize_2F_to_slash(b, qs, flags);
        if (-2 == qs) return -2;
    }

    if (flags & (HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
                |HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT)) {
        qs = burl_normalize_path(b, t, qs, flags);
        if (-2 == qs) return -2;
    }

    if (flags & HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS) {
        if (qs >= 0) burl_normalize_qs20_to_plus(b, qs);
    }

    return qs;
}


void
log_init(const char* filename, int use_syslog, const char* chrootdir)
{
	FILE *f;
	if(!key_created) {
		key_created = 1;
		ub_thread_key_create(&logkey, NULL);
		lock_basic_init(&log_lock);
	}
	lock_basic_lock(&log_lock);
	if(logfile
#if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
	|| logging_to_syslog
#endif
	) {
		lock_basic_unlock(&log_lock);
		verbose(VERB_QUERY, "switching log to %s",
			use_syslog?"syslog":(filename&&filename[0]?filename:"stderr"));
		lock_basic_lock(&log_lock);
	}
	if(logfile && logfile != stderr) {
		FILE* cl = logfile;
		logfile = NULL;
		fclose(cl);
	}
#ifdef HAVE_SYSLOG_H
	if(logging_to_syslog) {
		closelog();
		logging_to_syslog = 0;
	}
	if(use_syslog) {

		openlog(ident, LOG_NDELAY, UB_SYSLOG_FACILITY);
		logging_to_syslog = 1;
		lock_basic_unlock(&log_lock);
		return;
	}
#elif defined(UB_ON_WINDOWS)
	if(logging_to_syslog) {
		logging_to_syslog = 0;
	}
	if(use_syslog) {
		logging_to_syslog = 1;
		lock_basic_unlock(&log_lock);
		return;
	}
#endif
	if(!filename || !filename[0]) {
		logfile = stderr;
		lock_basic_unlock(&log_lock);
		return;
	}

	if(chrootdir && chrootdir[0] && strncmp(filename, chrootdir,
		strlen(chrootdir)) == 0)
		filename += strlen(chrootdir);
	f = fopen(filename, "a");
	if(!f) {
		lock_basic_unlock(&log_lock);
		log_err("Could not open logfile %s: %s", filename,
			strerror(errno));
		return;
	}
#ifndef UB_ON_WINDOWS

	setvbuf(f, NULL, (int)_IOLBF, 0);
#endif
	logfile = f;
	lock_basic_unlock(&log_lock);
}

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

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


void
log_nametypeclass(enum verbosity_value v, const char* str, uint8_t* name,
	uint16_t type, uint16_t dclass)
{
	char buf[LDNS_MAX_DOMAINLEN+1];
	char t[12], c[12];
	const char *ts, *cs;
	if(verbosity < v)
		return;
	dname_str(name, buf);
	if(type == LDNS_RR_TYPE_TSIG) ts = "TSIG";
	else if(type == LDNS_RR_TYPE_IXFR) ts = "IXFR";
	else if(type == LDNS_RR_TYPE_AXFR) ts = "AXFR";
	else if(type == LDNS_RR_TYPE_MAILB) ts = "MAILB";
	else if(type == LDNS_RR_TYPE_MAILA) ts = "MAILA";
	else if(type == LDNS_RR_TYPE_ANY) ts = "ANY";
	else if(sldns_rr_descript(type) && sldns_rr_descript(type)->_name)
		ts = sldns_rr_descript(type)->_name;
	else {
		snprintf(t, sizeof(t), "TYPE%d", (int)type);
		ts = t;
	}
	if(sldns_lookup_by_id(sldns_rr_classes, (int)dclass) &&
		sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name)
		cs = sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name;
	else {
		snprintf(c, sizeof(c), "CLASS%d", (int)dclass);
		cs = c;
	}
	log_info("%s %s %s %s", str, buf, ts, cs);
}


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


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 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");
	}
}


void ixmlElement_init(IXML_Element *element)
{
	if (element != NULL) {
		memset(element, 0, sizeof(IXML_Element));
	}
}

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


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);
}


errcode_t io_channel_alloc_buf(io_channel io, int count, void *ptr)
{
	size_t	size;

	if (count == 0)
		size = io->block_size;
	else if (count > 0)
		size = io->block_size * count;
	else
		size = -count;

	if (io->align > 0) {
		if ((unsigned) io->align > size)
			size = io->align;
		return ext2fs_get_memalign(size, io->align, ptr);
	} else
		return ext2fs_get_mem(size, ptr);
}