2010年12月20日 星期一

Script Kiddie Class: Quine

How can a program output its program code in runtime? It could be quite difficult. Let's see an example in VB:

Debug.Print("Code")
The output is Code, but I want the output to be Debug.Print("Code").

Debug.Print("Debug.Print(""Code"")")
Now the output is Debug.Print("Code"), but the program code has already changed, and I want Debug.Print("Debug.Print(""Code"")") now.


It would be rather difficult if you just directly print something. To write a quine program, you should have your program code stored in a string for output.

Example:

Function Q(x) As String
t = Split(x, vbCrLf)
For i = 0 To UBound(t) - 1
Q = Q & Chr(34) & Replace(t(i), Chr(34), Chr(34) & Chr(34)) & Chr(34) & " & vbCrLf & _" & vbCrLf & vbTab & vbTab
Next
Q = Q & Chr(34) & t(i) & Chr(34)
End Function

Sub Form_Load()
V = "Function Q(x) As String" & vbCrLf & _
" t = Split(x, vbCrLf)" & vbCrLf & _
" For i = 0 To UBound(t) - 1" & vbCrLf & _
" Q = Q & Chr(34) & Replace(t(i), Chr(34), Chr(34) & Chr(34)) & Chr(34) & "" & vbCrLf & _"" & vbCrLf & vbTab & vbTab" & vbCrLf & _
" Next" & vbCrLf & _
" Q = Q & Chr(34) & t(i) & Chr(34)" & vbCrLf & _
"End Function" & vbCrLf & _
"" & vbCrLf & _
"Sub Form_Load()" & vbCrLf & _
" V = ?" & vbCrLf & _
" Debug.Print Replace(V, Chr(63), Q(V))" & vbCrLf & _
"End Sub"
Debug.Print Replace(V, Chr(63), Q(V))
End Sub
The entire program is stored in V, and the function Q is to escape the string, and the question mark (chr 63) is to assign the escaped program code string to variable V.



Looks funny but messy. Then what is the purpose of doing this? ... I'll tell you later.

沒有留言:

張貼留言