Ejemplo n.º 1
0
	void readFile()
	{
		int rsize = 0;
		if ((strnicmp( filename.c_str(), "cdrom0:", strlen("cdromN:")) == 0) ||
			(strnicmp( filename.c_str(), "cdrom1:", strlen("cdromN:")) == 0))
		{
			int fi;
			fi = CDVDFS_open(filename.c_str() + strlen("cdromN:"), 1);//RDONLY
			if (fi < 0)
				throw Exception::FileNotFound( filename );
			CDVDFS_lseek( fi, 0, SEEK_SET );
			rsize = CDVDFS_read( fi, (char*)data.GetPtr(), data.GetSizeInBytes() );
			CDVDFS_close( fi );
		}
		else
		{
			FILE *f;

			f = fopen( filename.c_str(), "rb" );
			if( f == NULL )
				Exception::FileNotFound( filename );
			fseek( f, 0, SEEK_SET );
			rsize = fread( data.GetPtr(), 1, data.GetSizeInBytes(), f );
			fclose( f );
		}

		if( rsize < data.GetSizeInBytes() )
			throw Exception::EndOfStream( filename );
	}
Ejemplo n.º 2
0
	void loadProgramHeaders()
	{
		if ( proghead == NULL )
			return;

		for( int i = 0 ; i < header.e_phnum ; i++ )
		{
			ELF_LOG( "Elf32 Program Header\n" );	
			ELF_LOG( "type:      " );
			
			switch ( proghead[ i ].p_type ) {
				default:
					ELF_LOG( "unknown %x", (int)proghead[ i ].p_type );
				break;

				case 0x1:
				{
					ELF_LOG("load");
					const uint elfsize = data.GetLength();

					if (proghead[ i ].p_offset < elfsize) {
						int size;

						if ((proghead[ i ].p_filesz + proghead[ i ].p_offset) > elfsize)
							size = elfsize - proghead[ i ].p_offset;
						else
							size = proghead[ i ].p_filesz;

						if( proghead[ i ].p_vaddr != proghead[ i ].p_paddr )
							Console::Notice( "ElfProgram different load addrs: paddr=0x%8.8x, vaddr=0x%8.8x", params
								proghead[ i ].p_paddr, proghead[ i ].p_vaddr);

						// used to be paddr
						memcpy(
							&PS2MEM_BASE[proghead[ i ].p_vaddr & 0x1ffffff],
							data.GetPtr(proghead[ i ].p_offset), size
						);

						ELF_LOG("\t*LOADED*");
					}
				}
				break;
			}
			
			ELF_LOG("\n");
			ELF_LOG("offset:    %08x\n",(int)proghead[i].p_offset);
			ELF_LOG("vaddr:     %08x\n",(int)proghead[i].p_vaddr);
			ELF_LOG("paddr:     %08x\n",proghead[i].p_paddr);
			ELF_LOG("file size: %08x\n",proghead[i].p_filesz);
			ELF_LOG("mem size:  %08x\n",proghead[i].p_memsz);
			ELF_LOG("flags:     %08x\n",proghead[i].p_flags);
			ELF_LOG("palign:    %08x\n",proghead[i].p_align);
			ELF_LOG("\n");
			
		}
	}
Ejemplo n.º 3
0
	u32 GetCRC() const
	{
		u32 CRC = 0;

		const  u32* srcdata = (u32*)data.GetPtr();
		for(u32 i=data.GetSizeInBytes()/4; i; --i, ++srcdata)
			CRC ^= *srcdata;

		return CRC;
	}
Ejemplo n.º 4
0
/**
 * List machine groups.
 *
 * @returns See produceList.
 * @param   pVirtualBox         Reference to the IVirtualBox smart pointer.
 */
static HRESULT listGroups(const ComPtr<IVirtualBox> &pVirtualBox)
{
    SafeArray<BSTR> groups;
    CHECK_ERROR2_RET(pVirtualBox, COMGETTER(MachineGroups)(ComSafeArrayAsOutParam(groups)), hrcCheck);

    for (size_t i = 0; i < groups.size(); i++)
    {
        RTPrintf("\"%ls\"\n", groups[i]);
    }
    return S_OK;
}
Ejemplo n.º 5
0
	Void SafeArray::MoveFrom(SafeArray& other)
	{
		if (this != &other)
		{
			Attach(other.Detach());
		}
	}
