ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune huggingface dataset:
bool SplashOutputDev::functionShadedFill(GfxState *state, GfxFunctionShading *shading) {
  SplashFunctionPattern *pattern = new SplashFunctionPattern(colorMode, state, shading);
  double xMin, yMin, xMax, yMax;
  bool vaa = getVectorAntialias();
  // restore vector antialias because we support it here
  setVectorAntialias(true);

  bool retVal = false;
  // get the clip region bbox
  if (pattern->getShading()->getHasBBox()) {
    pattern->getShading()->getBBox(&xMin, &yMin, &xMax, &yMax);
  } else {
    state->getClipBBox(&xMin, &yMin, &xMax, &yMax);

    xMin = floor (xMin);
    yMin = floor (yMin);
    xMax = ceil (xMax);
    yMax = ceil (yMax);

    {
      Matrix ctm, ictm;
      double x[4], y[4];
      int i;

      state->getCTM(&ctm);
      ctm.invertTo(&ictm);

      ictm.transform(xMin, yMin, &x[0], &y[0]);
      ictm.transform(xMax, yMin, &x[1], &y[1]);
      ictm.transform(xMin, yMax, &x[2], &y[2]);
      ictm.transform(xMax, yMax, &x[3], &y[3]);

      xMin = xMax = x[0];
      yMin = yMax = y[0];
      for (i = 1; i < 4; i++) {
        xMin = std::min<double>(xMin, x[i]);
        yMin = std::min<double>(yMin, y[i]);
        xMax = std::max<double>(xMax, x[i]);
        yMax = std::max<double>(yMax, y[i]);
      }
    }
  }

  // fill the region
  state->moveTo(xMin, yMin);
  state->lineTo(xMax, yMin);
  state->lineTo(xMax, yMax);
  state->lineTo(xMin, yMax);
  state->closePath();
  SplashPath path = convertPath(state, state->getPath(), true);

#ifdef SPLASH_CMYK
  pattern->getShading()->getColorSpace()->createMapping(bitmap->getSeparationList(), SPOT_NCOMPS);
#endif
  setOverprintMask(pattern->getShading()->getColorSpace(), state->getFillOverprint(),
		   state->getOverprintMode(), nullptr);
  retVal = (splash->shadedFill(&path, pattern->getShading()->getHasBBox(), pattern) == splashOk);
  state->clearPath();
  setVectorAntialias(vaa);

  delete pattern;

  return retVal;
}
lpr_inherit_res_contents(fz_context *ctx, pdf_obj *res, pdf_obj *dict, pdf_obj *text)
{
	pdf_obj *o, *r;
	int i, n;

	/* If the parent node doesn't have an entry of this type, give up. */
	o = pdf_dict_get(ctx, dict, text);
	if (!o)
		return;

	/* If the resources dict we are building doesn't have an entry of this
	 * type yet, then just copy it (ensuring it's not a reference) */
	r = pdf_dict_get(ctx, res, text);
	if (r == NULL)
	{
		o = pdf_resolve_indirect(ctx, o);
		if (pdf_is_dict(ctx, o))
			o = pdf_copy_dict(ctx, o);
		else if (pdf_is_array(ctx, o))
			o = pdf_copy_array(ctx, o);
		else
			o = NULL;
		if (o)
			pdf_dict_put_drop(ctx, res, text, o);
		return;
	}

	/* Otherwise we need to merge o into r */
	if (pdf_is_dict(ctx, o))
	{
		n = pdf_dict_len(ctx, o);
		for (i = 0; i < n; i++)
		{
			pdf_obj *key = pdf_dict_get_key(ctx, o, i);
			pdf_obj *val = pdf_dict_get_val(ctx, o, i);

			if (pdf_dict_get(ctx, res, key))
				continue;
			pdf_dict_put(ctx, res, key, val);
		}
	}
}
type_kind(agooErr err, gqlDoc doc, gqlCobj obj, gqlField field, gqlSel sel, gqlValue result, int depth) {
    const char	*kind = NULL;
    const char	*key = sel->name;

    switch (((gqlType)obj->ptr)->kind) {
    case GQL_SCHEMA:	kind = "SCHEMA";	break;
    case GQL_OBJECT:	kind = "OBJECT";	break;
    case GQL_INPUT:	kind = "INPUT_OBJECT";	break;
    case GQL_UNION:	kind = "UNION";		break;
    case GQL_INTERFACE:	kind = "INTERFACE";	break;
    case GQL_ENUM:	kind = "ENUM";		break;
    case GQL_SCALAR:	kind = "SCALAR";	break;
    case GQL_LIST:	kind = "LIST";		break;
    case GQL_NON_NULL:	kind = "NON_NULL";	break;
    default:
	return agoo_err_set(err, AGOO_ERR_ARG, "__Type kind (%d) field not valid. %s:%d", ((gqlType)obj->ptr)->kind, __FILE__, __LINE__);
    }
    if (NULL != sel->alias) {
	key = sel->alias;
    }
    return gql_object_set(err, result, key, gql_token_create(err, kind, -1, gql_type_get("__TypeKind")));
}
tabpage_close(int forceit)
{
    /* First close all the windows but the current one.  If that worked then
     * close the last window in this tab, that will close it. */
    if (!ONE_WINDOW)
	close_others(TRUE, forceit);
    if (ONE_WINDOW)
	ex_win_close(forceit, curwin, NULL);
# ifdef FEAT_GUI
    need_mouse_correct = TRUE;
# endif
}
CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0,
                         const int x1, const int y1, const float u1, const float v1,
                         const tc *const color, const float opacity=1,
                         const float precision=0.25, const unsigned int pattern=~0U,
                         const bool init_hatch=true) {
      if (is_empty()) return *this;
      if (!color)
        throw CImgArgumentException(_cimg_instance
                                    "draw_spline(): Specified color is (null).",
                                    cimg_instance);
      if (x0==x1 && y0==y1) return draw_point(x0,y0,color,opacity);
      bool ninit_hatch = init_hatch;
      const float
        ax = u0 + u1 + 2*(x0 - x1),
        bx = 3*(x1 - x0) - 2*u0 - u1,
        ay = v0 + v1 + 2*(y0 - y1),
        by = 3*(y1 - y0) - 2*v0 - v1,
        _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1));
      int ox = x0, oy = y0;
      for (float t = 0; t<1; t+=_precision) {
        const float t2 = t*t, t3 = t2*t;
        const int
          nx = (int)(ax*t3 + bx*t2 + u0*t + x0),
          ny = (int)(ay*t3 + by*t2 + v0*t + y0);
        draw_line(ox,oy,nx,ny,color,opacity,pattern,ninit_hatch);
        ninit_hatch = false;
        ox = nx; oy = ny;
      }
      return draw_line(ox,oy,x1,y1,color,opacity,pattern,false);
    }
static ZIPARCHIVE_METHOD(getCommentIndex)
{
	struct zip *intern;
	zval *self = getThis();
	zend_long index, flags = 0;
	const char * comment;
	int comment_len = 0;
	struct zip_stat sb;

	if (!self) {
		RETURN_FALSE;
	}

	ZIP_FROM_OBJECT(intern, self);

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|l",
				&index, &flags) == FAILURE) {
		return;
	}

	PHP_ZIP_STAT_INDEX(intern, index, 0, sb);
	comment = zip_get_file_comment(intern, index, &comment_len, (int)flags);
	RETURN_STRINGL((char *)comment, (zend_long)comment_len);
}
static void lan9118_reset(DeviceState *d)
{
    lan9118_state *s = LAN9118(d);

    s->irq_cfg &= (IRQ_TYPE | IRQ_POL);
    s->int_sts = 0;
    s->int_en = 0;
    s->fifo_int = 0x48000000;
    s->rx_cfg = 0;
    s->tx_cfg = 0;
    s->hw_cfg = s->mode_16bit ? 0x00050000 : 0x00050004;
    s->pmt_ctrl &= 0x45;
    s->gpio_cfg = 0;
    s->txp->fifo_used = 0;
    s->txp->state = TX_IDLE;
    s->txp->cmd_a = 0xffffffffu;
    s->txp->cmd_b = 0xffffffffu;
    s->txp->len = 0;
    s->txp->fifo_used = 0;
    s->tx_fifo_size = 4608;
    s->tx_status_fifo_used = 0;
    s->rx_status_fifo_size = 704;
    s->rx_fifo_size = 2640;
    s->rx_fifo_used = 0;
    s->rx_status_fifo_size = 176;
    s->rx_status_fifo_used = 0;
    s->rxp_offset = 0;
    s->rxp_size = 0;
    s->rxp_pad = 0;
    s->rx_packet_size_tail = s->rx_packet_size_head;
    s->rx_packet_size[s->rx_packet_size_head] = 0;
    s->mac_cmd = 0;
    s->mac_data = 0;
    s->afc_cfg = 0;
    s->e2p_cmd = 0;
    s->e2p_data = 0;
    s->free_timer_start = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / 40;

    ptimer_transaction_begin(s->timer);
    ptimer_stop(s->timer);
    ptimer_set_count(s->timer, 0xffff);
    ptimer_transaction_commit(s->timer);
    s->gpt_cfg = 0xffff;

    s->mac_cr = MAC_CR_PRMS;
    s->mac_hashh = 0;
    s->mac_hashl = 0;
    s->mac_mii_acc = 0;
    s->mac_mii_data = 0;
    s->mac_flow = 0;

    s->read_word_n = 0;
    s->write_word_n = 0;

    phy_reset(s);

    s->eeprom_writable = 0;
    lan9118_reload_eeprom(s);
}
long oe_syscall(long number, ...)
{
    long ret;

    oe_va_list ap;
    oe_va_start(ap, number);
    long arg1 = oe_va_arg(ap, long);
    long arg2 = oe_va_arg(ap, long);
    long arg3 = oe_va_arg(ap, long);
    long arg4 = oe_va_arg(ap, long);
    long arg5 = oe_va_arg(ap, long);
    long arg6 = oe_va_arg(ap, long);
    ret = _syscall(number, arg1, arg2, arg3, arg4, arg5, arg6);
    oe_va_end(ap);

    return ret;
}
static enum_func_status
php_mysqlnd_read_row_ex(MYSQLND_PFC * pfc,
						MYSQLND_VIO * vio,
						MYSQLND_STATS * stats,
						MYSQLND_ERROR_INFO * error_info,
						MYSQLND_CONNECTION_STATE * connection_state,
						MYSQLND_MEMORY_POOL * pool,
						MYSQLND_ROW_BUFFER * buffer,
						size_t * const data_size)
{
	enum_func_status ret = PASS;
	MYSQLND_PACKET_HEADER header;
	zend_uchar * p = NULL;
	size_t prealloc_more_bytes;

	DBG_ENTER("php_mysqlnd_read_row_ex");

	/*
	  To ease the process the server splits everything in packets up to 2^24 - 1.
	  Even in the case the payload is evenly divisible by this value, the last
	  packet will be empty, namely 0 bytes. Thus, we can read every packet and ask
	  for next one if they have 2^24 - 1 sizes. But just read the header of a
	  zero-length byte, don't read the body, there is no such.
	*/

	/*
	  We're allocating an extra byte, as php_mysqlnd_rowp_read_text_protocol_aux
	  needs to be able to append a terminating \0 for atoi/atof.
	*/
	prealloc_more_bytes = 1;

	*data_size = 0;
	if (UNEXPECTED(FAIL == mysqlnd_read_header(pfc, vio, &header, stats, error_info))) {
		ret = FAIL;
		SET_CONNECTION_STATE(connection_state, CONN_QUIT_SENT);
		set_packet_error(error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
	} else {
		*data_size += header.size;
		buffer->ptr = pool->get_chunk(pool, *data_size + prealloc_more_bytes);
		p = buffer->ptr;

		if (UNEXPECTED(PASS != (ret = pfc->data->m.receive(pfc, vio, p, header.size, stats, error_info)))) {
			DBG_ERR("Empty row packet body");
			SET_CONNECTION_STATE(connection_state, CONN_QUIT_SENT);
			set_packet_error(error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
		} else {
			while (header.size >= MYSQLND_MAX_PACKET_SIZE) {
				if (FAIL == mysqlnd_read_header(pfc, vio, &header, stats, error_info)) {
					ret = FAIL;
					break;
				}

				*data_size += header.size;

				/* Empty packet after MYSQLND_MAX_PACKET_SIZE packet. That's ok, break */
				if (!header.size) {
					break;
				}

				/*
				  We have to realloc the buffer.
				*/
				buffer->ptr = pool->resize_chunk(pool, buffer->ptr, *data_size - header.size, *data_size + prealloc_more_bytes);
				if (!buffer->ptr) {
					SET_OOM_ERROR(error_info);
					ret = FAIL;
					break;
				}
				/* The position could have changed, recalculate */
				p = (zend_uchar *) buffer->ptr + (*data_size - header.size);

				if (PASS != (ret = pfc->data->m.receive(pfc, vio, p, header.size, stats, error_info))) {
					DBG_ERR("Empty row packet body");
					SET_CONNECTION_STATE(connection_state, CONN_QUIT_SENT);
					set_packet_error(error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone);
					break;
				}
			}
		}
	}
	if (ret == FAIL && buffer->ptr) {
		pool->free_chunk(pool, buffer->ptr);
		buffer->ptr = NULL;
	}
	DBG_RETURN(ret);
static void cma_remove_one(struct ib_device *device, void *client_data)
{
	struct cma_device *cma_dev = client_data;

	trace_cm_remove_one(device);

	mutex_lock(&lock);
	list_del(&cma_dev->list);
	mutex_unlock(&lock);

	cma_process_remove(cma_dev);
	kfree(cma_dev->default_roce_tos);
	kfree(cma_dev->default_gid_type);
	kfree(cma_dev);
}
static void
typebuilder_setup_properties (MonoClass *klass, MonoError *error)
{
	MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
	MonoReflectionPropertyBuilder *pb;
	MonoImage *image = klass->image;
	MonoProperty *properties;
	int i;

	mono_error_init (error);

	if (!klass->ext)
		klass->ext = image_g_new0 (image, MonoClassExt, 1);

	klass->ext->property.count = tb->properties ? mono_array_length (tb->properties) : 0;
	klass->ext->property.first = 0;

	properties = image_g_new0 (image, MonoProperty, klass->ext->property.count);
	klass->ext->properties = properties;
	for (i = 0; i < klass->ext->property.count; ++i) {
		pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
		properties [i].parent = klass;
		properties [i].attrs = pb->attrs;
		properties [i].name = mono_string_to_utf8_image (image, pb->name, error);
		if (!mono_error_ok (error))
			return;
		if (pb->get_method)
			properties [i].get = pb->get_method->mhandle;
		if (pb->set_method)
			properties [i].set = pb->set_method->mhandle;

		mono_save_custom_attrs (klass->image, &properties [i], pb->cattrs);
		if (pb->def_value) {
			guint32 len, idx;
			const char *p, *p2;
			MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
			if (!klass->ext->prop_def_values)
				klass->ext->prop_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->ext->property.count);
			properties [i].attrs |= PROPERTY_ATTRIBUTE_HAS_DEFAULT;
			idx = encode_constant (assembly, pb->def_value, &klass->ext->prop_def_values [i].def_type);
			/* Copy the data from the blob since it might get realloc-ed */
			p = assembly->blob.data + idx;
			len = mono_metadata_decode_blob_size (p, &p2);
			len += p2 - p;
			klass->ext->prop_def_values [i].data = mono_image_alloc (image, len);
			memcpy ((gpointer)klass->ext->prop_def_values [i].data, p, len);
		}
	}
static bool tcf_proto_is_unlocked(const char *kind)
{
	const struct tcf_proto_ops *ops;
	bool ret;

	if (strlen(kind) == 0)
		return false;

	ops = tcf_proto_lookup_ops(kind, false, NULL);
	/* On error return false to take rtnl lock. Proto lookup/create
	 * functions will perform lookup again and properly handle errors.
	 */
	if (IS_ERR(ops))
		return false;

	ret = !!(ops->flags & TCF_PROTO_OPS_DOIT_UNLOCKED);
	module_put(ops->owner);
	return ret;
}
parse_PUSH_VLAN(char *arg, struct ofpbuf *ofpacts,
                enum ofputil_protocol *usable_protocols OVS_UNUSED)
{
    uint16_t ethertype;
    char *error;

    *usable_protocols &= OFPUTIL_P_OF11_UP;
    error = str_to_u16(arg, "ethertype", &ethertype);
    if (error) {
        return error;
    }

    if (ethertype != ETH_TYPE_VLAN_8021Q) {
        /* XXX ETH_TYPE_VLAN_8021AD case isn't supported */
        return xasprintf("%s: not a valid VLAN ethertype", arg);
    }

    ofpact_put_PUSH_VLAN(ofpacts);
    return NULL;
}
CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy)
{
  struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg:
    &conn->data->state.negotiate;
  char *encoded = NULL;
  size_t len = 0;
  char *userp;
  CURLcode error;
  OM_uint32 discard_st;

  error = Curl_base64_encode(conn->data,
                             neg_ctx->output_token.value,
                             neg_ctx->output_token.length,
                             &encoded, &len);
  if(error) {
    gss_release_buffer(&discard_st, &neg_ctx->output_token);
    neg_ctx->output_token.value = NULL;
    neg_ctx->output_token.length = 0;
    return error;
  }

  if(!encoded || !len) {
    gss_release_buffer(&discard_st, &neg_ctx->output_token);
    neg_ctx->output_token.value = NULL;
    neg_ctx->output_token.length = 0;
    return CURLE_REMOTE_ACCESS_DENIED;
  }

  userp = aprintf("%sAuthorization: %s %s\r\n", proxy ? "Proxy-" : "",
                  neg_ctx->protocol, encoded);
  if(proxy) {
    Curl_safefree(conn->allocptr.proxyuserpwd);
    conn->allocptr.proxyuserpwd = userp;
  }
  else {
    Curl_safefree(conn->allocptr.userpwd);
    conn->allocptr.userpwd = userp;
  }

  Curl_safefree(encoded);
  Curl_cleanup_negotiate(conn->data);

  return (userp == NULL) ? CURLE_OUT_OF_MEMORY : CURLE_OK;
}
backend_valid_range (struct backend *b, struct connection *conn,
                     uint64_t offset, uint32_t count)
{
  struct b_conn_handle *h = &conn->handles[b->i];

  assert (h->exportsize >= 0); /* Guaranteed by negotiation phase */
  return count > 0 && offset <= h->exportsize &&
    offset + count <= h->exportsize;
}
static int _pack_job_cancel(void *x, void *arg)
{
	struct job_record *job_ptr = (struct job_record *) x;
	char job_id_str[BUFSIZ];
	time_t now = time(NULL);

	(void) jobid2fmt(job_ptr, job_id_str, sizeof(job_id_str));
	info("Cancelling aborted pack job submit: %s", job_id_str);
	job_ptr->job_state	= JOB_CANCELLED;
	job_ptr->start_time	= now;
	job_ptr->end_time	= now;
	job_ptr->exit_code	= 1;
	job_completion_logger(job_ptr, false);
	fed_mgr_job_complete(job_ptr, 0, now);

	return 0;
}
static int __init init_opl3 (void)
{
	printk(KERN_INFO "YM3812 and OPL-3 driver Copyright (C) by Hannu Savolainen, Rob Hooft 1993-1996\n");

	if (io != -1)	/* User loading pure OPL3 module */
	{
		if (!opl3_detect(io))
		{
			return -ENODEV;
		}

		me = opl3_init(io, THIS_MODULE);
	}

	return 0;
}
GF_EXPORT
GF_Err gf_isom_get_sidx_duration(GF_ISOFile *movie, u64 *sidx_dur, u32 *sidx_timescale)
{
	u64 dur=0;
	u32 i;
	if (!movie || !movie->moov || !sidx_timescale || !sidx_dur)
		return GF_BAD_PARAM;

	if (!movie->main_sidx) return GF_NOT_SUPPORTED;
	*sidx_timescale = movie->main_sidx->timescale;

	for (i=0; i<movie->main_sidx->nb_refs; i++) {
		dur += movie->main_sidx->refs[i].subsegment_duration;
	}
	*sidx_dur = dur;
	return GF_OK;
gimp_channel_convert (GimpItem  *item,
                      GimpImage *dest_image,
                      GType      old_type)
{
  GimpChannel  *channel  = GIMP_CHANNEL (item);
  GimpDrawable *drawable = GIMP_DRAWABLE (item);

  if (! gimp_drawable_is_gray (drawable))
    {
      gimp_drawable_convert_type (drawable, dest_image,
                                  GIMP_GRAY,
                                  gimp_image_get_precision (dest_image),
                                  gimp_drawable_has_alpha (drawable),
                                  NULL,
                                  GEGL_DITHER_NONE, GEGL_DITHER_NONE,
                                  FALSE, NULL);
    }

  if (gimp_drawable_has_alpha (drawable))
    {
      GeglBuffer *new_buffer;
      const Babl *format;
      GimpRGB     background;

      format = gimp_drawable_get_format_without_alpha (drawable);

      new_buffer =
        gegl_buffer_new (GEGL_RECTANGLE (0, 0,
                                         gimp_item_get_width (item),
                                         gimp_item_get_height (item)),
                         format);

      gimp_rgba_set (&background, 0.0, 0.0, 0.0, 0.0);

      gimp_gegl_apply_flatten (gimp_drawable_get_buffer (drawable),
                               NULL, NULL,
                               new_buffer, &background,
                               GIMP_LAYER_COLOR_SPACE_RGB_LINEAR);

      gimp_drawable_set_buffer_full (drawable, FALSE, NULL,
                                     new_buffer,
                                     GEGL_RECTANGLE (
                                       gimp_item_get_offset_x (item),
                                       gimp_item_get_offset_y (item),
                                       0, 0),
                                     TRUE);
      g_object_unref (new_buffer);
    }

  if (G_TYPE_FROM_INSTANCE (channel) == GIMP_TYPE_CHANNEL)
    {
      gint width  = gimp_image_get_width  (dest_image);
      gint height = gimp_image_get_height (dest_image);

      gimp_item_set_offset (item, 0, 0);

      if (gimp_item_get_width  (item) != width ||
          gimp_item_get_height (item) != height)
        {
          gimp_item_resize (item, gimp_get_user_context (dest_image->gimp),
                            GIMP_FILL_TRANSPARENT,
                            width, height, 0, 0);
        }
    }

  GIMP_ITEM_CLASS (parent_class)->convert (item, dest_image, old_type);
}
CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) {
      return get_shared_rows(y0,y0,z0,c0);
    }
void erase(TFE_Py_ForwardAccumulator* element) {
    MapType::iterator existing = map_.find(element);
    if (existing == map_.end()) {
      return;
    }
    ListType::iterator list_position = existing->second;
    map_.erase(existing);
    ordered_.erase(list_position);
  }
static GF_DOVIDecoderConfigurationRecord* DOVI_DuplicateConfig(GF_DOVIDecoderConfigurationRecord *cfg)
{
	GF_DOVIDecoderConfigurationRecord* out = NULL;
	GF_SAFEALLOC(out, GF_DOVIDecoderConfigurationRecord);
	if (!out) return NULL;

	out->dv_version_major = cfg->dv_version_major;
	out->dv_version_minor = cfg->dv_version_minor;
	out->dv_profile = cfg->dv_profile;
	out->dv_level = cfg->dv_level;
	out->rpu_present_flag = cfg->rpu_present_flag;
	out->el_present_flag = cfg->el_present_flag;
	out->bl_present_flag = cfg->bl_present_flag;

	return out;
}
int dd_delete_item(struct dump_dir *dd, const char *name)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot delete item. '%s' is not a valid file name", name);

    int res = unlinkat(dd->dd_fd, name, /*only files*/0);

    if (res < 0)
    {
        if (errno == ENOENT)
            errno = res = 0;
        else
            perror_msg("Can't delete file '%s'", name);
    }

    return res;
}
static int coolkey_read_binary(sc_card_t *card, unsigned int idx,
		u8 *buf, size_t count, unsigned long flags)
{
	coolkey_private_data_t * priv = COOLKEY_DATA(card);
	int r = 0, len;
	u8 *data = NULL;

	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
	if (idx > priv->obj->length) {
		LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED);
	}

	/* if we've already read the data, just return it */
	if (priv->obj->data) {
		sc_log(card->ctx, 
			 "returning cached value idx=%u count=%"SC_FORMAT_LEN_SIZE_T"u",
			 idx, count);
		len = MIN(count, priv->obj->length-idx);
		memcpy(buf, &priv->obj->data[idx], len);
		LOG_FUNC_RETURN(card->ctx, len);
	}

	sc_log(card->ctx, 
		 "clearing cache idx=%u count=%"SC_FORMAT_LEN_SIZE_T"u",
		 idx, count);

	data = malloc(priv->obj->length);
	if (data == NULL) {
		r = SC_ERROR_OUT_OF_MEMORY;
		goto done;
	}


	r = coolkey_read_object(card, priv->obj->id, 0, data, priv->obj->length,
												priv->nonce, sizeof(priv->nonce));
	if (r < 0)
		goto done;

	if ((size_t) r != priv->obj->length) {
		priv->obj->length = r;
	}


	/* OK we've read the data, now copy the required portion out to the callers buffer */
	len = MIN(count, priv->obj->length-idx);
	memcpy(buf, &data[idx], len);
	r = len;
	/* cache the data in the object */
	priv->obj->data=data;
	data = NULL;

done:
	if (data)
		free(data);
	LOG_FUNC_RETURN(card->ctx, r);
}