ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
static void _sx_sasl_stream(sx_t s, sx_plugin_t p) {
    Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];

    /* do nothing the first time */
    if(sd == NULL)
        return;

    /* are we auth'd? */
    if(NULL == gsasl_property_fast(sd, GSASL_AUTHID)) {
        _sx_debug(ZONE, "not auth'd, not advancing to auth'd state yet");
        return;
    }

    /* otherwise, its auth time */
    _sx_sasl_open(s, sd);
}
static struct list_head *xt_get_idx(struct list_head *list, struct seq_file *seq, loff_t pos)
{
	struct list_head *head = list->next;

	if (!head || list_empty(list))
		return NULL;

	while (pos && (head = head->next)) {
		if (head == list)
			return NULL;
		pos--;
	}
	return pos ? NULL : head;
}
static const jpc_mstabent_t *jpc_mstab_lookup(int id)
{
	const jpc_mstabent_t *mstabent;
	for (mstabent = jpc_mstab;; ++mstabent) {
		if (mstabent->id == id || mstabent->id < 0) {
			return mstabent;
		}
	}
	assert(0);
	return 0;
}
static unsigned long emulator_get_cached_segment_base(int seg,
						      struct kvm_vcpu *vcpu)
{
	return get_segment_base(vcpu, seg);
}
var_redir_start(char_u *name, int append)
{
    int		called_emsg_before;
    typval_T	tv;

    // Catch a bad name early.
    if (!eval_isnamec1(*name))
    {
	emsg(_(e_invalid_argument));
	return FAIL;
    }

    // Make a copy of the name, it is used in redir_lval until redir ends.
    redir_varname = vim_strsave(name);
    if (redir_varname == NULL)
	return FAIL;

    if (alloc_redir_lval() == FAIL)
    {
	var_redir_stop();
	return FAIL;
    }

    // The output is stored in growarray "redir_ga" until redirection ends.
    init_redir_ga();

    // Parse the variable name (can be a dict or list entry).
    redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, 0,
							     FNE_CHECK_START);
    if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
    {
	clear_lval(redir_lval);
	if (redir_endp != NULL && *redir_endp != NUL)
	    // Trailing characters are present after the variable name
	    semsg(_(e_trailing_characters_str), redir_endp);
	else
	    semsg(_(e_invalid_argument_str), name);
	redir_endp = NULL;  // don't store a value, only cleanup
	var_redir_stop();
	return FAIL;
    }

    // check if we can write to the variable: set it to or append an empty
    // string
    called_emsg_before = called_emsg;
    tv.v_type = VAR_STRING;
    tv.vval.v_string = (char_u *)"";
    if (append)
	set_var_lval(redir_lval, redir_endp, &tv, TRUE,
					     ASSIGN_NO_DECL, (char_u *)".", 0);
    else
	set_var_lval(redir_lval, redir_endp, &tv, TRUE,
					     ASSIGN_NO_DECL, (char_u *)"=", 0);
    clear_lval(redir_lval);
    if (called_emsg > called_emsg_before)
    {
	redir_endp = NULL;  // don't store a value, only cleanup
	var_redir_stop();
	return FAIL;
    }

    return OK;
}
ZEND_METHOD(exception, __wakeup)
{
	zval *value;
	zval *object = getThis();
	HashTable *intern_ht = zend_std_get_properties(getThis() TSRMLS_CC);
	CHECK_EXC_TYPE("message", IS_STRING);
	CHECK_EXC_TYPE("string", IS_STRING);
	CHECK_EXC_TYPE("code", IS_LONG);
	CHECK_EXC_TYPE("file", IS_STRING);
	CHECK_EXC_TYPE("line", IS_LONG);
	CHECK_EXC_TYPE("trace", IS_ARRAY);
	CHECK_EXC_TYPE("previous", IS_OBJECT);
}
MagickExport void ConcatenateStringInfo(StringInfo *string_info,
  const StringInfo *source)
{
  size_t
    length;

  assert(string_info != (StringInfo *) NULL);
  assert(string_info->signature == MagickCoreSignature);
  assert(source != (const StringInfo *) NULL);
  length=string_info->length;
  if (~length < source->length)
    ThrowFatalException(ResourceLimitFatalError,"UnableToConcatenateString");
  SetStringInfoLength(string_info,length+source->length);
  (void) memcpy(string_info->datum+length,source->datum,source->length);
}
static int oidc_target_link_uri_matches_configuration(request_rec *r,
		oidc_cfg *cfg, const char *target_link_uri) {

	apr_uri_t o_uri;
	apr_uri_parse(r->pool, target_link_uri, &o_uri);
	if (o_uri.hostname == NULL) {
		oidc_error(r,
				"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
				target_link_uri);
		return FALSE;
	}

	apr_uri_t r_uri;
	apr_uri_parse(r->pool, cfg->redirect_uri, &r_uri);

	if (cfg->cookie_domain == NULL) {
		/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
		if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
			char *p = strstr(o_uri.hostname, r_uri.hostname);
			if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
				oidc_error(r,
						"the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
						r_uri.hostname, o_uri.hostname);
				return FALSE;
			}
		}
	} else {
		/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
		char *p = strstr(o_uri.hostname, cfg->cookie_domain);
		if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
			oidc_error(r,
					"the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
					cfg->cookie_domain, o_uri.hostname, target_link_uri);
			return FALSE;
		}
	}

	/* see if the cookie_path setting matches the target_link_uri path */
	char *cookie_path = oidc_cfg_dir_cookie_path(r);
	if (cookie_path != NULL) {
		char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
		if ((p == NULL) || (p != o_uri.path)) {
			oidc_error(r,
					"the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
					cfg->cookie_domain, o_uri.path, target_link_uri);
			return FALSE;
		} else if (strlen(o_uri.path) > strlen(cookie_path)) {
			int n = strlen(cookie_path);
			if (cookie_path[n - 1] == '/')
				n--;
			if (o_uri.path[n] != '/') {
				oidc_error(r,
						"the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
						cfg->cookie_domain, o_uri.path, target_link_uri);
				return FALSE;
			}
		}
	}
	return TRUE;
}
CalendarRegressionTest::Test4149677()
{
    UErrorCode status = U_ZERO_ERROR;

    TimeZone *zones [] = {
        TimeZone::createTimeZone("GMT"),
        TimeZone::createTimeZone("PST"),
        TimeZone::createTimeZone("EAT")
    };
    if(U_FAILURE(status)) {
        errln("Couldn't create zones");
        return;
        // could leak memory
    }

    for (int32_t i=0; i < 3; ++i) {
        GregorianCalendar *calendar = new GregorianCalendar(zones[i], status);
        if(U_FAILURE(status)) {
            dataerrln("Couldnt' create calendar.: %s", u_errorName(status));
            return;
        }

        // Make sure extreme values don't wrap around
        calendar->setTime(EARLIEST_SUPPORTED_MILLIS, status);
        if(U_FAILURE(status))
            errln("setTime failed");
        if (calendar->get(UCAL_ERA, status) != GregorianCalendar::BC || U_FAILURE(status)) {
            errln("Fail: Date(EARLIEST_SUPPORTED_MILLIS) has an AD year");
        }
        calendar->setTime(LATEST_SUPPORTED_MILLIS, status);
        if(U_FAILURE(status))
            errln("setTime failed");
        if (calendar->get(UCAL_ERA, status) != GregorianCalendar::AD || U_FAILURE(status)) {
            errln("Fail: Date(LATEST_SUPPORTED_MILLIS) has a BC year");
        }

        calendar->setGregorianChange(LATEST_SUPPORTED_MILLIS, status);
        if(U_FAILURE(status))
            errln("setGregorianChange failed");
        // to obtain a pure Julian calendar

        UBool is100Leap = calendar->isLeapYear(100);
        if (!is100Leap) {
            UnicodeString temp;
            errln("test failed with zone " + zones[i]->getID(temp));
            errln(" cutover date is Date(Long.MAX_VALUE)");
            errln(UnicodeString(" isLeapYear(100) returns: ") + is100Leap);
        }
        delete calendar;
    }

    // no need for cleanup- zones were adopted
}
static js_Ast *conditional(js_State *J, int notin)
{
	js_Ast *a, *b, *c;
	a = logor(J, notin);
	if (jsP_accept(J, '?')) {
		b = assignment(J, 0);
		jsP_expect(J, ':');
		c = assignment(J, notin);
		return EXP3(COND, a, b, c);
	}
	return a;
}
static int __f2fs_commit_super(struct buffer_head *bh,
			struct f2fs_super_block *super)
{
	lock_buffer(bh);
	if (super)
		memcpy(bh->b_data + F2FS_SUPER_OFFSET, super, sizeof(*super));
	set_buffer_uptodate(bh);
	set_buffer_dirty(bh);
	unlock_buffer(bh);

