keyboard interrupt handler giving null value - c

I am learning Linux Kernel Module programming(Interrupt Handler) and using the tutorial (http://tldp.org/LDP/lkmpg/2.6/html/) exact module link(http://tldp.org/LDP/lkmpg/2.6/html/x1256.html).
In the tutorial I am getting error when I used
INIT_WORK(&task, got_char, &scancode);
The error was "error: macro "INIT_WORK" passed 3 arguments, but takes just 2"
So I found one solution and use the below line
INIT_WORK(&task, got_char);
It's working fine but the output I am getting is null. I am expecting the key number from the keyboard.
Any body have any idea ?
If it is not clear please let me know I will try to interpret more.
Thanks

Add a structure like follows,
struct getchar_info {
/* Other info ... */
struct work_struct work;
unsigned int scancode;
/* Other info ... */
};
static struct getchar_info gci; /* Statically declare or use kmalloc() */
Change got_char() to,
static void got_char(struct work_struct *work)
{
struct getchar_info *info = container_of(work, struct getchar_info, work);
info->scancode = my_val;
/* ... */
Initialize it like INIT_WORK(&gci.work, got_char);
This is a common Linux kernel paradigm or design pattern. The work queue code needs to manage this structure pointer so it is easy to provide to your got_char routine. Your driver must allocate it as part of a larger structure (it is inheritence in OO terms; it looks like composition as 'C' only supports that). The container_of is like a C++ dynamic_cast<> (with single inheritance in case any C++ gurus are looking). It lets you get the composed structure from the sub-structure.

Related

C, "extern" type of variables in hardware abstraction layer

I am working on a Hardware Abstraction Layer. The aim of this HAL is to easily switch between the drivers for linux and the drivers for an MCU.
I am working on the SPI interface. Below is the signature of the function of the HAL that "open" the interface of SPI.
hal/spi.h
spi_handle_t spi_open(spi_port_t channel, spi_config_t config);
spi_port_t :
On Linux, it is an elementary type : uint32_t
On the MCU, it is a struct.
spi_config_t :
On both Linux and the MCU it is a struct but with different fields.
So in mcu/spi.c I have at some point this :
typedef spiBASE_t spi_channel_t;
typedef spiDAT1_t spi_config_t;
spi_handle_t spi_open(spi_channel_t channel, spi_config_t config) {
.
.
.
}
And for linux/spi.c :
typedef uint32_t spi_channel_t;
typedef ChannelConfig_t spi_config_t;
spi_handle_t spi_open(spi_channel_t channel, spi_config_t config) {
.
.
.
}
Now the problem is in hal/spi.h, I need to define what is spi_channel_t and spi_config_t.
Is there a way to make something like (I know it is impossible with extern, but for explanation matters...) :
extern spi_channel_t;
extern spi_config_t;
This would say to the compiler : "Ok these two types are not defined in the header file, still you can find their storage size on one of the files I passed to the toolchain".
What you seem to be looking for is the trick called opaque type. It's a way to use forward declaration of structs in order to achieve private encapsulation and polymorphism in C. It is commonly used for professionally-written embedded systems drivers in particular and can be implemented like this:
hal/spi.h
// forward declaration of a struct, with typedef and struct tag:
typedef struct spi_handle_t spi_handle_t;
// Require the caller to declare a spi_handle_t* pointer, not an object:
spi_handle_t* spi_init (...);
mcu/spi.c
struct spi_handle_t
{
// whatever you need here - these are now 100% private members
};
spi_handle_t* spi_init (...)
{
spi_handle* result = address_of_some_static_memory_pool;
/* init struct members here */
return result;
}
linux/spi.c
struct spi_handle_t
{
uint32_t something;
// whatever you need here - these are now 100% private members
};
spi_handle_t* spi_init (...)
{
spi_handle* result = malloc(sizeof *result); // malloc is fine to use in Linux
/* init struct members here */
return result;
}
Now the caller will have to pass along the spi_handle* to other functions in the driver. This isn't just handy for OO design, but it also makes it possible to run the same code with multiple instances. For example if you have 2 different SPI hardware peripherals on the MCU and want to use them differently, but with the same driver code.
The typical way of doing this would be to use the preprocessor in hal/spi.h:
#if defined(HAL_LINUX)
typedef uint32_t spi_port_t; /* int in linux */
#elif defined(HAL_MCU)
typedef struct {
/* your struct in bare metal app */
} spi_port_t;
#else
#error "Platform not defined!"
#endif
You could also put the different types into different headers like hal/spi_linux.h and hal/spi_mcu.h and conditionally include one of them in hal/spi.h.
Alternatively, you could just take pointers and cast them to their actual type. This would be less safe because you would have to check the platform at runtime and decide the type behind the pointer, but this decision depends on many other things.

Accessing structure in structure through pointer

Brief description:
I write something to structure through pointer but something else gets written. I work in atollic true studio 8.1, programming an STM32F415RG MCU.
The strangest thing is that even if I look in variables and expression window, I can see the same structure with different values.
Same variable in two windows with different values
Now to elaborate a bit (I am going to simplify a lot of stuff to make it more readable).
I have my protocol handle type defined:
typedef struct
{
RS485DriverHandle master_rs485;
} EscomProtocolHandle;
My RS485 driver handle is defined as follows:
typedef struct
{
UART_HandleTypeDef* uart_handle;
TransceiverState transceiver_state;
GPIO_TypeDef* dir_gpio;
uint16_t dir_pin;
} RS485DriverHandle;
I have created my protocol handle as a global variable:
static EscomProtocolHandle hprot1;
I pass it to my protocol init function which takes a pointer to handle as an argument:
Escom_Protocol_Init(&hprot1);
Init function passes it to RS485 driver init function which takes pointer to RS485 handle as an argument (this call is simplified a lot):
void Escom_Protocol_Init(EscomProtocolHandle* protocol_handle)
{
RS485_Init(&protocol_handle->master_rs485)
}
RS485 init function sets default values:
void RS485_Init(RS485DriverHandle* rs485_handle, UART_HandleTypeDef* uart_handle,
GPIO_TypeDef* dir_gpio, uint16_t dir_pin)
{
/* default = listening */
rs485_handle->uart_handle = uart_handle;
rs485_handle->dir_gpio = dir_gpio;
rs485_handle->dir_pin = dir_pin;
ReceiverOutputEnable(rs485_handle);
rs485_handle->transceiver_state = kReceiving;
}
Now if I look at the local variable rs485_handle, the values are set correctly. But If I look at my handle hprot1, the values don't match. Even though rs485_handle's address matches the address of master_rs485 member of the hprot1 handle.
P.S.: I have not messed with the packing (#pragma pack) of any of the above mentioned structures, so that should not be an issue.
Got it!
There was a seemingly unrelated header file that had a structure prototype in it which was packed(1) and there was no #pragma pack() after the structre prototype to restore the packing to default state. Thus RS485DriverHandle was packed differently in different places. In both Escom_Protocol_Init and RS485_Init the address of the handle structure was the same, but the packing was different so for example the address of GPIO_TypeDef* dir_gpio member was 0x200000D6 in Escom_Protocol_Init but was 0x200000D9 in RS485_Init.

storage size of isn’t known using sigaltstack struct

I'm using the sigalstack struct, details at:
Here (MAC OSX)
HERE (LINUX)
I'm just declaring it like so
struct sigaltstack aa;
and i keep getting the following error
error: storage size of ‘aa’ isn’t known
I read and checked storage size of ‘names’ isn’t known but I'm just declaring it, so it doesn't really apply.
You can't just use an uninitialized alternate stack like that. You have to allocate the space for the stack in its ss_sp field and set the corresponding size in its ss_size field.
The man7 link you linked has more information on this. In fact, it provides an example at the bottom of the page:
stack_t ss;
ss.ss_sp = malloc(SIGSTKSZ);
if (ss.ss_sp == NULL)
/* Handle error */;
ss.ss_size = SIGSTKSZ;
ss.ss_flags = 0;
if (sigaltstack(&ss, NULL) == -1)
/* Handle error */;
Hope that helps.
The Mac OS page you link to says (in the section on 'Legacy Synopsis'):
COMPATIBILITY
Use of the (obsolete) sigaltstack struct will cause compiler diagnostics. Use stack_t, defined in <signal.h>.
This suggests that you should not attempt to use struct sigaltstack. The page also shows how you're expected to do it on Mac OS. The Linux page also shows how you're supposed to use the stack_t type and makes no mention of struct sigaltstack at all.

C naming suggestion for Error Code enums

I'm writing a simple parser to read the config file.The config.h interface have only three
main functions they are in brief as follows,
config_init();
config_dinit();
config_parse();
config_read_value();
My question is those functions will emit different type of errors , for a example,
config_init() emit , FILE_NOT_FOUND,FILE_EOF_ERROR,FILE_OPEN_ERROR, ...
config_dinit() emit , NOT_INIT_ERROR ,
config_parse() emit , PARSE_ERROR, OVERFLOW_ERROR, INVALID_CHARACTER_FOUND_ERROR,...
config_read_value() emit, SECTION_NOT_FOUND,KEYWORD_NOT_FOUND,OVERFLOW_ERROR,NOT_INITIALIZED_ERROR,INVALID_STATE_ERROR,... etc.
Then I create enums for each function, for by using these names ,
enum Config_ParseError{...} , enum Config_InitError{...} ,enum Config_ReadValueError{..}
etc.
Some enum values are overlapping each other and hit "compiler error" too. like
OVERFLOW_ERROR,
I'm opening for your suggestions,
and I have done a quick research on the google and found that most popular IRC client
source code have defined the enums like this,
enum {
CMDERR_OPTION_UNKNOWN = -3, /* unknown -option */
CMDERR_OPTION_AMBIGUOUS = -2, /* ambiguous -option */
CMDERR_OPTION_ARG_MISSING = -1, /* argument missing for -option */
CMDERR_UNKNOWN, /* unknown command */
CMDERR_AMBIGUOUS, /* ambiguous command */
CMDERR_ERRNO, /* get the error from errno */
CMDERR_NOT_ENOUGH_PARAMS, /* not enough parameters given */
CMDERR_NOT_CONNECTED, /* not connected to server */
CMDERR_NOT_JOINED, /* not joined to any channels in this window */
CMDERR_CHAN_NOT_FOUND, /* channel not found */
CMDERR_CHAN_NOT_SYNCED, /* channel not fully synchronized yet */
CMDERR_ILLEGAL_PROTO, /* requires different chat protocol than the active server */
CMDERR_NOT_GOOD_IDEA, /* not good idea to do, -yes overrides this */
CMDERR_INVALID_TIME, /* invalid time specification */
CMDERR_INVALID_CHARSET, /* invalid charset specification */
CMDERR_EVAL_MAX_RECURSE, /* eval hit recursion limit */
CMDERR_PROGRAM_NOT_FOUND /* program not found */
};
it defines enum without any name, is that a good style?Then why what are the reasons for
that?
Seriously need some more good naming decisions. Please don't hurt me I just only
start reading "writing beautiful C code" book.
Thanks In Advance.
Sandun.
I'm usually a fan of one set of error returns for an entire library. This way in consumers they don't have to worry about "was the -1 bad input to X or could not connect to Y".
I'm also a fan of E_ prefixes, but really any will do:
enum _config_error
{
E_SUCCESS = 0,
E_INVALID_INPUT = -1,
E_FILE_NOT_FOUND = -2, /* consider some way of returning the OS error too */
....
};
/* type to provide in your API */
typedef enum _config_error error_t;
/* use this to provide a perror style method to help consumers out */
struct _errordesc {
int code;
char *message;
} errordesc[] = {
{ E_SUCCESS, "No error" },
{ E_INVALID_INPUT, "Invalid input" },
{ E_FILE_NOT_FOUND, "File not found" },
....
};
I'm of the opinion that is good style. The CMDERR_ prefix groups together the related error codes (assuming they're related to some kind of "command invocation/execution")
Since all of your examples seem to be related to your config functions, I'd just go with a one enum definition using CONFIG_ prefix (or CFG_ for brevity).
enum Config_Errors {
CONFIG_FILE_NOT_FOUND,
CONFIG_FILE_EOF_ERROR,
CONFIG_FILE_OPEN_ERROR,
//etc.
};
The reasoning behind the common prefix is that when using an enumerated type you want to make it clear that the members of the type all belong to the same group.
The CMDERR_ prefix in the IRC client source code is a good style, but defining enum without any name is not a good style. Not good because you cannot say it is an enum type, only an integer type like below:
CMDERR function1();
int function1(); // actually returning CMDERR unnamed enum
and you cannot define variable using the enum type like below:
CMDERR errResult;
int errResult; // actually errResult is CMDERR unnamed enum

How do I mock objects without inheritance (in C)?

We use a simple object model for our low level networking code at work where struct pointers are passed around to functions which are pretending to be methods. I've inherited most of this code which was written by consultants with passable C/C++ experience at best and I've spent many late nights trying to refactor code into something that would resemble a reasonable structure.
Now I would like to bring the code under unit testing but considering the object model we have chosen I have no idea how to mock objects. See the example below:
Sample header (foo.h):
#ifndef FOO_H_
#define FOO_H_
typedef struct Foo_s* Foo;
Foo foo_create(TcpSocket tcp_socket);
void foo_destroy(Foo foo);
int foo_transmit_command(Foo foo, enum Command command);
#endif /* FOO_H_ */
Sample source (foo.c):
struct Foo_s {
TcpSocket tcp_socket;
};
Foo foo_create(TcpSocket tcp_socket)
{
Foo foo = NULL;
assert(tcp_socket != NULL);
foo = malloc(sizeof(struct Foo_s));
if (foo == NULL) {
goto fail;
}
memset(foo, 0UL, sizeof(struct Foo_s));
foo->tcp_socket = tcp_socket;
return foo;
fail:
foo_destroy(foo);
return NULL;
}
void foo_destroy(Foo foo)
{
if (foo != NULL) {
tcp_socket_destroy(foo->tcp_socket);
memset(foo, 0UL, sizeof(struct Foo_s));
free(foo);
}
}
int foo_transmit_command(Foo foo, enum Command command)
{
size_t len = 0;
struct FooCommandPacket foo_command_packet = {0};
assert(foo != NULL);
assert((Command_MIN <= command) && (command <= Command_MAX));
/* Serialize command into foo_command_packet struct */
...
len = tcp_socket_send(foo->tcp_socket, &foo_command_packet, sizeof(foo_command_packet));
if (len < sizeof(foo_command_packet)) {
return -1;
}
return 0;
}
In the example above I would like to mock the TcpSocket object so that I can bring "foo_transmit_command" under unit testing but I'm not sure how to go about this without inheritance. I don't really want to redesign the code to use vtables unless I really have to. Maybe there is a better approach to this than mocking?
My testing experience comes mainly from C++ and I'm a bit afraid that I might have painted myself into a corner here. I would highly appreciate any recommendations from more experienced testers.
Edit:
Like Richard Quirk pointed out it is really the call to "tcp_socket_send" that I want to override and I would prefer to do it without removing the real tcp_socket_send symbol from the library when linking the test since it is called by other tests in the same binary.
I'm starting to think that there is no obvious solution to this problem..
You can use macro to redefine tcp_socket_send to tcp_socket_send_moc and link with real tcp_socket_send and dummy implementation for tcp_socket_send_moc.
you will need to carefully select the proper place for :
#define tcp_socket_send tcp_socket_send_moc
Have a look at TestDept:
http://code.google.com/p/test-dept/
It is an open source project that aims at providing possiblity to have alternative implementations, e.g. stubs, of functions and being able to change in run-time which implementation of said function to use.
It is all accomplished by mangling object files which is very nicely described on the home page of the project.
Alternatively, you can use TestApe TestApe Unit testing for embedded software - It can do it, but note it is C only.
It would go like this -->
int mock_foo_transmit_command(Foo foo, enum Command command) {
VALIDATE(foo, a);
VALIDATE(command, b);
}
void test(void) {
EXPECT_VALIDATE(foo_transmit_command, mock_foo_transmit_command);
foo_transmit_command(a, b);
}
Not sure what you want to achieve.
You can add all foo_* functions as function pointer members to struct Foo_s but you still need to explicitly pass pointer to your object as there is no implicit this in C. But it will give you encapsulation and polymorphism.
What OS are you using? I believe you could do an override with LD_PRELOAD on GNU/Linux: This slide looks useful.
Use Macro to refine tcp_socket_send is good. But the mock only returns one behavior. Or you need implement some variable in the mock function and setup it differently before each test case.
Another way is to change tcp_socket_send to function point. And points it to different mock function for different test case.
To add to Ilya's answer. You can do this.
#define tcp_socket_send tcp_socket_send_moc
#include "your_source_code.c"
int tcp_socket_send_moc(...)
{ ... }
I use the technique of including the source file into the unit testing module to minimize modifications in the source file when creating unit tests.

Resources