Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / Visual Basic

Real Self-Replicating Program

Rate me:
Please Sign up or sign in to vote.
4.58/5 (16 votes)
19 Nov 2007CPOL3 min read 69.7K   1.3K   57   17
A self-reproducing, mutable, compiling, and executing computer program.

Screenshot - SelfReplication.png

Introduction

From Wiki:

Self-replication is any process by which a thing might make a copy of itself.

Background

At one point, I wanted a small program to compile some Notepad edited scripts and run them on the fly. There is this nice project called "C# Script: The Missing Puzzle Piece". But, that is for professionals. And then, one night I went to do some coding. And came up with a code compiler. But, this was not enough. I wanted to store the source-code for this program into the program itself, and a final spec was to generate this same source code out of the program.

In short:

  1. There is only one executable.
  2. When starting the executable, it generates its own source code.
  3. When starting the executable again, it compiles this source code and executes it, showing the same user interface!

    A nice test is to delete the executable and compile the generated source code by using Visual Studio or the command line C# compiler:

    > del SelfReplication.exe
    > csc SelfReplication.cs
    > move SelfReplication.cs SelfReplication-old.cs
    > SelfReplication.exe
  4. The last statement generates a SelfReplication.cs file.
  5. The old and the new generated files are exactly the same!!

A feature of the program is you can change (mutate) the source code, adding new functionality and generating a totally new executable. The new program will be able to replicate itself, including your mutation, in the same way as the original one.

Using the code

The code has four sections:

The compiler

The compiler is a straightforward C# compiler which uses a file path to a C# file and produces an assembly of the source file. A nice feature is to get the names for the ReferencedAssemblies by calling GetReferencedAssemblies on the assembly itself.

C#
private Assembly CompileCSharp(string strFilePath)
{
    if (strFilePath == null)
        return null;
    StreamReader sr = new StreamReader(strFilePath);
    string strSource = sr.ReadToEnd();
    sr.Close();
    CodeDomProvider cc = new CSharpCodeProvider();
    CompilerParameters cp = new CompilerParameters();
    foreach (AssemblyName assemblyName in 
    Assembly.GetEntryAssembly().GetReferencedAssemblies())
        cp.ReferencedAssemblies.Add(assemblyName.Name + ".dll");
    cp.GenerateInMemory = true;
    CompilerResults cr = cc.CompileAssemblyFromSource(cp, strSource);

    StringBuilder sb = new StringBuilder();

    if (cr.Errors.HasErrors || cr.Errors.HasWarnings)
    {
        foreach (CompilerError err in cr.Errors)
            sb.AppendLine(err.ToString());
        MessageBox.Show(sb.ToString(), "Error", 
        MessageBoxButtons.OK,
        MessageBoxIcon.Error);
        return null;
    }
    return cr.CompiledAssembly;
}

Compiling and executing an assembly

This function is also straightforward. It searches for any Main method on the compiled assembly, and invokes (executes) this Main method using the FilePath as an argument.

C#
private void Execute(object FilePath)
{
    Assembly assembly = CompileCSharp(FilePath as string);
    if (assembly == null)
        return;

    foreach (Type t in assembly.GetTypes())
    {
        MethodInfo info = t.GetMethod("Main",
            BindingFlags.Public |
            BindingFlags.NonPublic |
            BindingFlags.Static);

        if (info == null)
            continue;

        object[] parameters = new object[]
        { new string[] { FilePath as string } };
        info.Invoke(null, parameters);
    }
}

The main program

This is a tricky one. It checks for the existence of SeflReplication.cs. If it does not exist, it writes the contents of MYSELF to disk to clean up the code (not shown in this source listing for brevity). After writing it to disk, it is read back again and the MYSELF string is replaced by itself. It took me about 2 or 3 hours to get this right.

