Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/CalcManager/CalcManager.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>false</CompileAsWinRT>
<SDLCheck>true</SDLCheck>
<ControlFlowGuard>Guard</ControlFlowGuard>
<AdditionalOptions>/Zm250 /std:c++20 /permissive- /Zc:twoPhase- /utf-8 /w44242 %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>$(SolutionDir)..\src\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<WarningLevel>Level4</WarningLevel>
Expand Down Expand Up @@ -167,6 +168,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>false</CompileAsWinRT>
<SDLCheck>true</SDLCheck>
<ControlFlowGuard>Guard</ControlFlowGuard>
<AdditionalOptions>/Zm250 /std:c++20 /permissive- /Zc:twoPhase- /utf-8 /w44242 %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>$(SolutionDir)..\src\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<WarningLevel>Level4</WarningLevel>
Expand Down Expand Up @@ -202,6 +204,7 @@
<PrecompiledHeader>Use</PrecompiledHeader>
<CompileAsWinRT>false</CompileAsWinRT>
<SDLCheck>true</SDLCheck>
<ControlFlowGuard>Guard</ControlFlowGuard>
<AdditionalOptions>/Zm250 /std:c++20 /permissive- /Zc:twoPhase- /utf-8 /w44242 %(AdditionalOptions)</AdditionalOptions>
<AdditionalIncludeDirectories>$(SolutionDir)..\src\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<WarningLevel>Level4</WarningLevel>
Expand Down
46 changes: 21 additions & 25 deletions src/CalcManager/Ratpack/conv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1500,34 +1500,30 @@ void numpowi32(_Inout_ PNUMBER* proot, int32_t power, uint32_t radix, int32_t pr
void ratpowi32(_Inout_ PRAT* proot, int32_t power, int32_t precision)

{
if (power < 0)
{
// Take the positive power and invert answer.
PNUMBER pnumtemp = nullptr;
ratpowi32(proot, -power, precision);
pnumtemp = (*proot)->pp;
(*proot)->pp = (*proot)->pq;
(*proot)->pq = pnumtemp;
}
else
{
PRAT lret = nullptr;
const bool invertResult = power < 0;
uint32_t magnitude =
invertResult ? static_cast<uint32_t>(-static_cast<int64_t>(power)) : static_cast<uint32_t>(power);

lret = i32torat(1);
PRAT lret = i32torat(1);

while (power > 0)
while (magnitude > 0)
{
if (magnitude & 1)
{
if (power & 1)
{
mulnumx(&(lret->pp), (*proot)->pp);
mulnumx(&(lret->pq), (*proot)->pq);
}
mulrat(proot, *proot, precision);
trimit(&lret, precision);
trimit(proot, precision);
power >>= 1;
mulnumx(&(lret->pp), (*proot)->pp);
mulnumx(&(lret->pq), (*proot)->pq);
}
destroyrat(*proot);
*proot = lret;
mulrat(proot, *proot, precision);
trimit(&lret, precision);
trimit(proot, precision);
magnitude >>= 1;
}
destroyrat(*proot);
*proot = lret;

if (invertResult)
{
// Invert after exponentiation so INT32_MIN never needs to be negated as an int32_t.
std::swap((*proot)->pp, (*proot)->pq);
}
}
104 changes: 104 additions & 0 deletions src/Calculator.Tests/StandardCalculatorViewModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CalcManager.Interop;
using CalculatorApp.ViewModel;
using CalculatorApp.ViewModel.Common;
using CalculatorApp.ViewModel.Snapshot;

namespace Calculator.Tests
{
Expand Down Expand Up @@ -152,6 +154,58 @@ private void ValidateViewModelValueAndSecondaryExpression(string value, string e
}
}

private void ValidateSnapshotReplayRejectsInvalidCommands(bool includeExpression)
{
int[] invalidCommands =
{
(int)CalculatorCommand.CommandEQU,
(int)CalculatorCommand.CommandCLEAR,
(int)CalculatorCommand.CommandCENTR,
(int)CalculatorCommand.CommandBACK,
(int)CalculatorCommand.CommandMCLEAR,
-1,
int.MaxValue
};

foreach (int invalidCommand in invalidCommands)
{
var snapshot = new StandardCalculatorSnapshot();
if (includeExpression)
{
snapshot.ExpressionDisplay = new ExpressionDisplaySnapshot();
}
AppendSnapshotOperand(snapshot, (int)CalculatorCommand.Command1);
AppendSnapshotBinaryCommand(snapshot, invalidCommand);
AppendSnapshotOperand(snapshot, (int)CalculatorCommand.Command2);

_viewModel.Snapshot = snapshot;

ValidateViewModelValue("12");
}
}

private static void AppendSnapshotOperand(StandardCalculatorSnapshot snapshot, int command)
{
snapshot.DisplayCommands.Add(new ExpressionCommandWrapper(
CommandType.OperandCommand,
0,
new[] { command },
false,
false,
false));
}

private static void AppendSnapshotBinaryCommand(StandardCalculatorSnapshot snapshot, int command)
{
snapshot.DisplayCommands.Add(new ExpressionCommandWrapper(
CommandType.BinaryCommand,
command,
Array.Empty<int>(),
false,
false,
false));
}

#endregion

#region Constructor Tests
Expand All @@ -173,6 +227,56 @@ public void ViewModelConstructorButtonPressedInitializedTest()
Assert.IsNotNull(vm.ButtonPressed);
}

[TestMethod]
public void SnapshotReplayRejectsInvalidCommandsWithoutExpression()
{
ValidateSnapshotReplayRejectsInvalidCommands(false);
}

[TestMethod]
public void SnapshotReplayRejectsInvalidCommandsWithExpression()
{
ValidateSnapshotReplayRejectsInvalidCommands(true);
}

[TestMethod]
public void SnapshotReplayRejectsModeCommands()
{
int[] modeCommands =
{
(int)NumbersAndOperatorsEnum.Degree,
(int)NumbersAndOperatorsEnum.Radians,
(int)NumbersAndOperatorsEnum.Grads
};

foreach (int modeCommand in modeCommands)
{
var snapshot = new StandardCalculatorSnapshot();
AppendSnapshotBinaryCommand(snapshot, modeCommand);
AppendSnapshotOperand(snapshot, (int)CalculatorCommand.Command9);
AppendSnapshotOperand(snapshot, (int)CalculatorCommand.Command0);
AppendSnapshotBinaryCommand(snapshot, (int)CalculatorCommand.CommandSIN);

_viewModel.Snapshot = snapshot;

ValidateViewModelValue("1");
}
}

[TestMethod]
public void SnapshotReplayRejectsMemoryCommands()
{
var snapshot = new StandardCalculatorSnapshot();
AppendSnapshotOperand(snapshot, (int)CalculatorCommand.Command1);
AppendSnapshotBinaryCommand(snapshot, (int)CalculatorCommand.CommandMPLUS);
AppendSnapshotOperand(snapshot, (int)CalculatorCommand.Command2);

_viewModel.Snapshot = snapshot;

ValidateViewModelValue("12");
Assert.IsTrue(_viewModel.IsMemoryEmpty);
}

#endregion

#region Basic Arithmetic Tests
Expand Down
38 changes: 30 additions & 8 deletions src/Calculator.ViewModels/StandardCalculatorViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -708,10 +708,7 @@ public Snapshot.StandardCalculatorSnapshot Snapshot
{
// Expression was not evaluated before, or it was an error.
var displayCommands = GetCommandsFromExpressionCommands(snapshot.DisplayCommands);
foreach (var cmd in displayCommands)
{
_standardCalculatorManager?.SendCommand((CalculatorCommand)cmd);
}
ReplaySnapshotCommands(displayCommands);
if (snapshot.PrimaryDisplay.IsError)
{
SetPrimaryDisplay(snapshot.PrimaryDisplay.DisplayValue, true);
Expand All @@ -727,10 +724,7 @@ public Snapshot.StandardCalculatorSnapshot Snapshot
else
{
var commands = GetCommandsFromExpressionCommands(snapshot.DisplayCommands);
foreach (var cmd in commands)
{
_standardCalculatorManager?.SendCommand((CalculatorCommand)cmd);
}
ReplaySnapshotCommands(commands);
}
}
}
Expand Down Expand Up @@ -2055,6 +2049,34 @@ private static List<int> GetCommandsFromExpressionCommands(IList<ExpressionComma
return commands;
}

private void ReplaySnapshotCommands(IEnumerable<int> commands)
{
foreach (int command in commands)
{
if (IsValidSnapshotReplayCommand(command))
{
_standardCalculatorManager?.SendCommand((CalculatorCommand)command);
}
}
}

private static bool IsValidSnapshotReplayCommand(int command)
{
return (command >= (int)CalculatorCommand.Command0 && command <= (int)CalculatorCommand.CommandF)
|| (command >= (int)CalculatorCommand.CommandAnd && command <= (int)CalculatorCommand.CommandPWR)
|| (command >= (int)CalculatorCommand.CommandLogBaseY && command <= (int)CalculatorCommand.CommandNor)
|| command == (int)CalculatorCommand.CommandRSHFL
|| command == (int)CalculatorCommand.CommandSIGN
|| command == (int)CalculatorCommand.CommandPNT
|| (command >= (int)CalculatorCommand.CommandCHOP && command <= (int)CalculatorCommand.CommandPERCENT)
|| command == (int)CalculatorCommand.CommandEXP
|| command == (int)CalculatorCommand.CommandOPENP
|| command == (int)CalculatorCommand.CommandCLOSEP
|| (command >= (int)CalculatorCommand.CommandASIN && command <= (int)CalculatorCommand.CommandATANH)
|| (command >= (int)CalculatorCommand.CommandSEC && command <= (int)CalculatorCommand.CommandRORC)
|| command == (int)NumbersAndOperatorsEnum.Degrees;
}

}

}
91 changes: 91 additions & 0 deletions src/CalculatorUITests/StandardModeFunctionalTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@
using OpenQA.Selenium;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;

