Exemple #1
0
cBuf * pack_data(cBuf *buf, cData *data)
{
    buf = write_long(buf, data->type);
    switch (data->type) {

        case INTEGER:
            buf = write_long(buf, data->u.val);
            break;

        case FLOAT:
            buf = write_float(buf, data->u.fval);
            break;

        case STRING:
            buf = string_pack(buf, data->u.str);
            break;

        case OBJNUM:
            buf = write_long(buf, data->u.objnum);
            break;

        case LIST:
            buf = pack_list(buf, data->u.list);
            break;

        case SYMBOL:
            buf = write_ident(buf, data->u.symbol);
            break;

        case T_ERROR:
            buf = write_ident(buf, data->u.error);
            break;

        case FROB:
            buf = write_long(buf, data->u.frob->cclass);
            buf = pack_data(buf, &data->u.frob->rep);
            break;

        case DICT:
            buf = pack_dict(buf, data->u.dict);
            break;

        case BUFFER:
            buf = write_long(buf, data->u.buffer->len);
            buf = buffer_append(buf, data->u.buffer);
            break;

#ifdef USE_PARENT_OBJS
        case OBJECT:
            break;
#endif

        default: {
            INSTANCE_RECORD(data->type, r);
            buf = r->pack(buf, data);
        }
    }
    return buf;
}
Exemple #2
0
void mkdir(int fd, std::string name) {
	std::vector<std::string> dirs = split(name, '/');

	int inum = 1; //1 represents the root

	SuperBlock sb(fd);
	//Get the i-number for each directory along the path,
	//Until the first directory along the path isn't found
	//Create that directory
	for(std::vector<std::string>::iterator it = dirs.begin(); it != dirs.end(); ++it) {
		dout << *it << std::endl;
		int child_inum = path_to_inum(fd, *it, inum);

		//if the directory is not present
		if(child_inum < 1) {
			child_inum = sb.allocate_inode(fd);
			if(child_inum < 1) {
				std::cerr << "I-nodes depleted. Cannot allocate directory entry." << std::endl;
				return;
			}

			INode node(child_inum);
			node.flags = 0x8000 | 0x4000; //allocated and directory

			//We've allocated an inode, now we need to allocate a data block
			//Populate that data block with the entries for . and ..
			//and associate it with the inode.
			int block = sb.allocate_block(fd);
			if(block < 0) {
				std::cerr << "Data blocks depleted. Cannot allocate directory entry." << std::endl;
				return;
			}

			char buffer[BLOCK_SIZE] = {};
			write_long(child_inum, sizeof(child_inum), buffer);
			buffer[sizeof(child_inum)] = '.';
			write_long(inum, sizeof(inum), buffer + DIR_SIZE);
			buffer[sizeof(inum) + DIR_SIZE] = '.';
			buffer[sizeof(inum) + DIR_SIZE + 1] = '.';

			lseek(fd, block, SEEK_SET);
			write(fd, buffer, BLOCK_SIZE);

			char dir_entry[DIR_SIZE];
			write_long(child_inum, sizeof(child_inum), dir_entry);
			strncpy(dir_entry + sizeof(child_inum), (*it).c_str(), DIR_SIZE - sizeof(child_inum));

			//Add child inode to parent's directory listing
			addDirEntry(fd, inum, dir_entry);					

			node.flush(fd);
		}

		inum = child_inum;
	}

	sb.flush(fd);
}
Exemple #3
0
void write_times() {

  struct timespec tf;
  clock_gettime(CLOCK_MONOTONIC, &tf);

  write_long(ts.tv_sec);
  write_long(ts.tv_nsec);
  write_long(tf.tv_sec);
  write_long(tf.tv_nsec);

}
Exemple #4
0
static cBuf * pack_list(cBuf *buf, cList *list)
{
    cData *d;

    if (!list) {
        buf = write_long(buf, -1);
    } else {
        buf = write_long(buf, list_length(list));
        for (d = list_first(list); d; d = list_next(list, d))
            buf = pack_data(buf, d);
    }

    return buf;
}
Exemple #5
0
int write_object_basic(FILE *fp, int index, object *obj)
{
	int	i;
	
/* begin of object data */
	write_int(fp, index);  /* object # */
	
	printf("Writing object %s\n", obj->name );

	write_chars(fp, obj->name, sizeof(obj->name));
	write_chars(fp, obj->description, sizeof(obj->description));
	for (i = 0; i != 3; i++)
		write_chars(fp, obj->key[i], sizeof(obj->key[i]));
	write_chars(fp, obj->use_output, sizeof(obj->use_output));
	write_long(fp, obj->value);
	write_short(fp, obj->weight);
	
	write_char(fp, obj->type);
	write_char(fp, obj->adjustment);
	
	write_short(fp, obj->shotsmax);
	write_short(fp, obj->shotscur);
	write_short(fp, obj->ndice);
	write_short(fp, obj->sdice);
	write_short(fp, obj->pdice);
	
	write_char(fp, obj->armor);
	write_char(fp, obj->wearflag);
	write_char(fp, obj->magicpower);
	write_char(fp, obj->magicrealm);
	write_short(fp, obj->special);
	write_chars(fp, obj->flags, sizeof(obj->flags));
	write_char(fp, obj->questnum);
	write_char(fp,obj->strength);
	write_char(fp,obj->dexterity);
	write_char(fp,obj->constitution);
	write_char(fp,obj->intelligence);
	write_char(fp,obj->piety);
	for (i = 0; i != 16; i++)
		write_short(fp, obj->sets_flag[i]);
	write_short(fp,obj->special1);
	write_long(fp,obj->special2);

	
/* end of object data */

	return(0);
	
}
Exemple #6
0
void		command_ls(t_env *env, char **splitted)
{
	long	i;
	char	c;

	write_long(env, COMMAND_LS);
	write_long(env, tab_len(splitted));
	i = 1;
	while (splitted[i])
		write_str(env, splitted[i++]);
	while ((c = read_byte(env)))
		ft_putchar(c);
	ft_putendl("SUCCESS");
	(void)splitted;
}
Exemple #7
0
static cBuf * pack_dict(cBuf *buf, cDict *dict)
{
    Int i;

    buf = pack_list(buf, dict->keys);
    buf = pack_list(buf, dict->values);
    if (dict->keys->len > 64) {
        buf = write_long(buf, dict->hashtab_size);
        for (i = 0; i < dict->hashtab_size; i++) {
	    buf = write_long(buf, dict->links[i]);
	    buf = write_long(buf, dict->hashtab[i]);
        }
    }
    return buf;
}
Exemple #8
0
cBuf * write_ident(cBuf *buf, Ident id)
{
    Char *s;
    Int len;

    if (id == NOT_AN_IDENT) {
        buf = write_long(buf, NOT_AN_IDENT);
        return buf;
    }
    s = ident_name_size(id, &len);
    buf = write_long(buf, len);
    buf = buffer_append_uchars_single_ref(buf, (uChar *)s, len);

    return buf;
}
Exemple #9
0
static cBuf * pack_idents(cBuf *buf, Obj *obj)
{
    Int i;

    buf = write_long(buf, obj->methods->idents_size);
    buf = write_long(buf, obj->methods->num_idents);
    for (i = 0; i < obj->methods->num_idents; i++) {
	if (obj->methods->idents[i].id != NOT_AN_IDENT) {
	    buf = write_ident(buf, obj->methods->idents[i].id);
	    buf = write_long(buf, obj->methods->idents[i].refs);
	} else {
	    buf = write_long(buf, NOT_AN_IDENT);
	}
    }
    return buf;
}
Exemple #10
0
int WaveProc::write_header(FILE *out, unsigned int data_length)
{
	fprintf(out, "RIFF");
	write_long(out, fmt_chunk->riff_length);
	fprintf(out, "WAVE");
	fprintf(out, "fmt ");
	write_long(out, 16);
	write_word(out, fmt_chunk->format_type);
	write_word(out, fmt_chunk->channel_numbers);
	write_long(out, fmt_chunk->sample_rate);
	write_long(out, fmt_chunk->bytes_per_second);
	write_word(out, fmt_chunk->bytes_per_sample);
	write_word(out, fmt_chunk->bits_per_sample);
	fprintf(out, "data");
	write_long(out, data_length);
	return 0;
}
Exemple #11
0
cBuf *pack_handled (cBuf *buf, cData *d)
{
    HandledFrob *h = HANDLED_FROB(d);

    buf = write_long (buf, h->cclass);
    buf = pack_data  (buf, &h->rep);
    buf = write_ident(buf, h->handler);
    return buf;
}
Exemple #12
0
static void		do_the_thing(t_env *env, char **splitted)
{
	char	*file;
	int		fd;

	file = get_file_name(splitted[1]);
	if ((fd = open(file, O_CREAT | O_TRUNC | O_WRONLY
					, (int)read_long(env))) == -1)
	{
		write_long(env, 0);
		ft_putendl("ERROR: can't create file");
		return ;
	}
	write_long(env, 1);
	read_file(env, fd);
	close(fd);
	free(file);
}
Exemple #13
0
void write_log_delta (unsigned long when, unsigned char offset, unsigned char delta)
{
	unsigned long since_last = when - when_last;
	int rc;
	
	rc = write_long (fd, since_last);
	rc = write (fd, &offset, sizeof (offset));
	rc = write (fd, &delta, sizeof (delta));
	when_last = when;
}
Exemple #14
0
void	command_pwd(t_env *env, char **splitted)
{
	char	*path;

	write_long(env, COMMAND_PWD);
	path = read_str(env);
	ft_putendl(path);
	ft_putendl("SUCCESS");
	free(path);
	(void)splitted;
}
Exemple #15
0
    void close(Sink& snk, BOOST_IOS::openmode m)
    {
        try {
            // Close zlib compressor.
            base_type::close(snk, m);

            if (m == BOOST_IOS::out) {
                if (flags_ & f_header_done) {

                    // Write final fields of gzip file format.
                    write_long(this->crc(), snk);
                    write_long(this->total_in(), snk);
                }
            }
        } catch(...) {
            close_impl();
            throw;
        }
        close_impl();
    }
