ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
static NOINLINE void read_leases(const char *file)
{
	struct dyn_lease lease;
	int64_t written_at, time_passed;
	int fd;
#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
	unsigned i = 0;
#endif

	fd = open_or_warn(file, O_RDONLY);
	if (fd < 0)
		return;

	if (full_read(fd, &written_at, sizeof(written_at)) != sizeof(written_at))
		goto ret;
	written_at = SWAP_BE64(written_at);

	time_passed = time(NULL) - written_at;
	/* Strange written_at, or lease file from old version of udhcpd
	 * which had no "written_at" field? */
	if ((uint64_t)time_passed > 12 * 60 * 60)
		goto ret;

	while (full_read(fd, &lease, sizeof(lease)) == sizeof(lease)) {
		uint32_t y = ntohl(lease.lease_nip);
		if (y >= server_config.start_ip && y <= server_config.end_ip) {
			signed_leasetime_t expires = ntohl(lease.expires) - (signed_leasetime_t)time_passed;
			uint32_t static_nip;

			if (expires <= 0)
				/* We keep expired leases: add_lease() will add
				 * a lease with 0 seconds remaining.
				 * Fewer IP address changes this way for mass reboot scenario.
				 */
				expires = 0;

			/* Check if there is a different static lease for this IP or MAC */
			static_nip = get_static_nip_by_mac(server_config.static_leases, lease.lease_mac);
			if (static_nip) {
				/* NB: we do not add lease even if static_nip == lease.lease_nip.
				 */
				continue;
			}
			if (is_nip_reserved(server_config.static_leases, lease.lease_nip))
				continue;

			/* NB: add_lease takes "relative time", IOW,
			 * lease duration, not lease deadline. */
			if (add_lease(lease.lease_mac, lease.lease_nip,
					expires,
					lease.hostname, sizeof(lease.hostname)
				) == 0
			) {
				bb_error_msg("too many leases while loading %s", file);
				break;
			}
#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
			i++;
#endif
		}
	}
	log1("read %d leases", i);
 ret:
	close(fd);
}
registerForm(Buffer *buf, FormList *flist, struct parsed_tag *tag, int line,
	     int pos)
{
    Anchor *a;
    FormItemList *fi;

    fi = formList_addInput(flist, tag);
    if (fi == NULL)
	return NULL;
    buf->formitem = putAnchor(buf->formitem, (char *)fi, flist->target, &a,
			      NULL, NULL, '\0', line, pos);
    return a;
}
MagickPrivate void ReleaseOpenCLMemObject(cl_mem memobj)
{
  (void) openCL_library->clReleaseMemObject(memobj);
}
get_counters(const struct xt_table_info *t,
	     struct xt_counters counters[])
{
	struct ip6t_entry *iter;
	unsigned int cpu;
	unsigned int i;

	for_each_possible_cpu(cpu) {
		seqcount_t *s = &per_cpu(xt_recseq, cpu);

		i = 0;
		xt_entry_foreach(iter, t->entries, t->size) {
			struct xt_counters *tmp;
			u64 bcnt, pcnt;
			unsigned int start;

			tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
			do {
				start = read_seqcount_begin(s);
				bcnt = tmp->bcnt;
				pcnt = tmp->pcnt;
			} while (read_seqcount_retry(s, start));

			ADD_COUNTER(counters[i], bcnt, pcnt);
			++i;
			cond_resched();
		}
	}
}
static inline bool queue_pages_required(struct page *page,
					struct queue_pages *qp)
{
	int nid = page_to_nid(page);
	unsigned long flags = qp->flags;

