Exemple #1
0
static floperr_t get_offset(floppy_image_legacy *floppy, int head, int track, int sector, int sector_is_index, UINT64 *offset)
{
	UINT64 offs;
	UINT64 track_offset;
	UINT8 track_info[0x100];
	UINT8 sectors_per_track;
	int i;
	/* translate the sector to a raw sector */

	/* check to see if we are out of range */
	if ((head < 0) || (head >= get_tag(floppy)->heads) || (track < 0) || (track >= get_tag(floppy)->tracks)
			|| (sector < 0) )
		return FLOPPY_ERROR_SEEKERROR;

	track_offset = dsk_get_track_offset(floppy, head, track);

	floppy_image_read(floppy, track_info, track_offset, 0x100);

	sectors_per_track = track_info[0x015];
	if (!sector_is_index) {
		if (sector >= sectors_per_track) {
			return FLOPPY_ERROR_SEEKERROR;
		}
	}

	if (get_tag(floppy)->disk_image_type==0) {
		get_tag(floppy)->sector_size = (1<<(track_info[0x014]+7));
		offs = track_offset + 0x100 +sector * get_tag(floppy)->sector_size;
	} else {
		get_tag(floppy)->sector_size = track_info[0x18 + (sector<<3) + 6] + (track_info[0x18+(sector<<3) + 7]<<8);
		offs = track_offset + 0x100;
		for (i=0;i<sector;i++) {
			offs += track_info[0x18 + (i<<3) + 6] + (track_info[0x18+(i<<3) + 7]<<8);
		}
	}

	if (offset)
		*offset = offs;
	return FLOPPY_ERROR_SUCCESS;
}
static floperr_t internal_td0_read_sector(floppy_image_legacy *floppy, int head, int track, int sector, int sector_is_index, void *buffer, size_t buflen)
{
	UINT64 offset;
	floperr_t err;
	UINT8 *header;
	int size,realsize,i;
	int buff_pos;
	int data_pos;
	UINT8 *data;
	UINT8 *buf;

	buf = (UINT8*)buffer;
	// take sector offset
	err = get_offset(floppy, head, track, sector, sector_is_index, &offset);
	if (err)
		return err;

	// read sector header
	header = get_tag(floppy)->data + offset;
	offset+=6;
	// if there is no date just jump out
	if ((header[4] & 0x30)!=0) return FLOPPY_ERROR_SUCCESS;

	offset+=3;
	// take data size
	size = header[6] + (header[7]<<8)-1;
	// take real sector size
	realsize =  1 << (header[3] + 7);

	// read sector data
	data = get_tag(floppy)->data + offset;
	buff_pos = 0;
	data_pos = 0;

	switch(header[8]) {
		case 0:
				// encoding type 0
				//  - plain data
				memcpy(buffer,data,size);
				break;
		case 1:
				// encoding type 1
				//  - 2 bytes size
				//  - 2 bytes of data
				//  data is reapeted specified number of times
				while(buff_pos<realsize) {
					for (i=0;i<data[data_pos]+(data[data_pos+1] << 8);i++) {
						buf[buff_pos] = data[data_pos+2];buff_pos++;
						buf[buff_pos] = data[data_pos+3];buff_pos++;
					}
					data_pos+=4;
				}
				break;
		case 2:
				// encoding type 2
				//  - if first byte is zero next byte represent size of
				//      plain data after it
				//  - if different then zero when multiply by 2 represent
				//      size of data that should be reapeted next byte times
				while(buff_pos<realsize) {
					if (data[data_pos]==0x00) {
						int size_ = data[data_pos+1];
						memcpy(buf+buff_pos,data + data_pos + 2,size_);
						data_pos += 2 + size_;
						buff_pos += size_;
					} else {
						int size_  = 2*data[data_pos];
						int repeat = data[data_pos+1];
						data_pos+=2;

						for (i=0;i<repeat;i++) {
							memcpy(buf + buff_pos,data + data_pos,size_);
							buff_pos += size_;
						}
						data_pos += size_;
					}
				}
				break;
		default:
				return FLOPPY_ERROR_INTERNAL;
	}
	return FLOPPY_ERROR_SUCCESS;
}
Exemple #3
0
/* Given the enclosing tag t, decode from asn1/len the contents of the ASN.1
 * type specified by a, placing the result into val (caller-allocated). */
static asn1_error_code
decode_atype(const taginfo *t, const unsigned char *asn1,
             size_t len, const struct atype_info *a, void *val)
{
    asn1_error_code ret;

    switch (a->type) {
    case atype_fn: {
        const struct fn_info *fn = a->tinfo;
        assert(fn->dec != NULL);
        return fn->dec(t, asn1, len, val);
    }
    case atype_sequence:
        return decode_sequence(asn1, len, a->tinfo, val);
    case atype_ptr: {
        const struct ptr_info *ptrinfo = a->tinfo;
        void *ptr = LOADPTR(val, ptrinfo);
        assert(ptrinfo->basetype != NULL);
        if (ptr != NULL) {
            /* Container was already allocated by a previous sequence field. */
            return decode_atype(t, asn1, len, ptrinfo->basetype, ptr);
        } else {
            ret = decode_atype_to_ptr(t, asn1, len, ptrinfo->basetype, &ptr);
            if (ret)
                return ret;
            STOREPTR(ptr, ptrinfo, val);
            break;
        }
    }
    case atype_offset: {
        const struct offset_info *off = a->tinfo;
        assert(off->basetype != NULL);
        return decode_atype(t, asn1, len, off->basetype,
                            (char *)val + off->dataoff);
    }
    case atype_optional: {
        const struct optional_info *opt = a->tinfo;
        return decode_atype(t, asn1, len, opt->basetype, val);
    }
    case atype_counted: {
        const struct counted_info *counted = a->tinfo;
        void *dataptr = (char *)val + counted->dataoff;
        size_t count;
        assert(counted->basetype != NULL);
        ret = decode_cntype(t, asn1, len, counted->basetype, dataptr, &count);
        if (ret)
            return ret;
        return store_count(count, counted, val);
    }
    case atype_tagged_thing: {
        const struct tagged_info *tag = a->tinfo;
        taginfo inner_tag;
        const taginfo *tp = t;
        const unsigned char *rem;
        size_t rlen;
        if (!tag->implicit) {
            ret = get_tag(asn1, len, &inner_tag, &asn1, &len, &rem, &rlen);
            if (ret)
                return ret;
            /* Note: we don't check rlen (it should be 0). */
            tp = &inner_tag;
            if (!check_atype_tag(tag->basetype, tp))
                return ASN1_BAD_ID;
        }
        return decode_atype(tp, asn1, len, tag->basetype, val);
    }
    case atype_bool: {
        intmax_t intval;
        ret = k5_asn1_decode_bool(asn1, len, &intval);
        if (ret)
            return ret;
        return store_int(intval, a->size, val);
    }
    case atype_int: {
        intmax_t intval;
        ret = k5_asn1_decode_int(asn1, len, &intval);
        if (ret)
            return ret;
        return store_int(intval, a->size, val);
    }
    case atype_uint: {
        uintmax_t intval;
        ret = k5_asn1_decode_uint(asn1, len, &intval);
        if (ret)
            return ret;
        return store_uint(intval, a->size, val);
    }
    case atype_int_immediate: {
        const struct immediate_info *imm = a->tinfo;
        intmax_t intval;
        ret = k5_asn1_decode_int(asn1, len, &intval);
        if (ret)
            return ret;
        if (intval != imm->val && imm->err != 0)
            return imm->err;
        break;
    }
    default:
        /* Null-terminated sequence types are handled in decode_atype_to_ptr,
         * since they create variable-sized objects. */
        assert(a->type != atype_nullterm_sequence_of);
        assert(a->type != atype_nonempty_nullterm_sequence_of);
        assert(a->type > atype_min);
        assert(a->type < atype_max);
        abort();
    }
    return 0;
}
Exemple #4
0
static int imd_get_tracks_per_disk(floppy_image_legacy *floppy)
{
	return get_tag(floppy)->tracks;
}
Exemple #5
0
 tag_t get_next_tag() const
 {
     tag_t next = (get_tag() + 1u) & (std::numeric_limits<tag_t>::max)();
     return next;
 }
