SlideShare a Scribd company logo
Windows Kernel Internals
NT Registry Implementation
     David B. Probert, Ph.D.
  Windows Kernel Development
      Microsoft Corporation

          © Microsoft Corporation   1
Outline
•   High level overview
•   System whereabouts
•   Native registry APIs
•   Implementation Details
•   I/O
•   Mounting a Hive
•   Life Span
•   Backup/Restore
•   Limits

                    © Microsoft Corporation   2
High Level Overview
• Logical:
  – Registry = “a FS within a file”
  – Keys       directories
  – Values       files


• Physical:
  –   Registry = collection of Hives
  –   Hive = collection of Bins
  –   Bin = collection of Cells
  –   Cell = unit of allocation (contains raw data)


                            © Microsoft Corporation   3
Whereabouts
                                ADVAPI32.DLL                           svchost.exe


                                      Win32 Registry APIs               regsvc.dll

                                                 NT APIs
                                                                                      User
                                                                                      KERNEL
    MM             Volatile Storage
Memory Manager
                                         CM (registry)
                                                                               .LOG file
         PRIMARY file
                                                                      (NO_INTERMEDIATE_BUFFERING)
   (CC PRIVATE_WRITE streams)



                       CC                                            NTFS/FAT
                  Cache Manager




                                           © Microsoft Corporation
                                                                       Disk                  4
NT Registry APIs: Key Ops
NtCreateKey        (kname)             open a new or existing key

NtDeleteKey        (khandle)           mark key to delete at last handle close
NtEnumerateKey      (khandle, i)       return the name/info of subkey[i] of key

NtQueryKey         (khandle)           get info about a key

NtSetInformationKey                    set info on key
                  (khandle, info)
NtRenameKey     (khandle, string)      change the name of key
NtFlushKey       (khandle)             flush changes associated with key to disk
NtNotifyChangeKey                      notify caller of changes to a key/subtree
             (khandle, bsubtree)
NtNotifyChangeMultipleKeys             Multi-key version of NtNotifyChangeKey
            (knames[], bsubtree)

                               © Microsoft Corporation                             5
NT Registry APIs: Value Ops
NtEnumerateValueKey (khandle, i)        return the name/info of value[i] of key

NtQueryValueKey (khandle, vname)        get value (data & type)

NtQueryMultipleValueKey                 get multiple values
                (khandle, vnames[])

NtSetValueKey                           set a value
            (khandle, vname, value)
NtDeleteValueKey (khandle, vname)       delete a value belonging to a key


                            Misc Ops
NtQueryOpenSubKeys (kpath)              get count of open khandles under kpath

NtCompactKeys (count, khandles[])      optimize access to khandles[]

                           © Microsoft Corporation                                6
NT Registry APIs: Hive Ops
NtSaveKey     (khandle, fhandle)         write the subtree at key khandle to file
                                        via fhandle
NtRestoreKey                            copy a subtree or complete hive at key
           (khandle, hivefilename)
NtLoadKey (khandle, hivefilename)       mount a subtree or complete hive at key

NtUnloadKey (kname)                      remove a subtree or hive loaded or
                                        restored at key kname
NtReplaceKey                            prepare to replace hive at next reboot
       (newfile, roothandle, oldfile)
NtCompressKey        (roothandle)       compress hive (inplace SaveKey)




                              © Microsoft Corporation                               7
Implementation Details
• A Hive is a file (two if you also count the .LOG)
   – PRIMARY – holds the actual hive data
   – .LOG – used only when flushing (crash recovery)
• Two storage mappings:
   – Stable – maps to the backing file
   – Volatile – in paged pool, lost after reboot
• PRIMARY grows in 256K increments – to avoid
  fragmentation
• First page (4k) is the header
• Followed by chained Bins
• I/O to primary is cached, PRIVATE_WRITE stream (no
  CC Lazy Flush, no MPW)
                           © Microsoft Corporation     8
Hive Layout
                                                         Signature (‘regf’)
                                                       Sequence1 (ULONG)
                                                       Sequence2 (ULONG)
             HIVE HEADER (HBASE_BLOCK)                     TimeStamp
                      Size is 4K                         Major (ULONG)
                                                         Minor (ULONG)
                                                             ……other……..
                        Bin 0
                                                      RootCell (HCELL_INDEX)
                 size is multiple of 4K                   Length (ULONG)
                  ( x86 PAGE_SIZE)                     …reserved up to 1k -4 bytes…..
PRIMARY
                         Bin 1
Hive File:                                              CheckSum (ULONG)


                                                          …reserved up to 4K…..


                    …………..
                         Bin N




                            © Microsoft Corporation                                     9
Bin
•   Collection of cells
•   Size is increment of 4K
•   Unit of hive growth
•   0x20 bytes header followed by raw cells
                                                      Signature (‘hbin’)
                                                      FileOffset (ULONG)
                          Bin Header                    Size (ULONG)
                            (HBIN)                   Reserved (ULONG[2])
                                                         TimeStamp
                                                       Spare (ULONG)

            Bin:         raw cell data




                           © Microsoft Corporation                         10
Reading Stable Storage
• PRIMARY file is CC PRIVATE_WRITE stream
   – no CC Lazy Flush, no MM MPW, no read ahead
   – complete control over when data hits the disk
• Map/fault in 16K views of the hive in the system cache
  address space (CcMapData)
   – Views cannot cross 256K boundary
