Question

self deletion

Asked by: Wyn

I try to use code snippet below to delete the executable itself after run but fail , I don't know why, would you plz help?

========

#include <windows.h>

int main()
{
   
    ......//some here...

    HMODULE module = GetModuleHandle(0);

    CHAR buf[MAX_PATH];

    GetModuleFileName(module, buf, sizeof buf);

 
    __asm {
        lea     eax, buf
        push    0               // argument to ExitProcess
        push    0               // return address of ExitProcess
        push    eax             // argument to DeleteFile
        push    ExitProcess     // return address of DeleteFile
        push    module          // argument to UnmapViewOfFile
        push    DeleteFile      // return address of UnmapViewOfFile
        push    UnmapViewOfFile
        ret
    }

    return 0;
}
===

Regards
Yinan

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2001-08-18 at 23:25:13ID20170646
Tags

self

Topic

C++ Programming Language

Participating Experts
6
Points
150
Comments
23

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ASM running procedures.
    This is a question I remember dealing with some time ago, but can't find any reference to it at all now. Basically, I want to be able to have a procedure that you can pass a procedure name to so that it can run the secondary procedure. For example... procedure TFor...
  2. Getting eax,edx into char[4]
    I am using Micro-C (http://www.dunfield.com) and need to access the pentium's cpu timestampusing opcode 0x0f31. I can't use the datatype "long" as that is not supported by Micro-C. I need to get the 32bit contents of the two registers eax and edx into two char[4] ar...
  3. Help Delphi Inline ASM
    Hi, I have difficulty in converting from assembly code to delphi... is it possible to have such code in Delphi ? var MyPort : Word; begin MyPort := HexToInt('03F8'); asm RESIDENT_DATA SEGMENT WORD PUBLIC 'DATA' CMD BYTE 27, 112, 0, 200, 200 RESI...
  4. asm("nop")
    what is the use of asm("nop")??
  5. ASM question
    Following code works fine: function GetBump(x,y : integer) : integer; // return pixel at x,y (on 256x256 bump-map) asm push edi mov edi,bump and eax,$ff // modulate result: x := x mod 256 and edx,$ff // modulate result: y := y mod 256 mov ah,dl add edi,eax ...
  6. Asm > Pascal
    I'm trying to port some code to Delphi and it's confusing the hell out of me, i understand a fair amount of it appart from this.. Ycr db "Mydll.dll",0 ///dll does not matter, i am just trying to port this code... GetPass proc lptUser:DWORD,lp...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: NickRepinPosted on 2001-08-19 at 00:04:02ID: 6403022

This will not work at all on NT/2000/XP, inspite of the hack used.

Probably it will work on 95/98, but the following is much easier:

#include <windows.h>
int main()
{
   HMODULE module = GetModuleHandle(0);
   CHAR buf[MAX_PATH];
   GetModuleFileName(module, buf, sizeof buf);
   DeleteFile(buf);
}

 

by: NickRepinPosted on 2001-08-19 at 00:04:59ID: 6403023

Note that the code above is for 95 and maybe for 98.

 

by: WynPosted on 2001-08-19 at 00:16:14ID: 6403034

The program is based on win9x but it doesn't work, I don't know why.

I will try your code.

Thanks
Regards
Yinan

 

by: WynPosted on 2001-08-19 at 00:17:30ID: 6403036

Oh , i miss one line,the code is this:

====
#include <windows.h>

int main()
{
    HMODULE module = GetModuleHandle(0);

    CHAR buf[MAX_PATH];

    GetModuleFileName(module, buf, sizeof buf);

    CloseHandle(HANDLE(4));

    __asm {
        lea     eax, buf
        push    0               // argument to ExitProcess
        push    0               // return address of ExitProcess
        push    eax             // argument to DeleteFile
        push    ExitProcess     // return address of DeleteFile
        push    module          // argument to UnmapViewOfFile
        push    DeleteFile      // return address of UnmapViewOfFile
        push    UnmapViewOfFile
        ret
    }

    return 0;
}
=====

 

by: WynPosted on 2001-08-19 at 00:21:04ID: 6403041

Nick , your version still doesn't work, my windows os is win98 second version.

Regards
Yinan

 

by: AlexVirochovskyPosted on 2001-08-19 at 00:48:58ID: 6403076

Wyn(Yinan), in 95/98 apps can't deletes yourself!
Only in Nt/2000 you can use MoveFileEx for this.
In my practice, I use for this next trick:
1.From my apps write to disk some little apps, that
  make only 2 things: delay (2 sec) and delete main apps.
2. Lunch this small apps.
3. Close main

Now, after end of small, in HD stay only small apps,
that can't help your  feind.

 

by: jhancePosted on 2001-08-19 at 15:13:03ID: 6404491

So what's the point of calling DeleteFile from an _asm block vs. just calling it from C++?

 

by: NickRepinPosted on 2001-08-19 at 23:46:27ID: 6405210

>>Oh , i miss one line,the code is this:

Well, it changes the whole stuff! Inspite of that it works, it is an ungly, ugly hack!

#include <windows.h>

void main()
{
   HINSTANCE hModule=GetModuleHandle(0);

   CHAR buf[MAX_PATH];
   GetModuleFileName(hModule,buf,sizeof(buf));

   HINSTANCE hKernel=GetModuleHandle("KERNEL32");
   DWORD pExitProcess=(DWORD)GetProcAddress(hKernel,"ExitProcess");
   DWORD pDeleteFile=(DWORD)GetProcAddress(hKernel,"DeleteFileA");
   DWORD pUnmapViewOfFile=(DWORD)UnmapViewOfFile;

   

   CloseHandle(HANDLE(4));

   __asm {
       lea     eax, buf
       push    0               // argument to ExitProcess
       push    0               // return address of ExitProcess
       push    eax             // argument to DeleteFile
       push    pExitProcess     // return address of DeleteFile
       push    hModule          // argument to UnmapViewOfFile
       push    pDeleteFile      // return address of UnmapViewOfFile
       push    pUnmapViewOfFile
       ret
   }

}

 

by: NickRepinPosted on 2001-08-20 at 00:04:24ID: 6405259

As to the following code:

#include <windows.h>
int main()
{
  HMODULE module = GetModuleHandle(0);
  CHAR buf[MAX_PATH];
  GetModuleFileName(module, buf, sizeof buf);
  DeleteFile(buf);
}

Seems this really does not work even on 95. The reason I thought it would work was the SDK documentation about the DeleteFile:
<<Windows 95: The DeleteFile function deletes a file even if it is open for normal I/O or as a memory-mapped file.>>

 

by: newmangPosted on 2001-08-20 at 00:07:30ID: 6405263

For what its worth I wrote the following code to run under W95. It would run then delete itself.

// Allows an executable to delete itself

#include <windows.h>
#include <stdlib.h>
#include <tchar.h>

int WINAPI WinMain(HINSTANCE h, HINSTANCE h2, LPSTR psz, int n)
{
     // Is this the original EXE or the clone EXE ?
   // If command line = 1 arg this is the original
   // If the command line > 1 arg this is the clone
   if (__argc==1)
        {
      // Original EXE, spawn clone EXE to delete this one
      // Copy this EXE into users TEMP dir.
      TCHAR sz_path_orig[_MAX_PATH], sz_path_clone[_MAX_PATH];
      GetModuleFileName(NULL,sz_path_orig,_MAX_PATH);
      GetTempPath(_MAX_PATH,sz_path_clone);
      GetTempFileName(sz_path_clone,__TEXT("Del"),0,sz_path_clone);
      CopyFile(sz_path_orig,sz_path_clone,FALSE);

      // Open clone EXE using FILE_FLAG_DELETE_ON_CLOSE, this ensures that the clone will die
      // when it terminates.
      HANDLE hfile=CreateFile(sz_path_clone,0,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_DELETE_ON_CLOSE,NULL);

      // Spawn clone EXE by passig our EXE process's handle and path
      TCHAR sz_cmdline[512];
      HANDLE hproc_orig = OpenProcess(SYNCHRONIZE,TRUE,GetCurrentProcessId());
      wsprintf(sz_cmdline,__TEXT("%s %d \"%s\""),sz_path_clone,hproc_orig,sz_path_orig);
      STARTUPINFO si;
      ZeroMemory(&si,sizeof(si)) ;
      si.cb=sizeof(si);
      PROCESS_INFORMATION pi;
      CreateProcess(NULL,sz_cmdline,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
      CloseHandle(hproc_orig);
      CloseHandle(hfile);
      // This original process can now terminate
      }
   else
        {
      // Clone EXE : When original EXE terminates, delete it.
      HANDLE hproc_orig = (HANDLE)_ttoi(__targv[1]);
      WaitForSingleObject(hproc_orig,INFINITE);
      CloseHandle(hproc_orig);
      DeleteFile(__targv[2]);
      // Do any clean up stuff here
      }
   return 0;
}


If you need an NT/2000 version I could play around with this code to see if it can be made to work or else you can use this as a base to work from but you said earlier that you need code to run under 95 and this will do the trick

Cheers - Gavin

 

by: NickRepinPosted on 2001-08-20 at 00:27:56ID: 6405290

The problem is that NT does not allow to execute a file which is opened with FILE_FLAG_DELETE_ON_CLOSE.

The code above with the hack works fine on NT4.

 

by: WynPosted on 2001-08-20 at 07:59:15ID: 6406493

->>>Well, it changes the whole stuff!
=========

Yes, I just want to know why it changes the whole stuff,what does that line actually do indeed!??

i.e.:
CloseHandle(HANDLE(4));


 

->>>HINSTANCE hKernel=GetModuleHandle("KERNEL32");
  DWORD pExitProcess=(DWORD)GetProcAddress
(hKernel,"ExitProcess");
  DWORD pDeleteFile=(DWORD)GetProcAddress(hKernel,"DeleteFileA");
  DWORD pUnmapViewOfFile=(DWORD)UnmapViewOfFile;
===============
Why use GetProcAddress? Why not use API name directly as the original version do?

Best Regards
Yinan

 

by: newmangPosted on 2001-08-20 at 15:56:45ID: 6408031

NickRepin

I know that it doesn't work on NT kernels - I said as much in my post.

Earlier in the series of posts it was stated that the user wanted code that runs on Win 9x which the code I posted does and it is not a hack it uses standard Win32 APIs so it seems to me it fitted the requirements elucidated by the user.

Cheers - Gavin

 

by: NickRepinPosted on 2001-08-20 at 21:08:42ID: 6408502

Wyn, newmang claims that his answer is more fit for you. So reject my answer and accept his one.

 

by: WynPosted on 2001-08-20 at 21:12:50ID: 6408508

My point is to become aware of how/why those code work/doesn't work.

Regards
Yinan

 

by: NickRepinPosted on 2001-08-20 at 21:18:57ID: 6408518

Does it work now with my changes?

 

by: newmangPosted on 2001-08-20 at 21:53:53ID: 6408560

NickRepin

Please don't misunderstand my last post - I did not intend to claim that my answer is "more fit for you" and I don't believe I did.

I only acknowledged your comment that my code will not work under the NT kernel (which I stated when I posted the code) and that it would work under the 9x kernel which was what the original poster required.

No offence was intended......

Cheers - Gavin

 

by: NickRepinPosted on 2001-08-20 at 21:57:40ID: 6408573

Gavin,

no problem, thanks.

 

by: titzPosted on 2001-08-24 at 10:56:52ID: 6423061

hi to all,

i think that the simplest solutions which works under all operating systems, is the use
of a .BAT file.

in your app you create the .BAT-file and write only only line in it
delete app.exe

then you call this BAT-file immediatly before you close your app. that is all.
and it works fine.

regards to all
titz

 

by: titzPosted on 2001-08-25 at 01:52:36ID: 6424472

hi,
i am very sorry: i forgot the most important line in the BAT-file.
here it is completely:

killx.BAT:

delete app.exe
delete killx.bat


that's all. because a bat-file can kill himself.

regards
titz

 

by: NickRepinPosted on 2001-08-25 at 14:33:51ID: 6425302

>>My point is to become aware of how/why those code work/doesn't work.

When executing an .EXE, Windows opens it as a so-called section (something like CreateFileMapping), then maps the file into memory by MapViewOfFile.

By design (at least, on the Windows versions where the code above works) the handle returned by CreateFileMapping???("file.exe") is always 0x00000004. MapViewOfFile returns a pointer to memory, by design it is the pointer to the beginning of the file, and also by design HINSTANCE (or HMODULE) is just a pointer which points to the beginning of the file.

To delete itself, the executable must UnmapViewOfFile first, then close the file mapping object which in turn releases the file locks that prevent deletion. Then you can delete the file.

Once you called UnmapViewOfFile, the memory pointed by HINSTANCE becomes invalid, so if you called UnmapViewOfFile from within the C code, you would get an exception, for example:

address             instructions
00400000            MZ... (EXE header) == HINSTANCE
...
0040332A            push 00400000 ; HINSTANCE
00403330            call UnmapViewOfFile
00403336            ... other code here ....

UnmapViewOfFile unmaps all memory section beginning from 00400000. When UnmapViewOfFile returns, the IP (istruction pointer) register points to 00403336 which is not a valid piece of memory any more.

Because of this we have to place all the code to be executed on the stack, because the stack is not a part of the executable image, and it is not affected by UnmapViewOfFile().

DWORD pUnmapViewOfFile=(DWORD)UnmapViewOfFile;

The code above usually (by the compiler design) returns the address of the import thunk, which is a part of the executable image, and not the true address of the UnmapViewOfFile:


address             instructions
00400000            MZ... (EXE header) == HINSTANCE
...
00420000            jmp 77BF0500   ; import thunk
...                 .....

77B00000            MZ... (KERNEL32.DLL header) == HINSTANCE
....
77BF0500            proc UnmapViewOfFile
....                ......

So actually pUnmapViewOfFile points to a jump instruction to UnmapViewOfFile (00420000), and not to the UnmapViewOfFile itself (77BF0500). It's ok, because while we execute this particular jmp, it is still valid.

On the other hand,

DWORD pDeleteFile=(DWORD)GetProcAddress(hKernel,"DeleteFileA");

this code returns the true address (say 77BF0600), which is in the memory space of KERNEL32.DLL. We cannot use jmp thunks here, because they will be unmapped after UnmapViewOfFile.

P.S. It would be fine if you gave me additional points for such a time-consuming explanation.

 

by: DanRollinsPosted on 2001-08-26 at 00:11:42ID: 6425963

Now I know why I hang around here!  Nick, that is utterly cool beyond words.  Look for points in C++ section.

-- Dan

 

by: WynPosted on 2001-11-11 at 20:00:50ID: 6629967

another 100pt, ok? I have increased it .I miss my email ,also this new comment,so this late. i will check it soon,tks you very much,Nick!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...