ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
static void adapter_remove_connection(struct btd_adapter *adapter,
						struct btd_device *device,
						uint8_t bdaddr_type)
{
	DBG("");

	if (!g_slist_find(adapter->connections, device)) {
		btd_error(adapter->dev_id, "No matching connection for device");
		return;
	}

	device_remove_connection(device, bdaddr_type);

	if (device_is_authenticating(device))
		device_cancel_authentication(device, TRUE);

	/* If another bearer is still connected */
	if (btd_device_is_connected(device))
		return;

	adapter->connections = g_slist_remove(adapter->connections, device);
}
static int check_btf_info(struct bpf_verifier_env *env,
			  const union bpf_attr *attr,
			  union bpf_attr __user *uattr)
{
	struct btf *btf;
	int err;

	if (!attr->func_info_cnt && !attr->line_info_cnt) {
		if (check_abnormal_return(env))
			return -EINVAL;
		return 0;
	}

	btf = btf_get_by_fd(attr->prog_btf_fd);
	if (IS_ERR(btf))
		return PTR_ERR(btf);
	env->prog->aux->btf = btf;

	err = check_btf_func(env, attr, uattr);
	if (err)
		return err;

	err = check_btf_line(env, attr, uattr);
	if (err)
		return err;

	return 0;
}
static int vxlan_tun_opt_from_nlattr(const struct nlattr *attr,
				     struct sw_flow_match *match, bool is_mask,
				     bool log)
{
	struct nlattr *a;
	int rem;
	unsigned long opt_key_offset;
	struct vxlan_metadata opts;

	BUILD_BUG_ON(sizeof(opts) > sizeof(match->key->tun_opts));

	memset(&opts, 0, sizeof(opts));
	nla_for_each_nested(a, attr, rem) {
		int type = nla_type(a);

		if (type > OVS_VXLAN_EXT_MAX) {
			OVS_NLERR(log, "VXLAN extension %d out of range max %d",
				  type, OVS_VXLAN_EXT_MAX);
			return -EINVAL;
		}

		if (!check_attr_len(nla_len(a),
				    ovs_vxlan_ext_key_lens[type].len)) {
			OVS_NLERR(log, "VXLAN extension %d has unexpected len %d expected %d",
				  type, nla_len(a),
				  ovs_vxlan_ext_key_lens[type].len);
			return -EINVAL;
		}

		switch (type) {
		case OVS_VXLAN_EXT_GBP:
			opts.gbp = nla_get_u32(a);
			break;
		default:
			OVS_NLERR(log, "Unknown VXLAN extension attribute %d",
				  type);
			return -EINVAL;
		}
	}
	if (rem) {
		OVS_NLERR(log, "VXLAN extension message has %d unknown bytes.",
			  rem);
		return -EINVAL;
	}

	if (!is_mask)
		SW_FLOW_KEY_PUT(match, tun_opts_len, sizeof(opts), false);
	else
		SW_FLOW_KEY_PUT(match, tun_opts_len, 0xff, true);

	opt_key_offset = TUN_METADATA_OFFSET(sizeof(opts));
	SW_FLOW_KEY_MEMCPY_OFFSET(match, opt_key_offset, &opts, sizeof(opts),
				  is_mask);
	return 0;
}
static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
{
	/*
	 * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
	 * vmx_flush_tlb_guest() for an explanation of why this is ok.
	 */
	vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
}
bool DataReaderImpl::lifespan_expired()
{
    std::unique_lock<RecursiveTimedMutex> lock(reader_->getMutex());

    CacheChange_t* earliest_change;
    while (history_.get_earliest_change(&earliest_change))
    {
        auto source_timestamp = system_clock::time_point() + nanoseconds(earliest_change->sourceTimestamp.to_ns());
        auto now = system_clock::now();

        // Check that the earliest change has expired (the change which started the timer could have been removed from the history)
        if (now - source_timestamp < lifespan_duration_us_)
        {
            auto interval = source_timestamp - now + lifespan_duration_us_;
            lifespan_timer_->update_interval_millisec(static_cast<double>(duration_cast<milliseconds>(interval).count()));
            return true;
        }

        // The earliest change has expired
        history_.remove_change_sub(earliest_change);

        // Set the timer for the next change if there is one
        if (!history_.get_earliest_change(&earliest_change))
        {
            return false;
        }

        // Calculate when the next change is due to expire and restart
        source_timestamp = system_clock::time_point() + nanoseconds(earliest_change->sourceTimestamp.to_ns());
        now = system_clock::now();
        auto interval = source_timestamp - now + lifespan_duration_us_;

        if (interval.count() > 0)
        {
            lifespan_timer_->update_interval_millisec(static_cast<double>(duration_cast<milliseconds>(interval).count()));
            return true;
        }
    }

    return false;
}
static void leave_lazy(enum paravirt_lazy_mode mode)
{
	BUG_ON(this_cpu_read(paravirt_lazy_mode) != mode);

	this_cpu_write(paravirt_lazy_mode, PARAVIRT_LAZY_NONE);
}
static void check_firejail_credentials(ProcessHandle process) {
	// open /proc/pid/status
	FILE *fp = process_fopen(process, "status");

	uid_t ruid = -1;
	uid_t suid = -1;
	char buf[4096];
	while (fgets(buf, sizeof(buf), fp)) {
		if (sscanf(buf, "Uid: %u %*u %u", &ruid, &suid) == 2)
			break;
	}
	fclose(fp);

	// target process should be privileged and owned by the user
	if (suid != 0)
		goto errexit;
	uid_t u = getuid();
	if (ruid != u && u != 0)
		goto errexit;

	return;

errexit:
	fprintf(stderr, "Error: no valid sandbox\n");
	exit(1);
}
GF_Err gnrv_box_write(GF_Box *s, GF_BitStream *bs)
{
	GF_Err e;
	GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s;

	//carefull we are not writing the box type but the entry type so switch for write
	ptr->type = ptr->EntryType;
	e = gf_isom_box_write_header(s, bs);
	if (e) return e;
	ptr->type = GF_ISOM_BOX_TYPE_GNRV;

	gf_isom_video_sample_entry_write((GF_VisualSampleEntryBox *)ptr, bs);
	gf_bs_write_data(bs,  ptr->data, ptr->data_size);
	return GF_OK;
}
static int rpciod_start(void)
{
	struct workqueue_struct *wq;

	/*
	 * Create the rpciod thread and wait for it to start.
	 */
	dprintk("RPC:       creating workqueue rpciod\n");
	wq = alloc_workqueue("rpciod", WQ_MEM_RECLAIM, 0);
	rpciod_workqueue = wq;
	return rpciod_workqueue != NULL;
}
static int propfind_maxsize(const xmlChar *name, xmlNsPtr ns,
			    struct propfind_ctx *fctx,
			    xmlNodePtr resp __attribute__((unused)),
			    struct propstat propstat[],
			    void *rock __attribute__((unused)))
{
    static int maxsize = 0;

    if (!fctx->req_tgt->collection) return HTTP_NOT_FOUND;

    if (!maxsize) {
	maxsize = config_getint(IMAPOPT_MAXMESSAGESIZE);
	if (!maxsize) maxsize = INT_MAX;
    }

    buf_reset(&fctx->buf);
    buf_printf(&fctx->buf, "%d", maxsize);
    xml_add_prop(HTTP_OK, fctx->ns[NS_DAV], &propstat[PROPSTAT_OK],
		 name, ns, BAD_CAST buf_cstring(&fctx->buf), 0);

    return 0;
}
static int edge_chars_in_buffer(struct tty_struct *tty)
{
	struct usb_serial_port *port = tty->driver_data;
	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
	int chars = 0;
	unsigned long flags;
	if (edge_port == NULL)
		return 0;

	spin_lock_irqsave(&edge_port->ep_lock, flags);
	chars = kfifo_len(&port->write_fifo);
	spin_unlock_irqrestore(&edge_port->ep_lock, flags);

	dev_dbg(&port->dev, "%s - returns %d\n", __func__, chars);
	return chars;
}
static void cmd_parse_enabled(struct ImapData *idata, const char *s)
{
  mutt_debug(2, "Handling ENABLED\n");

  while ((s = imap_next_word((char *) s)) && *s != '\0')
  {
    if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) ||
        (mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0))
    {
      idata->unicode = 1;
    }
  }
}
rboolop(PG_FUNCTION_ARGS)
{
	/* just reverse the operands */
	return DirectFunctionCall2(boolop,
							   PG_GETARG_DATUM(1),
							   PG_GETARG_DATUM(0));
}
void virtqueue_map_sg(struct iovec *sg, hwaddr *addr,
    size_t num_sg, int is_write)
{
    unsigned int i;
    hwaddr len;

    if (num_sg >= VIRTQUEUE_MAX_SIZE) {
        error_report("virtio: map attempt out of bounds: %zd > %d",
                     num_sg, VIRTQUEUE_MAX_SIZE);
        exit(1);
    }

    for (i = 0; i < num_sg; i++) {
        len = sg[i].iov_len;
        sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
        if (sg[i].iov_base == NULL || len != sg[i].iov_len) {
            error_report("virtio: trying to map MMIO memory");
            exit(1);
        }
    }
}
static void maybe_install_looping_handler(void)
  {
    /* Install looping handler before the write fault handler, so we    */
    /* handle write faults correctly.                                   */
    if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
      GC_set_and_save_fault_handler(looping_handler);
      installed_looping_handler = TRUE;
    }
  }