static int g64_get_tracks_per_disk(floppy_image *floppy)
{
	return get_tag(floppy)->tracks;
}
Exemple #7
0
int read_item(
    int parent,
    void (*func)(void))
{
/**
Function: General function to read an item and fill in appropriate global
variables
Input: File descriptor for input
Outputs: Sets option flags
         Fills in tag, type, min, max, itemname, subclass, subtype,
            defaultname and numstring
Procedure:
1. WHILE token is neither ',' NOR '}'
        IF token is '[', get tag
        ELSE IF token is '('
            IF enumerated flag set, get material for tag or sub_val
            ELSE Get min-max
        ELSE IF token is CHOICE, set constructed bit in type
        ELSE IF token is COMPONENTS, do components stuff
        ELSE IF token is DEFAULT, make defaultname and set default flag
        ELSE IF token is DEFINED, do the defined thing to fill in defined_by
        ELSE IF token is EMPTY, do nothing
        ELSE IF token is EXPLICIT, set temporary explicit flag
        ELSE IF token is FUNCTION
            Set type
            Get all tokens up to comma or right brace
        ELSE IF token is IMPLICIT, clear temporary explicit flag
        ELSE IF token is OF, error
        ELSE IF token is OPTIONAL, set OPTIONAL flag in options
        ELSE IF token is SIZE, get min-max
        ELSE IF token is TABLE
            Get table name to skip it
            Set table variable
        ELSE IF token is TAGS OR UNIQUE, swallow it
        ELSE IF token is a defined type
            IF this is a table AND (there's a type OR a subclass already)
                append token to alt_subclasses
            ELSE IF have a subclass already, syntax error
            ELSE IF have no type yet, use that
            ELSE IF explicit tagging, set subtype
            ELSE
                'Or' the constructed bit into type
                Get expected sequel to token, if any
        ELSE IF token begins with a number
            IF TABLE bit is set, convert number
            ELSE IF enumerated flag is set
                Put token into itemname prefixed with e
                Set enumerated flag
        ELSE IF in a table AND (token is TRUE OR FALSE)
            Make type boolean
            Put token in subclass
        ELSE IF name begins with a capital letter
            IF this is a table item AND (there is already a subclass OR a type)
                Append this to the alt_subclasses
            ELSE IF there is already a subclass OR a type, syntax error
            ELSE set the subclass and option from the token
        ELSE IF name begins with a lower-case letter
            IF this is a table item, increment the array count
            IF no itemname so far, set token in itemname with options
        IF no next token, return -1
2. IF token is '}'
        Peek at the next token
        IF it's '(', set the constrained flag
   Return 0
**/
    char *c;
    long tmp;
    struct name_table *ntbp;
    struct id_table *idp = (struct id_table *)0;
    int parens;
    struct alt_subclass *altscp = (struct alt_subclass *)0;
    while (*token != ',' && *token != '}')
    {
        if (*token == '[')
        {
            tmp = get_tag(token);
            if (tag >= 0)
                tag |= tmp;
            else
                tag = tmp;
        }
        else if (*token == '(')
        {
            if ((flags & ASN_ENUM_FLAG))
            {
                if (!get_token(0, token))
                    syntax(itemname);
                if (*(c = token) == '_')
                    c++;
                if (find_name(classname)->type == ASN_OBJ_ID)
                {
                    if (*c > '2')
                    {
                        if (!(idp = find_id(c)))
                            syntax(c);
                        strcpy(c, idp->val);
                        idp = (struct id_table *)0;
                    }
                    sub_val = (char *)calloc(1, strlen(c) + 1);
                    strcpy(sub_val, c);
                }
                else if (*c >= '0' && *c <= '9')
                {
                    for (integer_val = 0; *c;
                         integer_val = (integer_val * 10) + *c++ - '0');
                    if (*token == '_')
                        integer_val = -integer_val;
                }
                else
                {
                    integer_val = find_ub(token);
                    add_child(token, parent, 0, (ulong) - 1, 0);
                }
                if (!get_known(0, token, ")"))
                    syntax(itemname);
            }
            else
                get_paren(token, &min, &max, parent);
        }
        else if (!strcmp(token, choice_w))
        {
            if (tag >= 0)
                tag |= ASN_CONSTRUCTED;
            else if (type >= 0)
                type |= ASN_CONSTRUCTED;
            else
                type = ASN_CONSTRUCTED;
        }
        else if (!strcmp(token, components_w))
            do_components(func);
        else if (!strcmp(token, default_w))
        {
            option |= (ASN_OPTIONAL_FLAG | ASN_DEFAULT_FLAG);
            get_token(0, token);
            c = defaultname;
            if (*token >= '0' && *token <= '9')
                *c++ = '0';
            else if (!strcmp(token, empty_w) || !strcmp(token, null_w) ||
                     (*token == '"' && token[1] == '"'))
                cat(token, "{");
            strcpy(c, token);
        }
        else if (!strcmp(token, defined_w))
        {
            do_defined();
        }
        else if (!strcmp(token, empty_w));
        else if (!strcmp(token, explicit_w))
            explicit1 |= 1;
        else if (!strcmp(token, function_w))
        {
            type = ASN_FUNCTION;
            for (c = itemname, parens = 0; get_must(0, token) && (parens ||
                                                                  (*token !=
                                                                   ','
                                                                   && *token !=
                                                                   '}'));)
            {
                if (*token == '(')
                    parens++;
                else if (*token == ')')
                    parens--;
                c = cat(cat(c, token), " ");
            }
            break;
        }
        else if (!strcmp(token, implicit_w))
        {
            explicit1 &= ~1;
            if (*subclass && tag < ASN_APPL_SPEC
                && (ntbp = find_name(subclass)) && ntbp->name)
            {
                if (type < 0)
                    type = ntbp->type;
                else if (ntbp->type != -1)
                    type |= (ntbp->type & ASN_CONSTRUCTED);
            }
        }
        else if (!strcmp(token, in_w))
        {
            if (!*definer)
                syntax(token);
            if (!get_token(0, inclass))
                syntax(definer);
        }
        else if (!strcmp(token, of_w))
            syntax(token);
        else if (!strcmp(token, optional_w))
        {
            option |= ASN_OPTIONAL_FLAG;
            if (altscp)
            {
                altscp->options = option;
                option &= ~(ASN_OPTIONAL_FLAG);
            }
        }
        else if (!strcmp(token, size_w))
        {
            get_size(token, &min, &max, parent);
            // if (type == ASN_UTCTIME || type == ASN_GENTIME) min = max = 0;
        }
        else if (!strcmp(token, table_w))
        {
            if (!get_token(0, tablename))
                syntax(table_w);
            if (*tablename < 'A' || *tablename > 'Z')
                syntax(tablename);
            option |= ASN_TABLE_FLAG;
        }
        else if (!strcmp(token, tags_w) || !strcmp(token, unique_w));
        else if ((tmp = (int)find_type(token)) != ASN_NOTYPE)
        {
            if ((flags & ASN_TABLE_FLAG) && (*subclass || type >= 0))
                altscp = append_subclasses(token);
            else if (*subclass)
                syntax(token);
            if (type < 0)
                type = (ulong) tmp;
            else if ((explicit1 & 1))
                subtype = (short)tmp;
            else if (tmp > 0)
                type |= (tmp & ASN_CONSTRUCTED);
            get_expected(0, tmp, token);
        }
        else if ((*token >= '0' && *token <= '9') ||
                 (*itemname && (idp = find_id(token))) || is_ub(token))
        {
            if (*token > '9')
            {
                if (idp)
                    cat(token, idp->val);
                else
                {
                    add_name(token, -1, 0);     /* keep it off the 'Defined
                                                 * but not used' list */
                    sprintf(token, "%ld", find_ub(token));
                }
            }
            if ((flags & ASN_TABLE_FLAG))
            {
                if (*token >= '0' && *token <= '9')
                    cvt_number(numstring, token);
            }
            else if ((flags & ASN_ENUM_FLAG))
            {
                if (!*itemname)
                    cat(cat(itemname, "e"), token);
                else
                {
                    if (*(c = token) == '_')
                        c++;
                    for (integer_val = 0; *c;
                         integer_val = (integer_val * 10) + *c++ - '0');
                    if (*token == '_')
                        integer_val = -integer_val;
                }
            }
            idp = (struct id_table *)0;
        }
        else if ((flags & ASN_TABLE_FLAG) && (!strcmp(token, false_w) ||
                                              !strcmp(token, true_w)
                                              || !strcmp(token, either_w)))
        {
            type = ASN_BOOLEAN;
            cat(subclass, token);
        }
        else if ((*token >= 'A' && *token <= 'Z') || *token == '*')
        {
            if ((flags & ASN_TABLE_FLAG))
            {
                if (!strcmp(token, "NONE"))
                    cat(token, "AsnNone");
                if (*subclass || type > 0)
                    altscp = append_subclasses(token);
                else
                    option |= set_name_option(subclass, token);
            }
            else if ((type > 0 && type < ASN_CHOICE) || *subclass)
                syntax(token);
            else
                option |= set_name_option(subclass, token);
        }
        else if (*token >= 'a' && *token <= 'z')
        {
            if ((flags & ASN_TABLE_FLAG))
                array++;
            if (*itemname)
                warn(MSG_SYNTAX_ERR, token);
            else
                cat(itemname, token);
        }
        if (!get_token(0, token))
            return -1;
    }
    if (*definer && !*inclass)
        cat(inclass, classname);
    if (*token == '}' && *peek_token(0) == '(')
    {
        get_known(0, &token[2], "(");
        get_def_paren(&token[2]);
    }
    return 0;
}
Exemple #8
0
static void gpx_end(VikTrwLayer *vtl, const char *el)
{
  static GTimeVal tp_time;
  static GTimeVal wp_time;

  g_string_truncate ( xpath, xpath->len - strlen(el) - 1 );

  switch ( current_tag ) {

     case tt_gpx:
       vik_trw_layer_set_metadata ( vtl, c_md );
       c_md = NULL;
       break;

     case tt_gpx_name:
       vik_layer_rename ( VIK_LAYER(vtl), c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_gpx_author:
       if ( c_md->author )
         g_free ( c_md->description );
       c_md->author = g_strdup ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_gpx_desc:
       if ( c_md->description )
         g_free ( c_md->description );
       c_md->description = g_strdup ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_gpx_keywords:
       if ( c_md->keywords )
         g_free ( c_md->keywords );
       c_md->keywords = g_strdup ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_gpx_time:
       if ( c_md->timestamp )
         g_free ( c_md->timestamp );
       c_md->timestamp = g_strdup ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_waypoint:
     case tt_wpt:
       if ( ! c_wp_name )
         c_wp_name = g_strdup_printf("VIKING_WP%04d", unnamed_waypoints++);
       vik_trw_layer_filein_add_waypoint ( vtl, c_wp_name, c_wp );
       g_free ( c_wp_name );
       c_wp = NULL;
       c_wp_name = NULL;
       break;

     case tt_trk:
       if ( ! c_tr_name )
         c_tr_name = g_strdup_printf("VIKING_TR%03d", unnamed_tracks++);
       // Delibrate fall through
     case tt_rte:
       if ( ! c_tr_name )
         c_tr_name = g_strdup_printf("VIKING_RT%03d", unnamed_routes++);
       vik_trw_layer_filein_add_track ( vtl, c_tr_name, c_tr );
       g_free ( c_tr_name );
       c_tr = NULL;
       c_tr_name = NULL;
       break;

     case tt_wpt_name:
       if ( c_wp_name )
         g_free ( c_wp_name );
       c_wp_name = g_strdup ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_name:
       if ( c_tr_name )
         g_free ( c_tr_name );
       c_tr_name = g_strdup ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_wpt_ele:
       c_wp->altitude = g_ascii_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_ele:
       c_tp->altitude = g_ascii_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_waypoint_name: /* .loc name is really description. */
     case tt_wpt_desc:
       vik_waypoint_set_description ( c_wp, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_wpt_cmt:
       vik_waypoint_set_comment ( c_wp, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_wpt_url:
       vik_waypoint_set_url ( c_wp, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_wpt_link:
       vik_waypoint_set_image ( c_wp, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_wpt_sym: {
       vik_waypoint_set_symbol ( c_wp, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;
       }

     case tt_trk_desc:
       vik_track_set_description ( c_tr, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_cmt:
       vik_track_set_comment ( c_tr, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_wpt_time:
       if ( g_time_val_from_iso8601(c_cdata->str, &wp_time) ) {
         c_wp->timestamp = wp_time.tv_sec;
         c_wp->has_timestamp = TRUE;
       }
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_name:
       vik_trackpoint_set_name ( c_tp, c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_time:
       if ( g_time_val_from_iso8601(c_cdata->str, &tp_time) ) {
         c_tp->timestamp = tp_time.tv_sec;
         c_tp->has_timestamp = TRUE;
       }
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_course:
       c_tp->course = g_ascii_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_speed:
       c_tp->speed = g_ascii_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_fix:
       if (!strcmp("2d", c_cdata->str))
         c_tp->fix_mode = VIK_GPS_MODE_2D;
       else if (!strcmp("3d", c_cdata->str))
         c_tp->fix_mode = VIK_GPS_MODE_3D;
       else  /* TODO: more fix modes here */
         c_tp->fix_mode = VIK_GPS_MODE_NOT_SEEN;
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_sat:
       c_tp->nsats = atoi ( c_cdata->str );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_hdop:
       c_tp->hdop = g_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_vdop:
       c_tp->vdop = g_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     case tt_trk_trkseg_trkpt_pdop:
       c_tp->pdop = g_strtod ( c_cdata->str, NULL );
       g_string_erase ( c_cdata, 0, -1 );
       break;

     default: break;
  }

  current_tag = get_tag ( xpath->str );
}
Exemple #9
0
int ompi_osc_pt2pt_compare_and_swap (const void *origin_addr, const void *compare_addr,
                                    void *result_addr, struct ompi_datatype_t *dt,
                                    int target, OPAL_PTRDIFF_TYPE target_disp,
                                    struct ompi_win_t *win)
{
    ompi_osc_pt2pt_module_t *module = GET_MODULE(win);
    ompi_proc_t *proc = ompi_comm_peer_lookup(module->comm, target);
    ompi_osc_pt2pt_frag_t *frag;
    ompi_osc_pt2pt_header_cswap_t *header;
    ompi_osc_pt2pt_sync_t *pt2pt_sync;
    size_t ddt_len, payload_len, frag_len;
    ompi_osc_pt2pt_request_t *request;
    const void *packed_ddt;
    int ret, tag;
    char *ptr;

    OPAL_OUTPUT_VERBOSE((50, ompi_osc_base_framework.framework_output,
                         "cswap: 0x%lx, 0x%lx, 0x%lx, %s, %d, %d, %s",
                         (unsigned long) origin_addr, (unsigned long) compare_addr,
                         (unsigned long) result_addr, dt->name, target, (int) target_disp,
                         win->w_name));

    pt2pt_sync = ompi_osc_pt2pt_module_sync_lookup (module, target, NULL);
    if (OPAL_UNLIKELY(NULL == pt2pt_sync)) {
        return OMPI_ERR_RMA_SYNC;
    }

    /* optimize self case. TODO: optimize local case */
    if (ompi_comm_rank (module->comm) == target) {
        return ompi_osc_pt2pt_cas_self (pt2pt_sync, origin_addr, compare_addr, result_addr, dt, target_disp,
                                        module);
    }

    /* compare-and-swaps are always request based, so that we know where to land the data */
    OMPI_OSC_PT2PT_REQUEST_ALLOC(win, request);

    request->type = OMPI_OSC_PT2PT_HDR_TYPE_CSWAP;
    request->origin_addr = origin_addr;
    request->internal = true;
    OMPI_DATATYPE_RETAIN(dt);
    request->origin_dt = dt;

    /* Compute datatype and payload lengths.  Note that the datatype description
     * must fit in a single frag. It should be small in this case. */
    ddt_len = ompi_datatype_pack_description_length(dt);

    /* we need to send both the origin and compare buffers */
    payload_len = dt->super.size * 2;

    ret = ompi_datatype_get_pack_description(dt, &packed_ddt);
    if (OMPI_SUCCESS != ret) {
        return ret;
    }

    frag_len = sizeof(ompi_osc_pt2pt_header_cswap_t) + ddt_len + payload_len;
    ret = ompi_osc_pt2pt_frag_alloc(module, target, frag_len, &frag, &ptr, false, false);
    if (OMPI_SUCCESS != ret) {
        return OMPI_ERR_OUT_OF_RESOURCE;
    }

    tag = get_tag (module);
    ompi_osc_signal_outgoing (module, target, 1);

    header = (ompi_osc_pt2pt_header_cswap_t *) ptr;
    header->base.type = OMPI_OSC_PT2PT_HDR_TYPE_CSWAP;
    header->base.flags = OMPI_OSC_PT2PT_HDR_FLAG_VALID;
    header->len = frag_len;
    header->displacement = target_disp;
    header->tag = tag;
    osc_pt2pt_hton(header, proc);
    ptr += sizeof(ompi_osc_pt2pt_header_cswap_t);

    memcpy((unsigned char*) ptr, packed_ddt, ddt_len);
    ptr += ddt_len;

    /* pack the origin and compare data */
    osc_pt2pt_copy_for_send (ptr, dt->super.size, origin_addr, proc, 1, dt);
    ptr += dt->super.size;
    osc_pt2pt_copy_for_send (ptr, dt->super.size, compare_addr, proc, 1, dt);

    request->outstanding_requests = 1;
    ret = ompi_osc_pt2pt_irecv_w_cb (result_addr, 1, dt,
                                    target, tag_to_origin(tag), module->comm,
                                    NULL, ompi_osc_pt2pt_req_comm_complete, request);
    if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
        return ret;
    }

    return ompi_osc_pt2pt_frag_finish (module, frag);
}
Exemple #10
0
static int
ompi_osc_pt2pt_accumulate_w_req (const void *origin_addr, int origin_count,
                                struct ompi_datatype_t *origin_dt,
                                int target, OPAL_PTRDIFF_TYPE target_disp,
                                int target_count,
                                struct ompi_datatype_t *target_dt,
                                struct ompi_op_t *op, ompi_win_t *win,
                                ompi_osc_pt2pt_request_t *request)
{
    int ret;
    ompi_osc_pt2pt_module_t *module = GET_MODULE(win);
    ompi_proc_t *proc = ompi_comm_peer_lookup(module->comm, target);
    bool is_long_datatype = false;
    bool is_long_msg = false;
    ompi_osc_pt2pt_frag_t *frag;
    ompi_osc_pt2pt_header_acc_t *header;
    ompi_osc_pt2pt_sync_t *pt2pt_sync;
    size_t ddt_len, payload_len, frag_len;
    char *ptr;
    const void *packed_ddt;
    int tag = -1;

    OPAL_OUTPUT_VERBOSE((50, ompi_osc_base_framework.framework_output,
                         "acc: 0x%lx, %d, %s, %d, %d, %d, %s, %s, %s",
                         (unsigned long) origin_addr, origin_count,
                         origin_dt->name, target, (int) target_disp,
                         target_count, target_dt->name, op->o_name,
                         win->w_name));

    pt2pt_sync = ompi_osc_pt2pt_module_sync_lookup (module, target, NULL);
    if (OPAL_UNLIKELY(NULL == pt2pt_sync)) {
        return OMPI_ERR_RMA_SYNC;
    }

    /* short-circuit case */
    if (0 == origin_count || 0 == target_count) {
        if (request) {
            ompi_osc_pt2pt_request_complete (request, MPI_SUCCESS);
        }

        return OMPI_SUCCESS;
    }

    /* optimize the self case. TODO: optimize the local case */
    if (ompi_comm_rank (module->comm) == target) {
        return ompi_osc_pt2pt_acc_self (pt2pt_sync, origin_addr, origin_count, origin_dt,
                                        target_disp, target_count, target_dt,
                                        op, module, request);
    }

    /* Compute datatype and payload lengths.  Note that the datatype description
     * must fit in a single frag */
    ddt_len = ompi_datatype_pack_description_length(target_dt);
    payload_len = origin_dt->super.size * origin_count;

    frag_len = sizeof(*header) + ddt_len + payload_len;
    ret = ompi_osc_pt2pt_frag_alloc(module, target, frag_len, &frag, &ptr, false, true);
    if (OMPI_SUCCESS != ret) {
        frag_len = sizeof(*header) + ddt_len;
        ret = ompi_osc_pt2pt_frag_alloc(module, target, frag_len, &frag, &ptr, true, !request);
        if (OMPI_SUCCESS != ret) {
            /* allocate space for the header plus space to store ddt_len */
            frag_len = sizeof(*header) + 8;
            ret = ompi_osc_pt2pt_frag_alloc(module, target, frag_len, &frag, &ptr, true, !request);
            if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
                return OMPI_ERR_OUT_OF_RESOURCE;
            }

            is_long_datatype = true;
         }

        is_long_msg = true;
        tag = get_tag (module);
    } else {
        /* still need to set the tag for the active/passive logic on the target */
        tag = !!(module->passive_target_access_epoch);
    }

    if (is_long_msg) {
        /* wait for synchronization before posting a long message */
        if (pt2pt_sync->type == OMPI_OSC_PT2PT_SYNC_TYPE_LOCK) {
            OPAL_THREAD_LOCK(&pt2pt_sync->lock);
            ompi_osc_pt2pt_peer_t *peer = ompi_osc_pt2pt_peer_lookup (module, target);
            while (!(peer->flags & OMPI_OSC_PT2PT_PEER_FLAG_EAGER)) {
                opal_condition_wait(&pt2pt_sync->cond, &pt2pt_sync->lock);
            }
            OPAL_THREAD_UNLOCK(&pt2pt_sync->lock);
        } else {
            ompi_osc_pt2pt_sync_wait_expected (pt2pt_sync);
        }
    }

    header = (ompi_osc_pt2pt_header_acc_t*) ptr;
    header->base.flags = 0;
    header->len = frag_len;
    header->count = target_count;
    header->displacement = target_disp;
    header->op = op->o_f_to_c_index;
    header->tag = tag;
    ptr += sizeof (*header);

    do {
        ret = ompi_datatype_get_pack_description(target_dt, &packed_ddt);
        if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
            break;
        }

        if (is_long_datatype) {
            /* the datatype does not fit in an eager message. send it seperately */
            header->base.flags |= OMPI_OSC_PT2PT_HDR_FLAG_LARGE_DATATYPE;

            OMPI_DATATYPE_RETAIN(target_dt);

            ret = ompi_osc_pt2pt_isend_w_cb ((void *) packed_ddt, ddt_len, MPI_BYTE,
                                            target, tag_to_target(tag), module->comm,
                                            ompi_osc_pt2pt_dt_send_complete, target_dt);
            if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
                break;
            }

            *((uint64_t *) ptr) = ddt_len;
            ptr += 8;
        } else {
            memcpy((unsigned char*) ptr, packed_ddt, ddt_len);
            ptr += ddt_len;
        }

        if (!is_long_msg) {
            header->base.type = OMPI_OSC_PT2PT_HDR_TYPE_ACC;
            osc_pt2pt_hton(header, proc);

            osc_pt2pt_copy_for_send (ptr, payload_len, origin_addr, proc,
                                    origin_count, origin_dt);

            /* the user's buffer is no longer needed so mark the request as
             * complete. */
            if (request) {
                ompi_osc_pt2pt_request_complete (request, MPI_SUCCESS);
            }
        } else {
            header->base.type = OMPI_OSC_PT2PT_HDR_TYPE_ACC_LONG;
            osc_pt2pt_hton(header, proc);

            OPAL_OUTPUT_VERBOSE((25, ompi_osc_base_framework.framework_output,
                                 "acc: starting long accumulate with tag %d", tag));

            ret = ompi_osc_pt2pt_data_isend (module, origin_addr, origin_count, origin_dt,
                                            target, tag_to_target(tag), request);
        }
    } while (0);

    if (OMPI_SUCCESS != ret) {
        OPAL_OUTPUT_VERBOSE((25, ompi_osc_base_framework.framework_output,
                             "acc: failed with eror %d", ret));
    } else {
        /* mark the fragment as valid */
        header->base.flags |= OMPI_OSC_PT2PT_HDR_FLAG_VALID;
    }

    return ompi_osc_pt2pt_frag_finish(module, frag);
}
Exemple #11
0
/*************************************************************************
 *
 * Put tags from a packet into a nice array
 *
 ************************************************************************/
static void extract_tags(struct pppoe_hdr *ph, struct pppoe_tag** buf){
    int i=0;
    for(;i<MAX_TAGS;++i){
	buf[i] = get_tag(ph,tag_map[i]);
    }
}
Exemple #12
0
static struct item *
map_rect_get_item_textfile(struct map_rect_priv *mr)
{
	char *p,type[SIZE];
	dbg(1,"map_rect_get_item_textfile id_hi=%d line=%s", mr->item.id_hi, mr->line);
	if (!mr->f) {
		return NULL;
	}
	while (mr->more) {
		struct coord c;
		textfile_coord_get(mr, &c, 1);
	}
	for(;;) {
		if (feof(mr->f)) {
			dbg(1,"map_rect_get_item_textfile: eof\n");
			if (mr->item.id_hi) {
				return NULL;
			}
			mr->item.id_hi++;
			if (mr->m->is_pipe) {
				pclose(mr->f);
				mr->f=popen(mr->args, "r");
			} else
				fseek(mr->f, 0, SEEK_SET);
			get_line(mr);
		}
		if ((p=strchr(mr->line,'\n'))) 
			*p='\0';
		if (mr->item.id_hi) {
			mr->attrs[0]='\0';
			if (!parse_line(mr, 1)) {
				get_line(mr);
				continue;
			}
			dbg(1,"map_rect_get_item_textfile: point found\n");
			mr->eoc=0;
			mr->item.id_lo=mr->pos;
		} else {
			if (parse_line(mr, 1)) {
				get_line(mr);
				continue;
			}
			dbg(1,"map_rect_get_item_textfile: line found\n");
			if (! mr->line[0]) {
				get_line(mr);
				continue;
			}
			mr->item.id_lo=mr->pos;
			strcpy(mr->attrs, mr->line);
			get_line(mr);
			dbg(1,"mr=%p attrs=%s\n", mr, mr->attrs);
		}
		dbg(1,"get_attrs %s\n", mr->attrs);
		if (get_tag(mr->attrs,"type",NULL,type,NULL)) {
			dbg(1,"type='%s'\n", type);
			mr->item.type=item_from_name(type);
			if (mr->item.type == type_none) 
				printf("Warning: type '%s' unknown\n", type);
		} else {
			get_line(mr);
			continue;
		}
		mr->attr_last=attr_none;
		mr->more=1;
		dbg(1,"return attr='%s'\n", mr->attrs);
		return &mr->item;
	}
}
Exemple #13
0
int tagfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi){
  LOGCALL();
  (void) offset;
  (void) fi;
  struct dirent *dirent;

  int res = 0;

  char** tagsbuf;
  comm_getTags(path, &tagsbuf);

  int i;
  // Check tag existence and count tags
  if (tagsbuf != NULL)
    for (i = 0; tagsbuf[i]; ++i)
      if (!exist_tag(db, tagsbuf[i]))
        return FAILURE;

  struct G_file* files = NULL;
  struct G_tags* tags = NULL;

  (void) tags;
  if (i >= 1){
    // One: get files then union tags of files
    if (i == 1){
      struct Tag* t = get_tag(db, *tagsbuf);
      unsigned j;
      for (j = 0; j < t->t_files_size; ++j){
        // Add file to files
        // Send tags in UNION
      }
    } else if (i > 1){
      /*
       Files corresponding to the tags. Intersect.
      */
      files = common_files(db, tagsbuf[0], tagsbuf[1]);
      int j;
      for (j = 2; j < i; ++j)
         files = intersect_files(db, files, tagsbuf[j]);
      /*
       Remaining tags from files.
      */
      if (files != NULL){
         struct G_file *tmp;
         for (tmp = files; tmp != NULL; tmp = tmp->next){
           // Send tags in UNION
         }
      }
    }
      /*
        Cross-check with the request.
      */
      /*
        for (tmp2 = tags; tmp2 != NULL; tmp2 = tmp2->next){
          if (!strcmp(union_tagname, tagsbuf))
            // remove union_tag from union
        }
      */
  }

  /*
  	Show results
  	Files:
    Stat each file in the results then call filler
  */
  rewinddir(dir);
  while ((dirent = readdir(dir)) != NULL) {
    struct stat stbuf;
    res = tagfs_getattr(dirent->d_name, &stbuf);
    /* TODO only files whose contents matches tags in path */
    if (S_ISREG(stbuf.st_mode)){ /* only display files, no directories */
      int ok = exist_file(db, dirent->d_name), i = 0;
      if (tagsbuf != NULL)
	    while (ok && tagsbuf[i] != NULL){
          if (is_file_in_tag(db, dirent->d_name, tagsbuf[i]))
	        ++i;
	      else
	        ok = 0;
	    }
      if (ok)
	    filler(buf, dirent->d_name, NULL, 0);
    }
  }

  /*
    Tags:
  */
  if (tagsbuf != NULL){
    for (i = 0; tagsbuf[i]; ++i)
      filler(buf, tagsbuf[i], NULL, 0);
    comm_freeTags(tagsbuf);
  } else {
    // call filler on each tag
  }

  LOG("readdir returning %s\n", strerror(-res));
  return 0;
}
Exemple #14
0
int gmi_get_lookup(struct gmi_lookup* l, struct agm_ent e)
{
  return *(get_tag(l, e));
}
Exemple #15
0
void gmi_set_lookup(struct gmi_lookup* l, struct agm_ent e, int tag)
{
  *(get_tag(l, e)) = tag;
}
Exemple #16
0
/* aiff input */
static int aiff_read_header(AVFormatContext *s,
                            AVFormatParameters *ap)
{
    int size, filesize;
    int64_t offset = 0;
    uint32_t tag;
    unsigned version = AIFF_C_VERSION1;
    AVIOContext *pb = s->pb;
    AVStream * st;
    AIFFInputContext *aiff = s->priv_data;

    /* check FORM header */
    filesize = get_tag(pb, &tag);
    if (filesize < 0 || tag != MKTAG('F', 'O', 'R', 'M'))
        return AVERROR_INVALIDDATA;

    /* AIFF data type */
    tag = avio_rl32(pb);
    if (tag == MKTAG('A', 'I', 'F', 'F'))       /* Got an AIFF file */
        version = AIFF;
    else if (tag != MKTAG('A', 'I', 'F', 'C'))  /* An AIFF-C file then */
        return AVERROR_INVALIDDATA;

    filesize -= 4;

    st = av_new_stream(s, 0);
    if (!st)
        return AVERROR(ENOMEM);

    while (filesize > 0) {
        /* parse different chunks */
        size = get_tag(pb, &tag);
        if (size < 0)
            return size;

        filesize -= size + 8;

        switch (tag) {
        case MKTAG('C', 'O', 'M', 'M'):     /* Common chunk */
            /* Then for the complete header info */
            st->nb_frames = get_aiff_header(pb, st->codec, size, version);
            if (st->nb_frames < 0)
                return st->nb_frames;
            if (offset > 0) // COMM is after SSND
                goto got_sound;
            break;
        case MKTAG('F', 'V', 'E', 'R'):     /* Version chunk */
            version = avio_rb32(pb);
            break;
        case MKTAG('N', 'A', 'M', 'E'):     /* Sample name chunk */
            get_meta(s, "title"    , size);
            break;
        case MKTAG('A', 'U', 'T', 'H'):     /* Author chunk */
            get_meta(s, "author"   , size);
            break;
        case MKTAG('(', 'c', ')', ' '):     /* Copyright chunk */
            get_meta(s, "copyright", size);
            break;
        case MKTAG('A', 'N', 'N', 'O'):     /* Annotation chunk */
            get_meta(s, "comment"  , size);
            break;
        case MKTAG('S', 'S', 'N', 'D'):     /* Sampled sound chunk */
            aiff->data_end = avio_tell(pb) + size;
            offset = avio_rb32(pb);      /* Offset of sound data */
            avio_rb32(pb);               /* BlockSize... don't care */
            offset += avio_tell(pb);    /* Compute absolute data offset */
            if (st->codec->block_align)    /* Assume COMM already parsed */
                goto got_sound;
            if (!pb->seekable) {
                av_log(s, AV_LOG_ERROR, "file is not seekable\n");
                return -1;
            }
            avio_skip(pb, size - 8);
            break;
        case MKTAG('w', 'a', 'v', 'e'):
            if ((uint64_t)size > (1<<30))
                return -1;
            st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
            if (!st->codec->extradata)
                return AVERROR(ENOMEM);
            st->codec->extradata_size = size;
            avio_read(pb, st->codec->extradata, size);
            break;
        default: /* Jump */
            if (size & 1)   /* Always even aligned */
                size++;
            avio_skip(pb, size);
        }
    }

    if (!st->codec->block_align) {
        av_log(s, AV_LOG_ERROR, "could not find COMM tag\n");
        return -1;
    }

got_sound:
    /* Now positioned, get the sound data start and end */
    if (st->nb_frames)
        s->file_size = st->nb_frames * st->codec->block_align;

    av_set_pts_info(st, 64, 1, st->codec->sample_rate);
    st->start_time = 0;
    st->duration = st->codec->frame_size ?
        st->nb_frames * st->codec->frame_size : st->nb_frames;

    /* Position the stream at the first block */
    avio_seek(pb, offset, SEEK_SET);

    return 0;
}
Exemple #17
0
static void gpx_start(VikTrwLayer *vtl, const char *el, const char **attr)
{
  static const gchar *tmp;

  g_string_append_c ( xpath, '/' );
  g_string_append ( xpath, el );
  current_tag = get_tag ( xpath->str );

  switch ( current_tag ) {

     case tt_gpx:
       c_md = vik_trw_metadata_new();
       break;

     case tt_wpt:
       if ( set_c_ll( attr ) ) {
         c_wp = vik_waypoint_new ();
         c_wp->visible = TRUE;
         if ( get_attr ( attr, "hidden" ) )
           c_wp->visible = FALSE;

         vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
       }
       break;

     case tt_trk:
     case tt_rte:
       c_tr = vik_track_new ();
       vik_track_set_defaults ( c_tr );
       c_tr->is_route = (current_tag == tt_rte) ? TRUE : FALSE;
       c_tr->visible = TRUE;
       if ( get_attr ( attr, "hidden" ) )
         c_tr->visible = FALSE;
       break;

     case tt_trk_trkseg:
       f_tr_newseg = TRUE;
       break;

     case tt_trk_trkseg_trkpt:
       if ( set_c_ll( attr ) ) {
         c_tp = vik_trackpoint_new ();
         vik_coord_load_from_latlon ( &(c_tp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
         if ( f_tr_newseg ) {
           c_tp->newsegment = TRUE;
           f_tr_newseg = FALSE;
         }
         c_tr->trackpoints = g_list_append ( c_tr->trackpoints, c_tp );
       }
       break;

     case tt_gpx_name:
     case tt_gpx_author:
     case tt_gpx_desc:
     case tt_gpx_keywords:
     case tt_gpx_time:
     case tt_trk_trkseg_trkpt_name:
     case tt_trk_trkseg_trkpt_ele:
     case tt_trk_trkseg_trkpt_time:
     case tt_wpt_cmt:
     case tt_wpt_desc:
     case tt_wpt_name:
     case tt_wpt_ele:
     case tt_wpt_time:
     case tt_wpt_url:
     case tt_wpt_link:
     case tt_trk_cmt:
     case tt_trk_desc:
     case tt_trk_name:
       g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer */
       break;

     case tt_waypoint:
       c_wp = vik_waypoint_new ();
       c_wp->visible = TRUE;
       break;

     case tt_waypoint_coord:
       if ( set_c_ll( attr ) )
         vik_coord_load_from_latlon ( &(c_wp->coord), vik_trw_layer_get_coord_mode ( vtl ), &c_ll );
       break;

     case tt_waypoint_name:
       if ( ( tmp = get_attr(attr, "id") ) ) {
         if ( c_wp_name )
           g_free ( c_wp_name );
         c_wp_name = g_strdup ( tmp );
       }
       g_string_erase ( c_cdata, 0, -1 ); /* clear the cdata buffer for description */
       break;
        
     default: break;
  }
}
Exemple #18
0
static inline int ompi_osc_pt2pt_rget_internal (void *origin_addr, int origin_count,
                                               struct ompi_datatype_t *origin_dt,
                                               int target,
                                               OPAL_PTRDIFF_TYPE target_disp,
                                               int target_count,
                                               struct ompi_datatype_t *target_dt,
                                               struct ompi_win_t *win, bool release_req,
                                               struct ompi_request_t **request)
{
    int ret, tag;
    ompi_osc_pt2pt_module_t *module = GET_MODULE(win);
    bool is_long_datatype = false;
    ompi_osc_pt2pt_frag_t *frag;
    ompi_osc_pt2pt_header_get_t *header;
    ompi_osc_pt2pt_sync_t *pt2pt_sync;
    size_t ddt_len, frag_len;
    char *ptr;
    const void *packed_ddt;
    ompi_osc_pt2pt_request_t *pt2pt_request;

    OPAL_OUTPUT_VERBOSE((50, ompi_osc_base_framework.framework_output,
                         "get: 0x%lx, %d, %s, %d, %d, %d, %s, %s",
                         (unsigned long) origin_addr, origin_count,
                         origin_dt->name, target, (int) target_disp,
                         target_count, target_dt->name, win->w_name));

    pt2pt_sync = ompi_osc_pt2pt_module_sync_lookup (module, target, NULL);
    if (OPAL_UNLIKELY(NULL == pt2pt_sync)) {
        return OMPI_ERR_RMA_SYNC;
    }

    /* gets are always request based, so that we know where to land the data */
    OMPI_OSC_PT2PT_REQUEST_ALLOC(win, pt2pt_request);

    pt2pt_request->internal = release_req;

    /* short-circuit case */
    if (0 == origin_count || 0 == target_count) {
        ompi_osc_pt2pt_request_complete (pt2pt_request, MPI_SUCCESS);
        *request = &pt2pt_request->super;
        return OMPI_SUCCESS;
    }

    /* optimize self communication. TODO: optimize local communication */
    if (ompi_comm_rank (module->comm) == target) {
        *request = &pt2pt_request->super;
        return ompi_osc_pt2pt_get_self (pt2pt_sync, origin_addr, origin_count, origin_dt,
                                        target_disp, target_count, target_dt,
                                        module, pt2pt_request);
    }

    pt2pt_request->type = OMPI_OSC_PT2PT_HDR_TYPE_GET;
    pt2pt_request->origin_addr = origin_addr;
    pt2pt_request->origin_count = origin_count;
    OMPI_DATATYPE_RETAIN(origin_dt);
    pt2pt_request->origin_dt = origin_dt;

    /* Compute datatype length.  Note that the datatype description
     * must fit in a single frag */
    ddt_len = ompi_datatype_pack_description_length(target_dt);

    frag_len = sizeof(ompi_osc_pt2pt_header_get_t) + ddt_len;
    ret = ompi_osc_pt2pt_frag_alloc(module, target, frag_len, &frag, &ptr, false, release_req);
    if (OMPI_SUCCESS != ret) {
        /* allocate space for the header plus space to store ddt_len */
        frag_len = sizeof(ompi_osc_pt2pt_header_get_t) + 8;
        ret = ompi_osc_pt2pt_frag_alloc(module, target, frag_len, &frag, &ptr, false, release_req);
        if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
            return OMPI_ERR_OUT_OF_RESOURCE;
        }

        is_long_datatype = true;
    }

    tag = get_tag (module);

    /* for bookkeeping the get is "outgoing" */
    ompi_osc_signal_outgoing (module, target, 1);

    if (!release_req) {
        /* wait for epoch to begin before starting rget operation */
        ompi_osc_pt2pt_sync_wait_expected (pt2pt_sync);
    }

    header = (ompi_osc_pt2pt_header_get_t*) ptr;
    header->base.type = OMPI_OSC_PT2PT_HDR_TYPE_GET;
    header->base.flags = 0;
    header->len = frag_len;
    header->count = target_count;
    header->displacement = target_disp;
    header->tag = tag;
    OSC_PT2PT_HTON(header, module, target);
    ptr += sizeof(ompi_osc_pt2pt_header_get_t);

    do {
        ret = ompi_datatype_get_pack_description(target_dt, &packed_ddt);
        if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
            break;
        }

        if (is_long_datatype) {
            /* the datatype does not fit in an eager message. send it seperately */
            header->base.flags |= OMPI_OSC_PT2PT_HDR_FLAG_LARGE_DATATYPE;

            OMPI_DATATYPE_RETAIN(target_dt);

            ret = ompi_osc_pt2pt_isend_w_cb ((void *) packed_ddt, ddt_len, MPI_BYTE,
                                            target, tag_to_target(tag), module->comm,
                                            ompi_osc_pt2pt_dt_send_complete, target_dt);
            if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
                break;
            }

            *((uint64_t *) ptr) = ddt_len;
            ptr += 8;
        } else {
            memcpy((unsigned char*) ptr, packed_ddt, ddt_len);
            ptr += ddt_len;
        }

        /* TODO -- store the request somewhere so we can cancel it on error */
        pt2pt_request->outstanding_requests = 1;
        ret = ompi_osc_pt2pt_irecv_w_cb (origin_addr, origin_count, origin_dt,
                                        target, tag_to_origin(tag), module->comm,
                                        NULL, ompi_osc_pt2pt_req_comm_complete, pt2pt_request);
    } while (0);

    if (OMPI_SUCCESS == ret) {
        header->base.flags |= OMPI_OSC_PT2PT_HDR_FLAG_VALID;
        *request = &pt2pt_request->super;
    }

    return ompi_osc_pt2pt_frag_finish(module, frag);
}
Exemple #19
0
int read_definition(
    int parent)
{
/**
Function: General function to read a definition and fill in the appropriate
            global variables
Inputs: file descriptor for input file
Outputs: Sets flags in option and in flags.
         Fills in tag, type, min, max, and subclass
         Sets state as follows:
             IF definition is an upper bound, GLOBAL
             ELSE IF '{' OR '\n' is found, IN_DEFINITION
Returns: IF end of file is reached, -1
         ELSE 0
Procedure:
1. DO
        IF token is CHOICE, set type of ASN_CHOICE
        ELSE IF token is DEFINED, do the defined thing to fill in defined_by
        ELSE IF token is EMPTY, do nothing
        ELSE IF token is EXPLICIT, set temporary explicit flag
        ELSE IF token is IMPLICIT, clear temporary explicit flag
        ELSE IF token is OF, set OF bit in options and get the subclass name
        ELSE IF token is SIZE, get sizes
        ELSE IF token is TABLE, set table bit in flags and note file position
        ELSE IF token is '[', get tag
        ELSE IF token is '(', get min-max
        ELSE IF token is ',' AND not at a real definition, reset type
        ELSE IF token is numeric
            Clear any line end
            Set state to GLOBAL
        ELSE IF token is a known type name
            IF type is ENUMERATED, set enumerated flag
            IF no type so far, use this one
            ELSE IF OF flag set, set subtype to this type
            ELSE 'Or' the constructed bit into the present type
        ELSE IF (token begins with a capital letter OR *) AND
            type is not -1, set subclass & options
        IF no next token, return -1
   WHILE state is IN_DEFINITION AND token is not '{' NOR '\n'
   Return 0
**/
    long tmp;
    do
    {
        if (!strcmp(token, choice_w))
            type = ASN_CHOICE;
        else if (!strcmp(token, defined_w))
        {
            do_defined();
            if (type >= ASN_CHOICE)
                subtype = type;
            else
                subtype = ASN_CHOICE;
        }
        else if (!strcmp(token, empty_w));
        else if (!strcmp(token, explicit_w))
            explicit1 |= 1;
        else if (!strcmp(token, implicit_w))
            explicit1 &= ~1;
        else if (!strcmp(token, in_w))
        {
            if (!*definer)
                syntax(token);
            if (!get_token(0, inclass))
                syntax(definer);
        }
        else if (!strcmp(token, of_w))
        {
            option |= ASN_OF_FLAG;
            if (!get_token(0, token))
                syntax(of_w);
            if ((tmp = find_type(token)) != ASN_NOTYPE)
                get_expected(0, (subtype = (short)tmp), token);
            else if ((*token < 'A' || *token > 'Z') && *token != '*')
                syntax(token);
            else if (*subclass)
                syntax(subclass);       /* misspelled SEQ/SET */
            else
                option |= set_name_option(subclass, token);
        }
        else if (!strcmp(token, size_w))
            get_size(token, &min, &max, parent);
        else if (!strcmp(token, table_w))
        {
            flags |= ASN_TABLE_FLAG;
            tablepos = tell_pos(streams.str);
            table_start_line = curr_line - 1;   /* adjust for extra \n */
        }
        else if (*token == '[')
            tag = get_tag(token);
        else if (*token == '(')
            get_paren(token, &min, &max, parent);
        else if (*token == ',' && (*classname & 0x20))
            type = -1;
        else if (*token >= '0' && *token <= '9')
        {
            while (get_token(0, token) && *token != '\n');
            state = GLOBAL;
            return 0;
        }
        else if ((tmp = find_type(token)) != ASN_NOTYPE)
        {
            get_expected(0, tmp, token);
            if (tmp == ASN_ENUMERATED)
                flags |= ASN_ENUM_FLAG;
            if (type < 0)
                type = tmp;
            else if ((option & ASN_OF_FLAG))
                subtype = (short)tmp;
            else if (tmp > 0)
                type |= (tmp & ASN_CONSTRUCTED);
        }
        else if (((*token >= 'A' && *token <= 'Z') || *token == '*') &&
                 type == -1)
            option |= set_name_option(subclass, token);
        if (!get_token(0, token))
            return -1;
    }
    while (state == IN_DEFINITION && *token != '{' && *token != '\n');
    return 0;
}
Exemple #20
0
static inline
int ompi_osc_pt2pt_rget_accumulate_internal (const void *origin_addr, int origin_count,
                                            struct ompi_datatype_t *origin_datatype,
                                            void *result_addr, int result_count,
                                            struct ompi_datatype_t *result_datatype,
                                            int target_rank, MPI_Aint target_disp,
                                            int target_count, struct ompi_datatype_t *target_datatype,
                                            struct ompi_op_t *op, struct ompi_win_t *win,
                                            bool release_req, struct ompi_request_t **request)
{
    int ret;
    ompi_osc_pt2pt_module_t *module = GET_MODULE(win);
    ompi_proc_t *proc = ompi_comm_peer_lookup(module->comm, target_rank);
    bool is_long_datatype = false;
    bool is_long_msg = false;
    ompi_osc_pt2pt_frag_t *frag;
    ompi_osc_pt2pt_header_acc_t *header;
    ompi_osc_pt2pt_sync_t *pt2pt_sync;
    size_t ddt_len, payload_len, frag_len;
    char *ptr;
    const void *packed_ddt;
    int tag;
    ompi_osc_pt2pt_request_t *pt2pt_request;

    OPAL_OUTPUT_VERBOSE((50, ompi_osc_base_framework.framework_output,
                         "rget_acc: 0x%lx, %d, %s, 0x%lx, %d, %s, 0x%x, %d, %d, %s, %s, %s",
                         (unsigned long) origin_addr, origin_count, origin_datatype->name,
                         (unsigned long) result_addr, result_count, result_datatype->name,
                         target_rank, (int) target_disp, target_count, target_datatype->name,
                         op->o_name, win->w_name));

    pt2pt_sync = ompi_osc_pt2pt_module_sync_lookup (module, target_rank, NULL);
    if (OPAL_UNLIKELY(NULL == pt2pt_sync)) {
        return OMPI_ERR_RMA_SYNC;
    }

    /* get_accumulates are always request based, so that we know where to land the data */
    OMPI_OSC_PT2PT_REQUEST_ALLOC(win, pt2pt_request);

    pt2pt_request->internal = release_req;

    /* short-circuit case. note that origin_count may be 0 if op is MPI_NO_OP */
    if (0 == result_count || 0 == target_count) {
        ompi_osc_pt2pt_request_complete (pt2pt_request, MPI_SUCCESS);
        *request = &pt2pt_request->super;
        return OMPI_SUCCESS;
    }

    if (!release_req) {
        /* wait for epoch to begin before starting operation */
        ompi_osc_pt2pt_sync_wait_expected (pt2pt_sync);
    }

    /* optimize the self case. TODO: optimize the local case */
    if (ompi_comm_rank (module->comm) == target_rank) {
        *request = &pt2pt_request->super;
        return ompi_osc_pt2pt_gacc_self (pt2pt_sync, origin_addr, origin_count, origin_datatype,
                                         result_addr, result_count, result_datatype,
                                         target_disp, target_count, target_datatype,
                                         op, module, pt2pt_request);
    }

    pt2pt_request->type = OMPI_OSC_PT2PT_HDR_TYPE_GET_ACC;
    pt2pt_request->origin_addr = origin_addr;
    pt2pt_request->origin_count = origin_count;
    OMPI_DATATYPE_RETAIN(origin_datatype);
    pt2pt_request->origin_dt = origin_datatype;

    /* Compute datatype and payload lengths.  Note that the datatype description
     * must fit in a single frag */
    ddt_len = ompi_datatype_pack_description_length(target_datatype);

    if (&ompi_mpi_op_no_op.op != op) {
        payload_len = origin_datatype->super.size * origin_count;
    } else {
        payload_len = 0;
    }

    frag_len = sizeof(*header) + ddt_len + payload_len;
    ret = ompi_osc_pt2pt_frag_alloc(module, target_rank, frag_len, &frag, &ptr, false, release_req);
    if (OMPI_SUCCESS != ret) {
        frag_len = sizeof(*header) + ddt_len;
        ret = ompi_osc_pt2pt_frag_alloc(module, target_rank, frag_len, &frag, &ptr, true, release_req);
        if (OMPI_SUCCESS != ret) {
            /* allocate space for the header plus space to store ddt_len */
            frag_len = sizeof(*header) + 8;
            ret = ompi_osc_pt2pt_frag_alloc(module, target_rank, frag_len, &frag, &ptr, true, release_req);
            if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
                return OMPI_ERR_OUT_OF_RESOURCE;
            }

            is_long_datatype = true;
        }

        is_long_msg = true;
    }

    tag = get_tag (module);

    /* If this is a long message then we need two completions before the
     * request is complete (1 for the send, 1 for the receive) */
    pt2pt_request->outstanding_requests = 1 + is_long_msg;

    /* increment the number of outgoing fragments */
    ompi_osc_signal_outgoing (module, target_rank, pt2pt_request->outstanding_requests);

    header = (ompi_osc_pt2pt_header_acc_t *) ptr;
    header->base.flags = 0;
    header->len = frag_len;
    header->count = target_count;
    header->displacement = target_disp;
    header->op = op->o_f_to_c_index;
    header->tag = tag;

    ptr = (char *)(header + 1);

    do {
        ret = ompi_datatype_get_pack_description(target_datatype, &packed_ddt);
        if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
            break;
        }

        if (is_long_datatype) {
            /* the datatype does not fit in an eager message. send it seperately */
            header->base.flags |= OMPI_OSC_PT2PT_HDR_FLAG_LARGE_DATATYPE;

            OMPI_DATATYPE_RETAIN(target_datatype);

            ret = ompi_osc_pt2pt_isend_w_cb ((void *) packed_ddt, ddt_len, MPI_BYTE,
                                            target_rank, tag_to_target(tag), module->comm,
                                            ompi_osc_pt2pt_dt_send_complete, target_datatype);
            if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
                break;
            }

            *((uint64_t *) ptr) = ddt_len;
            ptr += 8;
        } else {
            memcpy((unsigned char*) ptr, packed_ddt, ddt_len);
            ptr += ddt_len;
        }

        ret = ompi_osc_pt2pt_irecv_w_cb (result_addr, result_count, result_datatype,
                                        target_rank, tag_to_origin(tag), module->comm,
                                        NULL, ompi_osc_pt2pt_req_comm_complete, pt2pt_request);
        if (OPAL_UNLIKELY(OMPI_SUCCESS != ret)) {
            break;
        }

        if (!is_long_msg) {
            header->base.type = OMPI_OSC_PT2PT_HDR_TYPE_GET_ACC;
            osc_pt2pt_hton(header, proc);

            if (&ompi_mpi_op_no_op.op != op) {
                osc_pt2pt_copy_for_send (ptr, payload_len, origin_addr, proc, origin_count,
                                        origin_datatype);
            }
        } else {
            header->base.type = OMPI_OSC_PT2PT_HDR_TYPE_GET_ACC_LONG;
            osc_pt2pt_hton(header, proc);

            ret = ompi_osc_pt2pt_isend_w_cb (origin_addr, origin_count, origin_datatype,
                                            target_rank, tag_to_target(tag), module->comm,
                                            ompi_osc_pt2pt_req_comm_complete, pt2pt_request);
        }
    } while (0);

    if (OMPI_SUCCESS == ret) {
        header->base.flags |= OMPI_OSC_PT2PT_HDR_FLAG_VALID;
        *request = (ompi_request_t *) pt2pt_request;
    }

    return ompi_osc_pt2pt_frag_finish(module, frag);
}
static int g64_get_heads_per_disk(floppy_image *floppy)
{
	return get_tag(floppy)->heads;
}
/* aiff input */
static int aiff_read_header(AVFormatContext *s)
{
    int ret, size, filesize;
    int64_t offset = 0, position;
    uint32_t tag;
    unsigned version = AIFF_C_VERSION1;
    AVIOContext *pb = s->pb;
    AVStream * st;
    AIFFInputContext *aiff = s->priv_data;
    ID3v2ExtraMeta *id3v2_extra_meta = NULL;

    /* check FORM header */
    filesize = get_tag(pb, &tag);
    if (filesize < 0 || tag != MKTAG('F', 'O', 'R', 'M'))
        return AVERROR_INVALIDDATA;

    /* AIFF data type */
    tag = avio_rl32(pb);
    if (tag == MKTAG('A', 'I', 'F', 'F'))       /* Got an AIFF file */
        version = AIFF;
    else if (tag != MKTAG('A', 'I', 'F', 'C'))  /* An AIFF-C file then */
        return AVERROR_INVALIDDATA;

    filesize -= 4;

    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);

    while (filesize > 0) {
        /* parse different chunks */
        size = get_tag(pb, &tag);
        if (size < 0)
            return size;

        filesize -= size + 8;

        switch (tag) {
        case MKTAG('C', 'O', 'M', 'M'):     /* Common chunk */
            /* Then for the complete header info */
            st->nb_frames = get_aiff_header(s, size, version);
            if (st->nb_frames < 0)
                return st->nb_frames;
            if (offset > 0) // COMM is after SSND
                goto got_sound;
            break;
        case MKTAG('I', 'D', '3', ' '):
            position = avio_tell(pb);
            ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
            if (id3v2_extra_meta)
                if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0) {
                    ff_id3v2_free_extra_meta(&id3v2_extra_meta);
                    return ret;
                }
            ff_id3v2_free_extra_meta(&id3v2_extra_meta);
            if (position + size > avio_tell(pb))
                avio_skip(pb, position + size - avio_tell(pb));
            break;
        case MKTAG('F', 'V', 'E', 'R'):     /* Version chunk */
            version = avio_rb32(pb);
            break;
        case MKTAG('N', 'A', 'M', 'E'):     /* Sample name chunk */
            get_meta(s, "title"    , size);
            break;
        case MKTAG('A', 'U', 'T', 'H'):     /* Author chunk */
            get_meta(s, "author"   , size);
            break;
        case MKTAG('(', 'c', ')', ' '):     /* Copyright chunk */
            get_meta(s, "copyright", size);
            break;
        case MKTAG('A', 'N', 'N', 'O'):     /* Annotation chunk */
            get_meta(s, "comment"  , size);
            break;
        case MKTAG('S', 'S', 'N', 'D'):     /* Sampled sound chunk */
            aiff->data_end = avio_tell(pb) + size;
            offset = avio_rb32(pb);      /* Offset of sound data */
            avio_rb32(pb);               /* BlockSize... don't care */
            offset += avio_tell(pb);    /* Compute absolute data offset */
            if (st->codec->block_align && !pb->seekable)    /* Assume COMM already parsed */
                goto got_sound;
            if (!pb->seekable) {
                av_log(s, AV_LOG_ERROR, "file is not seekable\n");
                return -1;
            }
            avio_skip(pb, size - 8);
            break;
        case MKTAG('w', 'a', 'v', 'e'):
            if ((uint64_t)size > (1<<30))
                return -1;
            st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
            if (!st->codec->extradata)
                return AVERROR(ENOMEM);
            st->codec->extradata_size = size;
            avio_read(pb, st->codec->extradata, size);
            if (st->codec->codec_id == AV_CODEC_ID_QDM2 && size>=12*4 && !st->codec->block_align) {
                st->codec->block_align = AV_RB32(st->codec->extradata+11*4);
                aiff->block_duration = AV_RB32(st->codec->extradata+9*4);
            } else if (st->codec->codec_id == AV_CODEC_ID_QCELP) {
                char rate = 0;
                if (size >= 25)
                    rate = st->codec->extradata[24];
                switch (rate) {
                case 'H': // RATE_HALF
                    st->codec->block_align = 17;
                    break;
                case 'F': // RATE_FULL
                default:
                    st->codec->block_align = 35;
                }
                aiff->block_duration = 160;
                st->codec->bit_rate = st->codec->sample_rate * (st->codec->block_align << 3) /
                                      aiff->block_duration;
            }
            break;
        case MKTAG('C','H','A','N'):
            if(ff_mov_read_chan(s, pb, st, size) < 0)
                return AVERROR_INVALIDDATA;
            break;
        default: /* Jump */
            if (size & 1)   /* Always even aligned */
                size++;
            avio_skip(pb, size);
        }
    }

