Making sense of arguments to a function template - c++

Reading a code base and desperately trying to understand it.
template<typename selection>
void run_z_p_selection(xml_config &my_config){
system::start();
std::shared_ptr<selection> my = std::make_shared<selection>(my_config, machine, enable, timet);
system::addSelection(my);
}
(xml_config &my config){}. Is this an object being created as an address? I don't understand.
Where are all the (my_config, machine, enable, timet) coming from if they are not input arguments to the function?

That is something called pass by reference
It's hard to tell without seeing the whole code base, but it looks like those are global variables. Maybe system::start() sets them up?

xml_config &my_config is a reference: http://en.cppreference.com/w/cpp/language/reference A reference is an:
Alias to an already-existing object or function
my_config is the argument passed in that is an xml_config&. machine, enable, and timet are all variables which are in scope for your function. And that could mean a lot of things.
If run_z_p_selection is a method, these could be member variables.
Because run_z_p_selection is a template I assume that it is defined in your header, so you shouldn't need to look in included source files for these, only in included headers.
The variables must either be defined in run_z_p_selection's namespace, a containing namespace, or the global namespace.
If you have Visual Studio you can select the variable you want to know about and press: Ctrl + F12 to jump to where it is defined in your project.

Related

Function and stored procedure can't have same name?

I wrote a function:
function getArtists(where='', artistactive = true){
//yadayada
return artists;
}
and included it, in a template, after the following
<cfstoredproc datasource="#request.dsn#" procedure="GetArtists">
<cfprocresult name="GetArtists">
</cfstoredproc>
This produces an error:
Routines cannot be declared more than once. The routine getArtists has
been declared twice in different templates
Ok, so question 1: ColdFusion thinks that a function and a stored procedure are both 'routines' and cannot be declared twice?
So, next thing I did was to include my functions template before the stored procedure... and it seems to be fine, with that.
Question 2: what gives?
You should believe the error. In testing your code I get no error when declaring the function and then calling a stored proc of the same name. when I dump out the variables scope using <cfdump var="#variables#"> I only see the result set (not the function) because the function has been overwritten by the result set. If I try to call the function after declaring the function and then overwriting it I get "Incorrect entity type for being a function" as my error.
Remember that the CF Compiler goes through your code and compiles UDFs and components first. They are not compiled at runtime. The error you are referencing occurs during the compile, not the runtime. For this reason I think it is more likely that your UDF routine is actually being included more than once. Take a look at the debug information at the bottom and search for that file and see if this is the case - or examine custom tag calls and other ways where files are doubled.
Advice: As a rule UDF should be declared in their own space (onRequest() is a good spot for it) and should be protected from this sort of thing. I use a variable like "lib" and store my functions (which are members of objects just like in Java) as lib.function1(), lib.function2(). The way you are doing it leads to unpredictability. That last is just my Opinion - trying to help. :)

C++: Can function pointers be traced back to the original function before compilation without looking at the function name?

I want to set up a server on which students can upload and run code for a course. However, I don't want them to access various functions, like system(), which could allow bad access to my server. I can search the pre-processor output for an explicit function call, but if the user makes a function pointer like this:
int (*syst)(const char*) = system;
syst("rm *");
I'm still open to the threat. However, I can't just search for the string "system", for example, since it's otherwise a valid name - if the student didn't include cstdlib, they could use that name as a variable name. Since this is a beginning programming course, having a blacklist of variable names ten miles long is a bad idea.
Is there a way to define the functions other than by name and allow me to search for that other designation before compiling their code?
By far the easiest solution is to compile the code - that's pretty harmless - and then look at the actual library imports. Users may have defined their own system, but that wouldn't cause system to be imported from glibc.
Showing imported symbols
The main reason you can't look at the raw source code is because #define allows malicious users to hide the blacklisted symbol names. But there are plenty of other possibilities to do that, including
auto hidden = &sys\
tem;
So you need some processing of the source, and it's probably easiest just to fully process the whole source.
I would also suggest running this inside a chroot as a non-privileged user. It's lighter weight than a VM.
Alas, it's not possible (easily) to get a functions name from a pointer
How to get function's name from function's pointer in C? That question is from a C perspective, but it's the same problem, essentially.

Changing what a function points to

