public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { if (TbsHandle == UIntPtr.Zero) { throw new Exception("TBS context not created."); } var resultBuf = new byte[4096]; uint bytesReturned = (uint)resultBuf.Length; TbsWrapper.TBS_RESULT result = TbsWrapper.NativeMethods.Tbsip_Submit_Command(TbsHandle, (TbsWrapper.TBS_COMMAND_LOCALITY) active.ActiveLocality, active.ActivePriority, inBuf, (uint)inBuf.Length, resultBuf, ref bytesReturned); if (result != AlternativeResult && result != TbsWrapper.TBS_RESULT.TBS_SUCCESS) { string errMsg = new Win32Exception((int)result).Message; ProcessError("TBS error " + result.ToString("X") + ": " + errMsg, out outBuf); return; } if (bytesReturned == 0) { ProcessError(Globs.GetResourceString("SubmitError2"), out outBuf); return; } outBuf = new byte[bytesReturned]; Array.Copy(resultBuf, outBuf, (int)bytesReturned); }
public void Modify_ShouldNotModifyOtherThanDollarExpressions() { const string notDollarExpression = "from h in hests select h"; var modified = CommandModifier.Modify(notDollarExpression); Assert.That(modified, Is.EqualTo(notDollarExpression)); }
public void Modify_ShouldModifyMultipleQueries() { const string command = "from h in $(hest) where $(select Name from HestType).Any(n => n.Equals(h.Type)) select h"; var modified = CommandModifier.Modify(command); Assert.That(modified, Is.EqualTo("from h in Query(\"select * from hest\") where Query(\"select Name from HestType\").Any(n => n.Equals(h.Type)) select h")); }
public void NextLevel(CommandModifier cm) { requestStateClear(); LevelGenerator.level = 2; print("exit end level"); requestStackPush((int)GameFlowStates.ID.Level); }
public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { outBuf = new byte[] { 0x80, 0x01, // TPM_ST_NO_SESSIONS 0, 0, 0, 0x0A, // length 0x40, 0x28, 0x00, 0x10 // TSS_DISPATCH_FAILED }; if (CommandStream == null) { return; } if (LinuxTrm) { if (Globs.NetToHost4U(Globs.CopyData(inBuf, 6, 4)) == (uint)TpmCc.Startup) { outBuf[6] = outBuf[7] = 0; outBuf[8] = 0x01; outBuf[9] = 0; // TPM_RC_INITIALIZE return; } } UndoCancelContext(); var b = new ByteBuf(); b.Append(Globs.HostToNet((int)TcpTpmCommands.SendCommand)); b.Append(new[] { active.ActiveLocality }); if (LinuxTrm && OldTrm) { b.Append(new byte [] { 0, 1 }); } b.Append(Globs.HostToNet(inBuf.Length)); b.Append(inBuf); Write(CommandStream, b.GetBuffer()); outBuf = ReadVarArray(CommandStream); GetAck(CommandStream, "DispatchCommand"); }
public void GoToMenu(CommandModifier cm) { requestStateClear(); GameManager.instance.currentScene = 0; GameManager.instance.nextState = (int)GameFlowStates.ID.Menu; requestStackPush((int)GameFlowStates.ID.Loading); }
public static void TriggerEvent(string eventName, CommandModifier modifier) { Command e = null; eventName = eventName.ToLower(); if (instance.m_EventDictionary.TryGetValue(eventName, out e)) { e.Invoke(modifier); } }
void WrongCommand(CommandModifier cm) { m_WrongCommandNumber++; if (m_WrongCommandNumber == m_WrongCommandNumberBeforeDialogue) { m_WrongCommandNumber = 0; int name = Random.Range(0, 5); int index = Random.Range(1, 6); TriggerSitualtionalDialogue("WrongCommand" + names [name] + index); } }
public static OperationStatus ReadFrom( ReadOnlySpan <byte> span, CommandModifier modifier, out CommandArg arg) { bool ok; ulong value; int size; switch (modifier) { case CommandModifier.ZeroBytes: size = 0; ok = true; value = 0; break; case CommandModifier.OneByte: size = 1; ok = span.Length >= 1; value = ok ? span[0] : 0UL; break; case CommandModifier.TwoBytes: size = 2; ok = BinaryPrimitives.TryReadUInt16BigEndian(span, out var valShort); value = valShort; break; case CommandModifier.FourBytes: size = 4; ok = BinaryPrimitives.TryReadUInt32BigEndian(span, out var valInt); value = valInt; break; case CommandModifier.EightBytes: size = 8; ok = BinaryPrimitives.TryReadUInt64BigEndian(span, out value); break; default: throw new ArgumentException($"{nameof(CommandModifier)}.{modifier}"); } if (!ok) { arg = default; return(OperationStatus.NeedMoreData); } arg = new CommandArg(value, size, modifier); return(OperationStatus.Done); }
private void Laser(CommandModifier modifier) { Energy energy = GetComponent <Energy> (); if (energy != null) { float energyRequired = 30 * modifier.sizeModifier; if (energy.GetCurrentEnergy() > energyRequired) { m_WeaponManager.Fire(1, 1, modifier.sizeModifier, Vector3.up); energy.LoseEnergy(energyRequired); } } }
public CommandModifier GetModifiers(string[] words, int endIndex) { CommandModifier result = new CommandModifier(1, 1, 1); for (int i = 0; i < endIndex; i++) { string word = words [i]; result += new CommandModifier(m_SizeModifiers.GetModifier(word), m_NumberModifiers.GetModifier(word), m_SpeedModifiers.GetModifier(word) ); } return(result); }
public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { UndoCancelContext(); var b = new ByteBuf(); b.Append(Globs.HostToNet((int)TcpTpmCommands.SendCommand)); b.Append(new[] { active.ActiveLocality }); b.Append(Globs.HostToNet(inBuf.Length)); b.Append(inBuf); Write(CommandStream, b.GetBuffer()); outBuf = ReadVarArray(CommandStream); GetAck(CommandStream, "DispatchCommand"); }
public bool FireCommand(string command, CommandModifier modifier) { Command e = null; if (m_TextToInputMap.TryGetValue('"' + command + '"', out e)) { e.Invoke(modifier); return(true); } else { EventManager.TriggerEvent("WrongCommand", modifier); return(false); } }
public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { if (!PowerIsOn) { outBuf = new byte[0]; return; } TpmDllWrapper.NativeMethods._plat__LocalitySet(active.ActiveLocality); TpmDllWrapper.NativeMethods.ExecuteCommand((uint)inBuf.Length, inBuf, ref ResponseBufSize, ref ResponseBuf); outBuf = new byte[ResponseBufSize]; Marshal.Copy(ResponseBuf, outBuf, 0, (int)ResponseBufSize); }
public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { if (CommandCallbacks != null) { byte[] tempInBuf; CommandCallbacks.PreCallback(inBuf, out tempInBuf); if (tempInBuf != null) { inBuf = tempInBuf; } } Device.DispatchCommand(active, inBuf, out outBuf); if (CommandCallbacks != null) { CommandCallbacks.PostCallback(inBuf, outBuf); } }
// Send TPM-command buffer to device public override void DispatchCommand( CommandModifier mod, byte[] cmdBuf, out byte[] respBuf) { if (TrmDevice != null) { TrmDevice.DispatchCommand(mod, cmdBuf, out respBuf); return; } if (_tpmIO == null) { throw new InvalidOperationException("TPM context not created."); } _tpmIO.Write(cmdBuf, 0, cmdBuf.Length); int count = 0; int bytesRead = 0; do { bytesRead = _tpmIO.Read(_responseBuffer, 0, _responseBuffer.Length); if (bytesRead > 0) { break; } #if WINDOWS_UWP Task.Delay(TpmIORetryBackoffTime).Wait(); #else Thread.Sleep(TpmIORetryBackoffTime); #endif Debug.WriteLine($"TPM {_tpmDevicePath} retry {count}."); } while (count++ < TpmIORetryCount); if (bytesRead <= 0) { throw new IOException($"No response from {_tpmDevicePath}"); } respBuf = new byte[bytesRead]; Array.Copy(_responseBuffer, respBuf, bytesRead); }
private IDbCommandResult GetResultOf(string command) { if (command.Equals("reset")) { _cSharpEvaluator.Init(); return(new MessageResult(string.Format("C# Evaluator is reset"))); } command = CommandModifier.Modify(command); var builder = new StringBuilder(); builder.AppendFormat("Running: {0}", command).AppendLine(); var result = _cSharpEvaluator.Run(command); if (result.ResultSet) { if (result.Result == null) { return(new MessageResult("null")); } if (result.Result.IsCollection()) { return(_collectionConverter.Convert((IEnumerable)result.Result)); } if (result.Result.IsComplexType()) { return(_collectionConverter.Convert(new[] { result.Result })); } builder.AppendLine(result.Result == null ? "null" : result.Result.ToString()); } if (result.HasMessage) { builder.AppendLine(result.Message); } if (result.HasReport) { builder.AppendLine(result.Report); } return(new MessageResult(builder.ToString())); }
public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { if (TbsHandle == UIntPtr.Zero) { throw new Exception("TBS context not created."); } var resultBuf = new byte[4096]; uint resultByteCount = (uint)resultBuf.Length; TpmRc result = TpmRc.Success; TbsWrapper.TBS_RESULT tbsRes = TbsWrapper.NativeMethods. Tbsip_Submit_Command(TbsHandle, (TbsWrapper.TBS_COMMAND_LOCALITY)active.ActiveLocality, active.ActivePriority, inBuf, (uint)inBuf.Length, resultBuf, ref resultByteCount); string errMsg; if (tbsRes == TbsWrapper.TBS_RESULT.SUCCESS) { if (resultByteCount != 0) { outBuf = new byte[resultByteCount]; Array.Copy(resultBuf, outBuf, (int)resultByteCount); return; } result = TpmRc.TbsUnknownError; errMsg = Globs.GetResourceString("SubmitError2"); } else { errMsg = new Win32Exception((int)result).Message; } outBuf = TpmErrorHelpers.BuildErrorResponseBuffer(result); } // TbsDevice.DispatchCommand
public CommandArg(ulong value) { Value = value; if (value <= byte.MaxValue) { Size = 1; Modifier = CommandModifier.OneByte; } else if (value <= ushort.MaxValue) { Size = 2; Modifier = CommandModifier.TwoBytes; } else if (value <= uint.MaxValue) { Size = 4; Modifier = CommandModifier.FourBytes; } else { Size = 8; Modifier = CommandModifier.EightBytes; } }
private void Shield(CommandModifier cm) { requestStackPush((int)PlayerStates.ID.Shield); }
private void GodState(CommandModifier cm) { requestStackPop(); requestStackPush((int)PlayerStates.ID.God); }
public override void DispatchCommand(CommandModifier active, byte[] inBuf, out byte[] outBuf) { Tbs.DispatchCommand(this, active, inBuf, out outBuf); }
private void Fire(CommandModifier modifier) { m_WeaponManager.Fire(0, modifier.numberModifier, modifier.sizeModifier, Vector3.up); }
/// <summary> /// Dispatch a command to the underlying TPM. This method implements all significant functionality. /// DispatchCommand examines the command stream and performs (approximately) the following functions /// 1) If the command references a handle (session or transient object) then TBS makes sure that the entity /// is loaded. If it is, then the handle is "translated" to the underlying TPM handle. If it is not, then /// TBS checks to see if it has a saved context for the entity, and if so loads it. /// 2) If the command will fill a slot, then TBS ensures that a slot is available. It does this by ContextSaving /// the LRU entity of the proper type (that is not used in this command). /// </summary> /// <param name="caller"></param> /// <param name="active"></param> /// <param name="inBuf"></param> /// <param name="outBuf"></param> /// <exception cref="Exception"></exception> internal void DispatchCommand(TbsContext caller, CommandModifier active, byte[] inBuf, out byte[] outBuf) { lock (this) { CommandNumber++; // ReSharper disable once CompareOfFloatsByEqualityOperator if (StateSaveProbability != 0.0) { // S3 debug support DebugStateSave(); LastStateSaveCommandNumber = CommandNumber; } CommandHeader commandHeader; TpmHandle[] inHandles; SessionIn[] inSessions; byte[] commandParmsNoHandles; bool legalCommand = CommandProcessor.CrackCommand(inBuf, out commandHeader, out inHandles, out inSessions, out commandParmsNoHandles); if (!legalCommand) { // Is a diagnostics command. Pass through to TPM (a real RM would refuse). TpmDevice.DispatchCommand(active, inBuf, out outBuf); return; } TpmCc commandCode = commandHeader.CommandCode; // Lookup command CommandInfo command = Tpm2.CommandInfoFromCommandCode(commandCode); if (command == null) { throw new Exception("Unrecognized command"); } if (commandCode == TpmCc.ContextLoad || commandCode == TpmCc.ContextSave) { //throw new Exception("ContextLoad and ContextSave not supported in this build"); Console.Error.WriteLine("ContextLoad and ContextSave not supported in this build"); outBuf = Marshaller.GetTpmRepresentation(new Object[] { TpmSt.NoSessions, (uint)10, TpmRc.NotUsed }); } // Look up referenced objects and sessions ObjectContext[] neededObjects = GetReferencedObjects(caller, inHandles); ObjectContext[] neededSessions = GetSessions(caller, inSessions); if (neededObjects == null || neededSessions == null) { // This means that one or more of the handles was not registered for the context byte[] ret = FormatError(TpmRc.Handle); outBuf = ret; return; } // Load referenced objects and sessions (free slots if needed) bool loadOk = LoadEntities(neededObjects); bool loadOk2 = LoadEntities(neededSessions); if (!loadOk || !loadOk2) { throw new Exception("Failed to make space for objects or sessions at to execute command"); } // At this point everything referenced should be loaded, and there will be a free slot if needed // so we can translate the input handles to the underlying handles ReplaceHandlesIn(inHandles, inSessions, neededObjects, neededSessions); // create the translated command from the various components we have been manipulating byte[] commandBuf = CommandProcessor.CreateCommand(commandHeader.CommandCode, inHandles, inSessions, commandParmsNoHandles); Debug.Assert(commandBuf.Length == inBuf.Length); byte[] responseBuf; // Todo: Virtualize GetCapability for handle enumeration. // // Execute command on underlying TPM device. // If we get an ObjectMemory or SessionMemory error we try to make more space and try again // Note: If the TPM device throws an error above we let it propagate out. There should be no side // effects on TPM state that the TBS cares about. // do { TpmDevice.DispatchCommand(active, commandBuf, out responseBuf); TpmRc resCode = GetResultCode(responseBuf); if (resCode == TpmRc.Success) { break; } if (resCode == TpmRc.ObjectMemory) { bool slotMade = MakeSpace(SlotType.ObjectSlot, neededObjects); if (!slotMade) { throw new Exception("Failed to make an object slot in the TPM"); } continue; } if (resCode == TpmRc.SessionMemory) { bool slotMade = MakeSpace(SlotType.SessionSlot, neededSessions); if (!slotMade) { throw new Exception("Failed to make a session slot in the TPM"); } continue; } break; } while (true); // Parse the response from the TPM // TODO: Make this use the new methods in Tpm2 // ReSharper disable once UnusedVariable var mOut = new Marshaller(responseBuf); TpmSt responseTag; uint responseParamSize; TpmRc resultCode; TpmHandle[] responseHandles; SessionOut[] responseSessions; byte[] responseParmsNoHandles, responseParmsWithHandles; CommandProcessor.SplitResponse(responseBuf, command.HandleCountOut, out responseTag, out responseParamSize, out resultCode, out responseHandles, out responseSessions, out responseParmsNoHandles, out responseParmsWithHandles); // If we have an error there is no impact on the loaded sessions, but we update // the LRU values because the user will likely try again. if (resultCode != TpmRc.Success) { outBuf = responseBuf; UpdateLastUseCount(new[] { neededObjects, neededSessions }); return; } // Update TBS database with any newly created TPM objects ProcessUpdatedTpmState(caller, command, responseHandles, neededObjects); // And if there were any newly created objects use the new DB entries to translate the handles ReplaceHandlesOut(responseHandles); byte[] translatedResponse = CommandProcessor.CreateResponse(resultCode, responseHandles, responseSessions, responseParmsNoHandles); outBuf = translatedResponse; Debug.Assert(outBuf.Length == responseBuf.Length); } // lock(this) }
// Send TPM-command buffer to device public virtual void DispatchCommand(CommandModifier mod, byte[] cmdBuf, out byte[] respBuf) { throw new Exception("Tpm2Device.DispatchCommand: Should never be here"); }
private void MoveLeft(CommandModifier modifier) { m_Body.Move(-1 * modifier.speedModifier, 0); }
/// <summary> /// Dispatch a command to the underlying TPM. This method implements all /// significant functionality. It examines the command stream and performs /// (approximately) the following actions: /// 1) If the command references a handle (session or transient object), then /// TBS makes sure that the entity is loaded. If it is, then the handle is /// "translated" to the underlying TPM handle. If it is not, then TBS checks /// to see if it has a saved context for the entity, and if so, loads it. /// 2) If the command will fill a slot, then TBS ensures that a slot is available. /// It does this by ContextSaving the LRU entity of the proper type (that is /// not used in this command). /// </summary> /// <param name="caller"></param> /// <param name="active"></param> /// <param name="inBuf"></param> /// <param name="outBuf"></param> /// <exception cref="Exception"></exception> internal void DispatchCommand(TbsContext caller, CommandModifier active, byte[] inBuf, out byte[] outBuf) { lock (this) { CommandNumber++; // ReSharper disable once CompareOfFloatsByEqualityOperator if (StateSaveProbability != 0.0) { // S3 debug support DebugStateSave(); LastStateSaveCommandNumber = CommandNumber; } CommandHeader commandHeader; TpmHandle[] inHandles; SessionIn[] inSessions; byte[] commandParmsNoHandles; bool legalCommand = CommandProcessor.CrackCommand(inBuf, out commandHeader, out inHandles, out inSessions, out commandParmsNoHandles); if (!legalCommand) { // Is a diagnostics command. Pass through to TPM (a real RM would refuse). TpmDevice.DispatchCommand(active, inBuf, out outBuf); return; } TpmCc cc = commandHeader.CommandCode; // Lookup command CommandInfo command = Tpm2.CommandInfoFromCommandCode(cc); if (command == null) { throw new Exception("Unrecognized command"); } if (cc == TpmCc.ContextLoad || cc == TpmCc.ContextSave) { Debug.WriteLine("ContextLoad and ContextSave are not supported in this build"); outBuf = Marshaller.GetTpmRepresentation(new Object[] { TpmSt.NoSessions, (uint)10, TpmRc.NotUsed }); } // Look up referenced objects and sessions ObjectContext[] neededObjects = GetReferencedObjects(caller, inHandles); ObjectContext[] neededSessions = GetSessions(caller, inSessions); ObjectContext[] neededEntities = neededObjects != null ? neededSessions != null ? neededObjects.Concat(neededSessions).ToArray() : neededObjects : neededSessions; #if false // LibTester may intentionally use invalid handles, therefore it always // work in the passthru mode (all correctness checks by TSS infra suppressed) if (!Tpm2._TssBehavior.Passthrough && (neededObjects == null || neededSessions == null)) #endif if (neededObjects == null || neededSessions == null) { // One or more of the handles was not registered for the context byte[] ret = FormatError(TpmRc.Handle); outBuf = ret; return; } // Load referenced objects and sessions (free slots if needed) // It's important to load all object and session handles in a single call // to LoadEntities(), as for some commands (e.g. GetSessionAuditDigest) // the objects array may contain session handles. In this case the session // handles loaded by the invocation of LoadEntities for neededObjects // may be evicted again during the subsequent call for neededSessions. var expectedResponses = Tpm._GetExpectedResponses(); if (!LoadEntities(neededEntities)) { throw new Exception("Failed to make space for objects or sessions"); } else { // At this point everything referenced should be loaded, and // there will be a free slot if needed so we can translate // the input handles to the underlying handles ReplaceHandlesIn(inHandles, inSessions, neededObjects, neededSessions); } // Re-create the command using translated object and session handles byte[] commandBuf = CommandProcessor.CreateCommand(commandHeader.CommandCode, inHandles, inSessions, commandParmsNoHandles); if (!Tpm2._TssBehavior.Passthrough) { Debug.Assert(commandBuf.Length == inBuf.Length); } byte[] responseBuf; // TODO: Virtualize TPM2_GetCapability() for handle enumeration. // // Execute command on underlying TPM device. // If we get an ObjectMemory or SessionMemory error we try to make more space and try again // Note: If the TPM device throws an error above we let it propagate out. There should be no side // effects on TPM state that the TBS cares about. // ulong firstCtxSeqNum = 0; while (true) { Tpm._ExpectResponses(expectedResponses); TpmDevice.DispatchCommand(active, commandBuf, out responseBuf); TpmRc res = GetResultCode(responseBuf); if (res == TpmRc.Success || expectedResponses != null && expectedResponses.Contains(res)) { break; } if (res == TpmRc.ContextGap) { ulong seqNum = ShortenSessionContextGap(firstCtxSeqNum); if (seqNum == 0) { break; // Failed to handle CONTEXT_GAP error } if (firstCtxSeqNum == 0) { firstCtxSeqNum = seqNum; } //if (firstCtxSeqNum != 0) // Console.WriteLine("DispatchCommand: CONTEXT_GAP handled"); continue; } var slotType = SlotType.NoSlot; if (res == TpmRc.ObjectHandles || res == TpmRc.ObjectMemory) { slotType = SlotType.ObjectSlot; } else if (res == TpmRc.SessionHandles || res == TpmRc.SessionMemory) { slotType = SlotType.SessionSlot; } else { // Command failure not related to resources break; } if (!MakeSpace(slotType, neededEntities)) { // Failed to make an object slot in the TPM responseBuf = TpmErrorHelpers.BuildErrorResponseBuffer(TpmRc.Memory); break; } } // Parse the response from the TPM TpmSt responseTag; uint responseParamSize; TpmRc resultCode; TpmHandle[] responseHandles; SessionOut[] responseSessions; byte[] responseParmsNoHandles, responseParmsWithHandles; CommandProcessor.SplitResponse(responseBuf, command.HandleCountOut, out responseTag, out responseParamSize, out resultCode, out responseHandles, out responseSessions, out responseParmsNoHandles, out responseParmsWithHandles); // In case of an error there is no impact on the loaded sessions, but // we update the LRU values because the user will likely try again. if (resultCode != TpmRc.Success) { outBuf = responseBuf; UpdateLastUseCount(new[] { neededObjects, neededSessions }); return; } // Update TBS database with any newly created TPM objects ProcessUpdatedTpmState(caller, command, responseHandles, neededObjects); // And if there were any newly created objects use the new DB entries // to translate the handles ReplaceHandlesOut(responseHandles); outBuf = CommandProcessor.CreateResponse(resultCode, responseHandles, responseSessions, responseParmsNoHandles); Debug.Assert(outBuf.Length == responseBuf.Length); } // lock(this) }
private void MoveRight(CommandModifier modifier) { m_Body.Move(1 * modifier.speedModifier, 0); }
private void ExitGodState(CommandModifier cm) { requestStackPop(); requestStackPush((int)PlayerStates.ID.Normal); }
private void MoveStop(CommandModifier modifier) { m_Body.Move(0, 0); }