How to find out the age of a file in ASM? - windows

Greetings to all the geniuses of the digital age
Yesterday's task is still on the agenda: "Use the GetOpenFileName function to select a file. Check if the file is less than 3 days old, execute it. Otherwise, display a dialog asking to delete the file. If the user needs it, wipe." (Note: If a task is told to use a structure, it must be placed in dynamically allocated memory)"
I figured out how to open the file and now everything works like a Swiss watch. But another trouble arose.
How to determine the age of a file?
In general, I first thought to use GetFileTime to extract all data about the file time, then use FileTimeToLocalFileTime to convert it to local time, and using FileTimeToSystemTime - to system time. Then subtract one from the other using sub, and so on as per the task.
Here, the FileTimeToLocalFileTime function requires a FILETIME structure with the following parameters:
DWORD dwLowDateTime;
DWORD dwHighDateTime;
And the FileTimeToSystemTime function requires a SYSTEMTIME structure with the following parameters:
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
And how to be then? How to find the age of a file? Is there any alternative way? And if my method works, then what exactly and from what should I take it?
File.inc
include WINDOWS.inc
include user32.inc
include kernel32.inc
include comdlg32.inc
includelib user32.lib
includelib kernel32.lib
includelib comdlg32.lib
.data
Time_title db ' Lab_3',0
format db 'More than 3 days. Delete file?', 0
buf db 255 dup(0)
hFile dd 0
readed dd 0
hmem dd 0
File.asm
.386
.model flat,STDCALL
option casemap :none ;case sensitive
include Third.inc
include RADbg.inc
Mem_Alloc PROC Buf_Size:DWORD
add Buf_Size,4
invoke GlobalAlloc,GMEM_MOVEABLE or GMEM_ZEROINIT,Buf_Size
push eax
invoke GlobalLock,eax
pop [eax]
add eax,4
Mem_Alloc endp
Mem_Free PROC DATA:DWORD
mov eax,DATA
sub eax,4
mov eax,[eax]
push eax
push eax
call GlobalUnlock
call GlobalFree
Mem_Free endp
.code
Begin:
call main
invoke ExitProcess,NULL
main proc
LOCAL ftCreate, ftLocale: FILETIME;
LOCAL stUTC, stLocal: SYSTEMTIME;
invoke Mem_Alloc, 1000h
mov hmem, eax
invoke Mem_Alloc, sizeof OPENFILENAME
mov edi, eax
assume edi: ptr OPENFILENAME
xor eax, eax
mov [edi].lStructSize, sizeof OPENFILENAME
mov [edi].lpstrFile, offset buf
mov [edi].nMaxFile, 255
invoke GetOpenFileName, edi
invoke CreateFile, [edi].lpstrFile, GENERIC_READ,\
FILE_SHARE_READ, NULL, OPEN_EXISTING,\
FILE_ATTRIBUTE_NORMAL, NULL
mov hFile,eax ;
invoke GetFileTime, hFile, addr ftCreate, NULL, NULL
invoke FileTimeToLocalFileTime, addr ftCreate, addr ftLocale
invoke FileTimeToSystemTime, addr ftCreate, addr stUTC
cmp eax, 1
jz l1
invoke ReadFile, hFile, hmem, 1000h, addr readed, 0
invoke MessageBox, 0, hmem, addr Time_title, MB_OKCANCEL
jmp l2
l1:
invoke MessageBox, 0, addr format, addr Time_title, MB_OKCANCEL
cmp eax, IDOK
jne l2
invoke DeleteFile, addr [edi].lpstrFile
l2:
assume edi: dword
invoke CloseHandle, hFile
invoke Mem_Free, hmem
invoke Mem_Free, edi
ret
main endp
end Begin

As FILETIME and RtlTimeToSecondsSince1970 said, You should copy the low- and high-order parts of the file time to a ULARGE_INTEGER structure, perform 64-bit arithmetic on the QuadPart member.
So, subtract the 64-bit value in the ULARGE_INTEGER structure initialized with the file time from the 64-bit value of the ULARGE_INTEGER structure initialized with the current system time.

Related

Input Buffer holds old input despite FlushConsoleInputBuffer MASM