namespace CalculatorUITests
{
Expand Down Expand Up @@ -786,6 +793,90 @@ public void AoT_ErrorMessage_MessageRetentionUponExitingAoT()

#endregion

#region Snapshot Protocol Tests

[TestMethod]
[DataRow(false)]
[DataRow(true)]
[Priority(0)]
public void SnapshotProtocolRejectsInjectedCommands(bool includeExpression)
{
var standardSnapshot = new Dictionary<string, object>
{
["m"] = new Dictionary<string, object>(),
["p"] = new Dictionary<string, object>
{
["d"] = "12",
["e"] = false,
},
["c"] = new object[]
{
BinaryCommand(322),
OperandCommand(139),
BinaryCommand(121),
OperandCommand(130),
BinaryCommand(102),
BinaryCommand(int.MaxValue),
},
};
if (includeExpression)
{
standardSnapshot["e"] = new Dictionary<string, object>
{
["t"] = Array.Empty<object>(),
["c"] = Array.Empty<object>(),
};
}

var snapshot = new Dictionary<string, object>
{
["m"] = 0,
["s"] = standardSnapshot,
};
var json = JsonSerializer.Serialize(snapshot);
var uri = $"ms-calculator:snapshot/{Convert.ToBase64String(Compress(json))}";

Process.Start(new ProcessStartInfo(uri) { UseShellExecute = true });

Assert.IsTrue(
SpinWait.SpinUntil(() => page.CalculatorResults.GetCalculatorResultText() == "0", TimeSpan.FromSeconds(10)),
$"Snapshot replay produced '{page.CalculatorResults.GetCalculatorResultText()}' instead of rejecting the injected commands.");
}

private static Dictionary<string, object> BinaryCommand(int command)
{
return new Dictionary<string, object>
{
["$t"] = 1,
["c"] = command,
};
}

private static Dictionary<string, object> OperandCommand(int command)
{
return new Dictionary<string, object>
{
["$t"] = 2,
["n"] = false,
["d"] = false,
["s"] = false,
["c"] = new[] { command },
};
}

private static byte[] Compress(string value)
{
using var compressed = new MemoryStream();
using (var stream = new DeflateStream(compressed, CompressionMode.Compress, true))
{
var bytes = Encoding.UTF8.GetBytes(value);
stream.Write(bytes, 0, bytes.Length);
}
return compressed.ToArray();
}

#endregion

#region Error Tests
/// <summary>
/// These automated tests verify errors display gracefully
Expand Down
11 changes: 11 additions & 0 deletions src/CalculatorUnitTests/RationalTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include "pch.h"
#include <CppUnitTest.h>
#include <limits>
#include "Header Files/Rational.h"
#include "Header Files/RationalMath.h"

Expand Down Expand Up @@ -40,6 +41,16 @@ TEST_METHOD(TestModuloOperandsNotModified)
VERIFY_ARE_EQUAL(rat4, 4);
}

TEST_METHOD(TestInt32MinIntegerPower)
{
PRAT base = Rational(-1).ToPRAT();
ratpowi32(&base, std::numeric_limits<int32_t>::min(), RATIONAL_PRECISION);
Rational result{ base };
destroyrat(base);

VERIFY_ARE_EQUAL(result, 1);
}

TEST_METHOD(TestModuloInteger)
{
// Check with integers
Expand Down
Loading