got_sound:
    if (!st->codec->block_align) {
        av_log(s, AV_LOG_ERROR, "could not find COMM tag or invalid block_align value\n");
        return -1;
    }

    /* Now positioned, get the sound data start and end */
    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
    st->start_time = 0;
    st->duration = st->nb_frames * aiff->block_duration;

    /* Position the stream at the first block */
    avio_seek(pb, offset, SEEK_SET);

    return 0;
}
Exemple #23
0
/**
 * Get inode list from query tree. The returned list is allocated with malloc()
 * and should be freed with free().
 *
 * @param query The root of the query tree to calculate the inode list for.
 * @param count The number of inodes in the returned list.
 * @param neg   True if the query results should be negated.
 * @returns The list of inodes available given the query tree, or NULL on error
 * or if count is zero.
 */
fileptr *query_to_inodes(const qelem * const query, int * const count, int * const neg) {
  DEBUG("Function entry");
  if (!query) {
    PMSG(LOG_ERR, "Query was null");
    return NULL;
  }
  if (!count) {
    PMSG(LOG_ERR, "Count was null");
    return NULL;
  }
  if (!neg) {
    PMSG(LOG_ERR, "Neg was null");
    return NULL;
  }
  switch (query->type) {
    case QUERY_IS_ANY:
      /* IS_ANY node, output set is the set of limbo inodes, with internal
       * negation flag set to false
       */
      DEBUG("IS_ANY: creating list of limbo inodes, negation 0");
      *neg=0;
      *count = inode_get_all(0, NULL, 0);
      if (*count>0) {
        fileptr *inodes = calloc(*count, sizeof(fileptr));
        inode_get_all(0, inodes, *count);
        return inodes;
      } else if (*count==0) {
        /* empty return list to avoid error; must still be freed though */
        return calloc(1, sizeof(fileptr));
      } else if (*count<0) {
        DEBUG("Error calling inode_get_all(): %s", strerror(-*count));
        return NULL;
      }
      break;

    case QUERY_IS:
      /* IS node, the output set is the recursive union of the inodes belonging
       * to that tag and its subtags, with internal negation flag set to false
       */
      {
        fileptr dblock = get_tag(query->tag);

        DEBUG("IS: fetching recursive list of inodes from block %lu, negation 0", dblock);
        *neg=0;
        fileptr *inodes = inode_get_all_recurse(dblock, count);
        DEBUG("IS: %d inodes in block %lu", *count, dblock);
        if (inodes && *count>=0) {
          return inodes;
        } else {
          if (inodes) ifree(inodes);
          DEBUG("Error calling inode_get_all(): %s", strerror(-*count));
          return NULL;
        }
      }
      break;

    case QUERY_IS_NOSUB:
      /* IS_NOSUB node, the output set is the set of inodes belonging tag, with
       * internal negation flag set to false
       */
      {
        fileptr dblock = get_tag(query->tag);

        DEBUG("IS_NOSUB: creating list of inodes from block %lu, negation 0", dblock);
        *neg=0;
        *count = inode_get_all(dblock, NULL, 0);
        DEBUG("IS_NOSUB: %d inodes in block %lu", *count, dblock);
        if (*count>0) {
          fileptr *inodes = calloc(*count, sizeof(fileptr));
          inode_get_all(dblock, inodes, *count);
          return inodes;
        } else if (*count==0) {
          /* empty return list to avoid error; must still be freed though */
          return calloc(1, sizeof(fileptr));
        } else if (*count<0) {
          DEBUG("Error calling inode_get_all(): %s", strerror(-*count));
          return NULL;
        }
      }
      break;

    case QUERY_IS_INODE:
      /* IS_INODE node, the output set contains a single element: the inode. */
      {
        fileptr *ret = calloc(1, sizeof(fileptr));
        DEBUG("IS_INODE: single inode 0x%08lx, negation 0", query->inode);
        *count=1;
        *neg=0;
        *ret=query->inode;
        return ret;
      }
      break;

    case QUERY_NOT:
      if (query->tag) {
        /* IS_NOT node with a tag, the output set is the same as for an IS
         * node, with an internal negation flag set to true */
        PMSG(LOG_ERR, "Unhandled type of NOT query! Tag is available.");
        return NULL;
      } else if (query->next[0]) {
        /* IS_NOT node with a subquery, the output set is identical to the
         * subquery resultset, with an internal negation flag inverted */
        fileptr *res = query_to_inodes(query, count, neg);
        *neg = !*neg;
        return res;
      } else {
        PMSG(LOG_ERR, "Unknown type of NOT query! Both tag and next[0] are null.");
        return NULL;
      }
      break;

    case QUERY_AND:
      /* AND node output depends on the negation flags of its subqueries:
       *  * Both false: output is the set intersection of its subqueries, with
       *  negation flag clear
       *  * Both true: output is union of subqueries, with negation flag set
       *  * Otherwise: output is set difference, with the negation-true set
       *  removed from the negation-false set, and the negation flag cleared
       */
      {
        DEBUG("AND: Conjunction of two query subtrees");
        int count1=0, count2=0, neg1=0, neg2=0;
        fileptr *res1 = query_to_inodes(query->next[0], &count1, &neg1);
        if (!res1) {
          DEBUG("Error in left branch");
          return NULL;
        }
        if (!count1 && !neg1) {
          /* short-circuit query evaluation */
          DEBUG("Short-circuit: first branch yielded no results");
          *count=0;
          *neg=neg1;
          return res1;
        }
        fileptr *res2 = query_to_inodes(query->next[1], &count2, &neg2);
        if (!res2) {
          DEBUG("Error in right branch");
          ifree(res1);
          return NULL;
        }
        if (!count2 && !neg2) {
          /* no need to perform set operations */
          DEBUG("Short-circuit: second branch yielded no results");
          *count=0;
          *neg=neg2;
          ifree(res1);
          return res2;
        }
        /* both subtrees returned results */
        if (!neg1 && !neg2) {
          fileptr *res = calloc(MIN(count1, count2), sizeof(fileptr));
          if (!res) {
            PMSG(LOG_ERR, "Failed to allocate memory for return array");
            ifree(res1);
            ifree(res2);
            return NULL;
          }
          /* output is the intersection of subqueries, with negation flag clear */
          *neg=0;
          *count=set_intersect(res1, res2, res, count1, count2, MIN(count1, count2), sizeof(fileptr), inodecmp);
          if (*count < 0) {
            PMSG(LOG_ERR, "Error in set intersection operation.");
            ifree(res1);
            ifree(res2);
            ifree(res);
            return NULL;
          } else {
            DEBUG("Set intersection succeeded; %d results", *count);
            ifree(res1);
            ifree(res2);
            return res;
          }
        /* } else if (neg1 && neg2) { */
          /* output is union of subqueries, with negation flag set */
        /* } else { */
          /* output is set difference, with the negation-true set removed from
           * the negation-false set, and the negation flag cleared */
        } else {
          PMSG(LOG_ERR, "Unhandled case in AND");
          ifree(res1);
          ifree(res2);
          return NULL;
        }
      }
      break;

    case QUERY_OR:
      /* OR node output depends on the negation flags of its subqueries:
       *  * Both false: output is union of subquery results, with negation flag
       *  clear
       *  * Both true: output is intersection of subquery results, with
       *  negation flag set
       *  * Otherwise: output is ???
       */
      {
        PMSG(LOG_ERR, "Cannot handle OR queries yet!");
        return NULL;

        DEBUG("OR: Disjunction of two query subtrees");
        int count1=0, count2=0, neg1=0, neg2=0;
        fileptr *res1 = query_to_inodes(query->next[0], &count1, &neg1);
        if (!res1) {
          DEBUG("Error in left branch");
          return NULL;
        }
        fileptr *res2 = query_to_inodes(query->next[1], &count2, &neg2);
        if (!res2) {
          DEBUG("Error in right branch");
          ifree(res1);
          return NULL;
        }
        if (!count1 && !neg1) {
          /* no need to perform set operations */
          DEBUG("Short-circuit: first branch yielded no results");
          *count=0;
          *neg=neg2;
          ifree(res1);
          return res2;
        }
        if (!count2 && !neg2) {
          /* no need to perform set operations */
          DEBUG("Short-circuit: second branch yielded no results");
          *count=0;
          *neg=neg1;
          ifree(res2);
          return res1;
        }
        /* both subtrees returned results */
        if (!neg1 && !neg2) {
          fileptr *res = calloc(count1 + count2, sizeof(fileptr));
          if (!res) {
            PMSG(LOG_ERR, "Failed to allocate memory for return array");
            ifree(res1);
            ifree(res2);
            return NULL;
          }
          /* output is the union of subqueries, with negation flag clear */
          *neg=0;
          *count=set_union(res1, res2, res, count1, count2, MIN(count1, count2), sizeof(fileptr), inodecmp);
          if (*count < 0) {
            PMSG(LOG_ERR, "Error in set union operation.");
            ifree(res1);
            ifree(res2);
            ifree(res);
            return NULL;
          } else {
            DEBUG("Set union succeeded; %d results", *count);
            ifree(res1);
            ifree(res2);
            return res;
          }
        /* } else if (neg1 && neg2) { */
          /* output is union of subqueries, with negation flag set */
        /* } else { */
          /* output is set difference, with the negation-true set removed from
           * the negation-false set, and the negation flag cleared */
        } else {
          PMSG(LOG_ERR, "Unhandled case in AND");
          ifree(res1);
          ifree(res2);
          return NULL;
        }
      }
      break;

    default:
      PMSG(LOG_ERR, "Unknown query tree element type %d!", query->type);
      return NULL;
  }
  return NULL;
}
static void mfm_info_cache_sector_info(floppy_image *floppy,int track,int head)
{
	UINT8 track_data[TRACK_SIZE_MFM];

	/* initialise these with single density values if single density */
	UINT8 IdMark = 0x0fe;
	UINT8 DataMark = 0x0fb;
	UINT8 DeletedDataMark = 0x0f8;

	UINT8 SectorCount;
	UINT8 SearchCode = 0;
	UINT8 sector_number = 0;
	int ptr = 0;
	int track_offset = oric_get_track_offset(floppy,track,head);
	floppy_image_read(floppy, track_data, track_offset, TRACK_SIZE_MFM);
	SectorCount = 0;

	do
	{
		switch (SearchCode)
		{
			/* searching for id's */
			case 0:
			{
				/* found id mark? */
				if (track_data[ptr] == IdMark)
				{
					sector_number  = track_data[ptr+3]-1;
					/* store pointer to id mark */
					get_tag(floppy)->sector_data[sector_number].id_ptr = ptr + track_offset;
					SectorCount++;

					/* grab N value - used to skip data in data field */
					get_tag(floppy)->sector_data[sector_number].sector_size = (1<< (track_data[ptr+4]+7));

					/* skip past id field and crc */
					ptr+=7;

					/* now looking for data field */
					SearchCode = 1;
				}
				else
				{
					/* update position */
					ptr++;
				}
			}
			break;

			/* searching for data id's */
			case 1:
			{
				/* found data or deleted data? */
				if ((track_data[ptr] == DataMark) || (track_data[ptr] == DeletedDataMark))
				{
					/* yes */
					get_tag(floppy)->sector_data[sector_number].data_ptr = ptr + track_offset + 1;
					get_tag(floppy)->sector_data[sector_number].ddam = (track_data[ptr] == DeletedDataMark) ? ID_FLAG_DELETED_DATA : 0;

					/* skip data field and id */
					ptr += get_tag(floppy)->sector_data[sector_number].sector_size + 3;

					/* now looking for id field */
					SearchCode = 0;
				}
				else
				{
					ptr++;
				}
			}
			break;

			default:
				break;
		}
	}
	while (ptr < TRACK_SIZE_MFM);
	get_tag(floppy)->num_sectors = SectorCount;

}
Exemple #25
0
static int imd_get_heads_per_disk(floppy_image_legacy *floppy)
{
	return get_tag(floppy)->heads;
}
Exemple #26
0
 void set_state(T state) volatile
 {
     tag_type t = get_tag();
     state_ = pack_state(state, t);
 }
