Read windows core programming-4-Process

Source: Internet
Author: User

(4) Process

A process is an instance of the program running. It consists of the following two parts:

  1. Process Kernel Object: used by the operating system to manage and collect process information;
  2. Process address space: the code and data required for executing all processes exist in this address space.

A process is inert and needs to be executed by a thread in its context. After a process is created, the operating system also creates a primary thread for it, and the primary thread creates other threads. When all threads in a process are stopped, the operating system also destroys the process.

Possible process entry functions in windows are as follows:

Winmain/wwinmain is the entry to the window process program, and the corresponding C Runtime Library entry microwinmaincrtstartup/wwinmainstartup; similarly, main/wmain is the entry to the console process program, the corresponding library entry for C Runtime is maincrtstartup/wmaincrtstartup.

Through the compiler connection switch/subsystem: console and/subsystem: winodws, you can set which subsystem the program uses. In fact, you can not set this value, the Visual Studio compiler determines which subsystem to link to based on the provided entry functions. When the program is running, the loader of the Windows operating system checks the file header in the execution file image to obtain the subsystem value.

After a program is loaded to a process in windows, the corresponding CRT start function can be summarized as follows:

  1. Obtain the complete command line that only requires the new process;
  2. Obtain the pointer to the process environment variable;
  3. Initialize the global variables of the C/C ++ Runtime Library. You can include stdlib. h to access these variables. All these variables are summarized as follows;
  4. Initialize the CRT memory allocation function (malloc/calloc) and heap used by crt io );
  5. Call constructors of all global and static C ++ objects. (Microsoft does not recommend using these CRT variables, because their code may run before CRT initialization. It is best to call the corresponding Windows API)

 

If it is a console program, you can set the entry function

_ Tmain (INT argc, tchar * argv [])

Change

_ Tmain (INT argc, tchar * argv [], tchar * env [])

 

Windows calls

Int nmainretval = _ tmain (argc, argv, envp );

The third parameter points to the process environment variable.

After the entry function is returned, the CRT start function will call the CRT function exit and pass (nmainretval) as a parameter to it. The exit function executes the following tasks:

  1. Call any function registered by the _ onexit function;
  2. Call the destructor of all global and static C ++ objects;
  3. In debug, if the _ crtdbg_leak_check_df flag is set, the _ crtdumpmemoryleaks is called to generate a memory leak report;
  4. Call the exitprocess of the Windows operating system and pass in nmainretval. This will cause the operating system to kill the process and set its output code.

 

Process instance handle

// Connector pseudo variable, indicating the position in which the file (EXE/DLL) where the code is running is loaded to the application

Extern_c
Const
Image_dos_header _ imagebase;

Void dumpmodule ()

{

// Return the instance handle of the executable process File

Hmodule Happ = getmodulehandle (null );

Tchar szmodulename [max_path] = {};

Getmodulefilename (HAPP, szmodulename, max_path );

_ Tprintf (_ T ("getmodulehandle (null) returned-> address: 0x % x with name: % s \ r \ n"), Happ, szmodulename );


// Instance handle of the file where the code is currently executed

Hinstance hcurrentmodule = (hinstance) &__ imagebase;

Getmodulefilename (hcurrentmodule, szmodulename, max_path );

_ Tprintf (_ T ("_ imagebase returned-> address: 0x % x with name: % s \ r \ n"), hcurrentmodule, szmodulename );

 

Hmodule hcurrentexecutingmodule = NULL;

// Obtain the instance handle of the file where the dumpmodule function is located

DWORD r = getmodulehandleex (get_module_handle_ex_flag_from_address, (pctstr) dumpmodule, & hcurrentexecutingmodule );

Getmodulefilename (hcurrentexecutingmodule, szmodulename, max_path );

_ Tprintf (_ T ("getmodulehandleex (get_module_handle_ex_flag_from_address) returned-> address: 0x % x with name: % s \ r \ n "),

Hcurrentexecutingmodule, szmodulename );

 

}

 

Instance of the previous process

Wwinmain (


_ In _
Hinstance,


_ In_opt _
Hinstance hprevinstance,


_ In _
Lpwstr lpcmdline,


_ In _
Int nshowcmd

);

Hprevinstance is the handle of the previous instance, but it is always null in Win32. It is only compatible with Win16. In the Win16 era, all processes share the same process space. To instruct different instances of the program to know that something has been done by the previous instance, such as registering window
Class, so the previous instance handle is required. However, starting with Win32, each process has its own exclusive process space, so hprevinstance is no longer needed. However, to make the old code still run, keep this parameter, and always set to null.

 

Command Line of the process

Code for splitting command line parameters

Int nnumargs;

Ptstr * ppargv = commandlineargv (getcommandline (), & nnumargs );

// Use the arguments

If (* ppargv [1] ==_t ('x ')){

...

}

// Free heap

Heapfree (getprocessheap (), 0, ppargv );

Process environment variables

Getenvironmentstrings and freeenvironmentstrings are used to operate process environment variables.

Ptstr penvblock = getenviromentstrings ();

 

// Handle =: And Spaces

Freeenvironmentstrings (penvblock );

 

Functions of other operating environment variables

