Considering this example :
#include <stdio.h>
#include <unistd.h>
int main()
{
int pgid;
if ((pgid = getpgid(0)) == -1)
perror("getpgid");
else
printf("pgid : %d\n", pgid);
}
When I'm running this program without valgrind, everything is going right, and the pgid is printed.
Whenever I'm using valgrind, perror will print getpgid: Function not implemented.
Is it normal that getpgid is not available under valgrind ?
Is there any alternative to get the pgid of a specific pid (excluding
getpgrp) ?
I'm using macOS Sierra 10.12.6 and valgrind-3.15.0.
It seem that valgrind could have some trouble to perform some syscall.
In the valgrind trace, I'm having :
--17135-- WARNING: unhandled amd64-darwin syscall: unix:151
--17135-- You may be able to write your own handler.
--17135-- Read the file README_MISSING_SYSCALL_OR_IOCTL.
--17135-- Nevertheless we consider this a bug. Please report
--17135-- it at http://valgrind.org/support/bug_reports.html.
So I need to create a wrapper for the function, and it should work.
I will report the bug to the support.
You shouldn't test via valgrind on Mac OS X because after Sierra, it is not supported. Instead, also it is what I do, install ubuntu via an virtual machine software then run valgrind.
macOS Mojave 10.14.6's unistd.h has the following part,
#if __DARWIN_UNIX03
void encrypt(char *, int) __DARWIN_ALIAS(encrypt);
#else /* !__DARWIN_UNIX03 */
int encrypt(char *, int);
#endif /* __DARWIN_UNIX03 */
int fchdir(int);
long gethostid(void);
pid_t getpgid(pid_t);
pid_t getsid(pid_t);
Rule of thumb, always try to be portable!
Incidentally, as #Andrew Henle mentions, pid_t can be of system-dependent type. But, it shouldn't be unsigned type to preserve portability since it can be returned as -1 in the case of a failure. Moreover, on Mac OS X its type is int, as seen below
typedef int __int32_t;
typedef __int32_t __darwin_pid_t; /* [???] process and group IDs */
typedef __darwin_pid_t pid_t;
Related
I am testing a small code which involves creating a thread on my ARMv8 device.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *fun(void *arg)
{
sleep(2);
printf("%s: Exiting now\n", __func__);
pthread_exit(0);
//return 0;
}
int main()
{
pthread_t th;
pthread_create(&th, NULL, fun, NULL);
sleep(3);
printf("%s: Wait over\n", __func__);
return 0;
}
When I compile the code into a 32-bit executable and run it on the device, it seems to run fine.
fun: Exiting now
main: Wait over
But when I build it into 64-bit executable, I get the following output:
fun: Exiting now
Aborted (core dumped)
As far as I know, ARMv8 is completely backward-compatible. But here, the 32-bit binary runs while 64-bit binary hangs up.
Apart from that, while trying out things, I found when I change the fun() to:
void *fun(void *arg)
{
sleep(2);
printf("%s: Exiting now\n", __func__);
//pthread_exit(0);
return 0;
}
Both 32-bit and 64-bit binaries run fine.
I looked into this article:
Pthread: Why people bother using pthread_exit? and didn't get much information as to where the problem might be.
Here is some more information about my device:
Linux Version: Linux version 4.4.67 (lnxbuild#ecbld-bd213-lnx) (gcc version 4.9.3 (GCC) ) #1 SMP PREEMPT
Total Memory : 3721056
So here are my questions:
Can there be any reason why the 32-bit binary runs while the 64-bit crashes on an ARMv8 device?
How does this error fix when I replace pthread_exit(0) with return 0?
Is there anything else that I might be missing here?
Minor Update:
I have tried changing the wait times and making various combinations of pthread_join(), pthread_detach() and pthread_exit() at all possible places, but to no avail. This is the simplest version I could provide.
Here is the example code that crashes:
#include <stdio.h>
#include <poll.h>
#include <stdlib.h>
#include <limits.h>
#define POLL_SIZE 1024
int main(int argc, const char * argv[]) {
printf("%d\n", OPEN_MAX);
struct pollfd *poll_ = calloc(POLL_SIZE, sizeof(struct pollfd));
if (poll(poll_, POLL_SIZE, -1) < 0)
if (errno == EINVAL)
perror("poll error");
return 0;
}
If you set POLL_SIZE to 256 or less, the code works just fine. What's interesting is that if you run this code in Xcode, it executes normally, but if you run the binary yourself you get a crash.
The output is like this:
10240
poll error: Invalid argument
According to poll(2):
[EINVAL] The nfds argument is greater than OPEN_MAX or the
timeout argument is less than -1.
As you can see, POLL_SIZE is a lot smaller than the limit, and the timeout is exactly -1, yet it crashed.
My clang version that I use for manual building:
Configured with: prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.41)
Target: x86_64-apple-darwin16.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
On Unix systems, processes have limits on resources. See e.g. getrlimit. You might change them (using setrlimit) and your sysadmin can also change them (e.g. configure these limits at startup or login time). There is a limit RLIMIT_NOFILE related to file descriptors. Read also about the ulimit bash builtin. See also sysconf with _SC_OPEN_MAX.
The poll system call is given a not-too-big array, and it is bad taste (possible, but inefficient) to repeat some file descriptor in it. So in practice you'll often use it with a quite small array mentioning different (but valid) file descriptors. The second argument to poll is the number of useful entries (practically, all different), not the allocated size of the array.
You may deal with many file descriptors. Read about the C10K problem.
BTW, your code is not crashing. poll is failing as documented (but not crashing).
You should read some POSIX programming book. Advanced Linux Programming is freely available, and most of it is on POSIX (not Linux specific) things.
Consider the following program (vul.c) with buffer overflow vulnerability.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char buf[10];
strcpy(buf, argv[1]);
printf("%s\n", buf);
return 0;
}
Above program compiled using gcc -o vul vul.c and executed on arch linux - linux 4.4.16-1-lts x86-64 gave following output when executed in terminal with ./vul $(perl -e 'print "A"x100') command:
AAAAAAAAAAA...A
Segmentation fault (core dumped)
Then checking the program status using echo $? command gave 139 output.
Following program (exp.c) (for crashing the above program)
#include <stdlib.h>
int main(void)
{
printf("%d\n", system("./vul $(perl -e 'print \"A\"x100')"));
return 0;
}
compiled using gcc -o exp exp.c when executed with ./exp command on same system gave following output:
AAAAAAAAAAAA...A
139
I have two questions:
Why no error message was generated by 2nd program? and,
I need to compile the program with -fstack-protector flag to enable the *** stack smashing detected *** error messages in arch linux but not in Ubuntu. In Ubuntu, it might be that this flag is include by default in gcc or is there any other reason?
As I pointed out in my comment,system returns an int with the programs's return value, which is normally it's error code (0 if successful).
If you want to print the error as a nice looking message, you can probably use strerror.
According to #rht's comment (see my next edit) and the answers to the question referenced in that comment, the returned value will be 0 on success and on error it will be error | 0x80. To get the original error code, use 128 - err_code.
try this:
#include <stdlib.h>
#include <errno.h>
int main(void)
{
int tmp = system("./vul $(perl -e 'print \"A\"x100)");
if(tmp < 0)
error("Couldn't run system command");
else if(tmp >0)
printf(stderr, "System command returned error: %s", strerror(128 - tmp));
else
; // nothing
return 0;
}
The fact that vul.c does (or does not) print an error message should be irrelevant for your exp.c program, since it depends on vul.c's compile flags values and any default compiler flags - things exp.c can't control.
EDIT(2) - in answer to the comment.
It could be that the error message returned isn't an errno value, but a signal trap value.
These are sometimes hard to differentiate and I have no good advice about how you can tell which one it is without using memcmp against the answer.
In this case you know vul.c will never return it's errno value, which leaves you only with signal trap errors, so you can use strsignal to print the error message.
As pointed out in #rht's comment, which references this question:
Passing tmp to strsignal generates the same error message: "unknown signal 139". The reason is that there is no signal with this signal number. /usr/include/bits/signum.h contains all the signals with their signal numbers. Passing tmp-128 to strsignal works.
i.e.
#include <stdlib.h>
#include <string>
int main(void)
{
int tmp = system("./vul $(perl -e 'print \"A\"x100)");
if(tmp < 0)
error("Couldn't run system command");
else if(tmp >0)
printf(stderr, "System command returned error: %s", strsignal(tmp - 128));
else
; // nothing
return 0;
}
EDIT
The question was edited because it's code was mis-copied. I altered the answer to reflect that change.
From my comment to #Myst 's answer for "passing tmp-128 to strsignal()" function, after experimenting a little I found that it does not work in situations where the program exited normally but returned status other than 0.
Following are the contents of my /usr/include/bits/waitstatus.h:
/* If WIFEXITED(STATUS), the low-order 8 bits of the status. */
#define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)
/* If WIFSIGNALED(STATUS), the terminating signal. */
#define __WTERMSIG(status) ((status) & 0x7f)
/* Nonzero if STATUS indicates normal termination. */
#define __WIFEXITED(status) (__WTERMSIG(status) == 0)
/* Nonzero if STATUS indicates termination by a signal. */
#define __WIFSIGNALED(status) \
(((signed char) (((status) & 0x7f) + 1) >> 1) > 0)
Above code show that, exit status of a program is a 16bit number, the high order 8 bits of which are the status that the program returned and some/all of the remaining bits are set if the program exited because of a signal, 7 bits of which denote the signal that caused the program to exit. That's why subtracting 128 from the exit status returned by system() will not work in the situation as described above.
System()'s source code
Since system() function too uses fork() to create a new process and waits for the termination of the process, the same method of checking a child process's status in parent process can also be applied here. Following program demonstrates this:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main(void)
{
int status = system("prg_name");
if (WIFEXITED(status))
printf("Exited Normally, status = %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("Killed by Signal %d which was %s\n", WTERMSIG(status), strsignal(WTERMSIG(status)));
return 0;
}
Answering my own 2nd question.
gcc -Q -v vul.c command displayed the options passed to the gcc. The options in Ubuntu included -fstack-protector-strong flag but not in arch-linux. So in Ubuntu, the flag is passed by default to gcc.
There exists two problems in your vul.c and exp.c.
In vul.c,
char buf[10];
10 is not sufficient in this case, since the argv[1], i.e., $(perl -e 'print "A"x100', is larger than the buffer to be allocated. Enlarge the buf size should fix the segmentation fault.
In exp.c, you're missing one single quote, and should be modified as followed:
printf("%d\n", system("./vul $(perl -e 'print \"A\"x100')"));
I have to check Linux system information. I can execute system commands in C, but doing so I create a new process for every one, which is pretty expensive. I was wondering if there is a way to obtain system information without being forced to execute a shell command. I've been looking around for a while and I found nothing. Actually, I'm not even sure if it's more convenient to execute commands via Bash calling them from my C program or find a way to accomplish the tasks using only C.
Linux exposes a lot of information under /proc. You can read the data from there. For example, fopen the file at /proc/cpuinfo and read its contents.
A presumably less known (and more complicated) way to do that, is that you can also use the api interface to sysctl. To use it under Linux, you need to #include <unistd.h>, #include <linux/sysctl.h>. A code example of that is available in the man page:
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/sysctl.h>
int _sysctl(struct __sysctl_args *args );
#define OSNAMESZ 100
int
main(void)
{
struct __sysctl_args args;
char osname[OSNAMESZ];
size_t osnamelth;
int name[] = { CTL_KERN, KERN_OSTYPE };
memset(&args, 0, sizeof(struct __sysctl_args));
args.name = name;
args.nlen = sizeof(name)/sizeof(name[0]);
args.oldval = osname;
args.oldlenp = &osnamelth;
osnamelth = sizeof(osname);
if (syscall(SYS__sysctl, &args) == -1) {
perror("_sysctl");
exit(EXIT_FAILURE);
}
printf("This machine is running %*s\n", osnamelth, osname);
exit(EXIT_SUCCESS);
}
However, the man page linked also notes:
Glibc does not provide a wrapper for this system call; call it using
syscall(2). Or rather... don't call it: use of this system call has
long been discouraged, and it is so unloved that it is likely to
disappear in a future kernel version. Since Linux 2.6.24, uses of this
system call result in warnings in the kernel log. Remove it from your
programs now; use the /proc/sys interface instead.
This system call is available only if the kernel was configured with
the CONFIG_SYSCTL_SYSCALL option.
Please keep in mind that anything you can do with sysctl(), you can also just read() from /proc/sys. Also note that I do understand that the usefulness of that syscall is questionable, I just put it here for reference.
You can also use the sys/utsname.h header file to get the kernel version, hostname, operating system, machine hardware name, etc. More about sys/utsname.h is here. This is an example of getting the current kernel release.
#include <stdio.h> // I/O
#include <sys/utsname.h>
int main(int argc, char const *argv[])
{
struct utsname buff;
printf("Kernel Release = %s\n", buff.release); // kernel release
return 0;
}
This is the same as using the uname command. You can also use the -a option which stands for all information.
uname -r # -r stands for kernel release
I have a very simple question, but I have not managed to find any answers to it all weekend. I am using the sendto() function and it is returning error code 14: EFAULT. The man pages describe it as:
"An invalid user space address was specified for an argument."
I was convinced that this was talking about the IP address I was specifying, but now I suspect it may be the memory address of the message buffer that it is referring to - I can't find any clarification on this anywhere, can anyone clear this up?
EFAULT It happen if the memory address of some argument passed to sendto (or more generally to any system call) is invalid. Think of it as a sort of SIGSEGV in kernel land regarding your syscall. For instance, if you pass a null or invalid buffer pointer (for reading, writing, sending, recieving...), you get that
See errno(3), sendto(2) etc... man pages.
EFAULT is not related to IP addresses at all.
Minimal runnable example with getcpu
Just to make things more concrete, we can have a look at the getcpu system call, which is very simple to understand, and shows the same EFAULT behaviour.
From man getcpu we see that the signature is:
int getcpu(unsigned *cpu, unsigned *node, struct getcpu_cache *tcache);
and the memory pointed to by the cpu will contain the ID of the current CPU the process is running on after the syscall, the only possible error being:
ERRORS
EFAULT Arguments point outside the calling process's address space.
So we can test it out with:
main.c
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>
int main(void) {
int err, ret;
unsigned cpu;
/* Correct operation. */
assert(syscall(SYS_getcpu, &cpu, NULL, NULL) == 0);
printf("%u\n", cpu);
/* Bad trash address == 1. */
ret = syscall(SYS_getcpu, 1, NULL, NULL);
err = errno;
assert(ret == -1);
printf("%d\n", err);
perror("getcpu");
return EXIT_SUCCESS;
}
compile and run:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Sample output:
cpu 3
errno 14
getcpu: Bad address
so we see that the bad call with a trash address of 1 returned 14, which is EFAULT as seen from kernel code: https://stackoverflow.com/a/53958705/895245
Remember that the syscall itself returns -14, and then the syscall C wrapper detects that it is an error due to being negative, returns -1, and sets errno to the actual precise error code.
And since the syscall is so simple, we can confirm this from the kernel 5.4 implementation as well at kernel/sys.c:
SYSCALL_DEFINE3(getcpu, unsigned __user *, cpup, unsigned __user *, nodep,
struct getcpu_cache __user *, unused)
{
int err = 0;
int cpu = raw_smp_processor_id();
if (cpup)
err |= put_user(cpu, cpup);
if (nodep)
err |= put_user(cpu_to_node(cpu), nodep);
return err ? -EFAULT : 0;
}
so clearly we see that -EFAULT is returned if there is a problem with put_user.
It is worth mentioning that my glibc does have a getcpu wrapper as well in sched.h, but that implementation segfaults in case of bad addresses, which is a bit confusing: How do I include Linux header files like linux/getcpu.h? But it is not what the actual syscall does to the process, just whatever glibc is doing with that address.
Tested on Ubuntu 20.04, Linux 5.4.
EFAULT is a macro defined in a file "include/uapi/asm-generic/errno-base.h"
#define EFAULT 14 /* Bad address */