When the program file is automatically updated, replace the analysis of the running File

Source: Internet
Author: User
When upgrading program files automatically, some files will always be in use. How can I replace them:

[Reprinted] replacing the analysis of running files

Author: Dancefire
From: xfocus

I. Introduction

I always like to answer questions about everything. I have been asking myself why, but I have no question to ask. Of course I have also asked myself when I am too reluctant to ask again. Because the automatic update of a software is always faulty, sometimes it cannot be automatically updated. After analysis, it is found that a problem occurred while replacing the running program. Without knowing it, I began to analyze how to replace the running program.

Although I am not sure that I want to go deep into it, I just want to go deep into a problem and analyze it when I cannot continue to analyze it due to poor technology. However, I still hope this article will be helpful to people who think about this problem just like me.

Let's get down to the truth. First, I will be inspired by xfocus's bgate article "quietly replacing the system files in use on Win2000/XP.

He studied replacing the system files in use and analyzed a Microsoft tool zap, which can replace system files. After analysis, the tool first moves the file in use to a temporary directory, and then deletes the file, but marks it as deleted at next startup. At this time, the system file directory has made room for the new file to be moved.

The implementation code is as follows:

Copy content to clipboard

Code:

if(szFileToDel[1] == ':'){
sprintf(cTempPathName, "%c:", szFileToDel[0]);
}
else{
GetModuleFileName(NULL, cFileName, 0x100);
sprintf(cTempPathName, "%c:", cFileName[0]);
}

if(GetTempFileName(cTempPathName, "_@", 0, cTempFileName) == 0) return FALSE;
if(MoveFileEx(szFileToDel, cTempFileName, MOVEFILE_REPLACE_EXISTING) == 0) return FALSE;
if(MoveFileEx(cTempFileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) == 0) return FALSE;
if(MoveFileEx(szNewFile, szFileToDel, MOVEFILE_REPLACE_EXISTING) == 0) return FALSE;

Where

Copy content to clipboard

Code:

winbase.h:

#define MOVEFILE_REPLACE_EXISTING 0x00000001
#define MOVEFILE_COPY_ALLOWED 0x00000002
#define MOVEFILE_DELAY_UNTIL_REBOOT 0x00000004
#define MOVEFILE_WRITE_THROUGH 0x00000008

Ii. MoveFileEx Analysis

To understand how MoveFileEx () moves files at the next restart, I checked the operating system source code.
1. MoveFileEx () is actually the MoveFileWithProgressW () called, except that two callback parameters are NULL.
2. The BasepMoveFileDelayed () function is called for dwFlag = MOVEFILE_DELAY_UNTIL_REBOOT in MoveFileWithProgressW ().
3. BasepMoveFileDelayed () enables file operations when the operating system restarts by modifying the registry.
The modified key value is
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerPendingFileRenameOperations
This is the key value of REG_MULTI_SZ.
Format:

Copy content to clipboard

Code:

szDstFile
szSrcFileszDstFile
szSrcFile!szDstFile

In some articles, the source file and the target file are in the middle of a line break, which is acceptable, but the standard is Unicode, that is, 00

Note that if the MOVEFILE_REPLACE_EXISTING attribute is specified, an exclamation point is added before the target file.

After analyzing the source code, we found that the key value has been provided in MSDN, Faint ~~.

Later, I opened my key value and found a bunch of files that had not been deleted before, waiting for me to delete them during the next restart, it seems I should have restarted.

I also noticed another issue that I am not familiar with, that is, why the file is moved, but the application can still be executed, but the deletion won't work. I didn't take this issue into consideration, but I felt that something had not changed, such as a link. Although the location has changed, the link can still trace the location of the image, so all operations pointing to the link take effect. However, when a file is deleted, the link will be deleted, leading to operation failure. To avoid such failure, you are prohibited from deleting the file that is being occupied.

Iii. operations related to operating system startup

According to Microsoft's explanation of MOVEFILE_DELAY_UNTIL_REBOOT, the operating system will immediately move the specified file after the Autochk check is complete and before any PageFile file is created. Make sure that the file to be operated can be operated by the LocalSystem or administrator group.

I followed the Startup Process of NT and want to know how the system executes the above mentioned mobile or delete behavior at startup.

In the regionalization internal stage, ntoskrnl.exe takes control of NTLDR. In the last step, Session Manager starts the Windows XP advanced subsystems and services, session Manager starts and controls all input and output devices, Win32 sub-systems that access the display screen, and Winlogon processes. kernel Initialization is complete.

Session manager.exe is used on Session manager. We can often see smss.exe in the memory process. During disassembly, we can see in sub_48584D01 that XP has the CPU to be recognized:

Reference:

0x86
1 MIPS
2 ALPHA
3 PPC
4 IA64
5 ALPHA64
Other UNKNOWN

