bool kv(std::vector<KeyVal>* items, std::set<std::string>& seen)
	{
		std::string key;
		nextword(key);
		int ch = next();
		if (ch == '>' && key.empty())
		{
			return false;
		}
		else if (ch == '#' && key.empty())
		{
			comment();
			return true;
		}
		else if (ch != '=')
		{
			throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
		}

		std::string value;
		ch = next();
		if (ch != '"')
		{
			throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
		}
		while (1)
		{
			ch = next();
			if (ch == '&' && !(flags & FLAG_USE_COMPAT))
			{
				std::string varname;
				while (1)
				{
					ch = next();
					if (isalnum(ch) || (varname.empty() && ch == '#'))
						varname.push_back(ch);
					else if (ch == ';')
						break;
					else
					{
						stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
							<< "To include an ampersand or quote, use &amp; or &quot;\n";
						throw CoreException("Parse error");
					}
				}
				if (varname.empty())
					throw CoreException("Empty XML entity reference");
				else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
					throw CoreException("Empty numeric character reference");
				else if (varname[0] == '#')
				{
					const char* cvarname = varname.c_str();
					char* endptr;
					unsigned long lvalue;
					if (cvarname[1] == 'x')
						lvalue = strtoul(cvarname + 2, &endptr, 16);
					else
						lvalue = strtoul(cvarname + 1, &endptr, 10);
					if (*endptr != '\0' || lvalue > 255)
						throw CoreException("Invalid numeric character reference '&" + varname + ";'");
					value.push_back(static_cast<char>(lvalue));
				}
				else
				{
					insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
					if (var == stack.vars.end())
						throw CoreException("Undefined XML entity reference '&" + varname + ";'");
					value.append(var->second);
				}
			}
			else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
			{
				int esc = next();
				if (esc == 'n')
					value.push_back('\n');
				else if (isalpha(esc))
					throw CoreException("Unknown escape character \\" + std::string(1, esc));
				else
					value.push_back(esc);
			}
			else if (ch == '"')
				break;
			else if (ch != '\r')
				value.push_back(ch);
		}

		if (!seen.insert(key).second)
			throw CoreException("Duplicate key '" + key + "' found");

		items->push_back(KeyVal(key, value));
		return true;
	}
Exemple #2
0
void AppEditMenu::createEditAdvancedMenu(QToolBar *toolbar)
{
    editAdvancedMenu = new QMenu(tr("Advanced"));

    editCommentAction=editAdvancedMenu->addAction(IconUtil::getIcon("comment"), tr("Co&mment/Uncomment"), this, SLOT(comment()), QKeySequence("Ctrl+/"));
    editCommentAction->setStatusTip(tr("Comment/Uncomment line(s)"));
    toolbar->addAction(editCommentAction);

    editMoveUpAction=editAdvancedMenu->addAction(IconUtil::getIcon("move_up"), tr("Move &up"), this, SLOT(moveUp()), QKeySequence("Ctrl+Up"));
    editMoveUpAction->setStatusTip(tr("Move lines(s) up"));
    toolbar->addAction(editMoveUpAction);

    editMoveDownAction=editAdvancedMenu->addAction(IconUtil::getIcon("move_down"), tr("Move &down"), this, SLOT(moveDown()), QKeySequence("Ctrl+Down"));
    editMoveDownAction->setStatusTip(tr("Move lines(s) down"));
    toolbar->addAction(editMoveDownAction);

    editSelectBlockAction=editAdvancedMenu->addAction(tr("Select current block"), this, SLOT(selectBlock()), QKeySequence("Ctrl+B"));
    editSelectBlockAction->setStatusTip(tr("Select current block"));

    editToUpperCaseAction=editAdvancedMenu->addAction(tr("To upper case"), this, SLOT(toUpperCase()), QKeySequence("Ctrl+U"));
    editToUpperCaseAction->setStatusTip(tr("Change selection or current word text to upper case"));

    editToLowerCaseAction=editAdvancedMenu->addAction(tr("To lower case"), this, SLOT(toLowerCase()), QKeySequence("Ctrl+L"));
    editToLowerCaseAction->setStatusTip(tr("Change selection or current word text to lower case"));

    editCreateDuplicateAction=editAdvancedMenu->addAction(tr("Make duplicate"), this, SLOT(makeDuplicate()), QKeySequence("Ctrl+D"));
    editCreateDuplicateAction->setStatusTip(tr("Create duplicate of current line or selection"));

    editRemoveEmptyLinesAction=editAdvancedMenu->addAction(tr("Remove empty lines"), this, SLOT(removeEmptyLines()), QKeySequence("Ctrl+R"));
    editRemoveEmptyLinesAction->setStatusTip(tr("Remove empty lines"));

    editApplyCaseFoldingAction=editAdvancedMenu->addAction(tr("Apply case folding"), this, SLOT(applyCaseFolding()), QKeySequence("Ctrl+Shift+U"));
    editApplyCaseFoldingAction->setStatusTip(tr("Apply automatic case folding rules to selection"));

    editFormatCodeAction=editAdvancedMenu->addAction(tr("Format"), this, SLOT(formatCode()), QKeySequence("Ctrl+Shift+F"));
    editFormatCodeAction->setStatusTip(tr("Auto format code to make it more readable"));
}
Exemple #3
0
static void dt(int kind,
   size_t minSize, size_t avgSize, size_t maxSize,
   mps_count_t depth, mps_count_t fragLimit,
   size_t mins, size_t maxs, int number, int iter)
{
 mps_pool_t pool;
 mps_ap_t ap;
 int i, hd;
 clock_t time0, time1;
 size_t size;
 int secs;

 asserts(number <= MAXNUMBER, "number too big");

 time0 = clock();
 asserts(time0 != -1, "processor time not available");

 die(
  mps_pool_create(&pool, arena, mps_class_mv2(),
                  minSize, avgSize, maxSize, depth, fragLimit),
  "create MV2 pool");

 die(mps_ap_create(&ap, pool, mps_rank_ambig()), "create ap");

 for(hd=0; hd<number; hd++)
 {
  size = ranrange(mins, maxs);
  if ((ranint(2) && (kind & 2)) || (kind==DUMMY))
  {
   queue[hd].addr=NULL;
  }
  else
  {
   die(mv2_alloc(&queue[hd].addr, ap, size), "alloc");
   setobj(queue[hd].addr, size, (unsigned char) (hd%256));
   queue[hd].size = size;
  }
 };

 hd=-1;

 for(i=0; i<iter; i++)
 {
   if (kind & 1) hd = ranint(number);
   else {ranint(number); hd=(hd+1)%number;} /* call raninit anyway
                                               to use same time */

   if (queue[hd].addr != NULL)
   {
    asserts(chkobj(queue[hd].addr, queue[hd].size, (unsigned char) (hd%256)),
      "corrupt at %x (%s: %x, %x, %x, %i, %i, %x, %x, %i, %i)",
      queue[hd].addr,
      tdesc[kind], (int) minSize, (int) avgSize, (int) maxSize,
      (int) depth, (int) fragLimit,
      (int) mins, (int) maxs, number, iter);
    mps_free(pool, queue[hd].addr, queue[hd].size);
   }
   size = ranrange(mins, maxs);

   if ((ranint(2) && (kind & 2)) || (kind==DUMMY))
   {
    queue[hd].addr=NULL;
   }
   else
   {
    die(mv2_alloc(&queue[hd].addr, ap, size),"alloc");
    setobj(queue[hd].addr, size, (unsigned char) (hd%256));
    queue[hd].size = size;
   }
 }

 mps_pool_destroy(pool);

 time1=clock();
 secs=(int) 100*(time1-time0)/CLOCKS_PER_SEC;

 comment("%s test (%x, %x, %x, %i, %i, %x, %x, %i, %i) in %i centisecs",
  tdesc[kind], (int) minSize, (int) avgSize, (int) maxSize,
  (int) depth, (int) fragLimit,
  (int) mins, (int) maxs, number, iter, secs);
}
Exemple #4
0
static void test(void) {
 long int i;
 long int rsize;

 int inramp;

 mycell *r, *s;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(),
   (size_t) ARENALIMIT),
  "create arena");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(
  mps_root_create_reg(&root, arena, mps_rank_ambig(), 0, thread,
   mps_stack_scan_ambig, stackpointer, 0),
  "create root");

 cdie(
  mps_root_create_table(&root1, arena, mps_rank_exact(), 0, &objtab[0], TABSIZE),
  "create root table");

 cdie(
  mps_fmt_create_A(&format, arena, &fmtA),
  "create format");

 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 cdie(
  mps_pool_create(&poolamc, arena, mps_class_amc(), format, chain),
  "create pool");

 cdie(
  mps_ap_create(&apamc, poolamc, mps_rank_exact()),
  "create ap");

 inramp = 0;

 for (i = 0; i < ITERATIONS; i++) {
  if (i % 10000 == 0) {
   comment("%ld of %ld", i, ITERATIONS);
  }
  alloc_back();
  if (inramp) {
   s = allocone(apamc, 3, mps_rank_exact());
   setref(r, 0, s);
   setref(s, 1, r);
   r = s;
   s = allocdumb(apamc, RAMPSIZE, mps_rank_exact());
   setref(r, 2, s);
   rsize ++;
   if (ranint(LEAVERAMP) == 0) {
    r = allocone(apamc, 2, mps_rank_exact());
    s = allocone(apamc, 2, mps_rank_exact());
#ifdef RAMP_INTERFACE
    mps_ap_alloc_pattern_end(apamc, mps_alloc_pattern_ramp());
#endif
#ifdef COLLECT_WORLD
    mps_arena_collect(arena);
    mps_arena_release(arena);
#endif
    comment("ramp end, %ld objects", rsize);
    inramp = 0;
   }
  } else {
   if (ranint(ENTERRAMP) == 0) {
#ifdef RAMP_INTERFACE
    mps_ap_alloc_pattern_begin(apamc, mps_alloc_pattern_ramp());
#endif
    comment("ramp begin");
    r = allocone(apamc, 3, mps_rank_exact());
    inramp = 1;
    rsize = 0;
   }
  }
 }

 mps_ap_destroy(apamc);
 comment("Destroyed ap.");

 mps_pool_destroy(poolamc);
 comment("Destroyed pool.");

 mps_fmt_destroy(format);
 comment("Destroyed format.");

 mps_chain_destroy(chain);
 comment("Destroyed chain.");

 mps_root_destroy(root1);
 mps_root_destroy(root);
 comment("Destroyed roots.");

 mps_thread_dereg(thread);
 comment("Deregistered thread.");

 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
static void test(void) {

 mycell *p, *q;
 int i;
 mps_res_t res;
 size_t lim0, avail0, lim1, avail1, commit1, lim2, avail2, commit2;
 size_t lim3, avail3, commit3, lim4, avail4, commit4;
 size_t lim5, avail5, commit5, lim6, avail6, commit6;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), ARENA_SIZE),
  "create space");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(mps_root_create_reg(&root, arena, MPS_RANK_AMBIG, 0, thread,
  mps_stack_scan_ambig, stackpointer, 0), "create stack root");

 cdie(
  mps_fmt_create_A(&format, arena, &fmtA),
  "create format");

 cdie(
  mps_pool_create(&poolsnc, arena, mps_class_snc(), format),
  "create pool");

 cdie(
  mps_ap_create(&apsnc, poolsnc, MPS_RANK_EXACT),
  "create ap");

 report("lim0", "%d", lim0 = mps_reservoir_limit(arena));
 report("avail0",  "%d", avail0 = mps_reservoir_available(arena));
 mps_reservoir_limit_set(arena, (size_t) 0);

 mps_reservoir_limit_set(arena, (size_t) (5ul*1024*1024));
 report("lim1", "%d", lim1 = mps_reservoir_limit(arena));
 report("avail1",  "%d", avail1 = mps_reservoir_available(arena));
 report("commit1", "%d", commit1 = arena_committed_and_used(arena));
 report("defecit1", "%d", lim1-avail1);

 mps_reservoir_limit_set(arena, (size_t) (1045));
 report("lim2", "%d", lim2 = mps_reservoir_limit(arena));
 report("avail2",  "%d", avail2 = mps_reservoir_available(arena));
 report("commit2", "%d", commit2 = arena_committed_and_used(arena));
 report("defecit2", "%d", lim2-avail2);

/* set commit limit to whatever is currently committed plus 1 MB
*/

 die(mps_arena_commit_limit_set(arena, arena_committed_and_used(arena)+1024*1024), "commit limit set");
 mps_reservoir_limit_set(arena, (size_t) (10ul*1024*1024));
 report("lim3", "%d", lim3 = mps_reservoir_limit(arena));
 report("avail3",  "%d", avail3 = mps_reservoir_available(arena));
 report("commit3", "%d", commit3 = arena_committed_and_used(arena));
 report("defecit3", "%d", lim3-avail3);
 report("spill3", "%d", commit3-mps_arena_commit_limit(arena));

/* now raise it by 1/2 MB -- reservoir should grow
*/

 die(mps_arena_commit_limit_set(arena, arena_committed_and_used(arena)+512*1024), "commit limit set");
 report("lim4", "%d", lim4 = mps_reservoir_limit(arena));
 report("avail4",  "%d", avail4 = mps_reservoir_available(arena));
 report("commit4", "%d", commit4 = arena_committed_and_used(arena));
 report("grow4", "%d", avail4-avail3);
 report("spill4", "%d", commit4-mps_arena_commit_limit(arena));

/* try some allocation -- more than a small amount should fail
*/

 i = -1;
 p = NULL;
 res = MPS_RES_OK;
 while (res == MPS_RES_OK) {
  res = allocrone(&q, apsnc, 10, MPS_RANK_EXACT);
  if (res == MPS_RES_OK) {
   setref(q, 0, p);
   p = q;
  }
  i++;
 }
 report("allocfail", "%d", i);
 report_res("failres", res);
 
/* available shouldn't have changed since before allocation
*/

 report("lim5", "%d", lim5 = mps_reservoir_limit(arena));
 report("avail5",  "%d", avail5 = mps_reservoir_available(arena));
 report("commit5", "%d", commit5 = arena_committed_and_used(arena));
 report("grow5", "%d", avail5-avail4);
 report("spill5", "%d", commit5-mps_arena_commit_limit(arena));

/* try some allocation from reservoir -- not much should fail
*/

 i = -1;
 res = MPS_RES_OK;
 while (res == MPS_RES_OK) {
  res = reservoir_allocrone(&q, apsnc, 10, MPS_RANK_EXACT);
  if (res == MPS_RES_OK) {
   setref(q, 0, p);
   p = q;
  }
  i++;
 }
 report("allocfail2", "%d", i);
 report_res("failres2", res);
 
/* available should have changed now
*/

 report("lim6", "%d", lim6 = mps_reservoir_limit(arena));
 report("avail6",  "%d", avail6 = mps_reservoir_available(arena));
 report("commit6", "%d", commit6 = arena_committed_and_used(arena));
 report("spill6", "%d", commit6-mps_arena_commit_limit(arena));
 report("shrink6", "%d", avail5-avail6);
 
 mps_root_destroy(root);
 comment("Destroyed root.");

 mps_ap_destroy(apsnc);
 comment("Destroyed ap.");

 mps_pool_destroy(poolsnc);
 comment("Destroyed pool.");

 mps_fmt_destroy(format);
 comment("Destroyed format.");

 mps_thread_dereg(thread);
 comment("Deregistered thread.");

 mps_arena_destroy(arena);
 comment("Destroyed space.");
}
void string_instrumentationt::do_format_string_read(
  goto_programt &dest,
  goto_programt::const_targett target,
  const code_function_callt::argumentst &arguments,
  unsigned format_string_inx,
  unsigned argument_start_inx,
  const std::string &function_name)
{
  const exprt &format_arg = arguments[format_string_inx];
  
  if(format_arg.id()==ID_address_of &&
     format_arg.op0().id()==ID_index &&
     format_arg.op0().op0().id()==ID_string_constant)
  {
    format_token_listt token_list=
      parse_format_string(format_arg.op0().op0().get_string(ID_value));
    
    unsigned args=0;
    
    for(format_token_listt::const_iterator it=token_list.begin();
        it!=token_list.end();
        it++)
    {
      if(it->type==format_tokent::STRING)
      {
        const exprt &arg = arguments[argument_start_inx+args];
        const typet &arg_type = ns.follow(arg.type());
        
        if(arg.id()!=ID_string_constant) // we don't need to check constants
        {
          goto_programt::targett assertion=dest.add_instruction();
          assertion->source_location=target->source_location;
          assertion->source_location.set_property_class("string");
          std::string comment("zero-termination of string argument of ");
          comment += function_name;
          assertion->source_location.set_comment(comment);
          
          exprt temp(arg);
          
          if(arg_type.id()!=ID_pointer)
          {
            index_exprt index;
            index.array()=temp;
            index.index()=gen_zero(index_type());
            index.type()=arg_type.subtype();            
            temp=address_of_exprt(index);            
          }
          
          assertion->make_assertion(is_zero_string(temp));
        }
      }
      
      if(it->type!=format_tokent::TEXT && 
         it->type!=format_tokent::UNKNOWN) args++;
      
      if(find(it->flags.begin(), it->flags.end(), format_tokent::ASTERISK)!=
         it->flags.end())
        args++; // just eat the additional argument          
    }
  }
  else // non-const format string
  {
    goto_programt::targett format_ass=dest.add_instruction();
    format_ass->make_assertion(is_zero_string(arguments[1]));
    format_ass->source_location=target->source_location;
    format_ass->source_location.set_property_class("string");
    std::string comment("zero-termination of format string of ");
    comment += function_name;
    format_ass->source_location.set_comment(comment);
    
    for(unsigned i=2; i<arguments.size(); i++)
    {
      const exprt &arg = arguments[i];
      const typet &arg_type=ns.follow(arguments[i].type());
      
      if(arguments[i].id()!=ID_string_constant &&
         is_string_type(arg_type))
      {
        goto_programt::targett assertion=dest.add_instruction();        
        assertion->source_location=target->source_location;
        assertion->source_location.set_property_class("string");
        std::string comment("zero-termination of string argument of ");
        comment += function_name;
        assertion->source_location.set_comment(comment);
        
        exprt temp(arg);
                  
        if(arg_type.id()!=ID_pointer)
        {
          index_exprt index;
          index.array()=temp;
          index.index()=gen_zero(index_type());
          index.type()=arg_type.subtype();            
          temp=address_of_exprt(index);            
        }
        
        assertion->make_assertion(is_zero_string(temp));
      }
    }
  }
}
Exemple #7
0
int main(int argc, char * const *argv1)
{
    int ch;
    const char *arff_fn = 0;
    const char *text_fn = 0;
    string *xml_fn = 0;
    const char *audit_file = 0;
    bool opt_x = false;
    string command_line = xml::make_command_line(argc,argv1);
    bool opt_zap = false;
    u_int sector_size=512;			// defaults to 512; may be changed by AFF

    struct timeval tv0;
    struct timeval tv1;
    gettimeofday(&tv0,0);

    TSK_TCHAR * const *argv;

#ifdef TSK_WIN32
	char *opt_arg = NULL;
	char *argv_0 = NULL;


	argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv == NULL) {
		fprintf(stderr,"Error getting wide arguments\n");
		exit(1);
	}
#else
	argv = (TSK_TCHAR * const*) argv1;
#endif
	
    while ((ch = GETOPT(argc, argv, _TSK_T("A:a:C:dfG:gmv1IMX:S:T:VZn:c:b:xOzh?"))) > 0 ) { // s: removed
	switch (ch) {
	case _TSK_T('1'): opt_sha1 = true;break;
	case _TSK_T('m'):
	    opt_body_file = 1;
	    opt_sha1 = 0;
	    opt_md5  = 1;
	    t = stdout;
	    break;
	case _TSK_T('A'):
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		arff_fn = opt_arg;
#else
		arff_fn = OPTARG;
#endif
		break;
	case _TSK_T('C'): file_count_max = TATOI(OPTARG);break;
	case _TSK_T('d'): opt_debug++; break;
	case _TSK_T('f'): opt_magic = true;break;
	case _TSK_T('g'): opt_no_data = true; break;
  case _TSK_T('b'): opt_get_fragments = false; break;
	case _TSK_T('G'): opt_maxgig = TATOI(OPTARG);break;
	case _TSK_T('h'): usage(); break;
	case _TSK_T('I'): opt_ignore_ntfs_system_files=true;break;
	case _TSK_T('M'): opt_md5 = true;
	case _TSK_T('O'): opt_allocated_only=true; break;
	case _TSK_T('S'):
            opt_sector_hash = true;
            sectorhash_size = TATOI(OPTARG); break;
	case _TSK_T('T'):
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		text_fn = opt_arg;
#else
		text_fn = OPTARG;
#endif
		break;
	case _TSK_T('V'): print_version();exit(0);
	case _TSK_T('X'): 
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		xml_fn = new string(opt_arg);
#else
		xml_fn = new string(OPTARG);
#endif
		break;
	case _TSK_T('x'): opt_x = true;break;
	case _TSK_T('Z'): opt_zap = true;break;
	case _TSK_T('a'): 
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		audit_file = opt_arg;
#else
		audit_file = OPTARG;
#endif
		break;
	case _TSK_T('c'): 
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		config_file = opt_arg;
#else
		config_file = OPTARG;
#endif		
		break;
	case _TSK_T('n'):
		
#ifdef TSK_WIN32
		convert(OPTARG, &opt_arg);
		namelist.push_back(opt_arg);
#else
		namelist.push_back(OPTARG);
#endif
		break;
	    //case 's': save_outdir = optarg; opt_save = true; break;
	case _TSK_T('v'): tsk_verbose++; break; 			// sleuthkit option
	case _TSK_T('z'): opt_sha1=false;opt_md5=false;break;
	case _TSK_T('?'): usage();break;
	default:
	    fprintf(stderr, "Invalid argument: %s\n", argv[OPTIND]);
	    usage();
	}
    }

    if (OPTIND >= argc) usage();
    argc -= OPTIND;
	argv += OPTIND;
	argv1 += OPTIND;

#ifdef TSK_WIN32
		convert(argv[0],&argv_0);
		const char *filename = argv_0;
#else
	const char *filename = argv[0];