• Max 256 views per hive, then reuse the oldest unused
  view (LRU)
   – Regardless of hive size, we only commit 4 megs of address
     space / hive (XP/.NET)    no RSL
• PRIMARY is loaded as Stable storage, Volatile storage
  is allocated from paged pool
• Dirtied data is pinned (CcPinMappedData) in physical
  memory up to the first hive flush
                         © Microsoft Corporation                 11
Cell
 •   Unit of storage allocation within the hive
 •   Size rounded at 8 bytes boundary
 •   Referenced as a ‘cell index’ (HCELL_INDEX)
         – Cell index is offset within the file (minus 0x1000 – the header) – ULONG
         – Volatile cell indexes have first MSB set (i.e. 0x8xxxxxxx)
 •   Free Display bitmap keeps track of free cells with the same size
         –    Up to 128 bytes exact match
         –    128 bytes up to 2048 bytes, rounded at power of 2
         –    2048 OR higher in the same list
         –    Free cells in the same ‘size class’ linked together
 •   Always reuse free cells if one with the same size (or bigger) exists
         – If size is bigger than what we need, split & reenlist remaining
 •   Every time a cell is dirtied the whole page is marked dirty (in the Dirty Vector)


Cell :       Size (LONG)                         raw data


             positive = free cell                                       When cell is free, first ULONG
             negative = allocated cell (actual size is – Size)         points to the next free cells in the
                                                                                same size class
                                             © Microsoft Corporation                                          12
Example – value lookup “foo”
            Key                    Value List                  Value
              Size                       Size                      Size
                                   Val1 (cell index)               Type
            ……                     Val2 (cell index)               ….
                                                               Data Length
                                           ….
        ValueCount = N                                     Data Cell (cell index)
      ValueList (cell index)      Val K (cell index)
                                                                  FOO
                                           ….
             ……                                                                     Data
                                                                                     Size
                                  Val N (cell index)
                                                                           Whatever data was set
                                                                               on this value

•   Raw cells are used to build up logical data
     – Keys, values, security descriptors, indexes etc all are made up of cells
     – Fetching in a key, might involve several faults spread across the hive file
              Caching (Win2K) + locality enforcement (XP/.NET) to help with performance

                                 © Microsoft Corporation                                     13
Dirty Data
    •    When a cell is dirtied:                                Hive (Stable Storage)
          –   Containing view is pinned in memory
          –   Entire page is marked dirty
          –   Reserve space in the .LOG                                 Header
    •    Bitmap with dirty data at (x86) page level
    •    Used for flushing
                                                           Bin 0 (size = PAGE_SIZE) DIRTY
    •    Header is always flushed

                                                           Bin 1 (size = PAGE_SIZE) CLEAN
One bit per page        1
                        0
                                                                       ……..

  Dirty Vector
                        1
                                                                        DIRTY                 Bin K
                        0

(RTL_BITMAP)                                                                                 (size = 2 *
                                                                        CLEAN               PAGE_SIZE)

                                                                        ……..
                        1

                                                                 Bin N (last bin) DIRTY
                                          © Microsoft Corporation                              14
.LOG
  •     .LOG file used only while flushing
          –      In the event of a crash during flushing
          –      Reset after successful flush                                   Log header
  •     Physical log
                                                                                  Signature
          –      Logs raw dirty pages
          –      Unaware of high level data types (keys, values                  Sequence1
                 etc)                                                            Sequence2
  •     Same name as the hive file (+ .LOG                                        Signature         first 1K from
                                                                                                   the PRIMARY
        extension)                                                                   ..........         header
                                      .LOG file
                                                                              same as the header
                                     Log header                                for the PRIMARY
                                                                                     ………

I/O: no buffering
                              Dirty Vector (variable size)                       CheckSum

                               padding to sector alignment                      Dirty Vector
                                                                              Signature (‘DIRT’)
                                      dirty page


                                      dirty page
                                                                                 Dirty bitmap
 Full pages
 of dirty data                        dirty page


                                       …….
                                                    © Microsoft Corporation                             15
Hive Flush
•   The most expensive operation (by far)
•   Triggered from outside – NtFlushKey/RegFlushKey
•   … or from inside - Lazy Flush
     – Fires off 5 seconds after the write occurs
       (SetValue/DeleteValue/CreateKey/DeleteKey etc).
     – Walks the list of the hives loaded in the system and flushes every one that has
       dirty data
     – Ignores hives marked as NO_LAZY_FLUSH
•   Others may read during flush, no write allowed
•   All dirty data in the hive is written out
•   All or none makes it to the backing file
•   It is only after the flush that data is persisted to disk
     – i.e. If you:
          • CreateKey + SetValue
          • machine crashes (before lazy flush has a chance to flush the hive)
          •   the key/value is lost
•   Automatic flush at hive unload


                                     © Microsoft Corporation                             16
Hive Flush – algorithm
1.Write the LOG
2.Flush the LOG
                                                             Past this point all dirty data
                                                                is in the log (on disk)

3.Header.Sequence1++; compute checksum
4.Write the Header to PRIMARY
5.Flush the PRIMARY
                                                  Crash past this point Sequence1 != Sequence2
                                                  so we know the PRIMARY image has partial data
                           CcSetDirtyPinnedData
6.Write all dirty pages       CcUnpinData
7.Flush the PRIMARY          CcFlushCache
8.Header.Sequence2++; compute checksum
9.Write the Header to PRIMARY
10.Flush the PRIMARY
                                                          PRIMARY image is valid (on disk).

11.Reset LOG


                                © Microsoft Corporation                                       17
