Esempio n. 1
0
static IDCOffer_clp UnixLoginMod_New_m (
    UnixLoginMod_cl     *self,
    IDCOffer_clp    fs      /* IN */,
    string_t        passwd  /* IN */,
    string_t        group   /* IN */ )
{
    UnixLoginMod_st     *lst;
    Login_st        *st;
    FSClient_clp     fsclient;
    Type_Any         any, *dirany;
    FSTypes_RC       rc;
    FSDir_clp        dir;
    FileIO_clp       fileio;
    Rd_clp           rd;
    FSUtil_clp       fsutil;
    StringTblMod_clp strtbl;
    IDCTransport_clp shmt;
    IDCOffer_clp     offer;
    IDCService_clp   service;
    char buff[124];

    TRC(printf("UnixLoginMod_New_m(%p, %s, %s)\n",fs,passwd,group));

    fsutil=NAME_FIND("modules>FSUtil", FSUtil_clp);
    strtbl=NAME_FIND("modules>StringTblMod", StringTblMod_clp);
    shmt=NAME_FIND("modules>ShmTransport", IDCTransport_clp);

    lst=Heap$Malloc(Pvs(heap), sizeof(*lst));
    lst->heap=Pvs(heap);

    /* Bind to security service */
    TRC(printf(" + binding to security service\n"));
    lst->sec=IDC_OPEN("sys>SecurityOffer", Security_clp);

    /* Bind to FS */
    TRC(printf(" + binding to filesystem\n"));
    fsclient=IDC_BIND(fs, FSClient_clp);
    
    rc=FSClient$GetDir(fsclient, "", True, &dirany);
    if (rc!=FSTypes_RC_OK) {
	printf("UnixLoginMod: couldn't get directory\n");
	FREE(lst);
	return NULL;
    }

    dir=NARROW(dirany, FSDir_clp);
    FREE(dirany);

    /* Create tables */
    TRC(printf(" + creating tables\n"));
    lst->users=StringTblMod$New(strtbl, lst->heap);
    lst->groups=StringTblMod$New(strtbl, lst->heap);
    lst->certificate_tbl=StringTblMod$New(strtbl, lst->heap);
    lst->certificate_id = 1;

    /* Read in passwd file */
    TRC(printf(" + reading password file\n"));
    rc=FSDir$Lookup(dir, passwd, True);
    if (rc!=FSTypes_RC_OK) {
	printf("UnixLoginMod: couldn't lookup passwd file\n");
	FREE(lst);
	return NULL;
    }

    rc=FSDir$Open(dir, 0, FSTypes_Mode_Read, 0, &fileio);
    if (rc!=FSTypes_RC_OK) {
	printf("UnixLoginMod: couldn't open passwd file\n");
	FREE(lst);
	return NULL;
    }

    rd=FSUtil$GetRd(fsutil, fileio, lst->heap, True);
    
    while (!Rd$EOF(rd))
    {
	uint32_t l;
	l=Rd$GetLine(rd, buff, 120);
	buff[l]=0;
	/* TRC(printf("->%s\n",buff)); */
	add_passwd_line(lst, buff);
    }

    Rd$Close(rd);

    /* Read in group file */
    TRC(printf(" + reading group file\n"));
    rc=FSDir$Lookup(dir, group, True);
    if (rc!=FSTypes_RC_OK) {
	printf("UnixLoginMod: couldn't lookup group file\n");
	FREE(lst);
	return NULL;
    }

    rc=FSDir$Open(dir, 0, FSTypes_Mode_Read, 0, &fileio);
    if (rc!=FSTypes_RC_OK) {
	printf("UnixLoginMod: couldn't open group file\n");
	FREE(lst);
	return NULL;
    }

    rd=FSUtil$GetRd(fsutil, fileio, lst->heap, True);

    while (!Rd$EOF(rd))
    {
	uint32_t l;
	l=Rd$GetLine(rd, buff, 120);
	buff[l]=0;
	/* TRC(printf("=>%s\n",buff)); */
	add_group_line(lst, buff);
    }

    Rd$Close(rd);

    /* We don't need the filesystem any more */
    FSDir$Close(dir);

    LINK_INITIALISE(&lst->certificate_list);

    MU_INIT(&lst->mu);

    /* Closure for local access to the server */

    st=Heap$Malloc(lst->heap, sizeof(*st));
    CL_INIT(st->cl, &login_ms, st);
    st->id=VP$DomainID(Pvs(vp));
    st->lst=lst;

    /* Export */
    TRC(printf(" + exporting Login service\n"));
    ANY_INIT(&any, Login_clp, &st->cl);
    CL_INIT(lst->callback, &callback_ms, lst);
    offer=IDCTransport$Offer(shmt, &any, &lst->callback, lst->heap,
			     Pvs(gkpr), Pvs(entry), &service);

    return offer;
}
Esempio n. 2
0
static void ProcOptList( int pass )
{
    char        buff[80];
    char        err_buff[CMD_LEN];
    char        *curr;
    unsigned long   mem;

    SetupChar(); /* initialize scanner */
    for( ;; ) {
        SkipSpaces();
        if( !OptDelim( CurrChar ) ) break;
        NextChar();
        curr = buff;
#ifndef __GUI__
        if( CurrChar == '?' ) {
            PrintUsage( MSG_USAGE_BASE );
            StartupErr( "" );
        }
#endif
        while( isalnum( CurrChar ) ) {
            *curr++ = CurrChar;
            NextChar();
        }
        if( curr == buff ) {
            if( OptDelim( CurrChar ) ) {
                NextChar();
                SkipSpaces();
                break;
            }
            OptError( LIT( STARTUP_No_Recog_Optn ) );
        }
        switch( Lookup( OptNameTab, buff, curr - buff ) ) {
        case OPT_CONTINUE_UNEXPECTED_BREAK:
            _SwitchOn( SW_CONTINUE_UNEXPECTED_BREAK );
            break;
        case OPT_DEFERSYM:
            _SwitchOn( SW_DEFER_SYM_LOAD );
            break;
        case OPT_DOWNLOAD:
            DownLoadTask = TRUE;
            break;
        case OPT_NOEXPORTS:
            _SwitchOn( SW_NO_EXPORT_SYMS );
            break;
        case OPT_LOCALINFO:
            if( pass == 2 ) {
                char *file = GetFileName( pass );
                FindLocalDebugInfo( file );
                _Free( file );
            }
            break;
        case OPT_INVOKE:
            if( pass == 2 ) _Free( InvokeFile );
            InvokeFile = GetFileName( pass );
            break;
        case OPT_NOINVOKE:
            if( pass == 2 ) _Free( InvokeFile );
            InvokeFile = NULL;
            break;
        case OPT_NOSOURCECHECK:
            _SwitchOff( SW_CHECK_SOURCE_EXISTS );
            break;
        case OPT_NOSYMBOLS:
            _SwitchOff( SW_LOAD_SYMS );
            break;
        case OPT_NOMOUSE:
            _SwitchOff( SW_USE_MOUSE );
            break;
        case OPT_DYNAMIC:
            mem = GetMemory();
            if( pass == 1 ) {
                if( mem < MIN_MEM_SIZE ) mem = MIN_MEM_SIZE;
                MemSize = mem;
            }
            break;
        case OPT_DIP:
            {
                int i;

                for( i = 0; DipFiles[ i ] != NULL; ++i ) ;
                DipFiles[ i ] = GetFileName( pass );
            }
            break;
        case OPT_TRAP:
            if( pass == 2 ) _Free( TrpFile );
            TrpFile = GetFileName( pass );
            SkipSpaces();
            if( CurrChar == ';' ) {
                NextChar();
                GetTrapParm( pass );
            } else if( CurrChar == '{' ) {
                GetTrapParm( pass );
            }
            break;
#ifdef ENABLE_TRAP_LOGGING
        case OPT_TRAP_DEBUG_FLUSH:
            if( pass == 2 )
                _Free( TrpDebugFile );
            TrpDebugFile = GetFileName( pass );
            TrpDebugFileFlush = TRUE;
            break;
        case OPT_TRAP_DEBUG:
            if( pass == 2 )
                _Free( TrpDebugFile );
            TrpDebugFile = GetFileName( pass );
            TrpDebugFileFlush = FALSE;
            break;
#endif
        case OPT_REMOTE_FILES:
            _SwitchOn( SW_REMOTE_FILES );
            break;
        case OPT_LINES:
            SetNumLines( GetValue() );
            break;
        case OPT_COLUMNS:
            SetNumColumns( GetValue() );
            break;
#ifdef BACKWARDS
        case OPT_NO_FPU:
        case OPT_NO_ALTSYM:
            break;
        case OPT_REGISTERS:
            GetValue();
            break;
#endif
        case OPT_INITCMD:
            GetInitCmd( pass );
            break;
        case OPT_POWERBUILDER:
            _SwitchOn( SW_POWERBUILDER );
            break;
        case OPT_HELP:
#ifndef __GUI__
            PrintUsage( MSG_USAGE_BASE );
            StartupErr( "" );
#endif
            break;
        default:
            if( !ProcSysOption( buff, curr - buff, pass ) ) {
                Format( err_buff, LIT( STARTUP_Invalid_Option ), buff, curr - buff );
                StartupErr( err_buff );
            }
            break;
        }
    }
}
Esempio n. 3
0
void SymtabTraverseTree(TreeNode *p, char *path, int nestLevel, SymbolTable *symtab){
	char local_path[256];
	if (!p) return ;
	// printf("path:%s\n", path);
	switch (p->node){
		case routine_kind: {
			SymtabTraverseTree(p->children[0], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[1], path, nestLevel, symtab);
			break;
		}
		case const_kind: {
			if (DuplicateIdentifier(p->name, path))
				throw_error("duplicate identifier", p);
			InsertSymbol(p->name, p, symtab);
			SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
			break;
		} 
		case type_kind: {
			switch (p->type){
				case decl_type:{
					if (DuplicateIdentifier(p->name, path))
						throw_error("duplicate identifier", p);
					InsertSymbol(p->name, p, symtab);
					if(p->dtype->type!=record_type){
						SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
					} else {
						sprintf(local_path, "%s/%s", path, p->name);
						SymbolTable *new_symtab = CreateSymbolTable(local_path, nestLevel+1);
						ConnectSymtabs(symtab, new_symtab);
						SymtabTraverseTree(p->dtype, local_path, nestLevel+1, new_symtab);
						SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
					}
					break;
				}
				case record_type:{
					SymtabTraverseTree(p->children[0], path, nestLevel, symtab);
					break;
				}
				default:{ break; }
			}
			break;
		}
		case var_kind:{
			TreeNode *q;
			q = p->children[0];
			while (q){
				if (DuplicateIdentifier(q->name, path))
					throw_error("duplicate identifier", q);
				InsertSymbol(q->name, p, symtab);
				q = q->sibling;
			}
			SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
			break;
		} 
		case sub_kind: {
			switch(p->sub){
				case func_kind:{
					// printf("enter function %s decl:\n", p->name);
					InsertSymbol(p->name, p, symtab);
					sprintf(local_path, "%s/%s", path, p->name);
					SymbolTable * new_symtab = CreateSymbolTable(local_path, nestLevel+1);
					ConnectSymtabs(symtab, new_symtab);
					SymtabTraverseTree(p->children[0], local_path, nestLevel+1, new_symtab);
					SymtabTraverseTree(p->children[1], local_path, nestLevel+1, new_symtab);
					SymtabTraverseTree(p->children[2], local_path, nestLevel+1, new_symtab);
					break;
				}
				case proc_kind:{
					// printf("enter procedure %s decl:\n", p->name);
					InsertSymbol(p->name, p, symtab);
					sprintf(local_path, "%s/%s", path, p->name);
					SymbolTable * new_symtab = CreateSymbolTable(local_path, nestLevel+1);
					ConnectSymtabs(symtab, new_symtab);
					SymtabTraverseTree(p->children[0], local_path, nestLevel+1, new_symtab);
					SymtabTraverseTree(p->children[1], local_path, nestLevel+1, new_symtab);
					SymtabTraverseTree(p->children[2], local_path, nestLevel+1, new_symtab);
					break;
				}
				case param_var_kind:{
					TreeNode *q;
					q = p->children[0];
					while (q){
						if (DuplicateIdentifier(q->name, path))
							throw_error("duplicate identifier", q);
						InsertSymbol(q->name, p, symtab);
						q = q->sibling;
					}
					break;
				}
				case param_val_kind:{
					TreeNode *q;
					q = p->children[0];
					while (q){
						if (DuplicateIdentifier(q->name, path))
							throw_error("duplicate identifier", q);
						InsertSymbol(q->name, p, symtab);
						q = q->sibling;
					}
					break;
				}
			}
			SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
			break;
		};
		case expr_kind:{
			switch (p->expr){
				case id_kind:{
					// printf("look for identifier: %s\n", p->name);
					if (!Lookup(p->name, path))
						throw_error("unknown identifier", p);
					break;
				}
				case fn_kind:{
					// printf("look for function: %s\n", p->name);
					if (!Lookup(p->name, path) && !p->system)
						throw_error("unknown identifier", p);
				}
				default: break;
			}
			SymtabTraverseTree(p->children[0], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[1], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[2], path, nestLevel, symtab);
			SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
			break;
		}
		case stmt_kind:{
			switch (p->stmt){
				case for_stmt:{
					if (!Lookup(p->name, path))
						throw_error("unknown identifier", p);
				}
				case proc_stmt:{
					if (!Lookup(p->name, path) && !p->system)
						throw_error("unknown identifier", p);
				}
			}
			SymtabTraverseTree(p->children[0], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[1], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[2], path, nestLevel, symtab);
			SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
			break;
		}
		default: {
			SymtabTraverseTree(p->children[0], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[1], path, nestLevel, symtab);
			SymtabTraverseTree(p->children[2], path, nestLevel, symtab);
			SymtabTraverseTree(p->sibling, path, nestLevel, symtab);
			break;
		}
	}
}
Esempio n. 4
0
void COMF::DumpRelocations() {
   // Dump all LEDATA, LIDATA, COMDAT and FIXUPP records
   uint32 LastDataRecord = 0;          // Index to the data record that relocations refer to
   uint32 LastDataRecordSize = 0;      // Size of the data record that relocations refer to
   int8 * LastDataRecordPointer = 0;   // Pointer to data in the data record that relocations refer to
   uint32 i;                           // Loop counter
   uint32 Segment, Offset, Size;       // Contents of LEDATA or LIDATA record
   uint32 LastOffset = 0;              // Offset of last LEDATA or LIDATA record
   uint32 Frame, Target, TargetDisplacement; // Contents of FIXUPP record
   uint8 byte1, byte2;                 // First two bytes of subrecord

   // Bitfields in subrecords
   OMF_SLocat Locat;         // Structure of first two bytes of FIXUP subrecord swapped = Locat field
   OMF_SFixData FixData;     // Structure of FixData field in FIXUP subrecord of FIXUPP record
   OMF_STrdDat TrdDat;       // Structure of Thread Data field in THREAD subrecord of FIXUPP record

   printf("\n\nLEDATA, LIDATA, COMDAT and FIXUPP records:");
   for (i = 0; i < NumRecords; i++) {
      if (Records[i].Type2 == OMF_LEDATA) {
         // LEDATA record
         Segment = Records[i].GetIndex();             // Read segment and offset
         Offset  = Records[i].GetNumeric();
         Size    = Records[i].End - Records[i].Index; // Calculate size of data
         LastDataRecord = i;                          // Save for later FIXUPP that refers to this record
         LastDataRecordSize = Size;
         LastDataRecordPointer = Records[i].buffer + Records[i].FileOffset + Records[i].Index;
         if (Segment < 0x4000) {
            printf("\n  LEDATA: segment %s, Offset 0x%X, Size 0x%X", // Dump segment, offset, size
               GetSegmentName(Segment), Offset, Size);
            LastOffset = Offset;
         }
         else { // Undocumented Borland communal section
            printf("\n  LEDATA communal section %i, Offset 0x%X, Size 0x%X", // Dump segment, offset, size
               (Segment & ~0x4000), Offset, Size);
            LastOffset = Offset;
         }
      }

      if (Records[i].Type2 == OMF_LIDATA) {
         // LIDATA record
         Segment = Records[i].GetIndex();
         Offset  = Records[i].GetNumeric();
         LastDataRecord = i;
         LastDataRecordSize = Records[i].End - Records[i].Index; // Size before expansion of repeat blocks
         LastDataRecordPointer = Records[i].buffer + Records[i].FileOffset + Records[i].Index;
         printf("\n  LIDATA: segment %s, Offset 0x%X, Size ",
            GetSegmentName(Segment), Offset);
         // Call recursive function to interpret repeat data block
         Size = Records[i].InterpretLIDATABlock();
         printf(" = 0x%X", Size);
         LastOffset = Offset;
      }

      if (Records[i].Type2 == OMF_COMDAT) {
         // COMDAT record
         uint32 Flags = Records[i].GetByte(); // 1 = continuation, 2 = iterated, 4 = local, 8 = data in code segment
         uint32 Attributes = Records[i].GetByte(); 
         uint32 Base = 0;
         // 0 = explicit, 1 = far code, 2 = far data, 3 = code32, 4 = data32
         // 0x00 = no match, 0x10 = pick any, 0x20 = same size, 0x30 = exact match
         uint32 Align = Records[i].GetByte(); // Alignment
         Offset  = Records[i].GetNumeric();    // Offset
         uint32 TypeIndex = Records[i].GetIndex(); // Type index
         if ((Attributes & 0x0F) == 0) {
            Base = Records[i].GetIndex(); // Public base
         }
         uint32 NameIndex = Records[i].GetIndex(); // LNAMES index
         Size    = Records[i].End - Records[i].Index; // Calculate size of data

         printf("\n  COMDAT: name %s, Offset 0x%X, Size 0x%X, Attrib 0x%02X, Align %i, Type %i, Base %i",
            GetLocalName(NameIndex), Offset, Size, Attributes, Align, TypeIndex, Base);
         LastOffset = Offset;
      }

      if (Records[i].Type2 == OMF_FIXUPP) {
         // FIXUPP record
         printf("\n  FIXUPP:");
         Records[i].Index = 3;

         // Loop through entries in record
         while (Records[i].Index < Records[i].End) {

            // Read first byte
            byte1 = Records[i].GetByte();
            if (byte1 & 0x80) {
               // This is a FIXUP subrecord
               Frame = 0; Target = 0; TargetDisplacement = 0;

               // read second byte
               byte2 = Records[i].GetByte();
               // swap bytes and put into byte12 bitfield
               Locat.bytes[1] = byte1;
               Locat.bytes[0] = byte2;
               // Read FixData
               FixData.b = Records[i].GetByte();

               // print mode and location
               printf("\n   %s %s, Offset 0x%X", 
                  Lookup(OMFRelocationModeNames, Locat.s.M),
                  Lookup(OMFFixupLocationNames, Locat.s.Location),
                  Locat.s.Offset + LastOffset);

               // Read conditional fields
               if (FixData.s.F == 0) {
                  if (FixData.s.Frame < 4) {
                     Frame = Records[i].GetIndex();
                  }
                  else Frame = 0;

                  switch (FixData.s.Frame) { // Frame method
                  case 0:  // F0: segment
                     printf(", segment %s", GetSegmentName(Frame));  break;

                  case 1:  // F1: group
                     printf(", group %s", GetGroupName(Frame));  break;

                  case 2:  // F2: external symbol
                     printf(", external frame %s", GetSymbolName(Frame));  break;

                  case 4:  // F4: frame = source, 
                           // or Borland floating point emulation record (undocumented?)
                     printf(", frame = source; or Borland f.p. emulation record");
                     break;

                  case 5:  // F5: frame = target
                     printf(", frame = target");  break;

                  default:
                     printf(", target frame %i method F%i", Frame, FixData.s.Frame);
                  }
               }
               else {
                  printf(", frame uses thread %i", FixData.s.Frame);
               }
               
               if (FixData.s.T == 0) {
                  // Target specified
                  Target = Records[i].GetIndex();
                  uint32 TargetMethod = FixData.s.Target + FixData.s.P * 4;

                  switch (FixData.s.Target) { // = Target method modulo 4
                  case 0: // T0 and T4: Target = segment
                  case 1: // T1 and T5: Target = segment group
                     printf(". Segment %s (T%i)",
                        GetSegmentName(Target), TargetMethod);
                     break;
                  case 2: // T2 and T6: Target = external symbol
                     printf(". Symbol %s (T%i)",
                        GetSymbolName(Target), TargetMethod);
                     break;
                  default: // Unknown method
                     printf(", target %i unknown method T%i", Target, TargetMethod);
                  }
               }
               else {
                  // Target specified in previous thread
                  printf(", target uses thread %i", FixData.s.Target);
               }

               if (FixData.s.P == 0) {
                  TargetDisplacement = Records[i].GetNumeric();
                  printf("\n    target displacement %i", TargetDisplacement);
               }
               // Get inline addend
               if (LastDataRecordPointer && Locat.s.Offset < LastDataRecordSize) {
                  int8 * inlinep = LastDataRecordPointer + Locat.s.Offset;
                  switch (Locat.s.Location) {
                  case 0: case 4:  // 8 bit
                     printf(", inline 0x%X", *inlinep);  break;

                  case 1: case 2: case 5: // 16 bit
                     printf(", inline 0x%X", *(int16*)inlinep);  break;

                  case 3: // 16+16 bit
                     printf(", inline 0x%X:0x%X", *(int16*)(inlinep+2), *(int16*)inlinep);  break;

                  case 9: case 13: // 32 bit
                     printf(", inline 0x%X", *(int32*)inlinep);  break;

                  case 6: case 11: // 16+32 bit
                     printf(", inline 0x%X:0x%X", *(int16*)(inlinep+4), *(int32*)inlinep);  break;
                  }
               }
            }
            else {
               // This is a THREAD subrecord
               TrdDat.b = byte1;                 // Put byte into bitfield

               uint32 Index  = 0;
               if (TrdDat.s.Method < 4) {
                  Index  = Records[i].GetIndex(); // has index field if method < 4 ?
               }
               printf("\n   %s Thread %i. Method %s%i, index %i",
                  (TrdDat.s.D ? "Frame" : "Target"), TrdDat.s.Thread,
                  (TrdDat.s.D ? "F" : "T"), TrdDat.s.Method, Index);
            }
         } // Finished loop through subrecords
         if (Records[i].Index != Records[i].End) err.submit(1203);   // Check for consistency
      }
   } // Finished loop through records
}
Esempio n. 5
0
/**
 * Perform an action on a variable
 *
 * \param p_this The object that holds the variable
 * \param psz_name The name of the variable
 * \param i_action The action to perform. Must be one of \ref var_action
 * \param p_val First action parameter
 * \param p_val2 Second action parameter
 */
