Why does thunk not demand as many parameters as function? - ghidra

I'm dealing with the following thunk in Ghidra:
Now when I double-click the thunked function, Ghidra takes me to the real function, and I can see that it expects 2 parameters ("param_1" and "param_2").
Why is it allowed to call it with a single parameter ("&LAB_30007a18") only?
Thank you!

You showed the definition for the thunked function, but not the thunk. The thunk's signature may only include 1 param instead of 2. If so, fix that. Otherwise, the Decompiler may be confused by something earlier in the calling function (e.g., the 2nd param passed to the thunk is the return value from a previous call to a function that is currently defined as having a void return type).
The Decompiler can produce odd-looking results when functions are defined with incorrect parameters or return types.

Related

How do I assign to member of type std::function<bool(wxString&)>

I have a custom Dialog class (derived from wxDialog). I want to add a setter so you can set a call back function MyDialog::m_f with some function of type std::function<bool(wxString&)>.
Later, the dialog will call this function.
I want to be able to pass in a lambda function (otherwise I could solve my problem with ordinary function pointers).
It must also be possible to call this setter multiple times, the last set value for m_f should be valid, thus erasing any previous set values (the value being a new function).
But, if I declare the member m_f, does it have to be initialized in the initializer list in the constructor?
For my use case that would not really work. I have to be able to set MyDialog::m_f after the dialog has been constructed (but before ShowModal is called).
Should my member m_f be a (unique) pointer to a std::function<bool(wxString&)>, so it can be set to nullptr in MyDialog::MyDialog?
My basic problem is I do not fully understand std::function. How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later? What does it mean to have a variable like described which is uninitialized? How can I test whether it is (un)assigned? Is it at all possible to delay this assignment, that is: have a separate declaration and later initialization, or should a variable of std::function<...> be initialized immediately (like a const or reference)?
Thanks for any help.
BTW, the language is C++11 and we can't upgrade due to restrictions at work.
How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later?
std::function has a default constructor that results in an "empty" instance. In your case, just declare the data member std::function<...> m_f and don't explicitly initialize it.
What does it mean to have a variable like described which is uninitialized?
That depends on the type of the variable. In the std::function, it's simply unusable. If you try to inoke an empty std::function, and exception will be thrown.
How can I test whether it is (un)assigned?
std::function has an explicit conversion operator to bool. It evaluates to true when the object is non-empty, i.e.
if (m_f)
m_f(/* parameters... */);
else
; // do nothing, not set yet
How can you make a variable of some std::function<...> type and assign a value (concrete function) to it later?
If you want to later assign lambda expression to the function object through a setter, you can turn this member function into a template, e.g.
template<class Fct>
void setCallback(Fct&& f)
{
m_f = std::forward<Fct>(f);
}
Another option is to pass a std::function with the desired signature to a non-template member function.

Does boost::bind make a copy of a member function

Boost::bind documentation states:
By default, bind makes a copy of the provided function object. boost::ref and boost::cref can be used to make it store a reference to the function object, rather than a copy.
I am seeing excessive news and deletes in my code when I use boost::bind with a pointer to a member function. The documentation is unclear to me whether boost::bind(&classname::functionname,...) makes a copy of the function.
Or maybe the question makes no sense and as it is converting a member function into a function object it obviously has to new the function object.
So my question is there a way I can bind to a member function and avoid the new and delete?
According to my experiments (boost 1.49), boost::bind does not use dynamic memory for its own implementation. With this code
#include <boost/bind.hpp>
int f(int a , int b) {
return a>b ? a+b : a-b;
}
int main()
{
auto a = boost::bind(f, _1, 2);
return a(0);
}
I tried breaking on operator new variants in gdb and it didn't fire. So I suspect your problem is actually that boost::bind is making copies of either the bound arguments (compare the output of these two snippets) or the call arguments. Search for something among these that could allocate memory while copying, and try to get rid of it.
If you're using a C++11 compiler, you can get away with boost::bind completely and use a lambda function instead. The example would be transformed to
auto a = [&](int a1) { return f(a1, 2); }
That would only copy if you'd capture objects by value.
EDIT: With the code you posted, try changing the line in question to
TConstIterator pIt = std::find_if(rtContainer.begin(), rtContainer.end(),
boost::bind(&TValueType::bSameSocket, boost::cref(rtData), _1));
^^^^^^^^^^^
That should make it better; report if it doesn't.
What gets copied is the pointer to that method, so no new/delete involved. What bind returns is a function object that gets created and destroyed at some point, but again no dynamic memory allocation.
As far as I can tell if you use boost::bind in code such as to create a function object to act as the predicate in a find_if the function object is newed and deleted and this is what was causing my code to run slowly.
My question was: is there a way I can bind to a member function and avoid the new and delete?
I worked around the boost::bind by iterating through the list myself calling a member function through a member function pointer.
The type of the member pointer function is derived from template parameters for the list and its stored data types, but the same technique works whether the types are templated or not.
This solution reduced the user perception of response for a particular action from 5 minutes to effectively immediately.

