コード例 #1
0
ファイル: bootloader.c プロジェクト: PIC-Niagara/MPcopy
static void WriteHexRecord2Flash(UINT8* HexRecord)
{
	static T_HEX_RECORD HexRecordSt;
	UINT8 Checksum = 0;
	UINT i;
	UINT32 WrData;
	UINT32 ProgAddress;
	UINT Result;

	HexRecord = &HexRecord[0];
	HexRecordSt.RecDataLen = HexRecord[0];
	HexRecordSt.RecType = HexRecord[3];
	HexRecordSt.Data = &HexRecord[4];

	Checksum = 0;       // Hex Record checksum check.
	for (i = 0; i < HexRecordSt.RecDataLen + 5; i++)
	{
		Checksum += HexRecord[i];
	}

	if (Checksum != 0)
	{
		// Error. Hex record Checksum mismatch.
		error(ERR_HEX_CSUM);
	}
	else
	{
		// Hex record checksum OK.
		switch (HexRecordSt.RecType)
		{
			case DATA_RECORD:   // Record Type 00, data record.
				HexRecordSt.Address.byte.MB = 0;
				HexRecordSt.Address.byte.UB = 0;
				HexRecordSt.Address.byte.HB = HexRecord[1];
				HexRecordSt.Address.byte.LB = HexRecord[2];

				// Derive the address.
				HexRecordSt.Address.Val = HexRecordSt.Address.Val + HexRecordSt.ExtLinAddress.Val + HexRecordSt.ExtSegAddress.Val;

				while (HexRecordSt.RecDataLen) // Loop till all bytes are done.
				{
					// Convert the Physical address to Virtual address.
					ProgAddress = (HexRecordSt.Address.Val / 2);

					// Make sure we are not writing boot area and device configuration bits.
					if (((ProgAddress < AUX_FLASH_BASE_ADRS) ||
					     (ProgAddress > AUX_FLASH_END_ADRS)) &&
					    ((ProgAddress < DEV_CONFIG_REG_BASE_ADDRESS) ||
					     (ProgAddress > DEV_CONFIG_REG_END_ADDRESS)))
					{
						if (HexRecordSt.RecDataLen < 4)
						{
							// Sometimes record data length will not be in multiples of 4. Appending 0xFF will make sure that..
							// we don't write junk data in such cases.
							WrData = 0xFFFFFFFF;
							memcpy(&WrData, HexRecordSt.Data, HexRecordSt.RecDataLen);
						}
						else
						{
							memcpy(&WrData, HexRecordSt.Data, 4);
						}
						// Write the data into flash.
						Result = NVMemWriteWord(ProgAddress, WrData);
						// Assert on error. This must be caught during debug phase.
						while (Result!=0);
					}

					// Increment the address.
					HexRecordSt.Address.Val += 4;
					// Increment the data pointer.
					HexRecordSt.Data += 4;
					// Decrement data len.
					if (HexRecordSt.RecDataLen > 3)
					{
						HexRecordSt.RecDataLen -= 4;
					}
					else
					{
						HexRecordSt.RecDataLen = 0;
					}
				}
				break;

			case EXT_SEG_ADRS_RECORD:   // Record Type 02, defines 4th to 19th bits of the data address.
				HexRecordSt.ExtSegAddress.byte.MB = 0;
				HexRecordSt.ExtSegAddress.byte.UB = HexRecordSt.Data[0];
				HexRecordSt.ExtSegAddress.byte.HB = HexRecordSt.Data[1];
				HexRecordSt.ExtSegAddress.byte.LB = 0;
				// Reset linear address.
				HexRecordSt.ExtLinAddress.Val = 0;
				break;

			case EXT_LIN_ADRS_RECORD:   // Record Type 04, defines 16th to 31st bits of the data address. 
				HexRecordSt.ExtLinAddress.byte.MB = HexRecordSt.Data[0];
				HexRecordSt.ExtLinAddress.byte.UB = HexRecordSt.Data[1];
				HexRecordSt.ExtLinAddress.byte.HB = 0;
				HexRecordSt.ExtLinAddress.byte.LB = 0;
				// Reset segment address.
				HexRecordSt.ExtSegAddress.Val = 0;
				break;

			case END_OF_FILE_RECORD:    // Record Type 01, defines the end of file record.
			default:
				HexRecordSt.ExtSegAddress.Val = 0;
				HexRecordSt.ExtLinAddress.Val = 0;
				break;
		}
	}
}
コード例 #2
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType go	(	Parm1,Parm2,Parm3,Parm4) 				{ return error(4); };
コード例 #3
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType go	(	Parm1,Parm2,Parm3,Parm4,Parm5,Parm6,Parm7) 			{ return error(7); };
コード例 #4
0
ファイル: scan.c プロジェクト: Patsylou/Web-Classification
static SEXP scanVector(SEXPTYPE type, int maxitems, int maxlines,
		       int flush, SEXP stripwhite, int blskip, LocalData *d)
{
    SEXP ans, bns;
    int blocksize, c, i, n, linesread, nprev,strip, bch;
    char *buffer;
    R_StringBuffer strBuf = {NULL, 0, MAXELTSIZE};

    if (maxitems > 0) blocksize = maxitems;
    else blocksize = SCAN_BLOCKSIZE;

    R_AllocStringBuffer(0, &strBuf);
    PROTECT(ans = allocVector(type, blocksize));

    nprev = 0; n = 0; linesread = 0; bch = 1;

    if (d->ttyflag) sprintf(ConsolePrompt, "1: ");

    strip = asLogical(stripwhite);

    for (;;) {
	if(n % 10000 == 9999) R_CheckUserInterrupt();
	if (bch == R_EOF) {
	    if (d->ttyflag) R_ClearerrConsole();
	    break;
	}
	else if (bch == '\n') {
	    linesread++;
	    if (linesread == maxlines)
		break;
	    if (d->ttyflag) sprintf(ConsolePrompt, "%d: ", n + 1);
	    nprev = n;
	}
	if (n == blocksize) {
	    /* enlarge the vector*/
	    bns = ans;
	    if(blocksize > INT_MAX/2) error(_("too many items"));
	    blocksize = 2 * blocksize;
	    ans = allocVector(type, blocksize);
	    UNPROTECT(1);
	    PROTECT(ans);
	    copyVector(ans, bns);
	}
	buffer = fillBuffer(type, strip, &bch, d, &strBuf);
	if (nprev == n && strlen(buffer)==0 &&
	    ((blskip && bch =='\n') || bch == R_EOF)) {
	    if (d->ttyflag || bch == R_EOF)
		break;
	}
	else {
	    extractItem(buffer, ans, n, d);
	    if (++n == maxitems) {
		if (d->ttyflag && bch != '\n') { /* MBCS-safe */
		    while ((c = scanchar(FALSE, d)) != '\n')
			;
		}
		break;
	    }
	}
	if (flush && (bch != '\n') && (bch != R_EOF)) { /* MBCS-safe */
	    while ((c = scanchar(FALSE, d)) != '\n' && (c != R_EOF));
	    bch = c;
	}
    }
    if (!d->quiet) REprintf("Read %d item%s\n", n, (n == 1) ? "" : "s");
    if (d->ttyflag) ConsolePrompt[0] = '\0';

    if (n == 0) {
	UNPROTECT(1);
	R_FreeStringBuffer(&strBuf);
	return allocVector(type,0);
    }
    if (n == maxitems) {
	UNPROTECT(1);
	R_FreeStringBuffer(&strBuf);
	return ans;
    }

    bns = allocVector(type, n);
    switch (type) {
    case LGLSXP:
    case INTSXP:
	for (i = 0; i < n; i++)
	    INTEGER(bns)[i] = INTEGER(ans)[i];
	break;
    case REALSXP:
	for (i = 0; i < n; i++)
	    REAL(bns)[i] = REAL(ans)[i];
	break;
    case CPLXSXP:
	for (i = 0; i < n; i++)
	    COMPLEX(bns)[i] = COMPLEX(ans)[i];
	break;
    case STRSXP:
	for (i = 0; i < n; i++)
	    SET_STRING_ELT(bns, i, STRING_ELT(ans, i));
	break;
    case RAWSXP:
	for (i = 0; i < n; i++)
	    RAW(bns)[i] = RAW(ans)[i];
	break;
    default:
	UNIMPLEMENTED_TYPEt("scanVector", type);
    }
    UNPROTECT(1);
    R_FreeStringBuffer(&strBuf);
    return bns;
}
コード例 #5
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType go	(	Parm1,Parm2) 						{ return error(2); };
コード例 #6
0
ファイル: dpxoutput.cpp プロジェクト: bms20/oiio
bool
DPXOutput::prep_subimage (int s, bool allocate)
{
    m_spec = m_subimage_specs[s];  // stash the spec

    // determine descriptor
    m_desc = get_image_descriptor();

    // transfer function
    std::string colorspace = m_spec.get_string_attribute ("oiio:ColorSpace", "");
    if (Strutil::iequals (colorspace, "Linear"))  m_transfer = dpx::kLinear;
    else if (Strutil::iequals (colorspace, "GammaCorrected")) m_transfer = dpx::kUserDefined;
    else if (Strutil::iequals (colorspace, "Rec709")) m_transfer = dpx::kITUR709;
    else if (Strutil::iequals (colorspace, "KodakLog")) m_transfer = dpx::kLogarithmic;
    else {
        std::string dpxtransfer = m_spec.get_string_attribute ("dpx:Transfer", "");
        m_transfer = get_characteristic_from_string (dpxtransfer);
    }

    // colorimetric
    m_cmetr = get_characteristic_from_string
        (m_spec.get_string_attribute ("dpx:Colorimetric", "User defined"));

    // select packing method
    std::string pck = m_spec.get_string_attribute ("dpx:Packing", "Filled, method A");
    if (Strutil::iequals (pck, "Packed"))
        m_packing = dpx::kPacked;
    else if (Strutil::iequals (pck, "Filled, method B"))
        m_packing = dpx::kFilledMethodB;
    else
        m_packing = dpx::kFilledMethodA;

    switch (m_spec.format.basetype) {
    case TypeDesc::UINT8 :
    case TypeDesc::UINT16 :
    case TypeDesc::FLOAT :
    case TypeDesc::DOUBLE :
        // supported, fine
        break;
    case TypeDesc::HALF :
        // Turn half into float
        m_spec.format.basetype = TypeDesc::FLOAT;
        break;
    default:
        // Turn everything else into UINT16
        m_spec.format.basetype = TypeDesc::UINT16;
        break;
    }

    // calculate target bit depth
    m_bitdepth = m_spec.format.size () * 8;
    if (m_spec.format == TypeDesc::UINT16) {
        m_bitdepth = m_spec.get_int_attribute ("oiio:BitsPerSample", 16);
        if (m_bitdepth != 10 && m_bitdepth != 12 && m_bitdepth != 16) {
            error ("Unsupported bit depth %d", m_bitdepth);
            return false;
        }
    }

    // Bug workaround: libDPX doesn't appear to correctly support
    // "filled method A" for 12 bit data.  Does anybody care what
    // packing/filling we use?  Punt and just use "packed".
    if (m_bitdepth == 12)
        m_packing = dpx::kPacked;

    if (m_spec.format == TypeDesc::UINT8
        || m_spec.format == TypeDesc::INT8)
        m_datasize = dpx::kByte;
    else if (m_spec.format == TypeDesc::UINT16
             || m_spec.format == TypeDesc::INT16)
        m_datasize = dpx::kWord;
    else if (m_spec.format == TypeDesc::FLOAT
             || m_spec.format == TypeDesc::HALF) {
        m_spec.format = TypeDesc::FLOAT;
        m_datasize = dpx::kFloat;
    } else if (m_spec.format == TypeDesc::DOUBLE)
        m_datasize = dpx::kDouble;
    else {
        // use 16-bit unsigned integers as a failsafe
        m_spec.set_format (TypeDesc::UINT16);
        m_datasize = dpx::kWord;
    }

    // check if the client is giving us raw data to write
    m_wantRaw = m_spec.get_int_attribute ("dpx:RawData", 0) != 0;

    // see if we'll need to convert or not
    if (m_desc == dpx::kRGB || m_desc == dpx::kRGBA) {
        // shortcut for RGB(A) that gets the job done
        m_bytes = m_spec.scanline_bytes ();
        m_wantRaw = true;
    } else {
        m_bytes = dpx::QueryNativeBufferSize (m_desc, m_datasize, m_spec.width, 1);
        if (m_bytes == 0 && !m_wantRaw) {
            error ("Unable to deliver native format data from source data");
            return false;
        } else if (m_bytes < 0) {
            // no need to allocate another buffer
            if (!m_wantRaw)
                m_bytes = m_spec.scanline_bytes ();
            else
                m_bytes = -m_bytes;
        }
    }
    if (m_bytes < 0)
        m_bytes = -m_bytes;

    // allocate space for the image data buffer
    if (allocate)
        m_buf.resize (m_bytes * m_spec.height);

    return true;
}
コード例 #7
0
ファイル: system.c プロジェクト: BackupTheBerlios/portsman
/* proceeds installation/deinstallation/update action */
void
proceed_action(List *l) {
   extern List *lcats;
   extern Config config;
   extern bool redraw_dimensions;
   Iter itr = l->head;
   Iter citr; /* cat iterator */
   Iter oitr; /* option iterator */
   Iter ditr; /* dependency iterator */
   Port *p;
   char execstr[1000];
   char option[MAX_TOKEN];
   char wdir[MAX_PATH];
   int result = 0;

   /* leaving curses ... */
   def_prog_mode(); /* save current tty modes */
   endwin();        /* restore original tty modes */

   getcwd(wdir, MAX_PATH);
   /* action loop */
   while ((itr != NULL) && (result == 0)) {
      if (((Port *)itr->item)->type == PORT) {
         p = (Port *)itr->item;
         if (p->lopts != NULL)
            oitr = p->lopts->head; 

         switch (p->state) {
            case STATE_INSTALL:
               sprintf(execstr, "%s %s", config.make_cmd,
                     config.make_target[MK_TARGET_INST]);
              break;
            case STATE_UPDATE:
               sprintf(execstr, "%s %s", config.make_cmd,
                     config.make_target[MK_TARGET_UPDATE]);
               break;   
            case STATE_DEINSTALL:
               sprintf(execstr, "%s %s", config.make_cmd,
                     config.make_target[MK_TARGET_DEINST]);
               break;   
         }

         /* cat compile options */
         while (oitr != NULL) {
            Option *opt = (Option *)oitr->item;
            if (opt->state == STATE_SELECTED) {
               sprintf(option, " %s", opt->arg);
               strcat(execstr, option);
            }
            oitr = oitr->next;
         }

         /* fire up make */
         chdir(p->path);
         result = system(execstr);
         switch (result) {
            case -1:
               error("fork() could not be invoked");
               return;
               break;
            case 127:
               error("execution of shell failed");
               return;
               break;
            case 0: /* build/installation/deinstallation successful */
               switch (p->state) {
                  case STATE_INSTALL:
                  case STATE_UPDATE:
                     p->state = STATE_INSTALLED;
                     ditr = p->lbdep->head;
                     while (ditr != NULL) {
                        if (((Port *)ditr->item)->state != STATE_INSTALLED) 
                           ((Port *)ditr->item)->state = STATE_INSTALLED;
                        ditr = ditr->next;
                     }
                     ditr = p->lrdep->head;
                     while (ditr != NULL) {
                        if (((Port *)ditr->item)->state != STATE_INSTALLED) 
                           ((Port *)ditr->item)->state = STATE_INSTALLED;
                        ditr = ditr->next;
                     }
                     break;
                  case STATE_DEINSTALL:
                     p->state = STATE_NOT_SELECTED;
                     break;
               }
               break;
         }
      }
      itr = itr->next;
   }
   chdir(wdir);
   refresh_cat_states(); 

   /* ... coming back to curses */
   refresh();
   redraw_dimensions = TRUE;

}
コード例 #8
0
ファイル: GEMglFogi.cpp プロジェクト: Jackovic/Gem
//////////////////
// extension check
bool GEMglFogi :: isRunnable(void) {
  if(GLEW_VERSION_1_1)return true;
  error("your system does not support OpenGL-1.1");
  return false;
}
コード例 #9
0
void c_typecheck_baset::typecheck_c_enum_type(typet &type)
{
  // These come with the declarations
  // of the enum constants as operands.

  exprt &as_expr=static_cast<exprt &>(static_cast<irept &>(type));
  source_locationt source_location=type.source_location();

  // We allow empty enums in the grammar to get better
  // error messages.
  if(as_expr.operands().empty())
  {
    error().source_location=source_location;
    error() << "empty enum" << eom;
    throw 0;
  }

  // enums start at zero;
  // we also track min and max to find a nice base type
  mp_integer value=0, min_value=0, max_value=0;

  std::list<c_enum_typet::c_enum_membert> enum_members;

  // We need to determine a width, and a signedness
  // to obtain an 'underlying type'.
  // We just do int, but gcc might pick smaller widths
  // if the type is marked as 'packed'.
  // gcc/clang may also pick a larger width. Visual Studio doesn't.

  for(auto &op : as_expr.operands())
  {
    ansi_c_declarationt &declaration=to_ansi_c_declaration(op);
    exprt &v=declaration.declarator().value();

    if(v.is_not_nil()) // value given?
    {
      exprt tmp_v=v;
      typecheck_expr(tmp_v);
      add_rounding_mode(tmp_v);
      simplify(tmp_v, *this);
      if(tmp_v.is_true())
        value=1;
      else if(tmp_v.is_false())
        value=0;
      else if(!to_integer(tmp_v, value))
      {
      }
      else
      {
        error().source_location=v.source_location();
        error() << "enum is not a constant";
        throw 0;
      }
    }

    if(value<min_value)
      min_value=value;
    if(value>max_value)
      max_value=value;

    typet constant_type=
      enum_constant_type(min_value, max_value);

    v=from_integer(value, constant_type);

    declaration.type()=constant_type;
    typecheck_declaration(declaration);

    irep_idt base_name=
      declaration.declarator().get_base_name();

    irep_idt identifier=
      declaration.declarator().get_name();

    // store
    c_enum_typet::c_enum_membert member;
    member.set_identifier(identifier);
    member.set_base_name(base_name);
    member.set_value(integer2string(value));
    enum_members.push_back(member);

    // produce value for next constant
    ++value;
  }

  // Remove these now; we add them to the
  // c_enum symbol later.
  as_expr.operands().clear();

  bool is_packed=type.get_bool(ID_C_packed);

  // tag?
  if(type.find(ID_tag).is_nil())
  {
    // None, it's anonymous. We generate a tag.
    std::string anon_identifier="#anon_enum";

    for(const auto &member : enum_members)
    {
      anon_identifier+='$';
      anon_identifier+=id2string(member.get_base_name());
      anon_identifier+='=';
      anon_identifier+=id2string(member.get_value());
    }

    if(is_packed)
      anon_identifier+="#packed";

    type.add(ID_tag).set(ID_identifier, anon_identifier);
  }

  irept &tag=type.add(ID_tag);
  irep_idt base_name=tag.get(ID_C_base_name);
  irep_idt identifier=tag.get(ID_identifier);

  // Put into symbol table
  symbolt enum_tag_symbol;

  enum_tag_symbol.is_type=true;
  enum_tag_symbol.type=type;
  enum_tag_symbol.location=source_location;
  enum_tag_symbol.is_file_local=true;
  enum_tag_symbol.base_name=base_name;
  enum_tag_symbol.name=identifier;

  // throw in the enum members as 'body'
  irept::subt &body=enum_tag_symbol.type.add(ID_body).get_sub();

  for(const auto &member : enum_members)
    body.push_back(member);

  // We use a subtype to store the underlying type.
  typet underlying_type=
    enum_underlying_type(min_value, max_value, is_packed);

  enum_tag_symbol.type.subtype()=underlying_type;

  // is it in the symbol table already?
  symbol_tablet::symbolst::iterator s_it=
    symbol_table.symbols.find(identifier);

  if(s_it!=symbol_table.symbols.end())
  {
    // Yes.
    symbolt &symbol=s_it->second;

    if(symbol.type.id()==ID_incomplete_c_enum)
    {
      // Ok, overwrite the type in the symbol table.
      // This gives us the members and the subtype.
      symbol.type=enum_tag_symbol.type;
    }
    else if(symbol.type.id()==ID_c_enum)
    {
      // We might already have the same anonymous enum, and this is
      // simply ok. Note that the C standard treats these as
      // different types.
      if(!base_name.empty())
      {
        error().source_location=type.source_location();
        error() << "redeclaration of enum tag" << eom;
        throw 0;
      }
    }
    else
    {
      error().source_location=source_location;
      error() << "use of tag that does not match previous declaration" << eom;
      throw 0;
    }
  }
  else
  {
    symbolt *new_symbol;
    move_symbol(enum_tag_symbol, new_symbol);
  }

  // We produce a c_enum_tag as the resulting type.
  type.id(ID_c_enum_tag);
  type.remove(ID_tag);
  type.set(ID_identifier, identifier);
}
コード例 #10
0
/**
   Read in asterism WFS wvf.*/
