Einzelnen Beitrag anzeigen

Benutzerbild von Harry Stahl
Harry Stahl

Registriert seit: 2. Apr 2004
Ort: Bonn
2.479 Beiträge
 
Delphi 11 Alexandria
 
#20

AW: 10.4 : Warum Inline-Variablen?

  Alt 28. Mai 2020, 15:03
Ein schönes praktisches Beispiel wie man sich selbst ins Knie schießen kann hat Microsoft kürzlich erzählt. Ein uralter Bug in FAT32 lag im Endeffekt auch an einer unglücklich platzierten Deklaration einer Variable:

(Runterscrollen zu "Use-After-Free in FAT32")
https://msrc-blog.microsoft.com/2020...ry-on-windows/

Zitat:
The code was something along the lines of this:

Code:
for(int i = 0; i < size; i++)
{
      int tmp;
      DoStuff(&tmp, i);
}
This code was running in a loop. A variable was declared inside of the loop. On the first iteration of the loop, the function DoStuff would initialize the variable “tmp” that it is passed the address to. On every additional iteration of the loop, the variable “tmp” was used as an in/out parameter. In other words, the variable would be read from and then updated.

The issue here is that the variable comes in scope at the beginning of each iteration of the loop and goes out of scope after each iteration of the loop. With InitAll enabled, this variable is zero initialized for each iteration of the loop. This is effectively a use-after-free. This code is depending on the value of “tmp” being preserved each iteration of the loop even though it goes out of scope at the end of each iteration.
Das ist aber Fehler, der auch auch ohne Inline-Var recht ähnlich möglich wäre:

Delphi-Quellcode:
var
  tmp: Integer;
begin
  for L := 1 to 10 do begin
    // tmp := 0; <-- Oder so was
    inc (tmp);
    DoStuff (L, tmp);
  end;
Delphi würde Dir in dem oben beschriebenen C-Beispiel mit INLINE-Var eine Warnung ausgeben, dass tmp möglicherweise nicht initialisiert sei (so was wie ein "InitAll" gibts unter Delphi nicht).

Im meinem Fehler-Beispiel erhältst Du auch eine Warnung wegen der fehlenden Initialisierung (es sei denn Du initialisierst in der Schleife, dann nicht).

Aber ich sag mal: Jeder so wie er meint. Ich freue mich jedenfalls die zusätzliche Option zu haben und werde Sie auch nutzen, die Artikel in den Links, die ich oben genannt habe, führen ja auch sehr gute Gründe für eine Verwendung auf.

Wer es nicht mag, lässt es einfach...

Geändert von Harry Stahl (28. Mai 2020 um 15:19 Uhr)
  Mit Zitat antworten Zitat