Page fault with newlib functions - porting

I've been porting newlib to my very small kernel, and I'm stumped: whenever I include a function that references a system call, my program will page fault on execution. If I call a function that does not reference a system call, like rand(), nothing will go wrong.
Note: By include, I mean as long as the function, e.g. printf() or fopen(), is somewhere inside the program, even if it isn't called through main().
I've had this problem for quite some time now, and have no idea what could be causing this:
I've rebuilt newlib numerous times
Modified my ELF loader to load the
code from the section headers instead of program headers
Attempted to build newlib/libgloss separately (which failed)
Linked the libraries (libc, libnosys) through the ld script using GROUP, gcc and ld
I'm not quite sure what other information I should include with this, but I'd be happy to include what I can.
Edit: To verify, the page faults occurring are not at the addresses of the failing functions; they are elsewhere in the program. For example, when I call fopen(), located at 0x08048170, I will page fault at 0xA00A316C.
Edit 2:
Relevant code for loading ELF:
int krun(u8int *name) {
int fd = kopen(name);
Elf32_Ehdr *ehdr = kmalloc(sizeof(Elf32_Ehdr*));
read(fd, ehdr, sizeof(Elf32_Ehdr));
if (ehdr->e_ident[0] != 0x7F || ehdr->e_ident[1] != 'E' || ehdr->e_ident[2] != 'L' || ehdr->e_ident[3] != 'F') {
kfree(ehdr);
return -1;
}
int pheaders = ehdr->e_phnum;
int phoff = ehdr->e_phoff;
int phsize = ehdr->e_phentsize;
int sheaders = ehdr->e_shnum;
int shoff = ehdr->e_shoff;
int shsize = ehdr->e_shentsize;
for (int i = 0; i < pheaders; i++) {
lseek(fd, phoff + phsize * i, SEEK_SET);
Elf32_Phdr *phdr = kmalloc(sizeof(Elf32_Phdr*));
read(fd, phdr, sizeof(Elf32_Phdr));
u32int page = PMMAllocPage();
int flags = 0;
if (phdr->p_flags & PF_R) flags |= PAGE_PRESENT;
if (phdr->p_flags & PF_W) flags |= PAGE_WRITE;
int pages = (phdr->p_memsz / 0x1000) + 1;
while (pages >= 0) {
u32int mapaddr = (phdr->p_vaddr + (pages * 0x1000)) & 0xFFFFF000;
map(mapaddr, page, flags | PAGE_USER);
pages--;
}
lseek(fd, phdr->p_offset, SEEK_SET);
read(fd, (void *)phdr->p_vaddr, phdr->p_filesz);
kfree(phdr);
}
// Removed: code block that zeroes .bss: it's already zeroed whenever I check it anyways
// Removed: code block that creates thread and adds it to scheduler
kfree(ehdr);
return 0;
}
Edit 3: I've noticed that if I call a system call, such as write(), and then call printf() two or more times, I will get an unknown opcode interrupt. Odd.

Whoops! Figured it out: when I map the virtual address, I should allocate a new page each time, like so:
map(mapaddr, PMMAllocPage(), flags | PAGE_USER);
Now it works fine.
For those curious as to why it didn't work: when I wasn't including printf(), the size of the program was under 0x1000 bytes, so mapping with only one page was okay. When I include printf() or fopen(), the size of the program was much bigger so that's what caused the issue.

Related

STM32 Keil - Can not access target while debugging (AT Command UART)

