【问题标题】:Linux: Detect 64-bit kernel (long mode) from 32-bit user mode programLinux:从 32 位用户模式程序中检测 64 位内核(长模式)
【发布时间】:2011-08-22 12:52:12
【问题描述】:

检测 32 位用户模式程序是否在 64 位内核上运行(即系统是否处于“长模式”)的最佳和最可靠的方法是什么?如果可能的话,我宁愿不调用外部程序(或者必须加载任何内核模块)。

注意:我想检测是否正在使用 64 位内核(或者实际上,CPU 是否处于长模式),而不仅仅是是否存在支持 64 位的处理器(/proc/cpuinfo 告诉我但是不是是否正在使用 64 位功能)。

如果 uname 编译为 32 位或使用 setarch i686,则内核会伪造 32 位处理器。

【问题讨论】:

  • 你可以看看例如/proc/vmallocinfo 看看地址是32位还是64位
  • 那只能被root读取,对吧?
  • /proc/kallsyms 是默认世界可读的替代方案。

标签: linux kernel 32-bit mode


【解决方案1】:

调用uname() 函数并检查返回的machine 字符串,对于64 位Intel 平台,该字符串为x86_64

扭转使用setarch的效果的一种方法是重置个性:

#include <stdio.h>
#include <sys/utsname.h>
#include <sys/personality.h>

int main()
{
    struct utsname u;

    personality(PER_LINUX);

    uname(&u);
    puts(u.machine);
    return 0;
}

这显示了在 32 位模式下编译并在 64 位系统上运行时的正确结果:

$ gcc -m32 -o u u.c
$ ./u
x86_64
$ setarch i686 ./u
x86_64

编辑:修复代码以反转 setarch 的效果。

Reference.

【讨论】:

  • 这种工作,但如果我用setarch运行程序,即setarch i686 ./uname它会打印i686。
  • 这是正确的行为,不是吗?您正在显式更改流程所看到的架构。
  • 好吧,我真正想做的是找出 CPU 是否处于长模式。
  • @atomice:嗯,CPU 在运行 32 位进程时并没有处于长模式...
【解决方案2】:

假设 uname() 是作弊,仍然有几种机制。一种方法是检查任何内核符号的地址宽度。

#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  char *inputline = malloc(1024);
  char *oinputline = inputline;
  int fd = open("/proc/kallsyms", O_RDONLY);
  int numnibbles = 0;
  if (fd == -1) {
      perror("open");
      free(inputline);
      exit(1);
  }
  read(fd, inputline, 1024);
  close(fd);
  while(!isspace(*inputline)) {
      numnibbles++;
      inputline++;
  }
  printf("%dbit\n", numnibbles*4);
  free(oinputline);
  exit (0);
}

【讨论】:

    【解决方案3】:

    如果为它配置了内核,您可以从 /proc/config.gz 中读取内核配置

    zcat /proc/config.gz | grep CONFIG_64BIT
    # CONFIG_64BIT is not set
    

    我不确定您需要它的便携性 - 它似乎不是一个超级常见的配置选项。

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 2014-12-11
      • 2014-05-16
      • 2018-07-30
      • 2013-06-07
      • 2012-11-30
      相关资源
      最近更新 更多