Типы данных реестра windows

Как уже говорилось ранее, в реестре хранится громадное количество информации, включающее профили всех пользователей, сведения об установленном программном обеспечении и типах документов, которые могут быть созданы каждой программой, информация о свойствах папок и значках приложений, а также установленном оборудовании и используемых портах.

Поскольку реестр Microsoft Windows представляет собой сложную реляционную базу данных, вся информация, которая может храниться в конечных информационных контейнерах этой базы (параметрах), должна быть строго классифицирована. Классификация хранящихся в параметрах значений производится по типу данных, представляющих это значение. Всего насчитывается 11 таких типов

Раздел и подраздел могут содержать 0, 1 или несколько параметров, параметр по умолчанию, а также 0 или несколько подразделов. Каждый параметр имеет имя, тип и значение.

Три части параметра реестра всегда располагаются в определенном порядке: Имя, Тип данных, значение (например: [RegistrySizeLimit] [REG_DWORD] [0x8000000]).

В таблице, которая будет приведена ниже, содержится список типов данных, определенных и используемых Windows на сегодняшний день.

Максимальная длина имени параметра:

  • 16 383 символов для Windows Server 2003, Windows XP и Windows Vista
  • 260 символов ANSI или 16 383 символа Юникод для Windows 2000
  • 255 символов для Windows 95, Windows 98 и Windows Millennium Edition

Значения большого размера (больше 2048 байт) хранятся во внешних файлах, а в реестр заносится имя такого файла. Это способствует повышению эффективности использования реестра.

Максимальный размер параметра:

  • Вся доступная память для Windows NT 4.0/Windows 2000/Windows XP/Windows Server 2003/Windows Vista
  • 16 300 байт для Windows 95, Windows 98 и Windows Millennium Edition
Наименование Тип данных Назначение
REG_BINARY Двоичный Двоичные данные
REG_DWORD Числовой Число
REG_QWORD Числовой 64-разрядное числовое значение
REG_EXPAND_SZ Строковый Текст и переменные
REG_FULL_RESOURCE_DESCRIPTOR Строковый Идентификатор ресурса устройства
REG_LINK Строковый Путь к файлу
REG_MULTI_SZ Многостроковый Массив строк
REG_NONE Неизвестный Зашифрованные данные
REG_RESOURCE_LIST Строковый Список ресурсов устройств
REG_RESOURCE_REQUIREMENTS_LIST Строковый Идентификатор ресурса устройства
REG_SZ Строковый Текст

Ниже приводится назначение этих параметров.

REG_BINARY

Необработанные двоичные данные. Большинство сведений об аппаратных компонентах хранится в виде двоичных данных и выводится в редакторе реестра в шестнадцатеричном формате.

REG_DWORD

Данные, представленные целым числом (4 байта, 32 бита). Многие параметры служб и драйверов устройств имеют этот тип и отображаются в двоичном, шестнадцатеричном или десятичном форматах. Эквивалентами типа DWORD являются DWORD_LITTLE_ENDIAN (самый младший байт хранится в памяти в первом числе) и REG_DWORD_BIG_ENDIAN (самый младший байт хранится в памяти в последнем числе).

REG_EXPAND_SZ

Расширяемая строка данных. Эта строка представляет собой текст, содержащий переменную, которая может быть заменена при вызове со стороны приложения.

REG_MULTI_SZ

Многострочное поле. Значения, которые фактически представляют собой списки текстовых строк в формате, удобном для восприятия человеком, обычно имеют именно этот тип данных. Записи разделяются пробелами, запятыми или другими символами.

REG_SZ

Текстовая строка в формате, удобном для восприятия человеком. Значениям, представляющим собой описания компонентов, обычно присваивается именно этот тип данных. Имеет фиксированную длину.

REG_LINK

Символическая ссылка в формате Юникод.

REG_FULL_RESOURCE_DESCRIPTOR

Последовательность вложенных массивов. Служит для хранения списка ресурсов, которые используются физическим устройством. Обнаруженные данные система сохраняет в разделе \HardwareDescription. В окне редактора реестра эти данные отображаются в виде двоичного параметра в шестнадцатеричном формате

REG_RESOURCE_LIST

Последовательность вложенных массивов. Служит для хранения списка ресурсов, которые используются драйвером устройства или управляемым им физическим устройством. Обнаруженные данные система сохраняет в разделе \ResourceMap. В окне редактора реестра эти данные отображаются в виде двоичного параметра в шестнадцатеричном формате

REG_RESOURCE_REQUIREMENTS_LIST

Последовательность вложенных массивов. Служит для хранения списка драйверов аппаратных ресурсов, которые могут быть использованы определенным драйвером устройства или управляемым им физическим устройством. Часть этого списка система записывает в раздел \ResourceMap. Данные определяются системой. В окне редактора реестра они отображаются в виде двоичного параметра в шестнадцатеричном формате

REG_QWORD

Данные, представленные в виде 64-разрядного целого. Начиная с Windows 2000, такие данные отображаются в окне редактора реестра в виде двоичного параметра

REG_NONE

Данные, не имеющие определенного типа. Такие данные записываются в реестр системой или приложением. В окне редактора реестра отображаются в виде двоичного параметра в шестнадцатеричном формате

Windows Registry

Registry Editor, the user interface for the registry, in Windows 11

Developer(s) Microsoft
Initial release April 6, 1992; 33 years ago with Windows 3.1
Operating system Microsoft Windows
Platform IA-32, x86-64 and ARM (and historically DEC Alpha, Itanium, MIPS, and PowerPC)
Included with Microsoft Windows
Type Hierarchical database
License Proprietary
Website learn.microsoft.com/en-us/windows/win32/sysinfo/registry 

The Windows Registry is a hierarchical database that stores low-level settings for the Microsoft Windows operating system and for applications that opt to use the registry. The kernel, device drivers, services, Security Accounts Manager, and user interfaces can all use the registry. The registry also allows access to counters for profiling system performance.

In other words, the registry or Windows Registry contains information, settings, options, and other values for programs and hardware installed on all versions of Microsoft Windows operating systems. For example, when a program is installed, a new subkey containing settings such as a program’s location, its version, and how to start the program, are all added to the Windows Registry.

When introduced with Windows 3.1, the Windows Registry primarily stored configuration information for COM-based components. Windows 95 and Windows NT extended its use to rationalize and centralize the information in the profusion of INI files, which held the configurations for individual programs, and were stored at various locations.[1][2] It is not a requirement for Windows applications to use the Windows Registry. For example, .NET Framework applications use XML files for configuration, while portable applications usually keep their configuration files with their executables.

Prior to the Windows Registry, .INI files stored each program’s settings as a text file or binary file, often located in a shared location that did not provide user-specific settings in a multi-user scenario. By contrast, the Windows Registry stores all application settings in one logical repository (but also in a number of discrete files) and in a standardized form. According to Microsoft, this offers several advantages over .INI files.[2][3] Since file parsing is done much more efficiently with a binary format, it may be read from or written to more quickly than a text INI file. Furthermore, strongly typed data can be stored in the registry, as opposed to the text information stored in .INI files. This is a benefit when editing keys manually using regedit.exe, the built-in Windows Registry Editor. Because user-based registry settings are loaded from a user-specific path rather than from a read-only system location, the registry allows multiple users to share the same machine, and also allows programs to work for less privileged users. Backup and restoration is also simplified as the registry can be accessed over a network connection for remote management/support, including from scripts, using the standard set of APIs, as long as the Remote Registry service is running and firewall rules permit this.

Because the registry is a database, it offers improved system integrity with features such as atomic updates. If two processes attempt to update the same registry value at the same time, one process’s change will precede the other’s and the overall consistency of the data will be maintained. Where changes are made to .INI files, such race conditions can result in inconsistent data that does not match either attempted update. Windows Vista and later operating systems provide transactional updates to the registry by means of the Kernel Transaction Manager, extending the atomicity guarantees across multiple key or value changes with traditional commit–abort semantics. (Note however that NTFS provides such support for the file system as well, so the same guarantees could, in theory, be obtained with traditional configuration files.)

Structure of Registry Key

[edit]

The registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values and subkeys. Keys are referenced with a syntax similar to Windows’ path names, using backslashes to indicate levels of hierarchy. Keys must have a case insensitive name without backslashes.

The hierarchy of registry keys can only be accessed from a known root key handle (which is anonymous but whose effective value is a constant numeric handle) that is mapped to the content of a registry key preloaded by the kernel from a stored «hive», or to the content of a subkey within another root key, or mapped to a registered service or DLL that provides access to its contained subkeys and values.

E.g. HKEY_LOCAL_MACHINE\Software\Microsoft\Windows refers to the subkey «Windows» of the subkey «Microsoft» of the subkey «Software» of the HKEY_LOCAL_MACHINE root key.

There are seven predefined root keys, traditionally named according to their constant handles defined in the Win32 API, or by synonymous abbreviations (depending on applications):[4]

  • HKEY_LOCAL_MACHINE or HKLM
  • HKEY_CURRENT_CONFIG or HKCC
  • HKEY_CLASSES_ROOT or HKCR
  • HKEY_CURRENT_USER or HKCU
  • HKEY_USERS or HKU
  • HKEY_PERFORMANCE_DATA (only in Windows NT, but invisible in the Windows Registry Editor)[5]
  • HKEY_DYN_DATA (only in Windows 9x, and visible in the Windows Registry Editor)

Like other files and services in Windows, all registry keys may be restricted by access control lists (ACLs), depending on user privileges, or on security tokens acquired by applications, or on system security policies enforced by the system (these restrictions may be predefined by the system itself, and configured by local system administrators or by domain administrators). Different users, programs, services or remote systems may only see some parts of the hierarchy or distinct hierarchies from the same root keys.

Registry values are name/data pairs stored within keys. Registry values are referenced separately from registry keys. Each registry value stored in a registry key has a unique name whose letter case is not significant. The Windows API functions that query and manipulate registry values take value names separately from the key path or handle that identifies the parent key. Registry values may contain backslashes in their names, but doing so makes them difficult to distinguish from their key paths when using some legacy Windows Registry API functions (whose usage is deprecated in Win32).

The terminology is somewhat misleading, as each registry key is similar to an associative array, where standard terminology would refer to the name part of each registry value as a «key». The terms are a holdout from the 16-bit registry in Windows 3, in which registry keys could not contain arbitrary name/data pairs, but rather contained only one unnamed value (which had to be a string). In this sense, the Windows 3 registry was like a single associative array, in which the keys (in the sense of both ‘registry key’ and ‘associative array key’) formed a hierarchy, and the registry values were all strings. When the 32-bit registry was created, so was the additional capability of creating multiple named values per key, and the meanings of the names were somewhat distorted.[6] For compatibility with the previous behavior, each registry key may have a «default» value, whose name is the empty string.

Each value can store arbitrary data with variable length and encoding, but which is associated with a symbolic type (defined as a numeric constant) defining how to parse this data. The standard types are:[7]

List of standard registry value types