Loading (Mounting) a Hive
• When:
  – At boot: boot loader (NTLDR) & kernel
    (ntoskrnl.exe)
  – Explicitly, by calling NtLoadKey/RegLoadKey
    • Requires Restore privilege
  – File are opened in exclusive mode; and kept
    open by the kernel



                   © Microsoft Corporation        18
Loading (Mounting) a Hive
• How:
  – Read PRIMARY header; check it’s validity (checksum,
    signature etc)
  – If sequence numbers don’t match:
     • Hive has partial data, apply .LOG on top of PRIMARY
  – Build internal mappings as needed (Bins to Views)
  – Physical integrity check:
     • Walk the whole hive, check every single cell
  – Logical integrity check:
     • Walk the tree, check every key/value etc.

                       © Microsoft Corporation               19
Hives On a Typical (Clean) System

• Machine hives            %windir%¥system32¥config¥*
  –   SYSTEM – mounted at HKLM¥System
  –   SOFTWARE – mounted at HKLM¥Software
  –   SAM – mounted at HKLM¥SAM
  –   SECURITY – mounted at HKLM¥Security
  –   .DEFAULT – used when a new account is created
       • Failure to load any of these       OS will not boot




                          © Microsoft Corporation              20
Hives On a Typical (Clean) System
• User hives        two per each user account
   – NTUSER.DAT – roams (if roaming profile enabled)
       • Mounted under HKEY_USERS¥<SID>
       • Mounted under HKEY_USERS¥<SID>_Classes
   – UsrClass.DAT – local (does not roam) – per user registration data
   – Stored in %USERPROFILE% folder.
   – Loaded at logon, or whenever the user is impersonated
• ‘Special’ user hives
   – Two per account as above; always loaded
       • S-1-5-18   SYSTEM account
       • S-1-5-19   Local Service
       • S-1-5-20   Network Service
• Clusters – one additional hive: CLUSTER (cluster db)
   –    %windir%¥Cluster¥Cluster
• Any user/app with Restore privilege can mount own hive
                         © Microsoft Corporation                   21
Life Span
                   Power On
                               -loads ntoskrnl.exe and hal.dll
                               -loads SYSTEM hive in memory
Boot Loader
                               -uses info in the hive to load ‘load at boot’ drivers
 (NTLDR)                       -starts the executive and passes in memory copy of the
                               system hive (LoaderParameterBlock)
                               Phase1Initialization
  KERNEL
                               -Init MM
(ntoskrnl.exe)
                               -Init CM (CmInitSystem1): gets memory copy of the
                                   SYSTEM hive from LoaderBlock and mounts it in PagedPool
system process
                               - Init IO subsystem
                               -Initialize paging file
                               -Finish registry initialization (calls NtInitializeRegistry)
  smss.exe                             -Loads rest of system32¥config¥* hives
                                       -Converts SYSTEM hive to mapped


  winlogon                     -Loads/unloads user hives (logon/logoff)


   KERNEL                      -CmShutdownSystem
 system process
 (worker thread)
                               -IoShutdownSystem

                                © Microsoft Corporation                                       22
                   Power Off
Backup/Restore                                              …of the registry



•   Backup:
    – NtSaveKey(Ex) – saves an entire hive to a file
    – Also does compression
        • Tree copy to a in memory temporary & volatile hive
        • Save temporary to destination file
               – Slow on big hives
    – Ex called with REG_NO_COMPRESSION much faster
        • Just dumps what’s there to the file
        • No compression.
    – Requires SeBackupPrivilege
•   Restore:
    – NtReplaceKey(ExistingFile,NewFile,OldFileName) – followed by a reboot
        • NewFile hive is mounted/checked/unmounted
        • ExistingFile    OldFileName ; NewFile ExistingFile
        • Both files are kept open until reboot
               – Any changes made to the hive past this are lost at reboot
                    » Because the hive still maps to the old (existing) file
    – Requires SeRestorePrivilege



                                        © Microsoft Corporation                               23
Limits
• Win2K
  – RSL (Registry Size Limit) up to 80% sizeof(PagedPool)
     • Entire hive file loaded in paged pool
  – SYSTEM hive ~ 12 MB
     • sizeof(SYSTEM hive) + sizeof(ntoskrnl.exe) + sizeof(hal.dll) +
       sizeof(all drivers loaded at boot) <= 16 MB
          – Win2k loader only sees the first 16 MB of physical memory
• XP/WS03
  – No RSL – up to available space on system drive
     • only 4MB commit per hive
  – Sizeof(SYSTEM hive) <= min(200 MB, ¼ physical memory)
     • XP/.NET loader sees ¼ physical memory



                            © Microsoft Corporation                     24
Summary
Registry intended to maintain config info
Win32 registry interfaces in Advapi32
Registry implementation in kernel
Native APIs are NT APIs
Used by kernel, drivers, system, apps,
 security, policy, etc.


                 © Microsoft Corporation    25
Discussion




 © Microsoft Corporation   26

More Related Content

What's hot

Inside PostgreSQL Shared Memory
Inside PostgreSQL Shared MemoryInside PostgreSQL Shared Memory
Inside PostgreSQL Shared Memory
EDB
 
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
Chris Richardson
 
Git session-2012-2013
Git session-2012-2013Git session-2012-2013
Git session-2012-2013
Jose Manuel Vega Monroy
 
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
tdc-globalcode
 
Bacula - Backup system
Bacula - Backup systemBacula - Backup system
Bacula - Backup system
Mohammad Parvin
 
Mancoosi
MancoosiMancoosi
Introduction to Bacula
Introduction to BaculaIntroduction to Bacula
Introduction to Bacula
Hemant Shah
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Adrian Huang
 
Open-E Backup to iSCSI Target Volume over a LAN
Open-E Backup to iSCSI Target Volume over a LANOpen-E Backup to iSCSI Target Volume over a LAN
Open-E Backup to iSCSI Target Volume over a LAN
open-e
 
Bacula Overview
Bacula OverviewBacula Overview
Bacula Overview
sambismo
 
Lecture2 process structure and programming
Lecture2   process structure and programmingLecture2   process structure and programming
Lecture2 process structure and programming
Mohammed Farrag
 
Hadoop HDFS Detailed Introduction
Hadoop HDFS Detailed IntroductionHadoop HDFS Detailed Introduction
Hadoop HDFS Detailed Introduction
Hanborq Inc.
 
Open-E DSS V7 Synchronous Volume Replication over a LAN
Open-E DSS V7 Synchronous Volume Replication over a LANOpen-E DSS V7 Synchronous Volume Replication over a LAN
Open-E DSS V7 Synchronous Volume Replication over a LAN
open-e
 
Open-E DSS V7 Asynchronous Data Replication over a LAN
Open-E DSS V7 Asynchronous Data Replication over a LANOpen-E DSS V7 Asynchronous Data Replication over a LAN
Open-E DSS V7 Asynchronous Data Replication over a LAN
open-e
 
Aix commands
Aix commandsAix commands
Aix commands
SarowarMortoza
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
jorgesimao71
 
CASPUR Staging System II
CASPUR Staging System IICASPUR Staging System II
CASPUR Staging System II
Andrea PETRUCCI
 
basic linux command (questions)
basic linux command (questions)basic linux command (questions)
basic linux command (questions)
Sukhraj Singh
 
Inspection and maintenance tools (Linux / OpenStack)
Inspection and maintenance tools (Linux / OpenStack)Inspection and maintenance tools (Linux / OpenStack)
Inspection and maintenance tools (Linux / OpenStack)
Gerard Braad
 
Hadoop Introduction
Hadoop IntroductionHadoop Introduction
Hadoop Introduction
tutorialvillage
 

What's hot (20)

Inside PostgreSQL Shared Memory
Inside PostgreSQL Shared MemoryInside PostgreSQL Shared Memory
Inside PostgreSQL Shared Memory
 
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
SQL? NoSQL? NewSQL?!? What's a Java developer to do? - PhillyETE 2012
 
Git session-2012-2013
Git session-2012-2013Git session-2012-2013
Git session-2012-2013
 
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
TDC2016POA | Trilha Arquitetura - Apache Kafka: uma introdução a logs distrib...
 
Bacula - Backup system
Bacula - Backup systemBacula - Backup system
Bacula - Backup system
 
Mancoosi
MancoosiMancoosi
Mancoosi
 
Introduction to Bacula
Introduction to BaculaIntroduction to Bacula
Introduction to Bacula
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
 
Open-E Backup to iSCSI Target Volume over a LAN
Open-E Backup to iSCSI Target Volume over a LANOpen-E Backup to iSCSI Target Volume over a LAN
Open-E Backup to iSCSI Target Volume over a LAN
 
Bacula Overview
Bacula OverviewBacula Overview
Bacula Overview
 
Lecture2 process structure and programming
Lecture2   process structure and programmingLecture2   process structure and programming
Lecture2 process structure and programming
 
Hadoop HDFS Detailed Introduction
Hadoop HDFS Detailed IntroductionHadoop HDFS Detailed Introduction
Hadoop HDFS Detailed Introduction
 
Open-E DSS V7 Synchronous Volume Replication over a LAN
Open-E DSS V7 Synchronous Volume Replication over a LANOpen-E DSS V7 Synchronous Volume Replication over a LAN
Open-E DSS V7 Synchronous Volume Replication over a LAN
 
Open-E DSS V7 Asynchronous Data Replication over a LAN
Open-E DSS V7 Asynchronous Data Replication over a LANOpen-E DSS V7 Asynchronous Data Replication over a LAN
Open-E DSS V7 Asynchronous Data Replication over a LAN
 
Aix commands
Aix commandsAix commands
Aix commands
 
quickguide-einnovator-9-redis
quickguide-einnovator-9-redisquickguide-einnovator-9-redis
quickguide-einnovator-9-redis
 
CASPUR Staging System II
CASPUR Staging System IICASPUR Staging System II
CASPUR Staging System II
 
basic linux command (questions)
basic linux command (questions)basic linux command (questions)
basic linux command (questions)
 
Inspection and maintenance tools (Linux / OpenStack)
Inspection and maintenance tools (Linux / OpenStack)Inspection and maintenance tools (Linux / OpenStack)
Inspection and maintenance tools (Linux / OpenStack)
 
Hadoop Introduction
Hadoop IntroductionHadoop Introduction
Hadoop Introduction
 

Viewers also liked

MArtinez Carlos Intro PNL
MArtinez Carlos Intro PNLMArtinez Carlos Intro PNL
MArtinez Carlos Intro PNL
Carlos Martinez
 
Pnl Inter Intro Relaciones
Pnl Inter  Intro RelacionesPnl Inter  Intro Relaciones
Pnl Inter Intro Relaciones
luberza
 
