Quantcast
Channel: Active questions tagged linux-kernel - Stack Overflow
Viewing all 12191 articles
Browse latest View live

Char Driver Linux: What is the correct implementation of file_operations read and write? What are the offset checks needs to be made?

$
0
0

I am trying to read and write to a char driver. When i use a C program to open the device file and read and write it gives a SEG fault. When I use a cat to the device file it goes to infinite loop.

1) What am I missing, and what is the correct implementation of read and write in file_operations?

2) I know in prototype read/write: read(struct file *fp, char *ch, size_t count, loff_t *lofft) count refers to number of bytes read/write request. But what is the last parameter offset used for and what are the checks needs to be made for offset?

3) For multiple read calls like cat /dev/chardriver will the offset be incremented for each read? Like 1st read call offset from 1 to 100 for count=100, in next read call will the offset go from 101? Or will it go from any random number?

Here is my code:

    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/fs.h>
    #include <linux/cdev.h>
    #include <linux/device.h>
    #include <linux/uaccess.h>

    static int device_open(struct inode *, struct file *);
    static int device_release(struct inode *, struct file *);
    static ssize_t device_read(struct file *, char *, size_t, loff_t *);
    static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
    char kernelbuff[1024];

    MODULE_LICENSE("GPL");

    struct file_operations fops = {
    .read = device_read,
    .write = device_write,
    .open = device_open,
    .release = device_release
    };


    int device_open(struct inode *inode, struct file *fp)
    {
    printk("device_open called");
    return 0;
    }

    static int device_release(struct inode *inode, struct file *fp)
    {
    printk("device_release called");
    return 0;
    }

    static ssize_t device_read(struct file *fp, char *ch, size_t sz, loff_t *lofft)
    {
    printk("device_read called");      
    copy_to_user(ch, kernelbuff, 1024);
    return sz;
    }

    static ssize_t device_write(struct file *fp, const char *ch, size_t sz, loff_t *lofft)
    {
    printk("device_write called");
    copy_from_user(kernelbuff, ch, 50);
    return 1024;
    }

    static int hello_init(void)
    {
      printk("basicchardriver: module initialized");
      register_chrdev(500, "chr_device", &fops);
      return 0;
    }

    static void hello_exit(void)
    {
      printk("basicchardriver: module exited");
      unregister_chrdev(500, "chr_device");
    }

    module_init(hello_init);
    module_exit(hello_exit);
 }

To test:

sudo mknod -m 666 /dev/chardev c 500 0
echo "Hello World">> /dev/chardev    ===> Works fine
cat /dev/chardev     ===> Goes to infinite loop

If i call the driver using a C program it gives SEG fault:

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

int main()
{
  int fd;
  char buff[500];

  fd = open("/dev/chardev", O_RDWR);
  write(fd, "Hello World", 13);

  read(fd, buff, 500);
  printf("Reading data from kernel: \t");
  puts(buff);

  return 0;
}

raj@raj-VirtualBox:~/device-driver/chardriver/read-write$ ./a.out
Reading data from kernel: Hello World
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

What does commands uname -r, uname -i, uname -p in linux do? [closed]

$
0
0

For example

from the command:
$ ls /lib/modules/
print out all directories name as 4.15.0-XX-generic

and from the command
$ ls /lib/modules/$(uname -r)
prints out different module binaries, and directories like kernel, updates, intrd.

Why when i compile my kernel it gives errors [closed]

$
0
0

Im modifying the kernel for a Samsung Galaxy Core Prime SM-G316F to add external wifi dongle support and HID compatibility And when i enable USB functions configurable through configfs it gives errors while compiling... Im new to this world, so can you help me to understand the errors?

https://hastebin.com/yakajehinu.cs

Difference between skb_header_pointer and skb_transport_header?

$
0
0

I'm trying to implement a netfilter module, while processing sk_buff I found two possible ways to retrieve TCP header:

struct iphdr *ip_header = (struct iphdr *)skb_network_header(skb);
struct tcphdr *tcp_header = (struct tcphdr *)skb_transport_header(skb);

And

struct iphdr *ip_header = skb_header_pointer(skb, 0, sizeof(struct iphdr), &_iph)
struct tcphdr *tcp_header = skb_header_pointer(skb, ip_header->ihl * 4, sizeof(struct tcphdr), &_tcph);

Which one should I use?

what is the difference between kernel panic and software exception?

$
0
0

A software interrupt, also called an exception, is an interrupt that is caused by software, usually by a program in user mode. kernel panic is caused by Hosed updates, failing hardware, unsupported hardware, failed or missing drive or partition. By this i came to the conclusion that software exceptions occurs in user mode and kernel panic is occured in kernel.(not sure about this conculsion). is there any other differences between kernel panic and software exception.? thanku in advance

Is it possible to re-transmit a packet after capturing it using XDP and processing it in userspace?

$
0
0

I need to write an application that sits between two servers and modifies HTTP packets sent from one server to another by adding a specific HTTP header to each packet.
Apparently it has to be done as fast as possible, I have found that by using eBFP and XDP, I can capture packets with high performance, but as far as I can see XDP verdicts are either abort, drop, pass, and tx.
Using tx verdict I can send the captured packet to a user space program to modify it, but I couldn't figure out how to send the packet after header modification? This video here is an explanation of what can be done using eBPF and XDP, and it states that it can be done, but I couldn't find out how.
Any help would be appreciated.

Can't get data (payload) from sk_buff

$
0
0

I try to create a module for encrypt network packets but when try get data from sk_buff and print it in Hexa not get a correct packet. I use this method to print data in Hexa :

void pkt_hex_dump(struct sk_buff *skb)
{
    size_t len;
    int rowsize = 16;
    int i, l, linelen, remaining;
    int li = 0;
    uint8_t *data, ch;

    printk("Packet hex dump:\n");
    data = (uint8_t *) skb_mac_header(skb);

    if (skb_is_nonlinear(skb)) {
        len = skb->data_len;
    } else {
        len = skb->len;
    }

    remaining = len;
    for (i = 0; i < len; i += rowsize) {
        printk("%06d\t", li);

        linelen = min(remaining, rowsize);
        remaining -= rowsize;

        for (l = 0; l < linelen; l++) {
            ch = data[l];
            //data[l] = '1';
            printk(KERN_CONT "%02X ", (uint32_t) ch);
        }
        data += linelen;
        li += 10;

        printk(KERN_CONT "\n");
    }
}

I used this sample to create a chat application.

And output when I send hello world message from client to server is :

[ 3981.963124] Packet hex dump:
[ 3981.963125] 000000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00
[ 3981.963128] 000010   00 34 6A 1F 40 00 40 06 D1 A2 7F 00 01 01 7F 00
[ 3981.963130] 000020   00 01 07 E4 BD 36 A2 52 E9 62 6D 40 3D FE 80 10
[ 3981.963133] 000030   02 00 FF 28 

And I try to follow this solution but can't get any output.

Getting random junk output from my simple syscall test

$
0
0

Using Ubuntu 18.04.3 LTS (GNU/Linux 5.0.21+ x86_64)

I created a simple syscall and am trying to pass input (the integer 5) through it by calling it in a c program and then see if I can get the input back out. I keep getting random junk as my output rather than my input.

Simple system call:

#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/sched.h>
#include<linux/syscalls.h>
#include<linux/signal.h>
#include "tags.h"

asmlinkage int sys_get_tag(int pid)
{
  return pid;
}

my userspace test code:

#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
int main()
{
    int pid = syscall(335, 5); // 335 is the syscall number, 5 is the input to the syscall that I am trying to return
    printf("return: %d \n", pid);
    return 0;
}

my output:

return: 4980568

I get it to work when I return some integer in my syscall, like return 5; for example; so I know the syscall is being used.


error: implicit declaration of function ‘sys_kill’

$
0
0

I've created a system call to return a tag variable (that I added in the kernel) of a specific process. When I make I get error: implicit declaration of function ‘sys_kill’. Does anyone know what might be causing this or if there are any alternative functions I can use to see if a process is running to return the tag?

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>    
#include <linux/syscalls.h>
#include <linux/signal.h>
#include "tags.h"

asmlinkage int sys_get_tag(int pid){    //gets the process ID
  struct task_struct *p;                   //pointer to the struct
  p = find_task_by_vpid(pid);       //p = process found by PID

  if(sys_kill(p->pid, 0) == 0){ //syskill sends a 0 signal to all processes matching passed PID - checks if running
    return p->tag;  //the 0 signal found has the tag we are looking for
  }
  else{
    return -1;          //if nothing is found return -1
  }
}