Ejemplo n.º 6
0
s32 FileMemoryCard::Save( uint slot, const u8 *src, u32 adr, int size )
{
	wxFFile& mcfp( m_file[slot] );

	if( !mcfp.IsOpened() )
	{
		DevCon.Error( "(FileMcd) Ignoring attempted save/write to disabled slot." );
		return 1;
	}

	if(m_ispsx[slot])
	{
		m_currentdata.MakeRoomFor( size );
		for (int i=0; i<size; i++) m_currentdata[i] = src[i];
	}
	else
	{
		if( !Seek(mcfp, adr) ) return 0;
		m_currentdata.MakeRoomFor( size );
		mcfp.Read( m_currentdata.GetPtr(), size);
		

		for (int i=0; i<size; i++)
		{
			if ((m_currentdata[i] & src[i]) != src[i])
				Console.Warning("(FileMcd) Warning: writing to uncleared data. (%d) [%08X]", slot, adr);
			m_currentdata[i] &= src[i];
		}

		// Checksumness
		{
			if(adr == m_chkaddr) 
				Console.Warning("(FileMcd) Warning: checksum sector overwritten. (%d)", slot);

			u64 *pdata = (u64*)&m_currentdata[0];
			u32 loops = size / 8;

			for(u32 i = 0; i < loops; i++)
				m_chksum[slot] ^= pdata[i];
		}
	}

	if( !Seek(mcfp, adr) ) return 0;
	return mcfp.Write( m_currentdata.GetPtr(), size ) != 0;
}
Ejemplo n.º 7
0
int main() {
    SafeArray arrs[] = {SafeArray(5), SafeArray(10), SafeArray(15)};

    for(int i = 0; i < 3; i++) {
        SafeArray *safeArray = arrs + i;
        for(int j = 0; j < safeArray->length; j++) {
            safeArray->set(j, (j + 1) * 10);
        }
    }

    for(int i = 0; i < 3; i++) {
        SafeArray *safeArray = arrs + i;
        for(int j = 0; j < safeArray->length; j++) {
            cout << safeArray->get(j) << " ";
        }
        cout << endl;
    }

    return 0; 
}
Ejemplo n.º 8
0
	HRESULT ExecuteScript(const wchar_t* scriptPath, const vector<wstring>& arguments)
	{
		// Transfer all arguments to CLR
		//
		SafeArray safeArray;
		bstr_t bstrScriptPath = scriptPath;

		safeArray.CreateVector(VT_BSTR, 0, (ULONG)arguments.size());
		for (size_t i = 0; i < arguments.size(); i++)
		{
			// Intentionally allocating string because SafeArray will automatically dispose of it.
			//
			safeArray.PutElement((LONG)i, SysAllocString(arguments[i].c_str()));
		}

		// Execute script function
		//
		CHECKCOM(instance->ExecuteScript(bstrScriptPath, safeArray));
		return S_OK;
	}
