// THIS TEST METHOD WILL GO AWAY INTO ITS OWN SEPARATE SOURCE FILE
VError VRIAServerSolution::TEST_RegisterDebuggerUAGCallback ( )
{
	VError					vError = VE_OK;

	xbox_assert ( fDesignSolution != 0 );
	if ( fDesignSolution == NULL )
		return ThrowError ( VE_RIA_INVALID_DESIGN_SOLUTION );

	CUAGManager*			cmpUAGManager = VComponentManager::RetainComponentOfType <CUAGManager> ( );
	if ( cmpUAGManager == 0 )
		return ThrowError ( VE_RIA_UAG_COMPONENT_NOT_FOUND );

	bool					bCanDebug = false;

	VProjectItem*			pitemDirectory = fDesignSolution-> GetProjectItemFromTag ( kUAGDirectoryTag );
	VProjectItem*			pitemPerms = fDesignSolution-> GetProjectItemFromTag ( kPermissionsTag );
	if ( pitemDirectory != NULL )
	{
		VFilePath			pathPerms;
		pitemDirectory-> GetFilePath ( pathPerms );
		/*VFilePath	pathPerms;
		if ( pitemPerms != NULL )
			pitemPerms-> GetFilePath ( pathPerms );*/

		// Load and parse premissions file
		pathPerms. SetExtension ( CVSTR ( "waPerm" ) ); // Hardcoded to be at the same level as the directory file and to have the same name but different extension
		VFile				vfPerms ( pathPerms );
		VValueBag			vvbagPerms;
		vError = LoadBagFromXML ( vfPerms, L"Permissions", vvbagPerms );

		const VBagArray*	bgaPerms = vvbagPerms. GetElements ( CVSTR ( "allow" ) ); // Use namespaced bag keys instead, like SolutionPerms::allow
		if ( bgaPerms != 0 && fUAGDirectory != 0 )
		{
			//CUAGUser*		cUser = fUAGDirectory-> RetainUser ( CVSTR ( "stemnikov" ), &vError );
			CUAGUser*		cUser = fUAGDirectory-> RetainUser ( CVSTR ( "toto" ), &vError );
			if ( cUser != NULL && vError == VE_OK )
			{
				// NEED TO COMPARE the input HA1 with the one stored in the directory to validate user name and password
				VString		vstrValidHA1;
				vError = cUser-> GetHA1 ( vstrValidHA1 );

				CUAGSession*	cSession = fUAGDirectory-> OpenSession ( cUser, &vError );
				if ( cSession != NULL && vError  == VE_OK )
				{
					VIndex			nCount = bgaPerms-> GetCount ( );
					for ( VIndex i = 1; i <= nCount && vError == VE_OK; i++ )
					{
						const VValueBag*		vvbagOnePerm = bgaPerms-> GetNth ( i );
						if ( vvbagOnePerm == NULL )
							continue;

						VString		vstrAction;
						vvbagOnePerm-> GetString ( CVSTR ( "action" ), vstrAction ); // Use namespaced bag keys instead, like SolutionPerms::action
						VString		vstrGroupID;
						vvbagOnePerm-> GetString ( CVSTR ( "groupID" ), vstrGroupID ); // Use namespaced bag keys instead, like SolutionPerms::groupID
						::DebugMsg ( CVSTR ( "Action is \"" ) + vstrAction + CVSTR ( "\"\r\n" ) );
						::DebugMsg ( CVSTR ( "GroupID is \"" ) + vstrGroupID + CVSTR ( "\"\r\n" ) );

						if ( vstrAction. EqualToString ( CVSTR ( "debug" ) ) )
						{
							VUUID		vidGroup;
							vidGroup. FromString ( vstrGroupID );
							if ( cSession-> BelongsTo ( vidGroup ) )
							{
								bCanDebug = true;

								break;
							}
						}
					}
					cSession-> Release ( );
				}
				cUser-> Release ( );
			}
		}
	}
	else
		vError = ThrowError ( VE_RIA_INVALID_DESIGN_SOLUTION );

	cmpUAGManager-> Release ( );

	return vError;
}
예제 #2
0
void CZipCentralDir::Write(CZipActionCallback* pCallback)
{
	if (m_info.m_bOnDisk)
		return;
	if (!m_pStorage->IsSpanMode())
	{
		m_pStorage->Flush();
		m_pStorage->m_pFile->SeekToEnd();
	}

// 	else
// 		// we are at the end already

	m_info.m_uEntriesNumber = (WORD)m_headers.GetSize();
	m_info.m_uSize = 0;
	bool bDontAllowDiskChange = false;
	// if there is a disk spanning archive in creation and it is only one-volume,
	//	(current disk is 0 so far, no bytes has been written so we know they are 
	//  all in the buffer)	make sure that it will be after writing central dir 
	// and make it a non disk spanning archive
	if (m_pStorage->IsSpanMode() && m_pStorage->GetCurrentDisk() == 0)
	{
		DWORD uVolumeFree = m_pStorage->VolumeLeft();
		// calculate the size of data descriptors already in the buffer or on the disk
		// (they will be removed in the non disk spanning archive):
		// multi span signature at the beginnig (4 bytes) + the size of the data 
		// descr. for each file (multi span signature + 12 bytes data)
		// the number of bytes to add: central dir size - total to remove;
		DWORD uToGrow = GetSize(true) - (4 + m_info.m_uEntriesNumber * (4 + 12)); 
		if (uVolumeFree >= uToGrow) 
		// lets make sure it will be one-disk archive
		{
			// can the operation be done only in the buffer?
			if (!m_pStorage->m_iBytesWritten && // no bytes on the disk yet
				(m_pStorage->GetFreeInBuffer() >= uToGrow)) // is the buffer big enough?
			{
					RemoveDataDescr(true);
					bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later
			}
			else
			{
				m_pStorage->Flush();
				if (RemoveDataDescr(false))
					bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later
			}
		}
	}

	try
	{
		WriteHeaders(pCallback, bDontAllowDiskChange || !m_pStorage->IsSpanMode());

		m_info.m_uThisDisk = (WORD)m_pStorage->GetCurrentDisk();
		DWORD uSize = WriteCentralEnd();
		if (bDontAllowDiskChange)
		{
			if (m_pStorage->GetCurrentDisk() != 0)
				ThrowError(CZipException::badZipFile);
		}
		// if after adding a central directory there is a disk change, 
		// update the information and write it again
		if (m_info.m_uThisDisk != m_pStorage->GetCurrentDisk())
		{
			m_info.DiskChange(m_pStorage->GetCurrentDisk());

			if (m_pStorage->m_uBytesInWriteBuffer >= uSize)
				// if the data is still in the buffer, simply remove it
				m_pStorage->m_uBytesInWriteBuffer -= uSize;
			else
			{
				m_pStorage->Flush();
				m_pStorage->m_iBytesWritten -= uSize;
				m_pStorage->m_pFile->SeekToBegin();	
			}
			
			WriteCentralEnd();
		}
	}
	catch (...)
	{
		if (bDontAllowDiskChange)
		{
			m_pStorage->FinalizeSpan();
			m_info.m_uThisDisk = 0;
		}
		throw;
	}
	m_info.m_bOnDisk = true;
}
///
/// \brief Attaches a servo instance to a pin, specifying pulse width range.
/// \details This will designate which pin the Servo instance will change.
/// \param [in] pin - The PWM pin on which to generate the pulse (PWM0 - PWM15)
/// \param [in] min - The minimum microseconds for servo pulses, range: 0 - (max-1) )
/// \param [in] max - The maximum microseconds for servo pulses, range: (min+1) - 10000
///
void Servo::attach(int pin, int min, int max)
{
    HRESULT hr;
    ULONG ioPin;
    BoardPinsClass::BOARD_TYPE board;
    ULONG actualPwmFrequency = 0;

    if ((min < 0) || (max < (min + 1)) || (max > 10000))
    {
        ThrowError(E_INVALIDARG, "Servo pulse microsecond range specified is invalid");
    }
    _min = min;
    _max = max;

    hr = g_pins.getBoardType(board);
    if (FAILED(hr))
    {
        ThrowError(hr, "Error getting board type.  Error: 0x%08x", hr);
    }

    switch (board)
    {
    case BoardPinsClass::BOARD_TYPE::MBM_IKA_LURE:
        // The pin number passed in is a GPIO Pin number, use it as is.
        ioPin = pin;

        // Verify the pin is in PWM mode, and configure it for PWM use if not.
        hr = g_pins.verifyPinFunction(ioPin, FUNC_PWM, BoardPinsClass::LOCK_FUNCTION);
        if (FAILED(hr))
        {
            ThrowError(hr, "Error occurred verifying pin: %d function: PWM, Error: %08x", ioPin, hr);
        }
        break;

    case BoardPinsClass::BOARD_TYPE::MBM_BARE:
    case BoardPinsClass::BOARD_TYPE::PI2_BARE:
        // Translate the PWM channel numbers to fake pin numbers.
        if (pin < PWM0)
        {
            ioPin = PWM0 + pin;
        }
        else
        {
            ioPin = pin;
        }
        break;

    default:
        ThrowError(E_INVALIDARG, "Unrecognized board type: 0x%08x", board);
    }

    // Set the frequency on the PWM channel.
    hr = g_pins.setPwmFrequency(ioPin, SERVO_FREQUENCY_HZ);
    if (FAILED(hr))
    {
        ThrowError(hr, "Error occurred setting PWM frequency for servo use.");
    }

    // Record the information we need to drive a servo signal on the PWM pin.
    actualPwmFrequency = g_pins.getActualPwmFrequency(ioPin);
    _actualPeriodMicroseconds = (1000000 + (actualPwmFrequency / 2)) / actualPwmFrequency;
    _attachedPin = ioPin;

}
예제 #4
0
int FileInputStream::NextByte()
{
    if(!m_file) ThrowError(_T("file pointer is NULL"));
    return fgetc(m_file);
}
예제 #5
0
JNIEXPORT jint JNICALL Java_org_a11y_BrlAPI_Native_openConnection(JNIEnv *jenv, jobject jobj, jobject JclientSettings , jobject JusedSettings) {
  jclass jcclientSettings, jcusedSettings;
  jfieldID clientAuthID = NULL, clientHostID = NULL, usedAuthID, usedHostID;
  brlapi_connectionSettings_t clientSettings,  usedSettings,
            *PclientSettings, *PusedSettings;
  int result;
  jstring auth = NULL, host = NULL;
  const char *str;
  jfieldID handleID;
  brlapi_handle_t *handle;
  jclass jcls;

  GET_CLASS(jenv, jcls, jobj, -1);
  GET_ID(jenv, handleID, jcls, "handle", "J", -1);
  handle = malloc(brlapi_getHandleSize());
  if (!handle) {
    ThrowException(jenv, ERR_OUTOFMEM, __func__);
    return -1;
  }

  (*jenv)->SetLongField(jenv, jobj, handleID, (jlong) (intptr_t) handle);

  env = jenv;

  if (JclientSettings) {
    GET_CLASS(jenv, jcclientSettings, JclientSettings, -1);
    GET_ID(jenv, clientAuthID, jcclientSettings, "auth", "Ljava/lang/String;", -1);
    GET_ID(jenv, clientHostID, jcclientSettings, "host", "Ljava/lang/String;", -1);

    PclientSettings = &clientSettings;
    if ((auth = (*jenv)->GetObjectField(jenv, JclientSettings, clientAuthID))) {
      if (!(clientSettings.auth = (char *)(*jenv)->GetStringUTFChars(jenv, auth, NULL))) {
	ThrowException(jenv, ERR_OUTOFMEM, __func__);
	return -1;
      }
    } else clientSettings.auth = NULL;
    if ((host = (*jenv)->GetObjectField(jenv, JclientSettings, clientHostID))) {
      if (!(clientSettings.host = (char *)(*jenv)->GetStringUTFChars(jenv, host, NULL))) {
	ThrowException(jenv, ERR_OUTOFMEM, __func__);
	return -1;
      }
    } else clientSettings.host = NULL;
  } else PclientSettings = NULL;

  if (JusedSettings)
    PusedSettings = &usedSettings;
  else
    PusedSettings = NULL;

  if ((result = brlapi__openConnection(handle, PclientSettings, PusedSettings)) < 0) {
    ThrowError(jenv, __func__);
    return -1;
  }

  (void) brlapi__setExceptionHandler(handle, exceptionHandler);

  if (JclientSettings) {
    if (clientSettings.auth)
      (*jenv)->ReleaseStringUTFChars(jenv, auth,  clientSettings.auth); 
    if (clientSettings.host)
      (*jenv)->ReleaseStringUTFChars(jenv, host, clientSettings.host); 
  }

  if (PusedSettings) {
    GET_CLASS(jenv, jcusedSettings, JusedSettings, -1);
    GET_ID(jenv, usedAuthID, jcusedSettings, "auth", "Ljava/lang/String;", -1);
    GET_ID(jenv, usedHostID, jcusedSettings, "host", "Ljava/lang/String;", -1);

    auth = (*jenv)->NewStringUTF(jenv, usedSettings.auth);
    if (!auth) {
      ThrowException(jenv, ERR_OUTOFMEM, __func__);
      return -1;
    }
    str = (*jenv)->GetStringUTFChars(jenv, auth, NULL);
    (*jenv)->SetObjectField(jenv, JusedSettings, clientAuthID, auth);
    (*jenv)->ReleaseStringUTFChars(jenv, auth, str);

    host = (*jenv)->NewStringUTF(jenv, usedSettings.host);
    if (!host) {
      ThrowException(jenv, ERR_OUTOFMEM, __func__);
      return -1;
    }
    str = (*jenv)->GetStringUTFChars(jenv, host, NULL);
    (*jenv)->SetObjectField(jenv, JusedSettings, clientHostID, host);
    (*jenv)->ReleaseStringUTFChars(jenv, host, str);
  }

  return (jint) result;
}
HRESULT Library_spot_net_native_Microsoft_SPOT_Net_SocketNative::SendRecvHelper( CLR_RT_StackFrame& stack, bool fSend, bool fAddress )
{
    NATIVE_PROFILE_CLR_NETWORK();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock*       socket    = stack.Arg0().Dereference();
    CLR_INT32               handle;
    CLR_RT_HeapBlock_Array* arrData   = stack.Arg1().DereferenceArray(); 
    CLR_UINT32              offset    = stack.Arg2().NumericByRef().u4;
    CLR_UINT32              count     = stack.Arg3().NumericByRef().u4;
    CLR_INT32               flags     = stack.Arg4().NumericByRef().s4;
    CLR_INT32               timeout_ms = stack.ArgN(5).NumericByRef().s4;
    CLR_RT_HeapBlock        hbTimeout;

    CLR_INT64* timeout;
    CLR_UINT8* buf;
    bool       fRes = true;
    CLR_INT32  totReadWrite;
    CLR_INT32  ret = 0;

    FAULT_ON_NULL(socket);
    handle = socket[ FIELD__m_Handle ].NumericByRef().s4;

    FAULT_ON_NULL(arrData);
    
    if(offset + count > arrData->m_numOfElements) TINYCLR_SET_AND_LEAVE(CLR_E_INDEX_OUT_OF_RANGE);    

    /* Because we could have been a rescheduled call due to a prior call that would have blocked, we need to see
     * if our handle has been shutdown before continuing. */
    if (handle == DISPOSED_HANDLE)
    {
        ThrowError( stack, CLR_E_OBJECT_DISPOSED );
        TINYCLR_SET_AND_LEAVE (CLR_E_PROCESS_EXCEPTION);
    }

    hbTimeout.SetInteger( timeout_ms );
        
    TINYCLR_CHECK_HRESULT(stack.SetupTimeout( hbTimeout, timeout ));

    //
    // Push "totReadWrite" onto the eval stack.
    //
    if(stack.m_customState == 1)
    {
        stack.PushValueI4( 0 );
        
        stack.m_customState = 2;
    }

    totReadWrite = stack.m_evalStack[ 1 ].NumericByRef().s4;

    buf    = arrData->GetElement( offset + totReadWrite );
    count -= totReadWrite;

    while(count > 0)
    {
        CLR_INT32 bytes = 0;

        // first make sure we have data to read or ability to write
        while(fRes)
        {
            ret = Helper__SelectSocket( handle, fSend ? 1 : 0 );

            if(ret != 0) break;

            // non-blocking - allow other threads to run while we wait for handle activity
            TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.WaitEvents( stack.m_owningThread, *timeout, CLR_RT_ExecutionEngine::c_Event_Socket, fRes ));
        }

        // timeout expired
        if(!fRes)
        {
            ret = SOCK_SOCKET_ERROR;
            
            ThrowError( stack, SOCK_ETIMEDOUT );

            TINYCLR_SET_AND_LEAVE( CLR_E_PROCESS_EXCEPTION );
        }

        // socket is in the excepted state, so let's bail out
        if(SOCK_SOCKET_ERROR == ret)
        {
            break;
        }

        if(fAddress)
        {
            struct SOCK_sockaddr addr;
            CLR_UINT32 addrLen = sizeof(addr);
            CLR_RT_HeapBlock& blkAddr = stack.ArgN( 6 );

            if(fSend)
            {
                TINYCLR_CHECK_HRESULT(MarshalSockAddress( &addr, addrLen, blkAddr ));
                
                bytes = SOCK_sendto( handle, (const char*)buf, count, flags, &addr, addrLen );
            }
            else
            {
                CLR_RT_HeapBlock* pBlkAddr = blkAddr.Dereference();
                
                TINYCLR_CHECK_HRESULT(MarshalSockAddress( &addr, addrLen, *pBlkAddr ));

                bytes = SOCK_recvfrom( handle, (char*)buf, count, flags, &addr, (int*)&addrLen );

                if(bytes != SOCK_SOCKET_ERROR)
                {
                    TINYCLR_CHECK_HRESULT(MarshalSockAddress( blkAddr, &addr, addrLen ));
                }
            }
        }
        else
        {
            if(fSend)
            {
                bytes = SOCK_send( handle, (const char*)buf, count, flags );
            }
            else
            {
                bytes = SOCK_recv( handle, (char*)buf, count, flags );
            }
        }

        // send/recv/sendto/recvfrom failed
        if(bytes == SOCK_SOCKET_ERROR)
        {
            CLR_INT32 err = SOCK_getlasterror();
            
            if(err != SOCK_EWOULDBLOCK)
            {
                ret = SOCK_SOCKET_ERROR;
                break;
            }
            
            continue;
        }
                // zero recv bytes indicates the handle has been closed.
        else if(!fSend && (bytes == 0)) 
        {
            break;
        }
        
        buf          += bytes;
        totReadWrite += bytes;
        count        -= bytes;

        stack.m_evalStack[ 1 ].NumericByRef().s4 = totReadWrite;        

        // receive returns immediately after receiving bytes.
        if(!fSend && (totReadWrite > 0))
        {
            break;
        }

    }

    stack.PopValue();       // totReadWrite
    stack.PopValue();       // Timeout
    
    TINYCLR_CHECK_HRESULT(ThrowOnError( stack, ret ));

    stack.SetResult_I4( totReadWrite );

    TINYCLR_NOCLEANUP();
}
예제 #7
0
void SecureCellSeal::encrypt(const Nan::FunctionCallbackInfo<v8::Value>& args)
{
    themis_status_t status = THEMIS_FAIL;
    SecureCellSeal* obj = Nan::ObjectWrap::Unwrap<SecureCellSeal>(args.This());
    if (args.Length() < 1) {
        ThrowParameterError("Secure Cell (Seal) failed to encrypt",
                            "not enough arguments, expected message");
        args.GetReturnValue().SetUndefined();
        return;
    }
    if (!args[0]->IsUint8Array()) {
        ThrowParameterError("Secure Cell (Seal) failed to encrypt",
                            "message is not a byte buffer, use ByteBuffer or Uint8Array");
        args.GetReturnValue().SetUndefined();
        return;
    }
    if (node::Buffer::Length(args[0]) == 0) {
        ThrowParameterError("Secure Cell (Seal) failed to encrypt", "message is empty");
        args.GetReturnValue().SetUndefined();
        return;
    }
    size_t length = 0;
    const uint8_t* context = NULL;
    size_t context_length = 0;
    if (args.Length() == 2) {
        if (!args[1]->IsUint8Array()) {
            ThrowParameterError("Secure Cell (Seal) failed to encrypt",
                                "context is not a byte buffer, use ByteBuffer or Uint8Array");
            args.GetReturnValue().SetUndefined();
            return;
        }
        context = (const uint8_t*)(node::Buffer::Data(args[1]));
        context_length = node::Buffer::Length(args[1]);
    }
    status = themis_secure_cell_encrypt_seal(&(obj->key_)[0],
                                             obj->key_.size(),
                                             context,
                                             context_length,
                                             (const uint8_t*)(node::Buffer::Data(args[0])),
                                             node::Buffer::Length(args[0]),
                                             NULL,
                                             &length);
    if (status != THEMIS_BUFFER_TOO_SMALL) {
        ThrowError("Secure Cell (Seal) failed to encrypt", status);
        args.GetReturnValue().SetUndefined();
        return;
    }
    uint8_t* data = (uint8_t*)(malloc(length));
    status = themis_secure_cell_encrypt_seal(&(obj->key_)[0],
                                             obj->key_.size(),
                                             context,
                                             context_length,
                                             (const uint8_t*)(node::Buffer::Data(args[0])),
                                             node::Buffer::Length(args[0]),
                                             data,
                                             &length);
    if (status != THEMIS_SUCCESS) {
        ThrowError("Secure Cell (Seal) failed to encrypt", status);
        free(data);
        args.GetReturnValue().SetUndefined();
        return;
    }
    args.GetReturnValue().Set(Nan::NewBuffer((char*)(data), length).ToLocalChecked());
}
/*Load Register(Immediate) Encoding T4

   LDR<c> <Rt>,[<Rn>,#-<imm8>]
   LDR<c> <Rt>,[<Rn>],#+/-<imm8>
   LDR<c> <Rt>,[<Rn>,#+/-<imm8>]!

   31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
  |1  1  1   1  1| 0  0| 0  0  1  0  1|     Rn    |     Rt    | 1| P U W|     imm8      |

  where:
              <c><q>            See Standard assembler syntax fields on page A6-7.

              <Rt>              Specifies the destination register. This register is allowed to be the SP. It is also allowed to
                                be the PC, provided the instruction is either outside an IT block or the last instruction of an
                                IT block. If it is the PC, it causes a branch to the address (data) loaded into the PC.

              <Rn>              Specifies the base register. This register is allowed to be the SP. If this register is the PC, see
                                LDR (literal) on page A6-90.

              +/-               Is + or omitted to indicate that the immediate offset is added to the base register value
                                (add == TRUE), or – to indicate that the offset is to be subtracted (add == FALSE). Different
                                instructions are generated for #0 and #-0.

              <imm>             Specifies the immediate offset added to or subtracted from the value of <Rn> to form the
                                address. Allowed values are multiples of 4 in the range 0-124 for encoding T1, multiples of
                                4 in the range 0-1020 for encoding T2, any value in the range 0-4095 for encoding T3, and
                                any value in the range 0-255 for encoding T4. For the offset addressing syntax, <imm> can be
                                omitted, meaning an offset of 0.

*/
void LDRImmediateT4(uint32_t instruction)
{
  uint32_t address;
  uint32_t imm8 = getBits(instruction,7,0);
  uint32_t Rn   = getBits(instruction,19,16);
  uint32_t Rt   = getBits(instruction,15,12);
  uint32_t P = getBits(instruction,10,10);
  uint32_t U = getBits(instruction,9,9);
  uint32_t W = getBits(instruction,8,8);

  if(inITBlock())
  {
    if( checkCondition(cond) )
    {
      if(U == 1)
        address = coreReg[Rn] +  imm8;
      else
        address = coreReg[Rn] -  imm8;

      if(P == 1 && W == 0)
      {
        if(Rt == PC)
        {
          if( getBits(address,1,0) == 0b00)
          {
            writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
            // uint32_t bit0 = getBits(coreReg[Rt], 0, 0);
            // coreReg[xPSR] = setBits(coreReg[xPSR], bit0, 24, 24);   // EPSR.T = coreReg[Rt]<0>
          }
          else
          {
            //placePCtoVectorTable(UsageFault);
            ThrowError();
          }
        }
        else
          writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
      }
      else if(P == 1 && W == 1)
      {
        if(Rt != PC)
        {
          writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
          coreReg[Rn] = address;
        }
        else
        {
          if( getBits(address,1,0) == 0b00)
          {
            writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
            // uint32_t bit0 = getBits(coreReg[Rt], 0, 0);
            // coreReg[xPSR] = setBits(coreReg[xPSR], bit0, 24, 24);   // EPSR.T = coreReg[Rt]<0>
            coreReg[Rn] = address;
          }
          else
          {
            //placePCtoVectorTable(UsageFault);
            ThrowError();
          }
        }
      }
      else if(P == 0 && W == 1)
      {
        if(Rt != PC)
        {
          writeToCoreRegisters(Rt , loadByteFromMemory(coreReg[Rn], 4) );
          coreReg[Rn] = address;
        }
        else
        {
          if( getBits(coreReg[Rn],1,0) == 0b00)
          {
            writeToCoreRegisters(Rt , loadByteFromMemory(coreReg[Rn], 4) );
            // uint32_t bit0 = getBits(coreReg[Rt], 0, 0);
            // coreReg[xPSR] = setBits(coreReg[xPSR], bit0, 24, 24);   // EPSR.T = coreReg[Rt]<0>
            coreReg[Rn] = address;
          }
          else
          {
            //placePCtoVectorTable(UsageFault);
            ThrowError();
          }
        }
      }
    }
    shiftITState();
  }
  else
  {
      if(U == 1)
        address = coreReg[Rn] +  imm8;
      else
        address = coreReg[Rn] -  imm8;

      if(P == 1 && W == 0)
      {
        if(Rt == PC)
        {
          if( getBits(address,1,0) == 0b00)
          {
            writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
            // uint32_t bit0 = getBits(coreReg[Rt], 0, 0);
            // coreReg[xPSR] = setBits(coreReg[xPSR], bit0, 24, 24);   // EPSR.T = coreReg[Rt]<0>
          }
          else
          {
            //placePCtoVectorTable(UsageFault);
            ThrowError();
          }
        }
        else
          writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
      }
      else if(P == 1 && W == 1)
      {
        if(Rt != PC)
        {
          writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
          coreReg[Rn] = address;
        }
        else
        {
          if( getBits(address,1,0) == 0b00)
          {
            writeToCoreRegisters(Rt , loadByteFromMemory(address, 4) );
            // uint32_t bit0 = getBits(coreReg[Rt], 0, 0);
            // coreReg[xPSR] = setBits(coreReg[xPSR], bit0, 24, 24);   // EPSR.T = coreReg[Rt]<0>
            coreReg[Rn] = address;
          }
          else
          {
            //placePCtoVectorTable(UsageFault);
            ThrowError();
          }
        }
      }
      else if(P == 0 && W == 1)
      {
        if(Rt != PC)
        {
          writeToCoreRegisters(Rt , loadByteFromMemory(coreReg[Rn], 4) );
          coreReg[Rn] = address;
        }
        else
        {
          if( getBits(coreReg[Rn],1,0) == 0b00)
          {
            writeToCoreRegisters(Rt , loadByteFromMemory(coreReg[Rn], 4) );
            // uint32_t bit0 = getBits(coreReg[Rt], 0, 0);
            // coreReg[xPSR] = setBits(coreReg[xPSR], bit0, 24, 24);   // EPSR.T = coreReg[Rt]<0>
            coreReg[Rn] = address;
          }
          else
          {
            //placePCtoVectorTable(UsageFault);
            ThrowError();
          }
        }
      }
  }

  if(Rt != PC)
    coreReg[PC] += 4;
}
/*Load Register Signed Byte (immediate) Encoding T2

    LDRSB<c> <Rt>,[<Rn>,#-<imm8>]
    LDRSB<c> <Rt>,[<Rn>],#+/-<imm8>
    LDRSB<c> <Rt>,[<Rn>,#+/-<imm8>]!

   31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
  | 1  1  1  1  1| 0  0| 1  0  0  0  1|     Rn    |     Rt    |1 |P| U|W|      imm8     |

  where:
            <c><q>        See Standard assembler syntax fields on page A6-7.

            <Rt>          Specifies the destination register.

            <Rn>          Specifies the base register. This register is allowed to be the SP. If this register is the PC, see
                          LDRSB (literal) on page A6-120.

            +/-           Is + or omitted to indicate that the immediate offset is added to the base register value
                          (add == TRUE), or – to indicate that the offset is to be subtracted (add == FALSE). Different
                          instructions are generated for #0 and #-0.

            <imm>         Specifies the immediate offset added to or subtracted from the value of <Rn> to form the
                          address. The range of allowed values is 0-4095 for encoding T1, and 0-255 for encoding T2.
                          For the offset addressing syntax, <imm> can be omitted, meaning an offset of 0.

*/
void LDRSBImmediateT2(uint32_t instruction)
{
  uint32_t imm8 = getBits(instruction, 7, 0);
  uint32_t Rt = getBits(instruction,15,12);
  uint32_t Rn = getBits(instruction,19,16);
  uint32_t W = getBits(instruction,8,8);
  uint32_t U = getBits(instruction,9,9);
  uint32_t P = getBits(instruction,10,10);
  uint32_t address;

  if(U == 1)
    address = coreReg[Rn] + imm8;
  else
    address = coreReg[Rn] - imm8;

  int check = isOffPostOrPreIndex(P,W);

  if(check == UNDEFINED || Rt == 0b1111 || Rn == 0b1111)
  {
    //placePCtoVectorTable(UsageFault);
    ThrowError();
  }

  if(inITBlock())
  {
    if( checkCondition(cond) )
    {
      if(check == OFFINDEX)
        writeToCoreRegisters(Rt , signExtend( loadByteFromMemory(address, 1), 8) );
      else if(check == PREINDEX)
      {
        writeToCoreRegisters(Rt , signExtend( loadByteFromMemory(address, 1), 8) );
        coreReg[Rn] = address;
      }
      else
      {
        writeToCoreRegisters(Rt , signExtend( loadByteFromMemory(coreReg[Rn], 1), 8) );
        coreReg[Rn] = address;
      }
    }

    shiftITState();
  }
  else
  {
    if(check == OFFINDEX)
      writeToCoreRegisters(Rt , signExtend( loadByteFromMemory(address, 1), 8) );
    else if(check == PREINDEX)
    {
      writeToCoreRegisters(Rt , signExtend( loadByteFromMemory(address, 1), 8) );
      coreReg[Rn] = address;
    }
    else
    {
      writeToCoreRegisters(Rt , signExtend( loadByteFromMemory(coreReg[Rn], 1), 8) );
      coreReg[Rn] = address;
    }
  }

  coreReg[PC] += 4;

}
예제 #10
0
HRESULT CConvert::StartConversionDirect()
{
	StopConversion();
	printf("Initialising conversion...\n");
	m_tStartTime = timeGetTime();

	HRESULT hr = MakeNotificationWindow();
	if (FAILED(hr))
		return hr;

	hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, 
                          NULL, CLSCTX_INPROC_SERVER,
						  IID_ICaptureGraphBuilder2, 
						  (void **)&m_pBuilder);
	
	if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "GraphBuilder could not be created");
		return hr;
	}

	if (wcscmp(m_pSettings->strOutputFile, m_pSettings->strOutputFile) == 0)
	{
		StopConversion();
		ThrowError(E_FAIL, "The source and target files are the same.");
		return E_FAIL;
	}

    hr |= CreateFilterGraph(&m_pGraph);
    if(FAILED(hr))
    {
        StopConversion();
        ThrowError(hr, "Couldn't create filter graph! Please check that DirectX 8 (or higher) is installed");
        return hr;
    }
    
    hr = m_pBuilder->SetFiltergraph(m_pGraph);
	if(FAILED(hr))
    {
        StopConversion();
        ThrowError(hr, "Couldn't create filter graph! Please check that DirectX 8 (or higher) is installed");
        return hr;
    }    
    
	m_pCallback->ConversionConnecting();

    CComPtr<IBaseFilter> pSourceFilter = NULL;
    hr = m_pGraph->AddSourceFilter(m_pSettings->strInputFile, NULL, &pSourceFilter);  
    if (FAILED(hr))
    {
        StopConversion();
        ThrowError(hr, "Failed to render source UROL!");
        return hr;
    }

	if (m_pCallback)
		m_pCallback->ConversionStreaming();

	hr = RenderOutput(m_pBuilder, m_pGraph, NULL, NULL, NULL, NULL, pSourceFilter);


