how to make loadable kernel module on solaris? no linux - unix

1. how to create loadable kernel module on solaris 11?
simple loadable kernel module (hello world).
I searched, but only showed how to create a Linux kernel module.
in linux, header linux/kernel.h, but not included header on solaris
2. how to compile loadable kernel module on solaris 11?
gcc -D_KERNEL -m64 -c cpluscplus.cpp
Is it appropriate to compile as above?
64bit, x86

Here's the minimal hello world kernel module I can come up with:
#include <sys/modctl.h>
#include <sys/cmn_err.h>
/*
* Module linkage information for the kernel.
*/
static struct modlmisc modlmisc = {
&mod_miscops, "test module"
};
static struct modlinkage modlinkage = {
MODREV_1, (void *)&modlmisc, NULL
};
int
_init(void)
{
return (mod_install(&modlinkage));
}
int
_fini(void)
{
return (mod_remove(&modlinkage));
}
int
_info(struct modinfo *modinfop)
{
cmn_err(CE_NOTE, "hello kernel");
return (mod_info(&modlinkage, modinfop));
}
Compiling this as 64-bit binary with Oracle Developer Studio 12.6 and the Solaris linker like so:
cc -D_KERNEL -I include -m64 -c foomod.c
ld -64 -z type=kmod -znodefs -o foomod foomod.o
For GCC you will likely need a distinct set of options.
Then load it with:
modload ./foomod
This will complain about signature verification. This is innocuous unless you are running the system with Verified Boot enabled.
Check that module is loaded:
# modinfo -i foomod
ID LOADADDR SIZE INFO REV NAMEDESC
312 fffffffff7a8ddc0 268 -- 1 foomod (test module)
# dmesg | tail -1
Mar 16 12:22:57 ST091 foomod: [ID 548715 kern.notice] NOTICE: hello kernel
This works on Solaris 11.4 SRU 33 running on x86 machine (VirtualBox instance in fact).

Related

Accessing an external variable from a C library

I am currently learning C and am trying to understand the possibilities of dynamic libraries.
My current question is, if I have a simple "Hello World" application in C called "ProgA", and this program dynamically loads a shared library with some example code called "LibB", can LibB access a global variable in ProgA, which was declared as external?
Given is the following example code for demonstration of the problem:
file header.h
#ifndef TEST_H
#define TEST_H
typedef struct test_import_s {
int some_field;
} test_import_t;
extern test_import_t newtestimport;
#endif
file prog_a.c
#include <stdio.h>
#include <windows.h>
#include "header.h"
test_import_t newtestimport = {
.some_field = 42
};
int main()
{
HINSTANCE hinstLib;
typedef void (*FunctionPointer)();
newtestimport.some_field = 42;
hinstLib = LoadLibrary("lib_b.dll");
if (hinstLib != NULL)
{
FunctionPointer initialize_lib_b;
initialize_lib_b = (FunctionPointer)GetProcAddress(hinstLib, "initialize_lib_b");
if (initialize_lib_b != NULL)
{
initialize_lib_b();
}
FreeLibrary(hinstLib);
}
return 0;
}
file lib_b.c
#include <stdio.h>
#include "header.h"
test_import_t *timp;
void initialize_lib_b() {
timp = &newtestimport;
int some_field = timp->some_field;
printf("Result from function: %d\n", some_field);
}
file CMakeLists.txt
cmake_minimum_required(VERSION 3.24)
project(dynamic-library-2 C)
set(CMAKE_C_STANDARD 23)
add_library(lib_b SHARED lib_b.c)
set_target_properties(lib_b PROPERTIES PREFIX "" OUTPUT_NAME "lib_b")
add_executable(prog_a prog_a.c)
target_link_libraries(prog_a lib_b)
In the above example, the headerfile header.h defines the struct test_import_t and an external variable newtestimport using this struct. In the C file of the main program prog_a.c one property of this struct is assigned the value 42. It then dynamically loads the library lib_b.c using the Windows API and executes a function in it. The function then should access the variable newtestimport of the main program and print out the value of the variable (42).
This example does not work. The compiler throws the following error:
====================[ Build | prog_a | Debug ]==================================
C:\Users\user1\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\223.8617.54\bin\cmake\win\x64\bin\cmake.exe --build C:\Users\user1\projects\learning-c\cmake-build-debug --target prog_a -j 9
[1/2] Linking C shared library dynamic-library-2\lib_b.dll
FAILED: dynamic-library-2/lib_b.dll dynamic-library-2/liblib_b.dll.a
cmd.exe /C "cd . && C:\Users\user1\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\223.8617.54\bin\mingw\bin\gcc.exe -fPIC -g -Wl,--export-all-symbols -shared -o dynamic-library-2\lib_b.dll -Wl,--out-implib,dynamic-library-2\liblib_b.dll.a -Wl,--major-image-version,0,--minor-image-version,0 dynamic-library-2/CMakeFiles/lib_b.dir/lib_b.c.obj -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:\Users\user1\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\223.8617.54\bin\mingw\bin/ld.exe: dynamic-library-2/CMakeFiles/lib_b.dir/lib_b.c.obj:lib_b.c:(.rdata$.refptr.newtestimport[.refptr.newtestimport]+0x0): undefined reference to `newtestimport'
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
How can the example be fixed to accomplish the described goal?
Windows DLLs are self-contained, and can not have undefined references similar to newtestimport, unless these references are satisfied by another DLL.
How can the example be fixed to accomplish the described goal?
The best fix is to pass the address of newtestimport into the function that needs it (initialize_lib_b() here).
If for some reason you can't do that, your next best option is to define the newtestimport as a dllexport variable in another DLL, e.g. lib_c.dll.
Then both the main executable and lib_b.dll would be linked against lib_c.lib, and would both use that variable from lib_c.dll.
P.S. Global variables are a "code smell" and a significant source of bugs. You should avoid them whenever possible, and in your example there doesn't seem to be any good reason to use them.

