Using program as library that contains main function - c++

I am planning to write a program that makes calls to cdrecord. (I am a beginner, a beginner trying to "scratch an itch") The program would be written in C++. I have identified that I need to be able to run cdrecord in order for this to work.
cdrecord is written in C. However the documentation on using it is from the command line. The source code includes a main function that powers the command line app, which is the same as the code I wand cdrecord to do.
I am wondering whether I should:
Change main to another name, then include the source file and call it when I need to.
Call the compiled program using the system() command.
Something else.

system() is generally a nice way to go, just be careful not to inject arbitrary untrusted values into the string you execute. For example, if you have a web frontend where with a padsize option defaulted to 0, and someone types in not a number but "0; rm -rf *;", make sure you don't end up calling "cdrecord padsize=0; rm -rf *; ...".
The other thing with system is just that it can be slower starting a second distinct process - this might matter if you're running that program hundreds of times and each time it only has a few milliseconds of work to do, but in your case the overhead of launching is dwarfed by the likely cdrecord run-time.

Using system() will allow you to not worry about cdrecord's code. Personally, I would only include the code in my own program if I had some very pressing issues that require me to include it. I think system() is the way to go.
http://www.cplusplus.com/reference/clibrary/cstdlib/system/
1) Is there any particular reason you would rather include it in your own code, as opposed to just using it as it is?
2) Do you have the rights to change the code and include it in your own program?

Related

Open a new terminal screen in C ++

First of all, I have to say that I do not know English exactly. I am improving my English but I am not at a sufficient level yet. Please excuse me for my misspelling and write your answers in the simplest way.
My problem is that I want to run another program made in C ++ when the "1" key is pressed. The files are in the same directory. Can you tell me how to do it?
If you want to make cross-platform for your application, use system with predefined operating system macros.
For example:
#ifdef __FreeBSD__
system("Terminal application object is here");
#endif
#ifdef _WIN64
system("Terminal application object is here");
#endif
I want to run another program made in C ++
The only standard way to run another program in C++ is the std::system function. As per its documentation, this function will call the host environment's shell (also known as command line interpreter). The shell generally has an ability to execute other programs.
However, although std::system is standard, the shell itself is not, so any interaction with it will be implementation defined regardless. The use of std::system is somewhat problematic in many cases because it can potentially introduce shell injection vulnerability to the program. You should never pass any user input into std::system. Given this problem, and the fact that the shell is implementation defined anyway, it is often a good idea to use system specific API to directly execute a program without allowing arbitrary shell commands. How to do that depends on the host environment where the program will run.
Short description of how to do that in POSIX standard systems: First fork the process (if you want to stop executing current program entirely and replace with the new one, then you can skip fork), then in the child process call execv (or one of its sibling functions).
when the "1" key is pressed
When using standard input, a C++ program cannot react to a key being pressed. The way it works, you type the input and press enter to submit.
There may be non-standard ways to react to input in a way that you describe which will also be specific to the host environment.

Execute a command in a separate file

Is it possible to store a "command" in a separate file, and have it called whenever you input the name of that file?
Let's say: file help contains code: cout << "This is help file.";
So is it possible to get the content of file without need of creating a functions in it, straight to action, like it is in Lua?
Edit
Well, I'm in the process of learning the C++ so embedding Lua won't make sense for me, yet that's a very good idea for my future projects, thank you.
What i'm trying to do is a simulation of command line os. Something like ComputerCraft. Basically you type in a command, the program then, looks for a actual file with same name as user's input and if found executes it's content. It is all done in runtime, check for file, execution, adding new etc.
Something like
In console:
> help
Program checks for the file named help and if found executes it
Contents of help:
cout << "type help for help, programs for list of programs etc";
I want it that way to make it possible to create a new "command" file right from that simulated os and automatically make it usable with least effort possible for user.
I did it in lua before and I would like to know how and if it's possible in C++
I was working in Love2D, and it has a function love.filesystem.load(filename) basically what it does, it creates a function which has the content of the file as it's container, you assign it a name function = love.filesystem.load(filename) and then execute it as a normal function. What I'm seeking for is equivalent of it.
If you want to execute a script in a file, you will either need to use an existing scripting language and include an interpreter in your program, or invent your own scripting language and code how to interpret it.
If you want the files to contain C++ code to be executed at run-time, this is impossible or so you will be told. Actually it's not impossible; people who tell you that are technically wrong. But it is insanely difficult and definitely not a beginner's project.
You will either need to include a fully-fledged C++ compiler in your program, compile the code in the file at run-time and execute the result. Some virus scanners can get unhappy when a program tries to do that. (Sometimes my one complains about my creations in Visual Studio!)
Or you will need a run-time C++ interpreter. If such a thing exists, I would be very interested to know about it!
Practically speaking the best you could hope for is an interpreter that can work with a very limited subset of C++.

