Beispiel #1
0
//=============================================================================
bool ConfigStream::write_object(const ScriptRef* ref, int indent)
{
  if (ref == 0) {
    write("NULL");
    return true;
  }
  const ScriptMethodRef* mref = dynamic_cast<const ScriptMethodRef*>(ref);

  const ScriptObject* object = ref->object();
  const std::type_info& ti = typeid(*object);
  
  write("(" + type_name(ti) + (mref ? " method":"") + ") ");

  if (typeid(ScriptList) == ti) {
    const ScriptList* l = dynamic_cast<const ScriptList*>(object);
    write("[\n");
    int max = l->size();
    for (int i=0; i<max; ++i) {
      WRITE_INDENT(indent+1);
      write_object(l->get(i),indent+1);
      if (i != max-1) write(",");
      write("\n");
    }
    WRITE_INDENT(indent);
    write("]");

  } else if (typeid(ScriptMap) == ti) {
    const ScriptMap* m = dynamic_cast<const ScriptMap*>(object);
    write("{\n");
    std::vector<std::string> keys;
    m->keys(keys);
    for (std::vector<std::string>::const_iterator it = keys.begin();
	 it != keys.end();
	 ++it) {
      WRITE_INDENT(indent+1);
      std::string key = *it;
      write("\"" + key + "\": ");
      write_object(m->lookup(key),indent+1);
      if (it != keys.end()-1) write(",");
      write("\n");
    }
    WRITE_INDENT(indent);
    write("}");

  } else {
    write(object->get_string());
  }

  if (mref) {
    write("::" + mref->method());
  }

  if (ref->is_const()) {
    write(" [const]");
  }

  return true;
}
Beispiel #2
0
void JsonValue::write(std::string &json) const
{
	switch (type)
	{
	case Type::null:
		json += "null";
		break;
	case Type::object:
		write_object(json);
		break;
	case Type::array:
		write_array(json);
		break;
	case Type::string:
		write_string(value_string, json);
		break;
	case Type::number:
		write_number(json);
		break;
	case Type::boolean:
		json += value_boolean ? "true" : "false";
		break;
	case Type::undefined:
		break;
	}
}
Beispiel #3
0
int unlock_buffer(char *srvName,char *dirName,char *idBucket,BUCKET_T *buffer){
	char lock_flag;
	BUCKET_T header;
	
	header = *buffer;
	
	state	=	set_server(cluster,srvName,&ioctx);
	if(state < 0){
		fprintf(stderr,"[unlock_buffer/iceph.c] Servidor não localizado!\n");
		return 1;
	}
	
	//seta o diretorio
	state	=	set_directory(dirName,&ioctx);
	if(state >= 0){
		lock_flag = '0';
		//altera o valor do flag no sa
		state = write_object(ioctx,idBucket,&lock_flag,LOCK_FLAG_SIZE,0,0);
		if(state >= 0){
			//altera no buffer
			*(header+LCKFLAG_OFFSET) = lock_flag;
			//altera o parametro locked no buffer_pool
			state = set_locked(idBucket,srvName,lock_flag);
		}else
			return 1; //retorna 1 pois nao conseguiu escrever no buffer
	}else{
		fprintf(stderr,"[unlock_buffer/iceph.c] Diretório não localizado!\n");
		return 1;
	}		

	return 0; 
}
Beispiel #4
0
pfs::error_code ubjson_ostream<OStreamType, JsonType>::write_json (json_type const & j, bool with_prefix)
{
    switch (j.type()) {
    case data_type::null:
        _os << UBJSON_CHAR_NULL;
        break;

    case data_type::boolean:
        _os << (j.boolean_data()
                ? UBJSON_CHAR_TRUE
                : UBJSON_CHAR_FALSE);
        break;

    case data_type::integer:
        return write_integer(j.integer_data(), with_prefix);

    case data_type::real:
        return write_real(j.real_data(), with_prefix);

    case data_type::string:
        return write_string(j.string_data(), with_prefix);

    case data_type::array:
        return write_array(j);

    case data_type::object:
        return write_object(j);
    }

    return pfs::error_code();
}
bool write_file(size_t object_size, bool sized) {
    char filename[64];
    benchmark_filename(filename, sizeof(filename), object_size, BENCHMARK_FORMAT_UBJSON, sized ? NULL : "-unopt");

    FILE* file = fopen(filename, "wb");
    if (!file) {
        fprintf(stderr, "error opening file for writing!\n");
        return false;
    }

    // ubjw_open_file() doesn't register any error handler, and
    // does not check the return value of calls to fwrite() either.
    // it doesn't seem to have any way of handling i/o errors at all,
    // such as disk full errors or broken pipes. this seems like
    // a serious flaw; there's no way to tell if the data was
    // truncated.
    ubjw_context_t* dst = ubjw_open_file(file);

    object_t* object = benchmark_object_create(object_size);
    bool ok = write_object(dst, object, sized);
    object_destroy(object);

    ubjw_close_context(dst);
    return ok;
}
Beispiel #6
0
int write_creature(FILE *fp, int num, creature *crt)
{
	int	cnt;
	char perm_only;
	otag	*op;
	
	perm_only = 0;

	
	fprintf(fp, "#begcrt\n");
/* basic creature format (excluding pointers) */
	write_creature_basic(fp, num, crt);
	fprintf(fp, "#endcrt\n");
	
/* objects carried by creature */
	cnt = count_inv(crt, perm_only);
	write_int(fp, cnt);
	
	if(cnt > 0) {
		op = crt->first_obj;
		while(op) {
			if(!perm_only || (perm_only && op->obj->flags[0] & 1))
				write_object(fp, -1, op->obj);
			op = op->next_tag;
		}
	}
	
/* end of complete creature */ 

	return(0);

}
Beispiel #7
0
int write_object(FILE *fp, int num, object *obj)
{
	int	cnt;
	char perm_only;
	otag	*op;
	
	perm_only = 0;

	fprintf(fp, "#begobj\n");
	
/* basic object format (excluding pointers) */
	write_object_basic(fp, num, obj);
	
	fprintf(fp, "#endobj\n");

/* objects carried within objects */
	cnt = count_obj(obj, perm_only);
	write_int(fp, cnt);
	
	if(cnt > 0) {
		op = obj->first_obj;
		while(op) {
			if(!perm_only || (perm_only && op->obj->flags[0] & 1))
				write_object(fp, -1, op->obj);
			op = op->next_tag;
		}
	}
	
/* end of complete object */ 

	return(0);
}
bool setup_test(size_t object_size) {
    object_t* object = benchmark_object_create(object_size);
    binn root;
    bool ok;
    if (object->type == type_map) {
        binn_create_object(&root);
        ok = write_object(&root, object);
    } else {
        binn_create_list(&root);
        ok = write_list(&root, object);
    }
    object_destroy(object);

    if (!ok) {
        fprintf(stderr, "binn error writing data!\n");
        binn_free(&root);
        return false;
    }

    char filename[64];
    benchmark_filename(filename, sizeof(filename), object_size, BENCHMARK_FORMAT_BINN, NULL);
    FILE* file = fopen(filename, "wb");
    fwrite(binn_ptr(&root), binn_size(&root), 1, file);
    fclose(file);

    // like libbson, we call binn_free() regardless of whether
    // we placed it on the stack or the heap; it stores a flag
    // to say whether it should be freed. this apparently doesn't
    // cause warnings since GCC chooses not to inline binn_free().
    binn_free(&root);
    return true;
}
static int
write_db_file(const char *reason)
{
    Objid oid;
    Objid max_oid = db_last_used_objid();
    Verbdef *v;
    Var user_list;
    int i;
    volatile int nprogs = 0;
    volatile int success = 1;

    for (oid = 0; oid <= max_oid; oid++) {
        if (valid(oid))
            for (v = dbpriv_find_object(oid)->verbdefs; v; v = v->next)
                if (v->program)
                    nprogs++;
    }

    user_list = db_all_users();

    TRY {
        dbio_printf(header_format_string, current_db_version);
        dbio_printf("%d\n%d\n%d\n%d\n",
        max_oid + 1, nprogs, 0, user_list.v.list[0].v.num);
        for (i = 1; i <= user_list.v.list[0].v.num; i++)
            dbio_write_objid(user_list.v.list[i].v.obj);
        oklog("%s: Writing %d objects...\n", reason, max_oid + 1);
        for (oid = 0; oid <= max_oid; oid++) {
            write_object(oid);
            if (oid == max_oid || log_report_progress())
                oklog("%s: Done writing %d objects...\n", reason, oid + 1);
        }
        oklog("%s: Writing %d MOO verb programs...\n", reason, nprogs);
        for (i = 0, oid = 0; oid <= max_oid; oid++)
            if (valid(oid)) {
                int vcount = 0;

                for (v = dbpriv_find_object(oid)->verbdefs; v; v = v->next) {
                    if (v->program) {
                        dbio_printf("#%d:%d\n", oid, vcount);
                        dbio_write_program(v->program);
                        if (++i == nprogs || log_report_progress())
                            oklog("%s: Done writing %d verb programs...\n",
                            reason, i);
                    }
                    vcount++;
                }
            }
        oklog("%s: Writing forked and suspended tasks...\n", reason);
        write_task_queue();
        oklog("%s: Writing list of formerly active connections...\n", reason);
        write_active_connections();
    }
    EXCEPT(dbpriv_dbio_failed)
    success = 0;
    ENDTRY;

    return success;
}
Beispiel #10
0
/*prototipo: int get_lock(char *srvName,char *dirName,char *idBucket,BUCKET_T *buffer)
 *objetivo: verificar se o servidor que ira executar operacao de escrita adquiriu o lock ou nao*/