long setup_star_read_wvf(STAR_S *star, int nstar, const PARMS_S *parms, int seed){
    const double ngsgrid=parms->maos.ngsgrid;
    const int nwvl=parms->maos.nwvl;
    long nstep=0;
    TIC;tic;
    for(int istar=0; istar<nstar; istar++){
	STAR_S *stari=&star[istar];
	int npowfs=parms->maos.npowfs;
	stari->wvfout=mycalloc(npowfs,ccell**);
	const double thetax=stari->thetax*206265;/*in as */
	const double thetay=stari->thetay*206265;

	double thxnorm=thetax/ngsgrid;
	double thynorm=thetay/ngsgrid;
	long thxl=(long)floor(thxnorm);/*Used to be double, but -0 appears. */
	long thyl=(long)floor(thynorm);
	double wtx=thxnorm-thxl;
	double wty=thynorm-thyl;
	for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	    const int msa=parms->maos.msa[ipowfs];
	    const int nsa=parms->maos.nsa[ipowfs];
	    if(stari->use[ipowfs]==0){
		continue;
	    }
	    char *fnwvf[2][2]={{NULL,NULL},{NULL,NULL}};
	    PISTAT_S *pistati=&stari->pistat[ipowfs];
	    
	    /*info2("Reading PSF for (%5.1f, %5.1f), ipowfs=%d\n",thetax,thetay,ipowfs); */
	    double wtsum=0;
	    for(int ix=0; ix<2; ix++){
		double thx=(thxl+ix)*ngsgrid;
		for(int iy=0; iy<2; iy++){
		    double thy=(thyl+iy)*ngsgrid;
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty));

		    if(wtxi<0.01){
			/*info("skipping ix=%d,iy=%d because wt=%g\n",ix,iy,wtxi); */
			continue;
		    }
		    fnwvf[iy][ix]=myalloca(PATH_MAX, char);
		    snprintf(fnwvf[iy][ix],PATH_MAX,"%s/wvfout/wvfout_seed%d_sa%d_x%g_y%g",
			     dirstart,seed,msa,thx,thy);
	
		    if(!zfexist(fnwvf[iy][ix])){
			//warning("%s doesnot exist\n",fnwvf[iy][ix]);
			fnwvf[iy][ix]=0;
		    }else{
			wtsum+=wtxi;
		    }
		}
	    }
	    if(wtsum<0.01){
		error("PSF is not available for (%g,%g). wtsum=%g\n",thetax,thetay, wtsum);
	    }
	    /*Now do the actual reading */
	    for(int ix=0; ix<2; ix++){
		for(int iy=0; iy<2; iy++){
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty))/wtsum;
		    if(fnwvf[iy][ix]){
			/*info("Loading %.4f x %s\n", wtxi, fnwvf[iy][ix]); */
			file_t *fp_wvf=zfopen(fnwvf[iy][ix],"rb");
			header_t header={0,0,0,0};
			read_header(&header, fp_wvf);
			if(!iscell(&header.magic)){
			    error("expected data type: %u, got %u\n",(uint32_t)MCC_ANY, header.magic);
			}
			nstep=header.nx;
			free(header.str);
			if(parms->skyc.limitnstep >0 && nstep>parms->skyc.limitnstep){
			    nstep=parms->skyc.limitnstep;
			    warning("Only read %ld steps\n",nstep);
			}
			if(stari->nstep==0){
			    stari->nstep=nstep;
			}else{
			    if(stari->nstep!=nstep){
				error("Different type has different steps\n");
			    }
			}
		    
			if(!stari->wvfout[ipowfs]){
			    stari->wvfout[ipowfs]=mycalloc(nstep,ccell*);
			}
			ccell **pwvfout=stari->wvfout[ipowfs];
			for(long istep=0; istep<nstep; istep++){
			    ccell *wvfi=ccellreaddata(fp_wvf, 0);
			    ccelladd(&(pwvfout[istep]), 1, wvfi, wtxi);
			    ccellfree(wvfi);
			}
			/*zfeof(fp_wvf); */
			zfclose(fp_wvf);
		    }
		}/*iy */
	    }/*ix */
	    /*Don't bother to scale ztiltout since it does not participate in physical optics simulations. */
	    if(parms->skyc.bspstrehl){
		dmat*  scale=pistati->scale;
		ccell **pwvfout=stari->wvfout[ipowfs];
		for(int iwvl=0; iwvl<nwvl; iwvl++){
		    for(int isa=0; isa<nsa; isa++){
			/*info("Scaling WVF isa %d iwvl %d with %g\n", isa, iwvl, IND(scale,isa,iwvl)); */
			for(long istep=0; istep<stari->nstep; istep++){
			    cscale(pwvfout[istep]->p[isa+nsa*iwvl], IND(scale,isa,iwvl));
			}/*istep */
		    }/*isa */
		}/*iwvl */
	    }/* */
	}/*ipowfs */
    }/*istar */