Alternative to System() for running a batch file in a program

I want to make a system were I can run a make file and several other gcc related things within a program, basically to use gcc and compile stuff within the program. If I wrote up all the stuff I want to do to a batch file then I'd need to run that batch file from within the program.
Now everyone says System() calls are extremely bad because of security and various other things. So considering I am using c++ what would be a good alternative to System() to run batch files. If preferable I would like the alternative to cross platform.
Thanks
You could look to use the fork and execl family of calls although these are tied down to Unix / Linux and, depending on how you use them, are arguably no safer than system.
I doubt very much that you'll find a common, cross platform way of doing this if only because all platforms will have different and unique ways of doing this. Also, the scripts you're trying to run will no doubt have to be different on different platforms and there may be different ways of specifying things such as directory paths etc.
My suggestion would be to first ask yourself how you'll take the following questions - which would be my main concerns:
How am I going to prevent accidental / intentional misuse?
How am I going to detect errors or success status within the scripts I'm running?
How am I going to provide for dependencies? E.g. script A must run completely and correctly before script B runs.
How am I going to report the success and failure state.
My final question would be why do you want to do this in C++? Is there a specific reason? Naturally I'm a C++ evangelist although I would have thought this would be better tackled by a scripting language such as Perl, Python or possibly Bash unless you're embarking on something far more radical.

Disable system() and exec() function in C and Pascal

