0% found this document useful (0 votes)
0 views12 pages

Windows Driver Frameworks

The document discusses the essential functions of the Windows operating system, including memory management, file systems, and security. It highlights the evolution of Windows APIs, their compatibility across different versions, and the market significance of Windows due to its widespread use and development ecosystem. The author also contrasts Windows with UNIX, emphasizing key differences in handling resources and the importance of modern coding practices.

Uploaded by

Hoang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views12 pages

Windows Driver Frameworks

The document discusses the essential functions of the Windows operating system, including memory management, file systems, and security. It highlights the evolution of Windows APIs, their compatibility across different versions, and the market significance of Windows due to its widespread use and development ecosystem. The author also contrasts Windows with UNIX, emphasizing key differences in handling resources and the importance of modern coding practices.

Uploaded by

Hoang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Chap 1 Windows

1.1 What Every OS Must Do

The author begins by reminding us that Windows, like any modern operating system, exists
to manage a handful of critical resources and services:

 Memory management
A flat, virtual address space is presented to every process, with the OS shuffling pages
between RAM and disk behind the scenes.
 File systems
Files and directories live in a hierarchical namespace; Windows provides both random‐
access and streamed I/O plus directory operations.
 Processors and scheduling
Tasks (processes/threads) are scheduled across one or many CPUs, with preemption
and priority adjustment.
 Named resources
Everything from files to synchronization objects (-- mutexes, events, etc.) has a name
and a global namespace.
 Concurrency and synchronization
APIs for threads, mutexes, semaphores, I/O completion ports, etc., let you coordinate
work both locally and across the network.
 Security
Access tokens, ACLs, privileges, and integrity levels control who can open which object
in what mode.

Modern note: In C11 or later you’d still call the core Win32/Win64 APIs
(e.g. CreateFile, ReadFile, WriteFile, etc.) exactly as before, but you might wrap them in safer
RAII‐style C++ classes or use the Windows Driver Frameworks for kernel‐mode code.

1.2 How Windows Has Changed

Although multiple “flavors” of Windows exist (desktop, server, embedded), they all speak the
same basic Win32/Win64 API. Over time the API has grown in several dimensions:

 Scalability — runs on everything from phones (Windows CE) to 64-way servers.


 Performance — under-the-hood scheduler, I/O, memory improvements.
 Integration — each release folds in new subsystems (multimedia, networking stacks,
Web Services, plug-and-play).

1
 Usability — richer GUIs, user‐friendly dialogs, accessibility enhancements.
 API extensions — new synchronization primitives, file‐system features (Transactional
NTFS), networking models (IOCP, Winsock extensions), etc.

The author stresses that, for compatibility, Microsoft has kept new additions additive. You
can usually build today’s programs to run on yesterday’s OS, or guard your code with a
version‐check.

1.3 The Windows Version Matrix

At the time of writing, the major supported editions fall into two kernel‐generations:
Kernel “NT5” (5.x) Kernel “NT6” (6.x)
Windows 2000 (NT 5.0) Windows Vista (NT 6.0)
Windows XP (NT 5.1) Windows 7 (NT 6.1)
Windows Server 2003 (NT 5.2) Windows Server 2008 / R2 (NT 6.0 / 6.1)

 NT5 covers 2000, XP, Server 2003;


 NT6 covers Vista, 7 and Server 2008/R2.

Best practice: Query GetVersionEx (or VersionHelpers.h) at runtime if you plan to call APIs
that only exist in NT6+; otherwise gracefully fail or disable those features.

Windows CE, although much lighter, implements a subset of these APIs for mobile and
embedded devices. And the very old 9x line (95/98/Me) and NT 3.x/4.x have largely been
retired or lack many modern OS services.

1.4 Why Windows Matters in the Market

The author’s case for Windows boils down to two big pillars:

1. Market dominance. Tens of millions of desktops and servers ship with Windows, so
your user base is massive.
2. Ecosystem. Cheap, plentiful development tools, a familiar GUI, wide hardware support,
and enterprise‐grade features (clustering, Active Directory, Windows Services, etc.) all
lower your time-to-market.

2
Put another way: you trade off a proprietary API for uniformity, stability, and the ability to
reach virtually every PC on the planet.

1.5 Standards, Open Systems, and Interop

Here the author tackles the “Is Windows open?” question:

 Proprietary core API. Win32/Win64 isn’t POSIX or X/Open; Microsoft alone defines and
extends it.
 Supported standards. You still get Standard C/C++ libraries, Winsock (POSIX‐style
networking), ODBC/ADO/ODBC drivers, RPC, COM, HTTP(S), SQL, etc.
 Open interop is achievable via those supported standards—e.g., TCP/IP sockets let
Windows talk to Linux boxes, RPC or REST let diverse systems collaborate, and
database protocols (ODBC, OLE DB) let you plug into Oracle, SQL Server, or MySQL.

The author’s take is balanced: Windows is closed at the core but embraces enough open
standards to sit happily in a heterogeneous environment.

A Final Modern Tip