Exemple #27
0
static UINT64 imd_get_track_offset(floppy_image_legacy *floppy, int head, int track)
{
	return get_tag(floppy)->track_offsets[(track<<1) + head];
}
Exemple #28
0
static struct item *
map_rect_get_item_textfile(struct map_rect_priv *mr)
{
	char *p,type[SIZE];
	if (debug)
		printf("map_rect_get_item_textfile id_hi=%d line=%s", mr->item.id_hi, mr->line);
	if (!mr->f) {
		return NULL;
	}
	for(;;) {
		if (feof(mr->f)) {
			if (debug)
				printf("map_rect_get_item_textfile: eof\n");
			if (mr->item.id_hi) {
				return NULL;
			}
			mr->item.id_hi++;
			fseek(mr->f, 0, SEEK_SET);
			get_line(mr);
		}
		if (mr->item.id_hi) {
			if (!contains_coord(mr->line)) {
				get_line(mr);
				continue;
			}
			if ((p=index(mr->line,'\n'))) 
				*p='\0';
			if (debug)
				printf("map_rect_get_item_textfile: point found\n");
			mr->attrs[0]='\0';
			parse_line(mr);
			mr->eoc=0;
			mr->item.id_lo=mr->pos;
		} else {
			if (contains_coord(mr->line)) {
				get_line(mr);
				continue;
			}
			if ((p=index(mr->line,'\n'))) 
				*p='\0';
			if (debug)
				printf("map_rect_get_item_textfile: line found\n");
			if (! mr->line[0]) {
				get_line(mr);
				continue;
			}
			mr->item.id_lo=mr->pos;
			strcpy(mr->attrs, mr->line);
			get_line(mr);
			if (debug)
				printf("mr=%p attrs=%s\n", mr, mr->attrs);
		}
		if (debug)
			printf("get_attrs %s\n", mr->attrs);
		if (get_tag(mr->attrs,"type",NULL,type,NULL)) {
			if (debug)
				printf("type='%s'\n", type);
			mr->item.type=item_from_name(type);
			if (mr->item.type == type_none) 
				printf("Warning: type '%s' unknown\n", type);
		} else {
			get_line(mr);
			continue;
		}
		mr->attr_last=attr_none;
		if (debug)
			printf("return attr='%s'\n", mr->attrs);
		return &mr->item;
	}
}
Exemple #29
0
/*
 * Read a BER tag and length from asn1/len.  Place the tag parameters in
 * tag_out.  Set contents_out/clen_out to the octet range of the tag's
 * contents, and remainder_out/rlen_out to the octet range after the end of the
 * BER encoding.
 *
 * (krb5 ASN.1 encodings should be in DER, but for compatibility with some
 * really ancient implementations we handle the indefinite length form in tags.
 * However, we still insist on the primitive form of string types.)
 */