#endif
    opt_parent_tracking = true;

    if(!filename){
	errx(1,"must provide filename");
    }
    if(opt_no_data && (opt_md5 || opt_sha1 || opt_save || opt_magic)) {
      errx(1, "-g conflicts with options requiring data access (-z may be needed)");
    }

    if(opt_save){
	if(access(save_outdir.c_str(),F_OK)){
	    #ifdef WIN32
	    if(mkdir(save_outdir.c_str())) {
	    #else
	    if(mkdir(save_outdir.c_str(),0777)){
	    #endif
		err(1,"Cannot make directory: %s",save_outdir.c_str());
	    }
	}
	if(access(save_outdir.c_str(),R_OK)){
	    err(1,"Cannot access directory: %s",save_outdir.c_str());
	}
    }

    if(text_fn){
	if(access(text_fn,F_OK)==0) errx(1,"%s: file exists",text_fn);
	t = fopen(text_fn,"w");
	if(!t) err(1,"%s",text_fn);
    }

    if(arff_fn){
	if(access(arff_fn,F_OK)==0) errx(1,"%s: file exists",arff_fn);
	a = new arff("fiwalk");		// the ARFF output object
	a->set_outfile(arff_fn);
    }

    /* XML initialization */

    if(opt_x){
	x = new xml();			// default to stdout
    }
    if(xml_fn){
	if(*xml_fn == "0"){
	    string newfn = filename;
	    *xml_fn = newfn.substr(0,newfn.rfind(".")) + ".xml";
	}
	if(x) errx(1,"Cannot write XML to stdout and file at same time\n");
	if(access(xml_fn->c_str(),F_OK)==0){
	    if(opt_zap){
		if(unlink(xml_fn->c_str())){
		    err(1,"%s: file exists and cannot unlink",xml_fn->c_str());
		}
	    }
	    else{
		errx(1,"%s: file exists",xml_fn->c_str());
	    }
	}
	x = new xml(*xml_fn,true);	// we will make DTD going to a file
    }
	
    /* If no output file has been specified, output text to stdout */
    if(a==0 && x==0 && t==0){
	t = stdout;
    }

    if(strstr(filename,".aff") || strstr(filename,".afd") || strstr(filename,".afm")){
#ifndef HAVE_LIBAFFLIB
	fprintf(stderr,"ERROR: fiwalk was compiled without AFF support.\n");
	exit(0);
#else
#endif
    }

    /* If we are outputing ARFF, create the ARFF object and set the file types for the file system metadata */
    if(a){
	a->add_attribute("id",arff::NUMERIC);
	a->add_attribute("partition",arff::NUMERIC);
	a->add_attribute("filesize",arff::NUMERIC);
	a->add_attribute("mtime",arff::DATE);
	a->add_attribute("ctime",arff::DATE);
	a->add_attribute("atime",arff::DATE);
	a->add_attribute("fragments",arff::NUMERIC);
	a->add_attribute("frag1startsector",arff::NUMERIC);
	a->add_attribute("frag2startsector",arff::NUMERIC);
	a->add_attribute("filename",arff::STRING);
	if(opt_md5) a->add_attribute("md5",arff::STRING);
	if(opt_sha1) a->add_attribute("sha1",arff::STRING);
    }

    /* output per-run metadata for XML output */
    if(x){
	/* Output Dublin Core information */
	x->push("dfxml",
		"\n  xmlns='http://www.forensicswiki.org/wiki/Category:Digital_Forensics_XML'"
		"\n  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
		"\n  xmlns:dc='http://purl.org/dc/elements/1.1/'"
		"\n  version='1.0'" );
	x->push("metadata", "");
	x->xmlout("dc:type","Disk Image",fw_empty,false);
	x->pop();
	    
	/* Output carver information per photorec standard */
	x->add_DFXML_creator("fiwalk",tsk_version_get_str(),command_line);
    }

    /* Can't use comment until after here... */
    if(config_file){
	comment("Reading configuration file %s",config_file);
	config_read(config_file);    /* Read the configuration file */
    }

    /* Check that we have a valid file format */
    if(x) x->push("source");
    partition_info("image_filename",filename);

    if(!x){
	partition_info("fiwalk_version",tsk_version_get_str());
	partition_info("start_time",mytime());
	partition_info("tsk_version",tsk_version_get_str());
    }
    if(x) x->pop();

    if (opt_debug) printf("calling tsk_img_open(%s)\n",filename);

#ifdef SIGINFO
    signal(SIGINFO,sig_info);
#endif

#ifdef TSK_WIN32
    int count = process_image_file(argc,argv1,audit_file,sector_size);
    if(count<=0 || sector_size!=512){
	comment("Retrying with 512 byte sector size.");
	count = process_image_file(argc,argv1,audit_file,512);
    }
#else
    int count = process_image_file(argc,argv,audit_file,sector_size);
    if(count<=0 || sector_size!=512){
	comment("Retrying with 512 byte sector size.");
	count = process_image_file(argc,argv,audit_file,512);
    }
#endif

    /* Calculate time elapsed (reported as a comment and with rusage) */
    struct timeval tv;
    char tvbuf[64];
    gettimeofday(&tv1,0);
    tv.tv_sec = tv1.tv_sec - tv0.tv_sec;
    if(tv1.tv_usec > tv0.tv_usec){
        tv.tv_usec = tv1.tv_usec - tv0.tv_usec;
    } else {
        tv.tv_sec--;
        tv.tv_usec = (tv1.tv_usec+1000000) - tv0.tv_usec;
    }
    sprintf(tvbuf, "%d.%06d",(int)tv.tv_sec, (int)tv.tv_usec);

    comment("clock: %s",tvbuf);

#ifdef HAVE_SYS_RESOURCE_H
#ifdef HAVE_GETRUSAGE
    /* Print usage information */
    struct rusage ru;
    memset(&ru,0,sizeof(ru));
    if(getrusage(RUSAGE_SELF,&ru)==0){
	if(x) x->push("rusage");
	partition_info("utime",ru.ru_utime);
	partition_info("stime",ru.ru_stime);
	partition_info("maxrss",ru.ru_maxrss);
	partition_info("minflt",ru.ru_minflt);
	partition_info("majflt",ru.ru_majflt);
	partition_info("nswap",ru.ru_nswap);
	partition_info("inblock",ru.ru_inblock);
	partition_info("oublock",ru.ru_oublock);
	partition_info("clocktime",tv);
	comment("stop_time: %s",cstr(mytime()));
	if(x) x->pop();
    }
#endif
#endif

    // *** Added <finished time="(time_t)" duration="<seconds>" />

    if(a){
	a->write();
	delete a;
    }

    if(t) comment("=EOF=");
    if(x) {
	x->pop();			// <dfxml>
	x->close();
	delete(x);
    }
    exit(0);
}
Exemple #8
0
bool ZInstrument::loadSfz(const QString& s)
      {
      _program = 0;
      QFileInfo fi(s);
      QString path = fi.absolutePath();

      QStringList fileContents = readFile(s);

      if (fileContents.empty()) {
            return false;
            }

      SfzControl c;
      c.init();
      c.defines.clear();
      for (int i = 0;i < 128; i++)
            c.set_cc[i] = -1;

      int idx = 0;
      bool inBlockComment = false;
      // preprocessor
      while(idx < fileContents.size()) {
            QRegularExpression findWithSpaces("\"(.+)\"");
            QRegularExpression comment("//.*$");
            QRegularExpression trailingSpacesOrTab("^[\\s\\t]*");
            QRegularExpressionMatch foundWithSpaces;
            QString curLine = fileContents[idx];
            QString curLineCopy = curLine;
            bool nextIsImportant = false;
            int idxBlockComment = 0;
            int from = 0;

            for (QChar chr : curLineCopy) {
                  bool terminated = false;

                  if (nextIsImportant) {
                        nextIsImportant = false;
                        if (inBlockComment && chr == '/') { // found block end
                              inBlockComment = false;
                              terminated = true;
                              curLine.remove(from, idxBlockComment - from + 1);
                              idxBlockComment = from - 1;
                              }
                        else if (!inBlockComment && chr == '*') { // found block start
                              inBlockComment = true;
                              terminated = true;
                              from = idxBlockComment - 1;
                              }
                        }

                  if (!terminated && inBlockComment && chr == '*')
                        nextIsImportant = true;
                  else if (!terminated && !inBlockComment && chr == '/')
                        nextIsImportant = true;

                  idxBlockComment++;
                  }

            if (inBlockComment)
                  curLine.remove(from, curLine.size() - from);

            curLine = curLine.remove(comment);
            curLine.remove(trailingSpacesOrTab);
            fileContents[idx] = curLine;

            if (curLine.startsWith("#define")) {
                  QStringList define = curLine.split(" ");
                  foundWithSpaces = findWithSpaces.match(curLine);
                  if (define.size() == 3)
                        c.defines.insert(std::pair<QString, QString>(define[1], define[2]));
                  else if(foundWithSpaces.hasMatch())
                        c.defines.insert(std::pair<QString, QString>(define[1], foundWithSpaces.captured(1)));
                  fileContents.removeAt(idx);
                  }
            else if (curLine.startsWith("#include")) {
                  foundWithSpaces = findWithSpaces.match(curLine);
                  if (foundWithSpaces.hasMatch()) {
                        QString newFilename = foundWithSpaces.captured(1);

                        for(auto define : c.defines) {
                              newFilename.replace(define.first, define.second);
                              }

                        QStringList newFileContents = readFile(path + "/" + newFilename);
                        if (newFileContents.empty())
                              return false;

                        int offset = 1;
                        for (QString newFileLine : newFileContents) {
                              fileContents.insert(idx+offset, newFileLine);
                              offset++;
                              }

                        fileContents.removeAt(idx);
                        }
                  }
            else if (curLine.isEmpty())
                  fileContents.removeAt(idx);
            else
                  idx++;
            }

      int total = fileContents.size();
      SfzRegion r;
      SfzRegion g;      // group
      SfzRegion glob;
      r.init(path);
      g.init(path);
      glob.init(path);

      bool groupMode = false;
      bool globMode = false;
      zerberus->setLoadProgress(0);

      for (int idx = 0; idx < fileContents.size(); idx++) {
            QString curLine = fileContents[idx];
            zerberus->setLoadProgress(((qreal) idx * 100) /  (qreal) total);

            if (zerberus->loadWasCanceled())
                  return false;
            if (curLine.startsWith("<global>")) {
                  if (!globMode && !groupMode && !r.isEmpty())
                        addRegion(r);
                  glob.init(path);
                  g.init(path); // global also resets group
                  r.init(path);
                  globMode = true;
                  }
            if (curLine.startsWith("<group>")) {
                  if (!groupMode && !globMode && !r.isEmpty())
                        addRegion(r);
                  g.init(path);
                  if (globMode) {
                        glob = r;
                        globMode = false;
                        }
                  else {
                        r = glob; // initialize group with global values
                        }
                  groupMode = true;
                  curLine = curLine.mid(7);
                  }
            else if (curLine.startsWith("<region>")) {
                  if (groupMode) {
                        g = r;
                        groupMode = false;
                        }
                  else if (globMode) {
                        glob = r;
                        g = glob;
                        globMode = false;
                        }
                  else {
                        if (!r.isEmpty())
                              addRegion(r);
                        r = g;  // initialize next region with group values
                        }
                  curLine = curLine.mid(8);
                  }
            else if (curLine.startsWith("<control>"))
                  c.init();

            QRegularExpression re("\\s?([\\w\\$]+)="); // defines often use the $-sign
            QRegularExpressionMatchIterator i = re.globalMatch(curLine);

            while (i.hasNext()) {
                  QRegularExpressionMatch match = i.next();
                  int si = match.capturedEnd();
                  int ei;
                  if (i.hasNext()) {
                        QRegularExpressionMatch nextMatch = i.peekNext();
                        ei = nextMatch.capturedStart();
                        }
                  else
                        ei = curLine.size();
                  QString s = curLine.mid(si, ei-si);
                  r.readOp(match.captured(1), s, c);
                  }
            }

      for (int i = 0; i < 128; i++)
            _setcc[i] = c.set_cc[i];

      zerberus->setLoadProgress(100);
      if (!groupMode && !globMode && !r.isEmpty())
            addRegion(r);
      return true;
      }
