I try to call windows function inside my custom assembly function
The pseudocode would be something like:
MYFUNC
PUSH EBP
PUSH WINDOWSFUNCTIONPARAMETER
CALL [IMPORTEDWINDOWSFUNCTION]
POP EBP
RET
So I know its safe to leave this like this if I call only one function inside,
because thie stack will be restored anyway.
The problem is- why can't i add esp, 0x04 after this? - The app crashes
Im not sure if i even need to do this but imo its safer to do it after function
calls, and somehow i cant get this working inside a function
I'm gratefull for any help :)
I am not sure what you mean by "after this". Basically:
On a x86 architecture, the stack grows downwards.
Depending on your calling convention, either the caller or the callee cleans up the stack.
You are calling a windows function, therefore i assume the called function cleans up the stack parameters. This leads me to the following conclusion:
If you execute "add esp, 0x04" after your API call, "pop ebp" will receive the return address instead of the previously saved ebp register. Therefore, the final "ret" will fail and not return to the caller of MYFUNC.
If you want to perform "add esp, 0x04" to remove the function parameter: thats not necessary because the windows API has removed it already.
EDIT:
If you have a simple example like the one above, I recommend to use a debugger like ollydbg, x64dbg, etc. They are free and show you the registers, stack, etc. while your app is running.
Related
I need to use Rust code in a naked function, because the function handles an x86_64 OS context switch on a timer interrupt, and RSP should be untouched at the beginning of the function body, to save everything before moving on. I have tried to use #[naked] for this, but it is really inflexible, because I can only write assembly code in it.
If I use a stable calling convention (like extern "C"), the function makes some room for locals on the stack by subtracting whatever it's needed from RSP. This is not OK because if I want to save the pushed registers I need to know the stack pointer address of the last one, but now I am unable to, because I do not know how much does Rust subtract from RSP.
My naked function would still work with local variables if I subtract a known value (even though larger than needed) from RSP AFTER saving the stack pointer, but obviously Rust steps in my way by not letting me use anything besides ASM if I don't want a prologue.
I hear you asking, why couldn't I just push the registers after the prologue? The answer is that I need to take the saved RIP, CS, RFLAGS, RSP and SS registers too, pushed by the CPU when the timer interrupt happens, but before the prologue. I have seen that a couple of years ago Rust allowed actual code in a naked function, but now it does not, and I couldn't find a fitting replacement yet. I really think RFC #2972 made naked functions useless in most cases, because in my opinion if the developer really pays attention to what code they are writing and how, inspecting the generated assembly too, and if they make sure that the naked function only gets called from known places, it wouldn't "likely depend on undefined behavior".
What could match my requirements?
Solved it! I made the interrupt handler a naked function, that does the context save and passes the stack address to an extern "C" function through the first parameter.
#[naked]
#[no_mangle]
pub unsafe fn timer_handler_naked_scheduler() {
asm!("push r15; push r14; push r13; push r12; push r11; push r10; push r9;\
push r8; push rdi; push rsi; push rdx; push rcx; push rbx; push rax; push rbp;\
mov rdi, rsp; call scheduler_part_2;", options(noreturn));
}
#[no_mangle]
pub unsafe extern "C" fn scheduler_part_2(context: *const TaskContext) {
serial_println!("{:x?}", *context);
pic::end_of_interrupt(interrupts::HardwareInterrupt::Timer);
task::restore_context(&*context);
}
System.out.println("Check1");
expect(mockobject.function(parameters)).andReturn("hello";
System.out.println("check2***************************");
replay(mockobject);
While executing the test, the mockobject.function(parameters) executes and call goes to the method.Debugging using the system out, it checks inside the function is also displayed in console.
Why is it so? The expect() doesn't allow the call to be made to the desired function?
Assuming mockobject is a mock created with mock() or createMock() and not partialMockBuilder(), this can't happen unless function is final.
I have a tcl (expect) script to log into devices and transfer files. Unfortunately, the files are large, and during the transfer period the ssh connection ends (the files are still transferred though). So I basically have to login again before I can perform more actions on the device. Since the whole login process is long, I put it in a proc. The issue is that the proc logs into the device, but after the login, the script sends the commands to the terminal as, for some reason, the commands no longer reach the device. I cant figure out why the session I logged into in the proc does not carry over to the rest of the script.
proc login {} {
#login code - it works because I took it from the main script (which works).
# variables are all declared as global, no errors are thrown. Login is successful
}
login
send "show\r" ;# this command is not sent to the device,
#instead it prints to the terminal. When in the main script,
#these commands would not be printed to the terminal window.
Is there a command I am missing to maybe return the login session to the rest of the script? something similar to the interact command, but to the rest of the script.
This is a tricky one. The expect man page says this:
Expect takes a rather liberal view of scoping. In particular, variables read by commands specific
to the Expect program will be sought first from the local scope, and if not found, in the global
scope. For example, this obviates the need to place "global timeout" in every procedure you write
that uses expect. On the other hand, variables written are always in the local scope (unless a
"global" command has been issued). The most common problem this causes is when spawn is executed in
a procedure. Outside the procedure, spawn_id no longer exists, so the spawned process is no longer
accessible simply because of scoping. Add a global spawn_id to such a procedure.
So, add global spawn_id as the first line of the login proc
To make a procedure that evaluates code in its caller's scope, you need to use the uplevel command inside it. This lets you do what is essentially a macro very easily:
proc login {} {
uplevel {
# Put your code in here, which might look like this
spawn ssh user#host ...
expect Password:
send $thePassword\r
expect "bash$"
}
}
Then, when you use login it will work exactly like the commands you have inside the uplevel in the procedure, as if they'd been typed in place of the login call.
This isn't usually a particularly recommended approach, as it is very easy to make code that is inflexible and inclined to break unexpectedly, but in your case it is a very easy approach since you can easily guarantee to only call login at a sensible place in the overall program structure. (The uplevel command is more commonly used with scripts passed in with arguments — it's just like you're passing in a block — but that's not what you need.)
I have been working on something that checks an MySQL Database to check something - however the program stops responding because it is constantly checking the database. Is it possible to have it wait a few seconds to recheck the database? I have tried sleep() but it is giving a strange error:
A call to PInvoke function
'Game!WindowsApplication1.Form1::Sleep' has unbalanced the
stack. This is likely because the managed PInvoke signature
does not match the
unmanaged target signature. Check that the calling convention
and parameters of the
PInvoke signature match the target unmanaged signature.
I have been looking into this for quite a while and i am in a predicament. I do need the MySQL databases to be checked very often. I tried making a web browser refresh before checking it again - but it started to lag the application.
Code:
function updateit()
' SQL Code goes here, it succeeds.
updateit() ' Update it again.
return true
end
updateit()
Your code example shows a recursive function with no base case. The result of that is always a stack overflow (an uncatchable exception in .Net).
Don't call your updateit() function from within the function itself. Instead, just write a loop to call it over and over.
Try doing your checks from a separate thread. Try dragging a BackgroundWorker onto your form and putting your check in that to make your program more responsive. I've never seen that error before though. Is it System.Threading.Thread.Sleep() or something specific to VB?
Looking at your code it looks like you've got infinite recursion. That will cause a stackoverflow... try
while(true)
'SQL code
end
I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?
The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).
A trivial example, in Python:
void call_something_three_times(what_to_call, what_to_pass_it):
for i in xrange(3): what_to_call(what_to_pass_it)
# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")
This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.
In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.
Wiki says:
In computer programming, a callback is
a reference to executable code, or a
piece of executable code, that is
passed as an argument to other code.
This allows a lower-level software
layer to call a subroutine (or
function) defined in a higher-level
layer.
In common terms it is the mechanism to notify a piece of code i.e. a method, which piece of code to execute, i.e. another method, when it is needed.
Callback is related to the fact that the client of the calling function specifies a function that belongs to the client code's responsibility to the calling function to execute and this is passed as an argument.
An example is in GUIs. You pass as argument the function to be called once an event occurs (e.g. button pressed) and once the event
occurs this function is called.
This function is usually implemented by the object that originally registered for the event
Callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.
Why Should You Use Callback Functions?
A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the application's queue).
In general you supply a function as a parameter which gets called when something occurs.
In C code you will pass something that looks like this:
int (callback *)(void *, long );
meaning a function that takes two parameters, void * and long and returns an int.
With object-orientated languages the syntax is sometimes simpler. For example you might be able to construct a callback mechanism that allows the user to pass in an object that looks like a function or has an abstract method (thus wrapping a function) and context data too.
Modern languages use the term "delegate" to refer to a function "pattern". These can be used as callbacks. Some languages also use the term lambda which is essentially a function with no name, often created "on the fly" in a block of code and passed as a callback.
C++11 has introduced these into its standard.
The advantage of using a callback is that you can separate out, i.e. reduce / decouple an API from what is calling it, and to some extent vice versa, i.e. although in one place you know you are calling into the API, at the point of the "handler" it does not need to know from where it was called.
For example, you can have an API that generates objects and then "calls-back" as they get generated.
Call back means that you pass the code as a parameter. For example, imagine a button, that much show a dialog when pressed:
Button testBtn;
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onCLick() {
JOptionPane.showDialog(testBtn, "Test button pressed");
}
}
Here we tell the button what to execute, when it will be click. So, the framework will execute the passed code, when it detecs the click. Inside the framework there are some code like:
void processEvent(Event e) {
if (e.type == Event.CLICK) {
e.getComponent().getOnClickListener().onClick();
}
}
So, some basic code calls back the listener when the appropriate event happens.
PS: Pseudocode here, just do describe the idea.
A callback method is a method that gets called when an event occurs
In simple word, actually, a Callback is a reference to a function or method, which you can pass as a parameter to another function for calling it back later.
From the above figure, B_reference() is the callback method.
Source code sample:
>>> def A(A_msg,B_reference):
... # After printing message, method B is called.
... print(A_msg)
... B_reference()
...
>>> def B():
... print("Message from B")
...
>>>
>>> A("Message from A",B)
Message from A
Message from B
>>>
If you still don't understand what it is, you can check this video: