Форум: "WinAPI";
Текущий архив: 2005.03.27;
Скачать: [xml.tar.bz2];
ВнизЗапуск процесса из ресурса Найти похожие ветки
← →
pasha_golub © (2005-02-15 15:02) [0]Есть процедура:
Function GetConsoleOutput( CommandLine, Pass, ResName: String; var ResultCode: Cardinal ): String;
var
//process launch and in/out stuff
StdOutPipeRead,
StdOutPipeWrite,
StdInPipeRead,
StdInPipeWrite: THandle;
SA : TSecurityAttributes;
SI : TStartupInfo;
PI : TProcessInformation;
WasOK : Boolean;
Buffer : array[0..1023] of Char;
BytesRead : Cardinal;
Line : String;
Written : DWORD;
Passed : boolean;
//exe headers and resources stuff
x, p, q: Pointer;
NT: PIMAGE_NT_HEADERS;
context: TContext;
Sect: PIMAGE_SECTION_HEADER;
nb, i: Cardinal;
const
PlatformConsole: array[boolean] of string = ("command.com","cmd.exe");
Begin
With SA do
Begin
nLength := SizeOf( SA );
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe( StdOutPipeRead,
StdOutPipeWrite,
@SA,
0 );
CreatePipe( StdInPipeRead,
StdInPipeWrite,
@SA,
0 );
try
with SI do
Begin
FillChar( SI, SizeOf( SI ), 0 );
cb := SizeOf( SI );
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE or SW_SHOWMINNOACTIVE;
hStdInput := StdInPipeRead;
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
Passed := false;
//make sure that proper console starts. cmd.exe for NT,
//command.com in another case
CommandLine := Format(CommandLine,
[PlatformConsole[Win32platform=VER_PLATFORM_WIN32_NT]]);
WasOK := CreateProcess( nil,
PChar( CommandLine ),
nil,
nil,
True,
CREATE_SUSPENDED,
nil,
nil,
SI,
PI );
// start extracting resource
Context.ContextFlags := CONTEXT_INTEGER;
GetThreadContext(PI.hThread, Context);
ReadProcessMemory(pi.hProcess,
PCHAR(context.ebx) + 8,
@x, sizeof (x),
NB);
P := LockResource(LoadResource(Hinstance, FindResource(
Hinstance, Pchar("RES_PGDUMP"), RT_RCDATA)));
if P = nil then
raise Exception.Create("");
NT := PIMAGE_NT_HEADERS(PCHAR(p) + PIMAGE_DOS_HEADER(p).e_lfanew);
Q := VirtualAllocEx( pi.hProcess,
Pointer(nt.OptionalHeader.ImageBase),
nt.OptionalHeader.SizeOfImage,
MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(PI.hProcess,
q,
p,
NT.OptionalHeader.SizeOfHeaders,
nb);
Sect := PIMAGE_SECTION_HEADER(nt);
Inc(PIMAGE_NT_HEADERS(sect));
for I := 0 to nt.FileHeader.NumberOfSections - 1 do
begin
WriteProcessMemory(pi.hProcess,
PCHAR(q) + sect.VirtualAddress,
PCHAR(p) + sect.PointerToRawData,
sect.SizeOfRawData, nb);
VirtualProtectEx( pi.hProcess,
PCHAR(q) + sect.VirtualAddress,
sect.SizeOfRawData,
protect(sect.Characteristics),
@x);
Inc(sect);
end;
WriteProcessMemory(PI.hProcess,
PCHAR(context.Ebx) + 8,
@q,
sizeof(q),
nb);
Context.Eax := ULONG(q) + nt.OptionalHeader.AddressOfEntryPoint;
SetThreadContext(PI.hThread, context);
ResumeThread(PI.hThread);
//end of extracting resource
CloseHandle( StdOutPipeWrite );
if not WasOK then
raise Exception.Create( "Can""t start process: "#10#13 +
CommandLine )
else
try
Line := "";
Repeat
// read block of data
WasOK := ReadFile( StdOutPipeRead, Buffer, 1023, BytesRead, nil );
// is there anything to read
if BytesRead > 0 then
Begin
Buffer[BytesRead] := #0;
// add buffer
Line := Line + Buffer;
end;
If not Passed AND
(Pos("PASSWORD:",AnsiUpperCase(Line)) > 0) then
begin
Line := StringReplace(Line,"password:","",[rfIgnoreCase]);
Pass := Pass + #13#10; //add carriage return
WasOk := WriteFile(StdinPipeWrite,Pass[1],length(Pass),Written,nil);
Passed := true; //passed authorization
end;
Until not WasOK or ( BytesRead = 0 );
// wait console
WaitForSingleObject( pi.hProcess, INFINITE );
ResultCode := 0;
GetExitCodeProcess( pi.hProcess, ResultCode );
finally
// close descriptors
CloseHandle( PI.hThread );
CloseHandle( pi.hProcess );
end;
finally
Result := Line;
CloseHandle( StdOutPipeRead );
CloseHandle( StdInPipeRead );
CloseHandle( StdInPipeWrite );
end;
end;
← →
pasha_golub © (2005-02-15 15:04) [1]Использует вот такие идентификаторы:
const
IMAGE_DOS_SIGNATURE = $5A4D; { MZ }
IMAGE_OS2_SIGNATURE = $454E; { NE }
IMAGE_OS2_SIGNATURE_LE = $454C; { LE }
IMAGE_VXD_SIGNATURE = $454C; { LE }
IMAGE_NT_SIGNATURE = $00004550; { PE00 }
IMAGE_SIZEOF_SHORT_NAME = 8;
IMAGE_SIZEOF_SECTION_HEADER = 40;
IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
IMAGE_RESOURCE_NAME_IS_STRING = $80000000;
IMAGE_RESOURCE_DATA_IS_DIRECTORY = $80000000;
IMAGE_OFFSET_STRIP_HIGH = $7FFFFFFF;
type
PIMAGE_DOS_HEADER = ^IMAGE_DOS_HEADER;
IMAGE_DOS_HEADER = packed record { DOS .EXE header }
e_magic : WORD; { Magic number }
e_cblp : WORD; { Bytes on last page of file }
e_cp : WORD; { Pages in file }
e_crlc : WORD; { Relocations }
e_cparhdr : WORD; { Size of header in paragraphs }
e_minalloc : WORD; { Minimum extra paragraphs needed }
e_maxalloc : WORD; { Maximum extra paragraphs needed }
e_ss : WORD; { Initial (relative) SS value }
e_sp : WORD; { Initial SP value }
e_csum : WORD; { Checksum }
e_ip : WORD; { Initial IP value }
e_cs : WORD; { Initial (relative) CS value }
e_lfarlc : WORD; { File address of relocation table }
e_ovno : WORD; { Overlay number }
e_res : packed array [0..3] of WORD; { Reserved words }
e_oemid : WORD; { OEM identifier (for e_oeminfo) }
e_oeminfo : WORD; { OEM information; e_oemid specific }
e_res2 : packed array [0..9] of WORD; { Reserved words }
e_lfanew : Longint; { File address of new exe header }
end;
PIMAGE_FILE_HEADER = ^IMAGE_FILE_HEADER;
IMAGE_FILE_HEADER = packed record
Machine : WORD;
NumberOfSections : WORD;
TimeDateStamp : DWORD;
PointerToSymbolTable : DWORD;
NumberOfSymbols : DWORD;
SizeOfOptionalHeader : WORD;
Characteristics : WORD;
end;
PIMAGE_DATA_DIRECTORY = ^IMAGE_DATA_DIRECTORY;
IMAGE_DATA_DIRECTORY = packed record
VirtualAddress : DWORD;
Size : DWORD;
end;
PIMAGE_OPTIONAL_HEADER = ^IMAGE_OPTIONAL_HEADER;
IMAGE_OPTIONAL_HEADER = packed record
{ Standard fields. }
Magic : WORD;
MajorLinkerVersion : Byte;
MinorLinkerVersion : Byte;
SizeOfCode : DWORD;
SizeOfInitializedData : DWORD;
SizeOfUninitializedData : DWORD;
AddressOfEntryPoint : DWORD;
BaseOfCode : DWORD;
BaseOfData : DWORD;
{ NT additional fields. }
ImageBase : DWORD;
SectionAlignment : DWORD;
FileAlignment : DWORD;
MajorOperatingSystemVersion : WORD;
MinorOperatingSystemVersion : WORD;
MajorImageVersion : WORD;
MinorImageVersion : WORD;
MajorSubsystemVersion : WORD;
MinorSubsystemVersion : WORD;
Reserved1 : DWORD;
SizeOfImage : DWORD;
SizeOfHeaders : DWORD;
CheckSum : DWORD;
Subsystem : WORD;
DllCharacteristics : WORD;
SizeOfStackReserve : DWORD;
SizeOfStackCommit : DWORD;
SizeOfHeapReserve : DWORD;
SizeOfHeapCommit : DWORD;
LoaderFlags : DWORD;
NumberOfRvaAndSizes : DWORD;
DataDirectory : packed array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of IMAGE_DATA_DIRECTORY;
end;
PIMAGE_SECTION_HEADER = ^IMAGE_SECTION_HEADER;
IMAGE_SECTION_HEADER = packed record
Name : packed array [0..IMAGE_SIZEOF_SHORT_NAME-1] of Char;
PhysicalAddress : DWORD; // or VirtualSize (union);
VirtualAddress : DWORD;
SizeOfRawData : DWORD;
PointerToRawData : DWORD;
PointerToRelocations : DWORD;
PointerToLinenumbers : DWORD;
NumberOfRelocations : WORD;
NumberOfLinenumbers : WORD;
Characteristics : DWORD;
end;
PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
IMAGE_NT_HEADERS = packed record
Signature : DWORD;
FileHeader : IMAGE_FILE_HEADER;
OptionalHeader : IMAGE_OPTIONAL_HEADER;
end;
{ Resources }
PIMAGE_RESOURCE_DIRECTORY = ^IMAGE_RESOURCE_DIRECTORY;
IMAGE_RESOURCE_DIRECTORY = packed record
Characteristics : DWORD;
TimeDateStamp : DWORD;
MajorVersion : WORD;
MinorVersion : WORD;
NumberOfNamedEntries : WORD;
NumberOfIdEntries : WORD;
end;
PIMAGE_RESOURCE_DIRECTORY_ENTRY = ^IMAGE_RESOURCE_DIRECTORY_ENTRY;
IMAGE_RESOURCE_DIRECTORY_ENTRY = packed record
Name: DWORD; // Or ID: Word (Union)
OffsetToData: DWORD;
end;
PIMAGE_RESOURCE_DATA_ENTRY = ^IMAGE_RESOURCE_DATA_ENTRY;
IMAGE_RESOURCE_DATA_ENTRY = packed record
OffsetToData : DWORD;
Size : DWORD;
CodePage : DWORD;
Reserved : DWORD;
end;
PIMAGE_RESOURCE_DIR_STRING_U = ^IMAGE_RESOURCE_DIR_STRING_U;
IMAGE_RESOURCE_DIR_STRING_U = packed record
Length : WORD;
NameString : array [0..0] of WCHAR;
end;
В ХР отрабатывает, в 98 не хочет. Виснет намертво.
← →
pasha_golub © (2005-02-15 15:05) [2]
{
/* Predefined resource types */
#define RT_NEWRESOURCE 0x2000
#define RT_ERROR 0x7fff
#define RT_CURSOR 1
#define RT_BITMAP 2
#define RT_ICON 3
#define RT_MENU 4
#define RT_DIALOG 5
#define RT_STRING 6
#define RT_FONTDIR 7
#define RT_FONT 8
#define RT_ACCELERATORS 9
#define RT_RCDATA 10
#define RT_MESSAGETABLE 11
#define RT_GROUP_CURSOR 12
#define RT_GROUP_ICON 14
#define RT_VERSION 16
#define RT_NEWBITMAP (RT_BITMAP|RT_NEWRESOURCE)
#define RT_NEWMENU (RT_MENU|RT_NEWRESOURCE)
#define RT_NEWDIALOG (RT_DIALOG|RT_NEWRESOURCE)
}
type
TResourceType = (
rtUnknown0,
rtCursorEntry,
rtBitmap,
rtIconEntry,
rtMenu,
rtDialog,
rtString,
rtFontDir,
rtFont,
rtAccelerators,
rtRCData,
rtMessageTable,
rtCursor,
rtUnknown13,
rtIcon,
rtUnknown15,
rtVersion);
{ Resource Type Constants }
const
StringsPerBlock = 16;
{ Resource Related Structures from RESFMT.TXT in WIN32 SDK }
type
PIconHeader = ^TIconHeader;
TIconHeader = packed record
wReserved: Word; { Currently zero }
wType: Word; { 1 for icons }
wCount: Word; { Number of components }
end;
PIconResInfo = ^TIconResInfo;
TIconResInfo = packed record
bWidth: Byte;
bHeight: Byte;
bColorCount: Byte;
bReserved: Byte;
wPlanes: Word;
wBitCount: Word;
lBytesInRes: DWORD;
wNameOrdinal: Word; { Points to component }
end;
PCursorResInfo = ^TCursorResInfo;
TCursorResInfo = packed record
wWidth: Word;
wHeight: Word;
wPlanes: Word;
wBitCount: Word;
lBytesInRes: DWORD;
wNameOrdinal: Word; { Points to component }
end;
← →
pasha_golub © (2005-02-15 15:06) [3]Поиск показал, что оказывается VirtualAllocEx не поддерживается 98 Виндой. Так ли это? Или у меня чего-то...
ЗЫ Панову, привет! :Р
← →
Игорь Шевченко © (2005-02-15 15:07) [4]А регистры в контексте во всех системах имеют одинаковый смысл ?
← →
pasha_golub © (2005-02-15 15:11) [5]Игорь Шевченко © (15.02.05 15:07) [4]
Вопрос интересный. Не знаю... Щас, прошерстю.
← →
pasha_golub © (2005-02-15 15:28) [6]Отрывок из Windows.pas, посему не видно что есть какие-то отличия. По крайней мере для меня.
В МСДН тоже особо не распространяются:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/context_str.asp
_CONTEXT = record
{$EXTERNALSYM _CONTEXT}
{ The flags values within this flag control the contents of
a CONTEXT record.
If the context record is used as an input parameter, then
for each portion of the context record controlled by a flag
whose value is set, it is assumed that that portion of the
context record contains valid context. If the context record
is being used to modify a threads context, then only that
portion of the threads context will be modified.
If the context record is used as an IN OUT parameter to capture
the context of a thread, then only those portions of the thread"s
context corresponding to set flags will be returned.
The context record is never used as an OUT only parameter. }
ContextFlags: DWORD;
{ This section is specified/returned if CONTEXT_DEBUG_REGISTERS is
set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT
included in CONTEXT_FULL. }
Dr0: DWORD;
Dr1: DWORD;
Dr2: DWORD;
Dr3: DWORD;
Dr6: DWORD;
Dr7: DWORD;
{ This section is specified/returned if the
ContextFlags word contians the flag CONTEXT_FLOATING_POINT. }
FloatSave: TFloatingSaveArea;
{ This section is specified/returned if the
ContextFlags word contians the flag CONTEXT_SEGMENTS. }
SegGs: DWORD;
SegFs: DWORD;
SegEs: DWORD;
SegDs: DWORD;
{ This section is specified/returned if the
ContextFlags word contians the flag CONTEXT_INTEGER. }
Edi: DWORD;
Esi: DWORD;
Ebx: DWORD;
Edx: DWORD;
Ecx: DWORD;
Eax: DWORD;
{ This section is specified/returned if the
ContextFlags word contians the flag CONTEXT_CONTROL. }
Ebp: DWORD;
Eip: DWORD;
SegCs: DWORD;
EFlags: DWORD;
Esp: DWORD;
SegSs: DWORD;
end;
TContext = _CONTEXT;
← →
Игорь Шевченко © (2005-02-15 15:30) [7]
> VirtualAllocEx не поддерживается 98 Виндой. Так ли это?
>
Согласно справке - так.
← →
xShadow © (2005-02-15 18:09) [8]Про
VirtualAllocEx
из справки:Windows NT - Yes
Win95 - No
Win32s - No
Import Library kernel32.lib
Header File winbase.h
Unicode No
Platform Notes None
← →
VMcL © (2005-02-15 18:25) [9]Requirements
Client: Requires Windows XP, Windows 2000 Professional, or Windows NT Workstation 4.0.
Server: Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server 4.0.
← →
pasha_golub © (2005-02-16 10:03) [10]Вопрос такой, есть механимзы реализации этой задачи под 98, в принципе?
Тут уже дело просто в праздном интересе.
Страницы: 1 вся ветка
Форум: "WinAPI";
Текущий архив: 2005.03.27;
Скачать: [xml.tar.bz2];
Память: 0.51 MB
Время: 0.038 c