Exemple #9
0
void
match_trail(void)
{	int i, a, nst;
	Element *dothis;
	char snap[512], *q;

	/*
	 * if source model name is leader.pml
	 * look for the trail file under these names:
	 *	leader.pml.trail
	 *	leader.pml.tra
	 *	leader.trail
	 *	leader.tra
	 */

	if (trailfilename)
	{	if (strlen(*trailfilename) < sizeof(snap))
		{	strcpy(snap, (const char *) *trailfilename);
		} else
		{	fatal("filename %s too long", *trailfilename);
		}
	} else
	{	if (ntrail)
			sprintf(snap, "%s%d.trail", oFname->name, ntrail);
		else
			sprintf(snap, "%s.trail", oFname->name);
	}

	if ((fd = fopen(snap, "r")) == NULL)
	{	snap[strlen(snap)-2] = '\0';	/* .tra */
		if ((fd = fopen(snap, "r")) == NULL)
		{	if ((q = strchr(oFname->name, '.')) != NULL)
			{	*q = '\0';
				if (ntrail)
					sprintf(snap, "%s%d.trail",
						oFname->name, ntrail);
				else
					sprintf(snap, "%s.trail",
						oFname->name);
				*q = '.';

				if ((fd = fopen(snap, "r")) != NULL)
					goto okay;

				snap[strlen(snap)-2] = '\0';	/* last try */
				if ((fd = fopen(snap, "r")) != NULL)
					goto okay;
			}
			printf("spin: cannot find trail file\n");
			alldone(1);
	}	}
okay:
	if (xspin == 0 && newer(oFname->name, snap))
	printf("spin: warning, \"%s\" is newer than %s\n",
		oFname->name, snap);

	Tval = 1;

	/*
	 * sets Tval because timeouts may be part of trail
	 * this used to also set m_loss to 1, but that is
	 * better handled with the runtime -m flag
	 */

	hookup();

	while (fscanf(fd, "%d:%d:%d\n", &depth, &pno, &nst) == 3)
	{	if (depth == -2) { start_claim(pno); continue; }
		if (depth == -4) { merger = 1; ana_src(0, 1); continue; }
		if (depth == -1)
		{	if (verbose)
			{	if (columns == 2)
				dotag(stdout, " CYCLE>\n");
				else
				dotag(stdout, "<<<<<START OF CYCLE>>>>>\n");
			}
			continue;
		}

		if (cutoff > 0 && depth >= cutoff)
		{	printf("-------------\n");
			printf("depth-limit (-u%d steps) reached\n", cutoff);
			break;
		}

		if (Skip_claim && pno == 0) continue;

		for (dothis = Al_El; dothis; dothis = dothis->Nxt)
		{	if (dothis->Seqno == nst)
				break;
		}
		if (!dothis)
		{	printf("%3d: proc %d, no matching stmnt %d\n",
				depth, pno - Have_claim, nst);
			lost_trail();
		}

		i = nproc - nstop + Skip_claim;

		if (dothis->n->ntyp == '@')
		{	if (pno == i-1)
			{	run = run->nxt;
				nstop++;
				if (verbose&4)
				{	if (columns == 2)
					{	dotag(stdout, "<end>\n");
						continue;
					}
					if (Have_claim && pno == 0)
					printf("%3d: claim terminates\n",
						depth);
					else
					printf("%3d: proc %d terminates\n",
						depth, pno - Have_claim);
				}
				continue;
			}
			if (pno <= 1) continue;	/* init dies before never */
			printf("%3d: stop error, ", depth);
			printf("proc %d (i=%d) trans %d, %c\n",
				pno - Have_claim, i, nst, dothis->n->ntyp);
			lost_trail();
		}

		if (!xspin && (verbose&32))
		{	printf("i=%d pno %d\n", i, pno);
		}

		for (X = run; X; X = X->nxt)
		{	if (--i == pno)
				break;
		}

		if (!X)
		{	if (verbose&32)
			{	printf("%3d: no process %d (step %d)\n", depth, pno - Have_claim, nst);
				printf(" max %d (%d - %d + %d) claim %d",
					nproc - nstop + Skip_claim,
					nproc, nstop, Skip_claim, Have_claim);
				printf("active processes:\n");
				for (X = run; X; X = X->nxt)
				{	printf("\tpid %d\tproctype %s\n", X->pid, X->n->name);
				}
				printf("\n");
				continue;
			} else
			{	printf("%3d:\tproc  %d (?) ", depth, pno);
				lost_trail();
			}
		} else
		{	X->pc  = dothis;
		}

		lineno = dothis->n->ln;
		Fname  = dothis->n->fn;

		if (dothis->n->ntyp == D_STEP)
		{	Element *g, *og = dothis;
			do {
				g = eval_sub(og);
				if (g && depth >= jumpsteps
				&& ((verbose&32) || ((verbose&4) && not_claim())))
				{	if (columns != 2)
					{	p_talk(og, 1);

						if (og->n->ntyp == D_STEP)
						og = og->n->sl->this->frst;

						printf("\t[");
						comment(stdout, og->n, 0);
						printf("]\n");
					}
					if (verbose&1) dumpglobals();
					if (verbose&2) dumplocal(X);
					if (xspin) printf("\n");
				}
				og = g;
			} while (g && g != dothis->nxt);
			if (X != NULL)
			{	X->pc = g?huntele(g, 0, -1):g;
			}
		} else
void petabricks::CodeGenerator::mkCreateGpuSpatialMethodCallTask(
    const std::string& transname,
    const std::string& taskname, 
    const std::string& objname, 
    const std::string& methodname, 
    const SimpleRegion& region, 
    std::vector<RegionNodeGroup>& regionNodesGroups, 
    int nodeID, 
    int gpuCopyOut, 
    RegionList to, 
    bool divisible) {
  std::string taskclass
;
  int dim_int = region.totalDimensions();
  std::string lastdim = jalib::XToString(dim_int - 1);
  std::string max = region.maxCoord()[dim_int - 1]->toString();
  std::string min = region.minCoord()[dim_int - 1]->toString();

  if(!divisible) {
    taskclass = "petabricks::CreateGpuSpatialMethodCallTask<"+objname
      + ", " + jalib::XToString(region.totalDimensions())
      + ", &" + objname + "::" + methodname + TX_OPENCL_POSTFIX + "_createtasks"
      + ">";
    //beginIf(min+"<"+max);
    comment("MARKER 6");
    write("IndexT _tmp_begin[] = {" + region.getIterationLowerBounds() + "};");
    write("IndexT _tmp_end[] = {"   + region.getIterationUpperBounds() + "};");
    write("RegionNodeGroupMapPtr groups = new RegionNodeGroupMap();");
    for(std::vector<RegionNodeGroup>::iterator group = regionNodesGroups.begin(); group != regionNodesGroups.end(); ++group){
      write("{");
      incIndent();
      write("std::set<int> ids;");
      for(std::vector<int>::iterator id = group->nodeIDs().begin(); id != group->nodeIDs().end(); ++id){
	write("ids.insert("+jalib::XToString(*id)+");");
      }
      write("groups->insert(RegionNodeGroup(\""+group->matrixName()+"\",ids));");
      decIndent();
      write("}");
    }
    write(taskname+" = new "+taskclass+"(this,_tmp_begin, _tmp_end, "+jalib::XToString(nodeID)+", groups, "+jalib::XToString(gpuCopyOut)+");");
    //endIf();

    return;
  }

  std::string n_div = "cont_" + jalib::XToString(_contCounter++);
  write(taskname + " = new petabricks::MethodCallTask<"+_curClass+", &"+_curClass+"::"+n_div+">( this );");

  // Add divider function
  CodeGenerator helper = forkhelper();
  helper.beginFunc("DynamicTaskPtr", n_div);
  helper.write("DynamicTaskPtr _fini = new NullDynamicTask();");

  // Assign the gpu-cpu division point.
  helper.write("ElementT gpu_ratio = "+transname+"_gpuratio/8.0;");

  std::string div = "div";
  RegionPtr proxy = to.front();
  helper.write("IndexT totalRow = "+proxy->matrix()->name()+".size("+jalib::XToString(dim_int - 1)+");");
  helper.write("IndexT div = ceil(gpu_ratio * totalRow);");
  helper.beginIf("div > " + max);
  helper.write("div = "+max+";");
  helper.endIf();

  // GPU

  taskclass = "petabricks::CreateGpuSpatialMethodCallTask<"+objname
              + ", " + jalib::XToString(dim_int)
              + ", &" + objname + "::" + methodname + TX_OPENCL_POSTFIX + "_createtasks"
              + ">";
  helper.comment("MARKER 6");
  
  //helper.beginIf(min+" < div");
  helper.write("IndexT _gpu_begin[] = {" + region.getIterationLowerBounds() + "};");
  helper.write("IndexT _gpu_end[] = {" + region.getIterationMiddleEnd(div) + "};");
  helper.write("RegionNodeGroupMapPtr groups = new RegionNodeGroupMap();");

  for(std::vector<RegionNodeGroup>::iterator group = regionNodesGroups.begin(); group != regionNodesGroups.end(); ++group){
    helper.write("{");
    helper.incIndent();
    helper.write("std::set<int> ids;");
    for(std::vector<int>::iterator id = group->nodeIDs().begin(); id != group->nodeIDs().end(); ++id){
      helper.write("ids.insert("+jalib::XToString(*id)+");");
    }
    helper.write("groups->insert(RegionNodeGroup(\""+group->matrixName()+"\",ids));");
    helper.decIndent();
    helper.write("}");
  }

  helper.write("DynamicTaskPtr gpu_task = new "+taskclass+"(this,_gpu_begin, _gpu_end, "+jalib::XToString(nodeID)+", groups, "+jalib::XToString(gpuCopyOut)+");");
  helper.write("gpu_task->enqueue();");
  helper.write("_fini->dependsOn(gpu_task);");
  //helper.endIf();

  // CPU
  taskclass = "petabricks::SpatialMethodCallTask<CLASS"
              ", " + jalib::XToString(dim_int)
              + ", &CLASS::" + methodname + "_workstealing_wrap"
    //+ ", &CLASS::" + methodname + "_workstealing"
              + ">";
  helper.beginIf("div < " + max);
  helper.beginIf("div < " + min);
  helper.write("div = "+min+";");
  helper.endIf();
  helper.comment("MARKER 6");
  helper.write("IndexT _cpu_begin[] = {" + region.getIterationMiddleBegin(div) + "};");
  helper.write("IndexT _cpu_end[] = {"   + region.getIterationUpperBounds() + "};");
  helper.write("DynamicTaskPtr cpu_task = new "+taskclass+"(this,_cpu_begin, _cpu_end);");
  helper.write("cpu_task->enqueue();");
  helper.write("_fini->dependsOn(cpu_task);");
  helper.endIf();
  
  helper.write("return _fini;");
  helper.endFunc();
}
Exemple #11
0
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t poolamc, poollo;
 mps_thr_t thread;
 mps_root_t root;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t apamc, aplo;

 mycell *a, *b, *c, *d, *e, *f, *g;

 int i;
 int j;

 RC;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE),
      "create arena");

 die(mps_thread_reg(&thread, arena), "register thread");
 die(mps_root_create_reg(&root, arena, mps_rank_ambig(), 0, thread,
                         mps_stack_scan_ambig, stackpointer, 0),
     "create root");

 die(mps_fmt_create_A(&format, arena, &fmtA), "create format");
 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 die(mmqa_pool_create_chain(&poolamc, arena, mps_class_amc(), format, chain),
     "create pool(amc)");

 cdie(
  mps_pool_create(&poollo, arena, mps_class_lo(), format),
  "create pool");

 cdie(
  mps_ap_create(&apamc, poolamc, mps_rank_exact()),
  "create ap");
 cdie(
  mps_ap_create(&aplo, poollo, mps_rank_exact()),
  "create ap(lo)");

 b = allocone(apamc, 1, 1);

 for (j=1; j<100; j++) {
  comment("%i of 100.", j);
  UC;
  a = allocone(apamc, 5, 1);
  b = a;
  c = a;
  d = a;
  e = a;
  f = a;
  g = a;

  for (i=1; i<5000; i++) {
   UC;
   c = allocone(apamc, 20, 1);
   d = allocone(apamc, 20, 1);
   if (ranint(8) == 0) e = c;
   if (ranint(8) == 0) f = c;
   if (ranint(8) == 0) g = c;
   UC;
   setref(b, 0, c);
   UC;
   setref(c, 1, d);
   UC;
   setref(c, 2, e);
   UC;
   setref(c, 3, f);
   UC;
   setref(c, 4, g);
   UC;
   b = c;
  }
  DC;
  DMC;
 }

 mps_ap_destroy(apamc);
 mps_ap_destroy(aplo);
 comment("Destroyed aps.");
 mps_pool_destroy(poolamc);
 mps_pool_destroy(poollo);
 comment("Destroyed pools.");
 mps_chain_destroy(chain);
 mps_fmt_destroy(format);
 mps_root_destroy(root);
 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
Exemple #12
0
Fichier : 77.c Projet : bhanug/mps
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t poolamc, poolawl;
 mps_thr_t thread;
 mps_root_t root, root1;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t apamc, apawl;

 mycell *a, *b, *c, *d, *e, *f, *g;

 int i;
 int j;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE),
      "create arena");

 die(mps_thread_reg(&thread, arena), "register thread");
 die(mps_root_create_reg(&root, arena, mps_rank_ambig(), 0, thread,
                          mps_stack_scan_ambig, stackpointer, 0),
      "create root");

 cdie(
  mps_root_create_table(&root1,arena,mps_rank_ambig(),0,&exfmt_root,1),
  "create table root");

 die(mps_fmt_create_A(&format, arena, &fmtA), "create format");
 die(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 die(mmqa_pool_create_chain(&poolamc, arena, mps_class_amc(), format, chain),
     "create pool(amc)");

 die(mps_pool_create(&poolawl, arena, mps_class_awl(), format, getassociated),
     "create pool(awl)");

 die(mps_ap_create(&apawl, poolawl, mps_rank_exact()),
     "create ap(awl)");

 die(mps_ap_create(&apamc, poolamc, mps_rank_exact()),
     "create ap(amc)");

 b = allocone(apamc, 1, mps_rank_exact());

 for (j=1; j<=10; j++) {
  comment("%i of 10.", j);
  a = allocone(apamc, 5, mps_rank_exact());
  b = a;
  c = a;
  d = a;
  e = a;
  f = a;
  g = a;

  for (i=1; i<=3000; i++) {
   c = allocone(apamc, 20, mps_rank_exact());
   d = allocone(apawl, 20, mps_rank_exact());
   if (ranint(8) == 0) e = c;
   if (ranint(8) == 0) f = c;
   if (ranint(8) == 0) g = c;
   setref(b, 0, c);
   setref(c, 1, d);
   setref(c, 2, e);
   setref(c, 3, f);
   setref(c, 4, g);
   b = c;
  }
 }

 mps_arena_park(arena);
 mps_ap_destroy(apawl);
 mps_ap_destroy(apamc);
 mps_pool_destroy(poolamc);
 mps_pool_destroy(poolawl);
 mps_chain_destroy(chain);
 mps_fmt_destroy(format);
 mps_root_destroy(root);
 mps_root_destroy(root1);
 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
Exemple #13
0
Fichier : 109.c Projet : bhanug/mps
static void test(void)
{
 mps_pool_t poolamc, poolawl, poolamcz;
 mps_thr_t thread;
 mps_root_t root0, root1;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t apamc, apawl, apamcz;

 mycell *a, *b, *c, *d, *z;

 long int j;

 cdie(mps_arena_create_k(&arena, mps_arena_class_vm(), mps_args_none),
      "create arena");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(mps_root_create_reg(&root0, arena, mps_rank_ambig(), 0, thread,
                          mps_stack_scan_ambig, stackpointer, 0),
      "create root");
 
 cdie(mps_root_create_table(&root1, arena, mps_rank_ambig(), 0,
                            (mps_addr_t*)&exfmt_root, 1),
      "create table root");

 cdie(mps_fmt_create_A(&format, arena, &fmtA),
      "create format");

 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 cdie(mmqa_pool_create_chain(&poolamc, arena, mps_class_amc(), format, chain),
     "create pool(amc)");

 cdie(mps_pool_create(&poolawl, arena, mps_class_awl(), format, getassociated),
      "create pool(awl)");

 cdie(mmqa_pool_create_chain(&poolamcz, arena, mps_class_amcz(), format, chain),
     "create pool(amcz)");

 cdie(mps_ap_create(&apawl, poolawl, mps_rank_weak()),
      "create ap(awl)");

 cdie(mps_ap_create(&apamc, poolamc, mps_rank_exact()),
      "create ap(amc)");
 
 cdie(mps_ap_create(&apamcz, poolamcz, mps_rank_exact()),
      "create ap(amcz)");

 mps_message_type_enable(arena, mps_message_type_finalization());

 /* register loads of objects for finalization (1000*4) */

 a = allocone(apamc, 2, 1);
 b = a;

 for (j=0; j<1000; j++) {
  a = allocone(apamc, 2, mps_rank_exact());
  c = allocone(apawl, 2, mps_rank_weak());
  d = allocone(apamcz, 2, mps_rank_exact()); /* rank irrelevant here! */
  mps_finalize(arena, (mps_addr_t*)&a);
  mps_finalize(arena, (mps_addr_t*)&c);
  mps_finalize(arena, (mps_addr_t*)&d);
  mps_finalize(arena, (mps_addr_t*)&d);
  final_count += 4;
  setref(a, 0, b);
  setref(a, 1, c);
  setref(c, 1, d);
  b = a;
 }

 /* throw them all away and collect everything */

 a = NULL;
 b = NULL;
 c = NULL;
 d = NULL;

 mps_arena_collect(arena);

 while (mps_message_poll(arena)) {
  finalpoll(&z, FINAL_DISCARD);
 }

 /* How many are left? (Ideally, this would be 0 but there's no guarantee.) */

 report("count1", "%i", final_count);

 /* now to test leaving messages open for a long time! */

 for (j=0; j<1000; j++) {
  comment("%d of 1000", j+1);
  a = allocone(apamc, 10000, mps_rank_exact());
  mps_finalize(arena, (mps_addr_t*)&a);
  final_count +=1;
  comment("finalize");
  finalpoll(&z, FINAL_QUEUE);
 }

 comment("reregister");

 for (j=0; j<500; j++) {
  comment("%d of 500", j+1);
  qpoll(&z, FINAL_REREGISTER);
 }

 b = a;
 z = a;

 for (j=0; j<1000; j++) {
  comment("%d of 1000", j+1);
  finalpoll(&z, FINAL_QUEUE);
  qpoll(&z, FINAL_STORE);
  a = allocone(apamc, 2, mps_rank_exact());
  setref(z, 0, b);
  setref(a, 1, z);
  b = a;
 }


 for (j=0; j<1000; j++) {
  a = allocone(apamc, 2, mps_rank_exact());
  qpoll(&z, FINAL_DISCARD);
  finalpoll(&z, FINAL_DISCARD);
  setref(a, 0, b);
  b = a;
 }

 /* Force old objects to be killed */

 while (qmt() == 0) {
  qpoll(&z, FINAL_DISCARD);
 }

 mps_root_destroy(root0);
 mps_root_destroy(root1);
 comment("Destroyed roots.");

 mps_arena_collect(arena);
 comment("Collected arena.");

 while (mps_message_poll(arena)) {
  finalpoll(&z, FINAL_DISCARD);
 }

 report("count2", "%d", final_count);

 mps_arena_park(arena);
 mps_ap_destroy(apawl);
 mps_ap_destroy(apamc);
 mps_ap_destroy(apamcz);
 comment("Destroyed aps.");

 mps_pool_destroy(poolamc);
 mps_pool_destroy(poolawl);
 mps_pool_destroy(poolamcz);
 comment("Destroyed pools.");

 mps_chain_destroy(chain);
 mps_fmt_destroy(format);
 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
Exemple #14
0
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t pool;
 mps_thr_t thread;
 mps_root_t root;

 mps_chain_t chain;
 mps_fmt_t format;
 mps_ap_t ap;
 mps_addr_t p;
 mps_addr_t q;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE), "create arena");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(
  mps_root_create_reg(&root, arena, mps_rank_ambig(), 0, thread,
   mps_stack_scan_ambig, stackpointer, 0),
  "create root");

 cdie(
  mps_fmt_create_A(&format, arena, &fmtA),
  "create format");

 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 cdie(
  mps_pool_create(&pool, arena, mps_class_amc(), format, chain),
  "create pool");

 cdie(
  mps_ap_create(&ap, pool, mps_rank_exact()),
  "create ap");

 do
 {
  cdie(mps_reserve(&p, ap, 0x100), "Reserve: ");
  q = (mps_addr_t) ((char *)p + 0x10);
 }
 while (!mps_commit(ap, q, 0x100));
 comment("Committed.");

 mps_ap_destroy(ap);
 comment("Destroyed ap.");

 mps_pool_destroy(pool);
 comment("Destroyed pool.");

 mps_fmt_destroy(format);
 comment("Destroyed format.");

 mps_chain_destroy(chain);
 comment("Destroyed chain.");

 mps_root_destroy(root);
 comment("Destroyed root.");

 mps_thread_dereg(thread);
 comment("Deregistered thread.");

 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t poolamc;
 mps_thr_t thread;
 mps_root_t root, root2, root3, root4, root5, root6, root7, root1;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t apamc;

 typedef mycell * myroot;
 myroot a, b, c, d, e, f, g;

 int i;
 int j;

 RC;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE),
      "create arena");

 die(mps_thread_reg(&thread, arena), "register thread");

 cdie(
  mps_root_create_table(&root1, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&a, 1),
  "root");
 cdie(
  mps_root_create_table(&root2, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&b, 1),
  "root");
 cdie(
  mps_root_create_table(&root3, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&c, 1),
  "root");
 cdie(
  mps_root_create_table(&root4, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&d, 1),
  "root");
 cdie(
  mps_root_create_table(&root5, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&e, 1),
  "root");
 cdie(
  mps_root_create_table(&root6, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&f, 1),
  "root");
 cdie(
  mps_root_create_table(&root7, arena, MPS_RANK_EXACT, 0, (mps_addr_t*)&g, 1),
  "root");

 cdie(
  mps_root_create_table(&root, arena, MPS_RANK_EXACT, 0, &exfmt_root, 1),
  "create exfmt root");

 die(mps_fmt_create_A(&format, arena, &fmtA), "create format");
 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 die(mmqa_pool_create_chain(&poolamc, arena, mps_class_amc(), format, chain),
     "create pool");

 cdie(
  mps_ap_create(&apamc, poolamc, MPS_RANK_EXACT),
  "create ap");

 comment("parking...");
 mps_arena_park(arena);
 
 b = allocone(apamc, 1, 1);

 for (j=1; j<10; j++) {
  comment("%i of 10.", j);
  a = allocone(apamc, 5, 1);
  cutoff_id = getid(a);
  b = a;
  c = a;
  d = a;
  e = a;
  f = a;
  g = a;
  for (i=1; i<1000; i++) {
   c = allocone(apamc, 1000, 1);
   if (ranint(8) == 0) d = c;
   if (ranint(8) == 0) e = c;
   if (ranint(8) == 0) f = c;
   if (ranint(8) == 0) g = c;
   setref(c, 0, b);
   setref(c, 1, d);
   setref(c, 2, e);
   setref(c, 3, f);
   setref(c, 4, g);
   b = c;
  }

  for (i=1; i<1000; i++) {
   c = allocone(apamc, 1000, 1);
   if (ranint(8) == 0) d = c;
   if (ranint(8) == 0) e = c;
   if (ranint(8) == 0) f = c;
   if (ranint(8) == 0) g = c;
   setref(c, 0, b);
   setref(c, 1, d);
   setref(c, 2, e);
   setref(c, 3, f);
   setref(c, 4, g);
   b = c;
  }
  a = c;
  b = c;
  d = c;
  e = c;
  f = c;
  g = c;
  exfmt_root = c;
  mps_arena_collect(arena);
  comment(" reserved: %lu", (unsigned long) mps_arena_reserved(arena));
  comment("committed: %lu", (unsigned long) mps_arena_committed(arena));
  comment("calling amc_apply:");
  checkfrom(c);
  appcount = 0;
  apppadcount = 0;
  junk_size = 0;
  mps_amc_apply(poolamc, &test_apply, NULL, MAGICSIZE);
  comment("finished amc_apply");
  report("junksize", "%lu", (unsigned long) junk_size);
  report("appcount", "%ld", appcount);
  report("apppadcount", "%ld", apppadcount);
  RC;
 }

 mps_arena_release(arena);
 comment("released.");

 mps_ap_destroy(apamc);
 mps_pool_destroy(poolamc);
 mps_chain_destroy(chain);
 mps_fmt_destroy(format);

 mps_root_destroy(root);
 mps_root_destroy(root1);
 mps_root_destroy(root2);
 mps_root_destroy(root3);
 mps_root_destroy(root4);
 mps_root_destroy(root5);
 mps_root_destroy(root6);
 mps_root_destroy(root7);
 comment("Destroyed roots.");

 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
Exemple #16
0
/*===========================================================================*/
bool KVSMLImageObject::write( const std::string& filename )
{
    BaseClass::setFilename( filename );
    BaseClass::setSuccess( false );

    // XML document
    std::string comment(" Generated by kvs::KVSMLImageObject::write() ");
    kvs::XMLDocument document;
    document.InsertEndChild( kvs::XMLDeclaration("1.0") );
    document.InsertEndChild( kvs::XMLComment( comment.c_str() ) );

    // <KVSML>
    m_kvsml_tag.write( &document );

    // <Object type="ImageObject">
    m_object_tag.setType( "ImageObject" );
    if ( !m_object_tag.write( m_kvsml_tag.node() ) )
    {
        kvsMessageError( "Cannot write <%s>.", m_object_tag.name().c_str() );
        return false;
    }

    // <ImageObject width="xxx" height="xxx">
    kvs::kvsml::ImageObjectTag image_object_tag;
    image_object_tag.setWidth( m_width );
    image_object_tag.setHeight( m_height );
    if ( !image_object_tag.write( m_object_tag.node() ) )
    {
        kvsMessageError( "Cannot write <%s>.", image_object_tag.name().c_str() );
        return false;
    }

    // <Pixel>
    kvs::kvsml::PixelTag pixel_tag;
    pixel_tag.setType( m_pixel_type );
    if ( !pixel_tag.write( image_object_tag.node() ) )
    {
        kvsMessageError( "Cannot write <%s>.", pixel_tag.name().c_str() );
        return false;
    }
    else
    {
        if ( m_pixels.size() > 0 )
        {
            // <DataArray>
            kvs::kvsml::DataArrayTag data_tag;
            if ( m_writing_type == kvs::KVSMLImageObject::ExternalAscii )
            {
                data_tag.setFile( kvs::kvsml::DataArray::GetDataFilename( filename, "pixel" ) );
                data_tag.setFormat( "ascii" );
            }
            else if ( m_writing_type == kvs::KVSMLImageObject::ExternalBinary )
            {
                data_tag.setFile( kvs::kvsml::DataArray::GetDataFilename( filename, "pixel" ) );
                data_tag.setFormat( "binary" );
            }

            const std::string pathname = kvs::File( filename ).pathName();
            if ( !data_tag.write( pixel_tag.node(), m_pixels, pathname ) )
            {
                kvsMessageError( "Cannot write <%s> for <%s>.",
                                 data_tag.name().c_str(),
                                 pixel_tag.name().c_str() );
                return false;
            }
        }
    }

    const bool success = document.write( filename );
    BaseClass::setSuccess( success );

    return success;
}
Exemple #17
0
static void test(void) {

 mycell *p, *q;
 int i;
 mps_res_t res;
 size_t lim7, avail7, commit7, lim8, avail8, commit8;
 size_t lim9, avail9, commit9;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), ARENA_SIZE),
  "create arena");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(mps_root_create_reg(&root, arena, mps_rank_ambig(), 0, thread,
  mps_stack_scan_ambig, stackpointer, 0), "create stack root");

 cdie(
  mps_fmt_create_A(&format, arena, &fmtA),
  "create format");

 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 cdie(
  mps_pool_create(&poolamc, arena, mps_class_amc(), format, chain),
  "create pool");

 cdie(
  mps_ap_create(&apamc, poolamc, mps_rank_exact()),
  "create ap");

 mps_arena_commit_limit_set(arena, mps_arena_committed(arena)+1024*1024);

 mps_reservoir_limit_set(arena, 0);
 report("lim7", "%d", lim7 = mps_reservoir_limit(arena));
 report("avail7",  "%d", avail7 = mps_reservoir_available(arena));
 report("commit7", "%d", commit7 = mps_arena_committed(arena));
 
/* available should be zero, but should be able to allocate with
   reservoir permit, until commit_limit is reached
*/

 i = -1;
 p = NULL;
 res = MPS_RES_OK;
 while (res == MPS_RES_OK) {
  res = reservoir_allocrone(&q, apamc, 10, mps_rank_exact());
  if (res == MPS_RES_OK) {
   setref(q, 0, p);
   p = q;
  }
  i++;
 }
 report("allocfail3", "%d", i);
 report_res("failres3", res);

/* should be none left to make available */

 mps_reservoir_limit_set(arena, 10ul*1024*1024);
 report("lim8", "%d", lim8 = mps_reservoir_limit(arena));
 report("avail8",  "%d", avail8 = mps_reservoir_available(arena));
 report("commit8", "%d", commit8 = mps_arena_committed(arena));
 report("spill8", "%d", commit8-mps_arena_commit_limit(arena));

/* throw away objects and collect world */

 p = NULL;
 q = NULL;
 mps_root_destroy(root);
 mps_arena_collect(arena);

/* available should have gone up now */

 report("lim9", "%d", lim9 = mps_reservoir_limit(arena));
 report("avail9",  "%d", avail9 = mps_reservoir_available(arena));
 report("commit9", "%d", commit9 = mps_arena_committed(arena));
 report("grow9", "%d", avail9-avail8);
 report("spill9", "%d", commit9-mps_arena_commit_limit(arena));
 
/* destroy everything remaining
*/

 mps_ap_destroy(apamc);
 comment("Destroyed ap.");

 mps_pool_destroy(poolamc);
 comment("Destroyed pool.");

 mps_fmt_destroy(format);
 comment("Destroyed format.");

 mps_chain_destroy(chain);
 comment("Destroyed chain.");

 mps_thread_dereg(thread);
 comment("Deregistered thread.");

 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
Exemple #18
0
 void operator() () {
   comment();
   clauses();
 }