Ejemplo n.º 9
0
int main()
{
	SafeArray safe;
	int num;
	cout << "enter the number end with -1" << endl;
	while (1)
	{
		cin >> num;
		if (num < 0)
		{		cout << "enter over" << endl;
		break;
		}
		safe.setdate(num);
	}
	for (int i = 0; i < safe.getsize(); i++)
	{
		cout << safe.getdate(i) << endl;
	}
	system("pause");
	return 0;
}
int handleGetExtraData(HandlerArg *a)
{
    HRESULT rc = S_OK;

    if (a->argc != 2)
        return errorSyntax(USAGE_GETEXTRADATA, "Incorrect number of parameters");

    /* global data? */
    if (!strcmp(a->argv[0], "global"))
    {
        /* enumeration? */
        if (!strcmp(a->argv[1], "enumerate"))
        {
            SafeArray<BSTR> aKeys;
            CHECK_ERROR(a->virtualBox, GetExtraDataKeys(ComSafeArrayAsOutParam(aKeys)));

            for (size_t i = 0;
                 i < aKeys.size();
                 ++i)
            {
                Bstr bstrKey(aKeys[i]);
                Bstr bstrValue;
                CHECK_ERROR(a->virtualBox, GetExtraData(bstrKey.raw(),
                                                        bstrValue.asOutParam()));

                RTPrintf("Key: %ls, Value: %ls\n", bstrKey.raw(), bstrValue.raw());
            }
        }
        else
        {
            Bstr value;
            CHECK_ERROR(a->virtualBox, GetExtraData(Bstr(a->argv[1]).raw(),
                                                    value.asOutParam()));
            if (!value.isEmpty())
                RTPrintf("Value: %ls\n", value.raw());
            else
                RTPrintf("No value set!\n");
        }
    }
    else
    {
        ComPtr<IMachine> machine;
        CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
                                               machine.asOutParam()));
        if (machine)
        {
            /* enumeration? */
            if (!strcmp(a->argv[1], "enumerate"))
            {
                SafeArray<BSTR> aKeys;
                CHECK_ERROR(machine, GetExtraDataKeys(ComSafeArrayAsOutParam(aKeys)));

                for (size_t i = 0;
                    i < aKeys.size();
                    ++i)
                {
                    Bstr bstrKey(aKeys[i]);
                    Bstr bstrValue;
                    CHECK_ERROR(machine, GetExtraData(bstrKey.raw(),
                                                      bstrValue.asOutParam()));

                    RTPrintf("Key: %ls, Value: %ls\n", bstrKey.raw(), bstrValue.raw());
                }
            }
            else
            {
                Bstr value;
                CHECK_ERROR(machine, GetExtraData(Bstr(a->argv[1]).raw(),
                                                  value.asOutParam()));
                if (!value.isEmpty())
                    RTPrintf("Value: %ls\n", value.raw());
                else
                    RTPrintf("No value set!\n");
            }
        }
    }
    return SUCCEEDED(rc) ? 0 : 1;
}
Ejemplo n.º 11
0
s32 FileMemoryCard::Save( uint slot, const u8 *src, u32 adr, int size )
{
	wxFFile& mcfp( m_file[slot] );

	if( !mcfp.IsOpened() )
	{
		DevCon.Error( "(FileMcd) Ignoring attempted save/write to disabled slot." );
		return 1;
	}

	if(m_ispsx[slot])
	{
		m_currentdata.MakeRoomFor( size );
		for (int i=0; i<size; i++) m_currentdata[i] = src[i];
	}
	else
	{
		if( !Seek(mcfp, adr) ) return 0;
		m_currentdata.MakeRoomFor( size );
		mcfp.Read( m_currentdata.GetPtr(), size);
		

		for (int i=0; i<size; i++)
		{
			if ((m_currentdata[i] & src[i]) != src[i])
				Console.Warning("(FileMcd) Warning: writing to uncleared data. (%d) [%08X]", slot, adr);
			m_currentdata[i] &= src[i];
		}

		// Checksumness
		{
			if(adr == m_chkaddr) 
				Console.Warning("(FileMcd) Warning: checksum sector overwritten. (%d)", slot);

			u64 *pdata = (u64*)&m_currentdata[0];
			u32 loops = size / 8;

			for(u32 i = 0; i < loops; i++)
				m_chksum[slot] ^= pdata[i];
		}
	}

	if( !Seek(mcfp, adr) ) return 0;

	int status = mcfp.Write( m_currentdata.GetPtr(), size );

	if( status ) {
		static auto last = std::chrono::time_point<std::chrono::system_clock>();

		std::chrono::duration<float> elapsed = std::chrono::system_clock::now() - last;
		if(elapsed > std::chrono::seconds(5)) {
			wxString name, ext;
			wxFileName::SplitPath(m_file[slot].GetName(), NULL, NULL, &name, &ext);
			OSDlog( Color_StrongYellow, false, "Memory Card %s written.", (const char *)(name + "." + ext).c_str() );
			last = std::chrono::system_clock::now();
		}
		return 1;
	}

	return 0;
}
Ejemplo n.º 12
0
int handleModifyHardDisk(HandlerArg *a)
{
    HRESULT rc;
    int vrc;
    ComPtr<IMedium> hardDisk;
    MediumType_T DiskType;
    bool AutoReset = false;
    SafeArray<BSTR> mediumPropNames;
    SafeArray<BSTR> mediumPropValues;
    bool fModifyDiskType = false;
    bool fModifyAutoReset = false;
    bool fModifyProperties = false;
    bool fModifyCompact = false;
    bool fModifyResize = false;
    uint64_t cbResize = 0;
    const char *FilenameOrUuid = NULL;

    int c;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    // start at 0 because main() has hacked both the argc and argv given to us
    RTGetOptInit(&GetState, a->argc, a->argv, g_aModifyHardDiskOptions, RT_ELEMENTS(g_aModifyHardDiskOptions),
                 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
    while ((c = RTGetOpt(&GetState, &ValueUnion)))
    {
        switch (c)
        {
            case 't':   // --type
                vrc = parseDiskType(ValueUnion.psz, &DiskType);
                if (RT_FAILURE(vrc))
                    return errorArgument("Invalid hard disk type '%s'", ValueUnion.psz);
                fModifyDiskType = true;
                break;

            case 'z':   // --autoreset
                vrc = parseBool(ValueUnion.psz, &AutoReset);
                if (RT_FAILURE(vrc))
                    return errorArgument("Invalid autoreset parameter '%s'", ValueUnion.psz);
                fModifyAutoReset = true;
                break;

            case 'p':   // --property
            {
                /* Parse 'name=value' */
                char *pszProperty = RTStrDup(ValueUnion.psz);
                if (pszProperty)
                {
                    char *pDelimiter = strchr(pszProperty, '=');
                    if (pDelimiter)
                    {
                        *pDelimiter = '\0';

                        Bstr bstrName(pszProperty);
                        Bstr bstrValue(&pDelimiter[1]);
                        bstrName.detachTo(mediumPropNames.appendedRaw());
                        bstrValue.detachTo(mediumPropValues.appendedRaw());
                        fModifyProperties = true;
                    }
                    else
                    {
                        errorArgument("Invalid --property argument '%s'", ValueUnion.psz);
                        rc = E_FAIL;
                    }
                    RTStrFree(pszProperty);
                }
                else
                {
                    RTStrmPrintf(g_pStdErr, "Error: Failed to allocate memory for medium property '%s'\n", ValueUnion.psz);
                    rc = E_FAIL;
                }
                break;
            }

            case 'c':   // --compact
                fModifyCompact = true;
                break;

            case 'r':   // --resize
                cbResize = ValueUnion.u64 * _1M;
                fModifyResize = true;
                break;

            case 'R':   // --resizebyte
                cbResize = ValueUnion.u64;
                fModifyResize = true;
                break;

            case VINF_GETOPT_NOT_OPTION:
                if (!FilenameOrUuid)
                    FilenameOrUuid = ValueUnion.psz;
                else
                    return errorSyntax(USAGE_MODIFYHD, "Invalid parameter '%s'", ValueUnion.psz);
                break;

            default:
                if (c > 0)
                {
                    if (RT_C_IS_PRINT(c))
                        return errorSyntax(USAGE_MODIFYHD, "Invalid option -%c", c);
                    else
                        return errorSyntax(USAGE_MODIFYHD, "Invalid option case %i", c);
                }
                else if (c == VERR_GETOPT_UNKNOWN_OPTION)
                    return errorSyntax(USAGE_MODIFYHD, "unknown option: %s\n", ValueUnion.psz);
                else if (ValueUnion.pDef)
                    return errorSyntax(USAGE_MODIFYHD, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
                else
                    return errorSyntax(USAGE_MODIFYHD, "error: %Rrs", c);
        }
    }

    if (!FilenameOrUuid)
        return errorSyntax(USAGE_MODIFYHD, "Disk name or UUID required");

    if (!fModifyDiskType && !fModifyAutoReset && !fModifyProperties && !fModifyCompact && !fModifyResize)
        return errorSyntax(USAGE_MODIFYHD, "No operation specified");

    /* Always open the medium if necessary, there is no other way. */
    rc = openMedium(a, FilenameOrUuid, DeviceType_HardDisk,
                    AccessMode_ReadWrite, hardDisk,
                    false /* fForceNewUuidOnOpen */, false /* fSilent */);
    if (FAILED(rc))
        return 1;
    if (hardDisk.isNull())
    {
        RTMsgError("Invalid hard disk reference, avoiding crash");
        return 1;
    }

    if (fModifyDiskType)
    {
        MediumType_T hddType;
        CHECK_ERROR(hardDisk, COMGETTER(Type)(&hddType));

        if (hddType != DiskType)
            CHECK_ERROR(hardDisk, COMSETTER(Type)(DiskType));
    }

    if (fModifyAutoReset)
    {
        CHECK_ERROR(hardDisk, COMSETTER(AutoReset)(AutoReset));
    }

    if (fModifyProperties)
    {
        CHECK_ERROR(hardDisk, SetProperties(ComSafeArrayAsInParam(mediumPropNames), ComSafeArrayAsInParam(mediumPropValues)));
    }

    if (fModifyCompact)
    {
        ComPtr<IProgress> progress;
        CHECK_ERROR(hardDisk, Compact(progress.asOutParam()));
        if (SUCCEEDED(rc))
            rc = showProgress(progress);
        if (FAILED(rc))
        {
            if (rc == E_NOTIMPL)
                RTMsgError("Compact hard disk operation is not implemented!");
            else if (rc == VBOX_E_NOT_SUPPORTED)
                RTMsgError("Compact hard disk operation for this format is not implemented yet!");
            else if (!progress.isNull())
                CHECK_PROGRESS_ERROR(progress, ("Failed to compact hard disk"));
            else
                RTMsgError("Failed to compact hard disk!");
        }
    }

    if (fModifyResize)
    {
        ComPtr<IProgress> progress;
        CHECK_ERROR(hardDisk, Resize(cbResize, progress.asOutParam()));
        if (SUCCEEDED(rc))
            rc = showProgress(progress);
        if (FAILED(rc))
        {
            if (rc == E_NOTIMPL)
                RTMsgError("Resize hard disk operation is not implemented!");
            else if (rc == VBOX_E_NOT_SUPPORTED)
                RTMsgError("Resize hard disk operation for this format is not implemented yet!");
            else
                CHECK_PROGRESS_ERROR(progress, ("Failed to resize hard disk"));
        }
    }

    return SUCCEEDED(rc) ? 0 : 1;
}
Ejemplo n.º 13
0
	HRESULT Initialize(const wchar_t* csDebugScriptUI)
	{
		// We should figure out needed runtime version
		//
		CAutoComPtr<ICLRMetaHostPolicy> pClrHostPolicy;

		CHECKCOM(CLRCreateInstance(
			CLSID_CLRMetaHostPolicy,
			IID_ICLRMetaHostPolicy,
			(LPVOID*)&pClrHostPolicy));

		wchar_t queriedRuntimeVersion[100] = { 0 };
		DWORD length = sizeof(queriedRuntimeVersion) / sizeof(wchar_t);

		CHECKCOM(pClrHostPolicy->GetRequestedRuntime(
			METAHOST_POLICY_HIGHCOMPAT,
			csDebugScriptUI,
			nullptr,
			queriedRuntimeVersion,
			&length,
			nullptr,
			nullptr,
			nullptr,
			IID_PPV_ARGS(&runtimeInfo)));

		// Set custom memory manager and start CLR
		//
		CHECKCOM(runtimeInfo->BindAsLegacyV2Runtime());
		//CHECKCOM(runtimeInfo->SetDefaultStartupFlags(clrStartupFlags, nullptr));
		CHECKCOM(runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&clrRuntimeHost)));
		CHECKCOM(clrRuntimeHost->Start());

		// Create a new AppDomain that will contain application configuration.
		//
		CAutoComPtr<IUnknown> appDomainSetupThunk;
		CAutoComPtr<IAppDomainSetup> appDomainSetup;
		CAutoComPtr<IUnknown> appDomainThunk;

		CHECKCOM(runtimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&corRuntimeHost)));
		CHECKCOM(corRuntimeHost->CreateDomainSetup(&appDomainSetupThunk));
		CHECKCOM(appDomainSetupThunk->QueryInterface(IID_PPV_ARGS(&appDomainSetup)));
		CHECKCOM(corRuntimeHost->CreateDomainEx(L"MyDomain", appDomainSetup, nullptr, &appDomainThunk));
		CHECKCOM(appDomainThunk->QueryInterface(IID_PPV_ARGS(&appDomain)));

		// Load our assembly
		//
		CAutoComPtr<_Assembly> mscorlibAssembly;
		CAutoComPtr<_Type> reflectionAssemblyType;
		SafeArray loadFromArguments;
		variant_t loadFromResult;
		variant_t arg1(csDebugScriptUI);

		loadFromArguments.CreateVector(VT_VARIANT, 0, 1);
		loadFromArguments.PutElement(0, &arg1);

		CHECKCOM(GetAssemblyFromAppDomain(appDomain, L"mscorlib", &mscorlibAssembly));
		CHECKCOM(mscorlibAssembly->GetType_2(bstr_t(L"System.Reflection.Assembly"), &reflectionAssemblyType));
		CHECKCOM(reflectionAssemblyType->InvokeMember_3(bstr_t(L"LoadFrom"), (BindingFlags)(BindingFlags_InvokeMethod | BindingFlags_Public | BindingFlags_Static), nullptr, variant_t(), loadFromArguments, &loadFromResult));

		// Create our extension CLR instance
		//
		CAutoComPtr<_Assembly> assembly = (_Assembly*)(IDispatch*)loadFromResult;
		variant_t variant;

		CHECKCOM(assembly->CreateInstance_2(bstr_t(L"CsDebugScript.Executor"), true, &variant));
		CHECKCOM(variant.punkVal->QueryInterface(&instance));
		return S_OK;
	}
