GithubHelp home page GithubHelp logo

freertos / freertos-kernel Goto Github PK

View Code? Open in Web Editor NEW
2.5K 2.5K 1.1K 116.6 MB

FreeRTOS kernel files only, submoduled into https://github.com/FreeRTOS/FreeRTOS and various other repos.

Home Page: https://www.FreeRTOS.org

License: MIT License

C 90.46% Python 0.07% Assembly 8.96% Batchfile 0.05% CMake 0.47%

freertos-kernel's Introduction

The FreeRTOS 202212.00 release updates FreeRTOS Kernel, FreeRTOS+TCP, coreMQTT, corePKCS11, coreHTTP, coreJSON, AWS IoT Over-the-air-Updates (OTA), AWS IoT Device Shadow, AWS IoT Jobs, AWS IoT Device Defender, Backoff Algorithm, AWS IoT Fleet Provisioning, coreSNTP, SigV4, and FreeRTOS Cellular Interface libraries to their LTS 2.0 versions. It also updates coreMQTT Agent to v1.2.0 to be compatible with coreMQTT v2.X.X, and updates MbedTLS to v3.2.1. This release also adds Visual Studio static library projects for the FreeRTOS Kernel, FreeRTOS+TCP, Logging, MbedTLS, coreHTTP, and corePKCS11. With the addition of the static library projects, all Visual Studio projects have been updated to use them. Additionally, all demos dependent on coreMQTT have been updated to work with coreMQTT v2.X.X.

Getting started

The FreeRTOS.org website contains a FreeRTOS Kernel Quick Start Guide, a list of supported devices and compilers, the API reference, and many other resources.

Getting help

You can use your Github login to get support from both the FreeRTOS community and directly from the primary FreeRTOS developers on our active support forum. The FAQ provides another support resource.

Cloning this repository

This repo uses Git Submodules to bring in dependent components.

Note: If you download the ZIP file provided by the GitHub UI, you will not get the contents of the submodules. (The ZIP file is also not a valid git repository)

If using Windows, because this repository and its submodules contain symbolic links, set core.symlinks to true with the following command:

git config --global core.symlinks true

In addition to this, either enable Developer Mode or, whenever using a git command that writes to the system (e.g. git pull, git clone, and git submodule update --init --recursive), use a console elevated as administrator so that git can properly create symbolic links for this repository. Otherwise, symbolic links will be written as normal files with the symbolic links' paths in them as text. This gives more explanation.

To clone using HTTPS:

git clone https://github.com/FreeRTOS/FreeRTOS.git --recurse-submodules

Using SSH:

git clone [email protected]:FreeRTOS/FreeRTOS.git --recurse-submodules

If you have downloaded the repo without using the --recurse-submodules argument, you need to run:

git submodule update --init --recursive

Repository structure

This repository contains the FreeRTOS Kernel, a number of supplementary libraries including the LTS ones, and a comprehensive set of example projects. Many libraries (including the FreeRTOS kernel) are included as Git submodules from their own Git repositories.

Kernel source code and example projects

