I'd like to use LLVM lli tool as static library (rename main() to lli() and export it in libLLi.a) - to create rich UI for it. How can i modify it (or use without modifications) in order to intercept stdin?
Assume i know how to generate LLVM assembly file (using clang -S -emit-llvm .. -o output.ll) and how to execute it using lli tool (lli output.ll).
Common use case:
Source code of simple app to be interpreted by lli:
#include <iostream>
using namespace std;
int main() {
char name[128];
cout << "type your name: ";
cin.getline(name, sizeof(name));
cout << "hi, " << name << endl;
return 0;
}
I need to interpret LLVM assembly for it and to show InputBox when cin.getline invoked and show TextBox when cout << invoked (InputBox and TextBox are rich UI controls).
PS. I can't fork process and forward stdin/stdout of the whole child process.
lli is already a thin wrapper around llvm library functions, just use those instead. The main() function in tools/lli/lli.cpp is long only because it supports tons of flags to control every possible setting. After you strip it down it should be less than 10 lines to create an ExecutionEngine using an EngineBuilder and use it to run a llvm::Function.
You might also find chapter 4 of the Kaleidoscope tutorial helpful, where they add JIT support to the language. This also demonstrates how to use an EngineBuilder, though the ExecutionEngine they choose to build is a JIT instead of an Interpreter, you can customize it for your use case.
Now for the other part of your question, how do you trap stdin and stdout? LLVM is not a VM, the code is running in your process and using your stdin and stdout. My first suggestion is that since you already have the function in LLVM IR format, just run a transformation pass that replaces standard I/O functions with your own I/O functions. A simpler way to do that if you can get the ABI to line up, is to do the remapping with the ExecutionEngine. Call EE->updateGlobalMapping(functionDeclInIR, &replacementFunctionInNativeCode) to tell the ExecutionEngine that the Function* for functionDeclInIR is represented in native code by replacementFunctionInNativeCode. You would need to provide your own implementation of _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc (aka. ostream::operator<<) which uses your GUI.
Related
I'm currently working on a compiler for a C/C++ like language. I have reached the compiling phase of code generation. I'm using the LLVM C++ api to create an LLVM IR from the input file.
As far as I understood it my module object (I'm working with just one module) should contain all information I need for getting the textual representation of the LLVM IR as a string.
But I really don't know how to do that.
If you wish to get the LLVM IR of your llvm::Module you can use the llvm::Module::print function. Use this in combination with the LLVM standard streams like this:
llvm::Module module = ...
module.print(llvm::errs()); // for stderr, llvm::outs() for stdout
See also dump():
module.dump(); // print to stderr
Or use raw_ostream
llvm::outs() << module;
// or
llvm::errs() << module;
// or
llvm::dbgs() << module;
I'm interested in implementing a program written in C++ inside a Ruby on Rails 4 App.
The C++ app runs in console and works by giving it a file, it processes it and then it outputs another file.
I found 'Ruby Inline', a gem that allegedly allows the use of foreign code:
https://rubygems.org/gems/RubyInline
gem 'RubyInline', '~> 3.12', '>= 3.12.4'
Inline allows you to write foreign code within your ruby code. It automatically determines if the code in question has changed and builds it only when necessary. The extensions are then automatically loaded into the class/module that defines it. You can even write extra builders that will allow you to write inlined code in any language. Use Inline::C as a template and look at Module#inline for the required API.
According to the documentation, it allows the use of C and C++ programs like this:
require 'inline'
class MyTest
inline(:C) do |builder|
builder.include '<iostream>'
builder.add_compile_flags '-x c++', '-lstdc++'
builder.c '
void hello(int i) {
while (i-- > 0) {
std::cout << "hello" << std::endl;
}
}'
end
end
t = MyTest.new()
t.hello(3)
The problem is that I'm not entirely sure how to implement it with a larger C++ program made out of multiple files, I'm not proficient in C++.
This seems like a gem to add the C++ code inside a ruby script and the C++ program is made out of multiple files and folders.
Will Ruby Inline work for what I want to do or is there a better option out there?
Is there a way to call the C++ app directly without putting it inside a ruby file?
The file to be given to the C++ app will be uploaded via the web interface, how can I feed it to the C++ program so it outputs the result?
Ruby supports the functionality to run native commands using the ` character. For example, we have a C++ program below, that takes two arguments, and then prints to standard output both of them, concatenated together. The course code for this program can be seen below:
#include <iostream>
int main(int argc, char ** argv){
std::cout << argv[1] << argv[2] << std::endl;
return 0;
}
While the C++ code, really only needs to be compiled a single time, and this step wouldn't likely be necessary, we can compile it from within ruby by doing the following: (You can replace g++ with the compiler of your choice.) We will set the variable success to true if the command successfully compiles, false otherwise.
pathToSource = "your/path/to/file.cpp"
outputBinaryFile = "your/desired/output/file.bin"
success = system("g++ #{pathToSource} -o #{outputBinaryFile}")
Now that we have compiled our code, we can execute it by running the following in ruby:
word1 = "Hello"
word2 = "World"
commandOutput = `./#{outputBinaryFile} '#{word1}' '#{word2}'`
Which will set commandOutput to: "HelloWorld\n"
You may need to change small things such as the compiler depending on the system that you are running, but this should function for you on *NIX systems.
I am using MinGW (GCC) as a C++ compiler within my application. I have set it to redirect the output of its command line process to my app. Now, suppose I have the following simple C++ code:
int n = 5;
if (n == 6) cout << "YES";
else cout << "NO";
Is there a way to tell what line(s) of code were actually hit during execution of the application? Is there a command I can send to MinGW (GCC) process which, for the given example, would output 1 and 3, as those were the lines hit. And also, in case of a line inside a "for" loop, to tell how many times that statement was actually hit?
And, if not possible, what would be the best approach to having this information? Developing my own compiler or...? Thanks in advance
EDIT: Can someone provide a snippet of commands (in Windows) to be used in order to create a coverage-enabled GCC exe file?
"Is there a way to tell what line(s) of code were actually hit during execution of the application?"
Yes. It's an intrinsic GCC feature. You'll need to compile and link your code with the --coverage, -lgcov or -fprofile-arcs options set.
The gcov tool can be used to consolidate and interpret the actual informations gathered during program runs, that were instrumented with --coverage.
A very good tool to produce browsable consolidated and fairly visualized covearage information from gcov outputs is lcov.
Since you're using mingw you should be able to use gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
I need to launch some script using QProcess.
For this, under windows, I use QProcess::execute("cmd [...]");.
However, this won't work if I go under some other OS such as Linux.
So, I was wondering if the best solution to make that code portable, would be to interfere with a mutliplatform scripting solution, such as TCL for exemple.
So I use : QProcess:execute("tclsh text.tcl"); and it works.
But, I got three questions concerning that problem. Because I'm not sure of what I've done.
Will execute() execute tclsh with the file test.tcl both under Windows and Linux wherever I execute it ? It seems to do so, but I want to be sure ! Is there any bad scenario that can happen ?
Is this a good solution ? I know lots of people have way more experience than I do, and I'd be grateful for anything I could learn !
Why not using std::system() ? Is it less portable ?
While this isn't a total answer, I can point out a few things.
In particular, tclsh is quite happy under Windows; it's a major supported platform. The main problem that could happen in practice is if you pass a filename with a space in it (this is distinctly more likely under Windows than on a Unix due to differences in community practice). However, the execute() as you have written it has no problems. Well, as long as tclsh is located on the PATH.
The other main option for integrating Tcl script execution with Qt is to link your program against the Tcl binary library and use that. Tcl's API is aimed at C, so it should be pretty simple to use from C++ (if a little clunky from a C++ perspective):
// This holds the description of the API
#include "tcl.h"
// Initialize the Tcl library; *call only once*
Tcl_FindExecutable(NULL);
// Make an evaluation context
Tcl_Interp *interp = Tcl_CreateInterp();
// Execute a script loaded from a file (or whatever)
int resultCode = Tcl_Eval(interp, "source test.tcl");
// Check if an error happened and print the error if it did
if (resultCode == TCL_ERROR) {
std::cerr << "ERROR: " << Tcl_GetString(Tcl_GetObjResult(interp)) << std::endl;
}
// Squelch the evaluation context
Tcl_DeleteInterp(interp);
I'm not a particularly great C++ coder, but this should give the idea. I have no idea about QProcess::execute() vs std::system().
A weak point of your solution is that on windows you'll have to install tclsh. There is no tclsh on Solaris either. May be somewhere else.
Compared to std::system(), QProcess gives you more control and information about the process of executing your command. If all you need is just to execute script (without receiving the output, for example) - std::system() is a good choice.
What I've used in a similar situation:
#ifdef Q_OS_WIN
mCommand = QString("cmd /C %1 %2").arg(command).arg(args);
#else
mCommand = QString("bash %1 %2").arg(command).arg(args);
#endif
I am looking for a good approach to build a C++ GUI application. Its core is generating whole bunch of tcl code and execute it through Tcl C++ API (#include <tcl.h>). The GUI provides an easy way for users to complete those tcl scripting tasks.
In other words, inside each callback function associated with the GUI control, it's like using ostringstream to populate tcl code and passes it to tcl interpreter. Eg:
bool execTclProc1(options) {
ostringstream oss;
oss << "package require MyPackage \n";
string optionsForTcl = genOptionsForTcl(options);
oss << "myTclProc1 " << optionsForTcl << endl;
if(Tcl_Eval(interp, oss.c_str() == TCL_OK) {
// print out some messages to the GUI message window
}
...
}
The down side of this design:
Hard to debug tcl code error. Since every change in tcl code needs to re-compile the C code. Although a fast way is to write and test tcl code in tcl interactive shell. But a lot of tcl code is populated in C++, not hard-coded. So it's not so feasible.
Whole bunch of tcl code is written in C++ routines. This makes it hard to maintain.
I want to seek some insights from the community.
Can't you use the Tk toolkit called as library functions from C++?
Also, there is Tk/C++ - don't know how good it is. They overloaded operator- and use expression templates so that the C++ code like like Tcl. Pretty cool!