int get_lock(char *srvName,char *dirName,char *idBucket,BUCKET_T *buffer){
	
	char lock_flag;
	BUCKET_T header;
	char lock_owner[SRVNAME_SIZE];
	int locked;
	
	lock_flag = ' ';
	locked = 0;
	header = *buffer;
	
	memset(lock_owner,'\0',SRVNAME_SIZE);
	
	/*utilizar check_locked() para verifcar se o servidor ja adquiriu o lock
	  se ele ja tiver adquirido lock, locked vai retornar 1 e lock_owner vai
	  retornar o nome do servidor*/
	state = check_locked(idBucket,srvName,&locked,lock_owner);
	/*somente sera requerido lock se nao houver lock no bufffer
	  se o buffer ja tiver bloqueado pelo proprio servidor que esta pedindo
	  vai retornar 1 permitindo a operacao de escrita*/
	if((state == 1) && (locked == 0) && (strlen(lock_owner) == 0) ){
		// conecta-se ao pool/servidor
		state	=	set_server(cluster,srvName,&ioctx);
		if(state < 0){
			fprintf(stderr,"[get_lock/iceph.c] Servidor não localizado!\n");
			return 1;
		}
	
		//seta o diretorio
		state	=	set_directory(dirName,&ioctx);
		if(state >= 0){
			state = read_object(ioctx,idBucket,&lock_flag,LOCK_FLAG_SIZE,0,0);		
			if(state >= 0){
				if(lock_flag == '0'){
					lock_flag = '1';
					//altera o flag em disco
					state = write_object(ioctx,idBucket,&lock_flag,LOCK_FLAG_SIZE,0,0);
					if(state >= 0){
						//altera no buffer
						*(header+LCKFLAG_OFFSET) = lock_flag;
						//altera o parametro locked no buffer_pool
						state = set_locked(idBucket,srvName,lock_flag);
					}
				}else
				  return 0;
			}else
				return 0; //retorna 0 pois nao conseguir escrever no bucket
		}else{
			fprintf(stderr,"[get_lock/iceph.c] Diretório não localizado!\n");
			return 0;
		}
		header = NULL;
	}else if((state == 1) && (locked == 1))
		return 1; //srvName ja adquiriu o lock neste buffer

	return 1;	 
}
Beispiel #11
0
static void write_data(io::stream& e, bsdata* pd, bool(*comparer)(void* object, const bsreq* type)) {
	if(!pd)
		return;
	for(int index = 0; index < (int)pd->getcount(); index++) {
		auto object = pd->get(index);
		if(comparer && !comparer(object, pd->fields))
			write_object(e, object);
	}
}
Beispiel #12
0
int main(int argc, char *argv[])
{
  char *cases[] = {
    /* "(+. 1.1 1.2)", */
    /* "(integer->float 123)", */
    /* "(& 5 7)", */
    /* "'hello", */
    /* "-", */
    /* "(define a (string->in-port \"abc\"))", */
    /* "(read-string-in-port-char a)", */
    /* "(+i 1 2)", */
    /* "(*i 3 4)", */
    /* "(quotient 10 3)", */
    /* "(remainder 10 3)", */
    /* "(= 1 2)", */
    /* "(> 4 5)", */
    /* "(& 5 7)", */
    /* "(| 5 7)", */
    /* "(~ 5)", */
    /* "(eq? 'hello 'hello)", */
    /* "(eq? 1 1)", */
    /* "(eq? (string->symbol \"hello\") 'hello)", */
    /* "(type-of 'hello)", */
    /* "type-of", */
    /* "#\\a", */
    /* "(type-of #\\a)", */
    /* "(define a #(1 2 3))", */
    /* "#\\汉", */
    /* "(set! a 123)", */
    "(string-ref \"汉字\" 0)",
  };
  init_impl();
  /* printf("Address of `-': %p\n", &primitive_procs[1]); */
  for (int i = 0; i < sizeof(cases) / sizeof(char *); i++) {
    FILE *stream = fmemopen(cases[i], strlen(cases[i]), "r");
    sexp in_port = make_file_in_port(stream);
    /* inc_ref_count(in_port); */
    printf(">> %s\n=> ", cases[i]);
    sexp value = read_object(in_port);
    if (is_eof(value))
      break;
    /* inc_ref_count(input); */
    value = eval_object(value, repl_environment);
    /* if (!is_self_eval(input)) */
    /*   inc_ref_count(value); */
    write_object(value, scm_out_port);
    putchar('\n');
  }
  /* write_object(make_wstring("汉"), scm_out_port); */
  /* trigger_gc(); */
  return 0;
}
Beispiel #13
0
void save_state::save_to_file(thread_info *t_info, 
			      int steady_iter, 
			      void (*write_object)(object_write_buffer *)) {

  observe_jiffies(t_info);
  
  object_write_buffer *buf = new object_write_buffer();
  write_object(buf);
  //save_buffer(thread, steady_iter, buf);

  //checkpoint_info *c_info = new checkpoint_info(t_info, steady_iter, buf);
  //save_manager::push_item(c_info);
}
Beispiel #14
0
static void write_file(char *filename, TERMTYPE *tp)
{
	FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
	if (fp == 0) {
		perror(filename);
		_nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
	}
	DEBUG(1, ("Created %s", filename));

	if (write_object(fp, tp) == ERR) {
		_nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
	}
	fclose(fp);
}
Beispiel #15
0
static size_t
write_json(json_t* json, stream_t* stream)
{
    switch (json_typeof(json)) {
        case JSON_OBJECT:  return write_object(json, stream);
        case JSON_ARRAY:   return write_array(json, stream);
        case JSON_STRING:  return write_string(json, stream);
        case JSON_INTEGER: return write_integer(json, stream);
        case JSON_REAL:    return write_real(json, stream);
        case JSON_TRUE:    return write_true(json, stream);
        case JSON_FALSE:   return write_false(json, stream);
        case JSON_NULL:    return write_null(json, stream);
        default:           return 0;
    }
}
Beispiel #16
0
void write_all_obj()
{
	HFINDFILE	hff;
	char	filename[256];
	object *obj;
	int	num;
	int	index;
	FILE	*fp;

	fp = fopen( object_file, "w");
	if ( fp != NULL ) 
	{

		hff = find_first_file(get_object_path(), filename, 256);
		if ( hff )
		{
			do 
			{
				if ( filename[0] != '.' && toupper(filename[0]) == 'O' && strlen(filename) == 3)
				{
					index = OFILESIZE * atoi(&filename[1]);

					for (num=0; num < OFILESIZE ; num++) 
					{
						if (load_obj_from_file(index + num, &obj ) == 0 )
						{
							write_object(fp, index+num,obj);
							free_obj(obj);
						}
					}

				}
			} while( find_next_file( hff, filename, 256 ));

			close_find_file(hff);
		}

		fclose(fp);
	}

	return;
	
}
Beispiel #17
0
static void
write_file(char *filename, TERMTYPE *tp)
{
    char buffer[MAX_ENTRY_SIZE];
    unsigned limit = sizeof(buffer);
    unsigned offset = 0;

    FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
    if (fp == 0) {
	perror(filename);
	_nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
    }
    DEBUG(1, ("Created %s", filename));

    if (write_object(tp, buffer, &offset, limit) == ERR
	|| fwrite(buffer, sizeof(char), offset, fp) != offset) {
	_nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
    }

    fclose(fp);
}
static bool write_object(binn* parent, object_t* object) {
    for (size_t i = 0; i < object->l; ++i) {
        char* key = CONST_CAST(object->children[i * 2].str);
        object_t* value = object->children + i * 2 + 1;
        switch (value->type) {
            case type_nil:     if (!binn_object_set_null(parent, key))                        return false;  break;
            case type_bool:    if (!binn_object_set_bool(parent, key, (BOOL)value->b))        return false;  break;
            case type_double:  if (!binn_object_set_double(parent, key, value->d))            return false;  break;
            case type_int:     if (!binn_object_set_int64(parent, key, value->i))             return false;  break;
            case type_uint:    if (!binn_object_set_uint64(parent, key, value->u))            return false;  break;
            case type_str:     if (!binn_object_set_str(parent, key, CONST_CAST(value->str))) return false;  break;

            case type_array: {
                binn child;
                binn_create_list(&child);
                bool ok = write_list(&child, value);
                if (ok)
                    ok = binn_object_set_object(parent, key, &child);
                binn_free(&child);
                if (!ok)
                    return false;
            } break;

            case type_map: {
                binn child;
                binn_create_object(&child);
                bool ok = write_object(&child, value);
                if (ok)
                    ok = binn_object_set_object(parent, key, &child);
                binn_free(&child);
                if (!ok)
                    return false;
            } break;

            default:
                return false;
        }
    }
    return true;
}
Beispiel #19
0
static int sqlfs_flush(const char *path, struct fuse_file_info *fi)
{
  int err = 0;
  sqlfs_file_t *fsfile = g_hash_table_lookup(cache.open_table, &(fi->fh));
  if (!fsfile)
    return err;

  if (!err) {
    GError *terr = NULL;
    if (fsfile->flush == TRUE && strlen(fsfile->buffer) > 0) {
      write_object(path, fsfile->buffer, &terr);
      fsfile->flush = FALSE;
    }

    if (terr != NULL)
      err = -EFAULT;

    if (terr != NULL)
      g_error_free(terr);
  }

  return err;
}
Beispiel #20
0
bool persist_all_file(FILE *file, Stack *objects)
{
    int i;
    HashMap *hm = NULL;
    int maxm;
    uint32_t obj_encoded;
    Bucket *b;
    uint32_t ssize;

    if (objects->used)
    {
        hm = persist_collect(objects->nodes[0]);

        if (!hm)
        {
            return false;
        }

        for (i = 1; i < objects->used; i++)
        {
            if (!persist_collect_(objects->nodes[i], hm))
            {
                return false;
            }
        }

        maxm = persist_order_objects(hm);
    }
    else
    {
        maxm = 0; // empty stack is valid too
    }

    fwrite("\007DV\x03", 4, 1, file);
    ssize = htonl(objects->used + 1);
    fwrite(&ssize, 4, 1, file);

    for (i = 0; i < objects->used; i++)
    {
        obj_encoded = htonl((uint32_t)toInt(get_hashmap(hm, objects->nodes[i])));
        fwrite(&obj_encoded, 4, 1, file);
    }

    fwrite("\x12\0\0\0", 4, 1, file);

    V reverse_lookup[maxm];

    if (hm)
    {
        for (i = 0; i < hm->size; i++)
        {
            b = hm->map[i];
            while (b != NULL)
            {
                reverse_lookup[toInt(b->value)] = b->key;
                b = b->next;
            }
        }
    }

    for (i = 0; i < maxm; i++)
    {
        write_object(file, reverse_lookup[i], hm);
    }

    return true;
}
Beispiel #21
0
_nc_write_entry(TERMTYPE *const tp)
{
#if USE_HASHED_DB

    char buffer[MAX_ENTRY_SIZE + 1];
    unsigned limit = sizeof(buffer);
    unsigned offset = 0;

#else /* !USE_HASHED_DB */

    struct stat statbuf;
    char filename[PATH_MAX];
    char linkname[PATH_MAX];
#if USE_SYMLINKS
    char symlinkname[PATH_MAX];
#if !HAVE_LINK
#undef HAVE_LINK
#define HAVE_LINK 1
#endif
#endif /* USE_SYMLINKS */

    static int call_count;
    static time_t start_time;	/* time at start of writes */

#endif /* USE_HASHED_DB */

    char name_list[MAX_TERMINFO_LENGTH];
    char *first_name, *other_names;
    char *ptr;

    assert(strlen(tp->term_names) != 0);
    assert(strlen(tp->term_names) < sizeof(name_list));

    (void) strlcpy(name_list, tp->term_names, sizeof(name_list));
    DEBUG(7, ("Name list = '%s'", name_list));

    first_name = name_list;

    ptr = &name_list[strlen(name_list) - 1];
    other_names = ptr + 1;

    while (ptr > name_list && *ptr != '|')
	ptr--;

    if (ptr != name_list) {
	*ptr = '\0';

	for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
	    continue;

	if (*ptr == '\0')
	    other_names = ptr;
	else {
	    *ptr = '\0';
	    other_names = ptr + 1;
	}
    }

    DEBUG(7, ("First name = '%s'", first_name));
    DEBUG(7, ("Other names = '%s'", other_names));

    _nc_set_type(first_name);

#if USE_HASHED_DB
    if (write_object(tp, buffer + 1, &offset, limit - 1) != ERR) {
	DB *capdb = _nc_db_open(_nc_tic_dir(0), TRUE);
	DBT key, data;

	if (capdb != 0) {
	    buffer[0] = 0;

	    memset(&key, 0, sizeof(key));
	    key.data = tp->term_names;
	    key.size = strlen(tp->term_names);

	    memset(&data, 0, sizeof(data));
	    data.data = buffer;
	    data.size = offset + 1;

	    _nc_db_put(capdb, &key, &data);

	    buffer[0] = 2;

	    key.data = name_list;
	    key.size = strlen(name_list);

	    strlcpy(buffer + 1, tp->term_names, sizeof(buffer) - 1);
	    data.size = strlen(tp->term_names) + 1;

	    _nc_db_put(capdb, &key, &data);

	    while (*other_names != '\0') {
		ptr = other_names++;
		while (*other_names != '|' && *other_names != '\0')
		    other_names++;

		if (*other_names != '\0')
		    *(other_names++) = '\0';

		key.data = ptr;
		key.size = strlen(ptr);

		_nc_db_put(capdb, &key, &data);
	    }
	    _nc_db_close(capdb);
	}
    }
#else /* !USE_HASHED_DB */
    if (call_count++ == 0) {
	start_time = 0;
    }

    if (strlen(first_name) >= sizeof(filename) - 3)
	_nc_warning("terminal name too long.");

    snprintf(filename, sizeof(filename), LEAF_FMT "/%s", first_name[0], first_name);

    /*
     * Has this primary name been written since the first call to
     * write_entry()?  If so, the newer write will step on the older,
     * so warn the user.
     */
    if (start_time > 0 &&
	stat(filename, &statbuf) >= 0
	&& statbuf.st_mtime >= start_time) {
	_nc_warning("name multiply defined.");
    }

    check_writeable(first_name[0]);
    write_file(filename, tp);

    if (start_time == 0) {
	if (stat(filename, &statbuf) < 0
	    || (start_time = statbuf.st_mtime) == 0) {
	    _nc_syserr_abort("error obtaining time from %s/%s",
			     _nc_tic_dir(0), filename);
	}
    }
    while (*other_names != '\0') {
	ptr = other_names++;
	assert(ptr < buffer + sizeof(buffer) - 1);
	while (*other_names != '|' && *other_names != '\0')
	    other_names++;

	if (*other_names != '\0')
	    *(other_names++) = '\0';

	if (strlen(ptr) > sizeof(linkname) - 3) {
	    _nc_warning("terminal alias %s too long.", ptr);
	    continue;
	}
	if (strchr(ptr, '/') != 0) {
	    _nc_warning("cannot link alias %s.", ptr);
	    continue;
	}

	check_writeable(ptr[0]);
	snprintf(linkname, sizeof(linkname), LEAF_FMT "/%s", ptr[0], ptr);

	if (strcmp(filename, linkname) == 0) {
	    _nc_warning("self-synonym ignored");
	} else if (stat(linkname, &statbuf) >= 0 &&
		   statbuf.st_mtime < start_time) {
	    _nc_warning("alias %s multiply defined.", ptr);
	} else if (_nc_access(linkname, W_OK) == 0)
#if HAVE_LINK
	{
	    int code;
#if USE_SYMLINKS
            strlcpy(symlinkname, "../", sizeof(symlinkname));
            strlcat(symlinkname, filename, sizeof(symlinkname));
#endif /* USE_SYMLINKS */
#if HAVE_REMOVE
	    code = remove(linkname);
#else
	    code = unlink(linkname);
#endif
	    if (code != 0 && errno == ENOENT)
		code = 0;
#if USE_SYMLINKS
	    if (symlink(symlinkname, linkname) < 0)
#else
	    if (link(filename, linkname) < 0)
#endif /* USE_SYMLINKS */
	    {
		/*
		 * If there wasn't anything there, and we cannot
		 * link to the target because it is the same as the
		 * target, then the source must be on a filesystem
		 * that uses caseless filenames, such as Win32, etc.
		 */
		if (code == 0 && errno == EEXIST)
		    _nc_warning("can't link %s to %s", filename, linkname);
		else if (code == 0 && (errno == EPERM || errno == ENOENT))
		    write_file(linkname, tp);
		else {
#if MIXEDCASE_FILENAMES
		    _nc_syserr_abort("can't link %s to %s", filename, linkname);
#else
		    _nc_warning("can't link %s to %s (errno=%d)", filename,
				linkname, errno);
#endif
		}
	    } else {
		DEBUG(1, ("Linked %s", linkname));
	    }
	}
#else /* just make copies */
	    write_file(linkname, tp);
#endif /* HAVE_LINK */
    }
#endif /* USE_HASHED_DB */
}
Beispiel #22
0
/* Obj is PTR, except pair and vector */
static void write_general(ScmObj obj, ScmPort *out, ScmWriteContext *ctx)
{
    ScmClass *c = Scm_ClassOf(obj);
    if (c->print) c->print(obj, out, ctx);
    else          write_object(obj, out, ctx);
}
Beispiel #23
0
// -----------------------------------------------------------------------------
// Save game
int save_game_data(PHYSFS_file *SaveFile)
{
	short game_top_fileinfo_version = Gamesave_current_version >= 5 ? 31 : GAME_VERSION;
	int  player_offset=0, object_offset=0, walls_offset=0, doors_offset=0, triggers_offset=0, control_offset=0, matcen_offset=0; //, links_offset;
	int offset_offset=0, end_offset=0;
	int i;

	//===================== SAVE FILE INFO ========================

	PHYSFS_writeSLE16(SaveFile, 0x6705);	// signature
	PHYSFS_writeSLE16(SaveFile, game_top_fileinfo_version);
	PHYSFS_writeSLE32(SaveFile, sizeof(game_fileinfo));
	PHYSFS_write(SaveFile, Current_level_name, 15, 1);
	PHYSFS_writeSLE32(SaveFile, Current_level_num);
	offset_offset = PHYSFS_tell(SaveFile);	// write the offsets later
	PHYSFS_writeSLE32(SaveFile, -1);
	PHYSFS_writeSLE32(SaveFile, sizeof(player));

#define WRITE_HEADER_ENTRY(t, n) do { PHYSFS_writeSLE32(SaveFile, -1); PHYSFS_writeSLE32(SaveFile, n); PHYSFS_writeSLE32(SaveFile, sizeof(t)); } while(0)

	WRITE_HEADER_ENTRY(object, Highest_object_index + 1);
	WRITE_HEADER_ENTRY(wall, Num_walls);
	WRITE_HEADER_ENTRY(active_door, Num_open_doors);
	WRITE_HEADER_ENTRY(trigger, Num_triggers);
	WRITE_HEADER_ENTRY(0, 0);		// links (removed by Parallax)
	WRITE_HEADER_ENTRY(control_center_triggers, 1);
	WRITE_HEADER_ENTRY(matcen_info, Num_robot_centers);

	// Write the mine name
	PHYSFSX_printf(SaveFile, "%s\n", Current_level_name);

	PHYSFS_writeSLE16(SaveFile, N_polygon_models);
	PHYSFS_write(SaveFile, Pof_names, sizeof(*Pof_names), N_polygon_models);

	//==================== SAVE PLAYER INFO ===========================

	player_offset = PHYSFS_tell(SaveFile);
	PHYSFS_write(SaveFile, &Players[Player_num], sizeof(player), 1);	// not endian friendly, but not used either

	//==================== SAVE OBJECT INFO ===========================

	object_offset = PHYSFS_tell(SaveFile);
	//fwrite( &Objects, sizeof(object), game_fileinfo.object_howmany, SaveFile );
	for (i = 0; i <= Highest_object_index; i++)
		write_object(&Objects[i], SaveFile);

	//==================== SAVE WALL INFO =============================

	walls_offset = PHYSFS_tell(SaveFile);
	for (i = 0; i < Num_walls; i++)
		wall_write(&Walls[i], game_top_fileinfo_version, SaveFile);

	//==================== SAVE DOOR INFO =============================

#if 0 // FIXME: okay to leave this out?
	doors_offset = PHYSFS_tell(SaveFile);
	for (i = 0; i < Num_open_doors; i++)
		door_write(&ActiveDoors[i], game_top_fileinfo_version, SaveFile);
#endif

	//==================== SAVE TRIGGER INFO =============================

	triggers_offset = PHYSFS_tell(SaveFile);
	for (i = 0; i < Num_triggers; i++)
		trigger_write(&Triggers[i], game_top_fileinfo_version, SaveFile);

	//================ SAVE CONTROL CENTER TRIGGER INFO ===============

	control_offset = PHYSFS_tell(SaveFile);
	control_center_triggers_write(&ControlCenterTriggers, SaveFile);


	//================ SAVE MATERIALIZATION CENTER TRIGGER INFO ===============

	matcen_offset = PHYSFS_tell(SaveFile);
	for (i = 0; i < Num_robot_centers; i++)
		matcen_info_write(&RobotCenters[i], game_top_fileinfo_version, SaveFile);

	//============= REWRITE FILE INFO, TO SAVE OFFSETS ===============

	end_offset = PHYSFS_tell(SaveFile);

	// Update the offset fields

#define WRITE_OFFSET(o, n) do { PHYSFS_seek(SaveFile, offset_offset); PHYSFS_writeSLE32(SaveFile, o ## _offset); offset_offset += sizeof(int)*n; } while (0)

	WRITE_OFFSET(player, 2);
	WRITE_OFFSET(object, 3);
	WRITE_OFFSET(walls, 3);
	WRITE_OFFSET(doors, 3);
	WRITE_OFFSET(triggers, 6);
	WRITE_OFFSET(control, 3);
	WRITE_OFFSET(matcen, 3);

	// Go back to end of data
	PHYSFS_seek(SaveFile, end_offset);

	return 0;
}
static bool write_object(ubjw_context_t* dst, object_t* object, bool sized) {
    switch (object->type) {
        case type_nil:    ubjw_write_null   (dst);            break;
        case type_bool:   ubjw_write_bool   (dst, object->b); break;
        case type_double: ubjw_write_float64(dst, object->d); break;
        case type_int:    ubjw_write_integer(dst, object->i); break;

        case type_str:
            ubjw_write_string(dst, object->str);
            break;

        case type_uint:
            // UBJSON does not support unsigned 64-bit numbers (unless
            // they are written as high precision big integers, represented
            // by a decimal string.)
            if (object->u > INT64_MAX)
                return false;
            ubjw_write_integer(dst, (int64_t)object->u);
            break;

        case type_array: {
            UBJ_TYPE type = UBJ_MIXED;

            // in order to try to take advantage as much as possible of ubjson's
            // space-saving optimization, we check if each element of the array
            // is the same type. (we need all integers to be the same width to
            // use an int type, otherwise it would be a waste of space.)
            if (sized && object->l >= 2) {
                type = get_ubj_type(&object->children[0]);
                if (type != UBJ_MIXED) {
                    for (size_t i = 1; i < object->l; ++i) {
                        if (get_ubj_type(&object->children[i]) != type) {
                            type = UBJ_MIXED;
                            break;
                        }
                    }
                }
            }

            ubjw_begin_array(dst, type, sized ? object->l : 0);
            for (size_t i = 0; i < object->l; ++i)
                write_object(dst, object->children + i, sized);
            ubjw_end(dst);
        } break;

        case type_map: {
            UBJ_TYPE type = UBJ_MIXED;

            // as above, check if all map values are the same type
            if (sized && object->l >= 2) {
                type = get_ubj_type(&object->children[1]);
                if (type != UBJ_MIXED) {
                    for (size_t i = 1; i < object->l; ++i) {
                        if (get_ubj_type(&object->children[i * 2 + 1]) != type) {
                            type = UBJ_MIXED;
                            break;
                        }
                    }
                }
            }

            ubjw_begin_object(dst, type, sized ? object->l : 0);
            for (size_t i = 0; i < object->l; ++i) {

                // we expect keys to be short strings
                object_t* key = object->children + i * 2;
                assert(key->type == type_str);
                ubjw_write_key(dst, key->str);

                write_object(dst, object->children + i * 2 + 1, sized);
            }
            ubjw_end(dst);
        } break;

        default:
            return false;
    }

    return true;
}
Beispiel #25
0
Datei: vasm.c Projekt: ezrec/vasm
int main(int argc,char **argv)
{
    int i;
    for(i=1; i<argc; i++) {
        if(argv[i][0]=='-'&&argv[i][1]=='F') {
            output_format=argv[i]+2;
            argv[i][0]=0;
        }
        if(!strcmp("-quiet",argv[i])) {
            verbose=0;
            argv[i][0]=0;
        }
    }
    if(!init_output(output_format))
        general_error(16,output_format);
    if(!init_main())
        general_error(10,"main");
    if(verbose)
        printf("%s\n%s\n%s\n%s\n",copyright,cpu_copyright,syntax_copyright,output_copyright);
    for(i=1; i<argc; i++) {
        if(argv[i][0]==0)
            continue;
        if(argv[i][0]!='-') {
            if(inname)
                general_error(11);
            inname=argv[i];
            continue;
        }
        if(!strcmp("-o",argv[i])&&i<argc-1) {
            if(outname)
                general_error(28,'o');
            outname=argv[++i];
            continue;
        }
        if(!strcmp("-L",argv[i])&&i<argc-1) {
            if(listname)
                general_error(28,'L');
            listname=argv[++i];
            produce_listing=1;
            continue;
        }
        if(!strcmp("-Lnf",argv[i])) {
            listformfeed=0;
            continue;
        }
        if(!strcmp("-Lns",argv[i])) {
            listnosyms=1;
            continue;
        }
        if(!strncmp("-Ll",argv[i],3)) {
            sscanf(argv[i]+3,"%i",&listlinesperpage);
            continue;
        }
        if(!strncmp("-D",argv[i],2)) {
            char *def=NULL;
            expr *val;
            if(argv[i][2])
                def=&argv[i][2];
            else if (i<argc-1)
                def=argv[++i];
            if(def) {
                char *s=def;
                if(ISIDSTART(*s)) {
                    s++;
                    while(ISIDCHAR(*s))
                        s++;
                    def=cnvstr(def,s-def);
                    if(*s=='=') {
                        s++;
                        val=parse_expr(&s);
                    }
                    else
                        val=number_expr(1);
                    if(*s)
                        general_error(23,'D');  /* trailing garbage after option */
                    new_abs(def,val);
                    myfree(def);
                    continue;
                }
            }
        }
        if(!strncmp("-I",argv[i],2)) {
            char *path=NULL;
            if(argv[i][2])
                path=&argv[i][2];
            else if (i<argc-1)
                path=argv[++i];
            if(path) {
                new_include_path(path);
                continue;
            }
        }
        if(!strcmp("-unnamed-sections",argv[i])) {
            unnamed_sections=1;
            continue;
        }
        if(!strcmp("-ignore-mult-inc",argv[i])) {
            ignore_multinc=1;
            continue;
        }
        if(!strcmp("-nocase",argv[i])) {
            nocase=1;
            continue;
        }
        if(!strcmp("-noesc",argv[i])) {
            esc_sequences=0;
            continue;
        }
        if(!strcmp("-nosym",argv[i])) {
            no_symbols=1;
            continue;
        }
        if(!strncmp("-nowarn=",argv[i],8)) {
            int wno;
            sscanf(argv[i]+8,"%i",&wno);
            disable_warning(wno);
            continue;
        }
        else if(!strcmp("-w",argv[i])) {
            no_warn=1;
            continue;
        }
        if(!strncmp("-maxerrors=",argv[i],11)) {
            sscanf(argv[i]+11,"%i",&max_errors);
            continue;
        }
        else if(!strcmp("-pic",argv[i])) {
            pic_check=1;
            continue;
        }
        if(cpu_args(argv[i]))
            continue;
        if(syntax_args(argv[i]))
            continue;
        if(output_args(argv[i]))
            continue;
        if (!strncmp("-x",argv[i],2)) {
            auto_import=0;
            continue;
        }
        general_error(14,argv[i]);
    }
    if(inname) {
        setfilename(inname);
        setdebugname(inname);
        include_source(inname);
    } else
        general_error(15);
    if(!init_parse())
        general_error(10,"parse");
    if(!init_syntax())
        general_error(10,"syntax");
    if(!init_cpu())
        general_error(10,"cpu");
    parse();
    if(errors==0||produce_listing)
        resolve();
    if(errors==0||produce_listing)
        assemble();
    if(errors==0&&!auto_import)
        undef_syms();
    if(!listname)
        listname="a.lst";
    if(produce_listing)
        write_listing(listname);
    if(!outname)
        outname="a.out";
    if(errors==0) {
        if(verbose)
            statistics();
        outfile=fopen(outname,"wb");
        if(!outfile)
            general_error(13,outname);
        write_object(outfile,first_section,first_symbol);
    }
    leave();
    return 0; /* not reached */
}
Beispiel #26
0
int
main(
int argc,
char **argv,
char **envp)
{
    int	work_argc;	/* variable copy of argc */
    char **work_argv;	/* variable copy of argv */
    char *arg;		/* an arg to program */
    char a;		/* an arg flag (after -) */
    char *out_file_name;/* name of object file, argument to -o if specified */
    int i;
    struct directory_stack *dirtmp;

	progname = argv[0];

	/*
	 * Set up to catch the signals listed in sig[] that are not ignored.
	 */
	for(i = 0; sig[i] != 0; i++)
	    if(signal(sig[i], SIG_IGN) != SIG_IGN)
		signal(sig[i], got_sig);
	/*
	 * Set the default for the flags that will be parsed.
	 */
	memset(flagseen, '\0', sizeof(flagseen)); /* aint seen nothing yet */
	out_file_name = "a.out";	/* default .o file */

	/* This is the -dynamic flag, which is now the default */
	flagseen[(int)'k'] = TRUE;

	/*
	 * Parse arguments, but we are only interested in flags.
	 * When we find a flag, we process it then make it's argv[] NULL.
	 * This helps any future argv[] scanners avoid what we processed.
	 * Since it is easy to do here we interpret the special arg "-"
	 * to mean "use stdin" and we set that argv[] pointing to "".
	 * After we have munged argv[], the only things left are source file
	 * name(s) and ""(s) denoting stdin. These file names are used
	 * (perhaps more than once) later.
	 */
	work_argc = argc - 1;		/* don't count argv[0] */
	work_argv = argv + 1;		/* skip argv[0] */
	for( ; work_argc-- ; work_argv++){

	    /* work_argv points to this argument */
	    arg = *work_argv;

	    /* Filename. We need it later. */
	    if(*arg != '-')
		continue;

	    if(strcmp(arg, "--gstabs") == 0){
		/* generate stabs for debugging assembly code */
		flagseen[(int)'g'] = TRUE;
		*work_argv = NULL; /* NULL means 'not a file-name' */
		continue;
	    }
	    if(strcmp(arg, "--gdwarf2") == 0){
		as_fatal("%s: I don't understand %s flag!", progname, arg);
	    }

	    /* Keep scanning args looking for flags. */
	    if (arg[1] == '-' && arg[2] == 0) {
		/* "--" as an argument means read STDIN */
		/* on this scan, we don't want to think about filenames */
		*work_argv = "";	/* Code that means 'use stdin'. */
		continue;
	    }

	    /* This better be a switch ( -l where l is a letter. */
	    arg++;		/* -> letter. */

	    /* scan all the 1-char flags */
	    while((a = *arg)){
		arg ++;	/* arg -> after letter. */
		a &= 0x7F;	/* ascii only please */
		if(flagseen[(int)a] && (a != 'I') && (a != 'a') && (a != 'f') &&
		   (a != 'd') && (a != 's') && (a != 'k'))
			as_warn("%s: Flag option -%c has already been seen!",
				progname, a);
		if(a != 'f' && a != 'n')
		    flagseen[(int)a] = TRUE;
		switch(a){
		case 'f':
		    if(strcmp(arg-1, "force_cpusubtype_ALL") == 0){
			force_cpusubtype_ALL = 1;
			arg = "";	/* Finished with this arg. */
			break;
		    }
		    /* -f means fast - no need for "app" preprocessor. */
		    flagseen[(int)a] = TRUE;
		    break;

		case 'L': /* -L means keep L* symbols */
		    break;

		case 'o':
		    if(*arg != '\0') /* Rest of argument is object file-name. */
			out_file_name = arg;
		    else if(work_argc){	/* Want next arg for a file-name. */
			*work_argv = NULL; /* This is not a file-name. */
			work_argc--;
			out_file_name = *++work_argv;
		    }
		    else
			as_warn("%s: I expected a filename after -o. \"%s\" "
				"assumed.", progname, out_file_name);
		    arg = "";	/* Finished with this arg. */
		    break;

		case 'R':
		    /* -R means put data into text segment */
		    as_warn("%s: -R option not supported (use the "
			    ".const directive)", progname);
		    flagseen['R'] = FALSE;
		    break;

		case 'v':
		    fprintf(stderr,"Apple Computer, Inc. version "
			    "%s, ", apple_version);
		    fprintf(stderr, version_string);
		    if(*arg && strcmp(arg,"ersion"))
			as_warn("Unknown -v option ignored");
		    while(*arg)
			arg++;	/* Skip the rest */
		    break;

		case 'W':
		    /* -W means don't warn about things */
		    break;

		case 'I':
		    /* Add directory to path for includes */
		    dirtmp = (struct directory_stack *)
			xmalloc(sizeof(struct directory_stack));
		    /* New one goes on the end */
		    dirtmp->next = 0;
		    if(include == 0)
			include = dirtmp;
		    else
			include_tail->next = dirtmp;
		    /* Tail follows the last one */
		    include_tail = dirtmp;
		    /* Rest of argument is include file-name. */
		    if(*arg)
			dirtmp->fname = arg;
		    else if (work_argc){
			/* Want next arg for a file-name. */
			/* This is not a file-name. */
			*work_argv = NULL;
			work_argc--;
			dirtmp->fname = *++work_argv;
		    }
		    else
			as_warn("I expected a filename after -I.");
		    arg = "";	/* Finished with this arg. */
		    break;

		case 'g':
		    /* generate stabs for debugging assembly code */
		    break;

		case 'n':
#ifdef PPC
		    if(strcmp(arg-1, "no_ppc601") == 0)
			goto unknown_flag;
#endif
		    /* no default .text section */
		    flagseen[(int)a] = TRUE;
		    break;

#ifdef PPC
		case 'p':
		    if(strcmp(arg-1, "ppcasm") == 0)
			goto unknown_flag;
#endif

		case 'd':
		    if(strcmp(arg-1, "dynamic") == 0){
			arg = "";	/* Finished with this arg. */
			flagseen[(int)'k'] = TRUE;
			break;
		    }
		    goto unknown_flag;

		case 's':
		    if(strcmp(arg-1, "static") == 0){
			arg = "";	/* Finished with this arg. */
			flagseen[(int)'k'] = FALSE;
			break;
		    }
		    goto unknown_flag;

		case 'N':
		    if(strcmp(arg-1, "NEXTSTEP-deployment-target") == 0){
			arg = "";	/* Finished with this arg. */
			/* Want next arg for a <release_tag> */
			if(work_argc){
			    /* This, "-NEXTST..." is not a file-name. */
			    *work_argv = NULL;
			    work_argc--;
			    work_argv++;
			    if(strcmp(*work_argv, "3.3") == 0){
				flagseen[(int)'k'] = TRUE;
			    }
			    else if(strcmp(*work_argv, "3.2") == 0){
				flagseen[(int)'k'] = FALSE;
			    }
			    else{
				as_fatal("I expected '3.2' or '3.3' after "
				    "-NEXTSTEP-deployment-target.");
			    }
			}
			else
			    as_fatal("I expected a <release_tag> "
				     "after -NEXTSTEP-deployment-target.");
			break;
		    }
		    goto unknown_flag;

		case 'k':
		    /* use new features incompatible with 3.2 */
		    break;

		case 'V':
		    /* as driver's -V, verbose, flag */
		    break;

		case 'a':
		    if(strcmp(arg-1, "arch_multiple") == 0){
			arch_multiple = 1;
			arg = "";	/* Finished with this arg. */
			break;
		    }
		    else if(strcmp(arg-1, "arch") == 0){
			arg = "";	/* Finished with this arg. */
			/* Want next arg for a <arch_type> */
			if(work_argc){
			    /* This, "-arch" is not a file-name. */
			    *work_argv = NULL;
			    work_argc--;
			    work_argv++;
#ifdef M68K
			    if(strcmp(*work_argv, "m68030") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
				    CPU_SUBTYPE_MC68030_ONLY)
				    as_fatal("can't specify both "
					"-arch m68030 and -arch "
					"m68040");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_MC68030_ONLY;
			    }
			    else if(strcmp(*work_argv,
					    "m68040") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
				    CPU_SUBTYPE_MC68040)
				    as_fatal("can't specify both "
					"-arch m68030 and -arch "
					"m68040");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_MC68040;
			    }
			    else if(strcmp(*work_argv, "m68k") != 0)
				as_fatal("I expected 'm68k', "
				    "'m68030' or 'm68040' after "
				    "-arch for this assembler.");
#endif
#ifdef M88K
			    if(strcmp(*work_argv, "m88k") != 0)
				as_fatal("I expected 'm88k' after "
				       "-arch for this assembler.");
#endif
#if defined(PPC) && !defined(ARCH64)
			    if(strcmp(*work_argv, "ppc601") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_601)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_601;
			    }
			    else if(strcmp(*work_argv,
					   "ppc603") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_603)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_603;
			    }
			    else if(strcmp(*work_argv,
					   "ppc603e") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_603e)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_603e;
			    }
			    else if(strcmp(*work_argv,
					   "ppc603ev") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_603ev)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_603ev;
			    }
			    else if(strcmp(*work_argv,
					   "ppc604") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_604)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_604;
			    }
			    else if(strcmp(*work_argv,
					   "ppc604e") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_604e)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_604e;
			    }
			    else if(strcmp(*work_argv,
					   "ppc750") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_750)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_750;
			    }
			    else if(strcmp(*work_argv,
					   "ppc7400") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_7400)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_7400;
			    }
			    else if(strcmp(*work_argv,
					   "ppc7450") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_7450)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_7450;
			    }
			    else if(strcmp(*work_argv,
					   "ppc970") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_970)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_970;
			    }
			    else if(strcmp(*work_argv, "ppc") != 0 &&
			    	    strcmp(*work_argv, "m98k") != 0)
				as_fatal("I expected 'ppc' after "
				       "-arch for this assembler.");