	return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
}
fastrtps::TopicAttributes DataReaderImpl::topic_attributes() const
{
    fastrtps::TopicAttributes topic_att;
    topic_att.topicKind = type_->m_isGetKeyDefined ? WITH_KEY : NO_KEY;
    topic_att.topicName = topic_->get_name();
    topic_att.topicDataType = topic_->get_type_name();
    topic_att.historyQos = qos_.history();
    topic_att.resourceLimitsQos = qos_.resource_limits();
    if (type_->type_object())
    {
        topic_att.type = *type_->type_object();
    }
    if (type_->type_identifier())
    {
        topic_att.type_id = *type_->type_identifier();
    }
    if (type_->type_information())
    {
        topic_att.type_information = *type_->type_information();
    }
    topic_att.auto_fill_type_object = type_->auto_fill_type_object();
    topic_att.auto_fill_type_information = type_->auto_fill_type_information();

    return topic_att;
}
static bool tg3_test_and_report_link_chg(struct tg3 *tp, int curr_link_up)
{
	if (curr_link_up != tp->link_up) {
		if (curr_link_up) {
			netif_carrier_on(tp->dev);
		} else {
			netif_carrier_off(tp->dev);
			if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
				tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
		}

		tg3_link_report(tp);
		return true;
	}

	return false;
}
Locked_tables_list::reopen_tables(THD *thd, bool need_reopen)
{
  Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
  uint reopen_count= 0;
  MYSQL_LOCK *lock;
  MYSQL_LOCK *merged_lock;
  DBUG_ENTER("Locked_tables_list::reopen_tables");

  DBUG_ASSERT(some_table_marked_for_reopen || !need_reopen);


  /* Reset flag that some table was marked for reopen */
  some_table_marked_for_reopen= 0;

  for (TABLE_LIST *table_list= m_locked_tables;
       table_list; table_list= table_list->next_global)
  {
    if (need_reopen)
    {
      if (!table_list->table || !table_list->table->needs_reopen())
        continue;
      for (TABLE **prev= &thd->open_tables; *prev; prev= &(*prev)->next)
      {
        if (*prev == table_list->table)
        {
          thd->locked_tables_list.unlink_from_list(thd, table_list, false);
          mysql_lock_remove(thd, thd->lock, *prev);
          (*prev)->file->extra(HA_EXTRA_PREPARE_FOR_FORCED_CLOSE);
          close_thread_table(thd, prev);
          break;
        }
      }
      DBUG_ASSERT(table_list->table == NULL);
    }
    else
    {
      if (table_list->table)                      /* The table was not closed */
        continue;
    }

    DBUG_ASSERT(reopen_count < m_locked_tables_count);
    m_reopen_array[reopen_count++]= table_list;
  }
  if (reopen_count)
  {
    TABLE **tables= (TABLE**) my_alloca(reopen_count * sizeof(TABLE*));

    for (uint i= 0 ; i < reopen_count ; i++)
    {
      TABLE_LIST *table_list= m_reopen_array[i];
      /* Links into thd->open_tables upon success */
      if (open_table(thd, table_list, &ot_ctx))
      {
        unlink_all_closed_tables(thd, 0, i);
        my_afree((void*) tables);
        DBUG_RETURN(TRUE);
      }
      tables[i]= table_list->table;
      table_list->table->pos_in_locked_tables= table_list;
      /* See also the comment on lock type in init_locked_tables(). */
      table_list->table->reginfo.lock_type= table_list->lock_type;
    }

    thd->in_lock_tables= 1;
    /*
      We re-lock all tables with mysql_lock_tables() at once rather
      than locking one table at a time because of the case
      reported in Bug#45035: when the same table is present
      in the list many times, thr_lock.c fails to grant READ lock
      on a table that is already locked by WRITE lock, even if
      WRITE lock is taken by the same thread. If READ and WRITE
      lock are passed to thr_lock.c in the same list, everything
      works fine. Patching legacy code of thr_lock.c is risking to
      break something else.
    */
    lock= mysql_lock_tables(thd, tables, reopen_count,
                            MYSQL_OPEN_REOPEN | MYSQL_LOCK_USE_MALLOC);
    thd->in_lock_tables= 0;
    if (lock == NULL || (merged_lock=
                         mysql_lock_merge(thd->lock, lock)) == NULL)
    {
      unlink_all_closed_tables(thd, lock, reopen_count);
      if (! thd->killed)
        my_error(ER_LOCK_DEADLOCK, MYF(0));
      my_afree((void*) tables);
      DBUG_RETURN(TRUE);
    }
    thd->lock= merged_lock;
    my_afree((void*) tables);
  }
  DBUG_RETURN(FALSE);
}
static void handle_init_section_args(struct init_section_info *info, const char *key,
                                           int key_len, char **dest, int *dest_len)
{
    if (!strncmp(key, "URI=", key_len)) {
        *dest     =        info->uri;
        *dest_len = sizeof(info->uri);
    } else if (!strncmp(key, "BYTERANGE=", key_len)) {
        *dest     =        info->byterange;
        *dest_len = sizeof(info->byterange);
    }
}
Status AuthorizationManager::getUserDescription(OperationContext* opCtx,
                                                const UserName& userName,
                                                BSONObj* result) {
    return _externalState->getUserDescription(opCtx, userName, result);
}
skip_space(struct table *t, char *line, struct table_linfo *linfo,
	   int checkminimum)
{
    int skip = 0, s = linfo->prev_spaces;
    Lineprop ctype, prev_ctype = linfo->prev_ctype;
    Str prevchar = linfo->prevchar;
    int w = linfo->length;
    int min = 1;

    if (*line == '<' && line[strlen(line) - 1] == '>') {
	if (checkminimum)
	    check_minimum0(t, visible_length(line));
	return 0;
    }

    while (*line) {
	char *save = line, *c = line;
	int ec, len, wlen, plen;
	ctype = get_mctype(line);
	len = get_mcwidth(line);
	wlen = plen = get_mclen(line);

	if (min < w)
	    min = w;
	if (ctype == PC_ASCII && IS_SPACE(*c)) {
	    w = 0;
	    s++;
	}
	else {
	    if (*c == '&') {
		ec = getescapechar(&line);
		if (ec >= 0) {
		    c = conv_entity(ec);
		    ctype = get_mctype(c);
		    len = get_strwidth(c);
		    wlen = line - save;
		    plen = get_mclen(c);
		}
	    }
	    if (prevchar->length && is_boundary((unsigned char *)prevchar->ptr,
						(unsigned char *)c)) {
		w = len;
	    }
	    else {
		w += len;
	    }
	    if (s > 0) {
#ifdef USE_M17N
		if (ctype == PC_KANJI1 && prev_ctype == PC_KANJI1)
		    skip += s;
		else
#endif
		    skip += s - 1;
	    }
	    s = 0;
	    prev_ctype = ctype;
	}
	set_prevchar(prevchar, c, plen);
	line = save + wlen;
    }
    if (s > 1) {
	skip += s - 1;
	linfo->prev_spaces = 1;
    }
    else {
	linfo->prev_spaces = s;
    }
    linfo->prev_ctype = prev_ctype;
    linfo->prevchar = prevchar;

    if (checkminimum) {
	if (min < w)
	    min = w;
	linfo->length = w;
	check_minimum0(t, min);
    }
    return skip;
}
char* formatBytes(u_int32_t howMuch, char *buf, u_int buf_len) {
  char unit = 'B';

  if(howMuch < 1024) {
    snprintf(buf, buf_len, "%lu %c", (unsigned long)howMuch, unit);
  } else if(howMuch < (1024*1024)) {
    snprintf(buf, buf_len, "%.2f K%c", (float)(howMuch)/1024, unit);
  } else {
    float tmpGB = ((float)howMuch)/(1024*1024);

    if(tmpGB < 1024) {
      snprintf(buf, buf_len, "%.2f M%c", tmpGB, unit);
    } else {
      tmpGB /= 1024;

      snprintf(buf, buf_len, "%.2f G%c", tmpGB, unit);
    }
  }

  return(buf);
}
static int h2c_send_window_update(struct h2c *h2c, int sid, uint32_t increment)
{
	struct buffer *res;
	char str[13];
	int ret = -1;

	if (h2c_mux_busy(h2c, NULL)) {
		h2c->flags |= H2_CF_DEM_MBUSY;
		return 0;
	}

	res = h2_get_buf(h2c, &h2c->mbuf);
	if (!res) {
		h2c->flags |= H2_CF_MUX_MALLOC;
		h2c->flags |= H2_CF_DEM_MROOM;
		return 0;
	}

	/* length: 4, type: 8, flags: none */
	memcpy(str, "\x00\x00\x04\x08\x00", 5);
	write_n32(str + 5, sid);
	write_n32(str + 9, increment);

	ret = b_istput(res, ist2(str, 13));

	if (unlikely(ret <= 0)) {
		if (!ret) {
			h2c->flags |= H2_CF_MUX_MFULL;
			h2c->flags |= H2_CF_DEM_MROOM;
			return 0;
		}
		else {
			h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
			return 0;
		}
	}
	return ret;
}
TEST_F(TcpHealthCheckerImplTest, PassiveFailure) {
  InSequence s;

  setupNoData();
  cluster_->prioritySet().getMockHostSet(0)->hosts_ = {
      makeTestHost(cluster_->info_, "tcp://127.0.0.1:80", simTime())};
  expectSessionCreate();
  expectClientCreate();
  EXPECT_CALL(*connection_, write(_, _)).Times(0);
  EXPECT_CALL(*timeout_timer_, enableTimer(_, _));
  EXPECT_CALL(event_logger_, logEjectUnhealthy(_, _, _));
  EXPECT_CALL(event_logger_, logUnhealthy(_, _, _, true));
  health_checker_->start();

  // Do multiple passive failures. This will not reset the active HC timers.
  cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthChecker().setUnhealthy(
      HealthCheckHostMonitor::UnhealthyType::ImmediateHealthCheckFail);
  cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthChecker().setUnhealthy(
      HealthCheckHostMonitor::UnhealthyType::ImmediateHealthCheckFail);
  EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet(
      Host::HealthFlag::FAILED_ACTIVE_HC));
  EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet(
      Host::HealthFlag::EXCLUDED_VIA_IMMEDIATE_HC_FAIL));
  EXPECT_EQ(Host::Health::Unhealthy,
            cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->health());

  // A single success should not bring us back to healthy.
  EXPECT_CALL(*connection_, close(_));
  EXPECT_CALL(*timeout_timer_, disableTimer());
  EXPECT_CALL(*interval_timer_, enableTimer(_, _));
  connection_->raiseEvent(Network::ConnectionEvent::Connected);
  EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet(
      Host::HealthFlag::FAILED_ACTIVE_HC));
  EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet(
      Host::HealthFlag::EXCLUDED_VIA_IMMEDIATE_HC_FAIL));
  EXPECT_EQ(Host::Health::Unhealthy,
            cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->health());

  // Bring back to healthy and check flag clearing.
  expectClientCreate();
  EXPECT_CALL(*timeout_timer_, enableTimer(_, _));
  interval_timer_->invokeCallback();

  EXPECT_CALL(*connection_, close(_));
  EXPECT_CALL(event_logger_, logAddHealthy(_, _, false));
  EXPECT_CALL(*timeout_timer_, disableTimer());
  EXPECT_CALL(*interval_timer_, enableTimer(_, _));
  connection_->raiseEvent(Network::ConnectionEvent::Connected);
  EXPECT_FALSE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet(
      Host::HealthFlag::FAILED_ACTIVE_HC));
  EXPECT_FALSE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet(
      Host::HealthFlag::EXCLUDED_VIA_IMMEDIATE_HC_FAIL));
  EXPECT_EQ(Host::Health::Healthy, cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->health());

  EXPECT_EQ(2UL, cluster_->info_->stats_store_.counter("health_check.attempt").value());
  EXPECT_EQ(2UL, cluster_->info_->stats_store_.counter("health_check.success").value());
  EXPECT_EQ(2UL, cluster_->info_->stats_store_.counter("health_check.failure").value());
  EXPECT_EQ(2UL, cluster_->info_->stats_store_.counter("health_check.passive_failure").value());
}
colon_strtime (u32 t)
{
  static char buf[20];

  if (!t)
    return "";
  snprintf (buf, sizeof buf, "%lu", (ulong)t);
  return buf;
}
static int _crypt_format_integrity(struct crypt_device *cd,
				   const char *uuid,
				   struct crypt_params_integrity *params)
{
	int r;
	uint32_t integrity_tag_size;
	char *integrity = NULL, *journal_integrity = NULL, *journal_crypt = NULL;
	struct volume_key *journal_crypt_key = NULL, *journal_mac_key = NULL;

