1

this is a simple linux kernel module code to reverse a string which should Oops after insmod,but it works well,why?

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
static char *words = "words";
static int __init words_init(void)
{
  printk(KERN_INFO "debug info\n");
  int  len = strlen(words);
  int  k;
  for ( k = 0; k < len/2; k++ )
  {
     printk("the value of k %d\n",k);
     char  a = words[k];
     words[k]= words[len-1-k];
     words[len-1-k]=a;        
 }
 printk(KERN_INFO "words is %s\n", words);
 return 0;
}
static void __exit words_exit(void)
{
  printk(KERN_INFO "words exit.\n");
}
module_init(words_init);
module_exit(words_exit);
module_param(words, charp, S_IRUGO);
MODULE_LICENSE("GPL");
Reeno
  • 5,720
  • 11
  • 37
  • 50
firefroge
  • 39
  • 7

2 Answers2

0

static != const.

static in your example means "only visible in the current file". See What does "static" mean?

const just means "the code which can see this declaration isn't supposed to change the variable". But in certain cases, you can still create a non-const pointer to the same address and modify the contents.

Space removal from a String - In Place C style with Pointers suggests that writing to the string value shouldn't be possible.

Since static is the only difference between your code and that of the question, I looked further and found this: Global initialized variables declared as "const" go to text segment, while those declared "Static" go to data segment. Why?

Try static const char *word, that should do the trick.

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • I mean the words="hello" ,in the expression, "hello" store in the Constant storage area, which we can't change it's content; if you write the words_init function in a normal c program with main,it will get segmentation fault; but why it works well in linux kernel module? – firefroge Jun 09 '15 at 08:24
  • You want to believe that `"hello"` is in the text segment. Did you check this by looking at the assembler input or by dumping the symbol table of the object file? – Aaron Digulla Jun 09 '15 at 08:29
0

Haha!,I get the answer from the linux kernel source code by myself;When you use the insmod,it will call the init_moudle,load_module,strndup_usr then memdup_usr function;the memdup_usr function will use kmalloc_track_caller to alloc memery from slab and then use the copy_from_usr to copy the module paragram into kernel;this mean the linux kernel module paragram store in heap,not in the constant storage area!! So we can change it's content!

firefroge
  • 39
  • 7