#endif /* defined(PPC) && !defined(ARCH64) */
#if defined(PPC) && defined(ARCH64)
			    if(strcmp(*work_argv,
					   "ppc970-64") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_POWERPC_970)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_POWERPC_970;
			    }
			    else
#endif
#if defined(PPC) && defined(ARCH64)
			    if(strcmp(*work_argv, "ppc64") != 0)
			      as_fatal("I expected 'ppc64' after "
				       "-arch for this assembler.");
#endif
#ifdef I860
			    if(strcmp(*work_argv, "i860") != 0)
				as_fatal("I expected 'i860' after "
				       "-arch for this assembler.");
#endif
#if defined(I386) && !defined(ARCH64)
			    if(strcmp(*work_argv, "i486") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_486)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_486;
			    }
			    else if(strcmp(*work_argv,
					   "i486SX") == 0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_486SX)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_486SX;
			    }
			    else if(strcmp(*work_argv, "i586") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_586)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_586;
			    }
			    else if(strcmp(*work_argv, "pentium") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_PENT)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_PENT;
			    }
			    else if(strcmp(*work_argv, "pentpro") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_PENTPRO)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_PENTPRO;
			    }
			    else if(strcmp(*work_argv, "i686") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_PENTPRO)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_PENTPRO;
			    }
			    else if(strcmp(*work_argv, "pentIIm3") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_PENTII_M3)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_PENTII_M3;
			    }
			    else if(strcmp(*work_argv, "pentIIm5") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_PENTII_M5)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_PENTII_M5;
			    }
			    else if(strcmp(*work_argv, "pentium4") ==0){
				if(archflag_cpusubtype != -1 &&
				   archflag_cpusubtype !=
					CPU_SUBTYPE_PENTIUM_4)
				    as_fatal("can't specify more "
				       "than one -arch flag ");
				specific_archflag = *work_argv;
				archflag_cpusubtype =
				    CPU_SUBTYPE_PENTIUM_4;
			    }
			    else if(strcmp(*work_argv, "i386") != 0)
				as_fatal("I expected 'i386', 'i486', 'i486SX', "
				   "'i586', 'pentium', 'i686', 'pentpro', "
				   "'pentIIm3', or 'pentIIm5' after -arch "
				   "for this assembler.");