Herramientas para el Cambio (2). PNL.
Herramientas para el Cambio (2). PNL.Herramientas para el Cambio (2). PNL.
Herramientas para el Cambio (2). PNL.
ILIMITS
 
PNL 2
PNL 2PNL 2
PNL 2
Psi Buap
 
Pnl
PnlPnl
Diapositivas neurolinguistica[1]
Diapositivas neurolinguistica[1]Diapositivas neurolinguistica[1]
Diapositivas neurolinguistica[1]
Maria García
 
Introducción básica a la PNL
Introducción básica a la PNLIntroducción básica a la PNL
Introducción básica a la PNL
Alicia Herrando
 
"Introducción a la PNL" By: Joseph O'connor
"Introducción a la PNL" By: Joseph O'connor"Introducción a la PNL" By: Joseph O'connor
"Introducción a la PNL" By: Joseph O'connor
Jimee 'Meillon
 
Programación Neurolinguistica
Programación Neurolinguistica Programación Neurolinguistica
Programación Neurolinguistica
Sindya Rangel
 
PROGRAMACION NEUROLINGUISTICA
PROGRAMACION NEUROLINGUISTICAPROGRAMACION NEUROLINGUISTICA
PROGRAMACION NEUROLINGUISTICA
xmoreno
 
PNL y Estrategias
PNL y EstrategiasPNL y Estrategias
PNL y Estrategias
Jesús Gonzalez
 
LA PROGRAMACION NEUROLINGUISTICA (PNL)
LA PROGRAMACION NEUROLINGUISTICA (PNL)LA PROGRAMACION NEUROLINGUISTICA (PNL)
LA PROGRAMACION NEUROLINGUISTICA (PNL)
Armando Lopez
 
El poder de la palabra bra-robert-dilts
El poder de la palabra bra-robert-diltsEl poder de la palabra bra-robert-dilts
El poder de la palabra bra-robert-dilts
alexus1010
 

Viewers also liked (13)

MArtinez Carlos Intro PNL
MArtinez Carlos Intro PNLMArtinez Carlos Intro PNL
MArtinez Carlos Intro PNL
 
Pnl Inter Intro Relaciones
Pnl Inter  Intro RelacionesPnl Inter  Intro Relaciones
Pnl Inter Intro Relaciones
 
Herramientas para el Cambio (2). PNL.
Herramientas para el Cambio (2). PNL.Herramientas para el Cambio (2). PNL.
Herramientas para el Cambio (2). PNL.
 
PNL 2
PNL 2PNL 2
PNL 2
 
Pnl
PnlPnl
Pnl
 
Diapositivas neurolinguistica[1]
Diapositivas neurolinguistica[1]Diapositivas neurolinguistica[1]
Diapositivas neurolinguistica[1]
 
Introducción básica a la PNL
Introducción básica a la PNLIntroducción básica a la PNL
Introducción básica a la PNL
 
"Introducción a la PNL" By: Joseph O'connor
"Introducción a la PNL" By: Joseph O'connor"Introducción a la PNL" By: Joseph O'connor
"Introducción a la PNL" By: Joseph O'connor
 
Programación Neurolinguistica
Programación Neurolinguistica Programación Neurolinguistica
Programación Neurolinguistica
 
PROGRAMACION NEUROLINGUISTICA
PROGRAMACION NEUROLINGUISTICAPROGRAMACION NEUROLINGUISTICA
PROGRAMACION NEUROLINGUISTICA
 
PNL y Estrategias
PNL y EstrategiasPNL y Estrategias
PNL y Estrategias
 
LA PROGRAMACION NEUROLINGUISTICA (PNL)
LA PROGRAMACION NEUROLINGUISTICA (PNL)LA PROGRAMACION NEUROLINGUISTICA (PNL)
LA PROGRAMACION NEUROLINGUISTICA (PNL)
 
El poder de la palabra bra-robert-dilts
El poder de la palabra bra-robert-diltsEl poder de la palabra bra-robert-dilts
El poder de la palabra bra-robert-dilts
 

Similar to Registry

The building blocks of docker.
The building blocks of docker.The building blocks of docker.
The building blocks of docker.
Chafik Belhaoues
 
Ospresentation 120112074429-phpapp02 (1)
Ospresentation 120112074429-phpapp02 (1)Ospresentation 120112074429-phpapp02 (1)
Ospresentation 120112074429-phpapp02 (1)
Vivian Vhaves
 
ubantu ppt.pptx
ubantu ppt.pptxubantu ppt.pptx
ubantu ppt.pptx
MrGyanprakash
 
Bluestore
BluestoreBluestore
Bluestore
Patrick McGarry
 
Bluestore
BluestoreBluestore
Bluestore
Ceph Community
 
Updates
UpdatesUpdates
Updates
UpdatesUpdates
Beyondfs-intro
Beyondfs-introBeyondfs-intro
Beyondfs-intro
Kim Yong-Duk
 
Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...
Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...
Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...
BertrandDrouvot
 
NeXTBSD aka FreeBSD X
NeXTBSD aka FreeBSD XNeXTBSD aka FreeBSD X
NeXTBSD aka FreeBSD X
iXsystems
 
Libra Library OS
Libra Library OSLibra Library OS
Libra Library OS
Eric Van Hensbergen
 
Unix fundamentals
Unix fundamentalsUnix fundamentals
Unix fundamentals
Bimal Jain
 
Ubuntu OS Presentation
Ubuntu OS PresentationUbuntu OS Presentation
Ubuntu OS Presentation
Loren Schwappach
 