int var_Change( vlc_object_t *p_this, const char *psz_name,
                int i_action, vlc_value_t *p_val, vlc_value_t *p_val2 )
{
    int i;
    variable_t *p_var;
    vlc_value_t oldval;
    vlc_value_t newval;

    assert( p_this );

    vlc_object_internals_t *p_priv = vlc_internals( p_this );

    vlc_mutex_lock( &p_priv->var_lock );

    p_var = Lookup( p_this, psz_name );
    if( p_var == NULL )
    {
        vlc_mutex_unlock( &p_priv->var_lock );
        return VLC_ENOVAR;
    }

    switch( i_action )
    {
        case VLC_VAR_SETMIN:
            if( p_var->i_type & VLC_VAR_HASMIN )
            {
                p_var->ops->pf_free( &p_var->min );
            }
            p_var->i_type |= VLC_VAR_HASMIN;
            p_var->min = *p_val;
            p_var->ops->pf_dup( &p_var->min );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_GETMIN:
            if( p_var->i_type & VLC_VAR_HASMIN )
            {
                *p_val = p_var->min;
            }
            break;
        case VLC_VAR_SETMAX:
            if( p_var->i_type & VLC_VAR_HASMAX )
            {
                p_var->ops->pf_free( &p_var->max );
            }
            p_var->i_type |= VLC_VAR_HASMAX;
            p_var->max = *p_val;
            p_var->ops->pf_dup( &p_var->max );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_GETMAX:
            if( p_var->i_type & VLC_VAR_HASMAX )
            {
                *p_val = p_var->max;
            }
            break;
        case VLC_VAR_SETSTEP:
            if( p_var->i_type & VLC_VAR_HASSTEP )
            {
                p_var->ops->pf_free( &p_var->step );
            }
            p_var->i_type |= VLC_VAR_HASSTEP;
            p_var->step = *p_val;
            p_var->ops->pf_dup( &p_var->step );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_GETSTEP:
            if( p_var->i_type & VLC_VAR_HASSTEP )
            {
                *p_val = p_var->step;
            }
            break;
        case VLC_VAR_ADDCHOICE:
            i = p_var->choices.i_count;

            INSERT_ELEM( p_var->choices.p_values, p_var->choices.i_count,
                         i, *p_val );
            INSERT_ELEM( p_var->choices_text.p_values,
                         p_var->choices_text.i_count, i, *p_val );
            p_var->ops->pf_dup( &p_var->choices.p_values[i] );
            p_var->choices_text.p_values[i].psz_string =
                ( p_val2 && p_val2->psz_string ) ?
                strdup( p_val2->psz_string ) : NULL;

            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_DELCHOICE:
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                if( p_var->ops->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
                {
                    break;
                }
            }

            if( i == p_var->choices.i_count )
            {
                /* Not found */
                vlc_mutex_unlock( &p_priv->var_lock );
                return VLC_EGENERIC;
            }

            if( p_var->i_default > i )
            {
                p_var->i_default--;
            }
            else if( p_var->i_default == i )
            {
                p_var->i_default = -1;
            }

            p_var->ops->pf_free( &p_var->choices.p_values[i] );
            free( p_var->choices_text.p_values[i].psz_string );
            REMOVE_ELEM( p_var->choices.p_values, p_var->choices.i_count, i );
            REMOVE_ELEM( p_var->choices_text.p_values,
                         p_var->choices_text.i_count, i );

            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_CHOICESCOUNT:
            p_val->i_int = p_var->choices.i_count;
            break;
        case VLC_VAR_CLEARCHOICES:
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                p_var->ops->pf_free( &p_var->choices.p_values[i] );
            }
            for( i = 0 ; i < p_var->choices_text.i_count ; i++ )
                free( p_var->choices_text.p_values[i].psz_string );

            if( p_var->choices.i_count ) free( p_var->choices.p_values );
            if( p_var->choices_text.i_count ) free( p_var->choices_text.p_values );

            p_var->choices.i_count = 0;
            p_var->choices.p_values = NULL;
            p_var->choices_text.i_count = 0;
            p_var->choices_text.p_values = NULL;
            p_var->i_default = -1;
            break;
        case VLC_VAR_SETDEFAULT:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                if( p_var->ops->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
                {
                    break;
                }
            }

            if( i == p_var->choices.i_count )
            {
                /* Not found */
                break;
            }

            p_var->i_default = i;
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETVALUE:
            /* Duplicate data if needed */
            newval = *p_val;
            p_var->ops->pf_dup( &newval );
            /* Backup needed stuff */
            oldval = p_var->val;
            /* Check boundaries and list */
            CheckValue( p_var, &newval );
            /* Set the variable */
            p_var->val = newval;
            /* Free data if needed */
            p_var->ops->pf_free( &oldval );
            break;
        case VLC_VAR_GETCHOICES:
        case VLC_VAR_GETLIST:
            p_val->p_list = malloc( sizeof(vlc_list_t) );
            if( p_val2 ) p_val2->p_list = malloc( sizeof(vlc_list_t) );
            if( p_var->choices.i_count )
            {
                p_val->p_list->p_values = malloc( p_var->choices.i_count
                                                  * sizeof(vlc_value_t) );
                p_val->p_list->pi_types = malloc( p_var->choices.i_count
                                                  * sizeof(int) );
                if( p_val2 )
                {
                    p_val2->p_list->p_values =
                        malloc( p_var->choices.i_count * sizeof(vlc_value_t) );
                    p_val2->p_list->pi_types =
                        malloc( p_var->choices.i_count * sizeof(int) );
                }
            }
            p_val->p_list->i_count = p_var->choices.i_count;
            if( p_val2 ) p_val2->p_list->i_count = p_var->choices.i_count;
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                p_val->p_list->p_values[i] = p_var->choices.p_values[i];
                p_val->p_list->pi_types[i] = p_var->i_type;
                p_var->ops->pf_dup( &p_val->p_list->p_values[i] );
                if( p_val2 )
                {
                    p_val2->p_list->p_values[i].psz_string =
                        p_var->choices_text.p_values[i].psz_string ?
                    strdup(p_var->choices_text.p_values[i].psz_string) : NULL;
                    p_val2->p_list->pi_types[i] = VLC_VAR_STRING;
                }
            }
            break;
        case VLC_VAR_SETTEXT:
            free( p_var->psz_text );
            if( p_val && p_val->psz_string )
                p_var->psz_text = strdup( p_val->psz_string );
            else
                p_var->psz_text = NULL;
            break;
        case VLC_VAR_GETTEXT:
            p_val->psz_string = p_var->psz_text ? strdup( p_var->psz_text )
                                                : NULL;
            break;
        case VLC_VAR_SETISCOMMAND:
            p_var->i_type |= VLC_VAR_ISCOMMAND;
            break;

        default:
            break;
    }

    vlc_mutex_unlock( &p_priv->var_lock );

    return VLC_SUCCESS;
}
Esempio n. 6
0
static CService ResolveService(const char* ip, int port = 0)
{
    CService serv;
    BOOST_CHECK_MESSAGE(Lookup(ip, serv, port, false), strprintf("failed to resolve: %s:%i", ip, port));
    return serv;
}
Esempio n. 7
0
  if (init)
  {
    //Force filling out of the current item
    queue_end_++;
    Lookup(current_);
  }
}