static asn1_error_code
get_tag(const unsigned char *asn1, size_t len, taginfo *tag_out,
        const unsigned char **contents_out, size_t *clen_out,
        const unsigned char **remainder_out, size_t *rlen_out)
{
    asn1_error_code ret;
    unsigned char o;
    const unsigned char *c, *p, *tag_start = asn1;
    size_t clen, llen, i;
    taginfo t;

    *contents_out = *remainder_out = NULL;
    *clen_out = *rlen_out = 0;
    if (len == 0)
        return ASN1_OVERRUN;
    o = *asn1++;
    len--;
    tag_out->asn1class = o & 0xC0;
    tag_out->construction = o & 0x20;
    if ((o & 0x1F) != 0x1F) {
        tag_out->tagnum = o & 0x1F;
    } else {
        tag_out->tagnum = 0;
        do {
            if (len == 0)
                return ASN1_OVERRUN;
            o = *asn1++;
            len--;
            tag_out->tagnum = (tag_out->tagnum << 7) | (o & 0x7F);
        } while (o & 0x80);
    }

    if (len == 0)
        return ASN1_OVERRUN;
    o = *asn1++;
    len--;

    if (o == 0x80) {
        /* Indefinite form (should not be present in DER, but we accept it). */
        if (tag_out->construction != CONSTRUCTED)
            return ASN1_MISMATCH_INDEF;
        p = asn1;
        while (!(len >= 2 && p[0] == 0 && p[1] == 0)) {
            ret = get_tag(p, len, &t, &c, &clen, &p, &len);
            if (ret)
                return ret;
        }
        tag_out->tag_end_len = 2;
        *contents_out = asn1;
        *clen_out = p - asn1;
        *remainder_out = p + 2;
        *rlen_out = len - 2;
    } else if ((o & 0x80) == 0) {
        /* Short form (first octet gives content length). */
        if (o > len)
            return ASN1_OVERRUN;
        tag_out->tag_end_len = 0;
        *contents_out = asn1;
        *clen_out = o;
        *remainder_out = asn1 + *clen_out;
        *rlen_out = len - (*remainder_out - asn1);
    } else {
        /* Long form (first octet gives number of base-256 length octets). */
        llen = o & 0x7F;
        if (llen > len)
            return ASN1_OVERRUN;
        if (llen > sizeof(*clen_out))
            return ASN1_OVERFLOW;
        for (i = 0, clen = 0; i < llen; i++)
            clen = (clen << 8) | asn1[i];
        if (clen > len - llen)
            return ASN1_OVERRUN;
        tag_out->tag_end_len = 0;
        *contents_out = asn1 + llen;
        *clen_out = clen;
        *remainder_out = *contents_out + clen;
        *rlen_out = len - (*remainder_out - asn1);
    }
    tag_out->tag_len = *contents_out - tag_start;
    return 0;
}
Exemple #30
0
/*
 * Let the user select an item, save its "index"
 *
 * Return TRUE only if an acceptable item was chosen by the user.
 *
 * The selected item must satisfy the "item_tester_hook()" function,
 * if that hook is set, and the "item_tester_tval", if that value is set.
 *
 * All "item_tester" restrictions are cleared before this function returns.
 *
 * The user is allowed to choose acceptable items from the equipment,
 * inventory, or floor, respectively, if the proper flag was given,
 * and there are any acceptable items in that location.
 *
 * The equipment or inventory are displayed (even if no acceptable
 * items are in that location) if the proper flag was given.
 *
 * If there are no acceptable items available anywhere, and "str" is
 * not NULL, then it will be used as the text of a warning message
 * before the function returns.
 *
 * Note that the user must press "-" to specify the item on the floor,
 * and there is no way to "examine" the item on the floor, while the
 * use of "capital" letters will "examine" an inventory/equipment item,
 * and prompt for its use.
 *
 * If a legal item is selected from the inventory, we save it in "cp"
 * directly (0 to 35), and return TRUE.
 *
 * If a legal item is selected from the floor, we save it in "cp" as
 * a negative (-1 to -511), and return TRUE.
 *
 * If no item is available, we do nothing to "cp", and we display a
 * warning message, using "str" if available, and return FALSE.
 *
 * If no item is selected, we do nothing to "cp", and return FALSE.
 *
 * Global "p_ptr->command_wrk" is used to choose between equip/inven/floor
 * listings.  It is equal to USE_INVEN or USE_EQUIP or USE_FLOOR, except
 * when this function is first called, when it is equal to zero, which will
 * cause it to be set to USE_INVEN.
 *
 * We always erase the prompt when we are done, leaving a blank line,
 * or a warning message, if appropriate, if no items are available.
 *
 * Note that only "acceptable" floor objects get indexes, so between two
 * commands, the indexes of floor objects may change.  XXX XXX XXX
 */