FreeRTOS/Source contains the FreeRTOS kernel source code (submoduled from https://github.com/FreeRTOS/FreeRTOS-Kernel).

FreeRTOS/Demo contains pre-configured example projects that demonstrate the FreeRTOS kernel executing on different hardware platforms and using different compilers.

Supplementary library source code and example projects

FreeRTOS-Plus/Source contains source code for additional FreeRTOS component libraries, as well as select partner provided libraries. These subdirectories contain further readme files and links to documentation.

FreeRTOS-Plus/Demo contains pre-configured example projects that demonstrate the FreeRTOS kernel used with the additional FreeRTOS component libraries.

Previous releases

Releases contains older FreeRTOS releases.

FreeRTOS Lab Projects

FreeRTOS Lab projects are libraries and demos that are fully functional, but may be experimental or undergoing optimizations and refactorization to improve memory usage, modularity, documentation, demo usability, or test coverage.

Most FreeRTOS Lab libraries can be found in the FreeRTOS-Labs repository.

A number of FreeRTOS Lab Demos can be found in the FreeRTOS Github Organization by searching for "Lab" or following this link to the search results.

coreMQTT Agent Demos

The FreeRTOS/coreMQTT-Agent-Demos repository contains demos to showcase use of the coreMQTT-Agent library to share an MQTT connection between multiple application tasks.

The demos show a single MQTT connection usage between multiple application tasks for interacting with AWS services (including Over-the-air-Updates, Device Shadow, Device Defender) alongside performing simple Publish-Subscribe operations.

CBMC

The FreeRTOS/Test/CBMC/proofs directory contains CBMC proofs.

To learn more about CBMC and proofs specifically, review the training material here.

In order to run these proofs you will need to install CBMC and other tools by following the instructions here.

freertos-kernel's People

Contributors

aggarg avatar alfred2g avatar aniruddhakanhere avatar archigup avatar bradleysmith23 avatar chinglee-iot avatar cobusve avatar dachalco avatar dazza0 avatar feilipu avatar jefftenney avatar kar-rahul-aws avatar kilograham avatar kstribrnamzn avatar laroche avatar lundinc2 avatar mingyue86010 avatar moral-hao avatar n9wxu avatar paulbartell avatar phelter avatar ravibhagavandas avatar richardbarry avatar schilkp avatar shubhamkulkarni97 avatar skptak avatar tony-josi-aws avatar urutva avatar yuhui-zheng avatar zikalino avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

freertos-kernel's Issues

[BUG] -flto optimization fails with ARM_CM0 port (invalid offset, value too big)

When enabling the -flto optimization (in the C , C++ compilers and linker) with arm-none-eabi 9.2.1 in a project using the FreeRTOS kernel, the linker fails with following message
C:\Users\Victor\AppData\Local\Temp\ccmlDk9r.s:2750: Error: invalid offset, value too big (0x00006E80)
c:/nxp/mcuxpressoide_11.2.0_4120/ide/plugins/com.nxp.mcuxpresso.tools.win32_11.2.0.202001021529/tools/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld.exe: error: lto-wrapper failed

Target

  • LPC845 (cortex M0+)
  • IDE : Mcuxpresso 11.2.0
  • compiler : arm-none-eabi 9.2.1
  • FreeRTOS version [master] branch as of today
  • Host : Windows 10

image

Related post on NXP forums : https://community.nxp.com/message/1346393?commentID=1346393&et=watches.email.thread#comment-1346393

I do not have the knowledge to understand what goes wrong.

[BUG]Port for CCS/MSP430X - possible race condition in macro portRESTORE_CONTEXT

Describe the bug
There's possible race condition in the macro portRESTORE_CONTEXT.
This may destroy the stack of task, and later cause a jump to invalid memory address.

The analysis of the bug was very difficult, so the description will be very difficult, but I'll do my best.
If something is unclear, let me know.

Target

  • Development board: MSP430FR5969 (http://www.ti.com/tool/MSP-EXP430FR5969)
  • Instruction Set Architecture: MSP430X (the bug may occur when small or large memory model is used)
  • IDE and version: Code Composer Studio Version: 9.2.0.00013
  • Toolchain and version: cl430 MSP430 C/C++ Compiler v18.12.3.LTS, msp430-elf-gcc (Mitto Systems Limited - msp430-gcc 8.3.0.16) 8.3.0

Host

  • Host OS: Debian
  • Version: 9

To Reproduce

  • Use project with uses vPortYield frequently

Expected behavior

  • Race condition in context switching code, jump to invalid address

Screenshots
Debugging session, gdb:
obraz

Additional context
I'm trying to create FreeRTOS port for MSP430 and GCC with support for large memory model.

I try to reuse code from two ports:

The CCS port supports small memory model and large memory model.
The GCC port supports only small memory model.

The CSS port uses different approach in context switching code.

Generally: the context switching code is a critical section, the interrupts should be disabled till final return.

In the CSS port two instructions are used: pop sr, which enables interrupts, and reta which pops the return address from the stack and jumps to it. The last instruction reta IS NOT in critical section.
https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/master/portable/CCS/MSP430X/portext.asm#L65

In the GCC port one instruction is used: reti, which pops four bytes from stack and restores values of Status Register and Program Counter. The instruction reti is in critical section.
https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/master/portable/GCC/MSP430F449/port.c#L126

Additional info: MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User's Guide

If the Timer A ISR fire up after instruction pop sr and before instruction reta, the instruction reta will never be executed, and the stack of the task will be broken.

Scenario:

  1. One of the tasks calls vPortYield (see screenshot)
  2. context of the task is stored using macro portSAVE_CONTEXT
  3. another task is selected
  4. macro portRESTORE_CONTEXT is called (see screenshot)
    1. Machine instructions are executed, till pop sr (see screenshot)
    2. Instruction pop sr enables interrupts.
    3. There's still return address on the stack, which should be consumed by instruction reta (see screenshot)
    4. Interrupts are enabled, so the CPU jumps to timer A ISR, which performs context switching again.
  5. The stack of unlucky task is broken.

Possible fix
This is the hard part. I try to use reti instruction in the portRESTORE_CONTEXT macro, it works fine in small memory model, but in large memory model it needs additional hacking, but it works too.

[BUG] FreeRTOS 10.2.1 fails to build in IAR EWARM in C++ mode

Describe the bug
FreeRTOS 10.2.1 fails to build in IAR EWARM in C++ mode
Note that this is the FreeRTOS version provided by the STM development tools code generator, but part of this bug may be present in a newer FreeRTOS release.

Target

  • Development board: STM32L5
  • Instruction Set Architecture: Cortex-M33
  • IDE and version: IAR EWARM 8.50.9
  • Toolchain and version: IAR Compiler

Host

  • Host OS: Windows

To Reproduce

  • Use STM32CubeMX to generate an IAR project with FreeRTOS for a Cortex-M MCU. (STM32F7, STM32L5, etc)
  • Open the project in IAR EWARM 8.50.
  • Open the project properties of the project.
  • Switch project to C++ mode. (see screenshot).
  • Save project changes.
  • Attempt to build. (requires IAR license activation)

Screenshots
Build Failure when switching to C++ Mode:
FreeRTOS_IAR_CPP

Proposed Fix
Here is a patch to fix the issue. Just need to cast everything correctly.
The software still builds on GCC after the patch.
IAR_FreeRTOS_Patch.diff.txt

[BUG] xEventGroupClearBitsFromISR execution delay

Below is a simple example that causes event group clear operation (from ISR) to execute after event group set operation:

/* Interrupt handler (ISR context) */
void Peripheral_IRQHandler (void) {
  BaseType_t rval;

  rval = xEventGroupClearBitsFromISR (hEventGroup, (EventBits_t)0x00000001U);
}

/* Test task */
void Test (void *arg) {

  hEventGroup = xEventGroupCreate();

  bits_a = xEventGroupSetBits (hEventGroup, (EventBits_t)0x00000001U);
  // After execution: bits_a == 1

  // Peripheral_IRQHandler was triggered and executed (ISR context)

  bits_b = xEventGroupSetBits (hEventGroup, (EventBits_t)0x00000001U);
  // After execution: bits_b == 0
}

In a Test task, Event Group object is created and its LSB is set using xEventGroupSetBits .

Next, peripheral interrupt is fired and Peripheral_IRQHandler is executed, which calls xEventGroupClearBitsFromISR. This function registers vEventGroupClearBitsCallback for execution and moves timer service/daemon task to ready state.

After interrupt handler returns, xEventGroupSetBits is called again, setting LSB. This function calls vTaskSuspendAll, sets the LSB and before it returns, calls xTaskResumeAll - at this point, timer service/deamon task gets its chance to execute and calls vEventGroupClearBitsCallback which clears the Event Group LSB. Bits returned by pxEventBits->uxEventBits are therefore invalid.

This was verified on an Cortex-M target.

See

BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup,

static portTASK_FUNCTION( prvTimerTask, pvParameters )

static void prvProcessReceivedCommands( void )

void vEventGroupClearBitsCallback( void * pvEventGroup,

EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup,

return pxEventBits->uxEventBits;

A simple workaround is to just use portYIELD_FROM_ISR:

/* Interrupt handler (ISR context) */
void Peripheral_IRQHandler (void) {
  BaseType_t rval;

  rval = xEventGroupClearBitsFromISR (hEventGroup, (EventBits_t)0x00000001U);

  if (rval == pdPASS) {
    portYIELD_FROM_ISR (pdTRUE);
  }
}

Git tag schema is confusing

Describe the bug

There exists two types of git tags:
V10.4.1-kernel-only and V10.3.0

And both have different folder and file structure... If someone is using a package manager (like conan) a clone and build from the newest kernel version isn't that easy.

So that we can rely on: Will all future releases of the kernel be tagged <version>-kernel-only or could there be a V10.5.0 (including the kernel update) without a V10.5.0-kernel-only tag?

[Inquiry] Would lower-power ports benefit from portTICK_TYPE_ATOMIC

Looking at the latest kernel I noticed these macros:
portTICK_TYPE_ENTER_CRITICAL()
portTICK_TYPE_EXIT_CRITICAL()
portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR()
portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR(x)

After some more review it would save ~10-13 instructions with no optimization, and ~4-5 on full optimization. The benefit from this enhancement of course depends on how often this function is called, but it might be desirable for low-power targets. My target is not that stringent, but an MSP430 would see some benefit here for example.

In generalAPI design adding flexibility comes with added complexity, and the question is if this would be worthwhile. My target is fine, but this may be different for an MSP430.

There is also atomic.h that could be consolidated with a similar feature. My only concern is offering the port this much flexibility may run into determinism issues if it is poorly implemented on the port.

Stack checking method 2 improperly defined in the stack_macros.h

According to the documentation here setting a value of 2 to configCHECK_FOR_STACK_OVERFLOW should have the kernel check both the stack pointer position as well as the known value written to the stack when swapping tasks. As it is currently written in stack_macros.h, when configCHECK_FOR_STACK_OVERFLOW is set to 2 it only checks the known value on the stack and not the stack pointer position. This should be changed so the stack check function does both for all values greater than 1.

Do you plan to add a port for ARM_CM0_MPU?

I am currently working with FreeRTOS and MKM34 (which is a Cortex M0+MPU) and I would like to know if you plan to add this port. Theoretically, the management of the MPU is the same as that of the other processors in the Cortex-M family.

If not, what would be the right way to add it, with a little guidance I can do it myself and make a pull request later.

[BUG] The newly added GCC/RX200 port is wrong.

Describe the bug

The port should be for RX200 group MCUs using RXv1 CPU core but without FPU. RXv1 CPU core has only one accumulator. (On the other hand, RXv2 and RXv3 CPU cores has two accumulators.) Nevertheless the port attempts to save/restore FPSW(FPU's PSW) and two accumulators(using RXv2 CPU core instructions)! (Please compare GCC/RX200/port.c and Renesas/RX200/port.c.)

Conversation with source code is here.

Update Renesas GCC compiler ports #135
#135 (comment)

Best regards,
NoMaY

[RISCV] Support for vector only RISCV core (ibex) ?

On riscV, the code is asserting if the direct mode of mtvec is not set to "0" i.e. if it is not in direct mode.

/* Check the least significant two bits of mtvec are 00 - indicating
single vector mode. */
__asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) );
configASSERT( ( mtvec & 0x03UL ) == 0 );

There is the symetric issue in xPortStartFirstTask, when setting mtvec to point to freertos_trap_handler

Some cores (ibex) only supports vector mode

Would it be ok to have a configuration switch to allow for vectored mode ?
Maybe, an additional table with all entries pointing to freertos_trap_handler ?
If that's ok, i can try to propose a patch
Thank you.

[BUG] 'V10.3.1' of comment remains in header part of assembly source files though FreeRTOS-Kernel V10.4.0

Hello,

I notice that 'V10.3.1' of comment remains in header part of assembly source files though FreeRTOS-Kernel V10.4.0 in the following Renesas RX MCUs' portable layer. Not only in case of Renesas RX MCUs but also in case of other MCUs, source files other than *.{c, h} seem to be the same.

; * FreeRTOS Kernel V10.3.1

; * FreeRTOS Kernel V10.3.1

; * FreeRTOS Kernel V10.3.1

; * FreeRTOS Kernel V10.3.1

Best regards,
NoMaY

[Inquiry] Suggestions to improve vTaskDelayUntil

Hello,

I would like to suggest some possible improvements for vTaskDelayUntil.

For our application, we would like to check whether a deadline for a periodic task was missed.
For us, this is generally the case if vTaskDelayUntil() does not delay the task. Unfortunately, vTaskDelayUntil does not have a returnvalue, which tells me whether the task was delayed or not ( could also be implemented by passing a pointer to a boolean), so we needed to perform the check before calling vTaskDelayUntil (and we also had to implement the overflow checking again) because the last wake time will be updated internally by it. What do you think about this?

Basically, the interface for vTaskDelayUntil would change from

void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement)

to

void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement, BaseType_t* xWasDelayed)