Returning both computation result and status. Best practices

I was thinking about patterns which allow me to return both computation result and status:
There are few approaches which I could think about:
function returns computation result, status is being returned via out parameter (not all languages support out parameters and this seems wrong, since in general you don't expect parameters to be modified).
function returns object/pair consisting both values (downside is that you have to create artificial class just to return function result or use pair which have no semantic meaning - you know which argument is which by it's order).
if your status is just success/failure you can return computation value, and in case of error throw an exception (look like the best approach, but works only with success/failure scenario and shouldn't be abused for controlling normal program flow).
function returns value, function arguments are delegates to onSuccess/onFailure procedures.
there is a (state-full) method class which have status field, and method returning computation results (I prefer having state-less/immutable objects).
Please, give me some hints on pros, cons and situations' preconditions of using aforementioned approaches or show me other patterns which I could use (preferably with hints on preconditions when to use them).
EDIT:
Real-world example:
I am developing java ee internet application and I have a class resolving request parameters converting them from string to some business logic objects. Resolver is checking in db if object is being created or edited and then return to controller either new object or object fetched from db. Controller is taking action based on object status (new/editing) read from resolver. I know it's bad and I would like to improve code design here.
function returns computation result, status is being returned via out
parameter (not all languages support out parameters and this seems
wrong, since in general you don't expect parameters to be modified).
If the language supports multiple output values, then the language clearly was made to support them. It would be a shame not to use them (unless there are strong opinions in that particular community against them - this could be the case for languages that try and do everything)
function returns object/pair consisting both values (downside is that
you have to create artificial class just to return function result or
use pair which have no semantic meaning - you know which argument is
which by it's order).
I don't know about that downside. It seems to me that a record or class called "MyMethodResult" should have enough semantics by itself. You can always use such a class in an exception as well, if you are in an exceptional condition only of course. Creating some kind of array/union/pair would be less acceptable in my opinion: you would inevitably loose information somewhere.
if your status is just success/failure you can return computation
value, and in case of error throw an exception (look like the best
approach, but works only with success/failure scenario and shouldn't
be abused for controlling normal program flow).
No! This is the worst approach. Exceptions should be used for exactly that, exceptional circumstances. If not, they will halt debuggers, put colleagues on the wrong foot, harm performance, fill your logging system and bugger up your unit tests. If you create a method to test something, then the test should return a status, not an exception: to the implementation, returning a negative is not exceptional.
Of course, if you run out of bytes from a file during parsing, sure, throw the exception, but don't throw it if the input is incorrect and your method is called checkFile.
function returns value, function arguments are delegates to
onSuccess/onFailure procedures.
I would only use those if you have multiple results to share. It's way more complex than the class/record approach, and more difficult to maintain. I've used this approach to return multiple results while I don't know if the results are ignored or not, or if the user wants to continue. In Java you would use a listener. This kind of operation is probably more accepted for functinal languages.
there is a (state-full) method class which have status field, and
method returning computation results (I prefer having
state-less/immutable objects).
Yes, I prefer those to. There are producers of results and the results themselves. There is little need to combine the two and create a stateful object.
In the end, you want to go to producer.produceFrom(x): Result in my opinion. This is either option 1 or 2a, if I'm counting correctly. And yes, for 2a, this means writing some extra code.
My inclination would be to either use out parameters or else use an "open-field" struct, which simply contains public fields and specifies that its purpose is simply to carry the values of those fields. While some people suggest that everything should be "encapsulated", I would suggest that if a computation naturally yields two double values called the Moe and Larry coefficients, specifying that the function should return "a plain-old-data struct with fields of type double called MoeCoefficient and LarryCoefficient" would serve to completely define the behavior of the struct. Although the struct would have to be declared as a data type outside the method that performs the computation, having its contents exposed as public fields would make clear that none of the semantics associated with those values are contained in the struct--they're all contained in the method that returns it.
Some people would argue that the struct should be immutable, or that it should include validation logic in its constructor, etc. I would suggest the opposite. If the purpose of the structure is to allow a method to return a group of values, it should be the responsibility of that method to ensure that it puts the proper values into the structure. Further, while there's nothing wrong with a structure exposing a constructor as a "convenience member", simply having the code that will return the struct fill in the fields individually may be faster and clearer than calling a constructor, especially if the value to be stored in one field depends upon the value stored to the other.
If a struct simply exposes its fields publicly, then the semantics are very clear: MoeCoefficient contains the last value that was written to MoeCoefficient, and LarryCoefficient contains the last value written to LarryCoefficient. The meaning of those values would be entirely up to whatever code writes them. Hiding the fields behind properties obscures that relationship, and may impede performance as well.

Boost::asio async_wait handler signature

I am going through the boost::asio examples. I am looking at
Example 4
What is confusing is that, the WaitHandler in this example has the signature
void print (this)
But the async_wait call expects a handler whose
function signature of the handler must be:
void handler(
const boost::system::error_code& error // Result of operation.
);
Source: Boost documentation
Since the parameter type is part of a function's signature, why in the example above, async_wait accepts a handler whose parameter is not of type boost::system::error_code?
THanks.
As you correctly observe, the async_wait method accepts a handler function which takes one parameter (const boost::system::error_code&). But in the Timer.4 example, the call to async_wait is passed via boost bind as follows:
timer_.async_wait(boost::bind(&printer::print, this));
The boost::bind returns a function object which refers to method print for class printer for the object referenced by this. This function object is called by the async_wait method with the error parameter (since that is the signature it expects). But the error parameter is silently ignored because it is not referenced by the bind.
The official boost::bind documentation provides more details on boost::bind. See also the article How the Boost Bind Library Can Improve Your C++ Programs (there are probably many more articles available but I found this one very useful).
You specify in the call to async_wait what parameters your callback function takes, using placeholders. Check the sentence just above the async_wait call on the page you linked to:
You will note that the boost::asio::placeholders::error placeholder is
not specified here, as the print member function does not accept an
error object as a parameter.
Search for "placeholder" in this example and you'll see how to do it.

MATLAB functions refusing to function depending on placement

I've written a very simple GUI in MATLAB that will convert temperatures. It is meant to serve as a tutorial for a class of students. A strange thing has happened though. As with any MVC design pattern, there is a model object, a view object and a controller function. In order to set the output field of the GUI (the converted temperature), you can run this line in the controller function itself:
set(views.outputTextField,'string',num2str(round(model.outTemp)));
where views.outputTextField is a GUI text field to display the converted temperature and model.outTemp is the converted temperature. Pretty straightforward. The views object has references to all the GUI uicontrols and this updates the field with the newly converted temperature in the model object.
However, I would rather have view functions in the view object, so I attempted to create a line like this:
views.updateOutputField = #()set(views.outputTextField,'string',...
num2str(round(model.outTemp)));
Same line as before, just that now it is an anonymous function in the view object. This way I could call the function from the controllers as simply views.updateOutputField(); and keep the view logic out of the controller logic. But this method won't work! (It will work with the get() function.)
Instead I have to do the following:
views.updateOutputField = #updateOutputField
function updateOutputField()
set(views.outputTextField,'string',num2str(round(model.outTemp)));
end
By separating out the function (redundantly) instead of just using an anonymous function, it works again. What!? This makes no sense to me. The view and model objects are global and the anonymous function works with get(). Does anyone have a clue what's going on here?
Both approaches are not equivalent. Values in the body of anonymous function (aka lambda) are being frozen, see example below:
>> ii = 2;
>> val = #() ii+2;
>> val()
ans =
4
>> ii=5;
>> val()
ans =
4
You can do following to make it work:
views.updateOutputField = #(outTemp) ...
If you want to know how MATLAB captures the workspace context, use function FUNCTIONS on anonymous function.
Your example is a little bit more complicated because your view and model exist in the nested workspace but the essence is the same.
As side note: kudos for teaching also an important design pattern (MVC) in Matlab class!
Mikhail has the right answer. I'll elaborate a bit...
From the MATLAB documentation for anonymous functions:
Anonymous functions commonly include
two types of variables:
Variables specified in the argument
list. These often vary with each
function call.
Variables specified in the body of the
expression. MATLAB captures these
variables and holds them constant
throughout the lifetime of the
function handle.
When you make a call to SET inside your anonymous function, you access fields of your two structure variables views and model. These values are held fixed at what they were when the anonymous function was created. That doesn't matter for the graphics handles stored in views, since these never change (unless you are deleting and recreating graphics objects). This is why calling GET in your anonymous function works fine, since it only uses the unchanged graphics handles in views. However, the values in model change, so you would want to pass them in to the anonymous function as an argument. For example:
views.updateOutputField = #(model) set(views.outputTextField,'String',...
num2str(round(model.outTemp)));
When you instead create your updateOutputField function, you are creating a nested function. Nested functions have access to the variables that exist in the outer function within which they are nested, which is why you don't have to pass views and model as arguments. When these variables change in the outer function, that change is visible in the nested function as well (unlike anonymous functions).

Resources