Talk 160920 @ Cat System Workshop
Talk 160920 @ Cat System WorkshopTalk 160920 @ Cat System Workshop
Talk 160920 @ Cat System Workshop
Quey-Liang Kao
 
Privilege Escalation with Metasploit
Privilege Escalation with MetasploitPrivilege Escalation with Metasploit
Privilege Escalation with Metasploit
egypt
 
Linux architecture
Linux architectureLinux architecture
Linux architecture
mcganesh
 
Ch1 linux basics
Ch1 linux basicsCh1 linux basics
Ch1 linux basics
chandranath06
 
ch17
ch17ch17
Linux internal
Linux internalLinux internal
Linux internal
mcganesh
 
Linux architecture
Linux architectureLinux architecture
Linux architecture
mcganesh
 

Similar to Registry (20)

The building blocks of docker.
The building blocks of docker.The building blocks of docker.
The building blocks of docker.
 
Ospresentation 120112074429-phpapp02 (1)
Ospresentation 120112074429-phpapp02 (1)Ospresentation 120112074429-phpapp02 (1)
Ospresentation 120112074429-phpapp02 (1)
 
ubantu ppt.pptx
ubantu ppt.pptxubantu ppt.pptx
ubantu ppt.pptx
 
Bluestore
BluestoreBluestore
Bluestore
 
Bluestore
BluestoreBluestore
Bluestore
 
Updates
UpdatesUpdates
Updates
 
Updates
UpdatesUpdates
Updates
 
Beyondfs-intro
Beyondfs-introBeyondfs-intro
Beyondfs-intro
 
Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...
Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...
Reduce Resource Consumption & Clone in Seconds your Oracle Virtual Environmen...
 
NeXTBSD aka FreeBSD X
NeXTBSD aka FreeBSD XNeXTBSD aka FreeBSD X
NeXTBSD aka FreeBSD X
 
Libra Library OS
Libra Library OSLibra Library OS
Libra Library OS
 
Unix fundamentals
Unix fundamentalsUnix fundamentals
Unix fundamentals
 
Ubuntu OS Presentation
Ubuntu OS PresentationUbuntu OS Presentation
Ubuntu OS Presentation
 
Talk 160920 @ Cat System Workshop
Talk 160920 @ Cat System WorkshopTalk 160920 @ Cat System Workshop
Talk 160920 @ Cat System Workshop
 
Privilege Escalation with Metasploit
Privilege Escalation with MetasploitPrivilege Escalation with Metasploit
Privilege Escalation with Metasploit
 
Linux architecture
Linux architectureLinux architecture
Linux architecture
 
Ch1 linux basics
Ch1 linux basicsCh1 linux basics
Ch1 linux basics
 
ch17
ch17ch17
ch17
 
Linux internal
Linux internalLinux internal
Linux internal
 
Linux architecture
Linux architectureLinux architecture
Linux architecture
 

Recently uploaded

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 

Recently uploaded (20)

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 

