Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Commit

Permalink
Deal with integer overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams committed Aug 12, 2016
1 parent f3399bc commit fbabd72
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions src/mscorlib/src/System/Threading/ThreadPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,17 +148,16 @@ internal int Add(T e)
}
return i;
}
else if (i == array.Length - 1)
{
var newSnapshot = new Snapshot(array.Length * 2, array.Length + 1);
T[] newArray = newSnapshot.Data;

Array.Copy(array, newArray, i + 1);
newArray[i + 1] = e;
m_current = newSnapshot;
return i + 1;
}
}

var oldLength = array.Length;
var newSnapshot = new Snapshot(oldLength * 2, oldLength + 1);
T[] newArray = newSnapshot.Data;

Array.Copy(array, newArray, oldLength);
newArray[oldLength + 1] = e;
m_current = newSnapshot;
return oldLength + 1;
}
}
}
Expand Down Expand Up @@ -829,14 +828,17 @@ private static void DequeueStealWithQueue(WorkStealingQueue wsq, int index, ref
var otherQueues = allThreadQueues.Current;
var total = otherQueues.ActiveLength;
var data = otherQueues.Data;
Contract.Assert(data.Length >= total);

var remaining = total;
index = index % total;
// Only positive indices
index = (index & 0x7fff) % total;

while (remaining > 0)
{
remaining--;
WorkStealingQueue otherQueue = Volatile.Read(ref data[index]);
index = index + 1 == total ? 0 : index + 1;
index = (index + 1 >= total) ? 0 : index + 1;
if (otherQueue != null &&
otherQueue != wsq &&
otherQueue.TrySteal(ref callback, ref missedSteal))
Expand All @@ -857,14 +859,17 @@ private static void DequeueSteal(int index, ref IThreadPoolWorkItem callback, re
// No local queue, may not be other queues
if (total == 0) return;
var data = otherQueues.Data;
Contract.Assert(data.Length >= total);

var remaining = total;
index = index % total;
// Only positive indices
index = (index & 0x7fff) % total;

while (remaining > 0)
{
remaining--;
WorkStealingQueue otherQueue = Volatile.Read(ref data[index]);
index = index + 1 == total ? 0 : index + 1;
index = (index + 1 == total) ? 0 : index + 1;
if (otherQueue != null &&
otherQueue.TrySteal(ref callback, ref missedSteal))
{
Expand Down

0 comments on commit fbabd72

Please sign in to comment.