如何在Linux内核中将char[]字符串转换为int?

23

如何在Linux内核中将char[]转换为int?

并且还要验证输入的文本实际上是一个int。

int procfile_write(struct file *file, const char *buffer, unsigned long count,
       void *data)
{

   char procfs_buffer[PROCFS_MAX_SIZE];

    /* get buffer size */
   unsigned long procfs_buffer_size = count;
   if (procfs_buffer_size > PROCFS_MAX_SIZE ) {
       procfs_buffer_size = PROCFS_MAX_SIZE;
   }

   /* write data to the buffer */
   if ( copy_from_user(procfs_buffer, buffer, procfs_buffer_size) ) {
       return -EFAULT;
   }

   int = buffer2int(procfs_buffer, procfs_buffer_size);

   return procfs_buffer_size;
}

1
你是否在寻求具有更好验证功能的atoi - forsvarir
7
内核中没有atoistrtol函数,因为“C/C++标准库”仅适用于用户空间应用程序。然而,在内核中有许多功能类似的函数,但名称不一定相同。 - FrankH.
6个回答

37

请查看您友好的Linux源代码树中#include <include/linux/kernel.h>kstrtol()的不同实现。

您需要使用哪种实现取决于*buffer是用户地址还是内核地址,以及对错误处理/检查缓冲区内容严格的需求(例如,123qx是无效的还是应返回123?)。


是的,在这里可能需要使用 strict_strtol()simple_strtol() - Eugene
123dew是无效的,我需要检查用户地址。 - caeycae
请参阅 https://lkml.org/lkml/2011/4/12/361,了解 kstrtol...() 函数与 simple_strtol() 和/或 strict_strtol() 的区别。无论如何,如果您不是在最前沿使用它们,那么您是正确的。关于“用户地址”,也请参阅该链接。 - FrankH.
这是一个错误。kstrotox()不是simple_strtox()的替代品。 - 0andriy

7

最小可运行的kstrtoull_from_user debugfs示例

当处理用户数据时,kstrto*_from_user系列非常方便。

kstrto.c:

#include <linux/debugfs.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <uapi/linux/stat.h> /* S_IRUSR */

static struct dentry *toplevel_file;

static ssize_t write(struct file *filp, const char __user *buf, size_t len, loff_t *off)
{
    int ret;
    unsigned long long res;
    ret = kstrtoull_from_user(buf, len, 10, &res);
    if (ret) {
        /* Negative error code. */
        pr_info("ko = %d\n", ret);
        return ret;
    } else {
        pr_info("ok = %llu\n", res);
        *off= len;
        return len;
    }
}

static const struct file_operations fops = {
    .owner = THIS_MODULE,
    .write = write,
};

static int myinit(void)
{
    toplevel_file = debugfs_create_file("lkmc_kstrto", S_IWUSR, NULL, NULL, &fops);
    if (!toplevel_file) {
        return -1;
    }
    return 0;
}

static void myexit(void)
{
    debugfs_remove(toplevel_file);
}

module_init(myinit)
module_exit(myexit)
MODULE_LICENSE("GPL");

使用方法:

insmod kstrto.ko
cd /sys/kernel/debug
echo 1234 > lkmc_kstrto
echo foobar > lkmc_kstrto
ok = 1234
ko = -22

在Linux内核4.16中进行了测试,使用这个QEMU + Buildroot设置
对于这个特定的示例,您可能想使用debugfs_create_u32

1

由于Linux内核中缺乏许多常见函数/宏,您无法使用任何直接函数从字符串缓冲区中获取整数值。

这是我长期以来一直在使用的代码,并且可以在所有*NIX版本上使用(可能不需要任何修改)。

这是修改后的代码形式,我很久以前从一个开源项目中使用过(现在不记得了名称)。

#define ISSPACE(c)  ((c) == ' ' || ((c) >= '\t' && (c) <= '\r'))
#define ISASCII(c)  (((c) & ~0x7f) == 0)
#define ISUPPER(c)  ((c) >= 'A' && (c) <= 'Z')
#define ISLOWER(c)  ((c) >= 'a' && (c) <= 'z')
#define ISALPHA(c)  (ISUPPER(c) || ISLOWER(c))
#define ISDIGIT(c)  ((c) >= '0' && (c) <= '9')

unsigned long mystr_toul (
    char*   nstr,
    char**  endptr,
    int base)
{
#if !(defined(__KERNEL__))
    return strtoul (nstr, endptr, base);    /* user mode */

#else
    char* s = nstr;
    unsigned long acc;
    unsigned char c;
    unsigned long cutoff;
    int neg = 0, any, cutlim;

    do
    {
        c = *s++;
    } while (ISSPACE(c));

    if (c == '-')
    {
        neg = 1;
        c = *s++;
    }
    else if (c == '+')
        c = *s++;

    if ((base == 0 || base == 16) &&
        c == '0' && (*s == 'x' || *s == 'X'))
    {
        c = s[1];
        s += 2;
        base = 16;
    }
    if (base == 0)
        base = c == '0' ? 8 : 10;

    cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
    cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
    for (acc = 0, any = 0; ; c = *s++)
    {
        if (!ISASCII(c))
            break;
        if (ISDIGIT(c))
            c -= '0';
        else if (ISALPHA(c))
            c -= ISUPPER(c) ? 'A' - 10 : 'a' - 10;
        else
            break;

        if (c >= base)
            break;
        if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
            any = -1;
        else
        {
            any = 1;
            acc *= base;
            acc += c;
        }
    }

    if (any < 0)
    {
        acc = INT_MAX;
    }
    else if (neg)
        acc = -acc;
    if (endptr != 0)
        *((const char **)endptr) = any ? s - 1 : nstr;
    return (acc);
#endif
}

2
可移植性还好,但重新实现内核代码并不是最好的选择;当你谈论“其他UNIX”时,例如Solaris内核确实有strtol()(甚至在Solaris第9节手册中有文档记录),FreeBSD也有(它在libkern中)。Linux也有,只是命名不同。在所有这些系统上,使用#define就可以了... - FrankH.
@FrankH,同意。但我相信,如果你的代码要在很多操作系统上发布(就像我正在使用的那个),你肯定会发现至少有一个不支持/实现所需函数。无论如何,在这种情况下,使用现有代码总是比使用自己的代码更好。 - Vikram.exe
这完全是错误的。正如其他答案所说,Linux确实有非常可用的函数将字符串转换为整数。 - Roland
@Roland 只因为一个被接受的答案这么说并不意味着那是正确的。请阅读我在此帖子中的第二条评论,希望能够解决你的疑惑。而且我真的想不出有什么理由会被踩。 - Vikram.exe
这个问题涉及到Linux内核。其他内核?谁在乎呢。 - hookenz

0

我使用sscanf()(内核版本)从字符串流中扫描,并且它在2.6.39-gentoo-r3上运行良好。坦白地说,我从未能够让simple_strtol()在内核中工作 - 我目前正在弄清楚为什么这在我的计算机上无法正常工作。

  ...
  memcpy(bufActual, calc_buffer, calc_buffer_size);
  /* a = simple_strtol(bufActual, NULL, 10); */ // Could not get this to work
  sscanf(bufActual, "%c%ld", &opr, &a); // places '+' in opr and a=20 for bufActual = "20+\0"
  ...

0

2
据我所知,您不能直接在内核模式下使用它们,即使在某些内核中以某种形式可用,也不能保证在所有 *NIX 平台上都能正常工作。 - Vikram.exe
@Vikram:我不知道这个限制。 - Bhargav

-1

6
你可以在Linux内核中使用isdigit()函数(在<linux/ctype.h>中定义而非<ctype.h>),但是却没有atoi()函数。 - FrankH.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接