I came across this situation with WinAPI's MapViewOfFile function. An Internet search didn't turn up any apparent fixes, so I will share my problem and solution here.
Consider the following snippet:
const char *name = "Global\\Object_Name";
unsigned long size = get_object_size();
HANDLE handle = CreateFileMapping(INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
size,
name);
if (!handle || handle == INVALID_HANDLE_VALUE)
exit(GetLastError());
bool created = GetLastError() == 0;
void *block = MapViewOfFile( handle,
FILE_MAP_ALL_ACCESS,
0,
0,
size);
if (block == NULL)
exit(GetLastError());
In one particular case, CreateFileMapping was successfully returning a handle. GetLastError was returning ERROR_ALREADY_EXISTS, so created == false. Now, the call to MapViewOfFile, using the same size that I passed to CreateFileMapping, returns NULL and GetLastError returns 0x05: ERROR_ACCESS_DENIED. The process was running with administrator privileges.
The MSDN documentation doesn't really mention any reason why this situation would occur. So why does CreateFileMapping succeed, but MapViewOfFile fail?
After a lot of suffer, I finally found what was causing this error in my application, in case someone else is struggling with the same, the problem is not with the MapViewOfFile method, but with the CreateFileMapping, the size of the createFileMapping should be the size of the file, not the size of the element to read, if you don't know the size then it should be 0, this does not apply to the MapViewOfFile as the value to pass as size is the length of the block you want to read/write.
Your code working will look like this:
const char *name = "Global\\Object_Name";
unsigned long size = get_object_size();
HANDLE handle = CreateFileMapping(INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
0,
name);
if (!handle || handle == INVALID_HANDLE_VALUE)
exit(GetLastError());
bool created = GetLastError() == 0;
void *block = MapViewOfFile( handle,
FILE_MAP_ALL_ACCESS,
0,
0,
size);
if (block == NULL)
exit(GetLastError());
A just putting this here to document what I found, unfortunately is hard to search for this error when you don't know what is causing it. I hope this saves a couple of hours to someone else.
I'm sure there are many reasons why ERROR_ACCESS_DENIED could occur from a call to MapViewOfFile. In my particular situation, it was due to the size argument.
The hint is in the fact that created == false. It shows that the object "Global\\Object_Name" has already been created. For whatever reason, the creating call initialised the section with a smaller size. For what seems like an oversight, the second call to CreateFileMapping will happily give you a handle to the already-existing object, even if you asked for a bigger mapping.
The call to MapViewOfFile now fails, because it's requesting a view that is bigger than the actual section.
So, if you're in a similar situation where the second call to MapViewOfFile fails, check the size that you're trying to map to.
It could be that the second project is compiling with a different structure alignment, resulting in the sizeof() operator determining different values, or some other size-determining function is not behaving as expected.
Related
I would like to read (asynchronously) BLOCK_SIZE bytes of one file, and the BLOCK_SIZE bytes of the second file, printing what has been read to the buffer as soon as the respective buffer has been filled. Let me illustrate what I mean:
// in main()
int infile_fd = open(infile_name, O_RDONLY); // add error checking
int maskfile_fd = open(maskfile_name, O_RDONLY); // add error checking
char* buffer_infile = malloc(BLOCK_SIZE); // add error checking
char* buffer_maskfile = malloc(BLOCK_SIZE); // add error checking
struct aiocb cb_infile;
struct aiocb cb_maskfile;
// set AIO control blocks
memset(&cb_infile, 0, sizeof(struct aiocb));
cb_infile.aio_fildes = infile_fd;
cb_infile.aio_buf = buffer_infile;
cb_infile.aio_nbytes = BLOCK_SIZE;
cb_infile.aio_sigevent.sigev_notify = SIGEV_THREAD;
cb_infile.aio_sigevent.sigev_notify_function = print_buffer;
cb_infile.aio_sigevent.sigev_value.sival_ptr = buffer_infile;
memset(&cb_maskfile, 0, sizeof(struct aiocb));
cb_maskfile.aio_fildes = maskfile_fd;
cb_maskfile.aio_buf = buffer_maskfile;
cb_maskfile.aio_nbytes = BLOCK_SIZE;
cb_maskfile.aio_sigevent.sigev_notify = SIGEV_THREAD;
cb_maskfile.aio_sigevent.sigev_notify_function = print_buffer;
cb_maskfile.aio_sigevent.sigev_value.sival_ptr = buffer_maskfile;
and the print_buffer() function is defined as follows:
void print_buffer(union sigval sv)
{
printf("%s\n", __func__);
printf("buffer address: %p\n", sv.sival_ptr);
printf("buffer: %.128s\n", (char*)sv.sival_ptr);
}
By the end of the program I do the usual clean up, i.e.
// clean up
close(infile_fd); // add error checking
close(maskfile_fd); // add error checking
free(buffer_infile);
printf("buffer_inline freed\n");
free(buffer_maskfile);
printf("buffer_maskfile freed\n");
The problem is, every once in a while buffer_inline gets freed before print_buffer manages to print its contents to the console. In a usual case I would employ some kind of pthread_join() but as far as I know this is impossible since POSIX does not specify that sigev_notify_function must be implemented using threads, and besides, how would I get the TID of such thread to call pthread_join() on?
Don't do it this way, if you can avoid it. If you can, just let process termination take care of it all.
Otherwise, the answer indicated in Andrew Henle's comment above is right on. You need to be sure that no more sigev_notify_functions will improperly reference the buffers.
The easiest way to do this is simply to countdown the number of expected notifications before freeing the buffers.
Note: your SIGEV_THREAD function is executed in a separate thread, though not necessarily a new thread each time. (POSIX.1-2017 System Interfaces ยง2.4.2) Importantly, you are not meant to manage this thread's lifecycle: it is detached by default, with PTHREAD_CREATE_JOINABLE explicitly noted as undefined behavior.
As an aside, I'd suggest never using SIGEV_THREAD in robust code. Per spec, the signal mask of the sigev_notify_function thread is implementation-defined. Yikes. For me, that makes it per se unreliable. In my view, SIGEV_SIGNAL and a dedicated signal-handling thread are much safer.
I am wondering how to properly double buffer the framebuffer to avoid tearing. I've done lots of research on this topic and I can't seem to find anything.
I've tried FBIO_WAITFORVSYNC. But per this thread: How to query Vsync phase in Linux it seems that this won't work.
I've also tried using FBIOGET_VSCREENINFO
and FBIOPAN_DISPLAY per this thread: Linux framebuffer graphics and VSync. But it failed due to an error discussed in this thread: invalid argument error when setting yres_virtual in fb_var_screeninfo
That thread suggested using a different driver (vesafb) to resolve the error. I managed to install uvesafb on my machine but the "Invalid Argument" error didn't go away.
I've also tried just mmaping a larger buffer per this person's suggestion: http://betteros.org/tut/graphics1.php#doublebuffer but mmap keeps returning -1.
I've also tried to implement the solution discussed here: https://pyra-handheld.com/boards/threads/my-frustrating-experiences-with-dev-fb.21062/. However the thread died without the actual solution being posted and I am doubtful of the efficiency of swapping hardware addresses (or if it can even be done).
Any help would be so greatly appreciated on this topic!
Due to a request here is the code I would ideally like to get to work:
fb0 = open("/dev/fb0", O_RDWR);
if(fb0 == 0)
error("Could not open framebuffer located in /dev/fb0!");
if (ioctl(fb0, FBIOGET_FSCREENINFO, &screeninfo_fixed) == -1)
error("Could not retrive fixed screen info!");
if (ioctl(fb0, FBIOGET_VSCREENINFO, &screeninfo_var) == -1)
error("Could not retrive variable screen info!");
screeninfo_var.xres_virtual = screeninfo_var.xres;
screeninfo_var.yres_virtual = screeninfo_var.yres * 2;
screeninfo_var.width = screeninfo_var.xres;
screeninfo_var.height = screeninfo_var.yres;
screeninfo_var.xoffset = 0;
screeninfo_var.yoffset = 0;
if (ioctl(fb0, FBIOPUT_VSCREENINFO, &screeninfo_var) == -1)
error("Could not set variable screen info!");
This will always print "Could not set variable screen info!" due to some issue extending the virtual framebuffer size.
The way I have solved the double buffering issue for framebuffer on linux is by using a separate back buffer, allocated using mmap for the same screensize:
bbp = mmap(0, screensize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
(where screensize = vinfo.yres_virtual * finfo.line_length;)
Then write all changes to this back buffer, and after all writes are over, copy the entire back buffer to the main framebuffer pointer location using say, an update() function:
memcpy(fbp, bbp, screensize);
You could, also have an updateRect() function that copies only a given area. This logic is working fine on my x64 PC gnu/linux platform.
This is driving me crazy. I'm compiling my project on Visual Studio 2012. I want to read a REG_BINARY registry entry using RegOpenKeyEx and RegQueryValueEx calls. In Debug (Multi-Threaded Debug) mode, everything works perfectly. However, in Release (Multi-Threaded) mode, RegQueryValueEx will VERY often fail with error code ERROR_MORE_DATA. Here is the code I am using:
HKEY keyHandle;
TCHAR lpData[1024];
DWORD lpcbData;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &keyHandle) != ERROR_SUCCESS){
MessageBox(NULL, L"fail", L"title", MB_OK);
return NULL;
} else if (RegQueryValueEx(keyHandle, L"DigitalProductId", NULL, NULL, (LPBYTE)lpData, &lpcbData) != ERROR_SUCCESS){
MessageBox(NULL, L"fail!", L"title", MB_OK);
return NULL;
}
MessageBox(NULL, L"success", L"title", MB_OK);
By the definition of RegQueryValueEx, lpcbData is both an In and Out parameter. That is, RegQueryValueEx both reads it and writes to it. It complains because you are passing it without initializing it first with the size of the buffer, which in your case is 1024 (also I recommend that you change TCHAR to BYTE as required by the API; You can convert it to a Unicode string later on).
Try setting it to 1024 before calling the function. If then it fails with ERROR_MORE_DATA, then your buffer is not big enough - in other words, the registry key string is too long - you can either define it to contain more characters, or, better yet, call the function first with a NULL parameter instead of the buffer, and you will get back in lpcbData the required size of the buffer. You can then allocate the required buffer on the heap. Hope this helps!
You are not initializing lpcbData before calling RegQueryValueEx(). You have to tell it how large lpData is, in bytes, so it knows how many bytes it can retreive.
DWORD lpcbData = sizeof(lpData);
Read the documentation:
lpcbData [in, out, optional]
A pointer to a variable that specifies the size of the buffer pointed to by the lpData parameter, in bytes. When the function returns, this variable contains the size of the data copied to lpData.
A better option is to ask the Registry how large the data is, then (re)allocate the buffer as needed. The example in the documentation shows you how to do that.
You should set the lpcbData to size of your buffer before passing it to RegQueryValueEx().
Sample code:
HKEY keyHandle;
TCHAR lpData[1024];
DWORD lpcbData= sizeof(lpData); //set size.
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &keyHandle) != ERROR_SUCCESS){
MessageBox(NULL, L"fail", L"title", MB_OK);
return NULL;
} else if (RegQueryValueEx(keyHandle, L"DigitalProductId", NULL, NULL, (LPBYTE)lpData, &lpcbData) != ERROR_SUCCESS){
MessageBox(NULL, L"fail!", L"title", MB_OK);
return NULL;
}
Its working by chance so that lpcData contains some random value which is higher than the actual size of data. And probably your data is not more than 1024.
Moreover, if you get ERROR_MORE_DATA error, the lpcData will indicate how much size is required to read the data. So you should update your buffer accordingly and retry.
Edit: Here is the entire code, ignore Romanian comments. Also 2 or 3 names are untranslated from Romanian: http://pastebin.com/JjtayvXX
I am trying to learn the basics of OS, now I'm working with named pipes under windows and I can't tell what's wrong.
Honestly I'm working off an example a friend did, but he's just as bad as me if not worse. While hi's program works (albeit it does something else), he can't explain anything, most likely just copied from somewhere, still ... not important, what I was trying to say I'm learning from examples, and not professional ones.
Server receives a message from the client, returns max and min numbers.
Server.c:
#include "windows.h"
#include "stdio.h"
struct Msg {
int numbers[20];
int length;
};
...
int main () {
HANDLE inputPipe, outputPipe;
Msg msg;
while (true) {
inputPipe = CreateNamedPipe ("\\\\.\\pipe\\Client2Server",
PIPE_ACCESS_INBOUND,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
0, //Numb of output bytes
sizeof(Msg), // Numb of input bytes
0, // Wait forever
NULL); // Don't know how to use security
ConnectNamedPipe (inputPipe,NULL);
// Here is where the server dies
ReadFile (inputPipe, &msg,sizeof(Msg),NULL,NULL);
Now Client.c:
struct Msg {
int numbers[20];
int length;
};
int main () {
HANDLE outputPipe, inputPipe;
Msg msg;
// #misc: read data from keyboard, create msg
outputPipe = CreateFile ("\\\\.\\pipe\\Client2Server",
GENERIC_WRITE,
FILE_SHARE_READ, // * comment after code
NULL, // again, I know nothing about security attributes
CREATE_ALWAYS, // either create or overwrite
0,
NULL);
// Here is where it dies
WriteFile (outputPipe, &msg, sizeof(Msg), NULL, NULL);
I get Access violation writing location 0x00000000. No idea why.
I would like that this process only writes, and another process (server) only reads. Is FILE_SHARE_READ OK ?
Also I don't know how to mess with CreationDisposition / FlagsAndAttributes (last 2 parameters at CreateFile), are they OK ?
Edit: Added actual answer, reference to other topic, tried it myself
WriteFile()'s fourth parameter (pointer to variable that will store number of bytes) should not be null. Based on the API description, this parameter can ONLY be NULL if the fifth param, lpOverlapped, is NOT null.
See similar topic here:
Why does WriteFile crash when writing to the standard output?
Can you check/printf the return values of ReadFile() (failed if return = 0 or FALSE) and client.c CreateFile() (failed if returns INVALID_HANDLE_VALUE) to see if they succeed?
If failed, can you print the value returned by GetLastError() immediately after the call so that we can see the specific error?
I am learning C and I am wondering what I need to add for those values in my WriteFile and ReadFile methods
lpNumberOfBytesRead and lpNumberOfBytesWritten
WriteFile((HANDLE)sock, "\x05\x01\x00", 3, NULL, NULL);
ReadFile((HANDLE)sock, buf, 1024, NULL, NULL);
it says in the documentation one of the two NULL values can't be NULL as my friend pointed out...
Any ideas *cheers
Assuming that you are not going to use overlapped I/O, (and from your question, I get a strong feeling that you are not), you need to pass a pointer to a DWORD variable that will receive the values:
DWORD NumberOfBytesWritten;
WriteFile((HANDLE)sock, "\x05\x01\x00", 3, &NumberOfBytesWritten, NULL);
If the function returns successfully (and you should check its return value to determine that), NumberOfBytesWritten will be set to the number of bytes that were actually written to the file.