I wrote a program that processes the array and I need to check the correctness of the input. If you enter along with numbers and letters, then the input command loops and does not allow you to enter data, I decided to do the cleaning of the buffer before each input, but the problem remained
S1:invoke WriteConsole, h_output, ADDR ComSizeMas, Len_ComSize, ADDR nWrite, 0
invoke FlushConsoleInputBuffer,h_input
invoke crt_scanf, ADDR format_size_buf, ADDR Size_buf
CMP Size_buf,1
JL S1
CMP Size_buf,100
JG S1
scanf[_s] read data to internal crt buffer. call FlushConsoleInputBuffer have no effect on it. instead we need call fflush on stdin stream
If the stream is open for input, fflush clears the contents of the
buffer
so in c/c++ code we need fflush(__iob_func()) call.
demo example c/c++
ULONG __cdecl GetNumberc()
{
ULONG n;
while (!scanf_s("%u", &n))
{
if (fflush(__iob_func())) break;
printf("invalid number\n");
}
return n;
}
for x86 asm
extern __imp__fflush : DWORD,
__imp____iob_func : DWORD,
__imp__scanf_s : DWORD,
__imp__printf : DWORD
.const
format_number DB "%u",0
invalid_number DB "invalid number",10,0
.code
_GetNumber proc
sub esp,4
##0:
push esp
push offset format_number
call __imp__scanf_s
add esp,8
test eax,eax
jnz ##1
call __imp____iob_func
push eax
call __imp__fflush
add esp,4
test eax,eax
jnz ##1
push offset invalid_number
call __imp__printf
add esp,4
jmp ##0
##1:
mov eax,[esp]
add esp,4
ret
_GetNumber endp
for x64 asm
extern __imp_fflush : QWORD,
__imp___iob_func : QWORD,
__imp_scanf_s : QWORD,
__imp_printf : QWORD
.const
format_number DB "%u",0
invalid_number DB "invalid number",10,0
.code
GetNumber proc
sub rsp,28h
##0:
lea rdx,[rsp+30h]
lea rcx,format_number
call __imp_scanf_s
test eax,eax
jnz ##1
call __imp___iob_func
mov rcx,rax
call __imp_fflush
test eax,eax
jnz ##1
lea rcx,invalid_number
call __imp_printf
jmp ##0
##1:
mov eax,[rsp+30h]
add rsp,28h
ret
GetNumber endp

Appending character to a 'db' variable in masm assembly