__e_acsl_assert is not getting added for all given assert in .i file

I am new to Frama-C. I specifically need to use e-acsl plugin for verification purposes. I used first.i file as
int main(void) {
int x = 0;
/∗# assert x == 0; ∗/
/∗# assert x == 1; ∗/
return 0;
}
Created monitored_first.c file from first.i file using the following command.
$ frama-c -e-acsl first.i -then-last -print -ocode monitored_first.c
The main function inside the monitored_first.c looks like the one below.
int main(void)
{
int __retres;
__e_acsl_memory_init((int *)0,(char ***)0,8UL);
int x = 0;
__retres = 0;
__e_acsl_memory_clean();
return __retres;
}
It is not adding e_acsl assertion for x==1.
I tried it using the "e-acsl-gcc.sh" script , which generated the monitored_first.i file. But the main function inside monitored_first.i is same as that in monitored_first.c.
$ e-acsl-gcc.sh -c -omonitored_first.i first.i
The above command generated two executable, "a.out.e-acsl" and "a.out". It also generates some warnings when run in ubuntu 22.04 as follows:
/home/amrutha/.opam/4.11.1/bin/frama-c -remove-unused-specified-functions -machdep gcc_x86_64 '-cpp-extra-args= -std=c99 -D_DEFAULT_SOURCE -D__NO_CTYPE -D__FC_MACHDEP_X86_64 ' -no-frama-c-stdlib first.i -e-acsl -e-acsl-share=/home/amrutha/.opam/4.11.1/bin/../share/frama-c/e-acsl -then-last -print -ocode monitored_first.i
[kernel] Parsing first.i (no preprocessing)
[e-acsl] beginning translation.
[kernel] Parsing FRAMAC_SHARE/e-acsl/e_acsl.h (with preprocessing)
/tmp/ppannot15ad34.c:362: warning: "__STDC_IEC_60559_BFP__" redefined
362 | #define __STDC_IEC_60559_BFP__ 201404L
|
In file included from <command-line>:
/usr/include/stdc-predef.h:39: note: this is the location of the previous definition
39 | # define __STDC_IEC_60559_BFP__ 201404L
|
/tmp/ppannot15ad34.c:363: warning: "__STDC_IEC_60559_COMPLEX__" redefined
363 | #define __STDC_IEC_60559_COMPLEX__ 201404L
|
In file included from <command-line>:
/usr/include/stdc-predef.h:49: note: this is the location of the previous definition
49 | # define __STDC_IEC_60559_COMPLEX__ 201404L
|
[e-acsl] translation done in project "e-acsl".
+ gcc -std=c99 -m64 -g -O2 -fno-builtin -fno-merge-constants -Wall -Wno-long-long -Wno-attributes -Wno-nonnull -Wno-undef -Wno-unused -Wno-unused-function -Wno-unused-result -Wno-unused-value -Wno-unused-function -Wno-unused-variable -Wno-unused-but-set-variable -Wno-implicit-function-declaration -Wno-empty-body first.i -o a.out
+ gcc -DE_ACSL_SEGMENT_MMODEL -std=c99 -m64 -g -O2 -fno-builtin -fno-merge-constants -Wall -Wno-long-long -Wno-attributes -Wno-nonnull -Wno-undef -Wno-unused -Wno-unused-function -Wno-unused-result -Wno-unused-value -Wno-unused-function -Wno-unused-variable -Wno-unused-but-set-variable -Wno-implicit-function-declaration -Wno-empty-body -I/home/amrutha/.opam/4.11.1/bin/../share/frama-c/e-acsl -o a.out.e-acsl monitored_first.i /home/amrutha/.opam/4.11.1/bin/../share/frama-c/e-acsl/e_acsl_rtl.c /home/amrutha/.opam/4.11.1/bin/../lib/frama-c/e-acsl/libeacsl-dlmalloc.a -lgmp -lm
In ubuntu 20.04 there is no any warning, only the end part is getting displayed. When run ./a.out.e-acsl , it simply run the code without any message, which is not supposed. The expected output should look like this:
$ ./a.out.e-acsl
first.i: In function 'main'
first.i:4: Error: Assertion failed:
The failing predicate is:
x == 1.
Aborted (core dumped)
$ echo $?
134
I tried it in ubuntu 22.04 with opam version 2.1.2 and Fragma-C 25.0
and ubuntu 20.04 with opam version 2.0.5 and Fragma-C 25.0
The same issue has been posted to Frama-C's public bug tracking and it seems the cause might have been the non-ASCII asterisk characters used in the ACSL annotations: ∗ instead of *.
I still don't understand how the comments could parse at all (my compiler gives a syntax error), but the user seems to indicate that replacing them solved the problem.
In any case, in similar situations one can either use the Frama-C GUI to open the parsed file and check if Frama-C recognizes the ACSL annotations (they should show up in the CIL normalized code), or try other analyses, e.g. running frama-c -eva and checking that it detects the annotations.

