so-05 introducao a win32

Upload: bia3105

Post on 03-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 SO-05 Introducao a Win32

    1/74

    Introduo WIN32

    Mark E. Russinovich, David A. Solomon, Microsoft WindowsInternals, Fourth Edition, Microsoft Press, 2005 [cap. 2]

    Jeffrey Richter, Christophe Nasarre, Windows via C/C++, Fifth

    Edition, Microsoft Press, 2008 [cap. 1, 2 e 3]

    Microsoft, Microsoft Developers Network(MSDN)

  • 8/12/2019 SO-05 Introducao a Win32

    2/74

    205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 2

    Sumrio

    Arquitectura Windows

    Caracteres e Strings

    Objectos do Kernel Tratamento de erros

  • 8/12/2019 SO-05 Introducao a Win32

    3/74

    Arquitectura Windows

    Mark E. Russinovich, David A. Solomon, Microsoft WindowsInternals, Fourth Edition, Microsoft Press, 2005 [cap. 2]

  • 8/12/2019 SO-05 Introducao a Win32

    4/74

    405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 4

    Requirements drove the

    specification of Windows

    The following requirements drove the specification of Windows

    NT back in 1989: Provide a true 32-bit, preemptive, reentrant, virtual memory operating

    system

    Run on multiple hardware architectures and platforms

    Run and scale well on symmetric multiprocessing systems Be a great distributed computing platform, both as a network client and as

    a server

    Run most existing 16-bit MS-DOS and Microsoft Windows 3.1

    applications Meet government requirements for POSIX 1003.1 compliance

    Meet government and industry requirements for operating system security

    Be easily adaptable to the global market by supporting Unicode

  • 8/12/2019 SO-05 Introducao a Win32

    5/74

    505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 5

    Design goals

    Extensibility - The code must be written to comfortably grow and change asmarket requirements change

    Portability - The system must be able to run on multiple hardwarearchitectures and must be able to move with relative ease to new ones asmarket demands dictate

    Reliability and robustness - The system should protect itself from both

    internal malfunction and external tampering. Applications should not be ableto harm the operating system or other applications

    Compatibility - Although Windows NT should extend existing technology,its user interface and APIs should be compatible with older versions of

    Windows and with MS-DOS. It should also interoperate well with othersystems such as UNIX, OS/2, and NetWare

    Performance - Within the constraints of the other design goals, the systemshould be as fast and responsive as possible on each hardware platform

  • 8/12/2019 SO-05 Introducao a Win32

    6/74

    605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 6

    Architecture overview

  • 8/12/2019 SO-05 Introducao a Win32

    7/74

    705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 7

    Architecture overview

    Such as the logon process and the session manager, that are not Windows services. That is,

    they are not started by the service control manager

    Such as the logon process and the session manager, that are not Windows services. That is,

    they are not started by the service control manager

  • 8/12/2019 SO-05 Introducao a Win32

    8/74

    805 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 8

    Architecture overview

    That host Windows services, such as the Task Scheduler and Spooler services. Services generally

    have the requirement that they run independently of user logons. Many Windows server

    applications, such as Microsoft SQL Server and Microsoft Exchange Server, also include

    components that run as services.

    That host Windows services, such as the Task Scheduler and Spooler services. Services generally

    have the requirement that they run independently of user logons. Many Windows server

    applications, such as Microsoft SQL Server and Microsoft Exchange Server, also include

    components that run as services.

  • 8/12/2019 SO-05 Introducao a Win32

    9/74

    905 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 9

    Architecture overview

    Which can be one of six types:

    Windows 32-bit, Windows 64-bit,

    Windows 3.1 16-bit, MS-DOS 16-bit,

    POSIX 32-bit, or OS/2 32-bit.

    Which can be one of six types:

    Windows 32-bit, Windows 64-bit,

    Windows 3.1 16-bit, MS-DOS 16-bit,

    POSIX 32-bit, or OS/2 32-bit.

  • 8/12/2019 SO-05 Introducao a Win32

    10/74

    1005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 10

    Architecture overview

    Which implement part of the support for the operating system environment, or personality

    presented to the user and programmer.Windows NT originally shipped with three environment subsystems: Windows, POSIX, and OS/2.

    OS/2 was dropped as of Windows 2000.

    As of Windows XP, only the Windows subsystem is shipped in the base productan enhanced

    POSIX subsystem is available as part of the free Services for Unix product.

    Which implement part of the support for the operating system environment, or personality

    presented to the user and programmer.

    Windows NT originally shipped with three environment subsystems: Windows, POSIX, and OS/2.

    OS/2 was dropped as of Windows 2000.

    As of Windows XP, only the Windows subsystem is shipped in the base productan enhanced

    POSIX subsystem is available as part of the free Services for Unix product.

  • 8/12/2019 SO-05 Introducao a Win32

    11/74

    1105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 11

    Architecture overview

    Under Windows, user applications don't call the native Windows operating system services

    directly;

    Rather, they go through one or more subsystem dynamic-link libraries (DLLs)The role of the subsystem DLLs is to translate a documented function into the appropriate

    internal (and generally undocumented) Windows system service calls.

    This translation might or might not involve sending a message to the environment subsystem

    process that is serving the user application.

    Under Windows, user applications don't call the native Windows operating system services

    directly;

    Rather, they go through one or more subsystem dynamic-link libraries (DLLs)

    The role of the subsystem DLLs is to translate a documented function into the appropriate

    internal (and generally undocumented) Windows system service calls.

    This translation might or might not involve sending a message to the environment subsystem

    process that is serving the user application.

  • 8/12/2019 SO-05 Introducao a Win32

    12/74

    1205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 12

    Architecture overview

    The Windows executive contains the base operating system services, such as memory

    management, process and thread management, security, I/O, networking, and

    interprocess communication.

    The Windows executive contains the base operating system services, such as memory

    management, process and thread management, security, I/O, networking, and

    interprocess communication.

  • 8/12/2019 SO-05 Introducao a Win32

    13/74

    1305 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 13

    Architecture overview

    The Windows kernel consists of low-level operating system functions, such as thread

    scheduling, interrupt and exception dispatching, and multiprocessor synchronization.

    It also provides a set of routines and basic objects that the rest of the executive uses to

    implement higher-level constructs.

    The Windows kernel consists of low-level operating system functions, such as thread

    scheduling, interrupt and exception dispatching, and multiprocessor synchronization.

    It also provides a set of routines and basic objects that the rest of the executive uses to

    implement higher-level constructs.

  • 8/12/2019 SO-05 Introducao a Win32

    14/74

    1405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 14

    Architecture overview

    Device drivers include both hardware device drivers that translate user I/O function calls into

    specific hardware device I/O requests as well as file system and network drivers.

    Device drivers include both hardware device drivers that translate user I/O function calls into

    specific hardware device I/O requests as well as file system and network drivers.

  • 8/12/2019 SO-05 Introducao a Win32

    15/74

    1505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 15

    Architecture overview

    The hardware abstraction layer (HAL) is a layer of code that isolates the kernel, device drivers,

    and the rest of the Windows executive from platform-specific hardware differences (such as

    differences between motherboards).

    The hardware abstraction layer (HAL) is a layer of code that isolates the kernel, device drivers,

    and the rest of the Windows executive from platform-specific hardware differences (such as

    differences between motherboards).

  • 8/12/2019 SO-05 Introducao a Win32

    16/74

    1605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 16

    Architecture overview

    The windowing and graphics system implements the graphical user interface (GUI) functions

    (better known as the Windows USER and GDI functions), such as dealing with windows, user

    interface controls, and drawing.

    The windowing and graphics system implements the graphical user interface (GUI) functions

    (better known as the Windows USER and GDI functions), such as dealing with windows, user

    interface controls, and drawing.

  • 8/12/2019 SO-05 Introducao a Win32

    17/74

    1705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 17

    Architecture overview

    kernel32.dll

    advapi32.dll

    user32.dll

    gdi32.dll

    Ntoskrnl.exe

    Ntkrnlpa.exe

    (32-bit systems only)

    with support for Physical

    Address Extension (PAE),

    which allows addressing of upto 64 GB of physical memory

    hal.dll

    win32k.sys

    csrss.exe (windows)os2ss.exe (OS/2)psxss.exe (Posix)

  • 8/12/2019 SO-05 Introducao a Win32

    18/74

    1805 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 18

    Subsystem DLLs

  • 8/12/2019 SO-05 Introducao a Win32

    19/74

    1905 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 19

    Environment subsystems

    A informao de iniciao dos subsistemas guardada na chave do registry

    HKLM\SYSTEM\Current-ControlSet\Control\Session Manager\SubSystems

    A informao de iniciao dos subsistemas guardada na chave do registry

    HKLM\SYSTEM\Current-ControlSet\Control\Session Manager\SubSystems

  • 8/12/2019 SO-05 Introducao a Win32

    20/74

    2005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 20

    Architecture

  • 8/12/2019 SO-05 Introducao a Win32

    21/74

    2105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 21

    Architecture

    Ntdll.dll is a special system supportlibrary primarily for the use ofsubsystem DLLs. It contains two

    types of functions:

    Group of functions provides theinterface to the Windowsexecutive system services that

    can be called from user mode (e.g.NtCreateFile, NtSetEvent)

    Internal support functions usedby subsystems, subsystem DLLs,and other native images (e.g. image

    loader, the heap manager, Windowssubsystem process communicationfunctions

  • 8/12/2019 SO-05 Introducao a Win32

    22/74

    2205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 22

    Architecture System Processes

  • 8/12/2019 SO-05 Introducao a Win32

    23/74

    2305 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 23

    Architecture System Processes

    Idle processcontains one thread per CPU toaccount for idle CPU time

    System process is the homefor a special kind of thread thatruns only in kernel mode - akernel-mode system thread

  • 8/12/2019 SO-05 Introducao a Win32

    24/74

    2405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 24

    Architecture System Processes

    Session manager (smss.exe)

    The first user-mode process created in the system. The

    kernel-mode system thread that performs the final phaseof the initialization of the executive and kernel createsthe actual smss process

    The Session Manager is responsible for a number ofimportant steps in starting Windows, such as opening

    additional page files, performing delayed file rename anddelete operations, and creating system environmentvariables. It also launches the subsystem processes(normally just csrss.exe) and the Winlogon process

  • 8/12/2019 SO-05 Introducao a Win32

    25/74

    2505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 25

    Architecture System Processes

    Windows logon process (Winlogon.exe)

    Handles interactive user logons and logoffs Winlogon is notified of a user logon request when the

    secure attention sequence (SAS) keystrokecombination is entered. The default SAS on Windows isthe combination Ctrl+Alt+Delete. The reason for the SASis to protect users from password-capture programs thatsimulate the logon process, because this keyboardsequence cannot be intercepted by a user modeapplication

    Once the username and password have been captured,they are sent to the local security authentication serverprocess lsass.exe

    Upon a successful authentication Winlogon create theinitial process(es) in the user's session (default isuserinit.exe)*

    * registry key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

  • 8/12/2019 SO-05 Introducao a Win32

    26/74

    2605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 26

    Architecture System Processes

    Userinit

    performs some initialization of the user environment

    (such as running the login script and applying group

    policies) looks in the registry at the Shell value * and creates a

    process to run the system-defined shell (by default,

    Explorer.exe)

    Then Userinit exits (This is the reason Explorer.exe is

    shown with no parent)

    Winlogon is active not only during user logon and logoffbut also whenever it intercepts the SAS from the

    keyboard

    * registry key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

  • 8/12/2019 SO-05 Introducao a Win32

    27/74

    2705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 27

    Architecture System Processes

    Service control manager (Services.exe)

    This process (and the child service processes it creates(e.g. service host process - Svchost.exe) is a specialsystem process that is responsible for starting, stopping,and interacting with service processes

    Processes that can be configured to start automatically atsystem boot time without requiring an interactive logon

    Service programs are really just Windows images that call

    special Windows functions to interact with the servicecontrol manager to perform such actions as registeringthe service's successful startup, responding to statusrequests, pausing and shutting down the service

  • 8/12/2019 SO-05 Introducao a Win32

    28/74

    2805 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 28

    Services listing installed services

    Services are defined in the registry under

    HKLM\SYSTEM\CurrentControlSet\Services

    Administrative Tools from Control Panel and the select Services

  • 8/12/2019 SO-05 Introducao a Win32

    29/74

    2905 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 29

    Services listing installed services

    Detailed properties about a service right

    clicked on the service and select

    properties

  • 8/12/2019 SO-05 Introducao a Win32

    30/74

    3005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 30

    Services Process Explorer

    Double-click on a service-hosting process

  • 8/12/2019 SO-05 Introducao a Win32

    31/74

    3105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 31

    WIN 32

  • 8/12/2019 SO-05 Introducao a Win32

    32/74

    3205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 32

    Verses mais ligeiras do Windows (desktop use) Windows 1.0-1985, 2.0-1987 , 3.0-1990, 3.1-1992 Windows for Workgroups 3.11, 1994 Windows 95, Windows 98, Windows ME in 2000

    Verses do Windows baseadas no NT (New Technology) Windows NT 3.1, Workstation, Advanced Server, 1993, Windows NT 3.5, Workstation, Server, 1994 Windows NT 3.51 , Workstation, Server, 1995 Windows NT 4.0 Workstation, Server, Server Enterprise, 1996 Windows 2000 Professional, Server,Advanced ServereData Center Server editions,

    2000 Windows XPHome, Professional,Media Centere 64-bits editions, 2001 Windows Server 2003 (.net), Standard,Enterprise,Datacenter, Web e Small Business

    editions, 2003

    Windows Vista, Starter, Home Basic, Home Premium, Professional, Small Business,Enterprise, Ultimate (x64 editions will be available too), ~2006 Windows Longhorn Server (codename), ~2007

    Windows CE 1.0-1996, 2.0-1997, 3.0-2000, 4.0-2002, 5.0-2004, 6.0-2006

    Verses do Windows

  • 8/12/2019 SO-05 Introducao a Win32

    33/74

    3305 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 33

    Windows 95 NT/2000Windows 3.x

    Win32s

    Win32

    Win32s - uma extenso API de 16 bits do Windows 3.x para correr aplicaes de 32bits.

    Windows CE implementa parte da Win32 API mas com muitas limitaes visto quedever correr em mquinas sem disco e com pouca memria.

    Windows 95 uma implementao da Win32 API mas com limitaes visto que devercorrer em mquinas com 386 e 4Mb.

    Windows NT/2000/XP/Vista - implementam a totalidade da API Win32.

    Windows CEWindows 98 XP/server/Vista

    Implementaes da Win32

  • 8/12/2019 SO-05 Introducao a Win32

    34/74

    Caracteres e Strings

    Representao de texto

    Cdi ASCII

  • 8/12/2019 SO-05 Introducao a Win32

    35/74

    3505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 35

    Cdigo ASCII

    American Standard Code for Information Interchange (ANSIX3.4-1986)

    Cdigo de representao de caracteres a 8 bits apenas 256smbolos

    Ento como representar todos os caracteres e smbolos de todo omundo incluindo as escritas modernas mas tambm antigas, porexemplo o chins, japons, rabe, hebreu, etc

    Soluo 1: Representar alguns caracteres a 16 bits (DBCS Double ByteCharacter Strings)

    Soluo 2: Codificao UNICODE

    Cdi ASCII

  • 8/12/2019 SO-05 Introducao a Win32

    36/74

    3605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 36

    Cdigo ASCII

    Cdi ASCII t did

  • 8/12/2019 SO-05 Introducao a Win32

    37/74

    3705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 37

    Cdigo ASCII estendido

    U i d

  • 8/12/2019 SO-05 Introducao a Win32

    38/74

    3805 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 38

    Unicode

    Proposto inicialmente pela Apple e Xerox em 1988

    Em 1991 foi criado um consrcio para desenvolver e promover o Unicode. Noconsrcio estavam empresas como Apple, Compaq, Hewlett-Packard, IBM, Microsoft,Oracle, Silicon Graphics, Sybase, Unisys e Xerox (lista completa emhttp://www.unicode.org)

    Unicode define 1.114.112code points de 0hex at 10FFFFhex

    habitual indicar um Unicodecode point escrevendo U+

    capacidade para representar os caracteres das vrias lnguas e outros smbolos, como

    por exemplo smbolos matemticos e tcnicosPlane Range Description Abbreviation

    0 0000FFFF Basic Multilingual Plane BMP

    1 100001FFFF Supplementary Multilingual Plane SMP

    2 200002FFFF Supplementary Ideographic Plane SIP

    3 to 13 30000DFFFF currently unassigned

    14 E0000EFFFF Supplementary Special-purpose Plane SSP

    15 F0000FFFFF Supplementary Private Use Area-A

    16 10000010FFFF Supplementary Private Use Area-B

    U i d

  • 8/12/2019 SO-05 Introducao a Win32

    39/74

    3905 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 39

    Unicode

    Esto definidos standards para a representao dosUnicode (Unicode Transformation Format - UTF)

    UTF-8 Codificao a 1 byte, a 2 bytes, a 3 bytes ou a 4 bytes

    UTF-16

    codificao a 2 bytes 16 bits no suficiente para todos os caracteres Unicode nessas

    situaes o UTF-16 usa surrogates (uma forma de utilizar 4

    bytes na codificao).

    O Windows utiliza este tipo de codificao

    UTF-32

    Codifica todos os caracteres a 4 bytes

    Unicode

  • 8/12/2019 SO-05 Introducao a Win32

    40/74

    4005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 40

    Cdigo a 16 bits

    Partes mostradas:Basic LatinLatin SupplementLatin Extended-A

    GreekArabic

    Musical SymbolsArrows

    Geometric Shapes

    BasicLatin

    Latin

    Supplement

    Unicode

    Source:http://www.unicode.org/Public/5.0.0/charts/CodeCharts.pdf

    Unicode

  • 8/12/2019 SO-05 Introducao a Win32

    41/74

    4105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 41

    Greek

    A

    rabic

    La

    tinExtended-A

    Unicode

    Unicode

  • 8/12/2019 SO-05 Introducao a Win32

    42/74

    4205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 42

    Music

    alSymbols

    Arrows

    Geome

    tricShapes

    Unicode

    ASCII/Unicode na Win32

  • 8/12/2019 SO-05 Introducao a Win32

    43/74

    4305 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 43

    ASCII/Unicode na Win32

    O sistema operativo Windows 95 e suas evolues, Windows 98 e ME,no suportam Unicode nativo

    Se um aplicao utilizar cdigo Unicode quando faz uma chamada de sistema as

    strings so em primeiro lugar convertidas para ASCII, feita a chamada desistemas e as strings de resposta so convertidas novamente para Unicode

    O Windows NT e suas evolues, 2000, XP, 2003 (.NET), Vista, suportamnativamente o Unicode continuando, no entanto, a suportar o ASCII

    Se um aplicao utilizar cdigo ASCII quando faz uma chamada de sistema as

    strings so em primeiro lugar convertidas para Unicode, feita a chamada de

    sistemas e as strings de resposta so convertidas novamente para ASCII

    O Windows CE s suporta Unicode

    A concepo de cdigo na disciplina de S.O. assume o compromisso defazer cdigo que possa ser compilado nas vrias famlias do sistemaoperativo Windows

    Caracteres a 8 e 16 bits no ANSI C

  • 8/12/2019 SO-05 Introducao a Win32

    44/74

    4405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 44

    Caracteres a 8 e 16 bits no ANSI C

    Declarao de carateres a 8 bits:char c = s ;char *st r = Ol a;char a[ ] = ol a" ;

    Declarao de caracteres a 16 bits (wide char):wchar _t c = s ; / / wchar _t def i ni do em wchar . hwchar _t *st r = LOl a;wchar _t a[ ] = LOl a;

    No Windows um wchar_t representa um caracter Unicode de 16 bits no formato UTF-16

    A biblioteca de Run-Time C contm verses de funes paracaracteres a 8 e 16 bits, exemplos:8bits 16bits

    st r l en wcsl en

    st r cpy wcscpy

    st r cmp wcscmp

    pr i nt f wpr i nt f

    sscanf swscanf

    Vai-se utilizar compilao

    condicional para se obter as

    verses 8 e 16 bits

    ASCII/Unicode - RT/C

  • 8/12/2019 SO-05 Introducao a Win32

    45/74

    4505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 45

    Utilizao do tipo genrico de caracter TCHAR Definido no ficheiro de definies tchar.h (no compatvel com ANSI C)

    As definies do ficheiro tchar.h so expandias em funo da definio do smbolo

    _UNICODE

    A definio do smbolo _UNICODE deve aparecer antes dos includes ou atravs das opes

    do compilador

    #def i ne _UNI CODE / / par a c r un- t i me header f i l es

    Smbolo _UNICODE definido Sim: uso das verses com suporte de caracteres wide (16 bits)

    No: uso das verses com suporte de caracteres single (8 bits)

    Macros de utilizao condicional TCHAR para caracter (expande para wchar_t ou char)

    _TEXT() ou _T para caracteres ou strings (expande para L( ) ou no)

    Exemplos: TCHAR c0 = _T( s ) , c1 = _TEXT( s ) ;

    TCHAR *st r 0 = _T( Ol a) ;

    TCHAR *st r 1 = _TEXT( Ol a) ;

    ASCII/Unicode - RT/C

    ASCII/Unicode - RT/C

  • 8/12/2019 SO-05 Introducao a Win32

    46/74

    4605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 46

    ASCII/Unicode RT/C

    Macros para as funes da biblioteca ANSI que expandempara as verses de 8 ou 16 bits exemplos: 8bits 16bits tchar.h (condicional)

    st r l en wcsl en _t csl en

    pr i nt f wpr i nt f _t pr i nt f

    sscanf swscanf _st scanf

    Funo Main genrica _tmain expande para

    main (8 bits) ou

    wmain (16bits))

    Nota: a funo wsprintf no

    suporta a formatao defloats

    #ifdef _UNICODE

    #define _tcslen wcslen

    #else

    #define _tcslen strlen

    #endif

    ASCII/Unicode - Exemplo

  • 8/12/2019 SO-05 Introducao a Win32

    47/74

    4705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 47

    / / Li st Ar gs. cpp : Pr i nt t he ar gument s on t he consol e.

    #define _UNICODE / / f or c r un- t i me header f i l es

    #i ncl ude / / f or _t pr i nt f def i ni t i on _TEXT#i ncl ude / / f or pr i nt f and wpr i nt f

    i nt _t mai n( i nt ar gc, TCHAR* argv[ ] ){

    _t pr i nt f ( _TEXT( "Li st agem dos ar gument os: \ n") ) ;f or ( i nt i =0; i

  • 8/12/2019 SO-05 Introducao a Win32

    48/74

    4805 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 48

    ASCII/Unicode na Win32

    A Microsoft definiu os seus prprios tipos de caracteres, utilizadosna Win32 API, para separar dos tipos da linguagem C

    Estas definies encontram-se em WinNT.h

    t ypedef char CHAR; / / An 8-bit character

    t ypedef wchar _t WCHAR; / / A 16-bit character

    / / Pointer to 8-bit character(s)

    t ypedef CHAR *PCHAR;t ypedef CHAR *PSTR;t ypedef CONST CHAR *PCSTR;

    // Pointer to 16-bit character(s)

    t ypedef WCHAR *PWCHAR;t ypedef WCHAR *PWSTR;t ypedef CONST WCHAR *PCWSTR;

    ASCII/Unicode na Win32

  • 8/12/2019 SO-05 Introducao a Win32

    49/74

    4905 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 49

    ASCII/Unicode na Win32

    A escrita de cdigo genrica possvel atravs de tipos que expandempara as verses ASCII ou UNICODE em funo da definio do smbolode compilao UNICODE

    Essas definies encontram-se em WinNT.h#i f def UNICODEt ypedef WCHAR PTCH;t ypedef WCHAR *PTSTR;t ypedef CONST WCHAR *PCTSTR;

    #def i ne __TEXT( quot e) L##quot e#el set ypedef CHAR PTCH;t ypedef CHAR *PTSTR;t ypedef CONST CHAR *PCTSTR;#def i ne __TEXT( quot e) quot e#endi f

    #def i ne TEXT( quot e) __TEXT( quot e)

    ASCII/Unicode na Win32

  • 8/12/2019 SO-05 Introducao a Win32

    50/74

    5005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 50

    ASCII/Unicode na Win32

    A API possui funes que tm como argumento strings. Geralmente, so fornecidasduas verses da mesma funo

    HWND WINAPI CreateWindowExW(

    DWORD dwExStyle,

    PCWSTR pClassName, // A Unicode stringPCWSTR pWindowName, // A Unicode string

    ...);

    HWND WINAPI CreateWindowExA(

    DWORD dwExStyle,

    PCSTR pClassName, // An ANSI stringPCSTR pWindowName, // An ANSI string

    ...);

    No entanto podemos utilizar uma macro genrica que expande para uma das funesanteriores em funo da definio do smbolo UNICODE

    #ifdef UNICODE

    #define CreateWindowEx CreateWindowExW

    #else

    #define CreateWindowEx CreateWindowExA

    #endif

    Funes de stringseguras RT/C

  • 8/12/2019 SO-05 Introducao a Win32

    51/74

    5105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 51

    u es de st ing segu as /C

    Muitas das funes de manipulao de strings da biblioteca de run-timeC no possuem um argumento para o programador indicar a dimensomxima do buffer

    Assim as funes no consegue determinar se est a corromper amemria (aceder fora da memria associada ao buffer -overrun buffer),e.g strcat, strcpy,

    Este comportamento pode ser explorado por cdigo malicioso (e.g. virus) A Microsoft disponibiliza um novo conjunto de funes que substituem as

    funes originais consideradas inseguras e definidas em StrSafe.h As novas funes possuem o sufixo _s, basicamente possuem um novo

    argumento indicando a dimenso mxima do buffer e procedem validao de todos os seus argumentos (apontadores diferente de nulos,ausncia deoverrun buffer)

    PTSTR_tcscpy ( PTSTR st r Dest i nat i on, PCTSTR st r Sour ce) ;errno_t_tcscpy_s( PTSTR st r Dest i nat i on,

    si ze_t number Of Char act er s, PCTSTR st r Sour ce) ;

    Funes de stringseguras RT/C

  • 8/12/2019 SO-05 Introducao a Win32

    52/74

    5205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 52

    g g /

    Esto definidas outro conjunto de funes na biblioteca de RT/Cque oferecem um melhor controlo nas operaes sobre as strings

    Ao contrrio das funes anteriores estas deixam no buffer a

    informao que for possvel colocar (truncation) Existem funes que no seu nome tm:

    Cch (count of characters) em que as dimenses so indicadas emcaracteres e deve-se usar a macro _countof() para obter esse valor

    HRESULT StringCchCopy(PTSTR pszDest,size_t cchDest, PCTSTR pszSrc);

    HRESULT StringCchCopyEx(PTSTR pszDest, size_t cchDest,PCTSTR pszSrc, PTSTR *ppszDestEnd,size_t *pcchRemaining, DWORD dwFlags);

    Cb (Count of bytes) em que as dimenses so indicadas em bytesdevendo-se utilizar o operador sizeof

    HRESULT StringCbCopy(LPTSTR pszDest,

    size_t cbDest, LPCTSTR pszSrc );

  • 8/12/2019 SO-05 Introducao a Win32

    53/74

  • 8/12/2019 SO-05 Introducao a Win32

    54/74

    5405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 54

    Aplicaes Win32

    Windows.h

  • 8/12/2019 SO-05 Introducao a Win32

    55/74

    5505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 55

    O ficheiro faz o import dos seguintes ficheiros (deinclude):

    WinDEF.h Definio de tipos bsicos

    WinNT.h Definio de tipos para suporte UNICODE

    WinBASE.h Interface das funes do Kernel

    WinUSER.h Funes da Interface com utilizador (user interface)

    WinGDI.h Funes da interface grfica (Graphics Device Interface)

    Criao de um projecto no Visual Studio 2005

  • 8/12/2019 SO-05 Introducao a Win32

    56/74

    5605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 56

    para uma aplicao em modo de consola

    Criao de um projecto no Visual Studio 2005

  • 8/12/2019 SO-05 Introducao a Win32

    57/74

    5705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 57

    para uma aplicao em modo de consola

    _tmain macroque expande paramain ou wmain

    _TCHARmacro

    que expande parachar ou wchar_t

    Ol Mundo

  • 8/12/2019 SO-05 Introducao a Win32

    58/74

    5805 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 58

  • 8/12/2019 SO-05 Introducao a Win32

    59/74

    5905 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 59

    Localizao Locale

    Escrita na consola adequada ao Local

    Localizao

  • 8/12/2019 SO-05 Introducao a Win32

    60/74

    6005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 60

    "Locale" Refere a localizao (Pas/Regio e Lngua) para o qual podemosconfigurar certos aspectos do nosso programa. Categorias dependentes da localizao:

    Formatao de datas;

    Formatao de valores monetrios;

    Impresso de caracteres prprios da lngua.

    Alterao do locale _tsetlocale(int category, TCHAR *)

    macro que expande para setlocale()[8bits] ou _wsetlocale()[16bits]

    Categorias (ver MSDN para detalhes): LC_ALL (Afecta todas as categorias)

    LC_COLLATE

    LC_CTYPE

    LC_MONETARY

    LC_NUMERIC

    LC_TIME

    Local: "portuguese_portugal"

    TCHAR *act ual Local e =_tsetlocale(LC_ALL,_T("portuguese_portugal"));

    Exemplo

  • 8/12/2019 SO-05 Introducao a Win32

    61/74

    6105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 61

    Exemplo sem Localizao

  • 8/12/2019 SO-05 Introducao a Win32

    62/74

    6205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 62

  • 8/12/2019 SO-05 Introducao a Win32

    63/74

    Tratamento de erros

    Tratamento de erros

  • 8/12/2019 SO-05 Introducao a Win32

    64/74

    6405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 64

    As chamadas de sistema na situao de erro devolvem um valor quepermite aplicao verificar o sucesso ou insucesso do servio;

    Na situao de erro o sistema mantm o cdigo do ltimo erro que

    ocorreu (no contexto de cada tarefa);

    Este cdigo descreve de uma forma detalhada a situao que o provocou;

    As aplicaes podem obter este cdigo atravs da funo GetLastError()

    Atravs da funo FormatMessage() possvel converter o cdigo do erronuma informao textual (dependente da lngua do sistema operativo)

    De forma a facilitar a apresentao dos erros foram definidas asseguintes funes de apoio aos exemplos: ReportErrorSystem() eFatalErrorSystem() definidas nos ficheiros SesError.h e SesError.cpp

    Funes para apresentao de erros

  • 8/12/2019 SO-05 Introducao a Win32

    65/74

    6505 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 65

    Estas funes tm uma utilizao idntica funo printf() da linguagem C, masapresentam o seu output numa MessageBox.

    Ambas mostram o ltimo erro de sistema, mas a funo FatalErrorSystem tambm

    termina o prprio processo.

    void ReportErrorUser( const char *fmtStr, ... );void FatalErrorUser( const char *fmtStr, ... );

    Existem definidas mais duas funes semelhantes s anteriores sem

    apresentarem o cdigo de erro nem a informao textual do erro:

    void ReportErrorSystem( const char *fmtStr, ... );

    void FatalErrorSystem( const char *fmtStr, ... );

    Um exemplo utilizao FatalErrorSystem

  • 8/12/2019 SO-05 Introducao a Win32

    66/74

    6605 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 66

    int _tmain(int argc, _TCHAR* argv[])

    {

    HANDLE hFile = CreateFile(TEXT("DummyFile"), 0, 0, NULL, OPEN_EXISTING, 0, NULL);

    if (hFile == INVALID_HANDLE_VALUE)

    FatalErrorSystem(TEXT("Erro na abertura do ficheiro %s"), TEXT("DummyFile"));

    return 0;

    }

    No caso de ocorrer um erroeste vai ser apresentado na

    janela seguinte

    Cdigo do erro (GetLastError)

    Descrio textual (FormatMessage)

    Converso do cdigo de erro

  • 8/12/2019 SO-05 Introducao a Win32

    67/74

    6705 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 67

    O Visual Studio possui o utilitrio Error Lookup (menu Tools -> Error Lookup) que

    permite determinar a mensagem de erro associada a um cdigo de erro

    O Visual Studio possui o utilitrio Error Lookup (menu Tools -> Error Lookup) que

    permite determinar a mensagem de erro associada a um cdigo de erro

  • 8/12/2019 SO-05 Introducao a Win32

    68/74

  • 8/12/2019 SO-05 Introducao a Win32

    69/74

    Objectos do Kernel

    Objectos do Kernel(kernel objects)

  • 8/12/2019 SO-05 Introducao a Win32

    70/74

    7005 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 70

    Caractersticas dos objectos do kernel: so manipulados pelas funes da WIN32 API e controlados pelo

    SO

    so referenciados por um HANDLE

    tm um descritor de segurana associado, ...

    tm um contador de referncias

    File, Mailslot, pipe,...

    Mutex, Semaphore, Event, ...Process, Thread

    Exemplos de objectos

    Kernel

    O Kernelproporciona : partilha, proteco, acesso/nome,...

    (kernel objects)

    Uso de Objectos do Kernel

  • 8/12/2019 SO-05 Introducao a Win32

    71/74

    7105 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 71

    Um objecto s eliminado do sistema quando o seunmero de referncias for zero.

    Exempl o: HANDLE CreateMut ex( , Mut exName) ;

    Criar um objecto Kernel

    Partilhar um objecto j existente

    Eliminar uma referncia (handle) para o objecto

    BOOL CloseHandle( HANDLE hobj ect ) ;

    Exempl o: HANDLE OpenMut ex( access_per mi ssi ons, , Mut exName) ;

    Objectos do kernelnum processo

  • 8/12/2019 SO-05 Introducao a Win32

    72/74

    7205 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 72

    Processo Thr ead 0

    Fi l e

    Flags: herana, ...

    HANDLE ht hr ead0

    Thr ead 1

    HANDLE ht hr ead1

    HANDLE hf i l e

    Tabela dehandles deobjectos dokernelOs HANDLEsso simples referncias para

    entradas da tabela de handlesdo processo

    Permisses de acesso

    Partilha de objectos

  • 8/12/2019 SO-05 Introducao a Win32

    73/74

    7305 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 73

    Processo BProcesso A

    Thr ead B

    Handle 0

    Handle 1

    Handle 2

    Handletable

    Handle 0

    Handle 1

    Handle 2

    Handletable

    Partilha por:acesso ao objecto usando o nome

    passagem do handle ao outro processo:

    por herana

    por evocao da funo Dupl i cat eHandl e

    Thr ead A

    Mut ex

    Refs = 2

    Thr ead B

    Win32 Data Types

  • 8/12/2019 SO-05 Introducao a Win32

    74/74

    7405 Introduo Win 32 APIISEL - DEETC - ASO LEIC SO 74

    BOOL Bool ean var i abl e ( shoul d be TRUE or FALSE) .CALLBACK Cal l i ng convent i on f or cal l back f unct i ons.WI NAPI Cal l i ng convent i on f or t he Wi n32 API .WNDPROC Poi nt er t o an appl i cat i on- def i ned wi ndow pr ocedur e.DLGPROC Poi nt er t o an appl i cat i on- def i ned di al og box cal l back pr ocedur eDWORD 32- bi t unsi gned i nt eger .HANDLE Handl e t o an obj ect .HMENU Handl e t o a menu.LPARAM, WPARAM Message par amet er s.

    WCHAR 16- bi t Uni code char act er .WORD 16- bi t unsi gned i nt eger .LPCSTR Pt r t o a const ant nul l - t er mi nat ed st r i ng of 8- bi t Wi ndows ( ANSI ) char s.LPCWSTR Pt r t o a const ant nul l - t er mi nat ed st r i ng of 16- bi t Uni code char act er s.LPVOI D Poi nt er t o any t ype.LPDWORD Poi nt er t o a DWORD.

    LRESULT Si gned r esul t of message pr ocess i ng.PCWSTR Pt r t o a const ant nul l - t er mi nat ed st r i ng of 16- bi t Uni code char act er s.PHANDLE Poi nt er t o a HANDLE.

    Alguns exemplos