Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi TPath.GetTempPath result is cropped

I am using Delphi 2010 and my program wants to get the system's temp path. I am using TPath.GetTempPath and everything is working fine... at least for me and my coworkers. But on some customer machines this method returns a cropped path which is (of course) not existing. I found out that the problem seems to be the result from underlying call to GetLongPathName().

The complete code looks like this:

[...]
var
 TmpDir : String;
 Len : Integer;
begin

 [... Call to GetTempPath succeeds and we have a valid temp directory in short "~" notation in var TmpDir ...]

 Len := GetLongPathName(PChar(TmpDir), nil, 0);      // Len = 37
    SetLength(TmpDir, Len - 1);                         // We want to set the len of TmpDir to 37 - 1.
    GetLongPathName(PChar(TmpDir), PChar(TmpDir), Len); // Only 32 (instead of 36) characters are copied - so we have a cropped path - But why?!

end;
[...]

This only happens on some systems and I don't know why. I found a nasty workaround for this, but I would like to know what's going on here.

Can somebody put some light on this?

like image 544
Patrick Avatar asked Aug 09 '10 13:08

Patrick


2 Answers

There is a note about this Windows API function on the Homeland Security pages:

"The return buffer for GetLongPathName() and similar functions might return a truncated path and lead to hard-to-find errors."

https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/753-BSI.html

If you have the source code, you could check if the problem described in this article exists in the Delphi 2010 implementation.

like image 77
mjn Avatar answered Oct 29 '22 06:10

mjn


What happens if you try:

var
  longpath : string;

SetLength(longpath,MAX_PATH);
SetLength(longpath, GetLongPathName(PChar(TmpDir),PChar(LongPath),MAX_PATH));

This worked for me, your version truncated the path.

like image 40
2 revs Avatar answered Oct 29 '22 07:10

2 revs