Command cc not found : /bin/sh: 1: cc: not found

$
0
0

which gcc : o/p : /usr/bin/gcc

which g++ o/p : /usr/bin/g++

which cc: o/p : nothing

I have installed the build essential and gcc. But cc is somehow missing.

Can anyone help me to install cc in this scenar

How to "invalidate" or "flush" a range of CPU cache in PowerPC architecture?

$
0
0

I am working with an embedded device which communicates with my PowerPC CPU via PCIe. Due to the SDK constraints i have to use linux kernel version 4.1.8. This version doesn't have functions related to cache operations in $KERNEL_SOURCE/arch/powerpc/include/asm/, such as:

  • "invalidate_dcache_range()"
  • "flush_dcache_range()"
  • "clean_dcache_range()"

(in this directory "cacheflush.h" header just contains declaration of mentioned functions.)
Also, my embedded device's SDK needs to call these functions to prepare DMA access.
Note that Kernel versions higher than 4.5 provide declaration of these functions.

Now i have some questions:

  1. I can use and copy functions which are implemented in newer kernels, in my old kernel and rebuild it, but modifying the kernel source doesn't make sense, right?
  2. Can you suggest some workaround to resolve it?
  3. How can i test that cache invalidated or flushed correctly? is there any way to read cache blocks in userspace?

Thanks,

So I did edit my bash profile but I cant get out of bash due to errors that I have in my command? What should I do to exit. I using cygwin [closed]

$
0
0

[Bash Error} So I did edit my bash profile but I cant get out of bash due to errors that I have in my command? What should I do to exit. I using linux software

How to load Linux module while debugging Linux kernel with QEMU and gdb?

$
0
0

I am trying to debug the function "apply_relocate_add" in the Linux kernel with QEMU and gdb. This function called when the kernel loads new module.

Qemu command:

$ qemu-system-x86_64 -kernel /boot/vmlinuz-5.0.0-23-generic -append "console=ttyS0 nokaslr" -initrd ramdisk.img -m 512 -s -S

(gdb) b apply_relocate_add
(gdb) c

But the breakpoint not triggered. I think that the kernel doesn't load modules. How can I load modules and debug this function?

What are the steps to create patchset in git

$
0
0

So I want to create a patchset - total 3 different patches for a code fix. Its a git based project.

I have thought following steps-

  1. I am in master branch. Did by git checkout master Create 3 different branches - git branch First, git branch Second and git branch Third
  2. Do changes (Code fix 1) in First branch. Then create patch 1 with master and First.
  3. Do changes (Code fix 2) in Second. branch. Then create patch 2 with master and Second.
  4. And similarly for third fix.

It is important to note that all the code changes for all the 3 patches are in a single .c file. Also, I cant make a single patch of all the code fix - I have to make 3 different patches - this is a requirement.

Actually the patches should be independent - patch 1 can be applied by developer 1 at some commit hash, patch 2 can be applied by another developer at another different commit hash - and similarly for dev 3.

I am confident that there is a way to create the 3 patches using only a single branch. Kindly illuminate.

How to include kernel headers in a program

$
0
0

I am writing a libnetfilter_queue program. I am new to linux kernel programming. I need to include linux/skbuff.h, net/checksum.h and many related kernel headers which are not present in /usr/include/linux. I get following error on compilation

 fatal error: linux/skbuff.h: No such file or directory
 fatal error: net/checksum.h: No such file or directory

Unable to copy files / folders in /dev/sda partitions

$
0
0

I have recently installed linux 18.04 on my machine. previously I had installed windows & created 4 partitions that is C,D,E,F. I have installed linux on C drive. other 3 partitions are displaying as /dev/sda5, /dev/sda6, /dev/sda7.

Now I want to copy something in that partitions I am unable to do any operations. I tried to change permission of the partitions but it is throwing Error "chmod: changing permissions of '/media/lucky/others': Read-only file system" I also re-mount the partitions but nothing happen.

I don't find any possible solution, kindly help.

Thank You

Kernel module to filter NFS requests