	/* it's rare case, we can do fua all the time */
	return __sync_dirty_buffer(bh, REQ_PREFLUSH | REQ_FUA);
}
static char *get_object_name(struct fsck_options *options, struct object *obj)
{
	if (!options->object_names)
		return NULL;
	return lookup_decoration(options->object_names, obj);
}
inline static int jas_fast32_asl(int_fast32_t x, int n)
{
	// Ensure that the shift of a negative value appears to behave as a
	// signed arithmetic shift.
	assert(((JAS_CAST(int_fast32_t, -1)) << 1) == JAS_CAST(int_fast32_t, -2));
	assert(n >= 0);
	// The behavior is undefined when x is negative. */
	// We tacitly assume the behavior is equivalent to a signed
	// arithmetic left shift.
	return x << n;
}
static int bus_append_mount_property(sd_bus_message *m, const char *field, const char *eq) {

        if (STR_IN_SET(field, "What", "Where", "Options", "Type"))

                return bus_append_string(m, field, eq);

        if (streq(field, "TimeoutSec"))

                return bus_append_parse_sec_rename(m, field, eq);

        if (streq(field, "DirectoryMode"))

                return bus_append_parse_mode(m, field, eq);

        if (STR_IN_SET(field, "SloppyOptions", "LazyUnmount", "ForceUnmount"))

                return bus_append_parse_boolean(m, field, eq);

        return 0;
}
void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget,
		       u64 nodeid, u64 nlookup)
{
	forget->forget_one.nodeid = nodeid;
	forget->forget_one.nlookup = nlookup;

	spin_lock(&fc->lock);
	fc->forget_list_tail->next = forget;
	fc->forget_list_tail = forget;
	wake_up(&fc->waitq);
	kill_fasync(&fc->fasync, SIGIO, POLL_IN);
	spin_unlock(&fc->lock);
}
TEST(IndexBoundsBuilderTest, TranslateExprEqualHashedIndex) {
    BSONObj keyPattern = fromjson("{a: 'hashed'}");
    BSONElement elt = keyPattern.firstElement();
    auto testIndex = buildSimpleIndexEntry(keyPattern);
    BSONObj obj = BSON("a" << BSON("$_internalExprEq" << 4));
    auto expr = parseMatchExpression(obj);
    OrderedIntervalList oil;
    IndexBoundsBuilder::BoundsTightness tightness;
    IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);

    BSONObj expectedHash = ExpressionMapping::hash(BSON("" << 4).firstElement());
    BSONObjBuilder intervalBuilder;
    intervalBuilder.append("", expectedHash.firstElement().numberLong());
    intervalBuilder.append("", expectedHash.firstElement().numberLong());
    BSONObj intervalObj = intervalBuilder.obj();

    ASSERT_EQUALS(oil.name, "a");
    ASSERT_EQUALS(oil.intervals.size(), 1U);
    ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
                  oil.intervals[0].compare(Interval(intervalObj, true, true)));
    ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
