Jump to random parts of code/binary while debugging, own makefile for building

I've created a makefile:

#============================================#
#            Project Configuration           #
#============================================#

NAME = ProjectName
SOURCES_DIRECTORY = sources

# These directories should be created by build.py script
BUILD_DIRECTORY = builds
OBJECTS_DIRECTORY = objs

CORE = cortex-m3
# LOAD_TO_RAM: 0 - False, 1 - True

ifeq ($(LOAD_TO_RAM), 1) LINKER_SCRIPT = linker_ram.ld else LINKER_SCRIPT = linker_rom.ld endif # C definitions ifeq ($(RAM_FLASH), 1)
C_DEFS = -DRAM_FLASH
else
C_DEFS =
endif

INC_DIRS = sources
SRCS_DIRS = sources

# extension of C files
C_EXT = c

# wildcard for C source files (all files with C_EXT extension found in current
# folder and SRCS_DIRS folders will be compiled and linked)
C_SRCS = $(wildcard$(patsubst %, %/*.$(C_EXT), .$(SRCS_DIRS)))

# extension of ASM files
AS_EXT = s

# wildcard for ASM source files (all files with AS_EXT extension found in
# current folder and SRCS_DIRS folders will be compiled and linked)
AS_SRCS = $(wildcard$(patsubst %, %/*.$(AS_EXT), .$(SRCS_DIRS)))

# optimization flags ("-O0" - no optimization, "-O1" - optimize, "-O2" -
# optimize even more, "-Os" - optimize for size or "-O3" - optimize yet more)
OPTIMIZATION = -O0

# set to 1 to optimize size by removing unused code and data during link phase
REMOVE_UNUSED = 1

C_WARNINGS = -w

# C language standard ("c89" / "iso9899:1990", "iso9899:199409",
# "c99" / "iso9899:1999", "gnu89" - default, "gnu99")
C_STD = c99

VPATH = $(SRCS_DIRS) #============================================# # Toolchain Configuration # #============================================# TOOLCHAIN = arm-none-eabi- CXX =$(TOOLCHAIN)g++
CC = $(TOOLCHAIN)gcc AS =$(TOOLCHAIN)gcc -x assembler-with-cpp
OBJCOPY = $(TOOLCHAIN)objcopy OBJDUMP =$(TOOLCHAIN)objdump
SIZE = $(TOOLCHAIN)size RM = rm -f .PHONY: all clean #=============================================================================# # various compilation flags #=============================================================================# # core flags CORE_FLAGS = -mthumb -O0 -g -Wall -I. -mcpu=$(CORE) -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard -DSTM32F429xx

# flags for C compiler
C_FLAGS = -std=$(C_STD) -g -ggdb3 -fverbose-asm -Wa,-ahlms=$(OBJECTS_DIRECTORY)/$(notdir$(<:.$(C_EXT)=.lst)) # flags for assembler AS_FLAGS = -g -ggdb3 -Wa,-amhls=$(OBJECTS_DIRECTORY)/$(notdir$(<:.$(AS_EXT)=.lst)) # flags for linker LD_FLAGS = -T$(LINKER_SCRIPT) -g -Wl,-Map=$(OBJECTS_DIRECTORY)/$(NAME).map,--cref,--no-warn-mismatch

# process option for removing unused code
ifeq ($(REMOVE_UNUSED), 1) LD_FLAGS += -Wl,--gc-sections OPTIMIZATION += -ffunction-sections -fdata-sections endif #=============================================================================# # do some formatting #=============================================================================# C_OBJS =$(addprefix $(OBJECTS_DIRECTORY)/,$(notdir $(C_SRCS:.$(C_EXT)=.o)))
AS_OBJS = $(addprefix$(OBJECTS_DIRECTORY)/, $(notdir$(AS_SRCS:.$(AS_EXT)=.o))) OBJS =$(AS_OBJS) $(C_OBJS)$(CXX_OBJS) $(USER_OBJS) DEPS =$(OBJS:.o=.d)
INC_DIRS_F = -I. $(patsubst %, -I%,$(INC_DIRS))
LIB_DIRS_F = $(patsubst %, -L%,$(LIB_DIRS))

ELF = $(BUILD_DIRECTORY)/$(NAME).elf
HEX = $(BUILD_DIRECTORY)/$(NAME).hex
BIN = $(BUILD_DIRECTORY)/$(NAME).bin
LSS = $(BUILD_DIRECTORY)/$(NAME).lss
DMP = $(BUILD_DIRECTORY)/$(NAME).dmp

# format final flags for tools, request dependancies for C++, C and asm
C_FLAGS_F = $(CORE_FLAGS)$(OPTIMIZATION) $(C_WARNINGS)$(C_FLAGS) $(C_DEFS) -MD -MP -MF$(OBJECTS_DIRECTORY)/$(@F:.o=.d)$(INC_DIRS_F)
AS_FLAGS_F = $(CORE_FLAGS)$(AS_FLAGS) $(AS_DEFS) -MD -MP -MF$(OBJECTS_DIRECTORY)/$(@F:.o=.d)$(INC_DIRS_F)
LD_FLAGS_F = $(CORE_FLAGS)$(LD_FLAGS) $(LIB_DIRS_F) #contents of output directory GENERATED =$(wildcard $(patsubst %,$(BUILD_DIRECTORY)/*.%, bin d dmp elf hex lss lst map o))

#=============================================================================#
# make all
#=============================================================================#

all : $(ELF)$(LSS) $(DMP)$(HEX) $(BIN) print_size # make object files dependent on Makefile$(OBJS) : Makefile
# make .elf file dependent on linker script
$(ELF) :$(LINKER_SCRIPT)

#-----------------------------------------------------------------------------#
# linking - objects -> elf
#-----------------------------------------------------------------------------#

$(ELF) :$(OBJS)
@$(CC)$(LD_FLAGS_F) $(OBJS)$(LDLIBS) -o $@ #-----------------------------------------------------------------------------# # compiling - C source -> objects #-----------------------------------------------------------------------------# objs/%.o : %.$(C_EXT)
@$(CC) -c$(C_FLAGS_F) $< -o$@

#-----------------------------------------------------------------------------#
# assembling - ASM source -> objects
#-----------------------------------------------------------------------------#

objs/%.o : %.$(AS_EXT) @$(AS) -c $(AS_FLAGS_F)$< -o $@ #-----------------------------------------------------------------------------# # memory images - elf -> hex, elf -> bin #-----------------------------------------------------------------------------#$(HEX) : $(ELF) @$(OBJCOPY) -O ihex $<$@

$(BIN) :$(ELF)
@$(OBJCOPY) -O binary$< $@ #-----------------------------------------------------------------------------# # memory dump - elf -> dmp #-----------------------------------------------------------------------------#$(DMP) : $(ELF) @$(OBJDUMP) -x --syms $< >$@

#-----------------------------------------------------------------------------#
# extended listing - elf -> lss
#-----------------------------------------------------------------------------#

$(LSS) :$(ELF)
@$(OBJDUMP) -S$< > $@ #-----------------------------------------------------------------------------# # print the size of the objects and the .elf file #-----------------------------------------------------------------------------# print_size : @echo. @echo Size of target .elf file: @$(SIZE) -B $(ELF) @echo. # include dependancy files -include$(DEPS)


It creates binary files without any errors. I'm using GNU ARM Embedded Toolchain and GNU MCU Eclipse Windows Make Tools... however instead of Eclipse I'm running all manually from command line using makefile.

Here is a linker script, generated with STM32 Cube:

/*
*****************************************************************************
**

**  File        : LinkerScript.ld
**
**  Abstract    : Linker script for STM32F429ZITx Device with
**                2048KByte FLASH, 192KByte RAM
**
**                Set heap size, stack size and stack location according
**                to application requirements.
**
**                Set memory bank area and size if external memory is used.
**
**  Target      : STMicroelectronics STM32
**
**
**  Distribution: The file is distributed as is, without any warranty
**                of any kind.
**
*****************************************************************************
** @attention
**
** <h2><center>&copy; COPYRIGHT(c) 2014 Ac6</center></h2>
**
** Redistribution and use in source and binary forms, with or without modification,
** are permitted provided that the following conditions are met:
**   1. Redistributions of source code must retain the above copyright notice,
**      this list of conditions and the following disclaimer.
**   2. Redistributions in binary form must reproduce the above copyright notice,
**      this list of conditions and the following disclaimer in the documentation
**      and/or other materials provided with the distribution.
**   3. Neither the name of Ac6 nor the names of its contributors
**      may be used to endorse or promote products derived from this software
**      without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
*****************************************************************************
*/

/* Entry Point */
ENTRY(Reset_Handler)

/* Highest address of the user mode stack */
_estack = 0x20030000;    /* end of RAM */
/* Generate a link error if heap and stack don't fit into RAM */
_Min_Heap_Size = 0x200;      /* required amount of heap  */
_Min_Stack_Size = 0x400; /* required amount of stack */

/* Specify the memory areas */
MEMORY
{
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 192K
CCMRAM (rw)      : ORIGIN = 0x10000000, LENGTH = 64K
FLASH (rx)      : ORIGIN = 0x8000000, LENGTH = 2048K
}

/* Define output sections */
SECTIONS
{
/* The startup code goes first into FLASH */
.isr_vector :
{
. = ALIGN(4);
KEEP(*(.isr_vector)) /* Startup code */
. = ALIGN(4);
} >FLASH

/* The program code and other data goes into FLASH */
.text :
{
. = ALIGN(4);
*(.text)           /* .text sections (code) */
*(.text*)          /* .text* sections (code) */
*(.glue_7)         /* glue arm to thumb code */
*(.glue_7t)        /* glue thumb to arm code */
*(.eh_frame)

KEEP (*(.init))
KEEP (*(.fini))

. = ALIGN(4);
_etext = .;        /* define a global symbols at end of code */
} >FLASH

/* Constant data goes into FLASH */
.rodata :
{
. = ALIGN(4);
*(.rodata)         /* .rodata sections (constants, strings, etc.) */
*(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
. = ALIGN(4);
} >FLASH

.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH
.ARM : {
__exidx_start = .;
*(.ARM.exidx*)
__exidx_end = .;
} >FLASH

.preinit_array     :
{
PROVIDE_HIDDEN (__preinit_array_start = .);
KEEP (*(.preinit_array*))
PROVIDE_HIDDEN (__preinit_array_end = .);
} >FLASH
.init_array :
{
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array*))
PROVIDE_HIDDEN (__init_array_end = .);
} >FLASH
.fini_array :
{
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP (*(SORT(.fini_array.*)))
KEEP (*(.fini_array*))
PROVIDE_HIDDEN (__fini_array_end = .);
} >FLASH

/* used by the startup to initialize data */

/* Initialized data sections goes into RAM, load LMA copy after code */
.data :
{
. = ALIGN(4);
_sdata = .;        /* create a global symbol at data start */
*(.data)           /* .data sections */
*(.data*)          /* .data* sections */

. = ALIGN(4);
_edata = .;        /* define a global symbol at data end */
} >RAM AT> FLASH

/* CCM-RAM section
*
* IMPORTANT NOTE!
* If initialized variables will be placed in this section,
* the startup code needs to be modified to copy the init-values.
*/
.ccmram :
{
. = ALIGN(4);
_sccmram = .;       /* create a global symbol at ccmram start */
*(.ccmram)
*(.ccmram*)

. = ALIGN(4);
_eccmram = .;       /* create a global symbol at ccmram end */
} >CCMRAM AT> FLASH

/* Uninitialized data section */
. = ALIGN(4);
.bss :
{
/* This is used by the startup in order to initialize the .bss secion */
_sbss = .;         /* define a global symbol at bss start */
__bss_start__ = _sbss;
*(.bss)
*(.bss*)
*(COMMON)

. = ALIGN(4);
_ebss = .;         /* define a global symbol at bss end */
__bss_end__ = _ebss;
} >RAM

/* User_heap_stack section, used to check that there is enough RAM left */
._user_heap_stack :
{
. = ALIGN(8);
PROVIDE ( end = . );
PROVIDE ( _end = . );
. = . + _Min_Heap_Size;
. = . + _Min_Stack_Size;
. = ALIGN(8);
} >RAM

/* Remove information from the standard libraries */
{
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}

.ARM.attributes 0 : { *(.ARM.attributes) }
}


I'm debugging code on STM32 using J-Link Ozone... Unfortunately, the program flow behaves strange, it sometimes jumps to a middle of some function but it shouldn't...Each time, after System_Init function it jumps to completely different part of code... I'm trying to figure out what causes PC register to change, but with no progress so far. What I am doing wrong, what should I check and what additional data should I add here to give a better understanding of my work? Thanks...

• This could be because of optimizations. The logical flow of the program is sometimes rearranged by the compiler. But with the info provided it's hard to tell if that's the case. – Eugene Sh. Nov 20 '17 at 21:28
• That's why I asked what else I could paste here... Of course I won't add all code here, it doesn't make sense I think – VIPPER Nov 20 '17 at 21:31
• Can you come up with a shortest code reproducing it? – Eugene Sh. Nov 20 '17 at 21:32
• I have optimization turned off, it's -O0 in the makefile – VIPPER Nov 20 '17 at 21:36
• You have the assembly listing. Compare it with the dissaembly of the debugged code. Maybe you debug the binary file which is not the same as the newly compiled and linked. I has similar problem couple of years ago. Changed files location but forgot to change the paths in the debugger. – P__J__ Nov 21 '17 at 19:52