C#
static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        string strFilePath;
        if (args.Length == 0)
        {
            string strDirectory =
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            strFilePath = Path.Combine(strDirectory, "SelfReplication.cs");
            if (!File.Exists(strFilePath))
            {
                StreamWriter sw = new StreamWriter(strFilePath);
                sw.Write(Program.MYSELF);
                sw.Close();

                StreamReader sr = new StreamReader(strFilePath);
                string strCode = sr.ReadToEnd();
                sr.Close();

                int intI = strCode.IndexOf(" " + "MYSELF");
                if (intI > 0)
                    strCode = strCode.Substring(0, intI + 7) + 
                              ";\r\n\t}\r\n}\r\n";

                string strInsertCode = "MYSELF=@\"" + 
                       strCode.Replace("\"", "\"\"") + "\";";

                strCode = strCode.Replace("MYSELF" + ";", strInsertCode);

                sw = new StreamWriter(strFilePath);
                sw.Write(strCode);
                sw.Close();

                return;
            }
        }
        else
        {
            strFilePath = args[0];
        }
        Application.Run(new SelfReplication(strFilePath));
    }
    public static string MYSELF=@".......";
}

Now, the basics are in place. But in this era, there is not much place for Console programs, so I added a simple user interface to the program. You have to press a button for starting the replication (once). This prevents us from making some kind of runaway virus.

Adding a GUI

The GUI has a button on a small window. An event handler starts a new thread, having the FilePath as an argument. When the parent of all parents dies, it kills all the children.

C#
private string strFilePath;
public SelfReplication(string strFilePath)
{
    this.strFilePath = strFilePath;
    this.button1 = new Button();
    this.button1.Location = new Point(75, 25);
    this.button1.Size = new Size(100, 25);
    this.button1.Text = "Replicate";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    this.ClientSize = new Size(250, 75);
    this.Controls.Add(this.button1);
    this.Text = "SelfReplication";
}

private void button1_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(new ParameterizedThreadStart(Execute));
    thread.Name = "Execute";
    thread.IsBackground = true;
    thread.Start(strFilePath);
}

By writing this article, new ideas popped up. I am thinking of a contest to mutate the source-code, doing all kinds of weird stuff. There are only a few rules for this contest, which are mentioned in the head of this article.

Another idea is to compile to disk rather than compiling in-memory, leaving all other 'external' programs untouched.

Have fun with the program, and leave some comments when doing awful awesome things inspired by my article.

Points of interest

If you are interested in self-replication, you should definitely read the Wiki article about it.

And for this project, the Quin article will get you moving.

Acknowledgments

Thanks to Stewart Roberts for the Visual Basic .NET version of the program.

History

As of writing, the presented source code is version 1.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Retired Van der Heijden Holding BV
Netherlands Netherlands
I'm Alphons van der Heijden, living in Lelystad, Netherlands, Europa, Earth. And currently I'm retiring from hard working ( ;- ), owning my own company. Because I'm full of energy, and a little to young to relax ...., I don't sit down, but create and recreate software solutions, that I like. Reinventing the wheel is my second nature. My interest is in the area of Internet technologies, .NET etc. I was there in 1992 when Mosaic came out, and from that point, my life changed dramatically, and so did the world, in fact. (Y)

Comments and Discussions

 
GeneralMy vote of 5 Pin
Kanasz Robert6-Nov-12 2:32
professionalKanasz Robert6-Nov-12 2:32 
Generalanother possible usage Pin
Roey C21-Nov-07 1:52
Roey C21-Nov-07 1:52 
GeneralRe: another possible usage Pin
dawmail33323-Dec-07 15:05
dawmail33323-Dec-07 15:05 
GeneralRe: another possible usage Pin
Roey C24-Dec-07 5:33
Roey C24-Dec-07 5:33 
GeneralMalware source on CP Pin
jonty219-Nov-07 13:51
jonty219-Nov-07 13:51 
GeneralRe: Malware source on CP Pin
Alphons van der Heijden20-Nov-07 11:03
professionalAlphons van der Heijden20-Nov-07 11:03 
GeneralVB Version Pin
Stewart Roberts18-Nov-07 13:35
Stewart Roberts18-Nov-07 13:35 
Very awesome stuff! Big Grin | :-D
After a few tedious hours playing with quotes... here is the VB version of your code.
(Use vbc instead of csc to compile).
Why must VB hate whitespace so much?

