I can't get copy_from_user to work properly - linux-kernel

I am very new in kernel coding. My question might seem very silly but I have spent quite amount of time and couldn't figure out what I am doing wrong.
here is my code. It seems like nothing gets copied to buff and when I printk result_of_cfu, it is 8 meaning 8 bytes are not copied.
what am I doing wrong here?
asmlinkage long sys_take_stat(struct array_stats *stats, long data[],long size){
unsigned long result_of_cfu = 0;
int counter = 0;
for(counter = 0;counter<size;size++){
long buff = 0;
long current_data = data[counter];
result_of_cfu = copy_from_user(&buff,&current_data,sizeof(current_data));
}
}

You should use copy_from_user instead of dereferencing data pointer:
...
for(counter = 0;counter<size;size++){
long buff;
result_of_cfu = copy_from_user(&buf, data + counter, sizeof(*data));
}

Related

C - Heap Corruption Detected when freeing array

making an assignment and had to dynamically allocate an array of pointers and then free it at the end of the function.
the problem is when I free the array, it gives me a "Heap Corruption Detected" error and i cant figure out why that happens.
can anybody see something here ?
it says im writing after the end of allocated memory but i cant see why.
typedef struct _client
{
char id[9];
char phone[12];
} Client;
Short_client *createShortClientArr(int n)
{
Client *arr = (Client *)malloc(n * sizeof(Client));
char garbage;
garbage = getc(stdin);//for getting the '\n' from the last input
for (int i = 0; i < n; i++)
{
fgets(arr[i].id, 9, stdin);
arr[i].id[9] = '\0';
garbage = getc(stdin);
fgets(arr[i].phone, 12, stdin);
arr[i].phone[12] = '\0';
garbage = getc(stdin);
}
free(arr);
}
When you free memory, Windows will also check and see if you'd written past the end of the array. Since you did, it throws this exception, to let you know you have a bug.
char phone[12];
This creates an array whose indecies are 0-11.
arr[i].phone[12] = '\0';
12 is not a valid index for this array, and so this writes a '\0' to the char one past the end of the array. You have the same bug with your other array as well.

node.js c++ addon - afraid of memory leak