	if (!params)
		return -EINVAL;

	if (uuid) {
		log_err(cd, _("UUID is not supported for this crypt type."));
		return -EINVAL;
	}

	r = device_check_access(cd, crypt_metadata_device(cd), DEV_EXCL);
	if (r < 0)
		return r;

	/* Wipe first 8 sectors - fs magic numbers etc. */
	r = crypt_wipe_device(cd, crypt_metadata_device(cd), CRYPT_WIPE_ZERO, 0,
			      8 * SECTOR_SIZE, 8 * SECTOR_SIZE, NULL, NULL);
	if (r < 0) {
		log_err(cd, _("Cannot wipe header on device %s."),
			mdata_device_path(cd));
		return r;
	}

	if (!(cd->type = strdup(CRYPT_INTEGRITY)))
		return -ENOMEM;

	if (params->journal_crypt_key) {
		journal_crypt_key = crypt_alloc_volume_key(params->journal_crypt_key_size,
							   params->journal_crypt_key);
		if (!journal_crypt_key)
			return -ENOMEM;
	}

	if (params->journal_integrity_key) {
		journal_mac_key = crypt_alloc_volume_key(params->journal_integrity_key_size,
							 params->journal_integrity_key);
		if (!journal_mac_key) {
			r = -ENOMEM;
			goto out;
		}
	}

