How to evaluate functions in GDB? - function

I wonder why evaluate function doesn't work in gdb? In my source file I include, when debugging in gdb, these examples are wrong evaluations.
(gdb) p pow(3,2)
$10 = 1
(gdb) p pow(3,3)
$11 = 1
(gdb) p sqrt(9)
$12 = 0

The syntax for calling a function in gdb is
call pow(3,2)
Type
help call
at the gdb prompt for more information.

You need to tell gdb that it will find the return value in the floating point registers, not the normal ones, in addition to give the parameters the right types.
I.e.:
(gdb) p ((double(*)())pow)(2.,2.)
$1 = 4

My guess is that the compiler and linker does some magic with those particular functions. Most likely to increase performance.
If you absolutely need pow() to be available in gdb then you can create your own wrapper function:
double mypow(double a, double b)
{
return pow(a,b);
}
Maybe also wrap it into a #ifdef DEBUG or something to not clutter the final binary.
BTW, you will notice that other library functions can be called (and their return value printed), for instance:
(gdb) print printf("hello world")
$4 = 11

Actually, at least on my LINUX implementation of gcc, many of the math functions are replaced with variants specific to the types of their arguments via some fancy substitutions pulled in by math.h and bits/mathcalls.h (included from within math.h). As a consequence, functions like pow and exp are called instead as __pow or *__GI___exp (your results may vary depending on the types of the arguments and perhaps the particular version).
To identify what exactly the function is that is linked in to my code I put a break at a line where just that function is called, e.g. have a line in my code with b=exp(c);. Then I run in gdb up till that break point and then use the "step" command to enter the call from that line. Then I can use the "where" command to identify the name of the called routine. In my case that was *__GI___exp.
There are probably cleverer ways to get this information, however, I was not able to find the right name just by running the preprocessor alone (the -E option) or by looking at the assembly code generated (-s).

NAME
pow, powf, powl - power functions
SYNOPSIS
#include <math.h>
double pow(double x, double y);
You shouldn't pass an int in the place of a double
call pow( 3. , 2. )
Also, passing a single argument is not enough, you need two arguments just like the function expects
wrong: call pow ( 3. )

Related

TCL API coverage : check if a TCL command have been called and tested exaustively in a test suite

