I have narrowed it down to SDL_DisplayFormat after probing. I compiled with g++ -o test.exe test.cpp -lmingw32 -lSDLmain -lSDL -lSDL2_image on a windows machine, using msys, and ran the executable; then echo $? returned 3...
int main( int argc, char **args ) {
int status = SDL_Init( SDL_INIT_EVERYTHING );
if ( status == -1 ) return 4;
screen = SDL_SetVideoMode( W_WIDTH, W_HEIGHT, BPP, SDL_SWSURFACE );
if ( screen == NULL ) return 44;
SDL_Surface *loaded_surface = IMG_Load( "./res/figure.png" );
if ( loaded_surface == NULL ) return 444;
SDL_Surface *background = SDL_DisplayFormat( loaded_surface );
return 5;
if ( background == NULL ) return 4444;
SDL_FreeSurface( loaded_surface );
SDL_BlitSurface( background, NULL, screen, NULL );
SDL_Flip( screen );
SDL_Delay( 2000 );
return 0;
}
As stated here: can i use SDL-1.2.15 with SDL2-image extension?
SDL2_Image is not compatible with SDL 1.x, You should upgrade to SDL 2.
Related
Background:
I followed the instruction from Tlmada (https://github.com/TImada/raspi4_freertos) to get FreeRTOS on RPi4. (Host: Ubuntu 18.04, Cross-Compiler: aarch64-none-elf)
Next step was to get FreeRTOS+CLI on the board. I followed this tutorial (https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_CLI/FreeRTOS_Plus_Command_Line_Interface.html), aka added the libraries (FreeRTOS_CLI.c and FreeRTOS_CLI.h) to my project and ran the makefile:
CROSS ?= aarch64-none-elf-
CFLAGS = -mcpu=cortex-a72 \
-fpic \
-ffreestanding \
-std=gnu99 \
-O2 \
-Wall \
-Wextra \
-DGUEST \
-I$(INCLUDEPATH1) \
-I$(INCLUDEPATH2) \
-I$(INCLUDEPATH3) \
-I$(INCLUDEPATH4) \
-I$(INCLUDEPATH5) \
-D__LINUX__
BUILTIN_OPS = -fno-builtin-memset
ASMFLAGS = -mcpu=cortex-a72
INCLUDEPATH1 ?= ./src
INCLUDEPATH2 ?= ../musl_libc
INCLUDEPATH3 ?= ../mmu
INCLUDEPATH4 ?= ../../../Source/include
INCLUDEPATH5 ?= ../../../Source/portable /GCC/ARM_CA72_64_BIT
# From ./src
OBJS = build/startup.o
OBJS +=build/FreeRTOS_asm_vector.o
OBJS +=build/FreeRTOS_tick_config.o
OBJS +=build/interrupt.o
OBJS +=build/FreeRTOS_CLI.o
OBJS +=build/main.o
OBJS +=build/mmu_cfg.o
OBJS +=build/uart.o
# From ../mmu
OBJS +=build/mmu.o
# From ../cache
OBJS +=build/cache.o
# From ../musl_libc
OBJS +=build/memset.o
OBJS +=build/memcpy.o
# From ../../../Source/portable /GCC/ARM_CA72_64_BIT
OBJS +=build/port.o
OBJS +=build/portASM.o
OBJS +=build/list.o
OBJS +=build/queue.o
OBJS +=build/tasks.o
OBJS +=build/timers.o
OBJS +=build/heap_1.o
uart.elf : src/raspberrypi4.ld $(OBJS)
$(CROSS)gcc --build-id=none -std=gnu99 -T src/raspberrypi4.ld -o $# -nostdlib -ffreestanding --specs=nosys.specs $(BUILTIN_OPS) $(OBJS)
$(CROSS)objdump -d uart.elf > uart.list
build/%.o : src/%.S
$(CROSS)as $(ASMFLAGS) -c -o $# $<
build/%.o : src/%.c
$(CROSS)gcc $(CFLAGS) -c -o $# $<
build/%.o : ../mmu/%.c
$(CROSS)gcc $(CFLAGS) -c -o $# $<
build/%.o : ../cache/%.S
$(CROSS)gcc $(CFLAGS) -c -o $# $<
build/%.o : ../musl_libc/%.c
$(CROSS)gcc $(CFLAGS) -c -o $# $<
build/%.o : ../../../Source/%.c
$(CROSS)gcc $(CFLAGS) -c -o $# $<
build/%.o : ../../../Source/portable/GCC/ARM_CA72_64_BIT/%.c
$(CROSS)gcc $(CFLAGS) -c -o $# $<
build/%.o : ../../../Source/portable/GCC/ARM_CA72_64_BIT/%.S
$(CROSS)as $(ASMFLAGS) -c -o $# $<
build/%.o : ../../../Source/portable/MemMang/%.c
$(CROSS)gcc $(CFLAGS) -c -o $# $<
clean :
rm -f build/*.o
rm -f *.elf
rm -f *.list
Problem:
The file FreeRTOS_CLI.c is referring to string.h, so the functions strlen, strncpy , strncmp can't be found and I get the following output for make:
make CROSS=aarch64-none-elf-
aarch64-none-elf-gcc -Wl,--build-id=none -std=gnu99 -T src/raspberrypi4.ld -o uart.elf -ffreestanding -nostdlib --specs=nosys.specs -fno-builtin-memset build/startup.o build/FreeRTOS_asm_vector.o build/FreeRTOS_tick_config.o build/interrupt.o build/FreeRTOS_CLI.o build/main.o build/mmu_cfg.o build/uart.o build/mmu.o build/cache.o build/memset.o build/memcpy.o build/port.o build/portASM.o build/list.o build/queue.o build/tasks.o build/timers.o build/heap_1.o
/usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: build/FreeRTOS_CLI.o: in function `prvHelpCommand':
FreeRTOS_CLI.c:(.text+0x34): undefined reference to `strncpy'
FreeRTOS_CLI.c:(.text+0x34): relocation truncated to fit: R_AARCH64_CALL26 against undefined symbol `strncpy'
/usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: build/FreeRTOS_CLI.o: in function `FreeRTOS_CLIProcessCommand':
FreeRTOS_CLI.c:(.text+0x15c): undefined reference to `strlen'
FreeRTOS_CLI.c:(.text+0x15c): relocation truncated to fit: R_AARCH64_CALL26 against undefined symbol `strlen'
/usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: FreeRTOS_CLI.c:(.text+0x170): undefined reference to `strncmp'
FreeRTOS_CLI.c:(.text+0x170): relocation truncated to fit: R_AARCH64_CALL26 against undefined symbol `strncmp'
/usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: FreeRTOS_CLI.c:(.text+0x1a8): undefined reference to `strncpy'
FreeRTOS_CLI.c:(.text+0x1a8): relocation truncated to fit: R_AARCH64_CALL26 against undefined symbol `strncpy'
/usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: FreeRTOS_CLI.c:(.text+0x244): undefined reference to `strncpy'
FreeRTOS_CLI.c:(.text+0x244): relocation truncated to fit: R_AARCH64_CALL26 against undefined symbol `strncpy'
collect2: error: ld returned 1 exit status
Makefile:63: recipe for target 'uart.elf' failed
make: *** [uart.elf] Error 1
The output is clear to me, because the makefile prohibits the standard library string.h with the option -nostdlib.
FreeRTOS_CLI.c:
/*
* FreeRTOS+CLI V1.0.4
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/* Standard includes. */
#include <string.h>
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Utils includes. */
#include "FreeRTOS_CLI.h"
/* If the application writer needs to place the buffer used by the CLI at a
fixed address then set configAPPLICATION_PROVIDES_cOutputBuffer to 1 in
FreeRTOSConfig.h, then declare an array with the following name and size in
one of the application files:
char cOutputBuffer[ configCOMMAND_INT_MAX_OUTPUT_SIZE ];
*/
#ifndef configAPPLICATION_PROVIDES_cOutputBuffer
#define configAPPLICATION_PROVIDES_cOutputBuffer 0
#define configCOMMAND_INT_MAX_OUTPUT_SIZE 400
#endif
typedef struct xCOMMAND_INPUT_LIST
{
const CLI_Command_Definition_t *pxCommandLineDefinition;
struct xCOMMAND_INPUT_LIST *pxNext;
} CLI_Definition_List_Item_t;
/*----------------------------------------------------------------*/
// My own Commands:
/* This function implements the behaviour of a command, so must have the correct
prototype. */
static BaseType_t prvTaskStatsCommand( int8_t *pcWriteBuffer,
size_t xWriteBufferLen,
const int8_t *pcCommandString )
{
/* For simplicity, this function assumes the output buffer is large enough
to hold all the text generated by executing the vTaskList() API function,
so the xWriteBufferLen parameter is not used. */
( void ) xWriteBufferLen;
/* pcWriteBuffer is used directly as the vTaskList() parameter, so the table
generated by executing vTaskList() is written directly into the output
buffer. */
//vTaskList( pcWriteBuffer + strlen( pcHeader ) );
*pcWriteBuffer = ( char ) 0x00;
pcWriteBuffer = "Hello world";
/* The entire table was written directly to the output buffer. Execution
of this command is complete, so return pdFALSE. */
return pdFALSE;
}
static const CLI_Command_Definition_t xTaskStatsCommand =
{
"hello",
"hello: CLI say Hello to the world",
prvTaskStatsCommand,
0
};
// Registering the xDelCommand structure with FreeRTOS+CLI
//FreeRTOS_CLIRegisterCommand( &xTaskStatsCommand );
/*----------------------------------------------------------------*/
/*
* The callback function that is executed when "help" is entered. This is the
* only default command that is always present.
*/
static BaseType_t prvHelpCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );
/*
* Return the number of parameters that follow the command name.
*/
static int8_t prvGetNumberOfParameters( const char *pcCommandString );
/* The definition of the "help" command. This command is always at the front
of the list of registered commands. */
static const CLI_Command_Definition_t xHelpCommand =
{
"help",
"\r\nhelp:\r\n Lists all the registered commands\r\n\r\n",
prvHelpCommand,
0
};
/* The definition of the list of commands. Commands that are registered are
added to this list. */
static CLI_Definition_List_Item_t xRegisteredCommands =
{
&xHelpCommand, /* The first command in the list is always the help command, defined in this file. */
&xTaskStatsCommand,
NULL /* The next pointer is initialised to NULL, as there are no other registered commands yet. */
};
/* A buffer into which command outputs can be written is declared here, rather
than in the command console implementation, to allow multiple command consoles
to share the same buffer. For example, an application may allow access to the
command interpreter by UART and by Ethernet. Sharing a buffer is done purely
to save RAM. Note, however, that the command console itself is not re-entrant,
so only one command interpreter interface can be used at any one time. For that
reason, no attempt at providing mutual exclusion to the cOutputBuffer array is
attempted.
configAPPLICATION_PROVIDES_cOutputBuffer is provided to allow the application
writer to provide their own cOutputBuffer declaration in cases where the
buffer needs to be placed at a fixed address (rather than by the linker). */
#if( configAPPLICATION_PROVIDES_cOutputBuffer == 0 )
static char cOutputBuffer[ configCOMMAND_INT_MAX_OUTPUT_SIZE ];
#else
extern char cOutputBuffer[ configCOMMAND_INT_MAX_OUTPUT_SIZE ];
#endif
/*-----------------------------------------------------------*/
BaseType_t FreeRTOS_CLIRegisterCommand( const CLI_Command_Definition_t * const pxCommandToRegister )
{
static CLI_Definition_List_Item_t *pxLastCommandInList = &xRegisteredCommands;
CLI_Definition_List_Item_t *pxNewListItem;
BaseType_t xReturn = pdFAIL;
/* Check the parameter is not NULL. */
configASSERT( pxCommandToRegister );
/* Create a new list item that will reference the command being registered. */
pxNewListItem = ( CLI_Definition_List_Item_t * ) pvPortMalloc( sizeof( CLI_Definition_List_Item_t ) );
configASSERT( pxNewListItem );
if( pxNewListItem != NULL )
{
taskENTER_CRITICAL();
{
/* Reference the command being registered from the newly created
list item. */
pxNewListItem->pxCommandLineDefinition = pxCommandToRegister;
/* The new list item will get added to the end of the list, so
pxNext has nowhere to point. */
pxNewListItem->pxNext = NULL;
/* Add the newly created list item to the end of the already existing
list. */
pxLastCommandInList->pxNext = pxNewListItem;
/* Set the end of list marker to the new list item. */
pxLastCommandInList = pxNewListItem;
}
taskEXIT_CRITICAL();
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/
BaseType_t FreeRTOS_CLIProcessCommand( const char * const pcCommandInput, char * pcWriteBuffer, size_t xWriteBufferLen )
{
static const CLI_Definition_List_Item_t *pxCommand = NULL;
BaseType_t xReturn = pdTRUE;
const char *pcRegisteredCommandString;
size_t xCommandStringLength;
/* Note: This function is not re-entrant. It must not be called from more
thank one task. */
if( pxCommand == NULL )
{
/* Search for the command string in the list of registered commands. */
for( pxCommand = &xRegisteredCommands; pxCommand != NULL; pxCommand = pxCommand->pxNext )
{
pcRegisteredCommandString = pxCommand->pxCommandLineDefinition->pcCommand;
xCommandStringLength = strlen( pcRegisteredCommandString );
/* To ensure the string lengths match exactly, so as not to pick up
a sub-string of a longer command, check the byte after the expected
end of the string is either the end of the string or a space before
a parameter. */
if( strncmp( pcCommandInput, pcRegisteredCommandString, xCommandStringLength ) == 0 )
{
if( ( pcCommandInput[ xCommandStringLength ] == ' ' ) || ( pcCommandInput[ xCommandStringLength ] == 0x00 ) )
{
/* The command has been found. Check it has the expected
number of parameters. If cExpectedNumberOfParameters is -1,
then there could be a variable number of parameters and no
check is made. */
if( pxCommand->pxCommandLineDefinition->cExpectedNumberOfParameters >= 0 )
{
if( prvGetNumberOfParameters( pcCommandInput ) != pxCommand->pxCommandLineDefinition->cExpectedNumberOfParameters )
{
xReturn = pdFALSE;
}
}
break;
}
}
}
}
if( ( pxCommand != NULL ) && ( xReturn == pdFALSE ) )
{
/* The command was found, but the number of parameters with the command
was incorrect. */
strncpy( pcWriteBuffer, "Incorrect command parameter(s). Enter \"help\" to view a list of available commands.\r\n\r\n", xWriteBufferLen );
pxCommand = NULL;
}
else if( pxCommand != NULL )
{
/* Call the callback function that is registered to this command. */
xReturn = pxCommand->pxCommandLineDefinition->pxCommandInterpreter( pcWriteBuffer, xWriteBufferLen, pcCommandInput );
/* If xReturn is pdFALSE, then no further strings will be returned
after this one, and pxCommand can be reset to NULL ready to search
for the next entered command. */
if( xReturn == pdFALSE )
{
pxCommand = NULL;
}
}
else
{
/* pxCommand was NULL, the command was not found. */
strncpy( pcWriteBuffer, "Command not recognised. Enter 'help' to view a list of available commands.\r\n\r\n", xWriteBufferLen );
xReturn = pdFALSE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
char *FreeRTOS_CLIGetOutputBuffer( void )
{
return cOutputBuffer;
}
/*-----------------------------------------------------------*/
const char *FreeRTOS_CLIGetParameter( const char *pcCommandString, UBaseType_t uxWantedParameter, BaseType_t *pxParameterStringLength )
{
UBaseType_t uxParametersFound = 0;
const char *pcReturn = NULL;
*pxParameterStringLength = 0;
while( uxParametersFound < uxWantedParameter )
{
/* Index the character pointer past the current word. If this is the start
of the command string then the first word is the command itself. */
while( ( ( *pcCommandString ) != 0x00 ) && ( ( *pcCommandString ) != ' ' ) )
{
pcCommandString++;
}
/* Find the start of the next string. */
while( ( ( *pcCommandString ) != 0x00 ) && ( ( *pcCommandString ) == ' ' ) )
{
pcCommandString++;
}
/* Was a string found? */
if( *pcCommandString != 0x00 )
{
/* Is this the start of the required parameter? */
uxParametersFound++;
if( uxParametersFound == uxWantedParameter )
{
/* How long is the parameter? */
pcReturn = pcCommandString;
while( ( ( *pcCommandString ) != 0x00 ) && ( ( *pcCommandString ) != ' ' ) )
{
( *pxParameterStringLength )++;
pcCommandString++;
}
if( *pxParameterStringLength == 0 )
{
pcReturn = NULL;
}
break;
}
}
else
{
break;
}
}
return pcReturn;
}
/*-----------------------------------------------------------*/
static BaseType_t prvHelpCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
static const CLI_Definition_List_Item_t * pxCommand = NULL;
BaseType_t xReturn;
( void ) pcCommandString;
if( pxCommand == NULL )
{
/* Reset the pxCommand pointer back to the start of the list. */
pxCommand = &xRegisteredCommands;
}
/* Return the next command help string, before moving the pointer on to
the next command in the list. */
strncpy( pcWriteBuffer, pxCommand->pxCommandLineDefinition->pcHelpString, xWriteBufferLen );
pxCommand = pxCommand->pxNext;
if( pxCommand == NULL )
{
/* There are no more commands in the list, so there will be no more
strings to return after this one and pdFALSE should be returned. */
xReturn = pdFALSE;
}
else
{
xReturn = pdTRUE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
static int8_t prvGetNumberOfParameters( const char *pcCommandString )
{
int8_t cParameters = 0;
BaseType_t xLastCharacterWasSpace = pdFALSE;
/* Count the number of space delimited words in pcCommandString. */
while( *pcCommandString != 0x00 )
{
if( ( *pcCommandString ) == ' ' )
{
if( xLastCharacterWasSpace != pdTRUE )
{
cParameters++;
xLastCharacterWasSpace = pdTRUE;
}
}
else
{
xLastCharacterWasSpace = pdFALSE;
}
pcCommandString++;
}
/* If the command string ended with spaces, then there will have been too
many parameters counted. */
if( xLastCharacterWasSpace == pdTRUE )
{
cParameters--;
}
/* The value returned is one less than the number of space delimited words,
as the first word should be the command itself. */
return cParameters;
}
What I did so far:
Deleting -nostdlib in makefile. -> This leads to no reference to __bss_start__ in linker file.
Error output:
make CROSS=aarch64-none-elf-
aarch64-none-elf-gcc -Wl,--build-id=none -std=gnu99 -T src/raspberrypi4.ld -o uart.elf -ffreestanding --specs=nosys.specs -fno-builtin-memset build/startup.o build/FreeRTOS_asm_vector.o build/FreeRTOS_tick_config.o build/interrupt.o build/FreeRTOS_CLI.o build/main.o build/mmu_cfg.o build/uart.o build/mmu.o build/cache.o build/memset.o build/memcpy.o build/port.o build/portASM.o build/list.o build/queue.o build/tasks.o build/timers.o build/heap_1.o /usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: /usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/lib/crt0.o: in function '_cpu_init_hook': /tmp/dgboter/bbs/rhev-vm1--rhe6x86_64/buildbot/rhe6x86_64--aarch64-none-elf/build/src/newlib-cygwin/libgloss/aarch64/crt0.S:269: undefined reference to '__bss_start__' /usr/share/gcc-arm-9.2-2019.12-x86_64-aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/9.2.1/../../../../aarch64-none-elf/bin/ld: /tmp/dgboter/bbs/rhev-vm1--rhe6x86_64/buildbot/rhe6x86_64--aarch64-none-elf/build/src/newlib-cygwin/libgloss/aarch64/crt0.S:269: undefined reference to '__bss_end__' collect2: error: ld returned 1 exit status Makefile:63: recipe for target 'uart.elf' failed make: *** [uart.elf] Error 1
Here is the link file (raspberrypi4.ld):
ENTRY(_boot)
CODE_BASE = 0x20000000;
DATA_BASE = 0x20200000;
STACK_TOP = 0x20600000;
PT_BASE = 0x20600000;
SECTIONS
{
/* Starts at 0x20000000 (assuming ends at 0x208FFFFF, 9MB). */
. = CODE_BASE;
__start = .;
__text_start = .;
.text :
{
KEEP(*(.vectors))
KEEP(*(.text.boot))
*(.text)
}
__text_end = .;
. = ALIGN(4096); /* align to page size */
__data_start = DATA_BASE;
.data :
{
*(.data)
}
. = ALIGN(4096); /* align to page size */
__data_end = .;
__bss_start = .;
.bss :
{
bss = .;
*(.bss)
}
. = ALIGN(4096); /* align to page size */
__bss_end = .;
__end = .;
. = STACK_TOP; /* stack memory */
stack_top = .;
. = PT_BASE; /* Page tables */
.pt :
{
*(.pt)
}
}
__bss_size = (__bss_end -
__bss_start)>>3;
I want to put string.h in a project subfolder with the original content, so that I don't need the standard libraries. But I can't find a correct string.h file on the internet (without errors in the string.h itself).
Does anybody have a solution or can point me in the direction?
Thank you in advance.
I am trying to create a function which runs one command and then pipes the output to a second command and runs that. I'm running the function in an infinite loop. The problem is, the function works the first time, but doesn't show anything after that.
For example, when I run ls | wc -l, the first time it shows the correct results, but when I run it after that I get no output.
Here is my function (parsing is handled in another function):
void system_pipe(std::string command1, std::string command2)
{
int status;
int fd[2];
int fd2[2];
pipe(fd);
int pid = fork();
// Child process.
if (pid == 0)
{
std::shared_ptr<char> temp = string_to_char(command1);
char *name[] = {"/bin/bash", "-c", temp.get(), NULL};
close(fd[0]);
dup2(fd[1], 1);
execvp(name[0], name);
exit(EXIT_FAILURE);
}
// Parent process.
else
{
std::shared_ptr<char> temp = string_to_char(command2);
char *name[] = {"/bin/bash", "-c", temp.get(), NULL};
close(fd[1]);
dup2(fd[0], 0);
waitpid(pid, &status, 0);
//my_system(command2);
// Fork and exec a new process here.
int pid2 = fork();
if (pid2 == 0)
{
execvp(name[0], name);
exit(EXIT_FAILURE);
}
else
{
waitpid(pid2, NULL, 0);
}
}
if (status)
std::cout << "Bad" << std::endl;
}
I call the function like this:
while(true)
{
string line;
getline(cin, line);
pair<string, string> commands = parse(line);
system_pipe(commands.first, commands.second);
}
Why is the function only working correctly on the first loop? What is changing after that?
else
{
std::shared_ptr<char> temp = string_to_char(command2);
char *name[] = {"/bin/bash", "-c", temp.get(), NULL};
close(fd[1]);
dup2(fd[0], 0);
waitpid(pid, &status, 0);
//my_system(command2);
That was not your intention, I believe. dup2 had to be called in child.
int pid2 = fork();
if (pid2 == 0)
{
dup2(fd[0], 0); // here.
execvp(name[0], name);
exit(EXIT_FAILURE);
}
The second problem is that you leave your pipe files open.
This is not a good coding sample, but it's only to illustrate how it should work.
// ( g++ -std=c++11 )
// type `ls | grep file.cxx`
#include <iostream>
#include <string>
#include <cstring>
#include <array>
#include <memory>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void replace_with ( std::string command )
{
char exec_name [] = "bash" , arg [] = "-c" ;
char * line [] = { exec_name , arg , &command[ 0 ] , nullptr } ;
execvp( exec_name , line ) ;
}
void pipeline ( const std::string& command0 , const std::string& command1 )
{
std::array< int , 2 > pipe_fd ; enum { READ_END , WRITE_END } ;
if ( pipe( pipe_fd.data() ) ) throw std::runtime_error( "can't create a pipe" ) ;
int id = fork() ;
if ( id < 0 ) { for ( auto each : pipe_fd ) close( each ) ;
throw std::runtime_error( "can't create a child" ) ; }
if ( ! id ) /* child */
{
close( pipe_fd[ READ_END ] ) ;
dup2( pipe_fd[ WRITE_END ] , STDOUT_FILENO ) ;
close( pipe_fd[ WRITE_END ] ) ; //
replace_with( command0 ) ;
}
else /* parent */
{
close( pipe_fd[ WRITE_END ] ) ;
waitpid( id , nullptr , 0 ) ;
int id_second = fork () ;
if ( id_second > 0 ) waitpid( id_second , nullptr , 0 ) ;
else if ( ! id_second ) /* child */
{
dup2( pipe_fd[ READ_END ] , STDIN_FILENO ) ;
close( pipe_fd[ READ_END ] ) ; //
replace_with( command1 ) ;
}
close( pipe_fd[ READ_END ] ) ;
}
}
int main () try
{
while ( true )
{
std::string command0 , command1 ;
getline( std::cin , command0 , '|' ) ;
getline( std::cin , command1 ) ;
pipeline( command0 , command1 ) ;
}
} catch ( const std::runtime_error& e )
{ std::cerr << e.what() ; return - 1 ; }
I am using pipes to get redirected stdout output from a command line executable. Unfortunately I don't get any output until the process has completed. The executable outputs progress status as it runs and this is what I would like to parse.
BOOL RunCmd( char *pCmd,
char *pWorkingDir,
int nWaitSecs,
BOOL fRegImport,
DWORD *pdwExitCode )
{
BOOL fSuccess = TRUE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sFileSecurity;
ZeroMemory( &sFileSecurity, sizeof( sFileSecurity ) );
sFileSecurity.nLength = sizeof( sFileSecurity );
sFileSecurity.bInheritHandle = TRUE;
HANDLE hReadPipe = NULL;
HANDLE hWritePipe = NULL;
fSuccess = CreatePipe( &hReadPipe, &hWritePipe, &sFileSecurity, 0 );
SetHandleInformation( hReadPipe, HANDLE_FLAG_INHERIT, 0 );
ZeroMemory( &si, sizeof(si) );
ZeroMemory( &pi, sizeof(pi) );
si.cb = sizeof( si );
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
si.wShowWindow = SW_HIDE;
int rc;
// Start the child process.
rc = CreateProcess( NULL, // No module name (use command line).
pCmd, // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
TRUE,
CREATE_NO_WINDOW,
NULL, // Use parent's environment block.
pWorkingDir, // Working folder
&si, // Pointer to STARTUPINFO structure.
&pi ); // Pointer to PROCESS_INFORMATION structure.
if( ! rc )
return FALSE;
// Wait until child process exits.
DWORD dwWaitResult;
DWORD dwTimeStart = ::GetTickCount();
DWORD dwTimeNow;
#define BUFSIZE 4096
DWORD dwRead = 0;
DWORD dwAvail;
CHAR chBuf[ BUFSIZE ];
BOOL bSuccess = TRUE;
for( ;; )
{
dwTimeNow = ::GetTickCount();
dwWaitResult = ::WaitForSingleObject( pi.hProcess, ONE_SECOND );
dwRead = 0;
for( dwAvail = 0; PeekNamedPipe( hReadPipe, 0, 0, 0, &dwAvail, 0 ) && dwAvail; dwAvail = 0 )
{
dwRead = 0;
ReadFile( hReadPipe, chBuf, min( BUFSIZE, dwAvail ), &dwRead, NULL );
if( dwRead > 0 )
{
FILE *op = fopen( "c:\\REDIR.OUT", "a" );
if( op )
{
fwrite( chBuf, 1, dwRead, op );
fclose( op );
}
}
}
if( dwWaitResult == WAIT_OBJECT_0 )
{
DWORD dwExitCode;
GetExitCodeProcess( pi.hProcess, &dwExitCode );
if( pdwExitCode )
(*pdwExitCode) = dwExitCode;
break;
}
if( dwWaitResult == WAIT_TIMEOUT )
{
if( dwTimeNow - dwTimeStart < (DWORD)( ONE_SECOND * nWaitSecs ) )
continue;
else
{
fSuccess = FALSE;
break;
}
}
fSuccess = FALSE;
break;
}
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
CloseHandle( hReadPipe );
CloseHandle( hWritePipe );
return fSuccess;
}
The PeekNamedPipe() call is called every second and dwAvail is zero every time until the process completes.
How do I get output from the process sooner? When running the process from the console, I see progress output as it goes. The process will be using "\r" in it's output to display a percentage at the start of the same line.
Note: My answer only deals with executables compiled using MSVC.
The buffering policy is coded inside Microsoft C Runtime (CRT) Library. You can learn the details here. This article suggests using console handles and manipulate console buffers to receive unbuffered output.
However, there's an undocumented feature inside Microsoft C Runtime to inherit file handles with some internal flags directly from its parent process using lpReserved2 and cbReserved2 fields of STARTUPINFO structure. You can find the details in the crt source code provided by Microsoft Visual Studio. Or search for something like posfhnd on GitHub.
We can exploit this undocumented feature to provide a pipe handle and specify FOPEN | FDEV flags to the child process, to fool the child process treat that pipe handle the same way as a FILE_TYPE_CHAR handle.
I have a working Python3 script to demonstrate this method.
A simplified C/C++ version of the answer by #youfu.
STARTUPINFO si;
int nh = 2;
si.cbReserved2 = (WORD)(sizeof(int) + (nh *
(sizeof(char) + sizeof(HANDLE))));
si.lpReserved2 = (LPBYTE) calloc(si.cbReserved2, 1);
*((UNALIGNED int *)(si.lpReserved2)) = nh;
unsigned char* posfile = (unsigned char *)(si.lpReserved2 + sizeof(int));
UNALIGNED HANDLE* posfhnd = (UNALIGNED HANDLE *)(si.lpReserved2 + sizeof(int) +
(nh * sizeof(unsigned char)));
unsigned char FOPEN = 0x01;
unsigned char FDEV = 0x40;
*posfile = FOPEN | FDEV;
posfile++;
*posfile = FOPEN | FDEV;
*posfhnd = child_stdin_rd;
posfhnd++;
*posfhnd = child_stdout_wr;
-Suraj
My program has big leaks. I am using the debug heap by putting this in my stdafx.h:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
Then I'm capturing all the leaks in a text file by putting this code just before exit:
HANDLE hLogFile;
hLogFile = CreateFile( "T:\\MyProject\\heap.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtDumpMemoryLeaks();
exit( EXIT_SUCCESS );
However even then the data is leak by leak, which is far too low-level information.
Stepping into _CrtDumpMemoryLeaks(), the code is actually easy to follow. I wrote my own function that summarizes the data, reporting bytes leaked for each line of code and sorting by leak size.
However it requires a static variable inside dbgheap.c in order to work. I've tried to make a version of dbgheap.c that doesn't have these as static symbols and tried to make a mini-DLL out of it (but it complains about a missing symbol I can't find anywhere in the MSFT code, _heap_regions). Instead what I've settled on is putting this code right before the code above calling _CrtDumpMemoryLeaks():
// Put a breakpoint here; step INTO the malloc, then in variable watch
// window evaluate: _CrtDumpMemoryLeakSummary( _pFirstBlock );
void* pvAccess = malloc(1);
And in turn this is the code for the _CrtDumpMemoryLeakSummary function:
#define _CRTBLD
#include "C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src\dbgint.h"
typedef struct {
const char* pszFileName;
int iLine;
int iTotal;
} Location_T;
#define MAX_SUMMARY 5000
static Location_T aloc[ MAX_SUMMARY ];
static int CompareFn( const void* pv1, const void* pv2 ) {
Location_T* ploc1 = (Location_T*) pv1;
Location_T* ploc2 = (Location_T*) pv2;
if ( ploc1->iTotal > ploc2->iTotal )
return -1;
if ( ploc1->iTotal < ploc2->iTotal )
return 1;
return 0;
}
void _CrtDumpMemoryLeakSummary( _CrtMemBlockHeader* pHead )
{
int iLocUsed = 0, iUnbucketed = 0, i;
for ( /*pHead = _pFirstBlock */;
pHead != NULL && /* pHead != _pLastBlock && */ iLocUsed < MAX_SUMMARY;
pHead = pHead->pBlockHeaderNext ) {
const char* pszFileName = pHead->szFileName ? pHead->szFileName : "<UNKNOWN>";
// Linear search is theoretically horribly slow but saves trouble of
// avoiding heap use while measuring heap use.
int i;
for ( i = 0; i < iLocUsed; i++ ) {
// To speed search, compare line number (fast) before strcmp() (slow).
// If szFileName were guaranteed to be __LINE__ then we could take advantage
// of __LINE__ always having the same address for any given file, and just
// compare pointers rather than using strcmp(). However, szFileName could
// be something else.
if ( pHead->nLine == aloc[i].iLine &&
strcmp( pszFileName, aloc[i].pszFileName ) == 0 ) {
aloc[i].iTotal += pHead->nDataSize;
break;
}
}
if ( i == iLocUsed ) {
aloc[i].pszFileName = pszFileName;
aloc[i].iLine = pHead->nLine;
aloc[i].iTotal = pHead->nDataSize;
iLocUsed++;
}
}
if ( iLocUsed == MAX_SUMMARY )
_RPT0( _CRT_WARN, "\n\n\nARNING: RAN OUT OF BUCKETS! DATA INCOMPLETE!!!\n\n\n" );
qsort( aloc, iLocUsed, sizeof( Location_T ), CompareFn );
_RPT0(_CRT_WARN, "SUMMARY OF LEAKS\n" );
_RPT0(_CRT_WARN, "\n" );
_RPT0(_CRT_WARN, "bytes leaked code location\n" );
_RPT0(_CRT_WARN, "------------ -------------\n" );
for ( i = 0; i < iLocUsed; i++ )
_RPT3(_CRT_WARN, "%12d %s:%d\n", aloc[i].iTotal, aloc[i].pszFileName, aloc[i].iLine );
}
It produces output like this:
SUMMARY OF LEAKS
bytes leaked code location
------------ -------------
912997 <UNKNOWN>:0
377800 ..\MyProject\foo.h:205
358400 ..\MyProject\A.cpp:959
333672 ..\MyProject\B.cpp:359
8192 f:\dd\vctools\crt_bld\self_x86\crt\src\_getbuf.c:58
6144 ..\MyProject\Interpreter.cpp:196
4608 ..\MyProject\Interpreter.cpp:254
3634 f:\dd\vctools\crt_bld\self_x86\crt\src\stdenvp.c:126
2960 ..\MyProject\C.cpp:947
2089 ..\MyProject\D.cpp:1031
2048 f:\dd\vctools\crt_bld\self_x86\crt\src\ioinit.c:136
2048 f:\dd\vctools\crt_bld\self_x86\crt\src\_file.c:133
I want to convert device path to a file path.
I want to get process name by process id, so I am using this code
PsLookupProcessByProcessId(processId,&pEProcess);
ObOpenObjectByPointer(pEProcess,
OBJ_KERNEL_HANDLE,
NULL,
0,
NULL,
KernelMode,
&hProcess);
ObDereferenceObject (pEProcess);
nts = ZwQueryInformationProcess (hProcess,27,0,0,&ulSize);
But it gives path as \Device\hardDiskVolume1\windows\system32\taskmgr.exe
But I want this as a plain filename C:\windows\system32\taskmgr.exe
There's an article in Dr. Dobb's (NT Handle-to-Path Conversion by Jim Conyngham) that describes a way of getting from a handle to DOS path name: See the listing of GetFileNameFromHandleNT().
In your case, since you already have the device path, you don't need the initial parts of that code that does the handle-to-memory-map-to-get-device-path work.
// From device file name to DOS filename
BOOL GetFsFileName( LPCTSTR lpDeviceFileName, CString& fsFileName )
{
BOOL rc = FALSE;
TCHAR lpDeviceName[0x1000];
TCHAR lpDrive[3] = _T("A:");
// Iterating through the drive letters
for ( TCHAR actDrive = _T('A'); actDrive <= _T('Z'); actDrive++ )
{
lpDrive[0] = actDrive;
// Query the device for the drive letter
if ( QueryDosDevice( lpDrive, lpDeviceName, 0x1000 ) != 0 )
{
// Network drive?
if ( _tcsnicmp( _T("\\Device\\LanmanRedirector\\"), lpDeviceName, 25 ) == 0 )
{
//Mapped network drive
char cDriveLetter;
DWORD dwParam;
TCHAR lpSharedName[0x1000];
if ( _stscanf( lpDeviceName,
_T("\\Device\\LanmanRedirector\\;%c:%d\\%s"),
&cDriveLetter,
&dwParam,
lpSharedName ) != 3 )
continue;
_tcscpy( lpDeviceName, _T("\\Device\\LanmanRedirector\\") );
_tcscat( lpDeviceName, lpSharedName );
}
// Is this the drive letter we are looking for?
if ( _tcsnicmp( lpDeviceName, lpDeviceFileName, _tcslen( lpDeviceName ) ) == 0 )
{
fsFileName = lpDrive;
fsFileName += (LPCTSTR)( lpDeviceFileName + _tcslen( lpDeviceName ) );
rc = TRUE;
break;
}
}
}
return rc;
}