#endif
#if defined(I386) && defined(ARCH64)
			    if(strcmp(*work_argv, "x86_64") != 0)
			      as_fatal("I expected 'x86_64' after "
				       "-arch for this assembler.");
#endif
#ifdef HPPA
			    if(strcmp(*work_argv, "hppa") != 0)
				as_fatal("I expected 'hppa' after "
					 "-arch for this assembler.");
#endif
#ifdef SPARC
			    if(strcmp(*work_argv, "sparc") != 0)
				as_fatal("I expected 'sparc' after "
					 "-arch for this assembler.");
#endif
			}
			else
			    as_fatal("I expected an <arch_type> "
				     "after -arch.");
			break;
		    }
		    /* fall through for non -arch flag */
		default:
unknown_flag:
		    --arg;
		    if(md_parse_option(&arg, &work_argc, &work_argv) == 0)
			as_warn("%s: I don't understand '%c' flag!", progname,
				a);
		    if(arg && *arg)
			arg++;
		    break;
		}
	    }
	    /*
	     * We have just processed a "-..." arg, which was not a
	     * file-name. Smash it so the
	     * things that look for filenames won't ever see it.
	     *
	     * Whatever work_argv points to, it has already been used
	     * as part of a flag, so DON'T re-use it as a filename.
	     */
	    *work_argv = NULL; /* NULL means 'not a file-name' */
	}
	if(flagseen['g'] == TRUE && flagseen['n'] == TRUE)
	    as_fatal("-g can't be specified if -n is specified");
	/*
	 * If we haven't seen a -force_cpusubtype_ALL or an -arch flag for a
	 * specific architecture then let the machine instructions in the
	 * assembly determine the cpusubtype of the output file.
	 */
	if(force_cpusubtype_ALL_for_cputype(md_cputype) == TRUE)
	    force_cpusubtype_ALL = TRUE;
	if(force_cpusubtype_ALL && specific_archflag)
	    archflag_cpusubtype = -1;

	/*
	 * Test to see if the AS_SECURE_LOG_FILE environment
	 * variable is set and save the value.
	 */
	secure_log_file = getenv("AS_SECURE_LOG_FILE");

	/*
	 * Call the initialization routines.
	 */