	if (params->integrity && !(integrity = strdup(params->integrity))) {
		r = -ENOMEM;
		goto out;
	}
	if (params->journal_integrity && !(journal_integrity = strdup(params->journal_integrity))) {
		r = -ENOMEM;
		goto out;
	}
	if (params->journal_crypt && !(journal_crypt = strdup(params->journal_crypt))) {
		r = -ENOMEM;
		goto out;
	}

	integrity_tag_size = INTEGRITY_hash_tag_size(integrity);
	if (integrity_tag_size > 0 && params->tag_size && integrity_tag_size != params->tag_size)
		log_std(cd, _("WARNING: Requested tag size %d bytes differs from %s size output (%d bytes).\n"),
			params->tag_size, integrity, integrity_tag_size);

	if (params->tag_size)
		integrity_tag_size = params->tag_size;

	cd->u.integrity.journal_crypt_key = journal_crypt_key;
	cd->u.integrity.journal_mac_key = journal_mac_key;
	cd->u.integrity.params.journal_size = params->journal_size;
	cd->u.integrity.params.journal_watermark = params->journal_watermark;
	cd->u.integrity.params.journal_commit_time = params->journal_commit_time;
	cd->u.integrity.params.interleave_sectors = params->interleave_sectors;
	cd->u.integrity.params.buffer_sectors = params->buffer_sectors;
	cd->u.integrity.params.sector_size = params->sector_size;
	cd->u.integrity.params.tag_size = integrity_tag_size;
	cd->u.integrity.params.integrity = integrity;
	cd->u.integrity.params.journal_integrity = journal_integrity;
	cd->u.integrity.params.journal_crypt = journal_crypt;

