private unsafe void SetCapacity(int value) { if (internalCapacity < internalCount) { throw new System.ArgumentOutOfRangeException("value", "internalCapacity is set to a value that is than internalCount."); } if (value != 0) { value = (int)MemoryUtil.NextPowerOf2((uint)value); if (value < 4) { value = 4; } } internalCapacity = value; if (internalArray != null) { T[] oldArray = internalArray; T[] newArray = new T[internalCapacity]; for (int i = 0; i < internalCount; i++) { newArray[i] = oldArray[i]; } internalArray = newArray; // TODO: remove this and mark as deprecated when GC is working MemoryManager.Free(Stubs.GetPointerFromObject(oldArray)); } else { if (internalCapacity > 0) { internalArray = new T[internalCapacity]; } else { internalArray = null; } internalCount = 0; } }
public void String_AfterSettingSafeString_returnsStringOfSafeString() { //Arrange var sut = GetSut(); const string expected = "갿äÅ++¨¨'e"; var safeString = Stubs.Get <ISafeString>(); foreach (var ch in expected.ToCharArray()) { safeString.Append(ch); } //Act sut.SafeString = safeString; var actual = sut.String; //Assert Assert.That(actual, Is.EqualTo(expected)); }
public void BlockSizeInBytes_GivenEncryptor_ReturnsFromEncryptor() { // Arrange const int encryptorBlockSizeInBits = 32; const int expected = 4; var mock = new Mock <IFastEncryptor>(); mock.SetupGet(e => e.BlockSizeInBits) .Returns(encryptorBlockSizeInBits); var protector = new MemoryProtector( encryptor: mock.Object, random: Stubs.Get <IFastRandom>()); // Act var actual = protector.BlockSizeInBytes; // Assert Assert.AreEqual(expected, actual); }
public void When_adding_stuff_they_should_be_available() { // Arrange var repo = iocContainer.GetInstance <IRepository <Todo> >(); var todos = Stubs.CreateTodos(); var todoCount = todos.Count(); // Act foreach (var todo in todos) { repo.Create(todo); } var items = repo.ItemsWhere(p => true).ToList(); // Assert Assert.That( items.Count, Is.EqualTo(todoCount)); }
public async Task InsertAsyncISafeBytes_IndexHigherThanLength_ThrowsArgumentOutOfRangeException( [Random(0, 256, 1)] int i) { // Arrange using var sut = GetSut(); var safeBytes = Stubs.Get <ISafeBytes>(); await safeBytes.AppendAsync((byte)i); await sut.AppendAsync(safeBytes); var index = sut.Length + 1; // Act Task CallOnDisposedObject() => sut.InsertAsync(index, safeBytes); // Assert Assert.ThrowsAsync <ArgumentOutOfRangeException>(CallOnDisposedObject); }
internal static IRQCallBack[] callBacks; //TODO: create list per IRQ (for shared IRQs) #region Constructor internal IRQHandler16bit(byte irq) { spinLock.Enter(); if (irqs == null) { irqs = new bool[16]; callBacks = new IRQCallBack[16]; } this.irq = irq; IDT.Interrupt interrupt = (IDT.Interrupt)(irq + 0x20); IDT.RegisterIRQ(interrupt, Stubs.GetFunctionPointer(INTERRUPT16BIT_HANDLER)); spinLock.Exit(); }
private static IFastEncryptor GetSut( BlowfishCipherMode?cipherMode = null, ICryptoRandom random = null, PaddingMode paddingMode = PaddingMode.PKCS7, IPadder padder = null) { IPadderFactory factory = null; if (padder != null) { var factoryMock = new Mock <IPadderFactory>(); factoryMock.Setup(p => p.GetPadder(paddingMode)) .Returns(padder); factory = factoryMock.Object; } return(new BlowfishEncryptor(cipherMode ?? BlowfishCipherMode.Cbc, paddingMode, random ?? Stubs.Get <IFastRandom>(), factory ?? Stubs.Get <IPadderFactory>())); }
public void String_AfterDisposingTheInstance_doesNotReturnPlainText() { //Arrange var sut = GetSut(); const string plainText = "testString"; var safeString = Stubs.Get <ISafeString>(); foreach (var ch in plainText.ToCharArray()) { safeString.Append(ch); } //Act sut.SafeString = safeString; sut.Dispose(); var actual = sut.String; //assert Assert.That(actual, Is.Not.EqualTo(plainText)); }
public void SetUp() { cacheKey = Stubs.GetCacheKey(); var mockedCache = Create.MockedMemoryCache(); _dataManager = new Mock <IDataManager>(); _logger = new Mock <ILogger <HomeController> >(); _memoryCache = mockedCache; _utils = new Mock <IUtil>(); _controller = new HomeController( _dataManager.Object, _logger.Object, _utils.Object, _memoryCache ) { TempData = new Mock <TempDataDictionary>(new DefaultHttpContext(), Mock.Of <ITempDataProvider>()).Object }; }
public void When_deleting_something_it_should_be_removed_from_repo() { // Arrange var repo = iocContainer.GetInstance <IRepository <Todo> >(); foreach (var todo in Stubs.CreateTodos()) { repo.Create(todo); } var countBeforeDelete = repo.Items.Count(); // Act var id = repo.Items.First().Id; repo.Delete(repo.ItemBy(p => p.Id == id)); var countAfterDelete = repo.Items.Count(); // Assert Assert.That(countBeforeDelete, Is.GreaterThan(countAfterDelete)); }
public void When_updating_something_it_should_update() { // Arrange var repo = iocContainer.GetInstance <IRepository <Todo> >(); foreach (var todo in Stubs.CreateTodos()) { repo.Create(todo); } // Act var modelToUpdate = repo.Items.First(); modelToUpdate.Caption = "Buy more milk"; repo.Update(modelToUpdate); var items = repo.ItemsWhere(p => p.Caption == "Buy more milk").ToList(); // Assert Assert.That( items.Count, Is.EqualTo(1)); }
public void InsertISafeBytes_InsertingCharsTwice_increasesLength([Random(0, 256, 1)] int i1, [Random(0, 256, 1)] int i2) { //Arrange var sut = GetSut(); var insertPos = 0; var safeBytes1 = Stubs.Get <ISafeBytes>().AppendAndReturnDeepClone((byte)i1); var safeBytes2 = Stubs.Get <ISafeBytes>().AppendAndReturnDeepClone((byte)i2); int expected1 = 1, expected2 = 2; //Act sut.Insert(insertPos, safeBytes1); var actual1 = sut.Length; sut.Insert(insertPos, safeBytes2); var actual2 = sut.Length; //Assert Assert.That(actual1, Is.EqualTo(expected1)); Assert.That(actual2, Is.EqualTo(expected2)); }
private static IInjectionDetector GetSut(bool protectCode = true, bool protectState = true, bool isStateValid = true, bool isCodeValid = true, IStamper <object> stateStamper = null, IStamper <Type> codeStamper = null, IInjectionAlerter alerter = null, InjectionAlertChannel channel = Defaults.AlertChannel) { var codeStampMock = new Mock <IStamp>(); codeStampMock.Setup(m => m.Equals(It.IsAny <IStamp <int> >())).Returns(isCodeValid); var stateStampMock = new Mock <IStamp>(); stateStampMock.Setup(m => m.Equals(It.IsAny <IStamp <int> >())).Returns(isStateValid); var stateStamperMock = new Mock <IStamper <object> >(); stateStamperMock.Setup(m => m.GetStamp(It.IsAny <object>())).Returns(stateStampMock.Object); var codeStamperMock = new Mock <IStamper <Type> >(); codeStamperMock.Setup(m => m.GetStamp(It.IsAny <Type>())).Returns(codeStampMock.Object); return(new InjectionDetector(alerter ?? Mock.Of <IInjectionAlerter>(), Stubs.Get <ITypeIdGenerator>(), stateStamper ?? stateStamperMock.Object, codeStamper ?? codeStamperMock.Object, protectCode, protectState, channel)); }
/// <summary> /// Costruct with specific options. /// </summary> /// <param name="arguments">The collection of options used by stubby.</param> public Stubby(IArguments arguments) { _arguments = arguments ?? new Arguments { Mute = true }; _admin = arguments.DisableAdmin ? null : new Admin(_endpointDb); _stubs = new Stubs(_endpointDb); Out.Mute = _arguments.Mute; LoadEndpoints(); if (!_arguments.Watch) { return; } _watcher.Path = Path.GetDirectoryName(_arguments.Data); _watcher.Filter = Path.GetFileName(_arguments.Data); _watcher.Changed += OnDatafileChange; _watcher.EnableRaisingEvents = _arguments.Watch; }
/// <summary> /// Initializes the system clock. First the hardware time is read /// and stored as the boot time and current time. The times are /// stored as 64-bit unsigned integers with 100-nanosecond ticks /// since the epoch (January 1, 0001, 00:00:00). A handler is added /// to the system timer event which updates the current time and /// handles periodic synchronization with the hardware time. The /// amount added to the current time per timer fire is relevant /// to the frequency reportedly used by the system timer. /// </summary> public static unsafe void Setup() { Time time = null; EventRegisterStatus st = EventRegisterStatus.Success; // Read the hardware time currentTime = new Time(); GetHardwareTime(currentTime); bootTime = GetCurrentTimestamp(); // Install the clock handler st = Timer.RegisterTimerEvent(Stubs.GetFunctionPointer(CLOCK_HANDLER)); if (st != EventRegisterStatus.Success) { Diagnostics.Error("Failed to register clock handler"); } // Debug time = currentTime; TextMode.Write("Current time: "); TextMode.Write(time.Year); TextMode.Write("/"); TextMode.Write(time.Month); TextMode.Write("/"); TextMode.Write(time.Day); TextMode.Write(" "); TextMode.Write(time.Hour); TextMode.Write(":"); TextMode.Write(time.Minute); TextMode.Write(":"); TextMode.Write(time.Second); TextMode.WriteLine(); internalTime = new Time(); }
public async Task AppendAsyncBytes_Utf16LittleEndian_BytesAreSame() { // Arrange var textServiceMock = new Mock <ITextService>(); var expected = new byte[] { 104, 0, 101, 0, 108, 0, 108, 0, 111, 0 }; /*hello*/ using var sut = GetSut(textService: textServiceMock.Object); var safeBytes = Stubs.Get <ISafeBytes>(); foreach (var @byte in expected) { await safeBytes.AppendAsync(@byte); } // Act await sut.AppendAsync(safeBytes); var actual = await sut.RevealDecryptedBytesAsync(); // Assert Assert.AreEqual(expected, actual); }
public async Task AppendManyAsync_MultipleBytes_AppendsToInternalCollection() { // Arrange const byte firstByte = 55, secondByte = 77; var expected = Stubs.Get <ISafeBytes>(); var stream = new SafeMemoryStream(new [] { firstByte, secondByte }); await expected.AppendManyAsync(stream); var collection = Stubs.Get <ISafeByteCollection>(); using var sut = GetSut(collection: collection); // Act await sut.AppendAsync(expected); // Assert var actual = await collection.GetAllAsync(); Assert.AreEqual(2, actual.Length); Assert.AreEqual(firstByte, actual.ElementAt(0).RevealDecryptedByteAsync().Result); Assert.AreEqual(secondByte, actual.ElementAt(1).RevealDecryptedByteAsync().Result); }
public static void GetHelp(CommandExecutionContext *context) { if (context->parameters == null || context->parameters->Length == 0) { ADC.MemoryUtil.Call((void *)Stubs.GetFunctionPointer(lblExecute), (void *)context); } else { CommandExecutionAttemptResult result; result = Prompter.CommandTable->HandleLine(context->parameters, false, true); if (result == CommandExecutionAttemptResult.NotFound) { int indexOfSpace = context->parameters->IndexOf(" "); CString8 *tempStr; if (indexOfSpace >= 0) { tempStr = context->parameters->Substring(0, indexOfSpace); } else { tempStr = CString8.Copy(context->parameters); } TextMode.Write("No command '"); TextMode.Write(tempStr); TextMode.WriteLine("' is available to retrieve help for."); TextMode.WriteLine(CommandTableHeader.inform_USE_HELP_COMMANDS); CString8.DISPOSE(tempStr); return; } if (result == CommandExecutionAttemptResult.BlankEntry) { ADC.MemoryUtil.Call((void *)Stubs.GetFunctionPointer(Help.lblGetHelp), (void *)context); } } }
public async Task GenerateAsync_GenerateInvokesHashMethodOfHasher_returnsTrue() { // Arrange var mockHasher = new Mock <IFastHasher>(); var sequence = mockHasher.SetupSequence(m => m.ComputeFast(It.IsAny <byte[]>())); for (var i = 0; i < 256; i++) { sequence.Returns(i); } var salt = Stubs.Get <IMemoryProtectedBytes>(); var sut = GetSut(mockHasher.Object, sessionSalt: salt); await sut.GenerateAsync(It.IsAny <byte>()); // To ensure salt is initialized mockHasher.Reset(); // Act await sut.GenerateAsync(It.IsAny <byte>()); // Assert mockHasher.Verify(x => x.ComputeFast(It.IsNotNull <byte[]>()), Times.Exactly(1)); }
public async Task Salt_HasherProducesDifferentResults_IsSet() { // Arrange var mockHasher = new Mock <IFastHasher>(); var sequence = mockHasher.SetupSequence(m => m.ComputeFast(It.IsAny <byte[]>())); for (var i = 0; i < 256; i++) { sequence.Returns(i); } var salt = Stubs.Get <IMemoryProtectedBytes>(); var sut = GetSut(mockHasher.Object, sessionSalt: salt); // Act _ = await sut.GenerateAsync(5); // to trigger lazy initialization var sessionSalt = (await salt.RevealDecryptedBytesAsync()).PlainBytes; // Assert Assert.That(sessionSalt, Is.Not.Null); Assert.That(sessionSalt, Is.Not.Empty); Assert.That(sessionSalt, Has.Length.EqualTo(salt.BlockSizeInBytes)); }
public async Task AppendAsyncByte_UnknownISafeBytes_AppendsToInternalCollection() { // Arrange const byte firstByte = 55, secondByte = 77; var expected = new SafeBytesFaker() .Provide(); await expected.AppendAsync(firstByte); await expected.AppendAsync(secondByte); var collection = Stubs.Get <ISafeByteCollection>(); using var sut = GetSut(collection: collection); // Act await sut.AppendAsync(expected); // Assert var actual = await collection.GetAllAsync(); Assert.AreEqual(2, actual.Length); Assert.AreEqual(firstByte, actual.ElementAt(0).RevealDecryptedByteAsync().Result); Assert.AreEqual(secondByte, actual.ElementAt(1).RevealDecryptedByteAsync().Result); }
public void EnumerateItemsAllocatesChunks() { var jobResponse = Stubs.BuildJobResponse( Stubs.Chunk1(null, false, false), Stubs.Chunk2(Stubs.NodeId2, true, false), Stubs.Chunk3(null, false, false) ); var node1Client = new Mock <IDs3Client>(MockBehavior.Strict).Object; var node2Client = new Mock <IDs3Client>(MockBehavior.Strict).Object; var clientFactory = new Mock <IDs3ClientFactory>(MockBehavior.Strict); clientFactory.Setup(cf => cf.GetClientForNodeId(Stubs.NodeId1)).Returns(node1Client); clientFactory.Setup(cf => cf.GetClientForNodeId(Stubs.NodeId2)).Returns(node2Client); var client = new Mock <IDs3Client>(MockBehavior.Strict); client.Setup(c => c.BuildFactory(Stubs.Nodes)).Returns(clientFactory.Object); client .SetupSequence(c => c.AllocateJobChunk(Allocate(Stubs.ChunkId1))) .Returns(AllocateJobChunkResponse.RetryAfter(TimeSpan.FromMinutes(5))) .Returns(AllocateJobChunkResponse.Success(Stubs.Chunk1(Stubs.NodeId1, false, false))) .Returns(AllocateJobChunkResponse.Success(Stubs.Chunk1(Stubs.NodeId1, true, false))) .Returns(AllocateJobChunkResponse.ChunkGone); client .SetupSequence(c => c.AllocateJobChunk(Allocate(Stubs.ChunkId2))) .Returns(AllocateJobChunkResponse.Success(Stubs.Chunk2(Stubs.NodeId2, true, false))) .Returns(AllocateJobChunkResponse.Success(Stubs.Chunk2(Stubs.NodeId2, true, true))); client .SetupSequence(c => c.AllocateJobChunk(Allocate(Stubs.ChunkId3))) .Returns(AllocateJobChunkResponse.RetryAfter(TimeSpan.FromMinutes(3))) .Returns(AllocateJobChunkResponse.RetryAfter(TimeSpan.FromMinutes(1))) .Returns(AllocateJobChunkResponse.Success(Stubs.Chunk3(Stubs.NodeId2, false, false))); var sleeps = new List <TimeSpan>(); var source = new WriteTransferItemSource(sleeps.Add, client.Object, jobResponse); var transfers1 = source.EnumerateAvailableTransfers().Take(1).ToArray(); var transfers2 = source.EnumerateAvailableTransfers().Take(2).ToArray(); var transfers3 = source.EnumerateAvailableTransfers().ToArray(); CollectionAssert.AreEqual( new[] { new TransferItem(node1Client, new Blob(Range.ByLength(0, 15), "bar")), }, transfers1, new TransferItemSourceHelpers.TransferItemComparer() ); CollectionAssert.AreEqual( new[] { new TransferItem(node1Client, new Blob(Range.ByLength(10, 10), "foo")), new TransferItem(node2Client, new Blob(Range.ByLength(15, 20), "bar")), }, transfers2, new TransferItemSourceHelpers.TransferItemComparer() ); CollectionAssert.AreEqual( new[] { new TransferItem(node2Client, new Blob(Range.ByLength(0, 10), "hello")), new TransferItem(node2Client, new Blob(Range.ByLength(35, 11), "bar")) }, transfers3, new TransferItemSourceHelpers.TransferItemComparer() ); CollectionAssert.AreEqual( new[] { TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(1), }, sleeps ); client.VerifyAll(); clientFactory.VerifyAll(); }
public void Init() { _statisticsProvider = Stubs.BareMock <IProcessorStatisticsProvider>(); }
public static void __Test1() { byte *ptr1 = (byte *)Stubs.CString("US"), ptr2 = (byte *)Stubs.CString("SK"); byte *longer = (byte *)Stubs.CString("The US"); //Test constant CString buffers Testcase.Test(ByteString.Compare(ptr1, ptr2) != 0, "ByteString.Compare()", "Comparing: 'US' != 'SK'"); Testcase.Test(ByteString.Compare(ptr1, ptr1) == 0, "ByteString.Compare()", "Comparing: 'US' == 'US'"); Testcase.Test(ByteString.Compare(ptr1, 1, ptr1, 1, 1) == 0, "ByteString.Compare()", "Comparing substrings: 'U[S]' == 'U[S]'"); Testcase.Test(ByteString.Compare(longer, 4, ptr1, 0, 2) == 0, "ByteString.Compare()", "Comparing substrings: 'The [US]' == 'US'"); Testcase.Test(ByteString.Compare(longer, 4, ptr1, 0, 0) == 0, "ByteString.Compare()", "Comparing substrings: 'The [US]' == 'US' (count=0)"); //Test constant CString buffer with constant String type Testcase.Test(ByteString.Compare(ptr1, "SK") != 0, "ByteString.Compare()", "Comparing byte* and string constant: 'US' != const 'SK'"); Testcase.Test(ByteString.Compare(ptr1, "US") == 0, "ByteString.Compare()", "Comparing byte* and string constant: 'US' == const 'US'"); Testcase.Test(ByteString.Compare(longer, 4, "US", 0, 2) == 0, "ByteString.Compare()", "Comparing byte* substring and string constant: 'The [US]' == const 'US'"); Testcase.Test(ByteString.Compare(longer, 4, "US", 0, 2) == 0, "ByteString.Compare()", "Comparing byte* substring and string constant: 'The [US]' == const 'US' (count=2)"); Testcase.Test(ByteString.Compare(longer, 4, "US", 0, 0) == 0, "ByteString.Compare()", "Comparing byte* substring and string constant: 'The [US]' == const 'US' (count=0)"); //Test that constant String is working properly const string str1 = "US"; const string str2 = "SK"; Testcase.Test((byte)str1 [0] == (byte)'U', "ByteString", "Testing string constants: (byte)\"US\" [0] == (byte)'U'"); Testcase.Test((byte)str1 [1] == (byte)'S', "ByteString", "Testing string constants: (byte)\"US\" [1] == (byte)'S'"); Testcase.Test(str1.Length == 2, "ByteString", "Testing string constant length: \"US\".Length == 2"); Testcase.Test((byte)str1 [1] == (byte)str2 [0], "ByteString", "Testing string constants: (byte)\"US\" [1] == (byte)\"SK\" [0]"); // FIXME: This testcase does not test ByteString, but the string constants.... where should it go? Testcase.Test("\n".Length == 1, "ByteString", "Testing string constants: Length of newline (\"\\n\".Length == 1"); }
private ISafeByte GetSafeByteFor(byte b) { var safeByteFactory = Stubs.Get <ISafeByteFactory>(); return(safeByteFactory.GetByByte(b)); }
/* * // sigh.. one can only dream * public delegate void somefunction(uint value); * unsafe static somefunction[] timerEvents = (somefunction[])Stubs.StaticAlloc<somefunction>(Kernel.MaxEventHandlers); * public event somefunction function * { * add * { * for (int x = 0; x < Kernel.MaxEventHandlers; ++x) * if (timerEvents[x] == value) * return; * * for (int x = 0; x < Kernel.MaxEventHandlers; ++x) * if (timerEvents[x] == null) * timerEvents[x] = value; * } * remove * { * for (int x = 0; x < Kernel.MaxEventHandlers; ++x) * if (timerEvents[x] == value) * timerEvents[x] = null; * } * } */ #region Setup public static void Setup() { SetTimerFrequency(HZ); IDT.RegisterIRQ(IDT.Interrupt.SystemTimer, Stubs.GetFunctionPointer(TIMER_HANDLER)); }
private static IByteArrayProtector GetSut(IFastEncryptor encryptor = null, IFastRandom random = null) => new MemoryProtector( encryptor: encryptor ?? Stubs.Get <IFastEncryptor>(), random: random ?? Stubs.Get <IFastRandom>());
public static void Setup() { IDT.RegisterIRQ(IDT.Interrupt.DivideError, Stubs.GetFunctionPointer(DIVIDE_ERROR)); }
private IFastEncryptor GetSut(BlowfishCipherMode cipherMode) => new BlowfishEncryptor(cipherMode, Stubs.Get <IFastRandom>());
protected IFastEncryptor GetSut(ICryptoRandom random = null) => new BlowfishEncryptor(random ?? Stubs.Get <IFastRandom>());