Is there any way to disable system() and exec() function in C/C++ and Pascal, by using any compiler argument or modifying header/unit file? (It's a Windows)
I've tried using -Dsystem=NONEXIST for gcc and g++ but #include <cstdio> causes compile error.
EDIT: Of course I know they can use #undef system to bypass the defense, so I've tried to comment out the system function line in stdlib.h, but that doesn't work too.
EDIT2 (comment): It's a system, to which users submit their programs and the server compile and run it with different input data, then compare the program output with pre-calculated standard output to see if the program is correct. Now some users send code like system("shutdown -s -t 0"); to shutdown the server.
The server is running Windows system so I don't have any chroot environment. Also the server application is closed-source so I can do nothing to control how the program submitted by user is executed. What I can do is to modify the compiler commandline argument and modify header files.
Well, you could try:
#define system DontEvenThinkAboutUsingThisFunction
#define exec OrThisOneYouClown
in a header file but I'm pretty certain any code monkey worth their salt could bypass such a "protection".
I'd be interested in understanding why you thought this was necessary (there may be a better solution if we understood the problem better).
The only thing that comes to mind is that you want to provide some online compiler/runner akin to the Euler project. If that was the case, then you could search the code for the string system<whitespace>( as an option but, even then, a determined party could just:
#define InoccuousFunction system
to get around your defenses.
If that is the case, you might want to think about using something like chroot so that no-one can even get access to any dangerous binaries like shutdown (and that particular beast shouldn't really be runnable by a regular user anyway) - in other words, restrict their environment so that the only things they can even see are gcc and its kin.
You need to do proper sandboxing since, even if you somehow prevented them from running external programs, they may still be able to do dangerous things like overwite files or open up socket connections to their own box to send through the contents of your precious information.
One possibility is to create your own version of such functions, and link them into every program you compile/link on the server. If the symbol is found in your objects, it'll take precedence.
Just make sure you get them all ;)
It would be much better to run the programs as a user with as few privileges as possible. Then you don't have to worry about them deleting/accessing system files, shutting down the system, etc.
EDIT: of course, by my logic, the user could provide their own version of the function also, which does dynamic library loading & symbol lookup to find the original function. You really just need to sandbox it.
For unixoid environments, there is Geordi, which uses a lot of help from the operating system to sandbox the code to be executed.
Basically you want to run the code in a very restricted environment; Linux provides a special process flag for that which disables any system calls that would give access to resources that the process did not have at the point where the flag was set (i.e. it disallows opening new files, but any files that are already open may be accessed normally).
I think Windows should have a similar mechanism.
Not really (because of tricks like calling some library function which would call system itself, or because the functionality of spawning processes can be done with just fork & execve system calls, which remain available...).
But why do you ask that?
You can never (as you have found out) rely on user input to be safe. system and execXX are unlikely to be your only problems.
This means you have the following options:
Run the program in some kind of chrooted jail (not sure how to do this on windows)
Scan the code before before compiling to ensure there are no "illegal" functions.
Scan the executable binary after compiling to ensure that it is not using any "forbidden" library function.
Prevent the linker from linking to any external libraries including the standard C library (libc) on unix. You then create your own "libc" which explicilty allow certain functions.
Number 3 on unix can use utilities like readelf or objdump can check for linked in symbols. This can also probably be done using the Binary File Descriptor Library as well.
Number 4 will require fiddling with compiler flags but probably is the safest out of the options listed above.
You could use something like this
#include<stdlib.h>
#include<unistd.h>
#define system <stdlib.h>
#define exec <unistd.h>
In this case even if the user wants to swap macro values they can't. If they try to swap macro values like this
#define <stdlib.h> system
#define <unistd.h> exec
they can't because C wouldn't allow this type of first name in macros. Even if somehow they swap these values then we have included those header files that will create a compile time error.

MATLAB arbitrary code execution

I am writing an automatic grader program under linux. There are several graders written in MATLAB, so I want to tie them all together and let students run a program to do an assignment, and have them choose the assignment. I am using a C++ main program, which then has mcc-compiled MATLAB libraries linked to it.
Specifically, my program reads a config file for the names of the various matlab programs, and other information. It then uses that information to present choices to the student. So, If an assignment changes, is added or removed, then all you have to do is change the config file.
The idea is that next, the program invokes the correct matlab library that has been compiled with mcc. But, that means that the libraries have to be recompiled if a grader gets changed. Worse, the whole program must be recompiled if a grader is added or removed. So, I would like one, simple, unchanging matlab library function to call the grader m-files directly. I currently have such a library, that uses eval on a string passed to it from the main program.
The problem is that when I do this, apparently, mcc absorbs the grader m-code into itself; changing the grader m code after compilation has no effect. I would like for this not to happen. It was brought to my attention that Mathworks may not want me to be able to do this, since it could bypass matlab entirely. That is not my intention, and I would be happy with a solution that requires a full matlab install.
My possible solutions are to use a mex file for the main program, or have the main program call a mcc library, which then calls a mex file, which then calls the proper grader. The reason I am hesitant about the first solution is that I'm not sure how many changes I would have to make to my code to make it work; my code is C++, not C, which I think makes things more complicated. The 2nd solution, though, may just be more complicated and ultimately have the same problem.
So, any thoughts on this situation? How should I do this?
You seem to have picked the most complicated way of solving the problem. Here are some alternatives:
Don't use C/C++ at all -- Write a MATLAB program to display the menu of choices (either a GUI for a simple text menu in the MATLAB command window) and then invoke the appropriate MATLAB grading programs.
Write your menu program in C/C++, but invoke MATLAB using a -r argument to run a specific grading program (to speed up the startup times, use the -nodesktop, -nojvm or -nodisplay options as appropriate). However, note that MATLAB will be started anew on each menu selection.
Write your menu program in C/C++ and start MATLAB using the popen command (this sets up a pipe between your C++ program and the MATLAB process). After a menu selection by the user:
your C++ program writes the name of the MATLAB program (and any parameters) to the pipe.
On the MATLAB side, write a MATLAB program to a blocking read on that pipe. When it reads a command, it invokes the appropriate MATLAB function.
You could also use named pipes. See this MATLAB newsgroup thread for more information.
Update: Option #3 above is effectively how the MATLAB engine works, so you are probably better off using that directly.
Don't make this a mex function.
Use a regular m-file that has to be executed in matlab. If you don't want to launch matlab first, write a bat file. I believe -r or -m runs a given command (you will have to cd to the correct directory before running you ml function).
To compile c++ code using mex first install visual studio. Then run (in matlab) mex -setup. Select "locate installed compilers" or some such, and then select your compiler from the list. Now mex will compile c++ code.
Using the MATLAB Engine to Call MATLAB Software from C/C++ and Fortran Programs