	r = INTEGRITY_format(cd, params, cd->u.integrity.journal_crypt_key, cd->u.integrity.journal_mac_key);
	if (r)
		log_err(cd, _("Cannot format integrity for device %s."),
			mdata_device_path(cd));
out:
	if (r) {
		crypt_free_volume_key(journal_crypt_key);
		crypt_free_volume_key(journal_mac_key);
		free(integrity);
		free(journal_integrity);
		free(journal_crypt);
	}

	return r;
}
gdm_session_worker_watch_child (GdmSessionWorker *worker)
{
        g_debug ("GdmSession worker: watching pid %d", worker->priv->child_pid);
        worker->priv->child_watch_id = g_child_watch_add (worker->priv->child_pid,
                                                          (GChildWatchFunc)session_worker_child_watch,
                                                          worker);

}
void abort_early(struct req_state *s, RGWOp* op, int err_no,
		RGWHandler* handler)
{
  string error_content("");
  if (!s->formatter) {
    s->formatter = new JSONFormatter;
    s->format = RGW_FORMAT_JSON;
  }

  // op->error_handler is responsible for calling it's handler error_handler
  if (op != NULL) {
    int new_err_no;
    new_err_no = op->error_handler(err_no, &error_content);
    ldout(s->cct, 20) << "op->ERRORHANDLER: err_no=" << err_no
		      << " new_err_no=" << new_err_no << dendl;
    err_no = new_err_no;
  } else if (handler != NULL) {
    int new_err_no;
    new_err_no = handler->error_handler(err_no, &error_content);
    ldout(s->cct, 20) << "handler->ERRORHANDLER: err_no=" << err_no
		      << " new_err_no=" << new_err_no << dendl;
    err_no = new_err_no;
  }

  // If the error handler(s) above dealt with it completely, they should have
  // returned 0. If non-zero, we need to continue here.
  if (err_no) {
    // Watch out, we might have a custom error state already set!
    if (!s->err.http_ret || s->err.http_ret == 200) {
      set_req_state_err(s, err_no);
    }

    if (s->err.http_ret == 404 && !s->redirect_zone_endpoint.empty()) {
      s->err.http_ret = 301;
      err_no = -ERR_PERMANENT_REDIRECT;
      build_redirect_url(s, s->redirect_zone_endpoint, &s->redirect);
    }

    dump_errno(s);
    dump_bucket_from_state(s);
    if (err_no == -ERR_PERMANENT_REDIRECT || err_no == -ERR_WEBSITE_REDIRECT) {
      string dest_uri;
      if (!s->redirect.empty()) {
        dest_uri = s->redirect;
      } else if (!s->zonegroup_endpoint.empty()) {
        build_redirect_url(s, s->zonegroup_endpoint, &dest_uri);
      }

      if (!dest_uri.empty()) {
        dump_redirect(s, dest_uri);
      }
    }

    if (!error_content.empty()) {
      /*
       * TODO we must add all error entries as headers here:
       * when having a working errordoc, then the s3 error fields are
       * rendered as HTTP headers, e.g.:
       *   x-amz-error-code: NoSuchKey
       *   x-amz-error-message: The specified key does not exist.
       *   x-amz-error-detail-Key: foo
       */
      end_header(s, op, NULL, error_content.size(), false, true);
      RESTFUL_IO(s)->send_body(error_content.c_str(), error_content.size());
    } else {
      end_header(s, op);
    }
  }
  perfcounter->inc(l_rgw_failed_req);
}
static void nma_class_init (NMAppletClass *klass)
{
	GObjectClass *oclass = G_OBJECT_CLASS (klass);
	GParamSpec *pspec;

	oclass->set_property = set_property;
	oclass->constructor = constructor;
	oclass->finalize = finalize;

	pspec = g_param_spec_pointer ("loop", "Loop", "Applet mainloop", G_PARAM_CONSTRUCT | G_PARAM_WRITABLE);
	g_object_class_install_property (oclass, PROP_LOOP, pspec);
}
// Find max root of a 2nd-order polynomial.
    static bool ___distance_eikonal(const Tfloat a, const Tfloat b, const Tfloat c, Tfloat &root) {
      const Tfloat delta = b*b - 4*a*c;
      if (delta<0) return false;
      root = 0.5f*(-b + std::sqrt(delta))/a;
      return true;
inline bool AveragePool(const PoolParams& params,
                        const RuntimeShape& input_shape,
                        const int8_t* input_data,
                        const RuntimeShape& output_shape, int8_t* output_data) {
  TFLITE_DCHECK_LE(params.quantized_activation_min,
                   params.quantized_activation_max);
  TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
  const int batches = MatchingDim(input_shape, 0, output_shape, 0);
  const int depth = MatchingDim(input_shape, 3, output_shape, 3);
  const int input_height = input_shape.Dims(1);
  const int input_width = input_shape.Dims(2);
  const int output_height = output_shape.Dims(1);
  const int output_width = output_shape.Dims(2);
  const int stride_height = params.stride_height;
  const int stride_width = params.stride_width;
  for (int batch = 0; batch < batches; ++batch) {
    for (int out_y = 0; out_y < output_height; ++out_y) {
      for (int out_x = 0; out_x < output_width; ++out_x) {
        for (int channel = 0; channel < depth; ++channel) {
          const int in_x_origin =
              (out_x * stride_width) - params.padding_values.width;
          const int in_y_origin =
              (out_y * stride_height) - params.padding_values.height;
          // Compute the boundaries of the filter region clamped so as to
          // ensure that the filter window fits in the input array.
          const int filter_x_start = std::max(0, -in_x_origin);
          const int filter_x_end =
              std::min(params.filter_width, input_width - in_x_origin);
          const int filter_y_start = std::max(0, -in_y_origin);
          const int filter_y_end =
              std::min(params.filter_height, input_height - in_y_origin);
          int32_t acc = 0;
          int filter_count = 0;
          for (int filter_y = filter_y_start; filter_y < filter_y_end;
               ++filter_y) {
            for (int filter_x = filter_x_start; filter_x < filter_x_end;
                 ++filter_x) {
              const int in_x = in_x_origin + filter_x;
              const int in_y = in_y_origin + filter_y;
              acc +=
                  input_data[Offset(input_shape, batch, in_y, in_x, channel)];
              filter_count++;
            }
          }
          if (filter_count == 0) return false;
          // Round to the closest integer value.
          acc = acc > 0 ? (acc + filter_count / 2) / filter_count
                        : (acc - filter_count / 2) / filter_count;
          acc = std::max(acc, params.quantized_activation_min);
          acc = std::min(acc, params.quantized_activation_max);
          output_data[Offset(output_shape, batch, out_y, out_x, channel)] =
              static_cast<int8_t>(acc);
        }
      }
    }
  }
  return true;
}