コード例 #11
0
ファイル: linker.cpp プロジェクト: smolt/ldc
int executeMsvcToolAndWait(const std::string &tool,
                           const std::vector<std::string> &args, bool verbose) {
  llvm::SmallString<1024> commandLine; // full command line incl. executable

  // if the VSINSTALLDIR environment variable is NOT set,
  // the MSVC environment needs to be set up
  const bool needMsvcSetup = !getenv("VSINSTALLDIR");
  if (needMsvcSetup) {
    /* <command line> => %ComSpec% /s /c "<batch file> <command line>"
     *
     * cmd.exe /c treats the following string argument (the command)
     * in a very peculiar way if it starts with a double-quote.
     * By adding /s and enclosing the command in extra double-quotes
     * (WITHOUT additionally escaping the command), the command will
     * be parsed properly.
     */

    auto comspecEnv = getenv("ComSpec");
    if (!comspecEnv) {
      warning(Loc(), "'ComSpec' environment variable is not set, assuming 'cmd.exe'.");
      comspecEnv = "cmd.exe";
    }
    std::string cmdExecutable = comspecEnv;
    std::string batchFile = exe_path::prependBinDir(
        global.params.targetTriple.isArch64Bit() ? "amd64.bat" : "x86.bat");

    commandLine.append(windows::quoteArg(cmdExecutable));
    commandLine.append(" /s /c \"");
    commandLine.append(windows::quoteArg(batchFile));
    commandLine.push_back(' ');
    commandLine.append(windows::quoteArg(tool));
  } else {
    std::string toolPath = getProgram(tool.c_str());
    commandLine.append(windows::quoteArg(toolPath));
  }

  const size_t commandLineLengthAfterTool = commandLine.size();

  // append (quoted) args
  for (size_t i = 0; i < args.size(); ++i) {
    commandLine.push_back(' ');
    commandLine.append(windows::quoteArg(args[i]));
  }

  const bool useResponseFile = (!args.empty() && commandLine.size() > 2000);
  llvm::SmallString<128> responseFilePath;
  if (useResponseFile) {
    const size_t firstArgIndex = commandLineLengthAfterTool + 1;
    llvm::StringRef content(commandLine.data() + firstArgIndex,
                            commandLine.size() - firstArgIndex);

    if (llvm::sys::fs::createTemporaryFile("ldc_link", "rsp",
                                           responseFilePath) ||
        llvm::sys::writeFileWithEncoding(
            responseFilePath,
            content)) // keep encoding (LLVM assumes UTF-8 input)
    {
      error(Loc(), "cannot write temporary response file for %s", tool.c_str());
      return -1;
    }

    // replace all args by @<responseFilePath>
    std::string responseFileArg = ("@" + responseFilePath).str();
    commandLine.resize(firstArgIndex);
    commandLine.append(windows::quoteArg(responseFileArg));
  }

  if (needMsvcSetup)
    commandLine.push_back('"');

  const char *finalCommandLine = commandLine.c_str();

  if (verbose) {
    fprintf(global.stdmsg, finalCommandLine);
    fprintf(global.stdmsg, "\n");
    fflush(global.stdmsg);
  }

  const int exitCode = windows::executeAndWait(finalCommandLine);

  if (exitCode != 0) {
    commandLine.resize(commandLineLengthAfterTool);
    if (needMsvcSetup)
      commandLine.push_back('"');
    error(Loc(), "`%s` failed with status: %d", commandLine.c_str(), exitCode);
  }

  if (useResponseFile)
    llvm::sys::fs::remove(responseFilePath);

  return exitCode;
}
コード例 #12
0
long setup_star_read_ztilt(STAR_S *star, int nstar, const PARMS_S *parms, int seed){
    const double ngsgrid=parms->maos.ngsgrid;
    long nstep=0;
    TIC;tic;
    for(int istar=0; istar<nstar; istar++){
	STAR_S *stari=&star[istar];
	int npowfs=parms->maos.npowfs;
	stari->ztiltout=dcellnew(npowfs, 1);
	const double thetax=stari->thetax*206265;/*in as */
	const double thetay=stari->thetay*206265;

	double thxnorm=thetax/ngsgrid;
	double thynorm=thetay/ngsgrid;
	long thxl=(long)floor(thxnorm);/*Used to be double, but -0 appears. */
	long thyl=(long)floor(thynorm);
	double wtx=thxnorm-thxl;
	double wty=thynorm-thyl;
	for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	    const int msa=parms->maos.msa[ipowfs];
	    const int nsa=parms->maos.nsa[ipowfs];
	    const int ng=nsa*2;
	    char *fnztilt[2][2]={{NULL,NULL},{NULL,NULL}};
	    char *fngoff[2][2]={{NULL, NULL}, {NULL, NULL}};
	    double wtsum=0;
	    for(int ix=0; ix<2; ix++){
		double thx=(thxl+ix)*ngsgrid;
		for(int iy=0; iy<2; iy++){
		    double thy=(thyl+iy)*ngsgrid;
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty));

		    if(wtxi<0.01){
			/*info("skipping ix=%d,iy=%d because wt=%g\n",ix,iy,wtxi); */
			continue;
		    }
		    fnztilt[iy][ix]=myalloca(PATH_MAX, char);
		    if(parms->skyc.usephygrad){
			warning_once("Using phygrad\n");
			snprintf(fnztilt[iy][ix],PATH_MAX,"%s/phygrad/phygrad_seed%d_sa%d_x%g_y%g",
				 dirstart,seed,msa,thx,thy);
		    }else{
			snprintf(fnztilt[iy][ix],PATH_MAX,"%s/ztiltout/ztiltout_seed%d_sa%d_x%g_y%g",
				 dirstart,seed,msa,thx,thy);
		    }
		    fngoff[iy][ix]=myalloca(PATH_MAX, char);
		    snprintf(fngoff[iy][ix],PATH_MAX,"%s/gradoff/gradoff_sa%d_x%g_y%g",
			     dirstart,msa,thx,thy);
		    if(!zfexist(fnztilt[iy][ix])){
			//warning("%s doesnot exist\n",fnwvf[iy][ix]);
			fnztilt[iy][ix]=fngoff[iy][ix]=NULL;
		    }else{
			wtsum+=wtxi;
		    }
		}
	    }
	    if(wtsum<0.01){
		error("PSF is not available for (%g,%g). wtsum=%g\n",thetax,thetay, wtsum);
	    }
	    /*Now do the actual reading */
	    for(int ix=0; ix<2; ix++){
		for(int iy=0; iy<2; iy++){
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty))/wtsum;
		    if(fnztilt[iy][ix]){
			file_t *fp_ztilt=zfopen(fnztilt[iy][ix],"rb");
			header_t header={0,0,0,0};
			read_header(&header, fp_ztilt);
			
			if(iscell(&header.magic)){
			    // error("expected data type: %u, got %u\n",(uint32_t)MCC_ANY, header.magic);
			    nstep=header.nx;
			    free(header.str);
			    if(stari->nstep==0){
				stari->nstep=nstep;
			    }else{
				if(stari->nstep!=nstep){
				    error("Different type has different steps\n");
				}
			    }
			    if(!stari->ztiltout->p[ipowfs]){
				stari->ztiltout->p[ipowfs]=dnew(ng, nstep);
			    }
			    dmat  *ztiltout=stari->ztiltout->p[ipowfs];
			    for(long istep=0; istep<nstep; istep++){
				dmat *ztilti=dreaddata(fp_ztilt, 0);
				for(int ig=0; ig<ng; ig++){
				    ztiltout->p[ig+istep*ng]+=ztilti->p[ig]*wtxi;
				}
				dfree(ztilti);
			    }
			}else{
			    dmat *tmp=dreaddata(fp_ztilt, &header);
			    dadd(&stari->ztiltout->p[ipowfs], 1, tmp, wtxi );
			    dfree(tmp);
			}
			zfclose(fp_ztilt);
		    }/* if(fnwvf) */
		    if(fngoff[iy][ix] && zfexist(fngoff[iy][ix])){
			if(!stari->goff){
			    stari->goff=dcellnew(npowfs, 1);
			}
			dmat *tmp=dread("%s", fngoff[iy][ix]);
			dadd(&stari->goff->p[ipowfs], 1, tmp, wtxi);
			dfree(tmp);
		    }
		}/*iy */
	    }/*ix */
	}/*ipowfs */
    }/*istar */
    if(parms->skyc.verbose){
	toc2("Reading PSF");
    }
    //close(fd);
    return nstep;
}
コード例 #13
0
/**
   Create "star" data array from star information.
*/
static STAR_S *setup_star_create(const PARMS_S *parms, dmat *coord){
    if(!coord){
	return NULL;/*there are no stars available. */
    }
    int nstar=coord->ny;
    dmat* pc=coord;
    int nwvl=parms->maos.nwvl;
    STAR_S *star=mycalloc(nstar,STAR_S);
    double ngsgrid=parms->maos.ngsgrid/206265.;
    double r2=pow(parms->skyc.patfov/206265./2.,2);
    double keepout=pow(parms->skyc.keepout/206265.,2);
    double minrad2=pow(parms->skyc.minrad/206265.,2);
    int jstar=0;
    assert(nwvl+2==coord->nx);
    for(int istar=0; istar<nstar; istar++){
	if(parms->skyc.ngsalign){
	    star[jstar].thetax=round(IND(pc,0,istar)/ngsgrid)*ngsgrid;
	    star[jstar].thetay=round(IND(pc,1,istar)/ngsgrid)*ngsgrid;
	    if(pow(star[jstar].thetax,2)+pow(star[jstar].thetay,2)>r2){
		star[jstar].thetax=trunc(IND(pc,0,istar)/ngsgrid)*ngsgrid;
		star[jstar].thetay=round(IND(pc,1,istar)/ngsgrid)*ngsgrid;
		if(pow(star[jstar].thetax,2)+pow(star[jstar].thetay,2)>r2){
		    star[jstar].thetax=round(IND(pc,0,istar)/ngsgrid)*ngsgrid;
		    star[jstar].thetay=trunc(IND(pc,1,istar)/ngsgrid)*ngsgrid;
		    if(pow(star[jstar].thetax,2)+pow(star[jstar].thetay,2)>r2){
			star[jstar].thetax=trunc(IND(pc,0,istar)/ngsgrid)*ngsgrid;
			star[jstar].thetay=trunc(IND(pc,1,istar)/ngsgrid)*ngsgrid;
			if(pow(star[jstar].thetax,2)+pow(star[jstar].thetay,2)>r2){
			    error("What?\n");
			}
		    }
		}
	    }
	}else{
	    star[jstar].thetax=IND(pc,0,istar);
	    star[jstar].thetay=IND(pc,1,istar);
	}
	for(int kstar=0; kstar<jstar; kstar++){
	    if(pow(star[jstar].thetax-star[kstar].thetax,2)
	       +pow(star[jstar].thetay-star[kstar].thetay,2)<keepout){
		/*warning("start %d is too close to %d. use J brightest.\n", jstar, kstar); */
		if(IND(pc,0,istar)<star[kstar].mags->p[0]){
		    memcpy(star[kstar].mags->p, PCOL(pc,istar)+2, sizeof(double)*nwvl);
		    star[kstar].thetax=star[jstar].thetax;
		    star[kstar].thetay=star[jstar].thetay;
		}
		continue;
	    }
	}
	if(pow(star[istar].thetax,2)+pow(star[istar].thetay,2)<minrad2){
	    info2("Skip star at (%.0f, %.0f) because minrad=%g\n", 
		 star[istar].thetax*206265, star[istar].thetay*206265, parms->skyc.minrad);
	    continue;
	}
	star[jstar].mags=dnew(nwvl,1);
	memcpy(star[jstar].mags->p, PCOL(pc,istar)+2, sizeof(double)*nwvl);
	star[jstar].use=mycalloc(parms->maos.npowfs,int);
	jstar++;
    }
    if(jstar<nstar){
	/*warning2("%d stars dropped\n", nstar-jstar); */
	coord->ny=jstar;
	star=myrealloc(star, jstar,STAR_S);
    }
    return star;
}
コード例 #14
0
/**
   Read in pistat information, used to compute matched filter, and SANEA.
*/
static void setup_star_read_pistat(SIM_S *simu, STAR_S *star, int nstar, int seed){
    const PARMS_S *parms=simu->parms;
    const int npowfs=parms->maos.npowfs;
    const int nwvl=parms->maos.nwvl;
    const double ngsgrid=parms->maos.ngsgrid;
    for(int istar=0; istar<nstar; istar++){
	STAR_S *stari=&star[istar];
	stari->pistat=mycalloc(npowfs,PISTAT_S);
	const double thetax=stari->thetax*206265;/*in as */
	const double thetay=stari->thetay*206265;
	double thxnorm=thetax/ngsgrid;
	double thynorm=thetay/ngsgrid;
	long thxl=(long)floor(thxnorm);
	long thyl=(long)floor(thynorm);
	double wtx=thxnorm-thxl;
	double wty=thynorm-thyl;
	for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	    const int msa=parms->maos.msa[ipowfs];
	    const int nsa=parms->maos.nsa[ipowfs];
	    dcell *avgpsf=NULL;
	    dcell *neaspec=NULL;
	    double wtsum=0;
	    for(int ix=0; ix<2; ix++){
		double thx=(thxl+ix)*ngsgrid;
		for(int iy=0; iy<2; iy++){
		    double thy=(thyl+iy)*ngsgrid;
		    double wtxi=fabs(((1-ix)-wtx)*((1-iy)-wty));
		    if(wtxi<0.01){
			/*info("skipping ix=%d,iy=%d because wt=%g\n",ix,iy,wtxi); */
			continue;
		    }
		    char fn[PATH_MAX];
		    snprintf(fn,PATH_MAX,"%s/pistat/pistat_seed%d_sa%d_x%g_y%g",
			     dirstart, seed,msa,thx,thy);
		    if(!zfexist(fn)){
			/*warning("%s doesn't exist\n",fn); */
		    }else{
			dcell *avgpsfi=dcellread("%s",fn);
			dcelladd(&avgpsf, 1, avgpsfi, wtxi);
			dcellfree(avgpsfi);
			wtsum+=wtxi;
			
			snprintf(fn,PATH_MAX,"%s/neaspec/neaspec_seed%d_sa%d_x%g_y%g",
				 dirstart, seed, msa, thx, thy);
			dcell *neaspeci=dcellread("%s",fn);
			dcelladd(&neaspec, 1, neaspeci, wtxi);
			dcellfree(neaspeci);
		    }
		}
	    }
	    if(wtsum<0.01){
		warning("PISTAT is not available for (%g,%g) msa=%d\n",thetax,thetay,msa);
	    }
	    dcellscale(neaspec, 1./wtsum);
	    dcellscale(avgpsf, 1./wtsum);
	    dmat *scale=NULL;
	    if(parms->skyc.bspstrehl){
		scale=dnew(nsa,nwvl);
		dmat *gx=dnew(1,1); gx->p[0]=thxnorm;
		dmat *gy=dnew(1,1); gy->p[0]=thynorm;
		if(nsa!=avgpsf->nx || nwvl!=avgpsf->ny){
		    error("Mismatch: nsa=%d, nwvl=%d, avgpsf->nx=%ld, avgpsf->ny=%ld\n",
			  nsa, nwvl, avgpsf->nx, avgpsf->ny);
		}
		for(int ic=0; ic<nsa*nwvl; ic++){
		    dmat *val=dbspline_eval(simu->bspstrehl[ipowfs][ic],
					    simu->bspstrehlxy,simu->bspstrehlxy,
					    gx, gy);
		    double ratio=val->p[0]/avgpsf->p[ic]->p[0];
		    /*info("strehl: bilinear: %g, cubic: %g\n", avgpsf->p[ic]->p[0],val->p[0]); */
		    if(ratio<0){
			warning("Ratio=%g is less than zero.\n", ratio);
			scale->p[ic]=1;
		    }else{
			dscale(avgpsf->p[ic], ratio);
			scale->p[ic]=ratio;
		    }
		    dfree(val);
		}
		dfree(gx);
		dfree(gy);
	    }

	    stari->pistat[ipowfs].psf=avgpsf;/*PSF is in corner. */
	    stari->pistat[ipowfs].neaspec=dcellnew(nsa*2, 1);
	    for(int ig=0; ig<nsa*2; ig++){
		dmat *tmp=0;
		for(int iwvl=0; iwvl<nwvl; iwvl++){
		    dadd(&tmp, 0, neaspec->p[ig+nsa*2*iwvl], parms->skyc.wvlwt->p[iwvl]);
		}
		stari->pistat[ipowfs].neaspec->p[ig]=dinterp1(simu->neaspec_dtrats, tmp, parms->skyc.dtrats, 0);
		dfree(tmp);
	    }
	    dcellfree(neaspec);
	    stari->pistat[ipowfs].scale=scale;
	    {/* skip stars with large PSF.*/
		int size=INT_MAX;
		for(int ic=0; ic<avgpsf->nx*avgpsf->ny; ic++){
		    int size0=dfwhm(avgpsf->p[ic]);
		    if(size0<size) size=size0;
		}
		if(size>6){
		    stari->use[ipowfs]=-1;
		}
	    }
	    if(parms->skyc.dbg){
		writebin(avgpsf, "%s/avgpsf_star%d_ipowfs%d_psf",dirsetup,istar,ipowfs);
		writebin(stari->pistat[ipowfs].neaspec, "%s/pistat_star%d_ipowfs%d_neaspec",dirsetup,istar,ipowfs);
	    }
	}
    }
}
コード例 #15
0
void c_typecheck_baset::typecheck_compound_body(
  struct_union_typet &type)
{
  struct_union_typet::componentst &components=type.components();

  struct_union_typet::componentst old_components;
  old_components.swap(components);

  // We get these as declarations!
  for(auto &decl : old_components)
  {
    // the arguments are member declarations or static assertions
    assert(decl.id()==ID_declaration);

    ansi_c_declarationt &declaration=
      to_ansi_c_declaration(static_cast<exprt &>(decl));

    if(declaration.get_is_static_assert())
    {
      struct_union_typet::componentt new_component;
      new_component.id(ID_static_assert);
      new_component.add_source_location()=declaration.source_location();
      new_component.operands().swap(declaration.operands());
      assert(new_component.operands().size()==2);
      components.push_back(new_component);
    }
    else
    {
      // do first half of type
      typecheck_type(declaration.type());
      make_already_typechecked(declaration.type());

      for(const auto &declarator : declaration.declarators())
      {
        struct_union_typet::componentt new_component;

        new_component.add_source_location()=
          declarator.source_location();
        new_component.set(ID_name, declarator.get_base_name());
        new_component.set(ID_pretty_name, declarator.get_base_name());
        new_component.type()=declaration.full_type(declarator);

        typecheck_type(new_component.type());

        if(!is_complete_type(new_component.type()) &&
           (new_component.type().id()!=ID_array ||
            !to_array_type(new_component.type()).is_incomplete()))
        {
          error().source_location=new_component.type().source_location();
          error() << "incomplete type not permitted here" << eom;
          throw 0;
        }

        components.push_back(new_component);
      }
    }
  }

  unsigned anon_member_counter=0;

  // scan for anonymous members, and name them
  for(auto &member : components)
  {
    if(member.get_name()!=irep_idt())
      continue;

    member.set_name("$anon"+std::to_string(anon_member_counter++));
    member.set_anonymous(true);
  }

  // scan for duplicate members

  {
    std::unordered_set<irep_idt, irep_id_hash> members;

    for(struct_union_typet::componentst::iterator
        it=components.begin();
        it!=components.end();
        it++)
    {
      if(!members.insert(it->get_name()).second)
      {
        error().source_location=it->source_location();
        error() << "duplicate member '" << it->get_name() << '\'' << eom;
        throw 0;
      }
    }
  }

  // We allow an incomplete (C99) array as _last_ member!
  // Zero-length is allowed everywhere.

  if(type.id()==ID_struct ||
     type.id()==ID_union)
  {
    for(struct_union_typet::componentst::iterator
        it=components.begin();
        it!=components.end();
        it++)
    {
      typet &c_type=it->type();

      if(c_type.id()==ID_array &&
         to_array_type(c_type).is_incomplete())
      {
        // needs to be last member
        if(type.id()==ID_struct && it!=--components.end())
        {
          error().source_location=it->source_location();
          error() << "flexible struct member must be last member" << eom;
          throw 0;
        }

        // make it zero-length
        c_type.id(ID_array);
        c_type.set(ID_size, from_integer(0, index_type()));
      }
    }
  }

  // We may add some minimal padding inside and at
  // the end of structs and
  // as additional member for unions.

  if(type.id()==ID_struct)
    add_padding(to_struct_type(type), *this);
  else if(type.id()==ID_union)
    add_padding(to_union_type(type), *this);

  // Now remove zero-width bit-fields, these are just
  // for adjusting alignment.
  for(struct_typet::componentst::iterator
      it=components.begin();
      it!=components.end();
      ) // blank
  {
    if(it->type().id()==ID_c_bit_field &&
       to_c_bit_field_type(it->type()).get_width()==0)
      it=components.erase(it);
    else
      it++;
  }

  // finally, check _Static_assert inside the compound
  for(struct_union_typet::componentst::iterator
      it=components.begin();
      it!=components.end();
      ) // no it++
  {
    if(it->id()==ID_static_assert)
    {
      assert(it->operands().size()==2);
      exprt &assertion=it->op0();
      typecheck_expr(assertion);
      typecheck_expr(it->op1());
      assertion.make_typecast(bool_typet());
      make_constant(assertion);

      if(assertion.is_false())
      {
        error().source_location=it->source_location();
        error() << "failed _Static_assert" << eom;
        throw 0;
      }
      else if(!assertion.is_true())
      {
        // should warn/complain
      }

      it=components.erase(it);
    }
    else
      it++;
  }
}
コード例 #16
0
void c_typecheck_baset::typecheck_c_bit_field_type(c_bit_field_typet &type)
{
  typecheck_type(type.subtype());

  mp_integer i;

  {
    exprt &width_expr=static_cast<exprt &>(type.add(ID_size));

    typecheck_expr(width_expr);
    make_constant_index(width_expr);

    if(to_integer(width_expr, i))
    {
      error().source_location=type.source_location();
      error() << "failed to convert bit field width" << eom;
      throw 0;
    }

    if(i<0)
    {
      error().source_location=type.source_location();
      error() << "bit field width is negative" << eom;
      throw 0;
    }

    type.set_width(integer2size_t(i));
    type.remove(ID_size);
  }

  const typet &subtype=follow(type.subtype());

  std::size_t sub_width=0;

  if(subtype.id()==ID_bool)
  {
    // This is the 'proper' bool.
    sub_width=1;
  }
  else if(subtype.id()==ID_signedbv ||
          subtype.id()==ID_unsignedbv ||
          subtype.id()==ID_c_bool)
  {
    sub_width=to_bitvector_type(subtype).get_width();
  }
  else if(subtype.id()==ID_c_enum_tag)
  {
    // These point to an enum, which has a sub-subtype,
    // which may be smaller or larger than int, and we thus have
    // to check.
    const typet &c_enum_type=
      follow_tag(to_c_enum_tag_type(subtype));

    if(c_enum_type.id()==ID_incomplete_c_enum)
    {
      error().source_location=type.source_location();
      error() << "bit field has incomplete enum type" << eom;
      throw 0;
    }

    sub_width=c_enum_type.subtype().get_int(ID_width);
  }
  else
  {
    error().source_location=type.source_location();
    error() << "bit field with non-integer type: "
            << to_string(subtype) << eom;
    throw 0;
  }

  if(i>sub_width)
  {
    error().source_location=type.source_location();
    error() << "bit field (" << i
            << " bits) larger than type (" << sub_width << " bits)"
            << eom;
    throw 0;
  }
}
コード例 #17
0
ファイル: dpxoutput.cpp プロジェクト: bms20/oiio
bool
DPXOutput::open (const std::string &name, const ImageSpec &userspec,
                 OpenMode mode)
{
    if (mode == Create) {
        m_subimage = 0;
        if (m_subimage_specs.size() < 1) {
            m_subimage_specs.resize (1);
            m_subimage_specs[0] = userspec;
            m_subimages_to_write = 1;
        }
    } else if (mode == AppendSubimage) {
        if (m_write_pending)
            write_buffer ();
        ++m_subimage;
        if (m_subimage >= m_subimages_to_write) {
            error ("Exceeded the pre-declared number of subimages (%d)",
                   m_subimages_to_write);
            return false;
        }
        return prep_subimage (m_subimage, true);
        // Nothing else to do, the header taken care of when we opened with
        // Create.
    } else if (mode == AppendMIPLevel) {
        error ("DPX does not support MIP-maps");
        return false;
    }

    // From here out, all the heavy lifting is done for Create
    ASSERT (mode == Create);

    if (is_opened())
        close ();  // Close any already-opened file
    m_stream = new OutStream();
    if (! m_stream->Open(name.c_str ())) {
        error ("Could not open file \"%s\"", name.c_str ());
        return false;
    }
    m_dpx.SetOutStream (m_stream);
    m_dpx.Start ();
    m_subimage = 0;

    ImageSpec &m_spec (m_subimage_specs[m_subimage]); // alias the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }

    if (m_spec.depth < 1)
        m_spec.depth = 1;
    else if (m_spec.depth > 1) {
        error ("DPX does not support volume images (depth > 1)");
        return false;
    }

    // some metadata
    std::string software = m_spec.get_string_attribute ("Software", "");
    std::string project = m_spec.get_string_attribute ("DocumentName", "");
    std::string copyright = m_spec.get_string_attribute ("Copyright", "");
    std::string datestr = m_spec.get_string_attribute ("DateTime", "");
    if (datestr.size () >= 19) {
        // libdpx's date/time format is pretty close to OIIO's (libdpx uses
        // %Y:%m:%d:%H:%M:%S%Z)
        // NOTE: the following code relies on the DateTime attribute being properly
        // formatted!
        // assume UTC for simplicity's sake, fix it if someone complains
        datestr[10] = ':';
        datestr.replace (19, -1, "Z");
    }

    // check if the client wants endianness reverse to native
    // assume big endian per Jeremy's request, unless little endian is
    // explicitly specified
    std::string endian = m_spec.get_string_attribute ("oiio:Endian", littleendian() ? "little" : "big");
    m_wantSwap = (littleendian() != Strutil::iequals (endian, "little"));

    m_dpx.SetFileInfo (name.c_str (),                               // filename
        datestr.c_str (),                                           // cr. date
        software.empty () ? OIIO_INTRO_STRING : software.c_str (),  // creator
        project.empty () ? NULL : project.c_str (),                 // project
        copyright.empty () ? NULL : copyright.c_str (),             // copyright
        m_spec.get_int_attribute ("dpx:EncryptKey", ~0),            // encryption key
        m_wantSwap);

    // image info
    m_dpx.SetImageInfo (m_spec.width, m_spec.height);

    for (int s = 0;  s < m_subimages_to_write;  ++s) {
        prep_subimage (s, false);
        m_dpx.header.SetBitDepth (s, m_bitdepth);
        ImageSpec &spec (m_subimage_specs[s]);
        bool datasign = (spec.format == TypeDesc::INT8 ||
                         spec.format == TypeDesc::INT16);
        m_dpx.SetElement (s, m_desc, m_bitdepth, m_transfer, m_cmetr,
                          m_packing, dpx::kNone, datasign,
                          spec.get_int_attribute ("dpx:LowData", 0xFFFFFFFF),
                          spec.get_float_attribute ("dpx:LowQuantity", std::numeric_limits<float>::quiet_NaN()),
                          spec.get_int_attribute ("dpx:HighData", 0xFFFFFFFF),
                          spec.get_float_attribute ("dpx:HighQuantity", std::numeric_limits<float>::quiet_NaN()),
                          spec.get_int_attribute ("dpx:EndOfLinePadding", 0),
                          spec.get_int_attribute ("dpx:EndOfImagePadding", 0));
        std::string desc = spec.get_string_attribute ("ImageDescription", "");
        m_dpx.header.SetDescription (s, desc.c_str());
    }

    m_dpx.header.SetXScannedSize (m_spec.get_float_attribute
        ("dpx:XScannedSize", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetYScannedSize (m_spec.get_float_attribute
        ("dpx:YScannedSize", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetFramePosition (m_spec.get_int_attribute
        ("dpx:FramePosition", 0xFFFFFFFF));
    m_dpx.header.SetSequenceLength (m_spec.get_int_attribute
        ("dpx:SequenceLength", 0xFFFFFFFF));
    m_dpx.header.SetHeldCount (m_spec.get_int_attribute
        ("dpx:HeldCount", 0xFFFFFFFF));
    m_dpx.header.SetFrameRate (m_spec.get_float_attribute
        ("dpx:FrameRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetShutterAngle (m_spec.get_float_attribute
        ("dpx:ShutterAngle", std::numeric_limits<float>::quiet_NaN()));
    // FIXME: should we write the input version through or always default to 2.0?
    /*tmpstr = m_spec.get_string_attribute ("dpx:Version", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetVersion (tmpstr.c_str ());*/
    std::string tmpstr;
    tmpstr = m_spec.get_string_attribute ("dpx:FrameId", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetFrameId (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:SlateInfo", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetSlateInfo (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:SourceImageFileName", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetSourceImageFileName (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:InputDevice", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetInputDevice (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:InputDeviceSerialNumber", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetInputDeviceSerialNumber (tmpstr.c_str ());
    m_dpx.header.SetInterlace (m_spec.get_int_attribute ("dpx:Interlace", 0xFF));
    m_dpx.header.SetFieldNumber (m_spec.get_int_attribute ("dpx:FieldNumber", 0xFF));
    m_dpx.header.SetHorizontalSampleRate (m_spec.get_float_attribute
        ("dpx:HorizontalSampleRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetVerticalSampleRate (m_spec.get_float_attribute
        ("dpx:VerticalSampleRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetTemporalFrameRate (m_spec.get_float_attribute
        ("dpx:TemporalFrameRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetTimeOffset (m_spec.get_float_attribute
        ("dpx:TimeOffset", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBlackLevel (m_spec.get_float_attribute
        ("dpx:BlackLevel", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBlackGain (m_spec.get_float_attribute
        ("dpx:BlackGain", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBreakPoint (m_spec.get_float_attribute
        ("dpx:BreakPoint", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetWhiteLevel (m_spec.get_float_attribute
        ("dpx:WhiteLevel", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetIntegrationTimes (m_spec.get_float_attribute
        ("dpx:IntegrationTimes", std::numeric_limits<float>::quiet_NaN()));
    float aspect = m_spec.get_float_attribute ("PixelAspectRatio", 1.0f);
    int aspect_num, aspect_den;
    float_to_rational (aspect, aspect_num, aspect_den);
    m_dpx.header.SetAspectRatio (0, aspect_num);
    m_dpx.header.SetAspectRatio (1, aspect_den);
    m_dpx.header.SetXOffset ((unsigned int)std::max (0, m_spec.x));
    m_dpx.header.SetYOffset ((unsigned int)std::max (0, m_spec.y));
    m_dpx.header.SetXOriginalSize ((unsigned int)m_spec.full_width);
    m_dpx.header.SetYOriginalSize ((unsigned int)m_spec.full_height);

    static int DpxOrientations[] = { 0,
        dpx::kLeftToRightTopToBottom, dpx::kRightToLeftTopToBottom,
        dpx::kLeftToRightBottomToTop, dpx::kRightToLeftBottomToTop,
        dpx::kTopToBottomLeftToRight, dpx::kTopToBottomRightToLeft,
        dpx::kBottomToTopLeftToRight, dpx::kBottomToTopRightToLeft };
    int orient = m_spec.get_int_attribute ("Orientation", 0);
    orient = DpxOrientations[clamp (orient, 0, 8)];
    m_dpx.header.SetImageOrientation ((dpx::Orientation)orient);

    ImageIOParameter *tc = m_spec.find_attribute("smpte:TimeCode", TypeDesc::TypeTimeCode, false);
    if (tc) {
        unsigned int *timecode = (unsigned int*) tc->data();
        m_dpx.header.timeCode = timecode[0];
        m_dpx.header.userBits = timecode[1];
    }
    else {
        std::string timecode = m_spec.get_string_attribute ("dpx:TimeCode", "");
        int tmpint = m_spec.get_int_attribute ("dpx:TimeCode", ~0);
        if (timecode.size () > 0)
            m_dpx.header.SetTimeCode (timecode.c_str ());
        else if (tmpint != ~0)
        m_dpx.header.timeCode = tmpint;
        m_dpx.header.userBits = m_spec.get_int_attribute ("dpx:UserBits", ~0);
    }

    ImageIOParameter *kc = m_spec.find_attribute("smpte:KeyCode", TypeDesc::TypeKeyCode, false);
    if (kc) {
        int *array = (int*) kc->data();
        set_keycode_values(array);

        // See if there is an overloaded dpx:Format
        std::string format = m_spec.get_string_attribute ("dpx:Format", "");
        if (format.size () > 0)
            m_dpx.header.SetFormat (format.c_str ());
    }

    std::string srcdate = m_spec.get_string_attribute ("dpx:SourceDateTime", "");
    if (srcdate.size () >= 19) {
        // libdpx's date/time format is pretty close to OIIO's (libdpx uses
        // %Y:%m:%d:%H:%M:%S%Z)
        // NOTE: the following code relies on the DateTime attribute being properly
        // formatted!
        // assume UTC for simplicity's sake, fix it if someone complains
        srcdate[10] = ':';
        srcdate.replace (19, -1, "Z");
        m_dpx.header.SetSourceTimeDate (srcdate.c_str ());
    }

    // set the user data size
    ImageIOParameter *user = m_spec.find_attribute ("dpx:UserData");
    if (user && user->datasize () > 0 && user->datasize () <= 1024 * 1024) {
        m_dpx.SetUserData (user->datasize ());
    }

    // commit!
    if (!m_dpx.WriteHeader ()) {
        error ("Failed to write DPX header");
        return false;
    }

    // write the user data
    if (user && user->datasize () > 0 && user->datasize() <= 1024 * 1024) {
        if (!m_dpx.WriteUserData ((void *)user->data ())) {
            error ("Failed to write user data");
            return false;
        }
    }

    m_dither = (m_spec.format == TypeDesc::UINT8) ?
                    m_spec.get_int_attribute ("oiio:dither", 0) : 0;

    // If user asked for tiles -- which this format doesn't support, emulate
    // it by buffering the whole image.
    if (m_spec.tile_width && m_spec.tile_height)
        m_tilebuffer.resize (m_spec.image_bytes());

    return prep_subimage (m_subimage, true);
}
コード例 #18
0
void c_typecheck_baset::typecheck_custom_type(typet &type)
{
  // they all have a width
  exprt size_expr=
    static_cast<const exprt &>(type.find(ID_size));

  typecheck_expr(size_expr);
  source_locationt source_location=size_expr.source_location();
  make_constant_index(size_expr);

  mp_integer size_int;
  if(to_integer(size_expr, size_int))
  {
    error().source_location=source_location;
    error() << "failed to convert bit vector width to constant" << eom;
    throw 0;
  }

  if(size_int<1)
  {
    error().source_location=source_location;
    error() << "bit vector width invalid" << eom;
    throw 0;
  }

  type.remove(ID_size);
  type.set(ID_width, integer2string(size_int));

  // depending on type, there may be a number of fractional bits

  if(type.id()==ID_custom_unsignedbv)
    type.id(ID_unsignedbv);
  else if(type.id()==ID_custom_signedbv)
    type.id(ID_signedbv);
  else if(type.id()==ID_custom_fixedbv)
  {
    type.id(ID_fixedbv);

    exprt f_expr=
      static_cast<const exprt &>(type.find(ID_f));

    source_locationt source_location=f_expr.find_source_location();

    typecheck_expr(f_expr);

    make_constant_index(f_expr);

    mp_integer f_int;
    if(to_integer(f_expr, f_int))
    {
      error().source_location=source_location;
      error() << "failed to convert number of fraction bits to constant" << eom;
      throw 0;
    }

    if(f_int<0 || f_int>size_int)
    {
      error().source_location=source_location;
      error() << "fixedbv fraction width invalid" << eom;
      throw 0;
    }

    type.remove(ID_f);
    type.set(ID_integer_bits, integer2string(size_int-f_int));
  }
  else if(type.id()==ID_custom_floatbv)
  {
    type.id(ID_floatbv);

    exprt f_expr=
      static_cast<const exprt &>(type.find(ID_f));

    source_locationt source_location=f_expr.find_source_location();

    typecheck_expr(f_expr);

    make_constant_index(f_expr);

    mp_integer f_int;
    if(to_integer(f_expr, f_int))
    {
      error().source_location=source_location;
      error() << "failed to convert number of fraction bits to constant" << eom;
      throw 0;
    }

    if(f_int<1 || f_int+1>=size_int)
    {
      error().source_location=source_location;
      error() << "floatbv fraction width invalid" << eom;
      throw 0;
    }

    type.remove(ID_f);
    type.set(ID_f, integer2string(f_int));
  }
  else
    assert(false);
}
コード例 #19
0
ファイル: winnt-cxx.c プロジェクト: cyrilmagsuci/freebsd
bool
i386_pe_type_dllimport_p (tree decl)
{
    gcc_assert (TREE_CODE (decl) == VAR_DECL
                || TREE_CODE (decl) == FUNCTION_DECL);

    if (TARGET_NOP_FUN_DLLIMPORT && TREE_CODE (decl) == FUNCTION_DECL)
        return false;

    /* We ignore the dllimport attribute for inline member functions.
       This differs from MSVC behavior which treats it like GNUC
       'extern inline' extension.  Also ignore for template
       instantiations with linkonce semantics and artificial methods.  */
    if (TREE_CODE (decl) ==  FUNCTION_DECL
            && (DECL_DECLARED_INLINE_P (decl)
                || DECL_TEMPLATE_INSTANTIATION (decl)
                || DECL_ARTIFICIAL (decl)))
        return false;

    /* Since we can't treat a pointer to a dllimport'd symbol as a
        constant address, we turn off the attribute on C++ virtual
        methods to allow creation of vtables using thunks.  */
    else if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE
             && DECL_VIRTUAL_P (decl))
    {
        /* Even though we ignore the attribute from the start, warn if we later see
           an out-of class definition, as we do for other member functions in
           tree.c:merge_dllimport_decl_attributes.  If this is the key method, the
           definition may affect the import-export status of vtables, depending
               on how we handle MULTIPLE_SYMBOL_SPACES in cp/decl2.c.   */
        if (DECL_INITIAL (decl))
        {
            warning (OPT_Wattributes, "%q+D redeclared without dllimport attribute: "
                     "previous dllimport ignored", decl);
#ifdef PE_DLL_DEBUG
            if (decl == CLASSTYPE_KEY_METHOD (DECL_CONTEXT (decl)))
                warning (OPT_Wattributes, "key method %q+D of dllimport'd class defined"
                         decl);
#endif
        }
        return false;
    }

    /* Don't mark defined functions as dllimport.  This code will only be
       reached if we see a non-inline function defined out-of-class.  */
    else if (TREE_CODE (decl) ==  FUNCTION_DECL
             && (DECL_INITIAL (decl)))
        return false;

    /*  Don't allow definitions of static data members in dllimport class,
        If vtable data is marked as DECL_EXTERNAL, import it; otherwise just
        ignore the class attribute.  */
    else if (TREE_CODE (decl) == VAR_DECL
             && TREE_STATIC (decl) && TREE_PUBLIC (decl)
             && !DECL_EXTERNAL (decl))
    {
        if (!DECL_VIRTUAL_P (decl))
            error ("definition of static data member %q+D of "
                   "dllimport'd class", decl);
        return false;
    }

    return true;
}
コード例 #20
0
void c_typecheck_baset::typecheck_type(typet &type)
{
  // we first convert, and then check
  {
    ansi_c_convert_typet ansi_c_convert_type(get_message_handler());

    ansi_c_convert_type.read(type);
    ansi_c_convert_type.write(type);
  }

  if(type.id()==ID_already_typechecked)
  {
    // need to preserve any qualifiers
    c_qualifierst c_qualifiers(type);
    c_qualifiers+=c_qualifierst(type.subtype());
    bool packed=type.get_bool(ID_C_packed);
    exprt alignment=static_cast<const exprt &>(type.find(ID_C_alignment));

    type.swap(type.subtype());

    c_qualifiers.write(type);
    if(packed)
      type.set(ID_C_packed, true);
    if(alignment.is_not_nil())
      type.add(ID_C_alignment, alignment);

    return; // done
  }

  // do we have alignment?
  if(type.find(ID_C_alignment).is_not_nil())
  {
    exprt &alignment=static_cast<exprt &>(type.add(ID_C_alignment));
    if(alignment.id()!=ID_default)
    {
      typecheck_expr(alignment);
      make_constant(alignment);
    }
  }

  if(type.id()==ID_code)
    typecheck_code_type(to_code_type(type));
  else if(type.id()==ID_array)
    typecheck_array_type(to_array_type(type));
  else if(type.id()==ID_pointer)
    typecheck_type(type.subtype());
  else if(type.id()==ID_struct ||
          type.id()==ID_union)
    typecheck_compound_type(to_struct_union_type(type));
  else if(type.id()==ID_c_enum)
    typecheck_c_enum_type(type);
  else if(type.id()==ID_c_enum_tag)
    typecheck_c_enum_tag_type(to_c_enum_tag_type(type));
  else if(type.id()==ID_c_bit_field)
    typecheck_c_bit_field_type(to_c_bit_field_type(type));
  else if(type.id()==ID_typeof)
    typecheck_typeof_type(type);
  else if(type.id()==ID_symbol)
    typecheck_symbol_type(type);
  else if(type.id()==ID_vector)
    typecheck_vector_type(to_vector_type(type));
  else if(type.id()==ID_custom_unsignedbv ||
          type.id()==ID_custom_signedbv ||
          type.id()==ID_custom_floatbv ||
          type.id()==ID_custom_fixedbv)
    typecheck_custom_type(type);
  else if(type.id()==ID_gcc_attribute_mode)
  {
    // get that mode
    irep_idt mode=type.get(ID_size);

    // A list of all modes ist at
    // http://www.delorie.com/gnu/docs/gcc/gccint_53.html
    typecheck_type(type.subtype());

    typet underlying_type=type.subtype();

    // gcc allows this, but clang doesn't; it's a compiler hint only,
    // but we'll try to interpret it the GCC way
    if(underlying_type.id()==ID_c_enum_tag)
    {
      underlying_type=
        follow_tag(to_c_enum_tag_type(underlying_type)).subtype();

      assert(underlying_type.id()==ID_signedbv ||
             underlying_type.id()==ID_unsignedbv);
    }

    if(underlying_type.id()==ID_signedbv ||
       underlying_type.id()==ID_unsignedbv)
    {
      bool is_signed=underlying_type.id()==ID_signedbv;

      typet result;

      if(mode=="__QI__") // 8 bits
        result=is_signed?signed_char_type():unsigned_char_type();
      else if(mode=="__byte__") // 8 bits
        result=is_signed?signed_char_type():unsigned_char_type();
      else if(mode=="__HI__") // 16 bits
        result=is_signed?signed_short_int_type():unsigned_short_int_type();
      else if(mode=="__SI__") // 32 bits
        result=is_signed?signed_int_type():unsigned_int_type();
      else if(mode=="__word__") // long int, we think
        result=is_signed?signed_long_int_type():unsigned_long_int_type();
      else if(mode=="__pointer__") // we think this is size_t/ssize_t
        result=is_signed?signed_size_type():size_type();
      else if(mode=="__DI__") // 64 bits
      {
        if(config.ansi_c.long_int_width==64)
          result=is_signed?signed_long_int_type():unsigned_long_int_type();
        else
        {
          assert(config.ansi_c.long_long_int_width==64);
          result=
            is_signed?signed_long_long_int_type():unsigned_long_long_int_type();
        }
      }
      else if(mode=="__TI__") // 128 bits
        result=is_signed?gcc_signed_int128_type():gcc_unsigned_int128_type();
      else if(mode=="__V2SI__") // vector of 2 ints, deprecated by gcc
        result=
          vector_typet(
            is_signed?signed_int_type():unsigned_int_type(),
            from_integer(2, size_type()));
      else if(mode=="__V4SI__") // vector of 4 ints, deprecated by gcc
        result=
          vector_typet(
            is_signed?signed_int_type():unsigned_int_type(),
            from_integer(4, size_type()));
      else // give up, just use subtype
        result=type.subtype();

      // save the location
      result.add_source_location()=type.source_location();

      if(type.subtype().id()==ID_c_enum_tag)
      {
        const irep_idt &tag_name=
          to_c_enum_tag_type(type.subtype()).get_identifier();

        symbol_tablet::symbolst::iterator entry=
          symbol_table.symbols.find(tag_name);
        assert(entry!=symbol_table.symbols.end());

        entry->second.type.subtype()=result;
      }

      type=result;
    }
    else if(underlying_type.id()==ID_floatbv)
    {
      typet result;

      if(mode=="__SF__") // 32 bits
        result=float_type();
      else if(mode=="__DF__") // 64 bits
        result=double_type();
      else if(mode=="__TF__") // 128 bits
        result=gcc_float128_type();
      else if(mode=="__V2SF__") // vector of 2 floats, deprecated by gcc
        result=vector_typet(float_type(), from_integer(2, size_type()));
      else if(mode=="__V2DF__") // vector of 2 doubles, deprecated by gcc
        result=vector_typet(double_type(), from_integer(2, size_type()));
      else if(mode=="__V4SF__") // vector of 4 floats, deprecated by gcc
        result=vector_typet(float_type(), from_integer(4, size_type()));
      else if(mode=="__V4DF__") // vector of 4 doubles, deprecated by gcc
        result=vector_typet(double_type(), from_integer(4, size_type()));
      else // give up, just use subtype
        result=type.subtype();

      // save the location
      result.add_source_location()=type.source_location();

      type=result;
    }
    else if(underlying_type.id()==ID_complex)
    {
      // gcc allows this, but clang doesn't -- see enums above
      typet result;

      if(mode=="__SC__") // 32 bits
        result=float_type();
      else if(mode=="__DC__") // 64 bits
        result=double_type();
      else if(mode=="__TC__") // 128 bits
        result=gcc_float128_type();
      else // give up, just use subtype
        result=type.subtype();

      // save the location
      result.add_source_location()=type.source_location();

      type=complex_typet(result);
    }
    else
    {
      error().source_location=type.source_location();
      error() << "attribute mode `" << mode
              << "' applied to inappropriate type `"
              << to_string(type) << "'" << eom;
      throw 0;
    }
  }

  // do a mild bit of rule checking

  if(type.get_bool(ID_C_restricted) &&
     type.id()!=ID_pointer &&
     type.id()!=ID_array)
  {
    error().source_location=type.source_location();
    error() << "only a pointer can be 'restrict'" << eom;
    throw 0;
  }
}
コード例 #21
0
ファイル: test.c プロジェクト: schambersnh/school
int main (int argc, char *argv[])
{
    long i;
    int j;
    int correctSum = 0;
    int trials = TRIALS;
    int passed = 0;
    char *chkArg;

    if (argc != 2)
    {
        fprintf(stderr, "Usage: sync numberOfThreads\n");
        exit(-1);
    }

    n = strtol(argv[1], &chkArg, 10);

    // validate the command-line argument

    // errno would indicate overflow,
    // null string is also not allowed of course,
    // and, the full argument must be consumed
    if (errno || (*argv[1]  == '\0') || (*chkArg != '\0'))
    {
        fprintf(stderr, "invalid number of threads\n");
        exit(-1);
    }

    // finally, given integer must be in the correct range
    if (n <= 0)
    {
        fprintf(stderr, "number of threads must be > 0\n");
        exit(-1);
    }

    printf("using %d child threads\n", n);

    // compute the correct sum
    for (i = 0; i < N; i++)
    {
        correctSum += i;
    }

    // distribute the work
    chunk = N / n;
    split = N % n;
    if (split == 0)
    {
        split = n;
        chunk -= 1;
    }

    // initialize the mutex
    if (thread_mutex_init(&mu) == 0)
        error("can't init mutex");

    if (thread_mutex_init(&mu2) == 0)
        error("can't init mutex");

    // do the trials
    for (j = 0; j < trials; j++)
    {
        fprintf(stderr, "Trial %d/%d complete.\n", j, trials);
        cnt = 0;   // number of child threads that have exited

        sum = 0;

        for (i=0; i < n; i++)
        {
            if(i%2 == 0)
            {
                // create threads; DANGER: thread logical id (int) passed as "void *"
                if (thread_create(work, (void *) i) == 0)
                    error("error in thread create");
            }
            else
            {
                // create threads; DANGER: thread logical id (int) passed as "void *"
                if (thread_create(work2, (void *) i) == 0)
                    error("error in thread create");
            }
        }

        // wait for all children to finish
        while (cnt != n)
        {
            thread_yield();
        }

        if (sum == correctSum)
        {
            passed += 1;
        }
    }

    printf ("%d of %d trials passed\n", passed, trials);

    return 0;
}
コード例 #22
0
void c_typecheck_baset::typecheck_code_type(code_typet &type)
{
  // the return type is still 'subtype()'
  type.return_type()=type.subtype();
  type.remove_subtype();

  code_typet::parameterst &parameters=type.parameters();

  // if we don't have any parameters, we assume it's (...)
  if(parameters.empty())
  {
    type.make_ellipsis();
  }
  else // we do have parameters
  {
    // is the last one ellipsis?
    if(type.parameters().back().id()==ID_ellipsis)
    {
      type.make_ellipsis();
      type.parameters().pop_back();
    }

    parameter_map.clear();

    for(auto &param : type.parameters())
    {
      // turn the declarations into parameters
      if(param.id()==ID_declaration)
      {
        ansi_c_declarationt &declaration=
          to_ansi_c_declaration(param);

        code_typet::parametert parameter;

        // first fix type
        typet &type=parameter.type();
        type=declaration.full_type(declaration.declarator());
        std::list<codet> tmp_clean_code;
        tmp_clean_code.swap(clean_code); // ignore side-effects
        typecheck_type(type);
        tmp_clean_code.swap(clean_code);
        adjust_function_parameter(type);

        // adjust the identifier
        irep_idt identifier=declaration.declarator().get_name();

        // abstract or not?
        if(identifier==irep_idt())
        {
          // abstract
          parameter.add_source_location()=declaration.type().source_location();
        }
        else
        {
          // make visible now, later parameters might use it
          parameter_map[identifier]=type;
          parameter.set_base_name(declaration.declarator().get_base_name());
          parameter.add_source_location()=
            declaration.declarator().source_location();
        }

        // put the parameter in place of the declaration
        param.swap(parameter);
      }
    }

    parameter_map.clear();

    if(parameters.size()==1 &&
       follow(parameters[0].type()).id()==ID_empty)
    {
      // if we just have one parameter of type void, remove it
      parameters.clear();
    }
  }

  typecheck_type(type.return_type());

  // 6.7.6.3:
  // "A function declarator shall not specify a return type that
  // is a function type or an array type."

  const typet &return_type=follow(type.return_type());

  if(return_type.id()==ID_array)
  {
    error().source_location=type.source_location();
    error() << "function must not return array" << eom;
    throw 0;
  }

  if(return_type.id()==ID_code)
  {
    error().source_location=type.source_location();
    error() << "function must not return function type" << eom;
    throw 0;
  }
}
コード例 #23
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType go	(	Parm1) 							{ return error(1); };
コード例 #24
0
void c_typecheck_baset::typecheck_array_type(array_typet &type)
{
  exprt &size=type.size();
  source_locationt source_location=size.find_source_location();

  // check subtype
  typecheck_type(type.subtype());

  // we don't allow void as subtype
  if(follow(type.subtype()).id()==ID_empty)
  {
    error().source_location=type.source_location();
    error() << "array of voids" << eom;
    throw 0;
  }

  // check size, if any

  if(size.is_not_nil())
  {
    typecheck_expr(size);
    make_index_type(size);

    // The size need not be a constant!
    // We simplify it, for the benefit of array initialisation.

    exprt tmp_size=size;
    add_rounding_mode(tmp_size);
    simplify(tmp_size, *this);

    if(tmp_size.is_constant())
    {
      mp_integer s;
      if(to_integer(tmp_size, s))
      {
        error().source_location=source_location;
        error() << "failed to convert constant: "
                << tmp_size.pretty() << eom;
        throw 0;
      }

      if(s<0)
      {
        error().source_location=source_location;
        error() << "array size must not be negative, "
                   "but got " << s << eom;
        throw 0;
      }

      size=tmp_size;
    }
    else if(tmp_size.id()==ID_infinity)
    {
      size=tmp_size;
    }
    else if(tmp_size.id()==ID_symbol &&
            tmp_size.type().get_bool(ID_C_constant))
    {
      // We allow a constant variable as array size, assuming
      // it won't change.
      // This criterion can be tricked:
      // Of course we can modify a 'const' symbol, e.g.,
      // using a pointer type cast. Interestingly,
      // at least gcc 4.2.1 makes the very same mistake!
      size=tmp_size;
    }
    else
    {
      // not a constant and not infinity

      assert(current_symbol_id!=irep_idt());

      const symbolt &base_symbol=lookup(current_symbol_id);

      // Need to pull out! We insert new symbol.
      source_locationt source_location=size.find_source_location();
      unsigned count=0;
      irep_idt temp_identifier;
      std::string suffix;

      do
      {
        suffix="$array_size"+std::to_string(count);
        temp_identifier=id2string(base_symbol.name)+suffix;
        count++;
      }
      while(symbol_table.symbols.find(temp_identifier)!=
            symbol_table.symbols.end());

      // add the symbol to symbol table
      auxiliary_symbolt new_symbol;
      new_symbol.name=temp_identifier;
      new_symbol.pretty_name=id2string(base_symbol.pretty_name)+suffix;
      new_symbol.base_name=id2string(base_symbol.base_name)+suffix;
      new_symbol.type=size.type();
      new_symbol.type.set(ID_C_constant, true);
      new_symbol.is_type=false;
      new_symbol.is_static_lifetime=false;
      new_symbol.value.make_nil();
      new_symbol.location=source_location;

      symbol_table.add(new_symbol);

      // produce the code that declares and initializes the symbol
      symbol_exprt symbol_expr;
      symbol_expr.set_identifier(temp_identifier);
      symbol_expr.type()=new_symbol.type;

      code_declt declaration(symbol_expr);
      declaration.add_source_location()=source_location;

      code_assignt assignment;
      assignment.lhs()=symbol_expr;
      assignment.rhs()=size;
      assignment.add_source_location()=source_location;

      // store the code
      clean_code.push_back(declaration);
      clean_code.push_back(assignment);

      // fix type
      size=symbol_expr;
    }
  }
}
コード例 #25
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType go	(	Parm1,Parm2,Parm3) 					{ return error(3); };
コード例 #26
0
void c_typecheck_baset::typecheck_vector_type(vector_typet &type)
{
  exprt &size=type.size();
  source_locationt source_location=size.find_source_location();

  typecheck_expr(size);

  typet &subtype=type.subtype();
  typecheck_type(subtype);

  // we are willing to combine 'vector' with various
  // other types, but not everything!

  if(subtype.id()!=ID_signedbv &&
     subtype.id()!=ID_unsignedbv &&
     subtype.id()!=ID_floatbv &&
     subtype.id()!=ID_fixedbv)
  {
    error().source_location=source_location;
    error() << "cannot make a vector of subtype "
            << to_string(subtype) << eom;
    throw 0;
  }

  make_constant_index(size);

  mp_integer s;
  if(to_integer(size, s))
  {
    error().source_location=source_location;
    error() << "failed to convert constant: "
            << size.pretty() << eom;
    throw 0;
  }

  if(s<=0)
  {
    error().source_location=source_location;
    error() << "vector size must be positive, "
               "but got " << s << eom;
    throw 0;
  }

  // the subtype must have constant size
  exprt size_expr=c_sizeof(type.subtype(), *this);

  simplify(size_expr, *this);

  mp_integer sub_size;

  if(to_integer(size_expr, sub_size))
  {
    error().source_location=source_location;
    error() << "failed to determine size of vector base type `"
            << to_string(type.subtype()) << "'" << eom;
    throw 0;
  }

  if(sub_size==0)
  {
    error().source_location=source_location;
    error() << "type had size 0: `"
            << to_string(type.subtype()) << "'" << eom;
    throw 0;
  }

  // adjust by width of base type
  if(s%sub_size!=0)
  {
    error().source_location=source_location;
    error() << "vector size (" << s
            << ") expected to be multiple of base type size (" << sub_size
            << ")" << eom;
    throw 0;
  }

  s/=sub_size;

  type.size()=from_integer(s, signed_size_type());
}
コード例 #27
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType go	(	Parm1,Parm2,Parm3,Parm4,Parm5) 				{ return error(5); };
コード例 #28
0
void c_typecheck_baset::typecheck_compound_type(struct_union_typet &type)
{
  // These get replaced by symbol types later.
  irep_idt identifier;

  bool have_body=type.find(ID_components).is_not_nil();

  if(type.find(ID_tag).is_nil())
  {
    // Anonymous? Must come with body.
    assert(have_body);

    // produce symbol
    symbolt compound_symbol;
    compound_symbol.is_type=true;
    compound_symbol.type=type;
    compound_symbol.location=type.source_location();

    typecheck_compound_body(to_struct_union_type(compound_symbol.type));

    std::string typestr=type2name(compound_symbol.type);
    compound_symbol.base_name="#anon-"+typestr;
    compound_symbol.name="tag-#anon#"+typestr;
    identifier=compound_symbol.name;

    // We might already have the same anonymous union/struct,
    // and this is simply ok. Note that the C standard treats
    // these as different types.
    if(symbol_table.symbols.find(identifier)==symbol_table.symbols.end())
    {
      symbolt *new_symbol;
      move_symbol(compound_symbol, new_symbol);
    }
  }
  else
  {
    identifier=type.find(ID_tag).get(ID_identifier);

    // does it exist already?
    symbol_tablet::symbolst::iterator s_it=
      symbol_table.symbols.find(identifier);

    if(s_it==symbol_table.symbols.end())
    {
      // no, add new symbol
      irep_idt base_name=type.find(ID_tag).get(ID_C_base_name);
      type.remove(ID_tag);
      type.set(ID_tag, base_name);

      symbolt compound_symbol;
      compound_symbol.is_type=true;
      compound_symbol.name=identifier;
      compound_symbol.base_name=base_name;
      compound_symbol.type=type;
      compound_symbol.location=type.source_location();
      compound_symbol.pretty_name=id2string(type.id())+" "+id2string(base_name);

      typet new_type=compound_symbol.type;

      if(compound_symbol.type.id()==ID_struct)
        compound_symbol.type.id(ID_incomplete_struct);
      else if(compound_symbol.type.id()==ID_union)
        compound_symbol.type.id(ID_incomplete_union);
      else
        assert(false);

      symbolt *new_symbol;
      move_symbol(compound_symbol, new_symbol);

      if(have_body)
      {
        typecheck_compound_body(to_struct_union_type(new_type));

        new_symbol->type.swap(new_type);
      }
    }
    else
    {
      // yes, it exists already
      if(s_it->second.type.id()==ID_incomplete_struct ||
         s_it->second.type.id()==ID_incomplete_union)
      {
        // Maybe we got a body now.
        if(have_body)
        {
          irep_idt base_name=type.find(ID_tag).get(ID_C_base_name);
          type.remove(ID_tag);
          type.set(ID_tag, base_name);

          typecheck_compound_body(type);
          s_it->second.type.swap(type);
        }
      }
      else if(have_body)
      {
        error().source_location=type.source_location();
        error() << "redefinition of body of `"
                << s_it->second.pretty_name << "'" << eom;
        throw 0;
      }
    }
  }

  symbol_typet symbol_type;
  symbol_type.add_source_location()=type.source_location();
  symbol_type.set_identifier(identifier);

  c_qualifierst original_qualifiers(type);
  type.swap(symbol_type);
  original_qualifiers.write(type);
}
コード例 #29
0
ファイル: FunctorWrapper.hpp プロジェクト: DEMANY/trunk
		virtual ResultType goReverse(	Parm1) 							{ return error(1); };
コード例 #30
0
ファイル: bootloader.c プロジェクト: PIC-Niagara/MPcopy
static void file_flash(FSFILE* file)
{
	UINT readBytes;
	UINT i;

	// Erase Flash (Block Erase the program Flash)
	if (NVMemBlockErase() != 0)
	{
		error(ERR_NV_ERASE);
	}

	record.status = REC_NOT_FOUND;      // Initialize the state-machine to read the records.

	while (1)
	{
		USBTasks();
		BlinkBlueLED();
		BlinkOrangeLED();

		// For a faster read, fetch 512 bytes at a time and buffer it.
		readBytes = FSfread((void*)&asciiBuffer[pointer], 1, 512, file);

		if (readBytes == 0)
		{
			// Nothing to read. Come out of this loop
			// break;
			// Jump to start of application
			// Disable all enabled interrupts (only USB)
			// before jumping to the application code.
			IEC5bits.USB1IE = 0;
//			JumpToApp();
			return;
		}

		for (i = 0; i < (readBytes + pointer); i ++)
		{
			// This state machine seperates-out the valid hex records from the read 512 bytes.
			switch (record.status)
			{
			case REC_FLASHED:
			case REC_NOT_FOUND:
				if (asciiBuffer[i] == ':')
				{
					// We have a record found in the 512 bytes of data in the buffer.
					record.start = &asciiBuffer[i];
					record.len = 0;
					record.status = REC_FOUND_BUT_NOT_FLASHED;
				}
				break;
			case REC_FOUND_BUT_NOT_FLASHED:
				if ((asciiBuffer[i] == 0x0A) || (asciiBuffer[i] == 0xFF))
				{
					// We have got a complete record. (0x0A is new line feed and 0xFF is End of file)
					// Start the hex conversion from element
					// 1. This will discard the ':' which is
					// the start of the hex record.
					ConvertAsciiToHex(&record.start[1], hexRec);
					WriteHexRecord2Flash(hexRec);
					record.status = REC_FLASHED;
				}
				break;
			}
			record.len ++;  // Move to next byte in the buffer.
		}

		if (record.status == REC_FOUND_BUT_NOT_FLASHED)
		{
			// We still have a half read record in the buffer. The next half part of the record is read 
			// when we read 512 bytes of data from the next file read. 
			memcpy(asciiBuffer, record.start, record.len);
			pointer = record.len;
			record.status = REC_NOT_FOUND;
		}
		else
		{
			pointer = 0;
		}
	}
}