From e42c9e4824358b9b38414df0370919c822ed8523 Mon Sep 17 00:00:00 2001 From: AlanLiu90 Date: Mon, 16 May 2022 09:53:06 +0800 Subject: [PATCH] Fixed rare race condition in name table when deserializing on device with ARM processors (#2602) --- Src/Newtonsoft.Json/DefaultJsonNameTable.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json/DefaultJsonNameTable.cs b/Src/Newtonsoft.Json/DefaultJsonNameTable.cs index 5243160e..659eefab 100644 --- a/Src/Newtonsoft.Json/DefaultJsonNameTable.cs +++ b/Src/Newtonsoft.Json/DefaultJsonNameTable.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Threading; namespace Newtonsoft.Json { @@ -78,7 +79,12 @@ namespace Newtonsoft.Json hashCode -= hashCode >> 5; // make sure index is evaluated before accessing _entries, otherwise potential race condition causing IndexOutOfRangeException - var index = hashCode & _mask; +#if NET20 || NET35 || NET40 + int mask = Thread.VolatileRead(ref _mask); +#else + int mask = Volatile.Read(ref _mask); +#endif + var index = hashCode & mask; var entries = _entries; for (Entry entry = entries[index]; entry != null; entry = entry.Next) @@ -160,7 +166,12 @@ namespace Newtonsoft.Json } } _entries = newEntries; - _mask = newMask; + +#if NET20 || NET35 || NET40 + Thread.VolatileWrite(ref _mask, newMask); +#else + Volatile.Write(ref _mask, newMask); +#endif } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)