🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.arch
Article #2509

Re: Self-modifying code

#2509
From: David Chase
Date: Tue, 10 Oct 1989 19:50
66 lines
2483 bytes
jpoon@mipos2.intel.com (Jack Poon~) writes:
>Could any experts out there educate me WHY and HOW does self-modifying
>code use?

This was discussed at length a couple of months ago; I believe Robert
Henry made some sort of a summary.

>What the advantage of using self-modifying code that non-self-modifying code
>cannot achieve?

It's possible to generate a "function" on the fly.  Koopman and Lee
had a fun paper in this summer's SIGPLAN conference (SIGPLAN Notices
July 1989) where they used self-modifying code in an interpreter.

>Is there any compiler which will generate code that self-modified?  
I had one once, but scrapped that scheme for portability reasons.
I believe that some LISP compilers make use of self-modifying code in
various ways.

>A small and useful example of self-modifying will be very helpful.

The following runs on a Motorola 68020 (with Sun calling conventions):
---------------- 
typedef int (*PF)(); PF bar;

PF partially_apply_f_to_a(f,a) unsigned int f; unsigned int a; {

  static unsigned int pa_bits[] = {
  0x20172f00, 0x203a000e, 0x2f400004,
  0x4e714ef9, 0xFFFFFFFF, 0xAAAAAAAA};

  unsigned int * code = (unsigned int *) malloc (sizeof pa_bits);
  unsigned int i;
  
  for (i = 0; i < 6; i++) code[i] = pa_bits[i];

  code[4] = f;
  code[5] = a;

  return (PF) code;
}
----------------

If you have a 68020, you can test it with the following program:

----------------
foo(a,b) { return a - b; };
main() {
  PF bar;
  printf("Executing text gives 9 - 2 = %d\n", foo(9,2));

  bar = partially_apply_f_to_a(foo,9);
  printf("Executing partial application gives 9 - 2 = %d\n", (*bar)(2));

  bar = partially_apply_f_to_a(bar,2);
  printf("Executing second partial application gives 9 - 2 = %d\n", (*bar)());
}
----------------

Note that this code is less "self-modifying" and more
"run-time-generated", though rapid recycling of a block of memory
could cause it appear to be "self-modifying".

Enjoy,

David
Technical Details
Message-ID: <48682@ricerca.UUCP>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!gem.mps.ohio-state.edu!apple!oliveb!orc!Ozona!chase
References: <1080@mipos3.intel.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!gem.mps.ohio-state.edu!apple!oliveb!orc!Ozona!chase
From: chase@Ozona.orc.olivetti.com (David Chase)
Newsgroups: comp.arch
Subject: Re: Self-modifying code
Message-ID: <48682@ricerca.UUCP>
Date: 10 Oct 89 19:50:15 GMT
References: <1080@mipos3.intel.com>
Sender: news@orc.Olivetti.Com
Reply-To: chase@Ozona.UUCP (David Chase)
Organization: Olivetti Research California, Menlo Park, CA
Lines: 66