void string_instrumentationt::do_format_string_write(
  goto_programt &dest,
  goto_programt::const_targett target,
  const code_function_callt::argumentst &arguments,
  unsigned format_string_inx,
  unsigned argument_start_inx,
  const std::string &function_name)
{
  const exprt &format_arg = arguments[format_string_inx];
    
  if(format_arg.id()==ID_address_of &&
     format_arg.op0().id()==ID_index &&
     format_arg.op0().op0().id()==ID_string_constant) // constant format
  {
    format_token_listt token_list=
      parse_format_string(format_arg.op0().op0().get_string(ID_value));
    
    unsigned args=0;
    
    for(format_token_listt::const_iterator it=token_list.begin();
        it!=token_list.end();
        it++)
    {
      if(find(it->flags.begin(), it->flags.end(), format_tokent::ASTERISK)!=
         it->flags.end()) 
        continue; // asterisk means `ignore this'
      
      switch(it->type)
      {
        case format_tokent::STRING:
        {
            
          const exprt &argument=arguments[argument_start_inx+args];
          const typet &arg_type=ns.follow(argument.type());
          
          goto_programt::targett assertion=dest.add_instruction();
          assertion->source_location=target->source_location;
          assertion->source_location.set_property_class("string");
          std::string comment("format string buffer overflow in ");
          comment += function_name;
          assertion->source_location.set_comment(comment);
          
          if(it->field_width!=0)
          {
            exprt fwidth = from_integer(it->field_width, unsigned_int_type());
            exprt fw_1(ID_plus, unsigned_int_type());
            exprt one = gen_one(unsigned_int_type());
            fw_1.move_to_operands(fwidth);
            fw_1.move_to_operands(one); // +1 for 0-char
            
            exprt fw_lt_bs;
            
            if(arg_type.id()==ID_pointer)
              fw_lt_bs=binary_relation_exprt(fw_1, ID_le, buffer_size(argument));
            else
            {
              index_exprt index;
              index.array()=argument;
              index.index()=gen_zero(unsigned_int_type());
              address_of_exprt aof(index);
              fw_lt_bs=binary_relation_exprt(fw_1, ID_le, buffer_size(aof));
            }
            
            assertion->make_assertion(fw_lt_bs);
          }
          else
          {
            // this is a possible overflow.
            assertion->make_assertion(false_exprt());
          }
          
          // now kill the contents
          invalidate_buffer(dest, target, argument, arg_type, it->field_width);
          
          args++;
          break;
        }
        case format_tokent::TEXT:
        case format_tokent::UNKNOWN:
        {          
          // nothing
          break;
        }
        default: // everything else
        {
          const exprt &argument=arguments[argument_start_inx+args];
          const typet &arg_type=ns.follow(argument.type());
          
          goto_programt::targett assignment=dest.add_instruction(ASSIGN);
          assignment->source_location=target->source_location;
          
          exprt lhs(ID_dereference, arg_type.subtype());
          lhs.copy_to_operands(argument);
          
          exprt rhs=side_effect_expr_nondett(lhs.type());
          rhs.add_source_location()=target->source_location;
           
          assignment->code=code_assignt(lhs, rhs);
          
          args++;
          break;
        }
      }
    }
  }
  else // non-const format string
  {    
    for(unsigned i=argument_start_inx; i<arguments.size(); i++)
    {    
      const typet &arg_type=ns.follow(arguments[i].type());
      
      // Note: is_string_type() is a `good guess' here. Actually
      // any of the pointers could point into an array. But it
      // would suck if we had to invalidate all variables.
      // Luckily this case isn't needed too often.
      if(is_string_type(arg_type))
      {
        goto_programt::targett assertion=dest.add_instruction();
        assertion->source_location=target->source_location;
        assertion->source_location.set_property_class("string");
        std::string comment("format string buffer overflow in ");
        comment += function_name;
        assertion->source_location.set_comment(comment);

        // as we don't know any field width for the %s that 
        // should be here during runtime, we just report a 
        // possibly false positive
        assertion->make_assertion(false_exprt());
        
        invalidate_buffer(dest, target, arguments[i], arg_type, 0);
      }
      else
      {
        goto_programt::targett assignment = dest.add_instruction(ASSIGN);
        assignment->source_location=target->source_location;
        
        exprt lhs(ID_dereference, arg_type.subtype());
        lhs.copy_to_operands(arguments[i]);
        
        exprt rhs=side_effect_expr_nondett(lhs.type());
        rhs.add_source_location()=target->source_location;
         
        assignment->code=code_assignt(lhs, rhs);
      }
    }
  }
}
Exemple #20
0
static void test(void)
{
 int i = 0, f = 0;
 mps_ap_t sap;
 mps_arena_t arena;
 mps_fmt_t format;
 mps_pool_t spool;
 mps_thr_t thread;
 mps_frame_t frames[MAXFRAMES];
 int nobj[MAXFRAMES+1];
 mycell *p;

/* create an arena that can't grow beyond 30 M */

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), (size_t)THIRTY_MEG),
  "create arena");
 cdie(mps_arena_commit_limit_set(arena, (size_t)THIRTY_MEG),
  "commit limit set");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(
  mps_fmt_create_A(&format, arena, &fmtA),
  "create format");

 cdie(
  mps_pool_create(&spool, arena, mps_class_snc(), format),
  "create SNC pool");

 cdie(
  mps_ap_create(&sap, spool, mps_rank_exact()),
  "create ap");

/* repeatedly push and pop stack frames, and allocate objects in them
   at random. Parameters ensure that max allocation can't get too high.
*/

 for (i=0; i < ITERATIONS; i++) {
  switch (ranint(12)) {
  case 1: case 2: case 3: case 4: case 5:
   if (f < MAXFRAMES) {
    die(mps_ap_frame_push(&frames[f], sap), "push");
    comment("push %i", f);
    f++;
    nobj[f] = 0;
   }
   break;
  case 6: case 7: case 8: case 9: case 10:
   if (nobj[f] < MAXLEVOBJS) {
    p = allocone(sap, 16, mps_rank_exact());
    setref(p, 0, NULL);
    nobj[f]++;
   }
   break;
  case 11:
   if (f>0) {
    f -= 1+ranint(1+ranint(f)); /* new f is in [0, old f) */
    die(mps_ap_frame_pop(sap, frames[f]), "pop");
    comment("pop %i", f);
   }
   break;
  }
 }

 mps_ap_destroy(sap);
 comment("Destroyed ap.");

 mps_pool_destroy(spool);
 comment("Destroyed pool.");

 mps_fmt_destroy(format);
 comment("Destroyed format.");

 mps_thread_dereg(thread);
 comment("Deregistered thread.");

 mps_arena_destroy(arena);
 comment("Destroyed arena.");

}
Exemple #21
0
Fichier : 12.c Projet : bhanug/mps
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t pool;
 mps_thr_t thread;
 mps_root_t root;

 mps_fmt_t format;
 mps_chain_t chain;

 mycell *cells;
 int h,i,j,k,l;
 mycell *pobj;

 mycell *ambig[NAPS];

 size_t bytes;
 size_t alignment;
 mps_addr_t q;
 int nextid = 0x1000000;

 /* turn on comments about copying and scanning */
 formatcomments = VERBOSE;
 fixcomments = VERBOSE;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE),
      "create arena");

 cdie(mps_thread_reg(&thread, arena), "register thread");

 cdie(mps_root_create_reg(&root, arena, mps_rank_ambig(), 0, thread,
                          mps_stack_scan_ambig, stackpointer, 0),
      "create root");

 cdie(mps_fmt_create_A(&format, arena, &fmtA), "create format");
 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 cdie(mmqa_pool_create_chain(&pool, arena, mps_class_amc(), format, chain),
      "create pool");

 for (i=0; i<NAPS; i++) {
  die(mps_ap_create(&ap[i], pool, mps_rank_exact()), "create ap");
  ap_state[i] = 0;
 }

 cells = allocone(ap[0], NCELLS);

 /* ap_state can have the following values:
  0 before reserve
  1 after reverse
  2 after init
  3 after I=A
  0 after commit
 */

 for(h=0; h<ITERATIONS; h++) {
   comment("%i of %i", h, ITERATIONS);

   for(j=0; j<1000; j++) {
     if (j == 500) {
       mps_arena_collect(arena);
     }
     i = ranint(NAPS);

     switch (ap_state[i]) {
     case 0:
       nrefs[i] = NUMREFS;
       bytes = offsetof(struct data, ref)+nrefs[i]*sizeof(struct refitem);
       alignment = MPS_PF_ALIGN;
       bytes = (bytes+alignment-1)&~(alignment-1);
       s[i] = bytes;
       die(mps_reserve(&q, ap[i], s[i]), "reserve: ");
       p[i] = q;
       p[i]->data.tag = 0xD033E2A6;
       p[i]->data.id = nextid;
       ap_state[i] = 1;
       commentif(VERBOSE, "%i: reserve %li at %p", i, nextid, q);
       nextid +=1;
       break;
     case 1:
       commentif(VERBOSE, "%i: init %li", i, p[i]->data.id);
       p[i]->data.tag = MCdata;
       p[i]->data.numrefs = nrefs[i];
       p[i]->data.size = s[i];
       ap_state[i] = 2;
       for (k=0; k<nrefs[i]; k++) {
         if PNULL {
           p[i]->data.ref[k].addr = NULL;
           p[i]->data.ref[k].id   = 0;
         } else {
           l = ranint(NCELLS);
           pobj = getref(cells, l);
           p[i]->data.ref[k].addr = pobj;
           p[i]->data.ref[k].id = (pobj==NULL ? 0 : pobj->data.id);
         }
         commentif(VERBOSE, "    ref %i -> %li", k, p[i]->data.ref[k].id);
       }
       break;
     case 2:
       commentif(VERBOSE, "%i: begin commit %li", i, p[i]->data.id);
       ambig[i] = p[i];
       ap[i]->init = ap[i]->alloc;
       ap_state[i] = 3;
       break;
     case 3:
       commentif(VERBOSE, "%i: end commit %li", i, p[i]->data.id);
       q = p[i];
       if (ap[i]->limit != 0 || mps_ap_trip(ap[i], p[i], s[i])) {
         l = ranint(NCELLS);
         setref(cells, l, q);
         commentif(VERBOSE, "%i -> %i", i, l);
       }
       ap_state[i] = 0;
       ambig[i] = NULL;
       break;
     }
   }
   checkfrom(cells);
 }
Exemple #22
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Parameter::removeComment(const CommentIndex& i) {
	Comment* object = comment(i);
	if ( object == NULL ) return false;
	return remove(object);
}
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t poolamc, poolawl;
 mps_thr_t thread;
 mps_root_t root;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t apamc, apawl;

 mycell *a[100], *b;

 int i;
 int j;
 int k,z;

 alloccomments = 1;
 formatcomments = 1;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE),
      "create arena");

 die(mps_thread_reg(&thread, arena), "register thread");
 die(mps_root_create_reg(&root, arena, MPS_RANK_AMBIG, 0, thread,
                         mps_stack_scan_ambig, stackpointer, 0),
     "create root");

 die(mps_fmt_create_A(&format, arena, &fmtA), "create format");
 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 die(mmqa_pool_create_chain(&poolamc, arena, mps_class_amc(), format, chain),
     "create pool");

 cdie(
  mps_pool_create(&poolawl, arena, mps_class_awl(), format),
  "create pool");

 cdie(
  mps_ap_create(&apawl, poolawl, MPS_RANK_EXACT),
  "create ap");

 cdie(
  mps_ap_create(&apamc, poolamc, MPS_RANK_EXACT),
  "create ap");

 for(i=0; i<100; i++) {
  a[i] = allocone(apawl, 6, 1);
 }

 for(i=0; i<10000; i++) {
  j = ranint(100);
  k = 5 + ranint(50);
  comment("New object %i, %i", j, k);
  a[j] = allocone(apawl, k, 1);
  k = ranint(100);
  z = ranint(2);
  comment("setting %i (%p) %i", k, a[k], z);
  setref(a[k], z, a[j]);
  b = allocdumb(apamc, 0x400*64, 0);
 }

 mps_ap_destroy(apawl);
 mps_ap_destroy(apamc);
 mps_pool_destroy(poolamc);
 mps_pool_destroy(poolawl);
 mps_chain_destroy(chain);
 mps_fmt_destroy(format);
 mps_root_destroy(root);
 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
