How to read output of source code in another program with C++ - c++

I think this is really hard to explain what I want. But, let me try.
(I am trying to build a program for scoring student's programming homework)
There are a lot of simple source codes in C++. (Please think there are more than 100 code files)
// C:\homework1\studentA.cpp
int main()
{
cout << "The answer is 456" << endl;
}
And This is question. As you can see, there are tons of code files and I cannot compile it and check it whether right or wrong one by one. So, I need to make scoring program for convenience.
How can I read the standard output (The answer is 456) in another program? Is there any function for 'compiling source code' and 'save standard output' ?

I would use a bash script for this instead of C++. Something along the lines of:
g++ $filename
./a.out > student_answer.txt
diff -q student_answer.txt expected_answer.txt
Then, $? would tell you whether the answer was correct.

How can I read the standard output (The answer is 456) in another program?
You cannot do that without help from your operating system. Because you don't have (in general, according to the C++17 standard) some "other program" running (read about processes). When you have one, please thank your OS. Read some textbook about operating systems.
However, on Linux, you could just use popen(3) (or fork(2), execve(2), pipe(7) so pipe(2), dup2(2), waitpid(2)) and on operating systems for which Qt has been ported (that includes Windows, but read about the WinAPI), you could use QProcess.
If you are paranoid, consider using setuid and/or chroot techniques (perhaps with LXC) on Linux to increase the security of your tool.
Look also inside the POCO framework library.

Related

Print shared library dependencies from C++

I need to allocate an exact set of shared library dependencies of a binary program. I'm working on linux and the project is written in my C++. Thus, I need a recursive ldd-like functionality in C++. How can I do it?
To quote Han Solo, "I got a bad feeling about this". Setting up a chroot for a child process from within a C++ program sounds like some architectural misconception / screwup further up the line. Sorry, no ready-made C++ solution that springs to mind. You could, of course, run ltrace / strace / recursive-ldd and parse their output...
...but generally speaking, the idea is to set up the chroot environment statically (i.e. before any processes are started), not dynamically. With a dynamic approach, an attacker could fool the main process into believing it should give the child process things it shouldn't have in the chroot. That defeats the whole purpose.
Tools for statically setting up chroot environments for a given executable are plenty, tools for doing so dynamically I couldn't find any. This is a hint in itself.
In the meantime I've found the following:
linux/gcc: ldd functionality from inside a C/C++ program
where the accepted answer suggests to use:
setenv("LD_TRACE_LOADED_OBJECTS", "1", 1);
FILE *ldd = popen("/lib/libz.so");
I tried it out and worked both from bash and from C++ (ofc in this case I think of an equivalent version). However if I ran either versions for a SUID binary (what I actually have) then I got exit code 5 (i guess permission problems).
Then I traced what ldd exactly does and the following seems fine (at least in command line):
LD_TRACE_LOADED_OBJECTS=1 /lib64/ld-linux-x86-64.so.2 binary_name
The (dummy) question is: what is the equivalent implementation of this in C++?

Calling external files (e.g. executables) in C++ in a cross-platform way

I know many have asked this question before, but as far as I can see, there's no clear answer that helps C++ beginners. So, here's my question (or request if you like),
Say I'm writing a C++ code using Xcode or any text editor, and I want to use some of the tools provided in another C++ program. For instance, an executable. So, how can I call that executable file in my code?
Also, can I exploit other functions/objects/classes provided in a C++ program and use them in my C++ code via this calling technique? Or is it just executables that I can call?
I hope someone could provide a clear answer that beginners can absorb.. :p
So, how can I call that executable file in my code?
The easiest way is to use system(). For example, if the executable is called tool, then:
system( "tool" );
However, there are a lot of caveats with this technique. This call just asks the operating system to do something, but each operating system can understand or answer the same command differently.
For example:
system( "pause" );
...will work in Windows, stopping the exectuion, but not in other operating systems. Also, the rules regarding spaces inside the path to the file are different. Finally, even the separator bar can be different ('\' for windows only).
And can I also exploit other functions/objects/classes... from a c++
and use them in my c++ code via this calling technique?
Not really. If you want to use clases or functions created by others, you will have to get the source code for them and compile them with your program. This is probably one of the easiest ways to do it, provided that source code is small enough.
Many times, people creates libraries, which are collections of useful classes and/or functions. If the library is distributed in binary form, then you'll need the dll file (or equivalent for other OS's), and a header file describing the classes and functions provided y the library. This is a rich source of frustration for C++ programmers, since even libraries created with different compilers in the same operating system are potentially incompatible. That's why many times libraries are distributed in source code form, with a list of instructions (a makefile or even worse) to obtain a binary version in a single file, and a header file, as described before.
This is because the C++ standard does not the low level stuff that happens inside a compiler. There are lots of implementation details that were freely left for compiler vendors to do as they wanted, possibly trying to achieve better performance. This unfortunately means that it is difficult to distribute a simple library.
You can call another program easily - this will start an entirely separate copy of the program. See the system() or exec() family of calls.
This is common in unix where there are lots of small programs which take an input stream of text, do something and write the output to the next program. Using these you could sort or search a set of data without having to write any more code.
On windows it's easy to start the default application for a file automatically, so you could write a pdf file and start the default app for viewing a PDF. What is harder on Windows is to control a separate giu program - unless the program has deliberately written to allow remote control (eg with com/ole on windows) then you can't control anything the user does in that program.

When writing a portable c/c++ program, what is the best way to consume external files?

I'm pretty new to the c/c++ scene, I've been spoon fed on virtual machines for too long.
I'm modifying an existing C++ tool that we use across the company. The tool is being used on all the major operating systems (Windows, Mac, Ubuntu, Solaris, etc). I'm attempting to bridge the tool with another tool written Java. Basically I just need to call java -jar from the C++ tool.
The problem is, how do I know where the jar is located on the user's computer? The c++ executables are currently checked into Perforce, and users sync and then call the exe, presumably leaving the exe in place (although they could copy it somewhere else). My current solution checks in the jar file beside the exe.
I've looked at multiple ways to calculate the location of the exe from C++, but none of them seem to be portable. On windows there is a 'GetModuleLocation' and on posix you can look at the procs/process.exe info to figure out the location of the process. And on most systems you can look at argv[0] to figure out where the exe is. But most of these techniques are 100% guaranteed due to users using $PATH, symlinks, etc to call the exe.
So, any guidance on the right way to do this that will always work? I guess I have no problem ifdef'ing multiple solutions, but it seems like there should be a more elegant way to do this.
I don't believe there is a portable way of doing this. The C++ standard itself does not define anything about the execution environment. The best you get is the std::system call, and that can fail for things like Unicode characters in path names.
The issue here is that C and C++ are both used on systems where there's no such thing as an operating system. No such thing as $PATH. Therefore, it would be nonsensical for the standards committee to require a conforming implementation provide such features.
I would just write one implementation for POSIX, one for Mac (if it differs significantly from the POSIX one... never used it so I'm not sure), and one for Windows (Select which one at compilation time with the preprocessor). It's maybe 3 function calls for each one; not a lot of code, and you'll be sure you're following the conventions of your target platform.
I'd like to point you to a few URLs which might help you find where the current executable was located. It does not appear as if there is one method for all (aside from the ARGV[0] + path search method which as you note is spoofable, but…are you really in a threat environment such that this is likely to happen?).
How to get the application executable name in WindowsC++/CLI?
https://superuser.com/questions/49104/handy-tool-to-find-executable-program-location
Finding current executable's path without /proc/self/exe
How do I find the location of the executable in C?
There are several solutions, none of them perfect. Under Windows, as
you have said, you can use GetModuleLocation, but that's not available
under Unix. You can try to simulate how the shell works, using
argv[0] and getenv("PATH"), but that's not easy, and it's not 100%
reliable either. (Under Unix, and I think under Windows as well, the
spawning application can hoodwink you, and put any sort of junk in
argv[0].) The usual solution under Unix is to require an environment
variable, e.g. MYAPPLICATION_HOME, which should contain the root
directory where you're application is installed; the application won't
start without it. Or you can ask the user to specify the root path with
a command line option.
In practice, I usually use all three: the command line option has
precedence, and is very useful when testing; the environment variable
works well in the Unix world, since it's what people are used to; and if
neither are present, I'll try to work out the location from where I was
started, using system dependent code: GetModuleLocation under Windows,
and getenv("PATH") and all the rest under Unix. (The Unix solution
isn't that hard if you already have code for breaking a string into
fields, and are using boost::filesystem.)
Good solution would be to write your custom function that is guaranteed to work in every platform you use. Preferably should use runtime checks if it worked, and then fallback to ifdefs only if some way of detecting it is not available in all platforms. But it might not be easy to detect if your code that executes correctly for example argv[0] would return the correct path...

Is there such a thing as a C++ interpreter? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Have you used any of the C++ interpreters (not compilers)?
Hi,
I am currently learning C++ and a beginner in programming in general. I've been trying to write some code to a few programming problems from the book I'm using. What I find is that often I make mistakes in what I write and those mistakes come up when the program is run. Its usually quite obvious where in the program I've gone wrong when there is regular output. But in a long computation I'm often not sure why a particular code has acted a certain way. I've also looked at Python recently. Python works with an interpreter, which can take any piece of Python code and compute its output.
I was wondering if there was something similar for C++. Right now when I want to check a line or block of code I have to comment out a lot, save it, compile it, and then run it from a command line. And I have to do that many times for a single error until I've solved it. Is there a way to type code into an active terminal which would run code and show me output? What would be better still would be a way to select a block of code (like you select text) or multiple blocks (to see how a function is being handled) within the IDE and click run to run just that block of code and see its output without having comment out irrelevant lines or to save the file. The compiled code could just reside in memory.
CINT is a c & C++ interpretter that accepts nearly all valid C++. Unfortunately many Linux distros do not offer it, and you'll probably have to build it from source... and that is a non-trivial task.
Typically a debugger is used to step through code line by line, starting at a chosen breakpoint, and keep watch of all variables/values.
Unit testing is a technique to test smaller pieces of code.
A stepping debugger, as found in most IDEs will help you with this.
Here (for example) is a description of how to set the Execution point in In Visual Studio, which sounds like what you want to do.
For certain situations, the "Immediate Window" may be of use to you. It allows you to type in expressions to evaluate immediately.
Rather than just running individual lines independently, or relying on print statements to tell you the state of whatever variables you have decided to print, you can use the debugger to run to the point of interest (where you will have set a breakpoint), then you can examine the state of any in-scope variables, or even alter the normal flow of the program.
There are some solutions that try to do this - the ones I know are Ch and TextTransformer.
However, I doubt that this works very well. C++ is not at all designed to run as an interpreted language.
One of the problems is that C++ is very, very hard to parse. And this makes it very hard to provide certain types of tools that are usual for other languages. For example, I don't think there is any C++ refactoring tool that really works well.
C++ is a compiled language not like python. But there are few c/c++ interpreters out there but not sure about their features. Check these out: Ch interpreter and CINT
If you really want to learn c++ please do not use the c/c++ interpreters.
If you insist on using a interactive interpreter there is since a long time CINT which is the default interpreter used in the ROOT project. It got better over the years, but still has only limited capabilities when dealing with templates. Also, there is a move to replace it with a JIT compiling interpreter based on clang inside the ROOT project.
If I were you I would learn how to run compiler and an interactive debugger like suggested in some comments already.

Can I use boost library for crossplatform application executing?

Is there any WinAPI WinExec analog in boost (c++) libraries? I need to run executable from my program, and pass parameters to it. Should I use any other cross-platform libraries for this, or handle myself what OS my program is compiled for?
Important: see update at the end for POSIX systems.
My opinion is that you should use the APIs/syscalls provided by the various platforms you wish to support, or use some kind of abstraction layer (the Boost.Process library, mentioned by Noah Roberts, may be an idea) to avoid dealing with platform-specific details.
I strongly disagree with using the system function because it isn't intended to start a process you specify, but instead it's supposed to pass the string you specified to the "system default shell" or "command processor" (if any). This has several drawbacks:
resource wastage; instead of a process now (usually) you are spawning two, one of which (the shell) is useless for your final objective (starting the process you want). This is usually negligible, but may be noticeable on systems where processes aren't lightweight objects (Windows) if they are running low on resources.
useless confusion; several security suites I've dealt with warn every time an unknown/untrusted process starts a new process; instead of just displaying a warning, now the security suite will display two of them (and you're making the first one quite unclear);
unpredictability of the result; the platform-agnostic system's documentation could be replaced without much loss with "undefined behavior" - and actually it is quite like that. Why do I say this? Because:
first of all, there's not even a guarantee that system has some meaning on the current platform, as there could be no "default shell" at all. But this is an extreme case that isn't usually a problem - and that can be also caught quite easily (if(system(NULL)==0) there's no shell); the real problem is that
in general, you don't have idea about what shell is the "default shell", and how it parses its input; on Linux it will usually be /bin/sh update: actually, this is mandated by POSIX, see below, on Windows it may be command.com as well as cmd.exe, on another OS it will be still another thing. So, you aren't sure about, e.g., how to escape spaces in the path, or if you should quote the path; heck, you don't even know if such shell requires some special command to start executables!
More fun: you don't even know if the call is actually blocking: you know that by the time system will return the shell will be terminated, but you don't know if the shell will wait for the spawned process to end; concrete example: cmd.exe doesn't wait for GUI executables to end before returning, while on Linux GUI executables are executables like all the others and don't have such special treatment. In this case you'll have to create a special case for Windows, and make a command string like start /wait youexecutable.exe - hoping that the version of the interpreter still (or yet, depending on the version of Windows) supports that syntax. And IIRC start has different options on Windows 9x and Windows NT family, so you won't even be sure with that.
It's not enough: you aren't even sure if the application has been started: the system return value is relative to the command interpreter return code. As far as system is concerned, if a shell is started the call succeeded, and there ends what system considers an error.
Then you're left with the error code of the shell - about which, again, we don't know anything. Maybe it's a carbon-copy of the error code of the last executed command; maybe it is an error code relative just to the shell (e.g., 1 = last command executed, 0 = last command was invalid), maybe it's 42. Who knows?
Since in a good application you'll want, at least, to know if the call is blocking/nonblocking, to get a meaningful exit code (the one actually returned by the application you started), to be sure if the application has been started, to have meaningful error codes in case things went wrong, system most probably doesn't suit your needs; to earn any of these guarantees, you have to go with platform-specific hacks or with non guaranteed assumptions, wasting all the cross-platform "compatibility" of system.
So, I'll state it again: use the system calls provided by the various platforms (e.g., fork+exec on POSIX, CreateProcess on Windows), which specify exactly what they are guaranteed to do, or go with third party abstraction code; the system way is definitely not good.
Update: since when I wrote this answer, I learned that on POSIX systems system is specified way better - in particular, it's mandated that it will execute the commands with /bin/sh -c command, blocking until the termination of the shell process.
sh behavior, in turn, is mandated in several ways by POSIX; thus, on POSIX systems, some of the disadvantages listed under "unpredictability of the result" no longer apply:
the default shell is specified, so, as long as you use just sh stuff guaranteed by POSIX (e.g. no bashisms), you are safe;
the call is blocking;
if your command is well-formed, the shell itself doesn't encounter problems, waitpid succedes, ..., you should get a copy of the error code of the executed program
So, if you run on POSIX, the situation is way less tragic; if, instead, you have to be portable, keep avoiding system.
What is wrong with system(), which is part of standard C++? See http://www.cplusplus.com/reference/clibrary/cstdlib/system.
There's a library that I believe is trying to get into boost called Boost.Process. You'll have to find a download for it, probably in sandbox or whatnot.
You might want to take a look at this question regarding popen() on win32: popen