#ifdef OLD_PROJECTBUILDER_INTERFACE
	check_for_ProjectBuilder();	/* messages.c */
#endif /* OLD_PROJECTBUILDER_INTERFACE */
	symbol_begin();			/* symbols.c */
	sections_begin();		/* sections.c */
	read_begin();			/* read.c */
#ifdef PPC
	if(flagseen[(int)'p'] == TRUE)
	    ppcasm_read_begin();	/* read.c */
#endif /* PPC */
	md_begin();			/* MACHINE.c */
	input_scrub_begin();		/* input_scrub.c */

	/* Here with flags set up in flagseen[]. */
	perform_an_assembly_pass(argc, argv); /* Assemble it. */

	if(seen_at_least_1_file() && bad_error != TRUE){
	    layout_addresses();
	    write_object(out_file_name);
	}

	input_scrub_end();
	md_end();			/* MACHINE.c */

	return(bad_error);		/* WIN */
}
Beispiel #27
0
void stream_writer::write_string(const char * p_string,t_size p_len,abort_callback & p_abort) {
	t_uint32 len = pfc::downcast_guarded<t_uint32>(pfc::strlen_max(p_string,p_len));
	write_lendian_t(len,p_abort);
	write_object(p_string,len,p_abort);
}
Beispiel #28
0
void stream_writer::write_string_raw(const char * p_string,abort_callback & p_abort) {
	write_object(p_string,strlen(p_string),p_abort);
}
Beispiel #29
0
static void serialize_value(lua_State *L, int pos, luaL_Buffer* frame, int* indice, uint16_t* key) {
    if (!lua_checkstack(L, 2)) {
        luaL_error(L, "cannot serialize: stack won't grow");
    }
    uint8_t type = get_luatobin_type(L, pos);
    switch (type) {
    case BIN_NIL: {
        //printf("(nil[1])");
        lua_pushlstring(L, (char *) &type, 1);
        write_object(L, indice);
        break;
    }

    case BIN_BOOLEAN: {
        //printf("(boolean[2])");
        int boolean = lua_toboolean(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        luaL_addchar(frame, boolean & 0xFF);
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_DOUBLE: {
        double number = lua_tonumber(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        //printf("(number[%d])", sizeof(number));
        if (sendian.double_) hton(&number, sizeof(number), sendian.double_);
        luaL_addlstring(frame, (char*) &number, sizeof(number));
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_INTEGER: {
        int32_t number = lua_tointeger(L, pos);
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        //printf("(number[%d])", sizeof(number));
        if (sendian.int32_) hton(&number, sizeof(number), sendian.int32_);
        luaL_addlstring(frame, (char*) &number, sizeof(number));
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_STRING: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(stringref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        size_t s;
        const char* string = lua_tolstring(L, pos, &s);
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: string length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        //printf("(string[%d][%d])", *key, size);
        luaL_addlstring(frame, string, size);
        luaL_pushresult(frame);
        write_object(L, indice);
        break;
    }

    case BIN_FUNCTION: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(functionref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        serialize_function(L, frame, pos);
        size_t s;
        const char* string = lua_tolstring(L, -1, &s);
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: function length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        //printf("(function[%d][%d])", *key, size);
        luaL_addlstring(frame, string, size);
        luaL_pushresult(frame);
        write_object(L, indice);
        lua_pop(L, 1); // remove the serialized function
        break;
    }

    case BIN_TABLE: {
        uint16_t cached = verify_cache(L, pos, key);
        if (cached != 0) {
            //printf("(tableref[%d])", cached);
            luaL_buffinit(L, frame);
            luaL_addchar(frame, BIN_REF);
            if (sendian.int16_) hton(&cached, sizeof(cached), sendian.int16_);
            luaL_addlstring(frame, (char*) &cached, sizeof(cached));
            luaL_pushresult(frame);
            write_object(L, indice);
            break;
        }
        // reserved for table header (as size cannot be calculated beforehand)
        *indice = *indice + 1;
        int header = *indice;
        //printf("{table=");
        int top;
        size_t s = 0;
        lua_pushnil(L);
        while (lua_next(L, pos) != 0) {
            top = lua_gettop(L);
            serialize_value(L, top - 1, frame, indice, key);
            serialize_value(L, top, frame, indice, key);
            lua_pop(L, 1);
            s++;
        }
        if (s >= 0xFFFF)
            luaL_error(L, "cannot serialize: table length > 65k");
        uint16_t size = (uint16_t) s;
        luaL_buffinit(L, frame);
        luaL_addchar(frame, type);
        uint16_t nsize = size;
        if (sendian.int16_) hton(&nsize, sizeof(nsize), sendian.int16_);
        luaL_addlstring(frame, (char*) &nsize, sizeof(nsize));
        luaL_pushresult(frame);
        // set table header
        lua_rawseti(L, 3, header);
        //printf("[%d]}", size);
        break;
    }

    default:
        luaL_error(L, "cannot serialize: unsupported type (%d)", lua_type(L, pos));
    }
}
Beispiel #30
0
bool persist(char *fname, V obj)
{
    int i;
    HashMap *hm;
    int maxm;
    FILE *file;
    uint32_t obj_encoded;
    Bucket *b, *bb;

    hm = persist_collect(obj);
    if (hm)
    {
        maxm = persist_order_objects(hm);
        file = fopen(fname, "w");
        fwrite("\007DV\x03\0\0\0\x02", 8, 1, file);
        obj_encoded = htonl((uint32_t)toInt(get_hashmap(hm, obj)));
        fwrite(&obj_encoded, 4, 1, file);

        fwrite("\x12\0\0\0", 4, 1, file);

        V reverse_lookup[maxm];

        for (i = 0; i < hm->size; i++)
        {
            b = hm->map[i];
            while (b != NULL)
            {
                reverse_lookup[toInt(b->value)] = b->key;
                b = b->next;
            }
        }

        for (i = 0; i < maxm; i++)
        {
            write_object(file, reverse_lookup[i], hm);
        }

        fclose(file);

        if (hm->map != NULL)
        {
            for (i = 0; i < hm->size; i++)
            {
                b = hm->map[i];
                while(b != NULL)
                {
                    bb = b;
                    b = b->next;
                    free(bb);
                }
            }
            free(hm->map);
        }
        free(hm);

        return true;
    }
    else
    {
        return false;
    }
}