And the local variable xShouldDelay is assigned too *xWasDelayed at the function end.
Unfortunately, this is an API change but I think it would be a nice feature to implement the checking of missed deadlines.

[BUG] Re-introduce uxTopUsedPriority for OpenOCD Thread Support

OpenOCD is a popular Open Source On-Chip Debugger:

http://openocd.org/

One of its best features is thread support (Task support). With OpenOCD, the GNU gdb debugger can view the list of Tasks, and can look at an individual Task to see its stack trace, step through code in just that one Task, etc Basically, OpenOCD enables these gdb features:

https://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_24.html

(Eclipse also has desktop GUI support for walking through OpenOCD Tasks, much like a normal POSIX threaded program.)

Without thread support, gdb is very restricted and hard to use with a FreeRTOS application. For example, constant SysTick interrupts keep jumping you into the scheduler, making it very hard to follow your application code. It's basically only useful for debugging main() and ISRs.

In an older release of FreeRTOS (V7.5.3) there was a symbol removed called uxTopUsedPriority. That symbol is necessary for OpenOCD to find the list of Tasks and enable thread support.

Since that release, we developers have had to manually re-introduce that symbol so that we can debug our FreeRTOS apps. Usually this means adding a copy of this file to the build:

https://raw.githubusercontent.com/arduino/OpenOCD/master/contrib/rtos-helpers/FreeRTOS-openocd.c

Here is that entire file:

/*
 * Since at least FreeRTOS V7.5.3 uxTopUsedPriority is no longer
 * present in the kernel, so it has to be supplied by other means for
 * OpenOCD's threads awareness.
 *
 * Add this file to your project, and, if you're using --gc-sections,
 * ``--undefined=uxTopUsedPriority'' (or
 * ``-Wl,--undefined=uxTopUsedPriority'' when using gcc for final
 * linking) to your LDFLAGS; same with all the other symbols you need.
 */

#include "FreeRTOS.h"

#ifdef __GNUC__
#define USED __attribute__((used))
#else
#define USED
#endif

const int USED uxTopUsedPriority = configMAX_PRIORITIES - 1;

Some distributions of FreeRTOS, like WICED SDK, already put this back for you.

The Internet is littered with forum posts of developers asking why they can't debug FreeRTOS Tasks, and responses telling them about this annoying requirement. Just google "uxTopUsedPriority" to see what I'm talking about.

So: Could FreeRTOS please re-add the uxTopUsedPriority symbol, and then never remove it again?

[BUG]Keil EC++ compiler throws warnings when compiling C++ files

Describe the bug
The Keil C166 EC++ compiler throws an error for each compilation unit that includes the task.h header file. As you can imagine, this can be many files! It creates a problem where users of the framework I am providing are concerned when they see a warning for each compilation unit. I am unsure if this issue persists in other Keil toolsets, especially since there are so many official ports. Of course the users can ignore this, or I can fork the kernel, but I think that is bad practice.

Target

  • Custom Infineon XC2287M target

Host

  • Host OS: Windows 10 Latest corporate image
  • Version: 1909

To Reproduce

  • Use Keil C166 compiler
  • Compile a C++ file with the FreeRTOS headers attached

Expected behavior
You will see a warning that cannot be suppressed stating:

.\FreeRTOS\include\task.h(121): warning: class "xTASK_PARAMETERS" defines no constructor to initialize the following: const member "xTASK_PARAMETERS::pcName"

Additional context
My easy fix on line 124 of task.h in latest git commit:

/*
 * Parameters required to create an MPU protected task.
 */