using R's c code in my standalone executables: "Undefined symbols"

Suppose I have the following c source code, in dexp_test.c:
#include <stdio.h>
double dexp(double x, double scale, int log);
int main() {
double x;
x = dexp(1 , 2, 0);
printf("Value: %f\n", x);
return 0;
}
where dexp is defined in R's source code (https://github.com/wch/r-source/blob/trunk/src/nmath/dexp.c). I would like to compile this to a standalone executable. I have R 4.0 installed on my system. I have the following gcc lines:
gcc r-source/src/nmath/dexp.c -I/Library/Frameworks/R.framework/Versions/4.0/Resources/include -c -o a.o
gcc dexp_test.c -c -o b.o
These lines run just fine on my system and I am left with new files a.o and b.o without errors.
When I run this line to get an executable:
gcc -o test_exp a.o b.o
...I get these errors:
Undefined symbols for architecture x86_64:
"_R_NaN", referenced from:
_Rf_dexp in a.o
"_R_NegInf", referenced from:
_Rf_dexp in a.o
"_dexp", referenced from:
_main in b.o
(maybe you meant: _Rf_dexp)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I'm definitely missing something conceptually here; how do I get this to compile? If it helps, I'm on OSX 15.6, and the output of gcc -v is
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
You should mention the operating system you are using.
You need to include the appropriate headers. And tell the linker where and which libraries you want to use.
So your source should be
#include <stdio.h>
#include <R.h>
#include <Rmath.h>
int main() {
double x;
x = dexp(1 , 2, 0);
printf("Value: %f\n", x);
return 0;
}
And on the command line you should use the following
gcc -I/Library/Frameworks/R.framework/Versions/4.0/Resources/include -L/Library/Frameworks/R.framework/Versions/4.0/Resources/lib -lR -o test_exp trydexp.c

Qt output (qDebug qWarning etc) does not work if application is executed via cronjob

