Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to change a local typed constant from *outside* the routine it's declared in?

Please note that this is just a thought experiment.
I know global (static) vars are bad and breaking scope is a bad idea in any case.

Consider the following code:

function IsItChanged: integer;
const
  CanIBeChanged: integer = 0;
begin
  Result:= CanIBeChanged; 
end;

Assuming writable constants have been enabled, how can I change the value of CanIBeChanged from outside the scope of the function it's declared in?

PS No I do not intend to ever use this code it's just a question out of interest.

like image 529
Johan Avatar asked Mar 11 '12 13:03

Johan


1 Answers

Well, it can only be done by leaking a pointer to the writeable typed constant. Here is an example that takes a rather convoluted way to print the number of the beast:

program NaughtyNaughtyVeryNaughty;{$J+}
{$APPTYPE CONSOLE}
procedure Test(out MyPrivatesExposed: PInteger);
const
  I: Integer=665;
begin
  MyPrivatesExposed := @I;
  inc(I);
end;

var
  I: PInteger;
begin
  Test(I);
  Writeln(I^);
  Readln;
end.

Since the scope of a local is confined to the function in which it is defined, the approach outlined above is the only possible solution.

like image 124
David Heffernan Avatar answered Oct 20 '22 17:10

David Heffernan