//	PromptForGraph(m_pGraph, "stream");

	if (m_pCallback)
		m_pCallback->ConversionAboutToRun();


	hr = Run();
	
	if(FAILED(hr))
	{
        StopConversion();
		ThrowError(hr, "Could not start streaming!");
		return hr;
	}


    return hr;
}
예제 #11
0
void CCentralDir::Write()
{
	if (m_bOnDisk)
		return;
	if (!m_pStorage->IsSpanMode())
	{
		m_pStorage->Flush();
		m_pStorage->m_file.SeekToEnd();
	}
	if (m_szComment.GetLength() > USHRT_MAX)
		m_szComment = m_szComment.Left(USHRT_MAX);
	m_uCommentSize = (WORD)m_szComment.GetLength();
	m_uEntriesNumber = (WORD)m_headers.GetSize();
	m_uSize = 0;
	bool bDontAllowDiskChange = false;
	// if there is a disk spanning archive in creation and it is only one-volume,
	//	(current disk is 0 so far, no bytes has been written so we know they are 
	//  all in the buffer)	make sure that it will be after writting central dir 
	// and make it a non disk spanning archive
	if (m_pStorage->IsSpanMode() && !m_pStorage->GetCurrentDisk())
	{
		DWORD uVolumeFree = m_pStorage->VolumeLeft();
		// calculate the size of data descriptors already in the buffer or on the disk
		// (they will be removed in the non disk spanning archive):
		// multi span signature at the beginnig (4 bytes) + the size of the data 
		// descr. for each file (multi span signature + 12 bytes data)
		// the count of bytes to add: central dir size - total to remove;
		DWORD uToGrow = GetSize(true) - (4 + m_uEntriesNumber * (4 + 12)); 
		if (uVolumeFree >= uToGrow) // lets make sure it will be one-disk archive
		{
			// can the operation be done only in the buffer?
			if (!m_pStorage->m_iBytesWritten && // no bytes on the disk yet
				(m_pStorage->GetFreeInBuffer() >= uToGrow)) // is the buffer big enough?
			{
					RemoveDataDescr(true);
					bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later
			}
			else
			{
				m_pStorage->Flush();
				m_pStorage->m_file.Flush();
				if (RemoveDataDescr(false))
					bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later
			}
		}
	}

	WriteHeaders();
	m_uThisDisk = (WORD)m_pStorage->GetCurrentDisk();
	DWORD uSize = WriteCentralEnd();
	if (bDontAllowDiskChange && (m_pStorage->GetCurrentDisk() != 0))
		ThrowError(ZIP_BADZIPFILE);
	// if after adding a central directory there is a disk change, 
	// update the information and write it again
	if (m_uThisDisk != m_pStorage->GetCurrentDisk())
	{
		m_uThisDisk = (WORD)m_pStorage->GetCurrentDisk();
		if (m_uEntriesNumber)
		{
			m_uDiskEntriesNo = 0;	
		}
		else
		{
			m_uDiskWithCD = m_uThisDisk;
			m_uOffset = 0;
		}

		if (m_pStorage->m_uBytesInWriteBuffer >= uSize)
			// if the data is still in the buffer, simply remove it
			m_pStorage->m_uBytesInWriteBuffer -= uSize;
		else
		{
			m_pStorage->Flush();
			m_pStorage->m_iBytesWritten -= uSize;
			m_pStorage->m_file.SeekToBegin();	
		}
		
		WriteCentralEnd();
	}

}
예제 #12
0
HRESULT CConvert::StartConversion()
{
	StopConversion();
	
	printf("Initialising conversion...\n");
	
	bool bIsURL = IsURL(m_pSettings->strInputFile);
	if (bIsURL)
		return StartConversionDirect();

	HRESULT hr = MakeNotificationWindow();
	if (FAILED(hr))
		return hr;

	m_pSettings->ApplySettingsToFilter(m_pMPEGWriter);

	m_nLastEncodedFrameCount = 0;

	hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, 
                          NULL, CLSCTX_INPROC_SERVER,
						  IID_ICaptureGraphBuilder2, 
						  (void **)&m_pBuilder);
	
	if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "GraphBuilder could not be created");
		return hr;
	}

	if (wcscmp(m_pSettings->strInputFile, m_pSettings->strOutputFile) == 0)
	{
		StopConversion();
		ThrowError(E_FAIL, "The source and target files are the same.");
		return E_FAIL;
	}

    // make the timeline
    hr = CoCreateInstance(CLSID_AMTimeline, 
                         NULL, 
                         CLSCTX_INPROC_SERVER, 
                         IID_IAMTimeline, 
                         (void**) &m_pTimeline);

    if(FAILED( hr ))
	{
		StopConversion();
		ThrowError(hr, "Timeline could not be created");
        return hr;
	}

	BOOL bOutputHasVideo = TRUE;
	/*
	switch (m_audioFormat)
	{
	case formatMP3:
	case formatWAV:
		bOutputHasVideo = FALSE; 
		break;
	}*/

	double dFramerate = 0;
	BOOL bVideo = FALSE;
	BOOL bAudio = FALSE;
	long nWidth = 0;
	long nHeight = 0;
	
	hr = GetFileInfo(m_pSettings->strInputFile, &dFramerate, &m_dSourceLength, &bVideo, &bAudio, &nWidth, &nHeight, 0, 0);

	if (!bIsURL && FAILED(hr))
	{
		StopConversion();
		ThrowError(E_FAIL, "The source file could not be read. The conversion cannot proceed");
		return E_FAIL;
	}

	/*
	if ((bAudio && !bVideo || !bOutputHasVideo) && m_bLimitAudio)
	{
		SetStopTime(30);
	}
	*/

	/*
	if (m_dSourceLength == 0 && nWidth && nHeight)
	{
		// picture. We will encode as mpeg still image
		m_dSourceLength = 0.429f;
	}
	else */if (m_dSourceLength == 0)
	{
		StopConversion();
		ThrowError(E_FAIL, "The source file had a duration of 0 seconds. The conversion cannot proceed");
		return E_FAIL;
	}

	if (bVideo && (nWidth == 0 || nHeight == 0))
	{
		StopConversion();
		ThrowError(E_FAIL, "The source video could not be read. The conversion cannot proceed");
		return E_FAIL;
	}


	if (bVideo && bOutputHasVideo)
	{
		hr = AddVideoGroup(dFramerate, nWidth, nHeight);
		if (FAILED(hr))
		{
			StopConversion();
			ThrowError(hr, "Video group could not be added to timeline");
			_ASSERT(FALSE);
			return hr;
		}
	}

	if (bAudio)
	{
		hr = AddAudioGroup();
		if (FAILED(hr))
		{
			_ASSERT(FALSE);
			StopConversion();
			ThrowError(hr, "Audio group could not be added to timeline");
			return hr;
		}
	}

	if (bVideo && bOutputHasVideo)
	{
		hr = AddVideoTracks();
		if (FAILED(hr))
		{
			_ASSERT(FALSE);
			StopConversion();
			ThrowError(hr, "Video track could not be added to timeline");
			return hr;
		}
	}

	if (bAudio)
	{
		hr = AddAudioTracks();
		if (FAILED(hr))
		{
			_ASSERT(FALSE);
			StopConversion();
			ThrowError(hr, "Audio track could not be added to timeline");
			return hr;
		}
	}

	if (bVideo && bOutputHasVideo)
	{
		hr = AddVideoSourceFiles();
		if (FAILED(hr))
		{
			_ASSERT(FALSE);
			StopConversion();
			ThrowError(hr, "Video source file could not be added to timeline");
			return hr;
		}
	}
	
	if (bAudio)
	{
		hr = AddAudioSourceFiles();
		if (FAILED(hr))
		{
			_ASSERT(FALSE);
			StopConversion();
			ThrowError(hr, "Audio source file could not be added to timeline");
			
			return hr;
		}
	}

    hr = m_pTimeline->ValidateSourceNames(SFN_VALIDATEF_CHECK|SFN_VALIDATEF_POPUP|SFN_VALIDATEF_REPLACE, NULL, 0);
    _ASSERT(!FAILED(hr));

    hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER, IID_IRenderEngine, (void**) &m_pRenderEngine);
    if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "Render engine could not be created");
		return hr;
	}

    hr = m_pRenderEngine->SetTimelineObject( m_pTimeline );
    if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "Timeline object corrupt. Bad timeline!");		
		return hr;
	}

	if (m_pSettings->dStartTime || m_pSettings->dEndTime)
	{
		hr = m_pRenderEngine->SetRenderRange((__int64)(m_pSettings->dStartTime * UNITS), (__int64)(m_pSettings->dEndTime * UNITS));
		if (FAILED(hr))
		{
			_ASSERT(FALSE);
		}
	}

    hr = m_pRenderEngine->ConnectFrontEnd();
	if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "File could not be rendered");
		return hr;
	}

	hr = S_OK;
	hr = m_pRenderEngine->GetFilterGraph( &m_pGraph );
	hr |= m_pBuilder->SetFiltergraph(m_pGraph);
	if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "Filter graph could not be retrieved");
		return hr;
	}


	CComPtr<IPin> pVideoOutPin;
	CComPtr<IPin> pAudioOutPin;

	// if it has an audio stream, but no video stream, or does not need video out
	if (bAudio && (!bVideo || !bOutputHasVideo))
	{
		hr = m_pRenderEngine->GetGroupOutputPin(0, &pAudioOutPin);
	}
	else
	{
		hr = m_pRenderEngine->GetGroupOutputPin(0, &pVideoOutPin);
		hr = m_pRenderEngine->GetGroupOutputPin(1, &pAudioOutPin);
	}

	hr = RenderOutput(m_pBuilder, m_pGraph, m_pRenderEngine, NULL, pVideoOutPin, pAudioOutPin, NULL);
	if (FAILED(hr))
	{
		ThrowError(hr, "The output could not be rendered");
		_ASSERT(FALSE);
		StopConversion();
		return hr;
	}
	
	if (CheckVisibility() == S_OK)
	{
		m_pVideoWindow->put_Owner((OAHWND)m_hwndPreviewWnd);
		Resize(m_rcWin);
		m_pVideoWindow->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
	}


	// PromptForGraph(m_pGraph, "edit");

	if (m_pCallback)
		m_pCallback->ConversionAboutToRun();


	hr = Run();
	_ASSERT(SUCCEEDED(hr));
	if (FAILED(hr))
	{
		StopConversion();
		ThrowError(hr, "Everything was initialized okay, but the actual conversion could not start. Please check that you can write to the output file.");
	}

	return hr;
}
VError VRIAServerSolution::_LoadDatabaseSettings()
{
	VError err = VE_OK;

	VValueBag *settings = fSettings.RetainSettings( RIASettingID::database);
	if (settings != NULL)
	{
		// Set the DB4D cache size
		CDB4DManager *db4dMgr = VRIAServerApplication::Get()->GetComponentDB4D();
		if (db4dMgr != NULL)
		{
			// done from the function allocDatabaseCache() in init.cpp
			VSize minsizeblockmem = 0, wantedSizeBlockMem = 0, allocatedSize = 0, minSizeToFlush = 0;

			// calculate the wanted cache size
			if (fSettings.GetAdaptiveCache())
			{
				minsizeblockmem = ((VSize) fSettings.GetMinimumCacheSize()) * 1024 * 1024;

				sLONG8 maxCacheSize = ((sLONG8) fSettings.GetMaximumCacheSize()) * 1024 * 1024;
				sLONG8 minCacheSize = minsizeblockmem;
				sLONG8 minReservedSize = ((sLONG8) fSettings.GetMemoryForOtherApplications()) * 1024 * 1024;
				sLONG ourPercent = fSettings.GetMemoryForCache();
				
				VSize mandatoryMinimum = db4dMgr->GetMinimumCacheSize();

				if(minCacheSize < mandatoryMinimum)
					minCacheSize = mandatoryMinimum;

				if(maxCacheSize < minCacheSize)
					maxCacheSize = minCacheSize;
				
				if (minCacheSize == maxCacheSize)
				{
					wantedSizeBlockMem = minCacheSize;
				}
				else
				{
					sLONG8 cacheSize = 0;
					sLONG8 memMax = VSystem::GetPhysicalMemSize();

					if (memMax > minReservedSize)
						cacheSize = (memMax - minReservedSize)/100 * ourPercent;
					else
						cacheSize = minCacheSize;

					if (cacheSize > maxCacheSize)
						cacheSize = maxCacheSize;
					if (cacheSize < minCacheSize)
						cacheSize = minCacheSize;

					wantedSizeBlockMem = (VSize) cacheSize;
				}
			}
			else
			{
				minsizeblockmem = ((VSize) fSettings.GetFixedCacheSize()) * 1024 * 1024;
				wantedSizeBlockMem = minsizeblockmem;
			}
		
#if !VERSION_LINUX
//jmo - Bug sous Linux... Et probablement ailleurs ! Soit la pile d'appels suivante :

// #0  xbox::VCppMemMgr::AddVirtualAllocation (this=0x7fffec0bfb70, inMaxBytes=104857600, inHintAddress=0x0, inPhysicalMemory=true) at depot/XToolbox/Main/Kernel/Sources/VMemoryCpp.cpp:1480
// #1  0x00007ffff11924fb in VDBCacheMgr::SetMaxSize (this=0x7fffec0bfb60, inSize=209715200, inPhysicalMemOnly=true, outMaxSize=0x7fffffffcc08) at depot/Components/Main/DB4D/Sources/Cache.cpp:1066
// #2  0x00007ffff12a6841 in VDBMgr::SetCacheSize (this=0x7fffec0d5670, inSize=209715200, inPhysicalMemOnly=true, outActualCacheSize=0x7fffffffcc08) at depot/Components/Main/DB4D/Sources/DB4DMgr.cpp:675
// #3  0x00007ffff1302681 in VDB4DMgr::SetCacheSize (this=0x7fffec1d2480, inSize=209715200, inPhysicalMemOnly=true, outActualSize=0x7fffffffcc08) at depot/Components/Main/DB4D/Sources/DB4DComponent.cpp:582
// #4  0x0000000000494f7f in VRIAServerSolution::_LoadDatabaseSettings (this=0x7fffec34c250) at depot/4eDimension/main/4D/PC4D/Solution_RIAServer.cpp:685

//On voit dans xbox::VCppMemMgr::AddVirtualAllocation() qu'on retourne SYSTEMATIQUEMENT une erreur si on utilise le mem. manager standard. Cette erreur se propage jusqu'au "err=" de la ligne ci-dessous et empeche le chargement de la solution...

			err = db4dMgr->SetCacheSize( wantedSizeBlockMem, fSettings.GetKeepCacheInMemory(), &allocatedSize);
#endif

			// Calculate the minimum size to flush
			if ( allocatedSize <= 2*1024L*1024L)
			{
				minSizeToFlush = allocatedSize/4L;	// en dessous de 2 Mo: 25%
			}
			else
			{
				double r = (double) allocatedSize / (1024L*1024L);
				minSizeToFlush = (VSize) (1024.0 * 1024.0 * ::log(r));
				if (minSizeToFlush < 512L*1024L)
					minSizeToFlush = 512L*1024L;
			}

			db4dMgr->SetMinSizeToFlush( minSizeToFlush);

			if ((allocatedSize < minsizeblockmem) && ((((double) (minsizeblockmem - allocatedSize)) / ((double) minsizeblockmem)) > 0.01))
			{
				// TBD: returns a warning
			}

			// Set the data cache flush delay
			VRIAServerApplication::Get()->SetDataCacheFlushDelay( fSettings.GetFlushDataInterval() * 1000);
		}
		else
		{
			err = ThrowError( VE_RIA_DB4D_COMPONENT_NOT_FOUND);
		}
	}
	return err;	
}
VError VRIAServerSolution::_Open( VSolution* inDesignSolution, VRIAServerSolutionOpeningParameters *inOpeningParameters)
{
	if (fState.opened)
		return VE_OK;
	
	VError err = VE_OK;

	if (!testAssert(fDesignSolution == NULL))
		err = VE_UNKNOWN_ERROR;

	if (err == VE_OK && inDesignSolution == NULL)
		err = ThrowError( VE_RIA_INVALID_DESIGN_SOLUTION);

	if (err == VE_OK)
	{
		fDesignSolution = inDesignSolution;
		fDesignSolution->GetName( fName);

		CopyRefCountable( &fOpeningParameters, inOpeningParameters);

		if (fOpeningParameters == NULL)
		{
			fOpeningParameters = new VRIAServerSolutionOpeningParameters();
			if (fOpeningParameters == NULL)
				err = ThrowError( VE_MEMORY_FULL);
		}

		if (err == VE_OK)
			fState.inMaintenance = fOpeningParameters->GetOpeningMode() == eSOM_FOR_MAINTENANCE;

		if (err == VE_OK && !fState.inMaintenance)
		{
			VSize		nNameLength = fName. GetLength ( ) * 2 + 1;
			char*		szchName = new char [ nNameLength ];
			fName. ToCString ( szchName, nNameLength );
			fprintf ( stdout, "Publishing solution \"%s\"\n", szchName );
			delete [ ] szchName;
		}

		if (err == VE_OK && !fState.inMaintenance)
		{
			const VFolder *			vfRoot = RetainFolder ( );
			if ( vfRoot != 0 )
			{
				VJSGlobalContext::SetSourcesRoot ( *vfRoot );
				vfRoot-> Release ( );
				VJSGlobalContext::AllowDebuggerLaunch ( );
			}
		}

		fLoggerID = L"com.wakanda-software." + fName;

		if (err == VE_OK && !fState.inMaintenance)
		{
			// Create a messages logger
			VFolder *logFolder = RetainLogFolder( true);
			if (logFolder != NULL)
			{
				fLogger = new VLog4jMsgFileLogger( *logFolder,  fName + L"_log");
				if (fLogger == NULL)
				{
					err = ThrowError( VE_MEMORY_FULL);
				}
				else
				{
					VRIAServerApplication::Get()->SetLogger( fLogger);
					fLogger->Start();
				}

				logFolder->Release();
			}
			else
			{
				err = ThrowError( VE_RIA_LOG_FOLDER_NOT_FOUND);
			}
		}

		StUseLogger logger;

		if (err == VE_OK && !fState.inMaintenance)
		{
			// Create a log file reader
			fLogReader = new VLog4jMsgFileReader();
			if (fLogReader == NULL)
				err = ThrowError( VE_MEMORY_FULL);
			else
				fLogger->AttachReader( fLogReader);
		}

		if (err == VE_OK || fState.inMaintenance)
		{
			StErrorContextInstaller errContext;
			VMicrosecondsCounter usCounter;
			
			usCounter.Start();

			logger.Log( fLoggerID, eL4JML_Information, L"Opening the solution");

			if (err == VE_OK && !fState.inMaintenance)
			{
				fJSRuntimeDelegate = new VRIAServerSolutionJSRuntimeDelegate( this);
				if (fJSRuntimeDelegate == NULL)
					err = ThrowError( VE_MEMORY_FULL);
			}

			if (err == VE_OK && !fState.inMaintenance)
			{
				fJSContextPool = VRIAServerApplication::Get()->GetJSContextMgr()->CreateJSContextPool( err, this);
			}
	
			if (err == VE_OK || fState.inMaintenance)
			{
				// Load all available settings files
				err = _LoadFileSettings();
				if (err != VE_OK)
					err = ThrowError( VE_RIA_CANNOT_LOAD_SETTINGS_FILES);
			}

			if  (err == VE_OK || fState.inMaintenance)
			{
				// Load the database settings
				err = _LoadDatabaseSettings();
				if (err != VE_OK)
					err = ThrowError( VE_RIA_CANNOT_LOAD_DATABASE_SETTINGS);
			}

			if (err == VE_OK || fState.inMaintenance)
			{
				// Load users and groups directory
				fUAGDirectory = _OpenUAGDirectory( err);
				if (err != VE_OK)
					err = ThrowError( VE_RIA_CANNOT_LOAD_UAG_DIRECTORY);
			}

			if (err == VE_OK || fState.inMaintenance)
			{
				// Build the ServerAdmin project file path
				VFilePath serverAdminProjectPath;
				VFolder *folder = VRIAServerApplication::Get()->RetainApplicationResourcesFolder();
				if (folder != NULL)
				{
					folder->GetPath( serverAdminProjectPath);
					serverAdminProjectPath.ToSubFolder( L"Default Solution");
					serverAdminProjectPath.ToSubFolder( L"Admin");	// sc 18/02/2011 "ServerAdmin" become "Admin"
					serverAdminProjectPath.SetFileName( L"ServerAdmin", false);
					serverAdminProjectPath.SetExtension( RIAFileKind::kProjectFileExtension);
				}
				ReleaseRefCountable( &folder);

				// Opening the applications
				if (fApplicationsMutex.Lock())
				{
					// Note: the ServerAdmin project may be the project of the default solution
					// or the ServerAdmin project added to a solution which has none admin project.
					bool hasAdmin = false;
					VProject *serverAdminProject = fDesignSolution->GetProjectFromFilePathOfProjectFile( serverAdminProjectPath);

					bool ignoreProjectOpeningErrors = !fSettings.GetStopIfProjectFails();
					fGarbageCollect = fSettings.GetGarbageCollect();

					VectorOfProjects designProjects;
					fDesignSolution->GetVectorOfProjects( designProjects);
					for (VectorOfProjects::iterator iter = designProjects.begin() ; iter != designProjects.end() && (err == VE_OK || fState.inMaintenance) ; ++iter)
					{
						if (*iter != NULL)
						{
							VRIAServerProject *application = NULL;

							// Create opening parameters
							VRIAServerProjectOpeningParameters *projectOpeningParams = new VRIAServerProjectOpeningParameters();
							if (projectOpeningParams != NULL)
							{
								projectOpeningParams->SetOpeningMode( fState.inMaintenance ? ePOM_FOR_MAINTENANCE : ePOM_FOR_RUNNING);

								sLONG defaultAdminPort = 0;
								if (*iter == serverAdminProject && fOpeningParameters->GetCustomAdministratorHttpPort( defaultAdminPort))
									projectOpeningParams->SetCustomHttpPort( defaultAdminPort);
															
								// for Default solution, pass the WebAdmin opening parameters
								application = VRIAServerProject::OpenProject( err, this, *iter, projectOpeningParams);
								if ((application != NULL) && (err == VE_OK || fState.inMaintenance))
								{
									VUUID uuid;
									xbox_assert(application->GetUUID( uuid));
									
									fApplicationsCollection.push_back( VRefPtr<VRIAServerProject>(application));
									fApplicationsMap[uuid] = VRefPtr<VRIAServerProject>(application);
									hasAdmin |= application->IsAdministrator();

									if (!fState.inMaintenance)
									{
										VString			vstrHostName;
										VString			vstrIP;
										sLONG			nPort = 0;
										VString			vstrPattern;
										VString			vstrPublishName;
										VError			vErrorS = application-> GetPublicationSettings ( vstrHostName, vstrIP, nPort, vstrPattern, vstrPublishName );
										xbox_assert ( vErrorS == VE_OK );
										vstrPublishName. Clear ( );
										application-> GetName ( vstrPublishName );

										VString			vstrMessage;
										vstrMessage. AppendCString ( "\tProject \"" );
										vstrMessage. AppendString ( vstrPublishName );
										vstrMessage. AppendCString ( "\" published at " );
										vstrMessage. AppendString ( vstrIP );
										vstrMessage. AppendCString ( " on port " );
										vstrMessage. AppendLong ( nPort );
										vstrMessage. AppendCString ( "\n" );

										VSize		nNameLength = vstrMessage. GetLength ( ) * 2 + 1;
										char*		szchName = new char [ nNameLength ];
										vstrMessage. ToCString ( szchName, nNameLength );
										fprintf ( stdout, szchName );
										delete [ ] szchName;
									}
								}

								ReleaseRefCountable( &projectOpeningParams);
							}
							else
							{
								err = ThrowError( VE_MEMORY_FULL);
							}

							if (err != VE_OK)
							{
								VString name;
								(*iter)->GetName( name);

								VErrorBase *errBase = CreateErrorBase( VE_RIA_CANNOT_OPEN_PROJECT, &name, NULL);
								logger.LogMessageFromErrorBase( fLoggerID, errBase);
								ReleaseRefCountable( &errBase);

								if (!fState.inMaintenance)
								{
									if (application != NULL)
										application->Close();

									if (ignoreProjectOpeningErrors)
										err = VE_OK;
									else
										err = VE_RIA_CANNOT_OPEN_PROJECT;
								}
							}
							ReleaseRefCountable( &application);
						}
					}

					if (!hasAdmin && !fState.inMaintenance && (err == VE_OK))
					{
						VFile file( serverAdminProjectPath);
						if (file.Exists())
						{
							VURL url( serverAdminProjectPath);
							fDesignSolution->AddExistingProject( url, false);

							VProject *designProject = fDesignSolution->GetProjectFromFilePathOfProjectFile( serverAdminProjectPath);
							if (designProject != NULL)
							{
								VRIAServerProject *application = NULL;

								// Create opening parameters
								VRIAServerProjectOpeningParameters *projectOpeningParams = new VRIAServerProjectOpeningParameters();
								if (projectOpeningParams != NULL)
								{
									projectOpeningParams->SetOpeningMode( ePOM_FOR_RUNNING);

									sLONG defaultAdminPort = 0;
									if (fOpeningParameters->GetCustomAdministratorHttpPort( defaultAdminPort))
										projectOpeningParams->SetCustomHttpPort( defaultAdminPort);

									application = VRIAServerProject::OpenProject( err, this, designProject, projectOpeningParams);
									if (application != NULL && err == VE_OK)
									{
										VUUID uuid;
										xbox_assert(application->GetUUID( uuid));

										fApplicationsCollection.push_back( VRefPtr<VRIAServerProject>(application));
										fApplicationsMap[uuid] = VRefPtr<VRIAServerProject>(application);
									}
									ReleaseRefCountable( &projectOpeningParams);
								}
								else
								{
									err = ThrowError( VE_MEMORY_FULL);
								}

								if (err != VE_OK)
								{
									VString name;
									designProject->GetName( name);

									VErrorBase *errBase = CreateErrorBase( VE_RIA_CANNOT_OPEN_PROJECT, &name, NULL);
									logger.LogMessageFromErrorBase( fLoggerID, errBase);
									ReleaseRefCountable( &errBase);

									if (application != NULL)
										application->Close();

									if (ignoreProjectOpeningErrors)
										err = VE_OK;
									else
										err = VE_RIA_CANNOT_OPEN_PROJECT;
								}
								ReleaseRefCountable( &application);
							}
						}
					}

					fApplicationsMutex.Unlock();
				}
			}

			logger.LogMessagesFromErrorContext( fLoggerID, errContext.GetContext());

			if (err == VE_OK)
			{
				VString logMsg;
				logMsg.Printf( "Solution opened (duration: %i ms)", usCounter.Stop()/1000);
				logger.Log( fLoggerID, eL4JML_Information, logMsg);
			}
		}
	}

	fState.opened = true;

	return err;
}
예제 #15
0
void CoMutex::unlock()
{
    if (!block_.Wakeup())
        ThrowError(eCoErrorCode::ec_mutex_double_unlock);
}
예제 #16
0
uint32_t Processer::Run(ThreadLocalInfo &info, uint32_t &done_count)
{
    info.current_task = NULL;
    done_count = 0;
    uint32_t c = 0;
    SList<Task> slist = runnable_list_.pop_all();
    uint32_t do_count = slist.size();

    DebugPrint(dbg_scheduler, "Run [Proc(%d) do_count:%u] --------------------------", id_, do_count);

    SList<Task>::iterator it = slist.begin();
    for (; it != slist.end(); ++c)
    {
        Task* tk = &*it;
        info.current_task = tk;
        tk->state_ = TaskState::runnable;
        DebugPrint(dbg_switch, "enter task(%s)", tk->DebugInfo());
        RestoreStack(tk);
        int ret = swapcontext(&info.scheduler, &tk->ctx_);
        if (ret) {
            fprintf(stderr, "swapcontext error:%s\n", strerror(errno));
            runnable_list_.push(tk);
            ThrowError(eCoErrorCode::ec_swapcontext_failed);
        }
        DebugPrint(dbg_switch, "leave task(%s) state=%d", tk->DebugInfo(), tk->state_);
        info.current_task = NULL;

        switch (tk->state_) {
            case TaskState::runnable:
                ++it;
                break;

            case TaskState::io_block:
                it = slist.erase(it);
                g_Scheduler.io_wait_.SchedulerSwitch(tk);
                break;

            case TaskState::sleep:
                it = slist.erase(it);
                g_Scheduler.sleep_wait_.SchedulerSwitch(tk);
                break;

            case TaskState::sys_block:
            case TaskState::user_block:
                {
                    if (tk->block_) {
                        it = slist.erase(it);
                        if (!tk->block_->AddWaitTask(tk))
                            runnable_list_.push(tk);
                        tk->block_ = NULL;
                    } else {
                        std::unique_lock<LFLock> lock(g_Scheduler.user_wait_lock_);
                        auto &zone = g_Scheduler.user_wait_tasks_[tk->user_wait_type_];
                        auto &wait_pair = zone[tk->user_wait_id_];
                        auto &task_queue = wait_pair.second;
                        if (wait_pair.first) {
                            --wait_pair.first;
                            tk->state_ = TaskState::runnable;
                            ++it;
                        } else {
                            it = slist.erase(it);
                            task_queue.push(tk);
                        }
                        g_Scheduler.ClearWaitPairWithoutLock(tk->user_wait_type_,
                                tk->user_wait_id_, zone, wait_pair);
                    }
                }
                break;

            case TaskState::done:
            default:
                --task_count_;
                ++done_count;
                it = slist.erase(it);
                DebugPrint(dbg_task, "task(%s) done.", tk->DebugInfo());
                if (tk->eptr_) {
                    std::exception_ptr ep = tk->eptr_;
                    runnable_list_.push(slist);
                    tk->DecrementRef();
                    std::rethrow_exception(ep);
                } else
                    tk->DecrementRef();
                break;
        }
    }
    if (do_count)
        runnable_list_.push(slist);

    return c;
}
예제 #17
0
/****************************************************************************
Desc:
****************************************************************************/
JNIEXPORT jlong JNICALL Java_xflaim_Backup__1backup(
	JNIEnv *			pEnv,
	jobject,			// obj,
	jlong				lThis,
	jstring			sBackupPath,
	jstring			sPassword,
	jobject			backupClient,
	jobject			backupStatus)
{
	RCODE						rc = NE_XFLM_OK;
	IF_Backup *				pBackup = THIS_BACKUP();
	FLMUINT					uiSeqNum = 0;
	JavaVM *					pJvm;
	JNIBackupClient *		pClient = NULL;
	JNIBackupStatus *		pStatus = NULL;
	FLMBYTE					ucBackupPath [F_PATH_MAX_SIZE];
	F_DynaBuf				backupPathBuf( ucBackupPath, sizeof( ucBackupPath));
	FLMBYTE					ucPassword [100];
	F_DynaBuf				passwordBuf( ucPassword, sizeof( ucPassword));
	
	if (RC_BAD( rc = getUTF8String( pEnv, sBackupPath, &backupPathBuf)))
	{
		ThrowError( rc, pEnv);
		goto Exit;
	}
	if (RC_BAD( rc = getUTF8String( pEnv, sPassword, &passwordBuf)))
	{
		ThrowError( rc, pEnv);
		goto Exit;
	}
	
	flmAssert( backupClient);
	
	pEnv->GetJavaVM( &pJvm);
	if( (pClient = f_new JNIBackupClient( backupClient, pJvm)) == NULL)
	{
		rc = RC_SET( NE_XFLM_MEM);
		ThrowError( rc, pEnv);
		goto Exit;
	}
	
	if (backupStatus)
	{
		if( (pStatus = f_new JNIBackupStatus( backupStatus, pJvm)) == NULL)
		{
			rc = RC_SET( NE_XFLM_MEM);
			ThrowError( rc, pEnv);
			goto Exit;
		}
	}
	
	if (RC_BAD( rc = pBackup->backup(
							(const char *)(backupPathBuf.getDataLength() > 1
											   ? (const char *)backupPathBuf.getBufferPtr()
												: (const char *)NULL),
							(const char *)(passwordBuf.getDataLength() > 1
											   ? (const char *)passwordBuf.getBufferPtr()
												: (const char *)NULL),
							pClient, pStatus, &uiSeqNum)))
	{
		ThrowError( rc, pEnv);
		goto Exit;
	}
	
Exit:

	if (pClient)
	{
		pClient->Release();
	}
	
	if (pStatus)
	{
		pStatus->Release();
	}
	
	return( uiSeqNum);
}
예제 #18
0
DWORD CDeflateCompressor::Decompress(void *pBuffer, DWORD uSize)
{
	if (m_bDecompressionDone)
		return 0;

	DWORD uRead = 0;
	if (m_pFile->m_uMethod == methodDeflate)
	{
		m_stream.next_out = (zarch_Bytef*)pBuffer;
		m_stream.avail_out = uSize > m_uUncomprLeft ? (DWORD)m_uUncomprLeft : uSize;					

		// may happen when the file is 0 sized
		bool bForce = m_stream.avail_out == 0 && m_uComprLeft > 0;
		while (m_stream.avail_out > 0 || (bForce && m_uComprLeft > 0))
		{
			if (m_stream.avail_in == 0 /* && m_uComprLeft >= 0*/  // Also when there are zero bytes left. It should always be true.
				)
			{
				DWORD uToRead = FillBuffer();
				
				m_stream.next_in = (zarch_Bytef*)(char*)m_pBuffer;
				m_stream.avail_in = uToRead;
			}
			
			
			ZIP_SIZE_TYPE uTotal = m_stream.total_out;
			zarch_Bytef* pOldBuf =  m_stream.next_out;
			int ret = zarch_inflate(&m_stream, Z_SYNC_FLUSH);
			// will not exceed DWORD
			DWORD uToCopy = (DWORD)(m_stream.total_out - uTotal);
			
			UpdateCrc(pOldBuf, uToCopy);
			
			m_uUncomprLeft -= uToCopy;
			uRead += uToCopy;
            
			if (ret == Z_STREAM_END)
			{
				m_bDecompressionDone = true;
				return uRead;
			}
			else			
				CheckForError(ret);
		}

		if (!uRead && m_options.m_bCheckLastBlock && uSize != 0)
		{
			if (zarch_inflate(&m_stream, Z_SYNC_FLUSH) != Z_STREAM_END)
				// there were no more bytes to read and there was no ending block, 
				// otherwise the method would return earlier
				ThrowError(CZipException::badZipFile);
		}
	}
	else
	{
		if (m_uComprLeft < uSize)
			uRead = (DWORD)m_uComprLeft;
		else
			uRead = uSize;
				
		if (uRead > 0)
		{
			m_pStorage->Read(pBuffer, uRead, false);
			if (m_pCryptograph)
				m_pCryptograph->Decode((char*)pBuffer, uRead);
			UpdateCrc(pBuffer, uRead);
			m_uComprLeft -= uRead;			
			m_uUncomprLeft -= uRead;
			m_stream.total_out += uRead;
		}
	}
	return uRead;
}
HRESULT Library_spot_net_native_Microsoft_SPOT_Net_SocketNative::getaddrinfo___STATIC__VOID__STRING__BYREF_STRING__BYREF_SZARRAY_SZARRAY_U1( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_NETWORK();
    TINYCLR_HEADER();

    LPCSTR szName = stack.Arg0().RecoverString();
    struct SOCK_addrinfo hints;
    struct SOCK_addrinfo* addr = NULL;
    struct SOCK_addrinfo* addrT;
    CLR_UINT32        cAddresses = 0;
    CLR_RT_HeapBlock* pAddress;
    CLR_INT32         timeout_ms = 30000;
    CLR_RT_HeapBlock  hbTimeout;
    CLR_INT32         ret;
    bool              fRes = true;
    CLR_INT64*        timeout;

    hbTimeout.SetInteger( timeout_ms );

    TINYCLR_CHECK_HRESULT(stack.SetupTimeout( hbTimeout, timeout ));

    do
    {
        memset( &hints, 0, sizeof(hints) );

        ret = SOCK_getaddrinfo( szName, NULL, &hints, &addr );

        if(ret == SOCK_SOCKET_ERROR)
        {
            if(SOCK_getlasterror() == SOCK_EWOULDBLOCK)
            {
                // non-blocking - allow other threads to run while we wait for handle activity
                TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.WaitEvents( stack.m_owningThread, *timeout, CLR_RT_ExecutionEngine::c_Event_Socket, fRes ));
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    while(fRes);
    
    // timeout expired
    if(!fRes)
    {
        ret = SOCK_SOCKET_ERROR;
        
        ThrowError( stack, SOCK_ETIMEDOUT );
    
        TINYCLR_SET_AND_LEAVE( CLR_E_PROCESS_EXCEPTION );
    }

    // getaddrinfo returns a winsock error code rather than SOCK_SOCKET_ERROR, so pass this on to the exception handling
    if(ret != 0)
    {
        ThrowError( stack, ret );
        TINYCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION);
    }

    {
        CLR_RT_HeapBlock  hbCanonicalName;
        CLR_RT_HeapBlock  hbAddresses;
        
        hbCanonicalName.SetObjectReference( NULL );
        CLR_RT_ProtectFromGC gc( hbCanonicalName );

        hbAddresses.SetObjectReference( NULL );
        CLR_RT_ProtectFromGC gc2( hbAddresses );

        for(int pass = 0; pass < 2; pass++)
        {                                    
            cAddresses = 0;

            for(addrT = addr; addrT != NULL; addrT = addrT->ai_next)
            {
                if(pass == 1)
                {
                    if(addrT->ai_canonname && addrT->ai_canonname[ 0 ])
                    {
                        //allocate return string
                        TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_String::CreateInstance( hbCanonicalName, addrT->ai_canonname ));
                        TINYCLR_CHECK_HRESULT(hbCanonicalName.StoreToReference( stack.Arg1(), 0 ));
                    }

                    //allocate address and store into array
                    pAddress = (CLR_RT_HeapBlock*)hbAddresses.DereferenceArray()->GetElement( cAddresses );

                    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( *pAddress, (CLR_UINT32)addrT->ai_addrlen, g_CLR_RT_WellKnownTypes.m_UInt8 ));

                    //copy address.
                    memcpy( pAddress->DereferenceArray()->GetFirstElement(), addrT->ai_addr, addrT->ai_addrlen );
                }
                                
                cAddresses++;
            }
                            
            if(pass == 0)
            {
                //allocate array of byte arrays
                CLR_RT_ReflectionDef_Index idx;

                idx.m_kind               = REFLECTION_TYPE;
                idx.m_levels             = 2;
                idx.m_data.m_type.m_data = g_CLR_RT_WellKnownTypes.m_UInt8.m_data;

                TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( hbAddresses, cAddresses, idx ));

                TINYCLR_CHECK_HRESULT(hbAddresses.StoreToReference( stack.Arg2(), 0 ));                
            }
        }    
    }

    stack.PopValue();       // Timeout
    
    TINYCLR_CLEANUP();

    if( addr ) SOCK_freeaddrinfo( addr );

    TINYCLR_CLEANUP_END();
}
예제 #20
0
bool CZipFile::Open(LPCTSTR lpszFileName, UINT openFlags, bool bThrow)
{
	if (!IsClosed())
		Close();

	CZipString fileName = lpszFileName;
	if (fileName.IsEmpty())
	{
		return false;
	}
	DWORD access;
	DWORD temp = openFlags & 3;
	if (temp == modeWrite)
	{
		access = GENERIC_WRITE;
	}
	else if (temp == modeReadWrite)
	{
		access = GENERIC_READ | GENERIC_WRITE;
	}
	else
	{
		access = GENERIC_READ;
	}

	DWORD share;
	temp = openFlags & 0x70;
	if (temp == shareDenyWrite)
	{
		share = FILE_SHARE_READ;
	}
	else if (temp == shareDenyRead)
	{
		share = FILE_SHARE_WRITE;
	}
	else if (temp == shareDenyNone)
	{
		share = FILE_SHARE_READ | FILE_SHARE_WRITE;
	}
	else
	{
		share = 0;
	}
	CZipPathComponent::AddPrefix(fileName, false);

	DWORD create;
	if (openFlags & modeCreate)
	{
		if (openFlags & modeNoTruncate)
		{
			create = OPEN_ALWAYS;
		}
		else
		{
			create = CREATE_ALWAYS;
		}
	}
	else
	{
		create = OPEN_EXISTING;
	}

	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	m_hFile = ::CreateFile(fileName, access, share, &sa, create, FILE_ATTRIBUTE_NORMAL, NULL);
	if (m_hFile == INVALID_HANDLE_VALUE)
	{
		if (bThrow)
			ThrowError();
		else
			return false;
	}
		
	m_szFileName = lpszFileName;
	return true;
}
예제 #21
0
FileInputStream::FileInputStream(const TCHAR* fn)
    : m_file(NULL)
{
    if(_tfopen_s(&m_file, fn, _T("r")) != 0) ThrowError(_T("cannot open file '%s'"), fn);
}
예제 #22
0
	virtual double Call(vector<double>& params)
	{
		ThrowError("GFunctionStub::Eval should never be called. Was Link called?");
		return -1e308;
	}