Supposing I have a TCL API like :
namespaceXY::apiXY <value> -opt1 <value1> -opt2 <value2> -opt3 <value3>
This API is used (or maybe not) in a test suite (i.e thousands of tests).
How I can check if my API have been called + tested exhaustively (all options have been called/tested).
Many thanks
You can set an execution trace on the command. That way the signature of your command won't change. So you still get the same results if any code does info args namespaceXY::apiXY. Also error messages are not affected.
proc cmdtracer {cmd op} {
global cmdtracer
dict incr cmdtracer $cmd
}
trace add execution namespaceXY::apiXY enter cmdtracer
In the end you'll have a cmdtracer dict that contains the counts of each way the command was called. You will have to figure out yourself how to check if all options have been tested. There is not enough information in your question to provide suggestions for that part.
See #SchelteBron's answer for covering commands.
Exhaustively testing all options is going to be tricky, since they could potentially all interact in complex ways and some may be mutually-exclusive (think about the standard Tcl lsearch command for example). However, auditing that all options are at least called in your own commands can be done by additional audit-only probes. Checking all the sensible combinations of them is a manual task; you probably need a coverage tool for that.
Auditing Options in C Commands
Assuming that you're dealing with the case where you've got a C command that uses Tcl_GetIndexFromObj() to parse the option name (this is common and recommended) and where you don't mind having a threading hazard (also pretty common) the idea is simple. Make an integer variable (probably with file scope) in your C code, bind it to a Tcl variable with Tcl_LinkVar(), then use the resulting index from your (successful) Tcl_GetIndexFromObj() call to set a bit in that integer variable that says that the option was parsed.
#ifdef AUDIT_OPTIONS
static int foobar_optionTracker;
#endif
// in the implementation function, called FoobarImpl here for sake of argument
int index;
if (Tcl_GetIndexFromObj(interp, objPtr, optionNameTable, "option", 0, &index) != TCL_OK) {
return TCL_ERROR;
}
#ifdef AUDIT_OPTIONS
foobar_optionTracker |= 1 << index;
// Theoretically should call Tcl_UpdateLinkedVar() here, but for audit-only its not important
#endif
switch (index) {
// ...
}
// In your command registration function
Tcl_CreateObjCommand(interp, "foobar", FoobarImpl, NULL, NULL);
#ifdef AUDIT_OPTIONS
Tcl_LinkVar(interp, "optionTracker(foobar)", (void*) &foobar_optionTracker, TCL_LINK_INT);
#endif
With that in place, you can just read the array element optionTracker(foobar) from your Tcl test control code to see what options have been parsed (assuming you're happy with a bit-mask) in the foobar command since the last time the mask was reset. You reset the mask by just writing 0 to it.
Note that there's also Tcl_GetIndexFromObjStruct() in the C API, but auditing coverage of that is not significantly different from above.
Auditing Options in Tcl Commands
The equivalent of Tcl_GetIndexFromObj() in pure Tcl code is tcl::prefix match, but that doesn't return an index. Instead it returns the full option name that you can use with switch. Auditing that is most easily done with a full array. (This is morally the same as what the version for the C code does, but adapted to work with the optimal tools in a particular language.)
proc foobar {mandatoryArgument1 mandatoryArgument2 args} {
# Parse other things here, set up the TABLE of option descriptors, etc.
foreach option $args {
set option [tcl::prefix match $TABLE $option]
if {$::DoAudit} {
set ::foobarAudit($option) 1
}
switch -- $option {
# etc...
}
}
You can use things like array size foobarAudit to count the number of options actually used, or parray foobarAudit to print out what was actually used.

Can I call a function to solve for different variables?

I have a function where I want to solve for many variables separately, do I have to write down the function every time in terms of the other variable?
x,xG,xR
y = e.^tan(x.^2)+cos.^2(x);
yG = e.^tan(xG.^2)+cos.^2(xG);
First you cannot write an expression like cos.^2(x). If x is a single variable (ie x=pi) you could write either cos(x)^2 or cos(x^2). If x is a vector (a column vector might be x=[3;4;pi] and a row vector might be x=[3,4,pi], then you might write cos(x).^2 or cos(x.^2). The role of the period (.) in octave is explained here: https://octave.org/doc/v4.0.3/Arithmetic-Ops.html
Another issue has to do with understanding the difference between an expression: x=e^tanh(y); and a function. The later is a separate chunk of code that can be invoked from anywhere in your program.
Consider this simple example
1;
function y=myfunc(x)
y=exp(tanh(x));
endfunction
## main program
xxx=pi/3;
yyy=myfunc(xxx);
printf('%7.3f %7.3f\n',xxx,yyy)
y=exp(tanh(pi/3))
comments: The '1' in the first line tells Octave that there is more to the script than just the following function: the main program has to be interpreted as well. The function line specifies that inside the function, the input will be called x and the output y, so when my function is called from main, the input is xxx(=pi/2) and the output is yyy. The last line in this tiny script is an expression that does the same thing as the function. Note that since I didn't include a semi-colon at the end of that line the result is printed out
I suggest you play with this for a while, then if you have more questions, ask them in a new question.

Why does Octave allow renaming of functions?

If I open Octave and do:
a = 1:10;
sum(a)
ans = 55
But if I then do:
sum = 30;
sum(a)
I get an error:
error: A(I): index out of bounds; value 10 out of bound 1
Octave has allowed me to change where the word "sum" points so now it's at a value not a function. Why is this allowed and shouldn't I be given a warning - is this not incredibly dangerous?
How, if I realise I've done this, do I remove the reference without closing octave and losing my workspace?
Imagine Octave does not allow variables to have the same as a function. You write a program in Octave and you have a variable named total which is not a function. Everything is fine. A new Octave version comes out and adds a function named total. Your program would stop working and you would have to rename your variables. That level of backwards incompatibility would be worse. And the issue wouldn't be limited to new Octave versions. Maybe you later decide that you want to use an Octave package which brings a whole set of new functions, one of which could clash with your variables.
However, in the upcoming release of Octave, out of bounds errors will give a hint that the variable name is shadowing a function. In Octave 4.2.1:
octave-cli-4.2.0:1> a = 1:10;
octave-cli-4.2.0:2> sum = 30;
octave-cli-4.2.0:3> sum (a)
error: sum(10): out of bound 1
While in in 4.3.0+ (which one day will become 4.4):
octave-cli-4.3.0+:1> a = 1:10;
octave-cli-4.3.0+:2> sum = 30;
octave-cli-4.3.0+:3> sum(a)
error: sum(10): out of bound 1 (note: variable 'sum' shadows function)
However, the real problem is not that variables can shadow functions. The real problem is that the syntax does not allow to distinguish between a variable and a function. Both variable indexing and function calling uses the same brackets () (other languages typically use () for functions and [] for index variables). And even if you call a function without any arguments, the parentheses are optional:
foo(1) # 1st element of foo? Or is foo a function?
foo # Is this a variable or a function call without any arguments?
foo() # idem
This syntax is mainly required for Matlab compatibility which is one of the aims of GNU Octave.
To work around this deficiency, Octave coding guidelines (guidelines required for code contributed to Octave. The Octave parser does not really care) requires functions to always use parentheses and to have a space between them and the function name:
foo (x, y); # there is a space after foo so it must be a function
foo(x, y); # there is no space, it is indexing a matrix
foo # this is a variable
foo (); # this is a function
How, if I realise I've done this, do I remove the reference without closing octave and losing my workspace?
Use the command clear sum to clear the user definition of symbol sum, which will revert it to the built-in meaning. (That is, the built-in definition will no longer be shadowed by user definition.)
As for why Octave works this way, one would have to ask the maintainers of this open-source project. Perhaps it's because Matlab works this way, and Octave strives to be as compatible as possible.

Warning for variables with function names in Matlab

Sometimes I accidentally declare variables that have the name of a function.
Here is a constructed example:
max(4:5) % 5
max(1:10)=10*ones(10,1); % oops, should be == instead of =
max(4:5) % [10 10]
At the moment I always find this out the hard way and it especially happens with function names that I don't use frequently.
Is there any way to let matlab give a warning about this? It would be ideal to see this on the right hand side of the screen with the other warnings, but I am open to other suggestions.
Since Matlab allows you to overload built-in functionality, you will not receive any warnings when using existing names.
There are, however, a few tricks to minimize the risk of overloading existing functions:
Use explicitFunctionNames. It is much less likely that there is a function maxIndex instead of max.
Use the "Tab"-key often. Matlab will auto-complete functions on the path (as well as variables that you've declared previously). Thus, if the variable auto-completes, it already exists. In case you don't remember whether it's also a function, hit "F1" to see whether there exists a help page for it.
Use functions rather than scripts, so that "mis-"assigned variables in the workspace won't mess up your code.
I'm pretty sure mlint can also check for that.
Generally I would wrap code into functions as much as possible. That way the range of such an override is limited to the scope of the function - so no lasting problems, besides the accidental assumption of course.
When in doubt, check:
exist max
ans =
5
Looking at help exist, you can see that "max" is a function, and shouldn't be assigned as a variable.
>> help exist
exist Check if variables or functions are defined.
exist('A') returns:
0 if A does not exist
1 if A is a variable in the workspace
2 if A is an M-file on MATLAB's search path. It also returns 2 when
A is the full pathname to a file or when A is the name of an
ordinary file on MATLAB's search path
3 if A is a MEX-file on MATLAB's search path
4 if A is a MDL-file on MATLAB's search path
5 if A is a built-in MATLAB function
6 if A is a P-file on MATLAB's search path
7 if A is a directory
8 if A is a class (exist returns 0 for Java classes if you
start MATLAB with the -nojvm option.)

How to define an function in the eshell (Erlang shell)?

Is there any way to define an Erlang function from within the Erlang shell instead of from an erl file (aka a module)?
Yes but it is painful. Below is a "lambda function declaration" (aka fun in Erlang terms).
1> F=fun(X) -> X+2 end.
%%⇒ #Fun <erl_eval.6.13229925>
Have a look at this post. You can even enter a module's worth of declaration if you ever needed. In other words, yes you can declare functions.
One answer is that the shell only evaluates expressions and function definitions are not expressions, they are forms. In an erl file you define forms not expressions.
All functions exist within modules, and apart from function definitions a module consists of attributes, the more important being the modules name and which functions are exported from it. Only exported functions can be called from other modules. This means that a module must be defined before you can define the functions.
Modules are the unit of compilation in erlang. They are also the basic unit for code handling, i.e. it is whole modules which are loaded into, updated, or deleted from the system. In this respect defining functions separately one-by-one does not fit into the scheme of things.
Also, from a purely practical point of view, compiling a module is so fast that there is very little gain in being able to define functions in the shell.
This depends on what you actually need to do.
There are functions that one could consider as 'throwaways', that is, are defined once to perform a test with, and then you move on. In such cases, the fun syntax is used. Although a little cumbersome, this can be used to express things quickly and effectively. For instance:
1> Sum = fun(X, Y) -> X + Y end.
#Fun<erl_eval.12.128620087>
2> Sum(1, 2).
3
defines an anonymous fun that is bound to the variable (or label) Sum. Meanwhile, the following defines a named fun, called F, that is used to create a new process whose PID (<0.80.0>) is bound to Pid. Note that F is called in a tail recursive fashion in the second clause of receive, enabling the process to loop until the message stop is sent to it.
3> Pid = spawn(fun F() -> receive stop -> io:format("Stopped~n"); Msg -> io:format("Got: ~p~n", [Msg]), F() end end).
<0.80.0>
4> Pid ! hello.
hello
Got: hello
5> Pid ! stop.
Stopped
stop
6>
However you might need to define certain utility functions that you intend to use over and over again in the Erlang shell. In this case, I would suggest using the user_default.erl file together with .erlang to automatically load these custom utility functions into the Erlang shell as soon as this is launched. For instance, you could write a function that compiles all the Erlang files in living in the current directory.
I have written a small guide on how to do this on this GitHub link. You might find it helpful and instructive.
If you want to define a function on the shell to use it as macro (because it encapsulates some functionality that you need frequently), have a look at
https://erldocs.com/current/stdlib/shell_default.html