Ejemplo n.º 14
0
memSavingState::memSavingState( SafeArray<u8>& save_to ) : memBaseStateInfo( save_to, _("Saving state to: ") )
{
	save_to.ChunkSize = ReallocThreshold;
	save_to.MakeRoomFor( MemoryBaseAllocSize );
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    /* Init the runtime without loading the support driver. */
    RTR3InitExe(argc, &argv, 0);

    RTTEST hTest;
    RTEXITCODE rcExit = RTTestInitAndCreate("tstMediumLock", &hTest);
    if (rcExit)
        return rcExit;
    RTTestBanner(hTest);

    bool fComInit = false;
    ComPtr<IVirtualBox> pVirtualBox;
    char szPathTemp[RTPATH_MAX] = "";
    ComPtr<IMedium> pMedium;

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Constructing temp image name");
        TEST_RT_SUCCESS(hTest, RTPathTemp(szPathTemp, sizeof(szPathTemp)), "temp directory");
        RTUUID uuid;
        RTUuidCreate(&uuid);
        char szFile[50];
        RTStrPrintf(szFile, sizeof(szFile), "%RTuuid.vdi", &uuid);
        TEST_RT_SUCCESS(hTest, RTPathAppend(szPathTemp, sizeof(szPathTemp), szFile), "concatenate image name");
    }

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Initializing COM");
        TEST_COM_SUCCESS(hTest, Initialize(), "init");
    }

    if (!RTTestSubErrorCount(hTest))
    {
        fComInit = true;

        RTTestSub(hTest, "Getting VirtualBox reference");
        TEST_COM_SUCCESS(hTest, pVirtualBox.createLocalObject(CLSID_VirtualBox), "vbox reference");
    }

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Creating temp hard disk medium");
        TEST_COM_SUCCESS(hTest, pVirtualBox->CreateMedium(Bstr("VDI").raw(), Bstr(szPathTemp).raw(), AccessMode_ReadWrite, DeviceType_HardDisk, pMedium.asOutParam()), "create medium");
        if (!pMedium.isNull())
        {
            ComPtr<IProgress> pProgress;
            SafeArray<MediumVariant_T> variant;
            variant.push_back(MediumVariant_Standard);
            TEST_COM_SUCCESS(hTest, pMedium->CreateBaseStorage(_1M, ComSafeArrayAsInParam(variant), pProgress.asOutParam()), "create base storage");
            if (!pProgress.isNull())
                TEST_COM_SUCCESS(hTest, pProgress->WaitForCompletion(30000), "waiting for completion of create");
        }
    }

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Write locks");
        ComPtr<IToken> pToken1, pToken2;

        MediumState_T mediumState = MediumState_NotCreated;
        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong medium state %d", mediumState);

        TEST_COM_SUCCESS(hTest, pMedium->LockWrite(pToken1.asOutParam()), "write lock");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting lock write state");
        if (mediumState != MediumState_LockedWrite)
            RTTestFailed(hTest, "wrong lock write medium state %d", mediumState);

        TEST_COM_FAILURE(hTest, pMedium->LockWrite(pToken2.asOutParam()), "nested write lock succeeded");
        if (!pToken2.isNull())
            RTTestFailed(hTest, "pToken2 is not null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting after nested lock write state");
        if (mediumState != MediumState_LockedWrite)
            RTTestFailed(hTest, "wrong after nested lock write medium state %d", mediumState);

        if (!pToken1.isNull())
            TEST_COM_SUCCESS(hTest, pToken1->Abandon(), "write unlock");
        else
            RTTestFailed(hTest, "pToken1 is null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting unlock write state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong unlock write medium state %d", mediumState);
    }

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Read locks");
        ComPtr<IToken> pToken1, pToken2;

        MediumState_T mediumState = MediumState_NotCreated;
        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong medium state %d", mediumState);

        TEST_COM_SUCCESS(hTest, pMedium->LockRead(pToken1.asOutParam()), "read lock");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting lock read state");
        if (mediumState != MediumState_LockedRead)
            RTTestFailed(hTest, "wrong lock read medium state %d", mediumState);

        TEST_COM_SUCCESS(hTest, pMedium->LockRead(pToken2.asOutParam()), "nested read lock failed");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting after nested lock read state");
        if (mediumState != MediumState_LockedRead)
            RTTestFailed(hTest, "wrong after nested lock read medium state %d", mediumState);

        if (!pToken2.isNull())
            TEST_COM_SUCCESS(hTest, pToken2->Abandon(), "read nested unlock");
        else
            RTTestFailed(hTest, "pToken2 is null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting after nested lock read state");
        if (mediumState != MediumState_LockedRead)
            RTTestFailed(hTest, "wrong after nested lock read medium state %d", mediumState);

        if (!pToken1.isNull())
            TEST_COM_SUCCESS(hTest, pToken1->Abandon(), "read nested unlock");
        else
            RTTestFailed(hTest, "pToken1 is null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting unlock read state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong unlock read medium state %d", mediumState);
    }

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Mixing write and read locks");
        ComPtr<IToken> pToken1, pToken2;

        MediumState_T mediumState = MediumState_NotCreated;
        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong medium state %d", mediumState);

        TEST_COM_SUCCESS(hTest, pMedium->LockWrite(pToken1.asOutParam()), "write lock");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting lock write state");
        if (mediumState != MediumState_LockedWrite)
            RTTestFailed(hTest, "wrong lock write medium state %d", mediumState);

        TEST_COM_FAILURE(hTest, pMedium->LockRead(pToken2.asOutParam()), "write+read lock succeeded");
        if (!pToken2.isNull())
            RTTestFailed(hTest, "pToken2 is not null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting after nested lock write state");
        if (mediumState != MediumState_LockedWrite)
            RTTestFailed(hTest, "wrong after nested lock write medium state %d", mediumState);

        if (!pToken1.isNull())
            TEST_COM_SUCCESS(hTest, pToken1->Abandon(), "write unlock");
        else
            RTTestFailed(hTest, "pToken1 is null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting unlock write state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong unlock write medium state %d", mediumState);
    }

    if (!RTTestSubErrorCount(hTest))
    {
        RTTestSub(hTest, "Mixing read and write locks");
        ComPtr<IToken> pToken1, pToken2;

        MediumState_T mediumState = MediumState_NotCreated;
        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong medium state %d", mediumState);

        TEST_COM_SUCCESS(hTest, pMedium->LockRead(pToken1.asOutParam()), "read lock");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting lock read state");
        if (mediumState != MediumState_LockedRead)
            RTTestFailed(hTest, "wrong lock read medium state %d", mediumState);

        TEST_COM_FAILURE(hTest, pMedium->LockWrite(pToken2.asOutParam()), "read+write lock succeeded");
        if (!pToken2.isNull())
            RTTestFailed(hTest, "pToken2 is not null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting after nested lock read state");
        if (mediumState != MediumState_LockedRead)
            RTTestFailed(hTest, "wrong after nested lock read medium state %d", mediumState);

        if (!pToken1.isNull())
            TEST_COM_SUCCESS(hTest, pToken1->Abandon(), "read unlock");
        else
            RTTestFailed(hTest, "pToken1 is null");

        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting unlock read state");
        if (mediumState != MediumState_Created)
            RTTestFailed(hTest, "wrong unlock read medium state %d", mediumState);
    }

    /* Cleanup, also part of the testcase */

    if (!pMedium.isNull())
    {
        RTTestSub(hTest, "Closing medium");
        MediumState_T mediumState = MediumState_NotCreated;
        TEST_COM_SUCCESS(hTest, pMedium->COMGETTER(State)(&mediumState), "getting state");
        if (mediumState == MediumState_Created)
        {
            ComPtr<IProgress> pProgress;
            TEST_COM_SUCCESS(hTest, pMedium->DeleteStorage(pProgress.asOutParam()), "deleting storage");
            if (!pProgress.isNull())
                TEST_COM_SUCCESS(hTest, pProgress->WaitForCompletion(30000), "waiting for completion of delete");
        }
        TEST_COM_SUCCESS(hTest, pMedium->Close(), "closing");
        pMedium.setNull();
    }

    pVirtualBox.setNull();

    /* Make sure that there are no object references alive here, XPCOM does
     * a very bad job at cleaning up such leftovers, spitting out warning
     * messages in a debug build. */

    if (fComInit)
    {
        RTTestIPrintf(RTTESTLVL_DEBUG, "Shutting down COM...\n");
        Shutdown();
    }

    /*
     * Summary.
     */
    return RTTestSummaryAndDestroy(hTest);
}
Ejemplo n.º 16
0
HRESULT Guest::taskCopyFileFromGuest(GuestTask *aTask)
{
    LogFlowFuncEnter();

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    /*
     * Do *not* take a write lock here since we don't (and won't)
     * touch any class-specific data (of IGuest) here - only the member functions
     * which get called here can do that.
     */

    HRESULT rc = S_OK;

    try
    {
        ComObjPtr<Guest> pGuest = aTask->pGuest;

        /* Does our source file exist? */
        BOOL fFileExists;
        rc = pGuest->FileExists(Bstr(aTask->strSource).raw(),
                                Bstr(aTask->strUserName).raw(), Bstr(aTask->strPassword).raw(),
                                &fFileExists);
        if (SUCCEEDED(rc))
        {
            if (!fFileExists)
                rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress,
                                                     Guest::tr("Source file \"%s\" does not exist, or is not a file"),
                                                     aTask->strSource.c_str());
        }
        else
            rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest);

        /* Query file size to make an estimate for our progress object. */
        if (SUCCEEDED(rc))
        {
            LONG64 lFileSize;
            rc = pGuest->FileQuerySize(Bstr(aTask->strSource).raw(),
                                       Bstr(aTask->strUserName).raw(), Bstr(aTask->strPassword).raw(),
                                       &lFileSize);
            if (FAILED(rc))
                rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest);

            com::SafeArray<IN_BSTR> args;
            com::SafeArray<IN_BSTR> env;

            if (SUCCEEDED(rc))
            {
                /*
                 * Prepare tool command line.
                 */
                char szSource[RTPATH_MAX];
                if (RTStrPrintf(szSource, sizeof(szSource), "%s", aTask->strSource.c_str()) <= sizeof(szSource) - 1)
                {
                    /*
                     * Normalize path slashes, based on the detected guest.
                     */
                    Utf8Str osType = mData.mOSTypeId;
                    if (   osType.contains("Microsoft", Utf8Str::CaseInsensitive)
                        || osType.contains("Windows", Utf8Str::CaseInsensitive))
                    {
                        /* We have a Windows guest. */
                        RTPathChangeToDosSlashes(szSource, true /* Force conversion. */);
                    }
                    else /* ... or something which isn't from Redmond ... */
                    {
                        RTPathChangeToUnixSlashes(szSource, true /* Force conversion. */);
                    }

                    args.push_back(Bstr(szSource).raw()); /* Tell our cat tool which file to output. */
                }
                else
                    rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress,
                                                         Guest::tr("Error preparing command line"));
            }

            ComPtr<IProgress> execProgress;
            ULONG uPID;
            if (SUCCEEDED(rc))
            {
                LogRel(("Copying file \"%s\" to host \"%s\" (%u bytes) ...\n",
                        aTask->strSource.c_str(), aTask->strDest.c_str(), lFileSize));

                /*
                 * Okay, since we gathered all stuff we need until now to start the
                 * actual copying, start the guest part now.
                 */
                rc = pGuest->executeAndWaitForTool(Bstr(VBOXSERVICE_TOOL_CAT).raw(),
                                                   Bstr("Copying file to host").raw(),
                                                   ComSafeArrayAsInParam(args),
                                                   ComSafeArrayAsInParam(env),
                                                   Bstr(aTask->strUserName).raw(),
                                                   Bstr(aTask->strPassword).raw(),
                                                     ExecuteProcessFlag_WaitForProcessStartOnly
                                                   | ExecuteProcessFlag_WaitForStdOut,
                                                   NULL, NULL,
                                                   execProgress.asOutParam(), &uPID);
                if (FAILED(rc))
                    rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest);
            }

            if (SUCCEEDED(rc))
            {
                BOOL fCompleted = FALSE;
                BOOL fCanceled = FALSE;

                RTFILE hFileDest;
                int vrc = RTFileOpen(&hFileDest, aTask->strDest.c_str(),
                                     RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE);
                if (RT_FAILURE(vrc))
                    rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress,
                                                         Guest::tr("Unable to create/open destination file \"%s\", rc=%Rrc"),
                                                         aTask->strDest.c_str(), vrc);
                else
                {
                    size_t cbToRead = lFileSize;
                    size_t cbTransfered = 0;
                    while (   SUCCEEDED(execProgress->COMGETTER(Completed(&fCompleted)))
                           && !fCompleted)
                    {
                        SafeArray<BYTE> aOutputData;
                        rc = pGuest->GetProcessOutput(uPID, ProcessOutputFlag_None /* StdOut */,
                                                      0 /* No timeout. */,
                                                      _64K, ComSafeArrayAsOutParam(aOutputData));
                        if (SUCCEEDED(rc))
                        {
                            if (aOutputData.size())
                            {
                                vrc = RTFileWrite(hFileDest, aOutputData.raw(), aOutputData.size(), NULL /* No partial writes */);
                                if (RT_FAILURE(vrc))
                                {
                                    rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress,
                                                                         Guest::tr("Error writing to file \"%s\" (%u bytes left), rc=%Rrc"),
                                                                         aTask->strSource.c_str(), cbToRead, vrc);
                                    break;
                                }

                                Assert(cbToRead >= aOutputData.size());
                                cbToRead -= aOutputData.size();
                                cbTransfered += aOutputData.size();

                                aTask->pProgress->SetCurrentOperationProgress(cbTransfered / (lFileSize / 100.0));
                            }

                            /* Nothing read this time; try next round. */
                        }
                        else
                        {
                            rc = GuestTask::setProgressErrorInfo(rc, aTask->pProgress, pGuest);
                            break;
                        }
                    }

                    RTFileClose(hFileDest);

                    if (SUCCEEDED(rc))
                    {
                        if (   cbTransfered
                            && (cbTransfered != lFileSize))
                        {
                            /*
                             * Only bitch about an unexpected end of a file when there already
                             * was data read from that file. If this was the very first read we can
                             * be (almost) sure that this file is not meant to be read by the specified user.
                             */
                            rc = GuestTask::setProgressErrorInfo(VBOX_E_IPRT_ERROR, aTask->pProgress,
                                                                 Guest::tr("Unexpected end of file \"%s\" (%u bytes total, %u bytes transferred)"),
                                                                 aTask->strSource.c_str(), lFileSize, cbTransfered);
                        }

                        if (SUCCEEDED(rc))
                            aTask->pProgress->notifyComplete(S_OK);
                    }
                }
            }
        }
    }
    catch (HRESULT aRC)
    {
        rc = aRC;
    }

    /* Clean up */
    aTask->rc = rc;

    LogFlowFunc(("rc=%Rhrc\n", rc));
    LogFlowFuncLeave();

    return VINF_SUCCESS;
}
Ejemplo n.º 17
0
	ElfObject( const string& srcfile, uint hdrsize ) :
		filename( srcfile )
	,	data( hdrsize, "ELF headers" )
	,	header( *(ELF_HEADER*)data.GetPtr() )
	,	proghead( NULL )
	,	secthead( NULL )
	{
		readFile();

		if( header.e_phnum > 0 )
			proghead = (ELF_PHR*)&data[header.e_phoff];
			
		if( header.e_shnum > 0 )
			secthead = (ELF_SHR*)&data[header.e_shoff];

		if ( ( header.e_shnum > 0 ) && ( header.e_shentsize != sizeof(ELF_SHR) ) )
			Console::Error( "ElfLoader Warning > Size of section headers is not standard" );

		if ( ( header.e_phnum > 0 ) && ( header.e_phentsize != sizeof(ELF_PHR) ) )
			Console::Error( "ElfLoader Warning > Size of program headers is not standard" );

		ELF_LOG( "type:      " );
		switch( header.e_type ) 
		{
			default: 
				ELF_LOG( "unknown %x", header.e_type );
				break;

			case 0x0:
				ELF_LOG( "no file type" );
				break;

			case 0x1:
				ELF_LOG( "relocatable" );
				break;

			case 0x2: 
				ELF_LOG( "executable" );
				break;
		}  
		ELF_LOG( "\n" );
		ELF_LOG( "machine:   " );
		
		switch ( header.e_machine ) 
		{
			default:
				ELF_LOG( "unknown" );
				break;

			case 0x8:
				ELF_LOG( "mips_rs3000" );
				break;
		}
		
		ELF_LOG("\n");
		ELF_LOG("version:   %d\n",header.e_version);
		ELF_LOG("entry:     %08x\n",header.e_entry);
		ELF_LOG("flags:     %08x\n",header.e_flags);
		ELF_LOG("eh size:   %08x\n",header.e_ehsize);
		ELF_LOG("ph off:    %08x\n",header.e_phoff);
		ELF_LOG("ph entsiz: %08x\n",header.e_phentsize);
		ELF_LOG("ph num:    %08x\n",header.e_phnum);
		ELF_LOG("sh off:    %08x\n",header.e_shoff);
		ELF_LOG("sh entsiz: %08x\n",header.e_shentsize);
		ELF_LOG("sh num:    %08x\n",header.e_shnum);
		ELF_LOG("sh strndx: %08x\n",header.e_shstrndx);
		
		ELF_LOG("\n");
	}