Type ID Symbolic type name Meaning and encoding of the data stored in the registry value
0 REG_NONE No type (the stored value, if any)
1 REG_SZ A string value, normally stored and exposed in UTF-16LE (when using the Unicode version of Win32 API functions), usually terminated by a NUL character
2 REG_EXPAND_SZ An «expandable» string value that can contain environment variables, normally stored and exposed in UTF-16LE, usually terminated by a NUL character
3 REG_BINARY Binary data (any arbitrary data)
4 REG_DWORD / REG_DWORD_LITTLE_ENDIAN A DWORD value, a 32-bit unsigned integer (numbers between 0 and 4,294,967,295 [232 – 1]) (little-endian)
5 REG_DWORD_BIG_ENDIAN A DWORD value, a 32-bit unsigned integer (numbers between 0 and 4,294,967,295 [232 – 1]) (big-endian)
6 REG_LINK A symbolic link (UNICODE) to another registry key, specifying a root key and the path to the target key
7 REG_MULTI_SZ A multi-string value, which is an ordered list of non-empty strings, normally stored and exposed in Unicode, each one terminated by a null character, the list being normally terminated by a second null character.[8]
8 REG_RESOURCE_LIST A resource list (used by the Plug-n-Play hardware enumeration and configuration)
9 REG_FULL_RESOURCE_DESCRIPTOR A resource descriptor (used by the Plug-n-Play hardware enumeration and configuration)
10 REG_RESOURCE_REQUIREMENTS_LIST A resource requirements list (used by the Plug-n-Play hardware enumeration and configuration)
11 REG_QWORD / REG_QWORD_LITTLE_ENDIAN A QWORD value, a 64-bit integer (either big- or little-endian, or unspecified) (introduced in Windows 2000)[9]

The keys at the root level of the hierarchical database are generally named by their Windows API definitions, which all begin with «HKEY».[2] They are frequently abbreviated to a three- or four-letter short name starting with «HK» (e.g. HKCU and HKLM). Technically, they are predefined handles (with known constant values) to specific keys that are either maintained in memory, or stored in hive files stored in the local filesystem and loaded by the system kernel at boot time and then shared (with various access rights) between all processes running on the local system, or loaded and mapped in all processes started in a user session when the user logs on the system.

The HKEY_LOCAL_MACHINE (local machine-specific configuration data) and HKEY_CURRENT_USER (user-specific configuration data) nodes have a similar structure to each other; user applications typically look up their settings by first checking for them in HKEY_CURRENT_USER\Software\Vendor's name\Application's name\Version\Setting name, and if the setting is not found, look instead in the same location under the HKEY_LOCAL_MACHINE key. However, the converse may apply for administrator-enforced policy settings where HKLM may take precedence over HKCU. The Windows Logo Program has specific requirements for where different types of user data may be stored, and that the concept of least privilege be followed so that administrator-level access is not required to use an application.[a][10]

HKEY_LOCAL_MACHINE (HKLM)

[edit]

Abbreviated HKLM, HKEY_LOCAL_MACHINE stores settings that are specific to the local computer.[11]

The key located by HKLM is actually not stored on disk, but maintained in memory by the system kernel in order to map all the other subkeys. Applications cannot create any additional subkeys. On Windows NT, this key contains four subkeys, «SAM», «SECURITY», «SYSTEM», and «SOFTWARE», that are loaded at boot time within their respective files located in the %SystemRoot%\System32\config\ folder. A fifth subkey, «HARDWARE», is volatile and is created dynamically, and as such is not stored in a file (it exposes a view of all the currently detected Plug-and-Play devices). On Windows Vista and above, a sixth and seventh subkey, «COMPONENTS» and «BCD», are mapped in memory by the kernel on-demand and loaded from %SystemRoot%\System32\config\COMPONENTS or from boot configuration data, \boot\BCD on the system partition.

  • The «HKLM\SAM» key usually appears as empty for most users (unless they are granted access by administrators of the local system or administrators of domains managing the local system). It is used to reference all «Security Accounts Manager» (SAM) databases for all domains into which the local system has been administratively authorized or configured (including the local domain of the running system, whose SAM database is stored in a subkey also named «SAM»: other subkeys will be created as needed, one for each supplementary domain). Each SAM database contains all builtin accounts (mostly group aliases) and configured accounts (users, groups and their aliases, including guest accounts and administrator accounts) created and configured on the respective domain, for each account in that domain, it notably contains the user name which can be used to log on that domain, the internal unique user identifier in the domain, a cryptographic hash of each user’s password for each enabled authentication protocol, the location of storage of their user registry hive, various status flags (for example if the account can be enumerated and be visible in the logon prompt screen), and the list of domains (including the local domain) into which the account was configured.
  • The «HKLM\SECURITY» key usually appears empty for most users (unless they are granted access by users with administrative privileges) and is linked to the Security database of the domain into which the current user is logged on (if the user is logged on the local system domain, this key will be linked to the registry hive stored by the local machine and managed by local system administrators or by the builtin «System» account and Windows installers). The kernel will access it to read and enforce the security policy applicable to the current user and all applications or operations executed by this user. It also contains a «SAM» subkey which is dynamically linked to the SAM database of the domain onto which the current user is logged on.
  • The «HKLM\SYSTEM» key is normally only writable by users with administrative privileges on the local system. It contains information about the Windows system setup, data for the secure random number generator (RNG), the list of currently mounted devices containing a filesystem, several numbered HKLM\SYSTEM\Control Sets containing alternative configurations for system hardware drivers and services running on the local system (including the currently used one and a backup), a «HKLM\SYSTEM\Select» subkey containing the status of these Control Sets, and a «HKLM\SYSTEM\CurrentControlSet» which is dynamically linked at boot time to the Control Set which is currently used on the local system. Each configured Control Set contains:
    • an «Enum» subkey enumerating all known Plug-and-Play devices and associating them with installed system drivers (and storing the device-specific configurations of these drivers),
    • a «Services» subkey listing all installed system drivers (with non device-specific configuration, and the enumeration of devices for which they are instantiated) and all programs running as services (how and when they can be automatically started),
    • a «Control» subkey organizing the various hardware drivers and programs running as services and all other system-wide configuration,
    • a «Hardware Profiles» subkey enumerating the various profiles that have been tuned (each one with «System» or «Software» settings used to modify the default profile, either in system drivers and services or in the applications) as well as the Hardware Profiles\Current subkey which is dynamically linked to one of these profiles.
  • The «HKLM\SOFTWARE» subkey contains software and Windows settings (in the default hardware profile). It is mostly modified by application and system installers. It is organized by software vendor (with a subkey for each), but also contains a «Windows» subkey for some settings of the Windows user interface, a «Classes» subkey containing all registered associations from file extensions, MIME types, Object Classes IDs and interfaces IDs (for OLE, COM/DCOM and ActiveX), to the installed applications or DLLs that may be handling these types on the local machine (however these associations are configurable for each user, see below), and a «Policies» subkey (also organized by vendor) for enforcing general usage policies on applications and system services (including the central certificates store used for authenticating, authorizing or disallowing remote systems or services running outside the local network domain).
  • The «HKLM\SOFTWARE\Wow6432Node» key is used by 32-bit applications on a 64-bit Windows OS, and is equivalent to but separate from «HKLM\SOFTWARE«. The key path is transparently presented to 32-bit applications by WoW64 as HKLM\SOFTWARE[12] (in a similar way that 64-bit applications see %SystemRoot%\Syswow64 as %SystemRoot%\System32)

HKEY_CLASSES_ROOT (HKCR)

[edit]

Abbreviated HKCR, HKEY_CLASSES_ROOT contains information about registered applications, such as file associations and OLE Object Class IDs, tying them to the applications used to handle these items. On Windows 2000 and above, HKCR is a compilation of user-based HKCU\Software\Classes and machine-based HKLM\Software\Classes. If a given value exists in both of the subkeys above, the one in HKCU\Software\Classes takes precedence.[13] The design allows for either machine- or user-specific registration of COM objects.
Abbreviated HKU, HKEY_USERS contains subkeys corresponding to the HKEY_CURRENT_USER keys for each user profile actively loaded on the machine, though user hives are usually only loaded for currently logged-in users.

HKEY_CURRENT_USER (HKCU)

[edit]

Abbreviated HKCU, HKEY_CURRENT_USER stores settings that are specific to the currently logged-in user.[14] The HKEY_CURRENT_USER key is a link to the subkey of HKEY_USERS that corresponds to the user; the same information is accessible in both locations. The specific subkey referenced is (HKU)\(SID)\... where (SID) corresponds to the Windows SID; if the «(HKCU)» key has the following suffix (HKCU)\Software\Classes\... then it corresponds to (HKU)\(SID)_CLASSES\... i.e. the suffix string «_CLASSES» is appended to the (SID).
On Windows NT systems, each user’s settings are stored in their own files called NTUSER.DAT and USRCLASS.DAT inside their own Documents and Settings subfolder (or their own Users sub folder in Windows Vista and above). Settings in this hive follow users with a roaming profile from machine to machine.

HKEY_PERFORMANCE_DATA

[edit]

This key provides runtime information into performance data provided by either the NT kernel itself, or running system drivers, programs and services that provide performance data. This key is not stored in any hive and not displayed in the Registry Editor, but it is visible through the registry functions in the Windows API, or in a simplified view via the Performance tab of the Task Manager (only for a few performance data on the local system) or via more advanced control panels (such as the Performances Monitor or the Performances Analyzer which allows collecting and logging these data, including from remote systems).
This key is used only in Windows 95, Windows 98 and Windows ME.[15] It contains information about hardware devices, including Plug and Play and network performance statistics. The information in this hive is also not stored on the hard drive; the Plug and Play information is gathered and configured at startup and is stored in memory.[16]

Even though the registry presents itself as an integrated hierarchical database, branches of the registry are actually stored in a number of disk files called hives.[17] (The word hive constitutes an in-joke.)[18]

Some hives are volatile and are not stored on disk at all. An example of this is the hive of the branch starting at HKLM\HARDWARE. This hive records information about system hardware and is created each time the system boots and performs hardware detection.

Individual settings for users on a system are stored in a hive (disk file) per user. During user login, the system loads the user hive under the HKEY_USERS key and sets the HKCU (HKEY_CURRENT_USER) symbolic reference to point to the current user. This allows applications to store/retrieve settings for the current user implicitly under the HKCU key.

Not all hives are loaded at any one time. At boot time, only a minimal set of hives are loaded, and after that, hives are loaded as the operating system initializes and as users log in or whenever a hive is explicitly loaded by an application.

The registry is physically stored in several files, which are generally obfuscated from the user-mode APIs used to manipulate the data inside the registry. Depending upon the version of Windows, there will be different files and different locations for these files, but they are all on the local machine. The location for system registry files in Windows NT is %SystemRoot%\System32\config\; the user-specific HKEY_CURRENT_USER user registry hive is stored in Ntuser.dat inside the user profile. There is one of these per user; if a user has a roaming profile, then this file will be copied to and from a server at logout and login respectively. A second user-specific registry file named UsrClass.dat contains COM registry entries and does not roam by default.

Windows NT systems store the registry in a binary file format which can be exported, loaded and unloaded by the Registry Editor in these operating systems. The following system registry files are stored in %SystemRoot%\System32\config\:

  • SamHKEY_LOCAL_MACHINE\SAM
  • SecurityHKEY_LOCAL_MACHINE\SECURITY
  • SoftwareHKEY_LOCAL_MACHINE\SOFTWARE
  • SystemHKEY_LOCAL_MACHINE\SYSTEM
  • DefaultHKEY_USERS\.DEFAULT
  • Userdiff – Not associated with a hive. Used only when upgrading operating systems.[19]

The following file is stored in each user’s profile folder:

  • %USERPROFILE%\Ntuser.datHKEY_USERS\<User SID> (linked to by HKEY_CURRENT_USER)