I created a reproduction sample for this:
#include <iostream>
#include <QtCore/QLoggingCategory>
#include <QtCore/QDebug>
#include <QtCore/QtCore>
using namespace std;
int main () {
int i;
QLoggingCategory::setFilterRules("*.debug=true\n");
QLoggingCategory LogO(NULL);
if (LogO.isDebugEnabled()) {
cout << "QDebug enabled\n";
} else {
cout << "QDebug disabled!\n";
}
cout << "Start!\n";
qDebug() << "qStart!";
cerr << "print to stderr.\n";
qWarning() << "qWarning";
return 0;
}
Build steps:
g++ -c -fPIC -I/usr/include/qt5 main.cpp -o main.o
g++ -fPIC main.o -L /usr/lib64 -lQt5Core -o testapp
When executing the application in an interactive shell, output redirection works as expected:
Setup:
./testapp > out 2> err
Output:
>>cat out:
QDebug enabled
Start!
>>cat err:
qStart!
print to stderr.
qWarning
However, it does not work if the application is executed as a cronjob, the output of qDebug() and qWarning() is missing:
Setup:
* * * * * username /home/username/temp/build/testapp 1> /home/username/temp/log/out 2> /home/username/temp/log/err
Output:
>>cat /home/username/temp/log/out
QDebug enabled
Start!
>>cat home/username/temp/log/err
print to stderr.
Enviroment vars
The output of env in the interative shell is as follows:
LS_COLORS=*long string*
SSH_CONNECTION=*censored*
LANG=en_US.UTF-8
HISTCONTROL=ignoredups
HOSTNAME=*censored*
XDG_SESSION_ID=492
USER=username
SELINUX_ROLE_REQUESTED=
PWD=/home/username/temp/build
HOME=/home/username
SSH_CLIENT=*censored*
SELINUX_LEVEL_REQUESTED=
SSH_TTY=/dev/pts/0
MAIL=/var/spool/mail/username
TERM=xterm
SHELL=/bin/bash
SELINUX_USE_CURRENT_RANGE=
SHLVL=1
LOGNAME=username
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
XDG_RUNTIME_DIR=/run/user/1000
PATH=/usr/lib64/ccache:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/username/.local/bin:/home/username/bin
HISTSIZE=1000
LESSOPEN=||/usr/bin/lesspipe.sh %s
_=/usr/bin/env
OLDPWD=/home/username/temp/build/logs
The output of env when called via cronjob is as follows:
LS_COLORS=*long string*
LANG=en_US.UTF-8
HISTCONTROL=ignoredups
HOSTNAME=*censored*
XDG_SESSION_ID=995
USER=username
PWD=/home/username
HOME=/home/username
MAIL=/var/spool/mail/username
TERM=xterm
SHELL=/bin/bash
SHLVL=1
LOGNAME=username
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
XDG_RUNTIME_DIR=/run/user/1000
PATH=/usr/lib64/ccache:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/username/.local/bin:/home/username/bin
LESSOPEN=||/usr/bin/lesspipe.sh %s
_=/usr/bin/env
The issue is that qt behaves differently depending if it thinks that it is running in an (interactive?) terminal or not.
Quote:
One pitfall to be aware of: the destination of logging depends on an environment variable. If the variable QT_LOGGING_TO_CONSOLE is set to 1, the message functions will always log to the console. If set to 0, they will not log to the console, and will instead log to syslog, if enabled. When the environment variable is not set, the message functions log to a console if one is present (i.e. if the program is attached to a terminal). Thus, to ensure that the output of our example program goes to syslog, I set the environment variable to 0 within the program.
Therefore, the output of qDebug, QWarning etc. when executed from cron was not output via stderr, but directly handed over to journald.
TL;DR: quickfix: add QT_LOGGING_TO_CONSOLE=1 to /etc/crontab
.
.
PS: note if you need to debug an issue with QDebug:
be aware of this: https://bugzilla.redhat.com/show_bug.cgi?id=1227295
you can add QT_LOGGING_DEBUG=1 as an environment variable to make
qt output changes in logging behavior during execution.
cronjob redirects output and err to email address.
add >> /tmp/myscript.log 2>&1 in your crontab entry.
see this answer

How to include nmath.h?

I would like to include the header nmath.h for my C code (within an R package) to find R_FINITE and ML_ERR_return_NAN. I found that one cannot include nmath.h directly. For R_FINITE to be found, I could include R_ext/libextern.h. But I don't know what to include so that ML_ERR_return_NAN is found. Any ideas? I found here that Prof. Brian Ripley referred to Writing R Extensions, but I couldn't find nmath.h being addressed there (where exactly?)
On Debian or Ubuntu:
sudo apt-get install r-mathlib
after which you can build test programs such as this:
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4;
// compile-command: "gcc -s -Wall -O3 \
// -I/usr/share/R/include -o rmath_rnorm \
// rmath_rnorm.c -lRmath -lm" -*-
// Compare to
// $ Rscript -e "RNGkind('Marsaglia'); \
// .Random.seed[2:3] <- c(123L, 456L); rnorm(2)"
// [1] -0.2934974 -0.3343770
#include <stdio.h>
#define MATHLIB_STANDALONE 1
#include <Rmath.h>
int main(void) {
set_seed(123, 456);
printf("rnorm: %f %f\n", rnorm(0.0, 1.0), rnorm(0.0, 1.0));
return 0;
}
Note: The first four lines should be one-line in the file you safe, then M-x compile build the program for your. Ditto for the Rscript invocation: one line.
Edit: Drats. Answered the wrong question :) nmath.h appears to not be exported from src/nmath/nmath.h but this R Mathlibrary is what is exported by R Core for use by others. Where as the nmath.h file has
/* Private header file for use during compilation of Mathlib */
#ifndef MATHLIB_PRIVATE_H
#define MATHLIB_PRIVATE_H
so you are not supposed to rely on it.

Resources