I have just started learning assembly, and I am stuck.
I have a character in a WPARAM variable ( can also be DWORD ), and I have to append it to a db string. I have no idea as to how to do it.
Here is my code:
.386
.model flat, stdcall
option casemap: none
WinMain proto :DWORD,:DWORD,:DWORD,:DWORD
include C:\Program Files\masm32\include\windows.inc
include C:\Program Files\masm32\include\kernel32.inc
include C:\Program Files\masm32\include\user32.inc
include C:\Program Files\masm32\include\gdi32.inc
includelib "C:\Program Files\masm32\lib\kernel32.lib"
includelib "C:\Program Files\masm32\lib\user32.lib"
includelib "C:\Program Files\masm32\lib\gdi32.lib"
.data
cn db "Parth",0
an db "Priydarshi Singh",0
char WPARAM 21h
text db "A",0
ps DWORD ?
hin HINSTANCE ?
cmd LPSTR ?
.code
start:
invoke GetModuleHandle, 0
mov hin, eax
invoke GetCommandLine
mov cmd, eax
invoke WinMain, hin, 0, cmd, SW_SHOWDEFAULT
invoke ExitProcess, 0
WinMain proc inst:HINSTANCE, pinst:HINSTANCE, cml:LPSTR, show:DWORD
LOCAL wc:WNDCLASSEX
LOCAL msg:MSG
LOCAL hwnd:HWND
mov wc.cbSize, sizeof WNDCLASSEX
mov wc.style, CS_VREDRAW or CS_HREDRAW
mov wc.lpfnWndProc, offset WndProc
mov wc.cbClsExtra, 0
mov wc.cbWndExtra, 0
push hin
pop wc.hInstance
mov wc.hbrBackground,COLOR_WINDOW+1
mov wc.lpszMenuName,NULL
mov wc.lpszClassName,OFFSET cn
invoke LoadIcon,NULL,IDI_APPLICATION
mov wc.hIcon,eax
mov wc.hIconSm,eax
invoke LoadCursor,NULL,IDC_ARROW
mov wc.hCursor,eax
invoke RegisterClassEx, addr wc
invoke CreateWindowEx, NULL, addr cn, addr an, WS_OVERLAPPEDWINDOW, 0, 0, 1366, 750, NULL, NULL, inst, NULL
mov hwnd, eax
invoke ShowWindow, hwnd, show
invoke UpdateWindow, hwnd
.WHILE TRUE
invoke GetMessage, addr msg, NULL, 0, 0
.BREAK .IF(!eax)
invoke TranslateMessage, addr msg
invoke DispatchMessage, addr msg
.ENDW
mov eax, msg.wParam
ret
WinMain endp
WndProc proc hwnd:HWND, umsg:UINT, wp:WPARAM, lp:LPARAM
LOCAL hdc:HDC
LOCAL rect:RECT
.IF umsg==WM_DESTROY
invoke PostQuitMessage, 0
.ELSEIF umsg==WM_CHAR
push wp
pop eax
mov char, eax
; I need some code here to append 'char' to 'text'
invoke InvalidateRect, hwnd, NULL, TRUE
.ELSEIF umsg==WM_PAINT
invoke BeginPaint, hwnd, addr ps
mov hdc, eax
invoke TextOut, hdc, 0, 100, addr text, sizeof text
invoke EndPaint, hwnd, addr ps
.ELSE
invoke DefWindowProc, hwnd, umsg, wp, lp
ret
.ENDIF
xor eax, eax
ret
WndProc endp
end start
You can only append to a string if there's space available for additional characters.
You've declared text as text db "A",0, which reserves 2 bytes at text ('A' and 0), so there's no room for additional characters. If you know the maximum length that the string ever will be you can still allocate it statically; for example text db 1024 dup(0) would give you 1024 bytes of space where all bytes have the initial value 0. If you have another variable that keeps track of the current number of characters in the string you can use that to append to the string:
mov edi,text_length
mov [text + edi],al
inc dword ptr text_length
If your string can shrink as well as grow you'll have to make sure to insert a NUL terminator at right place when you "remove" characters from the string.
If you don't know the maximum length of the string in advance, or if the maximum is very large, you can allocate memory dynamically with one of the memory allocation functions provided by Windows, e.g. HeapAlloc. If the string is about to grow beyond the currently allocated size you increase the size of the allocated block with HeapReAlloc (e.g. to twice the size of the previous size).

Strange behaviour with a simple MASM32 program