I am trying to communicate with GSM module via UART communication. I could get message from the module as I expected. However when it comes to while loop (it is empty), debug session ends with "can not access target" error. Stepo by step, I am going to share my code:
Function 1 is AT_Send. (Note: Some of variables are declared globally.)
int AT_Send(UART_HandleTypeDef *huart, ATHandleTypedef *hat, unsigned char *sendBuffer, uint8_t ssize, unsigned char *responseBuffer, uint8_t rsize) {
if (HAL_UART_Transmit_IT(huart,sendBuffer,ssize) != HAL_OK) {
return -1;
}
while ((HAL_UART_GetState(huart) & HAL_UART_STATE_BUSY_TX) == HAL_UART_STATE_BUSY_TX) {
continue;
}
//;HAL_Delay(1000);
if (strstr((char*)receiveBuffer,(char*)responseBuffer) != NULL) {
rxIndex = 0;
memset(command, 0, sizeof(command));
return 0;
}
rxIndex = 0;
memset(command, 0, sizeof(command));
return 1;
}
Second function is AT_Init function. It sends AT to get OK response. At this point on, if I am not wrong, I am opening receive interrrupt and I am trying to get 1 byte.
int AT_Init(UART_HandleTypeDef *huart, ATHandleTypedef *hat)
{
HAL_UART_Receive_IT(huart,&rData,1);
tx = AT_Send(huart,hat,"AT\r",sizeof("AT\r\n"),"OK\r\n",sizeof("OK\r\n"));
return tx;
}
After these two functions, I am calling receive IT function in the call back while there are data on the bus.
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART1){
command[rxIndex] = rData;
rxIndex++;
if((rxIndex == 2) && (strstr((char*)command,"\r\n") != NULL)) {
rxIndex = 0;
} else if (strstr((char*)command,"\r\n") != NULL) {
memcpy(receiveBuffer, command, sizeof(command));
rxIndex = 0;
memset(command,0,sizeof(command));
}
HAL_UART_Receive_IT(&huart1,&rData,1);
}
}
Moreover, I am going to send a few HTTP commands simultaneously if I can get rid of this problem.
Can anyone share his/her knowledge?
Edit: Main function is shown below
tx = AT_Init(&huart1,&hat);
while (1)
{
HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_3);
HAL_Delay(500);
}
Edit 2: I had replaced uart channel by USART2, and debugger worked. I suppose that it is related to hardware. Still, I am curious about possible reasons that cause to this problem.
The question doesn't mention on which µC the program is running, I only see the "stm32" tag. Similarly, we don't know which debug protocol is used (JTAG or SWD?).
Still, I dare to guess that the toggle command for GPIO port PB3 in the main loop is causing the observations: On many (most? all?) STM32 controllers, PB3 is used as JTDO pin, which is needed for JTAG debug connections.
Please make sure to configure the debug connection to SWD (without SWO, i.e., neither SWV is correct). It may also help to check the wiring of the debug cable, the fast toggle at the PB3/JTDO line may influence the signal levels on some neighbouring SWD lines if the wiring is low quality or a fast SWD speed has been chosen.
My hypothesis can be falsified by removing all actions to PB3. If the problem remains, I'm wrong.

Why is the I2C communication failing on a second pass through the same code?

The landscape - I have a MCU that performs a lot of tasks. It exposes an I2C slave communication to a Raspberry Pi. There a number of 'registers' I have created in code on the MCU. All of these are working fine. I previously had a nano hooked up and tested everything on the MCU so I am fairly sure the MCU is behaving correctly. Most of my I2C communications are working on the Pi too. Except for one. It is a little different in that it writes three bytes.
This is my code for the RPi:
std::string i2cServo(uint8_t reg, uint8_t angle){
std::string error;
uint8_t TxBuf[3];
TxBuf[0] = 11; // The register.
TxBuf[1] = reg; // The first parameter.
TxBuf[2] = angle; // The second parameter.
close_fd();
if (!fd) {
if (open_fd_wronly() == -1) {
error = "Failed to open I2C bus.";
} else {
if (write(fd, &TxBuf, 3) != 3) {
std::cerr << errno << std::endl;
error = "Could not set servo.";
}
}
}
return error;
}
This code gets executed twice. The first time everything is fine, the second I get errno 5. Which is EIO.
This is the logic analyser output:
You can see the first pass is fine. The second pass is also fine till the end when a stop is expected.
I would suspect the MCU if it wasn't for the fact the nano behaves correctly, and the first pass of the code works fine.
Any ideas?
This is the fd opening:
int open_fd_wronly(){
error_flag = false;
if (fd) {
close_fd();
fd = 0;
}
if ((fd = open(devicefile.c_str(), O_WRONLY)) < 0)
return errorMsg("ERROR opening: " + devicefile + "\n");
if (ioctl(fd, I2C_SLAVE, slave_address) < 0)
return errorMsg("ERROR address: " + std::to_string(slave_address) + "\n");
return 0;
}
Sorry, no sooner posted the question. Than the answer dawned on me. It really helps to share a problem. The first register call prompts a write to EEPROM the second call was just arriving too fast triggering another write to the EEPROM and causing a crash. A little delay between the two calls solved the problem.
Many thanks.

How to list ALSA MIDI clients without reading `/proc/asound/seq/clients`?