static void test(void)
{
 mps_pool_t pool;
 mps_thr_t thread;

 mps_root_t root;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t ap, ap2;

 mycell *a, *b;

 mps_res_t res;
 int i;

 /* create an arena that can't grow beyond 30 M */
 cdie(mps_arena_create(&arena, mps_arena_class_vm(), (size_t) (1024*1024*30)),
      "create arena");
 mps_arena_commit_limit_set(arena, (size_t) (1024*1024*40));

 cdie(mps_thread_reg(&thread, arena), "register thread");
 cdie(mps_root_create_reg(&root, arena, MPS_RANK_AMBIG, 0, thread,
                          mps_stack_scan_ambig, stackpointer, 0),
      "create root");

 cdie(mps_fmt_create_A(&format, arena, &fmtA),
      "create format");
 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 die(mmqa_pool_create_chain(&pool, arena, mps_class_amc(), format, chain),
     "create pool");

 cdie(mps_ap_create(&ap, pool, MPS_RANK_EXACT),
      "create ap");

 /* allocate until full */

 i = 0;
 b = NULL;

 while (allocrone(&a, ap, 128, MPS_RANK_EXACT) == MPS_RES_OK) {
  i++;
  setref(a, 0, b);
  b = a;
 }

 comment("%d objs allocated.", i);
 report("committed", "%ld", mps_arena_committed(arena));

 /* try to allocate 10 times */

 cdie(mps_ap_create(&ap2, pool, MPS_RANK_EXACT), "create second ap");
 mps_ap_destroy(ap);

 for (i = 0; i < 10; i++) {
  res = allocrone(&a, ap2, 128, MPS_RANK_EXACT);
  report("predie", "%s", err_text(res));
 }

 /* now let everything die, and try to allocate 10 times */

 mps_root_destroy(root);

 for (i = 0; i < 10; i++) {
  res = allocrone(&a, ap2, 128, MPS_RANK_EXACT);
  report("postdie", "%s", err_text(res));
 }

 die(allocrone(&a, ap2, 128, MPS_RANK_EXACT), "alloc failed");

 mps_ap_destroy(ap2);
 mps_pool_destroy(pool);
 mps_chain_destroy(chain);
 mps_fmt_destroy(format);
 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
static void d_mc(int i, char *name)
{
 comment("%10d %s", maxcounters[i], name);
}
static void test(void)
{
 mps_arena_t arena;
 mps_pool_t poolamc, poolawl;
 mps_thr_t thread;
 mps_root_t root;

 mps_fmt_t format;
 mps_chain_t chain;
 mps_ap_t apamc, apexact, apweak;

 mycell *a, *b, *c, *d, *e, *f, *g;

 int i;
 int j;

 RC;

 cdie(mps_arena_create(&arena, mps_arena_class_vm(), mmqaArenaSIZE),
      "create arena");

 die(mps_thread_reg(&thread, arena), "register thread");
 die(mps_root_create_reg(&root, arena, MPS_RANK_AMBIG, 0, thread,
                         mps_stack_scan_ambig, stackpointer, 0),
     "create root");

 die(mps_fmt_create_A(&format, arena, &fmtA), "create format");
 cdie(mps_chain_create(&chain, arena, genCOUNT, testChain), "chain_create");

 die(mmqa_pool_create_chain(&poolamc, arena, mps_class_amc(), format, chain),
     "create pool");

 cdie(
  mps_pool_create(&poolawl, arena, mps_class_awl(), format),
  "create pool");

 cdie(
  mps_ap_create(&apexact, poolawl, MPS_RANK_EXACT),
  "create ap");

 cdie(
  mps_ap_create(&apweak, poolawl, MPS_RANK_WEAK),
  "create ap");

 cdie(
  mps_ap_create(&apamc, poolamc, MPS_RANK_EXACT),
  "create ap");

 b = allocone(apamc, 1, 1);

 for (j=1; j<10; j++) {
  comment("%i of 10.", j);
  UC;
  a = allocone(apexact, 5, 1);
  setref(a, 0, b);
  b = a;
  c = a;
  d = a;
  e = a;
  f = a;
  g = a;

  for (i=1; i<1000; i++) {
   UC;
   c = allocone(apamc, 1000, 0);
   if (ranint(2) == 0) {
    c = allocone(apweak, 100, 1);
   } else {
    c = allocone(apexact, 100, 1);
   }
   if (ranint(8) == 0) d = c;
   if (ranint(8) == 0) e = c;
   if (ranint(8) == 0) f = c;
   if (ranint(8) == 0) g = c;
   UC;
   setref(c, 0, b);
   UC;
   setref(c, 1, d);
   UC;
   setref(c, 2, e);
   UC;
   setref(c, 3, f);
   UC;
   setref(c, 4, g);
   UC;
   b = c;
  }
  DC;
  DMC;
 }

 mps_ap_destroy(apweak);
 mps_ap_destroy(apexact);
 mps_ap_destroy(apamc);
 comment("Destroyed aps.");

 mps_pool_destroy(poolamc);
 mps_pool_destroy(poolawl);
 mps_chain_destroy(chain);
 mps_fmt_destroy(format);
 mps_root_destroy(root);
 mps_thread_dereg(thread);
 mps_arena_destroy(arena);
 comment("Destroyed arena.");
}
Exemple #27
0
PrintcapEntry* LPRngToolHandler::createEntry(KMPrinter *prt)
{
	QString	prot = prt->deviceProtocol();
	if (prot != "parallel" && prot != "lpd" && prot != "smb" && prot != "socket")
	{
		manager()->setErrorMsg(i18n("Unsupported backend: %1.").arg(prot));
		return NULL;
	}
	PrintcapEntry	*entry = new PrintcapEntry;
	entry->addField("cm", Field::String, prt->description());
	QString	lp, comment("##LPRNGTOOL## ");
	if (prot == "parallel")
	{
		comment.append("DEVICE ");
		lp = prt->device().mid( 9 );
		entry->addField("rw@", Field::Boolean);
	}
	else if (prot == "socket")
	{
		comment.append("SOCKET ");
		KURL url( prt->device() );
		lp = url.host();
		if (url.port() == 0)
			lp.append("%9100");
		else
			lp.append("%").append(QString::number(url.port()));
	}
	else if (prot == "lpd")
	{
		comment.append("QUEUE ");
		KURL url( prt->device() );
		lp = url.path().mid(1) + "@" + url.host();
	}
	else if (prot == "smb")
	{
		comment.append("SMB ");
		lp = "| " + filterDir() + "/smbprint";
		QString	work, server, printer, user, passwd;
		if ( splitSmbURI( prt->device(), work, server, printer, user, passwd ) )
		{
			entry->addField("xfer_options", Field::String, QString::fromLatin1("authfile=\"auth\" crlf=\"0\" hostip=\"\" host=\"%1\" printer=\"%2\" remote_mode=\"SMB\" share=\"//%3/%4\" workgroup=\"%5\"").arg(server).arg(printer).arg(server).arg(printer).arg(work));
			QFile	authfile(LprSettings::self()->baseSpoolDir() + "/" + prt->printerName() + "/auth");
			if (authfile.open(IO_WriteOnly))
			{
				QTextStream	t(&authfile);
				t << "username="******"password="******"Invalid printer backend specification: %1" ).arg( prt->device() ) );
			delete entry;
			return NULL;
		}
	}

	if (prt->driver())
	{
		DrMain	*driver = prt->driver();
		comment.append("filtertype=IFHP ifhp_options=status@,sync@,pagecount@,waitend@ printerdb_entry=");
		comment.append(driver->get("driverID"));
		entry->addField("ifhp", Field::String, QString::fromLatin1("model=%1,status@,sync@,pagecount@,waitend@").arg(driver->get("driverID")));
		entry->addField("lprngtooloptions", Field::String, QString::fromLatin1("FILTERTYPE=\"IFHP\" IFHP_OPTIONS=\"status@,sync@,pagecount@,waitend@\" PRINTERDB_ENTRY=\"%1\"").arg(driver->get("driverID")));
		QMap<QString,QString>	opts;
		QString	optstr;
		driver->getOptions(opts, false);
		for (QMap<QString,QString>::ConstIterator it=opts.begin(); it!=opts.end(); ++it)
			if (it.key() != "lpr")
				optstr.append(*it).append(",");
		if (!optstr.isEmpty())
		{
			optstr.truncate(optstr.length()-1);
			entry->addField("prefix_z", Field::String, optstr);
		}
		if (!opts["lpr"].isEmpty())
			entry->addField("lpr", Field::String, opts["lpr"]);
	}

	entry->addField("lp", Field::String, lp);
	entry->comment = comment;

	return entry;
}
Exemple #28
0
static void t_alloc(int spare, int spare_total, int commit, int obj_size) { 
 size_t size, hisize, comsize, comlimit;
 size_t spsize = 0, losize = 0; /* stop warnings */
 mps_res_t res, res_expected;

 if (obj_size == OBJ_SMALL) size = SMALL_SIZE; else size = BIG_SIZE;

 switch (spare_total) {
 case SPARE_EMPTY:
  spsize = 0;
  break;
 case SPARE_LESS:
  if (size > DIFF_SIZE) {
   spsize = size-DIFF_SIZE;
  } else {
   spsize = 0;
  }
  break;
 case SPARE_EXACT:
  spsize = size;
  break;
 case SPARE_MORE:
  spsize = size+DIFF_SIZE;
  break;
 default:
  error("Illegal spare.\n");
  break;
 }

 switch (spare) {
 case SPARE_EMPTY:
  losize = 0;
  break;
 case SPARE_LESS:
  if (size > DIFF_SIZE) {
   losize = size-DIFF_SIZE;
  } else {
   losize = 0;
  }
  break;
 case SPARE_EXACT:
  losize = size;
  break;
 case SPARE_MORE:
  losize = size+DIFF_SIZE;
  break;
 }

 if (losize > spsize) {
  losize = spsize;
  hisize = 0;
 } else {
  hisize = spsize-losize;
 }

 /* turn off commit limit for a moment */
 mps_arena_commit_limit_set(arena, HUGE);

 /* create low and high pools */
 
 die(
  mps_pool_create(&poolhi, arena, mps_class_mvff(), MVFF_HI_PARMS),
  "create high pool");

 die(
  mps_pool_create(&poollo, arena, mps_class_mvff(), MVFF_LO_PARMS),
  "create low pool");

 /* flush hysteresis fund, then set limit */

 mps_arena_spare_commit_limit_set(arena, SPARE_ZERO);
 mps_arena_spare_commit_limit_set(arena, SPARE_LIMIT);

 /* allocate something in each pool (to reduce risk of subsidiary
    allocation being neede later */

 die(mps_alloc(&objlo, poollo, EXTEND), "low alloc");
 die(mps_alloc(&objhi, poolhi, EXTEND), "high alloc");

 /* set up spare committed the way we want it */

 if (losize>0) {
  die(mps_alloc(&objlo, poollo, losize), "low setup");
  mps_free(poollo, objlo, losize);
 }

 if (hisize>0) {
  die(mps_alloc(&objhi, poolhi, hisize), "high setup");
  mps_free(poolhi, objhi, hisize);
 }

 /* spare is now set up correctly */
 /* now we need to set the commit limit correctly */

 comsize = arena_committed_and_used(arena);

 /* allow for 1/16th memory overhead in setting commit limit */

 if (commit == COMMIT_EXACT) {
  comlimit = comsize+size+(size/16);
 } else if (commit == COMMIT_NOCHANGE) {
  comlimit = mps_arena_committed(arena);
 } else if (commit == COMMIT_PLENTY) {
  comlimit = HUGE;
 } else /* commit == COMMIT_LITTLE */ {
  if (size > DIFF_SIZE) {
   comlimit = comsize+size+(size/16)+DIFF_SIZE;
  } else {
   comlimit = comsize+size+(size/16);
  }
 }

 die(mps_arena_commit_limit_set(arena, comlimit), "commit limit set");

 res = mps_alloc(&objlo, poollo, size);

 asserts(comlimit >= comsize, "comlimit was less than comsize!");

 if (size <= (comlimit-comsize)) {
  res_expected = MPS_RES_OK;
 } else {
  res_expected = MPS_RES_COMMIT_LIMIT;
 }

 if (res != res_expected) {
  comment("Spare useful/total %i/%i. Limit %i. Size %i. Expected %s. Got %s", spare, spare_total, commit, obj_size, err_text(res_expected), err_text(res));
  report("failed", "yes");
 }

 mps_pool_destroy(poollo);
 mps_pool_destroy(poolhi);
}
Windowdef_simple* Windowdef_simple::copy() const
    {
    return new Windowdef_simple( comment(), title(), title_match_type(), wclass(),
        wclass_match_type(), role(), role_match_type(), window_types());
    }
Exemple #30
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool FocalMechanism::removeComment(const CommentIndex& i) {
	Comment* object = comment(i);
	if ( object == NULL ) return false;
	return remove(object);
}