Failure to compare strings with eBPF - bpf

When I run the following code I get an error.
#include <uapi/linux/utsname.h>
#include <linux/pid_namespace.h>
struct uts_namespace {
struct kref kref;
struct new_utsname name;
};
static __always_inline char * get_task_uts_name(struct task_struct *task){
return task->nsproxy->uts_ns->name.nodename;
}
int cmpNamespace(void *ctx) {
struct task_struct *task;
task = (struct task_struct *)bpf_get_current_task();
if (strcmp(get_task_uts_name(task),"namespace")==0){
...
}
return 0;
}
Error:
bpf: Failed to load program: Invalid argument
unknown opcode 00
processed 0 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0
HINT: The 'unknown opcode' can happen if you reference a global or static variable, or data in read-only section. For example, 'char *p = "hello"' will result in p referencing a read-only section, and 'char p[] = "hello"' will have "hello" stored on the stack.
But this works just fine
int cmpNamespace(void *ctx) {
char * test = "aaaa";
if (strcmp(test,"namespace")==0){
...
}
return 0;
}
Can anyone tell me why this is happening and how I could go about correcting it ?
I am using python bcc to hook the function.
Thanks!

The issue is that you are using strcmp. BPF programs cannot use functions from the libc.
Your second example probably works because the compiler is able to optimize it and remove the call to strcmp. Since both arguments are known at compile-time, there's no need to use strcmp to know if they are equal.
As pointed out by #Qeole in comments, you can use __builtin_memcmp() instead, since you know the size of one of your strings and are only trying to know if they are equal.

Related

Why the output of my program is the value of secret?

#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX-1)
int main()
{
int secret = 0x12345678;
int array[1] = {0};
printf("%d",array[INT_MIN+1]);
}
The code run without stack protector.
the question is about integer overflow, but i dont understand why it work because the value of INT_MIN + 1 is -2147483647. and if i want to print the value of secret, I need to write: array[-1]
Looking at your code, The printf returns 0 as it is an array of int, not the secret.
I think that there is an unpredictable behavior due to index outbound. You are declaring an array of 1 element but referring to an outbound index of the array. Maybe this post can help.

store string in char array assignment makes integer from pointer without a cast

#include <stdio.h>
int main(void){
char c[8];
*c = "hello";
printf("%s\n",*c);
return 0;
}
I am learning pointers recently. above code gives me an error - assignment makes integer from pointer without a cast [enabled by default].
I read few post on SO about this error but was not able to fix my code.
i declared c as any array of 8 char, c has address of first element. so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello".
Please someone help me identify the issue and help me fix it.
mark
i declared c as any array of 8 char, c has address of first element. - Yes
so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello". - No. Value of "hello" (pointer pointing to some static string "hello") will be assigned to *c(1byte). Value of "hello" is a pointer to string, not a string itself.
You need to use strcpy to copy an array of characters to another array of characters.
const char* hellostring = "hello";
char c[8];
*c = hellostring; //Cannot assign pointer to char
c[0] = hellostring; // Same as above
strcpy(c, hellostring); // OK
#include <stdio.h>
int main(void){
char c[8];//creating an array of char
/*
*c stores the address of index 0 i.e. c[0].
Now, the next statement (*c = "hello";)
is trying to assign a string to a char.
actually if you'll read *c as "value at c"(with index 0),
it will be more clearer to you.
to store "hello" to c, simply declare the char c[8] to char *c[8];
i.e. you have to make array of pointers
*/
*c = "hello";
printf("%s\n",*c);
return 0;
}
hope it'll help..:)

Matlab mex c: strange calculation error with long double

I've noticed a problem on some C code that I'm writing where when I multiply two long doubles I sometimes get lower than expected accuracy. I've isolated an example below, note that this is an mex file for use in matlab. Repeating exactly the same code in pure c results in the expected behaviour.
#include <mex.h>
#include <stdint.h>
typedef int32_t q0_31; // 32 bit signed fixed point number with 31 fractional bits
// conversion to long double from q0_31
long double q0_31_to_ldouble(q0_31 d) {
return d/2147483648.0L;
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize nInputs = 0;
mwSize nOutputs = 0;
q0_31 b;
long double b_ld;
/* check for proper number of arguments */
if( nrhs!=nInputs )
mexErrMsgIdAndTxt("filter_interface:nrhs","wrong number of inputs!");
if( nlhs!=nOutputs )
mexErrMsgIdAndTxt("filter_interface:nlhs","wrong number of outputs!");
// random value for b
b = 0x81948b0e;
// convert to long double directly
b_ld = b/2147483648.0L;
mexPrintf("Inline calculation...\n");
mexPrintf("b_ld:\t%0.16LA\n",b_ld);
mexPrintf("b_ld^2:\t %0.16LA\n",b_ld*b_ld);
// repeat with sub function
b_ld = q0_31_to_ldouble(b);
mexPrintf("Exactly the same with sub function...\n");
mexPrintf("b_ld:\t%0.16LA\n",b_ld);
mexPrintf("b_ld^2:\t %0.16LA\n",b_ld*b_ld);
}
After compilation, this is the output I get from the code:
Inline calculation...
b_ld: -0XF.CD6E9E4000000000P-4
b_ld^2: 0XF.9B7D0E4BEE0D3100P-4
Exactly the same with sub function...
b_ld: -0XF.CD6E9E4000000000P-4
b_ld^2: 0XF.9B7D0E4BEE0D0000P-4
It is totally bizarre, the value returned by the function is exactly the same as the inline calculation. Yet when I square it I get a different result.
As I only get this behaviour in the mex and not when I compile the same code directly with gcc I thought it might be due to some strange compiler flag that matlab uses. But I have not been able to find anything.
Any ideas? Can anyone replicate?
MATLAB Version: 7.14.0.739 (R2012a)
gcc: 4.8.1-10ubuntu9

