SystemC: read() and write() to port doesnt work - c++

I am new to systemC It might look stupid but I would appreciate help.
In the below code
In main function :write() to aa and bb shows value 0 when read using aa.read() and bb.read() which should be 10 and 20
And also I think it should enter the method do_add() in the adder module as it is sensitive to a and b and a,b are binded to aa and bb signals but it doesn't call the method do_add(). How does it work and is there any error in the code?
For compiling the code:
g++ -I. -I$SYSTEMC_HOME/include -L. -L$SYSTEMC_HOME/lib-linux64 -Wl,-rpath=$SYSTEMC_HOME/lib-linux64 -o out adder.cpp -lsystemc -lm
./out
#include "systemc.h"
#define WIDTH 32
SC_MODULE(adder) {
sc_in<sc_uint<WIDTH> > a, b;
sc_out<sc_uint<WIDTH> > sum;
void do_add() {
// cout<<"hello"<<endl;
// cout<<a.read()<<b.read()<<"\n";
sum.write(a.read() + b.read());
// cout<<sum.read()<<endl;
}
SC_CTOR(adder) {
SC_METHOD(do_add);
sensitive << a << b;
}
};
int sc_main(int argc, char* argv[]) {
sc_signal<sc_uint<WIDTH> >aa,bb;
adder add("Adder");
add.a(aa);
add.b(bb);
aa.write(10);
bb.write(20);
cout<<aa.read()<<bb.read()<<"\n";
}

There are a number of things here. Firstly, you never actually start the simulation (see function sc_start) and even if you did it would exit immediately since there are no events to process. And lastly, even if you fixed those issues you would still get the same result since SystemC simulates hardware and reading a port in the same delta cycle as it was written will give you the original value on the port not the newly written one. How can hardware change the value of a signal in zero time?
The best advice I can give is to look in the directory where you downloaded SystemC and you will see a directory of PDF documents. On my SystemC it is in a directory called 'docs' (it may be different on yours depending on who installed it and where). If you look in there you will find a 'user guide' and some other PDF documents. These explain how SystemC works and give you examples you can try and modify to your own needs. Also there are some examples in the SystemC sources in the 'examples' folder. You can try playing around with these to get a feel for it and maybe just cut and paste some code and modify it to get what you require.

Related

Stack is totally messed up by trying to produce a buffer overflow

after hours of debugging without any effort, I hope to find some help here on StackOverflow.
I'm currently on a PTP training and due to the fact that I'm only using Linux, i also want to practice the very firsts Labs on my local machine.
What i have to do is to exploit a very simple Program via buffer overflow. Just the Sources are given:
goodpwd.cpp:
#include <iostream>
#include <cstring>
int bf_overflow(char *str){
char buffer[10]; //our buffer
strcpy(buffer,str); //the vulnerable command
return 0;
}
int good_password(){ // a function which is never executed
printf("Valid password supplied\n");
printf("This is good_password function \n");
return 0;
}
int main(int argc, char *argv[])
{
int password=0; // controls whether password is valid or not
printf("You are in goodpwd.exe now\n");
bf_overflow(argv[1]); //call the function and pass user input
if ( password == 1) {
good_password(); //this should never happen
}
else {
printf("Invalid Password!!!\n");
}
printf("Quitting sample1.exe\n");
return 0;
}
I compiled it to get an executable by using
gcc -fno-stack-protector -z execstack -o goodpwd goodpwd.cpp -ggdb -m32 -lstdc++ -no-pie -O0
(I also already tried it without -no-pie and -O0 but I thought maybe the optimization could be the problem..)
I used gdb to debug the executable:
gdb goodpwd -tui -q
After setting a breakpoint to line 6 (the one with the vulnerable strcpy) I executed the following command:
(gdb) run AAAAAAAAAAAAAABCDE
after pressing n to go to the next line, I had a look into the stack:
(gdb) x/20x $esp
this gave me the following result:
0xffffd6f0: 0xffffd748 0x4141a8b0 0x41414141 0x41414141
0xffffd700: 0x41414141 0x45444342 0xffffd700 0x0804923b
0xffffd710: 0xffffd99c 0xf7fe4bd0 0xffffd800 0x08049209
0xffffd720: 0x00000002 0xffffd7f4 0xffffd800 0x00000000
0xffffd730: 0x0804c000 0x00000002 0x08049080 0xffffd760
I cannot explain myself why:
there are two A's at 0xffffd6f4
there are no A's at 0xffffd6f6
I got 16 A's starting at 0xffffd6f8
I got EDCB at 0xffffd704 (because of little endian, thank you #1201ProgramAlarm)
$bsp is 0xffffd708 and $eip is 0x80491a7 but after doing two more steps (leaving the function) $eip is set to 0x804923e because after all I've learned, I'm pretty sure it should be 0x08049209
after those two steps I get those error: main (argc=<error reading variable: Cannot access memory at address 0x4141a8b0>,
argv=<error reading variable: Cannot access memory at address 0x4141a8b4>) at goodpwd.cpp:21
I'd really appreciate if there's someone who's able to help me.
Struggling in module 3 of 43 is not the best feeling I've ever got :D
Edit:
ASLR should be deactivated:
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
Maybe it was a bit too late yesterday. But today I found out, that #1202ProgramAlarm made a very good point.
Because of using a little-endian system, 0xffffd704 was right.
My confusions about 0xffffd6f4 and 0xffffd6f6 have been irrelevant because they not influenced the result.
The value of the old $EIP was still in 0xffffd70e but I never touched it.
I just had to enhance the string in the argument and afterwards I've been able to exploit the vulnerability.
It was a lot of fun. Thanks for the advises.

Compiling Julia embedded in C++ code

I'm trying to compile the following C++ code
#include <julia.h>
int main(int argc, char *argv[])
{
/* required: setup the julia context */
jl_init(NULL);
/* run julia commands */
jl_eval_string("print(sqrt(2.0))");
/* strongly recommended: notify julia that the
program is about to terminate. this allows
julia time to cleanup pending write requests
and run all finalizers
*/
jl_atexit_hook();
return 0;
}
I compile the code using
gcc -I/usr/include/julia -L/usr/lib/x86_64-linux-gnu/julia -ljulia juliatest.cpp -o test
I get the following error-
juliatest.cpp:19:20:: error: too few arguments to function ‘void jl_atexit_hook(int)’
jl_atexit_hook();
^
In file included from juliatest.cpp:1:0:
/usr/include/julia/julia.h:1188:16: note: declared here
DLLEXPORT void jl_atexit_hook(int status);
^
If I remove jl_atexit_hook(); from the code, I get the following errors-
juliatest.cpp:(.text+0x1a): undefined reference to `jl_init_with_image'
juliatest.cpp:(.text+0x24): undefined reference to `jl_eval_string'
What am I doing wrong?
The example you are trying to compile is a little bit outdated. As already mentioned you need to give an exitcode to the jl_atexit_hook()
function. The linker message is about missing functions defined in libraries. To get rid of distribution details I downloaded and build the tarball. Now the example can be build using this makefile:
JULIA_DIR:=julia-0.4.2
JULIA_LIB:=$(JULIA_DIR)/usr/lib
JULIA_SRC:=$(JULIA_DIR)/src
JULIA_INC:=$(JULIA_DIR)/usr/include
CPPFLAGS:=-I$(JULIA_INC) -I$(JULIA_SRC) -I$(JULIA_SRC)/support
LDFLAGS:=-L$(JULIA_LIB)
LDLIBS=-ljulia
export LD_LIBRARY_PATH:=$(JULIA_LIB):$(JULIA_LIB)/julia
all: main
run: main
#./main
clean:
rm -f main
If you now type make run you will get the next error message about a wrong path the system image is searched in. As Thomas noted here the function jl_init() is creating a context that may fail in this case. We shall give the name and the path of the system image to the init function using jl_init_with_image("julia-0.4.2/usr/lib/julia", "sys.so") instead. This is an ugly hard coded path and can surely be replaced. But for getting started with this example and to get this problem known, it is enough. The corrected example is this:
#include <julia.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
/* required: setup the julia context */
jl_init_with_image("julia-0.4.2/usr/lib/julia", "sys.so");
/* run julia commands */
jl_eval_string("print(sqrt(2.0))");
/* strongly recommended: notify julia that the
program is about to terminate. this allows
julia time to cleanup pending write requests
and run all finalizers
*/
jl_atexit_hook(0);
putchar('\n');
return 0;
}
Running make run will now be a quite complicated way to calculate the square root of 2 :-)
Have fun.

Inputting values from .mat file to array in C++

I am trying to copy a 1100x1100 matrix from a .mat file to an array variable of type float in C++. I read online and found that the matio library is a good option. I installed their library using "make" on Ubuntu 12.04 (I followed the method given on their webpage).
However, I am unable to write code using it mainly because I am new to C++. I am using g++ to compile the file. I get errors such as "unknown reference to Mat_Open" and so on.
I did find this bit of code on the webpage:
#include <stdlib.h>
#include <stdio.h>
#include "matio.h"
int main(int argc,char **argv)
{
mat_t *matfp;
matvar_t *matvar;
matfp = Mat_Open(argv[1],MAT_ACC_RDONLY); //here argv[1] is "a.mat"?
if ( NULL == matfp )
{
fprintf(stderr,"Error opening MAT file %s0,argv[1]);
return EXIT_FAILURE;
}
matvar = Mat_VarReadInfo(matfp,"x"); // x is the variable we are trying to access?
if ( NULL == matvar )
{
fprintf(stderr,"Variable ’x’ not found, or error reading MAT file\n");
}
I have a couple of questions:
here, argv[1] corresponds to the .mat file I am trying to open right?
x in this code is the variable present in the .mat file I am trying to copy?
When I ran this code, I received errors stating - Unknown reference to Mat_Open and so on. Another couple of the same type of errors also were there.
I compiled this using : g++ abc.cpp -o test. (Followed by ./test. But I never got around to that due to the errors obtained during compilation).
How can I make it work? Is there any mistake with the code I used? Or with the compile statement I am using-maybe there are some linkers I need to use for compilation.
Thank you. Please remember that I am new to C++. Any advice would be helpful.
1) argv[1] - is a first parameter you put after your program call. If you want to "feel it", use debugger or code like this:
#include <iostream>
for (unsigned i = 0; i < argc; ++i)
{
std::cout << argv[i] << std::endl;
}
2) Yes, looking at http://libmatio.sourcearchive.com/documentation/1.3.4/group__MAT_g4c8205ff25c5b688a40775fbb1840b7e.html I can say, that you will read variable with name "x".
3) "undefined reference" means you need to build with matio libraries. Add something like "-lLibraryName" to your compile string. And it will have to be built.
To avoid many problems, try to install Code::Blocks, it's cross-platform and quite easy to start using C++ if you never did it before. It also supports debuggers, so you will avoid many problems quite easy.

Running c++ in browser

I have written some basic c++ programs in one of my classes for school. I was wondering if it was possible to somehow virtually run the program in a broswer. I would like to post the program to my website. Once its posted, a person could access the program, run the program, and, interact with the program. I'm not trying to write C++ for my website, it would be more for an interactive portfolio.
Is this possible?
Use codepad, a website which lets you compile and share code online.
#include <iostream>
int main(int argc, char** argv) {
std::cout << "Hello, Stack Overflow!" << std::endl;
return 0;
}
There is also Google Native Client SDK that allows C++ code to run in browser. Microsoft Active X is also a viable option. I am only saying it is possible not recommended.
You can only run the program on your server, not on the client's machine.
At least not without downloading and manually executing it. Anything else would be an open door for malware...
I see two options, but both very overkill:
Write (or find) a C++ interpreter in JavaScript
Use a VM running an operating system (e.g. jslinux and demonstrate your programs there.
The sensible option is to just give people a way to view and download the source code, I guess.
Google chrome supports this: http://www.readwriteweb.com/cloud/2011/08/google-officially-announces-cc.php
But it's by no means "mainstream" or standards-based.
Another solution (codepad like) would be to use https://ideone.com/ which seems much nicer to use than codepad, more user-friendly, but does the same:
Allow you to write C++ (60 languages possibles) directly from the browser and compile it and render result in the browser (I tried using printf and it worked fine). Possibility of forking source code.
https://ideone.com/baYzfe
The following two programs are quite useful :
1) Ideone
2) Codepad
You can compile, run, and share code online in any browser.
You can use Emscripten to compile C++ to Javascript. Emscripten can compile LLVM bitcode to Javascript. Some demos of Emscripten can be found here, including a raytracer and a text-to-speech engine that was compiled from C++ to Javascript.
To run x86 binaries in a web browser, you could also use an emulator such as v86. This is one possible way to compile and run C++ programs in a browser.
One of the best sites for running C++ and other multiple languages online is Repl.it
This example: repl.it/#abranhe/stackoverflow
#include <iostream>
int main() {
std::cout << "Hello Stackoverflow\n";
return 0;
}
One of the biggest pros it has is that you can work with multiple files, working with header (header.h) files etc. None of the below websites provide this option:
Codepad.org
JSLinux
IDEone
I really recommend it! You will love it!
Also wanted to add Google Colab here as an option:
Cell 1:
%%writefile hello.cpp
#include <iostream>
int main(int argc, char** argv) {
std::cout << "Hello, Stack Overflow!" << std::endl;
return 0;
}
Cell 2:
%%script bash
g++ hello.cpp -o test
ls -laX
./test

Run the same C++ Program from different Binary Names

Okay, for a homework assignment my professor wants us to write a program in C++ that converts from miles to km. I did all that, the program runs. However, he has this special way of calling the program:
The program's usage options are based
on the NAME of the BINARY FILE. If
the program name is 'km2miles', the
program interprets the command line
argument as a kilometer value to
convert to miles. If the name is
'miles2km', then it interprets as
miles being converted to km. Since the
first command line argument, argv[0]
is always the program's name, you can
use its value to decide which function
to call.
I only have 3 files in this project (he tells us to ONLY have these 3):
convert.cpp
distance.cpp
distance.h
Distance .h and .cpp have the different functions to convert Mi to Km and Vice Versa, the convert.cpp has the main function. However, the only way I know how to call this program (after compiling it) is to say:
./convert 10
Where 10 is the number to convert. He says it should be called like this:
$ km2miles 100
and
$ miles2km 60
I have no idea how to get the program to act differently by having a different name... especially when that name doesn't even run the program! Help would be appreciated.
You can:
specify a name when you build it, and build it twice
on Windows: copy convert miles2kms; copy convert kms2miles
on UNIX/Linux: cp convert miles2kms; cp convert kms2miles
on UNIX/Linx (better): make a link or symbolic link: ln -s convert miles2kms; ln -s convert kms2miles.
Inside your program, you should be doing something like:
#include <string>
#include <iostream>
int main(int argc, const char* argv[])
{
std::string program_name = argv[0];
if (argc != 2) {
std::cerr << "usage: " << program_name << " <value>\n";
return 0;
}
if (/* TODO: what would go here? */)
...
else
...
}
The instructions already tell you how:
Since the first command line argument, argv[0] is always the program's name, you can use its value to decide which function to call.
especially when that name doesn't even run the program!
If you're using gcc, by default it generates a binary named a.out, but you can rename it to be whatever you want. (Or you can specify the name of the output file via the -o command-line option.)
Well, he gave you one clue with the argv[0] thing.
Did you perhaps discuss symbolic links at some point in your class?
Difficult for me to give more hints without actually giving away the answer.
If you don't want to recompile the same code into 2 different executable files then you may need to use a symbolic link:
http://en.wikipedia.org/wiki/Symbolic_link