Exemple #16
0
static cBuf * pack_methods(cBuf *buf, Obj *obj)
{
    Int i;

    if (!object_has_methods(obj)) {
        buf = write_long(buf, -1);
        return buf;
    }

    buf = write_long(buf, obj->methods->size);
    buf = write_long(buf, obj->methods->blanks);

    for (i = 0; i < obj->methods->size; i++) {
	buf = write_long(buf, obj->methods->hashtab[i]);
	if (obj->methods->tab[i].m) {
	    buf = pack_method(buf, obj->methods->tab[i].m);
	} else {
	    /* Method begins with name identifier; write NOT_AN_IDENT. */
	    buf = write_long(buf, NOT_AN_IDENT);
	}
	buf = write_long(buf, obj->methods->tab[i].next);
    }

    buf = pack_strings(buf, obj);
    buf = pack_idents(buf, obj);

    return buf;
}
Exemple #17
0
static int erl_json_ei_number(void* ctx, const char * val, unsigned int len) {
  State* pState = (State*) ctx;

  flog(stderr, "number", 0, val, len);

  list_header_for_value(pState);

  switch(numbers_as(pState)) {
    case EEP0018_PARSE_NUMBERS_AS_NUMBER:
    {
      if(memchr(val, '.', len) || memchr(val, 'e', len) || memchr(val, 'E', len))
        write_double(pState, strtod(val, 0));
      else
        write_long(pState, strtol(val, 0, 10));
      break;
    }
    case EEP0018_PARSE_NUMBERS_AS_FLOAT:
    {
      write_double(pState, strtod(val, 0));
      break;
    }
    case EEP0018_PARSE_NUMBERS_AS_TUPLE:
    {
      /* 
        While "1e1" is a valid JSON number, it is not a valid parameter to list_to_float/1 
        We fix that by inserting ".0" before the exponent e. 
      */
      const char* exp = memchr(val, 'e', len);
      if(exp && exp > val) {
        const char* dot = memchr(val, '.', exp - val);
        if(!dot) {
          char* tmp = alloca(len + 5);
          memcpy(tmp, val, exp - val);
          memcpy(tmp + (exp - val), ".0", 2);
          memcpy(tmp + (exp - val) + 2, exp, len - (exp - val));
          len += 2;
          val = tmp;
          tmp[len] = 0;
        }
      }

      write_tuple_header(pState, 3);
      write_atom(pState, "number", 6);
      write_string(pState, val, len);
      write_atom(pState, "a", 1);       // a dummy
      break;
    }
  }

  
  return 1;
}
Exemple #18
0
void write_log_state (unsigned long when, unsigned char offset, unsigned char state)
{
	unsigned long since_last = when - when_last;
	unsigned char marker = 0xF8;
	int rc;

	rc = write (fd, &marker, sizeof (marker));
	rc = write_long (fd, since_last);
	rc =write (fd, &offset, sizeof (offset));
	rc = write (fd, &state, sizeof (state));
	when_last = when;
	io_state[offset] = state;
}
Exemple #19
0
static glui32 write_memstate(dest_t *dest)
{
  glui32 res, pos;
  int val;
  int runlen;
  unsigned char ch;

  res = write_long(dest, endmem);
  if (res)
    return res;

  runlen = 0;
  glk_stream_set_position(gamefile, gamefile_start+ramstart, seekmode_Start);

  for (pos=ramstart; pos<endmem; pos++) {
    ch = Mem1(pos);
    if (pos < endgamefile) {
      val = glk_get_char_stream(gamefile);
      if (val == -1) {
        fatal_error("The game file ended unexpectedly while saving.");
      }
      ch ^= (unsigned char)val;
    }
    if (ch == 0) {
      runlen++;
    }
    else {
      /* Write any run we've got. */
      while (runlen) {
        if (runlen >= 0x100)
          val = 0x100;
        else
          val = runlen;
        res = write_byte(dest, 0);
        if (res)
          return res;
        res = write_byte(dest, (val-1));
        if (res)
          return res;
        runlen -= val;
      }
      /* Write the byte we got. */
      res = write_byte(dest, ch);
      if (res)
        return res;
    }
  }
  /* It's possible we've got a run left over, but we don't write it. */

  return 0;
}
Exemple #20
0
/* Saves the table along with the offset. */
int rc_sftable (struct functab * table) {
	struct functab * t;
	int i;

	for (t = table; t != NULL; t = t->next) {
		for (i = 0; /*i < MAXWS && */t -> name [i] != '\0'; i++) {
			write_byte (t -> name [i]);
		}

		/*for (; i < MAXWS; i++)*/ write_byte ('\0');
		write_long (t -> offset);
	}
	return 0;
}
Exemple #21
0
static void compile_desc_entry(repo_t *repo, const alpm_pkg_meta_t *pkg, struct buffer *buf)
{
    write_string(buf, "FILENAME",  pkg->filename);
    write_string(buf, "NAME",      pkg->name);
    write_string(buf, "BASE",      pkg->base);
    write_string(buf, "VERSION",   pkg->version);
    write_string(buf, "DESC",      pkg->desc);
    write_list(buf,   "GROUPS",    pkg->groups);
    write_long(buf,   "CSIZE",     (long)pkg->size);
    write_long(buf,   "ISIZE",     (long)pkg->isize);

    if (pkg->md5sum) {
        write_string(buf, "MD5SUM", pkg->md5sum);
    } else {
        char *md5sum = _compute_md5sum(repo->dirfd, pkg->filename);
        write_string(buf, "MD5SUM", md5sum);
        free(md5sum);
    }

    if (pkg->sha256sum) {
        write_string(buf, "SHA256SUM", pkg->sha256sum);
    } else {
        char *sha256sum = _compute_sha256sum(repo->dirfd, pkg->filename);
        write_string(buf, "SHA256SUM", sha256sum);
        free(sha256sum);
    }

    if (pkg->base64_sig)
        write_string(buf, "PGPSIG", pkg->base64_sig);

    write_string(buf, "URL",       pkg->url);
    write_list(buf,   "LICENSE",   pkg->license);
    write_string(buf, "ARCH",      pkg->arch);
    write_long(buf,   "BUILDDATE", pkg->builddate);
    write_string(buf, "PACKAGER",  pkg->packager);
    write_list(buf,   "REPLACES",  pkg->replaces);
}
Exemple #22
0
/**
 * Goes back and writes out the subroutine list
 */
void write_index() {
	fseek(dest_file, 3, SEEK_SET);

	int bytesRemaining = indexSize - 3;
	for (int i = 0; i < subroutinesCount; ++i) {
		int entrySize = strlen(subroutinesTable[i].name) + 5;

		// Ensure there is enough remaining space
		if ((bytesRemaining - entrySize) < 0) {
			printf("Index has exceeded allowable size.\n");
			token = ERROR;
		}

		// Write out the name and the file offset
		write_bytes((byte *)&subroutinesTable[i].name, strlen(subroutinesTable[i].name) + 1);
		write_long(subroutinesTable[i].fileOffset);
	}
}
Exemple #23
0
void			command_get(t_env *env, char **splitted)
{
	int		res;

	if (!splitted[1])
	{
		ft_putendl("ERROR: you must specify a file to get");
		return ;
	}
	write_long(env, COMMAND_GET);
	write_str(env, splitted[1]);
	if ((res = read_long(env)) == -1)
		ft_putendl("ERROR: file not found");
	else if (res == -2)
		ft_putendl("ERROR: permissions denied");
	else if (res == -3)
		ft_putendl("ERROR: unknown error");
	else
		do_the_thing(env, splitted);
}
Exemple #24
0
static glui32 write_heapstate_sub(glui32 sumlen, glui32 *sumarray,
  dest_t *dest, int portable) 
{
  glui32 res, lx;

  /* If we're storing for the purpose of undo, we don't need to do any
     byte-swapping, because the result will only be used by this session. */
  if (!portable) {
    res = write_buffer(dest, (void *)sumarray, sumlen*sizeof(glui32));
    if (res)
      return res;
    return 0;
  }

  for (lx=0; lx<sumlen; lx++) {
    res = write_long(dest, sumarray[lx]);
    if (res)
      return res;
  }

  return 0;
}
Exemple #25
0
static cBuf * pack_vars(cBuf *buf, Obj *obj)
{
    Int i;

    buf = write_long(buf, obj->vars.size);
    buf = write_long(buf, obj->vars.blanks);

    for (i = 0; i < obj->vars.size; i++) {
	buf = write_long(buf, obj->vars.hashtab[i]);
	if (obj->vars.tab[i].name != NOT_AN_IDENT) {
	    buf = write_ident(buf, obj->vars.tab[i].name);
	    buf = write_long(buf, obj->vars.tab[i].cclass);
	    buf = pack_data(buf, &obj->vars.tab[i].val);
	} else {
	    buf = write_long(buf, NOT_AN_IDENT);
	}
	buf = write_long(buf, obj->vars.tab[i].next);
    }
    return buf;
}
Exemple #26
0
/* Initialisation du fichier TIFF résultat, avec les paramètres suivants:
   - width: la largeur de l'image ;
   - height: la hauteur de l'image ;
   - row_per_strip: le nombre de lignes de pixels par bande.
 */