I have been playing around with pointers and function pointers in c/c++. As you can get the adress of a function, can you change where a function call actually ends?
I tried getting the memory adress of a function, then writing a second functions adress to that location, but it gave me a access violation error.
Regards,
Function pointers are variables, just like ints and doubles. The address of a function is something different. It is the location of the beginning of the function in the .text section of the binary. You can assign the address of a function to a function pointer of the same type however the .text section is read only and therefore you can't modify it. Writing to the address of a function would attempt to overwrite the code at the beginning of the function and is therefore not allowed.
Note:
If you want to change, at runtime, where function calls end up you can create something called a vritual dispatch table, or vtable. This is a structure containing function pointers and is used in languages such as c++ for polymorphism.
e.g.:
struct VTable {
int (*foo)(void);
int (*bar)(int);
} vTbl;
At runtime you can change the values of vTbl.foo and vTbl.bar to point to different functions and any calls made to vTbl.foo() or .bar will be directed to the new functions.
If the function you're trying to call is inlined, then you're pretty much out of luck. However, if it's not inlined, then there may be a way:
On Unix systems there's a common feature of the dynamic linker called LD_PRELOAD which allows you to override functions in shared libraries with your own versions. See the question What is the LD_PRELOAD trick? for some discussion of this. If the function you're trying to hijack is not loaded from a shared library (i.e. if it's part of the executable or if it's coming from a statically linked library), you're probably out of luck.
On Windows, there are other attack vectors. If the function to be hooked is exported by some DLL, you could use Import Address Table Patching to hijack it without tinkering with the code of the function. If it's not exported by the DLL but you can get the address of it (i.e. by taking the address of a function) you could use something like the free (and highly recommended) N-CodeHook project.
In some environments, it is possible to "patch" the beginning instructions of a function to make the call go somewhere else. This is an unusual technique and is not used for normal programming. It is sometimes used if you have an existing compiled program and need to change how it interacts with the operating system.
Microsoft Detours is an example of a library that has the ability to this.
You can change what a function pointer points to, but you can't change a normal function nor can you change what the function contains.
You generally can't find where a function ends. There's no such standard functionality in the language and the compiler can optimize code in such ways that the function's code isn't contiguous and really has not a single point of end and in order to find where the code ends one would need to either use some non-standard tools or disassemble the code and make sense of it, which isn't something you can easily write a program for to do automatically.

False positive Error 503 for call to template function