$
0
0

I'm working on a proof-of-concept kernel module to filter NFS requests based on some criteria (client IP address, type of operation performed, etc.) I used a hacky method described in this question but I couldn't retrieve the client IP address inside this method.

My current thinking is to have a Netfilter hook to intercept the network packets, parse them to identify the operations and apply the filtering there.

He're is a sample of what I'm talking about.. It's for kernel version 4.15.0

#include <linux/kernel.h>       /* We're doing kernel work */
#include <linux/module.h>       /* Specifically, a module, */
#include <linux/moduleparam.h>  /* which will have params */
#include <linux/unistd.h>       /* The list of system calls */
#include <linux/dirent.h>
#include <linux/cred.h>
#include <linux/syscalls.h>
#include <linux/init.h>
#include <linux/netfilter.h>
#include <linux/ip.h>
#include <linux/tcp.h>

static struct nf_hook_ops nfin;

static unsigned int hook_func_in(void *priv,
                   struct sk_buff *skb,
                   const struct nf_hook_state *state)
{
    struct ethhdr *eth;
    struct iphdr *ip_header;
    struct tcphdr *tcph;
    char *data;

    eth = eth_hdr(skb);
    ip_header = ip_hdr(skb);
    tcph = tcp_hdr(skb);
    data = (char *)((unsigned char *)tcph + (tcph->doff * 4));
    /* Skip if it's not TCP packet */
    if (ip_header->protocol != IPPROTO_TCP)
        return NF_ACCEPT;
    printk("src mac %pM --- src IP addr:%pI4 --- protocol: %u\n", eth->h_source, &ip_header->saddr, ip_header->protocol);
    printk("TCP source : %hu, TCP  dest : %hu\n", ntohs(tcph->source), ntohs(tcph->dest));
    // Parse data pointer here..
    return NF_ACCEPT;
}

int init_module()
{
    nfin.hook     = hook_func_in;
    nfin.hooknum  = NF_INET_LOCAL_IN;
    nfin.pf       = PF_INET;
    nfin.priority = 0;
    nf_register_net_hook(&init_net, &nfin);
    return 0;
}

void cleanup_module()
{
    nf_unregister_net_hook(&init_net, &nfin);
}

How can I parse the data pointer to be able to identify the type of request I'm handling? or how to parse the RPC request from the sk_buff object?

Is this the right approach to go about this task?

Linux Kernel Changing Default CPU Scheduler

$
0
0

I am trying to hack the Linux kernel and I am wondering. How can I change the default Linux Process scheduler with another one? And can I just set every processes as a real time process?

How do i decode the output of /proc/$$/statm?

$
0
0

I am trying to understand the output given by statm. This is part of task to analyze memory usage of a process which keeps bothering the system performance.From few blogs i got to know "statm" is the simplified version of "smaps",but not sure how to read this.

Sample output:

myhost:/proc/64498 $ cat statm
30217 855 752 213 0 126 0

Can't open owasp-mantra, firefox already opened

$
0
0

I'm learning Kali Linux, tried to boot Mantra, but I always got the error msg like this:

'Firefox is already running, but is not responding. To open a new window, you must first close the existing Firefox process, or restart your system.'

I tried killall firefox, killall firefox-bin, restart my system, install xterm, but they didn't work...

I got these as well:

wasp-mantra-ff
firefoxportable:Debug/Info: 0=./OWASP Mantra
firefoxportable:Debug/Info: dir=/usr/share/owasp-mantra-ff
firefoxportable:Debug/Info: Current Dir=/usr/share/owasp-mantra-ff/Mantra

(process:1816): GLib-CRITICAL **: 14:50:06.375: g_slice_set_config: assertion 'sys_page_size == 0' failed
Welcome to the Linux version of firefox 18.0 in portable mode. Feedback is NOT disabled.
firefoxportable:Debug/Info: Profile Directory already exists!
Warning: Tried to connect to session manager, Authentication Rejected, reason : None of the authentication protocols specified are supported and host-based authentication failed
firefoxportable:Debug/Info: firefox is now closed.
./OWASP Mantra: 51: yaf-splash: not found
firefoxportable:Debug/Info: firefoxportable is now closed.

Can anyone help me? THX!!!

Viewing all 12191 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>