Ejemplo n.º 1
0
PerlFMM *
PerlFMM_clone(PerlFMM *self)
{
    PerlFMM *state;
    fmmagic *d, *s;

    state = PerlFMM_create(NULL);
    st_free_table(state->ext);
    state->ext = st_copy( self->ext );

    s = self->magic;
    Newxz(d, 1, fmmagic);
    memcpy(d, s, sizeof(fmmagic));
    state->magic = d;
    while (s->next != NULL) {
        Newxz(d->next, 1, fmmagic);
        memcpy(d->next, s->next, sizeof(struct _fmmagic));
        d = d->next;
        s = s->next;
    }
    state->last = d;
    state->last->next = NULL;

    return state;
}
Ejemplo n.º 2
0
FILE *
my_fdopen(int fd, char *mode)
{
    FILE *fp;
    char sockbuf[256];
    int optlen = sizeof(sockbuf);
    int retval;

    if (!wsock_started)
	return(fdopen(fd, mode));

    retval = getsockopt((SOCKET)fd, SOL_SOCKET, SO_TYPE, sockbuf, &optlen);
    if(retval == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK) {
	return(fdopen(fd, mode));
    }

    /*
     * If we get here, then fd is actually a socket.
     */
    Newxz(fp, 1, FILE);	/* XXX leak, good thing this code isn't used */
    if(fp == NULL) {
	errno = ENOMEM;
	return NULL;
    }

    fp->_file = fd;
    if(*mode == 'r')
	fp->_flag = _IOREAD;
    else
	fp->_flag = _IOWRT;
   
    return fp;
}
static void *create_event(plcba_cbcio *cbcio)
{
    PLCBA_c_event *cevent;
    PLCBA_t *async;
    
    async = (PLCBA_t*)cbcio->v.v0.cookie;
    Newxz(cevent, 1, PLCBA_c_event);
    
    cevent->pl_event = newAV();
    cevent->evtype = PLCBA_EVTYPE_IO;
    
    av_store(cevent->pl_event,
             PLCBA_EVIDX_OPAQUE,
             newSViv(PTR2IV(cevent)));
    
    if (async->cevents) {
        cevent->prev = NULL;
        cevent->next = async->cevents;
        async->cevents->prev = cevent;
        async->cevents = cevent;

    } else {
        async->cevents = cevent;
        cevent->next = NULL;
        cevent->prev = NULL;
    }
    
    return cevent;
}
Ejemplo n.º 4
0
SV *
PLCBA_construct(const char *pkg, AV *options)
{
    PLCBA_t *async;
    char *host, *username, *password, *bucket;
    libcouchbase_t instance;
    SV *blessed_obj;
    
    Newxz(async, 1, PLCBA_t);
    
    extract_async_options(async, options);
    
    plcb_ctor_conversion_opts(&async->base, options);
    
    plcb_ctor_cbc_opts(options, &host, &username, &password, &bucket);
    instance = libcouchbase_create(host, username, password, bucket,
                                   plcba_make_io_opts(async));
    
    if(!instance) {
        die("Couldn't create instance!");
    }
    
    plcb_ctor_init_common(&async->base, instance, options);
    plcba_setup_callbacks(async);
    async->base_rv = newRV_inc(newSViv(PTR2IV(&(async->base))));
    
    blessed_obj = newSV(0);
    sv_setiv(newSVrv(blessed_obj, pkg), PTR2IV(async));
    return blessed_obj;
}
Ejemplo n.º 5
0
Node *
_add_segment( Share * share ) {
  Node *node;
  int flags;

  Newxz( node, 1, Node );

  node->next = NULL;

  /* Does another shared memory segment already exist? */
  if ( share->tail->shmaddr->next_shmid >= 0 ) {
    node->shmid = share->tail->shmaddr->next_shmid;
    if ( ( node->shmaddr =
           ( Header * ) shmat( node->shmid, ( char * ) 0,
                               0 ) ) == ( Header * ) - 1 ) {
      return NULL;
    }
    share->tail->next = node;
    share->tail = node;
    return node;
  }

  flags = share->flags | IPC_CREAT | IPC_EXCL;

  /* We need to create a new segment */
  while ( 1 ) {
    node->shmid = shmget( share->next_key++, share->segment_size, flags );
    if ( node->shmid >= 0 ) {
      break;
    }
#ifdef EIDRM
    if ( errno == EEXIST || errno == EIDRM ) {
      continue;
    }
#else
    if ( errno == EEXIST ) {
      continue;
    }
#endif
    return NULL;
  }

  share->tail->shmaddr->next_shmid = node->shmid;
  share->tail->next = node;
  share->tail = node;
  if ( ( node->shmaddr =
         ( Header * ) shmat( node->shmid, ( char * ) 0,
                             0 ) ) == ( Header * ) - 1 ) {
    return NULL;
  }
  node->shmaddr->next_shmid = -1;
  node->shmaddr->length = 0;

  return node;
}
Ejemplo n.º 6
0
lmsxs_ll_ent*
lmsxs_ll_make_ent(IV key, SV* sv, IV list_num, IV list_idx)
{
    lmsxs_ll_ent* ent;
    Newxz(ent, 1, lmsxs_ll_ent);
    ent->key = key;
    ent->sv = sv;
    ent->list_num = list_num;
    ent->list_idx = list_idx;
    ent->next = NULL;
    return ent;
}
Ejemplo n.º 7
0
SRL_STATIC_INLINE void stack_push(srl_splitter_stack_t * stack, UV val) {
    if (stack->top >= stack->size) {
        UV new_size = stack->size + STACK_SIZE_INCR;
        UV* tmp;
        dTHX;
        Newxz(tmp, new_size, UV );
        memcpy(tmp, stack->data, stack->size * sizeof(UV));
        Safefree(stack->data);
        stack->data = tmp;
        stack->size = new_size;
    }
    stack->data[stack->top++] = val;
}
Ejemplo n.º 8
0
mop_method *
mop_method_create(char *name, char *package_name, mop_class *c, SV *body)
{
    mop_method *method;

    Newxz(method, 1, mop_method);

    Newxz( method->name, strlen(name) + 1, char );
    Copy( name, method->name, strlen(name) + 1, char );

    Newxz( method->package_name, strlen(package_name) + 1, char );
    Copy( package_name, method->package_name, strlen(package_name) + 1, char );

    method->associated_metaclass = c;

    method->body = SvREFCNT_inc( body );
}
Ejemplo n.º 9
0
/* Builds the C-level configuration and state struct.
 * Automatically freed at scope boundary. */