<br />
Imports System<br />
Imports System.IO<br />
Imports System.Text<br />
Imports System.Drawing<br />
Imports System.Threading<br />
Imports System.Reflection<br />
Imports Microsoft.VisualBasic<br />
Imports System.Windows.Forms<br />
Imports System.ComponentModel<br />
Imports System.CodeDom.Compiler<br />
Namespace SelfReplication<br />
    Public Class SelfReplication<br />
        Inherits Form<br />
        Private button1 As Button<br />
        Private Function CompileVisualBasic(ByVal strFilePath As String) As Assembly<br />
            If strFilePath Is Nothing Then<br />
                Return Nothing<br />
            End If<br />
            Dim sr As New StreamReader(strFilePath)<br />
            Dim strSource As String = sr.ReadToEnd()<br />
            sr.Close()<br />
            Dim cc As CodeDomProvider = New VBCodeProvider()<br />
            Dim cp As New CompilerParameters()<br />
            For Each assemblyName As AssemblyName In Assembly.GetEntryAssembly().GetReferencedAssemblies()<br />
                cp.ReferencedAssemblies.Add(assemblyName.Name + ".dll")<br />
            Next<br />
            cp.GenerateInMemory = True<br />
            Dim cr As CompilerResults = cc.CompileAssemblyFromSource(cp, strSource)<br />
            Dim sb As New StringBuilder()<br />
            If cr.Errors.HasErrors OrElse cr.Errors.HasWarnings Then<br />
                For Each err As CompilerError In cr.Errors<br />
                    sb.AppendLine(err.ToString())<br />
                Next<br />
                MessageBox.Show(sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])<br />
                Return Nothing<br />
            End If<br />
            Return cr.CompiledAssembly<br />
        End Function<br />
        Private Sub Execute(ByVal FilePath As Object)<br />
            Dim assembly As Assembly = CompileVisualBasic(TryCast(FilePath, String))<br />
            If assembly Is Nothing Then<br />
                Return<br />
            End If<br />
            For Each t As Type In assembly.GetTypes()<br />
                Dim info As MethodInfo = t.GetMethod("Main", BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.[Static])<br />
                If info Is Nothing Then<br />
                    Continue For<br />
                End If<br />
                Dim parameters As Object() = New Object() {New String() {TryCast(FilePath, String)}}<br />
                info.Invoke(Nothing, parameters)<br />
            Next<br />
        End Sub<br />
        Private strFilePath As String<br />
        Public Sub New(ByVal strFilePath As String)<br />
            Me.strFilePath = strFilePath<br />
            Me.button1 = New Button()<br />
            Me.button1.Location = New Point(75, 25)<br />
            Me.button1.Size = New Size(100, 25)<br />
            Me.button1.Text = "Replicate"<br />
            AddHandler Me.button1.Click, AddressOf button1_Click<br />
            Me.ClientSize = New Size(250, 75)<br />
            Me.Controls.Add(Me.button1)<br />
            Me.Text = "SelfReplication"<br />
        End Sub<br />
        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)<br />
            Dim thread As New Thread(New ParameterizedThreadStart(AddressOf Execute))<br />
            thread.Name = "Execute"<br />
            thread.IsBackground = True<br />
            thread.Start(strFilePath)<br />
        End Sub<br />
    End Class<br />
    NotInheritable Class Program<br />
        Private Sub New()<br />
        End Sub<br />
        Public Shared Sub Main(ByVal args As String())<br />
            Dim strFilePath As String<br />
            If args.Length = 0 Then<br />
                Dim strDirectory As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)<br />
                strFilePath = Path.Combine(strDirectory, "SelfReplication.vb")<br />
                If Not File.Exists(strFilePath) Then<br />
                    Dim sw As New StreamWriter(strFilePath)<br />
                    sw.Write(Program.MYSELF)<br />
                    sw.Close()<br />
                    Dim sr As New StreamReader(strFilePath)<br />
                    Dim strCode As String = String.Empty<br />
                    Dim line As String = String.Empty<br />
                    While sr.Peek <> -1<br />
                        line = sr.ReadLine()<br />
                        line = line.Replace(Chr(34), Chr(34) & " & Chr(34) & " & Chr(34))<br />
                        strCode &= Chr(34) & line & Chr(34) & " & Environment.NewLine _" & Environment.NewLine & "& "<br />
                    End While<br />
                    sr.Close()<br />
                    strCode = strCode.Substring(0, strCode.Length - 27)<br />
                    sr = New StreamReader(strFilePath)<br />
                    line = sr.ReadToEnd()<br />
                    sr.Close()<br />
                    line = line.Replace(line.Substring(line.Length - 26), " = _" & Environment.NewLine & strCode & Environment.NewLine & "End Class" & Environment.NewLine & "End Namespace")<br />
                    sw = New StreamWriter(strFilePath)<br />
                    sw.Write(line)<br />
                    sw.Close()<br />
                    Return<br />
                End If<br />
            Else<br />
                strFilePath = args(0)<br />
            End If<br />
            Application.Run(New SelfReplication(strFilePath))<br />
        End Sub<br />
        Public Shared MYSELF As String = _<br />
            "Imports System" & Environment.NewLine _<br />
            & "Imports System.IO" & Environment.NewLine _<br />
            & "Imports System.Text" & Environment.NewLine _<br />
            & "Imports System.Drawing" & Environment.NewLine _<br />
            & "Imports System.Threading" & Environment.NewLine _<br />
            & "Imports System.Reflection" & Environment.NewLine _<br />
            & "Imports Microsoft.VisualBasic" & Environment.NewLine _<br />
            & "Imports System.Windows.Forms" & Environment.NewLine _<br />
            & "Imports System.ComponentModel" & Environment.NewLine _<br />
            & "Imports System.CodeDom.Compiler" & Environment.NewLine _<br />
            & "Namespace SelfReplication" & Environment.NewLine _<br />
            & "Public Class SelfReplication" & Environment.NewLine _<br />
            & "Inherits Form" & Environment.NewLine _<br />
            & "Private button1 As Button" & Environment.NewLine _<br />
            & "Private Function CompileVisualBasic(ByVal strFilePath As String) As Assembly" & Environment.NewLine _<br />
            & "If strFilePath Is Nothing Then" & Environment.NewLine _<br />
            & "Return Nothing" & Environment.NewLine _<br />
            & "End If" & Environment.NewLine _<br />
            & "Dim sr As New StreamReader(strFilePath)" & Environment.NewLine _<br />
            & "Dim strSource As String = sr.ReadToEnd()" & Environment.NewLine _<br />
            & "sr.Close()" & Environment.NewLine _<br />
            & "Dim cc As CodeDomProvider = New VBCodeProvider()" & Environment.NewLine _<br />
            & "Dim cp As New CompilerParameters()" & Environment.NewLine _<br />
            & "For Each assemblyName As AssemblyName In Assembly.GetEntryAssembly().GetReferencedAssemblies()" & Environment.NewLine _<br />
            & "cp.ReferencedAssemblies.Add(assemblyName.Name + " & Chr(34) & ".dll" & Chr(34) & ")" & Environment.NewLine _<br />
            & "Next" & Environment.NewLine & "cp.GenerateInMemory = True" & Environment.NewLine _<br />
            & "Dim cr As CompilerResults = cc.CompileAssemblyFromSource(cp, strSource)" & Environment.NewLine _<br />
            & "Dim sb As New StringBuilder()" & Environment.NewLine _<br />
            & "If cr.Errors.HasErrors OrElse cr.Errors.HasWarnings Then" & Environment.NewLine _<br />
            & "For Each err As CompilerError In cr.Errors" & Environment.NewLine _<br />
            & "sb.AppendLine(err.ToString())" & Environment.NewLine _<br />
            & "Next" & Environment.NewLine _<br />
            & "MessageBox.Show(sb.ToString(), " & Chr(34) & "Error" & Chr(34) & ", MessageBoxButtons.OK, MessageBoxIcon.[Error])" & Environment.NewLine _<br />
            & "Return Nothing" & Environment.NewLine _<br />
            & "End If" & Environment.NewLine _<br />
            & "Return cr.CompiledAssembly" & Environment.NewLine _<br />
            & "End Function" & Environment.NewLine _<br />
            & "Private Sub Execute(ByVal FilePath As Object)" & Environment.NewLine _<br />
            & "Dim assembly As Assembly = CompileVisualBasic(TryCast(FilePath, String))" & Environment.NewLine _<br />
            & "If assembly Is Nothing Then" & Environment.NewLine _<br />
            & "Return" & Environment.NewLine _<br />
            & "End If" & Environment.NewLine _<br />
            & "For Each t As Type In assembly.GetTypes()" & Environment.NewLine _<br />
            & "Dim info As MethodInfo = t.GetMethod(" & Chr(34) & "Main" & Chr(34) & ", BindingFlags.[Public] Or BindingFlags.NonPublic Or BindingFlags.[Static])" & Environment.NewLine _<br />
            & "If info Is Nothing Then" & Environment.NewLine _<br />
            & "Continue For" & Environment.NewLine _<br />
            & "End If" & Environment.NewLine _<br />
            & "Dim parameters As Object() = New Object() {New String() {TryCast(FilePath, String)}}" & Environment.NewLine _<br />
            & "info.Invoke(Nothing, parameters)" & Environment.NewLine _<br />
            & "Next" & Environment.NewLine _<br />
            & "End Sub" & Environment.NewLine _<br />
            & "Private strFilePath As String" & Environment.NewLine _<br />
            & "Public Sub New(ByVal strFilePath As String)" & Environment.NewLine _<br />
            & "Me.strFilePath = strFilePath" & Environment.NewLine _<br />
            & "Me.button1 = New Button()" & Environment.NewLine _<br />
            & "Me.button1.Location = New Point(75, 25)" & Environment.NewLine _<br />
            & "Me.button1.Size = New Size(100, 25)" & Environment.NewLine _<br />
            & "Me.button1.Text = " & Chr(34) & "Replicate" & Chr(34) & Environment.NewLine _<br />
            & "AddHandler Me.button1.Click, AddressOf button1_Click" & Environment.NewLine _<br />
            & "Me.ClientSize = New Size(250, 75)" & Environment.NewLine _<br />
            & "Me.Controls.Add(Me.button1)" & Environment.NewLine _<br />
            & "Me.Text = " & Chr(34) & "SelfReplication" & Chr(34) & Environment.NewLine _<br />
            & "End Sub" & Environment.NewLine _<br />
            & "Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)" & Environment.NewLine _<br />
            & "Dim thread As New Thread(New ParameterizedThreadStart(AddressOf Execute))" & Environment.NewLine _<br />
            & "thread.Name = " & Chr(34) & "Execute" & Chr(34) & Environment.NewLine _<br />
            & "thread.IsBackground = True" & Environment.NewLine _<br />
            & "thread.Start(strFilePath)" & Environment.NewLine _<br />
            & "End Sub" & Environment.NewLine _<br />
            & "End Class" & Environment.NewLine _<br />
            & "NotInheritable Class Program" & Environment.NewLine _<br />
            & "Private Sub New()" & Environment.NewLine _<br />
            & "End Sub" & Environment.NewLine _<br />
            & "Public Shared Sub Main(ByVal args As String())" & Environment.NewLine _<br />
            & "Dim strFilePath As String" & Environment.NewLine _<br />
            & "If args.Length = 0 Then" & Environment.NewLine _<br />
            & "Dim strDirectory As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)" & Environment.NewLine _<br />
            & "strFilePath = Path.Combine(strDirectory, " & Chr(34) & "SelfReplication.vb" & Chr(34) & ")" & Environment.NewLine _<br />
            & "If Not File.Exists(strFilePath) Then" & Environment.NewLine _<br />
            & "Dim sw As New StreamWriter(strFilePath)" & Environment.NewLine _<br />
            & "sw.Write(Program.MYSELF)" & Environment.NewLine _<br />
            & "sw.Close()" & Environment.NewLine _<br />
            & "Dim sr As New StreamReader(strFilePath)" & Environment.NewLine _<br />
            & "Dim strCode As String = String.Empty" & Environment.NewLine _<br />
            & "Dim line As String = String.Empty" & Environment.NewLine _<br />
            & "While sr.Peek <> -1" & Environment.NewLine _<br />
            & "line = sr.ReadLine()" & Environment.NewLine _<br />
            & "line = line.Replace(Chr(34), Chr(34) & " & Chr(34) & " & Chr(34) & " & Chr(34) & " & Chr(34))" & Environment.NewLine _<br />
            & "strCode &= Chr(34) & line & Chr(34) & " & Chr(34) & " & Environment.NewLine _" & Chr(34) & " & Environment.NewLine & " & Chr(34) & "& " & Chr(34) & Environment.NewLine _<br />
            & "End While" & Environment.NewLine _<br />
            & "sr.Close()" & Environment.NewLine _<br />
            & "strCode = strCode.Substring(0, strCode.Length - 27)" & Environment.NewLine _<br />
            & "sr = New StreamReader(strFilePath)" & Environment.NewLine _<br />
            & "line = sr.ReadToEnd()" & Environment.NewLine _<br />
            & "sr.Close()" & Environment.NewLine _<br />
            & "line = line.Replace(line.Substring(line.Length - 26), " & Chr(34) & " = _" & Chr(34) & " & Environment.NewLine & strCode & Environment.NewLine & " & Chr(34) & "End Class" & Chr(34) & " & Environment.NewLine & " & Chr(34) & "End Namespace" & Chr(34) & ")" & Environment.NewLine _<br />
            & "sw = New StreamWriter(strFilePath)" & Environment.NewLine _<br />
            & "sw.Write(line)" & Environment.NewLine _<br />
            & "sw.Close()" & Environment.NewLine _<br />
            & "Return" & Environment.NewLine _<br />
            & "End If" & Environment.NewLine _<br />
            & "Else" & Environment.NewLine _<br />
            & "strFilePath = args(0)" & Environment.NewLine _<br />
            & "End If" & Environment.NewLine _<br />
            & "Application.Run(New SelfReplication(strFilePath))" & Environment.NewLine _<br />
            & "End Sub" & Environment.NewLine _<br />
            & "Public Shared MYSELF As String" & Environment.NewLine _<br />
            & "End Class" & Environment.NewLine _<br />
            & "End Namespace"<br />
    End Class<br />