I want to write a MASM program similar to the following C++ program :
#include <Windows.h>
#include <iostream>
typedef UINT (_stdcall *FuncPtr)(LPCSTR lpCmdLine, UINT uCmdShow);
int main(void)
{
HMODULE hDll = LoadLibrary(TEXT("Kernel32.dll"));
FuncPtr func_addr = reinterpret_cast<FuncPtr>(GetProcAddress(hDll, "WinExec"));
(*func_addr)("C:\\WINDOWS\\system32\\calc.exe", SW_SHOWDEFAULT);
FreeLibrary(hDll);
return (0);
}
As you can see, this code execute the microsoft calculator. I just want to do the same thing using MASM but the execution fails.
Here's the MASM source code :
.386
.model flat, stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc
include \masm32\include\masm32.inc
include \masm32\include\msvcrt.inc
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\msvcrt.lib
.data
LpFileName db "kernel32.dll", 0
procName db "WinExec", 0
display db "addr_func = 0x%x", 0
.data?
hModule HMODULE ?
procAddr FARPROC ?
.code
start:
invoke LoadLibrary, offset LpFileName
mov hModule, eax
invoke GetProcAddress, hModule, ADDR procName
mov procAddr, eax
INVOKE crt_printf, ADDR display, procAddr
mov esi, procAddr
call esi
db "C:\WINDOWS\system32\calc.exe"
invoke FreeLibrary, hModule
invoke ExitProcess, NULL
end start
The crt_printf output is correct. The same address is printed like withe the C++ program. So the address passed to call is the same one. However the execution fails.
Here's a MASM32 code which works but this time the address of the function WinExec is hardcoded like this :
.386
.model flat, stdcall
option casemap:none
include \masm32\include\windows.inc
.code
start:
jmp _Debut
_Final:
TCHAR 233
dword 42424242h
_Suite:
mov esi, 779e304eh
call esi
jmp _Final
_Debut:
xor eax, eax
push eax
call _Suite
db "C:\WINDOWS\system32\calc.exe"
end start
See the line mov esi, 779e304eh. But dynamically, there is a problem. If I disassemble the code just above we can see that the order of bytes is reversed.
8EEH047E379
Maybe it's not the case dynamically and maybe I need a keyword in the following line (between the comma and procAddr):
mov esi, procAddr
I cannot find the solution. I'm lost. Can anyone help me?
Thanks a lot in advance for your help.
The execution fails because you are not passing it's parameters.
Here you just call the function without any arguments or rather with invalid arguments (because whatever is currently on the stack will be taken and the stack is corrupted in the process).
mov esi, procAddr
call esi
You should do
push SW_SHOWDEFAULT
push offset YourPathToCalc
mov esi, procAddr
call esi
In your samplecode this is what is done here implicitly
xor eax, eax
push eax ; uCmdShow
call _Suite ; Returnadress is the address of the commandline so this is bascially the "push path"
Another thing you are missing is, that when WinExec returns, it will start executing the path in your case so you need a jmp somewhere after the call.
And as Gunner pointed out, the path must be 0 terminated.
To add to the correct answer Devolus posted, your path to calc is not NULL terminated.
This
"C:\WINDOWS\system32\calc.exe" is not correct!
Instead it should be:
"C:\WINDOWS\system32\calc.exe", 0
Also, if you are going to put strings in the code section to use, you need to give them a label in order to use them and you need to jump over them otherwise the CPU will try to execute the bytes.
INVOKE crt_printf, ADDR display, procAddr
mov esi, procAddr
push SW_SHOWDEFAULT
push offset Calc
call esi
jmp #F
Calc db "C:\WINDOWS\system32\calc.exe", 0
##:
invoke FreeLibrary, hModule
invoke ExitProcess, NULL
* EDIT *
To convert that code to Assembly using MASM, all that is needed is this:
.data
LpFileName db "kernel32", 0
procName db "WinExec", 0
Calc db "calc", 0
.code
start:
invoke LoadLibrary, offset LpFileName
push eax
invoke GetProcAddress, eax, ADDR procName
push SW_SHOWDEFAULT
push offset Calc
call eax
call FreeLibrary
invoke ExitProcess, NULL
end start

Windows (x86) Assembly Append Null Terminator To Inputted String