free_global_data(data_t * data)
{
	if (!data)
		return;

	free_list(&data->email);
#if HAVE_DECL_CLONE_NEWNET
	FREE_PTR(data->network_namespace);
#endif
	FREE_PTR(data->instance_name);
	FREE_PTR(data->router_id);
	FREE_PTR(data->email_from);
	FREE_PTR(data->smtp_helo_name);
	FREE_PTR(data->local_name);
#ifdef _WITH_SNMP_
	FREE_PTR(data->snmp_socket);
#endif
#if defined _WITH_LVS_ && defined _WITH_VRRP_
	FREE_PTR(data->lvs_syncd.ifname);
	FREE_PTR(data->lvs_syncd.vrrp_name);
#endif
	FREE_PTR(data->notify_fifo.name);
	free_notify_script(&data->notify_fifo.script);
#ifdef _WITH_VRRP_
	FREE_PTR(data->default_ifname);
	FREE_PTR(data->vrrp_notify_fifo.name);
	free_notify_script(&data->vrrp_notify_fifo.script);
#endif
#ifdef _WITH_LVS_
	FREE_PTR(data->lvs_notify_fifo.name);
	free_notify_script(&data->lvs_notify_fifo.script);
#endif
	FREE(data);
}
static void* local_LZ4_resetDictT(const char* fake)
{
    (void)fake;
    memset(&LZ4_dict, 0, sizeof(LZ4_stream_t));
    return NULL;
}
_gcry_mpi_point_new (unsigned int nbits)
{
  mpi_point_t p;

  (void)nbits;  /* Currently not used.  */

  p = xmalloc (sizeof *p);
  _gcry_mpi_point_init (p);
  return p;
}
tdbio_write_record( TRUSTREC *rec )
{
    byte buf[TRUST_RECORD_LEN], *p;
    int rc = 0;
    int i;
    ulong recnum = rec->recnum;

    if( db_fd == -1 )
	open_db();

    memset(buf, 0, TRUST_RECORD_LEN);
    p = buf;
    *p++ = rec->rectype; p++;
    switch( rec->rectype ) {
      case 0:  /* unused record */
	break;
      case RECTYPE_VER: /* version record */
	if( recnum )
	    BUG();
	memcpy(p-1, GPGEXT_GPG, 3 ); p += 2;
	*p++ = rec->r.ver.version;
	*p++ = rec->r.ver.marginals;
	*p++ = rec->r.ver.completes;
	*p++ = rec->r.ver.cert_depth;
	*p++ = rec->r.ver.trust_model;
	*p++ = rec->r.ver.min_cert_level;
	p += 2;
	ulongtobuf(p, rec->r.ver.created); p += 4;
	ulongtobuf(p, rec->r.ver.nextcheck); p += 4;
	p += 4;
	p += 4;
	ulongtobuf(p, rec->r.ver.firstfree ); p += 4;
	p += 4;
	ulongtobuf(p, rec->r.ver.trusthashtbl ); p += 4;
	break;

      case RECTYPE_FREE:
	ulongtobuf(p, rec->r.free.next); p += 4;
	break;


      case RECTYPE_HTBL:
	for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
	    ulongtobuf( p, rec->r.htbl.item[i]); p += 4;
	}
	break;

      case RECTYPE_HLST:
	ulongtobuf( p, rec->r.hlst.next); p += 4;
	for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
	    ulongtobuf( p, rec->r.hlst.rnum[i]); p += 4;
	}
	break;

      case RECTYPE_TRUST:
	memcpy( p, rec->r.trust.fingerprint, 20); p += 20;
	*p++ = rec->r.trust.ownertrust;
	*p++ = rec->r.trust.depth;
	*p++ = rec->r.trust.min_ownertrust;
        p++;
	ulongtobuf( p, rec->r.trust.validlist); p += 4;
	break;

      case RECTYPE_VALID:
	memcpy( p, rec->r.valid.namehash, 20); p += 20;
	*p++ = rec->r.valid.validity;
	ulongtobuf( p, rec->r.valid.next); p += 4;
	*p++ = rec->r.valid.full_count;
	*p++ = rec->r.valid.marginal_count;
	break;

      default:
	BUG();
    }

    rc = put_record_into_cache( recnum, buf );
    if( rc )
	;
    else if( rec->rectype == RECTYPE_TRUST )
	rc = update_trusthashtbl( rec );

    return rc;
}
void gf_av1_reset_state(AV1State *state, Bool is_destroy)
{
	GF_List *l1, *l2;

	if (state->frame_state.header_obus) {
		while (gf_list_count(state->frame_state.header_obus)) {
			GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.header_obus);
			if (a->obu) gf_free(a->obu);
			gf_free(a);
		}
	}

	if (state->frame_state.frame_obus) {
		while (gf_list_count(state->frame_state.frame_obus)) {
			GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.frame_obus);
			if (a->obu) gf_free(a->obu);
			gf_free(a);
		}
	}
	l1 = state->frame_state.frame_obus;
	l2 = state->frame_state.header_obus;
	memset(&state->frame_state, 0, sizeof(AV1StateFrame));
	state->frame_state.is_first_frame = GF_TRUE;

	if (is_destroy) {
		gf_list_del(l1);
		gf_list_del(l2);
		if (state->bs) {
			u32 size, asize=0;
			u8 *ptr=NULL;
			//detach BS internal buffer
			gf_bs_get_content_no_truncate(state->bs, &ptr, &size, &asize);
			//avoid double free, cf issue 1893
			if (ptr != state->frame_obus) {
				gf_free(ptr);
			}
			if (state->frame_obus) {
				gf_free(state->frame_obus);
				state->frame_obus = NULL;
				state->frame_obus_alloc = 0;
			}
			gf_bs_del(state->bs);
		}
		state->bs = NULL;
	}
	else {
		state->frame_state.frame_obus = l1;
		state->frame_state.header_obus = l2;
		if (state->bs)
			gf_bs_seek(state->bs, 0);
	}
}
WasmResult Context::defineMetric(MetricType type, absl::string_view name, uint32_t* metric_id_ptr) {
  auto stat_name = wasm_->stat_name_set_->getDynamic(name);
  if (type == MetricType::Counter) {
    auto id = wasm_->nextCounterMetricId();
    auto c = &wasm_->scope_->counterFromStatName(stat_name);
    wasm_->counters_.emplace(id, c);
    *metric_id_ptr = id;
    return WasmResult::Ok;
  } else if (type == MetricType::Gauge) {
    auto id = wasm_->nextGaugeMetricId();
    auto g = &wasm_->scope_->gaugeFromStatName(stat_name, Stats::Gauge::ImportMode::Accumulate);
    wasm_->gauges_.emplace(id, g);
    *metric_id_ptr = id;
    return WasmResult::Ok;
  } else if (type == MetricType::Histogram) {
    auto id = wasm_->nextHistogramMetricId();
    auto h = &wasm_->scope_->histogramFromStatName(stat_name, Stats::Histogram::Unit::Unspecified);
    wasm_->histograms_.emplace(id, h);
    *metric_id_ptr = id;
    return WasmResult::Ok;
  }
  return WasmResult::BadArgument;
}
draw_cmdline(int start, int len)
{
#if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
    int		i;

    if (cmdline_star > 0)
	for (i = 0; i < len; ++i)
	{
	    msg_putchar('*');
	    if (has_mbyte)
		i += (*mb_ptr2len)(ccline.cmdbuff + start + i) - 1;
	}
    else
#endif
#ifdef FEAT_ARABIC
	if (p_arshape && !p_tbidi && cmdline_has_arabic(start, len))
    {
	static int	buflen = 0;
	char_u		*p;
	int		j;
	int		newlen = 0;
	int		mb_l;
	int		pc, pc1 = 0;
	int		prev_c = 0;
	int		prev_c1 = 0;
	int		u8c;
	int		u8cc[MAX_MCO];
	int		nc = 0;

	/*
	 * Do arabic shaping into a temporary buffer.  This is very
	 * inefficient!
	 */
	if (len * 2 + 2 > buflen)
	{
	    // Re-allocate the buffer.  We keep it around to avoid a lot of
	    // alloc()/free() calls.
	    vim_free(arshape_buf);
	    buflen = len * 2 + 2;
	    arshape_buf = alloc(buflen);
	    if (arshape_buf == NULL)
		return;	// out of memory
	}

	if (utf_iscomposing(utf_ptr2char(ccline.cmdbuff + start)))
	{
	    // Prepend a space to draw the leading composing char on.
	    arshape_buf[0] = ' ';
	    newlen = 1;
	}

	for (j = start; j < start + len; j += mb_l)
	{
	    p = ccline.cmdbuff + j;
	    u8c = utfc_ptr2char_len(p, u8cc, start + len - j);
	    mb_l = utfc_ptr2len_len(p, start + len - j);
	    if (ARABIC_CHAR(u8c))
	    {
		// Do Arabic shaping.
		if (cmdmsg_rl)
		{
		    // displaying from right to left
		    pc = prev_c;
		    pc1 = prev_c1;
		    prev_c1 = u8cc[0];
		    if (j + mb_l >= start + len)
			nc = NUL;
		    else
			nc = utf_ptr2char(p + mb_l);
		}
		else
		{
		    // displaying from left to right
		    if (j + mb_l >= start + len)
			pc = NUL;
		    else
		    {
			int	pcc[MAX_MCO];

			pc = utfc_ptr2char_len(p + mb_l, pcc,
						      start + len - j - mb_l);
			pc1 = pcc[0];
		    }
		    nc = prev_c;
		}
		prev_c = u8c;

		u8c = arabic_shape(u8c, NULL, &u8cc[0], pc, pc1, nc);

		newlen += (*mb_char2bytes)(u8c, arshape_buf + newlen);
		if (u8cc[0] != 0)
		{
		    newlen += (*mb_char2bytes)(u8cc[0], arshape_buf + newlen);
		    if (u8cc[1] != 0)
			newlen += (*mb_char2bytes)(u8cc[1],
							arshape_buf + newlen);
		}
	    }
	    else
	    {
		prev_c = u8c;
		mch_memmove(arshape_buf + newlen, p, mb_l);
		newlen += mb_l;
	    }
	}

	msg_outtrans_len(arshape_buf, newlen);
    }
    else
#endif
	msg_outtrans_len(ccline.cmdbuff + start, len);
}
static int property_get_selinux_context(
                sd_bus *bus,
                const char *path,
                const char *interface,
                const char *property,
                sd_bus_message *reply,
                void *userdata,
                sd_bus_error *error) {

        ExecContext *c = userdata;

        assert(bus);
        assert(reply);
        assert(c);

        return sd_bus_message_append(reply, "(bs)", c->selinux_context_ignore, c->selinux_context);
}
static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
{
	struct vcpu_svm *svm = to_svm(vcpu);

	svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
	svm->vmcb->control.tsc_offset = offset;
	vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
}
static double mp_complex_pow_vv(_cimg_math_parser& mp) {
        const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1;
        double *ptrd = &_mp_arg(1) + 1;
        _mp_complex_pow(ptr1[0],ptr1[1],ptr2[0],ptr2[1],ptrd);
        return cimg::type<double>::nan();
static bool read_entry(RBuffer *b, ut64 addr, struct minidump_directory *entry) {
	st64 o_addr = r_buf_seek (b, 0, R_BUF_CUR);
	if (r_buf_seek (b, addr, R_BUF_SET) < 0) {
		return false;
	}
	entry->stream_type = r_buf_read_le32 (b);
	entry->location.data_size = r_buf_read_le32 (b);
	entry->location.rva = r_buf_read_le32 (b);
	r_buf_seek (b, o_addr, R_BUF_SET);
	return true;
}
static void DrawPathCurveToQuadraticBezierSmooth(DrawingWand *wand,
  const PathMode mode,const double x,const double y)
{
  assert(wand != (DrawingWand *) NULL);
  assert(wand->signature == MagickWandSignature);
  if (wand->debug != MagickFalse)
    (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name);
  if ((wand->path_operation != PathCurveToQuadraticBezierSmoothOperation) ||
      (wand->path_mode != mode))
    {
      wand->path_operation=PathCurveToQuadraticBezierSmoothOperation;
      wand->path_mode=mode;
      (void) MVGAutoWrapPrintf(wand,"%c%.20g %.20g",mode == AbsolutePathMode ?
        'T' : 't',x,y);
    }
  else
    (void) MVGAutoWrapPrintf(wand," %.20g %.20g",x,y);
}
on_launch_environment_session_exited (GdmLaunchEnvironment *launch_environment,
                                      int                   code,
                                      GdmDisplay           *self)
{
        g_debug ("GdmDisplay: Greeter exited: %d", code);
        self_destruct (self);
}
quick_random_gen( int onoff )
{
    int last;

    read_random_source(0,0,0); /* init */
    last = quick_test;
    if( onoff != -1 )
	quick_test = onoff;
    return faked_rng? 1 : last;
}
static void OnRxWindow2TimerEvent( void* context )
{
    // Check if we are processing Rx1 window.
    // If yes, we don't setup the Rx2 window.
    if( MacCtx.RxSlot == RX_SLOT_WIN_1 )
    {
        return;
    }
    MacCtx.RxWindow2Config.Channel = MacCtx.Channel;
    MacCtx.RxWindow2Config.Frequency = MacCtx.NvmCtx->MacParams.Rx2Channel.Frequency;
    MacCtx.RxWindow2Config.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime;
    MacCtx.RxWindow2Config.RxContinuous = false;
    MacCtx.RxWindow2Config.RxSlot = RX_SLOT_WIN_2;

    RxWindowSetup( &MacCtx.RxWindowTimer2, &MacCtx.RxWindow2Config );
}
RI_FKey_fk_upd_check_required(Trigger *trigger, Relation fk_rel,
							  HeapTuple old_row, HeapTuple new_row)
{
	const RI_ConstraintInfo *riinfo;

	/*
	 * Get arguments.
	 */
	riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);

	switch (riinfo->confmatchtype)
	{
		case FKCONSTR_MATCH_SIMPLE:

			/*
			 * If any new key value is NULL, the row must satisfy the
			 * constraint, so no check is needed.
			 */
			if (ri_NullCheck(new_row, riinfo, false) != RI_KEYS_NONE_NULL)
				return false;

			/*
			 * If the original row was inserted by our own transaction, we
			 * must fire the trigger whether or not the keys are equal.  This
			 * is because our UPDATE will invalidate the INSERT so that the
			 * INSERT RI trigger will not do anything; so we had better do the
			 * UPDATE check.  (We could skip this if we knew the INSERT
			 * trigger already fired, but there is no easy way to know that.)
			 */
			if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(old_row->t_data)))
				return true;

			/* If all old and new key values are equal, no check is needed */
			if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
				return false;

			/* Else we need to fire the trigger. */
			return true;

		case FKCONSTR_MATCH_FULL:

			/*
			 * If all new key values are NULL, the row must satisfy the
			 * constraint, so no check is needed.  On the other hand, if only
			 * some of them are NULL, the row must fail the constraint.  We
			 * must not throw error here, because the row might get
			 * invalidated before the constraint is to be checked, but we
			 * should queue the event to apply the check later.
			 */
			switch (ri_NullCheck(new_row, riinfo, false))
			{
				case RI_KEYS_ALL_NULL:
					return false;
				case RI_KEYS_SOME_NULL:
					return true;
				case RI_KEYS_NONE_NULL:
					break;		/* continue with the check */
			}

			/*
			 * If the original row was inserted by our own transaction, we
			 * must fire the trigger whether or not the keys are equal.  This
			 * is because our UPDATE will invalidate the INSERT so that the
			 * INSERT RI trigger will not do anything; so we had better do the
			 * UPDATE check.  (We could skip this if we knew the INSERT
			 * trigger already fired, but there is no easy way to know that.)
			 */
			if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(old_row->t_data)))
				return true;

			/* If all old and new key values are equal, no check is needed */
			if (ri_KeysEqual(fk_rel, old_row, new_row, riinfo, false))
				return false;

			/* Else we need to fire the trigger. */
			return true;

			/* Handle MATCH PARTIAL check. */
		case FKCONSTR_MATCH_PARTIAL:
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("MATCH PARTIAL not yet implemented")));
			break;

		default:
			elog(ERROR, "unrecognized confmatchtype: %d",
				 riinfo->confmatchtype);
			break;
	}

	/* Never reached */
	return false;
}
static void HeaderMapImplPopulate(benchmark::State& state) {
  const std::pair<LowerCaseString, std::string> headers_to_add[] = {
      {LowerCaseString("cache-control"), "max-age=0, private, must-revalidate"},
      {LowerCaseString("content-encoding"), "gzip"},
      {LowerCaseString("content-type"), "text/html; charset=utf-8"},
      {LowerCaseString("date"), "Wed, 23 Jan 2019 04:00:00 GMT"},
      {LowerCaseString("server"), "envoy"},
      {LowerCaseString("x-custom-header-1"), "example 1"},
      {LowerCaseString("x-custom-header-2"), "example 2"},
      {LowerCaseString("x-custom-header-3"), "example 3"},
      {LowerCaseString("set-cookie"), "_cookie1=12345678; path = /; secure"},
      {LowerCaseString("set-cookie"), "_cookie2=12345678; path = /; secure"},
  };
  for (auto _ : state) {
    HeaderMapImpl headers;
    for (const auto& key_value : headers_to_add) {
      headers.addReference(key_value.first, key_value.second);
    }
    benchmark::DoNotOptimize(headers.size());
  }
}
bgp_log_error(struct bgp_proto *p, u8 class, char *msg, uint code, uint subcode, byte *data, uint len)
{
  byte argbuf[256+16], *t = argbuf;
  uint i;

  /* Don't report Cease messages generated by myself */
  if (code == 6 && class == BE_BGP_TX)
    return;

  /* Reset shutdown message */
  if ((code == 6) && ((subcode == 2) || (subcode == 4)))
    proto_set_message(&p->p, NULL, 0);

  if (len)
    {
      /* Bad peer AS - we would like to print the AS */
      if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4)))
	{
	  t += bsprintf(t, ": %u", (len == 2) ? get_u16(data) : get_u32(data));
	  goto done;
	}

      /* RFC 8203 - shutdown communication */
      if (((code == 6) && ((subcode == 2) || (subcode == 4))))
	if (bgp_handle_message(p, data, len, &t))
	  goto done;

      *t++ = ':';
      *t++ = ' ';
      if (len > 16)
	len = 16;
      for (i=0; i<len; i++)
	t += bsprintf(t, "%02x", data[i]);
    }

done:
  *t = 0;
  const byte *dsc = bgp_error_dsc(code, subcode);
  log(L_REMOTE "%s: %s: %s%s", p->p.name, msg, dsc, argbuf);
}