itvEnum IsPackageTrusted(LPCSTR szSetupExe, LPCSTR szPackage, HWND hwndParent)
{
    WCHAR *szwSetup   = 0;
    WCHAR *szwPackage = 0;
    int   cchWide     = 0;

    bool    fPackageIsTrusted = false;
    bool    fSetupExeIsSigned = false;
    bool    fPackageIsSigned  = false;
    itvEnum itv               = itvUnTrusted;

    DWORD dwUILevel = 0;

    char szDebugOutput[MAX_STR_LENGTH] = {0};

    PCCERT_CONTEXT pcExeSigner = 0;
    PCCERT_CONTEXT pcMsiSigner = 0;

    HMODULE hCrypt32 = LoadLibrary(CRYPT32_DLL);
    if (!hCrypt32)
    {
        // no crypto on the machine
        return itvWintrustNotOnMachine;
    }
    PFnCertCompareCertificate pfnCertCompareCertificate = (PFnCertCompareCertificate)GetProcAddress(hCrypt32, CRYPTOAPI_CertCompareCertificate);
    PFnCertFreeCertificateContext pfnCertFreeCertificateContext = (PFnCertFreeCertificateContext)GetProcAddress(hCrypt32, CRYPTOAPI_CertFreeCertificateContext);
    if (!pfnCertCompareCertificate || !pfnCertFreeCertificateContext)
    {
        // no crypt on the machine
        FreeLibrary(hCrypt32);
        return itvWintrustNotOnMachine;
    }

    // convert szSetupExe to WIDE
    cchWide = MultiByteToWideChar(CP_ACP, 0, szSetupExe, -1, 0, 0);
    szwSetup = new WCHAR[cchWide];
    if (!szwSetup)
    {
        // out of memory
        FreeLibrary(hCrypt32);
        return itvUnTrusted;
    }
    if (0 == MultiByteToWideChar(CP_ACP, 0, szSetupExe, -1, szwSetup, cchWide))
    {
        // failed to convert string
        FreeLibrary(hCrypt32);
        delete [] szwSetup;
        return itvUnTrusted;
    }

    //
    // step 1: silently call WinVerifyTrust on szSetupExe, ignore return value - except for ivtWintrustNotOnMachine
    //

    DebugMsg("[WVT] step 1: silently call WinVerifyTrust on szSetupExe, ignoring return value\n");

    if (itvWintrustNotOnMachine == (itv = IsFileTrusted(szwSetup, hwndParent, WTD_UI_NONE, &fSetupExeIsSigned, &pcExeSigner)))
    {
        goto CleanUp;
    }

    DebugMsg("[WVT] fSetupExeIsSigned = %s\n", fSetupExeIsSigned ? "TRUE" : "FALSE");

    // convert szPackage to WIDE
    cchWide = MultiByteToWideChar(CP_ACP, 0, szPackage, -1, 0, 0);
    szwPackage = new WCHAR[cchWide];
    if (!szwPackage)
    {
        // out of memory
        FreeLibrary(hCrypt32);
        return itvUnTrusted;
    }
    if (0 == MultiByteToWideChar(CP_ACP, 0, szPackage, -1, szwPackage, cchWide))
    {
        // failed to convert string
        FreeLibrary(hCrypt32);
        return itvUnTrusted;
    }

    //
    // step 2: silently call WinVerifyTrust on szPackage, ignore return value - except for ivtWintrustNotOnMachine
    //

    if (fSetupExeIsSigned)
    {
        DebugMsg("[WVT] step2: silently call WinVerifyTrust on szPackage, ignoring return value\n");
        if (itvWintrustNotOnMachine == (itv = IsFileTrusted(szwPackage, hwndParent, WTD_UI_NONE, &fPackageIsSigned, &pcMsiSigner)))
        {
            goto CleanUp;
        }

        DebugMsg("[WVT] fPackageIsSigned = %s\n", fPackageIsSigned ? "TRUE" : "FALSE");
    }

    //
    // step 3: call WinVerifyTrust on szPackage, return value matters; use proper UI-level
    //

    if ( !fSetupExeIsSigned  // exe is not signed
        || !fPackageIsSigned // package is not signed
        || !pcExeSigner      // exe signer cert is missing
        || !pcMsiSigner      // package signer cert is missing
        || !pfnCertCompareCertificate(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pcExeSigner->pCertInfo, pcMsiSigner->pCertInfo)) // signed by different certs
    {
        // always show UI
        DebugMsg("[WVT] step3: last call to WinVerifyTrust using full UI\n");
        dwUILevel = WTD_UI_ALL;
    }
    else
    {
        // show UI only if bad
        DebugMsg("[WVT] step3: last call to WinVerifyTrust showing UI only if something is wrong\n");
        dwUILevel = WTD_UI_NOGOOD;
    }

    itv = IsFileTrusted(szwPackage, hwndParent, dwUILevel, NULL, NULL);

    //
    // cleanup
    //

CleanUp:
    if (szwPackage)
        delete [] szwPackage;
    if (szwSetup)
        delete [] szwSetup;

    if (pcExeSigner)
        pfnCertFreeCertificateContext(pcExeSigner);
    if (pcMsiSigner)
        pfnCertFreeCertificateContext(pcMsiSigner);

    FreeLibrary(hCrypt32);

    return itv;
}
Exemple #2
0
int
WriteNativeRecord(FieldSpec **fields,
                  FILE      *file)
{
   long    i;
   long    nopt;
   Uchar   flags;

   if (file == NULL || fields == NULL)
      {
         DebugMsg(1, "WriteNativeRecord: NULL argument.");
         return FALSE;
      }

   /*! If FieldOrder & TypeOrder returned a linear array of OPTIONAL
    * fields as well as the array of REQUIRED & OPTIONAL, we could
    * avoid scanning all of "fields" checking for OPTIONAL entries
    * for every record written. */

   nopt = 0;
   flags = 0;

   for (i = 0; fields[i] != NULL; i++)
      {
         if (fields[i]->occurrence == OPTIONAL)
            {
               flags |= fields[i]->present;

               nopt++;

               if (nopt % 8 == 0)
                  {
                     if (fwrite(&flags, 1, 1, file) != 1)
                        {
                           DebugMsg(1, ("WriteNativeRecord:  couldn't write "
                                        "\"presence\" flag for OPTIONAL field."));
                           return FALSE;
                        }

                     flags = 0;
                  }
               else
                  flags <<= 1;
            }
      }

   if (nopt % 8 != 0)
      {
         flags <<= (7 - nopt % 8);

         if (fwrite(&flags, 1, 1, file) != 1)
            {
               DebugMsg(1, ("WriteNativeRecord: couldn't write "
                            "\"presence\" flags for OPTIONAL fields."));
               return FALSE;
            }
      }

   for (i = 0; fields[i] != NULL; i++)
      {
         if (fields[i]->occurrence == REQUIRED || fields[i]->present)
            {
               if (!WriteNativeData(fields[i], file))
                  {
                     DebugMsg(1, "WriteNativeRecord: couldn't write field data.");
                     return FALSE;
                  }
            }
      }

   return TRUE;
}
// ---------------------------------------------------------------------------
// VComponentManager::RegisterComponentLibrary						[static]
// ---------------------------------------------------------------------------
// Load all component creators from a given library. Make sure that the
// library exports the VComponentLibrary interface.
//
VError VComponentManager::RegisterComponentLibrary( const VFilePath& inLibraryFile)
{
	DebugMsg("VComponentManager load %V\n", &inLibraryFile.GetPath());
	if (!IsInitialized())
		return vThrowError(VE_COMP_UNITIALISED);
	
	VError	error = VE_OK;
	
	VLibrary*	library;
	VArrayIteratorOf<VLibrary*>	iterator(*sComponentLibraries);
	
	// Iterate through libraries
	while ((library = iterator.Next()) != NULL)
	{
		if (library->IsSameFile(inLibraryFile))
		{
			error = vThrowError(VE_COMP_ALLREADY_REGISTRED);
			break;
		}
	}
	
	if (library == NULL)
	{
		library = new VLibrary(inLibraryFile);
		
		if (library != NULL)
		{
			if (!library->Load())
			{
				error = vThrowError(VE_COMP_CANNOT_LOAD_LIBRARY);
				library->Release();
				library = NULL;
			}
		}
		
		if (library != NULL)
		{
			// Make sure the library export the needed interface
			MainProcPtr	mainPtr = (MainProcPtr) library->GetProcAddress(kDEFAULT_MAIN_SYMBOL);
			GetNthComponentTypeProcPtr	fetchPtr = (GetNthComponentTypeProcPtr) library->GetProcAddress(kDEFAULT_GET_TYPES_SYMBOL);
			CreateComponentProcPtr	creatorPtr = (CreateComponentProcPtr) library->GetProcAddress(kDEFAULT_CREATE_SYMBOL);
			
			// Fetch all implemented components
			if (creatorPtr != NULL && fetchPtr != NULL && mainPtr != NULL)
			{
				sAccessingTypes->Lock();
				sAccessingChecked->Lock();
				
				(mainPtr)(kDLL_EVENT_REGISTER, library);
					
				CType	newType;
				sLONG	index = 1;
				while ((fetchPtr)(index, newType))
				{
					VIndex	oldPos = sComponentTypes->FindPos(newType);
					if (oldPos > 0)
					{
						// Assumes its allready installed using ProcPtr
						assert(sComponentProcs->GetNth(oldPos) != NULL);
						assert(sComponentLibraries->GetNth(oldPos) == NULL);
						
						sComponentLibraries->SetNth(library, oldPos);
					}
					else
					{
						// Add entries
						sComponentLibraries->AddTail(library);
						sComponentProcs->AddTail(NULL);
						sComponentTypes->AddTail(newType);
					}
					
					// Increment library refcount for each type
					library->Retain();
					
					index++;
		
					// Reset checking for unavailable components
					ResetComponentRequirements(newType, false);
				}
				
				sAccessingChecked->Unlock();
				sAccessingTypes->Unlock();
			}
			else
			{
				error = VE_COMP_BAD_LIBRARY_TYPE;
			}
			
			// Release library ('new' balance)
			library->Release();
		}
		else
		{
			error = VE_MEMORY_FULL;
		}
	}
	
	return error;
}
Exemple #4
0
void F3D_Reserved0( u32 w0, u32 w1 )
{
#ifdef DEBUG
	DebugMsg( DEBUG_MEDIUM | DEBUG_IGNORED | DEBUG_UNKNOWN, "G_RESERVED0: w0=0x%08lX w1=0x%08lX\n", w0, w1 );
#endif
}
BOOLEAN ReadInClothesStats(STR fileName)
{
	HWFILE		hFile;
	UINT32		uiBytesRead;
	UINT32		uiFSize;
	CHAR8 *		lpcBuffer;
	XML_Parser	parser = XML_ParserCreate(NULL);

	clothesParseData pData;

	DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading Clothes.xml" );

	// Open clothess file
	hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
	if ( !hFile )
		return( FALSE );

	uiFSize = FileGetSize(hFile);
	lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);

	//Read in block
	if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
	{
		MemFree(lpcBuffer);
		return( FALSE );
	}

	lpcBuffer[uiFSize] = 0; //add a null terminator

	FileClose( hFile );


	XML_SetElementHandler(parser, clothesStartElementHandle, clothesEndElementHandle);
	XML_SetCharacterDataHandler(parser, clothesCharacterDataHandle);


	memset(&pData,0,sizeof(pData));
	pData.curArray = Clothes;
	pData.maxArraySize = CLOTHES_MAX;

	XML_SetUserData(parser, &pData);


	if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
	{
		CHAR8 errorBuf[511];

		sprintf(errorBuf, "XML Parser Error in Clothes.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
		LiveMessage(errorBuf);

		MemFree(lpcBuffer);
		return FALSE;
	}

	MemFree(lpcBuffer);


	XML_ParserFree(parser);


	return( TRUE );
}
void RSP_ProcessDList()
{
    VI_UpdateSize();
    OGL_UpdateScale();

    RSP.PC[0] = *(u32*)&DMEM[0x0FF0];
    RSP.PCi = 0;
    RSP.count = 0;

    RSP.halt = FALSE;
    RSP.busy = TRUE;

    gSP.matrix.stackSize = min( 32, *(u32*)&DMEM[0x0FE4] >> 6 );
    gSP.matrix.modelViewi = 0;
    gSP.changed |= CHANGED_MATRIX;

    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            gSP.matrix.modelView[0][i][j] = 0.0f;

    gSP.matrix.modelView[0][0][0] = 1.0f;
    gSP.matrix.modelView[0][1][1] = 1.0f;
    gSP.matrix.modelView[0][2][2] = 1.0f;
    gSP.matrix.modelView[0][3][3] = 1.0f;

    u32 uc_start = *(u32*)&DMEM[0x0FD0];
    u32 uc_dstart = *(u32*)&DMEM[0x0FD8];
    u32 uc_dsize = *(u32*)&DMEM[0x0FDC];

    if ((uc_start != RSP.uc_start) || (uc_dstart != RSP.uc_dstart))
        gSPLoadUcodeEx( uc_start, uc_dstart, uc_dsize );

    gDPSetAlphaCompare( G_AC_NONE );
    gDPSetDepthSource( G_ZS_PIXEL );
    gDPSetRenderMode( 0, 0 );
    gDPSetAlphaDither( G_AD_DISABLE );
    gDPSetColorDither( G_CD_DISABLE );
    gDPSetCombineKey( G_CK_NONE );
    gDPSetTextureConvert( G_TC_FILT );
    gDPSetTextureFilter( G_TF_POINT );
    gDPSetTextureLUT( G_TT_NONE );
    gDPSetTextureLOD( G_TL_TILE );
    gDPSetTextureDetail( G_TD_CLAMP );
    gDPSetTexturePersp( G_TP_PERSP );
    gDPSetCycleType( G_CYC_1CYCLE );
    gDPPipelineMode( G_PM_NPRIMITIVE );

    while (!RSP.halt)
    {
        if ((RSP.PC[RSP.PCi] + 8) > RDRAMSize)
        {
#ifdef DEBUG
            switch (Debug.level)
            {
            case DEBUG_LOW:
                DebugMsg( DEBUG_LOW | DEBUG_ERROR, "ATTEMPTING TO EXECUTE RSP COMMAND AT INVALID RDRAM LOCATION\n" );
                break;
            case DEBUG_MEDIUM:
                DebugMsg( DEBUG_MEDIUM | DEBUG_ERROR, "Attempting to execute RSP command at invalid RDRAM location\n" );
                break;
            case DEBUG_HIGH:
                DebugMsg( DEBUG_HIGH | DEBUG_ERROR, "// Attempting to execute RSP command at invalid RDRAM location\n" );
                break;
            }
#endif
            break;
        }

//		printf( "!!!!!! RDRAM = 0x%8.8x\n", RDRAM );//RSP.PC[RSP.PCi] );
        /*		{
        			static u8 *lastRDRAM = 0;
        			if (lastRDRAM == 0)
        				lastRDRAM = RDRAM;
        			if (RDRAM != lastRDRAM)
        			{
        				__asm__( "int $3" );
        			}
        		}*/
        u32 w0 = *(u32*)&RDRAM[RSP.PC[RSP.PCi]];
        u32 w1 = *(u32*)&RDRAM[RSP.PC[RSP.PCi] + 4];
        RSP.cmd = _SHIFTR( w0, 24, 8 );

#ifdef DEBUG
        DebugRSPState( RSP.PCi, RSP.PC[RSP.PCi], _SHIFTR( w0, 24, 8 ), w0, w1 );
        DebugMsg( DEBUG_LOW | DEBUG_HANDLED, "0x%08lX: CMD=0x%02lX W0=0x%08lX W1=0x%08lX\n", RSP.PC[RSP.PCi], _SHIFTR( w0, 24, 8 ), w0, w1 );
#endif

        RSP.PC[RSP.PCi] += 8;
        RSP.nextCmd = _SHIFTR( *(u32*)&RDRAM[RSP.PC[RSP.PCi]], 24, 8 );

        GBI.cmd[RSP.cmd]( w0, w1 );
    }

    /*	if (OGL.frameBufferTextures && gDP.colorImage.changed)
    	{
    		FrameBuffer_SaveBuffer( gDP.colorImage.address, gDP.colorImage.size, gDP.colorImage.width, gDP.colorImage.height );
    		gDP.colorImage.changed = FALSE;
    	}*/

    RSP.busy = FALSE;
    RSP.DList++;
    gSP.changed |= CHANGED_COLORBUFFER;
}
void RSP_ProcessDList(void)
{
   int i, j;
   u32 uc_start, uc_dstart, uc_dsize;

   __RSP.PC[0] = *(u32*)&gfx_info.DMEM[0x0FF0];
   __RSP.PCi   = 0;
   __RSP.count = -1;

   __RSP.halt  = FALSE;
   __RSP.busy  = TRUE;

   gSP.matrix.stackSize = min( 32, *(u32*)&gfx_info.DMEM[0x0FE4] >> 6 );
   gSP.matrix.modelViewi = 0;
   gSP.changed &= ~CHANGED_CPU_FB_WRITE;
   gSP.changed |= CHANGED_MATRIX;
   gDPSetTexturePersp(G_TP_PERSP);

   for (i = 0; i < 4; i++)
      for (j = 0; j < 4; j++)
         gSP.matrix.modelView[0][i][j] = 0.0f;

   gSP.matrix.modelView[0][0][0] = 1.0f;
   gSP.matrix.modelView[0][1][1] = 1.0f;
   gSP.matrix.modelView[0][2][2] = 1.0f;
   gSP.matrix.modelView[0][3][3] = 1.0f;

   uc_start = *(u32*)&gfx_info.DMEM[0x0FD0];
   uc_dstart = *(u32*)&gfx_info.DMEM[0x0FD8];
   uc_dsize = *(u32*)&gfx_info.DMEM[0x0FDC];

   if ((uc_start != __RSP.uc_start) || (uc_dstart != __RSP.uc_dstart))
      gSPLoadUcodeEx( uc_start, uc_dstart, uc_dsize );

   gDPSetCombineKey(G_CK_NONE);
   gDPSetTextureLUT(G_TT_NONE);
   gDPSetTexturePersp(G_TP_PERSP);
   gDPSetCycleType(G_CYC_1CYCLE);

#ifdef NEW
	depthBufferList().setNotCleared();
#endif

   if (GBI_GetCurrentMicrocodeType() == Turbo3D)
	   RunTurbo3D();
   else
      while (!__RSP.halt)
      {
         u32 w0, w1, pc;
         pc = __RSP.PC[__RSP.PCi];

         if ((pc + 8) > RDRAMSize)
         {
#ifdef DEBUG
            DebugMsg( DEBUG_LOW | DEBUG_ERROR, "ATTEMPTING TO EXECUTE RSP COMMAND AT INVALID RDRAM LOCATION\n" );
#endif
            break;
         }


         w0 = *(u32*)&gfx_info.RDRAM[pc];
         w1 = *(u32*)&gfx_info.RDRAM[pc+4];
         __RSP.cmd = _SHIFTR( w0, 24, 8 );

#ifdef DEBUG
         DebugRSPState( RSP.PCi, RSP.PC[RSP.PCi], _SHIFTR( w0, 24, 8 ), w0, w1 );
         DebugMsg( DEBUG_LOW | DEBUG_HANDLED, "0x%08lX: CMD=0x%02lX W0=0x%08lX W1=0x%08lX\n", RSP.PC[RSP.PCi], _SHIFTR( w0, 24, 8 ), w0, w1 );
#endif

         __RSP.PC[__RSP.PCi] += 8;
         __RSP.nextCmd = _SHIFTR( *(u32*)&gfx_info.RDRAM[pc+8], 24, 8 );

         GBI.cmd[__RSP.cmd]( w0, w1 );
         RSP_CheckDLCounter();
      }

   if (config.frameBufferEmulation.copyToRDRAM)
	   FrameBuffer_CopyToRDRAM( gDP.colorImage.address );
   if (config.frameBufferEmulation.copyDepthToRDRAM)
	   FrameBuffer_CopyDepthBuffer( gDP.colorImage.address );
   __RSP.busy = FALSE;
   gSP.changed |= CHANGED_COLORBUFFER;
}
XBOX::VError VHTTPWebsocketHandler::ReadMessage( void* inData, uLONG* ioLength, bool* outIsTerminated )
{

	bool			l_header_found;
	uLONG			length;
	VError			l_err;

	if (!fEndpt)
	{
		xbox_assert((fEndpt != NULL));
		return VE_INVALID_PARAMETER;
	}

	l_err = VE_OK;

	if (!fBytesToRead)
	{
		l_err = ReadHeader(&l_header_found);
		if (l_err)
		{
			DebugMsg("ERR2\n");
		}
		if (!l_err && !l_header_found)
		{
			*ioLength = 0;
		}

		// not fragmented ?
		if (!l_err && (*ioLength) && (fFrame.header[0] & 0x80))
		{
			fBytesToRead = fFrame.len;
			fCurt = XBOX_LONG8(0);
			switch(fFrame.opcode)
			{
				case CONTINUATION_FRAME:
					DebugMsg("ERR3\n");
					l_err = VE_UNIMPLEMENTED;
					break;
				case CONNEXION_CLOSE:
					if (fFrame.len >= 126)
					{
						DebugMsg("ERR4\n");
						l_err = VE_INVALID_PARAMETER;
					}
					else
					{
						l_err = VE_STREAM_EOF;
					/*// close the socket
					goto NOK;
					while (!l_err && (fBytesToRead > 0))
					{
						length = (uLONG)( *ioLength >=fBytesToRead ? fBytesToRead : *ioLength);
						l_err = ReadBytes(inData,&length);
						if (l_err)
						{
							DebugMsg("ERR 5\n");
						}
						else
						{
							fBytesToRead -= length;
							*ioLength = length;
						}
					}*/
					}
					break;
				case TEXT_FRAME:
				case BIN_FRAME:
					break;
				default:
					break;
			}
		}
		else
		{
			if (!l_err && *(ioLength) )
			{
				DebugMsg("Fragmentation not handled ERR6\n");
			}
		}
	}
	//DebugMsg("ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
	if (!l_err && fBytesToRead)
	{
//printf("...... bef ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
		*ioLength = ( *ioLength >=fBytesToRead ? ((uLONG)fBytesToRead) : *ioLength);
//printf("...... aft ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
		l_err = ReadBytes(inData,ioLength);
		if (l_err)
		{
			DebugMsg("ERR1\n");
		}
		else
		{
			fBytesToRead -= *ioLength;
//printf("...... ....... aft ReadMessage read_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
			if (fFrame.masked)
			{
				for(uLONG l_i=0; l_i<*ioLength; l_i++)
				{
					((unsigned char *)inData)[l_i] ^= fFrame.msk[fCurt % 4];
					fCurt++;
				}
			}

			*outIsTerminated = !(fBytesToRead);
		}
	}
	if (l_err)
	{
		/*fEndpt = NULL;*/
		Close();
	}
	return l_err;

}
XBOX::VError VHTTPWebsocketHandler::WriteMessage( const void* inData, VSize inLength, bool inIsTerminated  )
{
	XBOX::VError	l_err;
	unsigned char	l_header[10];

	l_err = VE_OK;
	if (fOutputIsTerminated)
	{
		fOutputIsTerminated = inIsTerminated;
		if (inIsTerminated)
		{
			l_header[0] = 0x81;
		}
		else
		{
			l_header[0] = 0x01;
		}
	}
	else
	{
		fOutputIsTerminated = inIsTerminated;
		l_header[0] = (inIsTerminated ? 0x80 : 0x00 );
	}

//SEND_COMPLETE_FRAME:
	if (!l_err)
	{
		if (inLength <= 125)
		{
			l_header[1] = (unsigned char)inLength;
			l_err = WriteBytes(l_header,2);
			if (l_err)
			{
				DebugMsg("WriteBytes ERR\n");
			}
		}
		else
		{
			if (inLength < 65536)
			{
				l_header[1] = 126;
				l_header[2] = (uLONG)inLength / 256;
				l_header[3] = (uLONG)inLength % 256;
				l_err = WriteBytes(l_header,4);
				if (l_err)
				{
					DebugMsg("Write3 ERR\n");
				}
			}
			else
			{
				DebugMsg("WriteMessage ERR\n");
				l_err = VE_INVALID_PARAMETER;
			}
		}
//SEND_ALL_DATA:
		if (!l_err)
		{
			l_err = WriteBytes(inData,inLength);
			if (l_err)
			{
				DebugMsg("WriteBytes ERR\n");
			}	
		}
	}
	if (l_err)
	{
		/*fEndpt = NULL;*/
		Close();
	}

	return l_err;

}
VOID
TestUtilityMessages (
  VOID
  )
{
  CHAR8 *ArgStr = "ArgString";
  int   ArgInt;

  ArgInt  = 0x12345678;
  //
  // Test without setting utility name
  //
  fprintf (stdout, "* Testing without setting utility name\n");
  fprintf (stdout, "** Test debug message not printed\n");
  DebugMsg (NULL, 0, 0x00000001, NULL, NULL);
  fprintf (stdout, "** Test warning with two strings and two args\n");
  Warning (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
  fprintf (stdout, "** Test error with two strings and two args\n");
  Warning (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
  fprintf (stdout, "** Test parser warning with nothing\n");
  ParserWarning (0, NULL, NULL);
  fprintf (stdout, "** Test parser error with nothing\n");
  ParserError (0, NULL, NULL);
  //
  // Test with utility name set now
  //
  fprintf (stdout, "** Testingin with utility name set\n");
  SetUtilityName ("MyUtilityName");
  //
  // Test debug prints
  //
  SetDebugMsgMask (2);
  fprintf (stdout, "** Test debug message with one string\n");
  DebugMsg (NULL, 0, 0x00000002, "Text1", NULL);
  fprintf (stdout, "** Test debug message with one string\n");
  DebugMsg (NULL, 0, 0x00000002, NULL, "Text2");
  fprintf (stdout, "** Test debug message with two strings\n");
  DebugMsg (NULL, 0, 0x00000002, "Text1", "Text2");
  fprintf (stdout, "** Test debug message with two strings and two args\n");
  DebugMsg (NULL, 0, 0x00000002, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
  //
  // Test warning prints
  //
  fprintf (stdout, "** Test warning with no strings\n");
  Warning (NULL, 0, 1234, NULL, NULL);
  fprintf (stdout, "** Test warning with one string\n");
  Warning (NULL, 0, 1234, "Text1", NULL);
  fprintf (stdout, "** Test warning with one string\n");
  Warning (NULL, 0, 1234, NULL, "Text2");
  fprintf (stdout, "** Test warning with two strings and two args\n");
  Warning (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
  //
  // Test error prints
  //
  fprintf (stdout, "** Test error with no strings\n");
  Error (NULL, 0, 1234, NULL, NULL);
  fprintf (stdout, "** Test error with one string\n");
  Error (NULL, 0, 1234, "Text1", NULL);
  fprintf (stdout, "** Test error with one string\n");
  Error (NULL, 0, 1234, NULL, "Text2");
  fprintf (stdout, "** Test error with two strings and two args\n");
  Error (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
  //
  // Test parser prints
  //
  fprintf (stdout, "** Test parser errors\n");
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserError (1234, NULL, NULL);
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserError (1234, "Text1", NULL);
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserError (1234, NULL, "Text2");
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserError (1234, "Text1", "Text2");
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserError (1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);

  fprintf (stdout, "** Test parser warnings\n");
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserWarning (4321, NULL, NULL);
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserWarning (4321, "Text1", NULL);
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserWarning (4321, NULL, "Text2");
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserWarning (4321, "Text1", "Text2");
  ParserSetPosition (__FILE__, __LINE__ + 1);
  ParserWarning (4321, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
}
XBOX::VError VHTTPWebsocketHandler::ReadHeader(bool* found)
{
	VError			l_err;

	memset(&fFrame,0,sizeof(ws_frame_t));
	*found = false;
	fFrame.buf_len = 2;
//printf("ReadHeader called\n");

	l_err = ReadBytes((void *)fFrame.header, &fFrame.buf_len);
	if (!l_err && fFrame.buf_len)
	{
		// extensions not handled
		if (fFrame.header[0] & 0x70)
		{
			DebugMsg("VHTTPWebsocketHandler::ReadHeader RFC6455 EXTENSIONS NOT HANDLED!!!!\n");
			l_err = VE_INVALID_PARAMETER;
		}
		if (!l_err)
		{
			fFrame.opcode = (ws_opcode_t)(fFrame.header[0] & 0x0F);
		
			fFrame.masked = (fFrame.header[1] & 0x80);
			fFrame.len = (sLONG8)(fFrame.header[1] & 0x7F);
			if (fFrame.len == 127)
			{
				fFrame.buf_len = 8;
				l_err = ReadBytes((void *)(fFrame.header+2), &fFrame.buf_len);
				if ( !l_err && (fFrame.buf_len != 8) )
				{
					l_err = VE_STREAM_CANNOT_READ;
				}
				if (!l_err)
				{
					fFrame.len = 0;
					for(int l_i=0;l_i<8;l_i+=2)
					{
						fFrame.len = 65536*fFrame.len + (256*fFrame.header[2+l_i]+fFrame.header[3+l_i]);
					}
					DebugMsg("ReadHeader frame.len=%lld\n",fFrame.len);
				}
			}
			else
			{
				if (fFrame.len == 126)
				{
					fFrame.buf_len = 2;
					l_err = ReadBytes((void *)(fFrame.header+2), &fFrame.buf_len);
					if ( !l_err && (fFrame.buf_len != 2) )
					{
						l_err = VE_STREAM_CANNOT_READ;
					}
					if (!l_err)
					{
						fFrame.len = 256*fFrame.header[2]+fFrame.header[3];
						DebugMsg("ReadHeader frame.len=%d\n",fFrame.len);
					}
				}
				else
				{
					DebugMsg("ReadHeader frame.len=%d\n",fFrame.len);
				}
			}
			if (!l_err && fFrame.masked)
			{
				fFrame.buf_len = 4;
				l_err = ReadBytes((void *)fFrame.msk, &fFrame.buf_len);
				if ( !l_err && (fFrame.buf_len != 4) )
				{
					l_err = VE_STREAM_CANNOT_READ;
				}
			}
			*found = true;
		}
	}
	return l_err;
}
Exemple #12
0
int main( int argc, char **argv )
/*******************************/
{
    char    *pEnv;
    int     numArgs = 0;
    int     numFiles = 0;
    int     rc = 0;
#if WILDCARDS
    long    fh; /* _findfirst/next/close() handle, must be long! */
    struct  _finddata_t finfo;
    char    drv[_MAX_DRIVE];
    char    dir[_MAX_DIR];
    char    fname[_MAX_PATH];
#endif

#if 0 //def DEBUG_OUT    /* DebugMsg() cannot be used that early */
    int i;
    for ( i = 1; i < argc; i++ ) {
        printf("argv[%u]=>%s<\n", i, argv[i] );
    }
#endif

    pEnv = getenv( "JWASM" );
    if ( pEnv == NULL )
        pEnv = "";
    argv[0] = pEnv;

#ifndef DEBUG_OUT
    signal(SIGSEGV, genfailure);
#endif

#if CATCHBREAK
    signal(SIGBREAK, genfailure);
#else
    signal(SIGTERM, genfailure);
#endif

    MsgInit();

    while ( 1 ) {
        if ( ParseCmdline( (const char **)argv, &numArgs ) == NULL )
            break;  /* exit if no source file name supplied */
        numFiles++;
        write_logo();
#if WILDCARDS
        if ((fh = _findfirst( Options.names[ASM], &finfo )) == -1 ) {
            DebugMsg(("main: _findfirst(%s) failed\n", Options.names[ASM] ));
            EmitErr( CANNOT_OPEN_FILE, Options.names[ASM], ErrnoStr() );
            break;
        }
        _splitpath( Options.names[ASM], drv, dir, NULL, NULL );
        DebugMsg(("main: _splitpath(%s): drv=\"%s\" dir=\"%s\"\n", Options.names[ASM], drv, dir ));
        do {
            _makepath( fname, drv, dir, finfo.name, NULL );
            DebugMsg(("main: _makepath(\"%s\", \"%s\", \"%s\")=\"%s\"\n", drv, dir, finfo.name, fname ));
            rc = AssembleModule( fname );  /* assemble 1 module */
        } while ( ( _findnext( fh, &finfo ) != -1 ) );
        _findclose( fh );
#else
        rc = AssembleModule( Options.names[ASM] );
#endif
    };
    CmdlineFini();
    if ( numArgs == 0 ) {
        write_logo();
        printf( MsgGetEx( MSG_USAGE ) );
    } else if ( numFiles == 0 )
        EmitError( NO_FILENAME_SPECIFIED );

    MsgFini();
    return( 1 - rc ); /* zero if no errors */
}
Exemple #13
0
//Simply create videosurface, load image, and draw it to the screen.
void InitJA2SplashScreen()
{
	UINT32 uiLogoID = 0;
	STRING512			CurrentDir;
	STRING512			DataDir;
	HVSURFACE hVSurface;
	VSURFACE_DESC VSurfaceDesc;
	INT32 i = 0;

	InitializeJA2Clock();
	//InitializeJA2TimerID();
	// Get Executable Directory
	GetExecutableDirectory( CurrentDir );

	// Adjust Current Dir
	sprintf( DataDir, "%s\\Data", CurrentDir );
	if ( !SetFileManCurrentDirectory( DataDir ) )
	{
		DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Could not find data directory, shutting down");
		return;
	}

	//Initialize the file database
	InitializeFileDatabase( gGameLibaries, NUMBER_OF_LIBRARIES );

#if !defined( ENGLISH ) && defined( JA2TESTVERSION )
	memset( &VSurfaceDesc, 0, sizeof( VSURFACE_DESC ) );
	VSurfaceDesc.fCreateFlags = VSURFACE_CREATE_FROMFILE | VSURFACE_SYSTEM_MEM_USAGE;
	sprintf( VSurfaceDesc.ImageFile, "LOADSCREENS\\Notification.sti" );
	if( !AddVideoSurface( &VSurfaceDesc, &uiLogoID ) )
	{	
		AssertMsg( 0, String( "Failed to load %s", VSurfaceDesc.ImageFile ) );
		return;
	}
	GetVideoSurface(&hVSurface, uiLogoID );
			BltVideoSurfaceToVideoSurface( ghFrameBuffer, hVSurface, 0, 0, 0, 0, NULL );
	DeleteVideoSurfaceFromIndex( uiLogoID );


	InvalidateScreen();
	RefreshScreen( NULL );

	guiSplashStartTime = GetJA2Clock();
	while( i < 60 * 15 )//guiSplashStartTime + 15000 > GetJA2Clock() )
	{
		//Allow the user to pick his bum.
		InvalidateScreen();
		RefreshScreen( NULL );
		i++;
	}
#endif
	
	#ifdef ENGLISH
		ClearMainMenu();
	#else
		{

			memset( &VSurfaceDesc, 0, sizeof( VSURFACE_DESC ) );
			VSurfaceDesc.fCreateFlags = VSURFACE_CREATE_FROMFILE | VSURFACE_SYSTEM_MEM_USAGE;
			GetMLGFilename( VSurfaceDesc.ImageFile, MLG_SPLASH );
			if( !AddVideoSurface( &VSurfaceDesc, &uiLogoID ) )
			{	
				AssertMsg( 0, String( "Failed to load %s", VSurfaceDesc.ImageFile ) );
				return;
			}

			GetVideoSurface( &hVSurface, uiLogoID );
			BltVideoSurfaceToVideoSurface( ghFrameBuffer, hVSurface, 0, 0, 0, 0, NULL );
			DeleteVideoSurfaceFromIndex( uiLogoID );
		}
	#endif


	InvalidateScreen();
	RefreshScreen( NULL );

	guiSplashStartTime = GetJA2Clock();
}
/////////////////////////////////////////////////////////////////////////////
// IsFileTrusted
//
itvEnum IsFileTrusted(LPCWSTR lpwFile, HWND hwndParent, DWORD dwUIChoice, bool *pfIsSigned, PCCERT_CONTEXT *ppcSigner)
{
    char szDebugOutput[MAX_STR_LENGTH] = {0};

    itvEnum itv = itvUnTrusted;

    if (pfIsSigned)
        *pfIsSigned = false;
    if (ppcSigner)
        *ppcSigner  = 0;

    GUID guidAction = WINTRUST_ACTION_GENERIC_VERIFY_V2;

    WINTRUST_FILE_INFO sWintrustFileInfo;
    WINTRUST_DATA      sWintrustData;
    HRESULT            hr;

    memset((void*)&sWintrustFileInfo, 0x00, sizeof(WINTRUST_FILE_INFO)); // zero out
    memset((void*)&sWintrustData, 0x00, sizeof(WINTRUST_DATA)); // zero out

    sWintrustFileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
    sWintrustFileInfo.pcwszFilePath = lpwFile;
    sWintrustFileInfo.hFile = NULL;

    sWintrustData.cbStruct            = sizeof(WINTRUST_DATA);
    sWintrustData.dwUIChoice          = dwUIChoice;
    sWintrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
    sWintrustData.dwUnionChoice       = WTD_CHOICE_FILE;
    sWintrustData.pFile               = &sWintrustFileInfo;
    sWintrustData.dwStateAction       = (ppcSigner) ? WTD_STATEACTION_VERIFY : 0;

    HMODULE hWinTrust = LoadLibrary(WINTRUST_DLL);
    if (!hWinTrust)
    {
        // WinTrust is unavailable on the machine
        return itvWintrustNotOnMachine;
    }
    PFnWinVerifyTrust pfnWinVerifyTrust = (PFnWinVerifyTrust)GetProcAddress(hWinTrust, WINTRUSTAPI_WinVerifyTrust);
    PFnWTHelperProvDataFromStateData pfnWTHelperProvDataFromStateData= (PFnWTHelperProvDataFromStateData)GetProcAddress(hWinTrust, WINTRUSTAPI_WTHelperProvDataFromStateData);
    PFnWTHelperGetProvSignerFromChain pfnWTHelperGetProvSignerFromChain = (PFnWTHelperGetProvSignerFromChain)GetProcAddress(hWinTrust, WINTRUSTAPI_WTHelperGetProvSignerFromChain);
    PFnWTHelperGetProvCertFromChain pfnWTHelperGetProvCertFromChain = (PFnWTHelperGetProvCertFromChain)GetProcAddress(hWinTrust, WINTRUSTAPI_WTHelperGetProvCertFromChain);
    if (!pfnWinVerifyTrust || !pfnWTHelperProvDataFromStateData || !pfnWTHelperGetProvSignerFromChain || !pfnWTHelperGetProvCertFromChain)
    {
        // WinTrust is unavailable on the machine
        FreeLibrary(hWinTrust);
        return itvWintrustNotOnMachine;
    }

    hr = pfnWinVerifyTrust(/* UI Window Handle */ (dwUIChoice == WTD_UI_NONE) ? (HWND)INVALID_HANDLE_VALUE : hwndParent, &guidAction, &sWintrustData);
    DebugMsg("[WVT] WVT returned 0x%X\n", hr);

    itv = (TRUST_E_PROVIDER_UNKNOWN == hr) ? itvWintrustNotOnMachine : ((S_OK == hr) ? itvTrusted : itvUnTrusted); 

    if (itvWintrustNotOnMachine == itv)
    {
        // release state data
        sWintrustData.dwUIChoice = WTD_UI_NONE;
        sWintrustData.dwStateAction = WTD_STATEACTION_CLOSE;
        pfnWinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &guidAction, &sWintrustData);

        FreeLibrary(hWinTrust);
        return itv; // return immediately
    }

    if (pfIsSigned)
        *pfIsSigned = (TRUST_E_NOSIGNATURE == hr) ? false : true;

    if (TRUST_E_NOSIGNATURE == hr)
    {
        // release state data
        sWintrustData.dwUIChoice = WTD_UI_NONE;
        sWintrustData.dwStateAction = WTD_STATEACTION_CLOSE;
        pfnWinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &guidAction, &sWintrustData);

        FreeLibrary(hWinTrust);
        return itv;
    }

    if (ppcSigner)
    {
        CRYPT_PROVIDER_DATA const *psProvData     = NULL;
        CRYPT_PROVIDER_SGNR       *psProvSigner   = NULL;
        CRYPT_PROVIDER_CERT       *psProvCert     = NULL;

        // grab the provider data
        psProvData = pfnWTHelperProvDataFromStateData(sWintrustData.hWVTStateData);
        if (psProvData)
        {
            // grab the signer data from the CRYPT_PROV_DATA
            psProvSigner = pfnWTHelperGetProvSignerFromChain((PCRYPT_PROVIDER_DATA)psProvData, 0 /*first signer*/, FALSE /* not a counter signer */, 0);
            if (psProvSigner)
            {
                // grab the signer cert from CRYPT_PROV_SGNR (pos 0 = signer cert; pos csCertChain-1 = root cert)
                psProvCert = pfnWTHelperGetProvCertFromChain(psProvSigner, 0);
            }
        }
    
        if (!psProvCert)
        {
            // some failure in obtaining the signer cert data
            *ppcSigner = 0;
        }
        else
        {
            // duplicate the cert
            HMODULE hCrypt32 = LoadLibrary(CRYPT32_DLL);
            if (hCrypt32)
            {
                PFnCertDuplicateCertificateContext pfnCertDuplicateCertificateContext = (PFnCertDuplicateCertificateContext)GetProcAddress(hCrypt32, CRYPTOAPI_CertDuplicateCertificateContext);
                if (pfnCertDuplicateCertificateContext)
                    *ppcSigner = pfnCertDuplicateCertificateContext(psProvCert->pCert);
                FreeLibrary(hCrypt32);
            }
        }

        // release state data
        sWintrustData.dwUIChoice = WTD_UI_NONE;
        sWintrustData.dwStateAction = WTD_STATEACTION_CLOSE;
        pfnWinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &guidAction, &sWintrustData);
    }

    FreeLibrary(hWinTrust);
    return itv;
}
Exemple #15
0
LPMALLOC SHGetTaskAllocator(HRESULT *phres)
{
    HRESULT hres = NOERROR;

    //
    // Check if the task allocator is already initialized or not.
    //
    if (g_pmemTask == NULL)
    {
        //
        //  Check if OLE32 is loaded in this process or not.
        //
        HMODULE hmod = GetModuleHandle(c_szOLE32);
#ifdef DONTUSE_TASKALLOCATOR
        // We don't use OLE's task allocator if this is a low-memory machine
        // AND OLE32.DLL is retail.
        //
        // WARNING:
        //   We don't use OLE's task allocator unless OLE32.DLL is a debug
        //  version. To find it out, we call GetProcAddress of DumpMEMSTM.
        //  Note that retail version of OLE just allocate memory from
        //  the default process heap (which LocalAlloc uses).
        //
        BOOL fSlow = (GetSystemMetrics(SM_SLOWMACHINE) & 0x0002);
        if (hmod && !(fSlow && !_IsDebugOLE(hmod)))
#else
#ifdef DEBUG
        if (TRUE)
#else
        if (hmod)
#endif
#endif // DONTUSE_TASKALLOCATOR
        {
            //
            // Yes, get the task allocator from OLE.
            //
            LPFNCOGETMALLOC pfnGetMalloc;

            //
            // Bump the reference count of OLE32.DLL
            //  Notes:
            //   We don't know when we can safely call _UnloadOLE, but
            //   that's ok -- it will just stay in this process until
            //   the process terminate.
            //
            STDAPI _LoadOLE(BOOL fRegisterTargets);     // BUGBUG - BobDay - Move this into a headerfile

#ifndef WINNT

            _LoadOLE(FALSE);

#else

            //
            // On NT, if we're going to go about loading OLE we might as well
            // hand off drop targets, etc, right now. 
            //
            // BUGBUG If _LoadOLE(FALSE) is ever called before _LoadOLE(TRUE)
            // (as would be case if SHGetTaskAllocator() was called before a
            // view was openend), Ole will never be initialized.  So, we call
            // with TRUE here in case that happens.

            _LoadOLE(TRUE);

#endif

#ifdef DEBUG
            hmod = GetModuleHandle(c_szOLE32);
#endif

            pfnGetMalloc=(LPFNCOGETMALLOC)GetProcAddress(hmod, c_szCoGetMalloc);
            if (pfnGetMalloc)
            {
                hres=pfnGetMalloc(MEMCTX_TASK, &g_pmemTask);
                if (FAILED(hres))
                {
                    //
                    //  CoGetMalloc failed. It means (typically) a shell
                    // extension called SHAlloc from within LibMain before
                    // the main app calls OleInitialize().
                    //
                    DebugMsg(DM_WARNING, TEXT("sh WR - CoGetMalloc failed (%x)"), hres);
                    Assert(g_pmemTask==NULL);
                }
            }
            else
            {
                hres = ResultFromScode(E_UNEXPECTED);
            }
        }
        else
        {
            //
            // No, use the shell task allocator (which is LocalAlloc).
            //
            g_pmemTask = &c_mem;
        }
    }

    if (phres) {
        *phres = hres;
    }

    return g_pmemTask;
}
VOID
CVfrCompiler::OptionInitialization (
  IN INT32      Argc, 
  IN CHAR8      **Argv
  )
{
  INT32         Index;
  EFI_STATUS    Status;

  Status = EFI_SUCCESS;
  SetUtilityName ((CHAR8*) PROGRAM_NAME);

  mOptions.VfrFileName[0]                = '\0';
  mOptions.RecordListFile[0]             = '\0';
  mOptions.CreateRecordListFile          = FALSE;
  mOptions.CreateIfrPkgFile              = FALSE;
  mOptions.PkgOutputFileName[0]          = '\0';
  mOptions.COutputFileName[0]            = '\0';
  mOptions.OutputDirectory[0]            = '\0';
  mOptions.PreprocessorOutputFileName[0] = '\0';
  mOptions.VfrBaseFileName[0]            = '\0';
  mOptions.IncludePaths                  = NULL;
  mOptions.SkipCPreprocessor             = TRUE;
  mOptions.CPreprocessorOptions          = NULL;
  mOptions.CompatibleMode                = FALSE;
  mOptions.HasOverrideClassGuid          = FALSE;
  mOptions.WarningAsError                = FALSE;
  memset (&mOptions.OverrideClassGuid, 0, sizeof (EFI_GUID));
  
  if (Argc == 1) {
    Usage ();
    SET_RUN_STATUS (STATUS_DEAD);
    return;
  }

  for (Index = 1; (Index < Argc) && (Argv[Index][0] == '-'); Index++) {
    if ((stricmp(Argv[Index], "-h") == 0) || (stricmp(Argv[Index], "--help") == 0)) {
      Usage ();
      SET_RUN_STATUS (STATUS_DEAD);
      return;
    } else if (stricmp(Argv[Index], "--version") == 0) {
      Version ();
      SET_RUN_STATUS (STATUS_DEAD);
      return;
    } else if (stricmp(Argv[Index], "-l") == 0) {
      mOptions.CreateRecordListFile = TRUE;
      gCIfrRecordInfoDB.TurnOn ();
    } else if (stricmp(Argv[Index], "-i") == 0) {
      Index++;
      if ((Index >= Argc) || (Argv[Index][0] == '-')) {
        DebugError (NULL, 0, 1001, "Missing option", "-i missing path argument"); 
        goto Fail;
      }

      AppendIncludePath(Argv[Index]);
    } else if (stricmp(Argv[Index], "-o") == 0 || stricmp(Argv[Index], "--output-directory") == 0 || stricmp(Argv[Index], "-od") == 0) {
      Index++;
      if ((Index >= Argc) || (Argv[Index][0] == '-')) {
        DebugError (NULL, 0, 1001, "Missing option", "-o missing output directory name");
        goto Fail;
      }
      strcpy (mOptions.OutputDirectory, Argv[Index]);
      
      CHAR8 lastChar = mOptions.OutputDirectory[strlen(mOptions.OutputDirectory) - 1];
      if ((lastChar != '/') && (lastChar != '\\')) {
        if (strchr(mOptions.OutputDirectory, '/') != NULL) {
          strcat (mOptions.OutputDirectory, "/");
        } else {
          strcat (mOptions.OutputDirectory, "\\");
        }
      }
      DebugMsg (NULL, 0, 9, (CHAR8 *) "Output Directory", mOptions.OutputDirectory);
    } else if (stricmp(Argv[Index], "-b") == 0 || stricmp(Argv[Index], "--create-ifr-package") == 0 || stricmp(Argv[Index], "-ibin") == 0) {
      mOptions.CreateIfrPkgFile = TRUE;
    } else if (stricmp(Argv[Index], "-n") == 0 || stricmp(Argv[Index], "--no-pre-processing") == 0 || stricmp(Argv[Index], "-nopp") == 0) {
      mOptions.SkipCPreprocessor = TRUE;
    } else if (stricmp(Argv[Index], "-f") == 0 || stricmp(Argv[Index], "--pre-processing-flag") == 0 || stricmp(Argv[Index], "-ppflag") == 0) {
      Index++;
      if ((Index >= Argc) || (Argv[Index][0] == '-')) {
        DebugError (NULL, 0, 1001, "Missing option", "-od - missing C-preprocessor argument");
        goto Fail;
      }

      AppendCPreprocessorOptions (Argv[Index]);
    } else if (stricmp(Argv[Index], "-c") == 0 || stricmp(Argv[Index], "--compatible-framework") == 0) {
      mOptions.CompatibleMode = TRUE;
    } else if (stricmp(Argv[Index], "-s") == 0|| stricmp(Argv[Index], "--string-db") == 0) {
      Index++;
      if ((Index >= Argc) || (Argv[Index][0] == '-')) {
        DebugError (NULL, 0, 1001, "Missing option", "-s missing input string file name");
        goto Fail;
      }
      gCVfrStringDB.SetStringFileName(Argv[Index]);
      DebugMsg (NULL, 0, 9, (CHAR8 *) "Input string file path", Argv[Index]);
    } else if ((stricmp (Argv[Index], "-g") == 0) || (stricmp (Argv[Index], "--guid") == 0)) {
      Index++;
      Status = StringToGuid (Argv[Index], &mOptions.OverrideClassGuid);
      if (EFI_ERROR (Status)) {
        DebugError (NULL, 0, 1000, "Invalid format:", "%s", Argv[Index]);
        goto Fail;
      }
      mOptions.HasOverrideClassGuid = TRUE;
    } else if (stricmp(Argv[Index], "-w") == 0 || stricmp(Argv[Index], "--warning-as-error") == 0) {
      mOptions.WarningAsError = TRUE;
    } else {
      DebugError (NULL, 0, 1000, "Unknown option", "unrecognized option %s", Argv[Index]);
      goto Fail;
    }
  }

  if (Index != Argc - 1) {
    DebugError (NULL, 0, 1001, "Missing option", "VFR file name is not specified.");
    goto Fail;
  } else {
    strcpy (mOptions.VfrFileName, Argv[Index]);
  }

  if (SetBaseFileName() != 0) {
    goto Fail;
  }
  if (SetPkgOutputFileName () != 0) {
    goto Fail;
  }
  if (SetCOutputFileName() != 0) {
    goto Fail;
  }
  if (SetPreprocessorOutputFileName () != 0) {
    goto Fail;
  }
  if (SetRecordListFileName () != 0) {
    goto Fail;
  }
  return;

Fail:
  SET_RUN_STATUS (STATUS_DEAD);

  mOptions.VfrFileName[0]                = '\0';
  mOptions.RecordListFile[0]             = '\0';
  mOptions.CreateRecordListFile          = FALSE;
  mOptions.CreateIfrPkgFile              = FALSE;
  mOptions.PkgOutputFileName[0]          = '\0';
  mOptions.COutputFileName[0]            = '\0';
  mOptions.OutputDirectory[0]            = '\0';
  mOptions.PreprocessorOutputFileName[0] = '\0';
  mOptions.VfrBaseFileName[0]            = '\0';
  if (mOptions.IncludePaths != NULL) {
    delete mOptions.IncludePaths;
    mOptions.IncludePaths                = NULL;
  } 
  if (mOptions.CPreprocessorOptions != NULL) {
    delete mOptions.CPreprocessorOptions;
    mOptions.CPreprocessorOptions        = NULL;
  }
}
Exemple #17
0
static void CalcOffset( struct dsym *curr, bool firstseg )
/********************************************************/
{
    uint_32 align;
    uint_32 alignbytes;
    uint_32 offset;
    struct dsym *grp;

    if ( curr->e.seginfo->segtype == SEGTYPE_ABS ) {
        curr->e.seginfo->start_offset = curr->e.seginfo->abs_frame << 4;
        DebugMsg(("CalcOffset(%s): abs seg, offset=%" FX32 "h\n",
                  curr->sym.name, curr->e.seginfo->start_offset ));
        return;
    }

    grp = (struct dsym *)curr->e.seginfo->group;
    align = 1 << curr->e.seginfo->alignment;
    //alignbytes = ((offset + (align - 1)) & (-align)) - offset;
    alignbytes = ((fileoffset + (align - 1)) & (-align)) - fileoffset;
    fileoffset += alignbytes;

    if ( grp == NULL ) {
        offset = fileoffset - sizehdr; // + alignbytes;
        DebugMsg(("CalcOffset(%s): fileofs=%" FX32 "h, ofs=%" FX32 "h\n", curr->sym.name, fileoffset, offset ));
    } else {
        if ( grp->sym.total_size == 0 ) {
            grp->sym.offset = fileoffset - sizehdr;
            offset = 0;
        } else
            offset = grp->sym.total_size + alignbytes;
        DebugMsg(("CalcOffset(%s): fileofs=%" FX32 "h, alignbytes=%lu, ofs=%" FX32 "h, group=%s, grp.ofs=%" FX32 "h\n",
                  curr->sym.name, fileoffset, alignbytes, offset, grp->sym.name, grp->sym.offset ));
    }

    /* v2.04: added */
    /* v2.05: this addition did mess sample Win32_5.asm, because the
     * "empty" alignment sections are now added to <fileoffset>.
     * todo: VA in binary map is displayed wrong.
     */
    if ( firstseg == FALSE ) {
        /* v2.05: do the reset more carefully.
         * Do reset start_loc only if
         * - segment is in a group and
         * - group isn't FLAT or segment's name contains '$'
         */
        if ( grp && ( grp != ModuleInfo.flat_grp ||
                     strchr( curr->sym.name, '$' ) ) )
            curr->e.seginfo->start_loc = 0;
    }

    curr->e.seginfo->fileoffset = fileoffset;
    //if ( firstseg && ModuleInfo.header_format == HFORMAT_NONE ) {
    if ( ModuleInfo.header_format == HFORMAT_NONE ) {
        fileoffset += curr->sym.max_offset - curr->e.seginfo->start_loc;
        if ( firstseg )
            imagestart = curr->e.seginfo->start_loc;
    } else {
        /* v2.05: changed, removed */
        //curr->e.seginfo->fileoffset += curr->e.seginfo->start_loc;
        //fileoffset += curr->sym.max_offset;
        fileoffset += curr->sym.max_offset - curr->e.seginfo->start_loc;
    }

    curr->e.seginfo->start_offset = offset;

    /* there's no real entry address for BIN, therefore the
     start label must be at the very beginning of the file */
    if (entryoffset == -1) {
        entryoffset = offset;
        entryseg = (struct asym *)curr;
    }
    //offset += curr->sym.max_offset - curr->e.seginfo->start_loc;
    offset += curr->sym.max_offset;
    if ( grp ) {
        //grp->sym.total_size = offset + curr->e.seginfo->start_loc;
        grp->sym.total_size = offset;
        /* v2.07: for 16-bit groups, ensure that it fits in 64 kB */
        if ( grp->sym.total_size > 0x10000 && grp->sym.Ofssize == USE16 ) {
            EmitWarn( 2, GROUP_EXCEEDS_64K, grp->sym.name );
        }
    }
    DebugMsg(("CalcOffset(%s) exit: seg.fileofs=%" FX32 "h, seg.start_offset=%" FX32 "h, endofs=%" FX32 "h fileoffset=%" FX32 "h\n",
              curr->sym.name, curr->e.seginfo->fileoffset, curr->e.seginfo->start_offset, offset, fileoffset ));

    return;
}
VOID
CVfrCompiler::AdjustBin (
  VOID
  )
{
  EFI_VFR_RETURN_CODE Status;

  if (!IS_RUN_STATUS(STATUS_COMPILEED)) {
    return;
  }

  UpdateInfoForDynamicOpcode ();

  //
  // Check Binary Code consistent between Form and IfrRecord
  //

  //
  // Get Package Data and IfrRecord Data
  //
  gCFormPkg.BuildPkg (gCBuffer);
  gCIfrRecordInfoDB.IfrRecordOutput (gRBuffer); 

  //
  // Compare Form and Record data
  //
  if (gCBuffer.Buffer != NULL && gRBuffer.Buffer != NULL) {
    UINT32 Index;
    if (gCBuffer.Size != gRBuffer.Size) {
      DebugError (NULL, 0, 0001, "Error parsing vfr file", " %s. FormBinary Size 0x%X is not same to RecordBuffer Size 0x%X", mOptions.VfrFileName, gCBuffer.Size, gRBuffer.Size);
    }
    for (Index = 0; Index < gCBuffer.Size; Index ++) {
      if (gCBuffer.Buffer[Index] != gRBuffer.Buffer[Index]) {
        break;
      }
    }
    if (Index != gCBuffer.Size) {
      DebugError (NULL, 0, 0001, "Error parsing vfr file", " %s. the 0x%X byte is different between Form and Record", mOptions.VfrFileName, Index);
    }
    DebugMsg (NULL, 0, 9, (CHAR8 *) "IFR Buffer", (CHAR8 *) "Form Buffer same to Record Buffer and Size is 0x%X", Index);
  } else if (gCBuffer.Buffer == NULL && gRBuffer.Buffer == NULL) {
    //ok
  } else {
    DebugError (NULL, 0, 0001, "Error parsing vfr file", " %s.Buffer not allocated.", mOptions.VfrFileName);
  }

  //
  // For UEFI mode, not do OpCode Adjust
  //
  if (mOptions.CompatibleMode) {
    //
    // Adjust Opcode to be compatible with framework vfr
    //
    Status = gCIfrRecordInfoDB.IfrRecordAdjust ();
    if (Status != VFR_RETURN_SUCCESS) {
      //
      // Record List Adjust Failed
      //
      SET_RUN_STATUS (STATUS_FAILED);
      return;
    }
    //
    // Re get the IfrRecord Buffer.
    //
    gCIfrRecordInfoDB.IfrRecordOutput (gRBuffer); 
  }

  return;
}
Exemple #19
0
// Replaces the gui_main_task
static void
my_gui_main_task( void )
{
	gui_init_end();
	uint32_t * obj = 0;

	while(1)
	{
		struct event * event;
		msg_queue_receive(
			gui_main_struct.msg_queue,
			&event,
			0
		);

		if( !event )
			goto event_loop_bottom;

		if (!magic_is_off() && event->type == 0)
		{
			if (handle_buttons(event) == 0) // ML button/event handler
				goto event_loop_bottom;
		}

        if (IS_FAKE(event)) {
           event->arg = 0;      /* do not pass the "fake" flag to Canon code */
        }

        if (event->type == 0 && event->param < 0) {
            goto event_loop_bottom;           /* do not pass internal ML events to Canon code */
        }

		switch( event->type )
		{
		case 0:
			if( gui_main_struct.obj != obj
			   &&  event->param != 0x29
			   &&  event->param != 0x2A
			   &&  event->param != 0x2B
			   &&  event->param != 0x2C
			   &&  event->param != 0x2D
			   &&  event->param != 0x2E
			   &&  event->param != 0x23
			   &&  event->param != 0x2F
			   &&  event->param != 0x27
			   &&  event->param != 0x30
			   &&  event->param != 0x31
			   &&  event->param != 0x32
			   &&  event->param != 0x33
			   &&  event->param != 0x34
			   &&  event->param != 0x35
			   &&  event->param != 0x36
			   &&  event->param != 0x3F
			)
				goto queue_clear;

			DebugMsg( DM_MAGIC, 2, "GUI_CONTROL:%d", event->param );
			gui_massive_event_loop( event->param, event->obj, event->arg );
			break;

		case 1:
			if( gui_main_struct.obj != obj
			&&  event->param != 0x00
			&&  event->param != 0x07
			&&  event->param != 0x05
			)
				goto queue_clear;

			DebugMsg( 0x84, 2, "GUI_CHANGE_MODE:%d", event->param );

			if( event->param == 0 )
			{
				gui_local_post( 0x12, 0, 0 );
				if( gui_timer_struct.obj )
					gui_timer_something( gui_timer_struct.obj, 4 );
			}

			gui_change_mode( event->param );
			break;

		case 2:
			if( gui_main_struct.obj != obj
			   &&  event->param != 0x17
			   &&  event->param != 0x18
			   &&  event->param != 0x14
			   &&  event->param != 0x1B
			   &&  event->param != 0x32
			   &&  event->param != 0x33
			)
				goto queue_clear;

			gui_local_post( event->param, event->obj, event->arg );
			break;
		case 3:
			if( event->param == 0x11 )
			{
				DebugMsg( 0x84, 2, "GUIOTHER_CANCEL_ALL_EVENT" );
				obj = event->obj;
				break;
			}

			if( gui_main_struct.obj != obj
			   &&  event->param != 0x00
			   &&  event->param != 0x03
			   &&  event->param != 0x01
			   &&  event->param != 0x12
			   &&  event->param != 0x13
			   &&  event->param != 0x14
			   &&  event->param != 0x15
			)
				goto queue_clear;

			DebugMsg( 0x84, 2, "GUI_OTHEREVENT:%d", event->param );
			gui_other_post( event->param, event->obj, event->arg );
			break;
		case 4:
			gui_post_10000085( event->param, event->obj, event->arg );
			break;
		case 5:
			gui_init_event( event->obj );
			break;
		case 6:
			DebugMsg( 0x84, 2, "GUI_CHANGE_SHOOT_TYPE:%d", event->param );
			gui_change_shoot_type_post( event->param );
			break;
		case 7:
			DebugMsg( 0x84, 2, "GUI_CHANGE_LCD_STATE:%d", event->param );
			gui_change_lcd_state_post( event->param );
			break;

		default:
			break;
		}

event_loop_bottom:
		gui_main_struct.counter--;
		continue;

queue_clear:
		DebugMsg(
			0x84,
			3,
			"**** Queue Clear **** event(%d) param(%d)",
			event->type,
			event->param
		);

		goto event_loop_bottom;
	}
}
void CCopyThread::DoCopyDir(string source, string dest)
{
	WIN32_FIND_DATA findFileData;
	memset(&findFileData,0,sizeof(WIN32_FIND_DATA));
	string searchcmd = source + "\\*.*";
	searchcmd = str_replaceallA(searchcmd,"\\\\","\\");
	HANDLE hFind = FindFirstFile(searchcmd.c_str(), &findFileData);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		if (Action == CDA_MOVEFILES || Action == CDA_SDMODE || Action == CDA_DELETE)
		{
			source = str_replaceallA(source,"\\\\","\\");
			//DebugMsg("rmdir %s",source.c_str());
			int res = _rmdir(source.c_str());
			if (res != 0)
				DebugMsg("CopyThread","rmdir error %d - %d",res,GetLastError());
		}
		return;
	}

	do {
		if (Cancel)
		{
			FindClose(hFind);
			return;
		}

		if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			string newdest = dest + "\\" + findFileData.cFileName;
			newdest = str_replaceallA(newdest,"\\\\","\\");
			if (Action != CDA_DELETE)
			{
				//DebugMsg("Make dir %s",newdest.c_str());
                /*if(Action == CDA_COPYDVD && newdest.find("$SystemUpdate") )
                {
                    continue;
                }*/
                _mkdir(newdest.c_str());
			}
			DoCopyDir(source + "\\" + findFileData.cFileName,newdest);
		} 
        else 
        {
			if (Action == CDA_COPYDVD && make_lowercaseA(string(findFileData.cFileName)) == "default.xex")
            {
				continue;
            }
            
            if (Action == CDA_DELETE)
			{
				string filename = source + "\\" + findFileData.cFileName;
				filename = str_replaceallA(filename,"\\\\","\\");
				//DebugMsg("unlink %s",filename.c_str());
				_unlink(filename.c_str());
				Total_FilesCopied++;
			} 
            else 
            {
				DoCopyFile(source + "\\" + findFileData.cFileName,dest + "\\" + findFileData.cFileName);
			}
		}
	} 
    while (FindNextFile(hFind, &findFileData));
	
    FindClose(hFind);

	if (Action == CDA_MOVEFILES || Action == CDA_SDMODE || Action == CDA_DELETE)
	{
		source = str_replaceallA(source,"\\\\","\\");
		//DebugMsg("rmdir %s",source.c_str());
		int res = _rmdir(source.c_str());
		if (res != 0)
			DebugMsg("CopyThread","rmdir error %d - %d",res,GetLastError());
	}
}
Exemple #21
0
static ret_code DoPatch( struct asym *sym, struct fixup *fixup )
/**************************************************************/
{
    long                disp;
    long                max_disp;
    unsigned            size;
    struct dsym         *seg;
#if LABELOPT
    struct asym         *sym2;
    struct fixup        *fixup2;
#endif

    /* all relative fixups should occure only at first pass and they signal forward references
     * they must be removed after patching or skiped ( next processed as normal fixup )
     */

    DebugMsg(("DoPatch(%u, %s): fixup sym=%s type=%u ofs=%" FX32 "h loc=%" FX32 "h opt=%u def_seg=%s\n",
              Parse_Pass + 1, sym->name,
              fixup->sym ? fixup->sym->name : "NULL",
              fixup->type,
              fixup->offset,
              fixup->location,
              fixup->option,
              fixup->def_seg ? fixup->def_seg->sym.name : "NULL" ));
    seg = GetSegm( sym );
    if( seg == NULL || fixup->def_seg != seg ) {
        /* if fixup location is in another segment, backpatch is possible, but
         * complicated and it's a pretty rare case, so nothing's done.
         */
        DebugMsg(("DoPatch: skipped due to seg incompat: %s - %s\n",
                  fixup->def_seg ? fixup->def_seg->sym.name : "NULL",
                  seg ? seg->sym.name : "NULL" ));
        SkipFixup();
        return( NOT_ERROR );
    }

    if( Parse_Pass == PASS_1 ) {
        if( sym->mem_type == MT_FAR && fixup->option == OPTJ_CALL ) {
            /* convert near call to push cs + near call,
             * (only at first pass) */
            DebugMsg(("DoPatch: Phase error! caused by far call optimization\n"));
            ModuleInfo.PhaseError = TRUE;
            sym->offset++;  /* a PUSH CS will be added */
            /* todo: insert LABELOPT block here */
            OutputByte( 0 ); /* it's pass one, nothing is written */
            FreeFixup( fixup );
            return( NOT_ERROR );
            //} else if( sym->mem_type == MT_NEAR ) {
        } else {
            /* forward reference, only at first pass */
            switch( fixup->type ) {
            case FIX_RELOFF32:
            case FIX_RELOFF16:
                FreeFixup( fixup );
                DebugMsg(("DoPatch: FIX_RELOFF32/FIX_RELOFF16, return\n"));
                return( NOT_ERROR );
            case FIX_OFF8:  /* push <forward reference> */
                if ( fixup->option == OPTJ_PUSH ) {
                    size = 1;    /* size increases from 2 to 3/5 */
                    DebugMsg(("DoPatch: FIX_OFF8\n"));
                    goto patch;
                }
            }
        }
    }
    size = 0;
    switch( fixup->type ) {
    case FIX_RELOFF32:
        size = 2; /* will be 4 finally */
    /* fall through */
    case FIX_RELOFF16:
        size++; /* will be 2 finally */
    /* fall through */
    case FIX_RELOFF8:
        size++;
        /* calculate the displacement */
        // disp = fixup->offset + GetCurrOffset() - fixup->location - size;
        disp = fixup->offset + fixup->sym->offset - fixup->location - size - 1;
        max_disp = (1UL << ((size * 8)-1)) - 1;
        if( disp > max_disp || disp < (-max_disp-1) ) {
patch:
            DebugMsg(("DoPatch(%u): Phase error, disp=%X, fixup=%s(%X), loc=%X!\n", Parse_Pass + 1, disp, fixup->sym->name, fixup->sym->offset, fixup->location ));
            ModuleInfo.PhaseError = TRUE;
            /* ok, the standard case is: there's a forward jump which
             * was assumed to be SHORT, but it must be NEAR instead.
             */
            switch( size ) {
            case 1:
                size = 0;
                switch( fixup->option ) {
                case OPTJ_EXPLICIT:
#if 0 /* don't display the error at the destination line! */
                    sym->fixup = NULL;
                    DebugMsg(("DoPatch: jump out of range, disp=%d\n", disp ));
                    EmitErr( JUMP_OUT_OF_RANGE, disp - max_disp );
                    return( ERROR );
#else
                    return( NOT_ERROR ); /* nothing to do */
#endif
                case OPTJ_EXTEND: /* Jxx for 8086 */
                    size++;       /* will be 3/5 finally */
                /* fall through */
                case OPTJ_JXX: /* Jxx for 386 */
                    size++;
                /* fall through */
                default: /* normal JMP (and PUSH) */
                    // if( CodeInfo->Ofssize ) /* v1.96: don't use CodeInfo here! */
                    if( seg->e.seginfo->Ofssize )
                        size += 2; /* NEAR32 instead of NEAR16 */
                    size++;
#if LABELOPT
                    /* v2.04: if there's an ORG between src and dst, skip
                     * the optimization!
                     */
                    if ( Parse_Pass == PASS_1 ) {
                        for ( fixup2 = seg->e.seginfo->FixupListHead; fixup2; fixup2 = fixup2->nextrlc ) {
                            if ( fixup2->orgoccured ) {
                                DebugMsg(("DoPatch: ORG/ALIGN detected, optimization canceled\n" ));
                                return( NOT_ERROR );
                            }
                            /* do this check after the check for ORG! */
                            if ( fixup2->location <= fixup->location )
                                break;
                        }
                    }
                    /* scan the segment's label list and adjust all labels
                     * which are between the fixup loc and the current sym.
                     * ( PROCs are NOT contained in this list because they
                     * use the <next>-field of dsym already!)
                     */
                    for ( sym2 = seg->e.seginfo->labels; sym2; sym2 = (struct asym *)((struct dsym *)sym2)->next ) {
                        //if ( sym2 == sym )
                        //    continue;
                        /* v2.0: location is at least 1 byte too low, so
                         * use the "<=" operator instead of "<"!
                         */
                        //if ( sym2->offset < fixup->location )
                        if ( sym2->offset <= fixup->location )
                            break;
                        sym2->offset += size;
                        DebugMsg(("DoPatch(loc=%" FX32 "): sym %s, offset changed %" FX32 " -> %" FX32 "\n", fixup->location, sym2->name, sym2->offset - size, sym2->offset));
                    }
                    /* v2.03: also adjust fixup locations located between the
                     * label reference and the label. This should reduce the
                     * number of passes to 2 for not too complex sources.
                     */
                    if ( Parse_Pass == PASS_1 ) /* v2.04: added, just to be safe */
                        for ( fixup2 = seg->e.seginfo->FixupListHead; fixup2; fixup2 = fixup2->nextrlc ) {
                            if ( fixup2->sym == sym )
                                continue;
                            if ( fixup2->location <= fixup->location )
                                break;
                            fixup2->location += size;
                            DebugMsg(("for sym=%s fixup loc %" FX32 " changed to %" FX32 "\n", fixup2->sym->name, fixup2->location - size, fixup2->location ));
                        }
#else
                    DebugMsg(("DoPatch: sym %s, offset changed %" FX32 " -> %" FX32 "\n", sym->name, sym->offset, sym->offset + size));
                    sym->offset += size;
#endif
                    /*  it doesn't matter what's actually "written" */
                    for ( ; size; size-- )
                        OutputByte( 0xCC );
                    break;
                }
                break;
            case 2:
            case 4:
                DebugMsg(("DoPatch: jump out of range, disp=%d\n", disp ));
                EmitWarn( 4, JUMP_OUT_OF_RANGE, disp - max_disp );
                break;
            }
        }
#ifdef DEBUG_OUT
        else
            DebugMsg(("DoPatch, loc=%" FX32 ": displacement still short: %Xh\n", fixup->location, disp ));
#endif
        /* v2.04: fixme: is it ok to remove the fixup?
         * it might still be needed in a later backpatch.
         */
        FreeFixup( fixup );
        break;
    default:
        DebugMsg(("DoPatch: default branch, unhandled fixup type=%u\n", fixup->type ));
        SkipFixup();
        break;
    }
    return( NOT_ERROR );
}
Exemple #22
0
/* This routine should be called after a transfer finishes, even if no
 * progress reports were done.  Besides cleaning up the progress stuff,
 * we also do our logging here.
 */
void EndProgress(XferSpecPtr xp)
{
	double elapsedTime, xRate, xferred;
	char *unitStr;
	char *shortName;
	string statMsg;
	longstring fullRemote;
	long kb, hsecs;
	int wantStats;
	int localFileIsStdout;

	wantStats = 0;
	if ((xp->doReports) && (xp->bytesTransferred > 0) && (gVerbosity != kQuiet)) {
		ProgressReport(xp, kPrLastUpdateMsg);
		wantStats = (InForeGround()) &&
			((*xp->prProc)(xp, kPrEndMsg) == kPrWantStatsMsg);
	}
	(void) Gettimeofday(&xp->endTime);

	/* Compute transfer stats. */
	xRate = TransferRate(
		xp->bytesTransferred,
		&xp->startTime,
		&xp->endTime,
		&unitStr,
		&elapsedTime
	);

	/* Print the stats, if requested. */
	if (wantStats) {
		shortName = strrchr(xp->localFileName, '/');
		if (shortName == NULL)
			shortName = xp->localFileName;
		else
			shortName++;
		sprintf(statMsg, "%s:  %ld bytes %s%s in %.2f seconds",
			shortName,
			xp->bytesTransferred,
			NETREADING(xp) ? "received" : "sent",
			xp->startPoint ? " and appended to existing file" : "",
			elapsedTime
		);
		if (xRate > 0.0) {
			sprintf(statMsg + strlen(statMsg), ", %.2f %s",
				xRate,
				unitStr
			);
		}
		STRNCAT(statMsg, ".");
	
		/* Make sure echoing is back on! */
		Echo(stdin, 1);

		/* Make sure the rest of the line is padded with spaces, so it will
		 * erase junk that may have been leftover from a progress meter.
		 */
		EPrintF("%-79s\n", statMsg);
		FlushListWindow();
	} else {
		if (xRate > 0.0) {
			DebugMsg("%ld bytes transferred in %.2f seconds, %.2f %s.\n",
				xp->bytesTransferred,
				elapsedTime,
				xRate,
				unitStr
			);
		} else {
			DebugMsg("%ld bytes transferred in %.2f seconds.\n",
				xp->bytesTransferred,
				elapsedTime
			);
		}
	}

	/* Only log stuff if there was a remote filename specified.
	 * We don't want to log directory listings or globbings.
	 */
	if ((xp->remoteFileName != NULL)) {
		/* Get kilobytes transferred, rounding to the nearest kB. */
		kb = ((long) xp->bytesTransferred + 512L) / 1024L;
		OverflowAdd(&gTotalXferKiloBytes, kb);
		OverflowAdd(&gRmtInfo.xferKbytes, kb);

		/* Get hundredths of seconds, rounded up to nearest. */
		hsecs = (long) (100.0 * (elapsedTime + 0.0050));
		OverflowAdd(&gTotalXferHSeconds, hsecs);
		OverflowAdd(&gRmtInfo.xferHSeconds, hsecs);
		if (gTotalXferHSeconds < 0)
			gTotalXferHSeconds = 1L;
		if (gRmtInfo.xferHSeconds <= 0)
			gRmtInfo.xferHSeconds = 1L;

		localFileIsStdout =
			(STREQ(xp->remoteFileName, kLocalFileIsStdout));
	    /* If a simple path is given, try to log the full path. */
		if ((xp->remoteFileName[0] == '/') || (localFileIsStdout)) {
			/* Use what we had in the xp. */
			STRNCPY(fullRemote, xp->remoteFileName);
		} else {
			/* Make full path by appending what we had in the xp
			 * to the current remote directory.
			 */
			STRNCPY(fullRemote, gRemoteCWD);
			STRNCAT(fullRemote, "/");
			STRNCAT(fullRemote, xp->remoteFileName);
		}
	
		/* Save transfers to the user's logfile.  We only log something to
		 * the user log if we are actually saving a file;  we don't log
		 * to the user log if we are piping the remote output into something,
		 * or dumping it to stdout.
		 */
		if ((gLogFile != NULL) && (!localFileIsStdout)) {
			xferred = FileSize((double) xp->bytesTransferred, &unitStr, NULL);
			(void) fprintf(gLogFile, "  %-3s  %6.2f %-2s  ftp://%s%s\n",
				NETREADING(xp) ? "get" : "put",
				xferred,
				unitStr,
				gRmtInfo.name,
				fullRemote
			);
			fflush(gLogFile);
		}

#ifdef SYSLOG
    	{
        longstring infoPart1;

        /* Some syslog()'s can't take an unlimited number of arguments,
         * so shorten our call to syslog to 5 arguments total.
         */
        STRNCPY(infoPart1, gUserInfo.userName);
        if (NETREADING(xp)) {
            STRNCAT(infoPart1, " received ");
            STRNCAT(infoPart1, fullRemote);	/* kLocalFileIsStdout is ok. */
            STRNCAT(infoPart1, " as ");
            STRNCAT(infoPart1, xp->localFileName);
            STRNCAT(infoPart1, " from ");
        } else {
            STRNCAT(infoPart1, " sent ");
            STRNCAT(infoPart1, xp->localFileName);
            STRNCAT(infoPart1, " as ");
            STRNCAT(infoPart1, fullRemote);
            STRNCAT(infoPart1, " to ");
        }
        STRNCAT(infoPart1, gActualHostName);
#ifndef LOG_INFO
#	define LOG_INFO 6		/* Don't know if this is standard! */
#endif
        syslog (LOG_INFO, "%s (%ld bytes).", infoPart1, xp->bytesTransferred);
    	}
#endif  /* SYSLOG */
	}
}									   /* EndProgress */
int handleAssetUpload( ehttp &obj, void * cookie ) 
{	
	// Variables for Hidden Fields - required to find proper contentitem
	DWORD dwContentId, dwTitleId, dwContentType;
	string szSessionId;

	// Pointers to hold image information as data is uploaded
	HTTP_ENTRY_DATA assetIcon, assetBanner, assetBoxart, assetBackground;
	bool hasIconData = false, hasBannerData = false, hasBoxartData = false, hasBackgroundData = false;

	string szGameTitle, szGameDescription, szGameGenre, szGameDeveloper, szGameExecutable;

	// Loop through the upload and find the data chunk containing our content id
	DWORD chunkCount = obj.post_chunks.size();
	for(DWORD nChunks = 0; nChunks < chunkCount; nChunks++) {
		DWORD entryCount = obj.post_chunks.at(nChunks).Entries.size();
		for( DWORD nEntries = 0; nEntries < entryCount; nEntries++) {
			// loop through every entry and find the ones we want
			if( obj.post_chunks.at(nChunks).Entries.at(nEntries).EntryType == HTTP_ENTRYTYPE_HEADER) {
				if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters.find("name") != obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters.end()) {
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "sessionid") {
					
						// Grab the Content ID
						szSessionId = getEntryContent(obj, nChunks);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "contentid") {
					
						// Grab the Content ID
						string szContentId = getEntryContent(obj, nChunks);
						dwContentId = strtoul(szContentId.c_str(), NULL, 16);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "titleid") {
			
						// Grab the Title ID
						string szTitleId = getEntryContent(obj, nChunks);
						dwTitleId = strtoul(szTitleId.c_str(), NULL, 16);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "contenttype") {
						// Grab the ContentType
						string szContentType = getEntryContent(obj, nChunks);
						dwContentType = strtoul(szContentType.c_str(), NULL, 16);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameTitle") {
						
						// Grab the Title
						szGameTitle = getEntryContent(obj, nChunks);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameDescription") {
						
						// Grab the Description
						szGameDescription = getEntryContent(obj, nChunks);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameGenre") {
						
						// Grab the Genre
						szGameGenre = getEntryContent(obj, nChunks);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameDeveloper") {
						
						// Grab the Developer 
						szGameDeveloper = getEntryContent(obj, nChunks);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameExecutable") {
						
						// Grab the Executable
						szGameExecutable = getEntryContent(obj, nChunks);
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameIcon") {

						if(strcmp(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["filename"].c_str(), "") != 0) {
							
							// Extract image data
							assetIcon = obj.post_chunks.at(nChunks).FileData;
							hasIconData = true;
						}
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameBanner") {
						// check to make sure that a file was uploaded
						if(strcmp(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["filename"].c_str(), "") != 0) {
							
							// Extract image data
							assetBanner = obj.post_chunks.at(nChunks).FileData;
							hasBannerData = true;
						}
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameBoxart") {
						// check to make sure that a file was uploaded
						if(strcmp(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["filename"].c_str(), "") != 0) {
							
							// Extract image data
							assetBoxart = obj.post_chunks.at(nChunks).FileData;
							hasBoxartData = true;
						}
					}
					if(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["name"] == "GameBackground") {
						// check to make sure that a file was uploaded
						if(strcmp(obj.post_chunks.at(nChunks).Entries.at(nEntries).Parameters["filename"].c_str(), "") != 0) {
							
							// Extract image data
							assetBackground = obj.post_chunks.at(nChunks).FileData;
							hasBackgroundData = true;
						}
					}
				}
			}
		}
	}

	// Verify that the session Id matches before applying changes.
	if(strcmp(szSessionId.c_str(), HTTPServer::getInstance().g_mGlobalSessionId.c_str()) != 0)
		return 0;

	// We have officially received all of our posted data- now let's update our database and send out our messages to the ContentObservers
	ContentItemNew * pContentItem = NULL;
	pContentItem = ContentManager::getInstance().GetContentByContentId(dwContentId);

	if(pContentItem != NULL) 
	{
		if(pContentItem->getTitleId() != dwTitleId) 
			DebugMsg("HTTPServer", "WARNING:  Extracted ContentItem TitleID does not match uploaded content");

		// First we'll update our our text items
		pContentItem->setDisplayInfo(szGameTitle, szGameDescription, szGameGenre, szGameDeveloper);

		// Now we can start on the images
		if(hasIconData == true) {
			DebugMsg("HTTPServer", "GameIcon Path Found, Updating Content.");
			pContentItem->AddAsset(ITEM_UPDATE_TYPE_THUMBNAIL, assetIcon.Data, assetIcon.Length);
		}

		if(hasBannerData == true) {
			DebugMsg("HTTPServer", "GameBanner Path Found, Updating Content.");
			pContentItem->AddAsset(ITEM_UPDATE_TYPE_BANNER, assetBanner.Data, assetBanner.Length);
		}

		if(hasBoxartData == true) {
			DebugMsg("HTTPServer", "GameBoxart Path Found, Updating Content.");
			pContentItem->AddAsset(ITEM_UPDATE_TYPE_BOXART, assetBoxart.Data, assetBoxart.Length);
		}

		if(hasBackgroundData == true) {
			DebugMsg("HTTPServer", "GameBackground Path Found, Updating Content.");
			pContentItem->AddAsset(ITEM_UPDATE_TYPE_BACKGROUND, assetBackground.Data, assetBackground.Length);
		}
	}

	// Standard link was clicked- let's submit our session data and load the next page
	HTTP_SESSION_DATA * pData = new HTTP_SESSION_DATA;

	pData->Username = "";
	pData->Password = "";
	pData->SessionId = szSessionId;

	int ret = handleGetRequest( obj, (void*)pData );

	return ret;
}
BOOLEAN ReadInLBEPocketPopups(STR fileName)
{
	HWFILE		hFile;
	UINT32		uiBytesRead;
	UINT32		uiFSize;
	CHAR8 *		lpcBuffer;
	XML_Parser	parser = XML_ParserCreate(NULL);
	
	pocketPopupParseData pData;

	DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading pocketPopups.xml" );

	hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
	if ( !hFile )
		return( FALSE );
	
	uiFSize = FileGetSize(hFile);
	lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);

	//Read in block
	if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
	{
		MemFree(lpcBuffer);
		return( FALSE );
	}

	lpcBuffer[uiFSize] = 0; //add a null terminator

	FileClose( hFile );

	
	XML_SetElementHandler(parser, pocketPopupStartElementHandle, pocketPopupEndElementHandle);
	XML_SetCharacterDataHandler(parser, pocketPopupCharacterDataHandle);

	
	memset(&pData,0,sizeof(pData));
	XML_SetUserData(parser, &pData);
	
	XML_SetUserData(parser, &pData);

	if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
	{
		CHAR8 errorBuf[511];

		sprintf(errorBuf, "XML Parser Error in Pocket.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
		LiveMessage(errorBuf);

		MemFree(lpcBuffer);
		return FALSE;
	}

	/*
	// dummy popup

	 popupDef* popup = new popupDef();
	 popup->addOption(new std::wstring(L"Option one"),NULL,NULL);
	 popup->addOption(new std::wstring(L"Option two"),NULL,NULL);
	 popup->addOption(new std::wstring(L"Option three"),NULL,NULL);

	LBEPocketPopup[5] = *popup;
	*/

	MemFree(lpcBuffer);


	XML_ParserFree(parser);


	return( TRUE );
}
Exemple #25
0
BOOLEAN ReadInEmailOther(STR fileName, BOOLEAN localizedVersion)
{
	HWFILE		hFile;
	UINT32		uiBytesRead;
	UINT32		uiFSize;
	CHAR8 *		lpcBuffer;
	XML_Parser	parser = XML_ParserCreate(NULL);

	EmailOtherParseData pData;

	DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading EmailOther.xml" );

	EmailOther_TextOnly = localizedVersion;
	
	// Open file
	hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
	if ( !hFile )
		return( localizedVersion );

	uiFSize = FileGetSize(hFile);
	lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);

	//Read in block
	if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
	{
		MemFree(lpcBuffer);
		return( FALSE );
	}

	lpcBuffer[uiFSize] = 0; //add a null terminator

	FileClose( hFile );


	XML_SetElementHandler(parser, EmailOtherStartElementHandle, EmailOtherEndElementHandle);
	XML_SetCharacterDataHandler(parser, EmailOtherCharacterDataHandle);


	memset(&pData,0,sizeof(pData));
	XML_SetUserData(parser, &pData);


	if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
	{
		CHAR8 errorBuf[511];

		sprintf(errorBuf, "XML Parser Error in EmailOther.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
		LiveMessage(errorBuf);

		MemFree(lpcBuffer);
		return FALSE;
	}

	MemFree(lpcBuffer);


	XML_ParserFree(parser);


	return( TRUE );
}
Exemple #26
0
static
STATUS
ProcessFile (
  INT8              *TargetFileName,
  INT8              *FileName,
  UINT32            NestDepth,
  STRING_LIST       *ProcessedFiles,
  FILE_SEARCH_TYPE  FileSearchType
  )
