Skip to content

Commit

Permalink
libselinux: Do not clobber errno of the world
Browse files Browse the repository at this point in the history
libselinux clobbers errno of all consumers (systemd, sshd you name it)
because its constructors do not properly save and restore errno.
The following program demonstrates it.

int main(void)
{
        assert(errno == 0);
	/* Just a test, it doesn't matter already clobbered */
        if(is_selinux_enabled() < 0) {
                perror("not enabled");
                return 1;
        }
}

if any function sets errno, it is not switched back to the original
value and standards DO NOT require errno to the set to zero before
entering main

Signed-off-by: Cristian Rodríguez <[email protected]>
  • Loading branch information
crrodriguez committed Sep 28, 2024
1 parent b411742 commit 1fd585e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
1 change: 1 addition & 0 deletions libselinux/src/init.c
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ void set_selinuxmnt(const char *mnt)
static void init_lib(void) __attribute__ ((constructor));
static void init_lib(void)
{
SELINUX_PROTECT_ERRNO;
selinux_page_size = sysconf(_SC_PAGE_SIZE);
init_selinuxmnt();
#ifndef ANDROID
Expand Down
10 changes: 10 additions & 0 deletions libselinux/src/selinux_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <selinux/selinux.h>
#include <pthread.h>
#include <errno.h>


extern int require_seusers ;
Expand Down Expand Up @@ -131,4 +132,13 @@ void *reallocarray(void *ptr, size_t nmemb, size_t size);
#define IGNORE_DEPRECATED_DECLARATION_END
#endif

static inline void selinux_reset_errno(int *saved_errno) {
if (*saved_errno < 0)
return;

errno = *saved_errno;
}

#define SELINUX_PROTECT_ERRNO __attribute__((__cleanup__(selinux_reset_errno))) \
__attribute__((__unused__)) int __selinux_saved_errno = errno
#endif /* SELINUX_INTERNAL_H_ */

0 comments on commit 1fd585e

Please sign in to comment.