Is there a known way to list existing MIDI clients using the ALSA API only, without reading the special file /proc/asound/seq/clients?
I searched the ALSA MIDI API reference, and could not find any match. I believe there must be a way to achieve this using the API, otherwise that's a lot surprising.
As shown in the source code of aplaymidi and similar tools, ALSA sequencer clients are enumerated with snd_seq_query_next_client():
snd_seq_client_info_alloca(&cinfo);
snd_seq_client_info_set_client(cinfo, -1);
while (snd_seq_query_next_client(seq, cinfo) >= 0) {
int client = snd_seq_client_info_get_client(cinfo);
...
}
I could figure it, finally: snd_seq_get_any_client_info to get informations about the first client (there should be at least one, the system one) and snd_seq_query_next_client. to get the next one.
Here is a snippet to list MIDI clients:
static void list_clients(void) {
int count = 0;
int status;
snd_seq_client_info_t* info;
snd_seq_client_info_alloca(&info);
status = snd_seq_get_any_client_info(seq_handle, 0, info);
while (status >= 0) {
count += 1;
int id = snd_seq_client_info_get_client(info);
char const* name = snd_seq_client_info_get_name(info);
int num_ports = snd_seq_client_info_get_num_ports(info);
printf("Client “%s” #%i, with %i ports\n", name, id, num_ports);
status = snd_seq_query_next_client(seq_handle, info);
}
printf("Found %i clients\n", count);
}
The snippet assumes seq_handle is declared and initialized elsewhere (initialized with snd_seq_open).
The use of 0 as the client ID in the invocation of snd_seq_get_any_client_info, is a guess: ALSA uses negative numbers for errors, so I guess the first valid client ID is 0.

Causing a deliberate DEP error

In short what I want to do is be able to cause a Data Execution Prevention (DEP) error at will.
This is specifically on XP SP3 machines. I'd like it so that when I run a script or small program it brings up the XP DEP error box.
Would I be right in thinking the simplest way to do that is with some sort of script or program? I know DEP is used to prevent buffer overflow attacks but i'd rather not risk any
malicious code being used.
Can anybody suggest anything to get me on the right lines?
The simplest way is to allocate memory without the executable attribute and jump to the address allocated.
This can be done with the following code.
void Code(){
return;
}
void GenerateDepError(){
// Allocate data area
PVOID pMem = VirtualAlloc( NULL, 0x100,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE );
// Copy a function into data area
for( DWORD i = 0; i < 0x100; i++ ){
((char*)pMem)[i] = ((char*)Code)[i];
}
// Consider the memory area as a function.
void (*dep_trigger)() = (void (*)())pMem;
// Invoke the function. This should cause DEP error if DEP is ON.
dep_trigger();
// If it returns without error this message will be displayed.
printf("No error on dep_trigger()\n");
}
int main( int argc, char** argv ){
GenerateDepError();
return 0;
}

How to hide console window of subprocess?

I'm trying to write a very simple program to replace an existing executable. It should munge its arguments slightly and exec the original program with the new arguments. It's supposed to be invoked automatically and silently by a third-party library.
It runs fine, but it pops up a console window to show the output of the invoked program. I need that console window to not be there. I do not care about the program's output.
My original attempt was set up as a console application, so I thought I could fix this by writing a new Windows GUI app that did the same thing. But it still pops up the console. I assume that the original command is marked as a console application, and so Windows automatically gives it a console window to run in. I also tried replacing my original call to _exec() with a call to system(), just in case. No help.
Does anyone know how I can make this console window go away?
Here's my code:
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
char* lpCmdLine,
int nCmdShow)
{
char *argString, *executable;
// argString and executable are retrieved here
std::vector< std::string > newArgs;
// newArgs gets set up with the intended arguments here
char const ** newArgsP = new char const*[newArgs.size() + 1];
for (unsigned int i = 0; i < newArgs.size(); ++i)
{
newArgsP[i] = newArgs[i].c_str();
}
newArgsP[newArgs.size()] = NULL;
int rv = _execv(executable, newArgsP);
if (rv)
{
return -1;
}
}
Use the CreateProcess function instead of execve. For the dwCreationFlags paramter pass the CREATE_NO_WINDOW flag. You will also need to pass the command line as a string as well.
e.g.
STARTUPINFO startInfo = {0};
PROCESS_INFORMATION procInfo;
TCHAR cmdline[] = _T("\"path\\to\\app.exe\" \"arg1\" \"arg2\"");
startInfo.cb = sizeof(startInfo);
if(CreateProcess(_T("path\\to\\app.exe"), cmdline, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startInfo, &procInfo))
{
CloseHandle(procInfo.hProcess);
CloseHandle(procInfo.hThread);
}
Aha, I think I found the answer on MSDN, at least if I'm prepared to use .NET. (I don't think I'm really supposed to, but I'll ignore that for now.)
System::String^ command = gcnew System::String(executable);
System::Diagnostics::Process^ myProcess = gcnew Process;
myProcess->StartInfor->FileName = command;
myProcess->StartInfo->UseShellExecute = false; //1
myProcess->StartInfo->CreateNowindow = true; //2
myProcess->Start();
It's those two lines marked //1 and //2 that are important. Both need to be present.
I really don't understand what's going on here, but it seems to work.
You need to create a non-console application (i.e. a Windows GUI app). If all this app does is some processing of files or whatever, you won't need to have a WinMain, register any windows or have a message loop - just write your code as for a console app. Of course, you won't be able to use printf et al. And when you come to execute it, use the exec() family of functions, not system().