I found PendingFileRenameOperations in smss.exe. It can be seen that this file is responsible for executing the file movement operation during the boot. Unfortunately, I have not found any way to call PendingFileRenameOperations, And the disassembly skills are poor.

See a section in sysinternals.com about Session Manager calling PendingFileRenameOperations.

Http://www.sysinternals.com/ntw2k/info/regboot.shtml

^

Reference:

After you pass the point in the log where boot and system driver initialization is complete you'll be in to see records created by the smss.exe process, which is called the Session Manager. session Manager is the first user-mode process launched during a boot. you'll see it immediately check to see if there are any rename operations it shocould perform before the system is up and running by looking at the value HKLMSystemCurrentControlSetControlSession ManagerPendingFileRenameOperations. next you'll see it determine what DOS device mappings it shoshould create (e.g. COM1, LPT1), what environment variables are defined, what DLL's it "knows about" (standard DLLs in the system32 directory), and which protected subsystems it shoshould start (e.g. OS/2, POSIX ).

Session Manager typically launches Chkdsk (autocheck.exe), which is specified in the Session Manager's BootExecute value along with direction to run other boot-time native applications. after Autocheck finishes Session Manager starts Winlogon and the Win32 subsystem (CSRSS. EXE ). both of these generate interleaved Registry accesses as they start up concurrently. winlogon can be seen querying. default key's display settings, including colors and mouse settings under HKU. defaultControl Panel. the. default key's contents are user preferences that are active when no one is logged in, and Winlogon uses them for the screen on which it displays the logon dialog box.

^

However, this is different from Microsoft's description of Autochk first and then PendingFileRenameOperations.

Http://freehost02.websamba.com/brittanyfoo/BootProcess.html from another document) mentioned initialization process issues:

^
The main thread of the Smss performs the following initialization steps:

1. Create an LPC Port object (SmApiPort) and two threads waiting for customer requests. Customer requests include loading a new subsystem or creating a session.

2. Define symbolic links for MS-DOS device names such as COM1 and LPT1.

3. If Terminal Services is installed, create the Sessions directory in the namespace of the Object Manager.

4. Run the HKLMSYSTEMCurrentControlSet ControlSession ManagerBootExecute defined program. Typically, run Autochk (the version of Chkdsk in the pilot phase ).

5. Follow the command of HKLMSYSTEMCurrentControlSetControlSession ManagerPendingFileRenameOperations to rename the delayed file. The pending file is deleted in PendingFileRenameOperations2.

6. Open the known DLL.

7. Create another paging file.

8. initialize the registry. The Configuration Manager refreshes the registry and loads the registration file for the HKLMSAM, HKLMSECURITY, and HKLMSOFTWARE keywords. HKLMSYSTEM CurrentControlSetControlhivelist searches for the Registry file on the hard disk, and the Configuration Manager searches for it in WinntSystem32Config.

9. Create system environment variables.

10. Load the kernel mode of the Win32 subsystem (Win32k. sys ). In HKLMSYSTEMCurrentControlSetControlSession Manager, Smss searches for Win32k. sys and other paths of the components to be loaded to determine their locations. The initialization code in Win32k. sys uses the video driver to convert the screen resolution to the value defined in the default profile file. Therefore, the screen is switched from the VGA mode used by the boot video driver to the default resolution selected by the system.

11. Start the subsystem process, including Csrss.

12. Start the login process (Winlogon ).

13. Create LPC ports (DbgSsApiPort and DbgUiApiPort) for debugging event information and create threads that listen to these ports.

^

This is the most clearly described, and the related operations are also basically understood when the system is started.

Iv. Summary

So far, I have a preliminary understanding of replacing the files in use.

MoveFileExW-> MoveFileWithProgressW-> BasepMoveFileDelayed-> HKLMSystemCurrentControlSetControlSession ManagerPendingFileRenameOperations

Afterwards, ntldrboot starts the smss.exe (Session Manager), checks PendingFileRenameOperations after Autochk, and then performs the file replacement operation. Finally, smss starts the Winlogon process and allows users to log on.

Therefore, this method can replace almost all system files, because smss is the first UserMode process in the system. At this time, very few files are used, and it is impossible for someone to occupy files before it.

Put the rule in the correct directory. Move smss.exe in the local file to NULL, And it is MOVEFILE_DELAY_UNTIL_REBOOT. In this case, if the system restarts, the new smss.exe will be used, and then it will clear the garbage in the Temporary Folder. In fact, it is okay not to clear it at this time. After it is up, it is okay to clear it again, because nothing is occupying the garbage in the Temporary Folder.

To replace a common application, you only need to restart the application, because the contents in the application directory are already new files. Restart only to delete the garbage in the Temporary Folder.

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.