bool get_item(int *cp, const char *pmt, const char *str, cmd_code cmd, int mode)
{
	int py = p_ptr->py;
	int px = p_ptr->px;
	unsigned char cmdkey = cmd_lookup_key(cmd,
			OPT(rogue_like_commands) ? KEYMAP_MODE_ROGUE : KEYMAP_MODE_ORIG);

	//struct keypress which;
	ui_event press;

	int j, k;

	int i1, i2;
	int e1, e2;
	int f1, f2;

	bool done, item;

	bool oops = FALSE;

	bool use_inven = ((mode & USE_INVEN) ? TRUE : FALSE);
	bool use_equip = ((mode & USE_EQUIP) ? TRUE : FALSE);
	bool use_floor = ((mode & USE_FLOOR) ? TRUE : FALSE);
	bool is_harmless = ((mode & IS_HARMLESS) ? TRUE : FALSE);
	bool quiver_tags = ((mode & QUIVER_TAGS) ? TRUE : FALSE);

	int olist_mode = 0;

	bool allow_inven = FALSE;
	bool allow_equip = FALSE;
	bool allow_floor = FALSE;

	bool toggle = FALSE;

	char tmp_val[160];
	char out_val[160];

	int floor_list[MAX_FLOOR_STACK];
	int floor_num;

	bool show_list = TRUE;

	/* Hack - Only shift the command key if it actually needs to be shifted. */
	if (cmdkey < 0x20)
		cmdkey = UN_KTRL(cmdkey);

	/* Object list display modes */
	if (mode & SHOW_FAIL)
		olist_mode |= OLIST_FAIL;
	else
		olist_mode |= OLIST_WEIGHT;

	if (mode & SHOW_PRICES)
		olist_mode |= OLIST_PRICE;

	if (mode & SHOW_EMPTY)
		olist_mode |= OLIST_SEMPTY;

	/* Paranoia XXX XXX XXX */
	message_flush();


	/* Not done */
	done = FALSE;

	/* No item selected */
	item = FALSE;


	/* Full inventory */
	i1 = 0;
	i2 = INVEN_PACK - 1;

	/* Forbid inventory */
	if (!use_inven) i2 = -1;

	/* Restrict inventory indexes */
	while ((i1 <= i2) && (!get_item_okay(i1))) i1++;
	while ((i1 <= i2) && (!get_item_okay(i2))) i2--;

	/* Accept inventory */
	if (i1 <= i2) allow_inven = TRUE;


	/* Full equipment */
	e1 = INVEN_WIELD;
	e2 = ALL_INVEN_TOTAL - 1;

	/* Forbid equipment */
	if (!use_equip) e2 = -1;

	/* Restrict equipment indexes */
	while ((e1 <= e2) && (!get_item_okay(e1))) e1++;
	while ((e1 <= e2) && (!get_item_okay(e2))) e2--;

	/* Accept equipment */
	if (e1 <= e2) allow_equip = TRUE;


	/* Scan all non-gold objects in the grid */
	floor_num = scan_floor(floor_list, N_ELEMENTS(floor_list), py, px, 0x0B);

	/* Full floor */
	f1 = 0;
	f2 = floor_num - 1;

	/* Forbid floor */
	if (!use_floor) f2 = -1;

	/* Restrict floor indexes */
	while ((f1 <= f2) && (!get_item_okay(0 - floor_list[f1]))) f1++;
	while ((f1 <= f2) && (!get_item_okay(0 - floor_list[f2]))) f2--;

	/* Accept floor */
	if (f1 <= f2) allow_floor = TRUE;


	/* Require at least one legal choice */
	if (!allow_inven && !allow_equip && !allow_floor)
	{
		/* Oops */
		oops = TRUE;
		done = TRUE;
	}

	/* Analyze choices */
	else
	{
		/* Hack -- Start on equipment if requested */
		if ((p_ptr->command_wrk == USE_EQUIP) && allow_equip)
			p_ptr->command_wrk = USE_EQUIP;
		else if ((p_ptr->command_wrk == USE_INVEN) && allow_inven)
			p_ptr->command_wrk = USE_INVEN;
		else if ((p_ptr->command_wrk == USE_FLOOR) && allow_floor)
			p_ptr->command_wrk = USE_FLOOR;

		/* If we are using the quiver then start on equipment */
		else if (quiver_tags && allow_equip)
			p_ptr->command_wrk = USE_EQUIP;

		/* Use inventory if allowed */
		else if (use_inven && allow_inven)
			p_ptr->command_wrk = USE_INVEN;

		/* Use equipment if allowed */
		else if (use_equip && allow_equip)
			p_ptr->command_wrk = USE_EQUIP;

		/* Use floor if allowed */
		else if (use_floor && allow_floor)
			p_ptr->command_wrk = USE_FLOOR;

		/* Hack -- Use (empty) inventory */
		else
			p_ptr->command_wrk = USE_INVEN;
	}


	/* Start out in "display" mode */
	if (show_list)
	{
		/* Save screen */
		screen_save();
	}


	/* Repeat until done */
	while (!done)
	{
		int ni = 0;
		int ne = 0;

		/* Scan windows */
		for (j = 0; j < ANGBAND_TERM_MAX; j++)
		{
			/* Unused */
			if (!angband_term[j]) continue;

			/* Count windows displaying inven */
			if (op_ptr->window_flag[j] & (PW_INVEN)) ni++;

			/* Count windows displaying equip */
			if (op_ptr->window_flag[j] & (PW_EQUIP)) ne++;
		}

		/* Toggle if needed */
		if (((p_ptr->command_wrk == USE_EQUIP) && ni && !ne) ||
		    ((p_ptr->command_wrk == USE_INVEN) && !ni && ne))
		{
			/* Toggle */
			toggle_inven_equip();

			/* Track toggles */
			toggle = !toggle;
		}

		/* Redraw */
		p_ptr->redraw |= (PR_INVEN | PR_EQUIP);

		/* Redraw windows */
		redraw_stuff(p_ptr);

		/* Viewing inventory */
		if (p_ptr->command_wrk == USE_INVEN)
		{
			int nmode = olist_mode;

			/* Show the quiver counts in certain cases, like the 'i' command */
			if (mode & SHOW_QUIVER)
				nmode |= OLIST_QUIVER;

			/* Redraw if needed */
			if (show_list)
				show_inven(nmode);

			/* Begin the prompt */
			strnfmt(out_val, sizeof(out_val), "Inven:");

			/* List choices */
			if (i1 <= i2)
			{
				/* Build the prompt */
				strnfmt(tmp_val, sizeof(tmp_val), " %c-%c,",
				        index_to_label(i1), index_to_label(i2));

				/* Append */
				my_strcat(out_val, tmp_val, sizeof(out_val));
			}

			/* Indicate ability to "view" */
			if (!show_list)
			{
				my_strcat(out_val, " * to see,", sizeof(out_val));
				button_add("[*]", '*');
			}

			/* Indicate legality of "toggle" */
			if (use_equip)
			{
				my_strcat(out_val, " / for Equip,", sizeof(out_val));
				button_add("[/]", '/');
			}

			/* Indicate legality of the "floor" */
			if (allow_floor)
			{
				my_strcat(out_val, " - for floor,", sizeof(out_val));
				button_add("[-]", '-');
			}
		}

		/* Viewing equipment */
		else if (p_ptr->command_wrk == USE_EQUIP)
		{
			/* Redraw if needed */
			if (show_list) show_equip(olist_mode);

			/* Begin the prompt */
			strnfmt(out_val, sizeof(out_val), "Equip:");

			/* List choices */
			if (e1 <= e2)
			{
				/* Build the prompt */
				strnfmt(tmp_val, sizeof(tmp_val), " %c-%c,",
				        index_to_label(e1), index_to_label(e2));

				/* Append */
				my_strcat(out_val, tmp_val, sizeof(out_val));
			}

			/* Indicate ability to "view" */
			if (!show_list)
			{
				my_strcat(out_val, " * to see,", sizeof(out_val));
				button_add("[*]", '*');
			}

			/* Indicate legality of "toggle" */
			if (use_inven)
			{
				my_strcat(out_val, " / for Inven,", sizeof(out_val));
				button_add("[/]", '/');
			}

			/* Indicate legality of the "floor" */
			if (allow_floor)
			{
				my_strcat(out_val, " - for floor,", sizeof(out_val));
				button_add("[!]", '!');
			}
		}

		/* Viewing floor */
		else
		{
			/* Redraw if needed */
			if (show_list) show_floor(floor_list, floor_num, olist_mode);

			/* Begin the prompt */
			strnfmt(out_val, sizeof(out_val), "Floor:");

			/* List choices */
			if (f1 <= f2)
			{
				/* Build the prompt */
				strnfmt(tmp_val, sizeof(tmp_val), " %c-%c,", I2A(f1), I2A(f2));

				/* Append */
				my_strcat(out_val, tmp_val, sizeof(out_val));
			}

			/* Indicate ability to "view" */
			if (!show_list)
			{
				my_strcat(out_val, " * to see,", sizeof(out_val));
				button_add("[*]", '*');
			}

			/* Append */
			if (use_inven)
			{
				my_strcat(out_val, " / for Inven,", sizeof(out_val));
				button_add("[/]", '/');
			}

			/* Append */
			else if (use_equip)
			{
				my_strcat(out_val, " / for Equip,", sizeof(out_val));
				button_add("[/]", '/');
			}
		}

		redraw_stuff(p_ptr);

		/* Finish the prompt */
		my_strcat(out_val, " ESC", sizeof(out_val));

		/* if we have a prompt header, show the part that we just built */
		if (pmt) {
			/* Build the prompt */
			strnfmt(tmp_val, sizeof(tmp_val), "(%s) %s", out_val, pmt);

			/* Show the prompt */
			prt(tmp_val, 0, 0);
		}

		/* Get a key */
		//which = inkey();
		press = inkey_m();

		/* Parse it */
		if (press.type == EVT_MOUSE) {
			if (press.mouse.button == 2) {
				done = TRUE;
			} else
			if (press.mouse.button == 1) {
				k = -1;
				if (p_ptr->command_wrk == USE_INVEN) {
					if (press.mouse.y == 0) {
						if (use_equip) {
							p_ptr->command_wrk = USE_EQUIP;
						} else
						if (allow_floor) {
							p_ptr->command_wrk = USE_FLOOR;
						}
					} else
					if ((press.mouse.y <= i2-i1+1) ){
					//&& (press.mouse.x > Term->wid - 1 - max_len - ex_width)) {
						//k = label_to_inven(index_to_label(i1+press.mouse.y-1));
						/* get the item index, allowing for skipped indices */
						for (j = i1; j <= i2; j++) {
							if (get_item_okay(j)) {
								if (press.mouse.y == 1) {
									k = j;
									break;
								}
								press.mouse.y--;
							}
						}
					}
				} else
				if (p_ptr->command_wrk == USE_EQUIP) {
					if (press.mouse.y == 0) {
						if (allow_floor) {
							p_ptr->command_wrk = USE_FLOOR;
						} else
						if (use_inven) {
							p_ptr->command_wrk = USE_INVEN;
						}
					} else
					if (press.mouse.y <= e2-e1+1) {
						if (olist_mode & OLIST_SEMPTY) {
							/* If we are showing empties, just set the object (empty objects will just keep the loop going) */
							k = label_to_equip(index_to_label(e1+press.mouse.y-1));
						}
						else {
							/* get the item index, allowing for skipped indices */
							for (j = e1; j <= e2; j++) {
								/* skip the quiver slot which is a blank line in the list */
								if (j == 36) {
									press.mouse.y--;
								} else
									if (get_item_okay(j)) {
										if (press.mouse.y == 1) {
											k = j;
											break;
										}
										press.mouse.y--;
									}
							}
						}
					}
				} else
				if (p_ptr->command_wrk == USE_FLOOR) {
					if (press.mouse.y == 0) {
						if (use_inven) {
							p_ptr->command_wrk = USE_INVEN;
						} else
						if (use_equip) {
							p_ptr->command_wrk = USE_EQUIP;
						}
					} else
					if ((press.mouse.y <= floor_num) && (press.mouse.y >= 1)) {
						/* Special index */
						k = 0 - floor_list[press.mouse.y-1];
						/* get the item index, allowing for skipped indices */
						for (j = f1; j <= f2; j++) {
							if (get_item_okay(0 - floor_list[j])) {
								if (press.mouse.y == 1) {
									k = 0 - floor_list[j];
									break;
								}
								press.mouse.y--;
							}
						}
						/* check the bounds the item number */
						if (k < 0) {
							/* Allow player to "refuse" certain actions */
							if (!get_item_allow(k, cmdkey, cmd, is_harmless))
							{
								done = TRUE;
							}

							/* Accept that choice */
							(*cp) = k;
							item = TRUE;
							done = TRUE;
						} else {
							/* set k to a value that will be invalid below */
							k = -1;
						}
					}
				}
				if (k >= 0) {
					/* Validate the item */
					if (!get_item_okay(k)) {
						bell("Illegal object choice (normal)!");
					}

					/* Allow player to "refuse" certain actions */
					if (!get_item_allow(k, cmdkey, cmd, is_harmless)) {
						done = TRUE;
					}

					/* Accept that choice */
					(*cp) = k;
					item = TRUE;
					done = TRUE;
				} else
				if (press.mouse.y == 0) {
					/* Hack -- Fix screen */
					if (show_list) {
						/* Load screen */
						screen_load();

						/* Save screen */
						screen_save();
					}
				}
			}
		} else
		//switch (which.code)
		switch (press.key.code)
		{
			case ESCAPE:
			case ' ':
			{
				done = TRUE;
				break;
			}

			case '/':
			{
				/* Toggle to inventory */
				if (use_inven && (p_ptr->command_wrk != USE_INVEN))
				{
					p_ptr->command_wrk = USE_INVEN;
				}

				/* Toggle to equipment */
				else if (use_equip && (p_ptr->command_wrk != USE_EQUIP))
				{
					p_ptr->command_wrk = USE_EQUIP;
				}

				/* No toggle allowed */
				else
				{
					bell("Cannot switch item selector!");
					break;
				}


				/* Hack -- Fix screen */
				if (show_list)
				{
					/* Load screen */
					screen_load();

					/* Save screen */
					screen_save();
				}

				/* Need to redraw */
				break;
			}

			case '-':
			{
				/* Paranoia */
				if (!allow_floor)
				{
					bell("Cannot select floor!");
					break;
				}

				/* There is only one item */
				if (floor_num == 1)
				{
					/* Auto-select */
					if (p_ptr->command_wrk == (USE_FLOOR))
					{
						/* Special index */
						k = 0 - floor_list[0];

						/* Allow player to "refuse" certain actions */
						if (!get_item_allow(k, cmdkey, cmd, is_harmless))
						{
							done = TRUE;
							break;
						}

						/* Accept that choice */
						(*cp) = k;
						item = TRUE;
						done = TRUE;

						break;
					}
				}

				/* Hack -- Fix screen */
				if (show_list)
				{
					/* Load screen */
					screen_load();

					/* Save screen */
					screen_save();
				}

				p_ptr->command_wrk = (USE_FLOOR);

#if 0
				/* Check each legal object */
				for (i = 0; i < floor_num; ++i)
				{
					/* Special index */
					k = 0 - floor_list[i];

					/* Skip non-okay objects */
					if (!get_item_okay(k)) continue;

					/* Allow player to "refuse" certain actions */
					if (!get_item_allow(k, cmdkey, cmd, is_harmless)) continue;

					/* Accept that choice */
					(*cp) = k;
					item = TRUE;
					done = TRUE;
					break;
				}
#endif

				break;
			}

			case '0':
			case '1': case '2': case '3':
			case '4': case '5': case '6':
			case '7': case '8': case '9':
			{
				/* Look up the tag */
				//if (!get_tag(&k, which.code, cmd, quiver_tags))
				if (!get_tag(&k, press.key.code, cmd, quiver_tags))
				{
					bell("Illegal object choice (tag)!");
					break;
				}

				/* Hack -- Validate the item */
				if ((k < INVEN_WIELD) ? !allow_inven : !allow_equip)
				{
					bell("Illegal object choice (tag)!");
					break;
				}

				/* Validate the item */
				if (!get_item_okay(k))
				{
					bell("Illegal object choice (tag)!");
					break;
				}

				/* Allow player to "refuse" certain actions */
				if (!get_item_allow(k, cmdkey, cmd, is_harmless))
				{
					done = TRUE;
					break;
				}

				/* Accept that choice */
				(*cp) = k;
				item = TRUE;
				done = TRUE;
				break;
			}

			case KC_ENTER:
			{
				/* Choose "default" inventory item */
				if (p_ptr->command_wrk == USE_INVEN)
				{
					if (i1 != i2)
					{
						bell("Illegal object choice (default)!");
						break;
					}

					k = i1;
				}

				/* Choose the "default" slot (0) of the quiver */
				else if (quiver_tags)
					k = e1;

				/* Choose "default" equipment item */
				else if (p_ptr->command_wrk == USE_EQUIP)
				{
					if (e1 != e2)
					{
						bell("Illegal object choice (default)!");
						break;
					}

					k = e1;
				}

				/* Choose "default" floor item */
				else
				{
					if (f1 != f2)
					{
						bell("Illegal object choice (default)!");
						break;
					}

					k = 0 - floor_list[f1];
				}

				/* Validate the item */
				if (!get_item_okay(k))
				{
					bell("Illegal object choice (default)!");
					break;
				}

				/* Allow player to "refuse" certain actions */
				if (!get_item_allow(k, cmdkey, cmd, is_harmless))
				{
					done = TRUE;
					break;
				}

				/* Accept that choice */
				(*cp) = k;
				item = TRUE;
				done = TRUE;
				break;
			}

			default:
			{
				bool verify;

				/* Note verify */
				//verify = (isupper((unsigned char)which.code) ? TRUE : FALSE);
				verify = (isupper((unsigned char)press.key.code) ? TRUE : FALSE);

				/* Lowercase */
				//which.code = tolower((unsigned char)which.code);
				press.key.code = tolower((unsigned char)press.key.code);

				/* Convert letter to inventory index */
				if (p_ptr->command_wrk == USE_INVEN)
				{
					//k = label_to_inven(which.code);
					k = label_to_inven(press.key.code);

					if (k < 0)
					{
						bell("Illegal object choice (inven)!");
						break;
					}
				}

				/* Convert letter to equipment index */
				else if (p_ptr->command_wrk == USE_EQUIP)
				{
					//k = label_to_equip(which.code);
					k = label_to_equip(press.key.code);

					if (k < 0)
					{
						bell("Illegal object choice (equip)!");
						break;
					}
				}

				/* Convert letter to floor index */
				else
				{
					//k = (islower((unsigned char)which.code) ? A2I((unsigned char)which.code) : -1);
					k = (islower((unsigned char)press.key.code) ? A2I((unsigned char)press.key.code) : -1);

					if (k < 0 || k >= floor_num)
					{
						bell("Illegal object choice (floor)!");
						break;
					}

					/* Special index */
					k = 0 - floor_list[k];
				}

				/* Validate the item */
				if (!get_item_okay(k))
				{
					bell("Illegal object choice (normal)!");
					break;
				}

				/* Verify the item */
				if (verify && !verify_item("Try", k))
				{
					done = TRUE;
					break;
				}

				/* Allow player to "refuse" certain actions */
				if (!get_item_allow(k, cmdkey, cmd, is_harmless))
				{
					done = TRUE;
					break;
				}

				/* Accept that choice */
				(*cp) = k;
				item = TRUE;
				done = TRUE;
				break;
			}
		}
	}


	/* Fix the screen if necessary */
	if (show_list)
	{
		/* Load screen */
		screen_load();

		/* Hack -- Cancel "display" */
		show_list = FALSE;
	}


	/* Kill buttons */
	button_kill('*');
	button_kill('/');
	button_kill('-');
	button_kill('!');
	redraw_stuff(p_ptr);
 
	/* Forget the item_tester_tval restriction */
	item_tester_tval = 0;

	/* Forget the item_tester_hook restriction */
	item_tester_hook = NULL;


	/* Toggle again if needed */
	if (toggle) toggle_inven_equip();

	/* Update */
	p_ptr->redraw |= (PR_INVEN | PR_EQUIP);
	redraw_stuff(p_ptr);


	/* Clear the prompt line */
	prt("", 0, 0);

	/* Warning if needed */
	if (oops && str) msg("%s", str);

	/* Result */
	return (item);
}