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.
Related
Good evening!
During the use of a project called kodo, developed by steinwurf for random linear network coding in my simulation implemented in Omnet++ (5.1pre2), my linker told me about a multiple definition of several functions. The output of make is quoted below:
Creating executable: out/gcc-debug//simulation
./libs/boost/libboost_thread.a(once_atomic.cpp.1.o): In Funktion
`boost::thread_detail::enter_once_region(boost::once_flag&)':
once_atomic.cpp:(.text+0x0): Mehrfachdefinition von
boost::thread_detail::enter_once_region(boost::once_flag&)'
./libs/boost/libboost_thread.a(once.cpp.1.o):once.cpp:(.text+0x0): first
efined here
./libs/boost/libboost_thread.a(once_atomic.cpp.1.o): In Funktion
`boost::thread_detail::commit_once_region(boost::once_flag&)':
once_atomic.cpp:(.text+0x150): Mehrfachdefinition von
boost::thread_detail::commit_once_region(boost::once_flag&)'
./libs/boost/libboost_thread.a(once.cpp.1.o):once.cpp:(.text+0x150): first defined here
./libs/boost/libboost_thread.a(once_atomic.cpp.1.o): In Funktion
boost::thread_detail::rollback_once_region(boost::once_flag&)':
once_atomic.cpp:(.text+0x1e0): Mehrfachdefinition von
boost::thread_detail::rollback_once_region(boost::once_flag&)'
./libs/boost/libboost_thread.a(once.cpp.1.o):once.cpp:(.text+0x1e0): first defined here
/usr/bin/ld: ./libs/gtest/libgtest.a(gtest-all.cc.1.o): undefined
reference to symbol 'pthread_key_delete##GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO aus der Kommandozeile fehlt
collect2: error: ld returned 1 exit status
Makefile:111: die Regel für Ziel „out/gcc-debug//simulation“ scheiterte
make: *** [out/gcc-debug//simulation] Fehler 1
As you can see, there are several other multiple definitions and one unrecognized library (libgtest.a).
The kodo-rlnc downloaded from 1 and compiled, following the instructions of the Steinwurf-Documentation, downloaded itself the dependencies, also listed in 3.
Now for me it looks like there's a failure in the boost-library itself, producing this multiple definition error. But since I'm not an expert C++ programmer, I may oversee some details.
I will post my code below, but keep attention at the include-section and the Quelle::send_rlnc() function, which uses the kodo-rlnc. You will notice, that it isn't used by the initially called Quelle::initialize() function. The Problem with the linking occured before using it's functionality. (This is pretty standard).
So here's my written code with the included kodo:
#include<omnetpp.h>
#include<string.h>
#include<stdlib.h>
#include<vector>
#include<random>
#include<functional>
#include<map>
#include<iterator>
#include<algorithm>
#include<fstream>
#include <cstdint>
#include <iostream>
#include "payload_packet_m.h"
#include<kodo_core/object/file_encoder.hpp>
#include <kodo_rlnc/full_vector_codes.hpp>
#include<kodocpp/kodocpp.hpp>
#include<kodoc/kodoc.h>
using namespace omnetpp;
class Quelle : public cSimpleModule{
private:
//uint32_t max_symbols;
//uint32_t max_symbol_size;
int is_rlnc;
std::vector<uint8_t> readFile(const char* filename);
void send_rlnc();
void send_lnc();
protected:
virtual int calculate_vector_checksum(std::vector<unsigned int> input);
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
};
Define_Module(Quelle);
std::vector<uint8_t> Quelle::readFile(const char* filename){
std::ifstream file("testfile.txt", std::ios::binary);
file.unsetf(std::ios::skipws);
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> vec;
vec.reserve(fileSize);
vec.insert(vec.begin(),
std::istream_iterator<uint8_t>(file),
std::istream_iterator<uint8_t>());
return vec;
}
int Quelle::calculate_vector_checksum(std::vector<unsigned int> input){
int checksum = 0;
std::vector<unsigned int>::iterator It;
for(It = input.begin(); It != input.end(); It++){
checksum += *It;
}
return checksum;
}
void Quelle::send_rlnc(){
uint32_t max_symbols = 16; //par("max_symbols");
uint32_t max_symbol_size = 1400; //par("max_symbol_size");
fifi::api::field field = fifi::api::field::binary8;
using rlnc_encoder = kodo_rlnc::full_vector_encoder;
using rlnc_decoder = kodo_rlnc::full_vector_decoder;
rlnc_encoder::factory encoder_factory(field, max_symbols, max_symbol_size);
auto encoder = encoder_factory.build();
rlnc_decoder::factory decoder_factory(field, max_symbols, max_symbol_size);
auto decoder = decoder_factory.build();
std::vector<uint8_t> payload(encoder->payload_size());
std::vector<uint8_t> block_in(encoder->block_size());
std::generate(block_in.begin(), block_in.end(), rand);
encoder->set_const_symbols(storage::storage(block_in));
std::vector<uint8_t> block_out(decoder->block_size());
decoder->set_mutable_symbols(storage::storage(block_out));
uint32_t encoded_count = 0;
while(!decoder->is_complete()){
uint32_t bytes_used = encoder->write_payload(payload.data());
++encoded_count;
EV << "Bytes used: " << bytes_used << " Encoded count: " << encoded_count << "\n";
payload_packet *Datenpaket= new payload_packet("Datenpaket");
Datenpaket->setBytesArraySize(payload.size());
Datenpaket->setData_inArraySize(block_in.size());
uint8_t checksum = 0;
for(unsigned int i=0; i < payload.size();i++){
Datenpaket->setBytes(i,payload.at(i));
checksum += payload.at(i);
}
for(unsigned int i=0; i < block_in.size();i++){
Datenpaket->setData_in(i,block_in.at(i));
}
EV << "Packet " << encoded_count <<" payload checksum: " << (unsigned int) checksum;
int n = gateSize("out");
for(int i=0;i<n;i++){
payload_packet *temp = Datenpaket->dup();
send(temp,"out",i);
}
delete Datenpaket;
decoder->read_payload(payload.data());
}
}
void Quelle::send_lnc(){
uint32_t max_symbols = 16; //par("max_symbols");
uint32_t max_symbol_size = 1400; //par("max_symbol_size");
// std::vector<uint8_t> testvector = readFile("testfile.txt");
// EV << "File vector size: " << testvector.size() << "\n";
kodocpp::encoder_factory encoder_factory(
kodocpp::codec::full_vector,
kodocpp::field::binary8,
max_symbols,
max_symbol_size);
kodocpp::encoder encoder = encoder_factory.build();
kodocpp::decoder_factory decoder_factory(
kodocpp::codec::full_vector,
kodocpp::field::binary8,
max_symbols,
max_symbol_size);
kodocpp::decoder decoder = decoder_factory.build();
std::vector<uint8_t> data_out(decoder.block_size());
decoder.set_mutable_symbols(data_out.data(), decoder.block_size());
std::vector<uint8_t> payload(encoder.payload_size());
std::vector<uint8_t> data_in(encoder.block_size());
//std::vector<unsigned int> random_data(32);
std::generate(data_in.begin(), data_in.end(), rand);
// for(unsigned int l=0; l < data_in.size(); l++){
// data_in.push_back( (uint8_t) "a");
// }
encoder.set_const_symbols(data_in.data(),encoder.block_size());
//EV <<"Vector checksum: " << calculate_vector_checksum(data_in) << "\n";
uint32_t encoded_count = 0;
while(!decoder.is_complete()){
uint32_t bytes_used = encoder.write_payload(payload.data());
++encoded_count;
EV << "Bytes used: " << bytes_used << "\n";
payload_packet *Datenpaket= new payload_packet("Datenpaket");
Datenpaket->setBytesArraySize(payload.size());
Datenpaket->setData_inArraySize(data_in.size());
uint8_t checksum = 0;
for(unsigned int i=0; i < payload.size();i++){
Datenpaket->setBytes(i,payload.at(i));
checksum += payload.at(i);
}
for(unsigned int i=0; i < data_in.size();i++){
Datenpaket->setData_in(i,data_in.at(i));
}
EV << "Packet " << encoded_count <<" payload checksum: " << (unsigned int) checksum;
int n = gateSize("out");
for(int i=0;i<n;i++){
payload_packet *temp = Datenpaket->dup();
send(temp,"out",i);
}
delete Datenpaket;
decoder.read_payload(payload.data());
}
EV << "Ecoded " << encoded_count << " packets!" << "\n";
}
void Quelle::initialize(){
//cMessage *msg = new cMessage("Testmessage");
uint32_t max_symbols = 16; //par("max_symbols");
uint32_t max_symbol_size = 1400; //par("max_symbol_size");
is_rlnc = par("is_rlnc");
EV << "RLNC: " << is_rlnc << "\n";
// std::vector<uint8_t> testvector = readFile("testfile.txt");
// EV << "File vector size: " << testvector.size() << "\n";
kodocpp::encoder_factory encoder_factory(
kodocpp::codec::full_vector,
kodocpp::field::binary8,
max_symbols,
max_symbol_size);
kodocpp::encoder encoder = encoder_factory.build();
kodocpp::decoder_factory decoder_factory(
kodocpp::codec::full_vector,
kodocpp::field::binary8,
max_symbols,
max_symbol_size);
kodocpp::decoder decoder = decoder_factory.build();
std::vector<uint8_t> data_out(decoder.block_size());
decoder.set_mutable_symbols(data_out.data(), decoder.block_size());
std::vector<uint8_t> payload(encoder.payload_size());
std::vector<uint8_t> data_in(encoder.block_size());
//std::vector<unsigned int> random_data(32);
std::generate(data_in.begin(), data_in.end(), rand);
// for(unsigned int l=0; l < data_in.size(); l++){
// data_in.push_back( (uint8_t) "a");
// }
encoder.set_const_symbols(data_in.data(),encoder.block_size());
//EV <<"Vector checksum: " << calculate_vector_checksum(data_in) << "\n";
uint32_t encoded_count = 0;
while(!decoder.is_complete()){
uint32_t bytes_used = encoder.write_payload(payload.data());
++encoded_count;
EV << "Bytes used: " << bytes_used << "\n";
payload_packet *Datenpaket= new payload_packet("Datenpaket");
Datenpaket->setBytesArraySize(payload.size());
Datenpaket->setData_inArraySize(data_in.size());
uint8_t checksum = 0;
for(unsigned int i=0; i < payload.size();i++){
Datenpaket->setBytes(i,payload.at(i));
checksum += payload.at(i);
}
for(unsigned int i=0; i < data_in.size();i++){
Datenpaket->setData_in(i,data_in.at(i));
}
EV << "Packet " << encoded_count <<" payload checksum: " << (unsigned int) checksum;
int n = gateSize("out");
for(int i=0;i<n;i++){
payload_packet *temp = Datenpaket->dup();
send(temp,"out",i);
}
delete Datenpaket;
decoder.read_payload(payload.data());
}
EV << "Ecoded " << encoded_count << " packets!" << "\n";
// std::vector<unsigned int> converted_values;
//
// for(unsigned int i=0; i < data_in.size(); i++){
// unsigned int temp = 0;
//
// EV << "data_in Stelle " << i << ": " << (unsigned int) data_in[i] <<"\n";
//
// temp = (unsigned int) data_in[i];//(data_in[i] << 8) | data_in[1];
//
// EV << "Temp Stelle " << i << ": " << temp << "\n";
// converted_values.push_back(temp);
// }
//
// EV <<"Vector checksum: " << calculate_vector_checksum(converted_values) << "\n";
//
// payload_packet *testpacket = new payload_packet("Testpaket");
// testpacket->setBytesArraySize(data_in.size());
//
// for(unsigned int i=0; i< data_in.size();i++){
// testpacket->setBytes(i,data_in[i]);
// }
//
// testpacket->setDaten(converted_values);
//
// EV << "Generated a message";
// int n = gateSize("out");
// for(int i=0;i<n;i++){
// payload_packet *temp = testpacket->dup();
// send(temp,"out",i);
// }
//delete testpacket;
}
void Quelle::handleMessage(cMessage *msg){
//EV << "Received a message! Something is gone wrong!";
}
I'm sure that you recognized the creepy handling of the std::vector<uint8_t> payload while putting it into the payload_paket *Datenpaket. For some reason the Omnet++-packet-definition can't handle a pre-defined std::vector<uin8t_t>, so I had to declare an array for this and copy the content of my payload to the bytes array. But this doesn't matter for my question.
Does somebody have an idea what is wrong with my code or can give me a hint that it may be not my fault?
I appreciate any help with this!
Thanks in advance!
EDIT #1:
I use a Makefile for the compiling process with linked static and shared libraries. The order structure can be described as: sim_folder/libs/ many_libs_in_subdirectories and sim_folder/include/ many includes in subdirectories.
My Makefile looks like this:
#
# OMNeT++/OMNEST Makefile for simulation
#
# This file was generated with the command:
# opp_makemake -f -I./include -l libkodoc.so
#
# Name of target to be created (-o option)
TARGET = simulation$(EXE_SUFFIX)
# User interface (uncomment one) (-u option)
USERIF_LIBS = $(ALL_ENV_LIBS) # that is, $(TKENV_LIBS) $(QTENV_LIBS) $(CMDENV_LIBS)
#USERIF_LIBS = $(CMDENV_LIBS)
#USERIF_LIBS = $(TKENV_LIBS)
#USERIF_LIBS = $(QTENV_LIBS)
# C++ include paths (with -I)
INCLUDE_PATH = -I./include -I../Omnetpp/omnetpp-5.1pre2/include/omnetpp -I./include/kodo-rlnc #-I./include/platform -I./include/sak -I./include/kodo_core -I./include/fifi -I./include/storage -I./include/boost -I./include/endian -I./include/hex
# Additional object and library files to link with
EXTRA_OBJS =
# Additional libraries (-L, -l options)
#LIBS = libkodoc.so
LIBS = libkodoc.so \
./libs/fifi/libfifi.a \
./libs/cpuid/src/cpuid/libcpuid.a \
./libs/gtest/libgtest.a \
./libs/sak/libsak.a \
./libs/boost/libboost_chrono.a \
./libs/boost/libboost_filesystem.a \
./libs/boost/libboost_iostreams.a \
./libs/boost/libboost_program_options.a \
./libs/boost/libboost_system.a \
./libs/boost/libboost_timer.a \
./libs/boost/libboost_thread.a \
./libs/gauge/src/gauge/libgauge.a \
./libs/tables/src/tables/libtables.a
#-L./libs/allocate -L./libs/cpuid -L./libs/fifi/ -L./libs/gtest -L./libs/kodo-core -L./libs/sak -L./libs/stub -L./libs/boost -L./libs/endian -L./libs/gauge -L./libs/hex -L./libs/platform -L./libs/storage -L./libs/tables
# Output directory
PROJECT_OUTPUT_DIR = out
PROJECTRELATIVE_PATH =
O = $(PROJECT_OUTPUT_DIR)/$(CONFIGNAME)/$(PROJECTRELATIVE_PATH)
# Object files for local .cc, .msg and .sm files
OBJS = \
$O/eve.o \
$O/Quelle.o \
$O/Router.o \
$O/Senke.o \
$O/txc1.o \
$O/nc_packet_m.o \
$O/payload_packet_m.o
# Message files
MSGFILES = \
nc_packet.msg \
payload_packet.msg
# SM files
SMFILES =
#------------------------------------------------------------------------------
# Pull in OMNeT++ configuration (Makefile.inc)
ifneq ("$(OMNETPP_CONFIGFILE)","")
CONFIGFILE = $(OMNETPP_CONFIGFILE)
else
ifneq ("$(OMNETPP_ROOT)","")
CONFIGFILE = $(OMNETPP_ROOT)/Makefile.inc
else
CONFIGFILE = $(shell opp_configfilepath)
endif
endif
ifeq ("$(wildcard $(CONFIGFILE))","")
$(error Config file '$(CONFIGFILE)' does not exist -- add the OMNeT++ bin directory to the path so that opp_configfilepath can be found, or set the OMNETPP_CONFIGFILE variable to point to Makefile.inc)
endif
include $(CONFIGFILE)
# Simulation kernel and user interface libraries
OMNETPP_LIBS = $(OPPMAIN_LIB) $(USERIF_LIBS) $(KERNEL_LIBS) $(SYS_LIBS)
COPTS = $(CFLAGS) $(IMPORT_DEFINES) $(INCLUDE_PATH) -I$(OMNETPP_INCL_DIR)
MSGCOPTS = $(INCLUDE_PATH)
SMCOPTS =
# we want to recompile everything if COPTS changes,
# so we store COPTS into $COPTS_FILE and have object
# files depend on it (except when "make depend" was called)
COPTS_FILE = $O/.last-copts
ifneq ("$(COPTS)","$(shell cat $(COPTS_FILE) 2>/dev/null || echo '')")
$(shell $(MKPATH) "$O" && echo "$(COPTS)" >$(COPTS_FILE))
endif
#------------------------------------------------------------------------------
# User-supplied makefile fragment(s)
# >>>
# <<<
#------------------------------------------------------------------------------
# Main target
all: $O/$(TARGET)
$(Q)$(LN) $O/$(TARGET) .
$O/$(TARGET): $(OBJS) $(wildcard $(EXTRA_OBJS)) Makefile $(CONFIGFILE)
#$(MKPATH) $O
#echo Creating executable: $#
$(Q)$(CXX) $(LDFLAGS) -o $O/$(TARGET) $(OBJS) $(EXTRA_OBJS) $(AS_NEEDED_OFF) $(WHOLE_ARCHIVE_ON) $(LIBS) $(WHOLE_ARCHIVE_OFF) $(OMNETPP_LIBS)
.PHONY: all clean cleanall depend msgheaders smheaders
.SUFFIXES: .cc
$O/%.o: %.cc $(COPTS_FILE) | msgheaders smheaders
#$(MKPATH) $(dir $#)
$(qecho) "$<"
$(Q)$(CXX) -c $(CXXFLAGS) $(COPTS) -o $# $<
%_m.cc %_m.h: %.msg
$(qecho) MSGC: $<
$(Q)$(MSGC) -s _m.cc $(MSGCOPTS) $?
%_sm.cc %_sm.h: %.sm
$(qecho) SMC: $<
$(Q)$(SMC) -c++ -suffix cc $(SMCOPTS) $?
msgheaders: $(MSGFILES:.msg=_m.h)
smheaders: $(SMFILES:.sm=_sm.h)
clean:
$(qecho) Cleaning...
$(Q)-rm -rf $O
$(Q)-rm -f simulation simulation.exe libsimulation.so libsimulation.a libsimulation.dll libsimulation.dylib
$(Q)-rm -f ./*_m.cc ./*_m.h ./*_sm.cc ./*_sm.h
cleanall: clean
$(Q)-rm -rf $(PROJECT_OUTPUT_DIR)
# include all dependencies
-include $(OBJS:%.o=%.d)
As you can see there are several files included in my project (eve.cc, Router.cc, Quelle.cc ...). But the only class, that includes kodo-rlnc is the Quelle.cc I posted before.
Still thanks for any help!
EDIT #2
I managed to fix the multiple definition error by an quick&dirty approach: I forced the once.cpp to not include the once_atomic.cpp. This actually isn't a general fix but it may be sufficient for my purpose. But since I don't know which library may need the funtions of once_atomic.cpp too, the future proofness is unpredictable.
Now I'm still working at the undefined reference-issue.
EDIT #3
This morning I've figured out how to fix the issue with the undefined reference. First of all I needed to declare an additional option while linking the libgtest.a. Instead of ./libs/gtest/libgtest.a the correct form was ./libs/gtest/libgtest.a -pthread.
But that didn't fix the whole problem: As a newbie using the gcc, I forgot to check the linking order. Following the hint in this question I managed to enable a cycle-group within the linked libs with -Wl,--start-group -la -lb -lc -Wl,--end-group.
So with the first issue dirty-fixed and the second issue normally fixed,my project began to work.
For me the topic is closed now.
But does anybody may tell me how to fix the first issue in a clear normal way?
It would be great to not depend on a dirty solution.
Thanks!
As written in the edit sections, my problems were fixed by a quick&dirty solution. It appears to be working till now and hopefully likewise in the future.
To fix the multiple dfinition in once.cpp and once_atomic.cpp simply comment the include of the once_atomic.cpp in the once.cpp of boost::thread.
//#include "./once_atomic.cpp"
To fix the second issue with the undefined reference to a symbol within the gtest::pthread it just needed two simple entries in the Makefile:
Within the LIBS declare additionally: ./libs/gtest/libgtest.a -pthread and add a cycle group to the compile statement around the LIBS:
$(Q)$(CXX) $(LDFLAGS) -o $O/$(TARGET) $(OBJS) $(EXTRA_OBJS) $(AS_NEEDED_OFF) $(WHOLE_ARCHIVE_ON) -Wl,--start-group $(LIBS) -Wl,--eng-group $(WHOLE_ARCHIVE_OFF) $(OMNETPP_LIBS)
This did it for me. But maybe somebody can tell me a better and smoother solution for my problems!
Thanks 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 ; }
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 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.
Here is my code
#include<iostream>
#include<Windows.h>
using namespace std;
#define BUFSIZE 4602
#define VARNAME TEXT("zzz")
int main()
{
TCHAR chNewEnv[BUFSIZE];
GetEnvironmentVariable(VARNAME, chNewEnv, BUFSIZE);
if(GetLastError()==ERROR_ENVVAR_NOT_FOUND)
{
cout<<"Hello";
}
else
{
cout<<"Bye";
}
return 0;
}
I am checking whether zzz environment variable is available or not. I need to do the same without using if(GetLastError()==ERROR_ENVVAR_NOT_FOUND). Is there any way?
I am doing the same program using C# in which I don't use GetLastError(). I need to make these two programs similar that is why I am asking without the use of GetLastError(). Here is my C# snippet
string abc =Environment.GetEnvironmentVariable("zzz");
if (abc == null || abc.ToUpper() == "NULL" || abc.ToUpper() == "NUL")
You have to use GetLastError, as you may encounter cases where a variable is defined with no value.
Such cases can be emulated with:
SetEnvironmentVariable( "foo", "" );
When GetEnvironmentVariable return 0, it may be that the variable doesn't exist, or that is exists with an empty content. In the later case, GetLastError returns 0.
If you don't care (that is: a nonexistent variable or an empty one is the same for you), then don't bother with GetLastError.
Side note. You should always make a first call with a NULL nSize argument, as the documentation states:
If lpBuffer is not large enough to hold the data, the return value is
the buffer size, in characters, required to hold the string and its
terminating null character and the contents of lpBuffer are undefined.
And, I just tested (Windows 7), in such case GetLastError returns 0 (awkward, if you ask me)
Edit: On Windows 7, when I set an user variable to "null", the value retrieved by GetEnvironmentVariable (MBCS) is a 5 bytes string 'n', 'u', 'l', 'l', '\0'
Code (UNICODE build):
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <Windows.h>
#define BUFSIZE 4602
#define VARNAME L"zzz"
const wchar_t * MyGetEnv( const wchar_t * pszVarName, wchar_t * pszVarValue,
size_t cbValue ) {
DWORD dwCopied = GetEnvironmentVariable( pszVarName, pszVarValue, cbValue );
// The line bellow MAY BE COMMENTED OUT IF YOU REALLY
// DON'T LIKE GETLASTERROR, AS cbCopied WILL BE ZERO FOR
// NON-EXISTENT VARIABLE
if ( GetLastError() != NO_ERROR ) return NULL; // doesn't exist, or error
if ( dwCopied == 0 ) return NULL; // var is empty
return pszVarValue;
}
int main() {
wchar_t szVarValue[ BUFSIZE ];
const wchar_t * pszVarValue = MyGetEnv( VARNAME, szVarValue,
_countof( szVarValue ) );
if ( pszVarValue == NULL ) {
printf( "No variable or empty value\n" );
} else if ( ( _wcsicmp( pszVarValue, L"null" ) == 0 ) ||
( _wcsicmp( pszVarValue, L"nul" ) == 0 ) ) {
printf( "Special 'null' or 'nul' value\n" );
} else {
wprintf( L"Value is %s\n", szVarValue );
}
return 0;
}