AGB  ·  Datenschutz  ·  Impressum  







Anmelden
Nützliche Links
Registrieren
Zurück Delphi-PRAXiS Programmierung allgemein Win32/Win64 API (native code) ShellExecute liefert ERROR_ACCESS_DENIED

ShellExecute liefert ERROR_ACCESS_DENIED

Ein Thema von Amateurprofi · begonnen am 23. Dez 2017 · letzter Beitrag vom 17. Jan 2018
Antwort Antwort
Fukiszo
(Gast)

n/a Beiträge
 
#1

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 15. Jan 2018, 11:48
falls das weiterhelfen kann, hier meine funktionen um etwas zu laden/starten:
sorry, ich habs nur in englisch kommentiert.

viel spass damit.

Delphi-Quellcode:
// this is my oldschool Execution function from MS-DOS now "Windownized" ;-)
// Similar as if you would execute anything on Command-Line
// Result will be greater than 31 on success
// if result is 4294967295/$FFFFFFFF than its a general error
// Example: if ExecuteCommandLine('C;\WINDOWS\TEMP\FILENAME.EXE', False) > 31 then Success := True else Success := False;
Function ExecuteCommandLine(const cmdLine: string; const ShowConsole: Boolean): Cardinal;
const
  flags: array [Boolean] of Integer = (SW_HIDE, SW_SHOWNORMAL);
var
  cmdbuffer: array [0..MAX_PATH] of Char;
begin
 Result := Cardinal($FFFFFFFF);
 GetEnvironmentVariable('COMSPEC', cmdBUffer, SizeOf(cmdBuffer));
 StrCat(cmdbuffer, ' /C ');
 StrPCopy(StrEnd(cmdbuffer), cmdLine);
 Result := WinExec(cmdbuffer, flags[ShowConsole]);
end;