static void io_flush_timeouts(struct io_ring_ctx *ctx)
{
	u32 seq;

	if (list_empty(&ctx->timeout_list))
		return;

	seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);

	do {
		u32 events_needed, events_got;
		struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
						struct io_kiocb, timeout.list);

		if (io_is_timeout_noseq(req))
			break;

		/*
		 * Since seq can easily wrap around over time, subtract
		 * the last seq at which timeouts were flushed before comparing.
		 * Assuming not more than 2^31-1 events have happened since,
		 * these subtractions won't have wrapped, so we can check if
		 * target is in [last_seq, current_seq] by comparing the two.
		 */
		events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
		events_got = seq - ctx->cq_last_tm_flush;
		if (events_got < events_needed)
			break;

		list_del_init(&req->timeout.list);
		io_kill_timeout(req);
	} while (!list_empty(&ctx->timeout_list));

	ctx->cq_last_tm_flush = seq;
}
inline internal::NamedArgWithType<wchar_t, T> arg(WStringRef name, const T &arg) {
  return internal::NamedArgWithType<wchar_t, T>(name, arg);
}
Item *ha_maria::idx_cond_push(uint keyno_arg, Item* idx_cond_arg)
{
  /*
    Check if the key contains a blob field. If it does then MyISAM
    should not accept the pushed index condition since MyISAM will not
    read the blob field from the index entry during evaluation of the
    pushed index condition and the BLOB field might be part of the
    range evaluation done by the ICP code.
  */
  const KEY *key= &table_share->key_info[keyno_arg];

  for (uint k= 0; k < key->user_defined_key_parts; ++k)
  {
    const KEY_PART_INFO *key_part= &key->key_part[k];
    if (key_part->key_part_flag & HA_BLOB_PART)
    {
      /* Let the server handle the index condition */
      return idx_cond_arg;
    }
  }

  pushed_idx_cond_keyno= keyno_arg;
  pushed_idx_cond= idx_cond_arg;
  in_range_check_pushed_down= TRUE;
  if (active_index == pushed_idx_cond_keyno)
    ma_set_index_cond_func(file, handler_index_cond_check, this);
  return NULL;
}
bool TestMersenne()
{
	std::cout << "\nTesting Mersenne Twister...\n\n";

	static const unsigned int ENTROPY_SIZE = 32;
	bool pass = true, fail = false;

	// First 10; http://create.stephan-brumme.com/mersenne-twister/
	word32 result[10], expected[10] = {0xD091BB5C, 0x22AE9EF6,
		0xE7E1FAEE, 0xD5C31F79, 0x2082352C, 0xF807B7DF, 0xE9D30005,
		0x3895AFE1, 0xA1E24BBA, 0x4EE4092B};

	MT19937ar prng;
	prng.GenerateBlock(reinterpret_cast<byte*>(result), sizeof(result));
	fail = (0 != ::memcmp(result, expected, sizeof(expected)));

	pass &= !fail;
	if (fail)
		std::cout << "FAILED:";
	else
		std::cout << "passed:";
	std::cout << "  Expected sequence from MT19937ar (2002 version)\n";

	MeterFilter meter(new Redirector(TheBitBucket()));
	RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter)));

	fail = false;
	if (meter.GetTotalBytes() < 100000)
		fail = true;

	pass &= !fail;
	if (fail)
		std::cout << "FAILED:";
	else
		std::cout << "passed:";
	std::cout << "  100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n";

	try
	{
		fail = false;
		prng.DiscardBytes(100000);
	}
	catch (const Exception&)
	{
		fail = true;
	}

	pass &= !fail;
	if (fail)
		std::cout << "FAILED:";
	else
		std::cout << "passed:";
	std::cout << "  discarded 10000 bytes\n";

	try
	{
		fail = false;
		if(prng.CanIncorporateEntropy())
		{
			SecByteBlock entropy(ENTROPY_SIZE);
			GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes());

			prng.IncorporateEntropy(entropy, entropy.SizeInBytes());
			prng.IncorporateEntropy(entropy, entropy.SizeInBytes());
			prng.IncorporateEntropy(entropy, entropy.SizeInBytes());
			prng.IncorporateEntropy(entropy, entropy.SizeInBytes());
		}
	}
	catch (const Exception& /*ex*/)
	{
		fail = true;
	}

	pass &= !fail;
	if (fail)
		std::cout << "FAILED:";
	else
		std::cout << "passed:";
	std::cout << "  IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n";

	try
	{
		// Miscellaneous for code coverage
		(void)prng.AlgorithmName();
		word32 temp = prng.GenerateWord32();
		temp = prng.GenerateWord32((temp & 0xff), 0xffffffff - (temp & 0xff));
		prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 4);
		prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 3);
		prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 2);
		prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 1);
		prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 0);
		fail = false;
	}
	catch (const Exception&)
	{
		fail = true;
	}

	pass &= !fail;
	if (fail)
		std::cout << "FAILED:";
	else
		std::cout << "passed:";
	std::cout << "  GenerateWord32 and Crop\n";

	std::cout.flush();
	return pass;
}
static ssize_t iter_xarray_get_pages_alloc(struct iov_iter *i,
					   struct page ***pages, size_t maxsize,
					   size_t *_start_offset)
{
	struct page **p;
	unsigned nr, offset;
	pgoff_t index, count;
	size_t size = maxsize, actual;
	loff_t pos;

	if (!size)
		return 0;

	pos = i->xarray_start + i->iov_offset;
	index = pos >> PAGE_SHIFT;
	offset = pos & ~PAGE_MASK;
	*_start_offset = offset;

	count = 1;
	if (size > PAGE_SIZE - offset) {
		size -= PAGE_SIZE - offset;
		count += size >> PAGE_SHIFT;
		size &= ~PAGE_MASK;
		if (size)
			count++;
	}

	p = get_pages_array(count);
	if (!p)
		return -ENOMEM;
	*pages = p;

	nr = iter_xarray_populate_pages(p, i->xarray, index, count);
	if (nr == 0)
		return 0;

	actual = PAGE_SIZE * nr;
	actual -= offset;
	if (nr == count && size > 0) {
		unsigned last_offset = (nr > 1) ? 0 : offset;
		actual -= PAGE_SIZE - (last_offset + size);
	}
	return actual;
}
get_password_from_file(int file_descript, char *filename,
		       struct parsed_mount_info *parsed_info, const char *program)
{
	int rc = 0;
	char buf[sizeof(parsed_info->password) + 1];