Calling mxDestroyArray on mxArray objects returned from Matlab Compiler Runtime

We've been interfacing with a library created from the Matlab Compiler. Our problem is related to an array returned from the library.
Once we're finished with the array, we'd like to free the memory, however, doing this causes occasional segmentation faults.
Here is the Matlab library (bugtest.m)::
function x = bugtest(y)
x = y.^2;
Here is the command we used to build it (creating libbugtest.so, and libbugtest.h)::
mcc -v -W lib:libbugtest -T link:lib bugtest.m
Here is our C test program (bug_destroyarray.c)::
#include <stdio.h>
#include <stdlib.h>
#include "mclmcrrt.h"
#include "libbugtest.h"
#define TESTS 15000
int main(int argc, char **argv)
{
const char *opts[] = {"-nojvm", "-singleCompThread"};
mclInitializeApplication(opts, 2);
libbugtestInitialize();
mxArray *output;
mxArray *input;
double *data;
bool result;
int count;
for (count = 0; count < TESTS; count++) {
input = mxCreateDoubleMatrix(4, 1, mxREAL);
data = mxGetPr(input); data[0] = 0.5; data[1] = 0.2; data[2] = 0.2; data[3] = 0.1;
output = NULL;
result = mlfBugtest(1, &output, input);
if (result) {
/* HERE IS THE PROBLEMATIC LINE */
/*mxDestroyArray(output);*/
}
mxDestroyArray(input);
}
libbugtestTerminate();
mclTerminateApplication();
}
Here is how we compile the C program (creating bug_destroyarray)::
mbuild -v bug_destroyarray.c libbugtest.so
We believe that mxDestroyArray(output) is problematic.
We run the following to test crashing:
On each of the 32 cluster nodes.
Run bug_destroyarray.
Monitor output for segmentation faults.
Roughly 10% of the time there is a crash. If this is independent across nodes
then you might suppose it is crashing roughly 0.3% of the time.
When we take out that problematic line we are unable to cause it to crash.
However memory usage gradually increases when this line is not included.
From the research we've done, it seems we are not supposed to destroy the array returned, if not, how do we stop from leaking memory?
Thanks.
Okay, I know this is a little old now, but in case it helps clarify things for anyone passing by ...
Amro provides the most pertinent information, but to expand upon it, IF you don't call the mxDestroyArray function as things stand, then you WILL leak memory, because you've set output to NULL and so the mlf function won't try to call mxDestroyArray. The corollary of this is that if you've called mxDestroyArray AND then try to call the mlf function AND output is NOT NULL, then the mlf function WILL try to call mxDestroyArray on output. The question then is to what does output point? It's a bit of a dark corner what happens to output after passing it to mxDestroyArray. I'd say it's an unwarranted assumption that it's set to NULL; it's certainly not documented that mxDestroyArray sets its argument to NULL. Therefore, I suspect what is happening is that in between your call to mxDestroyArray and the code re-executing the mlf function, something else has been allocated the memory pointed to by output and so your mlf function tries to free memory belonging to something else. Voila, seg fault. And of course this will only happen if that memory has been reallocated. Sometimes you'll get lucky, sometimes not.
The golden rule is if you're calling mxDestroyArray yourself for something that is going to be re-used, set the pointer to NULL immediately afterwards. You only really need to destroy stuff at the end of your function anyway, because you can safely re-use output variables in mlf calls.
Guy
A few notes:
I don't see singleCompThread in the list of allowed options for mclInitializeApplication.
The recommended way to compile your C program is to dynamically link against the compiled library:
mbuild -v -I. bug_destroyarray.c -L. -lbugtest
At the top of your C program, just include the generated header file, it will include other headers in turn. From looking at the generated header, it has:
#pragma implementation "mclmcrrt.h"
#include "mclmcrrt.h"
I dont know the exact meaning of this pragma line, but maybe it matters with GCC compilers..
The fact that both mlx/mlf generated functions return booleans is undocumented. But looking at the header files, both signatures do indeed return a bool:
extern bool mlxBugtest(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
extern bool mlfBugtest(int nargout, mxArray** x, mxArray* y);
I tried your code and it works just fine with no segfaults. As I dont have access to a cluster of computers, my testing was only done on my local machine (WinXP with R2013a).
I had to remove both MCR initialization options for it to work (specifically the nojvm caused a runtime error). Below is the full code with slight modifications. It took around 10 seconds to run:
#include <stdio.h>
#include <stdlib.h>
#include "libbugtest.h"
#define TESTS 15000
int main()
{
mxArray *output, *input;
double *data;
int count;
bool result;
if( !mclInitializeApplication(NULL,0) ) {
fprintf(stderr, "Could not initialize the application.\n");
return EXIT_FAILURE;
}
if ( !libbugtestInitialize() ) {
fprintf(stderr, "Could not initialize the library.\n");
return EXIT_FAILURE;
}
for (count = 0; count < TESTS; count++) {
input = mxCreateDoubleMatrix(4, 1, mxREAL);
data = mxGetPr(input);
data[0] = 0.5; data[1] = 0.2; data[2] = 0.2; data[3] = 0.1;
output = NULL;
result = mlfBugtest(1, &output, input);
if (!result) {
fprintf(stderr, "call failed on count=%d\n", count);
return EXIT_FAILURE;
}
mxDestroyArray(output); output = NULL;
mxDestroyArray(input); input = NULL;
}
libbugtestTerminate();
mclTerminateApplication();
return EXIT_SUCCESS;
}
Also the compilation step is a bit different on Windows, since we statically link against the import lib (which inserts a stub to dynamically load the DLL on runtime):
mbuild -v -I. bug_destroyarray.c libbugtest.lib
Thanks for the detailed reply Amro.
We tried changing our compilation steps to the recommended ones, with no success.
The following fixed our seg-faulting problem:
Do not set output = NULL at each iteration, instead do it once outside of the loop.
Do not call mxDestroyArray(output) inside the loop, reference: here.
Our misunderstanding was that (it seems) you are supposed to reuse mxArray pointers which you pass to MATLAB functions. It makes things slightly cumbersome on our side as we need to be careful reusing this pointer.
However, memory is completely stable, and we've not had a crash since.

Adding a field to an empty struct

Assuming I have a struct S of size 0x1 with the fields a and b, what is the most elegant way to add a field c to it?
Usually I am able to do it like this:
S = struct('a',0,'b',0); %1x1 struct with fields a,b
S.c = 0
However, if I receive an empty struct this does not work anymore:
S = struct('a',0,'b',0);
S(1) = []; % 0x1 struct with fields a,b
S.c = 0;
% A dot name structure assignment is illegal when the structure is empty.
% Use a subscript on the structure.
I have thought of two ways to deal with this, but both are quite ugly and feel like workarounds rather than solutions. (Note the possibility of a non-empty struct should also be dealt with properly).
Adding something to the struct to ensure it is not empty, adding the field, and making the struct empty again
Initializing a new struct with the required fieldnames, filling it with the data from the original struct, and overwriting the original struct
I realize that it may be odd that I care about empty structs, but unfortunately part of the code that is not managed by me will crash if the fieldname does not exist. I have looked at help struct, help subsasgn and also searched for the given error message but so far I have not yet found any hints. Help is therefore much appreciated!
You can use deal to solve this problem:
S = struct('a',0,'b',0);
S(1) = [];
[S(:).c] = deal(0);
This results in
S =
1x0 struct array with fields:
a
b
c
This works also for non-empty structs:
S = struct('a',0,'b',0);
[S(:).c] = deal(0);
which results in
S =
a: 0
b: 0
c: 0
How about
S = struct('a', {}, 'b', {}, 'c', {} );
To create an empty struct?
Another way is to use mex file with mxAddField as a workaround to the error you got:
A dot name structure assignment is illegal when the structure is empty.
Use a subscript on the structure.
You can use setfield to solve the problem.
S = struct('a', {}, 'b', {});
S = setfield(S, {}, 'c', [])
This results in
S =
0x0 struct array with fields:
a
b
c
Just to expand on #Shai's answer, here is a simple MEX-function you can use:
addfield.c
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *fieldname;
/* Check for proper number of input and output arguments */
if (nrhs != 2) {
mexErrMsgIdAndTxt("struct:nrhs", "Two inputs required.");
} else if (nlhs > 1) {
mexErrMsgIdAndTxt("struct:nlhs", "Too many output arguments.");
} else if (!mxIsStruct(prhs[0])) {
mexErrMsgIdAndTxt("struct:wrongType", "First input must be a structure.");
} else if (!mxIsChar(prhs[1]) || mxGetM(prhs[1])!=1) {
mexErrMsgIdAndTxt("struct:wrongType", "Second input must be a string.");
}
/* copy structure for output */
plhs[0] = mxDuplicateArray(prhs[0]);
/* add field to structure */
fieldname = mxArrayToString(prhs[1]);
mxAddField(plhs[0], fieldname);
mxFree(fieldname);
}
Example:
>> S = struct('a',{});
>> S = addfield(S, 'b')
S =
0x0 struct array with fields:
a
b