For Windows 2000, Server 2003 and Windows XP, the following additional user-specific file is used for file associations and COM information:

  • %USERPROFILE%\Local Settings\Application Data\Microsoft\Windows\Usrclass.dat (path is localized) – HKEY_USERS\<User SID>_Classes (HKEY_CURRENT_USER\Software\Classes)

For Windows Vista and later, the path was changed to:

  • %USERPROFILE%\AppData\Local\Microsoft\Windows\Usrclass.dat (path is not localized) alias %LocalAppData%\Microsoft\Windows\Usrclass.dat – HKEY_USERS\<User SID>_Classes (HKEY_CURRENT_USER\Software\Classes)

Windows 2000 keeps an alternate copy of the registry hives (.ALT) and attempts to switch to it when corruption is detected.[20] Windows XP and Windows Server 2003 do not maintain a System.alt hive because NTLDR on those versions of Windows can process the System.log file to bring up to date a System hive that has become inconsistent during a shutdown or crash. In addition, the %SystemRoot%\Repair folder contains a copy of the system’s registry hives that were created after installation and the first successful startup of Windows.

Each registry data file has an associated file with a «.log» extension that acts as a transaction log that is used to ensure that any interrupted updates can be completed upon next startup.[21] Internally, Registry files are split into 4 kB «bins» that contain collections of «cells».[21]

The registry files are stored in the %WINDIR% directory under the names USER.DAT and SYSTEM.DAT with the addition of CLASSES.DAT in Windows ME. Also, each user profile (if profiles are enabled) has its own USER.DAT file which is located in the user’s profile directory in %WINDIR%\Profiles\<Username>\.

The only registry file is called REG.DAT and it is stored in the %WINDIR% directory.

To access the registry files, the device needs to be set in a special mode using either: 

  • WpInternals (Put the device into flash mode.)
  • InterOp Tools (Mount the MainOS Partition with MTP.)

If any of the above methods worked, the device’s registry files can be found in the following location:

 {Phone}\EFIESP\Windows\System32\config

The registry contains important configuration information for the operating system, for installed applications as well as individual settings for each user and application. A careless change to the operating system configuration in the registry could cause irreversible damage, so it is usually only installer programs which perform changes to the registry database during installation/configuration and removal. If a user wants to edit the registry manually, Microsoft recommends that a backup of the registry be performed before the change.[22] When a program is removed from control panel, it may not be completely removed and, in case of errors or glitches caused by references to missing programs, the user might have to manually check inside directories such as program files. After this, the user might need to manually remove any reference to the uninstalled program in the registry. This is usually done by using RegEdit.exe.[23] Editing the registry is sometimes necessary when working around Windows-specific issues e.g. problems when logging onto a domain can be resolved by editing the registry.[24]

Windows Registry can be edited manually using programs such as RegEdit.exe, although these tools do not expose some of the registry’s metadata such as the last modified date.

The registry editor for the 3.1/95 series of operating systems is RegEdit.exe and for Windows NT it is RegEdt32.exe; the functionalities are merged in Windows XP. Optional and third-party tools similar to RegEdit.exe are available for many Windows CE versions.

Registry Editor allows users to perform the following functions:

  • Creating, manipulating, renaming[25] and deleting registry keys, subkeys, values and value data
  • Importing and exporting .REG files, exporting data in the binary hive format
  • Loading, manipulating and unloading registry hive format files (Windows NT systems only)
  • Setting permissions based on ACLs (Windows NT systems only)
  • Bookmarking user-selected registry keys as Favorites
  • Finding particular strings in key names, value names and value data
  • Remotely editing the registry on another networked computer

.REG files (also known as Registration entries) are text-based human-readable files for exporting and importing portions of the registry using an INI-based syntax. On Windows 2000 and later, they contain the string Windows Registry Editor Version 5.00 at the beginning, while on Windows 9x and NT 4.0 systems, they contain the string REGEDIT4.[26] Windows 2000 and later REG files are Unicode-based, while on Windows 9x and NT 4.0 systems, they are ANSI-based. [citation needed] Windows 9x format .REG files are compatible with Windows 2000 and later.[26] The Registry Editor on Windows on these systems also supports exporting .REG files in Windows 9x/NT format.[citation needed] Data is stored in .REG files using the following syntax:[26]

[<Hive name>\<Key name>\<Subkey name>]
"Value name"=<Value type>:<Value data>

The Default Value of a key can be edited by using @ instead of «Value Name»:

[<Hive name>\<Key name>\<Subkey name>]
@=<Value type>:<Value data>

String values do not require a <Value type> (see example), but backslashes (\) need to be written as a double-backslash (\\), and quotes (") as backslash-quote (\").

For example, to add the values «Value A», «Value B», «Value C», «Value D», «Value E», «Value F», «Value G», «Value H», «Value I», «Value J», «Value K», «Value L», and «Value M» to the HKLM\SOFTWARE\Foobar key:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Foobar]
"Value A"="<String value data with escape characters>"
"Value B"=hex:<Binary data (as comma-delimited list of hexadecimal values)>
"Value C"=dword:<DWORD value integer>
"Value D"=hex(0):<REG_NONE (as comma-delimited list of hexadecimal values)>
"Value E"=hex(1):<REG_SZ (as comma-delimited list of hexadecimal values representing a UTF-16LE NUL-terminated string)>
"Value F"=hex(2):<Expandable string value data (as comma-delimited list of hexadecimal values representing a UTF-16LE NUL-terminated string)>
"Value G"=hex(3):<Binary data (as comma-delimited list of hexadecimal values)> ; equal to "Value B"
"Value H"=hex(4):<DWORD value (as comma-delimited list of 4 hexadecimal values, in little endian byte order)>
"Value I"=hex(5):<DWORD value (as comma-delimited list of 4 hexadecimal values, in big endian byte order)>
"Value J"=hex(7):<Multi-string value data (as comma-delimited list of hexadecimal values representing UTF-16LE NUL-terminated strings)>
"Value K"=hex(8):<REG_RESOURCE_LIST (as comma-delimited list of hexadecimal values)>
"Value L"=hex(a):<REG_RESOURCE_REQUIREMENTS_LIST (as comma-delimited list of hexadecimal values)>
"Value M"=hex(b):<QWORD value (as comma-delimited list of 8 hexadecimal values, in little endian byte order)>

Data from .REG files can be added/merged with the registry by double-clicking these files or using the /s switch in the command line. REG files can also be used to remove registry data.

To remove a key (and all subkeys, values and data), the key name must be preceded by a minus sign (-).[26]

For example, to remove the HKLM\SOFTWARE\Foobar key (and all subkeys, values and data),

[-HKEY_LOCAL_MACHINE\SOFTWARE\Foobar]

To remove a value (and its data), the values to be removed must have a minus sign (-) after the equal sign (=).[26]

For example, to remove only the «Value A» and «Value B» values (and their data) from the HKLM\SOFTWARE\Foobar key:

[HKEY_LOCAL_MACHINE\SOFTWARE\Foobar]
"Value A"=-
"Value B"=-

To remove only the Default value of the key HKLM\SOFTWARE\Foobar (and its data):

[HKEY_LOCAL_MACHINE\SOFTWARE\Foobar]
@=-

Lines beginning with a semicolon are considered comments:

; This is a comment. This can be placed in any part of a .reg file
[HKEY_LOCAL_MACHINE\SOFTWARE\Foobar]
"Value"="Example string"

Windows group policies can change registry keys for a number of machines or individual users based on policies. When a policy first takes effect for a machine or for an individual user of a machine, the registry settings specified as part of the policy are applied to the machine or user settings.

Windows will also look for updated policies and apply them periodically, typically every 90 minutes.[27]

Through its scope a policy defines to which machines and users the policy is to be applied. Whether a machine or user is within the scope of a policy or not is defined by a set of rules which can filter on the location of the machine or user account in organizational directory, specific users or machine accounts or security groups. More advanced rules can be set up using Windows Management Instrumentation expressions. Such rules can filter on properties such as computer vendor name, CPU architecture, installed software, or networks connected to.

For instance, the administrator can create a policy with one set of registry settings for machines in the accounting department and policy with another (lock-down) set of registry settings for kiosk terminals in the visitors area. When a machine is moved from one scope to another (e.g., changing its name or moving it to another organizational unit), the correct policy is automatically applied. When a policy is changed it is automatically re-applied to all machines currently in its scope.

The policy is edited through a number of administrative templates which provides a user interface for picking and changing settings. The set of administrative templates is extensible and software packages which support such remote administration can register their own templates.

Command line editing

[edit]

reg

Developer(s) Microsoft
Operating system Microsoft Windows
Type Command
License Proprietary commercial software
Website docs.microsoft.com/en-us/windows-server/administration/windows-commands/reg

regini

Developer(s) Microsoft
Operating system Microsoft Windows
Type Command
License Proprietary commercial software
Website docs.microsoft.com/en-us/windows-server/administration/windows-commands/regini

The registry can be manipulated in a number of ways from the command line. The Reg.exe and RegIni.exe utility tools are included in Windows XP and later versions of Windows. Alternative locations for legacy versions of Windows include the Resource Kit CDs or the original Installation CD of Windows.

Also, a .REG file can be imported from the command line with the following command:

RegEdit.exe /s file

The /s means the file will be silent merged to the registry. If the /s parameter is omitted the user will be asked to confirm the operation. In Windows 98, Windows 95 and at least some configurations of Windows XP the /s switch also causes RegEdit.exe to ignore the setting in the registry that allows administrators to disable it. When using the /s switch RegEdit.exe does not return an appropriate return code if the operation fails, unlike Reg.exe which does.

RegEdit.exe /e file

exports the whole registry in V5 format to a UNICODE .REG file, while any of

RegEdit.exe /e file HKEY_CLASSES_ROOT[\<key>]
RegEdit.exe /e file HKEY_CURRENT_CONFIG[\<key>]
RegEdit.exe /e file HKEY_CURRENT_USER[\<key>]
RegEdit.exe /e file HKEY_LOCAL_MACHINE[\<key>]
RegEdit.exe /e file HKEY_USERS[\<key>]

export the specified (sub)key (which has to be enclosed in quotes if it contains spaces) only.

RegEdit.exe /a file

exports the whole registry in V4 format to an ANSI .REG file.

RegEdit.exe /a file <key>

exports the specified (sub)key (which has to be enclosed in quotes if it contains spaces) only.

It is also possible to use Reg.exe. Here is a sample to display the value of the registry value Version:

Reg.exe QUERY HKLM\Software\Microsoft\ResKit /v Version

Other command line options include a VBScript or JScript together with CScript, WMI or WMIC.exe and Windows PowerShell.

Registry permissions can be manipulated through the command line using RegIni.exe and the SubInACL.exe tool. For example, the permissions on the HKEY_LOCAL_MACHINE\SOFTWARE key can be displayed using:

SubInACL.exe /keyreg HKEY_LOCAL_MACHINE\SOFTWARE /display

PowerShell commands and scripts

[edit]

Using PowerShell to navigate the registry

Windows PowerShell comes with a registry provider which presents the registry as a location type similar to the file system. The same commands used to manipulate files and directories in the file system can be used to manipulate keys and values of the registry.[28]