first of all I admit I'm a newbie in C++ addons for node.js.
I'm writing my first addon and I reached a good result: the addon does what I want. I copied from various examples I found in internet to exchange complex data between the two languages, but I understood almost nothing of what I wrote.
The first thing scaring me is that I wrote nothing that seems to free some memory; another thing which is seriously worrying me is that I don't know if what I wrote may helps or creating confusion for the V8 garbage collector; by the way I don't know if there are better ways to do what I did (iterating over js Object keys in C++, creating js Objects in C++, creating Strings in C++ to be used as properties of js Objects and what else wrong you can find in my code).
So, before going on with my job writing the real math of my addon, I would like to share with the community the nan and V8 part of it to ask if you see something wrong or that can be done in a better way.
Thank you everybody for your help,
iCC
#include <map>
#include <nan.h>
using v8::Array;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Value;
using v8::String;
using Nan::AsyncQueueWorker;
using Nan::AsyncWorker;
using Nan::Callback;
using Nan::GetFunction;
using Nan::HandleScope;
using Nan::New;
using Nan::Null;
using Nan::Set;
using Nan::To;
using namespace std;
class Data {
public:
int dt1;
int dt2;
int dt3;
int dt4;
};
class Result {
public:
int x1;
int x2;
};
class Stats {
public:
int stat1;
int stat2;
};
typedef map<int, Data> DataSet;
typedef map<int, DataSet> DataMap;
typedef map<float, Result> ResultSet;
typedef map<int, ResultSet> ResultMap;
class MyAddOn: public AsyncWorker {
private:
DataMap *datas;
ResultMap results;
Stats stats;
public:
MyAddOn(Callback *callback, DataMap *set): AsyncWorker(callback), datas(set) {}
~MyAddOn() { delete datas; }
void Execute () {
for(DataMap::iterator i = datas->begin(); i != datas->end(); ++i) {
int res = i->first;
DataSet *datas = &i->second;
for(DataSet::iterator l = datas->begin(); l != datas->end(); ++l) {
int dt4 = l->first;
Data *data = &l->second;
// TODO: real population of stats and result
}
// test result population
results[res][res].x1 = res;
results[res][res].x2 = res;
}
// test stats population
stats.stat1 = 23;
stats.stat2 = 42;
}
void HandleOKCallback () {
Local<Object> obj;
Local<Object> res = New<Object>();
Local<Array> rslt = New<Array>();
Local<Object> sts = New<Object>();
Local<String> x1K = New<String>("x1").ToLocalChecked();
Local<String> x2K = New<String>("x2").ToLocalChecked();
uint32_t idx = 0;
for(ResultMap::iterator i = results.begin(); i != results.end(); ++i) {
ResultSet *set = &i->second;
for(ResultSet::iterator l = set->begin(); l != set->end(); ++l) {
Result *result = &l->second;
// is it ok to declare obj just once outside the cycles?
obj = New<Object>();
// is it ok to use same x1K and x2K instances for all objects?
Set(obj, x1K, New<Number>(result->x1));
Set(obj, x2K, New<Number>(result->x2));
Set(rslt, idx++, obj);
}
}
Set(sts, New<String>("stat1").ToLocalChecked(), New<Number>(stats.stat1));
Set(sts, New<String>("stat2").ToLocalChecked(), New<Number>(stats.stat2));
Set(res, New<String>("result").ToLocalChecked(), rslt);
Set(res, New<String>("stats" ).ToLocalChecked(), sts);
Local<Value> argv[] = { Null(), res };
callback->Call(2, argv);
}
};
NAN_METHOD(AddOn) {
Local<Object> datas = info[0].As<Object>();
Callback *callback = new Callback(info[1].As<Function>());
Local<Array> props = datas->GetOwnPropertyNames();
Local<String> dt1K = Nan::New("dt1").ToLocalChecked();
Local<String> dt2K = Nan::New("dt2").ToLocalChecked();
Local<String> dt3K = Nan::New("dt3").ToLocalChecked();
Local<Array> props2;
Local<Value> key;
Local<Object> value;
Local<Object> data;
DataMap *set = new DataMap();
int res;
int dt4;
DataSet *dts;
Data *dt;
for(uint32_t i = 0; i < props->Length(); i++) {
// is it ok to declare key, value, props2 and res just once outside the cycle?
key = props->Get(i);
value = datas->Get(key)->ToObject();
props2 = value->GetOwnPropertyNames();
res = To<int>(key).FromJust();
dts = &((*set)[res]);
for(uint32_t l = 0; l < props2->Length(); l++) {
// is it ok to declare key, data and dt4 just once outside the cycles?
key = props2->Get(l);
data = value->Get(key)->ToObject();
dt4 = To<int>(key).FromJust();
dt = &((*dts)[dt4]);
int dt1 = To<int>(data->Get(dt1K)).FromJust();
int dt2 = To<int>(data->Get(dt2K)).FromJust();
int dt3 = To<int>(data->Get(dt3K)).FromJust();
dt->dt1 = dt1;
dt->dt2 = dt2;
dt->dt3 = dt3;
dt->dt4 = dt4;
}
}
AsyncQueueWorker(new MyAddOn(callback, set));
}
NAN_MODULE_INIT(Init) {
Set(target, New<String>("myaddon").ToLocalChecked(), GetFunction(New<FunctionTemplate>(AddOn)).ToLocalChecked());
}
NODE_MODULE(myaddon, Init)
One year and half later...
If somebody is interested, my server is up and running since my question and the amount of memory it requires is stable.
I can't say if the code I wrote really does not has some memory leak or if lost memory is freed at each thread execution end, but if you are afraid as I was, I can say that using same structure and calls does not cause any real problem.
You do actually free up some of the memory you use, with the line of code:
~MyAddOn() { delete datas; }
In essence, C++ memory management boils down to always calling delete for every object created by new. There are also many additional architecture-specific and legacy 'C' memory management functions, but it is not strictly necessary to use these when you do not require the performance benefits.
As an example of what could potentially be a memory leak: You're passing the object held in the *callback pointer to the function AsyncQueueWorker. Yet nowhere in your code is this pointer freed, so unless the Queue worker frees it for you, there is a memory leak here.
You can use a memory tool such as valgrind to test your program further. It will spot most memory problems for you and comes highly recommended.
One thing I've observed is that you often ask (paraphrased):
Is it okay to declare X outside my loop?
To which the answer actually is that declaring variables inside of your loops is better, whenever you can do it. Declare variables as deep inside as you can, unless you have to re-use them. Variables are restricted in scope to the outermost set of {} brackets. You can read more about this in this question.
is it ok to use same x1K and x2K instances for all objects?
In essence, when you do this, if one of these objects modifies its 'x1K' string, then it will change for all of them. The advantage is that you free up memory. If the string is the same for all these objects anyway, instead of having to store say 1,000,000 copies of it, your computer will only keep a single one in memory and have 1,000,000 pointers to it instead. If the string is 9 ASCII characters long or longer under amd64, then that amounts to significant memory savings.
By the way, if you don't intend to modify a variable after its declaration, you can declare it as const, a keyword short for constant which forces the compiler to check that your variable is not modified after declaration. You may have to deal with quite a few compiler errors about functions accepting only non-const versions of things they don't modify, some of which may not be your own code, in which case you're out of luck. Being as conservative as possible with non-const variables can help spot problems.

How to use mmap for devmemon MT7620n

I`m trying to access the GPIOs of a MT7620n via register settings. So far I can access them by using /sys/class/gpio/... but that is not fast enough for me.
In the Programming guide of the MT7620 page 84 you can see that the GPIO base address is at 0x10000600 and the single registers have an offset of 4 Bytes.
MT7620 Programming Guide
Something like:
devmem 0x10000600
from the shell works absolutely fine but I cannot access it from inside of a c Programm.
Here is my code:
#define GPIOCHIP_0_ADDDRESS 0x10000600 // base address
#define GPIO_BLOCK 4
volatile unsigned long *gpiochip_0_Address;
int gpioSetup()
{
int m_mfd;
if ((m_mfd = open("/dev/mem", O_RDWR)) < 0)
{
printf("ERROR open\n");
return -1;
}
gpiochip_0_Address = (unsigned long*)mmap(NULL, GPIO_BLOCK, PROT_READ|PROT_WRITE, MAP_SHARED, m_mfd, GPIOCHIP_0_ADDDRESS);
close(m_mfd);
if(gpiochip_0_Address == MAP_FAILED)
{
printf("mmap() failed at phsical address:%d %s\n", GPIOCHIP_0_ADDDRESS, strerror(errno));
return -2;
}
return 0;
}
The Output I get is:
mmap() failed at phsical address:268436992 Invalid argument
What do I have to take care of? Do I have to make the memory accessable before? I´m running as root.
Thanks
EDIT
Peter Cordes is right, thank you so much.
Here is my final solution, if somebody finds a bug, please tell me ;)
#define GPIOCHIP_0_ADDDRESS 0x10000600 // base address
volatile unsigned long *gpiochip_0_Address;
int gpioSetup()
{
const size_t pagesize = sysconf(_SC_PAGE_SIZE);
unsigned long gpiochip_pageAddress = GPIOCHIP_0_ADDDRESS & ~(pagesize-1); //get the closest page-sized-address
const unsigned long gpiochip_0_offset = GPIOCHIP_0_ADDDRESS - gpiochip_pageAddress; //calculate the offset between the physical address and the page-sized-address
int m_mfd;
if ((m_mfd = open("/dev/mem", O_RDWR)) < 0)
{
printf("ERROR open\n");
return -1;
}
page_virtual_start_Address = (unsigned long*)mmap(NULL, pagesize, PROT_READ|PROT_WRITE, MAP_SHARED, m_mfd, gpiochip_pageAddress);
close(m_mfd);
if(page_virtual_start_Address == MAP_FAILED)
{
printf("ERROR mmap\n");
printf("mmap() failed at phsical address:%d %d\n", GPIOCHIP_0_ADDDRESS, strerror(errno));
return -2;
}
gpiochip_0_Address = page_virtual_start_Address + (gpiochip_0_offset/sizeof(long));
return 0;
}
mmap's file offset argument has to be page-aligned, and that's one of the documented reasons for mmap to fail with EINVAL.
0x10000600 is not a multiple of 4k, or even 1k, so that's almost certainly your problem. I don't think any systems have pages as small as 512B.
mmap a whole page that includes the address you want, and access the MMIO registers at an offset within that page.
Either hard-code it, or maybe do something like GPIOCHIP_0_ADDDRESS & ~(page_size-1) to round down an address to a page-aligned boundary. You should be able to do something that gets the page size as a compile-time constant so it still compiles efficiently.

scoped_ptr for double pointers

Is there a halfway elegant way to upgrade to following code snipped by the use of boost's scoped_ptr or scoped_array?
MyClass** dataPtr = NULL;
dataPtr = new MyClass*[num];
memset(dataPtr, 0, sizeof(MyClass*));
allocateData(dataPtr); // allocates objects under all the pointers
// have fun with the data objects
// now I'm bored and want to get rid of them
for(uint i = 0; i < num; ++i)
delete dataPtr[i];
delete[] dataPtr;
I did it the following way now:
boost::scoped_array<MyClass*> dataPtr(new MyClass*[num]);
memset(dataPtr.get(), 0, num * sizeof(MyClass*));
allocateData(dataPtr.get());
Seems to work fine.

"Sigabrt Error" - Codechef

The following code ran perfectly in my DEV-C++ compiler but when I submitted in codechef, after running for 3-4 seconds it shows "SIGABRT ERROR". I have researched on this error and have done everything i could to debug, but even after a week I am not able to. Please Help !! Thanks in advance.
For reference question is http://www.codechef.com/problems/LOWSUM
enter code here
void selsort(long long *ssum,long long len)
{
long long low;
for(long long i=0;i<len;i++)
{
low = ssum[i];
long long pos=i;
for(int j=i+1;j<len;j++)
{
if(ssum[j]<low)
{
low = ssum[j];
pos = j;
}
}
ssum[pos] = ssum[i];
ssum[i] = low;
}
}
int main()
{
int t,k,q;
cin>>t;
for(int i=0;i<t;++i)
{
cin>>k;
cin>>q;
long long sq = k*k;
long long *mot=NULL,*sat=NULL;
mot = new long long [k];
sat = new long long [k];
long long *sum = new long long[sq];
long long qth;
long long b=0;
for(int j=0;j<k;++j)
{
cin>>mot[j];
}
for(int j=0;j<k;++j)
{
cin>>sat[j];
}
for(int j=0;j<k;++j)
{
for(int a=0;a<k;++a)
{
sum[b] = mot[a]+sat[j];
++b;
}
}
selsort(sum,sq);
for(int j=0;j<q;++j)
{
cout<<"\n";
cin>>qth;
cout<<"\n"<<sum[qth-1];
}
delete []sum;
delete []mot;
delete []sat;
}
return 0;
}
SIGABRT signal is sent due to many reasons quoting codechef
SIGABRT errors are caused by your program aborting due to a fatal error. In C++, this is normally due to an assert statement in C++ not returning true, but some STL elements can generate this if they try to store too much memory.
In your case it seems to be use of excessive memory
mot = new long long [k];
sat = new long long [k];
long long *sum = new long long[sq];
Note that the value of k can be as large as 20000 so declaring a array of size k will be fine but your sq = k*k which is of order of 4*10^8 which is causing a out of memory problem memory. And your algorithm is also not good enough to give AC within time limit.
Codechef has its own forum to ask such questions, and preferable ways to solve this problem has already been discussed there
http://discuss.codechef.com/problems/LOWSUM

Resources