// this is my "ShellExecuteEx" implementation
// Example:
// to run something type
// ExecuteShell('C;\Windows\Temp\FileName.exe','Parameters',False,False);
// to run something type and wait that it finish type
// ExecuteShell('C;\Windows\Temp\FileName.exe','-Parameters',False,True);
// ShowConsole should only be activated for Console Programs
// Returned Value is either ErrorCode from ShellExecuteEx or Init/Exit Code from "Executable"
// if result is 4294967295/$FFFFFFFF than its a general error
function ExecuteShell(const Executable, Commands: String; const ShowConsole, DoWait: Boolean): Cardinal;
 var
  ProcessInfo: TShellExecuteInfo;
 begin
  Result := Cardinal($FFFFFFFF);
  FillChar(ProcessInfo, SizeOf(TShellExecuteInfo), #0);
  with ProcessInfo do
  begin
   cbSize:= SizeOf( TShellExecuteInfo );
   fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
   Wnd := GetActiveWindow();
   lpVerb := 'open';
(* lpVerb can be one of this:
    'edit'  Launches an editor and opens the document for editing.
    'explore' Explores the folder specified by lpFile.
    'find' Initiates a search starting from the specified directory.
    'open' Opens the file, folder specified by the lpFile parameter.
    'print' Prints the document file specified by lpFile.
    'properties' Displays the file or folder's properties.*)

   lpFile:= PChar(Executable);
   lpParameters := PChar(Commands);
   lpDirectory := PChar(ExtractFilePath(Executable));
   if ShowConsole then nShow := SW_SHOWNORMAL else nShow := SW_HIDE;
  end;
  if ShellExecuteEx(@ProcessInfo) then
  begin
// if DoWait then WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
   if DoWait then while WaitForSingleObject(ProcessInfo.hProcess, 500) <> WAIT_OBJECT_0 do ProcessMessages;
   if not GetExitCodeProcess(ProcessInfo.hProcess, Result) then Result := Cardinal($FFFFFFFF);
// GetExitCodeProcess(ProcessInfo.hProcess, Result);
   CloseHandle(ProcessInfo.hProcess);
  end
  else
  begin
   Result := GetLastError;
   exit;
  end;
 end;

// this function execute any Associated Program with "Executable" as Input-Filename optional wait that it finish
// give back as Result the Init/Exit Code of Associated Program or Error Code from FindExecutable
// Example: ExecuteAssociated('ReadMe.txt', False, True);
// that would open "ReadMe.txt" in Editor and wait that Editor terminate
// ExecuteAssociated('ReadMe.html', False, False);
// that would open your Internet Browser with "ReadMe.html" and not wait
// ShowConsole should only be activated for Console Programs
// if result is 4294967295/$FFFFFFFF than its a general error
function ExecuteAssociated(const Executable: String; const ShowConsole, DoWait: Boolean): Cardinal;
var
  Prg: string;
  Security : TSecurityAttributes;
  ProcessInfo: TProcessInformation;
  StartupInfo: TStartupInfo;
 begin
  Result := Cardinal($FFFFFFFF);
  SetLength(Prg, MAX_PATH);
  Result := FindExecutable(PChar(Executable), nil, PChar(Prg));
  if Result > 32 then
  begin
   with Security do begin
    nLength := SizeOf(TSecurityAttributes);
    lpSecurityDescriptor := nil;
    bInheritHandle := False;
   end;
   SetLength(Prg, StrLen(PChar(Prg)));
   FillChar(StartupInfo, SizeOf(TStartupInfo), #0);
   with StartupInfo do
   begin
    cb := SizeOf(TStartupInfo);
    dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
    if ShowConsole then wShowWindow := SW_SHOWNORMAL else wShowWindow := SW_HIDE;
   end;
   if CreateProcess(PChar(Prg), PChar(Format('%s %s', [Prg, Executable])), @Security, @Security, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, PChar(ExtractFilePath(Executable)), StartupInfo, ProcessInfo) then
   begin
    if DoWait then while WaitForSingleObject(ProcessInfo.hProcess, 500) <> WAIT_OBJECT_0 do ProcessMessages;
// if DoWait then WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
    if not GetExitCodeProcess(ProcessInfo.hProcess, Result) then Result := Cardinal($FFFFFFFF);
// GetExitCodeProcess(ProcessInfo.hProcess, Result);
    CloseHandle(ProcessInfo.hProcess);
    CloseHandle(ProcessInfo.hThread);
   end
   else
    Result := GetLastError;
  end;
 end;

// this function execute any Executable with Commands optional wait that it finish
// give back as Result the Init/Exit Code of Executable or Error Code from CreateProcess
// example:
// to execute a executable type
// ExecuteExe('C:\WINDOWS\TEMP\FILENAME.EXE','Parameters',False,False);
// to execute a executable and wait type
// ExecuteExe('C:\WINDOWS\TEMP\FILENAME.EXE','Parameters',False,True);
// ShowConsole should only be activated for Console Programs
// DoWait will AntiFreeze and Lock your visible GUI
// this way you could still Update Display in your Application (like a text scroller, or any graphic etc)
// SideEffect: All commands that you click/do/set while in DoWait mode,
// will be executed at once when DoWait is finished.
// if result is 4294967295/$FFFFFFFF than its a general error
// Result can be Init/Exit Code of Executable
function ExecuteExe(const Executable: String; Commands: String; const ShowConsole, DoWait: Boolean): Cardinal;
  procedure WaitFor(processHandle: THandle);
  var
    Msg: TMsg;
    ret: DWORD;
  begin
    repeat
      ret := MsgWaitForMultipleObjects(1, { 1 handle to wait on }
              processHandle, { the handle }
              False, { wake on any event }
              INFINITE, { wait without timeout }
              QS_PAINT or { wake on paint messages }
              QS_SENDMESSAGE { or messages from other threads }
             );
      if ret = WAIT_FAILED then Exit; { can do little here }
      if ret = (WAIT_OBJECT_0 + 1) then
      begin
// if Msg.Message = WM_COMMAND then begin Msg.Message := WM_NULL end else
      while PeekMessage(Msg, 0, WM_PAINT, WM_PAINT, PM_REMOVE) do
// while PeekMessage(Msg, 0, WM_NULL, WM_USER, PM_REMOVE) do (* this would total un-freeze = DoWait would not lock GUI *)
          DispatchMessage(Msg);
      end;
    until ret = WAIT_OBJECT_0;
  end; { Waitfor }
var
  Security : TSecurityAttributes;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
begin
 Result := Cardinal($FFFFFFFF);
 if ((Length(Commands) > 1)and(Commands[1]<>' ')) then Commands := ' ' + Commands;
 with Security do begin
   nLength := SizeOf(TSecurityAttributes);
   lpSecurityDescriptor := nil;
   bInheritHandle := False;
 end;
  FillChar(StartupInfo, SizeOf(StartupInfo), #0);
  StartupInfo.cb := SizeOf(StartupInfo);
  StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
  if ShowConsole then StartupInfo.wShowWindow := SW_SHOWNORMAL else StartupInfo.wShowWindow := SW_HIDE;
  if CreateProcess(PChar(Executable), PChar(Commands), @Security, @Security, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, PChar(ExtractFilePath(Executable)), StartupInfo, ProcessInfo) then
  begin
   if DoWait then WaitFor(ProcessInfo.hProcess);
   if not GetExitCodeProcess(ProcessInfo.hProcess, Result) then Result := Cardinal($FFFFFFFF);
// GetExitCodeProcess(ProcessInfo.hProcess, Result);
// if Result = 0 then Result := STATUS_PENDING;
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
  end
  else
    Result := GetLastError;
end;

// this function will execute a console application
// give all console output back to "Output:PChar" parameter
// give back as Result the ExitCode of "Executable"
// ShowConsole should only be activated if you want to see a blank Console Window aslong Process is running
// WARNING: DO NOT EXECUTE CONSOLE APPLICATIONS THAT NEED KEYBOARD/MOUSE INPUT!!!
// if result is 4294967295/$FFFFFFFF than its a general error
Function ExecuteConsole(const Executable: String; Commands: String; const ShowConsole: Boolean; var Output: PChar): Cardinal;
const
 ReadBuffer = 4000;
var
  Security : TSecurityAttributes;
  ReadPipe,WritePipe : THandle;
  StartupInfo : TStartUpInfo;
  ProcessInfo : TProcessInformation;
  Buffer : Pchar;
  BytesRead : DWord;
  AppRunning : DWord;
begin
 Result := Cardinal($FFFFFFFF);
 if ((Length(Commands) > 1)and(Commands[1]<>' ')) then Commands := ' ' + Commands;
 with Security do begin
  nLength := SizeOf(TSecurityAttributes);
  lpSecurityDescriptor := nil;
  bInheritHandle := True;
 end;
 if CreatePipe (ReadPipe, WritePipe, @Security, 0) then
 begin
  Buffer := AllocMem(ReadBuffer + 1);
  FillChar(StartupInfo,SizeOf(StartupInfo), #0);
  StartupInfo.cb := SizeOf(StartupInfo);
  StartupInfo.hStdOutput := WritePipe;
  StartupInfo.hStdInput := ReadPipe;
  StartupInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
  if ShowConsole then StartupInfo.wShowWindow := SW_SHOWNORMAL else StartupInfo.wShowWindow := SW_HIDE;
  if CreateProcess(PChar(Executable), PChar(Commands), @Security, @Security, True, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, PChar(ExtractFilePath(Executable)), StartupInfo, ProcessInfo) then
  begin
   repeat
    ProcessMessages;
    Apprunning := WaitForSingleObject(ProcessInfo.hProcess,100);
   until (Apprunning <> WAIT_TIMEOUT);
// if DoWait then while WaitForSingleObject(ProcessInfo.hProcess, 500) <> WAIT_OBJECT_0 do ProcessMessages;
   repeat
    BytesRead := 0;
    ReadFile(ReadPipe,Buffer[0], ReadBuffer, BytesRead,nil);
    Buffer[BytesRead]:= #0;
   OemToChar(Buffer, Output);
   until (BytesRead < ReadBuffer);
   end;
  FreeMem(Buffer);
  if not GetExitCodeProcess(ProcessInfo.hProcess, Result) then Result := Cardinal($FFFFFFFF);
// GetExitCodeProcess(ProcessInfo.hProcess, Cardinal(Result));
  CloseHandle(ReadPipe);
  CloseHandle(WritePipe);
  CloseHandle(ProcessInfo.hThread);
  CloseHandle(ProcessInfo.hProcess);
 end;
end;

Geändert von Fukiszo (15. Jan 2018 um 11:59 Uhr)
  Mit Zitat antworten Zitat
Benutzerbild von himitsu
himitsu

Registriert seit: 11. Okt 2003
Ort: Elbflorenz
44.399 Beiträge
 
Delphi 12 Athens
 
#2

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 15. Jan 2018, 12:13
Zitat von MSDN - WinExec:
Note This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function.
Und ich könnte wetten, dass der Compiler hier ein paar Meldungen anzeigt, die jemand vergessen hat zu beheben.
> mindesten "Auf 'ExecuteCommandLine' zugewiesener Wert wird niemals benutzt"
> und seit Delphi 2009 wird es in ExecuteConsole bestimmt Meldungen bezüglich Unicode geben
Ein Therapeut entspricht 1024 Gigapeut.

Geändert von himitsu (15. Jan 2018 um 12:17 Uhr)
  Mit Zitat antworten Zitat
Fukiszo
(Gast)

n/a Beiträge
 
#3

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 15. Jan 2018, 12:38
Falls etwas mit meinem code nicht stimmen sollte, ich bin offen für Kritik
Ich nutz leider keine IDE um mir solche Meldungen anzuschauen,
ich programmier meist mit Notepad++, reicht aus für meine kleinen belange hehe
Ich hab den source mit/für Delphi 7 erschaffen, wie andere Delphi varianten reagieren weiss ich nicht und kann ich auch nicht testen, tut mir leid.
Für delphi 7 taugt der code, hat mich noch nie im stich gelassen.
WinExec ist rückwärtskompatibel, ja. Ich verstehe das zitat nicht.
Es sind ja mehrere varianten vorhanden, man kann entscheiden wie was ausgeführt wird.
Falls ich ein totes überbleibsel aus test zeiten vergessen hab zu löschen, verzeih #zwei
  Mit Zitat antworten Zitat
Benutzerbild von himitsu
himitsu

Registriert seit: 11. Okt 2003
Ort: Elbflorenz
44.399 Beiträge
 
Delphi 12 Athens
 
#4

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 15. Jan 2018, 13:37
Bis auf das Unicodeproblem, was aber zufällig keinen Bufferoverflow erzeugt, sondern eher einen Bufferunderflow, sah ich eine direkten "schwerwiegenden" Fehler.
OK, abgesehn von einer Funktion (WinExex), welche seit 23 Jahren als "nicht verwenden, nur für Abwärtskompatibilität von uraltem Code" gekennzeichnet ist.

In ExecuteConsole wird ab D2009 halt ANSI in einem Unicode-CharArray gespeichert wird, was so kaum stört, aber OemToChar wird meckern, vonwegen potentiellem Datenverlust, weil es ja einen PAnsiChar haben will, aber einen PChar/PWideChar bekommt. (der Compiler weiß nunmal nicht, dass dort wirklich nur ANSI drin ist, durch den vorherigen Fehler beim Befüllen).

Zitat:
Für delphi 7 taugt der code, hat mich noch nie im stich gelassen.
Problem ist halt, dass schon seit 9 Jahren Delphi standardmäßig mit Unicode arbeitet, was in der EDV gefühlt einem halben Jahrhundert entspricht.
Vorallem Codes, welche Andere verwenden sollen, wären gut beraten, wenn sie mit halbwegs aktuellen Delphiversionen zusammen arbeiten.
Tipp zum Testen: https://www.embarcadero.com/de/products/delphi/starter


PS: Wäre vor Jahrzehnten schon AnsiChar statt Char dort verwendet worden, wo explizit ANSI genutzt wird, dann hätte es dieses Problem nicht gegeben.
Sowas war eines der größten Gründe, welche bei Einführung von Delphi 2009 in vielen AltCodes zu Problemen führte.
> immer die "richtigen" Typen verwenden und schon minimieren sich die potentiellen Fehlerstellen.
Ein Therapeut entspricht 1024 Gigapeut.

Geändert von himitsu (15. Jan 2018 um 13:52 Uhr)
  Mit Zitat antworten Zitat
Fukiszo
(Gast)

n/a Beiträge
 
#5

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 15. Jan 2018, 15:38
UniCode, guter Rat kommt schnell, vielen Dank, das lässt sich ja problemlos justieren/nachrüsten,
zum beispiel mit einer "if compiler version >= XYZ" then pAnsiChar anstelle pChar direktive.

Danke für den Link, auf arbeit kann ich mit RADStudio XE 10.2 compilieren, ich sollt mal meine privaten codes damit checken,
danke nochmals für den Hinweis.

Für meine privaten Zwecke erstellt mir Delphi ab Version über 7 viel zu grosse Dateien (dateigröße),
deshalb bleib ich privat bei 7 und programmiere privat auch nur damit.

WinExec:
Nur weil was nicht benutzt werden sollte, sollte doch zumindest die möglichkeit gezeigt werden das solch eine funktion existiert
bzw. wie man diese veraltete funktion in der jetzt-zeit dennoch erfolgreich einsetzen könnte, oder etwa nicht?
Delphi 7 hat halt die definition in der Windows.pas datei, ich zeig wie man sie einsetzten könnte.

Danke für deine draufsicht ob fehler existieren!!!
  Mit Zitat antworten Zitat
HolgerX

Registriert seit: 10. Apr 2006
Ort: Leverkusen
984 Beiträge
 
Delphi 6 Professional
 
#6

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 15. Jan 2018, 17:35
Hmm..

Da bei Delphi 7 PChar = PAnsiChar ist, kannst Du auch eigendlich konsequent immer PAnsiChar verwenden.
Jedoch dann am Besten auch ShellExecuteA und die Strings sollte dann fix AnsiString sein.

Alternativ konsequent PWideChar in Verbindung mit ShellExecuteW und WideString.

Dann ist es Type-Konform, egal welche Delphi Version.
  Mit Zitat antworten Zitat
Benutzerbild von himitsu
himitsu

Registriert seit: 11. Okt 2003
Ort: Elbflorenz
44.399 Beiträge
 
Delphi 12 Athens
 
#7

AW: ShellExecute liefert ERROR_ACCESS_DENIED

  Alt 16. Jan 2018, 09:49
Eine nutzbare Funktion mit abgelaufenem Code neu zu verbreiten ist nicht wirklich ideal.
Am Ende kommt noch wer auf die Idee und baut es in ein neues Programm ein.


Wie gesagt, an der Stelle ist garkein IFDEF nötig.

ReadFile liefert OEM, also ANSI,
OemToChar will ANSI rein bekommen,
also braucht der Buffer immer nur ANSI zu sein und wird somit auch explizit als ANSI deklariert. (AnsiChar/PAnsiChar/AnsiString)



Da gibt es bei deinem Trainer schlimmere Problemstellen, wenn man mit Unicode kompilieren würde (ab Delphi 2009)
und Einiges (FixStr) ist in jeder Delphiversion potentiell gefährlich.

Hier Function StatusText ( StatusID : myStatusIDs ) : pChar; stdcall; klappt das mit dem Result, da es auf Konstanten zeigt, die bestehen bleiben.

Bei Function FixStr ( Input : PChar ) : PChar; stdcall; zeigt Result auf eine temporäre Variable, die beim Verlassen der Funktion freigegeben wird.
Wird der Speicher zwischenzeitlich mit irgendwas überschrieben, dann knallt es womöglich.
War die Variable der letzte genutzte Teil des Speicherblocks, dann wird der freigegeben und es knallt.
Mit etwas Glück passiert nichts und es wird anschließend auf den noch nicht freigegebenen/überschriebenen Speicherbereich zugegriffen.

MessageBox(Handle, PAnsiChar(... : Wie schon gesagt, muß alles zusammenpassen.
String > PChar > MessageBox
AnsiString > PAnsiChar > MessageBoxA
WideString/UnicodeString > PWideChar > MessageBoxW

Mein Tipp wäre hier einfach immer nur mit String/AnsiString/WideString/... zu arbeiten, vorallem bezütlich String-Verarbeitung und Speichermanagement (speichern und weitergeben der Strings)
und nur bei übergabe an die WinAPI nach PChar zu casten.
Ein Therapeut entspricht 1024 Gigapeut.

Geändert von himitsu (16. Jan 2018 um 10:09 Uhr)
  Mit Zitat antworten Zitat
Antwort Antwort

Themen-Optionen Thema durchsuchen
Thema durchsuchen:

Erweiterte Suche
Ansicht

Forumregeln

Es ist dir nicht erlaubt, neue Themen zu verfassen.
Es ist dir nicht erlaubt, auf Beiträge zu antworten.
Es ist dir nicht erlaubt, Anhänge hochzuladen.
Es ist dir nicht erlaubt, deine Beiträge zu bearbeiten.

BB-Code ist an.
Smileys sind an.
[IMG] Code ist an.
HTML-Code ist aus.
Trackbacks are an
Pingbacks are an
Refbacks are aus

Gehe zu:

Impressum · AGB · Datenschutz · Nach oben
Alle Zeitangaben in WEZ +1. Es ist jetzt 04:56 Uhr.
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024-2025 by Thomas Breitkreuz