Reset GetLastError value - delphi

Delphi Xe.
in delphi help: "...Calling this function usually resets the operating system error state..."
How to reset a current error on 0? I.e. that GetLastError=0
Example:
Try
// There is an error
except
showmessage(inttostr(getlasterror)); // Ok, getlasterror<>0
end;
....
// no errors
....
// How to reset a current error on 0?
showmessage(inttostr(getlasterror)); // Again will be <> 0

You should only be calling GetLastError when there has actually been an error. Some Windows API functions will reset the error to 0 on success, some won't. Either way, you should only interrogate the error state when you need to know the most recent error.
Note that there is a SetLastError method as well, but that doesn't help you; if you set the last error to 0, then of course GetLastError will return 0.

It's actually a Win32 call (not Delphi per se).
You can clear it with "SetLastError ()".
Here's the MSDN documentation:
http://msdn.microsoft.com/en-us/library/ms679360%28v=vs.85%29.aspx

This is an example of low quality documentation. GetLastError WinAPI function will retain its return value until next call of SetLastError so repeatedly invoking will have no effect.
SetLastError(42);
for I := 1 to 100 do
Assert(GetLastError() = 42); // all of those assertions evaluates to True
Also, in Delphi documentation GetLastError has been misplaced into exception handling routines; this is wrong too, these error handling mechanisms are unrelated to each other.
On that silly "usually" word in the reference: It happens because function used to output GetLastError return value invokes SetLastError. Eg:
SetLastError(42);
OutputDebugString(PChar(Format('GetLastError() = %d', [GetLastError()]))); // 42
OutputDebugString(PChar(Format('GetLastError() = %d', [GetLastError()]))); // 0! (ERROR_SUCCESS set by the previous OutputDebugString call)

Related

How to find if an IHTMLDocument2 is equal to IDispatch document in Delphi?

