«Single bit is such an amount of information that twice diminishes the uncertainty». I have delivered the definition of one bit from the information theory, because the talk in the article will be about the ways of logical values storage in the Windows system registry. |
«Один бит - это количество информации, которое уменьшает неопределенность вдвое». Я привел определение одного "бита" из теории информации, потому что речь в статье пойдет о способах хранения логических значений в системном реестре Windows. |
It looks like that the Boolean or logical values, for which storage one bit is enough, taking two values: «false» or «true» and are well-known to any programs developers, became for Microsoft one more way to manifest at minimum either peculiarity or to create good ground for the future bugs, service packs or incompatibility. |
Булевы или логические значения, для хранения которых достаточно одного бита, принимающие два значения «ложь» или «истина» и хорошо знакомые любому программисту, для Microsoft стали, похоже, еще одним способом проявить как минимум то ли странность, то ли снова создать хорошую почву для будущих багов, пакетов обновлений и несовместимости. |
While developing the system programs for the administering of various Windows 32-bit versions, I had to encounter the different Microsoft approaches to the storage of logical values. The fact is that the majority of the system policies and settings are represented with to Boolean values: «Yes» or «No». Besides this, it is necessary here to note, that again, in the majority of cases, the missing of value or the «value by default» (soon of all there will be the value in the system registry or its absence) is taken for «false». This article is an attempt to systemise nine, discovered by me, ways by which Windows stores the logical values in the system registry. By the way, this knowledge can be easily extrapolated for the obsolete initialisation files. |
При разработке системного программного обеспечения для администрирования различных версий 32-битных Windows мне пришлось столкнуться с различным подходом Microsoft к хранению логических значений. Дело в том, что подавляющее большинство системных политик и настроек Windows сводится к булевым значениям: «Да» или «Нет». Кроме того, здесь необходимо сразу отметить, что опять же, в подавляющем большинстве случаев, отсутствие величины или «значение по умолчанию» (скорее всего это будет параметр в системном реестре или его отсутствие) принимается за «ложь». Данная статья - это попытка систематизации девяти, обнаруженных мною, способов, с помощью которых Windows хранит логические значения в системном реестре. К слову, эти сведения могут быть легко экстраполированы и на устаревшие файлы инициализации (.ini). |
Binary values |
Бинарные параметры |
The logical values are stored in the system registry by two ways. |
Логические значения в параметрах бинарного типа хранятся двояко. |
1. The pair of values «01 00 00 00» (true), «00 00 00 00» (false) is mostly encountered. The values of system policies in early Windows version 95, 98 are stored in such a way. The transition was made to the storage Boolean values in values of integer DWORD type in version ME, NT, 2000 or XP. |
1. Пара значений «01 00 00 00» (истина), «00 00 00 00» (ложь), встречается наиболее часто. Таким способом хранятся значения системных политик в ранних версиях Windows 95, 98. В версиях ME, NT, 2000 или XP произошел переход на хранение булевых значений в параметрах целочисленного типа DWORD. |
I give an example of system policy behaving in such a manner: «Clear history of recently opened documents on exit». While enabled, this policy forces the automatic clear the following histories: the list of recent documents in «Documents» menu, the search list and the list of «Run» dialog box, available on «Start» menu, as well as the list of network addresses typed in the Internet Explorer address bar, when the Windows session or current user session finishes. The value «ClearRecentDocsOnExit» storing the state of this policy has the binary type in Windows 95/98 with the pair of values: «01 00 00 00», «00 00 00 00», and the integer type in other versions. It is stored in the registry branch «Software\Microsoft\Windows\CurrentVersion \Policies\Explorer» both in HKEY_CURRENT_USER hive and HKEY_LOCAL_MACHINE hive and can have the range either the entire «Computer» (Local Machine), or the «Current user» correspondingly. |
Приведу пример системной политики ведущей себя подобным образом: «Очистка истории последних открытых документов при завершении». Будучи задействованной, эта политика приводит к автоматической очистке при завершении сеанса Windows или сеанса текущего пользователя следующих историй: списка последних открытых документов в меню «Документы», списка меню поиска и списка команд диалога «Выполнить», доступных из меню «Пуск», а также списка сетевых адресов набранных в адресной строке Internet Explorer. Параметр «ClearRecentDocsOnExit», хранящий состояние этой политики имеет бинарный тип в Windows 95/98 с парой значений «01 00 00 00», «00 00 00 00» и целочисленный тип в других версиях. Хранится он в ветви реестра «Software\Microsoft\Windows\CurrentVersion \Policies\Explorer» как в разделе HKEY_CURRENT_USER, так и в разделе HKEY_LOCAL_MACHINE и может иметь область действия либо на весь «Компьютер» (Local Machine), либо на «Текущего пользователя» (Current User) соответственно. |
2. The following, rarer pair of binary values, representing the «true» and «false» is «01» and «00». Such a pair is used to store system settings. Such a pair of values is used for the storage of system setting in Windows 9.x, standing for the item «Suspend» display on «Start» menu, which switches the computer to the energy saving mode. The «APMMenuSuspend» value is located in the «Enum\Root\*PNP0C05\0000» of LOCAL_MACHINE system registry hive. The manual modification of this value has the sense, when the switching to energy saving mode is erratic. |
2. Следующая, более редкая пара бинарных значений представляющая «истину» или «ложь» - это «01» и «00». Такая пара используется для хранения системных настроек. Такая пара бинарных значений используется для хранения состояния системной настройки в Windows 9.x, отвечающий за отображение в меню «Пуск» пункта «Остановить», который переводит компьютер в режим с пониженным питанием. Параметр «APMMenuSuspend» находится в ветке «Enum\Root\*PNP0C05\0000» раздела LOCAL_MACHINE системного реестра. Редактировать этот бинарный параметр вручную имеет смысл, когда переход в режим с пониженным питанием дает сбои. |
Integer DWORD values |
Целочисленные параметры DWORD |
Here I discovered three methods of Boolean values storage. |
Здесь мною обнаружено три метода хранения булевых величин. |
3. The most frequently met pair is «1» and «0», meaning the «true» and «false» correspondingly. This method is used to store the system policies of Windows in the overwhelming majority of cases. It is necessary to note here, that the way of representation for the most of system policies in Windows 95, 98 suffers the transformation from the storage of values of binary type «01 00 00 00» and «00 00 00 00» to the storage of the values of integer type «1» and «0» for the same policies in Windows Windows Me, 2000 и XP. The obvious attempt by Microsoft to unify the storage of the system policy states is tracked down. |
3. Наиболее часто встречается пара «1» и «0», означающие «истина» и «ложь» соответственно. Этот способ используется для хранения системных политик Windows в подавляющем большинстве случаев. Здесь же необходимо отметить, что способ представления большинства системных политик в Windows 95, 98 претерпевает изменение от хранения бинарных значений типа «01 00 00 00» или «00 00 00 00» к хранению целочисленных значений типа «1» или «0» для тех же самых политик в Windows Me, 2000 и XP. Явно прослеживается попытка Microsoft унифицировать хранение состояния системных политик. |
For an instance, I bring the system policy, which, when enabled, blocks the context menu of «Windows Explorer» and «Desktop». The integer value «NoViewContextMenu», stored in the «Software\Microsoft\Windows\CurrentVersion \Policies\Explorer» branch, responds for the state of this policy. The value can be located either in HKEY_CURRENT_USER hive or HKEY_LOCAL_MACHINE hive and have the range either of «Local Machine» or «Current User». |
Для примера приведу системную политику, при активизации которой у «Проводника» и у «Рабочего стола» блокируется контекстное меню. Целочисленный параметр «NoViewContextMenu» хранящийся в ветви «Software\Microsoft\Windows\CurrentVersion \Policies\Explorer« отвечает за состояние этой политики. Параметр может находиться в реестре или в разделе HKEY_CURRENT_USER, или в разделе HKEY_LOCAL_MACHINE и иметь область действия либо всего «Компьютера» (Local Machine), либо «Текущего пользователя» (Current User). |
When the policies, stored in different system registry hives, are conflicted, the policy with the range of «Computer» and stored in HKEY_LOCAL_MACHINE hive, has a priority over the policy, stored in HKEY_CURRENT_USER hive and with the range of «Current User». |
При конфликте политик, хранящихся в разных разделах реестра, политика имеющая область действия весь «Компьютер», и хранящаяся в разделе HKEY_LOCAL_MACHINE имеет приоритет над, политикой хранящейся в разделе HKEY_CURRENT_USER и имеющей область действия «Текущего пользователя». |
4. Another pair of integer values representing the logical values is «2», denoting «true», and «0», denoting «false», correspondingly. Such, rather strange, at the first look; the representation of Boolean values is used most often to the store the policies related to the Microsoft Internet applications such as Internet Explorer and Outlook Express. Really, there is a little part of the system policies having three states, and three values, used for the representation: "0", "1" and "2". But these are not Boolean values and are out of this article topic. |
4. Другая пара целочисленных значений представляющих логические значения - это «2», означающее «истина» и «0», означающее «ложь» соответственно. Подобное, довольно странное на первый взгляд, представление булевых величин чаще всего используется для хранения политик, относящихся к Microsoft интернет-приложениям, таким как Internet Explorer и Outlook Express. На самом деле есть небольшая часть политик имеющих три состояния, и три величины, используемые для представления: "0", "1" и "2". Но это уже не является булевыми значениями и выходит за рамки рассмотрения данной статьи. |
The policy, removing the MSN Messenger from the interface of Outlook Express, can serve as an example of policy, using such a type of logical value representation. The value of DWORD type «Hide Messenger», which can be present in «SOFTWARE\Microsoft\Outlook Express» branch of HKEY_LOCAL_MACHINE hive, taking the value of «2», removes the MSN Messenger functionality from the mail client Outlook Express. |
Примером политики использующей такой тип представления логического состояния может послужить политика, убирающая MSN Messenger из интерфейса Outlook Express. Параметр типа DWORD «Hide Messenger», который может присутствовать в ветви «SOFTWARE\Microsoft\Outlook Express» раздела HKEY_LOCAL_MACHINE, принимая значение «2», убирает функциональность MSN Messenger из почтового клиента Outlook Express. |
5. The following way, how it could seem, is the most logical and economical, is used by Microsoft rather rare. To keep the settings the single bit (binary digit unity), stored in integer value. Two values: «set on», i.e. equals to «1», or «set off», in other words, equals to «0», are taken for «true» and «false». This is rarely encountered for the storage of settings in Microsoft Office. I found the explanation to this, that to check or manipulate the binary values, having bit representation, is more complex in program realisation. |
5. Следующий способ, казалось бы, наиболее логичный и экономный используется Microsoft достаточно редко. Для хранения настроек можно использовать один бит (двоичную единицу) хранящуюся в целочисленном параметре. Два значения бита: «выставлен», т.е. равен «1», или «не выставлен», другими словами, равен «0», принимаются за «истину» и «ложь». Такое редко встречается для хранения настроек в Microsoft Office. Я нахожу этому объяснение в том, что проверка и манипулирование двоичными значениями, имеющими битовое представление сложнее в программной реализации. |
As an illustration I give the «Options6» value, the third bit of which stands for the displaying the warning on macros launch in Microsoft Excel. It is stored in the «Software\Microsoft\Office\8.0\Excel\Microsoft Excel» branch of HKEY_CURRENT_USER hive. Excel from Office 2000 or XP stores this setting in the similar branch, where the digits «8.0» are replaced for «9.0» or «10.0» correspondingly. |
В качестве иллюстрации приведу параметр «Options6», третий бит которого отвечает за выдачу предупреждения в Microsoft Excel о запуске макроса. Хранится он в ветви «Software\Microsoft\Office\8.0\Excel\Microsoft Excel» раздела HKEY_CURRENT_USER. Excel из Microsoft Office 2000 или XP, хранит эту настройку в похожей ветви, где цифры «8.0» заменятся на «9.0» или «10.0» соответственно. |
String values |
Строковые параметры |
The abundance of ways to store the logical variables in the values of string type leads to the thought that, here the fantasy of Microsoft programmers was on the loose. |
Обилие способов применяемых для хранения логических величин в параметрах строкового типа наводит на мысль о том, что здесь фантазия программистов Microsoft разгулялась окончательно. |
6. The first, rather spread pair is «Yes», «No», responding for the «true» and «false». The most often this way is used yo store the setting in Internet and Windows Explorer. This pair of values is written in different ways: either with capital letters, or letters in lower case, or simply with first capital letter. The state of case is crucial for the several settings in Internet Explorer, where all the values are written only in lower case - «yes», «no». In other cases Windows processes these values in any form. |
6. Первая, достаточно распространенная пара - это «Yes», «No» отвечающая за «истину» и «ложь». Чаще всего этот способ используется для хранения настроек Internet и Windows Explorer. Эта пара значений записывается по-разному: и большими, и маленькими буквами, и просто с большой буквы. Состояние регистра принципиально для нескольких установок Internet Explorer, где все значения пишутся только малыми буквами - «yes», «no». В остальных случаях Windows отрабатывает эти значения в любом виде. |
The string value «BrowseNewProcess» stored in «Software\Microsoft\Windows\CurrentVersion \Explorer\BrowseNewProcess» of HKEY_CURRENT_USER hive can serve as an example of this. This setting determines whether the new process is created for each launched Windows Explorer or Internet Explorer instances. The activation of this system setting allows increasing the Windows stability but can diminish a little the performance rate. |
Примером этого может послужить строковый параметр «BrowseNewProcess» хранящийся в «Software\Microsoft\Windows\CurrentVersion \Explorer\BrowseNewProcess» раздела HKEY_CURRENT_USER. Эта установка определяет, создается ли новый процесс для каждой запущенной копии Windows Explorer (Проводника) или Internet Explorer. Активизация этой системной настройки повысит стабильность Windows, но может снизить немного производительность. |
7. The second rare pair of string values, very similar for the first one, is «Y», «N», signifying the «true» and «false», is used to store the Windows system settings. |
7. Вторая редкая пара строковых значений, очень похожая на первую, это «Y», «N» обозначающие «истину» и «ложь» используется для хранения системных настроек Windows. |
The system setting allowing the distributed COM-objects launch and connection to them the remote clients can serve as an illustration for this method. This value «EnableDCOM» is stored in «Software\Microsoft\OLE» of HKEY_LOCAL_MACHINE hive. Here I note that the access to write and free manipulation of this setting state is recommended only for administrators of systems. |
Иллюстрацией этого метода хранения логических значений может послужить системная настройка, разрешающая запуск распределенных COM-объектов и подключение к ним удаленных клиентов. Этот параметр «EnableDCOM» хранится в «Software\Microsoft\OLE» раздела HKEY_LOCAL_MACHINE. Здесь же отмечу, что доступ на запись и свободная манипуляция состоянием этой настройки рекомендовано только администраторам систем. |
8. It is evident that, to say openly: «yes or no» is as foreign to Microsoft as to diplomats. Because there is another way to store this state in the system registry - «TRUE» и «FALSE». It is necessary to note, that in particular cases the case has the importance, in other words, the value «true», written in lower case, is taken for «false». This method is encountered in the storage of the network settings of Windows. |
8. Видимо, сказать просто: «да или нет» для Microsoft столь же не свойственно, как и дипломатам. Поэтому есть еще один способ хранить это состояние в системном реестре - «TRUE» и «FALSE». Необходимо отметить, что в отдельных случаях регистр имеет значение, другими словами, значение «true», записанное в нижнем регистре принимается за «ложь». Этот способ встречается для хранения настроек сетевых настроек Windows. |
There is the system policy for Windows NT, 2000 and XP, which is responsible for the displaying of the message about unsuccessful connection to the domain controller, keeping the «roaming users' profiles». The content of the value «ReportControllerMissing», being worked through while registration in the system, which is stored in «SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon» branch of HKEY_LOCAL_MACHINE, is case sensitive. |
Для Windows NT, 2000 и XP есть системная политика, которая отвечает за выдачу сообщения о несостоявшемся подключении к контроллеру домена, хранящему «блуждающие профили пользователей». Значение параметра, отрабатывающегося при регистрации в системе, «ReportControllerMissing», которое хранится в ветви «SOFTWARE\Microsoft\Windows NT\CurrentVersion \Winlogon» в HKEY_LOCAL_MACHINE чувствительно к регистру. |
9. Like for the integer values, the pair of «1» and «0», responding for the «true» and «false», is encountered. It is remarkable that, there are many policies in Windows NT, for the states of which the values «1» or «0», but can have either string or integer type. Such a situation is extra rare in Windows 2000, and for the system policies inherited from Windows NT. This Boolean values representation for the storage of system settings and policies is used in Microsoft Office, the most often for the network settings, memory management and installation of applications. |
9. Как и для целочисленных параметров встречается и пара «1» и «0», отвечающие за «истину» и «ложь». Примечательно, что в Windows NT есть много политик, за состояние которых отвечают значения «1» или «0», но которые могут иметь и строковый, и целочисленный тип. В Windows 2000 такое встречается крайне редко и то для системных политик унаследованных от Windows NT. Это представление булевых величин для хранения состояний системных настроек и политик применяется в Microsoft Office, наиболее часто для сетевых настроек, управления памятью и инсталляцией приложений. |
As an instance, I give the system policy, compulsorily finishing the 16-bit processes, working in the Virtual DOS Machine, while ending Windows session. This closes the hung applications but can be the reason of data lost. The string value «AutoEndTasks», accepting «1» or «0» and responsible for the state of this policy, is stored in branch «Control Panel\Desktop» of HKEY_CURRENT_USER system registry hive. |
Как пример приведу системную политику, принудительно завершающую 16-битные процессы, работающие в виртуальной машине DOS (Virtual DOS Machine), при завершении сеанса Windows. Это снимает зависшие приложения, ускоряет закрытие Windows, но может послужить причиной потери данных. Строковый параметр «AutoEndTasks», принимающий значения «1» или «0» и отвечающий за состояние этой политики, хранится в ветви «Control Panel\Desktop» раздела HKEY_CURRENT_USER системного реестра. |
Valient Newman |