Although the book uses a raw Win32 file-copy example (the classic HANDLE hSrc =
CreateFile(...); ReadFile(...); WriteFile(...); CloseHandle(...)), in 2025 you might wrap these in:

 C++17/20 classes with RAII for automatic handle cleanup,


 safe‐handle types from the Windows WRL or WIL (Windows Implementation Libraries),
 or simply lean on .NET Core (if you’re not confined to unmanaged code) for even
higher-level APIs.

All of these still ultimately invoke the same Windows API foundation that this chapter lays
out.

-------------------------------

3
1. Windows API Is a Handle-Based, Object-Oriented‐Style Interface

 Kernel Objects & Handles


o Almost every resource (files, processes, threads, pipes, events, memory
mappings, etc.) is represented by a kernel object, accessed through an opaque
HANDLE (not a small integer like UNIX fd).
o These handles enforce encapsulation: there are no “back doors”—you must call
the documented WinAPI functions to manipulate them.
o Each object can carry its own security attributes, ACLs, and state.
 Convenience & Consistency
o The WinAPI surface is very rich: many overlapping functions, plus “convenience”
wrappers that bundle common sequences (e.g. CopyFile vs. manual
CreateFile→ReadFile→WriteFile→CloseHandle).
o Functions often have dozens of flags and parameters; the author correctly
suggests focusing first on core parameters, and gradually layering in advanced
options.

2. Naming Conventions & Types

 Function Names
o Long, descriptive, and case-sensitive: e.g.

cpp

CopyEdit

WaitForSingleObject(handle, INFINITE);

WaitForSingleObjectEx(handle, /*alertable*/ FALSE, INFINITE);

WaitForMultipleObjects(…, /*waitAll*/ TRUE, /*timeout*/ 5000);

WaitNamedPipe(TEXT("\\\\.\\pipe\\MyPipe"), NMPWAIT_WAIT_FOREVER);

 Predefined Types
o Uppercase, self-documenting:
 BOOL (32-bit boolean)
 HANDLE (pointer-sized opaque)
 DWORD (32-bit unsigned)
 LPCTSTR / LPTSTR (pointer to (const) TCHAR)

4
o The “LP” prefix originally stood for “long pointer” (16-bit days), now simply a
pointer. Modern code can use char*/wchar_t* or, better, <string>/std::wstring.

3. Windows vs. UNIX: Key Contrasts

 Opaque Handles vs. File Descriptors


o No special meaning for 0,1,2; handles for files, processes, events, pipes all share
the same type and are manipulated identically by Wait- and I/O functions.
 Process Model
o No strict parent–child hierarchy; processes can be grouped into job objects for
collective management.
 Text Files
o Lines end with CR+LF ("\r\n"), not just LF—important for manual file parsing or
binary blobs.

4. Legacy & Portability Considerations

 Backward Compatibility Quirks


o Many Win16 remnants: LPTSTR, macros still bear WIN32 (e.g.
WIN32_FIND_DATA) though they apply to x64 as well.
o Always prefer the modern Unicode (W) variants (e.g. CreateFileW) on
Windows 10+ for international support.
 C Runtime vs. Native API
o The ANSI C library (fopen, fread, fprintf, etc.) is perfectly fine for simple file I/O
and maximum portability.
o But to leverage Windows-only features—file locking (LockFileEx),
memory-mapped files (CreateFileMapping/MapViewOfFile), overlapped I/O, or
files >4 GB—you must drop down to the WinAPI (CreateFile, ReadFile, WriteFile,
etc.).

My Recommendations & Corrections

 Modern code should avoid Hungarian notation and the legacy TCHAR macros in favor
of explicit char/wchar_t or C++ <string> types.
 Always call CloseHandle (or UnmapViewOfFile + CloseHandle for mappings) to avoid
leaks.
5
 Prefer the “Ex” and Unicode variants of functions (e.g. CreateFile2,
WaitForSingleObjectEx, CreateFileW) for future-proofing and wider feature support.

This overview captures the author’s main points about Windows’ handle-centric design,
naming conventions, portability trade-offs, and when to use the C runtime versus the native
API—plus a few modern best practices for writing clear, maintainable Windows code.

------------------------------

1.9 Prerequisites for Following the Examples

 Language & Skill Assumptions


o The author assumes you already know C and general application-development
practices.
o All examples are in C (with occasional Microsoft extensions), even though you
can call the same APIs easily from C++.
 Why C?
o The Windows API itself is declared in C; using C keeps examples accessible to
beginners and experts alike.
o Much legacy—and even new—Windows code is in C, so the examples feel
authentic.
o The author acknowledges C’s quirks (e.g. declarations at block start, old-style /*
… */ comments), but prefers its universality over C++ features.
 Required Hardware/Software
1. Any PC running Windows (32- or 64-bit).
2. A C/C++ compiler—e.g. Visual Studio 2005/2008 (or newer)—plus its SDK/headers.
3. Sufficient RAM and disk space (modern machines far exceed these minimal needs).
4. Access to the MSDN documentation (local install or online) for reference.

1.10 Example: Simple Sequential File Copy

The author uses three variants of a “cp”-style utility to contrast portability, flexibility, and
Windows-specific power:

A. Using the Standard C Library (cpC)

 Key Points
1. Opens files via FILE *in = fopen(..., "rb"), FILE *out = fopen(..., "wb").
2. Reads and writes in a fixed-size buffer loop with fread/fwrite.
3. Checks bytesRead == bytesWritten and uses perror() + errno.
6
4. Always fclose() both streams.
5. I/O is synchronous and portable to UNIX/Linux.
 Limitations
o No file locking, asynchronous I/O, memory mapping, or >4 GB support in strict
ANSI C.
o Error reporting limited to errno.

Modern tweak: In C99/C11 you can declare variables at first use, e.g.

CopyEdit

size_t bytes;

char buffer[BUF_SIZE];

if ((bytes = fread(buffer,1,BUF_SIZE,in)) > 0) {

if (fwrite(buffer,1,bytes,out) != bytes) { … }

B. Using the Windows API (cpW)

 Key Points
1. Opens with CreateFile (generic access flags, share modes, creation disposition).
2. Reads/Writes via ReadFile/WriteFile, checking return BOOL and byte counts.
3. Retrieves extended error codes with GetLastError().
4. Closes handles with CloseHandle() (generic for most kernel objects).
5. Still synchronous—but paves the way for overlapped I/O, security, and large-file
support.
 Windows-specific advantages
o Full control over security attributes, sharing modes, and async operations.
o Can easily swap in memory‐mapped files or thread pools later.

Corrected snippet (typos fixed, Unicode-neutral):

CopyEdit

7
8
C. Using the Convenience Function (CopyFile)

 The author will next show how a single call to CopyFile(src, dst, FALSE) can replace all
the boilerplate above.
 This illustrates Windows’ rich “one-function” helpers for common tasks.

Takeaways & Best Practices

 Start simple: use the C library for quick, portable tools.


 Level up: drop into WinAPI when you need advanced features (locking, async, security,
>4 GB files).
 Always clean up: fclose or CloseHandle to avoid resource leaks.
 Prefer Unicode APIs (CreateFileW, CopyFileW) for internationalization.
 Leverage convenience functions where appropriate, but understand the underlying
steps.

This structured comparison shows how you can evolve a simple file-copy utility from fully
portable C into a Windows-powered tool, mastering both portability and platform-specific
power.

9
1.10 File Copying with a Windows Convenience Function

 CopyFile Overview
o CopyFile(src, dst, bFailIfExists) encapsulates all the steps—opening, buffering,
reading, writing, closing—and also preserves metadata (timestamps, attributes,
security).
o It can even leverage internal optimizations (e.g. block-level transfers) on newer
Windows, improving performance over manual loops.
 Corrected & Modernized Example

CopyEdit

#include <windows.h>

#include <stdio.h>

int main(int argc, TCHAR *argv[]) {

if (argc != 3) {

fprintf(stderr, "Usage: %s <src> <dst>\n", argv[0]);

return 1;

// FALSE = overwrite if dst exists

if (!CopyFile(argv[1], argv[2], FALSE)) {

fprintf(stderr, "CopyFile failed, error %lu\n", GetLastError());

return 2;

return 0;

}
10
o Uses fprintf(stderr, …) for error output.
o Calls CopyFile Unicode-neutral via TCHAR (or explicitly use
CopyFileW/CopyFileA).
 Timing & Performance
o The author mentions a helper timep utility (described in Chapter 6) for
measuring execution time.
o For large files, CopyFile often outperforms a simple ReadFile/WriteFile loop,
thanks to optimized kernel routines.

1.11 Chapter Summary

1. Three Copy Methods Compared


o ANSI C (fopen/fread/fwrite):
 Portable, synchronous, minimal dependencies.
 Lacks Windows-specific capabilities (locking, async I/O, large files,
metadata).
o Windows API Loop (CreateFile/ReadFile/WriteFile):
 Full control over sharing, security, async options; supports >4 GB.
 Requires explicit buffer management and handle cleanup.
o Windows Convenience (CopyFile):
 Easiest to code; automatically handles metadata and can be faster under
the hood.
2. Key Windows-vs-C Insights
o Handles vs. FILE*; GetLastError() vs. errno; CR-LF vs. LF; Unicode awareness.
o Emphasis on always closing handles/streams to free resources.
3. When to Choose Which
o Use C Library for simple, cross-platform tools without special requirements.
o Use Raw WinAPI when you need advanced features—file locking, overlapped
I/O, security controls, huge files.
o Use Convenience APIs when you just need a quick, robust operation and
metadata preservation.

Modern Best Practices & Corrections

 Prefer explicit Unicode APIs (CopyFileW) and avoid legacy TCHAR macros in new C++
projects—use wchar_t or std::wstring.

11
 Always check return values and report errors clearly with GetLastError() formatted as
decimal or hexadecimal.
 For performance tests, use high-resolution timers (e.g. QueryPerformanceCounter) or
modern profiling tools rather than simple wrappers.

This concludes the chapter’s walkthrough of file‐copy implementations, demonstrating how


you can evolve from portable C to full Windows power with just a few API choices.

12

You might also like