End Namespace

GeneralRe: VB Version Pin
Alphons van der Heijden18-Nov-07 14:36
professionalAlphons van der Heijden18-Nov-07 14:36 
QuestionRe: VB Version Pin
Stewart Roberts19-Nov-07 5:12
Stewart Roberts19-Nov-07 5:12 
AnswerRe: VB Version [modified] Pin
Alphons van der Heijden20-Nov-07 11:00
professionalAlphons van der Heijden20-Nov-07 11:00 
GeneralRe: VB Version Pin
Stewart Roberts20-Nov-07 12:46
Stewart Roberts20-Nov-07 12:46 
GeneralRe: VB Version Pin
dawmail33323-Dec-07 15:20
dawmail33323-Dec-07 15:20 
GeneralRe: VB Version Pin
Stewart Roberts27-Dec-07 7:52
Stewart Roberts27-Dec-07 7:52 
GeneralMutation Pin
Daniel Vaughan15-Nov-07 0:09
Daniel Vaughan15-Nov-07 0:09 
GeneralRe: Mutation Pin
Alphons van der Heijden18-Nov-07 14:32
professionalAlphons van der Heijden18-Nov-07 14:32 
QuestionWhy in memory? Pin
Giorgi Dalakishvili14-Nov-07 9:25
mentorGiorgi Dalakishvili14-Nov-07 9:25 
AnswerRe: Why in memory? Pin
Alphons van der Heijden14-Nov-07 11:08
professionalAlphons van der Heijden14-Nov-07 11:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.