	if (filename != NULL) {
		rc = toggle_dac_capability(0, 1);
		if (rc)
			return rc;

		rc = access(filename, R_OK);
		if (rc) {
			fprintf(stderr,
				"%s failed: access check of %s failed: %s\n",
				program, filename, strerror(errno));
			toggle_dac_capability(0, 0);
			return EX_SYSERR;
		}

		file_descript = open(filename, O_RDONLY);
		if (file_descript < 0) {
			fprintf(stderr,
				"%s failed. %s attempting to open password file %s\n",
				program, strerror(errno), filename);
			toggle_dac_capability(0, 0);
			return EX_SYSERR;
		}

		rc = toggle_dac_capability(0, 0);
		if (rc) {
			rc = EX_SYSERR;
			goto get_pw_exit;
		}
	}

	memset(buf, 0, sizeof(buf));
	rc = read(file_descript, buf, sizeof(buf) - 1);
	if (rc < 0) {
		fprintf(stderr,
			"%s failed. Error %s reading password file\n",
			program, strerror(errno));
		rc = EX_SYSERR;
		goto get_pw_exit;
	}

	rc = set_password(parsed_info, buf);

get_pw_exit:
	if (filename != NULL)
		close(file_descript);
	return rc;
}
static void free_fence_locked(struct vrend_fence *fence)
{
   list_del(&fence->fences);
#ifdef HAVE_EPOXY_EGL_H
   if (vrend_state.use_egl_fence) {
      virgl_egl_fence_destroy(egl, fence->eglsyncobj);
   } else
#endif
   {
      glDeleteSync(fence->glsyncobj);
   }
   free(fence);
}
dwarf_formdata16(Dwarf_Attribute attr,
    Dwarf_Form_Data16  * returned_val,
    Dwarf_Error*     error)
{
    Dwarf_Half attrform = 0;
    Dwarf_CU_Context cu_context = 0;
    Dwarf_Debug dbg = 0;
    int res  = 0;
    Dwarf_Small *section_end = 0;
    Dwarf_Unsigned section_length = 0;
    Dwarf_Small *section_start = 0;

    if (!attr) {
        _dwarf_error(NULL, error, DW_DLE_ATTR_NULL);
        return DW_DLV_ERROR;
    }
    if (!returned_val ) {
        _dwarf_error(NULL, error, DW_DLE_ATTR_NULL);
        return DW_DLV_ERROR;
    }
    res  = get_attr_dbg(&dbg,&cu_context,attr,error);
    if (res != DW_DLV_OK) {
        return res;
    }
    attrform = attr->ar_attribute_form;
    if (attrform != DW_FORM_data16) {
        generate_form_error(dbg,error,attrform,
            DW_DLE_ATTR_FORM_BAD,
            "DW_DLE_ATTR_FORM_BAD",
            "dwarf_formdata16");
        return DW_DLV_ERROR;
    }
    section_start = _dwarf_calculate_info_section_start_ptr(
        cu_context,&section_length);
    section_end = section_start + section_length;

    res = _dwarf_extract_data16(dbg, attr->ar_debug_ptr,
        section_start, section_end,
        returned_val,  error);
    return res;
}
longlong Item::val_int_from_str(int *error)
{
  char buff[MAX_FIELD_WIDTH];
  String tmp(buff,sizeof(buff), &my_charset_bin), *res;

  /*
    For a string result, we must first get the string and then convert it
    to a longlong
  */

  if (!(res= val_str(&tmp)))
  {
    *error= 0;
    return 0;
  }
  Converter_strtoll10_with_warn cnv(NULL, Warn_filter_all(),
                                    res->charset(), res->ptr(), res->length());
  *error= cnv.error();
  return cnv.result();
}
ecdsa_in_range (const struct ecc_curve *ecc, const mp_limb_t *xp)
{
  return !mpn_zero_p (xp, ecc->p.size)
    && mpn_cmp (xp, ecc->q.m, ecc->p.size) < 0;
}
bool maybe_stream_body(JSContext *cx, HandleObject body_owner, bool *requires_streaming) {
  RootedObject stream(cx, RequestOrResponse::body_stream(body_owner));
  if (!stream) {
    return true;
  }

  if (RequestOrResponse::body_unusable(cx, stream)) {
    // TODO: Improve this message; `disturbed` is probably too spec-internal a
    // term.
    JS_ReportErrorUTF8(cx, "Can't send a body stream that's locked or disturbed");
    return false;
  }

  // If the body stream is backed by a C@E body handle, we can directly pipe
  // that handle into the body we're about to send.
  if (builtins::NativeStreamSource::stream_is_body(cx, stream)) {
    // First, move the source's body handle to the target and lock the stream.
    RootedObject stream_source(cx, builtins::NativeStreamSource::get_stream_source(cx, stream));
    RootedObject source_owner(cx, builtins::NativeStreamSource::owner(stream_source));
    if (!RequestOrResponse::move_body_handle(cx, source_owner, body_owner)) {
      return false;
    }

    // Then, send the request/response without streaming. We know that content
    // won't append to this body handle, because we don't expose any means to do
    // so, so it's ok for it to be closed immediately.
    return true;
  }

  RootedObject reader(
      cx, JS::ReadableStreamGetReader(cx, stream, JS::ReadableStreamReaderMode::Default));
  if (!reader)
    return false;

  bool is_closed;
  if (!JS::ReadableStreamReaderIsClosed(cx, reader, &is_closed))
    return false;

  // It's ok for the stream to be closed, as its contents might
  // already have fully been written to the body handle.
  // In that case, we can do a blocking send instead.
  if (is_closed) {
    return true;
  }

  // Create handlers for both `then` and `catch`.
  // These are functions with two reserved slots, in which we store all
  // information required to perform the reactions. We store the actually
  // required information on the catch handler, and a reference to that on the
  // then handler. This allows us to reuse these functions for the next read
  // operation in the then handler. The catch handler won't ever have a need to
  // perform another operation in this way.
  RootedObject catch_handler(cx);
  RootedValue extra(cx, ObjectValue(*reader));
  catch_handler = create_internal_method<body_reader_catch_handler>(cx, body_owner, extra);
  if (!catch_handler)
    return false;

  RootedObject then_handler(cx);
  extra.setObject(*catch_handler);
  then_handler = create_internal_method<body_reader_then_handler>(cx, body_owner, extra);
  if (!then_handler)
    return false;

  RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, reader));
  if (!promise)
    return false;
  if (!JS::AddPromiseReactions(cx, promise, then_handler, catch_handler))
    return false;

  *requires_streaming = true;
  return true;
}