Also like the file system, PowerShell uses the concept of a current location which defines the context on which commands by default operate. The Get-ChildItem (also available through the aliases ls, dir or gci) retrieves the child keys of the current location. By using the Set-Location (or the alias cd) command the user can change the current location to another key of the registry.[28] Commands which rename items, remove items, create new items or set content of items or properties can be used to rename keys, remove keys or entire sub-trees or change values.

Through PowerShell scripts files, an administrator can prepare scripts which, when executed, make changes to the registry. Such scripts can be distributed to administrators who can execute them on individual machines. The PowerShell Registry provider supports transactions, i.e. multiple changes to the registry can be bundled into a single atomic transaction. An atomic transaction ensures that either all of the changes are committed to the database, or if the script fails, none of the changes are committed to the database.[28][29]

Programs or scripts

[edit]

The registry can be edited through the APIs of the Advanced Windows 32 Base API Library (advapi32.dll).[30] List of registry API functions:

  • RegCloseKey
  • RegConnectRegistry
  • RegCreateKey
  • RegCreateKeyEx
  • RegDeleteKey
  • RegDeleteValue
  • RegEnumKey
  • RegEnumKeyEx
  • RegEnumValue
  • RegFlushKey
  • RegGetKeySecurity
  • RegLoadKey
  • RegNotifyChangeKeyValue
  • RegOpenKey
  • RegOpenKeyEx
  • RegQueryInfoKey
  • RegQueryMultipleValues
  • RegQueryValue
  • RegQueryValueEx
  • RegReplaceKey
  • RegRestoreKey
  • RegSaveKey
  • RegSetKeySecurity
  • RegSetValue
  • RegSetValueEx
  • RegUnLoadKey