//-----------------------------------------------------------------------------

void PlayerHistory::SetPlayer(Player* player)
{
  connect(this, SIGNAL(OnPlayFile(Media,bool)), player, SLOT(PlayFile(Media,bool)));
  connect(player, SIGNAL(OnStatus(PlayerState)), this, SLOT(Status(PlayerState)));
  connect(player, SIGNAL(OnSourceChanged()), this, SLOT(SourceChanged()));
  OnPlayFile(Lookup(current_),false);//force through the current item to the player
}

//-----------------------------------------------------------------------------

void PlayerHistory::PlayFile(const Media& entry)
{
  LOG("History") << "PlayFile";
  if (entry == Lookup(current_))
  {
    //There is a bit of a special case if the current item has been re-requested
    //Causes it to play if we are stopped but otherwise ignores it
    if (!current_played_)
      OnPlayFile(Lookup(current_), true);
  }
  else
Esempio n. 8
0
// Creates a new hidden var
SymbolTableEntry * newtemp(){
	// MONO NEES KRIFES METAVLITES
	// OXI EPANAXRISIMOPOIHSH

	char* new_name = strdup(newtempname());
	if(lookup_sym(new_name, get_current_scope()) != NULL)
		{
		return lookup_sym(new_name, get_current_scope());
		}
	else
		{

		SymbolTableEntry* entry;
		entry = (SymbolTableEntry *)malloc(sizeof(SymbolTableEntry));

		Variable *var;
		var = (Variable *)malloc(sizeof(Variable));
	
		var->name = strdup(new_name);
		var->scope = get_current_scope();
		var->line = yylineno;

		entry->value.varVal = var;
		entry->isActive = SYM_TRUE;
		entry->scope = get_current_scope();
		entry->space = currscopespace();
		inccurrscopeoffset();
		entry->offset = currscopeoffset();
		if(get_current_scope() == 0)
			{
			entry->type = GLOBAL;
			printf("LOOKUP: %d\n", Lookup(new_name,VAR,GLOBAL));
			if(Lookup(new_name,VAR,GLOBAL) == 0)
				{
				insert(entry);
				insert_in_heads(entry);
				}
			else
				{
				printf("GLOBAL ERROR\n");
				}
			}
		else
			{
			entry->type = SYM_LOCAL;
			if(Lookup(new_name,VAR,SYM_LOCAL) == 1)
				{
				insert(entry);
				insert_in_heads(entry);
				}
			else if(Lookup(new_name,VAR,SYM_LOCAL) == 2)
				{
				insert(entry);
				update_heads(entry,0,0);
				}
			else if(Lookup(new_name,VAR,SYM_LOCAL) == 5)
				{
				printf("pedaraki\n");
				}
			else if(Lookup(new_name,VAR,SYM_LOCAL) == 0)
				{
				printf("LOCAL ERROR\n");
				}
			}
// kode gia insert tou entry sto symbol table

		return entry;
		}
}
Esempio n. 9
0
/*
  Setup for if, else, elseif, while, and for

  Routine to test logic and correspondingly set globals to affect course
  of parsing.  It sets globals affecting subsequent parsing.  It returns 0
  when an error is found.
 
  The first argument list is a LIST and the second is IF, ELSEIF, ELSE, WHILE
  or FOR.

  On IF, ELSEIF and WHILE, NCOMPS(list) should be 1 and COMPVALUE(list,0)
  should be a LOGICAL scalar specifying the condition.

  On ELSE, list is a null handle.

  On FOR, 2 <= NCOMPS(list) <= 4.
   NAME(COMPVALUE(list, 0)) is the name of the index variable
   If NCOMPS(list) == 2, COMPVALUE(list,1) is a REAL vector specifying
   the values of the index.
   If NCOMPS(list) == 4, COMPVALUE(list,3) must be a non-zero non-MISSING
   REAL scalar inc (default value 1)
   If NCOMPS(list) == 3 or 4, COMPVALUE(list,1) and COMPVALUE(list,2) must
   be non MISSING REAL scalars i1 and i2 and a range vector of the form
   run(i1,i2,inc) is computed and saved.

  The depth of nested for and while loops is given by WDEPTH which is
  incremented here and decremented in the parser.

  The name of the index variable used in for(index,range){} is
  IndexNames[WDEPTH-1] and the vector of values is stored in reverse
  order in FORVECTORS[WDEPTH-1].

  The depth of nested if/elseif/else statements is given by IDEPTH which is
  incremented here and decremented in the parser.

  The value of Logical in if(Logical){} or ...elseif(Logical){} is
  put in IFCONDITIONS[IDEPTH-1]

  As of 911002 only IF was processed and the input stream was modified was
  to skip ahead to be just before '{'  and to wipe out input stream on
  errors.  It was changed so that the input stream is not changed and all
  control of parsing is through globals.

   931110  Ifsetup() now returns error code rather than set Global IfsetupError
   980208  Fixed divide by zero bug in for(i,1,1){}
           Modified some of the code checking arguments to make use of
           isScalar() which incorporates a check for a 0 Symbolhandle
           Removed some unneeded externs
   980218  Corrected handling of MISSING i1, i2 and inc in for(i,i1,i2[,inc])
   980220  for(i,NULL){...} just skips compound statment and is not an error.

*/
int Ifsetup(Symbolhandle list, long op)
{
	Symbolhandle    logic, indexVal, range, start, end, inc;
	char           *opname;
	long            condition;
	long            i,i1, length, halfLength;
	long            iftype = (op == IF || op == ELSEIF);
	long            nullList = (list == (Symbolhandle) 0);
	long            ncomps = (nullList) ? 0 : NCOMPS(list);
	long            badForList;
	double          startVal, endVal, incVal = 1.0, endVal1, span, val;
	double         *forVector, *rangeVec;
	WHERE("Ifsetup");

	OUTSTR[0] = '\0';
	
	if (op != ELSE)
	{ /* IF, ELSEIF, FOR and WHILE */
		if (iftype)
		{
			opname = (op == IF) ? "if" : "elseif";
		}
		else
		{
			opname = (op == WHILE) ? "while" : "for";
		}
		
		if ((!iftype && WDEPTH >= MAXWDEPTH) ||
			(op == IF && IDEPTH >= MAXIDEPTH))
		{
			sprintf(OUTSTR,"ERROR: too many nested %s's",opname);

			goto yyerrorExit;
		}

		if (!iftype)
		{ /* for & while */
			WDEPTH++;
		}
		else if (op == IF)
		{
			IDEPTH++;
		}
	
		if (op == WHILE || (iftype && !nullList))
		{
			char       *condValue = "conditional value";
			
			if (ncomps > 1)
			{
				sprintf(OUTSTR,"ERROR: usage is %s(LOGICAL){ ... }", opname);
			}
			else if ((logic = COMPVALUE(list,0)) == (Symbolhandle) 0)
			{
				sprintf(OUTSTR,"ERROR: no %s %s", opname, condValue);
			}
			else if (!isDefined(logic))
			{
				sprintf(OUTSTR,"ERROR: %s %s is UNDEFINED", opname, condValue);
			}
			else if (TYPE(logic) != LOGIC)
			{
				sprintf(OUTSTR,"ERROR: %s %s not LOGICAL", opname, condValue);
			}
			else if (!isScalar(logic))
			{
				sprintf(OUTSTR,
						"ERROR: %s %s has length > 1", opname, condValue);
			}
			else if (isMissing(DATAVALUE(logic,0)))
			{
				sprintf(OUTSTR, "ERROR: %s %s is MISSING", opname, condValue);
			}
			if (*OUTSTR)
			{
				goto yyerrorExit;
			}
			condition = (DATAVALUE(logic,0) != 0.0);
		} /* if (op == WHILE || (iftype && !nullList) */
		else if (op == FOR)
		{ /* for */
			opname = "for";
			if (FORVECTORS[WDEPTH-1] == (double **) 0)
			{
				/* first time through at this level */
				indexVal = COMPVALUE(list,0);
				COMPVALUE(list,0) = (Symbolhandle) 0;
				/* Check index symbol */
				if (indexVal == (Symbolhandle) 0 ||
				   TYPE(indexVal) == BLTIN || isscratch(NAME(indexVal)))
				{
					sprintf(OUTSTR,
							"ERROR: %s index to %s loop",
							(indexVal==(Symbolhandle) 0) ? "missing" : "illegal",
							opname);
					goto yyerrorExit;
				}

				badForList = (ncomps == 1 || ncomps > 4) ? BADNCOMPS : 0;

				if (!badForList)
				{
					if (ncomps == 2)
					{
						range = COMPVALUE(list, 1);
						if (TYPE(range) != NULLSYM &&
							(!isVector(range) || TYPE(range) != REAL))
						{
							badForList = BADRANGEVAL;
						}
					} /*if (ncomps == 2)*/
					else
					{
						start = COMPVALUE(list, 1);
						end = COMPVALUE(list, 2);
						inc = (ncomps == 4) ?
						  COMPVALUE(list, 3) : (Symbolhandle) 0;
						if (!isScalar(start) || TYPE(start) != REAL ||
							!isScalar(end) || TYPE(end) != REAL ||
							(ncomps == 4 &&
							 (!isScalar(inc) || TYPE(inc) != REAL)))
						{
							badForList = BADLIMITSVAL;
						}
						else
						{
							startVal = DATAVALUE(start, 0);
							endVal = DATAVALUE(end, 0);
							incVal = (ncomps == 4) ? DATAVALUE(inc, 0) : 1.0;
						
							if (isMissing(startVal) || isMissing(endVal) ||
								isMissing(incVal))
							{
								badForList = MISSVALLIMITS;
							}
							else
							{
								double     howFar = endVal - startVal;
								
								if (ncomps == 3)
								{
									incVal = (howFar >= 0) ? 1.0 : -1.0;
								}
								else if (howFar != 0.0 && incVal == 0.0)
								{
									badForList = ZEROINC;
								}
								else if (incVal * howFar < 0.0)
								{
									badForList = WRONGSIGNINC;
								}
							}
						}
					} /*if (ncomps == 2){}else{}*/
				} /*if (!badForList)*/
				
				if (badForList)
				{
					char        *usage1 = "for(index,i1,i2[,inc]){...}";
					char        *usage2 = "for(index,i1,i2,inc){...}";
				
					switch (badForList)
					{
					  case BADNCOMPS:
						sprintf(OUTSTR,
							   "ERROR: usage is for(index,realVec){...} or %s", usage1);
						break;
						
					  case BADRANGEVAL:
						sprintf(OUTSTR,
								"ERROR: range must be REAL vector in for(index, range){...}");
						break;
						
					  case BADLIMITSVAL:
						sprintf(OUTSTR,
								"ERROR: i1, i2, inc must be non-MISSING REAL scalars in %s",
								usage1);
						break;

					  case MISSVALLIMITS:
						sprintf(OUTSTR,
								"ERROR: i1, i2, inc must not be MISSING in %s", 
								usage1);
						break;
						
					  case ZEROINC:
						sprintf(OUTSTR,
								"ERROR: inc must not be 0 in %s", usage2);
						break;
						
					  case WRONGSIGNINC:
						sprintf(OUTSTR,
								"ERROR: inc has wrong sign in %s", usage2);
						break;
					} /*switch (badForList)*/
					goto yyerrorExit;
				} /*if (badForList)*/
				
				incVal = (incVal) ? incVal : 1.0;

				if (ncomps == 2)
				{
					length = symbolSize(range);
				} /*if (ncomps == 2)*/
				else
				{
					span = endVal - startVal;
					length = (long) (span / incVal) + 1;

/* 
   The following is intended to insure that if endVal is essentially an exact
   multiple of by away from startVal, then the last element of the result
   will be close to endVal, even if slightly outside the interval from
   startVal to endVal; in addition, a very near zero is made exactly zero
   The behavior is supposed to be exactly that of run().
*/
					if (length > 1)
					{		
						for (endVal1 = startVal + length * incVal;
							 incVal > 0.0 && endVal1 <= endVal ||
							 incVal < 0.0 && endVal1 >= endVal ||
							 fabs((endVal1 - endVal)/span) <= RUNFUZZ;
							 endVal1 = startVal + length * incVal)
						{
							length++;
						}
					} /*if (length > 1)*/
				} /*if (ncomps == 2){}else{}*/
				
				WHILELIMITS[WDEPTH-1] = length;

				/* get temporary storage for range */
				if (length == 0)
				{
					/* must be for(i,NULL){...} */
					FORVECTORS[WDEPTH-1] = (double **) 0;
					WHILECONDITIONS[WDEPTH-1] = 0;
					/* return signal to skip compound statement*/
					return (-1);
				} /*if (length == 0)*/

				if (ncomps > 2 || !isscratch(NAME(range)))
				{
					FORVECTORS[WDEPTH-1] = 
					  (double **) mygethandle(length*sizeof(double));
					if (FORVECTORS[WDEPTH-1] == (double **) 0)
					{
						goto errorExit;
					}
					if (ncomps == 2)
					{
						rangeVec  = DATAPTR(range);
					}
				} /*if (ncomps > 2 || !isscratch(NAME(range)))*/
				else
				{ /* for(i,scratchVec){}*/
					rangeVec  = DATAPTR(range);
					FORVECTORS[WDEPTH-1] = DATA(range);
					setDATA(range, (double **) 0);
				} /*if (ncomps > 2 || !isscratch(NAME(range))){}else{}*/

				forVector = *FORVECTORS[WDEPTH-1];

				/*
				  Copy range or run(startVal,endVal, incVal) to FORVECTORS
				  in reverse order, doing it in such a way that forVector
				  can be the same as rangeVec
				  */
				if (ncomps == 2)
				{ /* copy from rangeVec to forVector in reverse order */
					halfLength = length/2;
					for (i = 0,i1 = length - 1;i < halfLength;i++, i1--)
					{
						val = rangeVec[i];
						forVector[i] = rangeVec[i1];
						forVector[i1] = val;
					}
					if (2*halfLength != length)
					{
						forVector[i] = rangeVec[i1];
					}
				} /*if (ncomps == 2)*/
				else if (length == 1)
				{
					forVector[0] = startVal;
				}
				else
				{ /* generate run(startVal,endVal,incVal)*/
					for (i = 0,i1 = length - 1;i1 >= 0;i1--, i++)
					{
						val = startVal + (double) i * incVal;
						forVector[i1] = 
						  (incVal && fabs(val/span) < RUNFUZZ) ? 0.0 : val;
					}
					if (fabs((val-endVal)/span) < RUNFUZZ)
					{
						forVector[0] = endVal;
					}
				} /*if (ncomps == 2){}else{}*/

				/* save index name */
				strncpy(IndexNames[WDEPTH-1],NAME(indexVal),NAMELENGTH);
				IndexNames[WDEPTH-1][NAMELENGTH] = '\0';
			} /* if (FORVECTORS[WDEPTH-1] == (double **) 0) */
			else
			{ /* not first time through */
				indexVal = Lookup(IndexNames[WDEPTH-1]);
			}
			/* re-use index variable if it is a REAL scalar */
			if (!isScalar(indexVal) || TYPE(indexVal) != REAL)
			{
				Removesymbol(indexVal);
				indexVal = (Symbolhandle) 0;
			}
			if (indexVal == (Symbolhandle) 0)
			{
				indexVal = RInstall(IndexNames[WDEPTH-1],1);
				if (indexVal == (Symbolhandle) 0)
				{
					goto errorExit;
				}
			}
			val = (*FORVECTORS[WDEPTH-1])[WHILELIMITS[WDEPTH-1]-1];
#if (USENOMISSING)
			if (isMissing(val))
			{
				clearNOMISSING(indexVal);
			}
			else
			{
				setNOMISSING(indexVal);
			}
#endif /*USENOMISSING*/
			DATAVALUE(indexVal,0) = val;
		}
 
		if (op == WHILE)
		{
			/* WHILESTARTS, WHILEBRACKETLEV, and IFBRACKETLEV set in yylex */
			if (--WHILELIMITS[WDEPTH-1] <= 0 && condition)
			{					/* safety precaution */
				/* Note: Parser also recognizes this condition and terminates
				   loop
				*/
				sprintf(OUTSTR,"ERROR: more than %ld repetitions of %s loop",
						(long) MAXWHILE-1,opname);
				putErrorOUTSTR();
			}	
			WHILECONDITIONS[WDEPTH-1] = condition;
		} /*if (op == WHILE)*/
		else if (op == FOR)
		{/* Note: WDEPTH & WHILELIMITS[WDEPTH-1] are decremented in mainpars */
			WHILECONDITIONS[WDEPTH-1] = 1;
			if (WHILELIMITS[WDEPTH-1] == 1)
			{ /* this is the last time */
				IndexNames[WDEPTH-1][0] = '\0';
				mydisphandle((char **) FORVECTORS[WDEPTH-1]);
				FORVECTORS[WDEPTH-1] = (double **) 0;
			}
		} /*if (op == WHILE){}else if (op == FOR)*/
		else if (!nullList) /* op == IF or op == ELSEIF */
		{
			IFCONDITIONS[IDEPTH-1] = condition;
		}
	} /* if (op != ELSE) */
	else
	{
		opname = "else";
	}
	
	/* go look for starting bracket enclosing the compound statement */
	if (!findLParen(op, '{'))
	{
		goto errorExit;
	}

	if (op == FOR)
	{
		WHILESTARTS[WDEPTH-1] = ISTRCHAR;
	}
	*OUTSTR = '\0';
	
	if (interrupted(DEFAULTTICKS) != INTNOTSET)
	{
		goto errorExit;
	}

	return (1);

  yyerrorExit:
	yyerror(OUTSTR);
	return (0);
	
  errorExit:
	putErrorOUTSTR();

	/* report error to parser */

	return (0);
	
} /*Ifsetup()*/
Esempio n. 10
0
void PressureTable::ComputeDatabaseInputs( const double rho, const double Z, const double Zv, const double Yc,
                                           double &P,  double &Sz , double &C,
                                           double P0,  double C0) {
  // Compute normalized variance
  double eps = 1.0e-3;
  if ((Z <= 1-eps)||(Z >= eps)) {
    Sz = Zv/(Z*(1.0-Z));
  } else {
    Sz = 0.0;
  }
  Sz = max(0.0, min(1.0, Sz));

  // Compute normalized progress variable
  Z_newton = Z;
  Zv_newton = Sz;
  Yc_newton = Yc;
  rho_newton = rho;
  // I need to solve ( Yc(C,P) - Yc_target , rho(C,P) - rho_target) = (0 , 0)
  C_newton = C0;
  P_newton = P0/P_scale;// Pressure is rescaled
  verbose_newton = false;
  Bool check;
  VecDoub_IO sol2(1, 0.0);
  VecDoub_IO sol(2, 0.0);
  int Newton_mode;

  try {
    //Newton  : newt(sol, check, usrfunc_wrapper);
    //Broyden : broydn(sol, check, usrfunc_wrapper);

    // Get Approximation of Yceq from highest pressure
    int nPress = GetDimension1();
    double P_max = GetCoordinate1(nPress-1);
    int nC = GetDimension4();
    double C_max = GetCoordinate4(nC-2); // Maximum C value before one
    double Yc_eq  = Lookup(P_max,Z_newton,Zv_newton,1.0,"PROG");
    double Yc_max = Lookup(P_max,Z_newton,Zv_newton,C_max,"PROG");
    // If Yc_eq is small, C is set to 1 and we look for pressure only
    if ((Yc_eq < eps)||(Yc > Yc_max)) {
      Newton_mode = 1;
      sol2[0] = P_newton;
      C_newton = 1.0;
      newt(sol2, check, usrfunc_wrapper2);
    } else {
      // usual
      Newton_mode = 2;
      sol[0] = C_newton;
      sol[1] = P_newton;
      try {newt(sol, check, usrfunc_wrapper);}
      catch (int e) {
       cout << "relaunched with Newton_mode = 1" <<  endl;
       Newton_mode = 1;
       C_newton = sol[0];
       sol2[0] = P0/P_scale;
       newt(sol2, check, usrfunc_wrapper2);
      }
    }
  }
  catch (int e) {
    int tol_failure = 0;
    if (Newton_mode == 1) {
      VecDoub out(1, 0.0);
      out = DensityFromP(sol2);
      if (abs(out[0]) > 1.0e-5) tol_failure = 1;
    } else if (Newton_mode == 2) {
      VecDoub out(2, 0.0);
      out = YcAndDensityFromCP(sol);
     if ((abs(out[0])>1.0e-4)||(abs(out[1]))>1.0e-5) tol_failure = 1;
    }
    cout << "Newton error. Test tol = " << tol_failure << endl;
    if (tol_failure == 1) { 
    cout << "Newton inputs : " << Z_newton   << " "
                               << Zv_newton  << " "
                               << Yc_newton  << " "
                               << rho_newton << " "
                               << C_newton   << " "
                               << P_newton*P_scale   << endl;
    cout << "C0 : " << C0 << " P0 : " << P0 << endl;
    cout << " Check : " << check << endl;
    if (Newton_mode == 2) {
      cout << " sol : C = " << sol[0] << " , P = " << sol[1]*P_scale << endl;
    } else if (Newton_mode == 1) {
      cout << " sol :  P = " << sol2[0]*P_scale << endl;
    }

    // Relaunch with verbose
    verbose_newton = true;
    try {
      Int MaxIter = 200;
      if (Newton_mode == 1) {
        sol2[0] = P_newton;
        C_newton = 1.0;
        cout << "Reinit with " <<  sol2[0] << " " << MaxIter <<  endl;
        newt(sol2, check, usrfunc_wrapper2, MaxIter);
      } else if (Newton_mode == 2) {
        // usual
        sol[0] = C_newton;
        sol[1] = P_newton;
        cout << "Reinit with " <<  sol[0] << " " << sol[1] << " " << MaxIter << endl;
        newt(sol, check, usrfunc_wrapper, MaxIter);
      } else {cerr << "Impossible value of Newton_mode: " << Newton_mode << endl;}

    }
    catch (int e2) {
      cout << "Bis Newton inputs : " << Z_newton   << " "
                                 << Zv_newton  << " "
                                 << Yc_newton  << " "
                                 << rho_newton << " "
                                 << C_newton   << " "
                                 << P_newton*P_scale   << endl;
      cout << "Bis Check : " << check << endl;
      if (Newton_mode == 2) {
        cout << "Bis sol : C = " << sol[0] << " , P = " << sol[1]*P_scale << endl;
      } else if (Newton_mode == 1) {
        cout << "Bis sol :  P = " << sol2[0]*P_scale << endl;
      }  
      throw(-1);
    }
    throw(-1);
    }
  }

  if (Newton_mode == 2) {
    C_newton = sol[0];
    P_newton = sol[1];
  } else if (Newton_mode == 1) {
    P_newton = sol2[0];
  }
  C = C_newton;
  P = P_newton*P_scale;
}
Esempio n. 11
0
void PressureTable::ComputeDatabaseInputs_FromT( const double rho, const double Z, const double Zv, const double Yc, const double T,
                                           double &P,  double &Sz , double &C,
                                           double P0,  double C0) {
  // Compute normalized variance
  double eps = 1.0e-3;
  Sz = ComputeNormalizedVariance(Z, Zv);

  // Compute normalized progress variable
  Z_newton = Z;
  Zv_newton = Sz;
  Yc_newton = Yc;
  rho_newton = rho;
  T_newton = T;
  // I need to solve ( Yc(C,P) - Yc_target , rho(C,P) - rho_target) = (0 , 0)
  C_newton = C0;
  P_newton = P0/P_scale;// Pressure is rescaled
  verbose_newton = false;
  Bool check;
  VecDoub_IO sol2(1, 0.0);
  VecDoub_IO sol(2, 0.0);
  int Newton_mode;


  try {
    // Get Approximation of Yceq from highest pressure
    int nPress = GetDimension1();
    double P_max = GetCoordinate1(nPress-1);
    int nC = GetDimension4();
    double C_max = GetCoordinate4(nC-2); // Maximum C value before one
    double Yc_eq  = Lookup(P_max,Z_newton,Zv_newton,1.0,"PROG");
    double Yc_max = Lookup(P_max,Z_newton,Zv_newton,C_max,"PROG");
    // If Yc_eq is small, C is set to 1 and we look for pressure only
    if ((Yc_eq < eps)||(Yc > Yc_max)) {
      Newton_mode = 1;
      sol2[0] = P_newton;
      C_newton = 1.0;
      newt(sol2, check, usrfunc_wrapper4);
    } else {
      // usual
      Newton_mode = 2;
      sol[0] = C_newton;
      sol[1] = P_newton;
      try {newt(sol, check, usrfunc_wrapper3);}
      catch (int e) {
       cout << "relaunched with Newton_mode = 1" <<  endl;
       Newton_mode = 1;
       C_newton = sol[0];
       sol2[0] = P0/P_scale;
       newt(sol2, check, usrfunc_wrapper4);
      }
    }
  }
  catch (int e) {
    int tol_failure = 0;
    if (Newton_mode == 1) {
      VecDoub out(1, 0.0);
      out = DensityFromP(sol2);
      if (abs(out[0]) > 1.0e-5) tol_failure = 1;
    } else if (Newton_mode == 2) {
      VecDoub out(2, 0.0);
      out = YcAndDensityFromCP(sol);
     if ((abs(out[0])>1.0e-4)||(abs(out[1]))>1.0e-5) tol_failure = 1;
    }
    cout << "Newton error. Test tol = " << tol_failure << endl;
    if (tol_failure == 1) {
    cout << "Newton inputs : " << Z_newton   << " "
                               << Zv_newton  << " "
                               << Yc_newton  << " "
                               << rho_newton << " "
                               << C_newton   << " "
                               << P_newton*P_scale   << endl;
    cout << "C0 : " << C0 << " P0 : " << P0 << endl;
    cout << " Check : " << check << endl;
    if (Newton_mode == 2) {
      cout << " sol : C = " << sol[0] << " , P = " << sol[1]*P_scale << endl;
    } else if (Newton_mode == 1) {
      cout << " sol :  P = " << sol2[0]*P_scale << endl;
    }
    }
  }
  if (Newton_mode == 2) {
    C_newton = sol[0];
    P_newton = sol[1];
  } else if (Newton_mode == 1) {
    P_newton = sol2[0];
  }
  C = C_newton;
  P = P_newton*P_scale;

}
Esempio n. 12
0
	void SubRectAllocator::GetRect(CRect& rect, const Subtitle* s, const Align& align, int tlb, int brb)
	{
		SubRect sr(rect, s->m_layer);
		sr.rect.InflateRect(tlb, tlb, brb, brb);

		StringMapW<SubRect>::CPair* pPair = Lookup(s->m_name);

		if(pPair && pPair->m_value.rect != sr.rect)
		{
			RemoveKey(s->m_name);
			pPair = NULL;
		}

		if(!pPair)
		{
			bool vertical = s->m_direction.primary == _T("down") || s->m_direction.primary == _T("up");

			bool fOK = false;

			while(!fOK)
			{
				fOK = true;

				POSITION pos = GetStartPosition();
				while(pos)
				{
					const SubRect& sr2 = GetNextValue(pos);

					if(sr.layer == sr2.layer && !(sr.rect & sr2.rect).IsRectEmpty())
					{
						if(vertical)
						{
							if(align.h < 0.5)
							{
								sr.rect.right = sr2.rect.right + sr.rect.Width();
								sr.rect.left = sr2.rect.right;
							}
							else
							{
								sr.rect.left = sr2.rect.left - sr.rect.Width();
								sr.rect.right = sr2.rect.left;
							}
						}
						else
						{
							if(align.v < 0.5)
							{
								sr.rect.bottom = sr2.rect.bottom + sr.rect.Height();
								sr.rect.top = sr2.rect.bottom;
							}
							else
							{
								sr.rect.top = sr2.rect.top - sr.rect.Height();
								sr.rect.bottom = sr2.rect.top;
							}
						}

						fOK = false;
					}
				}
			}

			SetAt(s->m_name, sr);

			rect = sr.rect;
			rect.DeflateRect(tlb, tlb, brb, brb);
		}
	}
Esempio n. 13
0
bool Tree::Lookup(Student &student) const{
    bool found = false;
    Lookup(student,m_root, found);
    return found;
}
Esempio n. 14
0
void CMACHO<MACSTRUCTURES>::Dump(int options) {
   uint32 icmd;                        // Command index
   int32  isec1;                       // Section index within segment
   int32  isec2;                       // Section index global
   int32  nsect;                        // Number of sections in segment

   if (options & DUMP_FILEHDR) {
      // File header
      printf("\nDump of Mach-O file %s", FileName);
      printf("\n-----------------------------------------------");
      printf("\nFile size: 0x%X", this->GetDataSize());
      printf("\nFile header:");
      printf("\n  CPU type: %s, subtype: %s",
         Lookup(MacMachineNames, FileHeader.cputype), 
         Lookup(MacCPUSubtypeNames, FileHeader.cpusubtype));
      
      printf("\n  File type: %s - %s", 
         GetFileFormatName(FileType), Lookup(MacFileTypeNames, FileHeader.filetype));

      printf("\n  Number of load commands: %i, Size of commands: 0x%X, Flags: %X",
         FileHeader.ncmds, FileHeader.sizeofcmds, FileHeader.flags);
   }

   uint32 cmd;                         // Load command
   uint32 cmdsize;                     // Command size
   // Pointer to current position
   uint8 * currentp = (uint8*)(Buf() + sizeof(TMAC_header));

   // Loop through file commands
   for (icmd = 1; icmd <= FileHeader.ncmds; icmd++) {
      cmd     = ((MAC_load_command*)currentp) -> cmd;
      cmdsize = ((MAC_load_command*)currentp) -> cmdsize;

      if (options & DUMP_SECTHDR) {
         // Dump command header
         printf("\n\nCommand %i: %s, size: 0x%X", icmd,
         Lookup(MacCommandTypeNames, cmd), cmdsize);

         // Interpret specific command type
         switch(cmd) {
            case MAC_LC_SEGMENT: {
               MAC_segment_command_32 * sh = (MAC_segment_command_32*)currentp;
               printf("\n  Name: %s, Memory address 0x%X, Memory size 0x%X"
                  "\n  File offset 0x%X, File size 0x%X, Maxprot 0x%X, Initprot 0x%X"
                  "\n  Number of sections %i, Flags 0x%X",
                  sh->segname, sh->vmaddr, sh->vmsize,
                  sh->fileoff, sh->filesize, sh->maxprot, sh->initprot, 
                  sh->nsects, sh->flags);
               break;}

            case MAC_LC_SEGMENT_64: {
               MAC_segment_command_64 * sh = (MAC_segment_command_64*)currentp;
               printf("\n  Name: %s, \n  Memory address 0x%08X%08X, Memory size 0x%08X%08X"
                  "\n  File offset 0x%08X%08X, File size 0x%08X%08X\n  Maxprot 0x%X, Initprot 0x%X"
                  "\n  Number of sections %i, Flags 0x%X",
                  sh->segname, (uint32)(sh->vmaddr>>32), (uint32)sh->vmaddr, 
                  (uint32)(sh->vmsize>>32), (uint32)sh->vmsize,
                  (uint32)(sh->fileoff>>32), (uint32)sh->fileoff, 
                  (uint32)(sh->filesize>>32), (uint32)sh->filesize, 
                  sh->maxprot, sh->initprot, 
                  sh->nsects, sh->flags);
               break;}

            case MAC_LC_SYMTAB: {
               MAC_symtab_command * sh = (MAC_symtab_command*)currentp;
               printf("\n  Symbol table offset 0x%X, number of symbols %i,"
                  "\n  String table offset 0x%X, String table size 0x%X",
                  sh->symoff, sh->nsyms, sh->stroff, sh->strsize);
               break;}

            case MAC_LC_DYSYMTAB: {
               MAC_dysymtab_command * sh = (MAC_dysymtab_command*)currentp;
               printf("\n  Index to local symbols %i, number of local symbols %i,"
                  "\n  Index to external symbols %i, number of external symbols %i,"
                  "\n  Index to undefined symbols %i, number of undefined symbols %i,"
                  "\n  File offset to TOC 0x%X, number of entries in TOC %i,",
                  sh->ilocalsym, sh->nlocalsym, sh->iextdefsym, sh->nextdefsym, 
                  sh->iundefsym, sh->nundefsym, sh->tocoff, sh->ntoc);
               printf("\n  File offset to module table 0x%X, Number of module table entries %i,"
                  "\n  Offset to referenced symbol table 0x%X, Number of referenced symtab entries %i"
                  "\n  Offset to indirect symbol table 0x%X, Number of indirect symtab entries %i"
                  "\n  Offset to external relocation entries 0x%X, Number of external reloc. entries %i"
                  "\n  Offset to local relocation entries 0x%X, Number of local reloc. entries %i",
                  sh->modtaboff, sh->nmodtab, sh->extrefsymoff, sh->nextrefsyms, 
                  sh->indirectsymoff, sh->nindirectsyms, sh->extreloff, sh->nextrel,
                  sh->locreloff, sh->nlocrel);	
               break;}
         }

      }
      currentp += cmdsize;
   }
Esempio n. 15
0
/**
 * Set a variable's value
 *
 * \param p_this The object that hold the variable
 * \param psz_name The name of the variable
 * \param val the value to set
 */
int __var_Set( vlc_object_t *p_this, const char *psz_name, vlc_value_t val )
{
    int i_var;
    variable_t *p_var;
    vlc_value_t oldval;

    vlc_mutex_lock( &p_this->var_lock );

    i_var = GetUnused( p_this, psz_name );
    if( i_var < 0 )
    {
        vlc_mutex_unlock( &p_this->var_lock );
        return i_var;
    }

    p_var = &p_this->p_vars[i_var];

    /* Duplicate data if needed */
    p_var->pf_dup( &val );

    /* Backup needed stuff */
    oldval = p_var->val;

    /* Check boundaries and list */
    CheckValue( p_var, &val );

    /* Set the variable */
    p_var->val = val;

    /* Deal with callbacks. Tell we're in a callback, release the lock,
     * call stored functions, retake the lock. */
    if( p_var->i_entries )
    {
        int i_var;
        int i_entries = p_var->i_entries;
        callback_entry_t *p_entries = p_var->p_entries;

        p_var->b_incallback = VLC_TRUE;
        vlc_mutex_unlock( &p_this->var_lock );

        /* The real calls */
        for( ; i_entries-- ; )
        {
            p_entries[i_entries].pf_callback( p_this, psz_name, oldval, val,
                                              p_entries[i_entries].p_data );
        }

        vlc_mutex_lock( &p_this->var_lock );

        i_var = Lookup( p_this->p_vars, p_this->i_vars, psz_name );
        if( i_var < 0 )
        {
            msg_Err( p_this, "variable %s has disappeared", psz_name );
            vlc_mutex_unlock( &p_this->var_lock );
            return VLC_ENOVAR;
        }

        p_var = &p_this->p_vars[i_var];
        p_var->b_incallback = VLC_FALSE;
    }

    /* Free data if needed */
    p_var->pf_free( &oldval );

    vlc_mutex_unlock( &p_this->var_lock );

    return VLC_SUCCESS;
}
Esempio n. 16
0
NodeInt stmt()
{
	switch (CurrToken) {
		case INT32:{
			mutch(INT32); 
			Token tokL = mutch(IDENTIFIER);
			int idNum = Lookup(lexeme, 1, INT32);
			NodeInt nodeL = AddLeaf(tokL, idNum);
			if(CurrToken == MOV_OP){
				Token tok = mutch(MOV_OP); 
				NodeInt nodeR = boool();

					mutch(COMM_POINT);

				return AddNode(tok, nodeL,0,nodeR);
			}
			mutch(COMM_POINT);
			NodeInt nodeR = AddLeaf(NUMBER, 0);
			return AddNode(MOV_OP, nodeL, 0,nodeR);
			break;
		}
		case INT16:{
			mutch(INT16); 
			Token tokL = mutch(IDENTIFIER);
			int idNum = Lookup(lexeme, 1, INT16);
			NodeInt nodeL = AddLeaf(tokL, idNum);
			if(CurrToken == MOV_OP){
				Token tok = mutch(MOV_OP); 
				NodeInt nodeR = boool();
				mutch(COMM_POINT);
				return AddNode(tok, nodeL,0,nodeR);
			}
			mutch(COMM_POINT);
			NodeInt nodeR = AddLeaf(NUMBER, 0);
			return AddNode(MOV_OP, nodeL, 0,nodeR);
			break;
		}
			
		case DO:{
			mutch(DO);
			NodeInt nodeL = stmt(); 
			mutch(WHILE);
			mutch(LEFT_BRECKET);
			NodeInt nodeR = boool();
			mutch(RIGHT_BRECKET);
			mutch(COMM_POINT);
			return AddNode(DO, nodeL, 0,nodeR);
			break;
		}
			
		case IF:{
			Token tok = mutch(IF); 
			mutch(LEFT_BRECKET);
			NodeInt nodeL = boool();
			mutch(RIGHT_BRECKET);
			NodeInt nodeR = stmt();
			NodeInt nodeM = 0;
			if(CurrToken == ELSE){
				tok = mutch(ELSE);
				nodeM = stmt();
			}
			return AddNode(tok, nodeL, nodeM, nodeR);
			break;
		}
			
		case LEFT_FIG_BRECKET:{
			mutch(LEFT_FIG_BRECKET);
			NodeInt node = stmts();
			mutch(RIGHT_FIG_BRECKET);
			return AddNode(STMT, node, 0, 0);
			break;
		}
			
		case IDENTIFIER:{
			Token tok =  mutch(IDENTIFIER);

			
			if(CurrToken == MOV_OP){
				int idNum = Lookup(lexeme,0,0);
				if (idNum < 0){
					printf("Syntax error:В строке %d использована не объявленая переменная \n",line);
					return 0;
				}
				NodeInt idLeaf = AddLeaf(IDENTIFIER, idNum);
				
				tok = mutch(MOV_OP);
				NodeInt nodeR = boool();
				mutch(COMM_POINT);
				return AddNode(tok, idLeaf, 0,nodeR);
			}
			if(CurrToken == LEFT_BRECKET){
				int idNum = Lookup(lexeme,1,0);
				if (idNum < 0){
					printf("Syntax error:В строке %d использована не объявленая переменная \n",line);
					return 0;
				}
				NodeInt idLeaf = AddLeaf(IDENTIFIER, idNum);
				
				mutch(LEFT_BRECKET);
				NodeInt nodeR =boool();
				mutch(RIGHT_BRECKET);
				mutch(COMM_POINT);
				return AddNode(FUNCTION, idLeaf, 0, nodeR);
			}
			break;
		}
			
		case CONTINUE:{
			return AddNode(CONTINUE, 0, 0, 0);
		}
			
		case BREAK:{
			return AddNode(BREAK, 0, 0, 0);
		}
			
			
		default:
			printf("Syntaxes error\n");
			return 0;
			break;
	}
}
Esempio n. 17
0
const std::string& RA_RichPresenceInterpretter::GetRichPresenceString()
{
	static std::string sReturnVal;
	sReturnVal.clear();

	bool bParsingLookupName = false;
	bool bParsingLookupContent = false;

	std::string sLookupName;
	std::string sLookupValue;

	for( size_t i = 0; i < m_sDisplay.size(); ++i )
	{
		const char& c = m_sDisplay.at( i );

		if( bParsingLookupContent )
		{
			if( c == ')' )
			{
				//	End of content
				bParsingLookupContent = false;	

				//	Lookup!

				sReturnVal.append( Lookup( sLookupName, sLookupValue ) );

				sLookupName.clear();
				sLookupValue.clear();
			}
			else
			{
				sLookupValue.push_back( c );
			}
		}
		else if( bParsingLookupName )
		{
			if( c == '(' )
			{
				//	Now parsing lookup content
				bParsingLookupContent = true;
				bParsingLookupName = false;
			}
			else
			{
				//	Continue to parse lookup name
				sLookupName.push_back( c );
			}
		}
		else
		{
			//	Not parsing a lookup at all.
			if( c == '@' )
			{
				bParsingLookupName = true;
			}
			else
			{
				//	Standard text.
				sReturnVal.push_back( c );
			}
		}
	}

	return sReturnVal;
}
Esempio n. 18
0
arg_list_t *Resource::Symbol()
{
  int i = 0, j;
  arg_list_t *a;
  bool string = false;
  bool fp = false;
  float f;
  arg_list_t *adt;


  _symbol[0] = 0;

  if (Is('"'))
  {
	  Lex();
	  string = true;
  }

  // Mongoose 2001.11.09: Best handle for? grouped (func (func
  if (Is('('))
  {
	  return Function(arg_peek(&_stack));
  }

  while (string || (i == 0 && _look == '-') ||
			isatoz(_look) || isAtoZ(_look) || isdigit(_look) || ismisc(_look))
  {
	  if (i < (int)_symbol_len)
	  {
		  _symbol[i++] = _look;
		  _symbol[i] = 0;
	  }

	  if (string && Is('"'))
	  {
		  i--;
		  _symbol[i] = 0;
		  Lex();
		  break;
	  }
    
	  Lex();

	  if (string)
	  {
		  continue;
	  }

	  if (Is('.'))
	  {
		  fp = true;

		  for (j = 0; j < i; j++)
		  {
			  if (!j && _symbol[j] == '-')
				  continue;

			  if (!isdigit(_symbol[j]))
				  break;
		  }

		  if (i == j)
		  {
			  _symbol[i++] = _look;
			  _symbol[i] = 0;
			  Lex();
		  }
	  }


	  // Mongoose 2002.01.23, Hhhmm... fixes -100.00 and -100, 
	  //   but is it 'good idea'?
	  if (Is('-') && i == 0)
	  {
		  _symbol[i++] = _look;
		  _symbol[i] = 0;
		  Lex();
	  }
  }

#ifdef DEBUG_RESOURCE_SYMBOL
  printf("%s\n", _symbol);
#endif

  if (isnumeric(_symbol, &f))
  {
	  if (fp)
	  {
		  new_float(&a, f);
	  }
	  else
	  {
		  new_int(&a, (int)f);
	  }
  }
  else
  {
	  // Mongoose 2002.01.21, FIXME support ADTs and etc too
	  if (Lookup(_symbol, &i))
	  {
		  new_int(&a, i);
	  }
	  else if (Lookup(_symbol, &f))
	  {
		  new_float(&a, f);
	  }
	  else if (string)
	  {
		  mlisp_new_string(&a, _symbol);
	  }
	  else if (Lookup(_symbol, &adt))
	  {
		  mlisp_new_adt(&a, adt->type, adt->data);
	  }
	  else
	  {
		  // Mongoose 2002.01.21, FIXME: hack to handle old string
		  //   use for def symbols
		  mlisp_new_string(&a, _symbol);
	  }
  }

  return a;
}
//////////////////
// Remove all the hooks for a window
//
void CSubclassWndMap::RemoveAll(HWND hwnd)
{
  CSubclassWnd* pSubclassWnd;
  while ((pSubclassWnd = Lookup(hwnd))!=NULL)
    pSubclassWnd->HookWindow((HWND)NULL);  // (unhook)
}
Esempio n. 20
0
const std::string&
GameFile::LookupUsingConfigLanguage(const std::map<DiscIO::Language, std::string>& strings) const
{
  const bool wii = DiscIO::IsWii(m_platform);
  return Lookup(SConfig::GetInstance().GetCurrentLanguage(wii), strings);
}
Esempio n. 21
0
void COMF::DumpSegments() {
   // Dump all segment records

   // Define structure of attributes
   OMF_SAttrib Attributes;

   // Record values
   uint32 Frame, Offset, SegLength, NameIndex, ClassIndex, OverlayIndex;

   uint32 i;                                     // Record number
   uint32 SegNum = 0;                            // Segment number
   
   printf("\n\nSegment records:");
   for (i = 0; i < NumRecords; i++) {
      if (Records[i].Type2 == OMF_SEGDEF) {
         // SEGDEF record
         Records[i].Index = 3;
         // Loop through entries in record. There should be only 1
         while (Records[i].Index < Records[i].End) {
            Attributes.b = Records[i].GetByte();     // Read attributes
            if (Attributes.u.A == 0) {
               // Frame and Offset only included if A = 0
               Frame = Records[i].GetWord();  Offset = Records[i].GetByte();
            }
            else Frame = Offset = 0;
            SegLength    = Records[i].GetNumeric();
            NameIndex    = Records[i].GetIndex();
            ClassIndex   = Records[i].GetIndex();
            OverlayIndex = Records[i].GetIndex();

            printf("\n  Segment %2i, Name %s, Class %s, Align %i, %s, %i bit",
               ++SegNum, GetLocalName(NameIndex), GetLocalName(ClassIndex), 
               OMFAlignTranslate[Attributes.u.A], 
               Lookup(OMFSegmentCombinationNames, Attributes.u.C),
               Attributes.u.P ? 32 : 16);
            if (Attributes.u.B) printf(", big");
            if (Attributes.u.A == 0) printf(", Frame %i, Offset 0x%X", Frame, Offset);
            printf(", Length %i", SegLength);
            if (OverlayIndex) printf("\n   Overlay %i", OverlayIndex);
         }
         if (Records[i].Index != Records[i].End) err.submit(1203);   // Check for consistency
      }
   }
   printf("\n\nGroup records:");
   for (i = 0; i < NumRecords; i++) {
      if (Records[i].Type2 == OMF_GRPDEF) {
         // GRPDEF record
         Records[i].Index = 3;
         ClassIndex = Records[i].GetIndex();
         printf("\n  Group: %s\n   Segments:", GetLocalName(ClassIndex));

         // Loop through remaining entries in record
         while (Records[i].Index < Records[i].End) {
            uint8 Type = Records[i].GetByte();
            if (Type != 0xFF) printf(" Type=%X:", Type);
            NameIndex =  Records[i].GetIndex();
            printf(" %s", GetSegmentName(NameIndex));
         }
         if (Records[i].Index != Records[i].End) err.submit(1203);   // Check for consistency
      }
   }
}
Esempio n. 22
0
bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
{
    return Lookup(pszName, addr, portDefault, false);
}
Esempio n. 23
0
const char * COMF::GetRecordTypeName(uint32 i) {
   // Get record type name
   return Lookup(OMFRecordTypeNames, i);
}
Esempio n. 24
0
/*****************************************************************************
 * InheritValue: try to inherit the value of this variable from the same one
 *               in our closest parent.
 *****************************************************************************/
static int InheritValue( vlc_object_t *p_this, const char *psz_name,
                         vlc_value_t *p_val, int i_type )
{
    int i_var;
    variable_t *p_var;

    /* No need to take the structure lock,
     * we are only looking for our parents */

    if( !p_this->p_parent )
    {
        switch( i_type & VLC_VAR_TYPE )
        {
        case VLC_VAR_FILE:
        case VLC_VAR_DIRECTORY:
        case VLC_VAR_STRING:
        case VLC_VAR_MODULE:
            p_val->psz_string = config_GetPsz( p_this, psz_name );
            if( !p_val->psz_string ) p_val->psz_string = strdup("");
            break;
        case VLC_VAR_FLOAT:
            p_val->f_float = config_GetFloat( p_this, psz_name );
            break;
        case VLC_VAR_INTEGER:
        case VLC_VAR_HOTKEY:
            p_val->i_int = config_GetInt( p_this, psz_name );
            break;
        case VLC_VAR_BOOL:
            p_val->b_bool = config_GetInt( p_this, psz_name );
            break;
        case VLC_VAR_LIST:
        {
            char *psz_orig, *psz_var;
            vlc_list_t *p_list = malloc(sizeof(vlc_list_t));
            p_val->p_list = p_list;
            p_list->i_count = 0;

            psz_var = psz_orig = config_GetPsz( p_this, psz_name );
            while( psz_var && *psz_var )
            {
                char *psz_item = psz_var;
                vlc_value_t val;
                while( *psz_var && *psz_var != ',' ) psz_var++;
                if( *psz_var == ',' )
                {
                    *psz_var = '\0';
                    psz_var++;
                }
                val.i_int = strtol( psz_item, NULL, 0 );
                INSERT_ELEM( p_list->p_values, p_list->i_count,
                             p_list->i_count, val );
                /* p_list->i_count is incremented twice by INSERT_ELEM */
                p_list->i_count--;
                INSERT_ELEM( p_list->pi_types, p_list->i_count,
                             p_list->i_count, VLC_VAR_INTEGER );
            }
            if( psz_orig ) free( psz_orig );
            break;
        }
        default:
            return VLC_ENOOBJ;
            break;
        }

        return VLC_SUCCESS;
    }

    /* Look for the variable */
    vlc_mutex_lock( &p_this->p_parent->var_lock );

    i_var = Lookup( p_this->p_parent->p_vars, p_this->p_parent->i_vars,
                    psz_name );

    if( i_var >= 0 )
    {
        /* We found it! */
        p_var = &p_this->p_parent->p_vars[i_var];

        /* Really get the variable */
        *p_val = p_var->val;

        /* Duplicate value if needed */
        p_var->pf_dup( p_val );

        vlc_mutex_unlock( &p_this->p_parent->var_lock );
        return VLC_SUCCESS;
    }

    vlc_mutex_unlock( &p_this->p_parent->var_lock );

    /* We're still not there */

    return InheritValue( p_this->p_parent, psz_name, p_val, i_type );
}
Esempio n. 25
0
/**
 * Perform a Get and Set on a variable
 *
 * \param p_this: The object that hold the variable
 * \param psz_name: the name of the variable
 * \param i_action: the action to perform
 * \param p_val: The action parameter
 * \return vlc error codes
 */
int var_GetAndSet( vlc_object_t *p_this, const char *psz_name, int i_action,
                   vlc_value_t *p_val )
{
    int i_ret;
    variable_t *p_var;
    vlc_value_t oldval;

    assert( p_this );
    assert( p_val );

    vlc_object_internals_t *p_priv = vlc_internals( p_this );

    vlc_mutex_lock( &p_priv->var_lock );
    p_var = Lookup( p_this, psz_name );
    if( p_var == NULL )
    {
        vlc_mutex_unlock( &p_priv->var_lock );
        return VLC_ENOVAR;
    }

    WaitUnused( p_this, p_var );

    /* Duplicated data if needed */
    //p_var->ops->pf_dup( &val );

    /* Backup needed stuff */
    oldval = p_var->val;

    /* depending of the action requiered */
    switch( i_action )
    {
    case VLC_VAR_BOOL_TOGGLE:
        assert( ( p_var->i_type & VLC_VAR_BOOL ) == VLC_VAR_BOOL );
        p_var->val.b_bool = !p_var->val.b_bool;
        break;
    case VLC_VAR_INTEGER_ADD:
        assert( ( p_var->i_type & VLC_VAR_INTEGER ) == VLC_VAR_INTEGER );
        p_var->val.i_int += p_val->i_int;
        break;
    case VLC_VAR_INTEGER_OR:
        assert( ( p_var->i_type & VLC_VAR_INTEGER ) == VLC_VAR_INTEGER );
        p_var->val.i_int |= p_val->i_int;
        break;
    case VLC_VAR_INTEGER_NAND:
        assert( ( p_var->i_type & VLC_VAR_INTEGER ) == VLC_VAR_INTEGER );
        p_var->val.i_int &= ~p_val->i_int;
        break;
    default:
        vlc_mutex_unlock( &p_priv->var_lock );
        return VLC_EGENERIC;
    }

    /*  Check boundaries */
    CheckValue( p_var, &p_var->val );
    *p_val = p_var->val;

    /* Deal with callbacks.*/
    i_ret = TriggerCallback( p_this, p_var, psz_name, oldval );

    vlc_mutex_unlock( &p_priv->var_lock );

    return i_ret;
}
Esempio n. 26
0
/**
 * Initialize a vlc variable
 *
 * We hash the given string and insert it into the sorted list. The insertion
 * may require slow memory copies, but think about what we gain in the log(n)
 * lookup phase when setting/getting the variable value!
 *
 * \param p_this The object in which to create the variable
 * \param psz_name The name of the variable
 * \param i_type The variables type. Must be one of \ref var_type combined with
 *               zero or more \ref var_flags
 */
int __var_Create( vlc_object_t *p_this, const char *psz_name, int i_type )
{
    int i_new;
    variable_t *p_var;
    static vlc_list_t dummy_null_list = {0, NULL, NULL};

    vlc_mutex_lock( &p_this->var_lock );

    /* FIXME: if the variable already exists, we don't duplicate it. But we
     * duplicate the lookups. It's not that serious, but if anyone finds some
     * time to rework Insert() so that only one lookup has to be done, feel
     * free to do so. */
    i_new = Lookup( p_this->p_vars, p_this->i_vars, psz_name );

    if( i_new >= 0 )
    {
        /* If the types differ, variable creation failed. */
        if( (i_type & ~VLC_VAR_DOINHERIT) != p_this->p_vars[i_new].i_type )
        {
            vlc_mutex_unlock( &p_this->var_lock );
            return VLC_EBADVAR;
        }

        p_this->p_vars[i_new].i_usage++;
        vlc_mutex_unlock( &p_this->var_lock );
        return VLC_SUCCESS;
    }

    i_new = Insert( p_this->p_vars, p_this->i_vars, psz_name );

    if( (p_this->i_vars & 15) == 15 )
    {
        p_this->p_vars = realloc( p_this->p_vars,
                                  (p_this->i_vars+17) * sizeof(variable_t) );
    }

    memmove( p_this->p_vars + i_new + 1,
             p_this->p_vars + i_new,
             (p_this->i_vars - i_new) * sizeof(variable_t) );

    p_this->i_vars++;

    p_var = &p_this->p_vars[i_new];
    memset( p_var, 0, sizeof(*p_var) );

    p_var->i_hash = HashString( psz_name );
    p_var->psz_name = strdup( psz_name );
    p_var->psz_text = NULL;

    p_var->i_type = i_type & ~VLC_VAR_DOINHERIT;
    memset( &p_var->val, 0, sizeof(vlc_value_t) );

    p_var->pf_dup = DupDummy;
    p_var->pf_free = FreeDummy;

    p_var->i_usage = 1;

    p_var->i_default = -1;
    p_var->choices.i_count = 0;
    p_var->choices.p_values = NULL;
    p_var->choices_text.i_count = 0;
    p_var->choices_text.p_values = NULL;

    p_var->b_incallback = VLC_FALSE;
    p_var->i_entries = 0;
    p_var->p_entries = NULL;

    /* Always initialize the variable, even if it is a list variable; this
     * will lead to errors if the variable is not initialized, but it will
     * not cause crashes in the variable handling. */
    switch( i_type & VLC_VAR_TYPE )
    {
        case VLC_VAR_BOOL:
            p_var->pf_cmp = CmpBool;
            p_var->val.b_bool = VLC_FALSE;
            break;
        case VLC_VAR_INTEGER:
        case VLC_VAR_HOTKEY:
            p_var->pf_cmp = CmpInt;
            p_var->val.i_int = 0;
            break;
        case VLC_VAR_STRING:
        case VLC_VAR_MODULE:
        case VLC_VAR_FILE:
        case VLC_VAR_DIRECTORY:
        case VLC_VAR_VARIABLE:
            p_var->pf_cmp = CmpString;
            p_var->pf_dup = DupString;
            p_var->pf_free = FreeString;
            p_var->val.psz_string = "";
            break;
        case VLC_VAR_FLOAT:
            p_var->pf_cmp = CmpFloat;
            p_var->val.f_float = 0.0;
            break;
        case VLC_VAR_TIME:
            p_var->pf_cmp = CmpTime;
            p_var->val.i_time = 0;
            break;
        case VLC_VAR_ADDRESS:
            p_var->pf_cmp = CmpAddress;
            p_var->val.p_address = NULL;
            break;
        case VLC_VAR_MUTEX:
            p_var->pf_cmp = CmpAddress;
            p_var->pf_free = FreeMutex;
            p_var->val.p_address = malloc( sizeof(vlc_mutex_t) );
            vlc_mutex_init( p_this, (vlc_mutex_t*)p_var->val.p_address );
            break;
        case VLC_VAR_LIST:
            p_var->pf_cmp = CmpAddress;
            p_var->pf_dup = DupList;
            p_var->pf_free = FreeList;
            p_var->val.p_list = &dummy_null_list;
            break;
    }

    /* Duplicate the default data we stored. */
    p_var->pf_dup( &p_var->val );

    if( i_type & VLC_VAR_DOINHERIT )
    {
        vlc_value_t val;

        if( InheritValue( p_this, psz_name, &val, p_var->i_type )
            == VLC_SUCCESS )
        {
            /* Free data if needed */
            p_var->pf_free( &p_var->val );
            /* Set the variable */
            p_var->val = val;

            if( i_type & VLC_VAR_HASCHOICE )
            {
                /* We must add the inherited value to our choice list */
                p_var->i_default = 0;

                INSERT_ELEM( p_var->choices.p_values, p_var->choices.i_count,
                             0, val );
                INSERT_ELEM( p_var->choices_text.p_values,
                             p_var->choices_text.i_count, 0, val );
                p_var->pf_dup( &p_var->choices.p_values[0] );
                p_var->choices_text.p_values[0].psz_string = NULL;
            }
        }
    }

    vlc_mutex_unlock( &p_this->var_lock );

    return VLC_SUCCESS;
}
Esempio n. 27
0
void EndPoint::NetworkThreadProc()
{
    IAllocator *const allocator(AllocatorManager::Instance().GetAllocator());

    THERON_ASSERT(mContext);
    THERON_ASSERT(!mLocation.IsNull());

    // Create the output socket.
    // This is the socket we use to publish messages sent by local actors.
    // EndPoint objects in other processors or on other hosts create SUB sockets
    // and connect them to the same endpoint.
    void *const outputSocketMemory(allocator->Allocate(sizeof(Detail::OutputSocket)));
    if (outputSocketMemory == 0)
    {
        THERON_FAIL_MSG("Failed to allocate output socket");
    }

    Detail::OutputSocket *const outputSocket = new (outputSocketMemory) Detail::OutputSocket(mContext);

    // Create the input socket.
    // This is the socket we use to subscribe to messages published by other actors.
    // We connect to the endpoints of the publish sockets of the remote processes.
    void *const inputSocketMemory(allocator->Allocate(sizeof(Detail::InputSocket)));
    if (inputSocketMemory == 0)
    {
        THERON_FAIL_MSG("Failed to allocate input socket");
    }

    Detail::InputSocket *const inputSocket = new (inputSocketMemory) Detail::InputSocket(mContext);

    // Bind the output socket to the local endpoint that is this EndPoint's address.
    if (!outputSocket->Bind(mLocation.GetValue()))
    {
        THERON_FAIL_MSG("Failed to bind output socket to endpoint - check network support is enabled");
    }

    // Create a network output message, which we reuse to send network messages within the loop.
    void *const outputMessageMemory(allocator->Allocate(sizeof(Detail::OutputMessage)));
    if (outputMessageMemory == 0)
    {
        THERON_FAIL_MSG("Failed to allocate output message");
    }

    Detail::OutputMessage *const outputMessage = new (outputMessageMemory) Detail::OutputMessage(mContext);

    // Create a network input message, which we reuse to receive network messages within the loop.
    void *const inputMessageMemory(allocator->Allocate(sizeof(Detail::InputMessage)));
    if (inputMessageMemory == 0)
    {
        THERON_FAIL_MSG("Failed to allocate input message");
    }

    Detail::InputMessage *const inputMessage = new (inputMessageMemory) Detail::InputMessage(mContext);

    // Initialize the input message once outside the loop.
    if (!inputMessage->Initialize())
    {
        THERON_FAIL_MSG("Failed to initialize network input message");
    }

    // Signal the main thread that we've started.
    mStarted = true;

    while (mRunning)
    {
        mNetworkLock.Lock();

        // Service connection requests.
        while (!mConnectQueue.Empty())
        {
            ConnectRequest *const request(mConnectQueue.Pop());
            const char *const address(request->mLocation.GetValue());

            mNetworkLock.Unlock();

            // Connect the input socket to the remote host.
            // The same socket can be connected to multiple remote endpoints.
            if (!inputSocket->Connect(address))
            {
                THERON_FAIL_MSG("Failed to connect input socket to remote endpoint");
            }

            mNetworkLock.Lock();

            request->~ConnectRequest();
            allocator->Free(request, sizeof(ConnectRequest));
        }

        // Service send requests.
        while (!mSendQueue.Empty())
        {
            SendRequest *const request(mSendQueue.Pop());

            mNetworkLock.Unlock();

            THERON_ASSERT_MSG(outputSocket, "No output socket found");

            Detail::IMessage *const message(request->mMessage);
            const char *const fromName(message->From().AsString());
            const char *const toName(request->mName.GetValue());
            const char *const messageName(message->TypeName());
            const void *const messageData(message->GetMessageData());
            const uint32_t messageSize(message->GetMessageSize());

            THERON_ASSERT_MSG(messageName, "Can't send unregistered messages to actors addressed by name!");

            // Calculate the size of the network message.
            const uint32_t networkMessageSize = Detail::NetworkMessage::GetSize(
                fromName,
                toName,
                messageName,
                messageData,
                messageSize);

            // Initialize the output message.
            if (!outputMessage->Initialize(networkMessageSize))
            {
                THERON_FAIL_MSG("Failed to initialize network output message");
            }

            // Initialize the XS message block as a network message.
            // This copies the message data into the memory block.
            void *const memoryBlock(outputMessage->Data());
            Detail::NetworkMessage::Initialize(
                memoryBlock,
                fromName,
                toName,
                messageName,
                messageData,
                messageSize);

            // Send the network message.
            if (!outputSocket->Send(outputMessage))
            {
                THERON_FAIL_MSG("Failed to send network output message");
            }

            // Release the output message.
            if (!outputMessage->Release())
            {
                THERON_FAIL_MSG("Failed to release network output message");
            }

            // Destroy the local message.
            // We return the message memory block to the global allocator.
            Detail::MessageCreator::Destroy(allocator, message);

            // Destroy the request structure.
            request->~SendRequest();
            allocator->Free(request, sizeof(SendRequest));

            mNetworkLock.Lock();
        }

        mNetworkLock.Unlock();

        // Read messages from the input socket without blocking.
        while (inputSocket->NonBlockingReceive(inputMessage))
        {
            // Read the data from the received network message.
            const uint32_t networkMessageSize(inputMessage->Size());
            if (networkMessageSize < sizeof(Detail::NetworkMessage))
            {
                THERON_FAIL_MSG("Invalid XS message data size");
            }

            const Detail::NetworkMessage *const networkMessage(reinterpret_cast<Detail::NetworkMessage *>(inputMessage->Data()));
            if (networkMessage == 0)
            {
                THERON_FAIL_MSG("Invalid XS message data pointer");
            }

            const char *const fromName(networkMessage->GetFromName());
            const Detail::String toName(networkMessage->GetToName());
            const Detail::String messageName(networkMessage->GetMessageName());
            const void *const messageData(networkMessage->GetMessageData());
            const uint32_t messageSize(networkMessage->GetMessageSize());

            // Look up the to address index using the received name.
            // If the name isn't known to us we just discard the message.
            Detail::Index toIndex;
            if (Lookup(toName, toIndex))
            {
                // Construct the name-only 'from' address.
                const Address fromAddress(fromName);

                // Try to build a message from the data based on the message name.
                Detail::IMessage *const message = mMessageFactory.Build(
                    messageName,
                    messageData,
                    messageSize,
                    fromAddress);

                if (message)
                {
                    // Try to deliver the allocated message to an actor in a local framework.
                    if (!Detail::MessageSender::DeliverWithinLocalProcess(message, toIndex))
                    {
                        // Destroy the undelivered message using the global allocator.
                        Detail::MessageCreator::Destroy(allocator, message);
                    }
                }
            }
        }

        // The network thread spends most of its time asleep.
        Detail::Utils::SleepThread(1);
    }

    mNetworkLock.Lock();

    // Drain the connection request queue.
    while (!mConnectQueue.Empty())
    {
        ConnectRequest *const request(mConnectQueue.Pop());
        request->~ConnectRequest();
        allocator->Free(request, sizeof(ConnectRequest));
    }

    // Drain the send request queue.
    while (!mSendQueue.Empty())
    {
        SendRequest *const request(mSendQueue.Pop());
        request->~SendRequest();
        allocator->Free(request, sizeof(SendRequest));
    }

    mNetworkLock.Unlock();

    // Release the input message used repeatedly within the loop.
    if (!inputMessage->Release())
    {
        THERON_FAIL_MSG("Failed to release network input message");
    }

    // Destroy the output and input messages.
    outputMessage->~OutputMessage();
    allocator->Free(outputMessage, sizeof(Detail::OutputMessage));

    inputMessage->~InputMessage();
    allocator->Free(inputMessage, sizeof(Detail::InputMessage));

    // Destroy the output and input sockets.
    outputSocket->~OutputSocket();
    allocator->Free(outputSocket, sizeof(Detail::OutputSocket));

    inputSocket->~InputSocket();
    allocator->Free(inputSocket, sizeof(Detail::InputSocket));
}
Esempio n. 28
0
/**
 * Perform an action on a variable
 *
 * \param p_this The object that holds the variable
 * \param psz_name The name of the variable
 * \param i_action The action to perform. Must be one of \ref var_action
 * \param p_val First action parameter
 * \param p_val2 Second action parameter
 */
int __var_Change( vlc_object_t *p_this, const char *psz_name,
                  int i_action, vlc_value_t *p_val, vlc_value_t *p_val2 )
{
    int i_var, i;
    variable_t *p_var;
    vlc_value_t oldval;

    vlc_mutex_lock( &p_this->var_lock );

    i_var = Lookup( p_this->p_vars, p_this->i_vars, psz_name );

    if( i_var < 0 )
    {
        vlc_mutex_unlock( &p_this->var_lock );
        return VLC_ENOVAR;
    }

    p_var = &p_this->p_vars[i_var];

    switch( i_action )
    {
        case VLC_VAR_SETMIN:
            if( p_var->i_type & VLC_VAR_HASMIN )
            {
                p_var->pf_free( &p_var->min );
            }
            p_var->i_type |= VLC_VAR_HASMIN;
            p_var->min = *p_val;
            p_var->pf_dup( &p_var->min );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETMAX:
            if( p_var->i_type & VLC_VAR_HASMAX )
            {
                p_var->pf_free( &p_var->max );
            }
            p_var->i_type |= VLC_VAR_HASMAX;
            p_var->max = *p_val;
            p_var->pf_dup( &p_var->max );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETSTEP:
            if( p_var->i_type & VLC_VAR_HASSTEP )
            {
                p_var->pf_free( &p_var->step );
            }
            p_var->i_type |= VLC_VAR_HASSTEP;
            p_var->step = *p_val;
            p_var->pf_dup( &p_var->step );
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_ADDCHOICE:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = p_var->choices.i_count ; i-- ; )
            {
                if( p_var->pf_cmp( p_var->choices.p_values[i], *p_val ) < 0 )
                {
                    break;
                }
            }

            /* The new place is i+1 */
            i++;

            if( p_var->i_default >= i )
            {
                p_var->i_default++;
            }

            INSERT_ELEM( p_var->choices.p_values, p_var->choices.i_count,
                         i, *p_val );
            INSERT_ELEM( p_var->choices_text.p_values,
                         p_var->choices_text.i_count, i, *p_val );
            p_var->pf_dup( &p_var->choices.p_values[i] );
            p_var->choices_text.p_values[i].psz_string =
                ( p_val2 && p_val2->psz_string ) ?
                strdup( p_val2->psz_string ) : NULL;

            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_DELCHOICE:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                if( p_var->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
                {
                    break;
                }
            }

            if( i == p_var->choices.i_count )
            {
                /* Not found */
                vlc_mutex_unlock( &p_this->var_lock );
                return VLC_EGENERIC;
            }

            if( p_var->i_default > i )
            {
                p_var->i_default--;
            }
            else if( p_var->i_default == i )
            {
                p_var->i_default = -1;
            }

            p_var->pf_free( &p_var->choices.p_values[i] );
            if( p_var->choices_text.p_values[i].psz_string )
                free( p_var->choices_text.p_values[i].psz_string );
            REMOVE_ELEM( p_var->choices.p_values, p_var->choices.i_count, i );
            REMOVE_ELEM( p_var->choices_text.p_values,
                         p_var->choices_text.i_count, i );

            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_CHOICESCOUNT:
            p_val->i_int = p_var->choices.i_count;
            break;
        case VLC_VAR_CLEARCHOICES:
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                p_var->pf_free( &p_var->choices.p_values[i] );
            }
            for( i = 0 ; i < p_var->choices_text.i_count ; i++ )
            {
                if( p_var->choices_text.p_values[i].psz_string )
                    free( p_var->choices_text.p_values[i].psz_string );
            }
            if( p_var->choices.i_count ) free( p_var->choices.p_values );
            if( p_var->choices_text.i_count ) free( p_var->choices_text.p_values );

            p_var->choices.i_count = 0;
            p_var->choices.p_values = NULL;
            p_var->choices_text.i_count = 0;
            p_var->choices_text.p_values = NULL;
            p_var->i_default = -1;
            break;
        case VLC_VAR_SETDEFAULT:
            /* FIXME: the list is sorted, dude. Use something cleverer. */
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                if( p_var->pf_cmp( p_var->choices.p_values[i], *p_val ) == 0 )
                {
                    break;
                }
            }

            if( i == p_var->choices.i_count )
            {
                /* Not found */
                break;
            }

            p_var->i_default = i;
            CheckValue( p_var, &p_var->val );
            break;
        case VLC_VAR_SETVALUE:
            /* Duplicate data if needed */
            p_var->pf_dup( p_val );
            /* Backup needed stuff */
            oldval = p_var->val;
            /* Check boundaries and list */
            CheckValue( p_var, p_val );
            /* Set the variable */
            p_var->val = *p_val;
            /* Free data if needed */
            p_var->pf_free( &oldval );
            break;
        case VLC_VAR_GETCHOICES:
        case VLC_VAR_GETLIST:
            p_val->p_list = malloc( sizeof(vlc_list_t) );
            if( p_val2 ) p_val2->p_list = malloc( sizeof(vlc_list_t) );
            if( p_var->choices.i_count )
            {
                p_val->p_list->p_values = malloc( p_var->choices.i_count
                                                  * sizeof(vlc_value_t) );
                p_val->p_list->pi_types = malloc( p_var->choices.i_count
                                                  * sizeof(int) );
                if( p_val2 )
                {
                    p_val2->p_list->p_values =
                        malloc( p_var->choices.i_count * sizeof(vlc_value_t) );
                    p_val2->p_list->pi_types =
                        malloc( p_var->choices.i_count * sizeof(int) );
                }
            }
            p_val->p_list->i_count = p_var->choices.i_count;
            if( p_val2 ) p_val2->p_list->i_count = p_var->choices.i_count;
            for( i = 0 ; i < p_var->choices.i_count ; i++ )
            {
                p_val->p_list->p_values[i] = p_var->choices.p_values[i];
                p_val->p_list->pi_types[i] = p_var->i_type;
                p_var->pf_dup( &p_val->p_list->p_values[i] );
                if( p_val2 )
                {
                    p_val2->p_list->p_values[i].psz_string =
                        p_var->choices_text.p_values[i].psz_string ?
                    strdup(p_var->choices_text.p_values[i].psz_string) : NULL;
                    p_val2->p_list->pi_types[i] = VLC_VAR_STRING;
                }
            }
            break;
        case VLC_VAR_FREELIST:
            FreeList( p_val );
            if( p_val2 && p_val2->p_list )
            {
                for( i = 0; i < p_val2->p_list->i_count; i++ )
                    if( p_val2->p_list->p_values[i].psz_string )
                        free( p_val2->p_list->p_values[i].psz_string );
                if( p_val2->p_list->i_count )
                {
                    free( p_val2->p_list->p_values );
                    free( p_val2->p_list->pi_types );
                }
                free( p_val2->p_list );
            }
            break;
        case VLC_VAR_SETTEXT:
            if( p_var->psz_text ) free( p_var->psz_text );
            if( p_val && p_val->psz_string )
                p_var->psz_text = strdup( p_val->psz_string );
            break;
        case VLC_VAR_GETTEXT:
            p_val->psz_string = NULL;
            if( p_var->psz_text )
            {
                p_val->psz_string = strdup( p_var->psz_text );
            }
            break;
        case VLC_VAR_INHERITVALUE:
            {
                vlc_value_t val;

                if( InheritValue( p_this, psz_name, &val, p_var->i_type )
                    == VLC_SUCCESS )
                {
                    /* Duplicate already done */

                    /* Backup needed stuff */
                    oldval = p_var->val;
                    /* Check boundaries and list */
                    CheckValue( p_var, &val );
                    /* Set the variable */
                    p_var->val = val;
                    /* Free data if needed */
                    p_var->pf_free( &oldval );
                }

                if( p_val )
                {
                    *p_val = p_var->val;
                    p_var->pf_dup( p_val );
                }
            }
            break;
        case VLC_VAR_TRIGGER_CALLBACKS:
            {
                /* Deal with callbacks. Tell we're in a callback, release the lock,
                 * call stored functions, retake the lock. */
                if( p_var->i_entries )
                {
                    int i_var;
                    int i_entries = p_var->i_entries;
                    callback_entry_t *p_entries = p_var->p_entries;

                    p_var->b_incallback = VLC_TRUE;
                    vlc_mutex_unlock( &p_this->var_lock );

                    /* The real calls */
                    for( ; i_entries-- ; )
                    {
                        p_entries[i_entries].pf_callback( p_this, psz_name, p_var->val, p_var->val,
                                                          p_entries[i_entries].p_data );
                    }

                    vlc_mutex_lock( &p_this->var_lock );

                    i_var = Lookup( p_this->p_vars, p_this->i_vars, psz_name );
                    if( i_var < 0 )
                    {
                        msg_Err( p_this, "variable %s has disappeared", psz_name );
                        vlc_mutex_unlock( &p_this->var_lock );
                        return VLC_ENOVAR;
                    }

                    p_var = &p_this->p_vars[i_var];
                    p_var->b_incallback = VLC_FALSE;
                }
            }
            break;

        default:
            break;
    }

    vlc_mutex_unlock( &p_this->var_lock );

    return VLC_SUCCESS;
}
//
// CList::Member
//
template <class C> int CList<C>::Member(C *memberP)
{
  return(Lookup(memberP) != 0);
}
Esempio n. 30
0
ICCItem *CCodeChain::Eval (CEvalContext *pEvalCtx, ICCItem *pItem)