/*++

Routine Description:

  Given a source file name, open the file and parse all #include lines.
  
Arguments:

  TargetFileName - name of the usually .obj target
  FileName       - name of the file to process
  NestDepth      - how deep we're nested in includes
  ProcessedFiles - list of processed files.
  FileSearchType - search type for FileName

Returns:

  standard status.
  
--*/
{
  FILE        *Fptr;
  INT8        Line[MAX_LINE_LEN];
  INT8        *Cptr;
  INT8        *EndPtr;
  INT8        *SaveCptr;
  INT8        EndChar;
  INT8        FileNameCopy[MAX_PATH];
  INT8        MacroIncludeFileName[MAX_LINE_LEN];
  INT8        SumDepsFile[MAX_PATH];
  STATUS      Status;
  UINT32      Index;
  UINT32      LineNum;
  STRING_LIST *ListPtr;
  STRING_LIST ParentPath;

  Status  = STATUS_SUCCESS;
  Fptr    = NULL;
  //
  // Print the file being processed. Indent so you can tell the include nesting
  // depth.
  //
  if (mGlobals.Verbose) {
    fprintf (stdout, "%*cProcessing file '%s'\n", NestDepth * 2, ' ', FileName);
  }
  //
  // If we're using summary dependency files, and a matching .dep file is
  // found for this file, then just emit the summary dependency file as
  // a dependency and return.
  //
  if (mGlobals.UseSumDeps) {
    strcpy (SumDepsFile, mGlobals.SumDepsPath);
    strcat (SumDepsFile, FileName);
    for (Cptr = SumDepsFile + strlen (SumDepsFile) - 1;
         (*Cptr != '\\') && (Cptr > SumDepsFile) && (*Cptr != '.');
         Cptr--
        )
      ;
    if (*Cptr == '.') {
      strcpy (Cptr, ".dep");
    } else {
      strcat (SumDepsFile, ".dep");
    }
    //
    // See if the summary dep file exists. Could use _stat() function, but
    // it's less portable.
    //
    if ((Fptr = fopen (SumDepsFile, "r")) != NULL) {
      PrintDependency (TargetFileName, SumDepsFile);
      fclose (Fptr);
      return STATUS_SUCCESS;
    }
  }

  //
  // Make sure we didn't exceed our maximum nesting depth
  //
  if (NestDepth > MAX_NEST_DEPTH) {
    Error (NULL, 0, 0, FileName, "max nesting depth exceeded on file");
    goto Finish;
  }
  //
  // Make a local copy of the filename. Then we can manipulate it
  // if we have to.
  //
  strcpy (FileNameCopy, FileName);
  
  if (FileSearchType == SearchCurrentDir) {
    //
    // Try to open the source file locally
    //
    if ((Fptr = fopen (FileNameCopy, "r")) == NULL) {
      Error (NULL, 0, 0, FileNameCopy, "could not open source file");
      return STATUS_ERROR;
    }
  } else {
    //
    // Try to find it among the paths.
    //
    Fptr = FindFile (FileNameCopy, sizeof (FileNameCopy), FileSearchType);
    if (Fptr == NULL) {
      //
      // If this is not the top-level file, and the command-line argument
      // said to ignore missing files, then return ok
      //
      if (NestDepth != START_NEST_DEPTH) {
        if (mGlobals.IgnoreNotFound) {
          if (!mGlobals.QuietMode) {
            DebugMsg (NULL, 0, 0, FileNameCopy, "could not find file");
          }

          return STATUS_SUCCESS;
        } else {
          Error (NULL, 0, 0, FileNameCopy, "could not find file");
          return STATUS_ERROR;
        }
      } else {
        //
        // Top-level (first) file. Emit an error.
        //
        Error (NULL, 0, 0, FileNameCopy, "could not find file");
        return STATUS_ERROR;
      }
    }
  }

  //
  // If we're not doing duplicates, and we've already seen this filename,
  // then return
  //
  if (mGlobals.NoDupes) {
    for (ListPtr = ProcessedFiles->Next; ListPtr != NULL; ListPtr = ListPtr->Next) {
      if (_stricmp (FileNameCopy, ListPtr->Str) == 0) {
        break;
      }
    }
    //
    // If we found a match, we're done. If we didn't, create a new element
    // and add it to the list.
    //
    if (ListPtr != NULL) {
      //
      // Print a message if verbose mode
      //
      if (mGlobals.Verbose) {
        DebugMsg (NULL, 0, 0, FileNameCopy, "duplicate include -- not processed again");
      }
      fclose (Fptr);
      return STATUS_SUCCESS;
    }

    ListPtr       = malloc (sizeof (STRING_LIST));
    ListPtr->Str  = malloc (strlen (FileNameCopy) + 1);
    strcpy (ListPtr->Str, FileNameCopy);
    ListPtr->Next         = ProcessedFiles->Next;
    ProcessedFiles->Next  = ListPtr;
  }
    
  //
  // Print the dependency, with string substitution
  //
  PrintDependency (TargetFileName, FileNameCopy);
  
  //
  // Get the file path and push to ParentPaths
  //
  Cptr = FileNameCopy + strlen (FileNameCopy) - 1;
  for (; (Cptr > FileNameCopy) && (*Cptr != '\\') && (*Cptr != '/'); Cptr--);
  if ((*Cptr == '\\') || (*Cptr == '/')) {
    *(Cptr + 1) = 0;
  } else {
    strcpy (FileNameCopy, ".\\");
  }
  ParentPath.Next = mGlobals.ParentPaths;
  ParentPath.Str = FileNameCopy;
  mGlobals.ParentPaths = &ParentPath;
  
  //
  // Now read in lines and find all #include lines. Allow them to indent, and
  // to put spaces between the # and include.
  //
  LineNum = 0;
  while ((fgets (Line, sizeof (Line), Fptr) != NULL) && (Status == STATUS_SUCCESS)) {
    LineNum++;
    Cptr = Line;
    //
    // Skip preceeding spaces on the line
    //
    while (*Cptr && (isspace (*Cptr))) {
      Cptr++;
    }
    //
    // Check for # character, there is no # for asm
    //
    if ((*Cptr == '#') || (mGlobals.IsAsm)) {
      if (*Cptr == '#') {
        Cptr++;
      }
      
      //
      // Check for "include", case insensitive for asm
      //
      while (*Cptr && (isspace (*Cptr))) {
        Cptr++;
      }
      if (((!mGlobals.IsAsm) && (strncmp (Cptr, "include", 7) == 0)) || 
          (mGlobals.IsAsm && (_strnicmp (Cptr, "include", 7) == 0))) {
        //
        // Skip over "include" and move on to filename as "file" or <file> or file for asm
        //
        Cptr += 7;
        while (*Cptr && (isspace (*Cptr))) {
          Cptr++;
        }

        if (*Cptr == '<') {
          EndChar = '>';
        } else if (*Cptr == '"') {
          EndChar = '"';
        } else if (mGlobals.IsAsm) {
          //
          // Handle include file for asm
          // Set EndChar to null so we fall through on processing below.
          //
          EndChar = 0;
          
          //
          // Look for the end of include file name
          //
          EndPtr = Cptr;
          while (*EndPtr && (!isspace (*EndPtr))) {
            EndPtr++;
          }
      
          //
          // Null terminate the filename and try to process it.
          //
          *EndPtr = 0;
          Status  = ProcessFile (TargetFileName, Cptr, NestDepth + 1, 
                                 ProcessedFiles, SearchAllPaths);
        } else {
          //
          // Handle special #include MACRO_NAME(file)
          // Set EndChar to null so we fall through on processing below.
          //
          EndChar = 0;
          //
          // Look for all the special include macros and convert accordingly.
          //
          for (Index = 0; mMacroConversion[Index].IncludeMacroName != NULL; Index++) {
            //
            // Save the start of the string in case some macros are substrings
            // of others.
            //
            SaveCptr = Cptr;
            if (strncmp (
                  Cptr,
                  mMacroConversion[Index].IncludeMacroName,
                  strlen (mMacroConversion[Index].IncludeMacroName)
                  ) == 0) {
              //
              // Skip over the macro name
              //
              Cptr += strlen (mMacroConversion[Index].IncludeMacroName);
              //
              // Skip over open parenthesis, blank spaces, then find closing
              // parenthesis or blank space
              //
              while (*Cptr && (isspace (*Cptr))) {
                Cptr++;
              }

              if (*Cptr == '(') {
                Cptr++;
                while (*Cptr && (isspace (*Cptr))) {
                  Cptr++;
                }

                EndPtr = Cptr;
                while (*EndPtr && !isspace (*EndPtr) && (*EndPtr != ')')) {
                  EndPtr++;
                }

                *EndPtr = 0;
                //
                // Create the path
                //
                strcpy (MacroIncludeFileName, mMacroConversion[Index].PathName);
                strcat (MacroIncludeFileName, Cptr);
                strcat (MacroIncludeFileName, "\\");
                strcat (MacroIncludeFileName, Cptr);
                strcat (MacroIncludeFileName, ".h");
                //
                // Process immediately, then break out of the outside FOR loop.
                //
                Status = ProcessFile (TargetFileName, MacroIncludeFileName, NestDepth + 1, 
                                      ProcessedFiles, SearchAllPaths);
                break;
              }
            }
            //
            // Restore the start
            //
            Cptr = SaveCptr;
          }
          //
          // Don't recognize the include line? Ignore it. We assume that the
          // file compiles anyway.
          //
          if (mMacroConversion[Index].IncludeMacroName == NULL) {
            //
            // Warning (FileNameCopy, LineNum, 0, "could not parse line", NULL);
            // Status = STATUS_WARNING;
            //
          }
        }
        //
        // Process "normal" includes. If the endchar is 0, then the
        // file has already been processed. Otherwise look for the
        // endchar > or ", and process the include file.
        //
        if (EndChar != 0) {
          Cptr++;
          EndPtr = Cptr;
          while (*EndPtr && (*EndPtr != EndChar)) {
            EndPtr++;
          }

          if (*EndPtr == EndChar) {
            //
            // If we're processing it, do it
            //
            if (EndChar != '>') {
              //
              // Null terminate the filename and try to process it.
              //
              *EndPtr = 0;
              Status  = ProcessFile (TargetFileName, Cptr, NestDepth + 1, 
                                     ProcessedFiles, SearchAllPaths);
            } else if (!mGlobals.NoSystem) {
              //
              // Null terminate the filename and try to process it.
              //
              *EndPtr = 0;
              Status  = ProcessFile (TargetFileName, Cptr, NestDepth + 1, 
                                     ProcessedFiles, SearchIncludePaths);
            }
          } else {
            Warning (FileNameCopy, LineNum, 0, "malformed include", "missing closing %c", EndChar);
            Status = STATUS_WARNING;
            goto Finish;
          }
        }
      }
    }
  }
  //
  // Pop the file path from ParentPaths
  //
  mGlobals.ParentPaths = ParentPath.Next;  

Finish:
  //
  // Close open files and return status
  //
  if (Fptr != NULL) {
    fclose (Fptr);
  }

  return Status;
}
void VDebugMsgAttachment::DoExecute(OsType /*inEventType*/, const void* /*inData*/)
{
	if (fDebugString != NULL)
		DebugMsg(*fDebugString);
}
Exemple #28
0
static
STATUS
ProcessClOutput (
  INT8            *TargetFileName,
  INT8            *FileName,
  STRING_LIST     *ProcessedFiles
  )
