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

Commit

Permalink
Cleanup registry usage within CoreLib (#20050)
Browse files Browse the repository at this point in the history
- Ensure that the registry keys are always disposed
- Use smaller subset of registry APIs
- Reduce diffs with CoreCLR/CoreFX
- Contributes to #11009 and #17899
  • Loading branch information
jkotas authored Sep 19, 2018
1 parent f52dfe4 commit 21078fb
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 141 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ internal partial class Errors
internal const int ERROR_NO_UNICODE_TRANSLATION = 0x459;
internal const int ERROR_NOT_FOUND = 0x490;
internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
internal const int ERROR_NO_SYSTEM_RESOURCES = 0x5AA;
internal const int E_FILENOTFOUND = unchecked((int)0x80070002);
internal const int ERROR_NO_SYSTEM_RESOURCES = 0x5AA;
internal const int ERROR_TIMEOUT = 0x000005B4;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ static class Registry

/// <summary>Local Machine key. This key should be used as the root for all machine specific settings.</summary>
public static readonly RegistryKey LocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);


#if REGISTRY_ASSEMBLY
/// <summary>Classes Root Key. This is the root key of class information.</summary>
public static readonly RegistryKey ClassesRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Default);

Expand Down Expand Up @@ -100,5 +101,6 @@ public static void SetValue(string keyName, string valueName, object value, Regi
key.SetValue(valueName, value, valueKind);
}
}
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -507,37 +507,39 @@ private unsafe void GetSessionInfo(SessionInfoCallback action, ref List<SessionI

// Determine our session from what is in the registry.
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerName + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
if (IntPtr.Size == 8)
regKey = @"Software" + @"\Wow6432Node" + regKey;
else
regKey = @"Software" + regKey;

var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey);
if (key != null)
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey))
{
foreach (string valueName in key.GetValueNames())
if (key != null)
{
if (valueName.StartsWith("ControllerData_Session_", StringComparison.Ordinal))
foreach (string valueName in key.GetValueNames())
{
string strId = valueName.Substring(23); // strip of the ControllerData_Session_
int etwSessionId;
if (int.TryParse(strId, out etwSessionId))
if (valueName.StartsWith("ControllerData_Session_", StringComparison.Ordinal))
{
// we need to assert this permission for partial trust scenarios
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
var data = key.GetValue(valueName) as byte[];
if (data != null)
string strId = valueName.Substring(23); // strip of the ControllerData_Session_
int etwSessionId;
if (int.TryParse(strId, out etwSessionId))
{
var dataAsString = System.Text.Encoding.UTF8.GetString(data);
int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword", StringComparison.Ordinal);
if (0 <= keywordIdx)
// we need to assert this permission for partial trust scenarios
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
var data = key.GetValue(valueName) as byte[];
if (data != null)
{
int startIdx = keywordIdx + 18;
int endIdx = dataAsString.IndexOf('\0', startIdx);
string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx);
int keywordBit;
if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit))
action(etwSessionId, 1L << keywordBit, ref sessionList);
var dataAsString = System.Text.Encoding.UTF8.GetString(data);
int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword", StringComparison.Ordinal);
if (0 <= keywordIdx)
{
int startIdx = keywordIdx + 18;
int endIdx = dataAsString.IndexOf('\0', startIdx);
string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx);
int keywordBit;
if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit))
action(etwSessionId, 1L << keywordBit, ref sessionList);
}
}
}
}
Expand Down Expand Up @@ -582,23 +584,26 @@ private unsafe bool GetDataFromController(int etwSessionId,
{
#if (!ES_BUILD_PCL && !ES_BUILD_PN && PLATFORM_WINDOWS)
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
if (IntPtr.Size == 8)
regKey = @"Software" + @"\Wow6432Node" + regKey;
else
regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;
regKey = @"Software" + regKey;

string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);

// we need to assert this permission for partial trust scenarios
#if !CORECLR
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
#endif
data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
if (data != null)
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey))
{
// We only used the persisted data from the registry for updates.
command = ControllerCommand.Update;
return true;
data = key?.GetValue(valueName, null) as byte[];
if (data != null)
{
// We only used the persisted data from the registry for updates.
command = ControllerCommand.Update;
return true;
}
}
#endif
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,56 +39,45 @@ private int GetHijriDateAdjustment()
============================================================================*/
private static int GetAdvanceHijriDate()
{
int hijriAdvance = 0;
Microsoft.Win32.RegistryKey key = null;

try
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(InternationalRegKey))
{
// Open in read-only mode.
key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser).OpenSubKey(InternationalRegKey, false);
}
//If this fails for any reason, we'll just return 0.
catch (ObjectDisposedException) { return 0; }
catch (ArgumentException) { return 0; }
// Abort if we didn't find anything
if (key == null)
{
return 0;
}

