Compare commits

...
37 Commits
Author SHA1 Message Date
cpq c2d95cc19b Nit 2026-10-05 14:00:38 +01:00
cpq 4aa0a243f9 Nit 2026-10-05 13:17:46 +01:00
cpq 65a7996ef9 nit 2026-10-05 12:59:23 +01:00
Sergey Lyubka 5879c3cbf2 Merge pull request #3719 from cesanta/azure
Add support for MS Azure MQTT
2026-10-05 12:43:41 +01:00
cpq cf9d56be79 Add support for MS Azure MQTT 2026-10-05 12:41:56 +01:00
cpq da82df2041 Add firmware.signed.bin target 2026-10-03 16:50:02 +01:00
Sergey Lyubka 954eb07b6d Merge pull request #3718 from cesanta/cr
Move crash handler to src/health.c
2026-10-02 13:00:56 +01:00
cpq d7e708b9bc Move crash handler to src/health.c 2026-10-02 12:47:05 +01:00
robertc2000 ce35cbf586 Merge pull request #3716 from cesanta/crash
Print crash record optionally
2026-10-01 14:48:36 +03:00
cpq 3aa5f2a1fd Print crash record optionally 2026-10-01 14:42:16 +03:00
cpq 1b0906510b Rename MG_OTA_FIRMWARE_VERSION -> MG_FIRMWARE_VERSION, rw612 nits 2026-10-01 10:10:42 +01:00
Sergey Lyubka 8a116d9289 Merge pull request #3715 from cesanta/is_resp
Remove c->is_resp, keep it private to http.c
2026-10-01 08:25:38 +01:00
cpq 71e0176944 Remove c->is_resp, keep it private to http.c 2026-09-30 15:12:54 +01:00
Sergey Lyubka bba5a0ca3a Merge pull request #3710 from cesanta/crash-report
Report the crash log to mdash
2026-09-30 15:11:13 +01:00
novlean 9c388b5f19 Merge pull request #3714 from cesanta/novlean-patch-1
Fix link formatting for STM32H5 article
2026-09-30 15:04:13 +02:00
novlean 8afa940acf Fix link formatting for STM32H5 article 2026-09-30 15:03:59 +02:00
novlean df1a409b21 Merge pull request #3713 from cesanta/novlean-patch-1
Add new articles to README links section
2026-09-30 15:03:21 +02:00
novlean 7ec403341c Add new articles to README links section 2026-09-30 15:02:57 +02:00
cpq 8e0c765c2c Nit - LFS include path 2026-09-28 16:50:50 +01:00
cpq 883e0a981f Reuse descriptors, pick minimum 2026-09-28 16:22:32 +01:00
cpq ff1fb5c745 Update pack 2026-09-28 16:04:15 +01:00
robert 795f16d5fb Report the crash log to mdash 2026-09-28 14:05:58 +03:00
cpq 51773ecea3 Add LFS-enabled project 2026-09-28 11:32:15 +01:00
cpq 2834aa57ee Not needed, minimal has it 2026-09-28 08:00:52 +01:00
Sergey Lyubka e2b5d7175f Merge pull request #3709 from cesanta/dirlist
Remove MG_ENABLE_DIRLIST, add mg_http_serve_opts :: enable_dir_listing
2026-09-26 15:46:35 +01:00
cpq a419e16f26 Remove MG_ENABLE_DIRLIST, add mg_http_serve_opts :: enable_dir_listing 2026-09-26 15:40:43 +01:00
Sergey Lyubka 789372c5b3 Merge pull request #3708 from cesanta/lfs
LFS amendments
2026-09-26 13:00:29 +01:00
cpq 81f6acbce7 LFS nits 2026-09-26 12:52:30 +01:00
Sergey Lyubka 7fa96f3a38 Merge pull request #3706 from cesanta/crash-report
Add stacktrace example
2026-09-25 13:18:24 +01:00
Sergey Lyubka 876cf5605f Merge pull request #3707 from cesanta/dash
Adjust dash to use core file manager
2026-09-25 13:09:54 +01:00
robert 8df146b1b8 Add stacktrace example 2026-09-25 10:52:15 +03:00
cpq f62f3545b4 Adjust dash to use core file manager 2026-09-24 17:04:32 +01:00
robert 4d6fa4b91c ota_rw612: ensure source buffer is aligned 2026-09-24 15:26:18 +03:00
Sergey Lyubka 1be11a66e3 Merge pull request #3705 from cesanta/filemgr
Implement HTTP file manager in the http core
2026-09-24 08:46:19 +01:00
cpq d1060d247b Directory listing as JSON 2026-09-23 15:54:04 +01:00
Sergey Lyubka 002c9df3de Merge pull request #3703 from cesanta/up
Replace mg_http_start_* with streaming uploads
2026-09-22 13:26:27 +01:00
cpq fa34b7439a Replace mg_http_start_* with streaming uploads 2026-09-22 11:18:48 +01:00
193 changed files with 195672 additions and 2523 deletions

No files matched your search

+1 -1
View File
@@ -486,7 +486,7 @@ embedded devices and needs only a few lines added to `mongoose_config.h`:
```c ```c
#define MG_OTA_URL "https://mongoose.ws/ota/u/PREFIX/ota.json" // Copy from instructions panel #define MG_OTA_URL "https://mongoose.ws/ota/u/PREFIX/ota.json" // Copy from instructions panel
#define MG_OTA_FIRMWARE_VERSION "MY_PRODUCT_1.4.2" // Change this #define MG_FIRMWARE_VERSION "MY_PRODUCT_1.4.2" // Change this
``` ```
No backend programming required. The device registers itself and checks in at No backend programming required. The device registers itself and checks in at
+2
View File
@@ -220,6 +220,8 @@ Technical guides and deep dives into embedded web servers, WebUI integration and
- [STM32 Ethernet and caches](https://mongoose.ws/articles/stm32-ethernet-and-cache/) - [STM32 Ethernet and caches](https://mongoose.ws/articles/stm32-ethernet-and-cache/)
- [NXP RW612 OTA Firmware Update](https://mongoose.ws/articles/rw612-ota-firmware-update/) - [NXP RW612 OTA Firmware Update](https://mongoose.ws/articles/rw612-ota-firmware-update/)
- [lwIP vs Mongoose - TCP/IP Stack Integration Benchmark](https://mongoose.ws/articles/lwip-vs-mongoose-tcpip-stack-integration/) - [lwIP vs Mongoose - TCP/IP Stack Integration Benchmark](https://mongoose.ws/articles/lwip-vs-mongoose-tcpip-stack-integration/)
- [Embedded TCP/IP Stacks Comparison](https://mongoose.ws/embedded-tcpip-stack-comparison/)
- [STM32H5 File System on Internal Flash: LittleFS + Mongoose](https://mongoose.ws/articles/stm32h5-file-system-on-internal-flash/)
## Contributions ## Contributions
+591 -586
View File
File diff suppressed because it is too large. Load diff
+85 -151
View File
@@ -103,8 +103,9 @@ extern "C" {
#include <sys/types.h> #include <sys/types.h>
#include <time.h> #include <time.h>
#ifndef MG_PATH_MAX
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#define MG_ENABLE_DIRLIST 0 #endif
#endif #endif
@@ -127,8 +128,9 @@ extern "C" {
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#ifndef MG_PATH_MAX
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#define MG_ENABLE_DIRLIST 0 #endif
#endif #endif
@@ -158,10 +160,6 @@ extern "C" {
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 0
#endif
#ifndef MG_ENABLE_TCPIP #ifndef MG_ENABLE_TCPIP
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack #define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
@@ -327,10 +325,6 @@ extern "C" {
#define MG_ENABLE_POSIX_FS 1 #define MG_ENABLE_POSIX_FS 1
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 1
#endif
#ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS #ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS
#define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U #define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U
#endif #endif
@@ -438,10 +432,6 @@ static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 0
#endif
#ifndef MG_ENABLE_TCPIP #ifndef MG_ENABLE_TCPIP
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack #define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
#endif #endif
@@ -890,10 +880,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 1
#endif
#ifndef MG_PATH_MAX #ifndef MG_PATH_MAX
#define MG_PATH_MAX FILENAME_MAX #define MG_PATH_MAX FILENAME_MAX
#endif #endif
@@ -1075,10 +1061,6 @@ typedef int socklen_t;
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR) #define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 1
#endif
#ifndef SIGPIPE #ifndef SIGPIPE
#define SIGPIPE 0 #define SIGPIPE 0
#endif #endif
@@ -1363,10 +1345,6 @@ struct timeval {
#define MG_ENABLE_WINSOCK 1 #define MG_ENABLE_WINSOCK 1
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 0
#endif
#ifndef MG_ENABLE_CUSTOM_RANDOM #ifndef MG_ENABLE_CUSTOM_RANDOM
#define MG_ENABLE_CUSTOM_RANDOM 0 #define MG_ENABLE_CUSTOM_RANDOM 0
#endif #endif
@@ -1416,7 +1394,7 @@ struct timeval {
#endif #endif
#ifndef MG_ENABLE_POSIX_FS #ifndef MG_ENABLE_POSIX_FS
#define MG_ENABLE_POSIX_FS 0 #define MG_ENABLE_POSIX_FS MG_ENABLE_LFS
#endif #endif
#ifndef MG_INVALID_SOCKET #ifndef MG_INVALID_SOCKET
@@ -1512,6 +1490,10 @@ struct timeval {
#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN #define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN
#endif #endif
#ifndef MG_ENABLE_HEALTH
#define MG_ENABLE_HEALTH 0
#endif
@@ -1929,6 +1911,7 @@ void mg_timer_poll(struct mg_timer **head, uint64_t new_ms);
// Flags returned by mg_fs.st() and passed to mg_fs.open(). // Flags returned by mg_fs.st() and passed to mg_fs.open().
enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4, MG_FS_EXCL = 8 }; enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4, MG_FS_EXCL = 8 };
@@ -1966,6 +1949,7 @@ void mg_fs_close(struct mg_fd *fd);
// Sequential directory iterator. Call repeatedly with the same buf/len; // Sequential directory iterator. Call repeatedly with the same buf/len;
// each call fills buf with the next entry name. Returns false when done. // each call fills buf with the next entry name. Returns false when done.
// Note: make sure buf[0] == 0 before the first call
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len); bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len);
// Reads the entire file into a heap-allocated buffer. The returned mg_str is // Reads the entire file into a heap-allocated buffer. The returned mg_str is
@@ -2005,6 +1989,26 @@ struct mg_str mg_unpacked(const char *path);
extern const struct mg_mem_file mg_packed_files[]; extern const struct mg_mem_file mg_packed_files[];
#if MG_ENABLE_LFS
#include <fcntl.h>
#include <lfs.h>
#ifndef DT_DIR
#define DT_DIR 4
#endif
#ifndef DT_REG
#define DT_REG 8
#endif
struct dirent {
char d_name[LFS_NAME_MAX + 1];
unsigned char d_type;
};
typedef struct mg_lfs_fd DIR;
#endif
@@ -2488,7 +2492,6 @@ struct mg_connection {
unsigned is_closing : 1; // Close and free immediately on next poll unsigned is_closing : 1; // Close and free immediately on next poll
unsigned is_full : 1; // Pause incoming reads until cleared unsigned is_full : 1; // Pause incoming reads until cleared
unsigned is_tls_throttled : 1; // TLS write was throttled; retry pending unsigned is_tls_throttled : 1; // TLS write was throttled; retry pending
unsigned is_resp : 1; // HTTP: response is still being generated
unsigned is_readable : 1; // Socket is ready to read (epoll/select) unsigned is_readable : 1; // Socket is ready to read (epoll/select)
unsigned is_writable : 1; // Socket is ready to write (epoll/select) unsigned is_writable : 1; // Socket is ready to write (epoll/select)
}; };
@@ -2665,6 +2668,9 @@ struct mg_http_serve_opts {
const char *mime_types; // Additional MIME types: "ext1=type1,ext2=type2". NULL for defaults only const char *mime_types; // Additional MIME types: "ext1=type1,ext2=type2". NULL for defaults only
const char *page404; // Path to a custom 404 page, e.g. "/404.html". NULL for built-in const char *page404; // Path to a custom 404 page, e.g. "/404.html". NULL for built-in
struct mg_fs *fs; // Filesystem to use. NULL defaults to POSIX struct mg_fs *fs; // Filesystem to use. NULL defaults to POSIX
bool enable_delete; // Allow to DELETE files
bool enable_upload; // Allow to POST/PUT files
bool enable_dir_listing; // Enable directory listing
}; };
// A single part of a multipart/form-data body, filled by mg_http_next_multipart(). // A single part of a multipart/form-data body, filled by mg_http_next_multipart().
@@ -2738,8 +2744,11 @@ struct mg_connection *mg_http_connect(struct mg_mgr *, const char *url,
// mg_http_listen(), mg_http_serve_file(), mg_http_reply(), mg_match() // mg_http_listen(), mg_http_serve_file(), mg_http_reply(), mg_match()
// Notes: // Notes:
// Call from an MG_EV_HTTP_MSG handler. The uri in hm is mapped under // Call from an MG_EV_HTTP_MSG handler. The uri in hm is mapped under
// opts->root_dir. Directory listing depends on MG_ENABLE_DIRLIST; SSI uses // opts->root_dir. opts->enable_dir_listing enables directory listing; SSI
// opts->ssi_pattern when configured. // uses opts->ssi_pattern when configured. opts->enable_delete enables
// DELETE; opts->enable_upload enables POST/PUT, writing the whole body to
// a file - see mg_http_serve_upload() to also stream big uploads without
// buffering.
void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm, void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
const struct mg_http_serve_opts *); const struct mg_http_serve_opts *);
@@ -2747,6 +2756,15 @@ void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
void mg_http_serve_file(struct mg_connection *, struct mg_http_message *hm, void mg_http_serve_file(struct mg_connection *, struct mg_http_message *hm,
const char *path, const struct mg_http_serve_opts *); const char *path, const struct mg_http_serve_opts *);
// Streams a big POST/PUT upload straight to a file, instead of buffering the
// whole body. Optional companion to mg_http_serve_dir(): call this from
// MG_EV_HTTP_HDRS with the same opts, and keep calling mg_http_serve_dir()
// from MG_EV_HTTP_MSG as usual - it still handles uploads this function skips.
// Does nothing unless opts->enable_upload is set, the method is POST or PUT,
// and Content-Length is known and big enough.
void mg_http_serve_upload(struct mg_connection *, struct mg_http_message *hm,
const struct mg_http_serve_opts *);
// Sends a complete HTTP response with Content-Length. // Sends a complete HTTP response with Content-Length.
// //
// Example: // Example:
@@ -2793,20 +2811,6 @@ void mg_http_creds(struct mg_http_message *, char *, size_t, char *, size_t);
long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm, long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
struct mg_fs *fs, const char *dir, size_t max_size); struct mg_fs *fs, const char *dir, size_t max_size);
// Streams the raw request body into dir/name via fs. Non-blocking: installs an
// internal handler and returns immediately. fn is called with NULL on success
// or an error string on failure.
void mg_http_start_upload(struct mg_connection *c, struct mg_http_message *hm,
struct mg_str name, struct mg_str dir,
struct mg_fs *fs,
void (*fn)(struct mg_connection *, const char *));
// Starts an OTA firmware update from an HTTP POST upload.
// Calls mg_ota_begin/write/end internally; fn is called with NULL on success,
// or an error string on failure.
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
void (*fn)(struct mg_connection *, const char *));
// Sends a 401 Unauthorized response with a Basic Auth WWW-Authenticate challenge. // Sends a 401 Unauthorized response with a Basic Auth WWW-Authenticate challenge.
void mg_http_bauth(struct mg_connection *, const char *user, const char *pass); void mg_http_bauth(struct mg_connection *, const char *user, const char *pass);
@@ -2825,7 +2829,7 @@ struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v);
// Full examples: // Full examples:
// tutorials/http/file-upload-html-form, tutorials/http/http-server // tutorials/http/file-upload-html-form, tutorials/http/http-server
// Related APIs: // Related APIs:
// mg_http_listen(), mg_http_start_upload() // mg_http_listen(), mg_http_stream_body()
// Notes: // Notes:
// Call from an MG_EV_HTTP_MSG handler after the full request body is // Call from an MG_EV_HTTP_MSG handler after the full request body is
// received. part.name, part.filename, and part.body are zero-copy slices into // received. part.name, part.filename, and part.body are zero-copy slices into
@@ -2836,27 +2840,33 @@ size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *);
int mg_http_status(const struct mg_http_message *hm); int mg_http_status(const struct mg_http_message *hm);
// Streams a POST/PUT body to a callback as it arrives, without buffering it. // Streams a POST/PUT body to a callback as it arrives, without buffering it.
// Call it from your connection handler on every event. // Call it from an MG_EV_HTTP_HDRS handler, after matching the request, e.g.
// with mg_match(). Returns true if it took over the connection, false if the
// request is not POST/PUT, is chunked, or has no Content-Length.
// //
// Callback upload_fn(hm, data, user_data) is called: // Callback upload_fn(hm, data, user_data) is called:
// - at start: hm is set, data is NULL. Open the file, set user_data. // - at start: hm is set. Open the file, set *user_data.
// - per chunk: hm is NULL, data is set. Chunks are 512 bytes aligned // - per chunk: data is set, 512 byte aligned except the last. Not called
// except the last one. // again after a failure.
// - at end: both NULL. Close the file. // - at end: both NULL. Always called once, also when the connection drops
// After the last chunk, "200 ok" is sent and the connection is drained. // early, so release resources here. A truncated body looks like a complete
// one: validate before committing.
// Return true on success, false on error.
// Example: // Example:
// mg_http_stream_body(c, ev, ev_data, mg_str("/fs/*"), upload); // if (ev == MG_EV_HTTP_HDRS && mg_match(hm->uri, mg_str("/fs/*"), NULL) {
// mg_http_stream_body(c, hm, upload, NULL));
// }
// Full example: // Full example:
// tutorials/http/file-upload-single-post // tutorials/http/file-upload-single-post
// Related APIs: // Related APIs:
// mg_http_start_upload(), mg_http_start_ota() // mg_http_listen(), mg_http_next_multipart()
// Notes: // Notes:
// Requires Content-Length, chunked bodies are not streamed. user_data is // After it returns true, this function hijacks the connection. Existing event
// &c->fn_data. While streaming, c->pfn is NULL // handler not called, hm is invalid, c->data and c->fn_data are modified
void mg_http_stream_body(struct mg_connection *c, int ev, void *ev_data, bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
struct mg_str uri_pattern, bool (*upload_fn)(struct mg_http_message *,
void (*upload_fn)(struct mg_http_message *, struct mg_str *, void **user_data),
struct mg_str *, void **user_data)); void *user_data);
void mg_http_serve_ssi(struct mg_connection *c, const char *root, void mg_http_serve_ssi(struct mg_connection *c, const char *root,
@@ -4642,9 +4652,7 @@ struct mg_field_set {
// fn sets *index = -1 to signal end of iteration. // fn sets *index = -1 to signal end of iteration.
// Size query: framework sets *index = -1 before fn(READ); fn // Size query: framework sets *index = -1 before fn(READ); fn
// sets *index = total size // sets *index = total size
bool (*get_dir)(const struct mg_dash_user *u, char *buf, struct mg_field_set *next; // Next set in the list
size_t len); // Non-NULL: file array
struct mg_field_set *next; // Next set in the list
}; };
// Custom URI handler, registered with MG_DASH_REGISTER_CUSTOM_HANDLER() // Custom URI handler, registered with MG_DASH_REGISTER_CUSTOM_HANDLER()
@@ -4665,6 +4673,9 @@ struct mg_dash {
int session_auto_expiration_seconds; // Session lifetime, 0: 1 hour default int session_auto_expiration_seconds; // Session lifetime, 0: 1 hour default
struct mg_dash_user *guest; // Used when authenticate == NULL struct mg_dash_user *guest; // Used when authenticate == NULL
struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix
// Resolves the built-in file manager's root dir for user u, e.g. per-user
// upload directories. NULL: file manager disabled
bool (*files_dir)(const struct mg_dash_user *u, char *buf, size_t len);
}; };
#define MG_DASH_ADD_FIELD_SET(dash_, set_) \ #define MG_DASH_ADD_FIELD_SET(dash_, set_) \
@@ -4690,43 +4701,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data);
// array size if *set->index < 0, or a single element update otherwise // array size if *set->index < 0, or a single element update otherwise
void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *); void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *);
// Default reader for file-backed array sets (set->get_dir != NULL)
// Usage example - this is a complete implemenation of the file manager:
// ```c
// static struct file {
// int index;
// char name[64];
// size_t size;
// uint64_t checksum;
// } s_file;
// static struct mg_field_set set_files;
//
// static bool get_dir(const struct mg_dash_user *u, char *buf, size_t len) {
// (void) u;
// mkdir("/tmp/dashboard", 0755);
// mg_snprintf(buf, len, "%s", "/tmp/dashboard");
// return true;
// }
//
// static struct mg_field fields_files[] = {
// {"name", MG_VAL_STR, s_file.name, sizeof(s_file.name)},
// {"size", MG_VAL_UINT64, &s_file.size, 0},
// {"checksum", MG_VAL_UINT64, &s_file.checksum, sizeof(s_file.checksum)},
// {NULL, MG_VAL_INT, NULL, 0},
// };
//
// static bool files_fn(enum mg_dash_op op, struct mg_dash_user *u) {
// if (op == MG_DASH_WRITE) return s_uploads_enabled && u->level >= 7;
// if (op != MG_DASH_READ) return false;
// if (!mg_dash_dir_read(&set_files, u)) return false;
// s_file.checksum = 0; // Mock to show how to set custom fields
// return true;
// }
//
// static struct mg_field_set set_files = {"files", fields_files, files_fn, &s_file.index, get_dir, NULL};
// ```
bool mg_dash_dir_read(struct mg_field_set *set, struct mg_dash_user *u);
// Helper forward declarations for Mongoose CMSIS pack modules // Helper forward declarations for Mongoose CMSIS pack modules
extern struct mg_mgr g_mgr; extern struct mg_mgr g_mgr;
extern void mg_dash_init(struct mg_mgr *); extern void mg_dash_init(struct mg_mgr *);
@@ -4738,7 +4712,7 @@ extern void mg_mqtt_poll(struct mg_mgr *);
// This is a low-level OTA API, not intended to be called directly by users. // This is a low-level OTA API, not intended to be called directly by users.
// Users are provided with a higher-level API: // Users are provided with a higher-level API:
// - defining MG_OTA_URL enables HTTP or HTTPS pull-based updates // - defining MG_OTA_URL enables HTTP or HTTPS pull-based updates
// - mg_http_start_ota() enables push-based updates // - mg_http_stream_body() enables push-based updates
// //
// However, it is possible to use the mg_ota_* API directly. Below is the // However, it is possible to use the mg_ota_* API directly. Below is the
// example code of a function that is called repeatedly. It expects the // example code of a function that is called repeatedly. It expects the
@@ -4889,7 +4863,7 @@ enum {
// needs to be defined. Fetches metadata_url, which must // needs to be defined. Fetches metadata_url, which must
// return a JSON object like: // return a JSON object like:
// { "version": "1.2.3", "url": "FIRMWARE_URL", "size": 324645 } // { "version": "1.2.3", "url": "FIRMWARE_URL", "size": 324645 }
// If the server version differs from MG_OTA_FIRMWARE_VERSION, downloads // If the server version differs from MG_FIRMWARE_VERSION, downloads
// FIRMWARE_URL and performs the OTA update. fn is called on every outcome: // FIRMWARE_URL and performs the OTA update. fn is called on every outcome:
// NULL on successful flash, "Same version" when already up to date, or an // NULL on successful flash, "Same version" when already up to date, or an
// error string on failure. Pass NULL to use the default handler which logs // error string on failure. Pass NULL to use the default handler which logs
@@ -4916,8 +4890,8 @@ void mg_ota_url_check(struct mg_mgr *mgr, const char *metadata_url,
#endif #endif
// Firmware version for mg_ota_poll(). Settable in mongoose_config.h // Firmware version for mg_ota_poll(). Settable in mongoose_config.h
#ifndef MG_OTA_FIRMWARE_VERSION #ifndef MG_FIRMWARE_VERSION
#define MG_OTA_FIRMWARE_VERSION "1.0.0" #define MG_FIRMWARE_VERSION "1.0.0"
#endif #endif
// Maximum version string length // Maximum version string length
@@ -4944,30 +4918,7 @@ void mg_ota_device_id(char *buf, size_t len);
// directly. // directly.
void mg_ota_poll(struct mg_mgr *); void mg_ota_poll(struct mg_mgr *);
// Device health monitoring // Device health monitoring
//
// Keeps a small record in a RAM region that survives a warm reset, so a device
// can tell why it restarted. The record holds a boot counter, the uptime this
// boot has reached, and the reset reason reported by the hardware. A crash
// loop, a hang loop and a marginal power supply each leave a different mark.
//
// Put MG_HEALTH_INIT() in main(), right after clock and memory init:
//
// ```c
// int main(void) {
// hal_clock_init();
// MG_HEALTH_INIT();
// ...
// }
// ```
//
// The record must live in RAM that startup code neither copies nor zeroes.
// See tutorials/stm32/nucleo-h723zg/minimal/link.ld for the .mg_health region,
// and tutorials/stm32/nucleo-h723zg/minimal/mongoose_config.h for the
// reset-reason hooks.
//
// On Cortex-M, a fault handler can record the crash: it sets reset_reason to
// MG_HEALTH_RESET_FAULT and walks the stack into backtrace[]. See
// tutorials/stm32/nucleo-h723zg/minimal/main.c for a sample HardFault_Handler.
@@ -4997,12 +4948,15 @@ enum mg_health_reason {
MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack
}; };
#define MG_HEALTH_BACKTRACE 20 // Return addresses in mg_health::backtrace #ifndef MG_HEALTH_DATA_SIZE
#define MG_HEALTH_DATA_SIZE 20
#endif
struct mg_health { struct mg_health {
char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data
uint32_t reset_reason; // enum mg_health_reason that started this boot uint32_t reset_reason; // enum mg_health_reason that started this boot
uint32_t backtrace[MG_HEALTH_BACKTRACE]; // Crash backtrace, frame 0 first uint32_t cpuid; // ARM CPU ID
uint32_t data[MG_HEALTH_DATA_SIZE];
}; };
extern struct mg_health mg_health_record; // Defined in health.c extern struct mg_health mg_health_record; // Defined in health.c
@@ -5043,27 +4997,10 @@ static inline void mg_health_init(void) {
memset(&mg_health_record, 0, sizeof(mg_health_record)); memset(&mg_health_record, 0, sizeof(mg_health_record));
memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic)); memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic));
} }
// h->prev_uptime = h->uptime;
// h->prev_reason = h->reason;
// h->counter++;
// h->uptime = 0;
// h->reason = mg_health_decode_reason();
// MG_HEALTH_RESET_CLEAR();
} }
// // Record that the main loop is still alive. Called from mg_mgr_poll(), so a
// // hung application leaves uptime frozen at the hang
// extern uint64_t mg_health_next_ms; // Defined in health.c
// static inline void mg_health_uptime(uint64_t now_ms) {
// struct mg_health *h = mg_health_get();
// if (now_ms >= mg_health_next_ms && mg_health_valid()) {
// mg_health_next_ms = now_ms + 1000;
// h->uptime++;
// }
// }
#define MG_HEALTH_INIT() mg_health_init() #define MG_HEALTH_INIT() mg_health_init()
extern size_t mg_print_crash_record(mg_pfn_t, void *, va_list *);
// Cloud connector API to https://mdash.net - device management cloud // Cloud connector API to https://mdash.net - device management cloud
@@ -5078,16 +5015,13 @@ static inline void mg_health_init(void) {
#define MG_MDASH_KEY "" #define MG_MDASH_KEY ""
#endif #endif
#ifndef MG_MDASH_FIRMWARE_VERSION
#define MG_MDASH_FIRMWARE_VERSION "1.0.0"
#endif
#ifndef MG_ENABLE_MDASH #ifndef MG_ENABLE_MDASH
#define MG_ENABLE_MDASH 0 #define MG_ENABLE_MDASH 0
#endif #endif
void mg_mdash_init(struct mg_mgr *); void mg_mdash_init(struct mg_mgr *);
void mg_mdash_poll(struct mg_mgr *); void mg_mdash_poll(struct mg_mgr *);
void mg_mdash_free(struct mg_mgr *);
@@ -8,6 +8,7 @@
<license>License.txt</license> <license>License.txt</license>
<supportContact>https://mongoose.ws/contact/</supportContact> <supportContact>https://mongoose.ws/contact/</supportContact>
<releases> <releases>
<release date="2026-09-28" version="7.23.1">See https://github.com/cesanta/mongoose/releases/tag/7.23</release>
<release date="2026-05-11" version="7.21.7">See https://github.com/cesanta/mongoose/releases/tag/7.21</release> <release date="2026-05-11" version="7.21.7">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
<release date="2026-05-05" version="7.21.5">See https://github.com/cesanta/mongoose/releases/tag/7.21</release> <release date="2026-05-05" version="7.21.5">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
<release date="2026-04-24" version="7.21.4">See https://github.com/cesanta/mongoose/releases/tag/7.21</release> <release date="2026-04-24" version="7.21.4">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
@@ -19,7 +20,7 @@
<keyword>IMPLEMENTED_WITH_STM32CUBEMX</keyword> <keyword>IMPLEMENTED_WITH_STM32CUBEMX</keyword>
</keywords> </keywords>
<components> <components>
<component Cclass="Mongoose" Cgroup="Networking Core" Cversion="7.21.7" maxInstances="1"> <component Cclass="Mongoose" Cgroup="Networking Core" Cversion="7.23.1" maxInstances="1">
<description>Networking Core</description> <description>Networking Core</description>
<files> <files>
<file category="doc" name="README.md"/> <file category="doc" name="README.md"/>
+2 -20
View File
@@ -1,4 +1,4 @@
VERSION = 7.21.7 VERSION = 7.23.1
REPO_ROOT = ../.. REPO_ROOT = ../..
MX ?= /Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/STM32CubeMX MX ?= /Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/STM32CubeMX
FILES = Cesanta.I-CUBE-Mongoose.pdsc Release_Notes.html mongoose_config.h README.md FILES = Cesanta.I-CUBE-Mongoose.pdsc Release_Notes.html mongoose_config.h README.md
@@ -44,23 +44,5 @@ mongoose.h: Mongoose
mongoose.c: Mongoose mongoose.c: Mongoose
cp $(REPO_ROOT)/mongoose.c $@ cp $(REPO_ROOT)/mongoose.c $@
pk: $(PACK)
rm -f gen.mx
echo swmgr remove Cesanta.I-CUBE-Mongoose.$(VERSION) >> gen.mx
echo swmgr install `pwd`/Cesanta.I-CUBE-Mongoose.$(VERSION).pack ask >> gen.mx
echo exit >> gen.mx
$(MX) -q `pwd`/gen.mx
mx: $(PACK)
mkdir -p $@
cp ../downloads/nucleo_h563zi.ioc $@
V=`grep 'Mcu.ThirdParty0' $@/nucleo_h563zi.ioc | sed 's,^.*se.,,'`; sed -i '' "s,$$V,$(VERSION),g" $@/nucleo_h563zi.ioc
rm -f gen.mx
echo config load `pwd`/$@/nucleo_h563zi.ioc >> gen.mx
echo project generate >> gen.mx
echo exit >> gen.mx
$(MX) -q `pwd`/gen.mx
clean: clean:
rm -rf *.pack STM32CubeMX/*.$(VERSION)_*.xml $(GENERATED) gen.mx mx rm -rf *.pack STM32CubeMX/*.$(VERSION)_*.xml $(GENERATED)
+2 -1
View File
@@ -12,7 +12,8 @@
#include <sys/types.h> #include <sys/types.h>
#include <time.h> #include <time.h>
#ifndef MG_PATH_MAX
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#define MG_ENABLE_DIRLIST 0 #endif
#endif #endif
+2 -1
View File
@@ -18,7 +18,8 @@
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#ifndef MG_PATH_MAX
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#define MG_ENABLE_DIRLIST 0 #endif
#endif #endif
-4
View File
@@ -25,10 +25,6 @@
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 0
#endif
#ifndef MG_ENABLE_TCPIP #ifndef MG_ENABLE_TCPIP
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack #define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
-4
View File
@@ -33,10 +33,6 @@
#define MG_ENABLE_POSIX_FS 1 #define MG_ENABLE_POSIX_FS 1
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 1
#endif
#ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS #ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS
#define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U #define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U
#endif #endif
-4
View File
@@ -27,10 +27,6 @@
#define MG_PATH_MAX 100 #define MG_PATH_MAX 100
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 0
#endif
#ifndef MG_ENABLE_TCPIP #ifndef MG_ENABLE_TCPIP
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack #define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
#endif #endif
-4
View File
@@ -50,10 +50,6 @@
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 1
#endif
#ifndef MG_PATH_MAX #ifndef MG_PATH_MAX
#define MG_PATH_MAX FILENAME_MAX #define MG_PATH_MAX FILENAME_MAX
#endif #endif
-4
View File
@@ -166,10 +166,6 @@ typedef int socklen_t;
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR) #define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 1
#endif
#ifndef SIGPIPE #ifndef SIGPIPE
#define SIGPIPE 0 #define SIGPIPE 0
#endif #endif
+5 -5
View File
@@ -82,10 +82,6 @@
#define MG_ENABLE_WINSOCK 1 #define MG_ENABLE_WINSOCK 1
#endif #endif
#ifndef MG_ENABLE_DIRLIST
#define MG_ENABLE_DIRLIST 0
#endif
#ifndef MG_ENABLE_CUSTOM_RANDOM #ifndef MG_ENABLE_CUSTOM_RANDOM
#define MG_ENABLE_CUSTOM_RANDOM 0 #define MG_ENABLE_CUSTOM_RANDOM 0
#endif #endif
@@ -135,7 +131,7 @@
#endif #endif
#ifndef MG_ENABLE_POSIX_FS #ifndef MG_ENABLE_POSIX_FS
#define MG_ENABLE_POSIX_FS 0 #define MG_ENABLE_POSIX_FS MG_ENABLE_LFS
#endif #endif
#ifndef MG_INVALID_SOCKET #ifndef MG_INVALID_SOCKET
@@ -230,3 +226,7 @@
#ifndef MG_ENABLE_CHACHA20 #ifndef MG_ENABLE_CHACHA20
#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN #define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN
#endif #endif
#ifndef MG_ENABLE_HEALTH
#define MG_ENABLE_HEALTH 0
#endif
+51 -179
View File
@@ -1,5 +1,6 @@
#include "dash.h" #include "dash.h"
#include "http.h" #include "http.h"
#include "ota.h"
#include "util.h" #include "util.h"
#define MG_NO_CACHE_HEADERS "Cache-Control: no-cache\r\n" #define MG_NO_CACHE_HEADERS "Cache-Control: no-cache\r\n"
@@ -77,12 +78,7 @@ static int mg_dash_array_size(struct mg_field_set *set,
struct mg_dash_user *u) { struct mg_dash_user *u) {
int saved = *set->index, sz = -1; int saved = *set->index, sz = -1;
*set->index = -1; *set->index = -1;
if (set->fn) { if (set->fn && set->fn(MG_DASH_READ, u)) sz = *set->index;
if (set->fn(MG_DASH_READ, u)) sz = *set->index;
} else if (set->get_dir) {
mg_dash_dir_read(set, u);
sz = *set->index;
}
*set->index = saved; *set->index = saved;
return sz; return sz;
} }
@@ -100,10 +96,7 @@ static size_t mg_dash_print_array(mg_pfn_t fn, void *arg, va_list *ap) {
for (;;) { for (;;) {
bool done = to >= 0 && *set->index > to; bool done = to >= 0 && *set->index > to;
if (!done) { if (!done) {
if (set->fn) if (set->fn) set->fn(MG_DASH_READ, u);
set->fn(MG_DASH_READ, u);
else if (set->get_dir)
mg_dash_dir_read(set, u);
done = *set->index < 0; done = *set->index < 0;
} }
if (done) break; if (done) break;
@@ -185,8 +178,7 @@ void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *set) {
MG_ESC("change"), MG_ESC("params"), MG_ESC(set->name), sz); MG_ESC("change"), MG_ESC("params"), MG_ESC(set->name), sz);
} else { } else {
int saved_idx = set->index != NULL ? *set->index : 0; int saved_idx = set->index != NULL ? *set->index : 0;
bool ok = set->fn ? set->fn(MG_DASH_READ, u) bool ok = set->fn ? set->fn(MG_DASH_READ, u) : true;
: (set->get_dir ? mg_dash_dir_read(set, u) : true);
if (!ok) { if (!ok) {
if (set->index != NULL) *set->index = saved_idx; if (set->index != NULL) *set->index = saved_idx;
continue; continue;
@@ -233,8 +225,7 @@ static int mg_dash_parse_field(struct mg_str json, struct mg_field *f) {
mg_json_get_num(json, json_path, (double *) f->value); mg_json_get_num(json, json_path, (double *) f->value);
} else if (f->type == MG_VAL_STR && f->value_size > 0) { } else if (f->type == MG_VAL_STR && f->value_size > 0) {
struct mg_str tok = mg_json_get_tok(json, json_path); struct mg_str tok = mg_json_get_tok(json, json_path);
ok = tok.len >= 2 && tok.buf[0] == '"' && ok = tok.len >= 2 && tok.buf[0] == '"' && tok.buf[tok.len - 1] == '"';
tok.buf[tok.len - 1] == '"';
if (ok) mg_json_unescape(json, json_path, (char *) f->value, f->value_size); if (ok) mg_json_unescape(json, json_path, (char *) f->value, f->value_size);
} else if (f->type == MG_VAL_RAW && f->value_size > 0) { } else if (f->type == MG_VAL_RAW && f->value_size > 0) {
ok = mg_snprintf((char *) f->value, f->value_size, "%.*s", json.len, ok = mg_snprintf((char *) f->value, f->value_size, "%.*s", json.len,
@@ -271,68 +262,6 @@ static int mg_dash_apply(struct mg_connection *c, struct mg_dash *dash,
return total_count; return total_count;
} }
bool mg_dash_dir_read(struct mg_field_set *set, struct mg_dash_user *u) {
char dir[256], fname[128] = "";
struct mg_fs *fs = u->dash->upload_fs ? u->dash->upload_fs : &mg_fs_posix;
struct mg_field *name_field = NULL, *size_field = NULL;
size_t i;
if (!set->get_dir(u, dir, sizeof(dir))) return false;
for (i = 0; set->fields[i].name != NULL; i++) {
if (name_field == NULL && set->fields[i].type == MG_VAL_STR &&
strcmp(set->fields[i].name, "name") == 0)
name_field = &set->fields[i];
if (size_field == NULL && strcmp(set->fields[i].name, "size") == 0)
size_field = &set->fields[i];
}
if (name_field == NULL) return false;
if (*set->index == -1) { // Size query: count all files
int count = 0;
while (mg_fs_ls(fs, dir, fname, sizeof(fname))) count++;
*set->index = count;
return true;
}
{ // Regular read: scan to *set->index
int target = *set->index, cur = 0;
while (mg_fs_ls(fs, dir, fname, sizeof(fname))) {
if (cur++ == target) {
mg_snprintf((char *) name_field->value, name_field->value_size, "%s",
fname);
if (size_field != NULL) {
char path[512];
size_t sz = 0;
mg_snprintf(path, sizeof(path), "%s/%s", dir, fname);
fs->st(path, &sz, NULL);
if (size_field->type == MG_VAL_UINT64)
*(uint64_t *) size_field->value = (uint64_t) sz;
else if (size_field->type == MG_VAL_INT)
*(int *) size_field->value = (int) sz;
}
return true;
}
}
*set->index = -1; // No more entries
return true;
}
}
static bool mg_dash_set_file_name(struct mg_field_set *set,
struct mg_str name) {
size_t i;
for (i = 0; set->fields[i].name != NULL; i++) {
struct mg_field *f = &set->fields[i];
if (f->type == MG_VAL_STR && strcmp(f->name, "name") == 0) {
mg_snprintf((char *) f->value, f->value_size, "%.*s", (int) name.len,
name.buf);
return true;
}
}
return false;
}
static inline void mg_log_http_req(struct mg_connection *c, static inline void mg_log_http_req(struct mg_connection *c,
struct mg_http_message *hm) { struct mg_http_message *hm) {
int len = 0; int len = 0;
@@ -365,33 +294,6 @@ static inline void mg_log_http_req(struct mg_connection *c,
c->send.buf + n)); c->send.buf + n));
} }
static void mg_dash_ota_cb(struct mg_connection *c, const char *errmsg) {
mg_http_reply(c, errmsg ? 500 : 200, NULL, errmsg ? errmsg : "ok\n");
c->is_draining = 1;
}
static void mg_dash_upload_cb(struct mg_connection *c, const char *errmsg) {
if (errmsg) {
mg_http_reply(c, 500, NULL, "%s\n", errmsg);
} else {
// mg_http_start_upload() repurposes c->data for its own bookkeeping,
// so the field set can't be cached there. Re-derive the dashboard from
// c->fn_data instead, and notify every file-backed array: the upload
// could belong to any of them, and re-querying get_dir() per recipient
// is what mg_dash_send_change() does anyway (directories can be
// user-specific)
struct mg_dash *dash = (struct mg_dash *) c->fn_data;
struct mg_field_set *fs;
mg_http_reply(c, 200, NULL, "ok\n");
for (fs = dash->sets; fs != NULL; fs = fs->next) {
if (fs->get_dir == NULL) continue;
*fs->index = -1; // Signal mg_dash_send_change() to broadcast new size
mg_dash_send_change(c->mgr, fs);
}
}
c->is_draining = 1;
}
static uint64_t mg_dash_make_expiration_time(struct mg_dash *dash) { static uint64_t mg_dash_make_expiration_time(struct mg_dash *dash) {
unsigned t = (unsigned) dash->session_auto_expiration_seconds; unsigned t = (unsigned) dash->session_auto_expiration_seconds;
if (t == 0) t = 3600; // Default expiration time in seconds if (t == 0) t = 3600; // Default expiration time in seconds
@@ -631,6 +533,40 @@ static void mg_dash_handle_add(struct mg_connection *c, struct mg_dash *dash,
} }
} }
// Firmware upload callback for mg_http_stream_body(). Uses *p as a flag:
// non-NULL means an OTA session is open and must be closed by mg_ota_end()
static bool otacb(struct mg_http_message *hm, struct mg_str *data, void **p) {
if (hm != NULL) { // Start
if (!mg_ota_begin(hm->body.len)) return false;
*p = (void *) (ptrdiff_t) 1;
return true;
} else if (data != NULL) { // Next chunk
return mg_ota_write(data->buf, data->len);
}
if (*p == NULL) return false; // End. Begin failed, nothing to finish
*p = NULL;
return mg_ota_end();
}
static void mg_serve_fs(struct mg_connection *c, struct mg_http_message *hm,
struct mg_dash_user *u, bool stream) {
struct mg_dash *dash = (struct mg_dash *) c->fn_data;
char root[128] = "/fs/=";
if (u == NULL) {
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
} else if (dash->files_dir(u, root + 5, sizeof(root) - 5) == false) {
mg_http_reply(c, 500, MG_JSON_HEADERS, "Upload dir error\n");
} else {
struct mg_http_serve_opts o;
memset(&o, 0, sizeof(o));
o.root_dir = root;
o.fs = dash->upload_fs ? dash->upload_fs : &mg_fs_posix;
o.enable_delete = o.enable_upload = o.enable_dir_listing = true;
if (stream) mg_http_serve_upload(c, hm, &o);
else mg_http_serve_dir(c, hm, &o);
}
}
void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) { void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
struct mg_dash *dash = (struct mg_dash *) c->fn_data; struct mg_dash *dash = (struct mg_dash *) c->fn_data;
struct mg_dash_cdata *d = (struct mg_dash_cdata *) c->data; struct mg_dash_cdata *d = (struct mg_dash_cdata *) c->data;
@@ -644,9 +580,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
// Received headers - check authentication and possibly start uploads/ota // Received headers - check authentication and possibly start uploads/ota
struct mg_http_message *hm = (struct mg_http_message *) ev_data; struct mg_http_message *hm = (struct mg_http_message *) ev_data;
struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash); struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash);
struct mg_str parts[3];
memset(parts, 0, sizeof(parts));
if (mg_match(hm->uri, mg_str("/api/hi"), NULL) || if (mg_match(hm->uri, mg_str("/api/hi"), NULL) ||
mg_match(hm->uri, mg_str("/api/logout"), NULL)) { mg_match(hm->uri, mg_str("/api/logout"), NULL)) {
// Do nothing, handle them MG_EV_HTTP_MSG. We bypass auth for those // Do nothing, handle them MG_EV_HTTP_MSG. We bypass auth for those
@@ -656,49 +589,21 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
} else if (mg_match(hm->uri, mg_str("/api/login"), NULL) && u != NULL) { } else if (mg_match(hm->uri, mg_str("/api/login"), NULL) && u != NULL) {
mg_handle_login(c, u); mg_handle_login(c, u);
d->marker = CONN_HANDLED; d->marker = CONN_HANDLED;
} else if (u != NULL && dash->files_dir != NULL &&
mg_match(hm->uri, mg_str("/fs/#"), NULL)) {
mg_serve_fs(c, hm, u, true);
return; // Important - the serve_fs() call can invalidate hm
} else if (mg_match(hm->uri, mg_str("/api/ota"), NULL)) { } else if (mg_match(hm->uri, mg_str("/api/ota"), NULL)) {
mg_http_start_ota(c, hm, mg_dash_ota_cb); // Authenticated above. If streaming started, the stream handler owns
} else if (mg_match(hm->uri, mg_str("/fs/*/*"), parts) && // the connection and c->data, so skip the marker check below
(mg_strcasecmp(hm->method, mg_str("POST")) == 0 || if (mg_http_stream_body(c, hm, otacb, NULL)) return;
mg_strcasecmp(hm->method, mg_str("PUT")) == 0)) {
struct mg_field_set *set = mg_dash_find_field_set(dash, parts[0]);
struct mg_str name = parts[1];
int len =
mg_url_decode(name.buf, name.len, (char *) name.buf, name.len + 1, 0);
if (len > 0 && (size_t) len <= name.len) name.len = (size_t) len;
if (set == NULL || set->get_dir == NULL) {
mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found\n");
d->marker = CONN_HANDLED;
} else if (u == NULL) {
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
d->marker = CONN_HANDLED;
} else if (!mg_path_is_sane(name)) {
mg_http_reply(c, 400, MG_JSON_HEADERS, "Bad file name\n");
d->marker = CONN_HANDLED;
} else {
mg_dash_set_file_name(set, name);
if (set->fn != NULL && !set->fn(MG_DASH_WRITE, u)) {
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
d->marker = CONN_HANDLED;
} else {
char dir[256];
struct mg_fs *fs = dash->upload_fs ? dash->upload_fs : &mg_fs_posix;
if (!set->get_dir(u, dir, sizeof(dir))) {
mg_http_reply(c, 500, MG_JSON_HEADERS, "Upload dir error\n");
d->marker = CONN_HANDLED;
} else {
mg_http_start_upload(c, hm, name, mg_str(dir), fs,
mg_dash_upload_cb);
}
}
}
} }
if (d->marker != '\0') mg_log_http_req(c, hm); if (d->marker != '\0') mg_log_http_req(c, hm);
} else if (ev == MG_EV_HTTP_MSG && d->marker != '\0') { } else if (ev == MG_EV_HTTP_MSG && d->marker != '\0') {
// The response has been send in EV_HDRS path, so we're not reponding // The response has been send in EV_HDRS path, so we're not reponding
// anything but clearing the marker for the next request. // anything but clearing the marker for the next request.
d->marker = 0; d->marker = 0;
c->is_resp = 0; c->pfn_data = NULL; // Response done
} else if (ev == MG_EV_HTTP_MSG && d->marker == '\0') { } else if (ev == MG_EV_HTTP_MSG && d->marker == '\0') {
struct mg_http_message *hm = (struct mg_http_message *) ev_data; struct mg_http_message *hm = (struct mg_http_message *) ev_data;
struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash); struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash);
@@ -714,42 +619,9 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
} else if (mg_match(hm->uri, mg_str("/api/websocket"), NULL)) { } else if (mg_match(hm->uri, mg_str("/api/websocket"), NULL)) {
d->u = u; d->u = u;
mg_ws_upgrade(c, hm, NULL); mg_ws_upgrade(c, hm, NULL);
} else if (mg_match(hm->uri, mg_str("/fs/*/*"), parts)) { } else if (dash->files_dir != NULL &&
struct mg_field_set *set = mg_dash_find_field_set(dash, parts[0]); mg_match(hm->uri, mg_str("/fs/#"), NULL)) {
if (set == NULL || set->get_dir == NULL) { mg_serve_fs(c, hm, u, false);
mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found");
} else if (u == NULL) {
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
} else {
char dir[256], path[512];
struct mg_fs *fs = dash->upload_fs ? dash->upload_fs : &mg_fs_posix;
struct mg_str name = parts[1];
int len = mg_url_decode(name.buf, name.len, (char *) name.buf,
name.len + 1, 0);
if (len > 0 && (size_t) len <= name.len) name.len = (size_t) len;
if (!mg_path_is_sane(name)) {
mg_http_reply(c, 400, MG_JSON_HEADERS, "Bad file name\n");
return;
}
if (!set->get_dir(u, dir, sizeof(dir))) {
mg_http_reply(c, 500, MG_JSON_HEADERS, "Upload dir error\n");
return;
}
mg_snprintf(path, sizeof(path), "%s/%.*s", dir, name.len, name.buf);
if (mg_strcasecmp(hm->method, mg_str("DELETE")) == 0) {
mg_dash_set_file_name(set, name);
if (set->fn != NULL && !set->fn(MG_DASH_DELETE, u)) {
mg_http_reply(c, 403, MG_JSON_HEADERS, "Not Authorised\n");
} else {
fs->rm(path);
*set->index = -1; // Signal mg_dash_send_change() to send new size
mg_dash_send_change(c->mgr, set);
mg_http_reply(c, 200, NULL, "true");
}
} else {
mg_http_serve_file(c, hm, path, NULL);
}
}
} else if (mg_match(hm->uri, mg_str("/api/del/*/*/*"), parts) || } else if (mg_match(hm->uri, mg_str("/api/del/*/*/*"), parts) ||
mg_match(hm->uri, mg_str("/api/del/*/*"), parts)) { mg_match(hm->uri, mg_str("/api/del/*/*"), parts)) {
mg_dash_handle_del(c, dash, u, parts); mg_dash_handle_del(c, dash, u, parts);
@@ -780,7 +652,7 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
break; break;
} }
} }
if (ch == NULL) mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found"); if (ch == NULL) mg_http_reply(c, 404, MG_JSON_HEADERS, "Not Found\n");
mg_log_http_req(c, hm); mg_log_http_req(c, hm);
} }
} }
+4 -40
View File
@@ -73,9 +73,7 @@ struct mg_field_set {
// fn sets *index = -1 to signal end of iteration. // fn sets *index = -1 to signal end of iteration.
// Size query: framework sets *index = -1 before fn(READ); fn // Size query: framework sets *index = -1 before fn(READ); fn
// sets *index = total size // sets *index = total size
bool (*get_dir)(const struct mg_dash_user *u, char *buf, struct mg_field_set *next; // Next set in the list
size_t len); // Non-NULL: file array
struct mg_field_set *next; // Next set in the list
}; };
// Custom URI handler, registered with MG_DASH_REGISTER_CUSTOM_HANDLER() // Custom URI handler, registered with MG_DASH_REGISTER_CUSTOM_HANDLER()
@@ -96,6 +94,9 @@ struct mg_dash {
int session_auto_expiration_seconds; // Session lifetime, 0: 1 hour default int session_auto_expiration_seconds; // Session lifetime, 0: 1 hour default
struct mg_dash_user *guest; // Used when authenticate == NULL struct mg_dash_user *guest; // Used when authenticate == NULL
struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix
// Resolves the built-in file manager's root dir for user u, e.g. per-user
// upload directories. NULL: file manager disabled
bool (*files_dir)(const struct mg_dash_user *u, char *buf, size_t len);
}; };
#define MG_DASH_ADD_FIELD_SET(dash_, set_) \ #define MG_DASH_ADD_FIELD_SET(dash_, set_) \
@@ -121,43 +122,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data);
// array size if *set->index < 0, or a single element update otherwise // array size if *set->index < 0, or a single element update otherwise
void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *); void mg_dash_send_change(struct mg_mgr *mgr, struct mg_field_set *);
// Default reader for file-backed array sets (set->get_dir != NULL)
// Usage example - this is a complete implemenation of the file manager:
// ```c
// static struct file {
// int index;
// char name[64];
// size_t size;
// uint64_t checksum;
// } s_file;
// static struct mg_field_set set_files;
//
// static bool get_dir(const struct mg_dash_user *u, char *buf, size_t len) {
// (void) u;
// mkdir("/tmp/dashboard", 0755);
// mg_snprintf(buf, len, "%s", "/tmp/dashboard");
// return true;
// }
//
// static struct mg_field fields_files[] = {
// {"name", MG_VAL_STR, s_file.name, sizeof(s_file.name)},
// {"size", MG_VAL_UINT64, &s_file.size, 0},
// {"checksum", MG_VAL_UINT64, &s_file.checksum, sizeof(s_file.checksum)},
// {NULL, MG_VAL_INT, NULL, 0},
// };
//
// static bool files_fn(enum mg_dash_op op, struct mg_dash_user *u) {
// if (op == MG_DASH_WRITE) return s_uploads_enabled && u->level >= 7;
// if (op != MG_DASH_READ) return false;
// if (!mg_dash_dir_read(&set_files, u)) return false;
// s_file.checksum = 0; // Mock to show how to set custom fields
// return true;
// }
//
// static struct mg_field_set set_files = {"files", fields_files, files_fn, &s_file.index, get_dir, NULL};
// ```
bool mg_dash_dir_read(struct mg_field_set *set, struct mg_dash_user *u);
// Helper forward declarations for Mongoose CMSIS pack modules // Helper forward declarations for Mongoose CMSIS pack modules
extern struct mg_mgr g_mgr; extern struct mg_mgr g_mgr;
extern void mg_dash_init(struct mg_mgr *); extern void mg_dash_init(struct mg_mgr *);
+5
View File
@@ -1,4 +1,5 @@
#include "fs.h" #include "fs.h"
#include "log.h"
#include "printf.h" #include "printf.h"
#include "str.h" #include "str.h"
#include "util.h" #include "util.h"
@@ -47,6 +48,7 @@ bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
char tmp[MG_PATH_MAX], rnd[10]; char tmp[MG_PATH_MAX], rnd[10];
size_t path_len = mg_snprintf(tmp, sizeof(tmp), "%s..%s", path, size_t path_len = mg_snprintf(tmp, sizeof(tmp), "%s..%s", path,
mg_random_str(rnd, sizeof(rnd))); mg_random_str(rnd, sizeof(rnd)));
fs->rm(tmp);
if (path_len < sizeof(tmp) && if (path_len < sizeof(tmp) &&
(fd = mg_fs_open(fs, tmp, MG_FS_WRITE | MG_FS_EXCL)) != NULL) { (fd = mg_fs_open(fs, tmp, MG_FS_WRITE | MG_FS_EXCL)) != NULL) {
result = fs->wr(fd->fd, buf, len) == len; result = fs->wr(fd->fd, buf, len) == len;
@@ -54,8 +56,11 @@ bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
if (result) { if (result) {
fs->rm(path); fs->rm(path);
result = fs->mv(tmp, path); result = fs->mv(tmp, path);
MG_DEBUG(("mv %s -> %s result=%d", tmp, path, result));
} }
fs->rm(tmp); fs->rm(tmp);
} else {
MG_ERROR(("mg_fs_open(%s) failed, path_len=%zu", tmp, path_len));
} }
return result; return result;
} }
+2
View File
@@ -2,6 +2,7 @@
#include "arch.h" #include "arch.h"
#include "config.h" #include "config.h"
#include "lfs.h"
// Flags returned by mg_fs.st() and passed to mg_fs.open(). // Flags returned by mg_fs.st() and passed to mg_fs.open().
enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4, MG_FS_EXCL = 8 }; enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4, MG_FS_EXCL = 8 };
@@ -40,6 +41,7 @@ void mg_fs_close(struct mg_fd *fd);
// Sequential directory iterator. Call repeatedly with the same buf/len; // Sequential directory iterator. Call repeatedly with the same buf/len;
// each call fills buf with the next entry name. Returns false when done. // each call fills buf with the next entry name. Returns false when done.
// Note: make sure buf[0] == 0 before the first call
bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len); bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len);
// Reads the entire file into a heap-allocated buffer. The returned mg_str is // Reads the entire file into a heap-allocated buffer. The returned mg_str is
+4 -4
View File
@@ -10,6 +10,10 @@
#define MG_STAT_FUNC stat #define MG_STAT_FUNC stat
#endif #endif
#if MG_ENABLE_LFS
#include <dirent.h>
#endif
static int p_stat(const char *path, size_t *size, time_t *mtime) { static int p_stat(const char *path, size_t *size, time_t *mtime) {
#if !defined(S_ISDIR) #if !defined(S_ISDIR)
MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime)); MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime));
@@ -161,7 +165,6 @@ struct dirent *readdir(DIR *d) {
static void p_list(const char *dir, void (*fn)(const char *, void *), static void p_list(const char *dir, void (*fn)(const char *, void *),
void *userdata) { void *userdata) {
#if MG_ENABLE_DIRLIST
struct dirent *dp; struct dirent *dp;
DIR *dirp; DIR *dirp;
if ((dirp = (opendir(dir))) == NULL) return; if ((dirp = (opendir(dir))) == NULL) return;
@@ -170,9 +173,6 @@ static void p_list(const char *dir, void (*fn)(const char *, void *),
fn(dp->d_name, userdata); fn(dp->d_name, userdata);
} }
closedir(dirp); closedir(dirp);
#else
(void) dir, (void) fn, (void) userdata;
#endif
} }
static void *p_open(const char *path, int flags) { static void *p_open(const char *path, int flags) {
+68
View File
@@ -1,5 +1,73 @@
#include "config.h"
#include "health.h" #include "health.h"
// The one health record. Lives in RAM that survives a warm reset, see // The one health record. Lives in RAM that survives a warm reset, see
// MG_HEALTH_RAM and the .mg_health region in the linker script // MG_HEALTH_RAM and the .mg_health region in the linker script
struct mg_health mg_health_record MG_HEALTH_RAM; struct mg_health mg_health_record MG_HEALTH_RAM;
// STM32 H723 support. Needs the _estack symbol from the linker script
#if MG_ENABLE_HEALTH && defined(STM32H723xx_H)
// Fault handler body. Runs in exception context: no printf, no malloc, no
// blocking calls. Copies the unwind registers and raw stack into the health
// record, then resets.
// "used" keeps the linker from garbage-collecting this section: the only
// reference is the "b fault_c" branch in the naked handler below
__attribute__((used, noinline)) static void fault_c(uint32_t *frame,
uint32_t exc_return) {
extern uint32_t _estack;
uint32_t *stack = frame + 8 + ((exc_return & (1U << 4)) ? 0 : 18);
uint32_t *r = mg_health_record.data;
if (frame[7] & (1U << 9)) stack++; // Eight-byte stack alignment padding
r[0] = (uint32_t) (uintptr_t) stack; // SP
r[1] = frame[5]; // LR
r[2] = frame[6]; // PC
for (size_t i = 0; i < MG_HEALTH_DATA_SIZE - 3; i++) { // Raw stack
r[3 + i] = stack + i < &_estack ? stack[i] : 0;
}
mg_health_record.cpuid = SCB->CPUID;
mg_health_record.reset_reason = MG_HEALTH_RESET_FAULT;
NVIC_SystemReset();
}
// Common fault entry. EXC_RETURN bit 2 tells which stack was in use:
// 0 = MSP, 1 = PSP. Load the faulting SP into r0 and hand it to fault_c()
__attribute__((naked)) void HardFault_Handler(void) {
__asm volatile(
"mov r1, lr\n\t"
"tst lr, #4\n\t"
"ite eq\n\t"
"mrseq r0, msp\n\t"
"mrsne r0, psp\n\t"
"b fault_c\n\t");
}
// Route the other fault types through the same entry point
void MemManage_Handler(void) __attribute__((alias("HardFault_Handler")));
void BusFault_Handler(void) __attribute__((alias("HardFault_Handler")));
void UsageFault_Handler(void) __attribute__((alias("HardFault_Handler")));
#endif
static size_t print_uint32(void (*fn)(char, void *), void *arg, va_list *ap) {
size_t n = va_arg(*ap, size_t);
uint32_t *p = va_arg(*ap, uint32_t *);
size_t len = 0;
while (n--) len += mg_xprintf(fn, arg, "%s%lu", len == 0 ? "" : ",", *p++);
return len;
}
size_t mg_print_crash_record(void (*fn)(char, void *), void *arg, va_list *ap) {
size_t len = 0;
if (mg_health_valid() &&
mg_health_record.reset_reason == MG_HEALTH_RESET_FAULT) {
size_t n = sizeof(mg_health_record.data) / sizeof(mg_health_record.data[0]);
len += mg_xprintf(fn, arg, "{%m:%hhu,%m:%u,%m:[%M]}", //
MG_ESC("version"), mg_health_record.magic[3], //
MG_ESC("cpuid"), mg_health_record.cpuid, //
MG_ESC("data"), print_uint32, n, mg_health_record.data);
} else {
len += mg_xprintf(fn, arg, "{}");
}
(void) ap;
return len;
}
+7 -44
View File
@@ -1,32 +1,9 @@
// Device health monitoring // Device health monitoring
//
// Keeps a small record in a RAM region that survives a warm reset, so a device
// can tell why it restarted. The record holds a boot counter, the uptime this
// boot has reached, and the reset reason reported by the hardware. A crash
// loop, a hang loop and a marginal power supply each leave a different mark.
//
// Put MG_HEALTH_INIT() in main(), right after clock and memory init:
//
// ```c
// int main(void) {
// hal_clock_init();
// MG_HEALTH_INIT();
// ...
// }
// ```
//
// The record must live in RAM that startup code neither copies nor zeroes.
// See tutorials/stm32/nucleo-h723zg/minimal/link.ld for the .mg_health region,
// and tutorials/stm32/nucleo-h723zg/minimal/mongoose_config.h for the
// reset-reason hooks.
//
// On Cortex-M, a fault handler can record the crash: it sets reset_reason to
// MG_HEALTH_RESET_FAULT and walks the stack into backtrace[]. See
// tutorials/stm32/nucleo-h723zg/minimal/main.c for a sample HardFault_Handler.
#pragma once #pragma once
#include "arch.h" #include "arch.h"
#include "printf.h"
#ifndef MG_HEALTH_MAGIC #ifndef MG_HEALTH_MAGIC
#define MG_HEALTH_MAGIC {'M', 'G', 'H', '3'} // '3' is the layout version #define MG_HEALTH_MAGIC {'M', 'G', 'H', '3'} // '3' is the layout version
@@ -52,12 +29,15 @@ enum mg_health_reason {
MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack
}; };
#define MG_HEALTH_BACKTRACE 20 // Return addresses in mg_health::backtrace #ifndef MG_HEALTH_DATA_SIZE
#define MG_HEALTH_DATA_SIZE 20
#endif
struct mg_health { struct mg_health {
char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data
uint32_t reset_reason; // enum mg_health_reason that started this boot uint32_t reset_reason; // enum mg_health_reason that started this boot
uint32_t backtrace[MG_HEALTH_BACKTRACE]; // Crash backtrace, frame 0 first uint32_t cpuid; // ARM CPU ID
uint32_t data[MG_HEALTH_DATA_SIZE];
}; };
extern struct mg_health mg_health_record; // Defined in health.c extern struct mg_health mg_health_record; // Defined in health.c
@@ -98,24 +78,7 @@ static inline void mg_health_init(void) {
memset(&mg_health_record, 0, sizeof(mg_health_record)); memset(&mg_health_record, 0, sizeof(mg_health_record));
memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic)); memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic));
} }
// h->prev_uptime = h->uptime;
// h->prev_reason = h->reason;
// h->counter++;
// h->uptime = 0;
// h->reason = mg_health_decode_reason();
// MG_HEALTH_RESET_CLEAR();
} }
// // Record that the main loop is still alive. Called from mg_mgr_poll(), so a
// // hung application leaves uptime frozen at the hang
// extern uint64_t mg_health_next_ms; // Defined in health.c
// static inline void mg_health_uptime(uint64_t now_ms) {
// struct mg_health *h = mg_health_get();
// if (now_ms >= mg_health_next_ms && mg_health_valid()) {
// mg_health_next_ms = now_ms + 1000;
// h->uptime++;
// }
// }
#define MG_HEALTH_INIT() mg_health_init() #define MG_HEALTH_INIT() mg_health_init()
extern size_t mg_print_crash_record(mg_pfn_t, void *, va_list *);
+215 -272
View File
@@ -3,7 +3,6 @@
#include "fmt.h" #include "fmt.h"
#include "log.h" #include "log.h"
#include "net.h" #include "net.h"
#include "ota.h"
#include "printf.h" #include "printf.h"
#include "ssi.h" #include "ssi.h"
#include "util.h" #include "util.h"
@@ -359,7 +358,7 @@ static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
if (c->send.len >= len + 10) { if (c->send.len >= len + 10) {
mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10); mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
c->send.buf[len + 8] = '\r'; c->send.buf[len + 8] = '\r';
if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker if (c->send.len == len + 10) c->pfn_data = NULL; // Last chunk, done
} }
if (!mg_send(c, "\r\n", 2)) mg_error(c, "OOM"); if (!mg_send(c, "\r\n", 2)) mg_error(c, "OOM");
} }
@@ -374,7 +373,7 @@ void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) { void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
mg_printf(c, "%lx\r\n", (unsigned long) len); mg_printf(c, "%lx\r\n", (unsigned long) len);
if (!mg_send(c, buf, len) || !mg_send(c, "\r\n", 2)) mg_error(c, "OOM"); if (!mg_send(c, buf, len) || !mg_send(c, "\r\n", 2)) mg_error(c, "OOM");
if (len == 0) c->is_resp = 0; if (len == 0) c->pfn_data = NULL; // Last chunk, response done
} }
// clang-format off // clang-format off
@@ -463,15 +462,14 @@ void mg_http_reply(struct mg_connection *c, int code, const char *headers,
(unsigned long) (c->send.len - len)); (unsigned long) (c->send.len - len));
c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
} }
c->is_resp = 0; c->pfn_data = NULL; // Response done
} }
static void http_cb(struct mg_connection *, int, void *); static void http_cb(struct mg_connection *, int, void *);
static void restore_http_cb(struct mg_connection *c) { static void restore_http_cb(struct mg_connection *c) {
mg_fs_close((struct mg_fd *) c->pfn_data); mg_fs_close((struct mg_fd *) c->pfn_data);
c->pfn_data = NULL; c->pfn_data = NULL; // Response done
c->pfn = http_cb; c->pfn = http_cb;
c->is_resp = 0;
} }
char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime); char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
@@ -659,7 +657,7 @@ void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "", etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
range, hdrs); range, hdrs);
if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0 || c->is_closing) { if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0 || c->is_closing) {
c->is_resp = 0; c->pfn_data = NULL; // Response done
mg_fs_close(fd); mg_fs_close(fd);
} else { // start serving static content only if not closing, see #3354 } else { // start serving static content only if not closing, see #3354
// Track to-be-sent content length at the end of c->data, aligned // Track to-be-sent content length at the end of c->data, aligned
@@ -677,161 +675,97 @@ struct printdirentrydata {
struct mg_http_message *hm; struct mg_http_message *hm;
const struct mg_http_serve_opts *opts; const struct mg_http_serve_opts *opts;
const char *dir; const char *dir;
size_t count;
}; };
#if MG_ENABLE_DIRLIST
// Print file name, escaping HTML chars
static size_t html_esc(void (*fn)(char, void *), void *arg, va_list *ap) {
const char *s = va_arg(*ap, const char *);
size_t i, len = 0;
for (i = 0; s[i] != '\0'; i++) {
if (s[i] == '<') {
len += mg_xprintf(fn, arg, "%s", "&lt;");
} else if (s[i] == '>') {
len += mg_xprintf(fn, arg, "%s", "&gt;");
} else if (s[i] == '&') {
len += mg_xprintf(fn, arg, "%s", "&amp;");
} else {
len += mg_xprintf(fn, arg, "%c", s[i]);
}
}
return len;
}
static void printdirentry(const char *name, void *userdata) { static void printdirentry(const char *name, void *userdata) {
struct printdirentrydata *d = (struct printdirentrydata *) userdata; struct printdirentrydata *d = (struct printdirentrydata *) userdata;
struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs; struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
size_t size = 0; size_t size = 0;
time_t t = 0; time_t t = 0;
char path[MG_PATH_MAX], sz[40], mod[40]; char path[MG_PATH_MAX];
int flags, n = 0; int flags;
// MG_DEBUG(("[%s] [%s]", d->dir, name)); if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >=
if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
sizeof(path)) { sizeof(path)) {
MG_ERROR(("%s truncated", name)); MG_ERROR(("%s truncated", name));
} else if ((flags = fs->st(path, &size, &t)) == 0) { } else if ((flags = fs->st(path, &size, &t)) == 0) {
MG_ERROR(("%lu stat(%s)", d->c->id, path)); MG_ERROR(("%lu stat(%s)", d->c->id, path));
} else { } else {
const char *slash = flags & MG_FS_DIR ? "/" : "";
if (flags & MG_FS_DIR) { if (flags & MG_FS_DIR) {
mg_snprintf(sz, sizeof(sz), "%s", "[DIR]"); mg_printf(d->c, "%s\n {%m: %m, %m: true}", //
d->count == 0 ? "" : ",", //
MG_ESC("name"), MG_ESC(name), MG_ESC("dir"));
} else { } else {
mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size); mg_printf(d->c, "%s\n {%m: %m, %m: %zu, %m: %llu, %m: false}", //
d->count == 0 ? "" : ",", //
MG_ESC("name"), MG_ESC(name), //
MG_ESC("size"), size, //
MG_ESC("modified"), (uint64_t) t, MG_ESC("dir"));
} }
#if defined(MG_HTTP_DIRLIST_TIME_FMT) d->count++;
{
char time_str[40];
struct tm *time_info = localtime(&t);
strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
mg_snprintf(mod, sizeof(mod), "%s", time_str);
}
#else
mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
#endif
n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
mg_printf(d->c,
" <tr><td><a href=\"%.*s%s\">%M%s</a></td>"
"<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
n, path, slash, html_esc, name, slash, (unsigned long) t, mod,
flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
} }
} }
static void listdir(struct mg_connection *c, struct mg_http_message *hm, static void listdir(struct mg_connection *c, struct mg_http_message *hm,
const struct mg_http_serve_opts *opts, char *dir) { const struct mg_http_serve_opts *opts, char *dir) {
const char *sort_js_code =
"<script>function srt(tb, sc, so, d) {"
"var tr = Array.prototype.slice.call(tb.rows, 0),"
"tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
"n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
"t1 = a.cells[2].getAttribute('name'), "
"t2 = b.cells[2].getAttribute('name'); "
"return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
"n1 ? parseInt(n2) - parseInt(n1) : "
"c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
const char *sort_js_code2 =
"for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
"if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
"};"
"window.onload = function() {"
"var tb = document.getElementById('tb');"
"var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
"var sc = m[1], so = m[2]; document.onclick = function(ev) { "
"var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
"sc = c; ev.preventDefault();}};"
"srt(tb, sc, so, true);"
"}"
"</script>";
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs; struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
struct printdirentrydata d = {c, hm, opts, dir}; struct printdirentrydata d = {c, hm, opts, dir, 0};
char tmp[10], buf[MG_PATH_MAX]; char tmp[10];
size_t off, n; size_t off, n;
int len = mg_url_decode(hm->uri.buf, hm->uri.len, buf, sizeof(buf), 0);
struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
mg_printf(c, mg_printf(c,
"HTTP/1.1 200 OK\r\n" "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n" "Content-Type: application/json; charset=utf-8\r\n"
"%s" "%s"
"Content-Length: \r\n\r\n", "Content-Length: \r\n\r\n",
opts->extra_headers == NULL ? "" : opts->extra_headers); opts->extra_headers == NULL ? "" : opts->extra_headers);
off = c->send.len; // Start of body off = c->send.len; // Start of body
mg_printf(c, mg_printf(c, "[");
"<!DOCTYPE html><html><head><title>Index of %M</title>%s%s"
"<style>th,td {text-align: left; padding-right: 1em; "
"font-family: monospace; }</style></head>"
"<body><h1>Index of %M</h1><table cellpadding=\"0\"><thead>"
"<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
"<a href=\"#\" rel=\"1\">Modified</a></th>"
"<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
"<tr><td colspan=\"3\"><hr></td></tr>"
"</thead>"
"<tbody id=\"tb\">\n",
mg_print_html_esc, (int) uri.len, uri.buf, sort_js_code, sort_js_code2,
mg_print_html_esc, (int) uri.len, uri.buf);
mg_printf(c, "%s",
" <tr><td><a href=\"..\">..</a></td>"
"<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
fs->ls(dir, printdirentry, &d); fs->ls(dir, printdirentry, &d);
mg_printf(c, mg_printf(c, "\n]\n");
"</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
"</table><address>Mongoose v.%s</address></body></html>\n",
MG_VERSION);
n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off)); n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
if (n > sizeof(tmp)) n = 0; if (n > sizeof(tmp)) n = 0;
memcpy(c->send.buf + off - 12, tmp, n); // Set content length memcpy(c->send.buf + off - 12, tmp, n); // Set content length
c->is_resp = 0; // Mark response end c->pfn_data = NULL; // Response done
}
// Map requested URI to the file path (buf,len). Use root directory r.
// r could be a path optionally followed by map: PATH,/PREFIX1=PATH1,...
static bool uri2path(const char *r, struct mg_str uri, char *buf, size_t len) {
struct mg_str k, v, part, s = mg_str(r), u = {NULL, 0}, d = u;
size_t n;
while (mg_span(s, &part, &s, ',')) {
if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
if (v.len == 0) v = k, k = mg_str("/"), u = k, d = v;
if (uri.len < k.len) continue;
if (mg_strcmp(k, mg_str_n(uri.buf, k.len)) != 0) continue;
u = k, d = v;
}
n = mg_snprintf(buf, len, "%.*s", (int) d.len, d.buf);
if (len == 0 || n + 2 >= len) return false; // Path overflow
if (n > 0 && buf[n - 1] != '/') buf[n++] = '/', buf[n] = '\0'; // Add slash
if (mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0) < 0) {
return false;
}
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (!mg_path_is_sane(mg_str_n(buf, n))) return false;
while (n > 1 && buf[n - 1] == '/') buf[--n] = 0; // Trim trailing slashes
return true;
} }
#endif
// Resolve requested file into `path` and return its fs->st() result // Resolve requested file into `path` and return its fs->st() result
static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm, static int uri_to_file_status(struct mg_connection *c,
struct mg_fs *fs, struct mg_str url, struct mg_str dir, struct mg_http_message *hm,
char *path, size_t path_size) { struct mg_fs *fs, const char *root_dir,
char *path, size_t path_size) {
int flags, tmp; int flags, tmp;
// Append URI to the root_dir, and sanitize it size_t n;
size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.buf); if (!uri2path(root_dir, hm->uri, path, path_size)) {
if (n + 2 >= path_size) {
mg_http_reply(c, 400, "", "Exceeded path size");
return -1;
}
path[path_size - 1] = '\0';
// Terminate root dir with slash
if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
if (url.len < hm->uri.len &&
mg_url_decode(hm->uri.buf + url.len, hm->uri.len - url.len, path + n,
path_size - n, 0) < 0) {
mg_http_reply(c, 400, "", "Invalid path"); mg_http_reply(c, 400, "", "Invalid path");
return -1; return -1;
} }
path[path_size - 1] = '\0'; // Double-check
n = strlen(path); n = strlen(path);
if (!mg_path_is_sane(mg_str_n(path, n))) {
mg_http_reply(c, 400, "", "Invalid path");
return -1;
}
while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR
: fs->st(path, NULL, NULL); : fs->st(path, NULL, NULL);
MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path, MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path,
@@ -846,7 +780,7 @@ static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
"Content-Length: 0\r\n" "Content-Length: 0\r\n"
"\r\n", "\r\n",
(int) hm->uri.len, hm->uri.buf); (int) hm->uri.len, hm->uri.buf);
c->is_resp = 0; c->pfn_data = NULL; // Response done
flags = -1; flags = -1;
} else if (flags & MG_FS_DIR) { } else if (flags & MG_FS_DIR) {
if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 && if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
@@ -868,34 +802,36 @@ static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
return flags; return flags;
} }
static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
const struct mg_http_serve_opts *opts, char *path,
size_t path_size) {
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
struct mg_str k, v, part, s = mg_str(opts->root_dir), u = {NULL, 0}, p = u;
while (mg_span(s, &part, &s, ',')) {
if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
if (hm->uri.len < k.len) continue;
if (mg_strcmp(k, mg_str_n(hm->uri.buf, k.len)) != 0) continue;
u = k, p = v;
}
return uri_to_path2(c, hm, fs, u, p, path, path_size);
}
void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm, void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
const struct mg_http_serve_opts *opts) { const struct mg_http_serve_opts *opts) {
char path[MG_PATH_MAX]; char path[MG_PATH_MAX];
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
const char *sp = opts->ssi_pattern; const char *sp = opts->ssi_pattern;
int flags = uri_to_path(c, hm, opts, path, sizeof(path)); int flags = uri_to_file_status(c, hm, fs, opts->root_dir, path, sizeof(path));
if (flags < 0) { if (flags < 0) {
// Do nothing: the response has already been sent by uri_to_path() // Do nothing: the response has already been sent by uri_to_file_status()
} else if (flags & MG_FS_DIR) { } else if (flags & MG_FS_DIR) {
#if MG_ENABLE_DIRLIST if (opts->enable_dir_listing) {
listdir(c, hm, opts, path); listdir(c, hm, opts, path);
#else } else {
mg_http_reply(c, 403, "", "Forbidden\n"); mg_http_reply(c, 403, "", "Forbidden\n");
#endif }
} else if (opts->enable_delete &&
mg_strcasecmp(hm->method, mg_str("DELETE")) == 0) {
mg_http_reply(c, flags && fs->rm(path) ? 200 : 404, "", "");
} else if (opts->enable_upload &&
(mg_strcasecmp(hm->method, mg_str("POST")) == 0 ||
mg_strcasecmp(hm->method, mg_str("PUT")) == 0)) {
// Small or already fully buffered body. mg_http_serve_upload() handles
// the same thing without buffering, for big uploads, from MG_EV_HTTP_HDRS
void *fd;
bool ok = false;
fs->rm(path); // MG_FS_WRITE appends, not truncates: drop any old file
if ((fd = fs->op(path, MG_FS_WRITE)) != NULL) {
ok = fs->wr(fd, hm->body.buf, hm->body.len) == hm->body.len;
fs->cl(fd);
}
mg_http_reply(c, ok ? 200 : 500, "", "");
} else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) { } else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) {
mg_http_serve_ssi(c, opts->root_dir, path); mg_http_serve_ssi(c, opts->root_dir, path);
} else { } else {
@@ -903,6 +839,52 @@ void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
} }
} }
// mg_http_stream_body() callback for mg_http_serve_upload(). The file is
// opened by the caller before streaming starts, so this only writes and closes
static bool serve_upload_cb(struct mg_http_message *hm, struct mg_str *data,
void **p) {
struct mg_fd *fd = (struct mg_fd *) *p;
if (hm != NULL) return fd != NULL; // Start
if (data != NULL) { // Next chunk
return fd != NULL && fd->fs->wr(fd->fd, data->buf, data->len) == data->len;
}
if (fd != NULL) mg_fs_close(fd); // End
*p = NULL;
return true;
}
// Starts a streaming upload for a big POST/PUT body, so it never sits fully
// buffered in memory. Companion to mg_http_serve_dir(): call this from
// MG_EV_HTTP_HDRS, and keep calling mg_http_serve_dir() from MG_EV_HTTP_MSG
// as before - it handles uploads too, for bodies this function skips.
// Does nothing unless opts->enable_upload is set, the method is POST or PUT,
// and Content-Length is known and >= 2 * MG_IO_SIZE.
void mg_http_serve_upload(struct mg_connection *c, struct mg_http_message *hm,
const struct mg_http_serve_opts *opts) {
char path[MG_PATH_MAX];
struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
if (!opts->enable_upload) {
// Not enabled, nothing to do
} else if (mg_strcasecmp(hm->method, mg_str("POST")) != 0 &&
mg_strcasecmp(hm->method, mg_str("PUT")) != 0) {
// Not an upload request, nothing to do
} else if (hm->body.len == (size_t) ~0 || hm->body.len < 2 * MG_IO_SIZE) {
// Unknown length, or small enough for mg_http_serve_dir() to buffer it
} else if (!uri2path(opts->root_dir, hm->uri, path, sizeof(path))) {
MG_ERROR(("Invalid upload path: %.*s", (int) hm->uri.len, hm->uri.buf));
} else if (fs->st(path, NULL, NULL) & MG_FS_DIR) {
// Target is a directory, let mg_http_serve_dir() list it
} else {
struct mg_fd *fd;
fs->rm(path); // MG_FS_WRITE appends, not truncates: drop any old file
if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
MG_ERROR(("Cannot open %s for upload", path));
} else if (!mg_http_stream_body(c, hm, serve_upload_cb, fd)) {
mg_fs_close(fd);
}
}
}
static bool mg_is_url_safe(int c) { static bool mg_is_url_safe(int c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~'; (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
@@ -1025,137 +1007,96 @@ int mg_http_status(const struct mg_http_message *hm) {
return atoi(hm->uri.buf); return atoi(hm->uri.buf);
} }
struct mg_upload_priv { // State of a streamed request or response body, kept in c->data. The callback
size_t expected; // is kept in c->fn_data, which is free because we own the connection
size_t received; struct mg_upload_state {
struct mg_fd *fd; // non-NULL: file upload; NULL: OTA size_t expected; // Number of body bytes to receive
void (*fn)(struct mg_connection *, const char *); size_t received; // Number of body bytes received so far
void *user_data; // Passed to cb, free for cb to use
bool failed; // Set when cb returned false
}; };
static void mg_upload_handler(struct mg_connection *c, int ev, void *ev_data) { // Event handler installed by mg_http_stream_body(). Feeds the body to the
struct mg_upload_priv *p = (struct mg_upload_priv *) c->data; // callback, then replies (servers only). It does not restore the previous
if (p->fn == NULL) return; // handler: the connection is closed after the reply.
if (ev == MG_EV_READ && c->recv.len > 0) { static void mg_stream_handler(struct mg_connection *c, int ev, void *ev_data) {
size_t alignment = 512; struct mg_upload_state *us = (struct mg_upload_state *) c->data;
size_t left = p->expected > p->received ? p->expected - p->received : 0; bool (*fn)(struct mg_http_message *, struct mg_str *, void **) =
size_t aligned = c->recv.len < left ? MG_ROUND_DOWN(c->recv.len, alignment) (bool (*)(struct mg_http_message *, struct mg_str *, void **))
: left; (ptrdiff_t) c->fn_data;
bool ok = true;
if (aligned > 0) {
if (p->fd != NULL) {
ok = p->fd->fs->wr(p->fd->fd, c->recv.buf, aligned) == aligned;
} else {
ok = mg_ota_write(c->recv.buf, aligned);
}
}
p->received += aligned;
mg_iobuf_del(&c->recv, 0, aligned);
if (!ok) {
if (p->fd != NULL) { mg_fs_close(p->fd); p->fd = NULL; }
else mg_ota_end();
p->fn(c, "write error");
mg_free(c->pfn_data); c->pfn_data = NULL; p->fn = NULL;
} else if (p->received >= p->expected) {
const char *errmsg = NULL;
if (p->fd != NULL) { mg_fs_close(p->fd); p->fd = NULL; }
else if (!mg_ota_end()) errmsg = "OTA finalize failed";
p->fn(c, errmsg);
mg_free(c->pfn_data); c->pfn_data = NULL; p->fn = NULL;
}
} else if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
if (p->fd != NULL) { mg_fs_close(p->fd); p->fd = NULL; }
else mg_ota_end();
p->fn(c, ev == MG_EV_ERROR ? (const char *) ev_data : "connection closed");
mg_free(c->pfn_data); c->pfn_data = NULL; p->fn = NULL;
}
(void) ev_data; (void) ev_data;
if (ev == MG_EV_CLOSE || ev == MG_EV_ERROR) {
if (us->received < us->expected) {
// Connection dropped mid-upload. Let cb clean up, e.g. call mg_ota_end()
us->received = us->expected; // MG_EV_ERROR is followed by MG_EV_CLOSE
fn(NULL, NULL, &us->user_data);
}
} else if (ev == MG_EV_READ && !c->is_draining) {
if (c->recv.len > 0 && us->received < us->expected) {
// Got some uploaded data. Feed by 512-byte aligned chunks, for OTA
size_t left = us->expected - us->received, r = c->recv.len;
size_t aligned = r < left ? MG_ROUND_DOWN(r, 512) : left;
struct mg_str data = mg_str_n((char *) c->recv.buf, aligned);
if (data.len > 0 && !us->failed) {
us->failed = !fn(NULL, &data, &us->user_data);
}
us->received += aligned;
mg_iobuf_del(&c->recv, 0, aligned); // Shift the unprocessed tail
}
if (us->received >= us->expected) {
// Finished upload. Always call cb, even after error, so it can clean up
us->failed |= !fn(NULL, NULL, &us->user_data);
if (!c->is_client) {
mg_http_reply(c, us->failed ? 500 : 200, NULL, "%zu %s\n",
us->received, us->failed ? "fail" : "ok");
}
c->is_draining = 1;
}
}
} }
static void mg_upload_default_cb(struct mg_connection *c, const char *status) { bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
MG_INFO(("%lu %s", c->id, status ? status : "ok")); bool (*cb)(struct mg_http_message *, struct mg_str *,
mg_http_reply(c, status ? 500 : 200, "", "%s\n", status ? status : "ok"); void **user_data),
} void *user_data) {
struct mg_upload_state *us = (struct mg_upload_state *) c->data;
struct mg_str *te = mg_http_get_header(hm, "Transfer-Encoding");
bool handled = false;
void mg_http_start_upload(struct mg_connection *c, struct mg_http_message *hm, // Catch upload requests early, without buffering whole body. Called on the
struct mg_str name, struct mg_str dir, // MG_EV_HTTP_HDRS event: we've received all HTTP headers but not necessarily
struct mg_fs *fs, // the full HTTP body
void (*fn)(struct mg_connection *, const char *)) { if (hm->body.len == (size_t) ~0 ||
struct mg_upload_priv *p = (struct mg_upload_priv *) c->data; (te != NULL && mg_strcasecmp(*te, mg_str("chunked")) == 0)) {
char path[MG_PATH_MAX]; // Unknown length or chunked, cannot stream. Leave it to the caller
struct mg_fd *fd; } else if (!c->is_client &&
if (fn == NULL) fn = mg_upload_default_cb; mg_strcmp(hm->method, mg_str("POST")) != 0 &&
if (sizeof(*p) > sizeof(c->data)) { fn(c, "data too small"); return; } mg_strcmp(hm->method, mg_str("PUT")) != 0) {
if (!mg_path_is_sane(name)) { fn(c, "bad name"); return; } // Not an upload request. Leave it to the caller
mg_snprintf(path, sizeof(path), "%.*s%c%.*s", (int) dir.len, dir.buf, } else if (sizeof(*us) > sizeof(c->data)) {
MG_DIRSEP, (int) name.len, name.buf); if (!c->is_client) { // Nobody to reply to on a client connection
fd = mg_fs_open(fs, path, MG_FS_WRITE); c->pfn = NULL;
if (fd == NULL) { fn(c, "open failed"); return; } mg_http_reply(c, 500, NULL, "data too small\n");
p->expected = hm->body.len; c->is_draining = 1;
p->received = 0; cb(NULL, NULL, &user_data); // Let cb release user_data, start skipped
p->fd = fd; handled = true;
p->fn = fn; }
c->fn = mg_upload_handler; } else {
c->pfn_data = strdup(path); c->pfn = NULL; // Silence HTTP protocol handler
c->pfn = NULL; memset(us, 0, sizeof(*us));
mg_iobuf_del(&c->recv, 0, hm->head.len); us->expected = hm->body.len; // Store number of bytes we expect
mg_call(c, MG_EV_READ, &c->recv.len); us->user_data = user_data;
} us->failed = !cb(hm, NULL, &us->user_data); // Call before deleting headers
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
void (*fn)(struct mg_connection *, const char *)) {
struct mg_upload_priv *p = (struct mg_upload_priv *) c->data;
if (fn == NULL) fn = mg_upload_default_cb;
if (sizeof(*p) > sizeof(c->data)) { fn(c, "data too small"); return; }
if (!mg_ota_begin(hm->body.len)) { fn(c, "ota begin failed"); return; }
p->expected = hm->body.len;
p->received = 0;
p->fd = NULL;
p->fn = fn;
c->fn = mg_upload_handler;
c->pfn = NULL;
mg_iobuf_del(&c->recv, 0, hm->head.len);
mg_call(c, MG_EV_READ, &c->recv.len);
}
void mg_http_stream_body(struct mg_connection *c, int ev, void *ev_data,
struct mg_str uri_pattern,
void (*cb)(struct mg_http_message *, struct mg_str *,
void **user_data)) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
// Catch upload requests early, without buffering whole body
// When we receive MG_EV_HTTP_HDRS event, that means we've received all
// HTTP headers but not necessarily full HTTP body
if (ev == MG_EV_HTTP_HDRS &&
(mg_strcmp(hm->method, mg_str("POST")) == 0 ||
mg_strcmp(hm->method, mg_str("PUT")) == 0) &&
hm->body.len != (size_t) ~0 && mg_match(hm->uri, uri_pattern, NULL)) {
c->pfn = NULL; // Silence HTTP protocol handler, we'll use MG_EV_READ
c->pfn_data = (void *) (ptrdiff_t) hm->body.len; // Record expected len
cb(hm, NULL, &c->fn_data); // Call handler before deleting headers
if (mg_http_get_header(hm, "Expect") != NULL) { if (mg_http_get_header(hm, "Expect") != NULL) {
mg_http_reply(c, 100, NULL, ""); // If curl expects, we continue mg_http_reply(c, 100, NULL, ""); // If curl expects, we continue
} }
mg_iobuf_del(&c->recv, 0, hm->head.len); // Delete HTTP headers mg_iobuf_del(&c->recv, 0, hm->head.len); // Delete HTTP headers
c->fn = mg_stream_handler; // We own the connection from now
c->fn_data = (void *) (ptrdiff_t) cb;
mg_call(c, MG_EV_READ, &c->recv.len); // Process the body bytes we have
handled = true;
} }
return handled;
if (c->pfn == NULL && ev != MG_EV_OPEN) {
if (c->pfn_data != NULL && c->recv.len > 0) {
// Got some uploaded data. Feed by 512-byte aligned chunks, for OTA
size_t left = (size_t) (ptrdiff_t) c->pfn_data, r = c->recv.len;
size_t aligned = r < left ? MG_ROUND_DOWN(r, 512) : left;
struct mg_str data = mg_str_n((char *) c->recv.buf, aligned);
if (data.len) cb(NULL, &data, &c->fn_data);
c->pfn_data = (void *) (ptrdiff_t) (left - aligned);
c->recv.len -= aligned;
}
if (c->pfn_data == NULL && c->is_draining == 0) {
// Finished upload
mg_http_reply(c, 200, NULL, "ok\n");
c->is_draining = 1;
cb(NULL, NULL, &c->fn_data);
}
}
} }
static bool is_hex_digit(int c) { static bool is_hex_digit(int c) {
@@ -1184,7 +1125,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
c->recv.len > 0)) { // see #2796 c->recv.len > 0)) { // see #2796
struct mg_http_message hm; struct mg_http_message hm;
size_t ofs = 0; // Parsing offset size_t ofs = 0; // Parsing offset
while (c->is_resp == 0 && ofs < c->recv.len) { // c->pfn_data is the "response generation in progress" marker. While it
// is set, don't parse the next pipelined request, to keep responses in order
while (c->pfn_data == NULL && ofs < c->recv.len) {
const char *buf = (char *) c->recv.buf + ofs; const char *buf = (char *) c->recv.buf + ofs;
int n = mg_http_parse(buf, c->recv.len - ofs, &hm); int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
struct mg_str *te; // Transfer - encoding header struct mg_str *te; // Transfer - encoding header
@@ -1277,9 +1220,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
ofs += (size_t) n + hm.body.len; ofs += (size_t) n + hm.body.len;
} }
if (c->is_accepted) c->is_resp = 1; // Start generating response if (c->is_accepted) c->pfn_data = c; // Response started
mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp mg_call(c, MG_EV_HTTP_MSG, &hm); // Handler sets pfn_data NULL when done
if (c->is_accepted && !c->is_resp) { if (c->is_accepted && c->pfn_data == NULL) {
struct mg_str *cc = mg_http_get_header(&hm, "Connection"); struct mg_str *cc = mg_http_get_header(&hm, "Connection");
if (cc != NULL && mg_strcasecmp(*cc, mg_str("close")) == 0) { if (cc != NULL && mg_strcasecmp(*cc, mg_str("close")) == 0) {
c->is_draining = 1; // honor "Connection: close" c->is_draining = 1; // honor "Connection: close"
+38 -31
View File
@@ -32,6 +32,9 @@ struct mg_http_serve_opts {
const char *mime_types; // Additional MIME types: "ext1=type1,ext2=type2". NULL for defaults only const char *mime_types; // Additional MIME types: "ext1=type1,ext2=type2". NULL for defaults only
const char *page404; // Path to a custom 404 page, e.g. "/404.html". NULL for built-in const char *page404; // Path to a custom 404 page, e.g. "/404.html". NULL for built-in
struct mg_fs *fs; // Filesystem to use. NULL defaults to POSIX struct mg_fs *fs; // Filesystem to use. NULL defaults to POSIX
bool enable_delete; // Allow to DELETE files
bool enable_upload; // Allow to POST/PUT files
bool enable_dir_listing; // Enable directory listing
}; };
// A single part of a multipart/form-data body, filled by mg_http_next_multipart(). // A single part of a multipart/form-data body, filled by mg_http_next_multipart().
@@ -105,8 +108,11 @@ struct mg_connection *mg_http_connect(struct mg_mgr *, const char *url,
// mg_http_listen(), mg_http_serve_file(), mg_http_reply(), mg_match() // mg_http_listen(), mg_http_serve_file(), mg_http_reply(), mg_match()
// Notes: // Notes:
// Call from an MG_EV_HTTP_MSG handler. The uri in hm is mapped under // Call from an MG_EV_HTTP_MSG handler. The uri in hm is mapped under
// opts->root_dir. Directory listing depends on MG_ENABLE_DIRLIST; SSI uses // opts->root_dir. opts->enable_dir_listing enables directory listing; SSI
// opts->ssi_pattern when configured. // uses opts->ssi_pattern when configured. opts->enable_delete enables
// DELETE; opts->enable_upload enables POST/PUT, writing the whole body to
// a file - see mg_http_serve_upload() to also stream big uploads without
// buffering.
void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm, void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
const struct mg_http_serve_opts *); const struct mg_http_serve_opts *);
@@ -114,6 +120,15 @@ void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
void mg_http_serve_file(struct mg_connection *, struct mg_http_message *hm, void mg_http_serve_file(struct mg_connection *, struct mg_http_message *hm,
const char *path, const struct mg_http_serve_opts *); const char *path, const struct mg_http_serve_opts *);
// Streams a big POST/PUT upload straight to a file, instead of buffering the
// whole body. Optional companion to mg_http_serve_dir(): call this from
// MG_EV_HTTP_HDRS with the same opts, and keep calling mg_http_serve_dir()
// from MG_EV_HTTP_MSG as usual - it still handles uploads this function skips.
// Does nothing unless opts->enable_upload is set, the method is POST or PUT,
// and Content-Length is known and big enough.
void mg_http_serve_upload(struct mg_connection *, struct mg_http_message *hm,
const struct mg_http_serve_opts *);
// Sends a complete HTTP response with Content-Length. // Sends a complete HTTP response with Content-Length.
// //
// Example: // Example:
@@ -160,20 +175,6 @@ void mg_http_creds(struct mg_http_message *, char *, size_t, char *, size_t);
long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm, long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
struct mg_fs *fs, const char *dir, size_t max_size); struct mg_fs *fs, const char *dir, size_t max_size);
// Streams the raw request body into dir/name via fs. Non-blocking: installs an
// internal handler and returns immediately. fn is called with NULL on success
// or an error string on failure.
void mg_http_start_upload(struct mg_connection *c, struct mg_http_message *hm,
struct mg_str name, struct mg_str dir,
struct mg_fs *fs,
void (*fn)(struct mg_connection *, const char *));
// Starts an OTA firmware update from an HTTP POST upload.
// Calls mg_ota_begin/write/end internally; fn is called with NULL on success,
// or an error string on failure.
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
void (*fn)(struct mg_connection *, const char *));
// Sends a 401 Unauthorized response with a Basic Auth WWW-Authenticate challenge. // Sends a 401 Unauthorized response with a Basic Auth WWW-Authenticate challenge.
void mg_http_bauth(struct mg_connection *, const char *user, const char *pass); void mg_http_bauth(struct mg_connection *, const char *user, const char *pass);
@@ -192,7 +193,7 @@ struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v);
// Full examples: // Full examples:
// tutorials/http/file-upload-html-form, tutorials/http/http-server // tutorials/http/file-upload-html-form, tutorials/http/http-server
// Related APIs: // Related APIs:
// mg_http_listen(), mg_http_start_upload() // mg_http_listen(), mg_http_stream_body()
// Notes: // Notes:
// Call from an MG_EV_HTTP_MSG handler after the full request body is // Call from an MG_EV_HTTP_MSG handler after the full request body is
// received. part.name, part.filename, and part.body are zero-copy slices into // received. part.name, part.filename, and part.body are zero-copy slices into
@@ -203,24 +204,30 @@ size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *);
int mg_http_status(const struct mg_http_message *hm); int mg_http_status(const struct mg_http_message *hm);
// Streams a POST/PUT body to a callback as it arrives, without buffering it. // Streams a POST/PUT body to a callback as it arrives, without buffering it.
// Call it from your connection handler on every event. // Call it from an MG_EV_HTTP_HDRS handler, after matching the request, e.g.
// with mg_match(). Returns true if it took over the connection, false if the
// request is not POST/PUT, is chunked, or has no Content-Length.
// //
// Callback upload_fn(hm, data, user_data) is called: // Callback upload_fn(hm, data, user_data) is called:
// - at start: hm is set, data is NULL. Open the file, set user_data. // - at start: hm is set. Open the file, set *user_data.
// - per chunk: hm is NULL, data is set. Chunks are 512 bytes aligned // - per chunk: data is set, 512 byte aligned except the last. Not called
// except the last one. // again after a failure.
// - at end: both NULL. Close the file. // - at end: both NULL. Always called once, also when the connection drops
// After the last chunk, "200 ok" is sent and the connection is drained. // early, so release resources here. A truncated body looks like a complete
// one: validate before committing.
// Return true on success, false on error.
// Example: // Example:
// mg_http_stream_body(c, ev, ev_data, mg_str("/fs/*"), upload); // if (ev == MG_EV_HTTP_HDRS && mg_match(hm->uri, mg_str("/fs/*"), NULL) {
// mg_http_stream_body(c, hm, upload, NULL));
// }
// Full example: // Full example:
// tutorials/http/file-upload-single-post // tutorials/http/file-upload-single-post
// Related APIs: // Related APIs:
// mg_http_start_upload(), mg_http_start_ota() // mg_http_listen(), mg_http_next_multipart()
// Notes: // Notes:
// Requires Content-Length, chunked bodies are not streamed. user_data is // After it returns true, this function hijacks the connection. Existing event
// &c->fn_data. While streaming, c->pfn is NULL // handler not called, hm is invalid, c->data and c->fn_data are modified
void mg_http_stream_body(struct mg_connection *c, int ev, void *ev_data, bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
struct mg_str uri_pattern, bool (*upload_fn)(struct mg_http_message *,
void (*upload_fn)(struct mg_http_message *, struct mg_str *, void **user_data),
struct mg_str *, void **user_data)); void *user_data);
+67 -52
View File
@@ -3,19 +3,18 @@
#include "flash.h" #include "flash.h"
#include "util.h" #include "util.h"
#include "lfs.h"
#if MG_ENABLE_LFS #if MG_ENABLE_LFS
#include <fcntl.h>
#include <littlefs/lfs.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef LFS_USE_RAM #ifndef LFS_USE_RAM
#define LFS_USE_RAM 0 // If 1, use RAM FS. If 0, use flash #define LFS_USE_RAM 0 // If 1, use RAM FS. If 0, use flash
#endif #endif
#ifndef MG_LFS_SIZE
#define MG_LFS_SIZE (64 * 1024)
#endif
#ifndef MG_LFS_BUF_SIZE #ifndef MG_LFS_BUF_SIZE
#define MG_LFS_BUF_SIZE 64 // Buffer size used for reads, writes, and cache #define MG_LFS_BUF_SIZE 64 // Buffer size used for reads, writes, and cache
#endif #endif
@@ -28,19 +27,6 @@
#define MG_LFS_BLOCK_SIZE 8192 #define MG_LFS_BLOCK_SIZE 8192
#endif #endif
#ifndef DT_DIR
#define DT_DIR 4
#endif
#ifndef DT_REG
#define DT_REG 8
#endif
typedef struct mg_lfs_fd DIR;
struct dirent {
char d_name[LFS_NAME_MAX + 1];
unsigned char d_type;
};
struct mg_lfs_fd { struct mg_lfs_fd {
struct mg_lfs_fd *next; struct mg_lfs_fd *next;
bool isopen; bool isopen;
@@ -52,7 +38,6 @@ struct mg_lfs_fd {
static lfs_t s_lfs; static lfs_t s_lfs;
static struct mg_lfs_fd *s_fds; static struct mg_lfs_fd *s_fds;
static uint8_t *s_fs; static uint8_t *s_fs;
static int s_next_fd = MG_LFS_FD_BASE;
static bool s_lfs_ready; static bool s_lfs_ready;
#if LFS_USE_RAM #if LFS_USE_RAM
static uint8_t *s_ram_fs; static uint8_t *s_ram_fs;
@@ -110,29 +95,50 @@ static int lfs_driver_sync(const struct lfs_config *cfg) {
} }
bool mg_lfs_init(size_t size) { bool mg_lfs_init(size_t size) {
int result = 0; //bool ok = false;
MG_DEBUG(("size: %zu", size));
if (s_lfs_ready) return true; if (s_lfs_ready) return true;
if (size == 0) return false; if (size == 0) {
MG_ERROR(("invalidsize = 0"));
} else {
#if LFS_USE_RAM #if LFS_USE_RAM
s_cfg.block_size = MG_LFS_BLOCK_SIZE; s_cfg.block_size = MG_LFS_BLOCK_SIZE;
if (s_ram_fs == NULL) s_ram_fs = (uint8_t *) mg_calloc(1, size); if (s_ram_fs == NULL) s_ram_fs = (uint8_t *) mg_calloc(1, size);
s_fs = s_ram_fs; s_fs = s_ram_fs;
#else #else
if (mg_flash == NULL || mg_flash->secsz == 0 || mg_flash->size < size) return false; {
if (mg_flash->write_fn == NULL) return false; // Some flash attributes may be initialised on ota_begin
s_cfg.block_size = mg_flash->secsz; int lev = mg_log_level;
s_fs = (uint8_t *) mg_flash->start + mg_flash->size - size; mg_log_level = MG_LL_NONE;
mg_ota_begin(1);
mg_ota_end();
mg_log_set(lev);
}
if (mg_flash == NULL || mg_flash->secsz == 0 || mg_flash->size < size) {
MG_ERROR(("mg_flash %p secsz %zu flash_size %zu < size %zu", mg_flash, mg_flash->secsz, mg_flash->size, size));
} else if (mg_flash->write_fn == NULL) {
MG_ERROR(("flash write_fn == NULL"));
} else {
s_cfg.block_size = mg_flash->secsz;
s_fs = (uint8_t *) mg_flash->start + mg_flash->size - size;
}
#endif #endif
if (s_fs == NULL || s_cfg.block_size == 0 || size % s_cfg.block_size != 0) { if (s_fs == NULL || s_cfg.block_size == 0 || size % s_cfg.block_size != 0) {
return false; MG_ERROR(("s_fs %p blk_size %zu size %zu", s_fs, s_cfg.block_size));
} else {
s_cfg.block_count = (lfs_size_t) (size / s_cfg.block_size);
if (s_cfg.block_count == 0) {
MG_ERROR(("blk_count == 0"));
} else {
if (lfs_mount(&s_lfs, &s_cfg) != 0) lfs_format(&s_lfs, &s_cfg);
if (lfs_mount(&s_lfs, &s_cfg) != 0) {
MG_ERROR(("lfs_mount"));
} else {
s_lfs_ready = true;
}
}
}
} }
s_cfg.block_count = (lfs_size_t) (size / s_cfg.block_size);
if (s_cfg.block_count == 0) return false;
if (lfs_mount(&s_lfs, &s_cfg) != 0) {
lfs_format(&s_lfs, &s_cfg);
if (lfs_mount(&s_lfs, &s_cfg) != 0) result = -1;
}
s_lfs_ready = result == 0;
return s_lfs_ready; return s_lfs_ready;
} }
@@ -145,16 +151,12 @@ static struct mg_lfs_fd *find_fd(int fd) {
} }
static struct mg_lfs_fd *open_fd(void) { static struct mg_lfs_fd *open_fd(void) {
struct mg_lfs_fd *f = NULL; struct mg_lfs_fd *f = NULL, *p = s_fds;
if (s_lfs_ready) { if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
f = (struct mg_lfs_fd *) mg_calloc(1, sizeof(*f)); if (s_lfs_ready && (f = (struct mg_lfs_fd *) mg_calloc(1, sizeof(*f)))) {
if (f != NULL) { f->isopen = true, f->fd = MG_LFS_FD_BASE, f->next = s_fds;
f->isopen = true; while (p != NULL) p = p->fd == f->fd ? (f->fd++, s_fds) : p->next;
f->fd = s_next_fd++; s_fds = f;
f->next = s_fds;
s_fds = f;
if (s_next_fd < MG_LFS_FD_BASE) s_next_fd = MG_LFS_FD_BASE;
}
} }
return f; return f;
} }
@@ -173,6 +175,7 @@ int _open(const char *path, int flags, mode_t mode) {
int err, lfs_flags = 0, fd = -1; int err, lfs_flags = 0, fd = -1;
struct mg_lfs_fd *f = open_fd(); struct mg_lfs_fd *f = open_fd();
(void) mode; (void) mode;
MG_DEBUG(("%s -> %p, lfs_ready %d", path, f, s_lfs_ready));
if (f == NULL) return -1; if (f == NULL) return -1;
fd = f->fd; fd = f->fd;
if ((flags & 3) == O_RDONLY) lfs_flags |= LFS_O_RDONLY; if ((flags & 3) == O_RDONLY) lfs_flags |= LFS_O_RDONLY;
@@ -214,11 +217,21 @@ int _lseek(int fd, int offset, int whence) {
} }
int _rename(const char *oldname, const char *newname) { int _rename(const char *oldname, const char *newname) {
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
return s_lfs_ready ? lfs_rename(&s_lfs, oldname, newname) : -1; return s_lfs_ready ? lfs_rename(&s_lfs, oldname, newname) : -1;
} }
int _unlink_r(void *r, const char *a) { // Some libc rename() implementations have no atomic rename syscall and emulate
(void) r; // it as link() + unlink() instead of calling _rename() directly. LittleFS has
// no real hard links, but forwarding to _rename() gives the same end result
// (oldname becomes newname), which is all mg_file_write()'s atomic-write
// pattern (write to a temp file, then rename it into place) needs
int _link(const char *oldname, const char *newname) {
return _rename(oldname, newname);
}
int _unlink(const char *a) {
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
return s_lfs_ready ? lfs_remove(&s_lfs, a) : -1; return s_lfs_ready ? lfs_remove(&s_lfs, a) : -1;
} }
@@ -227,7 +240,7 @@ DIR *opendir(const char *name) {
if (f == NULL) return NULL; if (f == NULL) return NULL;
if (lfs_dir_open(&s_lfs, &f->dir, name) != 0) { if (lfs_dir_open(&s_lfs, &f->dir, name) != 0) {
close_fd(f); close_fd(f);
return NULL; f = NULL;
} }
return (DIR *) f; return (DIR *) f;
} }
@@ -254,7 +267,9 @@ struct dirent *readdir(DIR *dir) {
int _stat(const char *path, struct stat *st) { int _stat(const char *path, struct stat *st) {
struct lfs_info info; struct lfs_info info;
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
if (!s_lfs_ready || lfs_stat(&s_lfs, path, &info) != 0) return -1; if (!s_lfs_ready || lfs_stat(&s_lfs, path, &info) != 0) return -1;
memset(st, 0, sizeof(*st));
st->st_mode = info.type == LFS_TYPE_DIR ? S_IFDIR : S_IFREG; st->st_mode = info.type == LFS_TYPE_DIR ? S_IFDIR : S_IFREG;
st->st_size = info.size; st->st_size = info.size;
return 0; return 0;
@@ -268,7 +283,7 @@ int _fstat(int fd, struct stat *st) {
int mkdir(const char *path, mode_t mode) { int mkdir(const char *path, mode_t mode) {
(void) mode; (void) mode;
if (s_lfs_ready == false) mg_lfs_init(MG_LFS_SIZE);
return s_lfs_ready ? lfs_mkdir(&s_lfs, path) : -1; return s_lfs_ready ? lfs_mkdir(&s_lfs, path) : -1;
} }
#endif #endif
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#if MG_ENABLE_LFS
#include <fcntl.h>
#include <lfs.h>
#ifndef DT_DIR
#define DT_DIR 4
#endif
#ifndef DT_REG
#define DT_REG 8
#endif
struct dirent {
char d_name[LFS_NAME_MAX + 1];
unsigned char d_type;
};
typedef struct mg_lfs_fd DIR;
#endif
+28 -14
View File
@@ -55,7 +55,10 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
// c->is_hexdumping = true; // c->is_hexdumping = true;
if (mg_url_is_ssl(MG_MDASH_URL)) { if (mg_url_is_ssl(MG_MDASH_URL)) {
struct mg_str host = mg_url_host(MG_MDASH_URL); struct mg_str host = mg_url_host(MG_MDASH_URL);
struct mg_tls_opts opts = {.ca = mg_str(mg_mdash_ca_pem), .name = host}; struct mg_tls_opts opts;
memset(&opts, 0, sizeof(struct mg_tls_opts));
opts.ca = mg_str(mg_mdash_ca_pem);
opts.name = host;
mg_tls_init(c, &opts); mg_tls_init(c, &opts);
} }
} }
@@ -65,16 +68,18 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
// mDashTriggerEvent(s_mDashState, NULL); // mDashTriggerEvent(s_mDashState, NULL);
} else if (ev == MG_EV_WS_MSG) { } else if (ev == MG_EV_WS_MSG) {
struct mg_iobuf io = {0, 0, 0, 512}; struct mg_iobuf io = {0, 0, 0, 512};
struct mg_ws_message *wm = ev_data; struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
struct mg_str s = wm->data; struct mg_str s = wm->data;
struct mg_rpc_req r;
while (s.len > 0 && isspace((uint8_t) s.buf[s.len - 1])) s.len--; while (s.len > 0 && isspace((uint8_t) s.buf[s.len - 1])) s.len--;
MG_INFO(("RPC: %.*s", (int) s.len, s.buf)); MG_INFO(("RPC: %.*s", (int) s.len, s.buf));
struct mg_rpc_req r = {.head = &c->mgr->rpcs, memset(&r, 0, sizeof(struct mg_rpc_req));
.rpc = NULL, r.head = &c->mgr->rpcs;
.pfn = mg_pfn_iobuf, r.rpc = NULL;
.pfn_data = &io, r.pfn = mg_pfn_iobuf;
.req_data = NULL, r.pfn_data = &io;
.frame = s}; r.req_data = NULL;
r.frame = s;
mg_rpc_process(&r); mg_rpc_process(&r);
if (io.buf != NULL) { if (io.buf != NULL) {
MG_INFO((" %s", io.buf)); MG_INFO((" %s", io.buf));
@@ -91,11 +96,13 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
} }
static void mg_mdash_rpc_get_info(struct mg_rpc_req *r) { static void mg_mdash_rpc_get_info(struct mg_rpc_req *r) {
mg_rpc_ok(r, "{%m:%m,%m:%llu,%m:%m,%m:\"mws.%d\"}", MG_ESC("fw_version"), const char *reset_reason = mg_health_reason_str(mg_health_reason());
MG_ESC(MG_MDASH_FIRMWARE_VERSION), MG_ESC("uptime"), mg_rpc_ok(r, "{%m:%m,%m:%llu,%m:%m,%m:\"mws.%d\",%m:%M}", //
(uint64_t) (mg_millis() / 1000), MG_ESC("reboot_reason"), MG_ESC("fw_version"), MG_ESC(MG_FIRMWARE_VERSION), //
MG_ESC(mg_health_reason_str(mg_health_reason())), MG_ESC("arch"), MG_ESC("uptime"), (uint64_t) (mg_millis() / 1000), //
MG_ARCH); MG_ESC("reboot_reason"), MG_ESC(reset_reason), //
MG_ESC("arch"), MG_ARCH, //
MG_ESC("crash"), mg_print_crash_record);
} }
static void mg_mdash_rpc_ota_begin(struct mg_rpc_req *r) { static void mg_mdash_rpc_ota_begin(struct mg_rpc_req *r) {
@@ -114,7 +121,7 @@ static void mg_mdash_rpc_ota_write(struct mg_rpc_req *r) {
mg_rpc_err(r, 500, "%m", MG_ESC("data required")); mg_rpc_err(r, 500, "%m", MG_ESC("data required"));
} else { } else {
struct mg_str s = mg_str_n(&r->frame.buf[ofs] + 1, (size_t) (len - 2)); struct mg_str s = mg_str_n(&r->frame.buf[ofs] + 1, (size_t) (len - 2));
size_t n = mg_base64_decode(s.buf, s.len, s.buf, s.len); // Decode in-place size_t n = mg_base64_decode(s.buf, s.len, s.buf, s.len); // Decode in-place
if (n == 0) { if (n == 0) {
mg_rpc_ok(r, "%m", MG_ESC("finished")); mg_rpc_ok(r, "%m", MG_ESC("finished"));
mg_ota_end(); mg_ota_end();
@@ -159,6 +166,10 @@ void mg_mdash_poll(struct mg_mgr *mgr) {
} }
} }
void mg_mdash_free(struct mg_mgr *mgr) {
mg_rpc_del(&mgr->rpcs, NULL);
}
#else #else
void mg_mdash_init(struct mg_mgr *mgr) { void mg_mdash_init(struct mg_mgr *mgr) {
(void) mgr; (void) mgr;
@@ -166,4 +177,7 @@ void mg_mdash_init(struct mg_mgr *mgr) {
void mg_mdash_poll(struct mg_mgr *mgr) { void mg_mdash_poll(struct mg_mgr *mgr) {
(void) mgr; (void) mgr;
} }
void mg_mdash_free(struct mg_mgr *mgr) {
(void) mgr;
}
#endif #endif
+1 -4
View File
@@ -12,13 +12,10 @@
#define MG_MDASH_KEY "" #define MG_MDASH_KEY ""
#endif #endif
#ifndef MG_MDASH_FIRMWARE_VERSION
#define MG_MDASH_FIRMWARE_VERSION "1.0.0"
#endif
#ifndef MG_ENABLE_MDASH #ifndef MG_ENABLE_MDASH
#define MG_ENABLE_MDASH 0 #define MG_ENABLE_MDASH 0
#endif #endif
void mg_mdash_init(struct mg_mgr *); void mg_mdash_init(struct mg_mgr *);
void mg_mdash_poll(struct mg_mgr *); void mg_mdash_poll(struct mg_mgr *);
void mg_mdash_free(struct mg_mgr *);
+11 -6
View File
@@ -1,8 +1,8 @@
#include "net.h"
#include "dns.h" #include "dns.h"
#include "fmt.h" #include "fmt.h"
#include "log.h" #include "log.h"
#include "mdash.h" #include "mdash.h"
#include "net.h"
#include "printf.h" #include "printf.h"
#include "profile.h" #include "profile.h"
#include "timer.h" #include "timer.h"
@@ -39,10 +39,10 @@ bool mg_dscp(struct mg_connection *c, uint8_t dscp) {
int tos = dscp << 2, level = IPPROTO_IP, optname = IP_TOS; int tos = dscp << 2, level = IPPROTO_IP, optname = IP_TOS;
c->dscp = (unsigned) (dscp & 63); c->dscp = (unsigned) (dscp & 63);
#if MG_ENABLE_IPV6 && !MG_ENABLE_LWIP #if MG_ENABLE_IPV6 && !MG_ENABLE_LWIP
if (c->loc.is_ip6) if (c->loc.is_ip6) level = IPPROTO_IPV6, optname = IPV6_TCLASS;
level = IPPROTO_IPV6, optname = IPV6_TCLASS;
#endif #endif
return setsockopt((MG_SOCKET_TYPE) (size_t) c->fd, level, optname, (char *) &tos, sizeof(tos)) == 0; return setsockopt((MG_SOCKET_TYPE) (size_t) c->fd, level, optname,
(char *) &tos, sizeof(tos)) == 0;
#endif #endif
#elif MG_ENABLE_TCPIP #elif MG_ENABLE_TCPIP
c->dscp = (unsigned) (dscp & 63); c->dscp = (unsigned) (dscp & 63);
@@ -300,6 +300,9 @@ void mg_mgr_free(struct mg_mgr *mgr) {
mgr->timers = NULL; // Important. Next call to poll won't touch timers mgr->timers = NULL; // Important. Next call to poll won't touch timers
for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1; for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
mg_mgr_poll(mgr, 0); mg_mgr_poll(mgr, 0);
#if MG_ENABLE_MDASH
mg_mdash_free(mgr);
#endif
#if MG_ENABLE_FREERTOS_TCP #if MG_ENABLE_FREERTOS_TCP
FreeRTOS_DeleteSocketSet(mgr->ss); FreeRTOS_DeleteSocketSet(mgr->ss);
#endif #endif
@@ -343,13 +346,15 @@ void mg_mgr_init(struct mg_mgr *mgr) {
mgr->dns4.url = "udp://8.8.8.8:53"; mgr->dns4.url = "udp://8.8.8.8:53";
mgr->dns6.url = "udp://[2001:4860:4860::8888]:53"; mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
mg_tls_ctx_init(mgr); mg_tls_ctx_init(mgr);
MG_DEBUG(("MG_IO_SIZE: %lu, TLS: %s", MG_IO_SIZE, MG_DEBUG(("MG_IO_SIZE: %lu, TLS: %s, conn size: %zu, mgr size: %zu",
MG_IO_SIZE,
MG_TLS == MG_TLS_NONE ? "none" MG_TLS == MG_TLS_NONE ? "none"
: MG_TLS == MG_TLS_MBED ? "MbedTLS" : MG_TLS == MG_TLS_MBED ? "MbedTLS"
: MG_TLS == MG_TLS_OPENSSL ? "OpenSSL" : MG_TLS == MG_TLS_OPENSSL ? "OpenSSL"
: MG_TLS == MG_TLS_BUILTIN ? "builtin" : MG_TLS == MG_TLS_BUILTIN ? "builtin"
: MG_TLS == MG_TLS_WOLFSSL ? "WolfSSL" : MG_TLS == MG_TLS_WOLFSSL ? "WolfSSL"
: "custom")); : "custom",
sizeof(struct mg_connection), sizeof(struct mg_mgr)));
#if MG_ENABLE_MDASH #if MG_ENABLE_MDASH
mg_mdash_init(mgr); mg_mdash_init(mgr);
#endif #endif
-1
View File
@@ -95,7 +95,6 @@ struct mg_connection {
unsigned is_closing : 1; // Close and free immediately on next poll unsigned is_closing : 1; // Close and free immediately on next poll
unsigned is_full : 1; // Pause incoming reads until cleared unsigned is_full : 1; // Pause incoming reads until cleared
unsigned is_tls_throttled : 1; // TLS write was throttled; retry pending unsigned is_tls_throttled : 1; // TLS write was throttled; retry pending
unsigned is_resp : 1; // HTTP: response is still being generated
unsigned is_readable : 1; // Socket is ready to read (epoll/select) unsigned is_readable : 1; // Socket is ready to read (epoll/select)
unsigned is_writable : 1; // Socket is ready to write (epoll/select) unsigned is_writable : 1; // Socket is ready to write (epoll/select)
}; };
+2
View File
@@ -2265,6 +2265,8 @@ void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
// MG_EPHEMERAL_PORT_BASE to 65535 // MG_EPHEMERAL_PORT_BASE to 65535
if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM")); if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
MG_DEBUG(("Builtin TCP/IP init done. Queue size: %zu, extra conn size: %zu",
ifp->recv_queue.size, mgr->extraconnsize));
} }
} }
+37 -5
View File
@@ -13,7 +13,7 @@
// Scannable version tag embedded in every firmware binary, for server-side // Scannable version tag embedded in every firmware binary, for server-side
// version extraction. The version string starts after the "MG_VERSION:" prefix. // version extraction. The version string starts after the "MG_VERSION:" prefix.
static const char s_fw_version[] = "MG_VERSION:" MG_OTA_FIRMWARE_VERSION; static const char s_fw_version[] = "MG_VERSION:" MG_FIRMWARE_VERSION;
static bool s_autocommit_ok; // True after OTA server confirms "same version" static bool s_autocommit_ok; // True after OTA server confirms "same version"
@@ -23,6 +23,9 @@ static struct mg_ota_state {
size_t size; size_t size;
uint8_t sha256[32]; uint8_t sha256[32];
void (*fn)(const char *error_message); void (*fn)(const char *error_message);
size_t received; // Firmware bytes written so far
bool open; // mg_ota_begin() succeeded, mg_ota_end() is pending
const char *err; // First error during download, NULL if none
} *s_ota; } *s_ota;
static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data); static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data);
@@ -143,11 +146,38 @@ static void status_fn(const char *errmsg) {
if (errmsg) MG_ERROR(("OTA failed: %s", errmsg)); if (errmsg) MG_ERROR(("OTA failed: %s", errmsg));
} }
static void status_fn_2(struct mg_connection *c, const char *errmsg) { // Firmware download callback for mg_http_stream_body(). Writes chunks to the
if (s_ota) s_ota->fn(errmsg); // OTA target and reports the result via s_ota->fn(). The end call also happens
// when the connection drops before the whole body arrived.
static bool s_firmware_cb(struct mg_http_message *hm, struct mg_str *data,
void **p) {
bool finalized = false, ok;
(void) p;
if (s_ota == NULL) return false;
if (hm != NULL) { // Start
s_ota->received = 0;
s_ota->open = mg_ota_begin(hm->body.len);
if (!s_ota->open) s_ota->err = "OTA begin failed";
return s_ota->open;
} else if (data != NULL) { // Next chunk
if (!mg_ota_write(data->buf, data->len)) {
s_ota->err = "OTA write failed";
return false;
}
s_ota->received += data->len;
return true;
}
// End
if (s_ota->open) finalized = mg_ota_end();
if (s_ota->err == NULL && s_ota->received != s_ota->size) {
s_ota->err = "Connection closed";
}
if (s_ota->err == NULL && !finalized) s_ota->err = "OTA finalize failed";
ok = s_ota->err == NULL;
s_ota->fn(s_ota->err);
mg_free(s_ota); mg_free(s_ota);
s_ota = NULL; s_ota = NULL;
mg_http_reply(c, errmsg ? 500 : 200, "", "%s\n", errmsg ? errmsg : "ok"); return ok;
} }
static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data) { static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data) {
@@ -178,7 +208,9 @@ static void s_firmware_fn(struct mg_connection *c, int ev, void *ev_data) {
(unsigned long) hm->body.len, (unsigned long) s_ota->size); (unsigned long) hm->body.len, (unsigned long) s_ota->size);
} else { } else {
MG_DEBUG(("Beginning OTA (%lu bytes)", (unsigned long) s_ota->size)); MG_DEBUG(("Beginning OTA (%lu bytes)", (unsigned long) s_ota->size));
mg_http_start_ota(c, hm, status_fn_2); if (!mg_http_stream_body(c, hm, s_firmware_cb, NULL)) {
mg_error(c, "Cannot stream firmware");
}
} }
} else if (ev == MG_EV_ERROR) { } else if (ev == MG_EV_ERROR) {
s_ota->fn((char *) ev_data); s_ota->fn((char *) ev_data);
+4 -4
View File
@@ -3,7 +3,7 @@
// This is a low-level OTA API, not intended to be called directly by users. // This is a low-level OTA API, not intended to be called directly by users.
// Users are provided with a higher-level API: // Users are provided with a higher-level API:
// - defining MG_OTA_URL enables HTTP or HTTPS pull-based updates // - defining MG_OTA_URL enables HTTP or HTTPS pull-based updates
// - mg_http_start_ota() enables push-based updates // - mg_http_stream_body() enables push-based updates
// //
// However, it is possible to use the mg_ota_* API directly. Below is the // However, it is possible to use the mg_ota_* API directly. Below is the
// example code of a function that is called repeatedly. It expects the // example code of a function that is called repeatedly. It expects the
@@ -154,7 +154,7 @@ enum {
// needs to be defined. Fetches metadata_url, which must // needs to be defined. Fetches metadata_url, which must
// return a JSON object like: // return a JSON object like:
// { "version": "1.2.3", "url": "FIRMWARE_URL", "size": 324645 } // { "version": "1.2.3", "url": "FIRMWARE_URL", "size": 324645 }
// If the server version differs from MG_OTA_FIRMWARE_VERSION, downloads // If the server version differs from MG_FIRMWARE_VERSION, downloads
// FIRMWARE_URL and performs the OTA update. fn is called on every outcome: // FIRMWARE_URL and performs the OTA update. fn is called on every outcome:
// NULL on successful flash, "Same version" when already up to date, or an // NULL on successful flash, "Same version" when already up to date, or an
// error string on failure. Pass NULL to use the default handler which logs // error string on failure. Pass NULL to use the default handler which logs
@@ -181,8 +181,8 @@ void mg_ota_url_check(struct mg_mgr *mgr, const char *metadata_url,
#endif #endif
// Firmware version for mg_ota_poll(). Settable in mongoose_config.h // Firmware version for mg_ota_poll(). Settable in mongoose_config.h
#ifndef MG_OTA_FIRMWARE_VERSION #ifndef MG_FIRMWARE_VERSION
#define MG_OTA_FIRMWARE_VERSION "1.0.0" #define MG_FIRMWARE_VERSION "1.0.0"
#endif #endif
// Maximum version string length // Maximum version string length
+5 -7
View File
@@ -291,24 +291,22 @@ MG_IRAM static bool mg_frdm_write(void *addr, const void *buf, size_t len) {
} }
uint32_t status; uint32_t status;
uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_frdm.start; uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_frdm.start;
size_t tmp_buf_size = s_mg_flash_frdm.align / sizeof(uint32_t);
uint32_t tmp[tmp_buf_size];
if ((char *) buf >= (char *) s_mg_flash_frdm.start && if ((char *) buf >= (char *) s_mg_flash_frdm.start &&
(char *) buf < (char *) buf <
(char *) (s_mg_flash_frdm.start + s_mg_flash_frdm.size)) { (char *) (s_mg_flash_frdm.start + s_mg_flash_frdm.size)) {
// If we copy from FLASH to FLASH, then we first need to copy the source // If we copy from FLASH to FLASH, then we first need to copy the source
// to RAM // to RAM
size_t tmp_buf_size = s_mg_flash_frdm.align / sizeof(uint32_t);
uint32_t tmp[tmp_buf_size];
for (size_t i = 0; i < tmp_buf_size; i++) { for (size_t i = 0; i < tmp_buf_size; i++) {
flash_wait(); flash_wait();
tmp[i] = src[i]; tmp[i] = src[i];
} }
status = flexspi_nor->page_program(MG_FLEXSPI_NOR_INSTANCE, &config,
(uint32_t) dst_ofs, tmp, false);
} else { } else {
status = flexspi_nor->page_program(MG_FLEXSPI_NOR_INSTANCE, &config, memcpy(tmp, src, sizeof(tmp));
(uint32_t) dst_ofs, src, false);
} }
status = flexspi_nor->page_program(MG_FLEXSPI_NOR_INSTANCE, &config,
(uint32_t) dst_ofs, tmp, false);
src = (uint32_t *) ((char *) src + s_mg_flash_frdm.align); src = (uint32_t *) ((char *) src + s_mg_flash_frdm.align);
dst = (uint32_t *) ((char *) dst + s_mg_flash_frdm.align); dst = (uint32_t *) ((char *) dst + s_mg_flash_frdm.align);
if (status != 0) { if (status != 0) {
-5
View File
@@ -772,13 +772,8 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
for (c = mgr->conns; c != NULL; c = tmp) { for (c = mgr->conns; c != NULL; c = tmp) {
long flush = 0; long flush = 0;
bool is_resp = c->is_resp;
tmp = c->next; tmp = c->next;
mg_call(c, MG_EV_POLL, &now); mg_call(c, MG_EV_POLL, &now);
if (is_resp && !c->is_resp) {
long n = 0;
mg_call(c, MG_EV_READ, &n);
}
MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id, MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id,
c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-', c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-',
c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c', c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c',
+98 -42
View File
@@ -107,7 +107,8 @@ struct tls_data {
uint8_t random[32]; // client random from ClientHello uint8_t random[32]; // client random from ClientHello
uint8_t session_id[32]; // client session ID between the handshake states uint8_t session_id[32]; // client session ID between the handshake states
uint8_t x25519_cli[32]; // client X25519 key between the handshake states uint8_t x25519_cli[32]; // client X25519 key between the handshake states
uint8_t x25519_sec[32]; // x25519 secret between the handshake states uint8_t p256_cli[32]; // client P-256 key between the handshake states
uint8_t x25519_sec[32]; // ECDHE secret (X25519 or P-256) between the states
bool skip_verification; // do not perform checks on server certificate bool skip_verification; // do not perform checks on server certificate
bool cert_requested; // client received a CertificateRequest bool cert_requested; // client received a CertificateRequest
@@ -130,6 +131,7 @@ struct tls_data {
// verify cert // verify cert
size_t pubkeysz; // size of the server public key size_t pubkeysz; // size of the server public key
uint8_t sighash[32]; // calculated signature verification hash uint8_t sighash[32]; // calculated signature verification hash
uint8_t sighash384[48]; // same, SHA-384, for ecdsa_secp384r1_sha384
struct tls_enc enc; // actual keys in use at this time struct tls_enc enc; // actual keys in use at this time
struct tls_enc app_keys; // storage during two-way auth handshake struct tls_enc app_keys; // storage during two-way auth handshake
@@ -344,6 +346,10 @@ static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
mg_hmac_sha256(tls->enc.handshake_secret, pre_extract_secret, mg_hmac_sha256(tls->enc.handshake_secret, pre_extract_secret,
sizeof(pre_extract_secret), tls->x25519_sec, sizeof(pre_extract_secret), tls->x25519_sec,
sizeof(tls->x25519_sec)); sizeof(tls->x25519_sec));
// ECDHE keys and secret are not needed anymore, wipe for forward secrecy
mg_bzero(tls->x25519_cli, sizeof(tls->x25519_cli));
mg_bzero(tls->p256_cli, sizeof(tls->p256_cli));
mg_bzero(tls->x25519_sec, sizeof(tls->x25519_sec));
mg_tls_hexdump("hs secret", tls->enc.handshake_secret, 32); mg_tls_hexdump("hs secret", tls->enc.handshake_secret, 32);
// mg_sha256_final is not idempotent, need to copy sha256 context to calculate // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
@@ -626,8 +632,11 @@ static int mg_tls_recv_record(struct mg_connection *c) {
return r; return r;
} }
// Hash the CertificateVerify content: SHA-256 into hash, and if hash384 is not
// NULL, SHA-384 into hash384 for ecdsa_secp384r1_sha384
static void mg_tls_calc_cert_verify_hash(struct mg_connection *c, static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
uint8_t hash[32], bool is_client) { uint8_t hash[32], uint8_t *hash384,
bool is_client) {
struct tls_data *tls = (struct tls_data *) c->tls; struct tls_data *tls = (struct tls_data *) c->tls;
uint8_t sig_content[130]; uint8_t sig_content[130];
mg_sha256_ctx sha256; mg_sha256_ctx sha256;
@@ -647,6 +656,7 @@ static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
mg_sha256_init(&sha256); mg_sha256_init(&sha256);
mg_sha256_update(&sha256, sig_content, sizeof(sig_content)); mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
mg_sha256_final(hash, &sha256); mg_sha256_final(hash, &sha256);
if (hash384 != NULL) mg_sha384(hash384, sig_content, sizeof(sig_content));
} }
// read and parse ClientHello record // read and parse ClientHello record
@@ -788,10 +798,15 @@ static bool mg_tls_server_send_ext(struct mg_connection *c) {
return mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE); return mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
} }
// signature algorithms we actually support: // signature algorithms we actually support: ecdsa_secp256r1_sha256,
// rsa_pkcs1_sha256, rsa_pss_rsae_sha256 and ecdsa_secp256r1_sha256 // ecdsa_secp384r1_sha384 (if enabled), rsa_pss_rsae_sha256, rsa_pkcs1_sha256
static const uint8_t secp256r1_sig_algs[12] = { static const uint8_t secp256r1_sig_algs[] = {
#if MG_UECC_SUPPORTS_secp384r1
0x00, 0x0d, 0x00, 0x0a, 0x00, 0x08, 0x04, 0x03,
0x05, 0x03, 0x08, 0x04, 0x04, 0x01};
#else
0x00, 0x0d, 0x00, 0x08, 0x00, 0x06, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01}; 0x00, 0x0d, 0x00, 0x08, 0x00, 0x06, 0x04, 0x03, 0x08, 0x04, 0x04, 0x01};
#endif
static bool mg_tls_server_send_cert_request(struct mg_connection *c) { static bool mg_tls_server_send_cert_request(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls; struct tls_data *tls = (struct tls_data *) c->tls;
@@ -1071,7 +1086,7 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
struct tls_data *tls = (struct tls_data *) c->tls; struct tls_data *tls = (struct tls_data *) c->tls;
uint8_t hash[32] = {0}; uint8_t hash[32] = {0};
mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash, is_client); mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash, NULL, is_client);
if (tls->rsa.n.len > 0 && tls->rsa.d.len > 0) { if (tls->rsa.n.len > 0 && tls->rsa.d.len > 0) {
// RSA certificate verify packet // RSA certificate verify packet
@@ -1199,6 +1214,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
struct mg_iobuf *wio = &tls->send; struct mg_iobuf *wio = &tls->send;
uint8_t x25519_pub[X25519_BYTES]; uint8_t x25519_pub[X25519_BYTES];
uint8_t p256_pub[64]; // X || Y, sent as an uncompressed point 0x04 || X || Y
// - "signature algorithms we actually support", see above // - "signature algorithms we actually support", see above
// uint8_t secp256r1_sig_algs[] // uint8_t secp256r1_sig_algs[]
@@ -1211,7 +1227,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
0xfe, 0x00, 0x00, 0xfe}; 0xfe, 0x00, 0x00, 0xfe};
// clang-format off // clang-format off
uint8_t msg_client_hello[145] = { uint8_t msg_client_hello[216] = {
// TLS Client Hello header reported as TLS1.2 (5) // TLS Client Hello header reported as TLS1.2 (5)
0x16, 0x03, 0x03, 0x00, 0xfe, 0x16, 0x03, 0x03, 0x00, 0xfe,
// client hello, tls 1.2 (6) // client hello, tls 1.2 (6)
@@ -1232,15 +1248,17 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
0x01, 0x00, 0x01, 0x00,
// extensions + keyshare // extensions + keyshare
0x00, 0xfe, 0x00, 0xfe,
// x25519 keyshare // keyshare: x25519
0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20, 0x00, 0x33, 0x00, 0x6b, 0x00, 0x69, 0x00, 0x1d, 0x00, 0x20,
PLACEHOLDER_32B, PLACEHOLDER_32B,
// supported groups (x25519) // keyshare: secp256r1, uncompressed point
0x00, 0x0a, 0x00, 0x04, 0x00, 0x02, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x41, 0x04, PLACEHOLDER_32B, PLACEHOLDER_32B,
// supported groups (x25519, secp256r1)
0x00, 0x0a, 0x00, 0x06, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x17,
// supported versions (tls1.3 == 0x304) // supported versions (tls1.3 == 0x304)
0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04, 0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04,
// session ticket (none) // session ticket (none)
0x00, 0x23, 0x00, 0x00, // 144 bytes till here 0x00, 0x23, 0x00, 0x00, // 215 bytes till here
}; };
// clang-format on // clang-format on
const char *hostname = tls->hostname; const char *hostname = tls->hostname;
@@ -1253,11 +1271,11 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
// patch ClientHello with correct hostname ext length (if any) // patch ClientHello with correct hostname ext length (if any)
MG_STORE_BE16(msg_client_hello + 3, MG_STORE_BE16(msg_client_hello + 3,
hostname_extsz + 183 - 9 - 34 + sig_alg_sz); hostname_extsz + 254 - 9 - 34 + sig_alg_sz);
MG_STORE_BE16(msg_client_hello + 7, MG_STORE_BE16(msg_client_hello + 7,
hostname_extsz + 179 - 9 - 34 + sig_alg_sz); hostname_extsz + 250 - 9 - 34 + sig_alg_sz);
MG_STORE_BE16(msg_client_hello + 82, MG_STORE_BE16(msg_client_hello + 82,
hostname_extsz + 104 - 9 - 34 + sig_alg_sz); hostname_extsz + 175 - 9 - 34 + sig_alg_sz);
if (hostnamesz > 0) { if (hostnamesz > 0) {
MG_STORE_BE16(server_name_ext + 2, hostnamesz + 5); MG_STORE_BE16(server_name_ext + 2, hostnamesz + 5);
@@ -1265,16 +1283,21 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
MG_STORE_BE16(server_name_ext + 7, hostnamesz); MG_STORE_BE16(server_name_ext + 7, hostnamesz);
} }
// calculate keyshare // calculate keyshares
if (!mg_random(tls->x25519_cli, sizeof(tls->x25519_cli))) mg_error(c, "RNG"); if (!mg_random(tls->x25519_cli, sizeof(tls->x25519_cli))) mg_error(c, "RNG");
mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1); mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
if (!mg_uecc_make_key(p256_pub, tls->p256_cli, mg_uecc_secp256r1())) {
mg_error(c, "P-256 key");
return false; // Do not send uninitialised p256_pub
}
// fill in the gaps: random + session ID + keyshare // fill in the gaps: random + session ID + keyshares
if (!mg_random(tls->session_id, sizeof(tls->session_id))) mg_error(c, "RNG"); if (!mg_random(tls->session_id, sizeof(tls->session_id))) mg_error(c, "RNG");
if (!mg_random(tls->random, sizeof(tls->random))) mg_error(c, "RNG"); if (!mg_random(tls->random, sizeof(tls->random))) mg_error(c, "RNG");
memmove(msg_client_hello + 11, tls->random, sizeof(tls->random)); memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id)); memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub)); memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
memmove(msg_client_hello + 131, p256_pub, sizeof(p256_pub));
// client hello message // client hello message
if (mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello)) == if (mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello)) ==
@@ -1344,17 +1367,29 @@ static int mg_tls_client_recv_hello(struct mg_connection *c) {
} }
if (ext_len2 < (2 + 2 + 32)) goto fail; if (ext_len2 < (2 + 2 + 32)) goto fail;
group = MG_LOAD_BE16(ext + j + 4); group = MG_LOAD_BE16(ext + j + 4);
if (group != 0x001d) { key_exchange_len = MG_LOAD_BE16(ext + j + 6);
key_exchange = ext + j + 8;
if (key_exchange_len > ext_len2 - 4) goto fail;
if (group == 0x001d) { // x25519
if (key_exchange_len != 32 ||
mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1) <
0) {
mg_error(c, "bad key");
return -1;
}
} else if (group == 0x0017) { // secp256r1, uncompressed point 0x04 || X || Y
if (key_exchange_len != 65 || key_exchange[0] != 0x04 ||
!mg_uecc_valid_public_key(key_exchange + 1, mg_uecc_secp256r1()) ||
!mg_uecc_shared_secret(key_exchange + 1, tls->p256_cli,
tls->x25519_sec, mg_uecc_secp256r1())) {
mg_error(c, "bad key");
return -1;
}
} else {
mg_error(c, "bad key exchange group"); mg_error(c, "bad key exchange group");
return -1; return -1;
} }
key_exchange_len = MG_LOAD_BE16(ext + j + 6); // mg_tls_hexdump("c ecdhe sec", tls->x25519_sec, 32);
key_exchange = ext + j + 8;
if (key_exchange_len != 32 || mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1) < 0) {
mg_error(c, "bad key");
return -1;
}
mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
mg_tls_drop_record(c); mg_tls_drop_record(c);
/* generate handshake keys */ /* generate handshake keys */
mg_tls_generate_handshake_keys(c); mg_tls_generate_handshake_keys(c);
@@ -1619,7 +1654,7 @@ static int countdots(struct mg_str s) {
char *p = s.buf; char *p = s.buf;
while (len--) { while (len--) {
if (*(p++) == '.') ++count; if (*(p++) == '.') ++count;
} }
return count; return count;
} }
@@ -1696,10 +1731,12 @@ static int mg_tls_verify_cert_signature(const struct mg_tls_cert *cert,
#if MG_UECC_SUPPORTS_secp384r1 #if MG_UECC_SUPPORTS_secp384r1
if (issuer->pubkey.len == 96) { if (issuer->pubkey.len == 96) {
const uint32_t N = 48; const uint32_t N = 48;
if (a.len > N) a.value += (a.len - N), a.len = N; if (a.len > N) a.value += (a.len - N), a.len = N; // padding
if (b.len > N) b.value += (b.len - N), b.len = N; if (b.len > N) b.value += (b.len - N), b.len = N;
memmove(sig, a.value, N); memset(sig, 0, N - a.len); // short encoding
memmove(sig + N, b.value, N); memmove(sig + (N - a.len), a.value, a.len);
memset(sig + N, 0, N - b.len);
memmove(sig + N + (N - b.len), b.value, b.len);
return mg_uecc_verify((uint8_t *) issuer->pubkey.buf, cert->tbshash, return mg_uecc_verify((uint8_t *) issuer->pubkey.buf, cert->tbshash,
(unsigned) cert->tbshashsz, sig, (unsigned) cert->tbshashsz, sig,
mg_uecc_secp384r1()); mg_uecc_secp384r1());
@@ -1928,7 +1965,7 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
} }
} }
mg_tls_drop_message(c); mg_tls_drop_message(c);
mg_tls_calc_cert_verify_hash(c, tls->sighash, !is_client); mg_tls_calc_cert_verify_hash(c, tls->sighash, tls->sighash384, !is_client);
return 0; return 0;
} }
@@ -1991,11 +2028,20 @@ static int mg_tls_recv_cert_verify(struct mg_connection *c) {
return -1; return -1;
} }
MG_VERBOSE(("certificate verification successful (RSA)")); MG_VERBOSE(("certificate verification successful (RSA)"));
} else if (sigalg == 0x0403) { // ecdsa_secp256r1_sha256 } else if (sigalg == 0x0403 ||
// Extract certificate signature and verify it using pubkey and sighash (sigalg == 0x0503 && MG_UECC_SUPPORTS_secp384r1)) {
uint8_t sig[64]; // ecdsa_secp256r1_sha256 or ecdsa_secp384r1_sha384. Extract certificate
// signature and verify it using pubkey and sighash
bool is384 = sigalg == 0x0503;
uint32_t N = is384 ? 48 : 32; // curve size: r and s are N bytes each
int ok;
uint8_t sig[96];
struct mg_der_tlv seq, r, s; struct mg_der_tlv seq, r, s;
memset(sig, 0, 64); memset(sig, 0, sizeof(sig));
if (tls->pubkeysz != 2 * N) {
mg_error(c, "certverify scheme %04x does not match the key", sigalg);
return -1;
}
if (mg_der_to_tlv(sigbuf, siglen, &seq) < 0) { if (mg_der_to_tlv(sigbuf, siglen, &seq) < 0) {
mg_error(c, "verification message is not an ASN.1 DER sequence"); mg_error(c, "verification message is not an ASN.1 DER sequence");
return -1; return -1;
@@ -2009,15 +2055,24 @@ static int mg_tls_recv_cert_verify(struct mg_connection *c) {
return -1; return -1;
} }
// Integers may be padded with zeroes // Integers may be padded with zeroes
if (r.len > 32) r.value = r.value + (r.len - 32), r.len = 32; if (r.len > N) r.value = r.value + (r.len - N), r.len = N;
if (s.len > 32) s.value = s.value + (s.len - 32), s.len = 32; if (s.len > N) s.value = s.value + (s.len - N), s.len = N;
// r or s may be shorter than 32 bytes, "right-justify" (network order) // r or s may be shorter than N bytes, "right-justify" (network order)
memmove(sig + (32 - r.len), r.value, r.len); memmove(sig + (N - r.len), r.value, r.len);
memmove(sig + 32 + (32 - s.len), s.value, s.len); memmove(sig + N + (N - s.len), s.value, s.len);
if (mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash), sig, #if MG_UECC_SUPPORTS_secp384r1
mg_uecc_secp256r1()) != 1) { if (is384) {
ok = mg_uecc_verify(tls->pubkey, tls->sighash384,
sizeof(tls->sighash384), sig, mg_uecc_secp384r1());
} else
#endif
{
ok = mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash),
sig, mg_uecc_secp256r1());
}
if (ok != 1) {
mg_error(c, "failed to verify EC certificate (certverify)"); mg_error(c, "failed to verify EC certificate (certverify)");
return -1; return -1;
} }
@@ -2758,7 +2813,7 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
MG_INFO(("Parsed PKCS#8 RSA private key: %d bytes", (int) key.len)); MG_INFO(("Parsed PKCS#8 RSA private key: %d bytes", (int) key.len));
} else { } else {
mg_free((void *) key.buf); mg_free((void *) key.buf);
MG_INFO(("Parsed PKCS#8 EC private key")); MG_VERBOSE(("Parsed PKCS#8 EC private key"));
} }
} else { } else {
mg_free((void *) key.buf); mg_free((void *) key.buf);
@@ -2809,6 +2864,7 @@ void mg_tls_free(struct mg_connection *c) {
} }
mg_free((void *) tls->ca_der.buf); mg_free((void *) tls->ca_der.buf);
mg_free((void *) tls->rsa_key_der.buf); mg_free((void *) tls->rsa_key_der.buf);
mg_bzero((unsigned char *) tls, sizeof(*tls)); // Wipe keys and secrets
} }
mg_free(c->tls); mg_free(c->tls);
c->tls = NULL; c->tls = NULL;
+1 -1
View File
@@ -287,7 +287,7 @@ void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
ws_handshake(c, wskey, wsproto, fmt, &ap); ws_handshake(c, wskey, wsproto, fmt, &ap);
va_end(ap); va_end(ap);
c->is_websocket = 1; c->is_websocket = 1;
c->is_resp = 0; c->pfn_data = NULL; // HTTP response done; mg_ws_cb uses it as an offset
mg_call(c, MG_EV_WS_OPEN, hm); mg_call(c, MG_EV_WS_OPEN, hm);
} }
} }
+4 -2
View File
@@ -1,6 +1,6 @@
SRCS = mongoose.c unit_test.c packed_fs.c SRCS = mongoose.c unit_test.c packed_fs.c
HDRS = $(wildcard ../src/*.h) $(wildcard ../src/drivers/*.h) HDRS = $(wildcard ../src/*.h) $(wildcard ../src/drivers/*.h)
DEFS ?= -DMG_MAX_HTTP_HEADERS=7 -DMG_ENABLE_LINES -DMG_ENABLE_SSI=1 -DMG_ENABLE_ASSERT=1 -DMG_ENABLE_IPV6=$(IPV6) DEFS ?= -DMG_MAX_HTTP_HEADERS=7 -DMG_ENABLE_LINES -DMG_ENABLE_SSI=1 -DMG_ENABLE_ASSERT=1 -DMG_ENABLE_IPV6=$(IPV6) -DMG_ENABLE_MDASH=$(MDASH)
WARN ?= -pedantic -W -Wall -Werror -Wshadow -Wdouble-promotion -fno-common -Wconversion -Wundef WARN ?= -pedantic -W -Wall -Werror -Wshadow -Wdouble-promotion -fno-common -Wconversion -Wundef
OPTS ?= -O3 -g3 OPTS ?= -O3 -g3
INCS ?= -Isrc -I. INCS ?= -Isrc -I.
@@ -13,6 +13,7 @@ DOCKER_BIN ?= docker
DOCKER ?= $(DOCKER_BIN) run --platform linux/amd64 --net=host --rm $(ENV) -v $(ROOT_DIR):$(ROOT_DIR) -w $(CWD) DOCKER ?= $(DOCKER_BIN) run --platform linux/amd64 --net=host --rm $(ENV) -v $(ROOT_DIR):$(ROOT_DIR) -w $(CWD)
VCFLAGS ?= /nologo /W3 /O2 /MD /I. VCFLAGS ?= /nologo /W3 /O2 /MD /I.
IPV6 ?= 1 IPV6 ?= 1
MDASH ?= 1
ASAN ?= -fsanitize=address,undefined,alignment -fno-sanitize-recover=all -fno-omit-frame-pointer -fno-common ASAN ?= -fsanitize=address,undefined,alignment -fno-sanitize-recover=all -fno-omit-frame-pointer -fno-common
ASAN_OPTIONS ?= detect_leaks=1 ASAN_OPTIONS ?= detect_leaks=1
# This does not include ESP32, ESP8266, Microchip; all examples that are directly placed under an OS tutorial. Also, it is needed that way... # This does not include ESP32, ESP8266, Microchip; all examples that are directly placed under an OS tutorial. Also, it is needed that way...
@@ -106,7 +107,7 @@ mongoose.c: Makefile $(wildcard ../src/*.c) $(wildcard ../src/drivers/*.c)
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#include "mongoose.h"' ; (for F in src/*.c src/drivers/*.c ; do echo; echo '#ifdef MG_ENABLE_LINES'; echo "#line 1 \"$$F\""; echo '#endif'; cat $$F | sed -e 's,#include ".*,,'; done))> $@ cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#include "mongoose.h"' ; (for F in src/*.c src/drivers/*.c ; do echo; echo '#ifdef MG_ENABLE_LINES'; echo "#line 1 \"$$F\""; echo '#endif'; cat $$F | sed -e 's,#include ".*,,'; done))> $@
mongoose.h: $(HDRS) Makefile mongoose.h: $(HDRS) Makefile
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_x25519.h src/tls_aes128.h src/tls_uecc.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@ cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/lfs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_x25519.h src/tls_aes128.h src/tls_uecc.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@
# Check that all external (exported) symbols have "mg_" prefix # Check that all external (exported) symbols have "mg_" prefix
mg_prefix: mongoose.c mongoose.h mg_prefix: mongoose.c mongoose.h
@@ -269,6 +270,7 @@ clean: clean_tutorials clean_tutorials_embedded
# MIP (net_builtin + L2 + driver) TESTS # MIP (net_builtin + L2 + driver) TESTS
mip_test: MDASH = 0
mip_test: mip_test.c mongoose.c mongoose.h packed_fs.c Makefile mip_test: mip_test.c mongoose.c mongoose.h packed_fs.c Makefile
$(CC) mip_test.c packed_fs.c $(CFLAGS) $(LDFLAGS) -o $@ $(CC) mip_test.c packed_fs.c $(CFLAGS) $(LDFLAGS) -o $@
ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./$@ ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./$@
+193 -72
View File
@@ -826,7 +826,16 @@ static void test_mqtt(void) {
static void eh1(struct mg_connection *c, int ev, void *ev_data) { static void eh1(struct mg_connection *c, int ev, void *ev_data) {
struct mg_tls_opts *topts = (struct mg_tls_opts *) c->fn_data; struct mg_tls_opts *topts = (struct mg_tls_opts *) c->fn_data;
if (ev == MG_EV_ACCEPT && topts != NULL) mg_tls_init(c, topts); if (ev == MG_EV_ACCEPT && topts != NULL) mg_tls_init(c, topts);
if (ev == MG_EV_HTTP_MSG) { if (ev == MG_EV_HTTP_HDRS &&
mg_match(((struct mg_http_message *) ev_data)->uri, mg_str("/big.bin"),
NULL)) {
// mg_http_serve_upload: streams big uploads, called from MG_EV_HTTP_HDRS
struct mg_http_serve_opts sopts;
memset(&sopts, 0, sizeof(sopts));
sopts.root_dir = "./data";
sopts.enable_upload = true;
mg_http_serve_upload(c, (struct mg_http_message *) ev_data, &sopts);
} else if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data; struct mg_http_message *hm = (struct mg_http_message *) ev_data;
MG_INFO(("[%.*s %.*s] message len %d", (int) hm->method.len, hm->method.buf, MG_INFO(("[%.*s %.*s] message len %d", (int) hm->method.len, hm->method.buf,
(int) hm->uri.len, hm->uri.buf, (int) hm->message.len)); (int) hm->uri.len, hm->uri.buf, (int) hm->message.len));
@@ -857,6 +866,7 @@ static void eh1(struct mg_connection *c, int ev, void *ev_data) {
memset(&sopts, 0, sizeof(sopts)); memset(&sopts, 0, sizeof(sopts));
sopts.root_dir = "."; sopts.root_dir = ".";
sopts.extra_headers = "A: B\r\nE: F\r\n"; sopts.extra_headers = "A: B\r\nE: F\r\n";
sopts.enable_dir_listing = true;
mg_http_serve_dir(c, hm, &sopts); mg_http_serve_dir(c, hm, &sopts);
} else if (mg_match(hm->uri, mg_str("/servefile"), NULL)) { } else if (mg_match(hm->uri, mg_str("/servefile"), NULL)) {
struct mg_http_serve_opts sopts; struct mg_http_serve_opts sopts;
@@ -874,6 +884,8 @@ static void eh1(struct mg_connection *c, int ev, void *ev_data) {
sopts.root_dir = "./data"; sopts.root_dir = "./data";
sopts.ssi_pattern = "#.shtml"; sopts.ssi_pattern = "#.shtml";
sopts.extra_headers = "C: D\r\n"; sopts.extra_headers = "C: D\r\n";
sopts.enable_delete = true;
sopts.enable_upload = true;
mg_http_serve_dir(c, hm, &sopts); mg_http_serve_dir(c, hm, &sopts);
} }
} else if (ev == MG_EV_WS_OPEN) { } else if (ev == MG_EV_WS_OPEN) {
@@ -1297,16 +1309,39 @@ ASSERT(system("touch 'dirtest/a<b&c>.txt'") == 0);
#endif #endif
ASSERT(fetch(&mgr, buf, url, "GET /dirtest/ HTTP/1.0\n\n") == 200); ASSERT(fetch(&mgr, buf, url, "GET /dirtest/ HTTP/1.0\n\n") == 200);
MG_DEBUG(("%s", buf)); MG_DEBUG(("%s", buf));
ASSERT(mgstrstr(mg_str(buf), mg_str(">Index of /dirtest/<")) != NULL); ASSERT(mgstrstr(mg_str(buf), mg_str("fuzz.c")) != NULL);
ASSERT(mgstrstr(mg_str(buf), mg_str(">fuzz.c<")) != NULL);
#if MG_ARCH == MG_ARCH_UNIX #if MG_ARCH == MG_ARCH_UNIX
ASSERT(mgstrstr(mg_str(buf), mg_str(">a&lt;b&amp;c&gt;.txt<")) != NULL); ASSERT(mgstrstr(mg_str(buf), mg_str("a<b&c>.txt")) != NULL);
if (system("rm 'dirtest/a<b&c>.txt'") == 0) (void) 0; if (system("rm 'dirtest/a<b&c>.txt'") == 0) (void) 0;
#endif #endif
ASSERT(cmpheader(buf, "A", "B")); ASSERT(cmpheader(buf, "A", "B"));
ASSERT(!cmpheader(buf, "C", "D")); ASSERT(!cmpheader(buf, "C", "D"));
ASSERT(cmpheader(buf, "E", "F")); ASSERT(cmpheader(buf, "E", "F"));
{
// mg_http_serve_dir: allow_upload, small file first (buffered), then a
// big one (mg_http_serve_upload, streamed - see the MG_EV_HTTP_HDRS
// branch in eh1), then allow_delete
struct mg_str big = mg_file_read(&mg_fs_posix, "mongoose.c");
struct mg_str got;
ASSERT(big.len > MG_IO_SIZE);
ASSERT(fetch(&mgr, buf, url,
"POST /del_me.txt HTTP/1.0\r\nContent-Length: 1\r\n\r\nx") ==
200);
ASSERT(fetch(&mgr, buf, url, "GET /del_me.txt HTTP/1.0\n\n") == 200);
ASSERT(fetch(&mgr, buf, url,
"POST /big.bin HTTP/1.0\r\nContent-Length: %d\r\n\r\n%.*s",
(int) big.len, (int) big.len, big.buf) == 200);
got = mg_file_read(&mg_fs_posix, "data/big.bin");
ASSERT(got.len == big.len && memcmp(got.buf, big.buf, big.len) == 0);
mg_free((void *) got.buf);
mg_free((void *) big.buf);
remove("data/big.bin");
ASSERT(fetch(&mgr, buf, url, "DELETE /del_me.txt HTTP/1.0\n\n") == 200);
ASSERT(fetch(&mgr, buf, url, "GET /del_me.txt HTTP/1.0\n\n") == 404);
ASSERT(fetch(&mgr, buf, url, "DELETE /del_me.txt HTTP/1.0\n\n") == 404);
}
{ {
// Credentials // Credentials
struct mg_http_message hm; struct mg_http_message hm;
@@ -3104,26 +3139,83 @@ static void uc(struct mg_connection *c, int ev, void *ev_data) {
} }
} }
static int s_su_done; static int s_su_done; // 1: upload ended, -1: upload rejected
static int s_su_end; // Number of end calls
static void su_cb(struct mg_connection *c, const char *errmsg) { // mg_http_stream_body() callback, saves the body to a file named as the URI
s_su_done = errmsg ? -1 : 1; static bool su_cb(struct mg_http_message *hm, struct mg_str *data, void **p) {
mg_http_reply(c, errmsg ? 400 : 200, "", errmsg ? errmsg : "ok\n"); if (hm != NULL) { // Start
c->is_draining = 1; char path[100];
struct mg_str name = mg_str_n(hm->uri.buf + 1, hm->uri.len - 1);
*p = NULL;
if (!mg_path_is_sane(name)) {
s_su_done = -1;
return false;
}
mg_snprintf(path, sizeof(path), "./%.*s", (int) name.len, name.buf);
*p = mg_fs_open(&mg_fs_posix, path, MG_FS_WRITE);
return *p != NULL;
} else if (data != NULL) { // Next chunk
struct mg_fd *fd = (struct mg_fd *) *p;
return fd != NULL && fd->fs->wr(fd->fd, data->buf, data->len) == data->len;
}
s_su_end++; // End, also called when the connection drops
if (*p != NULL) mg_fs_close((struct mg_fd *) *p);
*p = NULL;
if (s_su_done == 0) s_su_done = 1;
return true;
} }
static void su(struct mg_connection *c, int ev, void *ev_data) { static void su(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_HDRS) { if (ev == MG_EV_HTTP_HDRS) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data; mg_http_stream_body(c, (struct mg_http_message *) ev_data, su_cb, NULL);
struct mg_str name = mg_str_n(hm->uri.buf + 1, hm->uri.len - 1); } else if (ev == MG_EV_HTTP_MSG) { // Only for requests that were not streamed
mg_http_start_upload(c, hm, name, mg_str("."), &mg_fs_posix, su_cb); mg_http_reply(c, 400, "", "not streamed\n");
} }
} }
static void cu(struct mg_connection *c, int ev, void *ev_data) { // Client that announces a large body, sends a few bytes and stays silent
if (ev == MG_EV_CONNECT) static void cd(struct mg_connection *c, int ev, void *ev_data) {
mg_printf(c, "POST %s HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n", if (ev == MG_EV_CONNECT) {
(char *) c->fn_data); mg_printf(c, "POST /su_drop.txt HTTP/1.0\r\nContent-Length: 100000\r\n\r\nfoo\n");
}
(void) ev_data;
}
static char s_cr_buf[4096]; // Response body streamed by the client
static size_t s_cr_len;
static int s_cr_end;
static bool cr_cb(struct mg_http_message *hm, struct mg_str *data, void **p) {
(void) p;
if (hm != NULL) {
s_cr_len = 0;
} else if (data != NULL) {
ASSERT(s_cr_len + data->len <= sizeof(s_cr_buf));
memcpy(s_cr_buf + s_cr_len, data->buf, data->len);
s_cr_len += data->len;
} else {
s_cr_end++;
}
return true;
}
// Client that streams the response body with mg_http_stream_body()
static void cr(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_CONNECT) {
mg_printf(c, "GET / HTTP/1.0\r\n\r\n");
} else if (ev == MG_EV_HTTP_HDRS) {
ASSERT(mg_http_stream_body(c, (struct mg_http_message *) ev_data, cr_cb,
NULL));
}
}
static void cs(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
char body[3000];
memset(body, 'x', sizeof(body));
mg_http_reply(c, 200, "", "%.*s", (int) sizeof(body), body);
}
(void) ev_data; (void) ev_data;
} }
@@ -3141,16 +3233,18 @@ static void test_http_upload(void) {
mg_mgr_free(&mgr); mg_mgr_free(&mgr);
ASSERT(mgr.conns == NULL); ASSERT(mgr.conns == NULL);
// mg_http_start_upload: successful upload, file content verified // mg_http_stream_body: successful upload, file content verified
{ {
char buf[FETCH_BUF_SIZE]; char buf[FETCH_BUF_SIZE];
struct mg_str fc; struct mg_str fc;
remove("su_ok.txt"); remove("su_ok.txt");
s_su_done = s_su_end = 0;
mg_mgr_init(&mgr); mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://127.0.0.1:12355", su, NULL); mg_http_listen(&mgr, "http://127.0.0.1:12355", su, NULL);
ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12355", ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12355",
"POST /su_ok.txt HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n") == "POST /su_ok.txt HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n") ==
200); 200);
ASSERT(s_su_done == 1 && s_su_end == 1);
fc = mg_file_read(&mg_fs_posix, "su_ok.txt"); fc = mg_file_read(&mg_fs_posix, "su_ok.txt");
ASSERT(mg_strcmp(fc, mg_str("foo\nbar\n")) == 0); ASSERT(mg_strcmp(fc, mg_str("foo\nbar\n")) == 0);
mg_free((void *) fc.buf); mg_free((void *) fc.buf);
@@ -3159,14 +3253,68 @@ static void test_http_upload(void) {
ASSERT(mgr.conns == NULL); ASSERT(mgr.conns == NULL);
} }
// mg_http_start_upload: path traversal rejected, callback gets error // mg_http_stream_body: path traversal rejected by the callback, "500" sent
{ {
s_su_done = 0; char buf[FETCH_BUF_SIZE];
s_su_done = s_su_end = 0;
mg_mgr_init(&mgr); mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://127.0.0.1:12356", su, NULL); mg_http_listen(&mgr, "http://127.0.0.1:12356", su, NULL);
mg_http_connect(&mgr, "http://127.0.0.1:12356", cu, (void *) "/../evil.txt"); ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12356",
for (i = 0; i < 50 && !s_su_done; i++) mg_mgr_poll(&mgr, 5); "POST /../evil.txt HTTP/1.0\r\nContent-Length: 8\r\n\r\nfoo\nbar\n") ==
ASSERT(s_su_done == -1); 500);
ASSERT(s_su_done == -1 && s_su_end == 1);
ASSERT(fopen("../evil.txt", "r") == NULL);
mg_mgr_free(&mgr);
ASSERT(mgr.conns == NULL);
}
// mg_http_stream_body: chunked request is not streamed, caller replies "400"
{
char buf[FETCH_BUF_SIZE];
s_su_done = s_su_end = 0;
remove("su_chunked.txt");
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://127.0.0.1:12393", su, NULL);
ASSERT(fetch(&mgr, buf, "http://127.0.0.1:12393",
"POST /su_chunked.txt HTTP/1.1\r\n"
"Transfer-Encoding: chunked\r\n\r\n"
"3\r\nfoo\r\n0\r\n\r\n") == 400);
ASSERT(s_su_done == 0 && s_su_end == 0); // The callback was never called
ASSERT(fopen("su_chunked.txt", "r") == NULL);
mg_mgr_free(&mgr);
ASSERT(mgr.conns == NULL);
}
// mg_http_stream_body: connection drops mid-body, the end call still happens
{
struct mg_connection *cc;
s_su_done = s_su_end = 0;
remove("su_drop.txt");
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://127.0.0.1:12391", su, NULL);
cc = mg_http_connect(&mgr, "http://127.0.0.1:12391", cd, NULL);
ASSERT(cc != NULL);
for (i = 0; i < 20; i++) mg_mgr_poll(&mgr, 5);
ASSERT(s_su_end == 0); // Still waiting for the rest of the body
cc->is_closing = 1;
for (i = 0; i < 20; i++) mg_mgr_poll(&mgr, 5);
ASSERT(s_su_end == 1);
remove("su_drop.txt");
mg_mgr_free(&mgr);
ASSERT(mgr.conns == NULL);
}
// mg_http_stream_body on a client connection: response body is streamed
{
s_cr_end = 0;
s_cr_len = 0;
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://127.0.0.1:12392", cs, NULL);
mg_http_connect(&mgr, "http://127.0.0.1:12392", cr, NULL);
for (i = 0; i < 50 && s_cr_end == 0; i++) mg_mgr_poll(&mgr, 5);
ASSERT(s_cr_end == 1);
ASSERT(s_cr_len == 3000);
ASSERT(s_cr_buf[0] == 'x' && s_cr_buf[2999] == 'x');
mg_mgr_free(&mgr); mg_mgr_free(&mgr);
ASSERT(mgr.conns == NULL); ASSERT(mgr.conns == NULL);
} }
@@ -3203,7 +3351,7 @@ static void eY(struct mg_connection *c, int ev, void *ev_data) {
c->data[0]++; c->data[0]++;
if (c->data[0] == 10) mg_send(c, "a", 1); if (c->data[0] == 10) mg_send(c, "a", 1);
if (c->data[0] == 12) mg_send(c, "bc", 2); if (c->data[0] == 12) mg_send(c, "bc", 2);
if (c->data[0] == 30) mg_send(c, "d", 1), c->is_resp = 0, c->data[0] = 0; if (c->data[0] == 30) mg_send(c, "d", 1), c->pfn_data = NULL, c->data[0] = 0;
} }
(void) ev_data; (void) ev_data;
} }
@@ -3422,6 +3570,7 @@ static void eh7(struct mg_connection *c, int ev, void *ev_data) {
memset(&sopts, 0, sizeof(sopts)); memset(&sopts, 0, sizeof(sopts));
sopts.root_dir = "/"; sopts.root_dir = "/";
sopts.fs = &mg_fs_packed; sopts.fs = &mg_fs_packed;
sopts.enable_dir_listing = true;
mg_mem_files = mg_packed_files; mg_mem_files = mg_packed_files;
mg_http_serve_dir(c, hm, &sopts); mg_http_serve_dir(c, hm, &sopts);
} }
@@ -3591,6 +3740,7 @@ static void h7(struct mg_connection *c, int ev, void *ev_data) {
struct mg_http_serve_opts opts; struct mg_http_serve_opts opts;
memset(&opts, 0, sizeof(opts)); memset(&opts, 0, sizeof(opts));
opts.root_dir = "./data,/foo=./dirtest"; opts.root_dir = "./data,/foo=./dirtest";
opts.enable_dir_listing = true;
mg_http_serve_dir(c, hm, &opts); mg_http_serve_dir(c, hm, &opts);
} }
} }
@@ -4651,23 +4801,7 @@ static struct mg_field test_files_fields[] = {
{NULL, MG_VAL_INT, NULL, 0}, {NULL, MG_VAL_INT, NULL, 0},
}; };
static struct mg_field_set test_files_set = { static struct mg_field_set test_files_set = {
"files", test_files_fields, NULL, &s_test_file_index, test_upload_dir, NULL}; "files", test_files_fields, NULL, &s_test_file_index, NULL};
static struct test_file_entry s_delete_file;
static char s_deleted_file[sizeof(s_delete_file.name)];
static char s_uploaded_file[sizeof(s_delete_file.name)];
static struct mg_field_set *s_delete_file_set;
static bool delete_file_fn(enum mg_dash_op op, struct mg_dash_user *u) {
if (op == MG_DASH_READ) return mg_dash_dir_read(s_delete_file_set, u);
if (op == MG_DASH_WRITE) {
mg_snprintf(s_uploaded_file, sizeof(s_uploaded_file), "%s",
s_delete_file.name);
}
if (op == MG_DASH_DELETE) {
mg_snprintf(s_deleted_file, sizeof(s_deleted_file), "%s",
s_delete_file.name);
}
return true;
}
static bool arr_fn(enum mg_dash_op op, struct mg_dash_user *u) { static bool arr_fn(enum mg_dash_op op, struct mg_dash_user *u) {
(void) u; (void) u;
if (op == MG_DASH_READ) { if (op == MG_DASH_READ) {
@@ -4714,20 +4848,18 @@ static void test_dash(void) {
{"admin", MG_VAL_INT, &admin, sizeof(admin)}, {"admin", MG_VAL_INT, &admin, sizeof(admin)},
{NULL, MG_VAL_INT, NULL, 0}, {NULL, MG_VAL_INT, NULL, 0},
}; };
struct mg_field_set set1 = {"set1", fields1, set1_fn, NULL, NULL, NULL}; struct mg_field_set set1 = {"set1", fields1, set1_fn, NULL, NULL};
struct mg_field_set set2 = {"set2", fields2, set2_fn, NULL, NULL, NULL}; struct mg_field_set set2 = {"set2", fields2, set2_fn, NULL, NULL};
struct mg_field_set set3 = {"set3", fields3, set3_fn, NULL, NULL, NULL}; struct mg_field_set set3 = {"set3", fields3, set3_fn, NULL, NULL};
struct mg_field arr_fields[] = { struct mg_field arr_fields[] = {
{"val", MG_VAL_INT, &s_arr_val, sizeof(s_arr_val)}, {"val", MG_VAL_INT, &s_arr_val, sizeof(s_arr_val)},
{NULL, MG_VAL_INT, NULL, 0}, {NULL, MG_VAL_INT, NULL, 0},
}; };
struct mg_field_set arr_set = {"arr", arr_fields, arr_fn, &s_arr_index, NULL, struct mg_field_set arr_set = {"arr", arr_fields, arr_fn, &s_arr_index, NULL};
NULL};
const char *get_all_expected = const char *get_all_expected =
"{\"arr\":17,\"set3\":{\"admin\":7}," "{\"arr\":17,\"set3\":{\"admin\":7},"
"\"set2\":{\"two\":false}," "\"set2\":{\"two\":false},"
"\"set1\":{\"one\":1,\"three\":\"t: 1\"}," "\"set1\":{\"one\":1,\"three\":\"t: 1\"}}\n";
"\"files\":0}\n";
const char *set1_req = "POST /api/set HTTP/1.0\nContent-Length: 18\n\n" const char *set1_req = "POST /api/set HTTP/1.0\nContent-Length: 18\n\n"
"{\"set1\":{\"one\":2}}"; "{\"set1\":{\"one\":2}}";
const char *set1_set3_req = "POST /api/set HTTP/1.0\n" const char *set1_set3_req = "POST /api/set HTTP/1.0\n"
@@ -5080,51 +5212,40 @@ static void test_dash(void) {
ASSERT(mg_http_listen(&mgr2, url2, mg_dash_ev_handler, &dash2) != NULL); ASSERT(mg_http_listen(&mgr2, url2, mg_dash_ev_handler, &dash2) != NULL);
ASSERT(fetch(&mgr2, buf, url2, "GET /api/get HTTP/1.0\n\n") == 200); ASSERT(fetch(&mgr2, buf, url2, "GET /api/get HTTP/1.0\n\n") == 200);
ASSERT(strstr(buf, files_probe) == NULL); // no files fieldset ASSERT(strstr(buf, files_probe) == NULL); // no files fieldset
ASSERT(fetch(&mgr2, buf, url2, "GET /fs/files/test.txt HTTP/1.0\n\n") == 404); ASSERT(fetch(&mgr2, buf, url2, "GET /fs/test.txt HTTP/1.0\n\n") == 404);
ASSERT(fetch(&mgr2, buf, url2, ASSERT(fetch(&mgr2, buf, url2,
"POST /fs/files/test.txt HTTP/1.0\nContent-Length: 5\n\nhello") == "POST /fs/test.txt HTTP/1.0\nContent-Length: 5\n\nhello") ==
404); 404);
mg_mgr_free(&mgr2); mg_mgr_free(&mgr2);
} }
// Test files fieldset with get_dir: /fs/ endpoints active // Test the built-in file manager (struct mg_dash::files_dir): /fs/ active
{ {
const char *url3 = "http://localhost:26354"; const char *url3 = "http://localhost:26354";
struct mg_mgr mgr3; struct mg_mgr mgr3;
struct mg_dash dash3; struct mg_dash dash3;
static int idx3; struct mg_str uploaded;
static struct mg_field ff3[] = {
{"name", MG_VAL_STR, s_delete_file.name, sizeof(s_delete_file.name)},
{"size", MG_VAL_UINT64, &s_delete_file.size, 0},
{NULL, MG_VAL_INT, NULL, 0},
};
static struct mg_field_set fset3 = {"files", ff3, delete_file_fn, &idx3,
test_upload_dir, NULL};
memset(&dash3, 0, sizeof(dash3)); memset(&dash3, 0, sizeof(dash3));
s_deleted_file[0] = '\0'; dash3.files_dir = test_upload_dir;
s_uploaded_file[0] = '\0';
s_delete_file_set = &fset3;
MG_DASH_ADD_FIELD_SET(&dash3, &fset3);
mg_mgr_init(&mgr3); mg_mgr_init(&mgr3);
mg_mem_files = mg_packed_files; mg_mem_files = mg_packed_files;
ASSERT(mg_http_listen(&mgr3, url3, mg_dash_ev_handler, &dash3) != NULL); ASSERT(mg_http_listen(&mgr3, url3, mg_dash_ev_handler, &dash3) != NULL);
ASSERT(fetch(&mgr3, buf, url3, "GET /api/get HTTP/1.0\n\n") == 200); ASSERT(fetch(&mgr3, buf, url3, "GET /api/get HTTP/1.0\n\n") == 200);
ASSERT(strstr(buf, files_probe) != NULL); // files fieldset present ASSERT(strstr(buf, files_probe) == NULL); // files manager is not a fieldset
ASSERT(fetch(&mgr3, buf, url3, ASSERT(fetch(&mgr3, buf, url3,
"DELETE /fs/files/nofile.txt HTTP/1.0\n\n") == 200); "DELETE /fs/nofile.txt HTTP/1.0\n\n") == 404);
ASSERT(strcmp(s_deleted_file, "nofile.txt") == 0);
ASSERT(fetch(&mgr3, buf, url3, ASSERT(fetch(&mgr3, buf, url3,
"DELETE /fs/files/..%2Fevil.txt HTTP/1.0\n\n") == 400); "DELETE /fs/..%2Fevil.txt HTTP/1.0\n\n") == 400);
ASSERT(strcmp(s_deleted_file, "nofile.txt") == 0);
ASSERT(fetch(&mgr3, buf, url3, ASSERT(fetch(&mgr3, buf, url3,
"PUT /fs/files/test.bin HTTP/1.0\nContent-Length: 4\n\ndata") == "PUT /fs/test.bin HTTP/1.0\nContent-Length: 4\n\ndata") ==
200); 200);
ASSERT(strcmp(s_uploaded_file, "test.bin") == 0); uploaded = mg_file_read(&mg_fs_posix, "mongoose_dash_test/test.bin");
ASSERT(mg_strcmp(uploaded, mg_str("data")) == 0);
mg_free((void *) uploaded.buf);
ASSERT(fetch(&mgr3, buf, url3, ASSERT(fetch(&mgr3, buf, url3,
"PUT /fs/files/..%2Fevil.bin HTTP/1.0\nContent-Length: " "PUT /fs/..%2Fevil.bin HTTP/1.0\nContent-Length: "
"4\n\ndata") == 400); "4\n\ndata") == 400);
ASSERT(strcmp(s_uploaded_file, "test.bin") == 0); ASSERT(fetch(&mgr3, buf, url3, "GET /fs/ HTTP/1.0\n\n") == 200);
ASSERT(fetch(&mgr3, buf, url3, "GET /api/get/files/0 HTTP/1.0\n\n") == 200);
ASSERT(strstr(buf, test_bin_probe) != NULL); ASSERT(strstr(buf, test_bin_probe) != NULL);
mg_mgr_free(&mgr3); mg_mgr_free(&mgr3);
} }
+1 -1
View File
@@ -75,7 +75,7 @@ static bool arr_fn(enum mg_dash_op op, struct mg_dash_user *u) {
} }
static struct mg_field_set field_set_arr = { static struct mg_field_set field_set_arr = {
"event", fields_arr, arr_fn, &s_index, NULL, NULL, "event", fields_arr, arr_fn, &s_index, NULL,
}; };
void mg_dash_init(struct mg_mgr *mgr) { void mg_dash_init(struct mg_mgr *mgr) {
+10 -37
View File
@@ -27,7 +27,7 @@ static struct mg_field fields_actions[] = {
{NULL, MG_VAL_INT, NULL, 0}, {NULL, MG_VAL_INT, NULL, 0},
}; };
static struct mg_field_set set_actions = {"actions", fields_actions, actions_fn, static struct mg_field_set set_actions = {"actions", fields_actions, actions_fn,
NULL, NULL, NULL}; NULL, NULL};
// Control panel // Control panel
// s_led1, s_led2, s_led3 are used to communicate LED status // s_led1, s_led2, s_led3 are used to communicate LED status
@@ -43,7 +43,7 @@ static struct mg_field fields_leds[] = {
{NULL, MG_VAL_INT, NULL, 0}, {NULL, MG_VAL_INT, NULL, 0},
}; };
static struct mg_field_set set_leds = {"leds", fields_leds, leds_fn, static struct mg_field_set set_leds = {"leds", fields_leds, leds_fn,
NULL, NULL, NULL}; NULL, NULL};
// Read-only device Metrics // Read-only device Metrics
static int s_ram = 32, s_cpu = 7; static int s_ram = 32, s_cpu = 7;
@@ -66,7 +66,7 @@ static struct mg_field fields_metrics[] = {
}; };
static struct mg_field_set set_metrics = {"metrics", fields_metrics, metrics_fn, static struct mg_field_set set_metrics = {"metrics", fields_metrics, metrics_fn,
NULL, NULL, NULL}; NULL, NULL};
// Read-write device settings // Read-write device settings
static bool s_enable_login = false; static bool s_enable_login = false;
@@ -105,7 +105,7 @@ static struct mg_field fields_settings[] = {
}; };
static struct mg_field_set set_settings = { static struct mg_field_set set_settings = {
"settings", fields_settings, settings_fn, NULL, NULL, NULL}; "settings", fields_settings, settings_fn, NULL, NULL};
#define NUM_POINTS_GRAPH1 7 // How many graph1 data points to send #define NUM_POINTS_GRAPH1 7 // How many graph1 data points to send
@@ -150,7 +150,7 @@ static bool graph1_fn(enum mg_dash_op op, struct mg_dash_user *u) {
return true; return true;
} }
static struct mg_field_set set_graph1 = {"graph1", fields_graph1, graph1_fn, static struct mg_field_set set_graph1 = {"graph1", fields_graph1, graph1_fn,
NULL, NULL, NULL}; NULL, NULL};
#define NUM_POINTS_GRAPH2 100 // How many graph2 data points to send #define NUM_POINTS_GRAPH2 100 // How many graph2 data points to send
static char s_graph2_data[NUM_POINTS_GRAPH2 * 4 + 2 + 1]; static char s_graph2_data[NUM_POINTS_GRAPH2 * 4 + 2 + 1];
@@ -187,7 +187,7 @@ static bool graph2_fn(enum mg_dash_op op, struct mg_dash_user *u) {
return op == MG_DASH_READ || op == MG_DASH_WRITE; return op == MG_DASH_READ || op == MG_DASH_WRITE;
} }
static struct mg_field_set set_graph2 = {"graph2", fields_graph2, graph2_fn, static struct mg_field_set set_graph2 = {"graph2", fields_graph2, graph2_fn,
NULL, NULL, NULL}; NULL, NULL};
static int authenticate(char *user, size_t userlen, const char *pass) { static int authenticate(char *user, size_t userlen, const char *pass) {
int level = 0; // Authentication failure int level = 0; // Authentication failure
@@ -201,42 +201,14 @@ static int authenticate(char *user, size_t userlen, const char *pass) {
return level; return level;
} }
static struct file { static bool files_dir(const struct mg_dash_user *u, char *buf, size_t len) {
int index; (void) u; // Same dir for every user. Key off u->name for per-user dirs
char name[64];
size_t size;
uint64_t checksum;
} s_file;
static struct mg_field_set set_files;
static bool get_dir(const struct mg_dash_user *u, char *buf, size_t len) {
(void) u;
mg_snprintf(buf, len, "%s", "/tmp/dashboard"); mg_snprintf(buf, len, "%s", "/tmp/dashboard");
return true; return true;
} }
static struct mg_field fields_files[] = {
{"name", MG_VAL_STR, s_file.name, sizeof(s_file.name)},
{"size", MG_VAL_UINT64, &s_file.size, 0},
{"checksum", MG_VAL_UINT64, &s_file.checksum, sizeof(s_file.checksum)},
{NULL, MG_VAL_INT, NULL, 0},
};
// Custom reader: let the framework fill "name" and "size", then add our
// own field. A real implementation would hash the file instead of
// hardcoding zero
static bool files_fn(enum mg_dash_op op, struct mg_dash_user *u) {
if (op != MG_DASH_READ) return false;
if (!mg_dash_dir_read(&set_files, u)) return false;
s_file.checksum = 0;
return true;
}
static struct mg_field_set set_files = {"files", fields_files, files_fn,
&s_file.index, get_dir, NULL};
void mg_dash_init(struct mg_mgr *mgr) { void mg_dash_init(struct mg_mgr *mgr) {
MG_DASH_ADD_FIELD_SET(&s_dash, &set_files); s_dash.files_dir = files_dir; // Built-in file manager, see mg_dash.h
MG_DASH_ADD_FIELD_SET(&s_dash, &set_leds); MG_DASH_ADD_FIELD_SET(&s_dash, &set_leds);
MG_DASH_ADD_FIELD_SET(&s_dash, &set_metrics); MG_DASH_ADD_FIELD_SET(&s_dash, &set_metrics);
MG_DASH_ADD_FIELD_SET(&s_dash, &set_settings); MG_DASH_ADD_FIELD_SET(&s_dash, &set_settings);
@@ -246,6 +218,7 @@ void mg_dash_init(struct mg_mgr *mgr) {
#if MG_ARCH == MG_ARCH_UNIX #if MG_ARCH == MG_ARCH_UNIX
// Create demo files in the upload directory // Create demo files in the upload directory
mkdir("/tmp", 0755);
mkdir("/tmp/dashboard", 0755); mkdir("/tmp/dashboard", 0755);
mg_file_printf(&mg_fs_posix, "/tmp/dashboard/device-config.json", mg_file_printf(&mg_fs_posix, "/tmp/dashboard/device-config.json",
"{\"model\":\"example\",\"fw\":\"1.0\"}"); "{\"model\":\"example\",\"fw\":\"1.0\"}");
+90 -47
View File
@@ -16,7 +16,6 @@
leds: { led1: true, led2: false, led3: false }, leds: { led1: true, led2: false, led3: false },
settings: { volume: 12, log_level: 3, name: 'Galway', enable_login: true, ota_version: '1.2.3', ota_status: 'No checks yet', ota_url: 'http://my-product.com/ota.json', ota_interval: 30 }, settings: { volume: 12, log_level: 3, name: 'Galway', enable_login: true, ota_version: '1.2.3', ota_status: 'No checks yet', ota_url: 'http://my-product.com/ota.json', ota_interval: 30 },
metrics: { temperature: 1.2, cpu: 4, ram: 5, version: '1.2.3' }, metrics: { temperature: 1.2, cpu: 4, ram: 5, version: '1.2.3' },
files: {start: 0, end: 100, data: [{name: 'device-log-2026-04-25.txt', size: 8625563}]},
}, },
}); });
</script> </script>
@@ -110,6 +109,7 @@
Dashboard.on('ready', function() { Dashboard.on('ready', function() {
setupAutoLogout(); setupAutoLogout();
document.body.style.visibility = 'visible'; document.body.style.visibility = 'visible';
refreshFiles();
}); });
Dashboard.login().catch(err => showLogin(true)); Dashboard.login().catch(err => showLogin(true));
@@ -170,13 +170,80 @@
]); ]);
}; };
// Intercept change notifications: re-plot graphs, reload the file // Intercept change notifications: re-plot graphs
// list whenever its size changes (file uploaded or deleted)
Dashboard.on('change', args => { Dashboard.on('change', args => {
args?.graph1?.data && updateGraph1(args?.graph1?.data); args?.graph1?.data && updateGraph1(args?.graph1?.data);
args?.graph2?.data && updateGraph2(args?.graph2?.data); args?.graph2?.data && updateGraph2(args?.graph2?.data);
typeof args?.files === 'number' && Dashboard.call('get', { name: 'files', start: 0, end: 100 });
}); });
// File manager: served directly by the built-in mg_dash file manager
// (see struct mg_dash::files_dir), not by the generic data-repeat
// binding, since the listing endpoint returns a plain JSON array
const filesListEl = document.getElementById('files-list');
const filesCountEl = document.getElementById('files-count');
const filesUploadEl = document.getElementById('files-upload-input');
function renderFiles(list) {
filesCountEl.textContent = list.length + ' Files';
filesListEl.innerHTML = list.map(f => `
<div class="file-row">
<div class="file-info">
<span class="file-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z" />
<path d="M14 2v5h5" />
</svg>
</span>
<div class="file-name">${f.name}</div>
</div>
<div class="file-size">${f.size}</div>
<div class="file-actions">
<a href="fs/${encodeURIComponent(f.name)}" target="_blank" class="btn btn-secondary">
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 3v12" />
<path d="m7 10 5 5 5-5" />
<path d="M5 21h14" />
</svg>
</a>
<button data-del="${encodeURIComponent(f.name)}" class="btn btn-secondary">
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 6h18" />
<path d="M8 6V4h8v2" />
<path d="M19 6l-1 14H6L5 6" />
<path d="M10 11v5" />
<path d="M14 11v5" />
</svg>
</button>
</div>
</div>`).join('');
filesListEl.querySelectorAll('[data-del]').forEach(btn => {
btn.addEventListener('click', ev => {
ev.preventDefault();
fetch('fs/' + btn.dataset.del, { method: 'DELETE' }).then(refreshFiles);
});
});
}
function refreshFiles() {
fetch('fs/')
.then(r => r.ok ? r.json() : Promise.reject(r.statusText))
.then(list => renderFiles(list.filter(f => !f.dir)))
.catch(err => console.log('Files list failed', err));
}
filesUploadEl.addEventListener('change', ev => {
const f = ev.target.files[0];
ev.target.value = '';
if (!f) return;
const reader = new FileReader();
reader.readAsArrayBuffer(f);
reader.onload = () => {
fetch('fs/' + encodeURIComponent(f.name), { method: 'POST', body: reader.result })
.then(refreshFiles)
.catch(err => console.log('Upload failed', err));
};
});
}); });
</script> </script>
<style> <style>
@@ -691,7 +758,7 @@ a, a:visited, a:link { text-decoration: none; }
<div class="panel-title"> <div class="panel-title">
<span> <span>
<span>File Manager</span> <span>File Manager</span>
<span class="metric-status">${files.size ?? files.data.length} Files</span> <span class="metric-status" id="files-count">0 Files</span>
</span> </span>
<div class="header-actions"> <div class="header-actions">
<label class="btn btn-primary"> <label class="btn btn-primary">
@@ -701,56 +768,32 @@ a, a:visited, a:link { text-decoration: none; }
<path d="M5 21h14" /> <path d="M5 21h14" />
</svg> </svg>
Upload Upload
<input type="file" hidden data-upload="files" /> <input type="file" hidden id="files-upload-input" />
</label> </label>
</div> </div>
</div> </div>
<div class="panel-body"> <div class="panel-body">
<div class="file-list" data-repeat="files.data" data-iterator="f"> <div class="file-list" id="files-list"></div>
<div class="file-row">
<div class="file-info">
<span class="file-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z" />
<path d="M14 2v5h5" />
</svg>
</span>
<div class="file-name">${f.name}</div>
</div>
<div class="file-size">${f.size}</div>
<div class="file-actions">
<a href="fs/files/${encodeURIComponent(f.name)}" target="_blank" class="btn btn-secondary">
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 3v12" />
<path d="m7 10 5 5 5-5" />
<path d="M5 21h14" />
</svg>
</a>
<button onclick="fetch('fs/files/${encodeURIComponent(f.name)}', {method: 'DELETE'}); return false;" class="btn btn-secondary">
<svg viewBox="0 0 24 24" class="nav-icon" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 6h18" />
<path d="M8 6V4h8v2" />
<path d="M19 6l-1 14H6L5 6" />
<path d="M10 11v5" />
<path d="M14 11v5" />
</svg>
</button>
</div>
</div>
</div>
</div> </div>
</div> </div>
<div class="note"> <div class="note">
<p>The two default files are fake - you can delete them</p> <p>This file manager uses /tmp/dashboard/ directory.
<p>However the manager works - you can upload new files. They It works on any platform that supports
are uploaded to /tmp/ directory on the device. standard file IO: fopen, fread, fwrite, fclose.
This requires stdio (fopen/fread/...) implemeneted.</p> This includes Linux/Mac/Windows.</p>
<p>The easiest way to implement it is to use a filesystem like <p>
LittleFS on your internal or external flash Mongoose provides a built-in LittleFS integration that
and retarget the standard library to use it.</p> makes stadard file IO work on embedded systems like STM32.
<p>See <a href="https://github.com/cpq/bare-metal-programming-guide/tree/main/templates/lfs/nucleo-h563zi">this example</a> on how LittleFS can be implemented on For that, add "#define MG_ENABLE_LFS 1" to your
Nucleo-H563ZI internal flash partition.</p> mongoose_config.h
</p>
<p>See
<a href="https://github.com/cesanta/embedded-web-file-manager">this ready-to-build example</a>
which implements LittleFS on Nucleo-H563ZI internal flash. You
can upload, delete and serve files on STM32 - which is
a perfect use case for confuration files, keeping and viewing logs, etc.
</p>
</div> </div>
</div> </div>
@@ -34,7 +34,7 @@ static struct mg_field fields_status[] = {
}; };
static struct mg_field_set field_set_status = { static struct mg_field_set field_set_status = {
"status", fields_status, status_fn, NULL, NULL, NULL, "status", fields_status, status_fn, NULL, NULL,
}; };
void mg_dash_init(struct mg_mgr *mgr) { void mg_dash_init(struct mg_mgr *mgr) {
@@ -29,7 +29,7 @@ static const char *s_tls_key =
"4hf5Gx17YJkq5/z3k6ogPDPpoAYWIw1/sw==\n" "4hf5Gx17YJkq5/z3k6ogPDPpoAYWIw1/sw==\n"
"-----END EC PRIVATE KEY-----\n"; "-----END EC PRIVATE KEY-----\n";
static void upload(struct mg_http_message *hm, struct mg_str *data, void **p) { static bool upload(struct mg_http_message *hm, struct mg_str *data, void **p) {
struct mg_fs *fs = &mg_fs_posix; struct mg_fs *fs = &mg_fs_posix;
if (hm != NULL) { if (hm != NULL) {
char path[MG_PATH_MAX]; char path[MG_PATH_MAX];
@@ -48,6 +48,7 @@ static void upload(struct mg_http_message *hm, struct mg_str *data, void **p) {
MG_INFO(("UPLOAD END %p", p)); MG_INFO(("UPLOAD END %p", p));
if (*p) fs->cl(*p), *p = NULL; if (*p) fs->cl(*p), *p = NULL;
} }
return true; // signal success
} }
static void fn(struct mg_connection *c, int ev, void *ev_data) { static void fn(struct mg_connection *c, int ev, void *ev_data) {
@@ -55,13 +56,16 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
struct mg_tls_opts opts = {.cert = mg_str(s_tls_cert), struct mg_tls_opts opts = {.cert = mg_str(s_tls_cert),
.key = mg_str(s_tls_key)}; .key = mg_str(s_tls_key)};
mg_tls_init(c, &opts); mg_tls_init(c, &opts);
} else if (ev == MG_EV_HTTP_HDRS) {
// Handle upload requests to /fs/*
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/fs/*"), NULL)) {
mg_http_stream_body(c, hm, upload, NULL);
}
} else if (ev == MG_EV_HTTP_MSG && c->pfn != NULL) { } else if (ev == MG_EV_HTTP_MSG && c->pfn != NULL) {
struct mg_http_serve_opts opts = {.root_dir = "web_root"}; struct mg_http_serve_opts opts = {.root_dir = "web_root"};
mg_http_serve_dir(c, ev_data, &opts); mg_http_serve_dir(c, ev_data, &opts);
} }
// Handle upload requests to /fs/*
mg_http_stream_body(c, ev, ev_data, mg_str("/fs/*"), upload);
} }
int main(void) { int main(void) {
+1 -1
View File
@@ -65,7 +65,7 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
} }
c->fn_data = c2; c->fn_data = c2;
forward_request(hm, c2); forward_request(hm, c2);
c->is_resp = 0; // process further msgs in keep-alive connection c->pfn_data = NULL; // process further msgs in keep-alive connection
c2->is_hexdumping = 1; c2->is_hexdumping = 1;
} }
} else if (ev == MG_EV_CLOSE) { } else if (ev == MG_EV_CLOSE) {
+21 -16
View File
@@ -1,27 +1,32 @@
PROG ?= example # Program we are building REPO_ROOT ?= ../../..
DELETE = rm -rf # Command to remove files PROG ?= example
OUT ?= -o $(PROG) # Compiler argument for output file DELETE = rm -rf
SOURCES = main.c mongoose.c mongoose_mqtt.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS OUT ?= -o $(PROG)
CFLAGS = -W -Wall -Wextra -g -I. # Build options CFLAGS = -W -Wall -Wextra -g -I. -I$(REPO_ROOT)
SOURCES = main.c mongoose_mqtt.c $(REPO_ROOT)/mongoose.c
# Mongoose build options. See https://mongoose.ws/docs/getting-started/build-options/ # Mongoose build options. See https://mongoose.ws/docs/getting-started/build-options/
CFLAGS_EXTRA ?= -DMG_TLS=MG_TLS_BUILTIN CFLAGS_MONGOOSE += -DMG_TLS=MG_TLS_BUILTIN
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe # This is for Azure - it just cannot Chacha20
PROG ?= example.exe # Use .exe suffix for the binary CFLAGS_MONGOOSE += -DMG_ENABLE_CHACHA20=0
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library # Windows settings. Assume MinGW compiler.
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files # To use VS compiler, run: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
OUT ?= -o $(PROG) # Build output ifeq ($(OS),Windows_NT)
MAKE += WINDOWS=1 CC=$(CC) PROG ?= example.exe
CC = gcc
CFLAGS += -lws2_32
DELETE = cmd /C del /Q /F /S
OUT ?= -o $(PROG)
endif endif
all: $(PROG) # Default target. Build and run program all: $(PROG)
$(RUN) ./$(PROG) $(ARGS) $(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) # Build program from sources $(PROG): $(SOURCES)
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT) $(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
clean: # Cleanup. Delete built program and all build artifacts clean:
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls $(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
+97 -1
View File
@@ -1 +1,97 @@
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client/ # Mongoose MQTT client
This MQTT client implementation implements the following:
- Connects to the MQTT server specified by MQTT_SERVER_URL
- When connected, subscribes to the topic MQTT_SUBSCRIBE_TOPIC
- When it receives a message, echoes it back to MQTT_PUBLISH_TOPIC
- Timer-based reconnection logic revives the connection when it is down
- Ping server periodically. When disconnected, a last will is published
- Implements "ota.update" for OTA updates, see https://mongoose.ws/mqtt/
By default, it uses HiveMQ public broker, and can be tested with
the [HiveMQ Websocket Client](https://www.hivemq.com/demos/websocket-client/):
- Subscribe to `mg/123/#`
- Send a message to `mg/123/rx`
## Integrating into an embedded project
1. Copy `mongoose_mqtt.c` to your embedded project and add it to the build
2. Add `mg_mqtt_init(&mgr)` after `mg_mgr_init()`
3. Add `mg_mqtt_poll(&mgr)` after `mg_mgr_poll()`
## Microsoft Azure IoT Hub
1. Create IoT Hub
2. Generate device self-signed certificates:
```sh
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -pkeyopt ec_param_enc:named_curve -nodes -keyout device.key -out device.crt -days 3650 -subj "/CN=MYDEVICE"
```
3. Show certificate thumbprint:
```sh
openssl x509 -in device.crt -noout -fingerprint -sha256 | tr -d ':' | cut -d= -f2
```
4. Register a device with the thumbprint from above, and set the following:
```c
#define AZURE_HUB_NAME "HUB_NAME" // Change this
#define AZURE_DEVICE_ID "DEVICE_ID" // Change this
// Do not change this
#define MQTT_SERVER_URL "mqtts://" AZURE_HUB_NAME ".device.azure-devices.net"
#define MQTT_CLIENT_ID AZURE_DEVICE_ID
#define MQTT_USER AZURE_HUB_NAME ".azure-devices.net/" AZURE_DEVICE_ID "/?api-version=2021-04-12"
#define MQTT_PUBLISH_TOPIC "devices/" AZURE_DEVICE_ID "/messages/events/"
#define MQTT_SUBSCRIBE_TOPIC "devices/" AZURE_DEVICE_ID "/messages/devicebound/#"
```
5. Set `TLS_CA`. Visit https://mongoose.ws/tls/, enter "HUB_NAME.device.azure-devices.nett:8883" into the CA field and click on the "Get CA Certificate" button. Enable the "Show as C/C++ constant", copy-paste to your code.
6. Set `TLS_KEY` and `TLS_CRT` with the output of this commands:
```sh
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.key
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.crt
```
7. Add to your `mongoose_config.h`:
```c
#define MG_ENABLE_CHACHA20 0
```
## Microsoft Azure Event Grid
1. Create Azure Event Grid (EG) instance
2. Generate device self-signed certificates:
```sh
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -pkeyopt ec_param_enc:named_curve -nodes -keyout device.key -out device.crt -days 3650 -subj "/CN=MYDEVICE"
```
3. Show certificate thumbprint:
```sh
openssl x509 -in device.crt -noout -fingerprint -sha256 | tr -d ':' | cut -d= -f2
```
4. Register a client on EG: choose a name, and use the thumbprint from above
5. Set URL, username and client ID:
```c
#define MQTT_SERVER_URL "mqtts://INSTANCE.REGION.ts.eventgrid.azure.net:8883"
#define MQTT_CLIENT_ID "CLIENT_NAME"
#define MQTT_USER "CLIENT_NAME"
```
6. Set `TLS_CA`. Visit https://mongoose.ws/tls/, enter "INSTANCE.REGION.ts.eventgrid.azure.net:8883" into the CA field and click on the "Get CA Certificate" button. Enable the "Show as C/C++ constant", copy-paste to your code.
7. Set `TLS_KEY` and `TLS_CRT` with the output of this commands:
```sh
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.key
sed 's/\r$//; s/.*/ "&\\n"/; $!s/$/ \\/' device.crt
```
8. In Azure EG, go to Instance / MQTT Broker / Topic spaces, add "space1" with `mg/#` pattern
9. In Azure EG, go to Instance / MQTT Broker / Permissions bindings, add binding1 and binding2:
- $all , space1 , Publisher
- $all , space1 , Subscriber
-1
View File
@@ -1 +0,0 @@
../../../mongoose.c
-1
View File
@@ -1 +0,0 @@
../../../mongoose.h
+49 -30
View File
@@ -1,24 +1,22 @@
// Copyright (c) 2026 Cesanta Software Limited // Copyright (c) 2026 Cesanta Software Limited
// All rights reserved // All rights reserved
//
// Example MQTT client. It performs the following steps:
// 1. Connects to the MQTT server specified by MQTT_SERVER_URL
// 2. When connected, subscribes to the topic MQTT_SUBSCRIBE_TOPIC
// 3. When it receives a message, echoes it back to MQTT_PUBLISH_TOPIC
// 4. Timer-based reconnection logic revives the connection when it is down
// 5. Ping server periodically. When disconnected, a last will is published
// 6. Implements "ota.update" for OTA updates, see https://mongoose.ws/mqtt/
#include "mongoose.h" #include "mongoose.h"
#define MQTT_SERVER_URL "mqtt://broker.hivemq.com:1883" #define MQTT_SERVER_URL "mqtt://broker.hivemq.com:1883"
#define MQTT_PUBLISH_TOPIC "mg/123/tx" #define MQTT_CLIENT_ID "d3"
#define MQTT_SUBSCRIBE_TOPIC "mg/123/rx" #define MQTT_USER MQTT_CLIENT_ID
#define MQTT_PASS ""
#define MQTT_PUBLISH_TOPIC "mg/" MQTT_CLIENT_ID "/tx"
#define MQTT_SUBSCRIBE_TOPIC "mg/" MQTT_CLIENT_ID "/rx"
#define MQTT_QOS 1 #define MQTT_QOS 1
#define RECONNECT_PERIOD_MS 3000 #define MQTT_RECONNECT_PERIOD_MS 3000
#define TLS_CA ""
#define TLS_KEY ""
#define TLS_CRT ""
static struct mg_connection *s_mqtt_conn; // Client connection static struct mg_connection *s_mqtt_conn; // Client connection
static struct mg_rpc *s_rpc = NULL; // List of registered RPC methods
static void subscribe(struct mg_connection *c, struct mg_str topic) { static void subscribe(struct mg_connection *c, struct mg_str topic) {
struct mg_mqtt_opts opts = {}; struct mg_mqtt_opts opts = {};
@@ -69,7 +67,9 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
// c->is_hexdumping = 1; // c->is_hexdumping = 1;
} else if (ev == MG_EV_CONNECT) { } else if (ev == MG_EV_CONNECT) {
if (c->is_tls) { if (c->is_tls) {
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"), struct mg_tls_opts opts = {.ca = mg_str(TLS_CA),
.cert = mg_str(TLS_CRT),
.key = mg_str(TLS_KEY),
.name = mg_url_host(MQTT_SERVER_URL)}; .name = mg_url_host(MQTT_SERVER_URL)};
mg_tls_init(c, &opts); mg_tls_init(c, &opts);
} }
@@ -77,16 +77,31 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
// On error, log error message // On error, log error message
MG_ERROR(("%lu ERROR %s", c->id, (char *) ev_data)); MG_ERROR(("%lu ERROR %s", c->id, (char *) ev_data));
} else if (ev == MG_EV_MQTT_OPEN) { } else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connect is successful int status = *(int *) ev_data;
MG_DEBUG(("%lu CONNECTED to %s", c->id, MQTT_SERVER_URL)); MG_DEBUG(("%lu CONNECT status: %d", c->id, status));
subscribe(c, mg_str(MQTT_SUBSCRIBE_TOPIC)); if (status == 0) {
subscribe(c, mg_str(MQTT_SUBSCRIBE_TOPIC));
if (mg_match(mg_str(MQTT_SERVER_URL), mg_str("#azure-devices.net"), 0)) {
// This is Azure IoT Hub. Subscribe for DPS messages
subscribe(c, mg_str("$iothub/methods/POST/#"));
}
}
} else if (ev == MG_EV_MQTT_MSG) { } else if (ev == MG_EV_MQTT_MSG) {
// When we get echo response, print it // When we get echo response, print it
char response[100];
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data; struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
mg_snprintf(response, sizeof(response), "Got %.*s -> %.*s", mm->topic.len, struct mg_str caps[5]; // caps[0] = method name, caps[2] = request id
mm->topic.buf, mm->data.len, mm->data.buf); if (mg_match(mm->topic, mg_str("$iothub/methods/POST/*/?$rid=*"), caps)) {
publish(c, mg_str(MQTT_PUBLISH_TOPIC), mg_str(response)); // Azure direct method call. Construct a stub response, "{}"
char topic[128];
mg_snprintf(topic, sizeof(topic), "$iothub/methods/res/%d/?$rid=%.*s",
200, (int) caps[2].len, caps[2].buf);
publish(c, mg_str(topic), mg_str("{}"));
} else {
char response[100];
mg_snprintf(response, sizeof(response), "Got %.*s -> %.*s", mm->topic.len,
mm->topic.buf, mm->data.len, mm->data.buf);
publish(c, mg_str(MQTT_PUBLISH_TOPIC), mg_str(response));
}
} else if (ev == MG_EV_MQTT_CMD) { } else if (ev == MG_EV_MQTT_CMD) {
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data; struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
if (mm->cmd == MQTT_CMD_PINGREQ) mg_mqtt_pong(c); if (mm->cmd == MQTT_CMD_PINGREQ) mg_mqtt_pong(c);
@@ -97,9 +112,7 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
} }
void mg_mqtt_init(struct mg_mgr *mgr) { void mg_mqtt_init(struct mg_mgr *mgr) {
(void) mgr; mg_rpc_add(&mgr->rpcs, mg_str("ota.update"), rpc_ota_update, NULL);
if (!s_rpc) mg_rpc_add(&s_rpc, mg_str("ota.update"), rpc_ota_update, NULL);
mg_mem_files = mg_packed_files; // Use generated packed filesystem
} }
void mg_mqtt_poll(struct mg_mgr *mgr) { void mg_mqtt_poll(struct mg_mgr *mgr) {
@@ -107,18 +120,24 @@ void mg_mqtt_poll(struct mg_mgr *mgr) {
// Reconnect if connection is closed, and send MQTT PINGs to keep // Reconnect if connection is closed, and send MQTT PINGs to keep
// the connection alive or to detect connection loss // the connection alive or to detect connection loss
if (mg_timer_expired(&timer, RECONNECT_PERIOD_MS, mg_now())) { if (mg_timer_expired(&timer, MQTT_RECONNECT_PERIOD_MS, mg_now())) {
if (s_mqtt_conn == NULL) { if (s_mqtt_conn == NULL) {
struct mg_mqtt_opts opts = {.clean = true, struct mg_mqtt_opts opts = {
.qos = MQTT_QOS, .clean = true,
.topic = mg_str(MQTT_PUBLISH_TOPIC), .client_id = mg_str(MQTT_CLIENT_ID),
.keepalive = 5, .user = mg_str(MQTT_USER),
.version = 4, .pass = mg_str(MQTT_PASS),
.message = mg_str("bye")}; .qos = MQTT_QOS,
.keepalive = 5,
.version = 4, // MQTT 3.1.1
.topic = mg_str(MQTT_PUBLISH_TOPIC),
.message = mg_str("bye"),
};
s_mqtt_conn = s_mqtt_conn =
mg_mqtt_connect(mgr, MQTT_SERVER_URL, &opts, mqtt_ev_handler, NULL); mg_mqtt_connect(mgr, MQTT_SERVER_URL, &opts, mqtt_ev_handler, NULL);
} else { } else {
mg_mqtt_ping(s_mqtt_conn); mg_mqtt_ping(s_mqtt_conn);
// publish(s_mqtt_conn, mg_str(MQTT_PUBLISH_TOPIC), mg_str("hi"));
} }
} }
} }
-1
View File
@@ -1 +0,0 @@
../../http/http-client/packed_fs.c
+9 -7
View File
@@ -1,33 +1,31 @@
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/ # Environment setup: https://mongoose.ws/documentation/tutorials/tools/
MGDIR = ../../../..
CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion
CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion
CFLAGS += -g3 -Os -ffunction-sections -fdata-sections CFLAGS += -g3 -Os -ffunction-sections -fdata-sections
CFLAGS += -Wno-cast-function-type -Wno-old-style-declaration CFLAGS += -Wno-cast-function-type -Wno-old-style-declaration
CFLAGS += -Wno-unused-parameter CFLAGS += -Wno-unused-parameter
CFLAGS += -I. -Imongoose -Icmsis_core/CMSIS/Core/Include/ CFLAGS += -I. -I$(MGDIR) -Imongoose -Icmsis_core/CMSIS/Core/Include/
CFLAGS += -Icmsis_rw612/devices/RW612/ -Icmsis_rw612/devices/RW612/periph/ -Icmsis_rw612/devices/RW612/drivers/ CFLAGS += -Icmsis_rw612/devices/RW612/ -Icmsis_rw612/devices/RW612/periph/ -Icmsis_rw612/devices/RW612/drivers/
CFLAGS += -DCPU_RW612ETA2I -DCPU_RW612ETA2I_cm33_no_dsp CFLAGS += -DCPU_RW612ETA2I -DCPU_RW612ETA2I_cm33_no_dsp
CFLAGS += -DBOOT_HEADER_ENABLE=1 CFLAGS += -DBOOT_HEADER_ENABLE=1
CFLAGS += -mcpu=cortex-m33+nodsp -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 $(CFLAGS_EXTRA) CFLAGS += -mcpu=cortex-m33+nodsp -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 $(CFLAGS_EXTRA)
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=$@.map LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=$@.map
SOURCES = main.c hal.c startup.c flexspi.c flash_config.c mongoose/mongoose.c SOURCES = main.c hal.c startup.c flexspi.c flash_config.c $(MGDIR)/mongoose.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_clock.c SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_clock.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_trng.c SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_trng.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_reset.c SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_reset.c
all build: firmware.bin all build: firmware.bin
mongoose/mongoose.c mongoose/mongoose.h:
mkdir -p mongoose
cp ../../../../mongoose.[ch] mongoose/
firmware.bin: firmware.elf firmware.bin: firmware.elf
arm-none-eabi-objcopy -O binary $< $@ arm-none-eabi-objcopy -O binary $< $@
arm-none-eabi-size --format=berkeley $< arm-none-eabi-size --format=berkeley $<
firmware.elf: cmsis_core cmsis_rw612 $(SOURCES) $(wildcard *.h) link.ld Makefile firmware.elf: cmsis_core cmsis_rw612 $(SOURCES) $(wildcard *.h) link.ld Makefile mongoose_config.h
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@ arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
cmsis_core: cmsis_core:
@@ -38,5 +36,9 @@ cmsis_rw612:
unzip -q NXP.RW612_DFP.25.12.00.pack -d $@ unzip -q NXP.RW612_DFP.25.12.00.pack -d $@
rm NXP.RW612_DFP.25.12.00.pack rm NXP.RW612_DFP.25.12.00.pack
flash: firmware.bin
(echo 'loadfile firmware.elf'; echo 'reset'; echo 'exit';) | JLinkExe -device RW612 -if SWD -speed 4000 -autoconnect 1 -NoGui 1 -ExitOnError 1
# JRun --nogui --device RW612 --if SWD firmware.elf
clean: clean:
rm -rf firmware.* cmsis_* mongoose/mongoose.* rm -rf firmware.* cmsis_* mongoose/mongoose.*
+1 -1
View File
@@ -18,7 +18,7 @@ static void log_fn(char ch, void *param) {
static void blink_task(void) { static void blink_task(void) {
static uint64_t blink_timer = 0; static uint64_t blink_timer = 0;
if (hal_timer_expired(&blink_timer, 500, hal_get_tick())) { if (hal_timer_expired(&blink_timer, 100, hal_get_tick())) {
hal_gpio_toggle(LED1); hal_gpio_toggle(LED1);
} }
} }
@@ -8,6 +8,11 @@
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_OTA MG_OTA_RW612 #define MG_OTA MG_OTA_RW612
#define MG_TLS MG_TLS_BUILTIN
#define MG_ENABLE_MDASH 0 // Set to 1 to enable https://mdash.net
#define MG_MDASH_KEY "..." // Edit, see https://mdash.net/docs/#mongoose-library
#define MG_FIRMWARE_VERSION "1.0.1"
// #define MG_DRIVER_MDC_CR 51 // RMII MDC clock divider // #define MG_DRIVER_MDC_CR 51 // RMII MDC clock divider
// #define MG_DRIVER_MDC_HOLDTIME 3 // RMII MDC Holdtime (valid values [0-7]) // #define MG_DRIVER_MDC_HOLDTIME 3 // RMII MDC Holdtime (valid values [0-7])
@@ -0,0 +1,97 @@
cmake_minimum_required(VERSION 3.22)
#
# This file is generated only once,
# and is not re-generated if converter is called multiple times.
#
# User is free to modify the file as much as necessary
#
# Setup compiler settings
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)
# Define the build type
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Debug")
endif()
# Set the project name
set(CMAKE_PROJECT_NAME nucleo-h563zi)
# Enable compile command to ease indexing with e.g. clangd
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)
# Core project settings
project(${CMAKE_PROJECT_NAME})
message("Build type: " ${CMAKE_BUILD_TYPE})
# Enable CMake support for ASM and C languages
enable_language(C ASM)
# Create an executable object type
add_executable(${CMAKE_PROJECT_NAME})
# Add STM32CubeMX generated sources
add_subdirectory(cmake/stm32cubemx)
# Link directories setup
target_link_directories(${CMAKE_PROJECT_NAME} PRIVATE
# Add user defined library search paths
)
# Generate file_data.c from dashboard.html
add_custom_command(
OUTPUT ${CMAKE_SOURCE_DIR}/mongoose/file_data.c
COMMAND node ${CMAKE_SOURCE_DIR}/../../../../resources/html2c.js ${CMAKE_SOURCE_DIR}/mongoose/dashboard.html -o ${CMAKE_SOURCE_DIR}/mongoose/file_data.c
DEPENDS ${CMAKE_SOURCE_DIR}/mongoose/dashboard.html
VERBATIM
)
# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
# Add user sources here
${CMAKE_SOURCE_DIR}/mongoose/dashboard.c
${CMAKE_SOURCE_DIR}/mongoose/file_data.c
${CMAKE_SOURCE_DIR}/../../../../mongoose.c
${CMAKE_SOURCE_DIR}/littlefs/lfs.c
${CMAKE_SOURCE_DIR}/littlefs/lfs_util.c
)
# Add include paths
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
# Add user defined include paths
${CMAKE_SOURCE_DIR}/mongoose/
${CMAKE_SOURCE_DIR}/littlefs/
${CMAKE_SOURCE_DIR}/../../../..
)
# Add project symbols (macros)
target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
# Add user defined symbols
)
# Remove wrong libob.a library dependency when using cpp files
list(REMOVE_ITEM CMAKE_C_IMPLICIT_LINK_LIBRARIES ob)
# Add linked libraries
target_link_libraries(${CMAKE_PROJECT_NAME}
stm32cubemx
# Add user defined libraries
)
# Generate .bin from .elf
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
COMMAND arm-none-eabi-objcopy -O binary $<TARGET_FILE:${CMAKE_PROJECT_NAME}> ${CMAKE_PROJECT_NAME}.bin
VERBATIM
)
if(EXISTS ${CMAKE_SOURCE_DIR}/private.pem)
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
COMMAND node ${CMAKE_SOURCE_DIR}/mongoose/sign.js sign ${CMAKE_PROJECT_NAME}.bin ${CMAKE_SOURCE_DIR}/private.pem
VERBATIM
)
endif()
@@ -0,0 +1,38 @@
{
"version": 3,
"configurePresets": [
{
"name": "default",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"toolchainFile": "${sourceDir}/cmake/gcc-arm-none-eabi.cmake",
"cacheVariables": {
}
},
{
"name": "Debug",
"inherits": "default",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},
{
"name": "Release",
"inherits": "default",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
}
}
],
"buildPresets": [
{
"name": "Debug",
"configurePreset": "Debug"
},
{
"name": "Release",
"configurePreset": "Release"
}
]
}
@@ -0,0 +1,69 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32h5xx_hal.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */
@@ -0,0 +1,526 @@
/* USER CODE BEGIN Header */
/**
**********************************************************************************************************************
* @file stm32h5xx_hal_conf.h
* @author MCD Application Team
* @brief HAL configuration file.
**********************************************************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
**********************************************************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -----------------------------------------------------------------------------*/
#ifndef STM32H5xx_HAL_CONF_H
#define STM32H5xx_HAL_CONF_H
#ifdef __cplusplus
extern "C" {
#endif
/* Exported types ----------------------------------------------------------------------------------------------------*/
/* Exported constants ------------------------------------------------------------------------------------------------*/
/* ########################################### Module Selection ##################################################### */
/**
* @brief This is the list of modules to be used in the HAL driver
*/
#define HAL_MODULE_ENABLED
/*#define HAL_CCB_MODULE_ENABLED */
/*#define HAL_ADC_MODULE_ENABLED */
/*#define HAL_CEC_MODULE_ENABLED */
/*#define HAL_COMP_MODULE_ENABLED */
/*#define HAL_CORDIC_MODULE_ENABLED */
/*#define HAL_CRC_MODULE_ENABLED */
/*#define HAL_CRYP_MODULE_ENABLED */
/*#define HAL_DAC_MODULE_ENABLED */
/*#define HAL_DCACHE_MODULE_ENABLED */
/*#define HAL_DCMI_MODULE_ENABLED */
/*#define HAL_DTS_MODULE_ENABLED */
#define HAL_ETH_MODULE_ENABLED
/*#define HAL_FDCAN_MODULE_ENABLED */
/*#define HAL_FMAC_MODULE_ENABLED */
/*#define HAL_GTZC_MODULE_ENABLED */
/*#define HAL_HASH_MODULE_ENABLED */
/*#define HAL_HCD_MODULE_ENABLED */
/*#define HAL_IRDA_MODULE_ENABLED */
/*#define HAL_IWDG_MODULE_ENABLED */
/*#define HAL_I2C_MODULE_ENABLED */
/*#define HAL_I3C_MODULE_ENABLED */
/*#define HAL_I2S_MODULE_ENABLED */
/*#define HAL_LPTIM_MODULE_ENABLED */
/*#define HAL_NAND_MODULE_ENABLED */
/*#define HAL_NOR_MODULE_ENABLED */
/*#define HAL_OPAMP_MODULE_ENABLED */
/*#define HAL_XSPI_MODULE_ENABLED */
/*#define HAL_OTFDEC_MODULE_ENABLED */
/*#define HAL_PKA_MODULE_ENABLED */
#define HAL_RNG_MODULE_ENABLED
/*#define HAL_RTC_MODULE_ENABLED */
/*#define HAL_SAI_MODULE_ENABLED */
/*#define HAL_SD_MODULE_ENABLED */
/*#define HAL_SDIO_MODULE_ENABLED */
/*#define HAL_SDRAM_MODULE_ENABLED */
/*#define HAL_MMC_MODULE_ENABLED */
/*#define HAL_SMARTCARD_MODULE_ENABLED */
/*#define HAL_SMBUS_MODULE_ENABLED */
/*#define HAL_SPI_MODULE_ENABLED */
/*#define HAL_SRAM_MODULE_ENABLED */
/*#define HAL_TIM_MODULE_ENABLED */
/*#define HAL_RAMCFG_MODULE_ENABLED */
#define HAL_UART_MODULE_ENABLED
/*#define HAL_USART_MODULE_ENABLED */
/*#define HAL_WWDG_MODULE_ENABLED */
/*#define HAL_PSSI_MODULE_ENABLED */
#define HAL_ICACHE_MODULE_ENABLED
/*#define HAL_PCD_MODULE_ENABLED */
#define HAL_GPIO_MODULE_ENABLED
#define HAL_EXTI_MODULE_ENABLED
#define HAL_DMA_MODULE_ENABLED
#define HAL_RCC_MODULE_ENABLED
#define HAL_FLASH_MODULE_ENABLED
#define HAL_PWR_MODULE_ENABLED
#define HAL_CORTEX_MODULE_ENABLED
/* ####################################### Oscillator Values adaptation ##############################################*/
/**
* @brief Adjust the value of External High Speed oscillator (HSE) used in your application.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSE is used as system clock source, directly or through the PLL).
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE 25000000U /*!< Value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSE_STARTUP_TIMEOUT)
#define HSE_STARTUP_TIMEOUT 100U /*!< Time out for HSE start up, in ms */
#endif /* HSE_STARTUP_TIMEOUT */
/**
* @brief Internal Core Speed oscillator (CSI) default value.
* This value is the default CSI range value after Reset.
*/
#if !defined (CSI_VALUE)
#define CSI_VALUE 4000000UL /*!< Value of the Internal oscillator in Hz*/
#endif /* CSI_VALUE */
/**
* @brief Internal High Speed oscillator (HSI) value.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSI is used as system clock source, directly or through the PLL).
*/
#if !defined (HSI_VALUE)
#define HSI_VALUE 64000000UL /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
/**
* @brief Internal High Speed oscillator (HSI48) value for USB FS, SDMMC and RNG.
* This internal oscillator is mainly dedicated to provide a high precision clock to
* the USB peripheral by means of a special Clock Recovery System (CRS) circuitry.
* When the CRS is not used, the HSI48 RC oscillator runs on it default frequency
* which is subject to manufacturing process variations.
*/
#if !defined (HSI48_VALUE)
#define HSI48_VALUE 48000000UL /*!< Value of the Internal High Speed oscillator for USB FS/SDMMC/RNG in Hz.
The real value my vary depending on manufacturing process variations.*/
#endif /* HSI48_VALUE */
/**
* @brief Internal Low Speed oscillator (LSI) value.
*/
#if !defined (LSI_VALUE)
#define LSI_VALUE 32000UL /*!< LSI Typical Value in Hz*/
#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz
The real value may vary depending on the variations
in voltage and temperature.*/
#if !defined (LSI_STARTUP_TIME)
#define LSI_STARTUP_TIME 130UL /*!< Time out for LSI start up, in us */
#endif /* LSI_STARTUP_TIME */
/**
* @brief External Low Speed oscillator (LSE) value.
* This value is used by the UART, RTC HAL module to compute the system frequency
*/
#if !defined (LSE_VALUE)
#define LSE_VALUE 32768UL /*!< Value of the External oscillator in Hz*/
#endif /* LSE_VALUE */
#if !defined (LSE_STARTUP_TIMEOUT)
#define LSE_STARTUP_TIMEOUT 5000UL /*!< Time out for LSE start up, in ms */
#endif /* LSE_STARTUP_TIMEOUT */
/**
* @brief External clock source for SPI/SAI peripheral
* This value is used by the SPI/SAI HAL module to compute the SPI/SAI clock source
* frequency, this source is inserted directly through I2S_CKIN pad.
*/
#if !defined (EXTERNAL_CLOCK_VALUE)
#define EXTERNAL_CLOCK_VALUE 12288000UL /*!< Value of the External clock in Hz*/
#endif /* EXTERNAL_CLOCK_VALUE */
/* Tip: To avoid modifying this file each time you need to use different HSE,
=== you can define the HSE value in your toolchain compiler preprocessor. */
/* ############################################ System Configuration ################################################ */
/**
* @brief This is the HAL system configuration section
*/
#define VDD_VALUE 3300UL /*!< Value of VDD in mv */
#define TICK_INT_PRIORITY (15UL) /*!< tick interrupt priority (lowest by default) */
#define USE_RTOS 0U
#define PREFETCH_ENABLE 0U /*!< Enable prefetch */
/* ############################################ Assert Selection #################################################### */
/**
* @brief Uncomment the line below to expanse the "assert_param" macro in the
* HAL drivers code
*/
/* #define USE_FULL_ASSERT 1U */
/* ############################################ Register callback feature configuration ############################# */
/**
* @brief Set below the peripheral configuration to "1U" to add the support
* of HAL callback registration/unregistration feature for the HAL
* driver(s). This allows user application to provide specific callback
* functions thanks to HAL_PPP_RegisterCallback() rather than overwriting
* the default weak callback functions (see each stm32h5xx_hal_ppp.h file
* for possible callback identifiers defined in HAL_PPP_CallbackIDTypeDef
* for each PPP peripheral).
*/
#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */
#define USE_HAL_CCB_REGISTER_CALLBACKS 0U /* CCB register callback disabled */
#define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */
#define USE_HAL_COMP_REGISTER_CALLBACKS 0U /* COMP register callback disabled */
#define USE_HAL_CORDIC_REGISTER_CALLBACKS 0U /* CORDIC register callback disabled */
#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U /* CRYP register callback disabled */
#define USE_HAL_DAC_REGISTER_CALLBACKS 0U /* DAC register callback disabled */
#define USE_HAL_DCMI_REGISTER_CALLBACKS 0U /* DCMI register callback disabled */
#define USE_HAL_DTS_REGISTER_CALLBACKS 0U /* DTS register callback disabled */
#define USE_HAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */
#define USE_HAL_FDCAN_REGISTER_CALLBACKS 0U /* FDCAN register callback disabled */
#define USE_HAL_FMAC_REGISTER_CALLBACKS 0U /* FMAC register callback disabled */
#define USE_HAL_NOR_REGISTER_CALLBACKS 0U /* NOR register callback disabled */
#define USE_HAL_HASH_REGISTER_CALLBACKS 0U /* HASH register callback disabled */
#define USE_HAL_HCD_REGISTER_CALLBACKS 0U /* HCD register callback disabled */
#define USE_HAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */
#define USE_HAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */
#define USE_HAL_I3C_REGISTER_CALLBACKS 0U /* I3C register callback disabled */
#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */
#define USE_HAL_IWDG_REGISTER_CALLBACKS 0U /* IWDG register callback disabled */
#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U /* LPTIM register callback disabled */
#define USE_HAL_MMC_REGISTER_CALLBACKS 0U /* MMC register callback disabled */
#define USE_HAL_NAND_REGISTER_CALLBACKS 0U /* NAND register callback disabled */
#define USE_HAL_OPAMP_REGISTER_CALLBACKS 0U /* OPAMP register callback disabled */
#define USE_HAL_OTFDEC_REGISTER_CALLBACKS 0U /* OTFDEC register callback disabled */
#define USE_HAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */
#define USE_HAL_PKA_REGISTER_CALLBACKS 0U /* PKA register callback disabled */
#define USE_HAL_RAMCFG_REGISTER_CALLBACKS 0U /* RAMCFG register callback disabled */
#define USE_HAL_RNG_REGISTER_CALLBACKS 0U /* RNG register callback disabled */
#define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */
#define USE_HAL_SAI_REGISTER_CALLBACKS 0U /* SAI register callback disabled */
#define USE_HAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */
#define USE_HAL_SDIO_REGISTER_CALLBACKS 0U /* SDIO register callback disabled */
#define USE_HAL_SDRAM_REGISTER_CALLBACKS 0U /* SDRAM register callback disabled */
#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */
#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U /* SMBUS register callback disabled */
#define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */
#define USE_HAL_SRAM_REGISTER_CALLBACKS 0U /* SRAM register callback disabled */
#define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */
#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */
#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */
#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */
#define USE_HAL_XSPI_REGISTER_CALLBACKS 0U /* XSPI register callback disabled */
/* ############################################ SPI peripheral configuration ######################################## */
/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver
* Activated: CRC code is present inside driver
* Deactivated: CRC code cleaned from driver
*/
#define USE_SPI_CRC 0U
/* ################## SDMMC peripheral configuration ######################### */
#define USE_SD_TRANSCEIVER 0U
/* ################## SDIO peripheral configuration ######################### */
#define USE_SDIO_TRANSCEIVER 0U
#define SDIO_MAX_IO_NUMBER 7U
/* ################## ETH peripheral configuration ######################### */
#define ETH_TX_DESC_CNT 4U
#define ETH_RX_DESC_CNT 4U
/* Includes ----------------------------------------------------------------------------------------------------------*/
/**
* @brief Include module's header file
*/
#ifdef HAL_RCC_MODULE_ENABLED
#include "stm32h5xx_hal_rcc.h"
#endif /* HAL_RCC_MODULE_ENABLED */
#ifdef HAL_GPIO_MODULE_ENABLED
#include "stm32h5xx_hal_gpio.h"
#endif /* HAL_GPIO_MODULE_ENABLED */
#ifdef HAL_ICACHE_MODULE_ENABLED
#include "stm32h5xx_hal_icache.h"
#endif /* HAL_ICACHE_MODULE_ENABLED */
#ifdef HAL_DCACHE_MODULE_ENABLED
#include "stm32h5xx_hal_dcache.h"
#endif /* HAL_DCACHE_MODULE_ENABLED */
#ifdef HAL_GTZC_MODULE_ENABLED
#include "stm32h5xx_hal_gtzc.h"
#endif /* HAL_GTZC_MODULE_ENABLED */
#ifdef HAL_DMA_MODULE_ENABLED
#include "stm32h5xx_hal_dma.h"
#endif /* HAL_DMA_MODULE_ENABLED */
#ifdef HAL_DTS_MODULE_ENABLED
#include "stm32h5xx_hal_dts.h"
#endif /* HAL_DTS_MODULE_ENABLED */
#ifdef HAL_CORTEX_MODULE_ENABLED
#include "stm32h5xx_hal_cortex.h"
#endif /* HAL_CORTEX_MODULE_ENABLED */
#ifdef HAL_PKA_MODULE_ENABLED
#include "stm32h5xx_hal_pka.h"
#endif /* HAL_PKA_MODULE_ENABLED */
#ifdef HAL_ADC_MODULE_ENABLED
#include "stm32h5xx_hal_adc.h"
#endif /* HAL_ADC_MODULE_ENABLED */
#ifdef HAL_CRC_MODULE_ENABLED
#include "stm32h5xx_hal_crc.h"
#endif /* HAL_CRC_MODULE_ENABLED */
#ifdef HAL_CRYP_MODULE_ENABLED
#include "stm32h5xx_hal_cryp.h"
#endif /* HAL_CRYP_MODULE_ENABLED */
#ifdef HAL_DAC_MODULE_ENABLED
#include "stm32h5xx_hal_dac.h"
#endif /* HAL_DAC_MODULE_ENABLED */
#ifdef HAL_FLASH_MODULE_ENABLED
#include "stm32h5xx_hal_flash.h"
#endif /* HAL_FLASH_MODULE_ENABLED */
#ifdef HAL_HASH_MODULE_ENABLED
#include "stm32h5xx_hal_hash.h"
#endif /* HAL_HASH_MODULE_ENABLED */
#ifdef HAL_SRAM_MODULE_ENABLED
#include "stm32h5xx_hal_sram.h"
#endif /* HAL_SRAM_MODULE_ENABLED */
#ifdef HAL_SDRAM_MODULE_ENABLED
#include "stm32h5xx_hal_sdram.h"
#endif /* HAL_SDRAM_MODULE_ENABLED */
#ifdef HAL_SDIO_MODULE_ENABLED
#include "stm32h5xx_hal_sdio.h"
#endif /* HAL_SDIO_MODULE_ENABLED */
#ifdef HAL_MMC_MODULE_ENABLED
#include "stm32h5xx_hal_mmc.h"
#endif /* HAL_MMC_MODULE_ENABLED */
#ifdef HAL_NOR_MODULE_ENABLED
#include "stm32h5xx_hal_nor.h"
#endif /* HAL_NOR_MODULE_ENABLED */
#ifdef HAL_NAND_MODULE_ENABLED
#include "stm32h5xx_hal_nand.h"
#endif /* HAL_NAND_MODULE_ENABLED */
#ifdef HAL_I2C_MODULE_ENABLED
#include "stm32h5xx_hal_i2c.h"
#endif /* HAL_I2C_MODULE_ENABLED */
#ifdef HAL_I2S_MODULE_ENABLED
#include "stm32h5xx_hal_i2s.h"
#endif /* HAL_I2S_MODULE_ENABLED */
#ifdef HAL_I3C_MODULE_ENABLED
#include "stm32h5xx_hal_i3c.h"
#endif /* HAL_I3C_MODULE_ENABLED */
#ifdef HAL_IWDG_MODULE_ENABLED
#include "stm32h5xx_hal_iwdg.h"
#endif /* HAL_IWDG_MODULE_ENABLED */
#ifdef HAL_LPTIM_MODULE_ENABLED
#include "stm32h5xx_hal_lptim.h"
#endif /* HAL_LPTIM_MODULE_ENABLED */
#ifdef HAL_PWR_MODULE_ENABLED
#include "stm32h5xx_hal_pwr.h"
#endif /* HAL_PWR_MODULE_ENABLED */
#ifdef HAL_XSPI_MODULE_ENABLED
#include "stm32h5xx_hal_xspi.h"
#endif /* HAL_XSPI_MODULE_ENABLED */
#ifdef HAL_RNG_MODULE_ENABLED
#include "stm32h5xx_hal_rng.h"
#endif /* HAL_RNG_MODULE_ENABLED */
#ifdef HAL_RTC_MODULE_ENABLED
#include "stm32h5xx_hal_rtc.h"
#endif /* HAL_RTC_MODULE_ENABLED */
#ifdef HAL_SAI_MODULE_ENABLED
#include "stm32h5xx_hal_sai.h"
#endif /* HAL_SAI_MODULE_ENABLED */
#ifdef HAL_SD_MODULE_ENABLED
#include "stm32h5xx_hal_sd.h"
#endif /* HAL_SD_MODULE_ENABLED */
#ifdef HAL_SMBUS_MODULE_ENABLED
#include "stm32h5xx_hal_smbus.h"
#endif /* HAL_SMBUS_MODULE_ENABLED */
#ifdef HAL_SPI_MODULE_ENABLED
#include "stm32h5xx_hal_spi.h"
#endif /* HAL_SPI_MODULE_ENABLED */
#ifdef HAL_TIM_MODULE_ENABLED
#include "stm32h5xx_hal_tim.h"
#endif /* HAL_TIM_MODULE_ENABLED */
#ifdef HAL_UART_MODULE_ENABLED
#include "stm32h5xx_hal_uart.h"
#endif /* HAL_UART_MODULE_ENABLED */
#ifdef HAL_USART_MODULE_ENABLED
#include "stm32h5xx_hal_usart.h"
#endif /* HAL_USART_MODULE_ENABLED */
#ifdef HAL_IRDA_MODULE_ENABLED
#include "stm32h5xx_hal_irda.h"
#endif /* HAL_IRDA_MODULE_ENABLED */
#ifdef HAL_SMARTCARD_MODULE_ENABLED
#include "stm32h5xx_hal_smartcard.h"
#endif /* HAL_SMARTCARD_MODULE_ENABLED */
#ifdef HAL_WWDG_MODULE_ENABLED
#include "stm32h5xx_hal_wwdg.h"
#endif /* HAL_WWDG_MODULE_ENABLED */
#ifdef HAL_PCD_MODULE_ENABLED
#include "stm32h5xx_hal_pcd.h"
#endif /* HAL_PCD_MODULE_ENABLED */
#ifdef HAL_CCB_MODULE_ENABLED
#include "stm32h5xx_hal_ccb.h"
#endif /* HAL_CCB_MODULE_ENABLED */
#ifdef HAL_HCD_MODULE_ENABLED
#include "stm32h5xx_hal_hcd.h"
#endif /* HAL_HCD_MODULE_ENABLED */
#ifdef HAL_COMP_MODULE_ENABLED
#include "stm32h5xx_hal_comp.h"
#endif /* HAL_COMP_MODULE_ENABLED */
#ifdef HAL_CORDIC_MODULE_ENABLED
#include "stm32h5xx_hal_cordic.h"
#endif /* HAL_CORDIC_MODULE_ENABLED */
#ifdef HAL_DCMI_MODULE_ENABLED
#include "stm32h5xx_hal_dcmi.h"
#endif /* HAL_DCMI_MODULE_ENABLED */
#ifdef HAL_EXTI_MODULE_ENABLED
#include "stm32h5xx_hal_exti.h"
#endif /* HAL_EXTI_MODULE_ENABLED */
#ifdef HAL_ETH_MODULE_ENABLED
#include "stm32h5xx_hal_eth.h"
#endif /* HAL_ETH_MODULE_ENABLED */
#ifdef HAL_FDCAN_MODULE_ENABLED
#include "stm32h5xx_hal_fdcan.h"
#endif /* HAL_FDCAN_MODULE_ENABLED */
#ifdef HAL_CEC_MODULE_ENABLED
#include "stm32h5xx_hal_cec.h"
#endif /* HAL_CEC_MODULE_ENABLED */
#ifdef HAL_FMAC_MODULE_ENABLED
#include "stm32h5xx_hal_fmac.h"
#endif /* HAL_FMAC_MODULE_ENABLED */
#ifdef HAL_OPAMP_MODULE_ENABLED
#include "stm32h5xx_hal_opamp.h"
#endif /* HAL_OPAMP_MODULE_ENABLED */
#ifdef HAL_OTFDEC_MODULE_ENABLED
#include "stm32h5xx_hal_otfdec.h"
#endif /* HAL_OTFDEC_MODULE_ENABLED */
#ifdef HAL_PSSI_MODULE_ENABLED
#include "stm32h5xx_hal_pssi.h"
#endif /* HAL_PSSI_MODULE_ENABLED */
#ifdef HAL_RAMCFG_MODULE_ENABLED
#include "stm32h5xx_hal_ramcfg.h"
#endif /* HAL_RAMCFG_MODULE_ENABLED */
/* Exported macro ----------------------------------------------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/**
* @brief The assert_param macro is used for function's parameters check.
* @param expr: If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* @retval None
*/
#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ----------------------------------------------------------------------------------------------- */
void assert_failed(uint8_t *file, uint32_t line);
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
#ifdef __cplusplus
}
#endif
#endif /* STM32H5xx_HAL_CONF_H */
@@ -0,0 +1,66 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32h5xx_it.h
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32H5xx_IT_H
#define __STM32H5xx_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void SVC_Handler(void);
void DebugMon_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
#ifdef __cplusplus
}
#endif
#endif /* __STM32H5xx_IT_H */
@@ -0,0 +1,475 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "string.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "mongoose.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
ETH_TxPacketConfigTypeDef TxConfig;
ETH_DMADescTypeDef DMARxDscrTab[ETH_RX_DESC_CNT]; /* Ethernet Rx DMA Descriptors */
ETH_DMADescTypeDef DMATxDscrTab[ETH_TX_DESC_CNT]; /* Ethernet Tx DMA Descriptors */
ETH_HandleTypeDef heth;
RNG_HandleTypeDef hrng;
UART_HandleTypeDef huart3;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MPU_Config(void);
static void MX_GPIO_Init(void);
static void MX_ETH_Init(void);
static void MX_ICACHE_Init(void);
static void MX_RNG_Init(void);
static void MX_USART3_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static void log_fn(char ch, void *param) {
HAL_UART_Transmit(param, (unsigned char *) &ch, 1, HAL_MAX_DELAY);
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* MPU Configuration--------------------------------------------------------*/
MPU_Config();
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ETH_Init();
MX_ICACHE_Init();
MX_RNG_Init();
MX_USART3_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_log_set_fn(log_fn, &huart3);
mg_mgr_init(&mgr);
mg_dash_init(&mgr);
mg_log_set_fn(log_fn, &huart3);
while (1)
{
mg_mgr_poll(&mgr, 0);
mg_dash_poll(&mgr);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);
while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48|RCC_OSCILLATORTYPE_CSI;
RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
RCC_OscInitStruct.CSIState = RCC_CSI_ON;
RCC_OscInitStruct.CSICalibrationValue = RCC_CSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLL1_SOURCE_CSI;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 125;
RCC_OscInitStruct.PLL.PLLP = 2;
RCC_OscInitStruct.PLL.PLLQ = 2;
RCC_OscInitStruct.PLL.PLLR = 2;
RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1_VCIRANGE_2;
RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1_VCORANGE_WIDE;
RCC_OscInitStruct.PLL.PLLFRACN = 0;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
|RCC_CLOCKTYPE_PCLK3;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
/** Configure the programming delay
*/
__HAL_FLASH_SET_PROGRAM_DELAY(FLASH_PROGRAMMING_DELAY_2);
}
/**
* @brief ETH Initialization Function
* @param None
* @retval None
*/
static void MX_ETH_Init(void)
{
/* USER CODE BEGIN ETH_Init 0 */
/* USER CODE END ETH_Init 0 */
static uint8_t MACAddr[6];
/* USER CODE BEGIN ETH_Init 1 */
/* USER CODE END ETH_Init 1 */
heth.Instance = ETH;
MACAddr[0] = 0x00;
MACAddr[1] = 0x80;
MACAddr[2] = 0xE1;
MACAddr[3] = 0x00;
MACAddr[4] = 0x00;
MACAddr[5] = 0x00;
heth.Init.MACAddr = &MACAddr[0];
heth.Init.MediaInterface = HAL_ETH_RMII_MODE;
heth.Init.TxDesc = DMATxDscrTab;
heth.Init.RxDesc = DMARxDscrTab;
heth.Init.RxBuffLen = 1524;
/* USER CODE BEGIN MACADDRESS */
/* USER CODE END MACADDRESS */
if (HAL_ETH_Init(&heth) != HAL_OK)
{
Error_Handler();
}
memset(&TxConfig, 0 , sizeof(ETH_TxPacketConfigTypeDef));
TxConfig.Attributes = ETH_TX_PACKETS_FEATURES_CSUM | ETH_TX_PACKETS_FEATURES_CRCPAD;
TxConfig.ChecksumCtrl = ETH_CHECKSUM_IPHDR_PAYLOAD_INSERT_PHDR_CALC;
TxConfig.CRCPadCtrl = ETH_CRC_PAD_INSERT;
/* USER CODE BEGIN ETH_Init 2 */
/* USER CODE END ETH_Init 2 */
}
/**
* @brief ICACHE Initialization Function
* @param None
* @retval None
*/
static void MX_ICACHE_Init(void)
{
/* USER CODE BEGIN ICACHE_Init 0 */
/* USER CODE END ICACHE_Init 0 */
/* USER CODE BEGIN ICACHE_Init 1 */
/* USER CODE END ICACHE_Init 1 */
/** Enable instruction cache in 1-way (direct mapped cache)
*/
if (HAL_ICACHE_ConfigAssociativityMode(ICACHE_1WAY) != HAL_OK)
{
Error_Handler();
}
if (HAL_ICACHE_Enable() != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ICACHE_Init 2 */
/* USER CODE END ICACHE_Init 2 */
}
/**
* @brief RNG Initialization Function
* @param None
* @retval None
*/
static void MX_RNG_Init(void)
{
/* USER CODE BEGIN RNG_Init 0 */
/* USER CODE END RNG_Init 0 */
/* USER CODE BEGIN RNG_Init 1 */
/* USER CODE END RNG_Init 1 */
hrng.Instance = RNG;
hrng.Init.ClockErrorDetection = RNG_CED_ENABLE;
if (HAL_RNG_Init(&hrng) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN RNG_Init 2 */
/* USER CODE END RNG_Init 2 */
}
/**
* @brief USART3 Initialization Function
* @param None
* @retval None
*/
static void MX_USART3_UART_Init(void)
{
/* USER CODE BEGIN USART3_Init 0 */
/* USER CODE END USART3_Init 0 */
/* USER CODE BEGIN USART3_Init 1 */
/* USER CODE END USART3_Init 1 */
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
huart3.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart3.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart3.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart3, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart3, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART3_Init 2 */
/* USER CODE END USART3_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOF, GPIO_PIN_4, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_4, GPIO_PIN_RESET);
/*Configure GPIO pin : PF4 */
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
/*Configure GPIO pin : PB0 */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : PG4 */
GPIO_InitStruct.Pin = GPIO_PIN_4;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/* MPU Configuration */
void MPU_Config(void)
{
MPU_Region_InitTypeDef MPU_InitStruct = {0};
MPU_Attributes_InitTypeDef MPU_AttributesInit = {0};
/* Disables the MPU */
HAL_MPU_Disable();
/** Initializes and configures the Region 0 and the memory to be protected
*/
MPU_InitStruct.Enable = MPU_REGION_ENABLE;
MPU_InitStruct.Number = MPU_REGION_NUMBER0;
MPU_InitStruct.BaseAddress = 0x08FFF000;
MPU_InitStruct.LimitAddress = 0x08FFFFFF;
MPU_InitStruct.AttributesIndex = MPU_ATTRIBUTES_NUMBER0;
MPU_InitStruct.AccessPermission = MPU_REGION_ALL_RO;
MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
/** Initializes and configures the Attribute 0 and the memory to be protected
*/
MPU_AttributesInit.Number = MPU_ATTRIBUTES_NUMBER0;
MPU_AttributesInit.Attributes = INNER_OUTER(MPU_NOT_CACHEABLE);
HAL_MPU_ConfigMemoryAttributes(&MPU_AttributesInit);
/* Enables the MPU */
HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
}
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
@@ -0,0 +1,325 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32h5xx_hal_msp.c
* @brief This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
/* System interrupt init*/
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/**
* @brief ETH MSP Initialization
* This function configures the hardware resources used in this example
* @param heth: ETH handle pointer
* @retval None
*/
void HAL_ETH_MspInit(ETH_HandleTypeDef* heth)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(heth->Instance==ETH)
{
/* USER CODE BEGIN ETH_MspInit 0 */
/* USER CODE END ETH_MspInit 0 */
/* Peripheral clock enable */
__HAL_RCC_ETH_CLK_ENABLE();
__HAL_RCC_ETHTX_CLK_ENABLE();
__HAL_RCC_ETHRX_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOG_CLK_ENABLE();
/**ETH GPIO Configuration
PC1 ------> ETH_MDC
PA1 ------> ETH_REF_CLK
PA2 ------> ETH_MDIO
PA7 ------> ETH_CRS_DV
PC4 ------> ETH_RXD0
PC5 ------> ETH_RXD1
PB15 ------> ETH_TXD1
PG11 ------> ETH_TX_EN
PG13 ------> ETH_TXD0
*/
GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF11_ETH;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
/* USER CODE BEGIN ETH_MspInit 1 */
/* USER CODE END ETH_MspInit 1 */
}
}
/**
* @brief ETH MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param heth: ETH handle pointer
* @retval None
*/
void HAL_ETH_MspDeInit(ETH_HandleTypeDef* heth)
{
if(heth->Instance==ETH)
{
/* USER CODE BEGIN ETH_MspDeInit 0 */
/* USER CODE END ETH_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ETH_CLK_DISABLE();
__HAL_RCC_ETHTX_CLK_DISABLE();
__HAL_RCC_ETHRX_CLK_DISABLE();
/**ETH GPIO Configuration
PC1 ------> ETH_MDC
PA1 ------> ETH_REF_CLK
PA2 ------> ETH_MDIO
PA7 ------> ETH_CRS_DV
PC4 ------> ETH_RXD0
PC5 ------> ETH_RXD1
PB15 ------> ETH_TXD1
PG11 ------> ETH_TX_EN
PG13 ------> ETH_TXD0
*/
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1|GPIO_PIN_4|GPIO_PIN_5);
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_7);
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_15);
HAL_GPIO_DeInit(GPIOG, GPIO_PIN_11|GPIO_PIN_13);
/* USER CODE BEGIN ETH_MspDeInit 1 */
/* USER CODE END ETH_MspDeInit 1 */
}
}
/**
* @brief RNG MSP Initialization
* This function configures the hardware resources used in this example
* @param hrng: RNG handle pointer
* @retval None
*/
void HAL_RNG_MspInit(RNG_HandleTypeDef* hrng)
{
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
if(hrng->Instance==RNG)
{
/* USER CODE BEGIN RNG_MspInit 0 */
/* USER CODE END RNG_MspInit 0 */
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RNG;
PeriphClkInitStruct.RngClockSelection = RCC_RNGCLKSOURCE_HSI48;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
/* Peripheral clock enable */
__HAL_RCC_RNG_CLK_ENABLE();
/* USER CODE BEGIN RNG_MspInit 1 */
/* USER CODE END RNG_MspInit 1 */
}
}
/**
* @brief RNG MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param hrng: RNG handle pointer
* @retval None
*/
void HAL_RNG_MspDeInit(RNG_HandleTypeDef* hrng)
{
if(hrng->Instance==RNG)
{
/* USER CODE BEGIN RNG_MspDeInit 0 */
/* USER CODE END RNG_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_RNG_CLK_DISABLE();
/* USER CODE BEGIN RNG_MspDeInit 1 */
/* USER CODE END RNG_MspDeInit 1 */
}
}
/**
* @brief UART MSP Initialization
* This function configures the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
if(huart->Instance==USART3)
{
/* USER CODE BEGIN USART3_MspInit 0 */
/* USER CODE END USART3_MspInit 0 */
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USART3;
PeriphClkInitStruct.Usart3ClockSelection = RCC_USART3CLKSOURCE_PCLK1;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
/* Peripheral clock enable */
__HAL_RCC_USART3_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/**USART3 GPIO Configuration
PD8 ------> USART3_TX
PD9 ------> USART3_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
/* USER CODE BEGIN USART3_MspInit 1 */
/* USER CODE END USART3_MspInit 1 */
}
}
/**
* @brief UART MSP De-Initialization
* This function freeze the hardware resources used in this example
* @param huart: UART handle pointer
* @retval None
*/
void HAL_UART_MspDeInit(UART_HandleTypeDef* huart)
{
if(huart->Instance==USART3)
{
/* USER CODE BEGIN USART3_MspDeInit 0 */
/* USER CODE END USART3_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART3_CLK_DISABLE();
/**USART3 GPIO Configuration
PD8 ------> USART3_TX
PD9 ------> USART3_RX
*/
HAL_GPIO_DeInit(GPIOD, GPIO_PIN_8|GPIO_PIN_9);
/* USER CODE BEGIN USART3_MspDeInit 1 */
/* USER CODE END USART3_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
@@ -0,0 +1,203 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32h5xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32h5xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
/**
* @brief This function handles Pre-fetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_BusFault_IRQn 0 */
/* USER CODE END W1_BusFault_IRQn 0 */
}
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */
/* USER CODE END W1_UsageFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32H5xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32h5xx.s). */
/******************************************************************************/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
@@ -0,0 +1,244 @@
/**
******************************************************************************
* @file syscalls.c
* @author Auto-generated by STM32CubeMX
* @brief Minimal System calls file
*
* For more information about which c-functions
* need which of these lowlevel functions
* please consult the Newlib or Picolibc libc-manual
******************************************************************************
* @attention
*
* Copyright (c) 2020-2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes */
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
/* Variables */
extern int __io_putchar(int ch) __attribute__((weak));
extern int __io_getchar(void) __attribute__((weak));
char *__env[1] = { 0 };
char **environ = __env;
/* Functions */
void initialise_monitor_handles()
{
}
int _getpid(void)
{
return 1;
}
int _kill(int pid, int sig)
{
(void)pid;
(void)sig;
errno = EINVAL;
return -1;
}
void _exit (int status)
{
_kill(status, -1);
while (1) {} /* Make sure we hang here */
}
__attribute__((weak)) int _read(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
*ptr++ = __io_getchar();
}
return len;
}
__attribute__((weak)) int _write(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
__io_putchar(*ptr++);
}
return len;
}
__attribute__((weak)) int _close(int file)
{
(void)file;
return -1;
}
__attribute__((weak)) int _fstat(int file, struct stat *st)
{
(void)file;
st->st_mode = S_IFCHR;
return 0;
}
__attribute__((weak)) int _isatty(int file)
{
(void)file;
return 1;
}
__attribute__((weak)) int _lseek(int file, int ptr, int dir)
{
(void)file;
(void)ptr;
(void)dir;
return 0;
}
__attribute__((weak)) int _open(char *path, int flags, ...)
{
(void)path;
(void)flags;
/* Pretend like we always fail */
return -1;
}
__attribute__((weak)) int _wait(int *status)
{
(void)status;
errno = ECHILD;
return -1;
}
__attribute__((weak)) int _unlink(char *name)
{
(void)name;
errno = ENOENT;
return -1;
}
clock_t _times(struct tms *buf)
{
(void)buf;
return -1;
}
__attribute__((weak)) int _stat(const char *file, struct stat *st)
{
(void)file;
st->st_mode = S_IFCHR;
return 0;
}
__attribute__((weak)) int _link(char *old, char *new)
{
(void)old;
(void)new;
errno = EMLINK;
return -1;
}
__attribute__((weak)) int _fork(void)
{
errno = EAGAIN;
return -1;
}
__attribute__((weak)) int _execve(char *name, char **argv, char **env)
{
(void)name;
(void)argv;
(void)env;
errno = ENOMEM;
return -1;
}
// --- Picolibc Specific Section ---
#if defined(__PICOLIBC__)
/**
* @brief Picolibc helper function to output a character to a FILE stream.
* This redirects the output to the low-level __io_putchar function.
* @param c Character to write.
* @param file FILE stream pointer (ignored).
* @retval int The character written.
*/
static int starm_putc(char c, FILE *file)
{
(void) file;
__io_putchar(c);
return c;
}
/**
* @brief Picolibc helper function to input a character from a FILE stream.
* This redirects the input from the low-level __io_getchar function.
* @param file FILE stream pointer (ignored).
* @retval int The character read, cast to an unsigned char then int.
*/
static int starm_getc(FILE *file)
{
unsigned char c;
(void) file;
c = __io_getchar();
return c;
}
// Define and initialize the standard I/O streams for Picolibc.
// FDEV_SETUP_STREAM connects the starm_putc and starm_getc helper functions to a FILE structure.
// _FDEV_SETUP_RW indicates the stream is for reading and writing.
static FILE __stdio = FDEV_SETUP_STREAM(starm_putc,
starm_getc,
NULL,
_FDEV_SETUP_RW);
// Assign the standard stream pointers (stdin, stdout, stderr) to the initialized stream.
// Picolibc uses these pointers for standard I/O operations (printf, scanf, etc.).
FILE *const stdin = &__stdio;
__strong_reference(stdin, stdout);
__strong_reference(stdin, stderr);
// Create strong aliases mapping standard C library function names (without underscore)
// to the implemented system call stubs (with underscore). Picolibc uses these
// standard names internally, so this linking is required.
__strong_reference(_read, read);
__strong_reference(_write, write);
__strong_reference(_times, times);
__strong_reference(_execve, execve);
__strong_reference(_fork, fork);
__strong_reference(_link, link);
__strong_reference(_unlink, unlink);
__strong_reference(_stat, stat);
__strong_reference(_wait, wait);
__strong_reference(_open, open);
__strong_reference(_close, close);
__strong_reference(_lseek, lseek);
__strong_reference(_isatty, isatty);
__strong_reference(_fstat, fstat);
__strong_reference(_exit, exit);
__strong_reference(_kill, kill);
__strong_reference(_getpid, getpid);
#endif //__PICOLIBC__
@@ -0,0 +1,87 @@
/**
******************************************************************************
* @file sysmem.c
* @author Generated by STM32CubeMX
* @brief System Memory calls file
*
* For more information about which C functions
* need which of these lowlevel functions
* please consult the Newlib or Picolibc libc manual
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes */
#include <errno.h>
#include <stdint.h>
#include <stddef.h>
/**
* Pointer to the current high watermark of the heap usage
*/
static uint8_t *__sbrk_heap_end = NULL;
/**
* @brief _sbrk() allocates memory to the newlib heap and is used by malloc
* and others from the C library
*
* @verbatim
* ############################################################################
* # .data # .bss # newlib heap # MSP stack #
* # # # # Reserved by _Min_Stack_Size #
* ############################################################################
* ^-- RAM start ^-- _end _estack, RAM end --^
* @endverbatim
*
* This implementation starts allocating at the '_end' linker symbol
* The '_Min_Stack_Size' linker symbol reserves a memory for the MSP stack
* The implementation considers '_estack' linker symbol to be RAM end
* NOTE: If the MSP stack, at any point during execution, grows larger than the
* reserved size, please increase the '_Min_Stack_Size'.
*
* @param incr Memory size
* @return Pointer to allocated memory
*/
void *_sbrk(ptrdiff_t incr)
{
extern uint8_t _end; /* Symbol defined in the linker script */
extern uint8_t _estack; /* Symbol defined in the linker script */
extern uint32_t _Min_Stack_Size; /* Symbol defined in the linker script */
const uint32_t stack_limit = (uint32_t)&_estack - (uint32_t)&_Min_Stack_Size;
const uint8_t *max_heap = (uint8_t *)stack_limit;
uint8_t *prev_heap_end;
/* Initialize heap end at first call */
if (NULL == __sbrk_heap_end)
{
__sbrk_heap_end = &_end;
}
/* Protect heap from growing into the reserved MSP stack */
if (__sbrk_heap_end + incr > max_heap)
{
errno = ENOMEM;
return (void *)-1;
}
prev_heap_end = __sbrk_heap_end;
__sbrk_heap_end += incr;
return (void *)prev_heap_end;
}
#if defined(__PICOLIBC__)
// Picolibc expects syscalls without the leading underscore.
// This creates a strong alias so that
// calls to `sbrk()` are resolved to our `_sbrk()` implementation.
__strong_reference(_sbrk, sbrk);
#endif
@@ -0,0 +1,403 @@
/**
******************************************************************************
* @file system_stm32h5xx.c
* @author MCD Application Team
* @brief CMSIS Cortex-M33 Device Peripheral Access Layer System Source File
*
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
* This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32h5xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
* After each device reset the HSI (64 MHz) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32h5xx.s" file, to
* configure the system clock before to branch to main program.
*
* This file configures the system clock as follows:
*=============================================================================
*-----------------------------------------------------------------------------
* System Clock source | HSI
*-----------------------------------------------------------------------------
* SYSCLK(Hz) | 64000000
*-----------------------------------------------------------------------------
* HCLK(Hz) | 64000000
*-----------------------------------------------------------------------------
* AHB Prescaler | 1
*-----------------------------------------------------------------------------
* APB1 Prescaler | 1
*-----------------------------------------------------------------------------
* APB2 Prescaler | 1
*-----------------------------------------------------------------------------
* APB3 Prescaler | 1
*-----------------------------------------------------------------------------
* HSI Division factor | 1
*-----------------------------------------------------------------------------
* PLL1_SRC | No clock
*-----------------------------------------------------------------------------
* PLL1_M | Prescaler disabled
*-----------------------------------------------------------------------------
* PLL1_N | 129
*-----------------------------------------------------------------------------
* PLL1_P | 2
*-----------------------------------------------------------------------------
* PLL1_Q | 2
*-----------------------------------------------------------------------------
* PLL1_R | 2
*-----------------------------------------------------------------------------
* PLL1_FRACN | 0
*-----------------------------------------------------------------------------
* PLL2_SRC | No clock
*-----------------------------------------------------------------------------
* PLL2_M | Prescaler disabled
*-----------------------------------------------------------------------------
* PLL2_N | 129
*-----------------------------------------------------------------------------
* PLL2_P | 2
*-----------------------------------------------------------------------------
* PLL2_Q | 2
*-----------------------------------------------------------------------------
* PLL2_R | 2
*-----------------------------------------------------------------------------
* PLL2_FRACN | 0
*-----------------------------------------------------------------------------
* PLL3_SRC | No clock
*-----------------------------------------------------------------------------
* PLL3_M | Prescaler disabled
*-----------------------------------------------------------------------------
* PLL3_N | 129
*-----------------------------------------------------------------------------
* PLL3_P | 2
*-----------------------------------------------------------------------------
* PLL3_Q | 2
*-----------------------------------------------------------------------------
* PLL3_R | 2
*-----------------------------------------------------------------------------
* PLL3_FRACN | 0
*-----------------------------------------------------------------------------
*=============================================================================
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup STM32H5xx_system
* @{
*/
/** @addtogroup STM32H5xx_System_Private_Includes
* @{
*/
#include "stm32h5xx.h"
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Private_Defines
* @{
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE (25000000UL) /*!< Value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (CSI_VALUE)
#define CSI_VALUE (4000000UL) /*!< Value of the Internal oscillator in Hz*/
#endif /* CSI_VALUE */
#if !defined (HSI_VALUE)
#define HSI_VALUE (64000000UL) /*!< Value of the Internal oscillator in Hz */
#endif /* HSI_VALUE */
/************************* Miscellaneous Configuration ************************/
/*!< Uncomment the following line if you need to relocate your vector Table in
Internal SRAM. */
/* #define VECT_TAB_SRAM */
#if !defined(VECT_TAB_OFFSET)
#define VECT_TAB_OFFSET 0x00U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#endif /* VECT_TAB_OFFSET */
/******************************************************************************/
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Private_Variables
* @{
*/
/* The SystemCoreClock variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 64000000U;
const uint8_t AHBPrescTable[16] = {0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 1U, 2U, 3U, 4U, 6U, 7U, 8U, 9U};
const uint8_t APBPrescTable[8] = {0U, 0U, 0U, 0U, 1U, 2U, 3U, 4U};
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system.
* @param None
* @retval None
*/
void SystemInit(void)
{
uint32_t reg_opsr;
/* FPU settings ------------------------------------------------------------*/
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
SCB->CPACR |= ((3UL << 20U)|(3UL << 22U)); /* set CP10 and CP11 Full Access */
#endif
/* Reset the RCC clock configuration to the default reset state ------------*/
/* Set HSION bit while preserving the current HSIDIV value*/
RCC->CR = (RCC->CR & RCC_CR_HSIDIV_Msk) | RCC_CR_HSION;
/* Reset CFGR register */
RCC->CFGR1 = 0U;
RCC->CFGR2 = 0U;
/* Reset HSEON, HSECSSON, HSEBYP, HSEEXT, HSIDIV, HSIKERON, CSION, CSIKERON, HSI48 and PLLxON bits */
#if defined(RCC_CR_PLL3ON)
RCC->CR &= ~(RCC_CR_HSEON | RCC_CR_HSECSSON | RCC_CR_HSEBYP | RCC_CR_HSEEXT | RCC_CR_HSIKERON | \
RCC_CR_CSION | RCC_CR_CSIKERON |RCC_CR_HSI48ON | RCC_CR_PLL1ON | RCC_CR_PLL2ON | RCC_CR_PLL3ON);
#else
RCC->CR &= ~(RCC_CR_HSEON | RCC_CR_HSECSSON | RCC_CR_HSEBYP | RCC_CR_HSEEXT | RCC_CR_HSIKERON | \
RCC_CR_CSION | RCC_CR_CSIKERON |RCC_CR_HSI48ON | RCC_CR_PLL1ON | RCC_CR_PLL2ON);
#endif
/* Reset PLLxCFGR register */
RCC->PLL1CFGR = 0U;
RCC->PLL2CFGR = 0U;
#if defined(RCC_CR_PLL3ON)
RCC->PLL3CFGR = 0U;
#endif /* RCC_CR_PLL3ON */
/* Reset PLL1DIVR register */
RCC->PLL1DIVR = 0x01010280U;
/* Reset PLL1FRACR register */
RCC->PLL1FRACR = 0x00000000U;
/* Reset PLL2DIVR register */
RCC->PLL2DIVR = 0x01010280U;
/* Reset PLL2FRACR register */
RCC->PLL2FRACR = 0x00000000U;
#if defined(RCC_CR_PLL3ON)
/* Reset PLL3DIVR register */
RCC->PLL3DIVR = 0x01010280U;
/* Reset PLL3FRACR register */
RCC->PLL3FRACR = 0x00000000U;
#endif /* RCC_CR_PLL3ON */
/* Reset HSEBYP bit */
RCC->CR &= ~(RCC_CR_HSEBYP);
/* Disable all interrupts */
RCC->CIER = 0U;
/* Configure the Vector Table location add offset address ------------------*/
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */
#else
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */
#endif /* VECT_TAB_SRAM */
/* Check OPSR register to verify if there is an ongoing swap or option bytes update interrupted by a reset */
reg_opsr = FLASH->OPSR & FLASH_OPSR_CODE_OP;
if ((reg_opsr == FLASH_OPSR_CODE_OP) || (reg_opsr == (FLASH_OPSR_CODE_OP_2 | FLASH_OPSR_CODE_OP_1)))
{
/* Check FLASH Option Control Register access */
if ((FLASH->OPTCR & FLASH_OPTCR_OPTLOCK) != 0U)
{
/* Authorizes the Option Byte registers programming */
FLASH->OPTKEYR = 0x08192A3BU;
FLASH->OPTKEYR = 0x4C5D6E7FU;
}
/* Launch the option bytes change operation */
FLASH->OPTCR |= FLASH_OPTCR_OPTSTART;
/* Lock the FLASH Option Control Register access */
FLASH->OPTCR |= FLASH_OPTCR_OPTLOCK;
}
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is CSI, SystemCoreClock will contain the CSI_VALUE(*)
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(**)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(***)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(***)
* or HSI_VALUE(**) or CSI_VALUE(*) multiplied/divided by the PLL factors.
*
* (*) CSI_VALUE is a constant defined in stm32h5xx_hal.h file (default value
* 4 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSI_VALUE is a constant defined in stm32h5xx_hal.h file (default value
* 64 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (***) HSE_VALUE is a constant defined in stm32h5xx_hal.h file (default value
* 25 MHz), user has to ensure that HSE_VALUE is same as the real
* frequency of the crystal used. Otherwise, this function may
* have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
*
* @param None
* @retval None
*/
void SystemCoreClockUpdate(void)
{
uint32_t pllp, pllsource, pllm, pllfracen, hsivalue, tmp;
float_t fracn1, pllvco;
/* Get SYSCLK source -------------------------------------------------------*/
switch (RCC->CFGR1 & RCC_CFGR1_SWS)
{
case 0x00UL: /* HSI used as system clock source */
SystemCoreClock = (uint32_t) (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV)>> 3));
break;
case 0x08UL: /* CSI used as system clock source */
SystemCoreClock = CSI_VALUE;
break;
case 0x10UL: /* HSE used as system clock source */
SystemCoreClock = HSE_VALUE;
break;
case 0x18UL: /* PLL1 used as system clock source */
/* PLL_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLLM) * PLLN
SYSCLK = PLL_VCO / PLLR
*/
pllsource = (RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1SRC);
pllm = ((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1M)>> RCC_PLL1CFGR_PLL1M_Pos);
pllfracen = ((RCC->PLL1CFGR & RCC_PLL1CFGR_PLL1FRACEN)>>RCC_PLL1CFGR_PLL1FRACEN_Pos);
fracn1 = (float_t)(uint32_t)(pllfracen* ((RCC->PLL1FRACR & RCC_PLL1FRACR_PLL1FRACN)>> RCC_PLL1FRACR_PLL1FRACN_Pos));
switch (pllsource)
{
case 0x01UL: /* HSI used as PLL clock source */
hsivalue = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV)>> 3)) ;
pllvco = ((float_t)hsivalue / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1/(float_t)0x2000) +(float_t)1 );
break;
case 0x02UL: /* CSI used as PLL clock source */
pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1/(float_t)0x2000) +(float_t)1 );
break;
case 0x03UL: /* HSE used as PLL clock source */
pllvco = ((float_t)HSE_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1N) + \
(fracn1/(float_t)0x2000) +(float_t)1 );
break;
default: /* No clock sent to PLL*/
pllvco = (float_t) 0U;
break;
}
pllp = (((RCC->PLL1DIVR & RCC_PLL1DIVR_PLL1P) >>RCC_PLL1DIVR_PLL1P_Pos) + 1U ) ;
SystemCoreClock = (uint32_t)(float_t)(pllvco/(float_t)pllp);
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK clock frequency --------------------------------------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR2 & RCC_CFGR2_HPRE) >> RCC_CFGR2_HPRE_Pos)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
@@ -0,0 +1,261 @@
/**
******************************************************************************
* @file stm32h5xx.h
* @author MCD Application Team
* @brief CMSIS STM32H5xx Device Peripheral Access Layer Header File.
*
* The file is the unique include file that the application programmer
* is using in the C source code, usually in main.c. This file contains:
* - Configuration section that allows to select:
* - The STM32H5xx device used in the target application
* - To use or not the peripheral’s drivers in application code(i.e.
* code will be based on direct access to peripheral’s registers
* rather than drivers API), this option is controlled by
* "#define USE_HAL_DRIVER"
*
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32h5xx
* @{
*/
#ifndef STM32H5xx_H
#define STM32H5xx_H
#include "math.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @addtogroup Library_configuration_section
* @{
*/
/**
* @brief STM32 Family
*/
#if !defined (STM32H5)
#define STM32H5
#endif /* STM32H5 */
/* Uncomment the line below according to the target STM32H5 device used in your
application
*/
#if !defined (STM32H5F5xx) && !defined (STM32H5F4xx) \
&& !defined (STM32H5F4xx) && !defined (STM32H5E4xx) \
&& !defined (STM32H573xx) && !defined (STM32H563xx) \
&& !defined (STM32H562xx) && !defined (STM32H503xx) \
&& !defined (STM32H533xx) && !defined (STM32H523xx)
/* #define STM32H543xx */ /*!< STM32H543xx Devices */
/* #define STM32H553xx */ /*!< STM32H553xx Devices */
/* #define STM32H5F5xx */ /*!< STM32H5F5xx Devices */
/* #define STM32H5F4xx */ /*!< STM32H5F4xx Devices */
/* #define STM32H5E5xx */ /*!< STM32H5E5xx Devices */
/* #define STM32H5E4xx */ /*!< STM32H5E4xx Devices */
/* #define STM32H573xx */ /*!< STM32H573xx Devices */
/* #define STM32H563xx */ /*!< STM32H563xx Devices */
/* #define STM32H562xx */ /*!< STM32H562xx Devices */
/* #define STM32H503xx */ /*!< STM32H503xx Devices */
/* #define STM32H533xx */ /*!< STM32H533xx Devices */
/* #define STM32H523xx */ /*!< STM32H523xx Devices */
#endif
/* Tip: To avoid modifying this file each time you need to switch between these
devices, you can define the device in your toolchain compiler preprocessor.
*/
#if !defined (USE_HAL_DRIVER)
/**
* @brief Comment the line below if you will not use the peripherals drivers.
In this case, these drivers will not be included and the application code will
be based on direct access to peripherals registers
*/
/*#define USE_HAL_DRIVER */
#endif /* USE_HAL_DRIVER */
/**
* @brief CMSIS Device version number 1.4.0
*/
#define __STM32H5_CMSIS_VERSION_MAIN (0x01U) /*!< [31:24] main version */
#define __STM32H5_CMSIS_VERSION_SUB1 (0x06U) /*!< [23:16] sub1 version */
#define __STM32H5_CMSIS_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */
#define __STM32H5_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */
#define __STM32H5_CMSIS_VERSION ((__STM32H5_CMSIS_VERSION_MAIN << 24U)\
|(__STM32H5_CMSIS_VERSION_SUB1 << 16U)\
|(__STM32H5_CMSIS_VERSION_SUB2 << 8U )\
|(__STM32H5_CMSIS_VERSION_RC))
/**
* @}
*/
/** @addtogroup Device_Included
* @{
*/
#if defined(STM32H5F5xx)
#include "stm32h5f5xx.h"
#elif defined(STM32H5F4xx)
#include "stm32h5f4xx.h"
#elif defined(STM32H5E5xx)
#include "stm32h5e5xx.h"
#elif defined(STM32H5E4xx)
#include "stm32h5e4xx.h"
#elif defined(STM32H573xx)
#include "stm32h573xx.h"
#elif defined(STM32H563xx)
#include "stm32h563xx.h"
#elif defined(STM32H562xx)
#include "stm32h562xx.h"
#elif defined(STM32H503xx)
#include "stm32h503xx.h"
#elif defined(STM32H523xx)
#include "stm32h523xx.h"
#elif defined(STM32H533xx)
#include "stm32h533xx.h"
#else
#error "Please select first the target STM32H5xx device used in your application (in stm32h5xx.h file)"
#endif
/**
* @}
*/
/** @addtogroup Exported_types
* @{
*/
typedef enum
{
RESET = 0,
SET = !RESET
} FlagStatus, ITStatus;
typedef enum
{
DISABLE = 0,
ENABLE = !DISABLE
} FunctionalState;
#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE))
typedef enum
{
SUCCESS = 0,
ERROR = !SUCCESS
} ErrorStatus;
/**
* @}
*/
/** @addtogroup Exported_macros
* @{
*/
#define SET_BIT(REG, BIT) ((REG) |= (BIT))
#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT))
#define READ_BIT(REG, BIT) ((REG) & (BIT))
#define CLEAR_REG(REG) ((REG) = (0x0))
#define WRITE_REG(REG, VAL) ((REG) = (VAL))
#define READ_REG(REG) ((REG))
#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK)))
/* Use of CMSIS compiler intrinsics for register exclusive access */
/* Atomic 32-bit register access macro to set one or several bits */
#define ATOMIC_SET_BIT(REG, BIT) \
do { \
uint32_t val; \
do { \
val = __LDREXW((__IO uint32_t *)&(REG)) | (BIT); \
} while ((__STREXW(val,(__IO uint32_t *)&(REG))) != 0U); \
} while(0)
/* Atomic 32-bit register access macro to clear one or several bits */
#define ATOMIC_CLEAR_BIT(REG, BIT) \
do { \
uint32_t val; \
do { \
val = __LDREXW((__IO uint32_t *)&(REG)) & ~(BIT); \
} while ((__STREXW(val,(__IO uint32_t *)&(REG))) != 0U); \
} while(0)
/* Atomic 32-bit register access macro to clear and set one or several bits */
#define ATOMIC_MODIFY_REG(REG, CLEARMSK, SETMASK) \
do { \
uint32_t val; \
do { \
val = (__LDREXW((__IO uint32_t *)&(REG)) & ~(CLEARMSK)) | (SETMASK); \
} while ((__STREXW(val,(__IO uint32_t *)&(REG))) != 0U); \
} while(0)
/* Atomic 16-bit register access macro to set one or several bits */
#define ATOMIC_SETH_BIT(REG, BIT) \
do { \
uint16_t val; \
do { \
val = __LDREXH((__IO uint16_t *)&(REG)) | (BIT); \
} while ((__STREXH(val,(__IO uint16_t *)&(REG))) != 0U); \
} while(0)
/* Atomic 16-bit register access macro to clear one or several bits */
#define ATOMIC_CLEARH_BIT(REG, BIT) \
do { \
uint16_t val; \
do { \
val = __LDREXH((__IO uint16_t *)&(REG)) & ~(BIT); \
} while ((__STREXH(val,(__IO uint16_t *)&(REG))) != 0U); \
} while(0)
/* Atomic 16-bit register access macro to clear and set one or several bits */
#define ATOMIC_MODIFYH_REG(REG, CLEARMSK, SETMASK) \
do { \
uint16_t val; \
do { \
val = (__LDREXH((__IO uint16_t *)&(REG)) & ~(CLEARMSK)) | (SETMASK); \
} while ((__STREXH(val,(__IO uint16_t *)&(REG))) != 0U); \
} while(0)
#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL)))
/**
* @}
*/
#if defined (USE_HAL_DRIVER)
#include "stm32h5xx_hal.h"
#endif /* USE_HAL_DRIVER */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* STM32H5xx_H */
/**
* @}
*/
/**
* @}
*/
@@ -0,0 +1,107 @@
/**
******************************************************************************
* @file system_stm32h5xx.h
* @author MCD Application Team
* @brief CMSIS Cortex-M33 Device System Source File for STM32H5xx devices.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32h5xx_system
* @{
*/
#ifndef SYSTEM_STM32H5XX_H
#define SYSTEM_STM32H5XX_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup STM32H5xx_System_Includes
* @{
*/
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Exported_Variables
* @{
*/
/* The SystemCoreClock variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetSysClockFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */
extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */
extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */
/**
* @}
*/
/** @addtogroup STM32H5xx_System_Exported_Functions
* @{
*/
/**
* @brief Setup the microcontroller system.
*
* Initialize the System and update the SystemCoreClock variable.
*/
extern void SystemInit (void);
/**
* @brief Update SystemCoreClock variable.
*
* Updates the SystemCoreClock with current core Clock retrieved from cpu registers.
*/
extern void SystemCoreClockUpdate (void);
/**
* @brief Update SystemCoreClock variable from secure application and return its value
* when security is implemented in the system (Non-secure callable function).
*
* Returns the SystemCoreClock value with current core Clock retrieved from cpu registers.
*/
extern uint32_t SECURE_SystemCoreClockUpdate(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* SYSTEM_STM32H5XX_H */
/**
* @}
*/
/**
* @}
*/
@@ -0,0 +1,6 @@
This software component is provided to you as part of a software package and
applicable license terms are in the Package_license file. If you received this
software component outside of a package or without applicable license terms,
the terms of the Apache-2.0 license shall apply.
You may obtain a copy of the Apache-2.0 at:
https://opensource.org/licenses/Apache-2.0
@@ -0,0 +1,441 @@
/******************************************************************************
* @file cachel1_armv7.h
* @brief CMSIS Level 1 Cache API for Armv7-M and later
* @version V1.0.3
* @date 17. March 2023
******************************************************************************/
/*
* Copyright (c) 2020-2021 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef ARM_CACHEL1_ARMV7_H
#define ARM_CACHEL1_ARMV7_H
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_CacheFunctions Cache Functions
\brief Functions that configure Instruction and Data cache.
@{
*/
/* Cache Size ID Register Macros */
#define CCSIDR_WAYS(x) (((x) & SCB_CCSIDR_ASSOCIATIVITY_Msk) >> SCB_CCSIDR_ASSOCIATIVITY_Pos)
#define CCSIDR_SETS(x) (((x) & SCB_CCSIDR_NUMSETS_Msk ) >> SCB_CCSIDR_NUMSETS_Pos )
#ifndef __SCB_DCACHE_LINE_SIZE
#define __SCB_DCACHE_LINE_SIZE 32U /*!< Cortex-M7 cache line size is fixed to 32 bytes (8 words). See also register SCB_CCSIDR */
#endif
#ifndef __SCB_ICACHE_LINE_SIZE
#define __SCB_ICACHE_LINE_SIZE 32U /*!< Cortex-M7 cache line size is fixed to 32 bytes (8 words). See also register SCB_CCSIDR */
#endif
/**
\brief Enable I-Cache
\details Turns on I-Cache
*/
__STATIC_FORCEINLINE void SCB_EnableICache (void)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
if (SCB->CCR & SCB_CCR_IC_Msk) return; /* return if ICache is already enabled */
__DSB();
__ISB();
SCB->ICIALLU = 0UL; /* invalidate I-Cache */
__DSB();
__ISB();
SCB->CCR |= (uint32_t)SCB_CCR_IC_Msk; /* enable I-Cache */
__DSB();
__ISB();
#endif
}
/**
\brief Disable I-Cache
\details Turns off I-Cache
*/
__STATIC_FORCEINLINE void SCB_DisableICache (void)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
__DSB();
__ISB();
SCB->CCR &= ~(uint32_t)SCB_CCR_IC_Msk; /* disable I-Cache */
SCB->ICIALLU = 0UL; /* invalidate I-Cache */
__DSB();
__ISB();
#endif
}
/**
\brief Invalidate I-Cache
\details Invalidates I-Cache
*/
__STATIC_FORCEINLINE void SCB_InvalidateICache (void)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
__DSB();
__ISB();
SCB->ICIALLU = 0UL;
__DSB();
__ISB();
#endif
}
/**
\brief I-Cache Invalidate by address
\details Invalidates I-Cache for the given address.
I-Cache is invalidated starting from a 32 byte aligned address in 32 byte granularity.
I-Cache memory blocks which are part of given address + given size are invalidated.
\param[in] addr address
\param[in] isize size of memory block (in number of bytes)
*/
__STATIC_FORCEINLINE void SCB_InvalidateICache_by_Addr (volatile void *addr, int32_t isize)
{
#if defined (__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U)
if ( isize > 0 ) {
int32_t op_size = isize + (((uint32_t)addr) & (__SCB_ICACHE_LINE_SIZE - 1U));
uint32_t op_addr = (uint32_t)addr /* & ~(__SCB_ICACHE_LINE_SIZE - 1U) */;
__DSB();
do {
SCB->ICIMVAU = op_addr; /* register accepts only 32byte aligned values, only bits 31..5 are valid */
op_addr += __SCB_ICACHE_LINE_SIZE;
op_size -= __SCB_ICACHE_LINE_SIZE;
} while ( op_size > 0 );
__DSB();
__ISB();
}
#endif
}
/**
\brief Enable D-Cache
\details Turns on D-Cache
*/
__STATIC_FORCEINLINE void SCB_EnableDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
if (SCB->CCR & SCB_CCR_DC_Msk) return; /* return if DCache is already enabled */
SCB->CSSELR = 0U; /* select Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCISW = (((sets << SCB_DCISW_SET_Pos) & SCB_DCISW_SET_Msk) |
((ways << SCB_DCISW_WAY_Pos) & SCB_DCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk; /* enable D-Cache */
__DSB();
__ISB();
#endif
}
/**
\brief Disable D-Cache
\details Turns off D-Cache
*/
__STATIC_FORCEINLINE void SCB_DisableDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
struct {
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
} locals
#if ((defined(__GNUC__) || defined(__clang__)) && !defined(__OPTIMIZE__))
__ALIGNED(__SCB_DCACHE_LINE_SIZE)
#endif
;
SCB->CSSELR = 0U; /* select Level 1 data cache */
__DSB();
SCB->CCR &= ~(uint32_t)SCB_CCR_DC_Msk; /* disable D-Cache */
__DSB();
#if !defined(__OPTIMIZE__)
/*
* For the endless loop issue with no optimization builds.
* More details, see https://github.com/ARM-software/CMSIS_5/issues/620
*
* The issue only happens when local variables are in stack. If
* local variables are saved in general purpose register, then the function
* is OK.
*
* When local variables are in stack, after disabling the cache, flush the
* local variables cache line for data consistency.
*/
/* Clean and invalidate the local variable cache. */
#if defined(__ICCARM__)
/* As we can't align the stack to the cache line size, invalidate each of the variables */
SCB->DCCIMVAC = (uint32_t)&locals.sets;
SCB->DCCIMVAC = (uint32_t)&locals.ways;
SCB->DCCIMVAC = (uint32_t)&locals.ccsidr;
#else
SCB->DCCIMVAC = (uint32_t)&locals;
#endif
__DSB();
__ISB();
#endif
locals.ccsidr = SCB->CCSIDR;
/* clean & invalidate D-Cache */
locals.sets = (uint32_t)(CCSIDR_SETS(locals.ccsidr));
do {
locals.ways = (uint32_t)(CCSIDR_WAYS(locals.ccsidr));
do {
SCB->DCCISW = (((locals.sets << SCB_DCCISW_SET_Pos) & SCB_DCCISW_SET_Msk) |
((locals.ways << SCB_DCCISW_WAY_Pos) & SCB_DCCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (locals.ways-- != 0U);
} while(locals.sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief Invalidate D-Cache
\details Invalidates D-Cache
*/
__STATIC_FORCEINLINE void SCB_InvalidateDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /* select Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCISW = (((sets << SCB_DCISW_SET_Pos) & SCB_DCISW_SET_Msk) |
((ways << SCB_DCISW_WAY_Pos) & SCB_DCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief Clean D-Cache
\details Cleans D-Cache
*/
__STATIC_FORCEINLINE void SCB_CleanDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /* select Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* clean D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCCSW = (((sets << SCB_DCCSW_SET_Pos) & SCB_DCCSW_SET_Msk) |
((ways << SCB_DCCSW_WAY_Pos) & SCB_DCCSW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief Clean & Invalidate D-Cache
\details Cleans and Invalidates D-Cache
*/
__STATIC_FORCEINLINE void SCB_CleanInvalidateDCache (void)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
SCB->CSSELR = 0U; /* select Level 1 data cache */
__DSB();
ccsidr = SCB->CCSIDR;
/* clean & invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCCISW = (((sets << SCB_DCCISW_SET_Pos) & SCB_DCCISW_SET_Msk) |
((ways << SCB_DCCISW_WAY_Pos) & SCB_DCCISW_WAY_Msk) );
#if defined ( __CC_ARM )
__schedule_barrier();
#endif
} while (ways-- != 0U);
} while(sets-- != 0U);
__DSB();
__ISB();
#endif
}
/**
\brief D-Cache Invalidate by address
\details Invalidates D-Cache for the given address.
D-Cache is invalidated starting from a 32 byte aligned address in 32 byte granularity.
D-Cache memory blocks which are part of given address + given size are invalidated.
\param[in] addr address
\param[in] dsize size of memory block (in number of bytes)
*/
__STATIC_FORCEINLINE void SCB_InvalidateDCache_by_Addr (volatile void *addr, int32_t dsize)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
if ( dsize > 0 ) {
int32_t op_size = dsize + (((uint32_t)addr) & (__SCB_DCACHE_LINE_SIZE - 1U));
uint32_t op_addr = (uint32_t)addr /* & ~(__SCB_DCACHE_LINE_SIZE - 1U) */;
__DSB();
do {
SCB->DCIMVAC = op_addr; /* register accepts only 32byte aligned values, only bits 31..5 are valid */
op_addr += __SCB_DCACHE_LINE_SIZE;
op_size -= __SCB_DCACHE_LINE_SIZE;
} while ( op_size > 0 );
__DSB();
__ISB();
}
#endif
}
/**
\brief D-Cache Clean by address
\details Cleans D-Cache for the given address
D-Cache is cleaned starting from a 32 byte aligned address in 32 byte granularity.
D-Cache memory blocks which are part of given address + given size are cleaned.
\param[in] addr address
\param[in] dsize size of memory block (in number of bytes)
*/
__STATIC_FORCEINLINE void SCB_CleanDCache_by_Addr (volatile void *addr, int32_t dsize)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
if ( dsize > 0 ) {
int32_t op_size = dsize + (((uint32_t)addr) & (__SCB_DCACHE_LINE_SIZE - 1U));
uint32_t op_addr = (uint32_t)addr /* & ~(__SCB_DCACHE_LINE_SIZE - 1U) */;
__DSB();
do {
SCB->DCCMVAC = op_addr; /* register accepts only 32byte aligned values, only bits 31..5 are valid */
op_addr += __SCB_DCACHE_LINE_SIZE;
op_size -= __SCB_DCACHE_LINE_SIZE;
} while ( op_size > 0 );
__DSB();
__ISB();
}
#endif
}
/**
\brief D-Cache Clean and Invalidate by address
\details Cleans and invalidates D_Cache for the given address
D-Cache is cleaned and invalidated starting from a 32 byte aligned address in 32 byte granularity.
D-Cache memory blocks which are part of given address + given size are cleaned and invalidated.
\param[in] addr address (aligned to 32-byte boundary)
\param[in] dsize size of memory block (in number of bytes)
*/
__STATIC_FORCEINLINE void SCB_CleanInvalidateDCache_by_Addr (volatile void *addr, int32_t dsize)
{
#if defined (__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U)
if ( dsize > 0 ) {
int32_t op_size = dsize + (((uint32_t)addr) & (__SCB_DCACHE_LINE_SIZE - 1U));
uint32_t op_addr = (uint32_t)addr /* & ~(__SCB_DCACHE_LINE_SIZE - 1U) */;
__DSB();
do {
SCB->DCCIMVAC = op_addr; /* register accepts only 32byte aligned values, only bits 31..5 are valid */
op_addr += __SCB_DCACHE_LINE_SIZE;
op_size -= __SCB_DCACHE_LINE_SIZE;
} while ( op_size > 0 );
__DSB();
__ISB();
}
#endif
}
/*@} end of CMSIS_Core_CacheFunctions */
#endif /* ARM_CACHEL1_ARMV7_H */
@@ -0,0 +1,888 @@
/**************************************************************************//**
* @file cmsis_armcc.h
* @brief CMSIS compiler ARMCC (Arm Compiler 5) header file
* @version V5.3.2
* @date 27. May 2021
******************************************************************************/
/*
* Copyright (c) 2009-2021 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __CMSIS_ARMCC_H
#define __CMSIS_ARMCC_H
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 400677)
#error "Please use Arm Compiler Toolchain V4.0.677 or later!"
#endif
/* CMSIS compiler control architecture macros */
#if ((defined (__TARGET_ARCH_6_M ) && (__TARGET_ARCH_6_M == 1)) || \
(defined (__TARGET_ARCH_6S_M ) && (__TARGET_ARCH_6S_M == 1)) )
#define __ARM_ARCH_6M__ 1
#endif
#if (defined (__TARGET_ARCH_7_M ) && (__TARGET_ARCH_7_M == 1))
#define __ARM_ARCH_7M__ 1
#endif
#if (defined (__TARGET_ARCH_7E_M) && (__TARGET_ARCH_7E_M == 1))
#define __ARM_ARCH_7EM__ 1
#endif
/* __ARM_ARCH_8M_BASE__ not applicable */
/* __ARM_ARCH_8M_MAIN__ not applicable */
/* __ARM_ARCH_8_1M_MAIN__ not applicable */
/* CMSIS compiler control DSP macros */
#if ((defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) )
#define __ARM_FEATURE_DSP 1
#endif
/* CMSIS compiler specific defines */
#ifndef __ASM
#define __ASM __asm
#endif
#ifndef __INLINE
#define __INLINE __inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static __inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE static __forceinline
#endif
#ifndef __NO_RETURN
#define __NO_RETURN __declspec(noreturn)
#endif
#ifndef __USED
#define __USED __attribute__((used))
#endif
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef __PACKED
#define __PACKED __attribute__((packed))
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT __packed struct
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION __packed union
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
#define __UNALIGNED_UINT32(x) (*((__packed uint32_t *)(x)))
#endif
#ifndef __UNALIGNED_UINT16_WRITE
#define __UNALIGNED_UINT16_WRITE(addr, val) ((*((__packed uint16_t *)(addr))) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
#define __UNALIGNED_UINT16_READ(addr) (*((const __packed uint16_t *)(addr)))
#endif
#ifndef __UNALIGNED_UINT32_WRITE
#define __UNALIGNED_UINT32_WRITE(addr, val) ((*((__packed uint32_t *)(addr))) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
#define __UNALIGNED_UINT32_READ(addr) (*((const __packed uint32_t *)(addr)))
#endif
#ifndef __ALIGNED
#define __ALIGNED(x) __attribute__((aligned(x)))
#endif
#ifndef __RESTRICT
#define __RESTRICT __restrict
#endif
#ifndef __COMPILER_BARRIER
#define __COMPILER_BARRIER() __memory_changed()
#endif
/* ######################### Startup and Lowlevel Init ######################## */
#ifndef __PROGRAM_START
#define __PROGRAM_START __main
#endif
#ifndef __INITIAL_SP
#define __INITIAL_SP Image$$ARM_LIB_STACK$$ZI$$Limit
#endif
#ifndef __STACK_LIMIT
#define __STACK_LIMIT Image$$ARM_LIB_STACK$$ZI$$Base
#endif
#ifndef __VECTOR_TABLE
#define __VECTOR_TABLE __Vectors
#endif
#ifndef __VECTOR_TABLE_ATTRIBUTE
#define __VECTOR_TABLE_ATTRIBUTE __attribute__((used, section("RESET")))
#endif
/* ########################## Core Instruction Access ######################### */
/** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface
Access to dedicated instructions
@{
*/
/**
\brief No Operation
\details No Operation does nothing. This instruction can be used for code alignment purposes.
*/
#define __NOP __nop
/**
\brief Wait For Interrupt
\details Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs.
*/
#define __WFI __wfi
/**
\brief Wait For Event
\details Wait For Event is a hint instruction that permits the processor to enter
a low-power state until one of a number of events occurs.
*/
#define __WFE __wfe
/**
\brief Send Event
\details Send Event is a hint instruction. It causes an event to be signaled to the CPU.
*/
#define __SEV __sev
/**
\brief Instruction Synchronization Barrier
\details Instruction Synchronization Barrier flushes the pipeline in the processor,
so that all instructions following the ISB are fetched from cache or memory,
after the instruction has been completed.
*/
#define __ISB() __isb(0xF)
/**
\brief Data Synchronization Barrier
\details Acts as a special kind of Data Memory Barrier.
It completes when all explicit memory accesses before this instruction complete.
*/
#define __DSB() __dsb(0xF)
/**
\brief Data Memory Barrier
\details Ensures the apparent order of the explicit memory operations before
and after the instruction, without ensuring their completion.
*/
#define __DMB() __dmb(0xF)
/**
\brief Reverse byte order (32 bit)
\details Reverses the byte order in unsigned integer value. For example, 0x12345678 becomes 0x78563412.
\param [in] value Value to reverse
\return Reversed value
*/
#define __REV __rev
/**
\brief Reverse byte order (16 bit)
\details Reverses the byte order within each halfword of a word. For example, 0x12345678 becomes 0x34127856.
\param [in] value Value to reverse
\return Reversed value
*/
#ifndef __NO_EMBEDDED_ASM
__attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value)
{
rev16 r0, r0
bx lr
}
#endif
/**
\brief Reverse byte order (16 bit)
\details Reverses the byte order in a 16-bit value and returns the signed 16-bit result. For example, 0x0080 becomes 0x8000.
\param [in] value Value to reverse
\return Reversed value
*/
#ifndef __NO_EMBEDDED_ASM
__attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int16_t __REVSH(int16_t value)
{
revsh r0, r0
bx lr
}
#endif
/**
\brief Rotate Right in unsigned value (32 bit)
\details Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
\param [in] op1 Value to rotate
\param [in] op2 Number of Bits to rotate
\return Rotated value
*/
#define __ROR __ror
/**
\brief Breakpoint
\details Causes the processor to enter Debug state.
Debug tools can use this to investigate system state when the instruction at a particular address is reached.
\param [in] value is ignored by the processor.
If required, a debugger can use it to store additional information about the breakpoint.
*/
#define __BKPT(value) __breakpoint(value)
/**
\brief Reverse bit order of value
\details Reverses the bit order of the given value.
\param [in] value Value to reverse
\return Reversed value
*/
#if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \
(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) )
#define __RBIT __rbit
#else
__attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
{
uint32_t result;
uint32_t s = (4U /*sizeof(v)*/ * 8U) - 1U; /* extra shift needed at end */
result = value; /* r will be reversed bits of v; first get LSB of v */
for (value >>= 1U; value != 0U; value >>= 1U)
{
result <<= 1U;
result |= value & 1U;
s--;
}
result <<= s; /* shift when v's highest bits are zero */
return result;
}
#endif
/**
\brief Count leading zeros
\details Counts the number of leading zeros of a data value.
\param [in] value Value to count the leading zeros
\return number of leading zeros in value
*/
#define __CLZ __clz
#if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \
(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) )
/**
\brief LDR Exclusive (8 bit)
\details Executes a exclusive LDR instruction for 8 bit value.
\param [in] ptr Pointer to data
\return value of type uint8_t at (*ptr)
*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 5060020)
#define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr))
#else
#define __LDREXB(ptr) _Pragma("push") _Pragma("diag_suppress 3731") ((uint8_t ) __ldrex(ptr)) _Pragma("pop")
#endif
/**
\brief LDR Exclusive (16 bit)
\details Executes a exclusive LDR instruction for 16 bit values.
\param [in] ptr Pointer to data
\return value of type uint16_t at (*ptr)
*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 5060020)
#define __LDREXH(ptr) ((uint16_t) __ldrex(ptr))
#else
#define __LDREXH(ptr) _Pragma("push") _Pragma("diag_suppress 3731") ((uint16_t) __ldrex(ptr)) _Pragma("pop")
#endif
/**
\brief LDR Exclusive (32 bit)
\details Executes a exclusive LDR instruction for 32 bit values.
\param [in] ptr Pointer to data
\return value of type uint32_t at (*ptr)
*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 5060020)
#define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr))
#else
#define __LDREXW(ptr) _Pragma("push") _Pragma("diag_suppress 3731") ((uint32_t ) __ldrex(ptr)) _Pragma("pop")
#endif
/**
\brief STR Exclusive (8 bit)
\details Executes a exclusive STR instruction for 8 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 5060020)
#define __STREXB(value, ptr) __strex(value, ptr)
#else
#define __STREXB(value, ptr) _Pragma("push") _Pragma("diag_suppress 3731") __strex(value, ptr) _Pragma("pop")
#endif
/**
\brief STR Exclusive (16 bit)
\details Executes a exclusive STR instruction for 16 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 5060020)
#define __STREXH(value, ptr) __strex(value, ptr)
#else
#define __STREXH(value, ptr) _Pragma("push") _Pragma("diag_suppress 3731") __strex(value, ptr) _Pragma("pop")
#endif
/**
\brief STR Exclusive (32 bit)
\details Executes a exclusive STR instruction for 32 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 5060020)
#define __STREXW(value, ptr) __strex(value, ptr)
#else
#define __STREXW(value, ptr) _Pragma("push") _Pragma("diag_suppress 3731") __strex(value, ptr) _Pragma("pop")
#endif
/**
\brief Remove the exclusive lock
\details Removes the exclusive lock which is created by LDREX.
*/
#define __CLREX __clrex
/**
\brief Signed Saturate
\details Saturates a signed value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (1..32)
\return Saturated value
*/
#define __SSAT __ssat
/**
\brief Unsigned Saturate
\details Saturates an unsigned value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (0..31)
\return Saturated value
*/
#define __USAT __usat
/**
\brief Rotate Right with Extend (32 bit)
\details Moves each bit of a bitstring right by one bit.
The carry input is shifted in at the left end of the bitstring.
\param [in] value Value to rotate
\return Rotated value
*/
#ifndef __NO_EMBEDDED_ASM
__attribute__((section(".rrx_text"))) __STATIC_INLINE __ASM uint32_t __RRX(uint32_t value)
{
rrx r0, r0
bx lr
}
#endif
/**
\brief LDRT Unprivileged (8 bit)
\details Executes a Unprivileged LDRT instruction for 8 bit value.
\param [in] ptr Pointer to data
\return value of type uint8_t at (*ptr)
*/
#define __LDRBT(ptr) ((uint8_t ) __ldrt(ptr))
/**
\brief LDRT Unprivileged (16 bit)
\details Executes a Unprivileged LDRT instruction for 16 bit values.
\param [in] ptr Pointer to data
\return value of type uint16_t at (*ptr)
*/
#define __LDRHT(ptr) ((uint16_t) __ldrt(ptr))
/**
\brief LDRT Unprivileged (32 bit)
\details Executes a Unprivileged LDRT instruction for 32 bit values.
\param [in] ptr Pointer to data
\return value of type uint32_t at (*ptr)
*/
#define __LDRT(ptr) ((uint32_t ) __ldrt(ptr))
/**
\brief STRT Unprivileged (8 bit)
\details Executes a Unprivileged STRT instruction for 8 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
#define __STRBT(value, ptr) __strt(value, ptr)
/**
\brief STRT Unprivileged (16 bit)
\details Executes a Unprivileged STRT instruction for 16 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
#define __STRHT(value, ptr) __strt(value, ptr)
/**
\brief STRT Unprivileged (32 bit)
\details Executes a Unprivileged STRT instruction for 32 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
#define __STRT(value, ptr) __strt(value, ptr)
#else /* ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \
(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) ) */
/**
\brief Signed Saturate
\details Saturates a signed value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (1..32)
\return Saturated value
*/
__attribute__((always_inline)) __STATIC_INLINE int32_t __SSAT(int32_t val, uint32_t sat)
{
if ((sat >= 1U) && (sat <= 32U))
{
const int32_t max = (int32_t)((1U << (sat - 1U)) - 1U);
const int32_t min = -1 - max ;
if (val > max)
{
return max;
}
else if (val < min)
{
return min;
}
}
return val;
}
/**
\brief Unsigned Saturate
\details Saturates an unsigned value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (0..31)
\return Saturated value
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __USAT(int32_t val, uint32_t sat)
{
if (sat <= 31U)
{
const uint32_t max = ((1U << sat) - 1U);
if (val > (int32_t)max)
{
return max;
}
else if (val < 0)
{
return 0U;
}
}
return (uint32_t)val;
}
#endif /* ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \
(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) ) */
/*@}*/ /* end of group CMSIS_Core_InstructionInterface */
/* ########################### Core Function Access ########################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
@{
*/
/**
\brief Enable IRQ Interrupts
\details Enables IRQ interrupts by clearing special-purpose register PRIMASK.
Can only be executed in Privileged modes.
*/
/* intrinsic void __enable_irq(); */
/**
\brief Disable IRQ Interrupts
\details Disables IRQ interrupts by setting special-purpose register PRIMASK.
Can only be executed in Privileged modes.
*/
/* intrinsic void __disable_irq(); */
/**
\brief Get Control Register
\details Returns the content of the Control Register.
\return Control Register value
*/
__STATIC_INLINE uint32_t __get_CONTROL(void)
{
register uint32_t __regControl __ASM("control");
return(__regControl);
}
/**
\brief Set Control Register
\details Writes the given value to the Control Register.
\param [in] control Control Register value to set
*/
__STATIC_INLINE void __set_CONTROL(uint32_t control)
{
register uint32_t __regControl __ASM("control");
__regControl = control;
__ISB();
}
/**
\brief Get IPSR Register
\details Returns the content of the IPSR Register.
\return IPSR Register value
*/
__STATIC_INLINE uint32_t __get_IPSR(void)
{
register uint32_t __regIPSR __ASM("ipsr");
return(__regIPSR);
}
/**
\brief Get APSR Register
\details Returns the content of the APSR Register.
\return APSR Register value
*/
__STATIC_INLINE uint32_t __get_APSR(void)
{
register uint32_t __regAPSR __ASM("apsr");
return(__regAPSR);
}
/**
\brief Get xPSR Register
\details Returns the content of the xPSR Register.
\return xPSR Register value
*/
__STATIC_INLINE uint32_t __get_xPSR(void)
{
register uint32_t __regXPSR __ASM("xpsr");
return(__regXPSR);
}
/**
\brief Get Process Stack Pointer
\details Returns the current value of the Process Stack Pointer (PSP).
\return PSP Register value
*/
__STATIC_INLINE uint32_t __get_PSP(void)
{
register uint32_t __regProcessStackPointer __ASM("psp");
return(__regProcessStackPointer);
}
/**
\brief Set Process Stack Pointer
\details Assigns the given value to the Process Stack Pointer (PSP).
\param [in] topOfProcStack Process Stack Pointer value to set
*/
__STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
{
register uint32_t __regProcessStackPointer __ASM("psp");
__regProcessStackPointer = topOfProcStack;
}
/**
\brief Get Main Stack Pointer
\details Returns the current value of the Main Stack Pointer (MSP).
\return MSP Register value
*/
__STATIC_INLINE uint32_t __get_MSP(void)
{
register uint32_t __regMainStackPointer __ASM("msp");
return(__regMainStackPointer);
}
/**
\brief Set Main Stack Pointer
\details Assigns the given value to the Main Stack Pointer (MSP).
\param [in] topOfMainStack Main Stack Pointer value to set
*/
__STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
{
register uint32_t __regMainStackPointer __ASM("msp");
__regMainStackPointer = topOfMainStack;
}
/**
\brief Get Priority Mask
\details Returns the current state of the priority mask bit from the Priority Mask Register.
\return Priority Mask value
*/
__STATIC_INLINE uint32_t __get_PRIMASK(void)
{
register uint32_t __regPriMask __ASM("primask");
return(__regPriMask);
}
/**
\brief Set Priority Mask
\details Assigns the given value to the Priority Mask Register.
\param [in] priMask Priority Mask
*/
__STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
{
register uint32_t __regPriMask __ASM("primask");
__regPriMask = (priMask);
}
#if ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \
(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) )
/**
\brief Enable FIQ
\details Enables FIQ interrupts by clearing special-purpose register FAULTMASK.
Can only be executed in Privileged modes.
*/
#define __enable_fault_irq __enable_fiq
/**
\brief Disable FIQ
\details Disables FIQ interrupts by setting special-purpose register FAULTMASK.
Can only be executed in Privileged modes.
*/
#define __disable_fault_irq __disable_fiq
/**
\brief Get Base Priority
\details Returns the current value of the Base Priority register.
\return Base Priority register value
*/
__STATIC_INLINE uint32_t __get_BASEPRI(void)
{
register uint32_t __regBasePri __ASM("basepri");
return(__regBasePri);
}
/**
\brief Set Base Priority
\details Assigns the given value to the Base Priority register.
\param [in] basePri Base Priority value to set
*/
__STATIC_INLINE void __set_BASEPRI(uint32_t basePri)
{
register uint32_t __regBasePri __ASM("basepri");
__regBasePri = (basePri & 0xFFU);
}
/**
\brief Set Base Priority with condition
\details Assigns the given value to the Base Priority register only if BASEPRI masking is disabled,
or the new value increases the BASEPRI priority level.
\param [in] basePri Base Priority value to set
*/
__STATIC_INLINE void __set_BASEPRI_MAX(uint32_t basePri)
{
register uint32_t __regBasePriMax __ASM("basepri_max");
__regBasePriMax = (basePri & 0xFFU);
}
/**
\brief Get Fault Mask
\details Returns the current value of the Fault Mask register.
\return Fault Mask register value
*/
__STATIC_INLINE uint32_t __get_FAULTMASK(void)
{
register uint32_t __regFaultMask __ASM("faultmask");
return(__regFaultMask);
}
/**
\brief Set Fault Mask
\details Assigns the given value to the Fault Mask register.
\param [in] faultMask Fault Mask value to set
*/
__STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
{
register uint32_t __regFaultMask __ASM("faultmask");
__regFaultMask = (faultMask & (uint32_t)1U);
}
#endif /* ((defined (__ARM_ARCH_7M__ ) && (__ARM_ARCH_7M__ == 1)) || \
(defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) ) */
/**
\brief Get FPSCR
\details Returns the current value of the Floating Point Status/Control register.
\return Floating Point Status/Control register value
*/
__STATIC_INLINE uint32_t __get_FPSCR(void)
{
#if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) && \
(defined (__FPU_USED ) && (__FPU_USED == 1U)) )
register uint32_t __regfpscr __ASM("fpscr");
return(__regfpscr);
#else
return(0U);
#endif
}
/**
\brief Set FPSCR
\details Assigns the given value to the Floating Point Status/Control register.
\param [in] fpscr Floating Point Status/Control value to set
*/
__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
{
#if ((defined (__FPU_PRESENT) && (__FPU_PRESENT == 1U)) && \
(defined (__FPU_USED ) && (__FPU_USED == 1U)) )
register uint32_t __regfpscr __ASM("fpscr");
__regfpscr = (fpscr);
#else
(void)fpscr;
#endif
}
/*@} end of CMSIS_Core_RegAccFunctions */
/* ################### Compiler specific Intrinsics ########################### */
/** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics
Access to dedicated SIMD instructions
@{
*/
#if ((defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) )
#define __SADD8 __sadd8
#define __QADD8 __qadd8
#define __SHADD8 __shadd8
#define __UADD8 __uadd8
#define __UQADD8 __uqadd8
#define __UHADD8 __uhadd8
#define __SSUB8 __ssub8
#define __QSUB8 __qsub8
#define __SHSUB8 __shsub8
#define __USUB8 __usub8
#define __UQSUB8 __uqsub8
#define __UHSUB8 __uhsub8
#define __SADD16 __sadd16
#define __QADD16 __qadd16
#define __SHADD16 __shadd16
#define __UADD16 __uadd16
#define __UQADD16 __uqadd16
#define __UHADD16 __uhadd16
#define __SSUB16 __ssub16
#define __QSUB16 __qsub16
#define __SHSUB16 __shsub16
#define __USUB16 __usub16
#define __UQSUB16 __uqsub16
#define __UHSUB16 __uhsub16
#define __SASX __sasx
#define __QASX __qasx
#define __SHASX __shasx
#define __UASX __uasx
#define __UQASX __uqasx
#define __UHASX __uhasx
#define __SSAX __ssax
#define __QSAX __qsax
#define __SHSAX __shsax
#define __USAX __usax
#define __UQSAX __uqsax
#define __UHSAX __uhsax
#define __USAD8 __usad8
#define __USADA8 __usada8
#define __SSAT16 __ssat16
#define __USAT16 __usat16
#define __UXTB16 __uxtb16
#define __UXTAB16 __uxtab16
#define __SXTB16 __sxtb16
#define __SXTAB16 __sxtab16
#define __SMUAD __smuad
#define __SMUADX __smuadx
#define __SMLAD __smlad
#define __SMLADX __smladx
#define __SMLALD __smlald
#define __SMLALDX __smlaldx
#define __SMUSD __smusd
#define __SMUSDX __smusdx
#define __SMLSD __smlsd
#define __SMLSDX __smlsdx
#define __SMLSLD __smlsld
#define __SMLSLDX __smlsldx
#define __SEL __sel
#define __QADD __qadd
#define __QSUB __qsub
#define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \
((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) )
#define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \
((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) )
#define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \
((int64_t)(ARG3) << 32U) ) >> 32U))
#define __SXTB16_RORn(ARG1, ARG2) __SXTB16(__ROR(ARG1, ARG2))
#define __SXTAB16_RORn(ARG1, ARG2, ARG3) __SXTAB16(ARG1, __ROR(ARG2, ARG3))
#endif /* ((defined (__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) ) */
/*@} end of group CMSIS_SIMD_intrinsics */
#endif /* __CMSIS_ARMCC_H */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,283 @@
/**************************************************************************//**
* @file cmsis_compiler.h
* @brief CMSIS compiler generic header file
* @version V5.1.0
* @date 09. October 2018
******************************************************************************/
/*
* Copyright (c) 2009-2018 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __CMSIS_COMPILER_H
#define __CMSIS_COMPILER_H
#include <stdint.h>
/*
* Arm Compiler 4/5
*/
#if defined ( __CC_ARM )
#include "cmsis_armcc.h"
/*
* Arm Compiler 6.6 LTM (armclang)
*/
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) && (__ARMCC_VERSION < 6100100)
#include "cmsis_armclang_ltm.h"
/*
* Arm Compiler above 6.10.1 (armclang)
*/
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6100100)
#include "cmsis_armclang.h"
/*
* GNU Compiler
*/
#elif defined ( __GNUC__ )
#include "cmsis_gcc.h"
/*
* IAR Compiler
*/
#elif defined ( __ICCARM__ )
#include <cmsis_iccarm.h>
/*
* TI Arm Compiler
*/
#elif defined ( __TI_ARM__ )
#include <cmsis_ccs.h>
#ifndef __ASM
#define __ASM __asm
#endif
#ifndef __INLINE
#define __INLINE inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE __STATIC_INLINE
#endif
#ifndef __NO_RETURN
#define __NO_RETURN __attribute__((noreturn))
#endif
#ifndef __USED
#define __USED __attribute__((used))
#endif
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef __PACKED
#define __PACKED __attribute__((packed))
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT struct __attribute__((packed))
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION union __attribute__((packed))
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
struct __attribute__((packed)) T_UINT32 { uint32_t v; };
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
#endif
#ifndef __UNALIGNED_UINT16_WRITE
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void*)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
#endif
#ifndef __UNALIGNED_UINT32_WRITE
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
#endif
#ifndef __ALIGNED
#define __ALIGNED(x) __attribute__((aligned(x)))
#endif
#ifndef __RESTRICT
#define __RESTRICT __restrict
#endif
#ifndef __COMPILER_BARRIER
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
#define __COMPILER_BARRIER() (void)0
#endif
/*
* TASKING Compiler
*/
#elif defined ( __TASKING__ )
/*
* The CMSIS functions have been implemented as intrinsics in the compiler.
* Please use "carm -?i" to get an up to date list of all intrinsics,
* Including the CMSIS ones.
*/
#ifndef __ASM
#define __ASM __asm
#endif
#ifndef __INLINE
#define __INLINE inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE __STATIC_INLINE
#endif
#ifndef __NO_RETURN
#define __NO_RETURN __attribute__((noreturn))
#endif
#ifndef __USED
#define __USED __attribute__((used))
#endif
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef __PACKED
#define __PACKED __packed__
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT struct __packed__
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION union __packed__
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
struct __packed__ T_UINT32 { uint32_t v; };
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
#endif
#ifndef __UNALIGNED_UINT16_WRITE
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
#endif
#ifndef __UNALIGNED_UINT32_WRITE
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
#endif
#ifndef __ALIGNED
#define __ALIGNED(x) __align(x)
#endif
#ifndef __RESTRICT
#warning No compiler specific solution for __RESTRICT. __RESTRICT is ignored.
#define __RESTRICT
#endif
#ifndef __COMPILER_BARRIER
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
#define __COMPILER_BARRIER() (void)0
#endif
/*
* COSMIC Compiler
*/
#elif defined ( __CSMC__ )
#include <cmsis_csm.h>
#ifndef __ASM
#define __ASM _asm
#endif
#ifndef __INLINE
#define __INLINE inline
#endif
#ifndef __STATIC_INLINE
#define __STATIC_INLINE static inline
#endif
#ifndef __STATIC_FORCEINLINE
#define __STATIC_FORCEINLINE __STATIC_INLINE
#endif
#ifndef __NO_RETURN
// NO RETURN is automatically detected hence no warning here
#define __NO_RETURN
#endif
#ifndef __USED
#warning No compiler specific solution for __USED. __USED is ignored.
#define __USED
#endif
#ifndef __WEAK
#define __WEAK __weak
#endif
#ifndef __PACKED
#define __PACKED @packed
#endif
#ifndef __PACKED_STRUCT
#define __PACKED_STRUCT @packed struct
#endif
#ifndef __PACKED_UNION
#define __PACKED_UNION @packed union
#endif
#ifndef __UNALIGNED_UINT32 /* deprecated */
@packed struct T_UINT32 { uint32_t v; };
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
#endif
#ifndef __UNALIGNED_UINT16_WRITE
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT16_READ
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
#endif
#ifndef __UNALIGNED_UINT32_WRITE
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
#endif
#ifndef __UNALIGNED_UINT32_READ
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
#endif
#ifndef __ALIGNED
#warning No compiler specific solution for __ALIGNED. __ALIGNED is ignored.
#define __ALIGNED(x)
#endif
#ifndef __RESTRICT
#warning No compiler specific solution for __RESTRICT. __RESTRICT is ignored.
#define __RESTRICT
#endif
#ifndef __COMPILER_BARRIER
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
#define __COMPILER_BARRIER() (void)0
#endif
#else
#error Unknown compiler.
#endif
#endif /* __CMSIS_COMPILER_H */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,39 @@
/**************************************************************************//**
* @file cmsis_version.h
* @brief CMSIS Core(M) Version definitions
* @version V5.0.5
* @date 02. February 2022
******************************************************************************/
/*
* Copyright (c) 2009-2022 ARM Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef __CMSIS_VERSION_H
#define __CMSIS_VERSION_H
/* CMSIS Version definitions */
#define __CM_CMSIS_VERSION_MAIN ( 5U) /*!< [31:16] CMSIS Core(M) main version */
#define __CM_CMSIS_VERSION_SUB ( 6U) /*!< [15:0] CMSIS Core(M) sub version */
#define __CM_CMSIS_VERSION ((__CM_CMSIS_VERSION_MAIN << 16U) | \
__CM_CMSIS_VERSION_SUB ) /*!< CMSIS Core(M) version number */
#endif
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,952 @@
/**************************************************************************//**
* @file core_cm0.h
* @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File
* @version V5.0.8
* @date 21. August 2019
******************************************************************************/
/*
* Copyright (c) 2009-2019 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef __CORE_CM0_H_GENERIC
#define __CORE_CM0_H_GENERIC
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
\page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/**
\ingroup Cortex_M0
@{
*/
#include "cmsis_version.h"
/* CMSIS CM0 definitions */
#define __CM0_CMSIS_VERSION_MAIN (__CM_CMSIS_VERSION_MAIN) /*!< \deprecated [31:16] CMSIS HAL main version */
#define __CM0_CMSIS_VERSION_SUB (__CM_CMSIS_VERSION_SUB) /*!< \deprecated [15:0] CMSIS HAL sub version */
#define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16U) | \
__CM0_CMSIS_VERSION_SUB ) /*!< \deprecated CMSIS HAL version number */
#define __CORTEX_M (0U) /*!< Cortex-M Core */
/** __FPU_USED indicates whether an FPU is used or not.
This core does not support an FPU at all
*/
#define __FPU_USED 0U
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#if defined __ARM_FP
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TI_ARM__ )
#if defined __TI_VFP_SUPPORT__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __CSMC__ )
#if ( __CSMC__ & 0x400U)
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#endif
#include "cmsis_compiler.h" /* CMSIS compiler specific defines */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM0_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_CM0_H_DEPENDANT
#define __CORE_CM0_H_DEPENDANT
#ifdef __cplusplus
extern "C" {
#endif
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __CM0_REV
#define __CM0_REV 0x0000U
#warning "__CM0_REV not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 2U
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0U
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/* following defines should be used for structure members */
#define __IM volatile const /*! Defines 'read only' structure member permissions */
#define __OM volatile /*! Defines 'write only' structure member permissions */
#define __IOM volatile /*! Defines 'read / write' structure member permissions */
/*@} end of group Cortex_M0 */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
******************************************************************************/
/**
\defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/**
\brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/* APSR Register Definitions */
#define APSR_N_Pos 31U /*!< APSR: N Position */
#define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */
#define APSR_Z_Pos 30U /*!< APSR: Z Position */
#define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */
#define APSR_C_Pos 29U /*!< APSR: C Position */
#define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */
#define APSR_V_Pos 28U /*!< APSR: V Position */
#define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */
/**
\brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/* IPSR Register Definitions */
#define IPSR_ISR_Pos 0U /*!< IPSR: ISR Position */
#define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */
/**
\brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/* xPSR Register Definitions */
#define xPSR_N_Pos 31U /*!< xPSR: N Position */
#define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */
#define xPSR_Z_Pos 30U /*!< xPSR: Z Position */
#define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */
#define xPSR_C_Pos 29U /*!< xPSR: C Position */
#define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */
#define xPSR_V_Pos 28U /*!< xPSR: V Position */
#define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */
#define xPSR_T_Pos 24U /*!< xPSR: T Position */
#define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */
#define xPSR_ISR_Pos 0U /*!< xPSR: ISR Position */
#define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */
/**
\brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t _reserved0:1; /*!< bit: 0 Reserved */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/* CONTROL Register Definitions */
#define CONTROL_SPSEL_Pos 1U /*!< CONTROL: SPSEL Position */
#define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */
/*@} end of group CMSIS_CORE */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/**
\brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IOM uint32_t ISER[1U]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[31U];
__IOM uint32_t ICER[1U]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RESERVED1[31U];
__IOM uint32_t ISPR[1U]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[31U];
__IOM uint32_t ICPR[1U]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[31U];
uint32_t RESERVED4[64U];
__IOM uint32_t IP[8U]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */
} NVIC_Type;
/*@} end of group CMSIS_NVIC */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/**
\brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__IM uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IOM uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
uint32_t RESERVED0;
__IOM uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IOM uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IOM uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
uint32_t RESERVED1;
__IOM uint32_t SHP[2U]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */
__IOM uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24U /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20U /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16U /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4U /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0U /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31U /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28U /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27U /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26U /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25U /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23U /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22U /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12U /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0U /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16U /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16U /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15U /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2U /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1U /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4U /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2U /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1U /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9U /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3U /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_SVCALLPENDED_Pos 15U /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
/*@} end of group CMSIS_SCB */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/**
\brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IOM uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IOM uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IOM uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__IM uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16U /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2U /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1U /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0U /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0U /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0U /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31U /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30U /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0U /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor.
Therefore they are not covered by the Cortex-M0 header file.
@{
*/
/*@} end of group CMSIS_CoreDebug */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_core_bitfield Core register bit field macros
\brief Macros for use with bit field definitions (xxx_Pos, xxx_Msk).
@{
*/
/**
\brief Mask and shift a bit field value for use in a register bit range.
\param[in] field Name of the register bit field.
\param[in] value Value of the bit field. This parameter is interpreted as an uint32_t type.
\return Masked and shifted value.
*/
#define _VAL2FLD(field, value) (((uint32_t)(value) << field ## _Pos) & field ## _Msk)
/**
\brief Mask and shift a register value to extract a bit filed value.
\param[in] field Name of the register bit field.
\param[in] value Value of register. This parameter is interpreted as an uint32_t type.
\return Masked and shifted bit field value.
*/
#define _FLD2VAL(field, value) (((uint32_t)(value) & field ## _Msk) >> field ## _Pos)
/*@} end of group CMSIS_core_bitfield */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of Core Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Register Access Functions
******************************************************************************/
/**
\defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
#ifdef CMSIS_NVIC_VIRTUAL
#ifndef CMSIS_NVIC_VIRTUAL_HEADER_FILE
#define CMSIS_NVIC_VIRTUAL_HEADER_FILE "cmsis_nvic_virtual.h"
#endif
#include CMSIS_NVIC_VIRTUAL_HEADER_FILE
#else
#define NVIC_SetPriorityGrouping __NVIC_SetPriorityGrouping
#define NVIC_GetPriorityGrouping __NVIC_GetPriorityGrouping
#define NVIC_EnableIRQ __NVIC_EnableIRQ
#define NVIC_GetEnableIRQ __NVIC_GetEnableIRQ
#define NVIC_DisableIRQ __NVIC_DisableIRQ
#define NVIC_GetPendingIRQ __NVIC_GetPendingIRQ
#define NVIC_SetPendingIRQ __NVIC_SetPendingIRQ
#define NVIC_ClearPendingIRQ __NVIC_ClearPendingIRQ
/*#define NVIC_GetActive __NVIC_GetActive not available for Cortex-M0 */
#define NVIC_SetPriority __NVIC_SetPriority
#define NVIC_GetPriority __NVIC_GetPriority
#define NVIC_SystemReset __NVIC_SystemReset
#endif /* CMSIS_NVIC_VIRTUAL */
#ifdef CMSIS_VECTAB_VIRTUAL
#ifndef CMSIS_VECTAB_VIRTUAL_HEADER_FILE
#define CMSIS_VECTAB_VIRTUAL_HEADER_FILE "cmsis_vectab_virtual.h"
#endif
#include CMSIS_VECTAB_VIRTUAL_HEADER_FILE
#else
#define NVIC_SetVector __NVIC_SetVector
#define NVIC_GetVector __NVIC_GetVector
#endif /* (CMSIS_VECTAB_VIRTUAL) */
#define NVIC_USER_IRQ_OFFSET 16
/* The following EXC_RETURN values are saved the LR on exception entry */
#define EXC_RETURN_HANDLER (0xFFFFFFF1UL) /* return to Handler mode, uses MSP after return */
#define EXC_RETURN_THREAD_MSP (0xFFFFFFF9UL) /* return to Thread mode, uses MSP after return */
#define EXC_RETURN_THREAD_PSP (0xFFFFFFFDUL) /* return to Thread mode, uses PSP after return */
/* Interrupt Priorities are WORD accessible only under Armv6-M */
/* The following MACROS handle generation of the register offset and byte masks */
#define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL)
#define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) )
#define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) )
#define __NVIC_SetPriorityGrouping(X) (void)(X)
#define __NVIC_GetPriorityGrouping() (0U)
/**
\brief Enable Interrupt
\details Enables a device specific interrupt in the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_EnableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
__COMPILER_BARRIER();
NVIC->ISER[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
__COMPILER_BARRIER();
}
}
/**
\brief Get Interrupt Enable status
\details Returns a device specific interrupt enable status from the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt is not enabled.
\return 1 Interrupt is enabled.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetEnableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->ISER[0U] & (1UL << (((uint32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Disable Interrupt
\details Disables a device specific interrupt in the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_DisableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ICER[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
__DSB();
__ISB();
}
}
/**
\brief Get Pending Interrupt
\details Reads the NVIC pending register and returns the pending bit for the specified device specific interrupt.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->ISPR[0U] & (1UL << (((uint32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Set Pending Interrupt
\details Sets the pending bit of a device specific interrupt in the NVIC pending register.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ISPR[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Clear Pending Interrupt
\details Clears the pending bit of a device specific interrupt in the NVIC pending register.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ICPR[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Set Interrupt Priority
\details Sets the priority of a device specific interrupt or a processor exception.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
\note The priority cannot be set for every processor exception.
*/
__STATIC_INLINE void __NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
else
{
SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
}
/**
\brief Get Interrupt Priority
\details Reads the priority of a device specific interrupt or a processor exception.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\return Interrupt Priority.
Value is aligned automatically to the implemented priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t __NVIC_GetPriority(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8U - __NVIC_PRIO_BITS)));
}
else
{
return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8U - __NVIC_PRIO_BITS)));
}
}
/**
\brief Encode Priority
\details Encodes the priority for an interrupt with the given priority group,
preemptive priority value, and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
\param [in] PriorityGroup Used priority group.
\param [in] PreemptPriority Preemptive priority value (starting from 0).
\param [in] SubPriority Subpriority value (starting from 0).
\return Encoded priority. Value can be used in the function \ref NVIC_SetPriority().
*/
__STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);
SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS));
return (
((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) |
((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL)))
);
}
/**
\brief Decode Priority
\details Decodes an interrupt priority value with a given priority group to
preemptive priority value and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set.
\param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority().
\param [in] PriorityGroup Used priority group.
\param [out] pPreemptPriority Preemptive priority value (starting from 0).
\param [out] pSubPriority Subpriority value (starting from 0).
*/
__STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* const pPreemptPriority, uint32_t* const pSubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);
SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS));
*pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL);
*pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL);
}
/**
\brief Set Interrupt Vector
\details Sets an interrupt vector in SRAM based interrupt vector table.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
Address 0 must be mapped to SRAM.
\param [in] IRQn Interrupt number
\param [in] vector Address of interrupt handler function
*/
__STATIC_INLINE void __NVIC_SetVector(IRQn_Type IRQn, uint32_t vector)
{
uint32_t *vectors = (uint32_t *)(NVIC_USER_IRQ_OFFSET << 2); /* point to 1st user interrupt */
*(vectors + (int32_t)IRQn) = vector; /* use pointer arithmetic to access vector */
/* ARM Application Note 321 states that the M0 does not require the architectural barrier */
}
/**
\brief Get Interrupt Vector
\details Reads an interrupt vector from interrupt vector table.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\return Address of interrupt handler function
*/
__STATIC_INLINE uint32_t __NVIC_GetVector(IRQn_Type IRQn)
{
uint32_t *vectors = (uint32_t *)(NVIC_USER_IRQ_OFFSET << 2); /* point to 1st user interrupt */
return *(vectors + (int32_t)IRQn); /* use pointer arithmetic to access vector */
}
/**
\brief System Reset
\details Initiates a system reset request to reset the MCU.
*/
__NO_RETURN __STATIC_INLINE void __NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
SCB_AIRCR_SYSRESETREQ_Msk);
__DSB(); /* Ensure completion of memory access */
for(;;) /* wait until reset */
{
__NOP();
}
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ########################## FPU functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_FpuFunctions FPU Functions
\brief Function that provides FPU type.
@{
*/
/**
\brief get FPU type
\details returns the FPU type
\returns
- \b 0: No FPU
- \b 1: Single precision FPU
- \b 2: Double + Single precision FPU
*/
__STATIC_INLINE uint32_t SCB_GetFPUType(void)
{
return 0U; /* No FPU */
}
/*@} end of CMSIS_Core_FpuFunctions */
/* ################################## SysTick function ############################################ */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if defined (__Vendor_SysTickConfig) && (__Vendor_SysTickConfig == 0U)
/**
\brief System Tick Configuration
\details Initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk)
{
return (1UL); /* Reload value impossible */
}
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0UL); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM0_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,979 @@
/**************************************************************************//**
* @file core_cm1.h
* @brief CMSIS Cortex-M1 Core Peripheral Access Layer Header File
* @version V1.0.1
* @date 12. November 2018
******************************************************************************/
/*
* Copyright (c) 2009-2018 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef __CORE_CM1_H_GENERIC
#define __CORE_CM1_H_GENERIC
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
\page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/**
\ingroup Cortex_M1
@{
*/
#include "cmsis_version.h"
/* CMSIS CM1 definitions */
#define __CM1_CMSIS_VERSION_MAIN (__CM_CMSIS_VERSION_MAIN) /*!< \deprecated [31:16] CMSIS HAL main version */
#define __CM1_CMSIS_VERSION_SUB (__CM_CMSIS_VERSION_SUB) /*!< \deprecated [15:0] CMSIS HAL sub version */
#define __CM1_CMSIS_VERSION ((__CM1_CMSIS_VERSION_MAIN << 16U) | \
__CM1_CMSIS_VERSION_SUB ) /*!< \deprecated CMSIS HAL version number */
#define __CORTEX_M (1U) /*!< Cortex-M Core */
/** __FPU_USED indicates whether an FPU is used or not.
This core does not support an FPU at all
*/
#define __FPU_USED 0U
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#if defined __ARM_FP
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TI_ARM__ )
#if defined __TI_VFP_SUPPORT__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __CSMC__ )
#if ( __CSMC__ & 0x400U)
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#endif
#include "cmsis_compiler.h" /* CMSIS compiler specific defines */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM1_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_CM1_H_DEPENDANT
#define __CORE_CM1_H_DEPENDANT
#ifdef __cplusplus
extern "C" {
#endif
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __CM1_REV
#define __CM1_REV 0x0100U
#warning "__CM1_REV not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 2U
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0U
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/* following defines should be used for structure members */
#define __IM volatile const /*! Defines 'read only' structure member permissions */
#define __OM volatile /*! Defines 'write only' structure member permissions */
#define __IOM volatile /*! Defines 'read / write' structure member permissions */
/*@} end of group Cortex_M1 */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
******************************************************************************/
/**
\defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/**
\brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/* APSR Register Definitions */
#define APSR_N_Pos 31U /*!< APSR: N Position */
#define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */
#define APSR_Z_Pos 30U /*!< APSR: Z Position */
#define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */
#define APSR_C_Pos 29U /*!< APSR: C Position */
#define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */
#define APSR_V_Pos 28U /*!< APSR: V Position */
#define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */
/**
\brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/* IPSR Register Definitions */
#define IPSR_ISR_Pos 0U /*!< IPSR: ISR Position */
#define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */
/**
\brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/* xPSR Register Definitions */
#define xPSR_N_Pos 31U /*!< xPSR: N Position */
#define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */
#define xPSR_Z_Pos 30U /*!< xPSR: Z Position */
#define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */
#define xPSR_C_Pos 29U /*!< xPSR: C Position */
#define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */
#define xPSR_V_Pos 28U /*!< xPSR: V Position */
#define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */
#define xPSR_T_Pos 24U /*!< xPSR: T Position */
#define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */
#define xPSR_ISR_Pos 0U /*!< xPSR: ISR Position */
#define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */
/**
\brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t _reserved0:1; /*!< bit: 0 Reserved */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/* CONTROL Register Definitions */
#define CONTROL_SPSEL_Pos 1U /*!< CONTROL: SPSEL Position */
#define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */
/*@} end of group CMSIS_CORE */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/**
\brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IOM uint32_t ISER[1U]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[31U];
__IOM uint32_t ICER[1U]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RSERVED1[31U];
__IOM uint32_t ISPR[1U]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[31U];
__IOM uint32_t ICPR[1U]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[31U];
uint32_t RESERVED4[64U];
__IOM uint32_t IP[8U]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */
} NVIC_Type;
/*@} end of group CMSIS_NVIC */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/**
\brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__IM uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IOM uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
uint32_t RESERVED0;
__IOM uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IOM uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IOM uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
uint32_t RESERVED1;
__IOM uint32_t SHP[2U]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */
__IOM uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24U /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20U /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16U /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4U /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0U /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31U /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28U /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27U /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26U /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25U /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23U /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22U /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12U /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0U /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16U /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16U /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15U /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2U /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1U /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4U /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2U /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1U /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9U /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3U /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_SVCALLPENDED_Pos 15U /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
/*@} end of group CMSIS_SCB */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
\brief Type definitions for the System Control and ID Register not in the SCB
@{
*/
/**
\brief Structure type to access the System Control and ID Register not in the SCB.
*/
typedef struct
{
uint32_t RESERVED0[2U];
__IOM uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */
} SCnSCB_Type;
/* Auxiliary Control Register Definitions */
#define SCnSCB_ACTLR_ITCMUAEN_Pos 4U /*!< ACTLR: Instruction TCM Upper Alias Enable Position */
#define SCnSCB_ACTLR_ITCMUAEN_Msk (1UL << SCnSCB_ACTLR_ITCMUAEN_Pos) /*!< ACTLR: Instruction TCM Upper Alias Enable Mask */
#define SCnSCB_ACTLR_ITCMLAEN_Pos 3U /*!< ACTLR: Instruction TCM Lower Alias Enable Position */
#define SCnSCB_ACTLR_ITCMLAEN_Msk (1UL << SCnSCB_ACTLR_ITCMLAEN_Pos) /*!< ACTLR: Instruction TCM Lower Alias Enable Mask */
/*@} end of group CMSIS_SCnotSCB */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/**
\brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IOM uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IOM uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IOM uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__IM uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16U /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2U /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1U /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0U /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0U /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0U /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31U /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30U /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0U /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief Cortex-M1 Core Debug Registers (DCB registers, SHCSR, and DFSR) are only accessible over DAP and not via processor.
Therefore they are not covered by the Cortex-M1 header file.
@{
*/
/*@} end of group CMSIS_CoreDebug */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_core_bitfield Core register bit field macros
\brief Macros for use with bit field definitions (xxx_Pos, xxx_Msk).
@{
*/
/**
\brief Mask and shift a bit field value for use in a register bit range.
\param[in] field Name of the register bit field.
\param[in] value Value of the bit field. This parameter is interpreted as an uint32_t type.
\return Masked and shifted value.
*/
#define _VAL2FLD(field, value) (((uint32_t)(value) << field ## _Pos) & field ## _Msk)
/**
\brief Mask and shift a register value to extract a bit filed value.
\param[in] field Name of the register bit field.
\param[in] value Value of register. This parameter is interpreted as an uint32_t type.
\return Masked and shifted bit field value.
*/
#define _FLD2VAL(field, value) (((uint32_t)(value) & field ## _Msk) >> field ## _Pos)
/*@} end of group CMSIS_core_bitfield */
/**
\ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of Core Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Register Access Functions
******************************************************************************/
/**
\defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
#ifdef CMSIS_NVIC_VIRTUAL
#ifndef CMSIS_NVIC_VIRTUAL_HEADER_FILE
#define CMSIS_NVIC_VIRTUAL_HEADER_FILE "cmsis_nvic_virtual.h"
#endif
#include CMSIS_NVIC_VIRTUAL_HEADER_FILE
#else
#define NVIC_SetPriorityGrouping __NVIC_SetPriorityGrouping
#define NVIC_GetPriorityGrouping __NVIC_GetPriorityGrouping
#define NVIC_EnableIRQ __NVIC_EnableIRQ
#define NVIC_GetEnableIRQ __NVIC_GetEnableIRQ
#define NVIC_DisableIRQ __NVIC_DisableIRQ
#define NVIC_GetPendingIRQ __NVIC_GetPendingIRQ
#define NVIC_SetPendingIRQ __NVIC_SetPendingIRQ
#define NVIC_ClearPendingIRQ __NVIC_ClearPendingIRQ
/*#define NVIC_GetActive __NVIC_GetActive not available for Cortex-M1 */
#define NVIC_SetPriority __NVIC_SetPriority
#define NVIC_GetPriority __NVIC_GetPriority
#define NVIC_SystemReset __NVIC_SystemReset
#endif /* CMSIS_NVIC_VIRTUAL */
#ifdef CMSIS_VECTAB_VIRTUAL
#ifndef CMSIS_VECTAB_VIRTUAL_HEADER_FILE
#define CMSIS_VECTAB_VIRTUAL_HEADER_FILE "cmsis_vectab_virtual.h"
#endif
#include CMSIS_VECTAB_VIRTUAL_HEADER_FILE
#else
#define NVIC_SetVector __NVIC_SetVector
#define NVIC_GetVector __NVIC_GetVector
#endif /* (CMSIS_VECTAB_VIRTUAL) */
#define NVIC_USER_IRQ_OFFSET 16
/* The following EXC_RETURN values are saved the LR on exception entry */
#define EXC_RETURN_HANDLER (0xFFFFFFF1UL) /* return to Handler mode, uses MSP after return */
#define EXC_RETURN_THREAD_MSP (0xFFFFFFF9UL) /* return to Thread mode, uses MSP after return */
#define EXC_RETURN_THREAD_PSP (0xFFFFFFFDUL) /* return to Thread mode, uses PSP after return */
/* Interrupt Priorities are WORD accessible only under Armv6-M */
/* The following MACROS handle generation of the register offset and byte masks */
#define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL)
#define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) )
#define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) )
#define __NVIC_SetPriorityGrouping(X) (void)(X)
#define __NVIC_GetPriorityGrouping() (0U)
/**
\brief Enable Interrupt
\details Enables a device specific interrupt in the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_EnableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
__COMPILER_BARRIER();
NVIC->ISER[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
__COMPILER_BARRIER();
}
}
/**
\brief Get Interrupt Enable status
\details Returns a device specific interrupt enable status from the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt is not enabled.
\return 1 Interrupt is enabled.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetEnableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->ISER[0U] & (1UL << (((uint32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Disable Interrupt
\details Disables a device specific interrupt in the NVIC interrupt controller.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_DisableIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ICER[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
__DSB();
__ISB();
}
}
/**
\brief Get Pending Interrupt
\details Reads the NVIC pending register and returns the pending bit for the specified device specific interrupt.
\param [in] IRQn Device specific interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
\note IRQn must not be negative.
*/
__STATIC_INLINE uint32_t __NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->ISPR[0U] & (1UL << (((uint32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
else
{
return(0U);
}
}
/**
\brief Set Pending Interrupt
\details Sets the pending bit of a device specific interrupt in the NVIC pending register.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ISPR[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Clear Pending Interrupt
\details Clears the pending bit of a device specific interrupt in the NVIC pending register.
\param [in] IRQn Device specific interrupt number.
\note IRQn must not be negative.
*/
__STATIC_INLINE void __NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->ICPR[0U] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL));
}
}
/**
\brief Set Interrupt Priority
\details Sets the priority of a device specific interrupt or a processor exception.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
\note The priority cannot be set for every processor exception.
*/
__STATIC_INLINE void __NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if ((int32_t)(IRQn) >= 0)
{
NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
else
{
SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8U - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
}
/**
\brief Get Interrupt Priority
\details Reads the priority of a device specific interrupt or a processor exception.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\return Interrupt Priority.
Value is aligned automatically to the implemented priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t __NVIC_GetPriority(IRQn_Type IRQn)
{
if ((int32_t)(IRQn) >= 0)
{
return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8U - __NVIC_PRIO_BITS)));
}
else
{
return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8U - __NVIC_PRIO_BITS)));
}
}
/**
\brief Encode Priority
\details Encodes the priority for an interrupt with the given priority group,
preemptive priority value, and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
\param [in] PriorityGroup Used priority group.
\param [in] PreemptPriority Preemptive priority value (starting from 0).
\param [in] SubPriority Subpriority value (starting from 0).
\return Encoded priority. Value can be used in the function \ref NVIC_SetPriority().
*/
__STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);
SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS));
return (
((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) |
((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL)))
);
}
/**
\brief Decode Priority
\details Decodes an interrupt priority value with a given priority group to
preemptive priority value and subpriority value.
In case of a conflict between priority grouping and available
priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set.
\param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority().
\param [in] PriorityGroup Used priority group.
\param [out] pPreemptPriority Preemptive priority value (starting from 0).
\param [out] pSubPriority Subpriority value (starting from 0).
*/
__STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* const pPreemptPriority, uint32_t* const pSubPriority)
{
uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); /* only values 0..7 are used */
uint32_t PreemptPriorityBits;
uint32_t SubPriorityBits;
PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(__NVIC_PRIO_BITS)) ? (uint32_t)(__NVIC_PRIO_BITS) : (uint32_t)(7UL - PriorityGroupTmp);
SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(__NVIC_PRIO_BITS)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(__NVIC_PRIO_BITS));
*pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL);
*pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL);
}
/**
\brief Set Interrupt Vector
\details Sets an interrupt vector in SRAM based interrupt vector table.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
Address 0 must be mapped to SRAM.
\param [in] IRQn Interrupt number
\param [in] vector Address of interrupt handler function
*/
__STATIC_INLINE void __NVIC_SetVector(IRQn_Type IRQn, uint32_t vector)
{
uint32_t *vectors = (uint32_t *)0x0U;
vectors[(int32_t)IRQn + NVIC_USER_IRQ_OFFSET] = vector;
/* ARM Application Note 321 states that the M1 does not require the architectural barrier */
}
/**
\brief Get Interrupt Vector
\details Reads an interrupt vector from interrupt vector table.
The interrupt number can be positive to specify a device specific interrupt,
or negative to specify a processor exception.
\param [in] IRQn Interrupt number.
\return Address of interrupt handler function
*/
__STATIC_INLINE uint32_t __NVIC_GetVector(IRQn_Type IRQn)
{
uint32_t *vectors = (uint32_t *)0x0U;
return vectors[(int32_t)IRQn + NVIC_USER_IRQ_OFFSET];
}
/**
\brief System Reset
\details Initiates a system reset request to reset the MCU.
*/
__NO_RETURN __STATIC_INLINE void __NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
SCB_AIRCR_SYSRESETREQ_Msk);
__DSB(); /* Ensure completion of memory access */
for(;;) /* wait until reset */
{
__NOP();
}
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ########################## FPU functions #################################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_FpuFunctions FPU Functions
\brief Function that provides FPU type.
@{
*/
/**
\brief get FPU type
\details returns the FPU type
\returns
- \b 0: No FPU
- \b 1: Single precision FPU
- \b 2: Double + Single precision FPU
*/
__STATIC_INLINE uint32_t SCB_GetFPUType(void)
{
return 0U; /* No FPU */
}
/*@} end of CMSIS_Core_FpuFunctions */
/* ################################## SysTick function ############################################ */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if defined (__Vendor_SysTickConfig) && (__Vendor_SysTickConfig == 0U)
/**
\brief System Tick Configuration
\details Initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk)
{
return (1UL); /* Reload value impossible */
}
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0UL); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM1_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,275 @@
/******************************************************************************
* @file mpu_armv7.h
* @brief CMSIS MPU API for Armv7-M MPU
* @version V5.1.2
* @date 25. May 2020
******************************************************************************/
/*
* Copyright (c) 2017-2020 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef ARM_MPU_ARMV7_H
#define ARM_MPU_ARMV7_H
#define ARM_MPU_REGION_SIZE_32B ((uint8_t)0x04U) ///!< MPU Region Size 32 Bytes
#define ARM_MPU_REGION_SIZE_64B ((uint8_t)0x05U) ///!< MPU Region Size 64 Bytes
#define ARM_MPU_REGION_SIZE_128B ((uint8_t)0x06U) ///!< MPU Region Size 128 Bytes
#define ARM_MPU_REGION_SIZE_256B ((uint8_t)0x07U) ///!< MPU Region Size 256 Bytes
#define ARM_MPU_REGION_SIZE_512B ((uint8_t)0x08U) ///!< MPU Region Size 512 Bytes
#define ARM_MPU_REGION_SIZE_1KB ((uint8_t)0x09U) ///!< MPU Region Size 1 KByte
#define ARM_MPU_REGION_SIZE_2KB ((uint8_t)0x0AU) ///!< MPU Region Size 2 KBytes
#define ARM_MPU_REGION_SIZE_4KB ((uint8_t)0x0BU) ///!< MPU Region Size 4 KBytes
#define ARM_MPU_REGION_SIZE_8KB ((uint8_t)0x0CU) ///!< MPU Region Size 8 KBytes
#define ARM_MPU_REGION_SIZE_16KB ((uint8_t)0x0DU) ///!< MPU Region Size 16 KBytes
#define ARM_MPU_REGION_SIZE_32KB ((uint8_t)0x0EU) ///!< MPU Region Size 32 KBytes
#define ARM_MPU_REGION_SIZE_64KB ((uint8_t)0x0FU) ///!< MPU Region Size 64 KBytes
#define ARM_MPU_REGION_SIZE_128KB ((uint8_t)0x10U) ///!< MPU Region Size 128 KBytes
#define ARM_MPU_REGION_SIZE_256KB ((uint8_t)0x11U) ///!< MPU Region Size 256 KBytes
#define ARM_MPU_REGION_SIZE_512KB ((uint8_t)0x12U) ///!< MPU Region Size 512 KBytes
#define ARM_MPU_REGION_SIZE_1MB ((uint8_t)0x13U) ///!< MPU Region Size 1 MByte
#define ARM_MPU_REGION_SIZE_2MB ((uint8_t)0x14U) ///!< MPU Region Size 2 MBytes
#define ARM_MPU_REGION_SIZE_4MB ((uint8_t)0x15U) ///!< MPU Region Size 4 MBytes
#define ARM_MPU_REGION_SIZE_8MB ((uint8_t)0x16U) ///!< MPU Region Size 8 MBytes
#define ARM_MPU_REGION_SIZE_16MB ((uint8_t)0x17U) ///!< MPU Region Size 16 MBytes
#define ARM_MPU_REGION_SIZE_32MB ((uint8_t)0x18U) ///!< MPU Region Size 32 MBytes
#define ARM_MPU_REGION_SIZE_64MB ((uint8_t)0x19U) ///!< MPU Region Size 64 MBytes
#define ARM_MPU_REGION_SIZE_128MB ((uint8_t)0x1AU) ///!< MPU Region Size 128 MBytes
#define ARM_MPU_REGION_SIZE_256MB ((uint8_t)0x1BU) ///!< MPU Region Size 256 MBytes
#define ARM_MPU_REGION_SIZE_512MB ((uint8_t)0x1CU) ///!< MPU Region Size 512 MBytes
#define ARM_MPU_REGION_SIZE_1GB ((uint8_t)0x1DU) ///!< MPU Region Size 1 GByte
#define ARM_MPU_REGION_SIZE_2GB ((uint8_t)0x1EU) ///!< MPU Region Size 2 GBytes
#define ARM_MPU_REGION_SIZE_4GB ((uint8_t)0x1FU) ///!< MPU Region Size 4 GBytes
#define ARM_MPU_AP_NONE 0U ///!< MPU Access Permission no access
#define ARM_MPU_AP_PRIV 1U ///!< MPU Access Permission privileged access only
#define ARM_MPU_AP_URO 2U ///!< MPU Access Permission unprivileged access read-only
#define ARM_MPU_AP_FULL 3U ///!< MPU Access Permission full access
#define ARM_MPU_AP_PRO 5U ///!< MPU Access Permission privileged access read-only
#define ARM_MPU_AP_RO 6U ///!< MPU Access Permission read-only access
/** MPU Region Base Address Register Value
*
* \param Region The region to be configured, number 0 to 15.
* \param BaseAddress The base address for the region.
*/
#define ARM_MPU_RBAR(Region, BaseAddress) \
(((BaseAddress) & MPU_RBAR_ADDR_Msk) | \
((Region) & MPU_RBAR_REGION_Msk) | \
(MPU_RBAR_VALID_Msk))
/**
* MPU Memory Access Attributes
*
* \param TypeExtField Type extension field, allows you to configure memory access type, for example strongly ordered, peripheral.
* \param IsShareable Region is shareable between multiple bus masters.
* \param IsCacheable Region is cacheable, i.e. its value may be kept in cache.
* \param IsBufferable Region is bufferable, i.e. using write-back caching. Cacheable but non-bufferable regions use write-through policy.
*/
#define ARM_MPU_ACCESS_(TypeExtField, IsShareable, IsCacheable, IsBufferable) \
((((TypeExtField) << MPU_RASR_TEX_Pos) & MPU_RASR_TEX_Msk) | \
(((IsShareable) << MPU_RASR_S_Pos) & MPU_RASR_S_Msk) | \
(((IsCacheable) << MPU_RASR_C_Pos) & MPU_RASR_C_Msk) | \
(((IsBufferable) << MPU_RASR_B_Pos) & MPU_RASR_B_Msk))
/**
* MPU Region Attribute and Size Register Value
*
* \param DisableExec Instruction access disable bit, 1= disable instruction fetches.
* \param AccessPermission Data access permissions, allows you to configure read/write access for User and Privileged mode.
* \param AccessAttributes Memory access attribution, see \ref ARM_MPU_ACCESS_.
* \param SubRegionDisable Sub-region disable field.
* \param Size Region size of the region to be configured, for example 4K, 8K.
*/
#define ARM_MPU_RASR_EX(DisableExec, AccessPermission, AccessAttributes, SubRegionDisable, Size) \
((((DisableExec) << MPU_RASR_XN_Pos) & MPU_RASR_XN_Msk) | \
(((AccessPermission) << MPU_RASR_AP_Pos) & MPU_RASR_AP_Msk) | \
(((AccessAttributes) & (MPU_RASR_TEX_Msk | MPU_RASR_S_Msk | MPU_RASR_C_Msk | MPU_RASR_B_Msk))) | \
(((SubRegionDisable) << MPU_RASR_SRD_Pos) & MPU_RASR_SRD_Msk) | \
(((Size) << MPU_RASR_SIZE_Pos) & MPU_RASR_SIZE_Msk) | \
(((MPU_RASR_ENABLE_Msk))))
/**
* MPU Region Attribute and Size Register Value
*
* \param DisableExec Instruction access disable bit, 1= disable instruction fetches.
* \param AccessPermission Data access permissions, allows you to configure read/write access for User and Privileged mode.
* \param TypeExtField Type extension field, allows you to configure memory access type, for example strongly ordered, peripheral.
* \param IsShareable Region is shareable between multiple bus masters.
* \param IsCacheable Region is cacheable, i.e. its value may be kept in cache.
* \param IsBufferable Region is bufferable, i.e. using write-back caching. Cacheable but non-bufferable regions use write-through policy.
* \param SubRegionDisable Sub-region disable field.
* \param Size Region size of the region to be configured, for example 4K, 8K.
*/
#define ARM_MPU_RASR(DisableExec, AccessPermission, TypeExtField, IsShareable, IsCacheable, IsBufferable, SubRegionDisable, Size) \
ARM_MPU_RASR_EX(DisableExec, AccessPermission, ARM_MPU_ACCESS_(TypeExtField, IsShareable, IsCacheable, IsBufferable), SubRegionDisable, Size)
/**
* MPU Memory Access Attribute for strongly ordered memory.
* - TEX: 000b
* - Shareable
* - Non-cacheable
* - Non-bufferable
*/
#define ARM_MPU_ACCESS_ORDERED ARM_MPU_ACCESS_(0U, 1U, 0U, 0U)
/**
* MPU Memory Access Attribute for device memory.
* - TEX: 000b (if shareable) or 010b (if non-shareable)
* - Shareable or non-shareable
* - Non-cacheable
* - Bufferable (if shareable) or non-bufferable (if non-shareable)
*
* \param IsShareable Configures the device memory as shareable or non-shareable.
*/
#define ARM_MPU_ACCESS_DEVICE(IsShareable) ((IsShareable) ? ARM_MPU_ACCESS_(0U, 1U, 0U, 1U) : ARM_MPU_ACCESS_(2U, 0U, 0U, 0U))
/**
* MPU Memory Access Attribute for normal memory.
* - TEX: 1BBb (reflecting outer cacheability rules)
* - Shareable or non-shareable
* - Cacheable or non-cacheable (reflecting inner cacheability rules)
* - Bufferable or non-bufferable (reflecting inner cacheability rules)
*
* \param OuterCp Configures the outer cache policy.
* \param InnerCp Configures the inner cache policy.
* \param IsShareable Configures the memory as shareable or non-shareable.
*/
#define ARM_MPU_ACCESS_NORMAL(OuterCp, InnerCp, IsShareable) ARM_MPU_ACCESS_((4U | (OuterCp)), IsShareable, ((InnerCp) >> 1U), ((InnerCp) & 1U))
/**
* MPU Memory Access Attribute non-cacheable policy.
*/
#define ARM_MPU_CACHEP_NOCACHE 0U
/**
* MPU Memory Access Attribute write-back, write and read allocate policy.
*/
#define ARM_MPU_CACHEP_WB_WRA 1U
/**
* MPU Memory Access Attribute write-through, no write allocate policy.
*/
#define ARM_MPU_CACHEP_WT_NWA 2U
/**
* MPU Memory Access Attribute write-back, no write allocate policy.
*/
#define ARM_MPU_CACHEP_WB_NWA 3U
/**
* Struct for a single MPU Region
*/
typedef struct {
uint32_t RBAR; //!< The region base address register value (RBAR)
uint32_t RASR; //!< The region attribute and size register value (RASR) \ref MPU_RASR
} ARM_MPU_Region_t;
/** Enable the MPU.
* \param MPU_Control Default access permissions for unconfigured regions.
*/
__STATIC_INLINE void ARM_MPU_Enable(uint32_t MPU_Control)
{
__DMB();
MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk;
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
#endif
__DSB();
__ISB();
}
/** Disable the MPU.
*/
__STATIC_INLINE void ARM_MPU_Disable(void)
{
__DMB();
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
#endif
MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk;
__DSB();
__ISB();
}
/** Clear and disable the given MPU region.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegion(uint32_t rnr)
{
MPU->RNR = rnr;
MPU->RASR = 0U;
}
/** Configure an MPU region.
* \param rbar Value for RBAR register.
* \param rasr Value for RASR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegion(uint32_t rbar, uint32_t rasr)
{
MPU->RBAR = rbar;
MPU->RASR = rasr;
}
/** Configure the given MPU region.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rasr Value for RASR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegionEx(uint32_t rnr, uint32_t rbar, uint32_t rasr)
{
MPU->RNR = rnr;
MPU->RBAR = rbar;
MPU->RASR = rasr;
}
/** Memcpy with strictly ordered memory access, e.g. used by code in ARM_MPU_Load().
* \param dst Destination data is copied to.
* \param src Source data is copied from.
* \param len Amount of data words to be copied.
*/
__STATIC_INLINE void ARM_MPU_OrderedMemcpy(volatile uint32_t* dst, const uint32_t* __RESTRICT src, uint32_t len)
{
uint32_t i;
for (i = 0U; i < len; ++i)
{
dst[i] = src[i];
}
}
/** Load the given number of MPU regions from a table.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_Load(ARM_MPU_Region_t const* table, uint32_t cnt)
{
const uint32_t rowWordSize = sizeof(ARM_MPU_Region_t)/4U;
while (cnt > MPU_TYPE_RALIASES) {
ARM_MPU_OrderedMemcpy(&(MPU->RBAR), &(table->RBAR), MPU_TYPE_RALIASES*rowWordSize);
table += MPU_TYPE_RALIASES;
cnt -= MPU_TYPE_RALIASES;
}
ARM_MPU_OrderedMemcpy(&(MPU->RBAR), &(table->RBAR), cnt*rowWordSize);
}
#endif
@@ -0,0 +1,352 @@
/******************************************************************************
* @file mpu_armv8.h
* @brief CMSIS MPU API for Armv8-M and Armv8.1-M MPU
* @version V5.1.3
* @date 03. February 2021
******************************************************************************/
/*
* Copyright (c) 2017-2021 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef ARM_MPU_ARMV8_H
#define ARM_MPU_ARMV8_H
/** \brief Attribute for device memory (outer only) */
#define ARM_MPU_ATTR_DEVICE ( 0U )
/** \brief Attribute for non-cacheable, normal memory */
#define ARM_MPU_ATTR_NON_CACHEABLE ( 4U )
/** \brief Attribute for normal memory (outer and inner)
* \param NT Non-Transient: Set to 1 for non-transient data.
* \param WB Write-Back: Set to 1 to use write-back update policy.
* \param RA Read Allocation: Set to 1 to use cache allocation on read miss.
* \param WA Write Allocation: Set to 1 to use cache allocation on write miss.
*/
#define ARM_MPU_ATTR_MEMORY_(NT, WB, RA, WA) \
((((NT) & 1U) << 3U) | (((WB) & 1U) << 2U) | (((RA) & 1U) << 1U) | ((WA) & 1U))
/** \brief Device memory type non Gathering, non Re-ordering, non Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_nGnRnE (0U)
/** \brief Device memory type non Gathering, non Re-ordering, Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_nGnRE (1U)
/** \brief Device memory type non Gathering, Re-ordering, Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_nGRE (2U)
/** \brief Device memory type Gathering, Re-ordering, Early Write Acknowledgement */
#define ARM_MPU_ATTR_DEVICE_GRE (3U)
/** \brief Memory Attribute
* \param O Outer memory attributes
* \param I O == ARM_MPU_ATTR_DEVICE: Device memory attributes, else: Inner memory attributes
*/
#define ARM_MPU_ATTR(O, I) ((((O) & 0xFU) << 4U) | ((((O) & 0xFU) != 0U) ? ((I) & 0xFU) : (((I) & 0x3U) << 2U)))
/** \brief Normal memory non-shareable */
#define ARM_MPU_SH_NON (0U)
/** \brief Normal memory outer shareable */
#define ARM_MPU_SH_OUTER (2U)
/** \brief Normal memory inner shareable */
#define ARM_MPU_SH_INNER (3U)
/** \brief Memory access permissions
* \param RO Read-Only: Set to 1 for read-only memory.
* \param NP Non-Privileged: Set to 1 for non-privileged memory.
*/
#define ARM_MPU_AP_(RO, NP) ((((RO) & 1U) << 1U) | ((NP) & 1U))
/** \brief Region Base Address Register value
* \param BASE The base address bits [31:5] of a memory region. The value is zero extended. Effective address gets 32 byte aligned.
* \param SH Defines the Shareability domain for this memory region.
* \param RO Read-Only: Set to 1 for a read-only memory region.
* \param NP Non-Privileged: Set to 1 for a non-privileged memory region.
* \oaram XN eXecute Never: Set to 1 for a non-executable memory region.
*/
#define ARM_MPU_RBAR(BASE, SH, RO, NP, XN) \
(((BASE) & MPU_RBAR_BASE_Msk) | \
(((SH) << MPU_RBAR_SH_Pos) & MPU_RBAR_SH_Msk) | \
((ARM_MPU_AP_(RO, NP) << MPU_RBAR_AP_Pos) & MPU_RBAR_AP_Msk) | \
(((XN) << MPU_RBAR_XN_Pos) & MPU_RBAR_XN_Msk))
/** \brief Region Limit Address Register value
* \param LIMIT The limit address bits [31:5] for this memory region. The value is one extended.
* \param IDX The attribute index to be associated with this memory region.
*/
#define ARM_MPU_RLAR(LIMIT, IDX) \
(((LIMIT) & MPU_RLAR_LIMIT_Msk) | \
(((IDX) << MPU_RLAR_AttrIndx_Pos) & MPU_RLAR_AttrIndx_Msk) | \
(MPU_RLAR_EN_Msk))
#if defined(MPU_RLAR_PXN_Pos)
/** \brief Region Limit Address Register with PXN value
* \param LIMIT The limit address bits [31:5] for this memory region. The value is one extended.
* \param PXN Privileged execute never. Defines whether code can be executed from this privileged region.
* \param IDX The attribute index to be associated with this memory region.
*/
#define ARM_MPU_RLAR_PXN(LIMIT, PXN, IDX) \
(((LIMIT) & MPU_RLAR_LIMIT_Msk) | \
(((PXN) << MPU_RLAR_PXN_Pos) & MPU_RLAR_PXN_Msk) | \
(((IDX) << MPU_RLAR_AttrIndx_Pos) & MPU_RLAR_AttrIndx_Msk) | \
(MPU_RLAR_EN_Msk))
#endif
/**
* Struct for a single MPU Region
*/
typedef struct {
uint32_t RBAR; /*!< Region Base Address Register value */
uint32_t RLAR; /*!< Region Limit Address Register value */
} ARM_MPU_Region_t;
/** Enable the MPU.
* \param MPU_Control Default access permissions for unconfigured regions.
*/
__STATIC_INLINE void ARM_MPU_Enable(uint32_t MPU_Control)
{
__DMB();
MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk;
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
#endif
__DSB();
__ISB();
}
/** Disable the MPU.
*/
__STATIC_INLINE void ARM_MPU_Disable(void)
{
__DMB();
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
#endif
MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk;
__DSB();
__ISB();
}
#ifdef MPU_NS
/** Enable the Non-secure MPU.
* \param MPU_Control Default access permissions for unconfigured regions.
*/
__STATIC_INLINE void ARM_MPU_Enable_NS(uint32_t MPU_Control)
{
__DMB();
MPU_NS->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk;
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB_NS->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
#endif
__DSB();
__ISB();
}
/** Disable the Non-secure MPU.
*/
__STATIC_INLINE void ARM_MPU_Disable_NS(void)
{
__DMB();
#ifdef SCB_SHCSR_MEMFAULTENA_Msk
SCB_NS->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
#endif
MPU_NS->CTRL &= ~MPU_CTRL_ENABLE_Msk;
__DSB();
__ISB();
}
#endif
/** Set the memory attribute encoding to the given MPU.
* \param mpu Pointer to the MPU to be configured.
* \param idx The attribute index to be set [0-7]
* \param attr The attribute value to be set.
*/
__STATIC_INLINE void ARM_MPU_SetMemAttrEx(MPU_Type* mpu, uint8_t idx, uint8_t attr)
{
const uint8_t reg = idx / 4U;
const uint32_t pos = ((idx % 4U) * 8U);
const uint32_t mask = 0xFFU << pos;
if (reg >= (sizeof(mpu->MAIR) / sizeof(mpu->MAIR[0]))) {
return; // invalid index
}
mpu->MAIR[reg] = ((mpu->MAIR[reg] & ~mask) | ((attr << pos) & mask));
}
/** Set the memory attribute encoding.
* \param idx The attribute index to be set [0-7]
* \param attr The attribute value to be set.
*/
__STATIC_INLINE void ARM_MPU_SetMemAttr(uint8_t idx, uint8_t attr)
{
ARM_MPU_SetMemAttrEx(MPU, idx, attr);
}
#ifdef MPU_NS
/** Set the memory attribute encoding to the Non-secure MPU.
* \param idx The attribute index to be set [0-7]
* \param attr The attribute value to be set.
*/
__STATIC_INLINE void ARM_MPU_SetMemAttr_NS(uint8_t idx, uint8_t attr)
{
ARM_MPU_SetMemAttrEx(MPU_NS, idx, attr);
}
#endif
/** Clear and disable the given MPU region of the given MPU.
* \param mpu Pointer to MPU to be used.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegionEx(MPU_Type* mpu, uint32_t rnr)
{
mpu->RNR = rnr;
mpu->RLAR = 0U;
}
/** Clear and disable the given MPU region.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegion(uint32_t rnr)
{
ARM_MPU_ClrRegionEx(MPU, rnr);
}
#ifdef MPU_NS
/** Clear and disable the given Non-secure MPU region.
* \param rnr Region number to be cleared.
*/
__STATIC_INLINE void ARM_MPU_ClrRegion_NS(uint32_t rnr)
{
ARM_MPU_ClrRegionEx(MPU_NS, rnr);
}
#endif
/** Configure the given MPU region of the given MPU.
* \param mpu Pointer to MPU to be used.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rlar Value for RLAR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegionEx(MPU_Type* mpu, uint32_t rnr, uint32_t rbar, uint32_t rlar)
{
mpu->RNR = rnr;
mpu->RBAR = rbar;
mpu->RLAR = rlar;
}
/** Configure the given MPU region.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rlar Value for RLAR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegion(uint32_t rnr, uint32_t rbar, uint32_t rlar)
{
ARM_MPU_SetRegionEx(MPU, rnr, rbar, rlar);
}
#ifdef MPU_NS
/** Configure the given Non-secure MPU region.
* \param rnr Region number to be configured.
* \param rbar Value for RBAR register.
* \param rlar Value for RLAR register.
*/
__STATIC_INLINE void ARM_MPU_SetRegion_NS(uint32_t rnr, uint32_t rbar, uint32_t rlar)
{
ARM_MPU_SetRegionEx(MPU_NS, rnr, rbar, rlar);
}
#endif
/** Memcpy with strictly ordered memory access, e.g. used by code in ARM_MPU_LoadEx()
* \param dst Destination data is copied to.
* \param src Source data is copied from.
* \param len Amount of data words to be copied.
*/
__STATIC_INLINE void ARM_MPU_OrderedMemcpy(volatile uint32_t* dst, const uint32_t* __RESTRICT src, uint32_t len)
{
uint32_t i;
for (i = 0U; i < len; ++i)
{
dst[i] = src[i];
}
}
/** Load the given number of MPU regions from a table to the given MPU.
* \param mpu Pointer to the MPU registers to be used.
* \param rnr First region number to be configured.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_LoadEx(MPU_Type* mpu, uint32_t rnr, ARM_MPU_Region_t const* table, uint32_t cnt)
{
const uint32_t rowWordSize = sizeof(ARM_MPU_Region_t)/4U;
if (cnt == 1U) {
mpu->RNR = rnr;
ARM_MPU_OrderedMemcpy(&(mpu->RBAR), &(table->RBAR), rowWordSize);
} else {
uint32_t rnrBase = rnr & ~(MPU_TYPE_RALIASES-1U);
uint32_t rnrOffset = rnr % MPU_TYPE_RALIASES;
mpu->RNR = rnrBase;
while ((rnrOffset + cnt) > MPU_TYPE_RALIASES) {
uint32_t c = MPU_TYPE_RALIASES - rnrOffset;
ARM_MPU_OrderedMemcpy(&(mpu->RBAR)+(rnrOffset*2U), &(table->RBAR), c*rowWordSize);
table += c;
cnt -= c;
rnrOffset = 0U;
rnrBase += MPU_TYPE_RALIASES;
mpu->RNR = rnrBase;
}
ARM_MPU_OrderedMemcpy(&(mpu->RBAR)+(rnrOffset*2U), &(table->RBAR), cnt*rowWordSize);
}
}
/** Load the given number of MPU regions from a table.
* \param rnr First region number to be configured.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_Load(uint32_t rnr, ARM_MPU_Region_t const* table, uint32_t cnt)
{
ARM_MPU_LoadEx(MPU, rnr, table, cnt);
}
#ifdef MPU_NS
/** Load the given number of MPU regions from a table to the Non-secure MPU.
* \param rnr First region number to be configured.
* \param table Pointer to the MPU configuration table.
* \param cnt Amount of regions to be configured.
*/
__STATIC_INLINE void ARM_MPU_Load_NS(uint32_t rnr, ARM_MPU_Region_t const* table, uint32_t cnt)
{
ARM_MPU_LoadEx(MPU_NS, rnr, table, cnt);
}
#endif
#endif
@@ -0,0 +1,206 @@
/******************************************************************************
* @file pac_armv81.h
* @brief CMSIS PAC key functions for Armv8.1-M PAC extension
* @version V1.0.0
* @date 23. March 2022
******************************************************************************/
/*
* Copyright (c) 2022 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef PAC_ARMV81_H
#define PAC_ARMV81_H
/* ################### PAC Key functions ########################### */
/**
\ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_PacKeyFunctions PAC Key functions
\brief Functions that access the PAC keys.
@{
*/
#if (defined (__ARM_FEATURE_PAUTH) && (__ARM_FEATURE_PAUTH == 1))
/**
\brief read the PAC key used for privileged mode
\details Reads the PAC key stored in the PAC_KEY_P registers.
\param [out] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __get_PAC_KEY_P (uint32_t* pPacKey) {
__ASM volatile (
"mrs r1, pac_key_p_0\n"
"str r1,[%0,#0]\n"
"mrs r1, pac_key_p_1\n"
"str r1,[%0,#4]\n"
"mrs r1, pac_key_p_2\n"
"str r1,[%0,#8]\n"
"mrs r1, pac_key_p_3\n"
"str r1,[%0,#12]\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
/**
\brief write the PAC key used for privileged mode
\details writes the given PAC key to the PAC_KEY_P registers.
\param [in] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __set_PAC_KEY_P (uint32_t* pPacKey) {
__ASM volatile (
"ldr r1,[%0,#0]\n"
"msr pac_key_p_0, r1\n"
"ldr r1,[%0,#4]\n"
"msr pac_key_p_1, r1\n"
"ldr r1,[%0,#8]\n"
"msr pac_key_p_2, r1\n"
"ldr r1,[%0,#12]\n"
"msr pac_key_p_3, r1\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
/**
\brief read the PAC key used for unprivileged mode
\details Reads the PAC key stored in the PAC_KEY_U registers.
\param [out] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __get_PAC_KEY_U (uint32_t* pPacKey) {
__ASM volatile (
"mrs r1, pac_key_u_0\n"
"str r1,[%0,#0]\n"
"mrs r1, pac_key_u_1\n"
"str r1,[%0,#4]\n"
"mrs r1, pac_key_u_2\n"
"str r1,[%0,#8]\n"
"mrs r1, pac_key_u_3\n"
"str r1,[%0,#12]\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
/**
\brief write the PAC key used for unprivileged mode
\details writes the given PAC key to the PAC_KEY_U registers.
\param [in] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __set_PAC_KEY_U (uint32_t* pPacKey) {
__ASM volatile (
"ldr r1,[%0,#0]\n"
"msr pac_key_u_0, r1\n"
"ldr r1,[%0,#4]\n"
"msr pac_key_u_1, r1\n"
"ldr r1,[%0,#8]\n"
"msr pac_key_u_2, r1\n"
"ldr r1,[%0,#12]\n"
"msr pac_key_u_3, r1\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
#if (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3))
/**
\brief read the PAC key used for privileged mode (non-secure)
\details Reads the PAC key stored in the non-secure PAC_KEY_P registers when in secure mode.
\param [out] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __TZ_get_PAC_KEY_P_NS (uint32_t* pPacKey) {
__ASM volatile (
"mrs r1, pac_key_p_0_ns\n"
"str r1,[%0,#0]\n"
"mrs r1, pac_key_p_1_ns\n"
"str r1,[%0,#4]\n"
"mrs r1, pac_key_p_2_ns\n"
"str r1,[%0,#8]\n"
"mrs r1, pac_key_p_3_ns\n"
"str r1,[%0,#12]\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
/**
\brief write the PAC key used for privileged mode (non-secure)
\details writes the given PAC key to the non-secure PAC_KEY_P registers when in secure mode.
\param [in] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __TZ_set_PAC_KEY_P_NS (uint32_t* pPacKey) {
__ASM volatile (
"ldr r1,[%0,#0]\n"
"msr pac_key_p_0_ns, r1\n"
"ldr r1,[%0,#4]\n"
"msr pac_key_p_1_ns, r1\n"
"ldr r1,[%0,#8]\n"
"msr pac_key_p_2_ns, r1\n"
"ldr r1,[%0,#12]\n"
"msr pac_key_p_3_ns, r1\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
/**
\brief read the PAC key used for unprivileged mode (non-secure)
\details Reads the PAC key stored in the non-secure PAC_KEY_U registers when in secure mode.
\param [out] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __TZ_get_PAC_KEY_U_NS (uint32_t* pPacKey) {
__ASM volatile (
"mrs r1, pac_key_u_0_ns\n"
"str r1,[%0,#0]\n"
"mrs r1, pac_key_u_1_ns\n"
"str r1,[%0,#4]\n"
"mrs r1, pac_key_u_2_ns\n"
"str r1,[%0,#8]\n"
"mrs r1, pac_key_u_3_ns\n"
"str r1,[%0,#12]\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
/**
\brief write the PAC key used for unprivileged mode (non-secure)
\details writes the given PAC key to the non-secure PAC_KEY_U registers when in secure mode.
\param [in] pPacKey 128bit PAC key
*/
__STATIC_FORCEINLINE void __TZ_set_PAC_KEY_U_NS (uint32_t* pPacKey) {
__ASM volatile (
"ldr r1,[%0,#0]\n"
"msr pac_key_u_0_ns, r1\n"
"ldr r1,[%0,#4]\n"
"msr pac_key_u_1_ns, r1\n"
"ldr r1,[%0,#8]\n"
"msr pac_key_u_2_ns, r1\n"
"ldr r1,[%0,#12]\n"
"msr pac_key_u_3_ns, r1\n"
: : "r" (pPacKey) : "memory", "r1"
);
}
#endif /* (defined (__ARM_FEATURE_CMSE ) && (__ARM_FEATURE_CMSE == 3)) */
#endif /* (defined (__ARM_FEATURE_PAUTH) && (__ARM_FEATURE_PAUTH == 1)) */
/*@} end of CMSIS_Core_PacKeyFunctions */
#endif /* PAC_ARMV81_H */
@@ -0,0 +1,337 @@
/******************************************************************************
* @file pmu_armv8.h
* @brief CMSIS PMU API for Armv8.1-M PMU
* @version V1.0.1
* @date 15. April 2020
******************************************************************************/
/*
* Copyright (c) 2020 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef ARM_PMU_ARMV8_H
#define ARM_PMU_ARMV8_H
/**
* \brief PMU Events
* \note See the Armv8.1-M Architecture Reference Manual for full details on these PMU events.
* */
#define ARM_PMU_SW_INCR 0x0000 /*!< Software update to the PMU_SWINC register, architecturally executed and condition code check pass */
#define ARM_PMU_L1I_CACHE_REFILL 0x0001 /*!< L1 I-Cache refill */
#define ARM_PMU_L1D_CACHE_REFILL 0x0003 /*!< L1 D-Cache refill */
#define ARM_PMU_L1D_CACHE 0x0004 /*!< L1 D-Cache access */
#define ARM_PMU_LD_RETIRED 0x0006 /*!< Memory-reading instruction architecturally executed and condition code check pass */
#define ARM_PMU_ST_RETIRED 0x0007 /*!< Memory-writing instruction architecturally executed and condition code check pass */
#define ARM_PMU_INST_RETIRED 0x0008 /*!< Instruction architecturally executed */
#define ARM_PMU_EXC_TAKEN 0x0009 /*!< Exception entry */
#define ARM_PMU_EXC_RETURN 0x000A /*!< Exception return instruction architecturally executed and the condition code check pass */
#define ARM_PMU_PC_WRITE_RETIRED 0x000C /*!< Software change to the Program Counter (PC). Instruction is architecturally executed and condition code check pass */
#define ARM_PMU_BR_IMMED_RETIRED 0x000D /*!< Immediate branch architecturally executed */
#define ARM_PMU_BR_RETURN_RETIRED 0x000E /*!< Function return instruction architecturally executed and the condition code check pass */
#define ARM_PMU_UNALIGNED_LDST_RETIRED 0x000F /*!< Unaligned memory memory-reading or memory-writing instruction architecturally executed and condition code check pass */
#define ARM_PMU_BR_MIS_PRED 0x0010 /*!< Mispredicted or not predicted branch speculatively executed */
#define ARM_PMU_CPU_CYCLES 0x0011 /*!< Cycle */
#define ARM_PMU_BR_PRED 0x0012 /*!< Predictable branch speculatively executed */
#define ARM_PMU_MEM_ACCESS 0x0013 /*!< Data memory access */
#define ARM_PMU_L1I_CACHE 0x0014 /*!< Level 1 instruction cache access */
#define ARM_PMU_L1D_CACHE_WB 0x0015 /*!< Level 1 data cache write-back */
#define ARM_PMU_L2D_CACHE 0x0016 /*!< Level 2 data cache access */
#define ARM_PMU_L2D_CACHE_REFILL 0x0017 /*!< Level 2 data cache refill */
#define ARM_PMU_L2D_CACHE_WB 0x0018 /*!< Level 2 data cache write-back */
#define ARM_PMU_BUS_ACCESS 0x0019 /*!< Bus access */
#define ARM_PMU_MEMORY_ERROR 0x001A /*!< Local memory error */
#define ARM_PMU_INST_SPEC 0x001B /*!< Instruction speculatively executed */
#define ARM_PMU_BUS_CYCLES 0x001D /*!< Bus cycles */
#define ARM_PMU_CHAIN 0x001E /*!< For an odd numbered counter, increment when an overflow occurs on the preceding even-numbered counter on the same PE */
#define ARM_PMU_L1D_CACHE_ALLOCATE 0x001F /*!< Level 1 data cache allocation without refill */
#define ARM_PMU_L2D_CACHE_ALLOCATE 0x0020 /*!< Level 2 data cache allocation without refill */
#define ARM_PMU_BR_RETIRED 0x0021 /*!< Branch instruction architecturally executed */
#define ARM_PMU_BR_MIS_PRED_RETIRED 0x0022 /*!< Mispredicted branch instruction architecturally executed */
#define ARM_PMU_STALL_FRONTEND 0x0023 /*!< No operation issued because of the frontend */
#define ARM_PMU_STALL_BACKEND 0x0024 /*!< No operation issued because of the backend */
#define ARM_PMU_L2I_CACHE 0x0027 /*!< Level 2 instruction cache access */
#define ARM_PMU_L2I_CACHE_REFILL 0x0028 /*!< Level 2 instruction cache refill */
#define ARM_PMU_L3D_CACHE_ALLOCATE 0x0029 /*!< Level 3 data cache allocation without refill */
#define ARM_PMU_L3D_CACHE_REFILL 0x002A /*!< Level 3 data cache refill */
#define ARM_PMU_L3D_CACHE 0x002B /*!< Level 3 data cache access */
#define ARM_PMU_L3D_CACHE_WB 0x002C /*!< Level 3 data cache write-back */
#define ARM_PMU_LL_CACHE_RD 0x0036 /*!< Last level data cache read */
#define ARM_PMU_LL_CACHE_MISS_RD 0x0037 /*!< Last level data cache read miss */
#define ARM_PMU_L1D_CACHE_MISS_RD 0x0039 /*!< Level 1 data cache read miss */
#define ARM_PMU_OP_COMPLETE 0x003A /*!< Operation retired */
#define ARM_PMU_OP_SPEC 0x003B /*!< Operation speculatively executed */
#define ARM_PMU_STALL 0x003C /*!< Stall cycle for instruction or operation not sent for execution */
#define ARM_PMU_STALL_OP_BACKEND 0x003D /*!< Stall cycle for instruction or operation not sent for execution due to pipeline backend */
#define ARM_PMU_STALL_OP_FRONTEND 0x003E /*!< Stall cycle for instruction or operation not sent for execution due to pipeline frontend */
#define ARM_PMU_STALL_OP 0x003F /*!< Instruction or operation slots not occupied each cycle */
#define ARM_PMU_L1D_CACHE_RD 0x0040 /*!< Level 1 data cache read */
#define ARM_PMU_LE_RETIRED 0x0100 /*!< Loop end instruction executed */
#define ARM_PMU_LE_SPEC 0x0101 /*!< Loop end instruction speculatively executed */
#define ARM_PMU_BF_RETIRED 0x0104 /*!< Branch future instruction architecturally executed and condition code check pass */
#define ARM_PMU_BF_SPEC 0x0105 /*!< Branch future instruction speculatively executed and condition code check pass */
#define ARM_PMU_LE_CANCEL 0x0108 /*!< Loop end instruction not taken */
#define ARM_PMU_BF_CANCEL 0x0109 /*!< Branch future instruction not taken */
#define ARM_PMU_SE_CALL_S 0x0114 /*!< Call to secure function, resulting in Security state change */
#define ARM_PMU_SE_CALL_NS 0x0115 /*!< Call to non-secure function, resulting in Security state change */
#define ARM_PMU_DWT_CMPMATCH0 0x0118 /*!< DWT comparator 0 match */
#define ARM_PMU_DWT_CMPMATCH1 0x0119 /*!< DWT comparator 1 match */
#define ARM_PMU_DWT_CMPMATCH2 0x011A /*!< DWT comparator 2 match */
#define ARM_PMU_DWT_CMPMATCH3 0x011B /*!< DWT comparator 3 match */
#define ARM_PMU_MVE_INST_RETIRED 0x0200 /*!< MVE instruction architecturally executed */
#define ARM_PMU_MVE_INST_SPEC 0x0201 /*!< MVE instruction speculatively executed */
#define ARM_PMU_MVE_FP_RETIRED 0x0204 /*!< MVE floating-point instruction architecturally executed */
#define ARM_PMU_MVE_FP_SPEC 0x0205 /*!< MVE floating-point instruction speculatively executed */
#define ARM_PMU_MVE_FP_HP_RETIRED 0x0208 /*!< MVE half-precision floating-point instruction architecturally executed */
#define ARM_PMU_MVE_FP_HP_SPEC 0x0209 /*!< MVE half-precision floating-point instruction speculatively executed */
#define ARM_PMU_MVE_FP_SP_RETIRED 0x020C /*!< MVE single-precision floating-point instruction architecturally executed */
#define ARM_PMU_MVE_FP_SP_SPEC 0x020D /*!< MVE single-precision floating-point instruction speculatively executed */
#define ARM_PMU_MVE_FP_MAC_RETIRED 0x0214 /*!< MVE floating-point multiply or multiply-accumulate instruction architecturally executed */
#define ARM_PMU_MVE_FP_MAC_SPEC 0x0215 /*!< MVE floating-point multiply or multiply-accumulate instruction speculatively executed */
#define ARM_PMU_MVE_INT_RETIRED 0x0224 /*!< MVE integer instruction architecturally executed */
#define ARM_PMU_MVE_INT_SPEC 0x0225 /*!< MVE integer instruction speculatively executed */
#define ARM_PMU_MVE_INT_MAC_RETIRED 0x0228 /*!< MVE multiply or multiply-accumulate instruction architecturally executed */
#define ARM_PMU_MVE_INT_MAC_SPEC 0x0229 /*!< MVE multiply or multiply-accumulate instruction speculatively executed */
#define ARM_PMU_MVE_LDST_RETIRED 0x0238 /*!< MVE load or store instruction architecturally executed */
#define ARM_PMU_MVE_LDST_SPEC 0x0239 /*!< MVE load or store instruction speculatively executed */
#define ARM_PMU_MVE_LD_RETIRED 0x023C /*!< MVE load instruction architecturally executed */
#define ARM_PMU_MVE_LD_SPEC 0x023D /*!< MVE load instruction speculatively executed */
#define ARM_PMU_MVE_ST_RETIRED 0x0240 /*!< MVE store instruction architecturally executed */
#define ARM_PMU_MVE_ST_SPEC 0x0241 /*!< MVE store instruction speculatively executed */
#define ARM_PMU_MVE_LDST_CONTIG_RETIRED 0x0244 /*!< MVE contiguous load or store instruction architecturally executed */
#define ARM_PMU_MVE_LDST_CONTIG_SPEC 0x0245 /*!< MVE contiguous load or store instruction speculatively executed */
#define ARM_PMU_MVE_LD_CONTIG_RETIRED 0x0248 /*!< MVE contiguous load instruction architecturally executed */
#define ARM_PMU_MVE_LD_CONTIG_SPEC 0x0249 /*!< MVE contiguous load instruction speculatively executed */
#define ARM_PMU_MVE_ST_CONTIG_RETIRED 0x024C /*!< MVE contiguous store instruction architecturally executed */
#define ARM_PMU_MVE_ST_CONTIG_SPEC 0x024D /*!< MVE contiguous store instruction speculatively executed */
#define ARM_PMU_MVE_LDST_NONCONTIG_RETIRED 0x0250 /*!< MVE non-contiguous load or store instruction architecturally executed */
#define ARM_PMU_MVE_LDST_NONCONTIG_SPEC 0x0251 /*!< MVE non-contiguous load or store instruction speculatively executed */
#define ARM_PMU_MVE_LD_NONCONTIG_RETIRED 0x0254 /*!< MVE non-contiguous load instruction architecturally executed */
#define ARM_PMU_MVE_LD_NONCONTIG_SPEC 0x0255 /*!< MVE non-contiguous load instruction speculatively executed */
#define ARM_PMU_MVE_ST_NONCONTIG_RETIRED 0x0258 /*!< MVE non-contiguous store instruction architecturally executed */
#define ARM_PMU_MVE_ST_NONCONTIG_SPEC 0x0259 /*!< MVE non-contiguous store instruction speculatively executed */
#define ARM_PMU_MVE_LDST_MULTI_RETIRED 0x025C /*!< MVE memory instruction targeting multiple registers architecturally executed */
#define ARM_PMU_MVE_LDST_MULTI_SPEC 0x025D /*!< MVE memory instruction targeting multiple registers speculatively executed */
#define ARM_PMU_MVE_LD_MULTI_RETIRED 0x0260 /*!< MVE memory load instruction targeting multiple registers architecturally executed */
#define ARM_PMU_MVE_LD_MULTI_SPEC 0x0261 /*!< MVE memory load instruction targeting multiple registers speculatively executed */
#define ARM_PMU_MVE_ST_MULTI_RETIRED 0x0261 /*!< MVE memory store instruction targeting multiple registers architecturally executed */
#define ARM_PMU_MVE_ST_MULTI_SPEC 0x0265 /*!< MVE memory store instruction targeting multiple registers speculatively executed */
#define ARM_PMU_MVE_LDST_UNALIGNED_RETIRED 0x028C /*!< MVE unaligned memory load or store instruction architecturally executed */
#define ARM_PMU_MVE_LDST_UNALIGNED_SPEC 0x028D /*!< MVE unaligned memory load or store instruction speculatively executed */
#define ARM_PMU_MVE_LD_UNALIGNED_RETIRED 0x0290 /*!< MVE unaligned load instruction architecturally executed */
#define ARM_PMU_MVE_LD_UNALIGNED_SPEC 0x0291 /*!< MVE unaligned load instruction speculatively executed */
#define ARM_PMU_MVE_ST_UNALIGNED_RETIRED 0x0294 /*!< MVE unaligned store instruction architecturally executed */
#define ARM_PMU_MVE_ST_UNALIGNED_SPEC 0x0295 /*!< MVE unaligned store instruction speculatively executed */
#define ARM_PMU_MVE_LDST_UNALIGNED_NONCONTIG_RETIRED 0x0298 /*!< MVE unaligned noncontiguous load or store instruction architecturally executed */
#define ARM_PMU_MVE_LDST_UNALIGNED_NONCONTIG_SPEC 0x0299 /*!< MVE unaligned noncontiguous load or store instruction speculatively executed */
#define ARM_PMU_MVE_VREDUCE_RETIRED 0x02A0 /*!< MVE vector reduction instruction architecturally executed */
#define ARM_PMU_MVE_VREDUCE_SPEC 0x02A1 /*!< MVE vector reduction instruction speculatively executed */
#define ARM_PMU_MVE_VREDUCE_FP_RETIRED 0x02A4 /*!< MVE floating-point vector reduction instruction architecturally executed */
#define ARM_PMU_MVE_VREDUCE_FP_SPEC 0x02A5 /*!< MVE floating-point vector reduction instruction speculatively executed */
#define ARM_PMU_MVE_VREDUCE_INT_RETIRED 0x02A8 /*!< MVE integer vector reduction instruction architecturally executed */
#define ARM_PMU_MVE_VREDUCE_INT_SPEC 0x02A9 /*!< MVE integer vector reduction instruction speculatively executed */
#define ARM_PMU_MVE_PRED 0x02B8 /*!< Cycles where one or more predicated beats architecturally executed */
#define ARM_PMU_MVE_STALL 0x02CC /*!< Stall cycles caused by an MVE instruction */
#define ARM_PMU_MVE_STALL_RESOURCE 0x02CD /*!< Stall cycles caused by an MVE instruction because of resource conflicts */
#define ARM_PMU_MVE_STALL_RESOURCE_MEM 0x02CE /*!< Stall cycles caused by an MVE instruction because of memory resource conflicts */
#define ARM_PMU_MVE_STALL_RESOURCE_FP 0x02CF /*!< Stall cycles caused by an MVE instruction because of floating-point resource conflicts */
#define ARM_PMU_MVE_STALL_RESOURCE_INT 0x02D0 /*!< Stall cycles caused by an MVE instruction because of integer resource conflicts */
#define ARM_PMU_MVE_STALL_BREAK 0x02D3 /*!< Stall cycles caused by an MVE chain break */
#define ARM_PMU_MVE_STALL_DEPENDENCY 0x02D4 /*!< Stall cycles caused by MVE register dependency */
#define ARM_PMU_ITCM_ACCESS 0x4007 /*!< Instruction TCM access */
#define ARM_PMU_DTCM_ACCESS 0x4008 /*!< Data TCM access */
#define ARM_PMU_TRCEXTOUT0 0x4010 /*!< ETM external output 0 */
#define ARM_PMU_TRCEXTOUT1 0x4011 /*!< ETM external output 1 */
#define ARM_PMU_TRCEXTOUT2 0x4012 /*!< ETM external output 2 */
#define ARM_PMU_TRCEXTOUT3 0x4013 /*!< ETM external output 3 */
#define ARM_PMU_CTI_TRIGOUT4 0x4018 /*!< Cross-trigger Interface output trigger 4 */
#define ARM_PMU_CTI_TRIGOUT5 0x4019 /*!< Cross-trigger Interface output trigger 5 */
#define ARM_PMU_CTI_TRIGOUT6 0x401A /*!< Cross-trigger Interface output trigger 6 */
#define ARM_PMU_CTI_TRIGOUT7 0x401B /*!< Cross-trigger Interface output trigger 7 */
/** \brief PMU Functions */
__STATIC_INLINE void ARM_PMU_Enable(void);
__STATIC_INLINE void ARM_PMU_Disable(void);
__STATIC_INLINE void ARM_PMU_Set_EVTYPER(uint32_t num, uint32_t type);
__STATIC_INLINE void ARM_PMU_CYCCNT_Reset(void);
__STATIC_INLINE void ARM_PMU_EVCNTR_ALL_Reset(void);
__STATIC_INLINE void ARM_PMU_CNTR_Enable(uint32_t mask);
__STATIC_INLINE void ARM_PMU_CNTR_Disable(uint32_t mask);
__STATIC_INLINE uint32_t ARM_PMU_Get_CCNTR(void);
__STATIC_INLINE uint32_t ARM_PMU_Get_EVCNTR(uint32_t num);
__STATIC_INLINE uint32_t ARM_PMU_Get_CNTR_OVS(void);
__STATIC_INLINE void ARM_PMU_Set_CNTR_OVS(uint32_t mask);
__STATIC_INLINE void ARM_PMU_Set_CNTR_IRQ_Enable(uint32_t mask);
__STATIC_INLINE void ARM_PMU_Set_CNTR_IRQ_Disable(uint32_t mask);
__STATIC_INLINE void ARM_PMU_CNTR_Increment(uint32_t mask);
/**
\brief Enable the PMU
*/
__STATIC_INLINE void ARM_PMU_Enable(void)
{
PMU->CTRL |= PMU_CTRL_ENABLE_Msk;
}
/**
\brief Disable the PMU
*/
__STATIC_INLINE void ARM_PMU_Disable(void)
{
PMU->CTRL &= ~PMU_CTRL_ENABLE_Msk;
}
/**
\brief Set event to count for PMU eventer counter
\param [in] num Event counter (0-30) to configure
\param [in] type Event to count
*/
__STATIC_INLINE void ARM_PMU_Set_EVTYPER(uint32_t num, uint32_t type)
{
PMU->EVTYPER[num] = type;
}
/**
\brief Reset cycle counter
*/
__STATIC_INLINE void ARM_PMU_CYCCNT_Reset(void)
{
PMU->CTRL |= PMU_CTRL_CYCCNT_RESET_Msk;
}
/**
\brief Reset all event counters
*/
__STATIC_INLINE void ARM_PMU_EVCNTR_ALL_Reset(void)
{
PMU->CTRL |= PMU_CTRL_EVENTCNT_RESET_Msk;
}
/**
\brief Enable counters
\param [in] mask Counters to enable
\note Enables one or more of the following:
- event counters (0-30)
- cycle counter
*/
__STATIC_INLINE void ARM_PMU_CNTR_Enable(uint32_t mask)
{
PMU->CNTENSET = mask;
}
/**
\brief Disable counters
\param [in] mask Counters to enable
\note Disables one or more of the following:
- event counters (0-30)
- cycle counter
*/
__STATIC_INLINE void ARM_PMU_CNTR_Disable(uint32_t mask)
{
PMU->CNTENCLR = mask;
}
/**
\brief Read cycle counter
\return Cycle count
*/
__STATIC_INLINE uint32_t ARM_PMU_Get_CCNTR(void)
{
return PMU->CCNTR;
}
/**
\brief Read event counter
\param [in] num Event counter (0-30) to read
\return Event count
*/
__STATIC_INLINE uint32_t ARM_PMU_Get_EVCNTR(uint32_t num)
{
return PMU_EVCNTR_CNT_Msk & PMU->EVCNTR[num];
}
/**
\brief Read counter overflow status
\return Counter overflow status bits for the following:
- event counters (0-30)
- cycle counter
*/
__STATIC_INLINE uint32_t ARM_PMU_Get_CNTR_OVS(void)
{
return PMU->OVSSET;
}
/**
\brief Clear counter overflow status
\param [in] mask Counter overflow status bits to clear
\note Clears overflow status bits for one or more of the following:
- event counters (0-30)
- cycle counter
*/
__STATIC_INLINE void ARM_PMU_Set_CNTR_OVS(uint32_t mask)
{
PMU->OVSCLR = mask;
}
/**
\brief Enable counter overflow interrupt request
\param [in] mask Counter overflow interrupt request bits to set
\note Sets overflow interrupt request bits for one or more of the following:
- event counters (0-30)
- cycle counter
*/
__STATIC_INLINE void ARM_PMU_Set_CNTR_IRQ_Enable(uint32_t mask)
{
PMU->INTENSET = mask;
}
/**
\brief Disable counter overflow interrupt request
\param [in] mask Counter overflow interrupt request bits to clear
\note Clears overflow interrupt request bits for one or more of the following:
- event counters (0-30)
- cycle counter
*/
__STATIC_INLINE void ARM_PMU_Set_CNTR_IRQ_Disable(uint32_t mask)
{
PMU->INTENCLR = mask;
}
/**
\brief Software increment event counter
\param [in] mask Counters to increment
\note Software increment bits for one or more event counters (0-30)
*/
__STATIC_INLINE void ARM_PMU_CNTR_Increment(uint32_t mask)
{
PMU->SWINC = mask;
}
#endif
@@ -0,0 +1,70 @@
/******************************************************************************
* @file tz_context.h
* @brief Context Management for Armv8-M TrustZone
* @version V1.0.1
* @date 10. January 2018
******************************************************************************/
/*
* Copyright (c) 2017-2018 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#elif defined (__clang__)
#pragma clang system_header /* treat file as system include file */
#endif
#ifndef TZ_CONTEXT_H
#define TZ_CONTEXT_H
#include <stdint.h>
#ifndef TZ_MODULEID_T
#define TZ_MODULEID_T
/// \details Data type that identifies secure software modules called by a process.
typedef uint32_t TZ_ModuleId_t;
#endif
/// \details TZ Memory ID identifies an allocated memory slot.
typedef uint32_t TZ_MemoryId_t;
/// Initialize secure context memory system
/// \return execution status (1: success, 0: error)
uint32_t TZ_InitContextSystem_S (void);
/// Allocate context memory for calling secure software modules in TrustZone
/// \param[in] module identifies software modules called from non-secure mode
/// \return value != 0 id TrustZone memory slot identifier
/// \return value 0 no memory available or internal error
TZ_MemoryId_t TZ_AllocModuleContext_S (TZ_ModuleId_t module);
/// Free context memory that was previously allocated with \ref TZ_AllocModuleContext_S
/// \param[in] id TrustZone memory slot identifier
/// \return execution status (1: success, 0: error)
uint32_t TZ_FreeModuleContext_S (TZ_MemoryId_t id);
/// Load secure context (called on RTOS thread context switch)
/// \param[in] id TrustZone memory slot identifier
/// \return execution status (1: success, 0: error)
uint32_t TZ_LoadContext_S (TZ_MemoryId_t id);
/// Store secure context (called on RTOS thread context switch)
/// \param[in] id TrustZone memory slot identifier
/// \return execution status (1: success, 0: error)
uint32_t TZ_StoreContext_S (TZ_MemoryId_t id);
#endif // TZ_CONTEXT_H
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more