//	Eval
//
//	Evaluates the given item and returns a result

{
    //	Errors always evaluate to themselves

    if (pItem->IsError())
        return pItem->Reference();

    //	If this item is quoted, then return an unquoted item

    if (pItem->IsQuoted())
    {
        //	If this is a literal symbol table then we need to evaluate its
        //	values.

        if (pItem->IsSymbolTable())
            return EvalLiteralStruct(pEvalCtx, pItem);

        //	HACK: We clone the item so that when we try to modify a literal list we
        //	mody a copy instead of the original.

        else
        {
            ICCItem *pResult = pItem->Clone(this);
            pResult->ClearQuoted();
            return pResult;
        }
    }

    //	Evaluate differently depending on whether or not
    //	this is an atom or a list. If it is an atom, either return
    //	the value or look up the atom in a symbol table. If the item
    //	is a list, try to evaluate as a function

    else if (pItem->IsIdentifier())
        return Lookup(pEvalCtx, pItem);

    //	If this is an expression (a list with multiple terms) then we
    //	try to evaluate it.

    else if (pItem->IsExpression())
    {
        ICCItem *pFunctionName;
        ICCItem *pFunction;
        ICCItem *pArgs;
        ICCItem *pResult;

        //	The first element of the list is the function

        pFunctionName = pItem->Head(this);

        //	We must have a first element since this is a list (but not Nil)

        ASSERT(pFunctionName);

        //	If this is an identifier, then look up the function
        //	in the global symbols

        if (pFunctionName->IsIdentifier())
            pFunction = LookupFunction(pEvalCtx, pFunctionName);

        //	Otherwise, evaluate it

        else
            pFunction = Eval(pEvalCtx, pFunctionName);

        //	If we get an error, return it

        if (pFunction->IsError())
            return pFunction;

        //	Make sure this is a function

        if (!pFunction->IsFunction())
        {
            pFunction->Discard(this);
            return CreateError(LITERAL("Function name expected"), pFunctionName);
        }

        //	Get the arguments

        pArgs = pItem->Tail(this);

        //	Do it

        pResult = pFunction->Execute(pEvalCtx, pArgs);

        //	Handle error by appending the function call that failed

        if (pResult->IsError())
        {
            CCString *pError = dynamic_cast<CCString *>(pResult);
            if (pError)
            {
                CString sError = pError->GetValue();
                if (!sError.IsBlank())
                {
                    char *pPos = sError.GetASCIIZPointer() + sError.GetLength() - 1;
                    if (*pPos != '#')
                    {
                        sError.Append(strPatternSubst(CONSTLIT(" ### %s ###"), pItem->Print(this)));
                        pError->SetValue(sError);
                    }
                }
            }
        }

        //	Done

        pFunction->Discard(this);
        pArgs->Discard(this);
        return pResult;
    }

    //	Anything else is a literal so we return it.

    else
        return pItem->Reference();

}