I am currently trying to append a null terminator to an(a?) user inputted string:
.386
.model flat, stdcall
WriteFile PROTO STDCALL:DWORD, :PTR, :DWORD, :PTR DWORD, :PTR OVERLAPPED
ReadFile PROTO STDCALL:DWORD, :PTR, :DWORD, :PTR DWORD, :PTR OVERLAPPED
GetStdHandle PROTO STDCALL:DWORD
.data
buff DB 100h DUP(?)
stdInHandle DWORD 0
bytesRead DWORD ?
.code
start:
;read string from stdin
INVOKE GetStdHandle, -10
MOV stdInHandle, eax
INVOKE ReadFile, stdInHandle, BYTE PTR[buff], 100, ADDR bytesRead, 0
;append null terminator on CR,LF
MOV eax, bytesRead
MOV edx, BYTE PTR[buff]
SUB eax, 2
AND BYTE PTR [eax+edx], 0
RET
END start
It refuses to assemble at MOV edx, BYTE PTR[buff] and gives me an error:
error: Invalid combination of opcode and operands (or wrong CPU setting).
So I'm assuming I cannot MOV the value of BYTE PTR[buff] into register edx. So I can't even begin to test if this method of trying to apply a NULL terminator to a string will even work.
My question is, what is wrong with the above code (should I use a different register instead of edx?)
What is the best way to apply a NULL terminator to the string?
You can't move a byte value into a dword sized register. You either need to use a byte sized register such as dl, or zero-extend it with movzx. As you are working with bytes, I suggest you go with the first option.
When I had to create methods for strings without using anything from good ole Irvine, I got the length of the string, incremented what the length returned as (you need to include an extra +1 for the null-terminator) by 1, and then added 0h to the end of the string where the pointer was where the counter is.
MOV EAX, SIZEOF lpSourceString + 1 ; Get the string length of string, add 1 to include null-terminator
INVOKE allocMem, EAX ; Allocate memory for a target to copy to
LEA ESI, [lpSourceString] ; put source address in ESI
MOV EDI, EAX ; copy the dest address to another register we can increment
MOV ECX, SIZEOF lpSourceString ; Set up loop counter
We have the size of the string. Now we can add the null-terminate to it. To do that, we need to make sure that we have a pointer looking at the end of the string. So if we have a method that returns a string in EAX, EAX needs to point to the start of the string (so we leave the allocMem unmodified, instead incrementing a copy in EDI). Let's say that we are putting characters in a string:
nextByte: ; Jump label, get the next byte in the string until ECX is 0
MOV DL, [ESI] ; Get the next character in the string
MOV [EDI], DL ; Store the byte at the position of ESI
INC ESI ; Move to next char in source
INC EDI ; INCrement EDI by 1
loop nextByte ; Re-loop to get next byte
MOV byte ptr[EDI], 0h ; Add null-terminator to end of string
; EAX holds a pointer to the start of the dynamically-allocated
; 0-terminated copy of lpSourceString
MOV requires the byte ptr size specifier because neither the [EDI] memory operand nor the 0 immediate operand would imply a size for the operation. The assembler wouldn't know if you meant a byte, word, or dword store.
I have this in my MASM, but I use a String_length stdcall method I had written due to a class requirement.
This is so common that the MASM32 runtime supplies this functionality as part of its runtime. All you need to do is include the relevant code:
include \masm32\include\masm32rt.inc
Then use the StripLF function as so:
invoke StripLF, addr buff
To fix your current problem (if you want to do it manually) , you need to move the address of buff to edx instead.
mov edx, offset buff

Any Way To Make This Snippet More Efficient?

I just started playing around with MASM styled assembly and after playing around long enough managed to make a sort of loop. This is just from tinkering so I was wondering if anybody could give me any insight and explanation on if this code is inefficient or how it can be improved.
.386
.model flat, stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\masm32.inc
include \masm32\include\user32.inc
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\user32.lib
.data
MsgBxTitle db "Loop Step", NULL
.data?
Buff dd ?
MsgBxBody dd ?
.code
start:
XOR eax,eax
MOV Buff, eax
lp:
invoke dw2hex, Buff, addr MsgBxBody
invoke MessageBox, NULL, addr MsgBxBody, addr MsgBxTitle, MB_OKCANCEL
.IF eax==IDCANCEL
RET
.ENDIF
INC Buff
CMP Buff,10
JL lp
RET
end lp
invoke ExitProcess, NULL
end start
You can shave 16 bytes off the code this way. Zero a register and push that for zero. Use a register for you dword buffer. Using registers Assemble to smaller opcodes and are "faster" than memory (labels).
I personally don't like/use the high level stuff.
start:
xor edi, edi
xor esi, esi
mov ebx, 10
lp:
push offset MsgBxBody
push edi
call dw2hex
push MB_OKCANCEL
push offset MsgBxTitle
push offset MsgBxBody
push esi
call MessageBox
test eax, IDCANCEL
jnz Done
inc edi
dec ebx
jns lp
Done:
push esi
call ExitProcess
end start
When displaying your results with MessageBox, I don't see that efficiency or performance is relevant. I have questions about your control flow. Where is "RET" intended to return to? When, if ever, is ExitProcess invoked? I don't know what "end lp" does, so perhaps I'm missing something...
Best,
Frank

Resources