Change something in C program with Shell Script - c

Is it possible to write a script to run this code for different values of A;
#include <stdio.h>
#define A 3
int main (){
printf("In this version A = %d\n", A);
return(0);
}
I guess something like for loop?

Is it possible to write a script to run this code for different values of A;
Not as it is because the macro A has a fixed value defined in your code. Instead you can pass the value as an argument:
#include <stdio.h>
int main(int argc, char **argv){
if(argc == 2) {
printf("In this version A = %s\n", argv[1]);
}
return 0;
}
(The code doesn't check if its input is an integer -- which you can test if necessary).
and you can run it via script. For example, compile the above (gcc -Wall -Wextra test.c -o test) using a for loop of bash:
$ for ((i = 0; i < 10; i++)); do ./test $i; done
In this version A = 0
In this version A = 1
In this version A = 2
In this version A = 3
In this version A = 4
In this version A = 5
In this version A = 6
In this version A = 7
In this version A = 8
In this version A = 9
$

No. But you can make A a command line arg:
#include <stdio.h>
int main (int argc, char *argv[]) {
int a;
if (argc != 2 || sscanf(argv[1], "%d", &a) != 1) return 1;
printf("In this version A = %d\n", a);
return 0;
}
Compile to a binary named foo, then
foo 42
will print
In this version A = 42
You can also compile different versions by defining A in the compilation command line. From your original program, remove the #define. Then
gcc -DA=42 foo.c -o foo
./foo
will print the same as above.

DO you need run program repeated from script? why not to make program that accepts arguments from command line?
1)The main() function actually takes arguments, you can compile program once and pass different parameters, as shown in answers above
2) If you need to change some code parameters from make script, I'd say, create separate header that would contain defines and write script that would echo into that file (> for start, >> to continue writing).
3) Alternative way you can call you compiler with flag that would be equal to #define macro-command. For gcc it's -D, for example -DA=3 instead of #define A 3.
Most programs use makefile to be compiled. For that case you can script make file to use 2) or 3) Former is preferable because you do not need to pass that argument to all compilation targets, reducing time or re-compiling. There are tools for more advanced manipulations, like autoconf.

Related

scanf produces segfault when the program is run with a custom entry point (using gcc 7.4.0)

