示例#1
0
devcfg *
devcfg_new()
{
	devcfg *inf = (devcfg*)alloc_init(sizeof(devcfg));
	if (!inf)
		return NULL;

	inf->mp_deviceInfo = (DevInfo *)alloc_init(sizeof(DevInfo));

	if (!inf->mp_deviceInfo) {
		TUTRACE((TUTRACE_INFO, "Info::Info: Could not create deviceInfo\n"));
		free(inf);
		return NULL;
	}

	/* Initialize other member variables */
	memset(inf->mp_deviceInfo, 0, sizeof(DevInfo));
	inf->mp_deviceInfo->assocState = WPS_ASSOC_NOT_ASSOCIATED;
	inf->mp_deviceInfo->configError = 0; /* No error */
	inf->mp_deviceInfo->devPwdId = WPS_DEVICEPWDID_DEFAULT;
	inf->mb_infoConfigSet = false;
	inf->mb_useUsbKey = false;
	inf->mb_regWireless = false;
	inf->mb_useUpnp = false;
	inf->mb_nwKeySet = false;
	inf->m_nwKeyLen = 0;
	inf->mp_dhKeyPair = NULL;
	inf->mcp_devPwd = NULL;
	memset(inf->m_pubKey, 0, SIZE_PUB_KEY);
	memset(inf->m_sha256Hash, 0, SIZE_256_BITS);

	return inf;
}
示例#2
0
/** create context functionality, but no pipes */
static struct ub_ctx* ub_ctx_create_nopipe(void)
{
	struct ub_ctx* ctx;
	unsigned int seed;
#ifdef USE_WINSOCK
	int r;
	WSADATA wsa_data;
#endif
	
	log_init(NULL, 0, NULL); /* logs to stderr */
	log_ident_set("libunbound");
#ifdef USE_WINSOCK
	if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
		log_err("could not init winsock. WSAStartup: %s",
			wsa_strerror(r));
		return NULL;
	}