Registry

  • 1. Windows Kernel Internals NT Registry Implementation David B. Probert, Ph.D. Windows Kernel Development Microsoft Corporation © Microsoft Corporation 1
  • 2. Outline • High level overview • System whereabouts • Native registry APIs • Implementation Details • I/O • Mounting a Hive • Life Span • Backup/Restore • Limits © Microsoft Corporation 2
  • 3. High Level Overview • Logical: – Registry = “a FS within a file” – Keys directories – Values files • Physical: – Registry = collection of Hives – Hive = collection of Bins – Bin = collection of Cells – Cell = unit of allocation (contains raw data) © Microsoft Corporation 3
  • 4. Whereabouts ADVAPI32.DLL svchost.exe Win32 Registry APIs regsvc.dll NT APIs User KERNEL MM Volatile Storage Memory Manager CM (registry) .LOG file PRIMARY file (NO_INTERMEDIATE_BUFFERING) (CC PRIVATE_WRITE streams) CC NTFS/FAT Cache Manager © Microsoft Corporation Disk 4
  • 5. NT Registry APIs: Key Ops NtCreateKey (kname) open a new or existing key NtDeleteKey (khandle) mark key to delete at last handle close NtEnumerateKey (khandle, i) return the name/info of subkey[i] of key NtQueryKey (khandle) get info about a key NtSetInformationKey set info on key (khandle, info) NtRenameKey (khandle, string) change the name of key NtFlushKey (khandle) flush changes associated with key to disk NtNotifyChangeKey notify caller of changes to a key/subtree (khandle, bsubtree) NtNotifyChangeMultipleKeys Multi-key version of NtNotifyChangeKey (knames[], bsubtree) © Microsoft Corporation 5
  • 6. NT Registry APIs: Value Ops NtEnumerateValueKey (khandle, i) return the name/info of value[i] of key NtQueryValueKey (khandle, vname) get value (data & type) NtQueryMultipleValueKey get multiple values (khandle, vnames[]) NtSetValueKey set a value (khandle, vname, value) NtDeleteValueKey (khandle, vname) delete a value belonging to a key Misc Ops NtQueryOpenSubKeys (kpath) get count of open khandles under kpath NtCompactKeys (count, khandles[]) optimize access to khandles[] © Microsoft Corporation 6
  • 7. NT Registry APIs: Hive Ops NtSaveKey (khandle, fhandle) write the subtree at key khandle to file via fhandle NtRestoreKey copy a subtree or complete hive at key (khandle, hivefilename) NtLoadKey (khandle, hivefilename) mount a subtree or complete hive at key NtUnloadKey (kname) remove a subtree or hive loaded or restored at key kname NtReplaceKey prepare to replace hive at next reboot (newfile, roothandle, oldfile) NtCompressKey (roothandle) compress hive (inplace SaveKey) © Microsoft Corporation 7
  • 8. Implementation Details • A Hive is a file (two if you also count the .LOG) – PRIMARY – holds the actual hive data – .LOG – used only when flushing (crash recovery) • Two storage mappings: – Stable – maps to the backing file – Volatile – in paged pool, lost after reboot • PRIMARY grows in 256K increments – to avoid fragmentation • First page (4k) is the header • Followed by chained Bins • I/O to primary is cached, PRIVATE_WRITE stream (no CC Lazy Flush, no MPW) © Microsoft Corporation 8
  • 9. Hive Layout Signature (‘regf’) Sequence1 (ULONG) Sequence2 (ULONG) HIVE HEADER (HBASE_BLOCK) TimeStamp Size is 4K Major (ULONG) Minor (ULONG) ……other…….. Bin 0 RootCell (HCELL_INDEX) size is multiple of 4K Length (ULONG) ( x86 PAGE_SIZE) …reserved up to 1k -4 bytes….. PRIMARY Bin 1 Hive File: CheckSum (ULONG) …reserved up to 4K….. ………….. Bin N © Microsoft Corporation 9
  • 10. Bin • Collection of cells • Size is increment of 4K • Unit of hive growth • 0x20 bytes header followed by raw cells Signature (‘hbin’) FileOffset (ULONG) Bin Header Size (ULONG) (HBIN) Reserved (ULONG[2]) TimeStamp Spare (ULONG) Bin: raw cell data © Microsoft Corporation 10
  • 11. Reading Stable Storage • PRIMARY file is CC PRIVATE_WRITE stream – no CC Lazy Flush, no MM MPW, no read ahead – complete control over when data hits the disk • Map/fault in 16K views of the hive in the system cache address space (CcMapData) – Views cannot cross 256K boundary • Max 256 views per hive, then reuse the oldest unused view (LRU) – Regardless of hive size, we only commit 4 megs of address space / hive (XP/.NET) no RSL • PRIMARY is loaded as Stable storage, Volatile storage is allocated from paged pool • Dirtied data is pinned (CcPinMappedData) in physical memory up to the first hive flush © Microsoft Corporation 11
  • 12. Cell • Unit of storage allocation within the hive • Size rounded at 8 bytes boundary • Referenced as a ‘cell index’ (HCELL_INDEX) – Cell index is offset within the file (minus 0x1000 – the header) – ULONG – Volatile cell indexes have first MSB set (i.e. 0x8xxxxxxx) • Free Display bitmap keeps track of free cells with the same size – Up to 128 bytes exact match – 128 bytes up to 2048 bytes, rounded at power of 2 – 2048 OR higher in the same list – Free cells in the same ‘size class’ linked together • Always reuse free cells if one with the same size (or bigger) exists – If size is bigger than what we need, split & reenlist remaining • Every time a cell is dirtied the whole page is marked dirty (in the Dirty Vector) Cell : Size (LONG) raw data positive = free cell When cell is free, first ULONG negative = allocated cell (actual size is – Size) points to the next free cells in the same size class © Microsoft Corporation 12
  • 13. Example – value lookup “foo” Key Value List Value Size Size Size Val1 (cell index) Type …… Val2 (cell index) …. Data Length …. ValueCount = N Data Cell (cell index) ValueList (cell index) Val K (cell index) FOO …. …… Data Size Val N (cell index) Whatever data was set on this value • Raw cells are used to build up logical data – Keys, values, security descriptors, indexes etc all are made up of cells – Fetching in a key, might involve several faults spread across the hive file Caching (Win2K) + locality enforcement (XP/.NET) to help with performance © Microsoft Corporation 13
  • 14. Dirty Data • When a cell is dirtied: Hive (Stable Storage) – Containing view is pinned in memory – Entire page is marked dirty – Reserve space in the .LOG Header • Bitmap with dirty data at (x86) page level • Used for flushing Bin 0 (size = PAGE_SIZE) DIRTY • Header is always flushed Bin 1 (size = PAGE_SIZE) CLEAN One bit per page 1 0 …….. Dirty Vector 1 DIRTY Bin K 0 (RTL_BITMAP) (size = 2 * CLEAN PAGE_SIZE) …….. 1 Bin N (last bin) DIRTY © Microsoft Corporation 14
  • 15. .LOG • .LOG file used only while flushing – In the event of a crash during flushing – Reset after successful flush Log header • Physical log Signature – Logs raw dirty pages – Unaware of high level data types (keys, values Sequence1 etc) Sequence2 • Same name as the hive file (+ .LOG Signature first 1K from the PRIMARY extension) .......... header .LOG file same as the header Log header for the PRIMARY ……… I/O: no buffering Dirty Vector (variable size) CheckSum padding to sector alignment Dirty Vector Signature (‘DIRT’) dirty page dirty page Dirty bitmap Full pages of dirty data dirty page ……. © Microsoft Corporation 15
  • 16. Hive Flush • The most expensive operation (by far) • Triggered from outside – NtFlushKey/RegFlushKey • … or from inside - Lazy Flush – Fires off 5 seconds after the write occurs (SetValue/DeleteValue/CreateKey/DeleteKey etc). – Walks the list of the hives loaded in the system and flushes every one that has dirty data – Ignores hives marked as NO_LAZY_FLUSH • Others may read during flush, no write allowed • All dirty data in the hive is written out • All or none makes it to the backing file • It is only after the flush that data is persisted to disk – i.e. If you: • CreateKey + SetValue • machine crashes (before lazy flush has a chance to flush the hive) • the key/value is lost • Automatic flush at hive unload © Microsoft Corporation 16
  • 17. Hive Flush – algorithm 1.Write the LOG 2.Flush the LOG Past this point all dirty data is in the log (on disk) 3.Header.Sequence1++; compute checksum 4.Write the Header to PRIMARY 5.Flush the PRIMARY Crash past this point Sequence1 != Sequence2 so we know the PRIMARY image has partial data CcSetDirtyPinnedData 6.Write all dirty pages CcUnpinData 7.Flush the PRIMARY CcFlushCache 8.Header.Sequence2++; compute checksum 9.Write the Header to PRIMARY 10.Flush the PRIMARY PRIMARY image is valid (on disk). 11.Reset LOG © Microsoft Corporation 17
  • 18. Loading (Mounting) a Hive • When: – At boot: boot loader (NTLDR) & kernel (ntoskrnl.exe) – Explicitly, by calling NtLoadKey/RegLoadKey • Requires Restore privilege – File are opened in exclusive mode; and kept open by the kernel © Microsoft Corporation 18
  • 19. Loading (Mounting) a Hive • How: – Read PRIMARY header; check it’s validity (checksum, signature etc) – If sequence numbers don’t match: • Hive has partial data, apply .LOG on top of PRIMARY – Build internal mappings as needed (Bins to Views) – Physical integrity check: • Walk the whole hive, check every single cell – Logical integrity check: • Walk the tree, check every key/value etc. © Microsoft Corporation 19
  • 20. Hives On a Typical (Clean) System • Machine hives %windir%¥system32¥config¥* – SYSTEM – mounted at HKLM¥System – SOFTWARE – mounted at HKLM¥Software – SAM – mounted at HKLM¥SAM – SECURITY – mounted at HKLM¥Security – .DEFAULT – used when a new account is created • Failure to load any of these OS will not boot © Microsoft Corporation 20
  • 21. Hives On a Typical (Clean) System • User hives two per each user account – NTUSER.DAT – roams (if roaming profile enabled) • Mounted under HKEY_USERS¥<SID> • Mounted under HKEY_USERS¥<SID>_Classes – UsrClass.DAT – local (does not roam) – per user registration data – Stored in %USERPROFILE% folder. – Loaded at logon, or whenever the user is impersonated • ‘Special’ user hives – Two per account as above; always loaded • S-1-5-18 SYSTEM account • S-1-5-19 Local Service • S-1-5-20 Network Service • Clusters – one additional hive: CLUSTER (cluster db) – %windir%¥Cluster¥Cluster • Any user/app with Restore privilege can mount own hive © Microsoft Corporation 21
  • 22. Life Span Power On -loads ntoskrnl.exe and hal.dll -loads SYSTEM hive in memory Boot Loader -uses info in the hive to load ‘load at boot’ drivers (NTLDR) -starts the executive and passes in memory copy of the system hive (LoaderParameterBlock) Phase1Initialization KERNEL -Init MM (ntoskrnl.exe) -Init CM (CmInitSystem1): gets memory copy of the SYSTEM hive from LoaderBlock and mounts it in PagedPool system process - Init IO subsystem -Initialize paging file -Finish registry initialization (calls NtInitializeRegistry) smss.exe -Loads rest of system32¥config¥* hives -Converts SYSTEM hive to mapped winlogon -Loads/unloads user hives (logon/logoff) KERNEL -CmShutdownSystem system process (worker thread) -IoShutdownSystem © Microsoft Corporation 22 Power Off
  • 23. Backup/Restore …of the registry • Backup: – NtSaveKey(Ex) – saves an entire hive to a file – Also does compression • Tree copy to a in memory temporary & volatile hive • Save temporary to destination file – Slow on big hives – Ex called with REG_NO_COMPRESSION much faster • Just dumps what’s there to the file • No compression. – Requires SeBackupPrivilege • Restore: – NtReplaceKey(ExistingFile,NewFile,OldFileName) – followed by a reboot • NewFile hive is mounted/checked/unmounted • ExistingFile OldFileName ; NewFile ExistingFile • Both files are kept open until reboot – Any changes made to the hive past this are lost at reboot » Because the hive still maps to the old (existing) file – Requires SeRestorePrivilege © Microsoft Corporation 23
  • 24. Limits • Win2K – RSL (Registry Size Limit) up to 80% sizeof(PagedPool) • Entire hive file loaded in paged pool – SYSTEM hive ~ 12 MB • sizeof(SYSTEM hive) + sizeof(ntoskrnl.exe) + sizeof(hal.dll) + sizeof(all drivers loaded at boot) <= 16 MB – Win2k loader only sees the first 16 MB of physical memory • XP/WS03 – No RSL – up to available space on system drive • only 4MB commit per hive – Sizeof(SYSTEM hive) <= min(200 MB, ¼ physical memory) • XP/.NET loader sees ¼ physical memory © Microsoft Corporation 24
  • 25. Summary Registry intended to maintain config info Win32 registry interfaces in Advapi32 Registry implementation in kernel Native APIs are NT APIs Used by kernel, drivers, system, apps, security, policy, etc. © Microsoft Corporation 25
  • 26. Discussion © Microsoft Corporation 26