Читаем Windows® Internals, Sixth Edition, Part 2 полностью

Any process that has an open handle to a device will have a file object in its handle table corresponding to the open instance. You can view these handles with Process Explorer by selecting a process and checking Handles in the Lower Pane View submenu of the View menu. Sort by the Type column and scroll to where you see the handles that represent file objects, which are labeled as File.

In this example, the Csrss process has a handle open to a device created by the kernel security device driver (Ksecdd.sys). You can look at the specific file object in the kernel debugger by first identifying the address of the object. The following command reports information on the highlighted handle (handle value 0xD4) in the preceding screen shot, which is in the Csrss.exe process that has a process ID of 512 (0x200):lkd> !handle d4 f 200 Searching for Process with Cid == 200 PROCESS fffffa800bf35b30 SessionId: 0 Cid: 0200 Peb: 7fffffd8000 ParentCid: 0188 DirBase: 1dba50000 ObjectTable: fffff8a000f28d80 HandleCount: 630. Image: csrss.exe Handle table at fffff8a000f28d80 with 630 entries in use 00d4: Object: fffffa800c9cc9f0 GrantedAccess: 00100001 Entry: fffff8a001409350 Object: fffffa800c9cc9f0 Type: (fffffa800737a080) File ObjectHeader: fffffa800c9cc9c0 (new version) HandleCount: 1 PointerCount: 1

Because the object is a file object, you can get information about it with the !fileobj command:lkd> !fileobj fffffa800c9cc9f0 Device Object: 0xfffffa8007da1550 \Driver\KSecDD Vpb is NULL Event signalled Flags: 0x40002 Synchronous IO Handle Created CurrentByteOffset: 0

Because a file object is a memory-based representation of a shareable resource and not the resource itself, it’s different from other executive objects. A file object contains only data that is unique to an object handle, whereas the file itself contains the data or text to be shared. Each time a thread opens a file, a new file object is created with a new set of handle-specific attributes. For example, for files opened synchronously, the current byte offset attribute refers to the location in the file at which the next read or write operation using that handle will occur. Each handle to a file has a private byte offset even though the underlying file is shared. A file object is also unique to a process, except when a process duplicates a file handle to another process (by using the Windows DuplicateHandle function) or when a child process inherits a file handle from a parent process. In these situations, the two processes have separate handles that refer to the same file object.

Although a file handle is unique to a process, the underlying physical resource is not. Therefore, as with any shared resource, threads must synchronize their access to shareable resources such as files, file directories, and devices. If a thread is writing to a file, for example, it should specify exclusive write access when opening the file to prevent other threads from writing to the file at the same time. Alternatively, by using the Windows LockFile function, the thread could lock a portion of the file while writing to it when exclusive access is required.

When a file is opened, the file name includes the name of the device object on which the file resides. For example, the name \Device\HarddiskVolume1\Myfile.dat refers to the file Myfile.dat on the C: volume. The substring \Device\HarddiskVolume1 is the name of the internal Windows device object representing that volume. When opening Myfile.dat, the I/O manager creates a file object and stores a pointer to the HarddiskVolume1 device object in the file object and then returns a file handle to the caller. Thereafter, when the caller uses the file handle, the I/O manager can find the HarddiskVolume1 device object directly. Keep in mind that internal Windows device names can’t be used in Windows applications—instead, the device name must appear in a special directory in the object manager’s namespace, which is \Global??. This directory contains symbolic links to the real, internal Windows device names. As was described earlier, device drivers are responsible for creating links in this directory so that their devices will be accessible to Windows applications. You can examine or even change these links programmatically with the Windows QueryDosDevice and DefineDosDevice functions.

EXPERIMENT: Viewing Windows Device Name to Windows Device Name Mappings

You can examine the symbolic links that define the Windows device namespace with the WinObj utility from Sysinternals. Run WinObj, and click on the \Global?? directory, as shown here:

Notice the symbolic links on the right. Try right-clicking on the device C: and selecting Properties. You should see something like this:

Перейти на страницу:

Похожие книги

Веб-аналитика: анализ информации о посетителях веб-сайтов
Веб-аналитика: анализ информации о посетителях веб-сайтов

Компании в веб-пространстве тратят колоссальные средства на веб-аналитику и оптимизацию своих веб-сайтов, которые, в свою очередь, приносят миллиарды долларов дохода. Если вы аналитик или работаете с веб-данными, то эта книга ознакомит вас с новейшими точками зрения на веб-аналитику и то, как с ее помощью сделать вашу компанию весьма успешной в веб. Вы изучите инструментальные средства и показатели, которые можно использовать, но что важнее всего, эта книга ознакомит вас с новыми многочисленными точками зрения на веб-аналитику. Книга содержит много советов, приемов, идей и рекомендаций, которые вы можете взять на вооружение. Изучение веб-аналитики по этой уникальной книге позволит познакомиться с проблемами и возможностями ее современной концепции. Написанная практиком, книга охватывает определения и теории, проливающие свет на сложившееся мнение об этой области, а также предоставляет поэтапное руководство по реализации успешной стратегии веб-аналитики.Эксперт в данной области Авинаш Кошик в присущем ему блестящем стиле разоблачает укоренившиеся мифы и ведет по пути к получению действенного понимания аналитики. Узнайте, как отойти от анализа посещаемости сайта, почему основное внимание следует уделять качественным данным, каковы методы обретения лучшего понимания, которое поможет выработать мировоззрение, ориентированное на мнение клиента, без необходимости жертвовать интересами компании.- Изучите все преимущества и недостатки методов сбора данных.- Выясните, как перестать подсчитывать количество просмотренных страниц, получить лучшее представление о своих клиентах.- Научитесь определять ценность показателей при помощи тройной проверки "Ну и что".- Оптимизируйте организационную структуру и выберите правильный инструмент аналитики.- Изучите и примените передовые аналитические концепции, включая анализ SEM/PPC, сегментацию, показатели переходов и др.- Используйте решения с быстрым началом для блогов и электронной торговли, а также веб-сайтов мелкого бизнеса.- Изучите ключевые компоненты платформы экспериментирования и проверки.- Используйте анализ конкурентной разведки для обретения понимания и принятия мер.Здесь также находятся:- Десять шагов по улучшению веб-аналитики.- Семь шагов по созданию управляемой данными культуры в организации.- Шесть способов замера успеха блога.- Три секрета создания эффективной веб-аналитики.- Десять признаков великого веб-аналитика.

Авинаш Кошик

ОС и Сети, интернет