/*++

Routine Description:

  Given a source file name, open the file and parse all "Note: including file: xxx.h" lines.
  
Arguments:

  TargetFileName - name of the usually .obj target
  FileName       - name of the file to process
  ProcessedFiles - list of processed files.

Returns:

  standard status.
  
--*/
{
  FILE        *Fptr;
  INT8        Line[MAX_LINE_LEN];
  INT8        IncludeFileName[MAX_LINE_LEN];
  STRING_LIST *ListPtr;
  BOOLEAN     ClError;
  INT32       Ret;
  INT8        Char;

  if ((Fptr = fopen (FileName, "r")) == NULL) {
    Error (NULL, 0, 0, FileName, "could not open file for reading");
    return STATUS_ERROR;
  }
  if (fgets (Line, sizeof (Line), Fptr) != NULL) {
    //
    // First line is the source file name, print it
    //
    printf ("%s", Line);
  } else {
    //
    // No output from cl
    //
    fclose (Fptr);
    Error (NULL, 0, 0, NULL, "incorrect cl tool path may be used ");
    return STATUS_ERROR;
  }
  
  ClError = FALSE;
  while (fgets (Line, sizeof (Line), Fptr) != NULL) {
    Ret = sscanf (Line, "Note: including file: %s %c", IncludeFileName, &Char);
    if (Ret == 2) {
      //
      // There is space in include file name. It's VS header file. Ignore it.
      //
      continue;
    } else if ( Ret != 1) {
      //
      // Cl error info, print it
      // the tool will return error code to stop the nmake
      //
      ClError = TRUE;
      printf ("%s", Line);
      continue;
    }
    
    //
    // If we're not doing duplicates, and we've already seen this filename,
    // then continue
    //
    if (mGlobals.NoDupes) {
      for (ListPtr = ProcessedFiles->Next; ListPtr != NULL; ListPtr = ListPtr->Next) {
        if (_stricmp (IncludeFileName, ListPtr->Str) == 0) {
          break;
        }
      }
      //
      // If we found a match, we're done. If we didn't, create a new element
      // and add it to the list.
      //
      if (ListPtr != NULL) {
        //
        // Print a message if verbose mode
        //
        if (mGlobals.Verbose) {
          DebugMsg (NULL, 0, 0, IncludeFileName, "duplicate include -- not processed again");
        }
  
        continue;
      }
  
      ListPtr       = malloc (sizeof (STRING_LIST));
      ListPtr->Str  = malloc (strlen (IncludeFileName) + 1);
      strcpy (ListPtr->Str, IncludeFileName);
      ListPtr->Next         = ProcessedFiles->Next;
      ProcessedFiles->Next  = ListPtr;
    }
    
    PrintDependency (TargetFileName, IncludeFileName);
  }
  
  fclose (Fptr);
  
  if (ClError) {
    Error (NULL, 0, 0, NULL, "cl error");
    return STATUS_ERROR;
  } else {
    return STATUS_SUCCESS;
  }
}
//static
VFileKind* XLinuxFile::CreatePublicFileKindFromExtension(const VString& inExtension)
{
  DebugMsg(VString("Try to create new file kind from extension : ").AppendString(inExtension).AppendCString("\n"));

  return NULL;
}
extern "C" int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrevInst , __in LPSTR lpszCmdLine, int nCmdShow)
{

//-----------------------------------------------------------------------------------------------------------------
//  VARIABLES
//
//-----------------------------------------------------------------------------------------------------------------
    UINT    uiRet = ERROR_SUCCESS;
    HRESULT hr    = S_OK;

    char *szMsiFile          = 0;
    char *szBaseURL          = 0;
    char *szInstallPath      = 0;
    char *szMsiCacheFile     = 0;
    char *szOperation        = 0;
    char *szProductName      = 0;
    char *szMinimumMsi       = 0;
    char *szProperties       = 0;
    char *szInstProperties   = 0;
    char *szTempPath         = 0;
    char *szFilePart         = 0;
    char *szBase             = 0;
    char *szUpdate           = 0;

    char *szRegisteredMsiFolder = 0;
    char *szMsiDllLocation      = 0;

    char szAppTitle[MAX_STR_CAPTION]    = {0};
    char szError[MAX_STR_LENGTH]        = {0};
    char szText[MAX_STR_CAPTION]        = {0};
    char szBanner[MAX_STR_LENGTH]       = {0};
    char szAction[MAX_STR_LENGTH]       = {0};
    char szUserPrompt[MAX_STR_LENGTH]   = {0};
    char szProductCode[MAX_LENGTH_GUID] = {0};

    char szModuleFile[MAX_PATH]         = {0};
    DWORD dwModuleFileSize       = MAX_PATH;
    
    DWORD dwMsiFileSize          = 0;
    DWORD dwBaseURLSize          = 0;
    DWORD cchInstallPath         = 0;
    DWORD dwMsiCacheFileSize     = 0;
    DWORD dwOperationSize        = 0;
    DWORD dwProductNameSize      = 0;
    DWORD dwMinimumMsiSize       = 0;
    DWORD dwPropertiesSize       = 0;
    DWORD cchInstProperties      = 0;
    DWORD cchTempPath            = 0;
    DWORD dwLastError            = 0;
    DWORD cchReturn              = 0;
    DWORD dwBaseUpdateSize      = 0;
    DWORD dwUpdateSize          = 0;
    DWORD dwResult               = 0;
    DWORD dwType                 = 0;
    DWORD dwProductCodeSize      = MAX_LENGTH_GUID;

    DWORD dwRegisteredMsiFolderSize  = 0;
    DWORD dwMsiDllLocationSize       = 0;

    ULONG ulMsiMinVer        = 0;
    char *szStopScan         = NULL;

    bool        fDelayRebootReq    = false;
    bool        fPatch             = false;
    bool        fQFE               = false;
    bool        fOSSupported       = false;
    emEnum      emExecMode         = emPreset;

    HKEY hInstallerKey = 0;

    HMODULE hMsi = 0;
    PFnMsiSetInternalUI pfnMsiSetInternalUI = 0;
    PFnMsiInstallProduct pfnMsiInstallProduct = 0;
    PFnMsiApplyPatch pfnMsiApplyPatch = 0;
    PFnMsiReinstallProduct pfnMsiReinstallProduct = 0;
    PFnMsiQueryProductState pfnMsiQueryProductState = 0;
    PFnMsiOpenDatabase pfnMsiOpenDatabase = 0;
    PFnMsiDatabaseOpenView pfnMsiDatabaseOpenView = 0;
    PFnMsiViewExecute pfnMsiViewExecute = 0;
    PFnMsiViewFetch pfnMsiViewFetch = 0;
    PFnMsiRecordGetString pfnMsiRecordGetString = 0;
    PFnMsiCloseHandle pfnMsiCloseHandle = 0;

    MSIHANDLE hDatabase = 0;
    MSIHANDLE hView = 0;
    MSIHANDLE hRec = 0;

    INSTALLSTATE isProduct = INSTALLSTATE_UNKNOWN;
    
    const char * szAdminImagePath = 0;



//-----------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
    // create our UI object
    CDownloadUI DownloadUI;

    // Load our AppTitle (caption)
    WIN::LoadString(hInst, IDS_APP_TITLE, szAppTitle, sizeof(szAppTitle)/sizeof(char));

    // Obtain path we are running from
    if (0 == WIN::GetModuleFileName(hInst, szModuleFile, dwModuleFileSize))
    {
        // No UI displayed. Silent failure.
        uiRet = GetLastError();
        goto CleanUp;
    }
    DebugMsg("[Info] we are running from --> %s\n", szModuleFile);

    // Figure out what we want to do
    emExecMode = GetExecutionMode (lpszCmdLine);
    
    if (emVerify == emExecMode)
    {
        //
        // We don't want any UI to be displayed in this case. The return value
        // from the exe is the result of the verification. Therefore, this
        // should be done before initializing the UI.
        //
        uiRet = VerifyFileSignature (szModuleFile, lpszCmdLine);
        if (ERROR_BAD_ARGUMENTS != uiRet)
            goto CleanUp;
    }
    
    if (ERROR_BAD_ARGUMENTS == uiRet || emHelp == emExecMode)
    {
        DisplayUsage(hInst, NULL, szAppTitle);
        goto CleanUp;
    }
    
    //
    // NOTE:
    // Delay handling admin. installs until we have determined if we are
    // patching an existing install or if we are doing a default install.
    //
 
    // initialize our UI object with desktop as parent
    DownloadUI.Initialize(hInst, /* hwndParent = */ 0, szAppTitle);

    // Check if we are installing on an OS that supports Windows Installer 3.0
    fOSSupported = IsOSSupported();
    if(!fOSSupported)
    {
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_OS_NOT_SUPPORTED);
        uiRet = ERROR_INSTALL_FAILURE;
        goto CleanUp;
    }
    HANDLE hMutex = 0;

    // only run one instance at a time
    if (AlreadyInProgress(hMutex))
    {
        // silently return - correct return code ?
		uiRet = ERROR_INSTALL_ALREADY_RUNNING;
		goto CleanUp;
    }
    
    // determine operation, default (if not present) is INSTALL
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_OPERATION, &szOperation, dwOperationSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    if (ERROR_SUCCESS != uiRet)
    {
        // set operation to default which is install
        if (szOperation)
            delete [] szOperation;
        szOperation = new char[lstrlen(szDefaultOperation) + 1];
        if (!szOperation)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        if (FAILED(StringCchCopy(szOperation, lstrlen(szDefaultOperation) + 1, szDefaultOperation)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
    }

    // obtain name of product
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PRODUCTNAME, &szProductName, dwProductNameSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    if (ERROR_SUCCESS != uiRet)
    {
        // use default
        if (szProductName)
            delete [] szProductName;
        szProductName = new char[MAX_STR_CAPTION];
        if (!szProductName)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        WIN::LoadString(hInst, IDS_DEFAULT_PRODUCT, szProductName, MAX_STR_CAPTION);
    }

    // set banner text
    WIN::LoadString(hInst, IDS_BANNER_TEXT, szText, MAX_STR_CAPTION);
    StringCchPrintf(szBanner, sizeof(szBanner), szText, szProductName);
    if (irmCancel == DownloadUI.SetBannerText(szBanner))
    {
        ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        uiRet = ERROR_INSTALL_USEREXIT;
        goto CleanUp;
    }

    // Determine if this is a patch or a normal install.
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_DATABASE, &szMsiFile, dwMsiFileSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        // look for patch
        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PATCH, &szMsiFile, dwMsiFileSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS != uiRet)
        {
            PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_DATABASE);
            goto CleanUp;
        }

        fPatch = true;
    }
    
    //
    // If we are here, this is either an admin. install or a default install.
    // File signature verification, help and other invalid parameters have
    // already been taken care of above.
    //
    if (emAdminInstall == emExecMode)
    {
        uiRet = GetAdminInstallInfo (fPatch, lpszCmdLine, &szAdminImagePath);
        if (ERROR_BAD_ARGUMENTS == uiRet)
        {
            DisplayUsage(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
    }
    
    //
    // At this point, the validation of the commandline arguments is complete
    // and we have all the information we need.
    //

    // obtain minimum required MSI version
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_MINIMUM_MSI, &szMinimumMsi, dwMinimumMsiSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_MINIMUM_MSI);
        goto CleanUp;
    }

    // make sure required Msi version is a valid value -- must be >= 150
    ulMsiMinVer = strtoul(szMinimumMsi, &szStopScan, 10);
    if (!szStopScan || (szStopScan == szMinimumMsi) || (*szStopScan != 0) || ulMsiMinVer < MINIMUM_SUPPORTED_MSI_VERSION)
    {
        // invalid minimum version string
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_VER_STR, szMinimumMsi, MINIMUM_SUPPORTED_MSI_VERSION);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }

    DebugMsg("[Resource] Minimum Msi Value = %d\n", ulMsiMinVer);

    // compare minimum required MSI version to that which is on the machine
    if (IsMsiUpgradeNecessary(ulMsiMinVer))
    {
        DebugMsg("[Info] Upgrade of Windows Installer is requested\n");

        // make sure this is admin -- must have admin priviledges to upgrade Windows Installer
        if (!IsAdmin())
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_REQUIRES_ADMIN_PRIV);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }

        // Ask the user if they want to upgrade the installer
        WIN::LoadString(hInst, IDS_ALLOW_MSI_UPDATE, szUserPrompt, MAX_STR_LENGTH);
        if (IDYES != WIN::MessageBox(DownloadUI.GetCurrentWindow(), szUserPrompt, szAppTitle, MB_YESNO|MB_ICONQUESTION))
        {
            // user decided to cancel
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATE, &szUpdate, dwUpdateSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS != uiRet)
        {
            PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_UPDATE);
            goto CleanUp;
        }            
        
        // determine if we need to download the Windows Installer update package from the web -- based on presence of UPDATELOCATION property
        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATELOCATION, &szBase, dwBaseUpdateSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS == uiRet)
        {
            // presence of UPDATELOCATION property indicates assumption of URL source
            if (ERROR_SUCCESS != (uiRet = DownloadAndUpgradeMsi(hInst, &DownloadUI, szAppTitle, szBase, szUpdate, szModuleFile, ulMsiMinVer)))
            {
                if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet)
                {
                    // successful, but must reboot at end
                    fDelayRebootReq = true;
                }
                else
                    goto CleanUp;
            }
        }
        else
        {
            // lack of UPDATELOCATION property indicates assumption of Media source
            if (ERROR_SUCCESS != (uiRet = UpgradeMsi(hInst, &DownloadUI, szAppTitle, szModuleFile, szUpdate, ulMsiMinVer)))
            {
                if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet)
                {
                    // successful, but must reboot at end
                    fDelayRebootReq = true;
                }
                else
                    goto CleanUp;
            }
        }
    }

    DebugMsg("[Info] Windows Installer has been upgraded, or was already correct version\n");

    // perform some extra authoring validation
    if (fPatch
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMajPatchOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))
    {
        // wrong operation
        DebugMsg("[Error] Operation %s is not valid for a patch\n", szOperation);
        PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }
    else if (!fPatch
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))
    {
        // wrong operation
        DebugMsg("[Error] Operation %s is not valid for a package\n", szOperation);
        PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }

    // by now we either have a MSI or a MSP
    if (CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1)
        || CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1)
        || (fPatch && CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1)))
        fQFE = true;

    // obtain base URL
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_BASEURL, &szBaseURL, dwBaseURLSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS == uiRet)
    {
        // presence of BASEURL property indicates assumption of URL source . . .

        // generate the path to the installation package == baseURL + msiFile
        //   note: msiFile is a relative path
        cchTempPath = lstrlen(szBaseURL) + lstrlen(szMsiFile) + 2; // 1 for slash, 1 for null
        szTempPath = new char[cchTempPath ];
        if (!szTempPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }
        if (FAILED(StringCchCopy(szTempPath, cchTempPath, szBaseURL)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
        // check for trailing slash on szBaseURL
        char *pch = szBaseURL + lstrlen(szBaseURL) + 1; // put at null terminator
        pch = CharPrev(szBaseURL, pch);
        if (*pch != '/')
        {
            if (FAILED(StringCchCat(szTempPath, cchTempPath, szUrlPathSep)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }        

        // canocialize the URL path
        cchInstallPath = cchTempPath*2;
        szInstallPath = new char[cchInstallPath];
        if (!szInstallPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        dwLastError = 0; // success
        if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0))
        {
            dwLastError = GetLastError();
            if (ERROR_INSUFFICIENT_BUFFER == dwLastError)
            {
                // try again
                delete [] szInstallPath;
                szInstallPath = new char[cchInstallPath];
                if (!szInstallPath)
                {
                    ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                    uiRet = ERROR_OUTOFMEMORY;
                    goto CleanUp;
                }
                dwLastError = 0; // reset to success for 2nd attempt
                if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0))
                    dwLastError = GetLastError();
            }
        }
        if (0 != dwLastError)
        {
            // error -- invalid path/Url
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            uiRet = dwLastError;
            goto CleanUp;
        }

        // set action text for download
        WIN::LoadString(hInst, IDS_DOWNLOADING_PACKAGE, szText, MAX_STR_CAPTION);
        StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile);
        if (irmCancel == DownloadUI.SetActionText(szAction))
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        // download the msi file so we can attempt a trust check -- must be local for WinVerifyTrust
        DebugMsg("[Info] Downloading msi file %s for WinVerifyTrust check\n", szInstallPath);

        szMsiCacheFile = new char[MAX_PATH];
        dwMsiCacheFileSize = MAX_PATH;
        if (!szMsiCacheFile)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        hr = WIN::URLDownloadToCacheFile(NULL, szInstallPath, szMsiCacheFile, dwMsiCacheFileSize, 0, /* IBindStatusCallback = */ &CDownloadBindStatusCallback(&DownloadUI));
        if (DownloadUI.HasUserCanceled())
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }
        if (FAILED(hr))
        {
            // error during download -- probably because file not found (or lost connection)
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath);
            uiRet = ERROR_FILE_NOT_FOUND;
            goto CleanUp;
        }

        DebugMsg("[Info] Msi file was cached to %s\n", szMsiCacheFile);

        // set action text for trust verification
        WIN::LoadString(hInst, IDS_VALIDATING_SIGNATURE, szText, MAX_STR_CAPTION);
        StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile);
        if (irmCancel == DownloadUI.SetActionText(szAction))
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        // perform trust check 
        itvEnum itv = IsPackageTrusted(szModuleFile, szMsiCacheFile, DownloadUI.GetCurrentWindow());
        if (itvWintrustNotOnMachine == itv)
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NO_WINTRUST);
            uiRet = ERROR_CALL_NOT_IMPLEMENTED;
            goto CleanUp;
        }
        else if (itvUnTrusted == itv)
        {
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_UNTRUSTED, szInstallPath);
            uiRet = HRESULT_CODE(TRUST_E_SUBJECT_NOT_TRUSTED);
            goto CleanUp;
        }
    }
    else
    {
        // lack of BASEURL property indicates assumption of Media source

        // generate the path to the Msi file =  szModuleFile + msiFile
        //   note: msiFile is a relative path
        cchTempPath = lstrlen(szModuleFile) + lstrlen(szMsiFile) + 2; // 1 for null terminator, 1 for back slash
        szTempPath = new char[cchTempPath];
        if (!szTempPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        // find 'setup.exe' in the path so we can remove it
        if (0 == GetFullPathName(szModuleFile, cchTempPath, szTempPath, &szFilePart))
        {
            uiRet = GetLastError();
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            goto CleanUp;
        }
        if (szFilePart)
            *szFilePart = '\0';

        if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
        
        cchInstallPath = 2*cchTempPath;
        szInstallPath = new char[cchInstallPath];
        if (!szInstallPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        // normalize the path
        cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart);
        if (cchReturn > cchInstallPath)
        {
            // try again, with larger buffer
            delete [] szInstallPath;
            cchInstallPath = cchReturn;
            szInstallPath = new char[cchInstallPath];
            if (!szInstallPath)
            {
                ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                uiRet = ERROR_OUTOFMEMORY;
                goto CleanUp;
            }
            cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart);
        }
        if (0 == cchReturn)
        {
            // error -- invalid path
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            uiRet = dwLastError;
            goto CleanUp;
        }

        // no download is necessary -- but we can check for the file's existence
        DWORD dwFileAttrib = GetFileAttributes(szInstallPath);
        if (0xFFFFFFFF == dwFileAttrib)
        {
            // package is missing
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath);
            uiRet = ERROR_FILE_NOT_FOUND;
            goto CleanUp;
        }
    }

    //
    // good to go -- terminate our UI and let the Windows Installer take over
    //

    // retrieve the optional command line PROPERTY = VALUE strings if available
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PROPERTIES, &szProperties, dwPropertiesSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        uiRet = ERROR_OUTOFMEMORY;
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        // PROPERTY=VALUE pairs not specified
        if (szProperties)
            delete [] szProperties;
        szProperties = NULL;
    }

    DownloadUI.Terminate();

    //
    // perform install 
    //

    hMsi = LoadLibrary(MSI_DLL);
    
    if (hMsi)
    {
        pfnMsiSetInternalUI = (PFnMsiSetInternalUI)GetProcAddress(hMsi, MSIAPI_MsiSetInternalUI);
        pfnMsiInstallProduct = (PFnMsiInstallProduct)GetProcAddress(hMsi, MSIAPI_MsiInstallProduct);
        pfnMsiApplyPatch = (PFnMsiApplyPatch)GetProcAddress(hMsi, MSIAPI_MsiApplyPatch);
        pfnMsiReinstallProduct = (PFnMsiReinstallProduct)GetProcAddress(hMsi, MSIAPI_MsiReinstallProduct);
        pfnMsiQueryProductState = (PFnMsiQueryProductState)GetProcAddress(hMsi, MSIAPI_MsiQueryProductState);
        pfnMsiOpenDatabase = (PFnMsiOpenDatabase)GetProcAddress(hMsi, MSIAPI_MsiOpenDatabase);
        pfnMsiDatabaseOpenView = (PFnMsiDatabaseOpenView)GetProcAddress(hMsi, MSIAPI_MsiDatabaseOpenView);
        pfnMsiViewExecute = (PFnMsiViewExecute)GetProcAddress(hMsi, MSIAPI_MsiViewExecute);
        pfnMsiViewFetch = (PFnMsiViewFetch)GetProcAddress(hMsi, MSIAPI_MsiViewFetch);
        pfnMsiRecordGetString = (PFnMsiRecordGetString)GetProcAddress(hMsi, MSIAPI_MsiRecordGetString);
        pfnMsiCloseHandle = (PFnMsiCloseHandle)GetProcAddress(hMsi, MSIAPI_MsiCloseHandle);
    }
    if (!hMsi || !pfnMsiSetInternalUI || !pfnMsiInstallProduct || !pfnMsiApplyPatch || !pfnMsiReinstallProduct || !pfnMsiQueryProductState
        || !pfnMsiDatabaseOpenView || !pfnMsiViewExecute || !pfnMsiViewFetch || !pfnMsiRecordGetString || !pfnMsiCloseHandle)
    {
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_FAILED_TO_UPGRADE_MSI);
        uiRet = ERROR_INSTALL_FAILURE;
        goto CleanUp;
    }

    DebugMsg("[Info] Setting Internal UI level to FULL...\n");
    pfnMsiSetInternalUI(INSTALLUILEVEL_FULL, 0);

    if (!fPatch)
    {
        // performing install or reinstall/recache
        DebugMsg("[Info] Calling MsiInstallProduct with szInstallPath = %s", szInstallPath); 
        DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

        // default operation for a package is INSTALL

        if (fQFE)
        {
            // check to see if this product is already installed
            if (ERROR_SUCCESS == pfnMsiOpenDatabase(szMsiCacheFile ? szMsiCacheFile : szInstallPath, MSIDBOPEN_READONLY, &hDatabase)
                && ERROR_SUCCESS == pfnMsiDatabaseOpenView(hDatabase, sqlProductCode, &hView)
                && ERROR_SUCCESS == pfnMsiViewExecute(hView, 0)
                && ERROR_SUCCESS == pfnMsiViewFetch(hView, &hRec)
                && ERROR_SUCCESS == pfnMsiRecordGetString(hRec, 1, szProductCode, &dwProductCodeSize))
            {
                isProduct = pfnMsiQueryProductState(szProductCode);
                DebugMsg("[Info] MsiQueryProductState returned %d\n", isProduct);
                if (INSTALLSTATE_ADVERTISED != isProduct && INSTALLSTATE_DEFAULT != isProduct)
                {
                    // product is unknown, so this will be a first time install
                    DebugMsg("[Info] The product code '%s' is unknown. Will use first time install logic...\n", szProductCode);
                    fQFE = false;
                }
                else
                {
                    // product is known, use QFE syntax
                    DebugMsg("[Info] The product code '%s' is known. Will use QFE recache and reinstall upgrade logic...\n", szProductCode);
                }
            }
            else
            {
                // some failure occurred when processing the product code, so treat as non-QFE
                DebugMsg("[Info] Unable to process product code. Will treat as first time install...\n");
                fQFE = false;
            }
            if (hDatabase)
                pfnMsiCloseHandle(hDatabase);
            if (hView)
                pfnMsiCloseHandle(hView);
            if (hRec)
                pfnMsiCloseHandle(hRec);
        }
        
        //
        // Set up the properties to be passed into MSIInstallProduct
        //
        if (fQFE && !szProperties)
            cchInstProperties = lstrlen (szDefaultInstallUpdCommandLine);
        else if (szProperties)
            cchInstProperties = lstrlen (szProperties);
        if (emAdminInstall == emExecMode)
            cchInstProperties += lstrlen (szAdminInstallProperty);
        
        szInstProperties = new char[cchInstProperties + 1];
        if (! szInstProperties)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }
        
        if (fQFE && !szProperties)
        {
            if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szDefaultInstallUpdCommandLine)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        else if (szProperties)
        {
            if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szProperties)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        else
            szInstProperties[0] = '\0';
        if (emAdminInstall == emExecMode)
        {
            if (FAILED(StringCchCat(szInstProperties, cchInstProperties + 1, szAdminInstallProperty)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }

        uiRet = pfnMsiInstallProduct(szInstallPath, szInstProperties);
        if (ERROR_SUCCESS != uiRet)
        {
            // attempt to display an error message stored in msi.dll
            PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet);
        }

        DebugMsg("[Info] MsiInstallProduct returned %d\n", uiRet);
    }
    else
    {
        // default Operation for a patch is MINPATCH

        // if szProperties is NULL, use our default value for QFE patches
        if (!szProperties && fQFE)
        {
            DebugMsg("[Info] Patch is a MINPATCH (small or minor update patch) so using default command line '%s'\n", szDefaultMinPatchCommandLine);

            szProperties = new char[lstrlen(szDefaultMinPatchCommandLine) + 1];
            if (!szProperties)
            {
                ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                uiRet = ERROR_OUTOFMEMORY;
                goto CleanUp;
            }
            if (FAILED(StringCchCopy(szProperties, lstrlen(szDefaultMinPatchCommandLine) + 1, szDefaultMinPatchCommandLine)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }

        if (emAdminInstall == emExecMode)
        {
            // performing a patch
            DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szMsiCacheFile);
            DebugMsg(" and szInstallPackage = %s and eInstallType = INSTALLTYPE_NETWORK_IMAGE", szAdminImagePath);
            DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

            uiRet = pfnMsiApplyPatch(szMsiCacheFile, szAdminImagePath, INSTALLTYPE_NETWORK_IMAGE, szProperties);
        }
        else
        {
            // performing a patch
            DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szInstallPath);
            DebugMsg(" and szInstallPackage = {null} and eInstallType = INSTALLTYPE_DEFAULT");
            DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

            uiRet = pfnMsiApplyPatch(szInstallPath, NULL, INSTALLTYPE_DEFAULT, szProperties);
        }
        if (ERROR_SUCCESS != uiRet)
        {
            // attempt to display an error message stored in msi.dll
            PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet);
        }

        DebugMsg("[Info] MsiApplyPatch returned %d\n", uiRet);
    }

    