Ejemplo n.º 18
0
	void loadSectionHeaders() 
	{
		if( secthead == NULL || header.e_shoff > (u32)data.GetLength() )
			return;

		const u8* sections_names = data.GetPtr( secthead[ (header.e_shstrndx == 0xffff ? 0 : header.e_shstrndx) ].sh_offset );
			
		int i_st = -1;
		int i_dt = -1;

		for( int i = 0 ; i < header.e_shnum ; i++ )
		{
			ELF_LOG( "Elf32 Section Header [%x] %s", i, &sections_names[ secthead[ i ].sh_name ] );

			if ( secthead[i].sh_flags & 0x2 )
				args_ptr = min( args_ptr, secthead[ i ].sh_addr & 0x1ffffff );
			
#ifdef PCSX2_DEVBULD
			ELF_LOG("\n");
			ELF_LOG("type:      ");
			
			switch ( secthead[ i ].sh_type )
			{
				default:
					ELF_LOG("unknown %08x",secthead[i].sh_type);
					break;

				case 0x0:
					ELF_LOG("null");
					break;

				case 0x1:
					ELF_LOG("progbits");
					break;

				case 0x2:
					ELF_LOG("symtab");
					break;

				case 0x3:
					ELF_LOG("strtab");
					break;

				case 0x4:
					ELF_LOG("rela");
					break;

				case 0x8:
					ELF_LOG("no bits");
					break;

				case 0x9:
					ELF_LOG("rel");
					break;
			}
			
			ELF_LOG("\n");
			ELF_LOG("flags:     %08x\n", secthead[i].sh_flags);
			ELF_LOG("addr:      %08x\n", secthead[i].sh_addr);
			ELF_LOG("offset:    %08x\n", secthead[i].sh_offset);
			ELF_LOG("size:      %08x\n", secthead[i].sh_size);
			ELF_LOG("link:      %08x\n", secthead[i].sh_link);
			ELF_LOG("info:      %08x\n", secthead[i].sh_info);
			ELF_LOG("addralign: %08x\n", secthead[i].sh_addralign);
			ELF_LOG("entsize:   %08x\n", secthead[i].sh_entsize);
			// dump symbol table
		
			if( secthead[ i ].sh_type == 0x02 ) 
			{
				i_st = i; 
				i_dt = secthead[i].sh_link; 
			}
#endif
		}

		if( ( i_st >= 0 ) && ( i_dt >= 0 ) )
		{
			const char * SymNames;
			Elf32_Sym * eS;

			SymNames = (char*)data.GetPtr( secthead[ i_dt ].sh_offset );
			eS = (Elf32_Sym*)data.GetPtr( secthead[ i_st ].sh_offset );
			Console::WriteLn("found %d symbols", params secthead[ i_st ].sh_size / sizeof( Elf32_Sym ));

			for( uint i = 1; i < ( secthead[ i_st ].sh_size / sizeof( Elf32_Sym ) ); i++ ) {
				if ( ( eS[ i ].st_value != 0 ) && ( ELF32_ST_TYPE( eS[ i ].st_info ) == 2 ) ) {
					R5900::disR5900AddSym( eS[i].st_value, &SymNames[ eS[ i ].st_name ] );
				}
			}
		}
	}
Ejemplo n.º 19
0
void print(const SafeArray<T> &a) {
    for(int i = 0; i < a.getSize(); ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
}