typedef struct xTASK_PARAMETERS
{
	TaskFunction_t pvTaskCode;
  #ifdef __cplusplus
  const char * pcName;
	#else
  const char * const pcName;	/*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  #endif
  configSTACK_DEPTH_TYPE usStackDepth;
	void *pvParameters;
	UBaseType_t uxPriority;
	StackType_t *puxStackBuffer;
	MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
	#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
		StaticTask_t * const pxTaskBuffer;
	#endif
} TaskParameters_t;

I found an older post for the same issue, but on the ARM platform here

Unfortunately, I am not able to suppress this warning without globally disabling all warnings (no warning number associated). See this for details.

[BUG] Uncrustify breaks asm macro code for IAR IASMRL78 assembler

Hello,

I notice another build problem. The following changes cause additional assembler errors. Though code of V10.3.1 already has some build problem which is reported in the following thread, but code after Uncrustify is strongly broken due to wrong handling of single line comment starting with ';'.

Compilation/Linker Issues in Running the Demo Example for FreeRTOS/Demo/RL78_RL78G13_Promo_Board_IAR directory
https://forums.freertos.org/t/compilation-linker-issues-in-running-the-demo-example-for-freertos-demo-rl78-rl78g13-promo-board-iar-directory/9218

portable/IAR/RL78/ISR_Support.h

Before:

#include "FreeRTOSConfig.h"

; Variables used by scheduler
;------------------------------------------------------------------------------
    EXTERN    _pxCurrentTCB
    EXTERN    _usCriticalNesting

;------------------------------------------------------------------------------
;   portSAVE_CONTEXT MACRO
;   Saves the context of the general purpose registers, CS and ES (only in far
;   memory mode) registers the usCriticalNesting Value and the Stack Pointer
;   of the active Task onto the task stack
;------------------------------------------------------------------------------
portSAVE_CONTEXT MACRO

    PUSH      AX                    ; Save AX Register to stack.
    PUSH      HL
    MOV       A, CS                 ; Save CS register.
    XCH       A, X
    MOV       A, ES                 ; Save ES register.
    PUSH      AX
    PUSH      DE                    ; Save the remaining general purpose registers.
    PUSH      BC
    MOVW      AX, usCriticalNesting ; Save the usCriticalNesting value.
    PUSH      AX
    MOVW      AX, pxCurrentTCB      ; Save the Stack pointer.
    MOVW      HL, AX
    MOVW      AX, SP
    MOVW      [HL], AX
    ENDM
;------------------------------------------------------------------------------

;------------------------------------------------------------------------------
;   portRESTORE_CONTEXT MACRO
;   Restores the task Stack Pointer then use this to restore usCriticalNesting,
;   general purpose registers and the CS and ES (only in far memory mode)
;   of the selected task from the task stack
;------------------------------------------------------------------------------
portRESTORE_CONTEXT MACRO
    MOVW      AX, pxCurrentTCB      ; Restore the Stack pointer.
    MOVW      HL, AX
    MOVW      AX, [HL]
    MOVW      SP, AX
    POP       AX                    ; Restore usCriticalNesting value.
    MOVW      usCriticalNesting, AX
    POP       BC                    ; Restore the necessary general purpose registers.
    POP       DE
    POP       AX                    ; Restore the ES register.
    MOV       ES, A
    XCH       A, X                  ; Restore the CS register.
    MOV       CS, A
    POP       HL                    ; Restore general purpose register HL.
    POP       AX                    ; Restore AX.
    ENDM
;------------------------------------------------------------------------------

After:

#include "FreeRTOSConfig.h"

;
Variables used by scheduler
;
------------------------------------------------------------------------------
EXTERN pxCurrentTCB
EXTERN usCriticalNesting

;
------------------------------------------------------------------------------
;
portSAVE_CONTEXT MACRO
;
Saves the context of the general purpose registers, CS and ES( only in far
                                                               ;
                                                               memory mode ) registers the usCriticalNesting Value and the Stack Pointer
;
of the active Task onto the task stack
;
------------------------------------------------------------------------------
portSAVE_CONTEXT MACRO

PUSH AX;
Save AX Register to stack.
   PUSH HL
MOV A, CS;
Save CS register.
   XCH A, X
MOV A, ES;
Save ES register.
   PUSH AX
PUSH DE;
Save the remaining general purpose registers.
   PUSH BC
MOVW AX, usCriticalNesting;
Save the usCriticalNesting value.
   PUSH AX
MOVW AX, pxCurrentTCB;
Save the Stack pointer.
   MOVW HL, AX
MOVW AX, SP
        MOVW[ HL ], AX
        ENDM
;
------------------------------------------------------------------------------

;
------------------------------------------------------------------------------
;
portRESTORE_CONTEXT MACRO
;
Restores the task Stack Pointer then use this to restore usCriticalNesting,
;
general purpose registers and the CS and ES( only in far memory mode )
;
of the selected task from the task stack
;
------------------------------------------------------------------------------
portRESTORE_CONTEXT MACRO
MOVW AX, pxCurrentTCB;
Restore the Stack pointer.
   MOVW HL, AX
MOVW AX, [ HL ]
MOVW SP, AX
POP AX;
Restore usCriticalNesting value.
   MOVW usCriticalNesting, AX
POP BC;
Restore the necessary general purpose registers.
   POP DE
POP AX;
Restore the ES register.
   MOV ES, A
XCH A, X;
Restore the CS register.
   MOV CS, A
POP HL;
Restore general purpose register HL.
   POP AX;
Restore AX.
   ENDM
;
------------------------------------------------------------------------------

Best regards,
NoMaY

Mismatch of parameters in macro ulTaskNotifyTakeIndexed causes compilation error

Describe the bug
This issue was first reported on the FreeRTOS forums here https://forums.freertos.org/t/task-h-error-uxindextonotify-undeclared/10689

The macro ulTaskNotifyTakeIndexed was introduced with FreeRTOS 10.4.0. The implementation of the macro had a mismatch between the named macro parameters and the use of these parameters in the macro as follows:

As this macro was only introduced in V10.4.0 and the failure is at compile time we consider the potential risk from this bug to be very limited.

The offending code is shown here

  
#define ulTaskNotifyTakeIndexed( uxIndexToWaitOn, xClearCountOnExit, xTicksToWait )
ulTaskGenericNotifyTake( ( uxIndexToNotify ), ( xClearCountOnExit ), ( xTicksToWait ) )
  

To Reproduce

  • Use the new macro ulTaskNotifyTakeIndexed as described in the forum post and you will observe a compilation error.

Additional context

The test code for this macro unfortunately had a local variable named uxIndexToNotify which masked the error during testing. The test was using this variable to pass the value into the macro which resulted in correct behavior because the variable name in the test was an exact match to the variable name incorrectly used in the macro implementation.

See this location for the exact code
https://github.com/FreeRTOS/FreeRTOS/blob/89d475e9b112d7b52c3d16aeff97e1e8e6b95316/FreeRTOS/Demo/Common/Minimal/TaskNotifyArray.c#L954

Bad #if in GCC ARMCM0 port

File FreeRTOS-Kernel/portable/GCC/ARM_CM0/port.c contains two instances of the following #if directive:

#if !defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)

This makes no sense at all, because if __ARMCC_VERSION is not define then it should not be tested (and the subsequent test will always yield false). Also it is not MISRA-compliant, and it rightly causes a compiler warning if the gcc -Wundef compiler option is used. My guess is that it is supposed to read either:

#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)

or

#if !defined (__ARMCC_VERSION) || (__ARMCC_VERSION >= 6010050)

or possibly one of these with >= replaced by <. I have replaced it by #if 0 in my copy to avoid the compiler warning.

Delaying by 0 ticks violates assert

This is undocumented and not intuitive. I would expect, like most functions, for a delay of 0 to return immediately or to be an effective context switch. I feel like one of those things would be optional. Instead, an assert is triggered. Why?

configASSERT( ( xTimeIncrement > 0U ) );

[BUG] configTASK_RETURN_ADDRESS is not respected

Describe the bug

configTASK_RETURN_ADDRESS is not set as the return address of task.

Looking at the code:

#ifdef configTASK_RETURN_ADDRESS
#define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
#else
#define portTASK_RETURN_ADDRESS prvTaskExitError
#endif

However, neither configTASK_RETURN_ADDRESS nor portTASK_RETURN_ADDRESS are written to the task's stack.
Instead, 0 is written:

store_x x0, 0(a0) /* Return address onto the stack, could be portTASK_RETURN_ADDRESS */

Target

GCC/RISC-V

Host

Any

To Reproduce

  • Set configTASK_RETURN_ADDRESS in FreeRTOSConfig.h to function F
  • Create a task that returns
  • Function F is not called

Expected behavior

configTASK_RETURN_ADDRESS should set the return address of a task that returns.

Parenthesis around if-statement in macros

When macro is used within an if-else statement, it can lead to ambiguities, when not sourrounded by curly braces.

#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired != pdFALSE ) portYIELD()

It is a good practice and makes it more developer convenient if the following piece of code would be used:

#define portEND_SWITCHING_ISR( xSwitchRequired ) \
    do \
        { if( xSwitchRequired != pdFALSE ) portYIELD(); \
    } while(0)

Reference Issue: STMicroelectronics/STM32CubeF4#20

[BUG] Uncrustify breaks inline asm code for Renesas CC-RX compiler

Hello,

I notice the following two problems caused by Uncrustify.

(1) There are some mistakes of indent.
(2) Single line comment starting with ';' is moved to the next line. This causes compile error.

For example, following changes had been made.

portable/Renesas/RX600v2/port.c

Before:

#pragma inline_asm prvYieldHandler
static void prvYieldHandler( void )
{
...omit...

    /* Save the FPSW and accumulators. */
    MVFC    FPSW, R15
    PUSH.L  R15    <---- HERE and BELOW.
    MVFACGU #0, A1, R15
    PUSH.L  R15
    MVFACHI #0, A1, R15
    PUSH.L  R15
    MVFACLO #0, A1, R15 ; Low order word.    <---- HERE
    PUSH.L  R15
    MVFACGU #0, A0, R15
    PUSH.L  R15
    MVFACHI #0, A0, R15
    PUSH.L  R15
    MVFACLO #0, A0, R15 ; Low order word.    <---- HERE
    PUSH.L  R15

...omit...
}

After:

#pragma inline_asm prvYieldHandler
static void prvYieldHandler( void )
{
...omit...

    /* Save the FPSW and accumulators. */
    MVFC FPSW, R15
        PUSH.L R15     <---- mistakes of indent. HERE and BELOW.
        MVFACGU # 0, A1, R15
        PUSH.L R15
        MVFACHI # 0, A1, R15
        PUSH.L R15
        MVFACLO # 0, A1, R15;
    Low order word.    <---- This should be comment.
       PUSH.L R15
        MVFACGU # 0, A0, R15
        PUSH.L R15
        MVFACHI # 0, A0, R15
        PUSH.L R15
        MVFACLO # 0, A0, R15;
    Low order word.    <---- This should be comment.
       PUSH.L R15

...omit...
}

Best regards,
NoMaY

get next instruction address by adding 4 may result in wrong address when supporting "c" extension

Hi sir, in the portASM.S for riscv, I found that when traped by a synchronous exception, the next address to fetch instrustions
is calaulated by adding 4 ?! this may not always true when the core supporting "c" extension and the current execting instruction
is a compress instruction which is two bytes width, then the next address should be pc + 2 !
it's better to get the current instruction value, and check weather it's a "c" instr or NOT , and then decide to add 4 or 2
how do you think about this ?

addi a1, a1, 4 /* Synchronous so updated exception return address to the instruction after the instruction that generated the exeption. */

[BUG] Type mismatch in xTimerCreate, xTimerCreateStatic, and vTimerSetReloadMode uxAutoReload parameters/returns (takes UBaseType_t, but documentation calls for BaseType_t)

Describe the bug
xTimerCreate, xTimerCreateStatic, and vTimerSetReloadMode all take an argument const UBaseType_t uxAutoReload and uxTimerGetReloadMode returns UBaseType_t, yet the API documentation indicates valid values of pdTRUE and pdFALSE (which are defined as type BaseType_t in projdefs.h). This incompatibility is flagged as a type mismatch with a MISRA-C checker (and possibly other static checkers) and requires a cast to UBaseType_t to resolve. I'll note that this is being reported based on a "distribution" from STMicroelectronics, so it's possible that header file is from them, not part of the entire distribution.

Target

  • Development board: NUCLEO-F429ZI
  • Instruction Set Architecture: Cortex-M4
  • IDE and version: IAR Embedded Workbench 8.42.2.24293
  • Toolchain and version: IAR Embedded Workbench 8.42.2.24293

Host

  • Host OS: MS Windows 10 Pro
  • Version: 1909 (18363.900)

To Reproduce

  • Compiling the following w/ MISRA-C checks enabled
        m_hFreeRTOSTimer = xTimerCreateStatic(
            name,
            pdMS_TO_TICKS(m_period_ms),
            isRepeating ? pdTRUE : pdFALSE, // Converts boolean isRepeating to either pdTRUE or pdFALSE
            this,
            TimerExpiredCallback,
            &m_timerControlBlock);
        ASSERT(m_hFreeRTOSTimer != NULL);

causes the following MISRA-C(2004) error: Error[Pm128]: illegal implicit conversion from underlying MISRA type "long" to "unsigned long" (MISRA C 2004 rule 10.1) based on the uxAutoReload being of type BaseType_t, yet the function signatures take a UBaseType_t.

Expected behavior
While I think I've read that FreeRTOS doesn't claim compliance with MISRA-C, this seems like a legitimate issue.

Screenshots
N/A

Additional context
N/A

How to know if an ISR is executing ?

Is it possible to determine whether a method in FreeRTOS is being invoked from the context of an ISR (interrupt service request) or a task at runtime ? If this is not, will there be such a possibility in FreeRTOS in the future ?
Thanks.

[BUG] TaskNotify Indexes missing in trace points

Describe the bug
TaskNotify Index parameters are missing in some trace points. They can be useful for tracing.

Target
N/A

Host
N/A

To Reproduce
N/A

Expected behavior
N/A

Screenshots
N/A

Additional context
N/A

Could provide a .uncrustify.cfg file in root directory

late commits of uncrustify has made some code unreable, and new code submit could also bring code style problems. Therefore I would suggest puting a .uncrustify.cfg in root directory. So pull requests could align to a specify code style before they are merged, and also presenting a chance to find bugs ahead.

[BUG] taskEVENT_LIST_ITEM_VALUE_IN_USE breaks xEventGroupWaitBits behaviour

I create event group with one bit:

auto group = xEventGroupCreate();
xEventGroupSetBits(group, 0x01);

Then I want to block another task until receive this message by calling:
xEventGroupWaitBits(group, 0x01, pdFALSE, pdFALSE, portMAX_DELAY /* 0xFFFFFFFF */);

Unexpectedly this call immediately returns 0 instead to wait for event.

I walked step by step over code and seen that call inside of xEventGroupWaitBits body

        /* The task blocked to wait for its required bits to be set - at this
         * point either the required bits were set or the block time expired.  If
         * the required bits were set they will have been stored in the task's
         * event list item, and they should now be retrieved then cleared. */
        uxReturn = uxTaskResetEventItemValue(); // <<<< actually returns 0x80000001 instead of 0x00

        if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
        {
            taskENTER_CRITICAL();
            {
                /* The task timed out, just return the current event bit value. */
                uxReturn = pxEventBits->uxEventBits; // <<<< here is obtained right 0x0 value

Looks like it fetches result value from list with taskEVENT_LIST_ITEM_VALUE_IN_USE value and isn't wipes off it. And then it passes into wrong code branch.

Target

  • Development board:
    qemu-system-arm -machine mps2-an511 -nographic -rtc clock=vm -icount shift=3 -semihosting

  • Instruction Set Architecture:
    ARM Cortex-M3

  • Toolchain and version:
    clang -target thumbv7m-unknown-none-eabi

Expected behavior
Infinity waiting

Additional context
For this calls I use DPP generated bindings of FreeRTOS headers for Dlang.

[BUG] Uncrustify(?) breaks #warning in ARM_CMx_MPU/portmacro.h

Hello,

When I serached 'V10.3' in PR #166, I noticed that Uncrustify(?) breaks #warning in ARM_CMx_MPU/portmacro.h as follows.

portable\GCC\ARM_CM3_MPU\portmacro.h(300):         #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https: /*www.FreeRTOS.org/FreeRTOS-V10.3.x.html" */
portable\GCC\ARM_CM4_MPU\portmacro.h(389):     #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https: /*www.FreeRTOS.org/FreeRTOS-V10.3.x.html" */
portable\IAR\ARM_CM4F_MPU\portmacro.h(337):     #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https: /*www.FreeRTOS.org/FreeRTOS-V10.3.x.html" */
portable\RVDS\ARM_CM4_MPU\portmacro.h(402):     #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https: /*www.FreeRTOS.org/FreeRTOS-V10.3.x.html" */

i.e.

Something strange:

#warning "~~~. https: /*www.FreeRTOS.org/FreeRTOS-V10.3.x.html" */

Maybe correct:

#warning "~~~. https://www.FreeRTOS.org/FreeRTOS-V10.3.x.html"

Best regards,
NoMaY

[Added]

Probably these weren't caused by uncrustify but maybe caused by beautification like PR #131 and #134. (Theses were already broken before PR #134.)

Best regards,
NoMaY

[Added]

When I searched 'FreeRTOS-V10.3.x.html' in FreeRTOS-Kernel V10.3.1, the following result was obtained about this issue.

portable\GCC\ARM_CM3_MPU\portmacro.h(298):  #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https://www.freertos.org/FreeRTOS-V10.3.x.html"
portable\GCC\ARM_CM4_MPU\portmacro.h(298):  #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https://www.freertos.org/FreeRTOS-V10.3.x.html"
portable\IAR\ARM_CM4F_MPU\portmacro.h(249):     #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https://www.freertos.org/FreeRTOS-V10.3.x.html"
portable\RVDS\ARM_CM4_MPU\portmacro.h(306):     #warning "configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY is not defined. We recommend defining it to 1 in FreeRTOSConfig.h for better security. https://www.freertos.org/FreeRTOS-V10.3.x.html"

Best regards,
NoMaY

[BUG] Uncrustify breaks CCS MSP430X data_model.h file

Describe the bug
Uncrustify (specifically, commit 718178c), broke the formatting of the portable/CCS/MSP430X/data_model.h file. The header comment syntax and the indentation are wrong.

It seems this is one of many such instances, for various assembly files.

Target

  • Development board: MSP-EXP430FR5969
  • Instruction Set Architecture: MSP430
  • Toolchain and version: TI CGT msP430 20.2.0 (LTS)

To Reproduce
Run the FreeRTOS MSP430FR5969 launchpad demo project with at least commit 718178c of FreeRTOS-Kernel.

Expected behavior
The portext.asm file (this includes the erroneous data_model.h) should compile error-free.

Additional context
Reverting the changes introduced in 718178c fix the issue. (I.e., return to the old formatting.)

I am happy to submit a PR with the change reverted, but maybe the number of issues introduced by uncrustify indicate that a broader fix should be applied.

[BUG]: MPU not correctly supported for CM7 core.

Hi,

Describe the bug

the "ARM_CM4F_MPU" port is usable by either the CM4 based CMUs or CM7 ones (except the r0p1 version).

in this port the portEXPECTED_MPU_TYPE_VALUE is forced to 8 regions, while according to the ARM CM7 documentation, the MPU region can be 16 regions depending on the implmentation.

For some targets like the "STM32H7",FreeRTOS will silently fail in this check and the MPU won't be correctly enabled as the regions in this MCU are 16 not 8.

Target

  • STM32H743 eval board.
  • Instruction Set Architecture: [e.g. ARMv7]
  • IDE and version: [EWARM(but valid of other IDEs)]
  • Toolchain and version: [8.30.1]

Host

  • Host OS: [Windows]
  • Version: [10]

To Reproduce

  • Run a FreeRTOS/MPU based application.
  • verify that the MPU is not correctly configured.

regards
Haithem.

Support ARMV8M without trust-zone

In current /portable/ARMv8M, it could support V8M with trust-zone for secure or non-secure build.
However, some chip of V8M cpu core is not including trust-zone feature and current /portable/ARMv8M can't support this kind chip.
Is there any plan to add-on V8M without trust-zone in /portable ?

[BUG]:configPRE_SLEEP_PROCESSING()/configPOST_SLEEP_PROCESSING() argument passed by value.

Hi,

Describe the bug
When the configUSE_TICKLESS_IDLE is enabled, the following piece of code is executed:


configPRE_SLEEP_PROCESSING( xModifiableIdleTime );


if( xModifiableIdleTime > 0 )


{


__dsb( portSY_FULL_READ_WRITE );


__wfi();


__isb( portSY_FULL_READ_WRITE );


}


configPOST_SLEEP_PROCESSING( xExpectedIdleTime );

in both configPRE_SLEEP_PROCESSING() and configPOST_SLEEP_PROCESSING(), the arguments ,respectively , xModifiableIdleTime and xExpectedIdleTime , are passed by value, but If I understood correctly, they can be modified by the user application. Thus they should be passed by reference.

Target

  • Development board: STM32L4 board
  • Instruction Set Architecture: CM4F
  • IDE and version: KEIL, IAR, GCC
  • Toolchain and version: any tootchain.

regards

Function to check if is inside a critical section

I'm porting FreeRTOS to ChibiOS HAL OSAL interface, and one of my needs is a function to tell if I'm inside a critical section or not.

Currently, I'm adding a function to portmacro.h in the architectures I'm working on, which is ARM Cortex Mx. But I need to maintain a fork just because of that function.

Could possibly this functionality be added to FreeRTOS? I can provide a GCC/ARM_CMx Pull Request.

Currently implementation for GCC/ARM_CM3:

portFORCE_INLINE static BaseType_t xPortIsCriticalSection( void )
{
uint32_t ulReturn;

	__asm volatile
	(
		"	mrs %0, basepri	"
		:"=r" ( ulReturn )
	);

	return (ulReturn > 0) ? pdTRUE : pdFALSE;
}

Basically, I'm reading the basepri register, in the CM0 case, I read the PRIMASK register.

Another option would be expose the uxCriticalNesting variable, as it is incremented every call to vPortEnterCritical and decremented on vPortExitCritical.

[BUG] xPortIsInsideInterrupt missing in Cortex M0

Describe the bug

  • The port for Cortex M0 is missing this call.

Target

  • Development board:
  • Instruction Set Architecture: Cortex M0
  • IDE and version:
  • Toolchain and version:

Host

  • Host OS: [e.g. MacOS]
  • Version: [e.g. Mojave 10.14.6]

To Reproduce

Expected behavior

  • The port for M0 should have this.

Screenshots

Additional context

[BUG] "Item Size" Queue propertis numerically not working.

I find one problem (maybe bug) in CMSIS working with FreeRTOS. Working on the STMCubeIDE and programing F103RB (NUCLEO). I create the Queues. Properties "Item Size" set it to "20" (number). I want to convey a structure of this size. Default propertis is "uint16_t" (character string).
During operation, only the first 4 bytes of the structure are transferred.
I debug program and find problem and repear this.
In the file cmsis.os.c replase line 766
with
const osMessageQDef_t os_messageQ_def_##name =
{ (queue_sz), sizeof (type), NULL, NULL }
to
const osMessageQDef_t os_messageQ_def_##name =
{ (queue_sz), type, NULL, NULL }
Delete "sizeof"
After the change, program work good.

[BUG] Case sensitivity issue with MSVC_MinGW portmacro.h

Describe the bug
The MSVC_MinGW version of portmacro.h causes compilation errors when cross-compiling from GNU/Linux to Windows (both x86 and x86_64) since the header files it includes are written in sentence case e.g.: Windows.h whereas the mingw-w64-x86-64-dev package distributes them in lowercase e.g.: windows.h.

While this would not be an issue when compiling from Windows, it does affect those cross-compiling from any case-sensitive operating system such as GNU/Linux to Windows.


Target

  • Development board: N/A
  • Instruction Set Architecture: x86_64-w64-mingw32
  • IDE and version: N/A
  • Toolchain and version: x86_64-w64-mingw32-gcc (GCC) 7.3-win32 20180312

Host

  • Host OS: x86_64 GNU/Linux Kubuntu
  • Version: 20.04 LTS

To Reproduce
Cross-compile the Windows port of FreeRTOS from GNU/Linux or any other case-sensitive operating system that provides the mingw-w64-x86-64-dev package or similar.

Expected behavior
One or more compilation errors are triggered by x86_64-w64-mingw32-gcc each time portmacro.h is either directly or indirectly included by any other source file. The following description is provided by the compiler:

FreeRTOS-Kernel/portable/MSVC-MingW/portmacro.h:31:10: fatal error: Windows.h: No such file or directory
 #include <Windows.h>
          ^~~~~~~~~~~

Screenshots
N/A

Additional context
The solution is rather straightforward: modify the lines mentioned above so lowercase names are used instead. This would not affect those already compiling from Windows and would allow cross-compiling to Windows from case-sensitive platforms such as GNU/Linux.

[BUG] ListItem_t and MiniListItem_t violate strict aliasing rules

Describe the bug
ISO C’s “strict aliasing” rule says (roughly speaking) that the same memory must only be accessed either as the type it really is, or via a pointer to char. For example, an int can be accessed as an int or via a char*, but not via a short*. FreeRTOS breaks this rule: an object of type List_t contains an object of type MiniListItem_t (specifically xListEnd), but sometimes it is accessed via pointers of type ListItem_t * (not MiniListItem_t *). An example of this is in uxListRemove where, if removing the first item in the list, pxItemToRemove->pxPrevious is a ListItem_t * which points at xListEnd, and that pointer is written through in order to set pxItemToRemove->pxPrevious->pxNext, in violation of the strict aliasing rule.

Using aggressive optimizations in GCC 9, this generates bad code in xTaskResumeAll where pxTCB is not reloaded on each iteration of the first loop iterating over xPendingReadyList, resulting in the same TCB being added to the ready list more than once.

This could easily be fixed. Simply delete the listFIRST_ITEM_INTEGRITY_CHECK_VALUE, xItemValue, pxNext, and pxPrevious members from ListItem_t and replace them with an instance of MiniListItem_t (which contains exactly those members, and therefore does not change the memory layout of the structure at all), and fix up the resulting compile errors (which involves changing some ListItem_t * pointers to MiniListItem_t *). This should be totally standards-compliant. Now all iteration happens using the MiniListItem_t type, so the strict aliasing rule is obeyed. As long as a pointer is definitely pointing at a real item (not xListEnd), casting from MiniListItem_t * to ListItem_t * is also legal, because that is a cast between a pointer to a structure and a pointer to its first member, which is legal in both directions.

I would be happy to submit a PR if you agree that this should be changed.

Technically speaking I believe the Static types also constitute violations of the strict aliasing rule (for example, FreeRTOS accesses an object of type struct xSTATIC_TCB through a pointer of type struct tskTaskControlBlock *), but so far I have not seen this to cause actual problems, and it seems less likely to do so since the object is never actually accessed via its real type.

Target

  • Instruction Set Architecture: ARMv7-M
  • Toolchain and version: GCC 9.3.0

Host

  • Host OS: Linux
  • Version: Kernel 5.4.28

[BUG] portVECTACTIVE_MASK incorrect in Cortex M4F port

Describe the bug
The definition of portVECTACTIVE_MASK seems to be incorrect in the cortex M4 ports. Based on the ARMv7-M Architecture Reference Manual (Page B3-655) it seems like the correct mask for portVECTACTIVE_MASK should be 0x1FF, but is 0xFF the cortex M4 port and perhaps others.

Target

  • Development board: [n/a]
  • Instruction Set Architecture: [Cortex M4]
  • IDE and version: [n/a]
  • Toolchain and version: [n/a]

Host

  • Host OS: [n/a]
  • Version: [n/a]

To Reproduce
n/a

Expected behavior
n/a

Screenshots
image

[BUG] uxListRemove hit a data abort issue.

Describe the bug
We hit a data abort issue in our application, which creates one event group, and different tasks can set the same event. For example, task1 is blocked by event1, where both task2 and task3 can set event1. When task2 set event1, task1 will be moved from blocked list to ready list. Before task1 is blocked by event1 again, if task3 set event1, we hit the data abort issue.

We worked around this issue by making some small changes in tasks.c and list.c, It basically checks if 'pxItemToRemove->pxContainer' is empty before removing it. Please find the diff attached. diff.txt

The changes have zero impact on the existing kernel code. I was wondering if these changes can be merged into the master branch?

[BUG] Wrong critical section handling before the scheduler is started

Describe the bug
Before the scheduler has started, any call to FreeRTOS functions that require a critical section will mess up the interrupt enabling status.
This includes calls made by vTaskStartScheduler() itself, e.g. to create the idle task.

Target

  • Development board: irrelevant (STM32F746NG)
  • Instruction Set Architecture: ARM_CM7
  • IDE and version: irrelevant (Atollic TrueSTUDIO 9.2.0)
  • Toolchain and version: irrelevant (arm-atollic-eabi-gcc 6.3.1 20170215 (release) [ARM/embedded-6-branch revision 245512])

Host

  • Host OS: irrelevant (Windows)
  • Version: irrelevant (Windos 10 Pro)

To Reproduce

  • Just follow the execution of vTaskStartScheduler() in any ARM_CM7 project
    I'm also attaching a sample project created with STM32CubeMX for my MCU (STM32F746NG), with just FreeRTOS enabled; STM32CubeMX uses an older version (10.2.1), but the problem is exactly the same. In "Core/Src/main.c", you'll find the calls to MX_FREERTOS_Init() -to initializes the tasks- and osKernelStart() -to start the scheduler.

Additional context
In my init code, I first create a task (and possibly queues, mutexes, etc.), then start the scheduler.
The problem is that

  • in the task initialization code, there are critical sections, which use taskENTER_CRITICAL() and taskEXIT_CRITICAL()
  • these functions reference the global variable uxCriticalNesting
  • uxCriticalNesting is statically initialised to 0xaaaaaaaa, and it only gets initialized to 0 when the scheduler is started (vTaskStartScheduler()).
    This means that taskENTER_CRITICAL() increments uxCriticalNesting and disables interrupts, and taskEXIT_CRITICAL() decrements uxCriticalNesting, but it doesn't re-enable interrupts, since uxCriticalNesting is back to 0xaaaaaaaa, rather than back to 0. So, interrupts remain disabled until the scheduler is actually started.

I'm using FreeRTOS Kernel V10.3.1, with the GCC ARM_CM7 port (though at a first glance it seems that FreeRTOS Kernel V10.4.3 behaves the same).
This is where uxCriticalNesting is defined:
https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/portable/GCC/ARM_CM7/r0p1/port.c#L140
static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;

These are the definitions of (the port-specific versions of) taskENTER_CRITICAL() and taskEXIT_CRITICAL()
https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/portable/GCC/ARM_CM7/r0p1/port.c#L396
https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/portable/GCC/ARM_CM7/r0p1/port.c#L413
void vPortEnterCritical( void )
{
portDISABLE_INTERRUPTS();
uxCriticalNesting++;
...
}
void vPortExitCritical( void )
{
configASSERT( uxCriticalNesting );
uxCriticalNesting--;

	if( uxCriticalNesting == 0 )
	{
		portENABLE_INTERRUPTS();
	}
}

Note that "disabling interrupts" doesn't mean globally masking them (using the "cpsie i" and "cpsid i" ARM instructions); rather, it means altering BASEPRI (which only masks interrupts with priority no higher than that of FreeRTOS). See here:
https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/portable/GCC/ARM_CM7/r0p1/portmacro.h#L100

Here is a summary of what is happening. I'm listing function calls and variable values.

// static init: uxCriticalNesting = 0xaaaaaaaa, ints enabled
xTaskCreateStatic()
prvAddNewTaskToReadyList()
taskENTER_CRITICAL() // uxCriticalNesting = 0xaaaaaaab, ints disabled
taskEXIT_CRITICAL() // uxCriticalNesting = 0xaaaaaaaa, ints disabled
vTaskStartScheduler()
xTaskCreateStatic() // for the idle task
prvAddNewTaskToReadyList()
taskENTER_CRITICAL() // uxCriticalNesting = 0xaaaaaaab, ints disabled
taskEXIT_CRITICAL() // uxCriticalNesting = 0xaaaaaaaa, ints disabled
xTimerCreateTimerTask()
prvCheckForValidListAndQueue()
taskENTER_CRITICAL() // uxCriticalNesting = 0xaaaaaaab, ints disabled
taskEXIT_CRITICAL() // uxCriticalNesting = 0xaaaaaaaa, ints disabled
prvInitialiseNewQueue()
xQueueGenericReset()
taskENTER_CRITICAL() // uxCriticalNesting = 0xaaaaaaab, ints disabled
taskEXIT_CRITICAL() // uxCriticalNesting = 0xaaaaaaaa, ints disabled
xTaskCreateStatic()
prvAddNewTaskToReadyList()
taskENTER_CRITICAL() // uxCriticalNesting = 0xaaaaaaab, ints disabled
taskEXIT_CRITICAL() // uxCriticalNesting = 0xaaaaaaaa, ints disabled
// from now on, the behavior seems correct; it actually manages to fix the problem caused by the previous calls
portDISABLE_INTERRUPTS(); // this just disables interrupts, without changing uxCriticalNesting; it's done on purpose by vTaskStartScheduler(), see the comment for https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/tasks.c#L2059
xPortStartScheduler()
uxCriticalNesting=0 // https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/portable/GCC/ARM_CM7/r0p1/port.c#L363
prvPortStartFirstTask()
cpsie i
svc 0
vPortSVCHandler()
msr basepri, r0 // this re-enables interrupts; now we are in a clean working condition: interrupts enabled, uxCriticalNesting = 0
bx r14 // now the first task is actually started

This summary also shows that the problem is not in my creating a task beforehand; it exists even within vTaskStartScheduler(), with the creation of the idle task and the timer task.
However, the problem is worse if I create objects beforehand, since interrupts remain disabled for longer.

A straightforward and very lightweight solution would be to just initialize uxCriticalNesting to 0, statically.
Is there any reason to have it initialized to 0xaaaaaaaa? It seems that no function ever checks for this "uninitialized" value, and debuggers should have other better ways to detect whether the scheduler has been inited/started yet.

As an aside: is there any reason why there are these assertions in port.c?
configASSERT( uxCriticalNesting == 1000UL );
configASSERT( uxCriticalNesting == ~0UL );
rather than a simple:
configASSERT( 0 );
test_freertos.zip

[BUG] Recently added .gitattributes converts line endings to CRLF on Linux

Describe the bug
After cloning the repository all files are modified silently bu git converting LF to CRLF

xxx@yyy:/mnt/userdata/xxx/work/ext$ git clone [email protected]:FreeRTOS/FreeRTOS-Kernel.git
Cloning into 'FreeRTOS-Kernel'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 151604 (delta 0), reused 0 (delta 0), pack-reused 151600
Receiving objects: 100% (151604/151604), 104.39 MiB | 8.30 MiB/s, done.
Resolving deltas: 100% (109604/109604), done.
cd FreeRTOS-Kernel
xxx@yyy:/mnt/userdata/xxx/work/ext/FreeRTOS-Kernel$ git status
On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git restore ..." to discard changes in working directory)
modified: .github/CONTRIBUTING.md
modified: .github/SECURITY.md
modified: croutine.c
modified: event_groups.c
modified: include/FreeRTOS.h
modified: include/StackMacros.h
modified: include/atomic.h
modified: include/croutine.h
modified: include/deprecated_definitions.h
modified: include/list.h
modified: include/message_buffer.h
modified: include/mpu_prototypes.h
modified: include/mpu_wrappers.h
modified: include/portable.h
modified: include/projdefs.h
modified: include/semphr.h
modified: include/stack_macros.h
modified: include/stream_buffer.h
modified: list.c
modified: portable/ARMv8M/copy_files.py
...

[BUG] incorrect implementation of pvPortMalloc

Describe the bug

The function pvPortMalloc() is used to allocate memory for the required size.
The parameter xWantedSize indicates the length of memory required. However, when the required memory block size is zero. The memory pointer variable pvReturn will keep as NULL. If the configuration configUSE_MALLOC_FAILED_HOOK is enabled, it will recognize the variable xWantedSize valued zero as an error and handle it with the function vApplicationMallocFailedHook() as shown in

vApplicationMallocFailedHook();

Target

  • Development board: STM32H7B3I-DK and STM32H7B3I-EVAL
  • Instruction Set Architecture: Thumb
  • IDE and version: STMCubeIDE 1.4.0
  • Toolchain and version: Default toolchain of STMCubeIDE

Host

  • Host OS: Ubuntu
  • Version: 18.04 LTS

To Reproduce

  • STM32H7 MCU package. STM32H7B3I-DK/Domonstrations/ClockAndWeather. Default configuration for debug.
  • Run the example and the firmware loops infinitely.

Expected behavior

Normally, if the variable xWantedSize is zero, a pointer should be returned successfully, no matter the NULL pointer or a real pointer with the next available heap address.
As a result, the firmware could continue to execution.

Additional

This bug is also reported to STM as shown in STMicroelectronics/STM32CubeH7#85 where I find it.

Unable to compile FreeRTOS-Kernel files with Keil Compiler Version 6

Hi,

Using STM32CubeMX, I've generated a project for understanding how to create tasks. The (possibly) used FreeRTOS version is 10.2.1 with CMSIS-RTOS version 2.00

When using Keil ARM Compiler version 6 to compile the code, I am observing several concerns, possibly because the FreeRTOS-Kernel code is still compilable with help of Keil ARM Compiler Version 5

The files under question (port.c and portmacro.h) are available under folder:
https://github.com/FreeRTOS/FreeRTOS-Kernel/tree/master/portable/RVDS/ARM_CM4F

I have made modifications to the files and brought them up to a level wherein the compiler is now not throwing errors. I however need your help with how to correctly use the extern variables inside the ASM code. I am also concerned about how to handle C variables in assembly.

I have used the __CC_ARM macro to separate out the assembly code which can be compiled with Keil Compiler Version 5 from the one that can be compiled with Keil Compiler Version 6.

I hereby request you to please review the files and help me with an updated file ASAP (asit is crucial to my project).

Please help.

Thanks,
Rajeev

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.