I have some code that PC-Lint is giving me Error 503: Boolean argument to relational on. It is a call to a template function which is defined like this:
template <typename ITypeToUse>
void ShowWindowEx(
HWND hWnd,
int nCmdShow,
ITypeToUse *pControl);
The call itself looks like this:
ShowWindowEx<IActualType>(this->GetWndHandle(), SW_SHOW, m_spControl);
Appearantly, the part ShowWindowEx<IActualType>(...) is interpreted as Identifier1 < Identifier2 > Expression... PC-Lint seems not to be aware that ShowWindowEx is a template function which requires a type in angled brackets and tries its best to interpret it as a boolean expression.
I am aware that I can simply tell lint to ignore this error for this line (though in reality it's about 30 lines), but I'd like to prevent this from happening again. Also, as far as I know, PC-Lint should be capable of handling template function calls, any idea why this is not the case here?
The declaration is inside a class in a header and the call is in another member function of that class, which is declared right before ShowWindowEx is. The implementation of both member functions happens in the .cpp file in the same order, so the call to ShowWindowEx happens before its implementation. Is it possible PC-Lint just ignored the header?
EDIT:
I now changed the function prototype to:
template <typename IPointerToUse>
void ShowWindowEx(
HWND hWnd,
int nCmdShow,
IPointerToUse pControl);
So the template will take care of the type being a pointer. Thanks DeadMG for the suggestion. Question still stands, as I see no reason the above should not have worked, but it works this way as well.
503 normally is a C warning, not C++. Can it be that your C++ file containing the template function call is considered a C file by Lint, maybe by using *.C (capital letter) on a Windows machine? or using a non-standard extension?
I've seen this happen when using Samba to Lint a Unix C++ program on a Windows PC Lint installation.
If this is still an issue, look at the output lines indicating the module names like --- Module: ..., and look at the file type between parentheses. If switched off, you may need to use -vm (default).
If this is the case, I would expect many more warnings around the call, but interpreting the template <...> as two comparison operators would legitimately provoke this warning.
Other than that, the line you presented - without context - does not give any reason why 503 could be applicable here.
Perhaps the reason is that there is already a definition of ShowWindowEx (one that is no template definition) in the Windows headers.
Perhaps you should try to rename your function.

How do I make an unreferenced object load in C++?

I have a .cpp file (let's call it statinit.cpp) compiled and linked into my executable using gcc.
My main() function is not in statinit.cpp.
statinit.cpp has some static initializations that I need running.
However, I never explicitly reference anything from statinit.cpp in my main(), or in anything referenced by it.
What happens (I suppose) is that the linked object created from statinit.cpp is never loaded on runtime, so my static initializations are never run, causing a problem elsewhere in the code (that was very difficult to debug, but I traced it eventually).
Is there a standard library function, linker option, compiler option, or something that can let me force that object to load on runtime without referencing one of its elements?
What I thought to do is to define a dummy function in statinit.cpp, declare it in a header file that main() sees, and call that dummy function from main(). However, this is a very ugly solution and I'd very much like to avoid making changes in statinit.cpp itself.
Thanks,
Daniel
It is not exactly clear what the problem is:
C++ does not have the concept of static initializers.
So one presume you have an object in "File Scope".
If this object is in the global namespace then it will be constructed before main() is called and destroyed after main() exits (assuming it is in the application).
If this object is in a namespace then optionally the implementation can opt to lazy initialize the variable. This just means that it will be fully initialized before first use. So if you are relying on a side affect from construction then put the object in the global namespace.
Now a reason you may not be seeing the constructor to this object execute is that it was not linked into the application. This is a linker issue and not a language issue. This happens when the object is compiled into a static library and your application is then linked against the static library. The linker will only load into the application functions/objects that are explicitly referenced from the application (ie things that resolve undefined things in the symbol table).
To solve this problem you have a couple of options.
Don't use static libraries.
Compile into dynamic libraries (the norm nowadays).
Compile all the source directly into the application.
Make an explicit reference to the object from within main.
I ran into the same problem.
Write a file, DoNotOptimizeAway.cpp:
void NoDeadcodeElimination()
{
// Here use at least once each of the variables that you'll need.
}
Then call NoDeadcodeElimination() from main.
EDIT: alternatively you can edit your linker options and tell it to always link everything, even if it's not used. I don't like this approach though since executables will get much bigger.
These problems, and the problems with these potential solutions all revolve around the fact that you can't guarantee much about static initialization. So since it's not dependable, don't depend on it!
Explicitly initialize data with a static "InititalizeLibrary" type static function. Now you guarantee it happens, and you guarantee when it happens in relation to other code based on when you make the call.
One C++'ish way to do this is with Singletons.
Essentially, write a function to return a reference to the object. To force it to initialize, make it a static object inside the function.
Make a class static function that is vaguely like this:
class MyClass {
static MyClass& getObject()
{
static MyObject obj;
return obj;
}
};
Since you are using C++, you could always declare a global object (ie a global variable that references a class in statinit.cpp. As always, the constructor will be called on initialization and since the object is global, this will be called before main() is run.
There is one very important caveat though. There is no guarantee as to when the constructor will be called and there is no way to explicitly order when each of these constructors is called. This will also probably defeat any attempt to check for memory leaks since you can no longer guarantee that all the memory allocated while running main has been deallocated.
Is the problem that the static items were never initialized, or is the problem that the static items weren't initialized when you needed to use them?
All static initialization is supposed to be finished before your main() runs. However, you can run into issues if you initialize on static object with another static object. (Note: this doesn't apply if you are using primitives such as int)
For example, if you have in file x.cpp:
static myClass x(someVals);
And in y.cpp:
static myClass y = x * 2;
It's possible that the system will try to instantiate y before x is created. In that case, the "y" variable will likely be 0, as x is likely 0 before it is initialized.
In general, the best solution for this is to instantiate the object when it is first used (if possible). However, I noticed above you weren't allowed to modify that file. Are the values from that file being used elsewhere, and maybe you can change how those values are accessed?
Read the manual page for the ld command and look at the -u option. If statinit.cpp defines anything that looks like a function then try naming it in -u. Otherwise choose a data object that's defined in statinit.cpp and name that in -u, and hope it works. I think it's best if you write the command line so the -u option comes immediately before your -l option for your library that has statinit's object code in it.
Of course the dynamic library solution is the best, but I've also been told it's possible to link the whole static library with the linker option:
-Wl,-whole-archive
before the library's -l option, and
-Wl,-no-whole-archive
after it (to avoid including other libraries as a whole, too).