Skip to content

Instantly share code, notes, and snippets.

@clopez
Created April 2, 2013 19:58
Show Gist options
  • Save clopez/5295663 to your computer and use it in GitHub Desktop.
Save clopez/5295663 to your computer and use it in GitHub Desktop.
Check if running kernel is 32 bits or 64 bits
#!/bin/sh
# Return codes:
# 10 => The kernel is unknow
# 32 => The kernel is 32-bits
# 64 => The kernel is 64-bits
_testkernelbits() {
# Test method 1. Check the lenght of the kernel addresses
if [ -r "/proc/kallsyms" ]; then
addrlen=$(head -1 /proc/kallsyms|awk '{print $1}'|wc -c)
if [ ${addrlen} = 17 ]; then
return 64
elif [ ${addrlen} = 9 ]; then
return 32
fi
fi
# Test method 2. Check if the kernel knows about CONFIG_64BIT
CURDIR=$(pwd)
TESTDIR=$(mktemp -d)
cd "${TESTDIR}"
cat << EOF > Makefile
ifeq (\$(TEST), 64)
obj-m := test64bits.o
else
obj-m := testgeneric.o
endif
PWD := \$(shell pwd)
KVER ?= \$(shell uname -r)
KDIR := /lib/modules/\$(KVER)/build
default:
make -C \$(KDIR) M=\$(PWD) modules
clean:
rm -f .*.cmd *.o *.ko *.mod.c modules.order Module.symvers
rm -fr .tmp_versions
EOF
cat << EOF > testgeneric.c
#include <linux/kobject.h>
int main (void) {
return 0;
}
EOF
cat << EOF > test64bits.c
#include <linux/kobject.h>
int main (void) {
int val __attribute__ ((unused));
val = CONFIG_64BIT;
return 0;
}
EOF
# Test that module compilation works.
if make > /dev/null 2>&1; then
make clean > /dev/null 2>&1
# Test that the kernel is 64 bits.
if make TEST=64 > /dev/null 2>&1; then
RETCODE=64
else
RETCODE=32
fi
fi
# Clean
make clean > /dev/null 2>&1
cd "${CURDIR}"
rm -f "${TESTDIR}/Makefile"
rm -f "${TESTDIR}/testgeneric.c"
rm -f "${TESTDIR}/test64bits.c"
rmdir "${TESTDIR}"
if [ -n ${RETCODE} ]; then
return ${RETCODE}
fi
# Test method 3. Check if the config has CONFIG_64BIT defined.
KCONFIG="/boot/config-$(uname -r)"
if [ -r "$KCONFIG" ]; then
if grep -q 'CONFIG_64BIT=y' "$KCONFIG"; then
return 64
else
return 32
fi
fi
# If we reach here we really don't have a clue about this kernel.
return 10
}
_testkernelbits; kernelbits=$?
echo "${kernelbits}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment