How to use tcl apis in a c code - tcl

I want to use some of the functionalities(APIs) of my tcl code in another "c" code file. But i am not getting how to do that especiallly how to link them. For that i have taken a very simple tcl code which contains one API which adds two numbers and prints the sum. Can anybody tell me how can i call this tcl code to get the sum. How can i write a c wrapper that will call this tcl code. Below is my sample tcl program that i am using :
#!/usr/bin/env tclsh8.5
proc add_two_nos { } {
set a 10
set b 20
set c [expr { $a + $b } ]
puts " c is $c ......."
}

To evaluate a script from C code, use Tcl_Eval() or one of its close relatives. In order to use that API, you need to link in the Tcl library, initialize the Tcl library and create an interpreter to hold the execution context. Plus you really ought to do some work to retrieve the result and print it out (printing script errors out is particularly important, as that helps a lot with debugging!)
Thus, you get something like this:
#include <tcl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source myscript.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}

I think i have sloved it out. You were correct. The problem was with the include method that i was using. I have the files tcl.h, tclDecls.h and tclPlatDecls.h included in the c code but these files were not existing in the path /usr/include so i was copying these files to that directory, may be it was not a proper way to do. Finally i have not copied those files to /usr/include and gave the include path while compiling. I have created executable and it is givingthe proper result on terminal. Thanks for your help.
Here is the exact c code i am using :
#include <tcl.h>
#include <tclDecls.h>
#include <tclPlatDecls.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
printf("inside main function \n");
// Tcl_InitStubs(interp, "8.5", 0);
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source simple_addition.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}
And to compile this code and to generate executable file i am using below command :
gcc simple_addition_wrapper_new.c -I/usr/include/tcl8.5/ -ltcl8.5 -o simple_addition_op
I have executed the file simple_addition_op and got below result which was proper
inside main function
c is 30 .......
My special thanks to Donal Fellows and Johannes

Related

Running AFL-Fuzzer buffer overflow

I am trying to learn about AFL-fuzzer and I have some questions:
I saw a video shows that if for instance there are two inputs in the code, so in the test case each line is for each input. Is that correct? Since I want put a full message (for example HTTP request) into one variable, so how do I do it?
I don't understand when to put ##.
For example I am trying to fuzz this code:
void Check_buffer(char* data)
{
char buffer[5];
strcpy(buffer, data);
}
int main(int argc, char* argv[])
{
char tmp_data = argv[1];
Check_buffer(argv[1]);
return 0;
}
I have created the in and out folders. In the in folder I have created a txt file with this content: "AAA".
The command line I have executed is:afl-clang -fno-stack-protector -z execstack 4.c -o vul4
Then I run:afl-fuzz -m none -i in/ -o out/ ./vul4 ##
I get the following error:perform_dry_run(), afl-fuzz.c:2852
If I run the command like this:afl-fuzz -m none -i in/ -o out/ ./vul4 AA
it runs good but it does not find any new path and does not find crashes.
As well as, I am trying to understand the concepts of this. If I want to inject code in specific location, how do I do it?
You are trying to get data from command line arguments, but the AFL does not work with argv[] (unless your program reads files like ./prog file.txt ).
Instead use something like
#define INPUTSIZE 100
char input[INPUTSIZE] = {0};
read (STDIN_FILENO, input, INPUTSIZE)
If you are still interested in getting data from argv[], you can use the experimental method from the AFL repository afl argv experimental
## is used when your program accepts a file via the command line
this means that the fuzzer will take the file, mutate it, and substitute it into the program instead ##
p.s.
#include <stdio.h>
#include <unistd.h>
#define INPUTSIZE 100
void Check_buffer(char* data)
{
char buffer[5];
strcpy(buffer, data);
}
int main(int argc, char* argv[])
{
char input[INPUTSIZE] = {0};
read (STDIN_FILENO, input, INPUTSIZE);
Check_buffer(input);
return 0;
}
AFL result image

texinfo include HTML header from file

I am writing a Texinfo manual, and for its HTML I need to include the contents of another file into the <head> ... </head> section of the HTML output. To be more specific, I want to add mathjax capability to the HTML version of the output to show equations nicely. But I can't seem to find how I can add its <script>...</script> to the header!
Since I couldn't find an answer and doing the job my self didn't seem to hard, I wrote a tiny C program to do the job for me. It did the job perfectly in my case!
Ofcourse, if there is an option in Texinfo that does the job, that would be a proper answer, this is just a remedy to get things temporarily going for my self.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ADDTOHEADER " \n\
<script type=\"text/javascript\" \n\
src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\">\n\
</head>"
void
addtexttohtml(char *filename)
{
char toadd[]=ADDTOHEADER;
size_t len=0;
ssize_t read;
FILE *in, *out;
char tmpname[]="tmp457204598345.html", *line=NULL;
in=fopen(filename, "r");
out=fopen(tmpname, "w");
if (in == NULL) exit(EXIT_FAILURE);
if (out == NULL) exit(EXIT_FAILURE);
while ((read = getline(&line, &len, in)) != -1)
{
if(strcmp(line, "</head>\n")==0) break;
fprintf(out, "%s", line);
}
fprintf(out, "%s", toadd);
while ((read = getline(&line, &len, in)) != -1)
fprintf(out, "%s", line);
if(line)
free(line);
fclose(in);
fclose(out);
rename(tmpname, filename);
}
int
main(int argc, char *argv[])
{
int i;
for(i=1;i<argc;i++)
addtexttohtml(argv[i]);
return 0;
}
This program can easily be compiled with $ gcc addtoheader.c.
Then we can easily put the compiled program (by default it should be called a.out) with the HTML files and run:
$ a.out *.html
You can just change the macro for any text you want.

Clang fails to throw a std::bad_alloc when allocating objects that would exceed the limit

I am having trouble understanding how clang throws exceptions when I try to allocate an object that would exceed its limit. For instance if I compile and run the following bit of code:
#include <limits>
#include <new>
#include <iostream>
int main(int argc, char** argv) {
typedef unsigned char byte;
byte*gb;
try{
gb=new byte[std::numeric_limits<std::size_t>::max()];
}
catch(const std::bad_alloc&){
std::cout<<"Normal"<<std::endl;
return 0;}
delete[]gb;
std::cout<<"Abnormal"<<std::endl;
return 1;
}
then when I compile using "clang++ -O0 -std=c++11 main.cpp" the result I get is "Normal" as expected, but as soon as I enable optimizations 1 through 3, the program unexpectedly returns "Abnormal".
I am saying unexpectedly, because according to the C++11 standard 5.3.4.7:
When the value of the expression in a noptr-new-declarator is zero, the allocation function is called to
allocate an array with no elements. If the value of that expression is less than zero or such that the size
of the allocated object would exceed the implementation-defined limit, or if the new-initializer is a braced-
init-list for which the number of initializer-clauses exceeds the number of elements to initialize, no storage
is obtained and the new-expression terminates by throwing an exception of a type that would match a
handler (15.3) of type std::bad_array_new_length (18.6.2.2).
[This behavior is observed with both clang 3.5 using libstd++ on linux and clang 3.3 using libc++ on Mac. The same behavior is also observed when the -std=c++11 flag is removed.]
The plot thickens when I compile the same program using gcc 4.8, using the exact same command line options. In that case, the program returns "Normal" for any chosen optimization level.
I cannot find any undefined behavior in the code posted above that would explain why clang would feel free not to throw an exception when code optimizations are enabled. As far as the bug database is concerned, the closest I can find is http://llvm.org/bugs/show_bug.cgi?id=11644 but it seems to be related to the type of exception being thrown rather than a behavior difference between debug and release code.
So it this a bug from Clang? Or am I missing something? Thanks,
It appears that clang eliminates the allocation as the array is unused:
#include <limits>
#include <new>
#include <iostream>
int main(int argc, char** argv)
{
typedef unsigned char byte;
bytes* gb;
const size_t max = std::numeric_limits<std::size_t>::max();
try
{
gb = new bytes[max];
}
catch(const std::bad_alloc&)
{
std::cout << "Normal" << std::endl;
return 0;
}
try
{
gb[0] = 1;
gb[max - 1] = 1;
std::cout << gb[0] << gb[max - 1] << "\n";
}
catch ( ... )
{
std::cout << "Exception on access\n";
}
delete [] gb;
std::cout << "Abnormal" << std::endl;
return 1;
}
This code prints "Normal" with -O0 and -O3, see this demo. That means that in this code, it is actually tried to allocate the memory and it indeed fails, hence we get the exception. Note that if we don't output, clang is still smart enough to even ignore the writes.
It appears that clang++ on Mac OSX does throw bad_alloc, but it also prints an error message from malloc.
Program:
// bad_alloc example
#include <iostream> // std::cout
#include <sstream>
#include <new> // std::bad_alloc
int main(int argc, char *argv[])
{
unsigned long long memSize = 10000;
if (argc < 2)
memSize = 10000;
else {
std::istringstream is(argv[1]); // C++ atoi
is >> memSize;
}
try
{
int* myarray= new int[memSize];
std::cout << "alloc of " << memSize << " succeeded" << std::endl;
}
catch (std::bad_alloc& ba)
{
std::cerr << "bad_alloc caught: " << ba.what() << '\n';
}
std::cerr << "Program exiting normally" << std::endl;
return 0;
}
Mac terminal output:
david#Godel:~/Dropbox/Projects/Miscellaneous$ badalloc
alloc of 10000 succeeded
Program exiting normally
david#Godel:~/Dropbox/Projects/Miscellaneous$ badalloc 1234567891234567890
badalloc(25154,0x7fff7622b310) malloc: *** mach_vm_map(size=4938271564938272768)
failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
bad_alloc caught: std::bad_alloc
Program exiting normally
I also tried the same program using g++ on Windows 7:
C:\Users\David\Dropbox\Projects\Miscellaneous>g++ -o badallocw badalloc.cpp
C:\Users\David\Dropbox\Projects\Miscellaneous>badallocw
alloc of 10000 succeeded
C:\Users\David\Dropbox\Projects\Miscellaneous>badallocw 1234567890
bad_alloc caught: std::bad_alloc
Note: The program is a modified version of the example at
http://www.cplusplus.com/reference/new/bad_alloc/

How do I open a URL from C++?

how can I open a URL from my C++ program?
In ruby you can do
%x(open https://google.com)
What's the equivalent in C++? I wonder if there's a platform-independent solution. But if there isn't, I'd like the Unix/Mac better :)
Here's my code:
#include <stdio.h>
#include <string.h>
#include <fstream>
int main (int argc, char *argv[])
{
char url[1000] = "https://www.google.com";
std::fstream fs;
fs.open(url);
fs.close();
return 0;
}
Your question may mean two different things:
1.) Open a web page with a browser.
#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );
This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.
2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read this or/and this.
I hope it's at least a little helpful.
EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.
Use libcurl, here is a simple example.
EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system on a POSIX system:
system("<mybrowser> http://google.com");
By replacing <mybrowser> with the browser you want to launch.
Here's an example in windows code using winsock.
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
string website_HTML;
locale local;
void get_Website(char *url );
int main ()
{
//open website
get_Website("www.google.com" );
//format website HTML
for (size_t i=0; i<website_HTML.length(); ++i)
website_HTML[i]= tolower(website_HTML[i],local);
//display HTML
cout <<website_HTML;
cout<<"\n\n";
return 0;
}
//***************************
void get_Website(char *url )
{
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
char *get_http= new char[256];
memset(get_http,' ', sizeof(get_http) );
strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
strcat(get_http,url);
strcat(get_http,"\r\nConnection: close\r\n\r\n");
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(url);
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting to "<< url<<" ...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
{
cout << "Could not connect";
system("pause");
//return 1;
}
cout << "Connected.\n";
send(Socket,get_http, strlen(get_http),0 );
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
{
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')
{
website_HTML+=buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
delete[] get_http;
}
I was having the exact same problem in Windows.
I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:
'open' is not recognized as an internal or external command
After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.
Linux: xdg-open <URL>
Windows: start <URL>
For those of you that are using Windows, as I am, you can use the following:
std::string op = std::string("start ").append(url);
system(op.c_str());
I've had MUCH better luck using ShellExecuteA(). I've heard that there are a lot of security risks when you use "system()". This is what I came up with for my own code.
void SearchWeb( string word )
{
string base_URL = "http://www.bing.com/search?q=";
string search_URL = "dummy";
search_URL = base_URL + word;
cout << "Searching for: \"" << word << "\"\n";
ShellExecuteA(NULL, "open", search_URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
p.s. Its using WinAPI if i'm correct. So its not multiplatform solution.
There're already answers for windows. In linux, I noticed open https://www.google.com always launch browser from shell, so you can try:
system("open https://your.domain/uri");
that's say
system(("open "s + url).c_str()); // c++
https://linux.die.net/man/1/open
C isn't as high-level as the scripting language you mention. But if you want to stay away from socket-based programming, try Curl. Curl is a great C library and has many features. I have used it for years and always recommend it. It also includes some stand alone programs for testing or shell use.
For linux environments, you can use xdg-open. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.
$ xdg-open https://google.com
$ xdg-open steam://run/10
Of course you can wrap this in a system() call.
Create a function and copy the code using winsock which is mentioned already by Software_Developer.
For Instance:
#ifdef _WIN32
// this is required only for windows
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
//...
}
#endif
winsock code here
#ifdef _WIN32
WSACleanup();
#endif

Emulating execvp - Is There a Better Way To Do This?

I'm currently wrapping a command line tool (espeak) with Tcl/Tk, and I have figured this out so far:
load ./extensions/system.so
package require Tk
package require Tclx
set chid 0
proc kill {id} {
exec kill -9 $id
}
proc speak {} {
global chid
set chid [fork]
if {$chid == 0} {
execvp espeak [.text get 1.0 end]
}
}
proc silent {} {
global chid
kill $chid
}
Where system.so is an extension I hacked together to be able to use execvp:
#include <tcl.h>
#include <tclExtend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int
execvp_command(ClientData cdata, Tcl_Interp *interp, int argc, const char* argv[])
{
if (argc == 1)
{
interp->result = "execvp command ?args ...?";
return TCL_ERROR;
}
execvp(argv[1], argv + 1);
return TCL_OK;
}
int System_Init(Tcl_Interp* interp)
{
if (Tcl_InitStubs(interp, "8.1", 0) == NULL)
return TCL_ERROR;
Tcl_CreateCommand(interp, "execvp", execvp_command, NULL, NULL);
Tcl_PkgProvide(interp, "system", "1.0");
return TCL_OK;
}
The reason I need execvp is because a subprocess created by exec (Tcl) seems to keep going when the process dies (I can confirm this by ^C'ing out of the GUI), whereas if I use execvp, espeak dies properly.
Thus, all I really need out of this script is to be able to start a subprocess and kill it on demand.
Is there another library that can do this properly, like Expect?
Tcl uses execvp internally (really; I've just checked the source) so the difference lies elsewhere. That elsewhere will be in signals; the subprocess created by the exec command (and other things that use the same underlying engine) will have the majority of signals forced to use the default signal handlers, but since the only signal it sets to non-default is SIGPIPE, I wonder what else is going on.
That said, the definitive extension for working with this sort of thing is TclX. That gives you access to all the low-level POSIX functionality that you've been using partially. (Expect may also be able to do it.)