Consider the following code:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("main\n");
int a;
scanf("%d", &a);
printf("a = %d\n", a);
return 0;
}
int main1() {
printf("main1\n");
int a;
scanf("%d", &a);
printf("a = %d\n", a);
exit(0);
return 0;
}
int main2() {
printf("main2\n");
int a = getchar() - '0';
int b = getchar() - '0';
int c = getchar() - '0';
printf("a = %d\n", 100 * a + 10 * b + c);
exit(0);
return 0;
}
Assuming that the code resides in a file called test.c, the following works fine (it prints "a = 123"):
gcc -o test test.c
echo 123 | ./test
If, however, I run the program with a custom entry point, I get the dreaded Segmentation fault:
gcc -o test test.c -e"main1"
echo 123 | ./test
But if I replace the scanf with three getchars, the program runs fine again despite being run with a custom entry point:
gcc -o test test.c -e"main2"
echo 123 | ./test
To make things even more interesting, these problems occur with gcc 7.4.0 but not with gcc 4.8.4.
Any ideas?
The -e command line flag redefines the actual entry point of your program, not the “user” entry point. By default, using GCC with the GNU C standard library (glibc) this entry point is called _start, and it performs further setup before invoking the user-provided main function.
If you want to replace this entry point and continue using glibc you’ll need to perform further setup yourself. But alternatively you can use the following method to replace the main entry point, which is much simpler:
gcc -c test.c
objcopy --redefine-sym main1=main test.o
gcc -o test test.o
Note, this will only work if you don’t define main in your code, otherwise you’ll get a “multiple definition of `main'” error from the linker.

How to prints the built in functions name used in our program using a specific header file in C?

I need to find the built-in functions used in our program from a specific header file.
For example, I have the C file below:
#include<stdio.h>
int main()
{
int a;
scanf("%d",&a);
printf("a = %d\n", a);
}
If I given the stdio.h header file to any command, it needs to give the output as below:
scanf
printf
Is there any built-in command to get this?
Or any options available in the gcc or cc command to get this?
If you are using GCC as compiler, you can run this command:
echo "#include <stdio.h>" | gcc -E -
This will print many lines from the stdio.h header, and from the files that are included by that header, and so on.
Some lines look like #line …, they tell you where the following lines come from.
You can analyze these lines, but extracting the functions from them (parsing) is quite complicated. But if you just want a quick, unreliable check, you could search whether these lines contain the word scanf or printf.
EDIT
As suggested in a comment, the -aux-info is more useful, but it works only when compiling a file, not when preprocessing. Therefore:
cat <<EOF >so.c
#include <stdio.h>
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
fprintf(stdout, "%s%c", argv[i], i < argc - 1 ? ' ' : '\n');
}
fflush(stdout);
return ferror(stdout) == -1;
}
EOF
gcc -c so.c -aux-info so.aux
Determining the function calls from your program can be done using objdump, as follows:
objdump -t so.c
The above commands give you the raw data. You still need to parse this data and combine it to only give you the data relevant to your question.

Glob function gives only one result in C

I have to program a shell in C and need to handle globing in it and I am only allowed to use the function glob. But when I try to use it, it only gives me one result back.
#include <glob.h>
#include <stdlib.h>
int main(int ac, char **av)
{
glob_t s;
unsigned long i = -1;
if (glob(av[1], 0, NULL, &s))
printf("ERROR !\n");
else
while (++i < s.gl_pathc)
printf("%s\n", s.gl_pathv[i]);
return (0);
}
I run this code in a folder where there is two C files : replace_glob.c and test.c
And when I run this code :
$ ./a.out *.c
replace_glob.c
$
I dont understand why and I would really appreciate your help
In the command line
./a.out *.c
the shell expands the glob pattern, so your program sees
{"./a.out", "replace_glob.c", "test.c", NULL}
as its argv. You need to quote the pattern for the program to see it:
./a.out '*.c'

How can I Pass variables to C programm using gcc

How can I Pass variables to C program using gcc ??
For example
gcc -o server ./server.c --host=localhost --port=1234
how to access these variables in my code ?
Thank you.
Your question isn't clear; there are at least two things you might be asking about: how to access command line arguments passed to your program when it is run and how to access arguments passed to the compiler when your program is compiled.
Command line arguments:
./server --host=localhost --port=1234
These are accessed via arguments to main():
int main(int argc, char *argv[]) {
for (int i=0; i<argc; ++i) {
std::cout << argv[i] << '\n';
}
}
getopt is a pretty common way to parse these command line options, though it isn't part of the C or C++ standards.
Compiler arguments:
You can't necessarily access arguments passed to the compiler, but for the arguments you can detect you detect them through changes to the compile environment. For example if the compiler takes an option to enable a language feature then you can detect when that option is passed by detecting if the feature is enabled.
gcc -std=c11 main.cpp
int main() {
#if 201112L <= __STDC_VERSION__
printf("compiler was set to C11 mode (or greater).\n");
#else
printf("compiler set to pre-C11 mode.\n");
#endif
}
Additionally you can directly define macros in command line arguments to the compiler that the program will be able to access.
gcc -DHELLO="WORLD" main.cpp
int main() {
#if defined(HELLO)
printf("%s\n", HELLO);
#else
printf("'HELLO' is not defined\n");
#endif
}
If you want to define them at compile-time see the -D param, if you want to define them at runtime use something like
int main(int,char**);
int main(int argsc/*argument count*/, char**argv/*argument vector*/)
{
int i;
for(i=0;i<argsc;i++)
{
printf("%s\n",argsv[i]);
}
return 0;
}
If you want to pass variables to your program execution, you can use environment variables. Like this:
char* myOption = getenv("MY_OPTION_NAME");
if(!myOption) myOption = "my default value";
//Do whatever you like with the value...
And when you call your program, you can set the variables inline by assigning them before the program name:
MY_OPTION_NAME="foo" ./server
You could also set your environment variables once and for all using
export MY_OPTION_NAME="foo"

Dynamic obfuscation by self-modifying code

Here what's i am trying to do:
assume you have two fonction
void f1(int *v)
{
*v = 55;
}
void f2(int *v)
{
*v = 44;
}
char *template;
template = allocExecutablePages(...);
char *allocExecutablePages (int pages)
{
template = (char *) valloc (getpagesize () * pages);
if (mprotect (template, getpagesize (),
PROT_READ|PROT_EXEC|PROT_WRITE) == -1) {
perror (“mprotect”);
}
}
I would like to do a comparison between f1 and f2 (so tell what is identical and what is not) (so get the assembly lines of those function and make a line by line comparison)
And then put those line in my template.
Is there a way in C to do that?
THanks
Update
Thank's for all you answers guys but maybe i haven't explained my need correctly.
basically I'm trying to write a little obfuscation method.
The idea consists in letting two or more functions share the same location in memory. A region of memory (which we will call a template) is set up containing some of the
machine code bytes from the functions, more specifically, the ones they all
have in common. Before a particular function is executed, an edit script is used
to patch the template with the necessary machine code bytes to create a
complete version of that function. When another function assigned to the same
template is about to be executed, the process repeats, this time with a
different edit script. To illustrate this, suppose you want to obfuscate a
program that contains two functions f1 and f2. The first one (f1) has the
following machine code bytes
Address Machine code
0 10
1 5
2 6
3 20
and the second one (f2) has
Address Machine code
0 10
1 9
2 3
3 20
At obfuscation time, one will replace f1 and f2 by the template
Address Machine code
0 10
1 ?
2 ?
3 20
and by the two edit scripts e1 = {1 becomes 5, 2 becomes 6} and e2 = {1
becomes 9, 2 becomes 3}.
#include <stdlib.h>
#include <string.h>
typedef unsigned int uint32;
typedef char * addr_t;
typedef struct {
uint32 offset;
char value;
} EDIT;
EDIT script1[200], script2[200];
char *template;
int template_len, script_len = 0;
typedef void(*FUN)(int *);
int val, state = 0;
void f1_stub ()
{
if (state != 1) {
patch (script1, script_len, template);
state = 1;
}
((FUN)template)(&val);
}
void f2_stub () {
if (state != 2) {
patch (script2, script_len, template);
state = 2;
}
((FUN)template)(&val);
}
int new_main (int argc, char **argv)
{
f1_stub ();
f2_stub ();
return 0;
}
void f1 (int *v) { *v = 99; }
void f2 (int *v) { *v = 42; }
int main (int argc, char **argv)
{
int f1SIZE, f2SIZE;
/* makeCodeWritable (...); */
/* template = allocExecutablePages(...); */
/* Computed at obfuscation time */
diff ((addr_t)f1, f1SIZE,
(addr_t)f2, f2SIZE,
script1, script2,
&script_len,
template,
&template_len);
/* We hide the proper code */
memset (f1, 0, f1SIZE);
memset (f2, 0, f2SIZE);
return new_main (argc, argv);
}
So i need now to write the diff function. that will take the addresses of my two function and that will generate a template with the associated script.
So that is why i would like to compare bytes by bytes my two function
Sorry for my first post who was not very understandable!
Thank you
Do you want to do this at runtime or during authorship?
You can probably instruct your C compiler to produce assembly language output, for example gcc has the -S option which will produce output in file.s Your compiler suite may also have a program like objdump which can decompile an object file or entire executable. However, you generally want to leave optimizations up to a modern compiler rather than do it yourself.
At runtime the & operator can take the address of a function and you can read through it, though you have to be prepared for the possibility of encountering a branch instruction before anything interesting, so you actually have to programatically "understand" at least a subset of the instruction set. What you will run into when reading function pointers will of course vary all over the place by machine, ABI, compiler, optimization flags, etc.
Put the functions into t1.c and t2.c use gcc -S to generate assembly output:
gcc -S t1.c
gcc -S t2.c
Now compare t1.s and t2.s.
If you are using Visual Studio, go to
Project Properties -> Configuration -> C/C++ -> Output Files -> Assembler output
or use compiler switches /FA, /FAc, /FAs, /FAcs. Lower-case c means output machine code, s-source code side-by-side with assembly code. And don't forget to disable compiler optimizations.
Having read through some of the answers and the comments there, I'm not sure I fully understand your question, but maybe you're looking for a gcc invocation like the following:
gcc -S -xc - -o -
This tells gcc to input C code from stdin and output assembly to stdout.
If you use a vi-like editor, you can highlight the function body in visual mode and then run the command:
:'<,'>!gcc -S -xc - -o - 2> /dev/null
...and this will replace the function body with assembly (the "stderr > /dev/null" business is to skip errors about #include's).
You could otherwise use this invocation of gcc as part of a pipeline in a script.

Resources