I have a TEmbeddedWB (https://sourceforge.net/projects/embeddedwb/) with an iFrame in it. I have to find out that a specific HTML Tag is inside that iFrame or not. My iFrame object is a IHTMLFrameBase2, while the Tag is a IHTMLElement. I know that the iFrame.contentWindow.document (which is a IHTMLDocument2) is the same as Tag.document. But the Tag.document is an IDispatch object, therefore the following gives a false:
if iFrame.contentWindow.document = Tag.document then ShowMessage('In iFrame')
else ShowMessage('Not in iFrame');
I know that the two object is the same, because the Watch List can show their memory address:
But I can't get their addresses from code. What I've tried:
Addr(iFrame.contentWindow.document) // Gives variable required error
#iFrame.contentWindow.document // Gives variable required error
Pointer(iFrame.contentWindow.document) //Compiles, but gives wrong address
Format('%p',[iFrame.contentWindow.document]) //Compiles, but gives EConvertError
Note: If I run line-by-line the addresses that the Watch List is showing change after EVERY line of code, no matter the code affects the WebBrowser or not.
From the rules of COM:
It is required that any call to QueryInterface on any interface for a given object instance for the specific interface IUnknown must always return the same physical pointer value. This enables calling QueryInterface(IID_IUnknown, ...) on any two interfaces and comparing the results to determine whether they point to the same instance of an object (the same COM object identity).
So, ask them both for their IUnknown interface, and compare.
var
disp: IDispatch;
doc: IHTMLDocument2;
....
if (disp as IUnknown) = (doc as IUnknown) then
....

LuaJava Error in Error Handling

I am trying to call a simple Lua function from Java using LuaJava.
calc.lua:
function foo(n) return n*2 end
Thats all there is in calc.lua and subsequent calls from command line work.
Here is the call that always has error :
L.getGlobal("foo");
L.pushNumber(8.0);
int retCode=L.pcall(1, 1,-2); // retCode value is always 5 pcall(numArgs,numRet,errHandler)
String s = L.toString(-1); // s= "Error in Error Handling Code"
I have also tried
L.remove(-2);
L.insert(-2);
Not sure why its giving any error at all or what the error is. Maybe I'm not setting up error handler correctly? So it does not make the call? After load I tried from console and can run print(foo(5)) getting back 10 as expected.
UPDATE: It looks like I need to provide an error handler on the stack. What is the signature for such an error handler and how would I place it at a point on the stack. Thanks
This is taken from the Lua reference manual -- under the C API section it says this about pcall:
When you call a function with lua_call, any error inside the called function is propagated upwards (with a longjmp). If you need to handle errors, then you should use lua_pcall:
int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
...
If errfunc is 0, then the error message returned is exactly the
original error message. Otherwise, errfunc gives the stack index for
an error handler function. (In the current implementation, that index
cannot be a pseudo-index.) In case of runtime errors, that function
will be called with the error message and its return value will be the
message returned by lua_pcall
So assuming LuaJava's API just mirrors the C API, then just pass 0 to indicate no special errfunc. Something like this should work:
int retCode = L.pcall(1, 1, 0);
String errstr = retCode ? L.toString(-1) : "";
Why on earth have you provided -2? That should not be there. You have told Lua that on the Lua stack there exists an error function that will deal with the error at the index -2, while your code does not indicate anything of the sort. pcall should only take two arguments in most cases.

SetUnhandledExceptionFilter : Continue execution 1 opcode further

I'm working on an Xbox1 emulator in Delphi, and because I run the games on the local CPU I have to create a failsafe for ring0 instructions that can occur inside the game-code.
To be able to trap these instructions, I've learned that SetUnhandledExceptionFilter can register a function that's going to be called on non-Delphi exceptions (provided I set JITEnable to a value above 0). The signature of the registered callback function reads :
function ExceptionFilter(E: LPEXCEPTION_POINTERS): Integer; stdcall;
Inside that function, I can test for illegal instructions like this :
// STATUS_PRIVILEGED_INSTRUCTION = $C0000096
if E.ExceptionRecord.ExceptionCode = STATUS_PRIVILEGED_INSTRUCTION then
One of the offending instructions is WVINDB ($0F,$09) which I can detect like this :
// See if the instruction pointer is a WBINVD opcode :
if (PAnsiChar(E.ExceptionRecord.ExceptionAddress)[0] = #$0F)
and (PAnsiChar(E.ExceptionRecord.ExceptionAddress)[1] = #$09) then
This all works (provided I run this outside the debugger) but I can't get the code to execute beyond the failing instruction - I tried it like this:
begin
// Skip the WBINVD instruction, and continue execution :
Inc(DWORD(E.ExceptionRecord.ExceptionAddress), 2);
Result := EXCEPTION_CONTINUE_EXECUTION;
Exit;
end;
Alas, that doesn't work. Actually, I would have used the real instruction pointer (E.ContextRecord.Eip), but somehow the entire ContextRecord doesn't seem populated.
What can I do so this does work as intended?
PS: When running with the debugger, I would expect this code to end up in my ExceptionFilter routine, but it doesn't - it only works without the debugger; Why's that?
DebugHook := 0; // Act as if there's no debugger
// Trigger a privileged instruction exception via this ring0 instruction :
asm
WBINVD
end;
// Prove that my exception-filter worked :
ShowMessage('WBINVD succesfully ignored!');
SetUnhandledExceptionFilter seems to be some kind of Delphi wrapper, maybe you have more luck if you do it directly?
You can register your own Exception handler with AddVectoredExceptionHandler, this will call a callback function that gives you an EXCEPTION_POINTERS structure. The Context member of that structure returns ao EIP which you can modify.
If you return EXCEPTION_CONTINUE_EXECUTION in the Callback execution continues at the given EIP.

What can cause SysFreeString to hit an Int 3 breakpoint?

I've got some code that worked fine under Delphi 2007 but breaks under D2010. It involves passing in a string, converting it to a PWideChar (specifically, a WideString pointer, not a UnicodeString pointer), doing some processing, and then calling SysFreeString on it. It works fine until a blank string is passed in, then SysFreeString breaks. It calls a bunch of things that end up raising an Int 3 breakpoint inside NTDLL.DLL. Continuing past this point results in
Project raised exception class
$C0000005 with message 'access
violation at 0x7747206e: read of
address 0x539b8dba'.
Which, if you look closely, is not the standard Access Violation message.
The top of the stack trace when it hits the Int 3 looks like this:
:774e475d ; ntdll.dll
:774afad0 ; ntdll.dll
:774e5de9 ; ntdll.dll
:774a6dff ; ntdll.dll
:76fc1075 ; C:\Windows\system32\ole32.dll
:770e443a ; C:\Windows\system32\oleaut32.dll
:770e3ea3 oleaut32.SysFreeString + 0x4a
Does anyone have any idea what's going on here?
Edit (from the comments):
This isn't a WideString, though. It's
a PWideChar generated by
StringToOleStr, and there are no
double-free errors when a non-blank
string is passed in. Unfortunately, I
can't really post a code sample
because this is a third-party
component that's under copyright. (And
I can't ask them for support because
it's no longer supported. Basically,
the whole thing's one big mess.)
I'm going to try psychic debugging. You've got some kind of heap corruption in your application and SysFreeString is the unfortunate victim (it's hard to tell without OS symbols, you should probably install the MSFT symbol packages for your OS).
Try enabling application verifier (in particular pageheap) for your app and see if it crashes earlier.
It is hard to diagnose without seeing your actual code, however WideString automatically calls SysFreeString() when it goes out of scope. It sounds like your code may be making a second call to SysFreeString() on memory that has already been freed. WideString itself has not changed at all between D2007 and D2010, but other aspects of Delphi's string handling have. Maybe you are not managing the strings correctly. Can you please show your actual code?
A simple test shows that you need to be really careful on what you do in which order.
So: even though you cannot post a small example, can you indicate what you are doing in a bit more detail?
Bad debugging; ignore the things below; see comment.
The SysFreeString() is being called at the end of the the Allocate() call, even though it returns a PWideChar:
program ShowStringToOleStrBehaviourProject;
{$APPTYPE CONSOLE}
uses
SysUtils;
function Allocate(const Value: UnicodeString): PWideChar;
begin
Result := StringToOleStr(Value);
// implicit SysFreeString(WideChars);
end;
procedure Run;
var
WideChars: PWideChar;
begin
WideChars := Allocate('Foo');
Writeln(WideChars);
end;
begin
try
Run();
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Note the console still outputs 'Foo' because the memory has not been overwritten yet.
--jeroen
It can be different reasons of such kind of errors:
You try to free with SysFreeString a memory which are allocated not with SysAllocString, but for example with CoTaskMemAlloc.
You have heap correct.
Heap corruptions are difficult to localize. The function HeapSetInformation can be very helpful. For example you can use
HeapSetInformation(NULL,HeapEnableTerminationOnCorruption,NULL,0);
Other good way is usage of HeapValidate function. For example you can define a function which verify all heaps pf the process (code in C, which can be easy rewritten in Delphi):
BOOL MyHeapValidate (void)
{
HANDLE hProcessHeaps[1024];
DWORD i;
DWORD dwNumberOfHeaps;
BOOL bSuccess = FALSE;
dwNumberOfHeaps = GetProcessHeaps (sizeof(hProcessHeaps)/sizeof(hProcessHeaps[0]),
hProcessHeaps);
if (dwNumberOfHeaps > sizeof(hProcessHeaps)/sizeof(hProcessHeaps[0])) {
MessageBox(NULL, TEXT("GetProcessHeaps()"),
TEXT("Error in MyHeapValidate()"), MB_OK);
return FALSE;
}
for (i=0; i<dwNumberOfHeaps; i++) {
bSuccess = HeapValidate (hProcessHeaps[i], 0, NULL);
if (!bSuccess)
return bSuccess;
}
return bSuccess;
}
The usage of this function can be like following:
void BadFunction(BSTR bstr)
{
LPOLESTR psz = OLESTR("Test12");
lstrcpy (bstr, psz);
}
int main()
{
LPOLESTR psz = OLESTR("Test");
BSTR bstr = SysAllocString (psz);
// verify that before call of BadFunction() all process heaps are OK!
if (!MyHeapValidate()) {
_tprintf(TEXT("heap is corrupted after the step 1.\n"));
return 1;
}
BadFunction(bstr);
if (!MyHeapValidate()) {
_tprintf(TEXT("heap is corrupted after the step 1.\n"));
return 1;
}
SysFreeString (bstr);
return 0;
}
With respect of inserting MyHeapValidate() in different suspected places you can very quickly local the place of corruption.
+1 for Larry Osterman's answer.
Some Windows memory functions behave slightly different under debugger: if they detect some kind of misuse - they trigger breakpoint to notify debugger. So, basically, your code is doing something wrong.
You can install hooks on SysAllocString/SysFreeString and redirect them to your memory manager (which should be in full debug mode) to collect more info. Or you can just pass these calls through to original functions, installing only a filter, which watches for memory actions.
And you can install debug symbols to get more info too (I'm not sure if Delphi debugger can use it, but Process Explorer - can. You can connect it to your process and see call stack).

Increasing a pointer not compiling the way I had planned

I tried to make my code as simple as possible,but I failed at it.
This is my code:
class function TWS.WinsockSend(s:integer;buffer:pointer;size:word):boolean;
begin
dwError := Send(s,buffer,size,0);
// Debug
if(dwError = SOCKET_ERROR) then
begin
dwError := WSAGetLastError;
CloseSocket(s);
WSACleanup;
case (dwerror) of
//Case statement
else
LogToFile('Unhandled error: ' + IntToStr(dwError) + ' generated by WSASend');
end;
Exit(false);
end;
// if the size of the bytes sent isn't the expected one.
while(dwError <> size) do
dwError:= dwError + Send(s,Ptr(cardinal(buffer) + dwError),size-dwError,0);
Exit(true);
end;
The error is placed at
dwError:= dwError + Send(s,Ptr(cardinal(buffer) + dwError),size-dwError,0);
Error is "Constant object cannot be passed as var parameter"
I understand I need a variable,but isn't there a way I can do it without adding one more line?
When the compiler complains about the way you're passing a parameter, the first thing you need to know is what the parameter expects. Therefore, you should go look at the declaration of Send. If looking at the declaration doesn't immediately give you an idea of what to fix, then you need to include that declaration with the code you post in your question.
I suspect that this actually has nothing to do with incrementing a pointer. Instead, the compiler is complaining about the third parameter, where you are trying to pass the expression size-dwError. I guess the parameter is declared like this:
var buffersize: Word;
The function plans on providing a new value for that parameter — that's what var means — so the thing you pass to that parameter needs to be something that can receive a value. You can't assign a new value to the result of subtracting two variables.
Take a closer look at where the compiler complained about that line. Didn't it place the cursor somewhere near the third parameter? That's a clue that the problem is there.
Decrement size, and then pass it to the function.
Dec(size, dwError);
Inc(dwError, Send(s, Ptr(cardinal(buffer) + dwError), size, 0));
Why do you care about adding another line? Have you reached your quota for the day? Lines are cheap; don't be afraid to use two to express yourself when one won't do. Likewise for variables. When your code doesn't work, saving a byte or two doesn't matter at all.
At the very least, you should have added more lines in order to track down the source of the problem. When you have one line of code that's performing several independent calculations (such as getting a new pointer value, getting a new size, and calling a function), break the line into several separate pieces. That way, if there's a problem with one of them and the compiler complains, you'll know exactly which one to blame.
Correct, this will not work as written. When your dealing with var parameters, you have to build the parameter BEFORE passing it to the procedure/function. When a Var parameter is passed, the procedure is allowed to modify it. If you attempted to copy two variables together on the call, where would this result go?
The other issue is that dwError is not delcared. A class method does NOT have access to the data elements of the object the class defines. If you drop the class, then you will have access to the data elements, but will require that the class first be created.
You should only be using class methods in places where the input and output are completely contained within the method.
How are you allocating your buffer? Internally is it an array?
Sounds like Send has a format parameter (like send (const something;size:integer)
Workaround is using pchar (entirepointerexpression)[0]

Resources