struct tiff_file_desc *init_tiff_file (const char *file_name,
                                       uint32_t width,
                                       uint32_t height,
                                       uint32_t row_per_strip)
{
        FILE *file = NULL;
        struct tiff_file_desc *tfd = calloc(1, sizeof(struct tiff_file_desc));
        uint32_t line_size;

        if (tfd == NULL)
                return NULL;


        /* Allocate & check write_buf */
        tfd->row_size = width * 3;

        tfd->write_buf = malloc(tfd->row_size);
        if (tfd->write_buf == NULL)
                return NULL;


        /* Allocate & check strip_offsets */
        tfd->nb_strips = height / row_per_strip;

        if (height % row_per_strip)
                tfd->nb_strips++;

        tfd->strip_offsets = malloc(tfd->nb_strips * sizeof(uint32_t));
        if (tfd->strip_offsets == NULL)
                return NULL;


        /* Allocate & check strip_bytes */
        tfd->strip_bytes = malloc(tfd->nb_strips * sizeof(uint32_t));
        if (tfd->strip_bytes == NULL)
                return NULL;


        file = fopen(file_name, "wb");
        if (file == NULL)
                return NULL;

        tfd->file = file;

        tfd->is_le = true;
        tfd->width = width;
        tfd->height = height;
        tfd->rows_per_strip = row_per_strip;


        /* Software comment definition */
        const char *comment = COMMENT;
        const uint32_t comment_size = strlen(comment) + 1;


        /* Header construction */
        const uint32_t ifd_offset = 8 + comment_size;
        const uint16_t entry_count = 13;

        /* Endianness + TIFF identification */
        write_short(tfd, LITTLE_ENDIAN);
        write_short(tfd, 42);

        /* IFD offset */
        write_long(tfd, ifd_offset);

        /* Software comment */
        fwrite(comment, 1, comment_size, file);


        uint32_t next = ifd_offset + 2 + 12 * entry_count + 4;

        /* IFD data */
        write_short(tfd, entry_count);

        /* Image Width */
        write_short(tfd, IMAGE_WIDTH);
        write_short(tfd, LONG);
        write_long(tfd, 1);
        write_long(tfd, tfd->width);

        /* Image Length */
        write_short(tfd, IMAGE_LENGTH);
        write_short(tfd, LONG);
        write_long(tfd, 1);
        write_long(tfd, tfd->height);


        /* BitsPerSample */
        write_short(tfd, BITS_PER_SAMPLE);
        write_short(tfd, SHORT);
        write_long(tfd, 3);
        write_long(tfd, next);
        next += 3 * 2;

        /* Compression */
        write_short(tfd, COMPRESSION);
        write_short(tfd, SHORT);
        write_long(tfd, 1);
        write_long(tfd, 1);

        /* PhotometricInterpretation */
        write_short(tfd, PHOTOMETRIC);
        write_short(tfd, SHORT);
        write_long(tfd, 1);
        write_long(tfd, 2);

        /* StripOffsets */
        write_short(tfd, STRIP_OFFSETS);
        write_short(tfd, LONG);
        write_long(tfd, tfd->nb_strips);

        const uint32_t strips_pos = next + 16;
        uint32_t line_offset = strips_pos;


        /* One row handling */
        if (tfd->nb_strips > 1) {
                line_offset += 8 * tfd->nb_strips;
                write_long(tfd, strips_pos);
        }

        else {
                write_long(tfd, line_offset);
                tfd->strip_offsets[0] = line_offset;
        }


        /* SamplesPerPixel */
        write_short(tfd, SAMPLES_PER_PIXEL);
        write_short(tfd, SHORT);
        write_long(tfd, 1);
        write_long(tfd, 3);

        /* RowsPerStrip */
        write_short(tfd, ROWS_PER_STRIP);
        write_short(tfd, LONG);
        write_long(tfd, 1);
        write_long(tfd, tfd->rows_per_strip);

        /* StripByteCounts */
        write_short(tfd, STRIP_BYTE_COUNTS);
        write_short(tfd, LONG);
        write_long(tfd, tfd->nb_strips);


        /* Last line's height */
        uint32_t line_height = tfd->height % tfd->rows_per_strip;

        if (tfd->height > 0  && line_height == 0)
                line_height = tfd->rows_per_strip;


        /* One row handling */
        if (tfd->nb_strips > 1) {
                line_size = tfd->rows_per_strip * tfd->width * 3;
                write_long(tfd, strips_pos + 4 * tfd->nb_strips);
        }

        else {
                line_size = line_height * tfd->width * 3;
                write_long(tfd, line_size);

                tfd->strip_bytes[0] = line_size;
        }


        /* XResolution */
        write_short(tfd, X_RESOLUTION);
        write_short(tfd, RATIONAL);
        write_long(tfd, 1);
        write_long(tfd, next);
        next += 2 * 4;

        /* YResolution */
        write_short(tfd, Y_RESOLUTION);
        write_short(tfd, RATIONAL);
        write_long(tfd, 1);
        write_long(tfd, next);
        next += 2 * 4;

        /* ResolutionUnit */
        write_short(tfd, RESOLUTION_UNIT);
        write_short(tfd, SHORT);
        write_long(tfd, 1);
        write_long(tfd, 2);

        /* Software */
        write_short(tfd, SOFTWARE);
        write_short(tfd, ASCII);
        write_long(tfd, comment_size);
        write_long(tfd, 8);


        /* No other IFD */
        write_long(tfd, 0);


        /* BitsPerSample data */
        write_short(tfd, 8);
        write_short(tfd, 8);
        write_short(tfd, 8);

        /* XResolution data */
        write_long(tfd, 100);
        write_long(tfd, 1);

        /* YResolution data */
        write_long(tfd, 100);
        write_long(tfd, 1);


        /* Initialize internal writing data */
        tfd->current_line = 0;
        tfd->line_size = line_size;

        /* Initialize the first MCU position */
        tfd->next_pos_mcu = 0;

        /* If there are multiple strips */
        if (tfd->nb_strips > 1) {

                /* Write all StripOffsets */
                for (uint32_t i = 0; i < tfd->nb_strips; i++){
                        write_long(tfd, line_offset);
                        tfd->strip_offsets[i] = line_offset;

                        line_offset += line_size;
                }


                /* StripByteCounts data */
                for (uint32_t i = 0; i < tfd->nb_strips - 1; i++) {
                        write_long(tfd, line_size);
                        tfd->strip_bytes[i] = line_size;
                }

                /* Last line's size */
                line_size = line_height * tfd->width*3;
                tfd->strip_bytes[tfd->nb_strips-1] = line_size;

                write_long(tfd, line_size);
        }


        return tfd;
}
Exemple #27
0
bool Quetzal::save(Common::WriteStream *svf, Processor *proc, const Common::String &desc) {
	Processor &p = *proc;
	uint ifzslen = 0, cmemlen = 0, stkslen = 0, descLen = 0;
	uint pc;
	zword i, j, n;
	zword nvars, nargs, nstk;
	zbyte var;
	long cmempos, stkspos;
	int c;

	// Set a temporary memory stream for writing out the data. This is needed, since we need to
	// do some seeking within it at the end to fill out totals before properly writing it all out
	Common::MemoryWriteStreamDynamic saveData(DisposeAfterUse::YES);
	_out = &saveData;

	// Write `IFZS' header.
	write_chnk(ID_FORM, 0);
	write_long(ID_IFZS);

	// Write `IFhd' chunk
	pc = p.getPC();
	write_chnk(ID_IFhd, 13);
	write_word(p.h_release);
	for (i = H_SERIAL; i<H_SERIAL + 6; ++i)
		write_byte(p[i]);

	write_word(p.h_checksum);
	write_long(pc << 8);		// Includes pad

	// Write 'ANNO' chunk
	descLen = desc.size() + 1;
	write_chnk(ID_ANNO, descLen);
	saveData.write(desc.c_str(), desc.size());
	write_byte(0);
	if ((desc.size() % 2) == 0) {
		write_byte(0);
		++descLen;
	}

	// Write `CMem' chunk.
	cmempos = saveData.pos();
	write_chnk(ID_CMem, 0);
	_storyFile->seek(0);

	// j holds current run length.
	for (i = 0, j = 0, cmemlen = 0; i < p.h_dynamic_size; ++i) {
		c = _storyFile->readByte();
		c ^= p[i];

		if (c == 0) {
			// It's a run of equal bytes
			++j;
		} else {
			// Write out any run there may be.
			if (j > 0) {
				for (; j > 0x100; j -= 0x100) {
					write_run(0xFF);
					cmemlen += 2;
				}
				write_run(j - 1);
				cmemlen += 2;
				j = 0;
			}

			// Any runs are now written. Write this (nonzero) byte
			write_byte((zbyte)c);
			++cmemlen;
		}
	}

	// Reached end of dynamic memory. We ignore any unwritten run there may be at this point.
	if (cmemlen & 1)
		// Chunk length must be even.
		write_byte(0);

	// Write `Stks' chunk. You are not expected to understand this. ;)
	stkspos = saveData.pos();
	write_chnk(ID_Stks, 0);

	// We construct a list of frame indices, most recent first, in `frames'.
	// These indices are the offsets into the `stack' array of the word before
	// the first word pushed in each frame.
	frames[0] = p._sp - p._stack;	// The frame we'd get by doing a call now.
	for (i = p._fp - p._stack + 4, n = 0; i < STACK_SIZE + 4; i = p._stack[i - 3] + 5)
		frames[++n] = i;

	// All versions other than V6 can use evaluation stack outside a function
	// context. We write a faked stack frame (most fields zero) to cater for this.
	if (p.h_version != V6) {
		for (i = 0; i < 6; ++i)
			write_byte(0);
		nstk = STACK_SIZE - frames[n];
		write_word(nstk);
		for (j = STACK_SIZE - 1; j >= frames[n]; --j)
			write_word(p._stack[j]);
		stkslen = 8 + 2 * nstk;
	}

	// Write out the rest of the stack frames.
	for (i = n; i > 0; --i) {
		zword *pf = p._stack + frames[i] - 4;	// Points to call frame
		nvars = (pf[0] & 0x0F00) >> 8;
		nargs = pf[0] & 0x00FF;
		nstk = frames[i] - frames[i - 1] - nvars - 4;
		pc = ((uint)pf[3] << 9) | pf[2];

		// Check type of call
		switch (pf[0] & 0xF000)	{
		case 0x0000:
			// Function
			var = p[pc];
			pc = ((pc + 1) << 8) | nvars;
			break;

		case 0x1000:
			// Procedure
			var = 0;
			pc = (pc << 8) | 0x10 | nvars;	// Set procedure flag
			break;

		default:
			p.runtimeError(ERR_SAVE_IN_INTER);
			return 0;
		}
		if (nargs != 0)
			nargs = (1 << nargs) - 1;	// Make args into bitmap

		// Write the main part of the frame...
		write_long(pc);
		write_byte(var);
		write_byte(nargs);
		write_word(nstk);

		// Write the variables and eval stack
		for (j = 0, --pf; j<nvars + nstk; ++j, --pf)
			write_word(*pf);

		// Calculate length written thus far
		stkslen += 8 + 2 * (nvars + nstk);
	}

	// Fill in variable chunk lengths
	ifzslen = 4 * 8 + 4 + 14 + cmemlen + stkslen + descLen;
	if (cmemlen & 1)
		++ifzslen;

	saveData.seek(4);
	saveData.writeUint32BE(ifzslen);
	saveData.seek(cmempos + 4);
	saveData.writeUint32BE(cmemlen);
	saveData.seek(stkspos + 4);
	saveData.writeUint32BE(stkslen);

	// Write the save data out
	svf->write(saveData.getData(), saveData.size());

	// After all that, still nothing went wrong!
	return true;
}
Exemple #28
0
/* Constructs and queues a request packet describing the http query pointed
 * to by 'start'.
 */