예제 #23
0
int MemoryInputStream::NextByte()
{
    if(!m_pBytes) ThrowError(_T("memory stream pointer is NULL"));
    if(m_pos >= m_len) return Stream::EOS;
    return (int)m_pBytes[m_pos++];
}
예제 #24
0
// virtual
void GNeighborTransducer::transduce(GData* pDataLabeled, GData* pDataUnlabeled, int labelDims)
{
	if(labelDims != 1)
		ThrowError("Only 1 nominal label is supported");
	if(!pDataLabeled->relation()->areNominal(pDataLabeled->relation()->size() - 1, 1))
		ThrowError("Only nominal labels are supported");
	if(!pDataLabeled->relation()->areContinuous(0, pDataLabeled->relation()->size() - 1))
		ThrowError("Only continuous features are supported");
	if(pDataLabeled->cols() != pDataUnlabeled->cols())
		ThrowError("relations don't match");

	// Make a dataset containing all rows
	GData dataAll(pDataLabeled->relation());
	dataAll.reserve(pDataLabeled->rows() + pDataUnlabeled->rows());
	GReleaseDataHolder hDataAll(&dataAll);
	for(size_t i = 0; i < pDataUnlabeled->rows(); i++)
		dataAll.takeRow(pDataUnlabeled->row(i));
	for(size_t i = 0; i < pDataLabeled->rows(); i++)
		dataAll.takeRow(pDataLabeled->row(i));
	int featureDims = pDataLabeled->cols() - labelDims;
	sp_relation pRelInputs = new GUniformRelation(featureDims, 0);
	dataAll.setRelation(pRelInputs);

	// Find friends
	GNeighborFinder* pNF;
	if(m_intrinsicDims == 0)
		pNF = new GNeighborFinderCacheWrapper(new GKdTree(&dataAll, 0, m_friendCount, NULL, true), true);
	else
		pNF = new GManifoldNeighborFinder(
			&dataAll,
			m_friendCount, // littleK
			m_friendCount * 4, // bigK
			m_intrinsicDims, // intrinsicDims
			m_alpha, // alpha
			m_beta, // beta
			false, // prune?
			m_pRand);
	Holder<GNeighborFinder> hNF(pNF);
	GTEMPBUF(size_t, neighbors, m_friendCount);
	int labelValues = pDataLabeled->relation()->valueCount(featureDims);
	GTEMPBUF(double, tallys, labelValues);

	// Label the unlabeled patterns
	GBitTable labeled(pDataUnlabeled->rows());
	GData labelList(3); // pattern index, most likely label, confidence
	labelList.newRows(pDataUnlabeled->rows());
	for(size_t i = 0; i < pDataUnlabeled->rows(); i++)
		labelList.row(i)[0] = i;
	while(labelList.rows() > 0)
	{
		// Compute the most likely label and the confidence for each pattern
		for(size_t i = 0; i < labelList.rows(); i++)
		{
			// Find the most common label
			double* pRow = labelList.row(i);
			size_t index = (size_t)pRow[0];
			pNF->neighbors(neighbors, index);
			GVec::setAll(tallys, 0.0, labelValues);
			for(int j = 0; j < m_friendCount; j++)
			{
				if(neighbors[j] >= dataAll.rows())
					continue;
				double* pFriend = dataAll.row(neighbors[j]);
				if(neighbors[j] >= pDataUnlabeled->rows())
				{
					if((int)pFriend[featureDims] >= 0 && (int)pFriend[featureDims] < labelValues)
						tallys[(int)pFriend[featureDims]] += 1.0;
				}
				else if(labeled.bit(neighbors[j]))
				{
					if((int)pFriend[featureDims] >= 0 && (int)pFriend[featureDims] < labelValues)
						tallys[(int)pFriend[featureDims]] += 0.6;
				}
			}
			int label = GVec::indexOfMax(tallys, labelValues, m_pRand);
			double conf = tallys[label];

			// Penalize for dissenting votes
			for(int j = 0; j < m_friendCount; j++)
			{
				if(neighbors[j] >= dataAll.rows())
					continue;
				double* pFriend = dataAll.row(neighbors[j]);
				if(neighbors[j] >= pDataUnlabeled->rows())
				{
					if((int)pFriend[featureDims] != label)
						conf *= 0.5;
				}
				else if(labeled.bit(neighbors[j]))
				{
					if((int)pFriend[featureDims] != label)
						conf *= 0.8;
				}
			}
			pRow[1] = label;
			pRow[2] = conf;
		}
		labelList.sort(2);

		// Assign the labels to the patterns we are most confident about
		size_t maxCount = MAX((size_t)5, pDataLabeled->rows() / 5);
		size_t count = 0;
		for(size_t i = labelList.rows() - 1; i < labelList.rows(); i--)
		{
			double* pRow = labelList.row(i);
			size_t index = (size_t)pRow[0];
			int label = (int)pRow[1];
			pDataUnlabeled->row(index)[featureDims] = label;
			labeled.set(index);
			labelList.deleteRow(i);
			if(count >= maxCount)
				break;
			count++;
		}
	}
}
void ThrowDjvuError(JNIEnv* env, const ddjvu_message_t* msg)
{
    if (!msg || !msg->m_error.message)
        ThrowError(env, "Djvu decoding error!");
    else ThrowError(env, msg->m_error.message);
}
예제 #26
0
// virtual
GTwtNode* GInstanceTable::toTwt(GTwtDoc* pDoc)
{
	ThrowError("not implemented yet");
	return NULL;
}
예제 #27
0
void CZipCentralDir::WriteHeaders(CZipActionCallback* pCallback, bool bOneDisk)
{
	m_info.m_uDiskEntriesNo = 0;
	m_info.m_uDiskWithCD = (WORD)m_pStorage->GetCurrentDisk();
	m_info.m_uOffset = m_pStorage->GetPosition() - m_info.m_uBytesBeforeZip;
	if (!m_info.m_uEntriesNumber)
		return;

	WORD iDisk = m_info.m_uDiskWithCD;
	int iStep = 0; // for the compiler

	if (pCallback)
	{
		pCallback->Init();
		pCallback->SetTotal(m_info.m_uEntriesNumber);
		iStep = CZipActionCallback::m_iStep;// we don't want to wait forever
	}

	int iAborted = 0;
	for (int i = 0; i < m_info.m_uEntriesNumber; i++)
	{
		CZipFileHeader* pHeader = (*this)[i];
		

		CZipString szRemember;
		if (m_bConvertAfterOpen)
			// if CZipArchive::Flush is called we will be still using the archive, so restore changed name
			szRemember = pHeader->GetFileName();

		ConvertFileName(false, true, pHeader);
		m_info.m_uSize += pHeader->Write(m_pStorage);

		if (m_bConvertAfterOpen)
			pHeader->SetFileName(szRemember);

		if (m_pStorage->GetCurrentDisk() != iDisk)
		{
			m_info.m_uDiskEntriesNo = 1;
			iDisk = (WORD)m_pStorage->GetCurrentDisk();
			// update the information about the offset and starting disk if the 
			// first header was written on the new disk
			if (i == 0)
			{
				m_info.m_uOffset = 0;
				m_info.m_uDiskWithCD = iDisk;
			}
		}
		else 
			m_info.m_uDiskEntriesNo++;
		if (pCallback && !(i%iStep))
			if (!pCallback->Callback(iStep))
			{
				
				if (bOneDisk) 
				{
					if (!m_pStorage->IsSpanMode())
						m_pStorage->EmptyWriteBuffer();
					else
						m_pStorage->Flush(); // must be flush before - flush was not called in span mode
					
					// remove saved part from the disk
					m_pStorage->m_pFile->SetLength(m_info.m_uBytesBeforeZip + m_info.m_uOffset);
//	 				We can now abort safely
					iAborted = CZipException::abortedSafely;
				}
				else
					iAborted = CZipException::abortedAction;
				break;
			}
	}

	if (pCallback)
		pCallback->CallbackEnd();

	if (iAborted)
		ThrowError(iAborted);
}
예제 #28
0
// virtual
void GInstanceTable::trainSparse(GSparseMatrix* pData, int labelDims)
{
	ThrowError("Sorry, trainSparse is not implemented yet in GInstanceTable");
}
HRESULT Library_spot_net_security_native_Microsoft_SPOT_Net_Security_SslNative::ReadWriteHelper( CLR_RT_StackFrame& stack, bool isWrite )
{
    NATIVE_PROFILE_CLR_NETWORK();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock*       socket     = stack.Arg0().Dereference();
    CLR_RT_HeapBlock_Array* arrData    = stack.Arg1().DereferenceArray(); 
    CLR_INT32               offset     = stack.Arg2().NumericByRef().s4;
    CLR_INT32               count      = stack.Arg3().NumericByRef().s4;
    CLR_INT32               timeout_ms = stack.Arg4().NumericByRef().s4;
    CLR_UINT8*              buffer;
    CLR_RT_HeapBlock        hbTimeout;

    CLR_INT32  totReadWrite;
    bool       fRes = true;
    CLR_INT64 *timeout;
    int        result = 0;
    CLR_INT32 handle;

    if(count == 0) 
    {
        stack.SetResult_I4( 0 );
        TINYCLR_SET_AND_LEAVE(S_OK);
    }

    FAULT_ON_NULL(socket);

    handle = socket[ Library_spot_net_native_Microsoft_SPOT_Net_SocketNative::FIELD__m_Handle ].NumericByRef().s4;

    /* Because we could have been a rescheduled call due to a prior call that would have blocked, we need to see
     * if our handle has been shutdown before continuing. */
    if (handle == Library_spot_net_native_Microsoft_SPOT_Net_SocketNative::DISPOSED_HANDLE)
    {
        ThrowError( stack, CLR_E_OBJECT_DISPOSED );
        TINYCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION);
    }


    FAULT_ON_NULL(arrData);

    hbTimeout.SetInteger( timeout_ms );
        
    TINYCLR_CHECK_HRESULT(stack.SetupTimeout( hbTimeout, timeout ));

    //
    // Push "totReadWrite" onto the eval stack.
    //
    if(stack.m_customState == 1)
    {
        stack.PushValueI4( 0 );

        stack.m_customState = 2;
    }

    totReadWrite = stack.m_evalStack[ 1 ].NumericByRef().s4;

    buffer = arrData->GetElement( offset + totReadWrite );
    count -= totReadWrite;

    if((offset + count + totReadWrite) > (int)arrData->m_numOfElements) TINYCLR_SET_AND_LEAVE(CLR_E_INDEX_OUT_OF_RANGE);    

    while(count > 0)
    {
        // first make sure we have data to read or ability to write
        while(fRes)
        {
            if(!isWrite)
            {
                // check SSL_DataAvailable() in case SSL has already read and buffered socket data
                result = SSL_DataAvailable(handle);

                if((result > 0) || ((result < 0) && (SOCK_getlasterror() != SOCK_EWOULDBLOCK)))
                {
                    break;
                }
            }

            result = Library_spot_net_native_Microsoft_SPOT_Net_SocketNative::Helper__SelectSocket( handle, isWrite ? 1 : 0 );

            if((result > 0) || ((result < 0) && (SOCK_getlasterror() != SOCK_EWOULDBLOCK)))
            {
                break;
            }

            // non-blocking - allow other threads to run while we wait for socket activity
            TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.WaitEvents( stack.m_owningThread, *timeout, CLR_RT_ExecutionEngine::c_Event_Socket, fRes ));

            // timeout expired 
            if(!fRes)
            {
                result = SOCK_SOCKET_ERROR;
                
                ThrowError(stack, SOCK_ETIMEDOUT);
            
                TINYCLR_SET_AND_LEAVE( CLR_E_PROCESS_EXCEPTION );
            }
        }

        // socket is in the excepted state, so let's bail out
        if(SOCK_SOCKET_ERROR == result)
        {
            break;
        }

        if(isWrite)
        {
            result = SSL_Write( handle, (const char*)buffer, count );
        }
        else
        {
            result = SSL_Read( handle, (char*)buffer, count );

            if(result == SSL_RESULT__WOULD_BLOCK)
            {
                continue;
            }
        }

        // ThrowOnError expects anything other than 0 to be a failure - so return 0 if we don't have an error
        if(result <= 0)
        {
            break;
        }

        buffer       += result;
        totReadWrite += result;
        count        -= result;


        // read is non-blocking if we have any data
        if(!isWrite && (totReadWrite > 0))
        {
            break;
        }

        stack.m_evalStack[ 1 ].NumericByRef().s4 = totReadWrite;        
    }

    stack.PopValue();       // totReadWrite
    stack.PopValue();       // Timeout

    if(result < 0)
    {
        TINYCLR_CHECK_HRESULT(ThrowOnError( stack, result ));
    }

    stack.SetResult_I4( totReadWrite );
    
    TINYCLR_NOCLEANUP();
    
}
CUAGDirectory* VRIAServerSolution::_OpenUAGDirectory( VError& outError)
{
	outError = VE_OK;

	CUAGDirectory *directory = nil;

	CUAGManager *uag = VComponentManager::RetainComponentOfType<CUAGManager>();
	if (uag != NULL)
	{
		if (testAssert(fDesignSolution != NULL))
		{
			StUseLogger logger;
			VMicrosecondsCounter usCounter;

			VProjectItem *dirItem = fDesignSolution->GetProjectItemFromTag( kUAGDirectoryTag);
			if (dirItem != NULL)
			{
				VFilePath directoryPath;
				dirItem->GetFilePath( directoryPath);
			
				usCounter.Start();
				logger.Log( fLoggerID, eL4JML_Information, L"Opening the users and groups directory");
				
				VFile file( directoryPath);
				directory = uag->RetainDirectory( file, FA_READ_WRITE, NULL, NULL, &outError);
			}

			if (directory == NULL && outError == VE_OK)
			{
				VFilePath solpath;
				fDesignSolution->GetSolutionFilePath(solpath);
				solpath.SetExtension(RIAFileKind::kDirectoryFileExtension);
				VFile defaultDirFile(solpath);
				directory = uag->RetainDirectory( defaultDirFile, FA_READ_WRITE, NULL, NULL, &outError, NULL, true);
			}

			if (directory != NULL && outError == VE_OK)
			{
				// Create an "admin" user if needed

				CUAGGroup *adminGroup = directory->RetainSpecialGroup( CUAGDirectory::AdminGroup);
				CUAGGroup *debuggerGroup = directory->RetainSpecialGroup( CUAGDirectory::DebuggerGroup);

				if ((adminGroup != NULL) && (debuggerGroup != NULL))
				{
					StErrorContextInstaller errorContext( VE_UAG_USERNAME_DOES_NOT_EXIST, VE_OK);

					CUAGUser *adminUser = directory->RetainUser( L"admin");
					
					if (adminUser == NULL)
						adminUser = directory->AddOneUser( L"admin", L"", L"", outError);

					if ((outError == VE_OK) && (adminUser != NULL))
					{
						VUUID adminUserID, userID;
						adminUser->GetID( adminUserID);
						
						CUAGUserVector users;
						adminGroup->RetainUsers( users);

						bool hasAdminUser = false;
						for (CUAGUserVector::iterator userIter = users.begin() ; (userIter != users.end()) && !hasAdminUser ; ++userIter)
						{
							(*userIter)->GetID( userID);
							hasAdminUser = (adminUserID == userID);
						}

						if (!hasAdminUser)
							outError = adminUser->PutIntoGroup( adminGroup);

						if (outError == VE_OK)
						{
							users.clear();
							debuggerGroup->RetainUsers( users);

							hasAdminUser = false;
							for (CUAGUserVector::iterator userIter = users.begin() ; (userIter != users.end()) && !hasAdminUser ; ++userIter)
							{
								(*userIter)->GetID( userID);
								hasAdminUser = (adminUserID == userID);
							}

							if (!hasAdminUser)
								outError = adminUser->PutIntoGroup( debuggerGroup);
						}
					}
					ReleaseRefCountable( &adminUser);
				}
				QuickReleaseRefCountable( adminGroup);
				QuickReleaseRefCountable( debuggerGroup);
			}

			if (directory != NULL && outError == VE_OK)
			{
				VString logMsg;
				logMsg.Printf( "Users and groups directory opened (duration: %i ms)", usCounter.Stop()/1000);
				logger.Log( fLoggerID, eL4JML_Information, logMsg);
			}
		}
		uag->Release();
	}
	else
	{
		outError = ThrowError( VE_RIA_UAG_COMPONENT_NOT_FOUND);
	}
	return directory;
}