srl_decoder_t *
srl_build_decoder_struct(pTHX_ HV *opt)
{
    srl_decoder_t *dec;
    SV **svp;

    Newxz(dec, 1, srl_decoder_t);

    dec->ref_seenhash = PTABLE_new();
    dec->max_recursion_depth = DEFAULT_MAX_RECUR_DEPTH;
    dec->max_num_hash_entries = 0; /* 0 == any number */

    /* load options */
    if (opt != NULL) {
        if ( (svp = hv_fetchs(opt, "refuse_snappy", 0)) && SvTRUE(*svp))
            SRL_DEC_SET_OPTION(dec, SRL_F_DECODER_REFUSE_SNAPPY);

        if ( (svp = hv_fetchs(opt, "refuse_objects", 0)) && SvTRUE(*svp))
            SRL_DEC_SET_OPTION(dec, SRL_F_DECODER_REFUSE_OBJECTS);

        if ( (svp = hv_fetchs(opt, "no_bless_objects", 0)) && SvTRUE(*svp))
            SRL_DEC_SET_OPTION(dec, SRL_F_DECODER_NO_BLESS_OBJECTS);

        if ( (svp = hv_fetchs(opt, "validate_utf8", 0)) && SvTRUE(*svp))
            SRL_DEC_SET_OPTION(dec, SRL_F_DECODER_VALIDATE_UTF8);

        if ( (svp = hv_fetchs(opt, "max_recursion_depth", 0)) && SvTRUE(*svp))
            dec->max_recursion_depth = SvUV(*svp);

        if ( (svp = hv_fetchs(opt, "max_num_hash_entries", 0)) && SvTRUE(*svp))
            dec->max_num_hash_entries = SvUV(*svp);

        if ( (svp = hv_fetchs(opt, "incremental", 0)) && SvTRUE(*svp))
            SRL_DEC_SET_OPTION(dec,SRL_F_DECODER_DESTRUCTIVE_INCREMENTAL);
    }

    return dec;
}
Ejemplo n.º 10
0
static void *
create_event_common(lcb_io_opt_t cbcio, int type)
{
    plcb_EVENT *cevent;
    plcb_IOPROCS *async;
    SV *initproc = NULL, *tmprv = NULL;
    async = (plcb_IOPROCS*) cbcio->v.v0.cookie;

    Newxz(cevent, 1, plcb_EVENT);
    cevent->pl_event = newAV();
    cevent->rv_event = newRV_noinc((SV*)cevent->pl_event);
    cevent->evtype = type;
    cevent->fd = -1;

    sv_bless(cevent->rv_event, gv_stashpv(PLCB_EVENT_CLASS, GV_ADD));
    av_store(cevent->pl_event, PLCB_EVIDX_OPAQUE, newSViv(PTR2IV(cevent)));
    av_store(cevent->pl_event, PLCB_EVIDX_FD, newSViv(-1));
    av_store(cevent->pl_event, PLCB_EVIDX_TYPE, newSViv(type));
    av_store(cevent->pl_event, PLCB_EVIDX_WATCHFLAGS, newSViv(0));

    tmprv = newRV_inc(*av_fetch(cevent->pl_event, PLCB_EVIDX_OPAQUE, 0));
    sv_bless(tmprv, gv_stashpv("Couchbase::IO::_CEvent", GV_ADD));
    SvREFCNT_dec(tmprv);


    if (type == PLCB_EVTYPE_IO) {
        initproc = async->cv_evinit;
    } else {
        initproc = async->cv_tminit;
    }

    if (initproc) {
        cb_args_noret(initproc, 0, 2, async->userdata, cevent->rv_event);
    }
    return cevent;
}
Ejemplo n.º 11
0
int csv_select_run_child(
	csv_parse_t *parse, csv_result_set_t *result, size_t table_pos
) {
	csv_select_t *select = parse->select;
	csv_table_def_t *table, *table2;
	char *s1, *s2;
	int ch, has_child = select->table_count - table_pos > 1;
	size_t i, j, k, l, m, rp = 0, nr = 0, l1;
	Expr *x1;
	ExprList *xl_cols = select->columns;
	csv_row_t *row;
	csv_var_t *v1, v2;
	csv_column_def_t *col;
	csv_t *csv = parse->csv;
	/* reset table */
	table = select->tables[table_pos];
	PerlIO_seek( table->dstream, table->header_offset, SEEK_SET );
	if( table->flags & TEXT_TABLE_COLNAMEHEADER ) {
		if( ! table->header_offset ) {
			do {
				ch = PerlIO_getc( table->dstream );
			} while( ch != EOF && ch != '\n' );
			table->header_offset = PerlIO_tell( table->dstream );
		}
	}
	table->row_pos = 0;
	/* read rows */
	while( (s1 = csv_read_row( table )) != NULL ) {
#ifdef CSV_DEBUG
		_debug( "table '%s' row %lu\n", table->name, table->row_pos );
#endif
		if( has_child ) {
			ch = csv_select_run_child( parse, result, table_pos + 1 );
			if( ch != CSV_OK )
				return ch;
			continue;
		}
		/* eval WHERE */
		if( (x1 = select->where) != NULL ) {
			ch = expr_eval( parse, x1 );
			if( ch != CSV_OK )
				return ch;
			if( x1->var.flags & VAR_HAS_IV ) {
				if( ! x1->var.iv )
					continue;
			}
			else if( x1->var.flags & VAR_HAS_NV ) {
				if( ! x1->var.nv )
					continue;
			}
			else if( x1->var.sv == NULL || x1->var.sv[0] == '0' )
				continue;
		}
		/* eval columns */
		for( i = 0; i < xl_cols->expr_count; i ++ ) {
			x1 = xl_cols->expr[i];
			if( (x1->flags & EXPR_IS_AGGR) == 0 ) {
				ch = expr_eval( parse, x1 );
				if( ch != CSV_OK )
					return ch;
			}
		}
		if( select->groupby == NULL )
			goto add_row;
		/* eval groupby */
		for( i = 0; i < select->groupby->expr_count; i ++ ) {
			ch = expr_eval( parse, select->groupby->expr[i] );
			if( ch != CSV_OK )
				return ch;
		}
		/* search groupby row */
		for( j = 0; j < result->row_count; j ++ ) {
			row = result->rows[j];
			for( i = 0; i < select->groupby->expr_count; i ++ ) {
				v1 = &row->groupby[i];
				x1 = select->groupby->expr[i];
				VAR_COMP_OP( v2, *v1, x1->var, ==, "==", 0, 0 );
				if( ! v2.iv )
					goto groupby_next;
			}
			goto eval_row;
groupby_next:
			continue;
		}
add_row:
		if( select->offset && rp < select->offset ) {
			rp ++;
			continue;
		}
		if( select->limit && rp - select->offset >= select->limit )
			goto finish;
		rp ++;
		Newxz( row, 1, csv_row_t );
		row->select = select;
		if( (result->row_count % ROW_COUNT_EXPAND) == 0 ) {
			Renew( result->rows, result->row_count + ROW_COUNT_EXPAND,
				csv_row_t * );
		}
		result->rows[result->row_count ++] = row;
		Newxz( row->data, result->column_count, csv_var_t );
		if( select->orderby != NULL )
			Newxz( row->orderby, select->orderby->expr_count, csv_var_t );
		if( select->groupby != NULL )
			Newxz( row->groupby, select->groupby->expr_count, csv_var_t );
		nr = 1;
eval_row:
		for( i = 0, j = 0; i < xl_cols->expr_count; i ++, j ++ ) {
			x1 = xl_cols->expr[i];
			if( x1->op == TK_TABLE ) {
				table2 = x1->table;
				for( l = 0; l < table2->column_count; l ++, j ++ ) {
					col = table2->columns + l;
					v1 = row->data + j;
					s1 = table->data + col->offset;
					l1 = col->length;
					if( l1 == 4 && strcmp( s1, "NULL" ) == 0 )
						continue;
					switch( col->type ) {
					case FIELD_TYPE_INTEGER:
						v1->iv = atoi( s1 );
						v1->flags = VAR_HAS_IV;
						break;
					case FIELD_TYPE_DOUBLE:
						if( table2->decimal_symbol != '.' ) {
							s2 = strchr( s1, table2->decimal_symbol );
							if( s2 != NULL )
								*s2 = '.';
						}
						v1->nv = atof( s1 );
						v1->flags = VAR_HAS_NV;
						break;
					case FIELD_TYPE_CHAR:
						v1->sv_len = charset_convert(
							s1, l1, table2->charset,
							csv->client_charset, &v1->sv
						);
						v1->flags = VAR_HAS_SV;
						break;
					case FIELD_TYPE_BLOB:
						if( l1 >= 2 && s1[0] == '0' && s1[1] == 'x' ) {
							l1 = (l1 - 2) / 2;
							if( ! l1 ) {
								v1->flags = 0;
								continue;
							}
							Renew( v1->sv, l1 + 1, char );
							for( m = 0, s1 += 2; m < l1; m ++ ) {
								ch = CHAR_FROM_HEX[*s1 & 0x7f] << 4;
								s1 ++;
								ch += CHAR_FROM_HEX[*s1 & 0x7f];
								s1 ++;
								v1->sv[m] = (char) ch;
							}
							v1->sv[l1] = '\0';
							v1->sv_len = l1;
							v1->flags = VAR_HAS_SV;
							break;
						}
					default:
						Renew( v1->sv, l1 + 1, char );
						Copy( s1, v1->sv, l1, char );
						v1->sv[l1] = '\0';
						v1->sv_len = l1;
						v1->flags = VAR_HAS_SV;
						break;
					}
				}
				continue;
			}
Ejemplo n.º 12
0
SV *
PLCB_ioprocs_new(SV *options)
{
    plcb_IOPROCS async_s = { NULL }, *async = NULL;
    lcb_io_opt_t cbcio = NULL;
    SV *ptriv, *blessedrv;

    /* First make sure all the options are ok */
    plcb_OPTION argopts[] = {
        #define X(name, t, tgt) PLCB_KWARG(name, t, &async_s.tgt),
        X_IOPROCS_OPTIONS(X)
        #undef X
        { NULL }
    };

    plcb_extract_args(options, argopts);

    /* Verify we have at least the basic functions */
    if (!async_s.cv_evmod) {
        die("Need event_update");
    }
    if (!async_s.cv_timermod) {
        die("Need timer_update");
    }

    if (!async_s.userdata) {
        async_s.userdata = &PL_sv_undef;
    }

    Newxz(cbcio, 1, struct lcb_io_opt_st);
    Newxz(async, 1, plcb_IOPROCS);

    *async = async_s;

    #define X(name, t, tgt) SvREFCNT_inc(async->tgt);
    X_IOPROCS_OPTIONS(X)
    #undef X

    ptriv = newSViv(PTR2IV(async));
    blessedrv = newRV_noinc(ptriv);
    sv_bless(blessedrv, gv_stashpv(PLCB_IOPROCS_CLASS, GV_ADD));

    async->refcount = 1;
    async->iops_ptr = cbcio;
    cbcio->v.v0.cookie = async;

    async->selfrv = newRV_inc(ptriv); sv_rvweaken(async->selfrv);
    async->action_sv = newSViv(0); SvREADONLY_on(async->action_sv);
    async->flags_sv = newSViv(0); SvREADONLY_on(async->flags_sv);
    async->usec_sv = newSVnv(0); SvREADONLY_on(async->usec_sv);
    async->sched_r_sv = newSViv(0); SvREADONLY_on(async->sched_r_sv);
    async->sched_w_sv = newSViv(0); SvREADONLY_on(async->sched_w_sv);
    async->stop_r_sv = newSViv(0); SvREADONLY_on(async->stop_r_sv);
    async->stop_w_sv = newSViv(0); SvREADONLY_on(async->stop_w_sv);

    /* i/o events */
    cbcio->v.v0.create_event = create_event;
    cbcio->v.v0.destroy_event = destroy_event;
    cbcio->v.v0.update_event = update_event;
    cbcio->v.v0.delete_event = delete_event;

    /* timer events */
    cbcio->v.v0.create_timer = create_timer;
    cbcio->v.v0.destroy_timer = destroy_event;
    cbcio->v.v0.delete_timer = delete_timer;
    cbcio->v.v0.update_timer = update_timer;

    wire_lcb_bsd_impl(cbcio);

    cbcio->v.v0.run_event_loop = startstop_dummy;
    cbcio->v.v0.stop_event_loop = startstop_dummy;
    cbcio->v.v0.need_cleanup = 0;

    /* Now all we need to do is return the blessed reference */
    return blessedrv;
}
Ejemplo n.º 13
0
Share *
new_share( key_t key, int segment_size, int flags ) {
  Share *share;
  Node *node;
  int semid;
  struct shmid_ds shmctl_arg;
  SEMUN semun_arg;

again:
  if ( ( semid = semget( key, 3, flags ) ) < 0 ) {
    LOG1( "semget failed (%d)", errno );
    return NULL;
  }

  /* It's possible for another process to obtain the semaphore, lock it, *
   * and remove it from the system before we have a chance to lock it.   *
   * In this case (EINVAL) we just try to create it again.               */
  if ( GET_EX_LOCK( semid ) < 0 ) {
    if ( errno == EINVAL ) {
      goto again;
    }
    LOG1( "GET_EX_LOCK failed (%d)", errno );
    return NULL;
  }

  /* XXX IS THIS THE RIGHT THING TO DO? */
  if ( segment_size <= sizeof( Header ) ) {
    segment_size = SHM_SEGMENT_SIZE;
  }

  Newxz( node, 1, Node );

  if ( ( node->shmid = shmget( key, segment_size, flags ) ) < 0 ) {
    LOG1( "shmget failed (%d)", errno );
    return NULL;
  }

  if ( ( node->shmaddr =
         ( Header * ) shmat( node->shmid, ( char * ) 0,
                             0 ) ) == ( Header * ) - 1 ) {
    LOG1( "shmat failed (%d)", errno );
    return NULL;
  }

  node->next = NULL;

  Newxz( share, 1, Share );

  share->key = key;
  share->next_key = key + 1;
  share->flags = flags;
  share->semid = semid;
  share->lock = 0;
  share->head = node;
  share->tail = node;

  /* is this a newly created segment?  if so, initialize it */
  if ( ( semun_arg.val =
         semctl( share->semid, 0, GETVAL, semun_arg ) ) < 0 ) {
    LOG1( "shmctl failed (%d)", errno );
    return NULL;
  }

  if ( semun_arg.val == 0 ) {
    semun_arg.val = 1;
    if ( semctl( share->semid, 0, SETVAL, semun_arg ) < 0 ) {
      LOG1( "shmctl failed (%d)", errno );
      return NULL;
    }
    share->head->shmaddr->length = 0;
    share->head->shmaddr->next_shmid = -1;
    share->head->shmaddr->shm_state = 1;
    share->head->shmaddr->version = 1;
  }

  share->shm_state = share->head->shmaddr->shm_state;
  share->version = share->head->shmaddr->version;

  /* determine the true length of the segment.  this may disagree *
   * with what the user requested, since shmget() calls will      *
   * succeed if the requested size <= the existing size           */
  if ( shmctl( share->head->shmid, IPC_STAT, &shmctl_arg ) < 0 ) {
    LOG1( "shmctl failed (%d)", errno );
    return NULL;
  }

  share->segment_size = shmctl_arg.shm_segsz;
  share->data_size = share->segment_size - sizeof( Header );

  if ( RM_EX_LOCK( semid ) < 0 ) {
    LOG1( "RM_EX_LOCK failed (%d)", errno );
    return NULL;
  }

  return share;
}
Ejemplo n.º 14
0
srl_splitter_t * srl_build_splitter_struct(pTHX_ HV *opt) {
    srl_splitter_t *splitter;
    SV **svp;
    STRLEN input_len;

    splitter = srl_empty_splitter_struct(aTHX);

    /* load options */
    svp = hv_fetchs(opt, "input", 0);
    if (svp && SvOK(*svp)) {
        splitter->input_str = SvPV(*svp, input_len);
        splitter->pos = splitter->input_str;
        splitter->input_len = input_len;
        splitter->input_str_end = splitter->input_str + input_len;
        splitter->input_sv = SvREFCNT_inc(*svp);
        SRL_SPLITTER_TRACE("input_size %" UVuf, input_len);
    } else {
        croak ("no input given");
    }
    svp = hv_fetchs(opt, "chunk_size", 0);
    if (svp && SvOK(*svp)) {
        splitter->size_limit = SvUV(*svp);
        SRL_SPLITTER_TRACE("size_limit %" UVuf, splitter->size_limit);
    }

    splitter->compression_format = 0;
    svp = hv_fetchs(opt, "compress", 0);
    if (svp && SvOK(*svp)) {
        IV compression_format = SvIV(*svp);

        /* See also Splitter.pm's constants */
        switch (compression_format) {
        case 0:
            SRL_SPLITTER_TRACE("no compression %s", "");
            break;
        case 1:
            croak("incremental snappy compression not yet supported. Try gzip");
            break;
        case 2:
            splitter->compression_format = 2;
            SRL_SPLITTER_TRACE("gzip compression %s", "");
            break;
        default:
            croak("invalid valie for 'compress' parameter");
        }
    }

    splitter->header_str = NULL;
    splitter->header_sv = NULL;
    splitter->header_len = 0;
    svp = hv_fetchs(opt, "header_data_template", 0);
    if (svp && SvOK(*svp)) {
        STRLEN header_len;
        splitter->header_str = SvPV(*svp, header_len);
        splitter->header_sv = SvREFCNT_inc(*svp);
        splitter->header_len = header_len;
        SRL_SPLITTER_TRACE("header_data_template found, of length %lu", header_len);
    }

    splitter->header_count_idx = -1;
    svp = hv_fetchs(opt, "header_count_idx", 0);
    if (svp && SvOK(*svp)) {
        splitter->header_count_idx = SvIV(*svp);
        SRL_SPLITTER_TRACE("header_count_idx found, %ld", splitter->header_count_idx);
    }

    _parse_header(aTHX_ splitter);

    /* initialize stacks */
    srl_splitter_stack_t * status_stack;
    Newxz(status_stack, 1, srl_splitter_stack_t );
    Newxz(status_stack->data, STACK_SIZE_INCR, UV );
    status_stack->size = STACK_SIZE_INCR;
    status_stack->top = 0;
    splitter->status_stack = status_stack;

    /* initialize */
    splitter->deepness = 0;

    char tag = *(splitter->pos);
    splitter->pos++;
    if (IS_SRL_HDR_ARRAYREF(tag)) {
        int len = tag & 0xF;
        splitter->input_nb_elts = len;
        SRL_SPLITTER_TRACE(" * ARRAYREF of len, %d", len);
        while (len-- > 0) {
            stack_push(splitter->status_stack, ST_VALUE);
        }
    } else if (tag == SRL_HDR_REFN) {
        tag = *(splitter->pos);
        splitter->pos++;
        if (tag == SRL_HDR_ARRAY) {
            UV len = _read_varint_uv_nocheck(splitter);
            splitter->input_nb_elts = len;
            SRL_SPLITTER_TRACE(" * ARRAY of len, %lu", len);
            while (len-- > 0) {
                stack_push(splitter->status_stack, ST_VALUE);
            }
        } else {
            croak("first tag is REFN but next tag is not ARRAY");
        }
    } else {
        croak("first tag is not an ArrayRef");
    }

    /* now splitter->pos is on the first array element */
    return splitter;
}
Ejemplo n.º 15
0
static AV*
S_mro_get_linear_isa_c3(pTHX_ HV* stash, U32 level)
{
    AV* retval;
    GV** gvp;
    GV* gv;
    AV* isa;
    const HEK* stashhek;
    struct mro_meta* meta;

    PERL_ARGS_ASSERT_MRO_GET_LINEAR_ISA_C3;
    assert(HvAUX(stash));

    stashhek = HvNAME_HEK(stash);
    if (!stashhek)
      Perl_croak(aTHX_ "Can't linearize anonymous symbol table");

    if (level > 100)
        Perl_croak(aTHX_ "Recursive inheritance detected in package '%s'",
		   HEK_KEY(stashhek));

    meta = HvMROMETA(stash);

    /* return cache if valid */
    if((retval = meta->mro_linear_c3)) {
        return retval;
    }

    /* not in cache, make a new one */

    gvp = (GV**)hv_fetchs(stash, "ISA", FALSE);
    isa = (gvp && (gv = *gvp) && isGV_with_GP(gv)) ? GvAV(gv) : NULL;

    if ( isa && ! SvAVOK(isa) ) {
	Perl_croak(aTHX_ "@ISA is not an array but %s", Ddesc((SV*)isa));
    }

    /* For a better idea how the rest of this works, see the much clearer
       pure perl version in Algorithm::C3 0.01:
       http://search.cpan.org/src/STEVAN/Algorithm-C3-0.01/lib/Algorithm/C3.pm
       (later versions go about it differently than this code for speed reasons)
    */

    if(isa && AvFILLp(isa) >= 0) {
        SV** seqs_ptr;
        I32 seqs_items;
        HV* const tails = MUTABLE_HV(sv_2mortal(MUTABLE_SV(newHV())));
        AV *const seqs = MUTABLE_AV(sv_2mortal(MUTABLE_SV(newAV())));
        I32* heads;

        /* This builds @seqs, which is an array of arrays.
           The members of @seqs are the MROs of
           the members of @ISA, followed by @ISA itself.
        */
        I32 items = AvFILLp(isa) + 1;
        SV** isa_ptr = AvARRAY(isa);
        while(items--) {
            SV* const isa_item = *isa_ptr++;
	    if ( ! SvPVOK(isa_item) ) {
		Perl_croak(aTHX_ "@ISA element which is not an plain value");
	    }
	    {
		HV* const isa_item_stash = gv_stashsv(isa_item, 0);
		if(!isa_item_stash) {
		    /* if no stash, make a temporary fake MRO
		       containing just itself */
		    AV* const isa_lin = newAV();
		    av_push(isa_lin, newSVsv(isa_item));
		    av_push(seqs, (SV*)isa_lin);
		}
		else {
		    /* recursion */
		    AV* const isa_lin = mro_get_linear_isa_c3(isa_item_stash, level + 1);
		    av_push(seqs, SvREFCNT_inc_NN((SV*)isa_lin));
		}
	    }
        }
        av_push(seqs, SvREFCNT_inc_NN((SV*)isa));

        /* This builds "heads", which as an array of integer array
           indices, one per seq, which point at the virtual "head"
           of the seq (initially zero) */
        Newxz(heads, AvFILLp(seqs)+1, I32);

        /* This builds %tails, which has one key for every class
           mentioned in the tail of any sequence in @seqs (tail meaning
           everything after the first class, the "head").  The value
           is how many times this key appears in the tails of @seqs.
        */
        seqs_ptr = AvARRAY(seqs);
        seqs_items = AvFILLp(seqs) + 1;
        while(seqs_items--) {
            AV *const seq = MUTABLE_AV(*seqs_ptr++);
            I32 seq_items = AvFILLp(seq);
            if(seq_items > 0) {
                SV** seq_ptr = AvARRAY(seq) + 1;
                while(seq_items--) {
                    SV* const seqitem = *seq_ptr++;
		    /* LVALUE fetch will create a new undefined SV if necessary
		     */
                    HE* const he = hv_fetch_ent(tails, seqitem, 1, 0);
                    if(he) {
                        SV* const val = HeVAL(he);
			/* This will increment undef to 1, which is what we
			   want for a newly created entry.  */
                        sv_inc(val);
                    }
                }
            }
        }

        /* Initialize retval to build the return value in */
        retval = newAV();
        av_push(retval, newSVhek(stashhek)); /* us first */

        /* This loop won't terminate until we either finish building
           the MRO, or get an exception. */
        while(1) {
            SV* cand = NULL;
            SV* winner = NULL;
            int s;

            /* "foreach $seq (@seqs)" */
            SV** const avptr = AvARRAY(seqs);
            for(s = 0; s <= AvFILLp(seqs); s++) {
                SV** svp;
                AV * const seq = MUTABLE_AV(avptr[s]);
		SV* seqhead;
                if(!seq) continue; /* skip empty seqs */
                svp = av_fetch(seq, heads[s], 0);
                seqhead = *svp; /* seqhead = head of this seq */
                if(!winner) {
		    HE* tail_entry;
		    SV* val;
                    /* if we haven't found a winner for this round yet,
                       and this seqhead is not in tails (or the count
                       for it in tails has dropped to zero), then this
                       seqhead is our new winner, and is added to the
                       final MRO immediately */
                    cand = seqhead;
                    if((tail_entry = hv_fetch_ent(tails, cand, 0, 0))
                       && (val = HeVAL(tail_entry))
                       && (SvIV(val) > 0))
                           continue;
                    winner = newSVsv(cand);
                    av_push(retval, winner);
                    /* note however that even when we find a winner,
                       we continue looping over @seqs to do housekeeping */
                }
                if(!sv_cmp(seqhead, winner)) {
                    /* Once we have a winner (including the iteration
                       where we first found him), inc the head ptr
                       for any seq which had the winner as a head,
                       NULL out any seq which is now empty,
                       and adjust tails for consistency */

                    const int new_head = ++heads[s];
                    if(new_head > AvFILLp(seq)) {
                        SvREFCNT_dec(avptr[s]);
                        avptr[s] = NULL;
                    }
                    else {
			HE* tail_entry;
			SV* val;
                        /* Because we know this new seqhead used to be
                           a tail, we can assume it is in tails and has
                           a positive value, which we need to dec */
                        svp = av_fetch(seq, new_head, 0);
                        seqhead = *svp;
                        tail_entry = hv_fetch_ent(tails, seqhead, 0, 0);
                        val = HeVAL(tail_entry);
                        sv_dec(val);
                    }
                }
            }

            /* if we found no candidates, we are done building the MRO.
               !cand means no seqs have any entries left to check */
            if(!cand) {
                Safefree(heads);
                break;
            }

            /* If we had candidates, but nobody won, then the @ISA
               hierarchy is not C3-incompatible */
            if(!winner) {
                SV *errmsg;
                I32 i;

                errmsg = newSVpvf(aTHX_ "Inconsistent hierarchy during C3 merge of class '%s':\n\t"
                                  "current merge results [\n", HEK_KEY(stashhek));
                for (i = 0; i <= av_len(retval); i++) {
                    SV **elem = av_fetch(retval, i, 0);
                    sv_catpvf(aTHX_ errmsg, "\t\t%"SVf",\n", SVfARG(*elem));
                }
                sv_catpvf(aTHX_ errmsg, "\t]\n\tmerging failed on '%"SVf"'", SVfARG(cand));

                /* we have to do some cleanup before we croak */

                AvREFCNT_dec(retval);
                Safefree(heads);

                croak(aTHX_ "%"SVf, SVfARG(errmsg));
            }
        }
    }
    else { /* @ISA was undefined or empty */
        /* build a retval containing only ourselves */
        retval = newAV();
        av_push(retval, newSVhek(stashhek));
    }

    /* we don't want anyone modifying the cache entry but us,
       and we do so by replacing it completely */
    SvREADONLY_on(retval);

    meta->mro_linear_c3 = retval;
    return retval;
}
Ejemplo n.º 16
0
void
PLCBA_request(
    SV *self,
    int cmd, int reqtype,
    SV *callcb, SV *cbdata, int cbtype,
    AV *params)
{
    PLCBA_cmd_t cmdtype;
    struct PLCBA_request_st r;
    
    PLCBA_t *async;
    libcouchbase_t instance;
    PLCB_t *base;
    AV *reqav;
    
    PLCBA_cookie_t *cookie;
    int nreq, i;
    libcouchbase_error_t *errors;
    int errcount;
    int has_conversion;
    
    SV **tmpsv;
    
    time_t *multi_exp;
    void **multi_key;
    size_t *multi_nkey;
    
    libcouchbase_error_t err;
    libcouchbase_storage_t storop;
    
    _mk_common_vars(self, instance, base, async);
    
    Newxz(cookie, 1, PLCBA_cookie_t);
    if(SvTYPE(callcb) == SVt_NULL) {
        die("Must have callback for asynchronous request");
    }
    
    if(reqtype == PLCBA_REQTYPE_MULTI) {
        nreq = av_len(params) + 1;
        if(!nreq) {
            die("No requests specified");
        }
    } else {
        nreq = 1;
    }
    
    cookie->callcb = callcb; SvREFCNT_inc(callcb);
    cookie->cbdata = cbdata; SvREFCNT_inc(cbdata);
    cookie->cbtype = cbtype;
    cookie->results = newHV();
    cookie->parent = async;
    cookie->remaining = nreq;
    
    /*pseudo-multi system:
     
     Most commands do not have a libcouchbase-level 'multi' implementation, but
     nevertheless it's more efficient to allow a 'multi' option from Perl because
     sub and xsub overhead is very expensive.
     
     Each operation defines a macro '_do_cbop' which does the following:
        1) call the libcouchbase api function appropriate for that operation
        2) set the function variable 'err' to the error which ocurred.
        
    the predefined pseudo_perform macro does the rest by doing the following:
        1) check to see if the request is multiple or single
        in the case of multiple requests, it:
            I) fetches the current request AV
            II) ensures the request is valid and defined
            III) extracts the information from the request into our request_st
                structure named 'r'
            IV) calls the locally-defined _do_cbop (which sets the error)
            V) checks the current value of 'err', if it is not a success, the
                error counter is incremented
            VI) when the loop has terminated, the error counter is checked again,
                and if it is greater than zero, the error dispatcher is called
        in the case of a single request, it:
            I) treats 'params' as the request AV
            II) passes the AV to av2request,
            III) calls _do_cbop once, and checks for errors
            IV) if there is an erorr, the dispatcher is called     
    */
    
    #define _fetch_assert(idx) \
        if((tmpsv = av_fetch(params, idx, 0)) == NULL) { \
            die("Null request found in request list"); \
        } \
        if(!SvROK(*tmpsv)) { \
            die("Expected reference type in parameter list."); \
        } \
        av2request(async, cmd, (AV*)(SvRV(*tmpsv)), &r);
        
    #define pseudo_multi_begin \
        Newxz(errors, nreq, libcouchbase_error_t); \
        errcount = 0;
    #define pseudo_multi_maybe_add \
        if( (errors[i] = err) != LIBCOUCHBASE_SUCCESS ) \
            errcount++;
    #define pseudo_multi_end \
        if(errcount) \
            error_pseudo_multi(async, params, errors, cookie); \
        Safefree(errors);
    
    #define pseudo_perform \
        if(reqtype == PLCBA_REQTYPE_MULTI) { \
            pseudo_multi_begin; \
            for(i = 0; i < nreq; i++) { \
                _fetch_assert(i); \
                _do_cbop(); \
                pseudo_multi_maybe_add; \
            } \
            if(errcount < nreq) { \
                libcouchbase_wait(instance); \
            } \
        } else { \
            av2request(async, cmd, params, &r); \
            _do_cbop(); \
            if(err != LIBCOUCHBASE_SUCCESS) { \
                warn("Key %s did not return OK (%d)", r.key, err); \
                error_single(async, cookie, r.key, r.nkey, err); \
            } else { \
                libcouchbase_wait(instance); \
            } \
        } \
    
    switch(cmd) {
        
    case PLCBA_CMD_GET:
    case PLCBA_CMD_TOUCH:
        #define _do_cbop(klist, szlist, explist) \
        if(cmd == PLCBA_CMD_GET) { \
            err = libcouchbase_mget(instance, cookie, nreq, \
                                    (const void* const*)klist, \
                                    (szlist), explist); \
        } else { \
            err = libcouchbase_mtouch(instance, cookie, nreq, \
                                    (const void* const*)klist, \
                                    szlist, explist); \
        }
        
        if(reqtype == PLCBA_REQTYPE_MULTI) {
            Newx(multi_key, nreq, void*);
            Newx(multi_nkey, nreq, size_t);
            Newx(multi_exp, nreq, time_t);
            for(i = 0; i < nreq; i++) {
                _fetch_assert(i);
                multi_key[i] = r.key;
                multi_nkey[i] = r.nkey;
                multi_exp[i] = r.exp;
            }

            _do_cbop(multi_key, multi_nkey, multi_exp);
            if(err != LIBCOUCHBASE_SUCCESS) {
                error_true_multi(
                    async, cookie, nreq, (const char**)multi_key, multi_nkey, err);
            } else {
                libcouchbase_wait(instance);
            }
            Safefree(multi_key);
            Safefree(multi_nkey);
            Safefree(multi_exp);
        } else {
            av2request(async, cmd, params, &r);
            _do_cbop(&(r.key), &(r.nkey), &(r.exp));
            if(err != LIBCOUCHBASE_SUCCESS) {
                error_single(async, cookie, r.key, r.nkey, err);
            } else {
                libcouchbase_wait(instance);
            }
        }
        break;
        #undef _do_cbop

    case PLCBA_CMD_SET:
    case PLCBA_CMD_ADD:
    case PLCBA_CMD_REPLACE:
    case PLCBA_CMD_APPEND:
    case PLCBA_CMD_PREPEND:
        storop = async_cmd_to_storop(cmd);
        //warn("Storop is %x (cmd=%x)", storop, cmd);
        has_conversion = plcba_cmd_needs_conversion(cmd);
        #define _do_cbop() \
            err = libcouchbase_store(instance, cookie, storop, r.key, r.nkey, \
                                    SvPVX(r.value), r.nvalue, r.store_flags, \
                                    r.exp, r.cas); \
            if(has_conversion) { \
                plcb_convert_storage_free(base, r.value, r.store_flags); \
            }
        
        pseudo_perform;
        break;
        #undef _do_cbop
    
    case PLCBA_CMD_ARITHMETIC:
        #define _do_cbop() \
            err = libcouchbase_arithmetic(instance, cookie, r.key, r.nkey, \
                                r.arithmetic.delta, r.exp, \
                                r.arithmetic.create, r.arithmetic.initial);
        pseudo_perform;
        break;
        #undef _do_cbop
    case PLCBA_CMD_REMOVE:
        #define _do_cbop() \
            err = libcouchbase_remove(instance, cookie, r.key, r.nkey, r.cas);
        pseudo_perform;
        break;
        #undef _do_cbop

    default:
        die("Unimplemented!");
    }
    
    #undef _fetch_assert
    #undef pseudo_multi_begin
    #undef pseduo_multi_maybe_add
    #undef pseudo_multi_end
    #undef pseudo_perform
}