CleanUp:

    if (szMsiFile)
        delete [] szMsiFile;
    if (szBaseURL)
        delete [] szBaseURL;
    if (szInstallPath)
        delete [] szInstallPath;
    if (szMsiCacheFile)
    {
        WIN::DeleteUrlCacheEntry(szMsiCacheFile);
        delete [] szMsiCacheFile;
    }
    if (szProductName)
        delete [] szProductName;
    if (szMinimumMsi)
        delete [] szMinimumMsi;
    if (szProperties)
        delete [] szProperties;
    if (szTempPath)
        delete [] szTempPath;
    if (szBase)
        delete [] szBase;
    if (szUpdate)
        delete [] szUpdate;
    if (szRegisteredMsiFolder)
        delete [] szRegisteredMsiFolder;
    if (szMsiDllLocation)
        delete [] szMsiDllLocation;
    if (szOperation)
        delete [] szOperation;

    if(hMutex)
        CloseHandle(hMutex);

    if (hMsi)
        FreeLibrary(hMsi);

    DebugMsg("[Info] Setup exit code is %d\n", uiRet);

    if (fDelayRebootReq)
    {
        // need to reboot machine for updating Windows Installer
        WIN::LoadString(hInst, IDS_REBOOT_REQUIRED, szAction, MAX_STR_LENGTH);
        if (IDYES == MessageBox(NULL, szAction, szAppTitle, MB_YESNO|MB_ICONQUESTION))
        {
            // must first aquire system shutdown privileges on NT/Win2K
            AcquireShutdownPrivilege();
            // initiate system shutdown for reboot
            WIN::ExitWindowsEx(EWX_REBOOT, PCLEANUI | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION);
        }
    }

    return uiRet;
}