#endif
	verbosity = 0; /* errors only */
	checklock_start();
	ctx = (struct ub_ctx*)calloc(1, sizeof(*ctx));
	if(!ctx) {
		errno = ENOMEM;
		return NULL;
	}
	alloc_init(&ctx->superalloc, NULL, 0);
	seed = (unsigned int)time(NULL) ^ (unsigned int)getpid();
	if(!(ctx->seed_rnd = ub_initstate(seed, NULL))) {
		seed = 0;
		ub_randfree(ctx->seed_rnd);
		free(ctx);
		errno = ENOMEM;
		return NULL;
	}
	seed = 0;
	lock_basic_init(&ctx->qqpipe_lock);
	lock_basic_init(&ctx->rrpipe_lock);
	lock_basic_init(&ctx->cfglock);
	ctx->env = (struct module_env*)calloc(1, sizeof(*ctx->env));
	if(!ctx->env) {
		ub_randfree(ctx->seed_rnd);
		free(ctx);
		errno = ENOMEM;
		return NULL;
	}
	ctx->env->cfg = config_create_forlib();
	if(!ctx->env->cfg) {
		free(ctx->env);
		ub_randfree(ctx->seed_rnd);
		free(ctx);
		errno = ENOMEM;
		return NULL;
	}
	ctx->env->alloc = &ctx->superalloc;
	ctx->env->worker = NULL;
	ctx->env->need_to_validate = 0;
	modstack_init(&ctx->mods);
	rbtree_init(&ctx->queries, &context_query_cmp);
	return ctx;
}
/** verify DS matches DNSKEY from a file */
static void
dstest_file(const char* fname)
{
	/* 
	 * The file contains a list of ldns-testpkts entries.
	 * The first entry must be a query for DNSKEY.
	 * The answer rrset is the keyset that will be used for verification
	 */
	struct regional* region = regional_create();
	struct alloc_cache alloc;
	ldns_buffer* buf = ldns_buffer_new(65535);
	struct entry* e;
	struct entry* list = read_datafile(fname);
	struct module_env env;

	if(!list)
		fatal_exit("could not read %s: %s", fname, strerror(errno));
	alloc_init(&alloc, NULL, 1);
	memset(&env, 0, sizeof(env));
	env.scratch = region;
	env.scratch_buffer = buf;
	unit_assert(region && buf);

	/* ready to go! */
	for(e = list; e; e = e->next) {
		dstest_entry(e, &alloc, region, buf, &env);
	}

	delete_entry(list);
	regional_destroy(region);
	alloc_clear(&alloc);
	ldns_buffer_free(buf);
}
示例#4
0
struct alloc_cache* 
context_obtain_alloc(struct ub_ctx* ctx, int locking)
{
	struct alloc_cache* a;
	int tnum = 0;
	if(locking) {
		lock_basic_lock(&ctx->cfglock);
	}
	a = ctx->alloc_list;
	if(a)
		ctx->alloc_list = a->super; /* snip off list */
	else	tnum = ctx->thr_next_num++;
	if(locking) {
		lock_basic_unlock(&ctx->cfglock);
	}
	if(a) {
		a->super = &ctx->superalloc;
		return a;
	}
	a = (struct alloc_cache*)calloc(1, sizeof(*a));
	if(!a)
		return NULL;
	alloc_init(a, &ctx->superalloc, tnum);
	return a;
}
示例#5
0
void *
calloc(size_t num, size_t size) noexcept {
    alloc_init();
    void *ptr = default_calloc(num, size);
    alloc_call_count++;
    total_bytes_allocated += size;
    return ptr;
}
示例#6
0
void msgparse_test(void)
{
	sldns_buffer* pkt = sldns_buffer_new(65553);
	sldns_buffer* out = sldns_buffer_new(65553);
	struct alloc_cache super_a, alloc;
	/* init */
	alloc_init(&super_a, NULL, 0);
	alloc_init(&alloc, &super_a, 2);

	unit_show_feature("message parse");
	simpletest(pkt, &alloc, out);
	/* plain hex dumps, like pcat */
	testfromfile(pkt, &alloc, out, "testdata/test_packets.1");
	testfromfile(pkt, &alloc, out, "testdata/test_packets.2");
	testfromfile(pkt, &alloc, out, "testdata/test_packets.3");
	/* like from drill -w - */
	testfromdrillfile(pkt, &alloc, out, "testdata/test_packets.4");
	testfromdrillfile(pkt, &alloc, out, "testdata/test_packets.5");

	matches_nolocation = 1; /* RR order not important for the next test */
	testfromdrillfile(pkt, &alloc, out, "testdata/test_packets.6");
	check_rrsigs = 1;
	testfromdrillfile(pkt, &alloc, out, "testdata/test_packets.7");
	check_rrsigs = 0;
	matches_nolocation = 0; 

	check_formerr_gone = 1;
	testfromdrillfile(pkt, &alloc, out, "testdata/test_packets.8");
	check_formerr_gone = 0;

	check_rrsigs = 1;
	check_nosameness = 1;
	testfromdrillfile(pkt, &alloc, out, "testdata/test_packets.9");
	check_nosameness = 0;
	check_rrsigs = 0;

	/* cleanup */
	alloc_clear(&alloc);
	alloc_clear(&super_a);
	sldns_buffer_free(pkt);
	sldns_buffer_free(out);
}
示例#7
0
main()
{
 alloc_init();
 int i;
 
 for (i=0;i<100;i++) alloc_page(1);
 
 free_page(50);
 
 alloc_page(1);
}
示例#8
0
void *
wps_init(void *bcmwps, DevInfo *ap_devinfo)
{
	WPSAPI_T *gp_mc;
	DevInfo *dev_info;

	gp_mc = (WPSAPI_T *)alloc_init(sizeof(*gp_mc));
	if (!gp_mc) {
		TUTRACE((TUTRACE_INFO, "wps_init::malloc failed!\n"));
		return 0;
	}

	gp_mc->dev_info = devinfo_new();
	if (gp_mc->dev_info == NULL)
		goto error;

	/* copy user provided DevInfo to mp_deviceInfo */
	dev_info = gp_mc->dev_info;
	memcpy(dev_info, ap_devinfo, sizeof(DevInfo));

	/* copy prebuild enrollee noce and private key */
	if (dev_info->flags & DEVINFO_FLAG_PRE_PRIV_KEY) {
		if (reg_proto_generate_prebuild_dhkeypair(
			&dev_info->DHSecret, dev_info->pre_privkey) != WPS_SUCCESS) {
			TUTRACE((TUTRACE_ERR, "wps_init::prebuild_dhkeypair failed!\n"));
			goto error;
		}
	}
	else {
		if (reg_proto_generate_dhkeypair(&dev_info->DHSecret) != WPS_SUCCESS) {
			TUTRACE((TUTRACE_ERR, "wps_init::gen dhkeypair failed!\n"));
			goto error;
		}
	}

	gp_mc->mb_initialized = true;
	TUTRACE((TUTRACE_INFO, "wps_init::Done!\n"));

	/* Everything's initialized ok */
	gp_mc->bcmwps = bcmwps;

	return (void *)gp_mc;

error:
	TUTRACE((TUTRACE_ERR, "wps_init::Init failed\n"));
	if (gp_mc) {
		wps_deinit(gp_mc);
	}

	return 0;
}
示例#9
0
static void *qos_create_machine_arm_virt(QTestState *qts)
{
    QVirtMachine *machine = g_new0(QVirtMachine, 1);

    alloc_init(&machine->alloc, 0,
               ARM_VIRT_RAM_ADDR,
               ARM_VIRT_RAM_ADDR + ARM_VIRT_RAM_SIZE,
               ARM_PAGE_SIZE);
    qvirtio_mmio_init_device(&machine->virtio_mmio, qts, VIRTIO_MMIO_BASE_ADDR,
                             VIRTIO_MMIO_SIZE);

    machine->obj.get_device = virt_get_device;
    machine->obj.get_driver = virt_get_driver;
    machine->obj.destructor = virt_destructor;
    return machine;
}
示例#10
0
static void *qos_create_machine_arm_sabrelite(QTestState *qts)
{
    QSabreliteMachine *machine = g_new0(QSabreliteMachine, 1);

    alloc_init(&machine->alloc, 0,
               SABRELITE_RAM_START,
               SABRELITE_RAM_END,
               ARM_PAGE_SIZE);
    machine->obj.get_device = sabrelite_get_device;
    machine->obj.get_driver = sabrelite_get_driver;
    machine->obj.destructor = sabrelite_destructor;
    qos_init_sdhci_mm(&machine->sdhci, qts, 0x02190000, &(QSDHCIProperties) {
        .version = 3,
        .baseclock = 0,
        .capab.sdma = true,
        .capab.reg = 0x057834b4,
    });
示例#11
0
void *my_malloc( WP_U32 size )
{
   WP_U32 fsize;
   WPL_mem_unit *p;

   if( malloc_num_of_calls == 0 && (WP_U32)msys.free == WPL_UNINITIALIZED && (WP_U32)msys.heap == WPL_UNINITIALIZED )
   {
      WP_U32 hp_start = heapStart();
      WP_U32 sp_start = spStart();
      alloc_init( (void*)hp_start, sp_start - hp_start );
   }

   if( size == 0 ) return 0;

   size += 3 + sizeof(WPL_mem_unit);
   size >>= 2;
   size <<= 2;

   if( msys.free == 0 || size > msys.free->size )
   {
      msys.free = compact( msys.heap, size );
      if( msys.free == 0 ) return 0;
   }

   p = msys.free;
   fsize = msys.free->size;

   if( fsize >= size + sizeof(WPL_mem_unit) )
   {
      msys.free = (WPL_mem_unit *)( (WP_U32)p + size );
      msys.free->size = fsize - size;
   }
   else
   {
      msys.free = 0;
      size = fsize;
   }

   p->size = size | WPL_USED;

   if( !(++malloc_num_of_calls % 15) )
   alloc_compact();

   return (void *)( (WP_U32)p + sizeof(WPL_mem_unit) );
}
示例#12
0
/* Functions for devinfo */
DevInfo *
devinfo_new()
{
	DevInfo *dev_info;

	dev_info = (DevInfo *)alloc_init(sizeof(DevInfo));
	if (!dev_info) {
		TUTRACE((TUTRACE_INFO, "Could not create deviceInfo\n"));
		return NULL;
	}

	/* Initialize other member variables */
	dev_info->assocState = WPS_ASSOC_NOT_ASSOCIATED;
	dev_info->configError = 0; /* No error */
	dev_info->devPwdId = WPS_DEVICEPWDID_DEFAULT;

	return dev_info;
}
示例#13
0
int main(int argc, char *argv[])
{
	void *mem;

	plan_tests(7);

	mem = malloc(1179648);
	alloc_init(mem, 1179648);
	ok1(alloc_check(mem, 1179648));
	ok1(alloc_get(mem, 1179648, 48, 16));
	ok1(alloc_check(mem, 1179648));
	ok1(alloc_get(mem, 1179648, 53, 16));
	ok1(alloc_check(mem, 1179648));
	ok1(alloc_get(mem, 1179648, 53, 16));
	ok1(alloc_check(mem, 1179648));
	free(mem);

	return exit_status();
}
/** verify from a file */
static void
verifytest_file(const char* fname, const char* at_date)
{
	/* 
	 * The file contains a list of ldns-testpkts entries.
	 * The first entry must be a query for DNSKEY.
	 * The answer rrset is the keyset that will be used for verification
	 */
	struct ub_packed_rrset_key* dnskey;
	struct regional* region = regional_create();
	struct alloc_cache alloc;
	ldns_buffer* buf = ldns_buffer_new(65535);
	struct entry* e;
	struct entry* list = read_datafile(fname);
	struct module_env env;
	struct val_env ve;
	uint32_t now = time(NULL);

	if(!list)
		fatal_exit("could not read %s: %s", fname, strerror(errno));
	alloc_init(&alloc, NULL, 1);
	memset(&env, 0, sizeof(env));
	memset(&ve, 0, sizeof(ve));
	env.scratch = region;
	env.scratch_buffer = buf;
	env.now = &now;
	ve.date_override = cfg_convert_timeval(at_date);
	unit_assert(region && buf);
	dnskey = extract_keys(list, &alloc, region, buf);
	if(vsig) log_nametypeclass(VERB_QUERY, "test dnskey",
			dnskey->rk.dname, ntohs(dnskey->rk.type), 
			ntohs(dnskey->rk.rrset_class));
	/* ready to go! */
	for(e = list->next; e; e = e->next) {
		verifytest_entry(e, &alloc, region, buf, dnskey, &env, &ve);
	}

	ub_packed_rrset_parsedelete(dnskey, &alloc);
	delete_entry(list);
	regional_destroy(region);
	alloc_clear(&alloc);
	ldns_buffer_free(buf);
}
示例#15
0
HEADERS *headerentry(HEADERS *chain, HEADER *header)
{
	HEADERS *c;

#if 1
	if (!hdralloc)
		hdralloc = alloc_init(sizeof(HEADERS), 64);
	c = (HEADERS *) alloc_enter(hdralloc);
#else
	c = (HEADERS *)malloc(sizeof(HEADERS));
#endif
	c->header = header;

	if (!chain) chain = c;
	else chain->tail->next = c;
	chain->tail = c;
	c->next = 0;

	return chain;
}
示例#16
0
文件: pkernel.c 项目: hoo2/pkernel
/*!
 * \brief Boot the kernel.
 * - Set priorities
 * - Set clock
 * - Set os frequency,
 * - Start allocator
 * - Create the idle process. Allocator though will
 * not give heap though before pkernel_run().
 *
 * \param __kmsize The pkernels size (aka the idle process stack size).
 * \param clk The CPU clock used by application.
 * \param os_f The OS freq requested by application.
 *
 * \return 0(proc_idle's pid) on success.
 */
int kinit (size_t kmsize, clock_t clk, clock_t os_f)
{
   pid_t pid;

   kSetPriority(kPendSV_IRQn, OS_PENDSV_PRI);
   kSetPriority(kSysTick_IRQn, OS_SYSTICK_PRI);

   set_clock (clk);     // Set kernel's knowledge for clocking and freq
   set_freq (os_f);
   alloc_init ();       // Init the Stack allocation table.

   // Make the idle proc
   pid = proc_newproc ((process_ptr_t)&proc_idle, kmsize, 0, 0);
   /*
    * \note
    * We make sure that we are outside off ANY process (cur_pid=-1)
    * so the idle's proc[0].tcb.sp remains untouched by PendSV until
    * our first context_switch from idle.
    */
   proc_set_current_pid(-1);
   return (int)pid; // Must be 0 (idle's pid)
}
/** Read file to test NSEC3 hash algo */
static void
nsec3_hash_test(const char* fname)
{
	/* 
	 * The list contains a list of ldns-testpkts entries.
	 * Every entry is a test.
	 * 	The qname is hashed.
	 * 	The answer section AAAA RR name is the required result.
	 * 	The auth section NSEC3 is used to get hash parameters.
	 * The hash cache is maintained per file.
	 *
	 * The test does not perform canonicalization during the compare.
	 */
	rbtree_t ct;
	struct regional* region = regional_create();
	struct alloc_cache alloc;
	ldns_buffer* buf = ldns_buffer_new(65535);
	struct entry* e;
	struct entry* list = read_datafile(fname);

	if(!list)
		fatal_exit("could not read %s: %s", fname, strerror(errno));
	rbtree_init(&ct, &nsec3_hash_cmp);
	alloc_init(&alloc, NULL, 1);
	unit_assert(region && buf);

	/* ready to go! */
	for(e = list; e; e = e->next) {
		nsec3_hash_test_entry(e, &ct, &alloc, region, buf);
	}

	delete_entry(list);
	regional_destroy(region);
	alloc_clear(&alloc);
	ldns_buffer_free(buf);
}
示例#18
0
文件: main.c 项目: gonmf/matilda
int main()
{
    alloc_init();

    flog_config_modes(LOG_MODE_ERROR | LOG_MODE_WARN);
    flog_config_destinations(LOG_DEST_STDF);

    assert_data_folder_exists();


    fprintf(stderr, "This process aims to reduce the bit distribution variance \
of the data.\nWhen you are satisfied press ENTER\n\n");

    u64 iv[TOTAL_BOARD_SIZ][2];
    memset(iv, 0, TOTAL_BOARD_SIZ * sizeof(u64));

    u32 table_size = TOTAL_BOARD_SIZ * 2;
    u64 * table = (u64 *)malloc(table_size * sizeof(u64));
    u32 bits[64];
    double best_variance = 999999.0;
    fd_set readfs;
    memset(&readfs, 0, sizeof(fd_set));

    while(best_variance > 0.0)
    {
        rand_reinit();
        for(u32 attempts = 0; attempts < 100; ++attempts)
        {
            for(u32 i = 0; i < table_size; ++i)
            {
                do
                {
                    table[i] = 0;
                    for(u32 j = 0; j < 64; ++j)
                        table[i] = (table[i] << 1) | rand_u16(2);

                    bool found = false;
                    for(u32 j = 0; j < i; ++j)
                        if(table[i] == table[j])
                        {
                            found = true;
                            break;
                        }
                    if(found)
                        continue;
                }
                while(count_bits(table[i]) != 32);
            }

            memset(bits, 0, sizeof(u32) * 64);
            for(u32 i = 0; i < table_size; ++i)
                for(u32 b = 0; b < 64; ++b)
                    if((table[i] >> b) & 1)
                        ++bits[b];


            u32 total = 0;
            for(u32 b = 0; b < 64; ++b)
                total += bits[b];
            double average = ((double)total) / ((double)64);

            double variance = 0.0;
            for(u32 b = 0; b < 64; ++b)
                variance += (((double)bits[b]) - average) * (((double)bits[b]) -
                    average);
            variance = variance / ((double)64);

            if(variance < best_variance)
            {
                best_variance = variance;
                memcpy(iv, table, sizeof(u64) * table_size);
                fprintf(stderr, "\rBest variance=%5f ", best_variance);
                fflush(stderr);
            }
        }

        FD_ZERO(&readfs);
        FD_SET(STDIN_FILENO, &readfs);
        struct timeval tm;
        tm.tv_sec = 0;
        tm.tv_usec = 0;

        int ready = select(STDIN_FILENO + 1, &readfs, NULL, NULL, &tm);
        if(ready > 0)
            break;
    }

    free(table);

    fprintf(stderr, "\nSearch stopped.\n");

    char * filename = alloc();
    snprintf(filename, MAX_PAGE_SIZ, "%s%ux%u.zt.new", data_folder(),
        BOARD_SIZ, BOARD_SIZ);


    FILE * h = fopen(filename, "wb");
    if(h == NULL)
    {
        fprintf(stderr, "Error: failed to open file %s for writing\n",
            filename);
        release(filename);
        exit(EXIT_FAILURE);
    }

    size_t w = fwrite(iv, sizeof(u64), TOTAL_BOARD_SIZ * 2, h);
    if(w != TOTAL_BOARD_SIZ * 2)
    {
        fprintf(stderr, "Error: unexpected number of bytes written\n");
        release(filename);
        exit(EXIT_FAILURE);
    }

    fclose(h);

    fprintf(stderr, "Zobrist table written to %s\n", filename);
    release(filename);
    return EXIT_SUCCESS;
}
示例#19
0
int main() {

  	static unsigned char alloc_buffer[4096*(1+1+4+1+16+1+256)];	
	char json_buffer[4096];
	char print_buffer[4096];
	int ret;
	int readlen;
	int json_offset;
	void * root_node;
	void * findlist;
	void * memdb_template ;
	BYTE uuid[DIGEST_SIZE];
	int i;
	MSG_HEAD * msg_head;
	
	char * baseconfig[] =
	{
		"typelist.json",
		"subtypelist.json",
		"msghead.json",
		"headrecord.json",
		NULL
	};

	alloc_init(alloc_buffer);
	struct_deal_init();
	memdb_init();

// test namelist reading start

	for(i=0;baseconfig[i]!=NULL;i++)
	{
		ret=read_json_file(baseconfig[i]);
		if(ret<0)
			return ret;
		printf("read %d elem from file %s!\n",ret,baseconfig[i]);
	}

	void * record;

// test struct desc reading start
	
	int msg_type = memdb_get_typeno("MESSAGE");
	if(msg_type<=0)
		return -EINVAL;

	int subtype=memdb_get_subtypeno(msg_type,"HEAD");
	if(subtype<=0)
		return -EINVAL;

	record=memdb_get_first(msg_type,subtype);
	while(record!=NULL)
	{
		ret=memdb_print(record,print_buffer);
		if(ret<0)
			return -EINVAL;
		printf("%s\n",print_buffer);
		record=memdb_get_next(msg_type,subtype);
	}

	msgfunc_init();
	
	void * message;

	message=message_create(512,1,NULL);	

	ret=Galloc0(&msg_head,sizeof(MSG_HEAD));
	if(msg_head==NULL)
		return -EINVAL;
	Strcpy(msg_head->sender_uuid,"Test sender");	
	Strcpy(msg_head->receiver_uuid,"Test receiver");
	ret=message_add_record(message,msg_head);
	if(ret<0)
	{
		printf("add message head record failed!\n");
		return ret;
	}	

	ret=message_record_struct2blob(message);
	if(ret<0)
	{
		printf("message struct2blob failed!\n");
		return ret;
	}	

	BYTE * blob;
	
	message_output_blob(message,&blob);
	ret=message_output_json(message,json_buffer);
	if(ret<0)
	{
		printf("message output json failed!\n");
		return ret;
	}

	printf("%s\n",json_buffer);
	
	
	void * new_msg;

	ret=json_2_message(json_buffer,&new_msg);

	if(ret<0)
		return ret;

	printf ("read % from json_buffer\n",ret);

	ret=message_output_json(message,json_buffer);
	if(ret<0)
	{
		printf("message output json failed!\n");
		return ret;
	}

	printf("%s\n",json_buffer);
	

	
	return 0;

}
示例#20
0
文件: region.c 项目: RAttab/ilka
struct ilka_region * ilka_open(const char *file, struct ilka_options *options)
{
    journal_recover(file);

    struct ilka_region *r = calloc(1, sizeof(struct ilka_region));
    if (!r) {
        ilka_fail("out-of-memory for ilka_region struct: %lu",
                sizeof(struct ilka_region));
        return NULL;
    }

    slock_init(&r->lock);

    r->file = file;
    r->options = *options;

    if ((r->fd = file_open(file, &r->options)) == -1) goto fail_open;
    if ((r->len = file_grow(r->fd, ILKA_PAGE_SIZE)) == -1UL) goto fail_grow;
    if (!mmap_init(&r->mmap, r->fd, r->len, &r->options)) goto fail_mmap;
    if (!persist_init(&r->persist, r, r->file)) goto fail_persist;

    const struct meta * meta = meta_read(r);
    if (meta->magic != ilka_magic) {
        if (!r->options.create) {
            ilka_fail("invalid magic for file '%s'", file);
            goto fail_magic;
        }

        struct meta * m = meta_write(r);
        m->magic = ilka_magic;
        m->version = ilka_version;
        m->alloc = sizeof(struct meta);
    }

    if (meta->version != ilka_version) {
        ilka_fail("invalid version for file '%s': %lu != %lu",
                file, meta->version, ilka_version);
        goto fail_version;
    }

    if (!alloc_init(&r->alloc, r, &r->options, meta->alloc)) goto fail_alloc;
    if (!epoch_init(&r->epoch, r, &r->options)) goto fail_epoch;
    if (ILKA_MCHECK) mcheck_init(&r->mcheck);

    r->header_len = alloc_end(&r->alloc);

    return r;

  fail_epoch:
  fail_alloc:
  fail_version:
  fail_magic:
    persist_close(&r->persist);

  fail_persist:
    mmap_close(&r->mmap);

  fail_mmap:
  fail_grow:
    file_close(r->fd);

  fail_open:
    free(r);
    return NULL;
}
示例#21
0
void malloc_init(void)
{
    alloc_init(AllocPool, ALLOC_POOL_SIZE);
}
示例#22
0
struct daemon* 
daemon_init(void)
{
	struct daemon* daemon = (struct daemon*)calloc(1, 
		sizeof(struct daemon));
#ifdef USE_WINSOCK
	int r;
	WSADATA wsa_data;
#endif
	if(!daemon)
		return NULL;
#ifdef USE_WINSOCK
	r = WSAStartup(MAKEWORD(2,2), &wsa_data);
	if(r != 0) {
		fatal_exit("could not init winsock. WSAStartup: %s",
			wsa_strerror(r));
	}
#endif /* USE_WINSOCK */
	signal_handling_record();
	checklock_start();
#ifdef HAVE_SSL
#  ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
	ERR_load_crypto_strings();
#  endif
#if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
	ERR_load_SSL_strings();
#endif
#  ifdef USE_GOST
	(void)sldns_key_EVP_load_gost_id();
#  endif
#  if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
	OpenSSL_add_all_algorithms();
#  else
	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
		| OPENSSL_INIT_ADD_ALL_DIGESTS
		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
#  endif
#  if HAVE_DECL_SSL_COMP_GET_COMPRESSION_METHODS
	/* grab the COMP method ptr because openssl leaks it */
	comp_meth = (void*)SSL_COMP_get_compression_methods();
#  endif
#  if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
	(void)SSL_library_init();
#  else
	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
#  endif
#  if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED)
	if(!ub_openssl_lock_init())
		fatal_exit("could not init openssl locks");
#  endif
#elif defined(HAVE_NSS)
	if(NSS_NoDB_Init(NULL) != SECSuccess)
		fatal_exit("could not init NSS");
#endif /* HAVE_SSL or HAVE_NSS */
#ifdef HAVE_TZSET
	/* init timezone info while we are not chrooted yet */
	tzset();
#endif
	/* open /dev/random if needed */
	ub_systemseed((unsigned)time(NULL)^(unsigned)getpid()^0xe67);
	daemon->need_to_exit = 0;
	modstack_init(&daemon->mods);
	if(!(daemon->env = (struct module_env*)calloc(1, 
		sizeof(*daemon->env)))) {
		free(daemon);
		return NULL;
	}
	/* init edns_known_options */
	if(!edns_known_options_init(daemon->env)) {
		free(daemon->env);
		free(daemon);
		return NULL;
	}
	alloc_init(&daemon->superalloc, NULL, 0);
	daemon->acl = acl_list_create();
	if(!daemon->acl) {
		edns_known_options_delete(daemon->env);
		free(daemon->env);
		free(daemon);
		return NULL;
	}
	if(gettimeofday(&daemon->time_boot, NULL) < 0)
		log_err("gettimeofday: %s", strerror(errno));
	daemon->time_last_stat = daemon->time_boot;
	if((daemon->env->auth_zones = auth_zones_create()) == 0) {
		acl_list_delete(daemon->acl);
		edns_known_options_delete(daemon->env);
		free(daemon->env);
		free(daemon);
		return NULL;
	}
	return daemon;	
}
示例#23
0
void
sys$bootstrap(struct vms$meminfo *mem_info, vms$pointer pagesize)
{
    struct memsection       *heap;

    unsigned int            i;

    vms$pointer             base;
    vms$pointer             end;

    notice(SYSBOOT_I_SYSBOOT "reserving memory for preloaded objects\n");

    // Initialization
    pm_alloc.internal.base = 0;
    pm_alloc.internal.end = 0;
    pm_alloc.internal.active = 0;

    vm_alloc.internal.base = 0;
    vm_alloc.internal.end = 0;
    vm_alloc.internal.active = 0;

    for(i = 0; i <= MAX_FPAGE_ORDER; i++)
    {
        TAILQ_INIT(&vm_alloc.flist[i]);
        TAILQ_INIT(&pm_alloc.flist[i]);
    }

    // Bootimage objects are removed from free virtual memory.
    for(i = 0; i < mem_info->num_objects; i++)
    {
        if (mem_info->objects[i].flags & VMS$IOF_VIRT)
        {
            notice(MEM_I_ALLOC "allocating $%016lX - $%016lX\n",
                    mem_info->objects[i].base, mem_info->objects[i].end);
            sys$remove_virtmem(mem_info, mem_info->objects[i].base,
                    mem_info->objects[i].end, pagesize);
        }
    }

    // Free up som virtual memory to bootstrap the fpage allocator.
    for(i = 0; i < mem_info->num_vm_regions; i++)
    {
        base = sys$page_round_up(mem_info->vm_regions[i].base, pagesize);
        end = sys$page_round_down(mem_info->vm_regions[i].end + 1, pagesize)
            - 1;

        if ((end - (base + 1)) >= (2 * pagesize))
        {
            notice(MEM_I_FALLOC "bootstrapping Fpage allocator at virtual "
                    "addresses\n");
            notice(MEM_I_FALLOC "$%016lX - $%016lX\n", base, end);
            sys$fpage_free_internal(&vm_alloc, base, end);
            mem_info->vm_regions[i].end = mem_info->vm_regions[i].base;
            break;
        }
    }

    PANIC(i >= mem_info->num_regions);

    // We need to make sure the first chunk of physical memory we free
    // is at least 2 * pagesize to bootstrap the slab allocators for
    // memsections and the fpage lists.

    for(i = 0; i < mem_info->num_regions; i++)
    {
        base = sys$page_round_up(mem_info->regions[i].base, pagesize);
        end = sys$page_round_down(mem_info->regions[i].end + 1, pagesize) - 1;

        if (((end - base) + 1) >= (2 * pagesize))
        {
            notice(MEM_I_SALLOC "bootstrapping Slab allocator at physical "
                    "addresses\n");
            notice(MEM_I_SALLOC "$%016lX - $%016lX\n", base, end);
            sys$fpage_free_chunk(&pm_alloc, base, end);
            mem_info->regions[i].end = mem_info->regions[i].base;
            break;
        }
    }

    PANIC(i >= mem_info->num_regions);

    // Base and end may not be aligned, but we need them to be aligned. If
    // the area is less than a page than we should not add it to the free list.

    for(i = 0; i < mem_info->num_regions; i++)
    {
        if (mem_info->regions[i].base == mem_info->regions[i].end)
        {
            continue;
        }

        base = sys$page_round_up(mem_info->regions[i].base, pagesize);
        end = sys$page_round_down(mem_info->regions[i].end + 1, pagesize) - 1;

        if (base < end)
        {
            notice(MEM_I_FREE "freeing region $%016lX - $%016lX\n", base, end);
            sys$fpage_free_chunk(&pm_alloc, base, end);
        }
    }

    sys$fpage_clear_internal(&vm_alloc);

    // Initialize VM allocator

    for(i = 0; i < mem_info->num_vm_regions; i++)
    {
        if (mem_info->vm_regions[i].base < mem_info->vm_regions[i].end)
        {
            notice(MEM_I_VALLOC "adding $%016lX - $%016lX to VM allocator\n",
                    mem_info->vm_regions[i].base, mem_info->vm_regions[i].end);
            sys$fpage_free_chunk(&vm_alloc, mem_info->vm_regions[i].base,
                    mem_info->vm_regions[i].end);
        }
    }

    // Setup the kernel heap

    heap = sys$pd_create_memsection((struct pd *) NULL, VMS$HEAP_SIZE, 0,
            VMS$MEM_NORMAL | VMS$MEM_USER, pagesize);

    PANIC(heap == NULL, notice(SYS_F_HEAP "cannot allocate kernel heap\n"));

    sys$alloc_init(heap->base, heap->end);
    return;
}
示例#24
0
static int __init capi_init(void)
{
	char *p;
	char *compileinfo;

	MOD_INC_USE_COUNT;

	if ((p = strchr(revision, ':')) != 0 && p[1]) {
		strncpy(rev, p + 2, sizeof(rev));
		rev[sizeof(rev)-1] = 0;
		if ((p = strchr(rev, '$')) != 0 && p > rev)
		   *(p-1) = 0;
	} else
		strcpy(rev, "1.0");

	if (devfs_register_chrdev(capi_major, "capi20", &capi_fops)) {
		printk(KERN_ERR "capi20: unable to get major %d\n", capi_major);
		MOD_DEC_USE_COUNT;
		return -EIO;
	}

#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
	if (devfs_register_chrdev(capi_rawmajor, "capi/r%d", &capinc_raw_fops)) {
		devfs_unregister_chrdev(capi_major, "capi20");
		printk(KERN_ERR "capi20: unable to get major %d\n", capi_rawmajor);
		MOD_DEC_USE_COUNT;
		return -EIO;
	}
        devfs_register_series (NULL, "capi/r%u", CAPINC_NR_PORTS,
			      DEVFS_FL_DEFAULT,
                              capi_rawmajor, 0,
                              S_IFCHR | S_IRUSR | S_IWUSR,
                              &capinc_raw_fops, NULL);
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
	devfs_register (NULL, "isdn/capi20", DEVFS_FL_DEFAULT,
			capi_major, 0, S_IFCHR | S_IRUSR | S_IWUSR,
			&capi_fops, NULL);
	printk(KERN_NOTICE "capi20: started up with major %d\n", capi_major);

	if ((capifuncs = attach_capi_interface(&cuser)) == 0) {

		MOD_DEC_USE_COUNT;
		devfs_unregister_chrdev(capi_major, "capi20");
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
		devfs_unregister_chrdev(capi_rawmajor, "capi/r%d");
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
		devfs_unregister(devfs_find_handle(NULL, "capi20",
						   capi_major, 0,
						   DEVFS_SPECIAL_CHR, 0));
		return -EIO;
	}

#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
	if (capinc_tty_init() < 0) {
		(void) detach_capi_interface(&cuser);
		devfs_unregister_chrdev(capi_major, "capi20");
		devfs_unregister_chrdev(capi_rawmajor, "capi/r%d");
		MOD_DEC_USE_COUNT;
		return -ENOMEM;
	}
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */

	if (alloc_init() < 0) {
#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
		unsigned int j;
		devfs_unregister_chrdev(capi_rawmajor, "capi/r%d");
		for (j = 0; j < CAPINC_NR_PORTS; j++) {
			char devname[32];
			sprintf(devname, "capi/r%u", j);
			devfs_unregister(devfs_find_handle(NULL, devname, capi_rawmajor, j, DEVFS_SPECIAL_CHR, 0));
		}
		capinc_tty_exit();
#endif /* CONFIG_ISDN_CAPI_MIDDLEWARE */
		(void) detach_capi_interface(&cuser);
		devfs_unregister_chrdev(capi_major, "capi20");
		devfs_unregister(devfs_find_handle(NULL, "capi20",
						   capi_major, 0,
						   DEVFS_SPECIAL_CHR, 0));
		MOD_DEC_USE_COUNT;
		return -ENOMEM;
	}

	(void)proc_init();

#ifdef CONFIG_ISDN_CAPI_MIDDLEWARE
#if defined(CONFIG_ISDN_CAPI_CAPIFS) || defined(CONFIG_ISDN_CAPI_CAPIFS_MODULE)
        compileinfo = " (middleware+capifs)";
#else
        compileinfo = " (no capifs)";
#endif
#else
        compileinfo = " (no middleware)";
#endif
	printk(KERN_NOTICE "capi20: Rev %s: started up with major %d%s\n",
				rev, capi_major, compileinfo);

	MOD_DEC_USE_COUNT;
	return 0;
}
示例#25
0
/*
 * Name        : wpsenr_wksp_mainloop
 * Description : Main loop point for the WPS stack
 * Arguments   : wpsenr_param_t *param - argument set
 * Return type : int
 */
static wpssta_wksp_t *
wpssta_init(char *ifname)
{
	wpssta_wksp_t *sta_wksp = NULL;
	int pbc = WPS_UI_PBC_SW;
	char start_ok = false;
	wps_ap_list_info_t *wpsaplist;
	char scan = false;
	char *val, *next;
	char op[6] = {0};
	int oob = 0;
	int i, imax;
	int wps_action;
	char *env_ssid = NULL;
	char *env_sec = NULL;
	char *env_bssid = NULL;
	char *env_pin = NULL;
#ifdef __CONFIG_WFI__
	char *ui_env_pin = NULL;
#endif /* __CONFIG_WFI__ */
	char tmp[100];
	char *wlnames, name[256];


	TUTRACE((TUTRACE_INFO, "*********************************************\n"));
	TUTRACE((TUTRACE_INFO, "WPS - Enrollee App Broacom Corp.\n"));
	TUTRACE((TUTRACE_INFO, "Version: %s\n", MOD_VERSION_STR));
	TUTRACE((TUTRACE_INFO, "*********************************************\n"));

	/* we need to specify the if name before anything else */
	if (!ifname) {
		TUTRACE((TUTRACE_INFO, "no ifname exist!! return\n"));
		return 0;
	}

	/* WSC 2.0,  support WPS V2 or not */
	if (strcmp(wps_safe_get_conf("wps_version2"), "enabled") == 0)
		b_wps_version2 = true;

	wps_set_ifname(ifname);
	wps_osl_set_ifname(ifname);

	/* reset assoc_state in INIT state */
	assoc_state = WPS_ASSOC_STATE_INIT;

	/* reset enroll_again */
	enroll_again = false;

	/* Check whether scan needed */
	val = wps_ui_get_env("wps_enr_scan");
	if (val)
		scan = atoi(val);

	/* if scan requested : display and exit */
	if (scan) {
		/* do scan and wait the scan results */
		do_wps_scan();
		while (get_wps_scan_results() == NULL)
			WpsSleep(1);

		/* use scan result to create ap list */
		wpsaplist = create_aplist();
		if (wpsaplist) {
			wpssta_display_aplist(wpsaplist);
			wps_get_aplist(wpsaplist, wpsaplist);

			TUTRACE((TUTRACE_INFO, "WPS Enabled AP list :\n"));
			wpssta_display_aplist(wpsaplist);
		}
		goto exit;
	}

	/* init workspace */
	if ((sta_wksp = (wpssta_wksp_t *)alloc_init(sizeof(wpssta_wksp_t))) == NULL) {
		TUTRACE((TUTRACE_INFO, "Can not allocate memory for wps workspace...\n"));
		return NULL;
	}
	memset(sta_wksp, 0, sizeof(wpssta_wksp_t));
	wps_action = atoi(wps_ui_get_env("wps_action"));

	/* Setup STA action */
	if (wps_action == WPS_UI_ACT_STA_CONFIGAP || wps_action == WPS_UI_ACT_STA_GETAPCONFIG) {
		sta_wksp->mode = WPSM_STA_BUILTINREG;
		if (wps_action == WPS_UI_ACT_STA_CONFIGAP)
			sta_wksp->configap = true;
	}
	else
		sta_wksp->mode = WPSM_STA_ENROLL;

	val = wps_ui_get_env("wps_pbc_method");
	if (val)
		pbc = atoi(val);


	/* Save maximum instance number, and probe if any wl interface */
	imax = wps_get_ess_num();
	for (i = 0; i < imax; i++) {
		sprintf(tmp, "ess%d_wlnames", i);
		wlnames = wps_safe_get_conf(tmp);

		foreach(name, wlnames, next) {
			if (!strcmp(name, ifname)) {
				sta_wksp->ess_id = i;
				goto found;
			}
		}
	}
	goto exit;

found:
	/* Retrieve ENV */
	if (pbc ==  WPS_UI_PBC_HW) {
		strcat(op, "pb");
	}
	else {
		/* SW PBC */
		if (atoi(wps_ui_get_env("wps_method")) == WPS_UI_METHOD_PBC) {
			strcat(op, "pb");
		}
		else { /* PIN */
			strcat(op, "pin");
			env_pin = wps_get_conf("wps_device_pin");
			
			env_sec = wps_ui_get_env("wps_enr_wsec");
			if (env_sec[0] != 0) {
				wsec = atoi(env_sec);
			}

			env_ssid = wps_ui_get_env("wps_enr_ssid");
			if (env_ssid[0] == 0) {
				TUTRACE((TUTRACE_ERR, "\n\nPlease specify ssid or use pbc method\n\n"));
				goto exit;
			}
			wps_strncpy(ssid, env_ssid, sizeof(ssid));

			env_bssid = wps_ui_get_env("wps_enr_bssid");
			if (env_bssid[0] == 0) {
				/*
				 * WARNING : this "bssid" is used only to create an 802.1X socket.
				 *
				 * Normally, it should be the bssid of the AP we will associate to.
				 *
				 * Setting this manually means that we might be proceeding to
				 * eapol exchange with a different AP than the one we are associated to,
				 * which might work ... or not.
				 *
				 * When implementing an application, one might want to enforce association
				 * with the AP with that particular BSSID. In case of multiple AP
				 * on the ESS, this might not be stable with roaming enabled.
				 */
				ether_atoe(env_bssid, bssid);
			}
#ifdef __CONFIG_WFI__
			/* For WiFi-Invite session PIN */
			ui_env_pin = wps_ui_get_env("wps_device_pin");
			if (ui_env_pin[0] != '\0')
				env_pin = ui_env_pin;
#endif /* __CONFIG_WFI__ */

			if (sta_wksp->mode == WPSM_STA_BUILTINREG) {
				env_pin = wps_ui_get_env("wps_stareg_ap_pin");
				if (wps_validate_pin(env_pin) == FALSE) {
					TUTRACE((TUTRACE_INFO, "Not a valid PIN [%s]\n",
						env_pin ? (char *)env_pin : ""));
					goto exit;
				}

				sprintf(tmp, "ess%d_wps_oob", sta_wksp->ess_id);
				val = wps_ui_get_env(tmp);
				if (strcmp(val, "enabled") == 0)
					oob = 1;
			}

			/* If we want to get AP config and the AP is unconfigured,
			 * configure the AP directly
			*/
			if (sta_wksp->mode == WPSM_STA_BUILTINREG && sta_wksp->configap == false) {
				val = wps_ui_get_env("wps_scstate");
				if (strcmp(val, "unconfigured") == 0) {
					sta_wksp->configap = true;
					TUTRACE((TUTRACE_INFO, "AP-%s is unconfigure, "
						"using our security settings to configre it.\n"));
				}
			}
		}
	}

	TUTRACE((TUTRACE_INFO,
		"pbc = %s, wpsenr param: ifname = %s, mode= %s, op = %s, sec = %s, "
		"ssid = %s, bssid = %s, pin = %s, oob = %s\n",
		(pbc == 1? "HW_PBC": "SW_PBC"),
		ifname,
		(sta_wksp->mode == WPSM_STA_BUILTINREG) ? "STA_REG" : "STA_ENR",
		op,
		(env_sec? (char *)env_sec : "NULL"),
		(env_ssid? (char *)env_ssid : "NULL"),
		(env_bssid? (char *)env_bssid : "NULL"),
		(env_pin? (char *)env_pin : "NULL"),
		(oob == 1? "Enabled": "Disabled")));

	/*
	 * setup device configuration for WPS
	 * needs to be done before eventual scan for PBC.
	 */
	if (sta_wksp->mode == WPSM_STA_BUILTINREG) {
		if (wpssta_reg_config_init(sta_wksp, ifname, bssid, oob) != WPS_SUCCESS) {
			TUTRACE((TUTRACE_ERR, "wpssta_reg_config_init failed, exit.\n"));
			goto exit;
		}
	}
	else {
		if (wpssta_enr_config_init() != WPS_SUCCESS) {
			TUTRACE((TUTRACE_ERR, "wpssta_enr_config_init failed, exit.\n"));
			goto exit;
		}
	}

	/* if ssid specified, use it */
	if (!strcmp(op, "pin")) {
		pin = env_pin;
		if (!pin) {
			pin = def_pin;
			TUTRACE((TUTRACE_ERR,
				"\n\nStation Pin not specified, use default Pin %s\n\n",
				def_pin));
		}
		start_ok = true;
		/* WSC 2.0,  Test Plan 5.1.1 step 8 must add wps ie to probe request */
		if (b_wps_version2)
			add_wps_ie(NULL, 0, 0, b_wps_version2);
	}
	else {
		pin = NULL;
		wpsenr_osl_proc_states(WPS_FIND_PBC_AP);

		/* add wps ie to probe  */
		add_wps_ie(NULL, 0, TRUE, b_wps_version2);
		do_wps_scan();
		assoc_state_time = get_current_time();
		assoc_state = WPS_ASSOC_STATE_SCANNING;

		start_ok = false;
	}

	/* start WPS two minutes period at Finding a PBC AP or Associating with AP */
	start_time = get_current_time();

	if (start_ok) {
		/* clear current security setting */
		wpsenr_osl_clear_wsec();

		/*
		 * join. If user_bssid is specified, it might not
		 * match the actual associated AP.
		 * An implementation might want to make sure
		 * it associates to the same bssid.
		 * There might be problems with roaming.
		 */
		wpssta_do_join(false);
		return sta_wksp;
	}
	else if (assoc_state == WPS_ASSOC_STATE_SCANNING) {
		return sta_wksp;
	}

exit:
	wpssta_deinit(sta_wksp);
	return NULL;
}
示例#26
0
void			kaneton(t_init*				bootloader)
{
  /*
   * 1)
   */
  init = bootloader;

  /*
   * 2)
   */

  if (cons_init() != ERROR_NONE)
    core_error("cannot initialise the console manager\n");

  /*
   * 3)
   */

  printf("\n");
  cons_msg('+', "%s\n", version);
  printf("\n");

  /*
   * 4)
   */

#if (DEBUG & DEBUG_PARAMS)
  kaneton_dump();
#endif

  /*
   * 5)
   */

  cons_msg('+', "starting malloc\n");

  alloc_init(init->alloc, init->allocsz);

  /*
   * 6)
   */

  cons_msg('+', "starting kernel manager\n");

  kernel_init();

  /*
   * 7)
   */

  cons_msg('+', "kaneton started\n");

  /*
   * XXX
   */

#if defined(CONF_ENABLE_CHECK)
  cons_msg('+', "running manual tests\n");
  check_tests();
  while(1)
    ;
#endif

#ifdef SERIAL
  cons_msg('+', "starting debug manager\n");
  debug_init();
  while(1)
    ;
#endif

  /*
   * /XXX
   */

#ifdef APP
  APP();
#endif

  while(1)
    ;

  cons_msg('#', "kaneton is stopping...\n");

  /*
   * 8)
   */

  kernel_clean();

  /*
   * 21)
   */

  cons_msg('+', "system shutdown\n");

  while (1)
    ;
}
示例#27
0
int main() {

    static unsigned char alloc_buffer[4096*(1+1+4+1+32+1+256)];
    char json_buffer[4096];
    char print_buffer[4096];
    int ret;
    int readlen;
    int json_offset;
    void * root_node;
    void * findlist;
    void * memdb_template ;
    BYTE uuid[DIGEST_SIZE];
    int i;
    MSG_HEAD * msg_head;
    pthread_t  cube_thread;

    char * baseconfig[] =
    {
        "typelist.json",
        "subtypelist.json",
        "msghead.json",
        "login_struct.json",
        "headrecord.json",
        NULL
    };

    alloc_init(alloc_buffer);
    struct_deal_init();
    memdb_init();

// test namelist reading start

    for(i=0; baseconfig[i]!=NULL; i++)
    {
        ret=read_json_file(baseconfig[i]);
        if(ret<0)
            return ret;
        printf("read %d elem from file %s!\n",ret,baseconfig[i]);
    }

    void * record;

// test struct desc reading start

    msgfunc_init();

    void * message;
    void * policy;

    dispatch_init(NULL);
    policy=dispatch_policy_create();
    if(policy==NULL)
    {
        printf("create policy failed!\n");
        return -EINVAL;
    }

    ret=read_dispatch_file("dispatch_policy.json");

//	routine_start();
//	sleep(100000);

    return 0;

}
示例#28
0
文件: main.c 项目: matzipan/hapr
void main(void)
{
	char read_buffer[16];
	char s[16];

	uint16_t skip_reading = 0;

	serial_init();
	#if DEBUG==1
	tty_writeln("Serial Init");
	#endif

	dac_init();
	#if DEBUG==1
	tty_writeln("DAC Init");
	#endif

	adc_init();
	#if DEBUG==1
	tty_writeln("ADC Init");
	#endif

	timer_init(frequency);
	#if DEBUG==1
	tty_writeln("Timer Init");
	#endif

	alloc_init();
	#if DEBUG==1
	tty_writeln("Alloc Init");
	#endif

	//scramble_init();
	//tty_writeln("Scramble Init");
	//scramble_enable();
	//while(1); // @TODO: Make scramble work alongside main function

	#if DEBUG==1
		do_debug();
	#else
		do_passthrough();
	#endif

	#if DEBUG==1
	tty_writeln("Passthrough Init");
	#endif

	while(1)  {
		if(!skip_reading)
			tty_read_blocking(read_buffer, 16);
		skip_reading = 0;

		#if DEBUG==1 && TRACE==1
		tty_writeln("While");
		#endif

		if(read_buffer[0] == REPL_NOOP_COMMAND) {
			// noop command used to check the connection status when the GUI connects
			tty_writeln("Noop");
		}

		if(read_buffer[0] == REPL_HALT_COMMAND) {
			// halt command, enables passthrough
			do_passthrough();
			tty_writeln("Halt");
		}

		if(read_buffer[0] == REPL_GET_COMMAND) {
			sprintf(s, "Get:%d", frequency);
			tty_writeln(s);
		}

		// Download current filter chain to GUI
		if(read_buffer[0] == REPL_DOWNLOAD_COMMAND) {
			// download the filter that is currently loaded into memory (including passthrough)

			#if DEBUG==1
			tty_writeln("Downloading filter chain to gui");
			#endif

			sprintf(s, "Download:%d", filters_count);
			tty_writeln(s);

			int i=0;
			while(i < filters_count){
				tty_read_blocking(read_buffer, 16);
				if(read_buffer[0] == REPL_DOWNLOAD_COMMAND) {
					sprintf(s, "Download:%c%c%c%c%c%c%c%c",
									filters_buf[i*8 + 0]+32, //adding 32 because python is fussy with special characters
									filters_buf[i*8 + 1]+32,
									filters_buf[i*8 + 2]+32,
									filters_buf[i*8 + 3]+32,
									filters_buf[i*8 + 4]+32,
									filters_buf[i*8 + 5]+32,
									filters_buf[i*8 + 6]+32,
									filters_buf[i*8 + 7]+32);

					tty_writeln(s);

					if(i == filters_count-1) {
						#if DEBUG==1
						tty_writeln("Filter download done");
						#endif

						break;
					}
				} else {
					skip_reading = 1; //the command was invalid, which probably means the interface or connection crashed
					break;
				}


				i++;
			}
		}

		// Load a filter chain from the flash memory, initialise and run it
		if(read_buffer[0] == REPL_LOAD_COMMAND) {
			uint8_t block = read_buffer[1];
			if(block > 9){ //10 blocks available to load from
				#if DEBUG==1
				tty_writeln("ERROR: Requested block does not exist");
				#else
				tty_writeln("ERROR");
				#endif

				break;
			}

			// store so we can recover in case of failure of retrieval
			uint16_t fc = filters_count;

			get_filter_chain_size(&filters_count, block);


			if(filters_count == 0){
				#if DEBUG==1
				tty_writeln("Requested block is empty");
				#else
				tty_writeln("Block empty");
				#endif

				filters_count = fc;
			}else{
				timer_stop();

				// copy filters_count here as it is wiped by free_all_filters()
				fc = filters_count;

				free_all_filters();
				free_all_buf();

				// reset filters_count to what it was before
				filters_count = fc;

				flash_to_filter_chain(filters_buf, filters_count, block);

				filter_init(filters_buf, filters_count);

				timer_start();

				tty_writeln("Loaded");
			}
		}

		// Save a filter chain to flash
		// Can only save to each block once due to flash sectors not erasing
		if(read_buffer[0] == REPL_SAVE_COMMAND) {
			uint8_t block = read_buffer[1];

			if(block > 9){ //10 blocks available to load from
				#if DEBUG==1
				tty_writeln("ERROR: Requested block does not exist");
				#else
				tty_writeln("ERROR");
				#endif

				break;
			}
			//Save into requested block
			if(filter_chain_to_flash(filters_buf, &filters_count, block) != 0){
				#if DEBUG==1
				tty_writeln("ERROR: Block has already been written to");
				#else
				tty_writeln("Error");
				#endif
			} else {
				tty_writeln("Saved");
			}
		}

		if(read_buffer[0] == REPL_SET_COMMAND) {
			// command that gets the frequency from CLI and sets
			int index = 1;
			frequency = 0;

			while(read_buffer[index] != 0) { //if not EOL
				frequency = frequency*10+(read_buffer[index]-'0');

				index++;
			}

			timer_stop(); //@TODO test if it is really needed
			timer_init(frequency);
			timer_start(); //@TODO test if it is really needed

			tty_writeln("Set");
		}

		if(read_buffer[0] == REPL_APPLY_COMMAND) {
			// command that gets a filter chain from CLI and applies it
			timer_stop();

			free_all_filters();
			free_all_buf();

			tty_writeln("Apply");

			filters_count = 0;

			while(1) {
				tty_read_blocking(read_buffer, 16);

				if(read_buffer[0]== REPL_APPLY_COMMAND) {
					uint16_t error =  filter_init(filters_buf, filters_count);
					if(error == 0) {
						timer_start();

						tty_writeln("End filters");
					} else {
						sprintf(s, "Error: %d", error);

						tty_writeln(s);
					}

					break;
				} else if(read_buffer[0]== REPL_FILTER_COMMAND) {
					// the first filter is always the INPUT!

					// (int)read_buffer[1] is filter function index
					// (int)read_buffer[2] filter id (unique) - 1
					// (int)read_buffer[3,4] filter ids to output to, it is limited to 2 for simplicity - 2,3
					// each of the following bytes can be a parameter (the gui takes 4 values of 0-254 !!! 254, not 255!!! comma sepparated)
					// next_id of 0x00 implies there is no next filter - filter->next = NULL (next filter is set to the input filter, which is obviously not taking any buffer input)

					/*
						filters_buf[n*8 + 0] = filter_type
						filters_buf[n*8 + 1] = unique_filter_id
						filters_buf[n*8 + 2] = output_filter_id #1
						filters_buf[n*8 + 3] = output_filter_id #2
						filters_buf[n*8 + 4] = parameter 0
						filters_buf[n*8 + 5] = parameter 1
						filters_buf[n*8 + 6] = parameter 2
						filters_buf[n*8 + 7] = parameter 3
					*/

					int i;
					for(i=0; i<8; i++) {
						filters_buf[filters_count*8 + i] = read_buffer[i+1];
					}

					filters_count++;

					tty_writeln("Filter");
				} else {
					skip_reading = 1; //the command was invalid, which probably means, the interface or connection crashed
					break;
				}
			}
		}
	}

	#if DEBUG==1 && TRACE==1
	tty_writeln("Escaped loop. This should not happen");
	#endif

	while(1);
}
示例#29
0
void memory_init(multiboot_info_t * mbi) {
   uint32_t k;
   uint64_t sizemodules = 0;
   
   // Copy E820 entries
   if(mbi->flags & MULTIBOOT_INFO_MEM_MAP) {
		multiboot_memory_map_t * mmap;
   
		for(mmap = (multiboot_memory_map_t *) mbi->mmap_addr, nbentries = 0 ;
                    (unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length ;
                    mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof (mmap->size)), nbentries++) {
			if(nbentries == E820ENTRYMAX) {
			   LOGERROR("!! Too many E820 entries !!\n");
	         return;
			}
			
			if((nbentries > 0) &&
                           (e820tab[nbentries - 1].addr + e820tab[nbentries - 1].size == mmap->addr &&
                            e820tab[nbentries - 1].type == mmap->type)) {
			   e820tab[nbentries - 1].size += mmap->len;
			} else {
			   e820tab[nbentries].addr = mmap->addr;
			   e820tab[nbentries].size = mmap->len;
			   e820tab[nbentries].type = mmap->type;
			}
		}
	} else {
	   LOGERROR("!! Can't get memory information from multiboot !!\n");
	   return;
	}
	
	// Get size of modules to relocate
	if(mbi->flags & MULTIBOOT_INFO_MODS) {
		multiboot_module_t * mod;
		
		for(k = 0, mod = (multiboot_module_t *) mbi->mods_addr ; k < mbi->mods_count ; k++, mod++) {
		   sizemodules += ((mod->mod_end - mod->mod_start) + 0xfff) & -0x1000;
		}
	}
	
	// Found the upper max of 32 bits memory in order to put our relocation area
	// The max can't be greater than 0xfffff000 in order to prevent some arithmetic errors
	for(k = 0 ; k < nbentries ; k++) {
	   uint64_t temp;
	   
	   // Is RAM ?
	   if(e820tab[k].type != E820_RAM) {
	      continue;
	   }
      
       // Is greater than our max ?
      if(e820tab[k].addr >= 0xfffff000) {
         continue;
      }
	   
	   temp = e820tab[k].addr + e820tab[k].size;

      // Adjust if this area is overlapping  our max
	   if(temp >= 0xfffff000) {
	      temp = 0xfffff000;
	   }
	   
	   // Align
	   temp &= -0x1000;
	   
	   // Don't use this area if there is not enought memory
	   if(temp - e820tab[k].addr < sizemodules + HEAPSIZE) {
	      continue;
	   }
	    
	   if(mem_relocmax < (uint8_t *) (uintptr_t) temp) {
	      mem_relocmax = (uint8_t *) (uintptr_t) temp;
	   }
	}
	
	if(mem_relocmax == 0) {
	   LOGERROR("!! Can't find the upper max of 32 bits memory !!\n");
	   return;
	}
	
	mem_relocmin = mem_relocmax;
	
	// Relocate multiboot module in the upper heap
	if(mbi->flags & MULTIBOOT_INFO_MODS) {
		multiboot_module_t * mod;
		
		for(k = 0, mod = (multiboot_module_t *) mbi->mods_addr ; k < mbi->mods_count ; k++, mod++) {
		   uint64_t start = mod->mod_start;
		   uint64_t end = mod->mod_end;
		   
		   // Create a aligned area for this module
			mem_relocmin -= (uintptr_t) (end - start);
			mem_relocmin = (uint8_t *) ((uintptr_t) mem_relocmin & -0x1000);
			
			// Relocate the module
			memcpy(mem_relocmin, (uint8_t *) (uintptr_t) start, end - start);
			
			// Update multiboot structure
			mod->mod_start = (uint64_t) (uintptr_t) mem_relocmin;
			mod->mod_end = (uint64_t) (uintptr_t) mem_relocmin + end - start;
			
			// Wipe old area
			memset((uint8_t *) (uintptr_t) start, 0, end - start);
		}
	}
	
	// Initialize HEAP
	heap_base = mem_relocmin - HEAPSIZE;
	alloc_init(&heapdescr, heap_base, HEAPSIZE);
	
	LOGDEBUG("Memory initialization done !");
}
示例#30
0
int main() {

  	static unsigned char alloc_buffer[4096*(1+1+4+1+16+1+256)];	
	char json_buffer[4096];
	char print_buffer[4096];
	int ret;
	int readlen;
	int json_offset;
	void * root_node;
	void * findlist;
	void * memdb_template ;
	BYTE uuid[DIGEST_SIZE];
	int i;
	MSG_HEAD * msg_head;
	pthread_t  cube_thread;
	
	char * baseconfig[] =
	{
		"typelist.json",
		"subtypelist.json",
		"msghead.json",
		"headrecord.json",
		NULL
	};

	alloc_init(alloc_buffer);
	struct_deal_init();
	memdb_init();

// test namelist reading start

	for(i=0;baseconfig[i]!=NULL;i++)
	{
		ret=read_json_file(baseconfig[i]);
		if(ret<0)
			return ret;
		printf("read %d elem from file %s!\n",ret,baseconfig[i]);
	}

	void * record;

// test struct desc reading start

	msgfunc_init();
	
	void * message;
	routine_init(NULL);

	routine_register("sub1",ROUTINE_SOURCE,&sub1_ops,NULL);
	routine_register("sub2",ROUTINE_SOURCE,&sub2_ops,NULL);

	pthread_create(&cube_thread,NULL,routine_start,NULL);

	int * thread_return;

	ret=pthread_join(cube_thread,&thread_return);

	printf("return value is %d\n",thread_return);
	
//	routine_start();
//	sleep(100000);
	
	return 0;

}