Getenvironmentvariable

Expandenvironmentstrings

Setenvironmentvariable

 

Association of processes (affinity)

Generally, a process can be executed on any CPU, but it can also be forced to run on a subset of the available CPU, known as the processor affinity. Sub-processes will inherit the parent process associativity.

 

Process Error Mode

 

Current process directory

Getcurrentdirectory

Setcurrentdirctory

System Version

Getversion returns the MS-DOS and Windows version, the function's Windows version is good high byte and low byte reversed

Getversionex returns more detailed information

Verifyversioninfo can be used to test the detailed version information of the system.

 

CreateProcess Function

Pszapplicationname: if it is not null, this parameter is used, but must contain the complete path and extension;

Pszcommandline: If pszapplicationnameis null, you can use this option without the extension name or .exe. If the path is not included, CreateProcess will search in the following directory:

  1. Directory where the main process exe is located;
  2. The current directory of the main process;
  3. Windows System directory, that is, the System32 directory returned by getsystemdirectory;
  4. Windows Directory;
  5. Directory listed in the PATH environment variable.

Psaprocess, psathread, and binherithandles can specify the process's security description parameters and whether to inherit the inherited kernel objects owned by the parent process.

Fdwcreate contains the flag of the process to be created.

Pvenvironment includes the environment variables passed to the new process. If it is null, It inherits from the parent process.

Pszcurdir allows the parent process to set the current drive and directory of the child process.

Psistartinfo must initialize each Member to 0 and set the struct size. Otherwise, the creation process may fail, that is, startupinfo Si = {sizeof (SI )};

Ppiprocinfo is the parameter that the system returns to us. It contains information about the created process and its main thread.

 

Terminate a process

There are four methods to terminate a process:

  1. Process exits from main function (recommended)
  2. Actively call exitprocess: The displayed call exitprocess will cause global and static C ++ object destructor not to be called, and many other cleanup tasks during C Runtime cannot be completed;
  3. Other processes call terminalprocess: The kill process itself will not complete the cleaning, but the Windows operating system will ensure the cleaning, so that the system resources will be released, that is to say, the process will not omit any resources after the end:
    1. Process Memory release
    2. Close all open files
    3. All kernel objects reduce the number of references.
    4. All user objects and GDI objects are destroyed (differentiated from the kernel, user and GDI object standards: to see which dll The create * or other operation functions come from, kernel32.dll/user. dll/GDI. DLL)
  4. All threads of the process "natural death": it will hardly happen. Unless other people call terminalthread or actively call exitthread, the exit code of the process will be set to the exit code of the last thread.

 

When a process is terminated, the following actions are performed:

  1. Terminate any legacy threads;
  2. Release the allocated user object and GDI object and disable the referenced kernel object;
  3. The process exit code changes from still_active to the parameter passed to exitprocess and terminalprocess (getexitcodeprocess can obtain this exit code );
  4. The status of the Process kernel object changes to the triggered status;
  5. Process Kernel Object reference count minus 1 (the lifetime of the Process kernel object may be longer than the process itself, so other processes have the opportunity to get the exit code and statistical information after the process is terminated ).

 

Sub-Process

After creating a sub-process in CreateProcess, you can use proces_information to operate the sub-process. If you do not need it, immediately closehandle the sub-process main thread and the sub-process itself (hprocess). Waitforsingleobject (hprocess, infinite) can wait until the child process ends.

 

Process Security

The UAC (User Account Control) is introduced in Windows Vista. Each time a process needs to access a protected or resource with a higher level of system integrity, the user's confirmation is required (that is, the UAC dialog box is displayed, this proves to be very annoying, and Microsoft has greatly reduced the frequency of pop-up windows in subsequent Windows versions ). Even if a user logs on as an administrator (most Windows users do this), by default, the started process only has a filtered Security token.

 

Automatic permission escalation: The program can embed the list Resource (rt_manifest) and declare requestedexecutionlevel information in the trustinfo section.

Manual permission escalation: Call shellexecuteex to set lpverb = "RunAs", lpfile = "executable file" parameters to apply for permission escalation. Of course, this requires confirmation from the user.

 

Permission context:

The following functions can be used to obtain the permission context:

  1. Openprocesstoken
  2. Gettokeninformation
  3. Cratewellknownsid
  4. Checktokenmembership:
  5. Isuseradmin: determines whether the current process runs as an administrator.

 

Enumerate PROCESSES IN THE SYSTEM

APIS for processes in two enumeration systems:

  1. Process32first, process32next in PDH. dll
  2. Enumprocesses in psapi. dll

Integrity Level)

The process token also contains the system integrity level of the process, and each kernel object also has its corresponding system integrity level. With these two information, windows systems can compare the integrity level when a process accesses a kernel object. Processes with low integrity level cannot modify or delete objects with high integrity, it depends on the resource policy settings of the ACE (access control entry) related to the object.

Because the integrity level occurs before the ACL (Access Control List), if the integrity level is lower than the resource to be accessed, the access will be rejected even if the process has the permission to access the resource. For example, a process downloads and executes code from the Internet. This design is particularly important.

Getprocessintegritylevel can obtain the complete new level of the process.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.