File size: 27,495 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Numerics;
using System.Reflection;
using System.Security.Cryptography;
using System.Threading;
using Debug = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class implements base class for `Get-Random` and `Get-SecureRandom` cmdlets.
/// </summary>
public class GetRandomCommandBase : PSCmdlet
{
#region Parameter set handling
internal const string RandomNumberParameterSet = "RandomNumberParameterSet";
private const string RandomListItemParameterSet = "RandomListItemParameterSet";
private const string ShuffleParameterSet = "ShuffleParameterSet";
private static readonly object[] _nullInArray = new object[] { null };
private enum MyParameterSet
{
Unknown,
RandomNumber,
RandomListItem
}
private MyParameterSet _effectiveParameterSet;
private MyParameterSet EffectiveParameterSet
{
get
{
// cache MyParameterSet enum instead of doing string comparison every time
if (_effectiveParameterSet == MyParameterSet.Unknown)
{
if (MyInvocation.ExpectingInput && (Maximum == null) && (Minimum == null))
{
_effectiveParameterSet = MyParameterSet.RandomListItem;
}
else if (ParameterSetName == GetRandomCommandBase.RandomListItemParameterSet
|| ParameterSetName == GetRandomCommandBase.ShuffleParameterSet)
{
_effectiveParameterSet = MyParameterSet.RandomListItem;
}
else if (ParameterSetName.Equals(GetRandomCommandBase.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase))
{
if ((Maximum != null) && Maximum.GetType().IsArray)
{
InputObject = (object[])Maximum;
_effectiveParameterSet = MyParameterSet.RandomListItem;
}
else
{
_effectiveParameterSet = MyParameterSet.RandomNumber;
}
}
else
{
Debug.Assert(false, "Unrecognized parameter set");
}
}
return _effectiveParameterSet;
}
}
#endregion Parameter set handling
#region Error handling
private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue)
{
if (minValue == null)
{
throw PSTraceSource.NewArgumentNullException("min");
}
if (maxValue == null)
{
throw PSTraceSource.NewArgumentNullException("max");
}
ErrorRecord errorRecord = new(
new ArgumentException(string.Format(
CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)),
"MinGreaterThanOrEqualMax",
ErrorCategory.InvalidArgument,
null);
ThrowTerminatingError(errorRecord);
}
#endregion
#region Random generator state
private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new();
// 1-to-1 mapping of cmdlet + runspacesId and random number generators
private static readonly Dictionary<string, PolymorphicRandomNumberGenerator> s_runspaceGeneratorMap = new();
private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e)
{
switch (e.RunspaceStateInfo.State)
{
case RunspaceState.Broken:
case RunspaceState.Closed:
try
{
GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterWriteLock();
GetRandomCommandBase.s_runspaceGeneratorMap.Remove(MethodBase.GetCurrentMethod().DeclaringType.Name + ((Runspace)sender).InstanceId.ToString());
}
finally
{
GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitWriteLock();
}
break;
}
}
private PolymorphicRandomNumberGenerator _generator;
/// <summary>
/// Gets and sets generator associated with the current cmdlet and runspace.
/// </summary>
internal PolymorphicRandomNumberGenerator Generator
{
get
{
if (_generator == null)
{
string runspaceId = Context.CurrentRunspace.InstanceId.ToString();
bool needToInitialize = false;
try
{
GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterReadLock();
needToInitialize = !GetRandomCommandBase.s_runspaceGeneratorMap.TryGetValue(this.GetType().Name + runspaceId, out _generator);
}
finally
{
GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitReadLock();
}
if (needToInitialize)
{
Generator = new PolymorphicRandomNumberGenerator();
}
}
return _generator;
}
set
{
_generator = value;
Runspace myRunspace = Context.CurrentRunspace;
try
{
GetRandomCommandBase.s_runspaceGeneratorMapLock.EnterWriteLock();
if (!GetRandomCommandBase.s_runspaceGeneratorMap.ContainsKey(this.GetType().Name + myRunspace.InstanceId.ToString()))
{
// make sure we won't leave the generator around after runspace exits
myRunspace.StateChanged += CurrentRunspace_StateChanged;
}
GetRandomCommandBase.s_runspaceGeneratorMap[this.GetType().Name + myRunspace.InstanceId.ToString()] = _generator;
}
finally
{
GetRandomCommandBase.s_runspaceGeneratorMapLock.ExitWriteLock();
}
}
}
#endregion
#region Parameters for RandomNumberParameterSet
/// <summary>
/// Gets or sets the maximum number to generate.
/// </summary>
[Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)]
public object Maximum { get; set; }
/// <summary>
/// Gets or sets the minimum number to generate.
/// </summary>
[Parameter(ParameterSetName = RandomNumberParameterSet)]
public object Minimum { get; set; }
private static bool IsInt(object o)
{
if (o == null || o is int)
{
return true;
}
return false;
}
private static bool IsInt64(object o)
{
if (o == null || o is long)
{
return true;
}
return false;
}
private static object ProcessOperand(object o)
{
if (o == null)
{
return null;
}
PSObject pso = PSObject.AsPSObject(o);
object baseObject = pso.BaseObject;
if (baseObject is string)
{
// The type argument passed in does not decide the number type we want to convert to. ScanNumber will return
// int/long/double based on the string form number passed in.
baseObject = System.Management.Automation.Language.Parser.ScanNumber((string)baseObject, typeof(int));
}
return baseObject;
}
private static double ConvertToDouble(object o, double defaultIfNull)
{
if (o == null)
{
return defaultIfNull;
}
double result = (double)LanguagePrimitives.ConvertTo(o, typeof(double), CultureInfo.InvariantCulture);
return result;
}
#endregion
#region Parameters and variables for RandomListItemParameterSet
private List<object> _chosenListItems;
private int _numberOfProcessedListItems;
/// <summary>
/// Gets or sets the list from which random elements are chosen.
/// </summary>
[Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)]
[Parameter(ParameterSetName = ShuffleParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)]
[System.Management.Automation.AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public object[] InputObject { get; set; }
/// <summary>
/// Gets or sets the number of items to output (number of list items or of numbers).
/// </summary>
[Parameter(ParameterSetName = RandomNumberParameterSet)]
[Parameter(ParameterSetName = RandomListItemParameterSet)]
[ValidateRange(1, int.MaxValue)]
public int Count { get; set; } = 1;
#endregion
#region Shuffle parameter
/// <summary>
/// Gets or sets whether the command should return all input objects in randomized order.
/// </summary>
[Parameter(ParameterSetName = ShuffleParameterSet, Mandatory = true)]
public SwitchParameter Shuffle { get; set; }
#endregion
#region Cmdlet processing methods
private double GetRandomDouble(double minValue, double maxValue)
{
double randomNumber;
double diff = maxValue - minValue;
// I couldn't find a better fix for bug #216893 then
// to test and retry if a random number falls outside the bounds
// because of floating-point-arithmetic inaccuracies.
//
// Performance in the normal case is not impacted much.
// In low-precision situations we should converge to a solution quickly
// (diff gets smaller at a quick pace).
if (double.IsInfinity(diff))
{
do
{
double r = Generator.NextDouble();
randomNumber = minValue + (r * maxValue) - (r * minValue);
}
while (randomNumber >= maxValue);
}
else
{
do
{
double r = Generator.NextDouble();
randomNumber = minValue + (r * diff);
diff *= r;
}
while (randomNumber >= maxValue);
}
return randomNumber;
}
/// <summary>
/// Get a random Int64 type number.
/// </summary>
/// <param name="minValue">Minimum value.</param>
/// <param name="maxValue">Maximum value.</param>
/// <returns>Rnadom long.</returns>
private long GetRandomInt64(long minValue, long maxValue)
{
// Randomly generate eight bytes and convert the byte array to UInt64
var buffer = new byte[sizeof(ulong)];
ulong randomUint64;
BigInteger bigIntegerDiff = (BigInteger)maxValue - (BigInteger)minValue;
// When the difference is less than int.MaxValue, use Random.Next(int, int)
if (bigIntegerDiff <= int.MaxValue)
{
int randomDiff = Generator.Next(0, (int)(maxValue - minValue));
return minValue + randomDiff;
}
// The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number.
ulong uint64Diff = (ulong)bigIntegerDiff;
// Calculate the number of bits to represent the diff in type UInt64
int bitsToRepresentDiff = 0;
ulong diffCopy = uint64Diff;
for (; diffCopy != 0; bitsToRepresentDiff++)
{
diffCopy >>= 1;
}
// Get the mask for the number of bits
ulong mask = 0xffffffffffffffff >> (64 - bitsToRepresentDiff);
do
{
// Randomly fill the buffer
Generator.NextBytes(buffer);
randomUint64 = BitConverter.ToUInt64(buffer, 0);
// Get the last 'bitsToRepresentDiff' number of random bits
randomUint64 &= mask;
} while (uint64Diff <= randomUint64);
double randomNumber = (minValue * 1.0) + (randomUint64 * 1.0);
return (long)randomNumber;
}
/// <summary>
/// This method implements the BeginProcessing method for derived cmdlets.
/// </summary>
protected override void BeginProcessing()
{
if (EffectiveParameterSet == MyParameterSet.RandomNumber)
{
object maxOperand = ProcessOperand(Maximum);
object minOperand = ProcessOperand(Minimum);
if (IsInt(maxOperand) && IsInt(minOperand))
{
int minValue = minOperand != null ? (int)minOperand : 0;
int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue;
if (minValue >= maxValue)
{
ThrowMinGreaterThanOrEqualMax(minValue, maxValue);
}
for (int i = 0; i < Count; i++)
{
int randomNumber = Generator.Next(minValue, maxValue);
Debug.Assert(minValue <= randomNumber, "lower bound <= random number");
Debug.Assert(randomNumber < maxValue, "random number < upper bound");
WriteObject(randomNumber);
}
}
else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand)))
{
long minValue = minOperand != null ? ((minOperand is long) ? (long)minOperand : (int)minOperand) : 0;
long maxValue = maxOperand != null ? ((maxOperand is long) ? (long)maxOperand : (int)maxOperand) : long.MaxValue;
if (minValue >= maxValue)
{
ThrowMinGreaterThanOrEqualMax(minValue, maxValue);
}
for (int i = 0; i < Count; i++)
{
long randomNumber = GetRandomInt64(minValue, maxValue);
Debug.Assert(minValue <= randomNumber, "lower bound <= random number");
Debug.Assert(randomNumber < maxValue, "random number < upper bound");
WriteObject(randomNumber);
}
}
else
{
double minValue = (minOperand is double) ? (double)minOperand : ConvertToDouble(Minimum, 0.0);
double maxValue = (maxOperand is double) ? (double)maxOperand : ConvertToDouble(Maximum, double.MaxValue);
if (minValue >= maxValue)
{
ThrowMinGreaterThanOrEqualMax(minValue, maxValue);
}
for (int i = 0; i < Count; i++)
{
double randomNumber = GetRandomDouble(minValue, maxValue);
Debug.Assert(minValue <= randomNumber, "lower bound <= random number");
Debug.Assert(randomNumber < maxValue, "random number < upper bound");
WriteObject(randomNumber);
}
}
}
else if (EffectiveParameterSet == MyParameterSet.RandomListItem)
{
_chosenListItems = new List<object>();
_numberOfProcessedListItems = 0;
}
}
// rough proof that when choosing random K items out of N items
// each item has got K/N probability of being included in the final list
//
// probability that a particular item in chosenListItems is NOT going to be replaced
// when processing I-th input item [assumes I > K]:
// P_one_step(I) = 1 - ((K / I) * ((K - 1) / K) + ((I - K) / I) = (I - 1) / I
// <--A--> <-----B-----> <-----C----->
// A - probability that I-th element is going to be replacing an element from chosenListItems
// (see (1) in the code below)
// B - probability that a particular element from chosenListItems is NOT going to be replaced
// (see (2) in the code below)
// C - probability that I-th element is NOT going to be replacing an element from chosenListItems
// (see (1) in the code below)
//
// probability that a particular item in chosenListItems is NOT going to be replaced
// when processing input items J through N [assumes J > K]
// P_removal(J) = Multiply(for I = J to N) P(I) =
// = ((J - 1) / J) * (J / (J + 1)) * ... * ((N - 2) / (N - 1)) * ((N - 1) / N) =
// = (J - 1) / N
//
// probability that when processing an element it is going to be put into chosenListItems
// P_insertion(I) = 1.0 when I <= K - see (3) in the code below
// P_insertion(I) = K/N otherwise - see (1) in the code below
//
// probability that a given element is going to be a part of the final list
// P_final(I) = P_insertion(I) * P_removal(max(I + 1, K + 1))
// [for I <= K] = 1.0 * ((K + 1) - 1) / N = K / N
// [otherwise] = (K / I) * ((I + 1) - 1) / N = K / N
//
// which proves that P_final(I) = K / N for all values of I. QED.
/// <summary>
/// This method implements the ProcessRecord method for derived cmdlets.
/// </summary>
protected override void ProcessRecord()
{
if (EffectiveParameterSet == MyParameterSet.RandomListItem)
{
if (Shuffle)
{
// this allows for $null to be in an array passed to InputObject
foreach (object item in InputObject ?? _nullInArray)
{
_chosenListItems.Add(item);
}
}
else
{
foreach (object item in InputObject ?? _nullInArray)
{
// (3)
if (_numberOfProcessedListItems < Count)
{
Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems");
_chosenListItems.Add(item);
}
else
{
Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K");
// (1)
if (Generator.Next(_numberOfProcessedListItems + 1) < Count)
{
// (2)
int indexToReplace = Generator.Next(_chosenListItems.Count);
_chosenListItems[indexToReplace] = item;
}
}
_numberOfProcessedListItems++;
}
}
}
}
/// <summary>
/// This method implements the EndProcessing method for derived cmdlets.
/// </summary>
protected override void EndProcessing()
{
if (EffectiveParameterSet == MyParameterSet.RandomListItem)
{
// make sure the order is truly random
// (all permutations with the same probability)
// O(n) time
int n = _chosenListItems.Count;
for (int i = 0; i < n; i++)
{
// randomly choose j from [i...n)
int j = Generator.Next(i, n);
WriteObject(_chosenListItems[j]);
// remove the output object from consideration in the next iteration.
if (i != j)
{
_chosenListItems[j] = _chosenListItems[i];
}
}
}
}
#endregion Processing methods
}
/// <summary>
/// Provides an adapter API for random numbers that may be either cryptographically random, or
/// generated with the regular pseudo-random number generator. Re-implementations of
/// methods using the NextBytes() primitive based on the CLR implementation:
/// https://referencesource.microsoft.com/#mscorlib/system/random.cs.
/// </summary>
internal sealed class PolymorphicRandomNumberGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="PolymorphicRandomNumberGenerator"/> class.
/// </summary>
public PolymorphicRandomNumberGenerator()
{
_cryptographicGenerator = RandomNumberGenerator.Create();
_pseudoGenerator = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="PolymorphicRandomNumberGenerator"/> using pseudorandom generator instead of the cryptographic one.
/// </summary>
/// <param name="seed">The seed value.</param>
internal PolymorphicRandomNumberGenerator(int seed)
{
_cryptographicGenerator = null;
_pseudoGenerator = new Random(seed);
}
private readonly Random _pseudoGenerator = null;
private readonly RandomNumberGenerator _cryptographicGenerator = null;
/// <summary>
/// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0.
/// </summary>
/// <returns>A random floating-point number that is greater than or equal to 0.0, and less than 1.0.</returns>
internal double NextDouble()
{
// According to the CLR source:
// "Including this division at the end gives us significantly improved random number distribution."
return Next() * (1.0 / int.MaxValue);
}
/// <summary>
/// Generates a non-negative random integer.
/// </summary>
/// <returns>A non-negative random integer.</returns>
internal int Next()
{
int randomNumber;
// The CLR implementation just fudges
// Int32.MaxValue down to (Int32.MaxValue - 1). This implementation
// errs on the side of correctness.
do
{
randomNumber = InternalSample();
}
while (randomNumber == int.MaxValue);
if (randomNumber < 0)
{
randomNumber += int.MaxValue;
}
return randomNumber;
}
/// <summary>
/// Returns a random integer that is within a specified range.
/// </summary>
/// <param name="maxValue">The exclusive upper bound of the random number returned.</param>
/// <returns>Next random integer.</returns>
internal int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue), GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi);
}
return Next(0, maxValue);
}
/// <summary>
/// Returns a random integer that is within a specified range.
/// </summary>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.</param>
/// <returns>Next random integer.</returns>
public int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException(nameof(minValue), GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi);
}
int randomNumber = 0;
long range = (long)maxValue - (long)minValue;
if (range <= int.MaxValue)
{
randomNumber = (int)(NextDouble() * range) + minValue;
}
else
{
double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)int.MaxValue)));
randomNumber = (int)((long)(largeSample * range) + minValue);
}
return randomNumber;
}
/// <summary>
/// Fills the elements of a specified array of bytes with random numbers.
/// </summary>
/// <param name="buffer">The array to be filled.</param>
internal void NextBytes(byte[] buffer)
{
if (_cryptographicGenerator != null)
{
_cryptographicGenerator.GetBytes(buffer);
}
else
{
_pseudoGenerator.NextBytes(buffer);
}
}
/// <summary>
/// Samples a random integer.
/// </summary>
/// <returns>A random integer, using the full range of Int32.</returns>
private int InternalSample()
{
int randomNumber;
byte[] data = new byte[sizeof(int)];
NextBytes(data);
randomNumber = BitConverter.ToInt32(data, 0);
return randomNumber;
}
/// <summary>
/// Samples a random int when the range is large. This does
/// not need to be in the range of -Double.MaxValue .. Double.MaxValue,
/// just 0.. (2 * Int32.MaxValue) - 1 .
/// </summary>
/// <returns>A random double.</returns>
private double InternalSampleLargeRange()
{
double randomNumber;
do
{
randomNumber = InternalSample();
}
while (randomNumber == int.MaxValue);
randomNumber += int.MaxValue;
return randomNumber;
}
}
}
|