int make_request_packet(Server *serv, int fd, int num_chars)
{
    struct sockaddr_in client_name, local_name;
    int client_namelen, local_namelen;
    int free_start, free_end;
    int packet_length;
    char *request;
    int len;

    client_namelen = sizeof(struct sockaddr_in);
    if (getpeername(fd, (struct sockaddr *) &client_name, &client_namelen) < 0)
    {
	syslog(LOG_INFO, "make_request_packet: failed to get peer "
		"name: %m\n");
	return 0;
    }
    local_namelen = sizeof(struct sockaddr_in);
    if (getsockname(fd, (struct sockaddr *) &local_name, &local_namelen) < 0)
    {
	syslog(LOG_INFO, "make_request_packet: failed to get sock name: %m\n");
	return 0;
    }
    change_state(serv, fd, fs_requested_backend);
    /* locate the free end of the buffer (possibly appending to previous
     * control packets) */
    append_data(serv, serv->control_fd, &free_start, &free_end, fs_output);
    /* reserve the first 4 bytes of the packet for the size field */
    packet_length = PAK_COM_OFF;
    /* add command field to packet */
    serv->writebuf.buffer[free_start + packet_length++] = PAK_REQUEST;
    /* add unique ID field to packet */
    write_long(&serv->writebuf.buffer[free_start], &packet_length,
	    (getpid() & 0xffff) | (fd << 16), 1);
    /* add client IP field to packet */
    write_long(&serv->writebuf.buffer[free_start], &packet_length,
	    client_name.sin_addr.s_addr, 0);
    /* add local IP field to packet */
    write_long(&serv->writebuf.buffer[free_start], &packet_length,
	    local_name.sin_addr.s_addr, 0);
    /* add local port field to packet */
    write_short(&serv->writebuf.buffer[free_start], &packet_length,
	    serv->port, 1);
    /* write the http headers */
    request = &serv->writebuf.buffer[serv->writebuf.pos[fd]];
    while (request[0] == '\r' || request[0] == '\n')
	request++;
    for (len = 0; len < num_chars && !isspace(request[len]); len++)
	;
    if (len < num_chars)
    {
	write_string(&serv->writebuf.buffer[free_start], &packet_length,
		"method");
	write_string_n(&serv->writebuf.buffer[free_start], &packet_length,
		request, len);
	num_chars -= len;
	request += len;
	for (len = 0; len < num_chars && isspace(request[len]); len++)
	    ;
	if (len < num_chars)
	{
	    num_chars -= len;
	    request += len;
	    for (len = 0; request[len] && !isspace(request[len]); len++)
		;
	    write_string(&serv->writebuf.buffer[free_start], &packet_length,
		    "uri");
	    write_string_n(&serv->writebuf.buffer[free_start], &packet_length,
		    request, len);
	    num_chars -= len;
	    request += len;
	    for (len = 0; len < num_chars && isspace(request[len]); len++)
		;
	    if (len < num_chars)
	    {
		num_chars -= len;
		request += len;
		for (len = 0; request[len] && !isspace(request[len]); len++)
		    ;
		write_string(&serv->writebuf.buffer[free_start],
			&packet_length, "version");
		write_string_n(&serv->writebuf.buffer[free_start],
			&packet_length, request, len);
		/* each line should end with \r\n.  Be a bit lenient, and
		 * allow just \r or \n, too.  End of request is indicated
		 * by two such lines in a row */
		if (request[len] == '\r')
		    len++;
		if (request[len] == '\n')
		    len++;
		num_chars -= len;
		request += len;
		/* find "field: value\r\n" on successive lines, adding them
		 * to the buffer as field\0value\0 */
		while (num_chars > 0 && request[0] != '\r' &&
			request[0] != '\n')
		{
		    for (len = 0; len < num_chars && request[len] != ':' &&
			    request[len] != '\r' && request[len] != '\n'; len++)
			;
		    if (len < num_chars && request[len] == ':')
		    {
			write_string_n(&serv->writebuf.buffer[free_start],
				&packet_length, request, len);
			for (len++; len < num_chars && isspace(request[len]);
				len++)
			    ;
			num_chars -= len;
			request += len;
			for (len = 0; len < num_chars && request[len] != '\r' &&
				request[len] != '\n'; len++)
			    ;
			write_string_n(&serv->writebuf.buffer[free_start],
				&packet_length, request, len);
		    }
		    if (request[len] == '\r')
			len++;
		    if (request[len] == '\n')
			len++;
		    num_chars -= len;
		    request += len;
		}
	    }
	}
    }
    /* set first 4 bytes of packet to the total packet length */
    write_long(&serv->writebuf.buffer[free_start], NULL,
	    packet_length, 1);
    /* add the packet to the output buffer properly */
    if (free_end - free_start < packet_length)
	fatal(serv, "request packet overflowed the buffer\n");
    add_data(serv, serv->control_fd, NULL, free_start, packet_length,
	    fs_output);
    return 1;
}
Exemple #29
0
int make_backend_error_packet(Server *serv, int fd, u32 ip, u16 nbo_port)
{
    struct sockaddr_in local_name;
    struct sockaddr_in remote_name;
    int local_namelen;
    int remote_namelen;
    int packet_length;
    int free_start, free_end;

    local_namelen = sizeof(struct sockaddr_in);
    if (getsockname(fd, (struct sockaddr *) &local_name, &local_namelen) < 0)
    {
	syslog(LOG_INFO, "make_backend_error_packet: failed to get sock "
		"name: %m\n");
	return 0;
    }
    /* locate the free end of the buffer (possibly appending to previous
     * control packets) */
    append_data(serv, serv->control_fd, &free_start, &free_end, fs_output);
    packet_length = PAK_COM_OFF;
    /* write control code */
    serv->writebuf.buffer[free_start + packet_length++] = PAK_BE_ERROR;
    /* write unique id */
    write_long(&serv->writebuf.buffer[free_start], &packet_length,
	    (getpid() & 0xffff) | (fd << 16), 1);
    /* add local IP field to packet */
    write_long(&serv->writebuf.buffer[free_start], &packet_length,
	    local_name.sin_addr.s_addr, 0);
    /* add local port field to packet */
    write_short(&serv->writebuf.buffer[free_start], &packet_length,
	    serv->port, 1);
    if (serv->fd_partner[fd] == -1)
    {
	/* the connection failed straight away, so we've still got the ip
	 * and port (already in network byte order) to use */
	write_long(&serv->writebuf.buffer[free_start], &packet_length, ip, 0);
	write_short(&serv->writebuf.buffer[free_start], &packet_length,
		nbo_port, 0);
    }
    else
    {
	/* else the partner (which is the failed backend fd) has the ip and
	 * port stored in serv->fd_connection_* */
	write_long(&serv->writebuf.buffer[free_start], &packet_length,
		serv->fd_connection_ip[serv->fd_partner[fd]], 0);
	write_short(&serv->writebuf.buffer[free_start], &packet_length,
		serv->fd_connection_port[serv->fd_partner[fd]], 1);
    }
    /* add client IP field to packet */
    remote_namelen = sizeof(struct sockaddr_in);
    if (getpeername(fd,  (struct sockaddr *) &remote_name,
	    &remote_namelen) == -1)
    {
	syslog(LOG_INFO, "make_backend_error_packet: failed to getpeer "
		"name: %m\n");
	return 0;
    }
    write_long(&serv->writebuf.buffer[free_start], &packet_length,
	    remote_name.sin_addr.s_addr, 0);
    /* write length */
    write_long(&serv->writebuf.buffer[free_start], NULL, packet_length, 1);
    /* add the packet to the output buffer properly */
    if (free_end - free_start < packet_length)
	fatal(serv, "unable to fit backend_error packet in static buffer\n");
    add_data(serv, serv->control_fd, NULL, free_start, packet_length,
	    fs_output);
    return 1;
}
Exemple #30
0
static void lstore(void)
{
	const u32 *aaddr = (u32 *)cell2pointer(POP());
	const u32 longval = POP();
	write_long(aaddr, longval);
}