if (key != null)
{
try
object value = key.GetValue(HijriAdvanceRegKeyEntry, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (value == null)
{
object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false);
if (value == null)
{
return (0);
}
string str = value.ToString();
if (string.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0)
return 0;
}

int hijriAdvance = 0;
string str = value.ToString();
if (string.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0)
{
if (str.Length == HijriAdvanceRegKeyEntry.Length)
hijriAdvance = -1;
else
{
if (str.Length == HijriAdvanceRegKeyEntry.Length)
hijriAdvance = -1;
else
try
{
try
int advance = int.Parse(str.AsSpan(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture);
if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri))
{
int advance = int.Parse(str.AsSpan(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture);
if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri))
{
hijriAdvance = advance;
}
hijriAdvance = advance;
}
// If we got garbage from registry just ignore it.
// hijriAdvance = 0 because of declaraction assignment up above.
catch (ArgumentException) { }
catch (FormatException) { }
catch (OverflowException) { }
}
// If we got garbage from registry just ignore it.
// hijriAdvance = 0 because of declaraction assignment up above.
catch (ArgumentException) { }
catch (FormatException) { }
catch (OverflowException) { }
}
}
finally
{
key.Close();
}
return hijriAdvance;
}
return (hijriAdvance);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ namespace System.Globalization
{
public partial class JapaneseCalendar : Calendar
{
private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
private const string JapaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";

// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
Expand All @@ -37,29 +36,30 @@ private static EraInfo[] GetJapaneseEras()
try
{
// Need to access registry
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine).OpenSubKey(c_japaneseErasHive, false);

// Abort if we didn't find anything
if (key == null) return null;

// Look up the values in our reg key
string[] valueNames = key.GetValueNames();
if (valueNames != null && valueNames.Length > 0)
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(JapaneseErasHive))
{
registryEraRanges = new EraInfo[valueNames.Length];
// Abort if we didn't find anything
if (key == null) return null;

// Loop through the registry and read in all the values
for (int i = 0; i < valueNames.Length; i++)
// Look up the values in our reg key
string[] valueNames = key.GetValueNames();
if (valueNames != null && valueNames.Length > 0)
{
// See if the era is a valid date
EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
registryEraRanges = new EraInfo[valueNames.Length];

// Loop through the registry and read in all the values
for (int i = 0; i < valueNames.Length; i++)
{
// See if the era is a valid date
EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());

// continue if not valid
if (era == null) continue;
// continue if not valid
if (era == null) continue;

// Remember we found one.
registryEraRanges[iFoundEras] = era;
iFoundEras++;
// Remember we found one.
registryEraRanges[iFoundEras] = era;
iFoundEras++;
}
}
}
}
Expand Down Expand Up @@ -199,7 +199,7 @@ private static EraInfo GetEraFromValue(string value, string data)

// PAL Layer ends here

private static string[] s_japaneseErasEnglishNames = new string[] { "M", "T", "S", "H" };
private static readonly string[] s_japaneseErasEnglishNames = new string[] { "M", "T", "S", "H" };

private static string GetJapaneseEnglishEraName(int era)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ private static EraInfo[] GetJapaneseEras()

// PAL Layer ends here

private static string[] JapaneseErasEnglishNames = new string[] { "M", "T", "S", "H" };
private static readonly string[] s_JapaneseErasEnglishNames = new string[] { "M", "T", "S", "H" };

private static string GetJapaneseEnglishEraName(int era)
{
Debug.Assert(era > 0);
return era <= JapaneseErasEnglishNames.Length ? JapaneseErasEnglishNames[era - 1] : " ";
return era <= s_JapaneseErasEnglishNames.Length ? s_JapaneseErasEnglishNames[era - 1] : " ";
}

private static bool GetJapaneseEraInfo(int era, out DateTimeOffset dateOffset, out string eraName, out string abbreviatedEraName)
Expand Down
20 changes: 10 additions & 10 deletions src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs
Original file line number Diff line number Diff line change
Expand Up @@ -574,8 +574,8 @@ private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaul
// read LastEntry {(yearN, 1, 1) - MaxValue }

// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1, RegistryValueOptions.None);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1, RegistryValueOptions.None);
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1);

if (first == -1 || last == -1 || first > last)
{
Expand Down Expand Up @@ -678,7 +678,7 @@ private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaul

private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)
{
byte[] regValue = key.GetValue(name, null, RegistryValueOptions.None) as byte[];
byte[] regValue = key.GetValue(name, null) as byte[];
if (regValue == null || regValue.Length != sizeof(REG_TZI_FORMAT))
{
dtzi = default;
Expand Down Expand Up @@ -744,7 +744,7 @@ private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMA
//
if (result)
{
string registryStandardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
string registryStandardName = key.GetValue(StandardValue, string.Empty) as string;
result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);
}
return result;
Expand Down Expand Up @@ -873,9 +873,9 @@ private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string d
daylightName = string.Empty;

// read the MUI_ registry keys
string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty, RegistryValueOptions.None) as string;
string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty, RegistryValueOptions.None) as string;
string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty, RegistryValueOptions.None) as string;
string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;
string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;
string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;

// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
Expand All @@ -896,15 +896,15 @@ private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string d
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
displayName = key.GetValue(DisplayValue, string.Empty, RegistryValueOptions.None) as string;
displayName = key.GetValue(DisplayValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(standardName))
{
standardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
standardName = key.GetValue(StandardValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
daylightName = key.GetValue(DaylightValue, string.Empty, RegistryValueOptions.None) as string;
daylightName = key.GetValue(DaylightValue, string.Empty) as string;
}
}

Expand Down
Loading

0 comments on commit 21078fb

Please sign in to comment.