Many programming languages offer built-in runtime library functions or classes that wrap the underlying Windows APIs and thereby enable programs to store settings in the registry (e.g. Microsoft.Win32.Registry in VB.NET and C#, or TRegistry in Delphi and Free Pascal). COM-enabled applications like Visual Basic 6 can use the WSH WScript.Shell object. Another way is to use the Windows Resource Kit Tool, Reg.exe by executing it from code,[31] although this is considered poor programming practice.

Similarly, scripting languages such as Perl (with Win32::TieRegistry), Python (with winreg), TCL (which comes bundled with the registry package),[32] Windows Powershell and Windows Scripting Host also enable registry editing from scripts.

The offreg.dll[33] available from the Windows Driver Kit offers a set of APIs for the creation and manipulation of currently not loaded registry hives similar to those provided by advapi32.dll.

It is also possible to edit the registry (hives) of an offline system from Windows PE or Linux (in the latter case using open source tools).

COM self-registration

[edit]

Prior to the introduction of registration-free COM, developers were encouraged to add initialization code to in-process and out-of-process binaries to perform the registry configuration required for that object to work. For in-process binaries such as .DLL and .OCX files, the modules typically exported a function called DllInstall()[34] that could be called by installation programs or invoked manually with utilities like Regsvr32.exe;[35] out-of-process binaries typically support the commandline arguments /Regserver and /Unregserver that created or deleted the required registry settings.[36] COM applications that break because of DLL Hell issues can commonly be repaired with RegSvr32.exe or the /RegServer switch without having to re-invoke installation programs.[37]

Advanced functionality

[edit]

Windows exposes APIs that allows user-mode applications to register to receive a notification event if a particular registry key is changed.[38] APIs are also available to allow kernel-mode applications to filter and modify registry calls made by other applications.[39]

Windows also supports remote access to the registry of another computer via the RegConnectRegistry function[40] if the Remote Registry service is running, correctly configured and its network traffic is not firewalled.[41]

Each key in the registry of Windows NT versions can have an associated security descriptor. The security descriptor contains an access control list (ACL) that describes which user groups or individual users are granted or denied access permissions. The set of registry permissions include 10 rights/permissions which can be explicitly allowed or denied to a user or a group of users.

Registry permissions

Permission Description
Query Value The right to read the registry key value.
Set Value The right to write a new value
Create Subkey The right to create subkeys.
Enumerate Subkeys Allow the enumeration of subkeys.
Notify The right to request change notifications for registry keys or subkeys.
Create Link Reserved by the operating system.
Delete The right to delete a key.
Write DACL The right to modify permissions of the container’s DACL.
Write Owner The right to modify the container’s owner.
Read Control The right to read the DACL.

As with other securable objects in the operating system, individual access control entries (ACE) on the security descriptor can be explicit or inherited from a parent object.[42]

Windows Resource Protection is a feature of Windows Vista and later versions of Windows that uses security to deny Administrators and the system WRITE access to some sensitive keys to protect the integrity of the system from malware and accidental modification.[43]

Special ACEs on the security descriptor can also implement mandatory integrity control for the registry key and subkeys. A process running at a lower integrity level cannot write, change or delete a registry key/value, even if the account of the process has otherwise been granted access through the ACL. For instance, Internet Explorer running in Protected Mode can read medium and low integrity registry keys/values of the currently logged on user, but it can only modify low integrity keys.[44]

Outside security, registry keys cannot be deleted or edited due to other causes. Registry keys containing NUL characters cannot be deleted with standard registry editors and require a special utility for deletion, such as RegDelNull.[45][46]

Backups and recovery

[edit]

Different editions of Windows have supported a number of different methods to back up and restore the registry over the years, some of which are now deprecated:

  • System Restore can back up the registry and restore it as long as Windows is bootable, or from the Windows Recovery Environment (starting with Windows Vista).
  • NTBackup can back up the registry as part of the System State and restore it. Automated System Recovery in Windows XP can also restore the registry.
  • On Windows NT, the Last Known Good Configuration option in startup menu relinks the HKLM\SYSTEM\CurrentControlSet key, which stores hardware and device driver information.
  • Windows 98 and Windows ME include command line (Scanreg.exe) and GUI (Scanregw.exe) registry checker tools to check and fix the integrity of the registry, create up to five automatic regular backups by default and restore them manually or whenever corruption is detected.[47] The registry checker tool backs up the registry, by default, to %Windir%\Sysbckup Scanreg.exe can also run from MS-DOS.[48]
  • The Windows 95 CD-ROM included an Emergency Recovery Utility (ERU.exe) and a Configuration Backup Tool (Cfgback.exe) to back up and restore the registry. Additionally Windows 95 backs up the registry to the files system.da0 and user.da0 on every successful boot.
  • Windows NT 4.0 included RDISK.EXE, a utility to back up and restore the entire registry.[49]
  • Windows 2000 Resource Kit contained an unsupported pair of utilities called Regback.exe and RegRest.exe for backup and recovery of the registry.[50]
  • Periodic automatic backups of the registry are now disabled by default on Windows 10 May 2019 Update (version 1903). Microsoft recommends System Restore be used instead.[51]

Windows 2000 and later versions of Windows use Group Policy to enforce registry settings through a registry-specific client extension in the Group Policy processing engine.[52] Policy may be applied locally to a single computer using gpedit.msc or to multiple users and computers in a domain using gpmc.msc.

With Windows 95, Windows 98, Windows ME and Windows NT 4.0, administrators can use a special file to be merged into the registry, called a policy file (POLICY.POL). The policy file allows administrators to prevent non-administrator users from changing registry settings like, for instance, the security level of Internet Explorer and the desktop background wallpaper. The policy file is primarily used in a business with a large number of computers where the business needs to be protected from rogue or careless users.

The default extension for the policy file is .POL.
The policy file filters the settings it enforces by user and by group (a «group» is a defined set of users). To do that the policy file merges into the registry, preventing users from circumventing it by simply changing back the settings.
The policy file is usually distributed through a LAN, but can be placed on the local computer.

The policy file is created by a free tool by Microsoft that goes by the filename poledit.exe for Windows 95/Windows 98 and with a computer management module for Windows NT. The editor requires administrative permissions to be run on systems that uses permissions.
The editor can also directly change the current registry settings of the local computer and if the remote registry service is installed and started on another computer it can also change the registry on that computer.
The policy editor loads the settings it can change from .ADM files, of which one is included, that contains the settings the Windows shell provides. The .ADM file is plain text and supports easy localisation by allowing all the strings to be stored in one place.

INI file virtualization

[edit]

Windows NT kernels support redirection of INI file-related APIs into a virtual file in a registry location such as HKEY_CURRENT_USER using a feature called «InifileMapping».[53] This functionality was introduced to allow legacy applications written for 16-bit versions of Windows to be able to run under Windows NT platforms on which the System folder is no longer considered an appropriate location for user-specific data or configuration. Non-compliant 32-bit applications can also be redirected in this manner, even though the feature was originally intended for 16-bit applications.

Registry virtualization

[edit]

Windows Vista introduced limited registry virtualization, whereby poorly written applications that do not respect the principle of least privilege and instead try to write user data to a read-only system location (such as the HKEY_LOCAL_MACHINE hive), are silently redirected to a more appropriate location, without changing the application itself.

Similarly, application virtualization redirects all of an application’s invalid registry operations to a location such as a file. Used together with file virtualization, this allows applications to run on a machine without being installed on it.

Low integrity processes may also use registry virtualization. For example, Internet Explorer 7 or 8 running in «Protected Mode» on Windows Vista and above will automatically redirect registry writes by ActiveX controls to a sandboxed location in order to frustrate some classes of security exploits.

The Application Compatibility Toolkit[54] provides shims that can transparently redirect HKEY_LOCAL_MACHINE or HKEY_CLASSES_ROOT Registry operations to HKEY_CURRENT_USER to address «LUA» bugs that cause applications not to work for users with insufficient rights.

Critics labeled the registry in Windows 95 a single point of failure, because re-installation of the operating system was required if the registry became corrupt. However, Windows NT uses transaction logs to protect against corruption during updates. Current versions of Windows use two levels of log files to ensure integrity even in the case of power failure or similar catastrophic events during database updates.[55] Even in the case of a non-recoverable error, Windows can repair or re-initialize damaged registry entries during system boot.[55]

Equivalents and alternatives

[edit]

In Windows, use of the registry for storing program data is a matter of developer’s discretion. Microsoft provides programming interfaces for storing data in XML files (via MSXML) or database files (via SQL Server Compact) which developers can use instead. Developers are also free to use non-Microsoft alternatives or develop their own proprietary data stores.

In contrast to Windows Registry’s binary-based database model, some other operating systems use separate plain-text files for daemon and application configuration, but group these configurations together for ease of management.

  • In Unix-like operating systems (including Linux) that follow the Filesystem Hierarchy Standard, system-wide configuration files (information similar to what would appear in HKEY_LOCAL_MACHINE on Windows) are traditionally stored in files in /etc/ and its subdirectories, or sometimes in /usr/local/etc/. Per-user information (information that would be roughly equivalent to that in HKEY_CURRENT_USER) is stored in hidden directories and files (that start with a period/full stop) within the user’s home directory. However XDG-compliant applications should refer to the environment variables defined in the Base Directory specification.[56]
  • In macOS, system-wide configuration files are typically stored in the /Library/ folder, whereas per-user configuration files are stored in the corresponding ~/Library/ folder in the user’s home directory, and configuration files set by the system are in /System/Library/. Within these respective directories, an application typically stores a property list file in the Preferences/ sub-directory.
  • RISC OS (not to be confused with MIPS RISC/os) uses directories for configuration data, which allows applications to be copied into application directories, as opposed to the separate installation process that typifies Windows applications; this approach is also used on the ROX Desktop for Linux.[57] This directory-based configuration also makes it possible to use different versions of the same application, since the configuration is done «on the fly».[58] If one wishes to remove the application, it is possible to simply delete the folder belonging to the application.[59][60] This will often not remove configuration settings which are stored independently from the application, usually within the computer’s !Boot structure, in !Boot.Choices or potentially anywhere on a network fileserver. It is possible to copy installed programs between computers running RISC OS by copying the application directories belonging to the programs, however some programs may require re-installing, e.g. when shared files are placed outside an application directory.[58]
  • IBM AIX (a Unix variant) uses a registry component called Object Data Manager (ODM). The ODM is used to store information about system and device configuration. An extensive set of tools and utilities provides users with means of extending, checking, correcting the ODM database. The ODM stores its information in several files, default location is /etc/objrepos.
  • The GNOME desktop environment uses a registry-like interface called dconf for storing configuration settings for the desktop and applications.
  • The Elektra Initiative provides alternative back-ends for various different text configuration files.
  • While not an operating system, the Wine compatibility layer, which allows Windows software to run on a Unix-like system, also employs a Windows-like registry as text files in the WINEPREFIX folder: system.reg (HKEY_LOCAL_MACHINE), user.reg (HKEY_CURRENT_USER) and userdef.reg.[61]
  • Registry cleaner
  • Application virtualization
  • LogParser – SQL-like querying of various types of log files
  • List of Shell Icon Overlay Identifiers
  • Ransomware attack that uses Registry
  1. ^ When applications fail to execute because they request more privileges than they require (and are denied those privileges), this is known as a limited user application (LUA) bug.
  1. ^ Esposito, Dino (November 2000). «Windows 2000 Registry: Latest Features and APIs Provide the Power to Customize and Extend Your Apps». MSDN Magazine. Microsoft. Archived from the original on April 15, 2003. Retrieved July 19, 2007.
  2. ^ a b c «The System Registry».
  3. ^ «Windows 95 Architecture Components». www.microsoft.com. Archived from the original on February 7, 2008. Retrieved April 29, 2008. The following table shows other difficulties or limitations caused by using .INI files that are overcome by using the Registry.
  4. ^ Hipson 2002, p. 5, 41–43.
  5. ^ Richter, Jeffrey; Nasarre, Christophe (2008). Windows Via C/C++ (Fifth ed.). Microsoft Press. ISBN 9780735642461. Retrieved August 28, 2021.
  6. ^ Raymond Chen, «Why do registry keys have a default value?»
  7. ^ Hipson 2002, pp. 207, 513–514.
  8. ^ Hipson 2002, pp. 520–521.
  9. ^ Hipson 2002, p. 7.
  10. ^ «Designed for Windows XP Application Specification». Microsoft. August 20, 2002. Retrieved April 8, 2009.
  11. ^ «HKEY_LOCAL_MACHINE». Gautam. 2009. Retrieved April 8, 2009.
  12. ^ «Registry Keys Affected by WOW64 (Windows)». Msdn.microsoft.com. Retrieved April 10, 2014.
  13. ^ «Description of the Microsoft Windows registry». Retrieved September 25, 2008.
  14. ^ «HKEY_CURRENT_USER». Microsoft. 2009. Retrieved April 8, 2009.
  15. ^ «Description of the HKEY_DYN_DATA Registry Key in Windows 95, Windows 98, and Windows 98 SE». support.microsoft.com.
  16. ^ «A Closer Look at HKEY_DYN_DATA». rinet.ru. Archived from the original on May 9, 2008.
  17. ^ «Registry hives». Retrieved July 19, 2007.
  18. ^ Chen, Raymond (August 8, 2011). «Why is a registry file called a «hive»?». The Old New Thing. Retrieved July 29, 2011.
  19. ^ «Overview of the Windows NT Registry». Retrieved December 2, 2011.
  20. ^ «Inside the Registry». Retrieved December 28, 2007.
  21. ^ a b Norris, Peter (February 2009). «The Internal Structure of the Windows Registry» (PDF). Cranfield University. Archived from the original (PDF) on May 29, 2009.
  22. ^ «Incorrect Icons Displayed for .ico Files». November 15, 2009. Retrieved March 31, 2012.
  23. ^ «How to Completely Uninstall / Remove a Software Program in Windows without using 3rd Party Software? — AskVG». www.askvg.com. August 26, 2011.
  24. ^ «You may receive a «STOP 0x00000035 NO_MORE_IRP_STACK_LOCATIONS» error message when you try to log on to a domain». October 9, 2011. Retrieved March 31, 2012. This page tells the user to edit the registry when resolving the issue.
  25. ^ key renaming is implemented as removal and add while retaining subkeys/values, as the underlying APIs do not support the rename function directly
  26. ^ a b c d e «How to add, modify, or delete registry subkeys and values by using a .reg file». support.microsoft.com.
  27. ^ «Applying Group Policy». Microsoft.
  28. ^ a b c Payette, Bruce; Siddaway, Richard (2018). Windows PowerShell in Action (Third ed.). Manning Publications. pp. 7–8, 24, 608, 708–710. ISBN 9781633430297. Retrieved August 28, 2021.
  29. ^ Warner, Timothy L. (May 2015). Windows PowerShell in 24 Hours, Sams Teach Yourself. Sams Publishing. p. 19, 211. ISBN 9780134049359. Retrieved August 28, 2021.
  30. ^ «Reading and Writing Registry Values with Visual Basic». Retrieved July 19, 2007.
  31. ^ «REG command in Windows XP». Retrieved July 19, 2007.
  32. ^ «registry manual page – Tcl Bundled Packages». www.tcl.tk. Retrieved December 14, 2017.
  33. ^ «Offline Registry Library». Retrieved June 4, 2014.
  34. ^ «DllInstall Function». Microsoft. March 7, 2012. Retrieved March 22, 2012.
  35. ^ «Regsvr32». Microsoft. Retrieved March 22, 2012.
  36. ^ «How to: Register Automation Servers». Microsoft. Retrieved March 22, 2012.
  37. ^ «How to re-register PowerPoint 2000, PowerPoint 2003, PowerPoint 2007 and PowerPoint 2010». Microsoft. January 2012. Retrieved March 22, 2012.
  38. ^ «RegNotifyChangeKeyValue function». Microsoft.
  39. ^ «Registering for Notifications». Microsoft.
  40. ^ «RegConnectRegistry function». Microsoft.
  41. ^ «How to Manage Remote Access to the Registry». Microsoft.
  42. ^ Gibson, Darril (June 28, 2011). «Chapter 4: Securing Access with Permissions». Microsoft Windows security : essentials. Indianapolis, Ind.: Wiley. ISBN 978-1-118-01684-8.
  43. ^ «Application Compatibility: Windows Resource Protection (WRP)». Microsoft. Retrieved August 8, 2012.
  44. ^ Marc Silbey, Peter Brundrett. «Understanding and Working in Protected Mode Internet Explorer». Retrieved August 8, 2012.
  45. ^ «RegDelNull v1.1». November 1, 2006. Retrieved August 8, 2012.
  46. ^ «Unable to delete certain registry keys – Error while deleting key». March 23, 2010. Retrieved August 8, 2012. Microsoft Support page.
  47. ^ «Description of the Windows Registry Checker Tool (Scanreg.exe)».
  48. ^ «Command-Line Switches for the Registry Checker Tool».
  49. ^ «How To Backup, Edit, and Restore the Registry in Windows NT 4.0». support.microsoft.com.
  50. ^ «Technical Reference to the Registry: Related Resources». Microsoft. Retrieved September 9, 2011.
  51. ^ Whitwam, Ryan (July 2019). «Microsoft Kills Automatic Registry Backups in Windows 10». ExtremeTech. Retrieved July 1, 2019.
  52. ^ «How Core Group Policy Works». Microsoft. September 2, 2009. Retrieved August 13, 2012.
  53. ^ «Chapter 26 – Initialization Files and the Registry». Microsoft. Retrieved March 3, 2008.
  54. ^ «Microsoft Application Compatibility Toolkit 5.0». Microsoft. Retrieved July 26, 2008.
  55. ^ a b Ionescu, Mark Russinovich, David A. Solomon, Alex (2012). «Registry Internals». Windows internals (6th ed.). Redmond, Wash.: Microsoft Press. ISBN 978-0-7356-4873-9.{{cite book}}: CS1 maint: multiple names: authors list (link)
  56. ^ «XDG Base Directory Specification». standards.freedesktop.org.
  57. ^ «Application directories». Archived from the original on May 27, 2012. Retrieved May 17, 2012.
  58. ^ a b «Case Studies Of The Top 132 Annoyances With Operating Systems Other Than RISC OS». Retrieved April 3, 2012. Page from the riscos.com website. Mentioned in points 82 and 104.
  59. ^ «RISC OS tour». Retrieved July 19, 2007.
  60. ^ «The RISC OS Products Directory». November 2, 2006. Archived from the original on February 19, 2007. Retrieved April 1, 2012.
  61. ^ 3.2. Using the Registry and Regedit (Wine User Guide)
  • Hipson, Peter (2002). Mastering Windows XP Registry. Wiley. ISBN 0-7821-2987-0. Retrieved August 28, 2021.
  • Russinovich, Mark E.; Solomon, David A. (2005). Microsoft Windows Internals (Fourth ed.). Microsoft Press. pp. 183–236. ISBN 978-0-7356-1917-3.
  • Windows Registry info & reference in the MSDN Library

Во многих своих статьях я указываю твики реестра и говорю об изменении каких-либо параметров, которые тем или иным образом изменяют конфигурацию операционной системы Windows. Насколько известно большинству пользователей персональных компьютеров, реестр играет основную роль в конфигурировании и управлении операционных систем, и является неким хранилищем общесистемных и пользовательских параметров. Несмотря на то, что многие уверены в том, что все конфигурационные данные хранятся именно в виде данных на жестком диске, на самом деле параметры системного реестра расположены в памяти самого компьютера и поддерживаются исполнительной системой, а также ядром самой операционной системы. Об этом моменте, как и о многих других, вы узнаете из контекста данной статьи.

Использование системного реестра

Итак, реестром Windows является иерархическая база данных, которая хранит конфигурационную информацию операционной системы, приложений, а также информации о пользователях и оборудовании. Структура данных для удобности использования предоставлена в древовидном формате. Большую часть параметров, содержащихся в реестре вы можете отконфигурировать вручную при помощи пользовательского интерфейса (например, в разделе HKEY_CURRENT_USERSoftwarePoliciesMicrosoftWindowsExplorer вы можете выполнять настройки в меню «Пуск», что также можете сделать из диалогового окна «Настройка меню «Пуск»», вызываемого по нажатии на кнопку «Настроить» в свойствах панели задач и меню «Пуск»), однако, для изменения некоторых дополнительных параметров никакого графического пользовательского интерфейса (GUI) не предусмотрено (например, для настройки диалога переключения между окнами вы можете воспользоваться параметрами из раздела HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorerAltTab). Для настройки таких параметров удобнее всего использовать ряд утилит, предназначенных для модификации реестра. Операционная система Windows предоставляет такие штатные средства для работы с реестром, как утилита «Редактор реестра» (Regedit.exe), которая имеет удобный для работы графический интерфейс, а также утилиты командной строки Reg. При помощи этих обеих утилит вы можете просматривать, добавлять, удалять, сравнивать, а также копировать, составлять и восстанавливать отдельные копии элементов реестра. При работе с каждой из этих утилит стоит быть внимательными и осторожными, так как некорректное изменение параметров реестра чревато серьезными последствиями, из-за которых может даже понадобиться переустанавливать операционную систему.

Считываться конфигурационная информация системного реестра может в различные моменты работы операционной системы, начиная с модификации какого-либо конкретного параметра или раздела и заканчивая мониторингом конфигурационных параметров специфического программного обеспечения. Но всегда конфигурационные данные системного реестра считываются в следующих случаях:

  • Во время загрузки операционной системы считываются некоторые параметры, которые определяют, какие драйвера для различных устройств необходимо загрузить;
  • Во время загрузки ядра операционной системы, также используются некоторые параметры, которые позволяют настраивать поведение операционной системы, такие как диспетчер памяти, диспетчер процессов и пр.;
  • При загрузке графической подсистемы и компонентов Windows, таких как Проводник Windows, Панель Управления и пр., из системного реестра считываются конфигурационные настройки и предпочтения текущего пользователя. К этой категории можно отнести расположение ярлыков на рабочем столе, цветовые схемы, различные надстройки и панели управления веб-браузера Internet Explorer и другие;
  • Во время запуска любого приложения из реестра считываются общесистемные параметры, включая информацию о лицензировании, настройки для данного пользователя и прочее.

Помимо считывания данных о разделах и параметрах системного реестра, его данные также могут модифицироваться. Далее предоставлен список наиболее часто повторяющихся ситуаций, связанных с модификацией параметров и разделов реестра:

  • Прежде всего, вся структура системного реестра, а также настройки, установленные по умолчанию, определяются версией, поставляемой на дистрибутиве операционной системы, которая копируется при установке новой системы;
  • Разделы и параметры в реестре создаются при установке драйвера Plug and Play, которые определяют работу самого драйвера, а также в каком случае следует запускать драйвер для устройства;
  • Во время установки всевозможных приложений, для их настроек по умолчанию создаются новые разделы с параметрами;
  • Во время изменения параметров приложений или свойств самой операционной системы посредствам пользовательского интерфейса изменяются определённые параметры реестра.

Структура реестра

Все вышеперечисленные конфигурационные параметры содержатся в разделах реестра, которые размещены в корневом разделе, контролирующем, как и когда будут использоваться вложенные разделы и параметры. В каждом разделе могут быть созданы записи, называемые параметрами. Раздел может содержать любое количество параметров, значения которых могут быть предоставлены в любой возможной форме. Каждый раздел имеет свое уникальное имя, состоящее из одного или нескольких символов, не чувствительных к регистру. Все имена корневых разделов представляют Windows-описатели (Handlers) разделов (HEY), в связи с этим и было создано название ключевых разделов HKEY (HK). В следующей таблице вы можете увидеть названия разделов, их аббревиатур, а также краткое описание:

Имя корневого раздела Аббревиатура Описание
HKEY_USERS HKU В текущем разделе содержатся подразделы, в которых хранится информация обо всех учетных записях на текущем компьютере
HKEY_CURRENT_USER HKCU Данный раздел содержит данные, которые ссылаются на профиль пользователя, который вошел в систему на данный момент
HK_LOCAL_MACHINE HKLM Этот раздел содержит конфигурационные параметры системного уровня
HKEY_CLASSES_ROOT HKCR В текущем разделе расположены конфигурационные параметры для приложений и файлов, а также хранится регистрационная информация COM-объектов
HKEY_CURRENT_CONFIG HKCC В данный раздел включены информационные сведения об используемом профиле оборудования
HKEY_PERFORMANCE_DATA HKPD Этот раздел хранит некоторые сведения о производительности системы

Таблица 1. Описание корневых разделов системного реестра Windows

В следующих подразделах вы найдете более подробную информацию о каждом корневом разделе реестра.

HKEY_USERS

В корневом разделе HKEY_USERS (HKU) системного реестра вы можете найти подразделы для каждого пользовательского профиля, а также регистрационную базу данных классов и подраздел HKU.DEFAULT, который связан с профилем, предназначенным для процессов, выполняемых под локальной системной учетной записью. Помимо этого, данный профиль используется службой Winlogon, скажем, для изменения параметров фона рабочего стола на экране входа в систему. Также, много системных служб запускается от имени учетной записи Local System, где применяется профиль по умолчанию. Для этого раздела недоступна информация, которая хранится в профиле пользователей, сопоставленных с другими учетными записями. Информация по каждому профилю операционной системы помещается в подраздел, имя которого соответствует идентификатору (SID) учетной записи. Сами конфигурационные данные, которые находятся в таких подразделах, включают в себя время последней загрузки данного профиля, двоичное представление этого идентификатора, а также путь к кусту профиля на жестком диске.

Еще некоторые службы используют учетную запись, которой необходимо аутентифицироваться на других компьютерах, расположенных в локальной сети, но не требуется членство в административных группах или привилегий, которые назначаются учетной записью Local System. Такая учетная запись называется Network Service и процессы, выполняемые под этой учетной записью, используют ее профиль, который расположен в разделе HKUS-1-5-20 и его файлы расположены в папке %SystemRoot%ServiceProfilesNetworkService.

Еще есть учетная запись Local Service, которая по своим особенностям очень похожа на Network Service, но к основному ее отличию можно отнести то, что эта учетная запись обращается только лишь к тем сетевым ресурсам, которые разрешают анонимный доступ. Такой профиль загружается в разделе HKUS-1-5-19 и физически хранится в папке %SystemRoot%ServiceProfilesLocalService.

HKEY_CURRENT_USER

В корневом разделе HKEY_CURRENT_USER (HKCU) вы найдете конфигурационные параметры программного обеспечения и пользовательские данные, зарегистрированные для текущего локального пользователя. Всегда подразделы HKCU и их параметры будут ссылаться только на профиль текущего пользователя, который на жестком диске можно найти в файле c:Users%username%Ntuser.dat. И каждый раз, при загрузке профиля пользователя, на подраздел в HKEY_USERS создается ссылка, соответствующая текущему вошедшему в систему пользователю. Во вложенных подразделах этого корневого раздела системного реестра вы можете настраивать:

  • Сопоставления звуковых сигналов, согласно различным событиям (подраздел AppEvent);
  • Параметры внешнего вида окна командной строки (подраздел Console);
  • Конфигурационные параметры для настроек панели управления текущего пользователя (подраздел Control Panel, в котором вы можете настроить дополнительные параметры существующих экранных заставок, оформление вашего рабочего стола, настройки специальных возможностей, компонента «Часы, язык и регион», а также параметры клавиатуры и мыши);
  • Указать пути переменных окружений для текущего пользователя (подраздел Environment);
  • Информация о знаках EUDC для конечного пользователя (подраздел EUDC);
  • Конфигурационные параметры для учетной записи Windows Mail (подраздел Identities);
  • Изменить параметры раскладки клавиатуры (подраздел Keyboard Layout);
  • Указывать имена и всевозможные параметры подключенных к этому текущему пользователю сетевых дисков (подраздел Network);
  • Изменять параметры подключенных принтеров (подраздел Printers);
  • Управлять настройками удаленного использования данного компьютера (подраздел RemoteAccess);
  • Устанавливать всевозможные настройки для штатного программного обеспечения, а также приложений, разработанных третьими сторонами (подраздел Software);
  • Изменять некоторые системные параметры (подраздел System);
  • Указывать переменные окружения, отвечающие за имя пользователя, расположение папки AppData и прочее (подраздел Volatile Environment);
  • Настраивать группы главного меню, которые являются специфическими для каждого пользователя.

HKEY_LOCAL_MACHINE

Корневой раздел HKEY_LOCAL_MACHINE (HKLM) содержит свои подразделы с параметрами конфигурации, относящиеся к общесистемной конфигурации текущего компьютера, то есть конфигурационных данных, которые не настраиваются для всех пользователей. Стоит обратить внимание на то, что системный реестр 64-разрядных версий операционных систем Windows состоит из 32- и 64-битных разделов реестра, где у большинства 32-разрядных разделов реестра названия разделов идентичны тем, которые указаны в 64-разрядном разделе, и наоборот. По умолчанию, 64-разрядная версия редактора реестра (утилита Regedit.exe), которая входит в состав 64-разрядных операционных систем Windows отображает как 64, так и 32-разрядные разделы. В 64-разрядной версии утилиты «Редактор реестра», 32-разрядные разделы расположены здесь: HKEY_LOCAL_MACHINESoftwareWOW6432Node. Раздел HKLM содержит следующие основные подразделы:

BCD. Данный подраздел содержит информацию о конфигурационной базе данных загрузки (Boot Configuration Database BCD). Эта база данных заменяет файл Boot.ini, который использовался в операционных системах, вышедших до Windows Vista, и предоставляет больше возможностей для конфигурации данных о загрузке ОС. Каждая запись в текущем подразделе, которая была сделана во время установки операционной системы или во время изменения параметров загрузка средствами командной строки, хранится в дочернем подразделе Objects или в качестве самого объекта, на который ссылается загрузочная запись в виде GUID, или в подразделах с названиями в виде цифр. Значения, связанные с каждым параметром подразделов соответствуют параметрам утилиты bcdedit.exe командной строки.

COMPONENTS. В текущем подразделе содержится информация, которая относится к компоненту на основании обслуживания стека (Component Based Servicing CBS). Данный стек включает в себя всевозможные файлы и ресурсы, которые являются частью образа установщика Windows. Параметры CBS API, которые расположены в данном разделе, предназначены для определения установленных компонентов и их конфигурации. Используется же вся эта информация каждый раз, когда компоненты устанавливаются, обновляются или удаляются в индивидуальном, либо в пакетном режимах.

HARDWARE. Этот подраздел включает в себя описание аппаратного обеспечения для локальной системы, а также все сопоставления драйверов с физическими устройствами. Здесь вы можете найти конфигурационные параметры для всех устройств, которые присутствуют в «Диспетчере устройств». В разделе HARDWARE можно отметить четыре основных подраздела. Подраздел ACPI содержит информацию о конкретных возможностях ACPI на этом компьютере. Подраздел Descriptions содержит описания центральных процессоров, процессоров для операций с плавающей точкой, а также многофункциональных устройств компьютера. Подраздел DeviceMap сопоставляет устройства драйверам. В подразделе ResourceMap имеются три основных подраздела. Первый предназначен для уровня аппаратных абстракций, таких как HAL, применяемый при отслеживании найденных устройств. Второй — для Plug-and-Play Manager, то есть для записи устройств, про которые известно. А третий — для отображения объема оперативной памяти. В зависимости от аппаратной конфигурации данный раздел может содержать дополнительные подразделы.

SAM. Подраздел SAM (Security Accounts Manager) раздела HKLM включает в себя такую информацию о локальных пользователях и группах, как сопоставления с доменом Active Directory, определения групп, а также пароли. Несмотря на то, что на контроллерах домена Active Directory в базе данных хранятся общедоступные параметры и сведения о пользователях, компьютерах и доменных группах, SAM-файл является базой учетных записей пользователей, содержащей сведения об уровнях пользовательских привилегий, паролей и т.п., дескриптор защиты которой сконфигурирован так, что к нему не имеет доступ даже администратор. Поэтому по умолчанию вся ветвь подраздела SAM закрыта от просмотра. Вспомогательными файлами для данного раздела являются файлы Sam, Sam.log и Sam.sav.

SECURITY. С данным подразделом связаны данные, которые имеют отношение к общесистемным политикам безопасности. Помимо этого, подразделы SAM и SECURITY связаны специально для хранения информации о правах, назначенных пользователям в подразделе HKLMSECURITYSAM. Просмотр данного раздела многого не даст (по умолчанию дескриптор защиты установлен так, что доступ к этому разделу есть только у учетной записи System), так как данные, которые в нем содержаться, не документированы, а все пароли тщательно зашифрованы. Вспомогательными файлами для данного раздела являются файлы Security, Security.log и Security.sav.

SOFTWARE. Текущий подраздел можно назвать в какой-то степени корнем всей структуры подразделов HKLM, так как это именно то место, где операционная система Windows хранит общесистемную конфигурационную информацию приложений и компонентов, которые не принимают участие в загрузке самой системы. Кроме того, при установке программного обеспечения именно в этом разделе создаются подразделы, предназначенные для сохранения своих общесистемных настроек. Большая часть данных о настройках пользовательского интерфейса хранится в подразделе HKLMSoftwareMicrosoftWindowsCurrentVersion. Здесь также вы можете с легкостью найти подразделы, предназначенные для восстановления системы, шифрующей файловой системы, службы терминалов и многое другое. Вспомогательными файлами для данного раздела являются файлы Software, Software.log и Software.sav.

SYSTEM. В этом, последнем, разделе HKLM находится общесистемная конфигурационная информация, которая выполняется в последнюю очередь после завершения загрузки операционной системы. К таким данным можно отнести управляющие настройки, список драйверов и запускаемых служб, которые применяются при последней удачной загрузке, также называемой последней конфигурацией, так как для запуска операционной системы она критична и Windows всегда делает ее копию. Одним из основных подразделов HKLMSYSTEM является подраздел CurrentControlSet, который указывает на набор управляющих настроек, используемых на данный момент операционной системой. Вспомогательными файлами для данного раздела являются файлы System, System.alt, System.log и System.sav.

HKEY_CLASSES_ROOT

Этот корневой раздел, в какой-то степени, можно назвать подразделом HKEY_LOCAL_MACHINESoftwareClasses, содержащий параметры по умолчанию, которые относятся ко всем пользователям локального компьютера. Он включает в себя сопоставления расширений файлов, а также идентифицирующие данные COM-классов. Здесь для каждого зарегистрированного типа файлов, в соответствующих подразделах, указаны сведения, обеспечивающие выполнение необходимой программы при открытии файла. В свою очередь, в подразделе HKEY_CURRENT_USERSoftwareClasses, параметры определяют регистрационные данные классов расширений файлов, которые относятся только к текущему пользователю и физически расположены в файле c:Users%имя_пользователя%AppDataLocalMicrosoftWindows UsrClass.dat. Данные этого источника также включены в раздел HKCR, но данные, которые были добавлены или изменены непосредственно из этого раздела будут сохранены операционной системой в разделе HKEY_LOCAL_MACHINESoftwareClasses. Стоит также обратить внимание на то, что для каждого пользователя локального компьютера такие данные являются специфическими, что не позволяет непривилегированному пользователю изменять или удалять разделы в HKCR, а также указывать специфические настройки для определенных типов файлов конкретным пользователям.

HKEY_CURRENT_CONFIG

Если корневой раздел HKEY_CLASSES_ROOT можно назвать ссылкой на разделы HKEY_LOCAL_MACHINESoftwareClasses и HKEY_CURRENT_USERSoftwareClasses, то данный раздел является обыкновенной ссылкой на текущий профиль оборудования, расположенный в разделе HKEY_LOCAL_MACHINESystemCurrentControlSetHardware ProfileCurrent. Именно при помощи этого раздела реестра вы можете управлять возможными настройками системных драйверов для существующих аппаратных устройств. Несмотря на то, что можно указать профиль, который будет активен при следующей загрузке операционной системы, настройки HKCC будут всегда применяться для активного профиля.

HKEY_PERFORMANCE_DATA

Известно, что при обнаружении возможных проблем с аппаратной конфигурацией и всей производительностью системы в целом, рекомендуется использовать оснастку «Системный монитор» с соответствующими счетчиками производительности. В операционных системах Windows системный реестр также относится к механизму, обеспечивающему доступ ко всем значениям счетчиков производительности, используемых для мониторинга системы. Основным преимуществом в использовании счетчиков производительности средствами реестра является возможность мониторинга удаленных компьютеров без особых затрат, так как API-функции реестра позволяют получить быстрый доступ к удаленному реестру. В связи с тем, что в данном разделе хранятся не конфигурационные параметры, а только ссылки на соответствующие источники данных счетчиков производительности, доступ к разделу HKPD средствами утилиты «Редактор реестра» запрещен. Информацию из данного раздела реестра вы можете получить при помощи функции PDH (Performance Data Helper), которая предоставляется библиотекой Pdh.dll (Performance Data Helper API), компоненты которой вы можете увидеть на следующей иллюстрации:

regedit-01

 
Рис. 1. Архитектура доступа к счетчикам производительности

Значение параметров реестра Windows

Как вы уже поняли, разделы системного реестра можно назвать контейнерами, которые содержат конфигурационную информацию. Информация такого рода содержится в параметрах, которые вполне можно сравнить с файлами, расположенными в папках на диске, откуда, собственно, и заимствовано соглашение об их именовании. Соответственно, вы можете дать одинаковые названия множеству параметров, но только в том случае, если эти параметры расположены в разных разделах или подразделах. Каждый параметр реестра состоит из таких составляющих, как имя параметра, тип данных, а также самого значения. С соблюдением правильных типов данных добавляемых вами параметров нужно быть крайне внимательными и осторожными. Используйте именно тот тип данных, который указан в источнике самого твика, так как в противном случае последствия могут быть весьма существенными. Начиная с версии операционной системы Windows XP, максимальная длина имени параметра не должна превышать 16383 символов. В общей сложности насчитывается 15 типов данных, но в большинстве случаев используются только параметры типа REG_DWORD, REG_BINARY, а также REG_SZ. Все типы данных параметров реестра описаны в следующей таблице:

Название типа данных Тип параметра Описание
Двоичный параметр REG_BINARY Содержит необработанные двоичные данные произвольной длины. В виде таких двоичных данных хранится большинство сведений об аппаратных компонентах. Эти данные вы можете просматривать в двоичном или шестнадцатеричном виде при помощи редактора реестра.
Параметр DWORD REG_DWORD Включает в себя параметры, которые представлены в виде значения, длина которого составляет 4 байта, то есть 32-разрядное целое. Используется такой тип данных для хранения параметров драйверов устройств, служб, а также системных настроек, причем, в редакторе реестра его значение можно просматривать в двоичном, шестнадцатеричном или десятичном формате.
Параметр DWORD REG_DWORD_BIG_ENDIAN То же относится к параметру DWORD, где значение представляет собой 32-разрядное целое, но здесь первым является старший байт; эквивалентно REG_DWORD
Параметр DWORD REG_DWORD_LITTLE_ENDIAN Данный тип тоже относится к параметру DWORD, где значение представляет собой 32-разрядное целое, но здесь первым является младший байт; эквивалентно REG_DWORD
Расширяемая строка данных REG_BINARY Содержит необработанные двоичные данные произвольной длины. В виде таких двоичных данных хранится большинство сведений об аппаратных компонентах. Эти данные вы можете просматривать в двоичном или шестнадцатеричном виде при помощи редактора реестра.
Параметр DWORD REG_EXPAND_SZ Представляет собой Unicode-строку данных переменной длины, которая может включать переменные окружения. Эти переменные при использовании данных обрабатываются конкретной программой или службой.
Двоичный параметр REG_FULL_RESOURCE_DESCRIPTOR Также как и REG_RESOURCE_LIST является последовательностью вложенных массивов, используемых только физическими устройствами, которые расположены в разделе HardwareDescription.
Ссылка REG_LINK Символическая ссылка в кодировке Unicode, которая позволяет разделу ссылаться на другой раздел или параметр. Ссылки используют три из шести корневых раздела реестра, которые не записываются на диск, а создаются динамически при каждой загрузке операционной системы
Многострочный параметр REG_MULTI_SZ Массив многострочного текста в Unicode кодировке, содержащий списки или другие записи, которые удобны для чтения и могут разделяться запятыми, пробелами и другими символами. В этом типе данных может храниться список IP-адресов, а также другая информация.
Отсутствует REG_NONE Данные этого параметра являются нетипизированными, т.е. они не имеют определенного типа. Обычно данные такого типа записываются самой операционной системой или приложениями и в редакторе реестра они отображаются в виде двоичного параметра в шестнадцатеричном формате.
Параметр QWORD REG_QWORD Данные этого типа представляются в виде 64-разрядного целого. Параметры с этим типом данных в оснастке «Редактор реестра» отображаются в виде двоичного параметра.
Параметр QWORD REG_QWORD_BIG_ENDIAN То же относится к параметру REG_QWORD и подобно REG_DWORD_BIG_ENDIAN, значение представляет собой 64-разрядное целое, но здесь первым является старший байт; эквивалентно REG_QWORD
Параметр QWORD REG_QWORD_LITTLE_ENDIAN Подобно параметру REG_DWORD_LITTLE_ENDIAN, где значение представляет собой 64-разрядное целое, но здесь первым является старший байт; эквивалентно REG_QWORD
Двоичный параметр REG_RESOURCE_LIST Включает последовательность вложенных массивов, предназначенных для хранения описания аппаратного ресурса, используемого драйверами или управляемыми ими физическими устройствами. Данные такого типа операционная система держит в разделе ResourceMap, которые отображаются в виде двоичного параметра в шестнадцатеричном формате.
Двоичный параметр REG_RESOURCE_REQUIREMENTS_LIST Как и типы данных REG_RESOURCE_LIST и REG_FULL_RESOURCE_DESCRIPTOR включает в себя последовательность вложенных массивов, но, в отличие от вышеперечисленных типов данных, служит для хранения списка драйверов аппаратных ресурсов, которые могут быть использованы определенным драйвером устройства или управляемым им физическим устройством. Большую часть из этого списка операционная система записывает в раздел ResourceMap.
Строковый параметр REG_SZ Значением такого параметра выступает текстовая строка в кодировке Unicode фиксированной длины

Таблица 2. Типы данных параметров реестра

Также стоит отметить то, что для повышения эффективности использования системного реестра, в реестр заносится имя внешнего файла, где хранятся значения, превышающие размер в 2048 байт. Общий размер всех параметров раздела не должен превышать 64 КВ.

Продолжение следует.

Реестр Windows (Windows Registry) – это центральная база данных настроек и параметров во всех операционных системах семейства Windows (начиная с Windows 3.1). В нем хранится вся информация об аппаратных средствах, операционной системе и установленных в ней приложениях, а также пользовательские данные и настройки. По аналогии с человеческой анатомией я бы назвал реестр центральной нервной системой компьютера, ведь от настроек реестра напрямую зависит поведение системы в той или иной ситуации.


Реестр не является единым целым, а представляет из себя составную структуру, динамически формирующуюся из различных данных следующим образом:

  • Сначала, при установке ОС, создаются файлы, хранящие данные о начальной конфигурации системы.
  • Затем, в процессе загрузки и входа пользователя в систему формируется некий виртуальный объект Registry. Данные для формирования он берет частично из тех самых файлов, частично из информации, собранной при загрузке Windows.

Этот объект и является тем самым реестром, с которым взаимодействует операционная система и который видим мы.

Основные файлы, отвечающие за формирование реестра

  • system
  • software
  • sam
  • security
  • default
  • components
  • bcd-template

Хранятся они в папке %SystemRoot%\System32\Config\ (обычно это C:\Windows\System32\Config\) и в зависимости от версии ОС их состав может несколько различаться.

файлы реестра

Также файлы, отвечающие за пользовательские настройки, могут храниться в C:\Documents and Settings\%Username%\ (Ntuser.dat) и в C:\Documents and Settings\%Username%\Local Settings\Application Data\Microsoft\Windows\ (UsrClass.dat).

Еще есть резервные копии файлов реестра, созданные системой, в зависимости от ОС они хранятся в:

C:\Windows\repair — для XP и Server 2003;
C:\Windows\System32\config\RegBack — для  Windows 7 \Server 2008 и более новых.

По умолчанию операционная система делает резервные копии этих файлов раз в 10 дней с помощью планировщика задач.

Взаимодействие реестра с операционной системой

• При запуске компьютера распознаватель аппаратных средств (hardware recognizer) помещает в реестр список обнаруженных им устройств. Обычно распознавание аппаратных средств осуществляется программой Ntdetect.com и ядром операционной системы Ntoskrnl.exe

• При старте системы ядро системы  извлекает из реестра сведения о загружаемых драйверах устройств и порядке их загрузки. Кроме того, программа Ntoskrnl.exe передает в реестр информацию о себе (напр. номер версии).

• В процессе загрузки системы драйверы устройств обмениваются с реестром параметрами загрузки и конфигурационными данными. Драйвер устройства сообщает об используемых им системных ресурсах, включая аппаратные прерывания (IRQ) и каналы доступа к памяти (DMA), чтобы система могла включить эти данные в реестр. Кстати, реестр позволяет создавать несколько аппаратных профилей. Аппаратный профиль (hardware profile) представляет собой набор инструкций, с помощью которого можно указать операционной системе, драйверы каких устройств должны загружаться при запуске компьютера. По умолчанию системой создается стандартный аппаратный профиль, который содержит информацию обо всех аппаратных средствах, обнаруженных на компьютере.

• При входе пользователя в систему загружаются пользовательские профили (user profiles). Вся информация, относящаяся к конкретному имени пользователя и связанными с ним правами хранится в реестре. Пользовательский профиль определяет индивидуальные параметры настройки системы (разрешение дисплея, параметры сетевых соединений, подключенные устройства и многое другое). Информация о пользовательских профилях также хранится в реестре.

• При установке приложений. Каждый раз при запуске программы установки происходит добавление в реестр новых конфигурационных данных. Начиная свою работу, все программы установки должны считывать информацию из реестра, чтобы определить, присутствуют ли в системе необходимые им компоненты. Кроме того, системный реестр позволяет приложениям совместно использовать конфигурационную информацию, что предоставляет им больше возможностей для взаимодействия. Приложение должно активно и правильно использовать реестр, а также иметь возможность корректного удаления, не затрагивая при этом компонентов, которые могут использоваться другими программами (библиотеки, программные модули и т. п.). Эта информация тоже хранится в реестре.

• При администрировании системы. Когда пользователь вносит изменения в конфигурацию системы с помощью средств администрирования системы (напр. утилиты Панели управления или оснастки MMC), все изменения сразу отражаются в системном реестре. По сути средства администрирования представляют собой наиболее удобные и безопасные средства модификации реестра. Кстати, к средствам администрирования можно отнести и редактор реестра (regedit.exe), ведь все изменения в систему можно вносить непосредственно правкой реестра.

Структура реестра

Реестр имеет древовидную структуру и состоит из 5 основных разделов, их еще называют ветвями реестра (Registry hives):

HKEY_LOCAL_MACHINE (HKLM) — самый большой раздел реестра. В нем сосредоточены все основные настройки операционной системы, а также аппаратного и программного обеспечения компьютера. Информация, содержащаяся в этом разделе, применяется ко всем пользователям, регистрирующимся в системе.

HKEY_LOCAL_MACHINE

HKEY_ CLASSES_ ROOT (HKCR) — содержит ассоциации между приложениями и типами файлов (по расширениям файлов). Кроме того, в этом разделе находится информация о зарегистрированных типах файлов и объектах COM и ActiveX. Кроме HKEY_ CLASSES_ ROOT эти сведения хранятся также в разделах HKEY_LOCAL_MACHINE и HKEY_CURRENT_USER. Раздел HKEY_LOCAL_MACHINE\Software\Classes содержит параметры по умолчанию, которые относятся ко всем пользователям локального компьютера. Параметры, содержащиеся в разделе HKEY_CURRENT_USER\Software\Classes, переопределяют принятые по умолчанию и относятся только к текущему пользователю. Раздел HKEY_CLASSES_ROOT включает в себя данные из обоих источников.

HKEY_ CLASSES_ ROOT

HKEY_USERS( HKU) — содержит настройки среды для каждого из загруженных пользовательских профилей, а также для профиля по умолчанию. В HKEY_USERS находится вложенный раздел \Default, а также другие подразделы, определяемые идентификатором безопасности (Security ID, SID) каждого пользователя

HKEY_ USERS

HKEY_CURRENT USER (HKCU) — cодержит настройки среды для пользователя, на данный момент зарегистрировавшегося в системе (переменные окружения, настройки рабочего стола, параметры сети, приложений и подключенных устройств).
Этот раздел дублирует информацию в HKEY_USERS\user SID, где user SID — идентификатор безопасности пользователя, зарегистрировавшегося в системе на текущий момент (узнать SID текущего пользователя можно, набрав в командной строке whoami /user) .

HKEY_CURRENT_USER

HKEY_CURRENT_ CONFIG (HKCC) — cодержит настройки для текущего аппаратного профиля. Текущий аппаратный профиль включает в себя наборы изменений, внесенных в стандартную конфигурацию устройств, заданную в подразделах Software и System корневого раздела HKEY LOCAL_MACHINE. В HKEY_CURRENT_CONFIG отражаются только изменения. Кроме того, информация этого раздела находится в HKEY_LOCAL_MACHINE\System \CurrentControlSet\HardwareProfiles\Current

HKEY_CURRENT_ CONFIG

Данные в реестре хранятся в виде параметров, расположенных в ключах реестра. Каждый параметр характеризуется именем, типом данных и значением.

Основные типы данных, применяемые в реестре

REG_DWORD —  32-х разрядное число. Этот тип данных используют многие параметры драйверов устройств и сервисов. Редакторы реестра могут отображать эти данные в двоичном, шестнадцатеричном и десятичном формате

REG_SZ — Текстовая строка в формате, удобном для восприятия человеком. Значениям, представляющим собой описания компонентов, обычно присваивается именно этот тип данных

REG_EXPAND_SZ — Расширяемая строка данных. Эта строка представляет собой текст, содержащий переменную, которая может быть заменена при вызове со стороны приложения, например, используется для записи переменных окружения

REGJMULTI_SZ — Многострочное поле. Значения, которые фактически представляют собой списки текстовых строк в формате, удобном для восприятия человеком, обычно имеют этот тип данных. Строки разделены символом NULL

REG_BINARY — Двоичные данные. Большинство аппаратных компонентов используют информацию, которая хранится в виде двоичных данных. Редакторы реестра отображают эту информацию в шестнадцатеричном формате

REG_BINARY

REG_RESOURCE_LIST — Список аппаратных ресурсов. Применяется только в ветви HKEY_LOCAL_MACHINE\HARDWARE

Также иногда можно встретить такие типы данных реестра:

REG_RESOUECE_ REQUIREMENTS_LIST — Список необходимых аппаратных ресурсов. Применяется только в ветви HKEY_LOCAL_MACHINE\HARDWARE

REG_FULL_RESOURCE_ DESCRIPTOR — Дескриптор (описатель) аппаратного ресурса. Применяется только в ветви HKEY_LOCAL_MACHINE\HARDWARE

REG_LINK — Символическая ссылка Unicode. Этот тип данных интересен тем, что позволяет одному элементу реестра ссылаться на другой ключ или параметр.

REG_QWORD — 64-х разрядное число.

REG_DWORD_ LITTLE_ENDIAN — 32-разрядное число в формате «остроконечников» (little-endian), эквивалент REG_DWORD

REG_DWORD_BIG_ ENDIAN — 32-разрядное число в формате «тупоконечников» (big-endian)

REG_QWORD_LITTLE_ ENDIAN — 64-разрядное число в формате «остроконечников». Эквивалент REG_QWORD

REG_NONE — Параметр не имеет определенного типа данных

ConstantDescription

REG_BINARY
Binary data. Stored as binary and displayed in RegEdit in hexadecimal format. Pass a hex value to REG /ADD
REG_DWORD
32-bit number. Pass a decimal number to REG /ADD
REG_QWORD
64-bit number. Pass a decimal number to REG /ADD
REG_DWORD_LITTLE_ENDIAN
32-bit number in little-endian format. This is equivalent to REG_DWORD.
In little-endian format, a multibyte value is stored in memory from the lowest byte (the «little end») to the highest byte.
For example, the value 0x12345678 is stored as (0x78 0x56 0x34 0x12) in little-endian format.
REG_QWORD_LITTLE_ENDIAN
A 64-bit number in little-endian format. This is equivalent to REG_QWORD.
REG_DWORD_BIG_ENDIAN
32-bit number in big-endian format.
In big-endian format, a multibyte value is stored in memory from the highest byte (the «big end») to the lowest byte.
For example, the value 0x12345678 is stored as (0x12 0x34 0x56 0x78) in big-endian format.
REG_EXPAND_SZ
Null-terminated string that contains unexpanded references to environment variables (for example, «%PATH%»).
It will be a Unicode or ANSI string, depending on whether you use the Unicode or ANSI functions.
REG_LINK
Unicode symbolic link.
REG_MULTI_SZ
Array of null-terminated strings that are terminated by two null characters.
REG_NONE
No defined value type. Will be displayed in RegEdit as a Binary value in Hex format.
REG_FULL_RESOURCE_DESCRIPTOR
A series of nested arrays that is designed to store a resource list that is used by a physical hardware device. This data is detected and written in the \HardwareDescription tree by the system and is displayed in Registry Editor in hexadecimal format as a Binary Value.

REG_RESOURCE_LIST
Device-driver resource list.

REG_RESOURCE_REQUIREMENTS
Binary data. Stored as binary and displayed in RegEdit in hexadecimal format. Pass a hex value to REG /ADD

REG_RESOURCE_REQUIREMENTS_LIST
Binary data. Stored as binary and displayed in RegEdit in hexadecimal format. Pass a hex value to REG /ADD

REG_SZ
Null-terminated string. The default Data Type.
This will be a Unicode or ANSI string, depending on whether you use the Unicode or ANSI functions.

“Have a place for everything and keep the thing somewhere else; this is not advice, it is merely custom” ~ Mark Twain

SETX — Set environment variables permanently, can also read a registry key and write the value to a text file.
REG — Read, Set, Export & Delete registry keys and values.
REGEDIT — Load Registry settings from a .REG file.
PowerShell: Set-ItemProperty

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как изменить разрешение экрана в windows 10 на нетбуке
  • Эмуляторы sony playstation 2 ps2 для windows
  • Lan drivers windows 7 packard bell
  • Учетные данные введены неверно или отсутствует связь с сервером выполняющим аутентификацию windows 7
  • По vipnet client for windows 4 х кс2 срок использования