Merge branch 'fz-dev' into dev

This commit is contained in:
MX
2022-08-03 21:09:13 +03:00
102 changed files with 2340 additions and 354 deletions

4
.vscode/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
./c_cpp_properties.json
./launch.json
./settings.json
./tasks.json

32
.vscode/example/c_cpp_properties.json vendored Normal file
View File

@@ -0,0 +1,32 @@
{
"configurations": [
{
"name": "Win32",
"compilerPath": "${workspaceFolder}/toolchain/i686-windows/bin/arm-none-eabi-gcc.exe",
"intelliSenseMode": "gcc-arm",
"compileCommands": "${workspaceFolder}/build/latest/compile_commands.json",
"configurationProvider": "ms-vscode.cpptools",
"cStandard": "gnu17",
"cppStandard": "c++17"
},
{
"name": "Linux",
"compilerPath": "${workspaceFolder}/toolchain/x86_64-linux/bin/arm-none-eabi-gcc",
"intelliSenseMode": "gcc-arm",
"compileCommands": "${workspaceFolder}/build/latest/compile_commands.json",
"configurationProvider": "ms-vscode.cpptools",
"cStandard": "gnu17",
"cppStandard": "c++17"
},
{
"name": "Mac",
"compilerPath": "${workspaceFolder}/toolchain/x86_64-darwin/bin/arm-none-eabi-gcc",
"intelliSenseMode": "gcc-arm",
"compileCommands": "${workspaceFolder}/build/latest/compile_commands.json",
"configurationProvider": "ms-vscode.cpptools",
"cStandard": "gnu17",
"cppStandard": "c++17"
}
],
"version": 4
}

87
.vscode/example/launch.json vendored Normal file
View File

@@ -0,0 +1,87 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"inputs": [
{
"id": "BLACKMAGIC",
"type": "command",
"command": "shellCommand.execute",
"args": {
"command": "./fbt get_blackmagic",
"description": "Get Blackmagic device",
}
}
],
"configurations": [
{
"name": "Attach FW (ST-Link)",
"cwd": "${workspaceFolder}",
"executable": "./build/latest/firmware.elf",
"request": "attach",
"type": "cortex-debug",
"servertype": "openocd",
"device": "stlink",
"svdFile": "./debug/STM32WB55_CM4.svd",
"rtos": "FreeRTOS",
"configFiles": [
"interface/stlink.cfg",
"./debug/stm32wbx.cfg",
],
"postAttachCommands": [
// "attach 1",
"compare-sections",
]
// "showDevDebugOutput": "raw",
},
{
"name": "Attach FW (blackmagic)",
"cwd": "${workspaceFolder}",
"executable": "./build/latest/firmware.elf",
"request": "attach",
"type": "cortex-debug",
"servertype": "external",
"gdbTarget": "${input:BLACKMAGIC}",
"svdFile": "./debug/STM32WB55_CM4.svd",
"rtos": "FreeRTOS",
"postAttachCommands": [
"monitor swdp_scan",
"attach 1",
"set confirm off",
"set mem inaccessible-by-default off",
"compare-sections",
]
// "showDevDebugOutput": "raw",
},
{
"name": "Attach FW (JLink)",
"cwd": "${workspaceFolder}",
"executable": "./build/latest/firmware.elf",
"request": "attach",
"type": "cortex-debug",
"servertype": "jlink",
"interface": "swd",
"device": "STM32WB55RG",
"svdFile": "./debug/STM32WB55_CM4.svd",
"rtos": "FreeRTOS",
// "showDevDebugOutput": "raw",
},
{
"name": "fbt debug",
"type": "python",
"request": "launch",
"program": "./lib/scons/scripts/scons.py",
"args": [
"sdk"
]
},
{
"name": "python debug",
"type": "python",
"request": "launch",
"program": "${file}",
"args": []
}
]
}

22
.vscode/example/settings.json vendored Normal file
View File

@@ -0,0 +1,22 @@
{
"C_Cpp.default.cStandard": "gnu17",
"C_Cpp.default.cppStandard": "c++17",
"python.formatting.provider": "black",
"workbench.tree.indent": 12,
"cortex-debug.enableTelemetry": false,
"cortex-debug.variableUseNaturalFormat": true,
"cortex-debug.showRTOS": true,
"cortex-debug.armToolchainPath.windows": "${workspaceFolder}/toolchain/i686-windows/bin",
"cortex-debug.armToolchainPath.linux": "${workspaceFolder}/toolchain/x86_64-linux/bin",
"cortex-debug.armToolchainPath.osx": "${workspaceFolder}/toolchain/x86_64-darwin/bin",
"cortex-debug.openocdPath.windows": "${workspaceFolder}/toolchain/i686-windows/openocd/bin/openocd.exe",
"cortex-debug.openocdPath.linux": "${workspaceFolder}/toolchain/x86_64-linux/openocd/bin/openocd",
"cortex-debug.openocdPath.osx": "${workspaceFolder}/toolchain/x86_64-darwin/openocd/bin/openocd",
"editor.formatOnSave": true,
"files.associations": {
"*.scons": "python",
"SConscript": "python",
"SConstruct": "python",
"*.fam": "python",
}
}

103
.vscode/example/tasks.json vendored Normal file
View File

@@ -0,0 +1,103 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "[Release] Build",
"group": "build",
"type": "shell",
"command": "./fbt COMPACT=1 DEBUG=0"
},
{
"label": "[Debug] Build",
"group": "build",
"type": "shell",
"command": "./fbt"
},
{
"label": "[Release] Flash (ST-Link)",
"group": "build",
"type": "shell",
"command": "./fbt COMPACT=1 DEBUG=0 FORCE=1 flash"
},
{
"label": "[Debug] Flash (ST-Link)",
"group": "build",
"type": "shell",
"command": "./fbt FORCE=1 flash"
},
{
"label": "[Release] Flash (blackmagic)",
"group": "build",
"type": "shell",
"command": "./fbt COMPACT=1 DEBUG=0 FORCE=1 flash_blackmagic"
},
{
"label": "[Debug] Flash (blackmagic)",
"group": "build",
"type": "shell",
"command": "./fbt FORCE=1 flash_blackmagic"
},
{
"label": "[Release] Flash (JLink)",
"group": "build",
"type": "shell",
"command": "./fbt COMPACT=1 DEBUG=0 FORCE=1 jflash"
},
{
"label": "[Debug] Flash (JLink)",
"group": "build",
"type": "shell",
"command": "./fbt FORCE=1 jflash"
},
{
"label": "[Release] Build update bundle",
"group": "build",
"type": "shell",
"command": "./fbt update_package COMPACT=1 DEBUG=0"
},
{
"label": "[Debug] Build update bundle",
"group": "build",
"type": "shell",
"command": "./fbt update_package"
},
{
"label": "[Release] Build updater",
"group": "build",
"type": "shell",
"command": "./fbt updater_all COMPACT=1 DEBUG=0"
},
{
"label": "[Debug] Build updater",
"group": "build",
"type": "shell",
"command": "./fbt updater_all"
},
{
"label": "[Debug] Flash (USB, w/o resources)",
"group": "build",
"type": "shell",
"command": "./fbt FORCE=1 flash_usb"
},
{
"label": "[Release] Flash (USB, w/o resources)",
"group": "build",
"type": "shell",
"command": "./fbt COMPACT=1 DEBUG=0 FORCE=1 flash_usb"
},
{
"label": "[Debug:unit_tests] Flash (USB)",
"group": "build",
"type": "shell",
"command": "./fbt FIRMWARE_APP_SET=unit_tests FORCE=1 flash_usb"
},
{
"label": "[Release] Flash (USB, with resources)",
"group": "build",
"type": "shell",
"command": "./fbt COMPACT=1 DEBUG=0 FORCE=1 flash_usb_full"
},
]
}

15
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
// List of extensions which should be recommended for users of this workspace.
"recommendations": [
"ms-python.black-formatter",
"ms-vscode.cpptools",
"amiralizadeh9480.cpp-helper",
"marus25.cortex-debug",
"zxh404.vscode-proto3",
"augustocdias.tasks-shell-input"
],
// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
"unwantedRecommendations": []
}

View File

@@ -274,8 +274,13 @@ distenv.PhonyTarget("cli", "${PYTHON3} scripts/serial_cli.py")
# Find blackmagic probe # Find blackmagic probe
distenv.PhonyTarget( distenv.PhonyTarget(
"get_blackmagic", "get_blackmagic",
"@echo $( ${BLACKMAGIC_ADDR} $)", "@echo $( ${BLACKMAGIC_ADDR} $)",
) )
# Prepare vscode environment
vscode_dist = distenv.Install("#.vscode", distenv.Glob("#.vscode/example/*"))
distenv.Precious(vscode_dist)
distenv.NoClean(vscode_dist)
distenv.Alias("vscode_dist", vscode_dist)

View File

@@ -45,7 +45,7 @@ static DialogMessageButton compliance_screen(DialogsApp* dialogs, DialogMessage*
DialogMessageButton result; DialogMessageButton result;
const char* screen_text = "For all compliance\n" const char* screen_text = "For all compliance\n"
"certificates please visit\n" "certificates please visit:\n"
"www.flipp.dev/compliance"; "www.flipp.dev/compliance";
dialog_message_set_text(message, screen_text, 0, 0, AlignLeft, AlignTop); dialog_message_set_text(message, screen_text, 0, 0, AlignLeft, AlignTop);
@@ -122,13 +122,13 @@ static DialogMessageButton hw_version_screen(DialogsApp* dialogs, DialogMessage*
furi_hal_version_get_hw_region_name(), furi_hal_version_get_hw_region_name(),
my_name ? my_name : "Unknown"); my_name ? my_name : "Unknown");
string_cat_printf(buffer, "Serial number:\n"); string_cat_printf(buffer, "Serial Number:\n");
const uint8_t* uid = furi_hal_version_uid(); const uint8_t* uid = furi_hal_version_uid();
for(size_t i = 0; i < furi_hal_version_uid_size(); i++) { for(size_t i = 0; i < furi_hal_version_uid_size(); i++) {
string_cat_printf(buffer, "%02X", uid[i]); string_cat_printf(buffer, "%02X", uid[i]);
} }
dialog_message_set_header(message, "HW Version info:", 0, 0, AlignLeft, AlignTop); dialog_message_set_header(message, "HW Version Info:", 0, 0, AlignLeft, AlignTop);
dialog_message_set_text(message, string_get_cstr(buffer), 0, 13, AlignLeft, AlignTop); dialog_message_set_text(message, string_get_cstr(buffer), 0, 13, AlignLeft, AlignTop);
result = dialog_message_show(dialogs, message); result = dialog_message_show(dialogs, message);
dialog_message_set_text(message, NULL, 0, 0, AlignLeft, AlignTop); dialog_message_set_text(message, NULL, 0, 0, AlignLeft, AlignTop);
@@ -164,7 +164,7 @@ static DialogMessageButton fw_version_screen(DialogsApp* dialogs, DialogMessage*
version_get_gitbranch(ver)); version_get_gitbranch(ver));
} }
dialog_message_set_header(message, "FW Version info:", 0, 0, AlignLeft, AlignTop); dialog_message_set_header(message, "FW Version Info:", 0, 0, AlignLeft, AlignTop);
dialog_message_set_text(message, string_get_cstr(buffer), 0, 13, AlignLeft, AlignTop); dialog_message_set_text(message, string_get_cstr(buffer), 0, 13, AlignLeft, AlignTop);
result = dialog_message_show(dialogs, message); result = dialog_message_show(dialogs, message);
dialog_message_set_text(message, NULL, 0, 0, AlignLeft, AlignTop); dialog_message_set_text(message, NULL, 0, 0, AlignLeft, AlignTop);

View File

@@ -37,7 +37,7 @@ void archive_scene_rename_on_enter(void* context) {
false); false);
ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( ValidatorIsFile* validator_is_file = validator_is_file_alloc_init(
string_get_cstr(archive->browser->path), archive->file_extension, NULL); string_get_cstr(archive->browser->path), archive->file_extension, "");
text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); text_input_set_validator(text_input, validator_is_file_callback, validator_is_file);
string_clear(filename); string_clear(filename);

View File

@@ -59,7 +59,7 @@ BadUsbApp* bad_usb_app_alloc(char* arg) {
string_init(app->file_path); string_init(app->file_path);
string_init(app->keyboard_layout); string_init(app->keyboard_layout);
if(arg != NULL) { if(arg && strlen(arg)) {
string_set_str(app->file_path, arg); string_set_str(app->file_path, arg);
} }
@@ -121,7 +121,6 @@ void bad_usb_app_free(BadUsbApp* app) {
} }
// Views // Views
view_dispatcher_remove_view(app->view_dispatcher, BadUsbAppViewFileSelect);
view_dispatcher_remove_view(app->view_dispatcher, BadUsbAppViewWork); view_dispatcher_remove_view(app->view_dispatcher, BadUsbAppViewWork);
view_dispatcher_remove_view(app->view_dispatcher, BadUsbAppViewConfigLayout); view_dispatcher_remove_view(app->view_dispatcher, BadUsbAppViewConfigLayout);
bad_usb_free(app->bad_usb_view); bad_usb_free(app->bad_usb_view);

View File

@@ -43,7 +43,6 @@ struct BadUsbApp {
typedef enum { typedef enum {
BadUsbAppViewError, BadUsbAppViewError,
BadUsbAppViewFileSelect,
BadUsbAppViewWork, BadUsbAppViewWork,
BadUsbAppViewConfig, BadUsbAppViewConfig,
BadUsbAppViewConfigLayout, BadUsbAppViewConfigLayout,

View File

@@ -90,7 +90,7 @@ BtHid* bt_hid_app_alloc() {
submenu_add_item( submenu_add_item(
app->submenu, "Keyboard", BtHidSubmenuIndexKeyboard, bt_hid_submenu_callback, app); app->submenu, "Keyboard", BtHidSubmenuIndexKeyboard, bt_hid_submenu_callback, app);
submenu_add_item( submenu_add_item(
app->submenu, "Media player", BtHidSubmenuIndexMedia, bt_hid_submenu_callback, app); app->submenu, "Media Player", BtHidSubmenuIndexMedia, bt_hid_submenu_callback, app);
submenu_add_item(app->submenu, "Mouse", BtHidSubmenuIndexMouse, bt_hid_submenu_callback, app); submenu_add_item(app->submenu, "Mouse", BtHidSubmenuIndexMouse, bt_hid_submenu_callback, app);
view_set_previous_callback(submenu_get_view(app->submenu), bt_hid_exit); view_set_previous_callback(submenu_get_view(app->submenu), bt_hid_exit);
view_dispatcher_add_view( view_dispatcher_add_view(
@@ -103,7 +103,7 @@ BtHid* bt_hid_app_alloc() {
dialog_ex_set_left_button_text(app->dialog, "Exit"); dialog_ex_set_left_button_text(app->dialog, "Exit");
dialog_ex_set_right_button_text(app->dialog, "Stay"); dialog_ex_set_right_button_text(app->dialog, "Stay");
dialog_ex_set_center_button_text(app->dialog, "Menu"); dialog_ex_set_center_button_text(app->dialog, "Menu");
dialog_ex_set_header(app->dialog, "Close current app?", 16, 12, AlignLeft, AlignTop); dialog_ex_set_header(app->dialog, "Close Current App?", 16, 12, AlignLeft, AlignTop);
view_dispatcher_add_view( view_dispatcher_add_view(
app->view_dispatcher, BtHidViewExitConfirm, dialog_ex_get_view(app->dialog)); app->view_dispatcher, BtHidViewExitConfirm, dialog_ex_get_view(app->dialog));

View File

@@ -347,7 +347,8 @@ static void bt_close_connection(Bt* bt) {
furi_event_flag_set(bt->api_event, BT_API_UNLOCK_EVENT); furi_event_flag_set(bt->api_event, BT_API_UNLOCK_EVENT);
} }
int32_t bt_srv() { int32_t bt_srv(void* p) {
UNUSED(p);
Bt* bt = bt_alloc(); Bt* bt = bt_alloc();
if(furi_hal_rtc_get_boot_mode() != FuriHalRtcBootModeNormal) { if(furi_hal_rtc_get_boot_mode() != FuriHalRtcBootModeNormal) {

View File

@@ -10,9 +10,9 @@ void bt_settings_scene_forget_dev_confirm_dialog_callback(DialogExResult result,
void bt_settings_scene_forget_dev_confirm_on_enter(void* context) { void bt_settings_scene_forget_dev_confirm_on_enter(void* context) {
BtSettingsApp* app = context; BtSettingsApp* app = context;
DialogEx* dialog = app->dialog; DialogEx* dialog = app->dialog;
dialog_ex_set_header(dialog, "Unpair all devices?", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog, "Unpair All Devices?", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog, "All previous pairings\nwill be lost.", 64, 22, AlignCenter, AlignTop); dialog, "All previous pairings\nwill be lost!", 64, 22, AlignCenter, AlignTop);
dialog_ex_set_left_button_text(dialog, "Back"); dialog_ex_set_left_button_text(dialog, "Back");
dialog_ex_set_right_button_text(dialog, "Unpair"); dialog_ex_set_right_button_text(dialog, "Unpair");
dialog_ex_set_context(dialog, app); dialog_ex_set_context(dialog, app);

View File

@@ -439,9 +439,9 @@ void cli_session_open(Cli* cli, void* session) {
cli->session = session; cli->session = session;
if(cli->session != NULL) { if(cli->session != NULL) {
cli->session->init(); cli->session->init();
furi_stdglue_set_thread_stdout_callback(cli->session->tx_stdout); furi_thread_set_stdout_callback(cli->session->tx_stdout);
} else { } else {
furi_stdglue_set_thread_stdout_callback(NULL); furi_thread_set_stdout_callback(NULL);
} }
furi_semaphore_release(cli->idle_sem); furi_semaphore_release(cli->idle_sem);
furi_check(furi_mutex_release(cli->mutex) == FuriStatusOk); furi_check(furi_mutex_release(cli->mutex) == FuriStatusOk);
@@ -455,7 +455,7 @@ void cli_session_close(Cli* cli) {
cli->session->deinit(); cli->session->deinit();
} }
cli->session = NULL; cli->session = NULL;
furi_stdglue_set_thread_stdout_callback(NULL); furi_thread_set_stdout_callback(NULL);
furi_check(furi_mutex_release(cli->mutex) == FuriStatusOk); furi_check(furi_mutex_release(cli->mutex) == FuriStatusOk);
} }
@@ -469,9 +469,9 @@ int32_t cli_srv(void* p) {
furi_record_create(RECORD_CLI, cli); furi_record_create(RECORD_CLI, cli);
if(cli->session != NULL) { if(cli->session != NULL) {
furi_stdglue_set_thread_stdout_callback(cli->session->tx_stdout); furi_thread_set_stdout_callback(cli->session->tx_stdout);
} else { } else {
furi_stdglue_set_thread_stdout_callback(NULL); furi_thread_set_stdout_callback(NULL);
} }
if(furi_hal_rtc_get_boot_mode() == FuriHalRtcBootModeNormal) { if(furi_hal_rtc_get_boot_mode() == FuriHalRtcBootModeNormal) {

View File

@@ -25,7 +25,7 @@ struct CliSession {
void (*deinit)(void); void (*deinit)(void);
size_t (*rx)(uint8_t* buffer, size_t size, uint32_t timeout); size_t (*rx)(uint8_t* buffer, size_t size, uint32_t timeout);
void (*tx)(const uint8_t* buffer, size_t size); void (*tx)(const uint8_t* buffer, size_t size);
void (*tx_stdout)(void* _cookie, const char* data, size_t size); void (*tx_stdout)(const char* data, size_t size);
bool (*is_connected)(void); bool (*is_connected)(void);
}; };

View File

@@ -277,8 +277,7 @@ static void cli_vcp_tx(const uint8_t* buffer, size_t size) {
#endif #endif
} }
static void cli_vcp_tx_stdout(void* _cookie, const char* data, size_t size) { static void cli_vcp_tx_stdout(const char* data, size_t size) {
UNUSED(_cookie);
cli_vcp_tx((const uint8_t*)data, size); cli_vcp_tx((const uint8_t*)data, size);
} }

View File

@@ -26,11 +26,11 @@ static void keypad_test_render_callback(Canvas* canvas, void* ctx) {
canvas_clear(canvas); canvas_clear(canvas);
char strings[5][20]; char strings[5][20];
sprintf(strings[0], "Ok: %d", state->ok); snprintf(strings[0], 20, "Ok: %d", state->ok);
sprintf(strings[1], "L: %d", state->left); snprintf(strings[1], 20, "L: %d", state->left);
sprintf(strings[2], "R: %d", state->right); snprintf(strings[2], 20, "R: %d", state->right);
sprintf(strings[3], "U: %d", state->up); snprintf(strings[3], 20, "U: %d", state->up);
sprintf(strings[4], "D: %d", state->down); snprintf(strings[4], 20, "D: %d", state->down);
canvas_set_font(canvas, FontPrimary); canvas_set_font(canvas, FontPrimary);
canvas_draw_str(canvas, 0, 10, "Keypad test"); canvas_draw_str(canvas, 0, 10, "Keypad test");

View File

@@ -143,7 +143,7 @@ static void bubble_animation_activate(BubbleAnimationView* view, bool force) {
furi_assert(view); furi_assert(view);
bool activate = true; bool activate = true;
BubbleAnimationViewModel* model = view_get_model(view->view); BubbleAnimationViewModel* model = view_get_model(view->view);
if(!model->current) { if(model->current == NULL) {
activate = false; activate = false;
} else if(model->freeze_frame) { } else if(model->freeze_frame) {
activate = false; activate = false;
@@ -151,6 +151,7 @@ static void bubble_animation_activate(BubbleAnimationView* view, bool force) {
activate = false; activate = false;
} }
if(model->current != NULL) {
if(!force) { if(!force) {
if((model->active_ended_at + model->current->active_cooldown * 1000) > if((model->active_ended_at + model->current->active_cooldown * 1000) >
xTaskGetTickCount()) { xTaskGetTickCount()) {
@@ -161,6 +162,7 @@ static void bubble_animation_activate(BubbleAnimationView* view, bool force) {
activate = false; activate = false;
} }
} }
}
view_commit_model(view->view, false); view_commit_model(view->view, false);
if(!activate && !force) { if(!activate && !force) {
@@ -288,7 +290,10 @@ static void bubble_animation_enter(void* context) {
bubble_animation_activate(view, false); bubble_animation_activate(view, false);
BubbleAnimationViewModel* model = view_get_model(view->view); BubbleAnimationViewModel* model = view_get_model(view->view);
uint8_t frame_rate = model->current->icon_animation.frame_rate; uint8_t frame_rate = 0;
if(model->current != NULL) {
frame_rate = model->current->icon_animation.frame_rate;
}
view_commit_model(view->view, false); view_commit_model(view->view, false);
if(frame_rate) { if(frame_rate) {

View File

@@ -90,7 +90,7 @@ void desktop_settings_app_free(DesktopSettingsApp* app) {
extern int32_t desktop_settings_app(void* p) { extern int32_t desktop_settings_app(void* p) {
DesktopSettingsApp* app = desktop_settings_app_alloc(); DesktopSettingsApp* app = desktop_settings_app_alloc();
LOAD_DESKTOP_SETTINGS(&app->settings); LOAD_DESKTOP_SETTINGS(&app->settings);
if(!strcmp(p, DESKTOP_SETTINGS_RUN_PIN_SETUP_ARG)) { if(p && (strcmp(p, DESKTOP_SETTINGS_RUN_PIN_SETUP_ARG) == 0)) {
scene_manager_next_scene(app->scene_manager, DesktopSettingsAppScenePinSetupHowto); scene_manager_next_scene(app->scene_manager, DesktopSettingsAppScenePinSetupHowto);
} else { } else {
scene_manager_next_scene(app->scene_manager, DesktopSettingsAppSceneStart); scene_manager_next_scene(app->scene_manager, DesktopSettingsAppSceneStart);

View File

@@ -23,7 +23,7 @@ void desktop_debug_render(Canvas* canvas, void* model) {
const Version* ver; const Version* ver;
char buffer[64]; char buffer[64];
static const char* headers[] = {"FW Version info:", "Dolphin info:"}; static const char* headers[] = {"FW Version Info:", "Dolphin Info:"};
canvas_set_color(canvas, ColorBlack); canvas_set_color(canvas, ColorBlack);
canvas_set_font(canvas, FontPrimary); canvas_set_font(canvas, FontPrimary);
@@ -78,7 +78,6 @@ void desktop_debug_render(Canvas* canvas, void* model) {
canvas_draw_str(canvas, 5, 50 + STATUS_BAR_Y_SHIFT, buffer); canvas_draw_str(canvas, 5, 50 + STATUS_BAR_Y_SHIFT, buffer);
} else { } else {
char buffer[64];
Dolphin* dolphin = furi_record_open(RECORD_DOLPHIN); Dolphin* dolphin = furi_record_open(RECORD_DOLPHIN);
DolphinStats stats = dolphin_stats(dolphin); DolphinStats stats = dolphin_stats(dolphin);
furi_record_close(RECORD_DOLPHIN); furi_record_close(RECORD_DOLPHIN);
@@ -87,18 +86,20 @@ void desktop_debug_render(Canvas* canvas, void* model) {
uint32_t remaining = dolphin_state_xp_to_levelup(m->icounter); uint32_t remaining = dolphin_state_xp_to_levelup(m->icounter);
canvas_set_font(canvas, FontSecondary); canvas_set_font(canvas, FontSecondary);
snprintf(buffer, 64, "Icounter: %ld Butthurt %ld", m->icounter, m->butthurt); snprintf(buffer, sizeof(buffer), "Icounter: %ld Butthurt %ld", m->icounter, m->butthurt);
canvas_draw_str(canvas, 5, 19 + STATUS_BAR_Y_SHIFT, buffer); canvas_draw_str(canvas, 5, 19 + STATUS_BAR_Y_SHIFT, buffer);
snprintf( snprintf(
buffer, buffer,
64, sizeof(buffer),
"Level: %ld To level up: %ld", "Level: %ld To level up: %ld",
current_lvl, current_lvl,
(remaining == (uint32_t)(-1) ? remaining : 0)); (remaining == (uint32_t)(-1) ? remaining : 0));
canvas_draw_str(canvas, 5, 29 + STATUS_BAR_Y_SHIFT, buffer); canvas_draw_str(canvas, 5, 29 + STATUS_BAR_Y_SHIFT, buffer);
snprintf(buffer, 64, "%s", asctime(localtime((const time_t*)&m->timestamp))); // even if timestamp is uint64_t, it's safe to cast it to uint32_t, because furi_hal_rtc_datetime_to_timestamp only returns uint32_t
snprintf(buffer, sizeof(buffer), "%ld", (uint32_t)m->timestamp);
canvas_draw_str(canvas, 5, 39 + STATUS_BAR_Y_SHIFT, buffer); canvas_draw_str(canvas, 5, 39 + STATUS_BAR_Y_SHIFT, buffer);
canvas_draw_str(canvas, 0, 49 + STATUS_BAR_Y_SHIFT, "[< >] icounter value [ok] save"); canvas_draw_str(canvas, 0, 49 + STATUS_BAR_Y_SHIFT, "[< >] icounter value [ok] save");
} }

View File

@@ -67,7 +67,7 @@ void desktop_lock_menu_render(Canvas* canvas, void* model) {
const char* str = Lockmenu_Items[i]; const char* str = Lockmenu_Items[i];
if(i == 1 && !m->pin_set) str = "Set PIN"; if(i == 1 && !m->pin_set) str = "Set PIN";
if(m->hint_timeout && m->idx == 2 && m->idx == i) str = "Not implemented"; if(m->hint_timeout && m->idx == 2 && m->idx == i) str = "Not Implemented";
if(str != NULL) if(str != NULL)
canvas_draw_str_aligned( canvas_draw_str_aligned(

View File

@@ -20,7 +20,7 @@ static bool gpio_test_process_ok(GpioTest* gpio_test, InputEvent* event);
static void gpio_test_draw_callback(Canvas* canvas, void* _model) { static void gpio_test_draw_callback(Canvas* canvas, void* _model) {
GpioTestModel* model = _model; GpioTestModel* model = _model;
canvas_set_font(canvas, FontPrimary); canvas_set_font(canvas, FontPrimary);
elements_multiline_text_aligned(canvas, 64, 2, AlignCenter, AlignTop, "Gpio Output mode test"); elements_multiline_text_aligned(canvas, 64, 2, AlignCenter, AlignTop, "GPIO Output Mode Test");
canvas_set_font(canvas, FontSecondary); canvas_set_font(canvas, FontSecondary);
elements_multiline_text_aligned( elements_multiline_text_aligned(
canvas, 64, 16, AlignCenter, AlignTop, "Press < or > to change pin"); canvas, 64, 16, AlignCenter, AlignTop, "Press < or > to change pin");

View File

@@ -185,6 +185,7 @@ static void button_menu_process_ok(ButtonMenu* button_menu, InputType type) {
return false; return false;
}); });
if(item) {
if(item->type == ButtonMenuItemTypeControl) { if(item->type == ButtonMenuItemTypeControl) {
if(type == InputTypeShort) { if(type == InputTypeShort) {
if(item && item->callback) { if(item && item->callback) {
@@ -199,6 +200,7 @@ static void button_menu_process_ok(ButtonMenu* button_menu, InputType type) {
} }
} }
} }
}
} }
static bool button_menu_view_input_callback(InputEvent* event, void* context) { static bool button_menu_view_input_callback(InputEvent* event, void* context) {

View File

@@ -147,7 +147,7 @@ static void text_input_backspace_cb(TextInputModel* model) {
static void text_input_view_draw_callback(Canvas* canvas, void* _model) { static void text_input_view_draw_callback(Canvas* canvas, void* _model) {
TextInputModel* model = _model; TextInputModel* model = _model;
uint8_t text_length = strlen(model->text_buffer); uint8_t text_length = model->text_buffer ? strlen(model->text_buffer) : 0;
uint8_t needed_string_width = canvas_width(canvas) - 8; uint8_t needed_string_width = canvas_width(canvas) - 8;
uint8_t start_pos = 4; uint8_t start_pos = 4;

View File

@@ -1,7 +1,7 @@
#pragma once #pragma once
// #include <gui/view.h>
#include <m-string.h> #include <m-string.h>
#include <core/common_defines.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {

View File

@@ -353,7 +353,7 @@ int32_t ibutton_app(void* p) {
bool key_loaded = false; bool key_loaded = false;
bool rpc_mode = false; bool rpc_mode = false;
if(p) { if(p && strlen(p)) {
uint32_t rpc_ctx = 0; uint32_t rpc_ctx = 0;
if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) { if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) {
FURI_LOG_D(TAG, "Running in RPC mode"); FURI_LOG_D(TAG, "Running in RPC mode");

View File

@@ -21,7 +21,7 @@ void ibutton_scene_exit_confirm_on_enter(void* context) {
widget_add_string_element( widget_add_string_element(
widget, 64, 19, AlignCenter, AlignBottom, FontPrimary, "Exit to iButton menu?"); widget, 64, 19, AlignCenter, AlignBottom, FontPrimary, "Exit to iButton menu?");
widget_add_string_element( widget_add_string_element(
widget, 64, 31, AlignCenter, AlignBottom, FontSecondary, "All unsaved data will be lost."); widget, 64, 31, AlignCenter, AlignBottom, FontSecondary, "All unsaved data will be lost!");
view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewWidget); view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewWidget);
} }

View File

@@ -14,7 +14,7 @@ void ibutton_scene_read_on_enter(void* context) {
DOLPHIN_DEED(DolphinDeedIbuttonRead); DOLPHIN_DEED(DolphinDeedIbuttonRead);
popup_set_header(popup, "iButton", 95, 26, AlignCenter, AlignBottom); popup_set_header(popup, "iButton", 95, 26, AlignCenter, AlignBottom);
popup_set_text(popup, "waiting\nfor key ...", 95, 30, AlignCenter, AlignTop); popup_set_text(popup, "Waiting\nfor key ...", 95, 30, AlignCenter, AlignTop);
popup_set_icon(popup, 0, 5, &I_DolphinWait_61x59); popup_set_icon(popup, 0, 5, &I_DolphinWait_61x59);
view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewPopup); view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewPopup);

View File

@@ -21,7 +21,7 @@ void ibutton_scene_retry_confirm_on_enter(void* context) {
widget_add_string_element( widget_add_string_element(
widget, 64, 19, AlignCenter, AlignBottom, FontPrimary, "Return to reading?"); widget, 64, 19, AlignCenter, AlignBottom, FontPrimary, "Return to reading?");
widget_add_string_element( widget_add_string_element(
widget, 64, 29, AlignCenter, AlignBottom, FontSecondary, "All unsaved data will be lost."); widget, 64, 29, AlignCenter, AlignBottom, FontSecondary, "All unsaved data will be lost!");
view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewWidget); view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewWidget);
} }

View File

@@ -405,7 +405,7 @@ int32_t infrared_app(void* p) {
bool is_remote_loaded = false; bool is_remote_loaded = false;
bool is_rpc_mode = false; bool is_rpc_mode = false;
if(p) { if(p && strlen(p)) {
uint32_t rpc_ctx = 0; uint32_t rpc_ctx = 0;
if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) { if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) {
infrared->rpc_ctx = (void*)rpc_ctx; infrared->rpc_ctx = (void*)rpc_ctx;

View File

@@ -27,7 +27,7 @@ static void signal_received_callback(void* context, InfraredWorkerSignal* receiv
if(infrared_worker_signal_is_decoded(received_signal)) { if(infrared_worker_signal_is_decoded(received_signal)) {
const InfraredMessage* message = infrared_worker_get_decoded_signal(received_signal); const InfraredMessage* message = infrared_worker_get_decoded_signal(received_signal);
buf_cnt = sniprintf( buf_cnt = snprintf(
buf, buf,
sizeof(buf), sizeof(buf),
"%s, A:0x%0*lX, C:0x%0*lX%s\r\n", "%s, A:0x%0*lX, C:0x%0*lX%s\r\n",
@@ -43,13 +43,13 @@ static void signal_received_callback(void* context, InfraredWorkerSignal* receiv
size_t timings_cnt; size_t timings_cnt;
infrared_worker_get_raw_signal(received_signal, &timings, &timings_cnt); infrared_worker_get_raw_signal(received_signal, &timings, &timings_cnt);
buf_cnt = sniprintf(buf, sizeof(buf), "RAW, %d samples:\r\n", timings_cnt); buf_cnt = snprintf(buf, sizeof(buf), "RAW, %d samples:\r\n", timings_cnt);
cli_write(cli, (uint8_t*)buf, buf_cnt); cli_write(cli, (uint8_t*)buf, buf_cnt);
for(size_t i = 0; i < timings_cnt; ++i) { for(size_t i = 0; i < timings_cnt; ++i) {
buf_cnt = sniprintf(buf, sizeof(buf), "%lu ", timings[i]); buf_cnt = snprintf(buf, sizeof(buf), "%lu ", timings[i]);
cli_write(cli, (uint8_t*)buf, buf_cnt); cli_write(cli, (uint8_t*)buf, buf_cnt);
} }
buf_cnt = sniprintf(buf, sizeof(buf), "\r\n"); buf_cnt = snprintf(buf, sizeof(buf), "\r\n");
cli_write(cli, (uint8_t*)buf, buf_cnt); cli_write(cli, (uint8_t*)buf, buf_cnt);
} }
} }

View File

@@ -10,13 +10,13 @@ void infrared_scene_ask_back_on_enter(void* context) {
DialogEx* dialog_ex = infrared->dialog_ex; DialogEx* dialog_ex = infrared->dialog_ex;
if(infrared->app_state.is_learning_new_remote) { if(infrared->app_state.is_learning_new_remote) {
dialog_ex_set_header(dialog_ex, "Exit to Infrared menu?", 64, 0, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Exit to Infrared Menu?", 64, 0, AlignCenter, AlignTop);
} else { } else {
dialog_ex_set_header(dialog_ex, "Exit to remote menu?", 64, 0, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Exit to Remote Menu?", 64, 0, AlignCenter, AlignTop);
} }
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "All unsaved data\nwill be lost.", 64, 31, AlignCenter, AlignCenter); dialog_ex, "All unsaved data\nwill be lost!", 64, 31, AlignCenter, AlignCenter);
dialog_ex_set_icon(dialog_ex, 0, 0, NULL); dialog_ex_set_icon(dialog_ex, 0, 0, NULL);
dialog_ex_set_left_button_text(dialog_ex, "Exit"); dialog_ex_set_left_button_text(dialog_ex, "Exit");
dialog_ex_set_center_button_text(dialog_ex, NULL); dialog_ex_set_center_button_text(dialog_ex, NULL);

View File

@@ -9,9 +9,9 @@ void infrared_scene_ask_retry_on_enter(void* context) {
Infrared* infrared = context; Infrared* infrared = context;
DialogEx* dialog_ex = infrared->dialog_ex; DialogEx* dialog_ex = infrared->dialog_ex;
dialog_ex_set_header(dialog_ex, "Return to reading?", 64, 0, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Return to Reading?", 64, 0, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "All unsaved data\nwill be lost.", 64, 31, AlignCenter, AlignCenter); dialog_ex, "All unsaved data\nwill be lost!", 64, 31, AlignCenter, AlignCenter);
dialog_ex_set_icon(dialog_ex, 0, 0, NULL); dialog_ex_set_icon(dialog_ex, 0, 0, NULL);
dialog_ex_set_left_button_text(dialog_ex, "Exit"); dialog_ex_set_left_button_text(dialog_ex, "Exit");
dialog_ex_set_center_button_text(dialog_ex, NULL); dialog_ex_set_center_button_text(dialog_ex, NULL);

View File

@@ -16,7 +16,7 @@ void infrared_scene_edit_delete_on_enter(void* context) {
int32_t current_button_index = infrared->app_state.current_button_index; int32_t current_button_index = infrared->app_state.current_button_index;
furi_assert(current_button_index != InfraredButtonIndexNone); furi_assert(current_button_index != InfraredButtonIndexNone);
dialog_ex_set_header(dialog_ex, "Delete button?", 64, 0, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Delete Button?", 64, 0, AlignCenter, AlignTop);
InfraredRemoteButton* current_button = InfraredRemoteButton* current_button =
infrared_remote_get_button(remote, current_button_index); infrared_remote_get_button(remote, current_button_index);
InfraredSignal* signal = infrared_remote_button_get_signal(current_button); InfraredSignal* signal = infrared_remote_button_get_signal(current_button);
@@ -45,7 +45,7 @@ void infrared_scene_edit_delete_on_enter(void* context) {
} }
} else if(edit_target == InfraredEditTargetRemote) { } else if(edit_target == InfraredEditTargetRemote) {
dialog_ex_set_header(dialog_ex, "Delete remote?", 64, 0, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Delete Remote?", 64, 0, AlignCenter, AlignTop);
infrared_text_store_set( infrared_text_store_set(
infrared, infrared,
0, 0,

View File

@@ -64,7 +64,8 @@ const char* input_get_type_name(InputType type) {
return "Unknown"; return "Unknown";
} }
int32_t input_srv() { int32_t input_srv(void* p) {
UNUSED(p);
input = malloc(sizeof(Input)); input = malloc(sizeof(Input));
input->thread_id = furi_thread_get_current_id(); input->thread_id = furi_thread_get_current_id();
input->event_pubsub = furi_pubsub_alloc(); input->event_pubsub = furi_pubsub_alloc();

View File

@@ -74,7 +74,7 @@ void LfRfidApp::run(void* _args) {
make_app_folder(); make_app_folder();
if(strlen(args)) { if(args && strlen(args)) {
uint32_t rpc_ctx_ptr = 0; uint32_t rpc_ctx_ptr = 0;
if(sscanf(args, "RPC %lX", &rpc_ctx_ptr) == 1) { if(sscanf(args, "RPC %lX", &rpc_ctx_ptr) == 1) {
rpc_ctx = (RpcAppSystem*)rpc_ctx_ptr; rpc_ctx = (RpcAppSystem*)rpc_ctx_ptr;

View File

@@ -107,7 +107,7 @@ static void lfrfid_cli_write(Cli* cli, string_t args) {
UNUSED(cli); UNUSED(cli);
UNUSED(args); UNUSED(args);
// TODO implement rfid write // TODO implement rfid write
printf("Not implemented :(\r\n"); printf("Not Implemented :(\r\n");
} }
static void lfrfid_cli_emulate(Cli* cli, string_t args) { static void lfrfid_cli_emulate(Cli* cli, string_t args) {

View File

@@ -17,9 +17,9 @@ void LfRfidAppSceneExitConfirm::on_enter(LfRfidApp* app, bool /* need_restore */
auto line_1 = container->add<StringElement>(); auto line_1 = container->add<StringElement>();
auto line_2 = container->add<StringElement>(); auto line_2 = container->add<StringElement>();
line_1->set_text("Exit to RFID menu?", 64, 19, 128 - 2, AlignCenter, AlignBottom, FontPrimary); line_1->set_text("Exit to RFID Menu?", 64, 19, 128 - 2, AlignCenter, AlignBottom, FontPrimary);
line_2->set_text( line_2->set_text(
"All unsaved data will be lost.", 64, 31, 0, AlignCenter, AlignBottom, FontSecondary); "All unsaved data will be lost!", 64, 31, 0, AlignCenter, AlignBottom, FontSecondary);
app->view_controller.switch_to<ContainerVM>(); app->view_controller.switch_to<ContainerVM>();
} }

View File

@@ -17,9 +17,9 @@ void LfRfidAppSceneRetryConfirm::on_enter(LfRfidApp* app, bool /* need_restore *
auto line_1 = container->add<StringElement>(); auto line_1 = container->add<StringElement>();
auto line_2 = container->add<StringElement>(); auto line_2 = container->add<StringElement>();
line_1->set_text("Return to reading?", 64, 19, 128 - 2, AlignCenter, AlignBottom, FontPrimary); line_1->set_text("Return to Reading?", 64, 19, 128 - 2, AlignCenter, AlignBottom, FontPrimary);
line_2->set_text( line_2->set_text(
"All unsaved data will be lost.", 64, 29, 0, AlignCenter, AlignBottom, FontSecondary); "All unsaved data will be lost!", 64, 29, 0, AlignCenter, AlignBottom, FontSecondary);
app->view_controller.switch_to<ContainerVM>(); app->view_controller.switch_to<ContainerVM>();
} }

View File

@@ -300,7 +300,7 @@ int32_t music_player_app(void* p) {
string_init(file_path); string_init(file_path);
do { do {
if(p) { if(p && strlen(p)) {
string_cat_str(file_path, p); string_cat_str(file_path, p);
} else { } else {
string_set_str(file_path, MUSIC_PLAYER_APP_PATH_FOLDER); string_set_str(file_path, MUSIC_PLAYER_APP_PATH_FOLDER);

View File

@@ -238,7 +238,7 @@ int32_t nfc_app(void* p) {
char* args = p; char* args = p;
// Check argument and run corresponding scene // Check argument and run corresponding scene
if((*args != '\0')) { if(args && strlen(args)) {
nfc_device_set_loading_callback(nfc->dev, nfc_show_loading_popup, nfc); nfc_device_set_loading_callback(nfc->dev, nfc_show_loading_popup, nfc);
uint32_t rpc_ctx = 0; uint32_t rpc_ctx = 0;
if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) { if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) {

View File

@@ -37,7 +37,7 @@ static void nfc_scene_detect_reader_widget_config(Nfc* nfc, bool data_received)
widget_add_icon_element(widget, 0, 14, &I_Reader_detect); widget_add_icon_element(widget, 0, 14, &I_Reader_detect);
widget_add_string_element( widget_add_string_element(
widget, 64, 3, AlignCenter, AlignTop, FontSecondary, "Hold near reader"); widget, 64, 3, AlignCenter, AlignTop, FontSecondary, "Hold Near Reader");
widget_add_string_element(widget, 55, 22, AlignLeft, AlignTop, FontPrimary, "Emulating..."); widget_add_string_element(widget, 55, 22, AlignLeft, AlignTop, FontPrimary, "Emulating...");
if(data_received) { if(data_received) {

View File

@@ -12,9 +12,9 @@ void nfc_scene_exit_confirm_on_enter(void* context) {
dialog_ex_set_left_button_text(dialog_ex, "Exit"); dialog_ex_set_left_button_text(dialog_ex, "Exit");
dialog_ex_set_right_button_text(dialog_ex, "Stay"); dialog_ex_set_right_button_text(dialog_ex, "Stay");
dialog_ex_set_header(dialog_ex, "Exit to NFC menu?", 64, 11, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Exit to NFC Menu?", 64, 11, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "All unsaved data\nwill be lost.", 64, 25, AlignCenter, AlignTop); dialog_ex, "All unsaved data\nwill be lost!", 64, 25, AlignCenter, AlignTop);
dialog_ex_set_context(dialog_ex, nfc); dialog_ex_set_context(dialog_ex, nfc);
dialog_ex_set_result_callback(dialog_ex, nfc_scene_exit_confirm_dialog_callback); dialog_ex_set_result_callback(dialog_ex, nfc_scene_exit_confirm_dialog_callback);

View File

@@ -1,5 +1,7 @@
#include "../nfc_i.h" #include "../nfc_i.h"
#define TAG "NfcMfClassicDictAttack"
typedef enum { typedef enum {
DictAttackStateIdle, DictAttackStateIdle,
DictAttackStateUserDictInProgress, DictAttackStateUserDictInProgress,
@@ -32,7 +34,9 @@ static void nfc_scene_mf_classic_dict_attack_update_view(Nfc* nfc) {
static void nfc_scene_mf_classic_dict_attack_prepare_view(Nfc* nfc, DictAttackState state) { static void nfc_scene_mf_classic_dict_attack_prepare_view(Nfc* nfc, DictAttackState state) {
MfClassicData* data = &nfc->dev->dev_data.mf_classic_data; MfClassicData* data = &nfc->dev->dev_data.mf_classic_data;
NfcMfClassicDictAttackData* dict_attack_data = &nfc->dev->dev_data.mf_classic_dict_attack_data;
NfcWorkerState worker_state = NfcWorkerStateReady; NfcWorkerState worker_state = NfcWorkerStateReady;
MfClassicDict* dict = NULL;
// Identify scene state // Identify scene state
if(state == DictAttackStateIdle) { if(state == DictAttackStateIdle) {
@@ -47,16 +51,36 @@ static void nfc_scene_mf_classic_dict_attack_prepare_view(Nfc* nfc, DictAttackSt
// Setup view // Setup view
if(state == DictAttackStateUserDictInProgress) { if(state == DictAttackStateUserDictInProgress) {
worker_state = NfcWorkerStateMfClassicUserDictAttack; worker_state = NfcWorkerStateMfClassicDictAttack;
dict_attack_set_header(nfc->dict_attack, "Mf Classic User Dict."); dict_attack_set_header(nfc->dict_attack, "Mf Classic User Dict.");
} else if(state == DictAttackStateFlipperDictInProgress) { dict = mf_classic_dict_alloc(MfClassicDictTypeUser);
worker_state = NfcWorkerStateMfClassicFlipperDictAttack;
dict_attack_set_header(nfc->dict_attack, "Mf Classic Flipper Dict."); // If failed to load user dictionary - try flipper dictionary
if(!dict) {
FURI_LOG_E(TAG, "User dictionary not found");
state = DictAttackStateFlipperDictInProgress;
} }
}
if(state == DictAttackStateFlipperDictInProgress) {
worker_state = NfcWorkerStateMfClassicDictAttack;
dict_attack_set_header(nfc->dict_attack, "Mf Classic Flipper Dict.");
dict = mf_classic_dict_alloc(MfClassicDictTypeFlipper);
if(!dict) {
FURI_LOG_E(TAG, "Flipper dictionary not found");
// Pass through to let worker handle the failure
}
}
// Free previous dictionary
if(dict_attack_data->dict) {
mf_classic_dict_free(dict_attack_data->dict);
}
dict_attack_data->dict = dict;
scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfClassicDictAttack, state); scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfClassicDictAttack, state);
dict_attack_set_callback(nfc->dict_attack, nfc_dict_attack_dict_attack_result_callback, nfc); dict_attack_set_callback(nfc->dict_attack, nfc_dict_attack_dict_attack_result_callback, nfc);
dict_attack_set_current_sector(nfc->dict_attack, 0); dict_attack_set_current_sector(nfc->dict_attack, 0);
dict_attack_set_card_detected(nfc->dict_attack, data->type); dict_attack_set_card_detected(nfc->dict_attack, data->type);
dict_attack_set_total_dict_keys(
nfc->dict_attack, dict ? mf_classic_dict_get_total_keys(dict) : 0);
nfc_scene_mf_classic_dict_attack_update_view(nfc); nfc_scene_mf_classic_dict_attack_update_view(nfc);
nfc_worker_start( nfc_worker_start(
nfc->worker, worker_state, &nfc->dev->dev_data, nfc_dict_attack_worker_callback, nfc); nfc->worker, worker_state, &nfc->dev->dev_data, nfc_dict_attack_worker_callback, nfc);
@@ -112,6 +136,10 @@ bool nfc_scene_mf_classic_dict_attack_on_event(void* context, SceneManagerEvent
nfc_scene_mf_classic_dict_attack_update_view(nfc); nfc_scene_mf_classic_dict_attack_update_view(nfc);
dict_attack_inc_current_sector(nfc->dict_attack); dict_attack_inc_current_sector(nfc->dict_attack);
consumed = true; consumed = true;
} else if(event.event == NfcWorkerEventNewDictKeyBatch) {
nfc_scene_mf_classic_dict_attack_update_view(nfc);
dict_attack_inc_current_dict_key(nfc->dict_attack, NFC_DICT_KEY_BATCH_SIZE);
consumed = true;
} else if(event.event == NfcCustomEventDictAttackSkip) { } else if(event.event == NfcCustomEventDictAttackSkip) {
if(state == DictAttackStateUserDictInProgress) { if(state == DictAttackStateUserDictInProgress) {
nfc_worker_stop(nfc->worker); nfc_worker_stop(nfc->worker);
@@ -130,8 +158,13 @@ bool nfc_scene_mf_classic_dict_attack_on_event(void* context, SceneManagerEvent
void nfc_scene_mf_classic_dict_attack_on_exit(void* context) { void nfc_scene_mf_classic_dict_attack_on_exit(void* context) {
Nfc* nfc = context; Nfc* nfc = context;
NfcMfClassicDictAttackData* dict_attack_data = &nfc->dev->dev_data.mf_classic_dict_attack_data;
// Stop worker // Stop worker
nfc_worker_stop(nfc->worker); nfc_worker_stop(nfc->worker);
if(dict_attack_data->dict) {
mf_classic_dict_free(dict_attack_data->dict);
dict_attack_data->dict = NULL;
}
dict_attack_reset(nfc->dict_attack); dict_attack_reset(nfc->dict_attack);
nfc_blink_stop(nfc); nfc_blink_stop(nfc);
} }

View File

@@ -10,7 +10,7 @@ void nfc_scene_restore_original_confirm_on_enter(void* context) {
Nfc* nfc = context; Nfc* nfc = context;
DialogEx* dialog_ex = nfc->dialog_ex; DialogEx* dialog_ex = nfc->dialog_ex;
dialog_ex_set_header(dialog_ex, "Restore card data?", 64, 0, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Restore Card Data?", 64, 0, AlignCenter, AlignTop);
dialog_ex_set_icon(dialog_ex, 5, 15, &I_Restoring); dialog_ex_set_icon(dialog_ex, 5, 15, &I_Restoring);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "It will be returned\nto its original state.", 47, 21, AlignLeft, AlignTop); dialog_ex, "It will be returned\nto its original state.", 47, 21, AlignLeft, AlignTop);

View File

@@ -12,9 +12,9 @@ void nfc_scene_retry_confirm_on_enter(void* context) {
dialog_ex_set_left_button_text(dialog_ex, "Retry"); dialog_ex_set_left_button_text(dialog_ex, "Retry");
dialog_ex_set_right_button_text(dialog_ex, "Stay"); dialog_ex_set_right_button_text(dialog_ex, "Stay");
dialog_ex_set_header(dialog_ex, "Retry reading?", 64, 11, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Retry Reading?", 64, 11, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "All unsaved data will be\nlost.", 64, 25, AlignCenter, AlignTop); dialog_ex, "All unsaved data will be\nlost!", 64, 25, AlignCenter, AlignTop);
dialog_ex_set_context(dialog_ex, nfc); dialog_ex_set_context(dialog_ex, nfc);
dialog_ex_set_result_callback(dialog_ex, nfc_scene_retry_confirm_dialog_callback); dialog_ex_set_result_callback(dialog_ex, nfc_scene_retry_confirm_dialog_callback);

View File

@@ -2,6 +2,7 @@
enum SubmenuIndex { enum SubmenuIndex {
SubmenuIndexEmulate, SubmenuIndexEmulate,
SubmenuIndexEditUid,
SubmenuIndexRename, SubmenuIndexRename,
SubmenuIndexDelete, SubmenuIndexDelete,
SubmenuIndexInfo, SubmenuIndexInfo,
@@ -27,6 +28,14 @@ void nfc_scene_saved_menu_on_enter(void* context) {
SubmenuIndexEmulate, SubmenuIndexEmulate,
nfc_scene_saved_menu_submenu_callback, nfc_scene_saved_menu_submenu_callback,
nfc); nfc);
if(nfc->dev->dev_data.protocol == NfcDeviceProtocolUnknown) {
submenu_add_item(
submenu,
"Edit UID",
SubmenuIndexEditUid,
nfc_scene_saved_menu_submenu_callback,
nfc);
}
} else if( } else if(
nfc->dev->format == NfcDeviceSaveFormatMifareUl || nfc->dev->format == NfcDeviceSaveFormatMifareUl ||
nfc->dev->format == NfcDeviceSaveFormatMifareClassic) { nfc->dev->format == NfcDeviceSaveFormatMifareClassic) {
@@ -71,6 +80,9 @@ bool nfc_scene_saved_menu_on_event(void* context, SceneManagerEvent event) {
} else if(event.event == SubmenuIndexRename) { } else if(event.event == SubmenuIndexRename) {
scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName);
consumed = true; consumed = true;
} else if(event.event == SubmenuIndexEditUid) {
scene_manager_next_scene(nfc->scene_manager, NfcSceneSetUid);
consumed = true;
} else if(event.event == SubmenuIndexDelete) { } else if(event.event == SubmenuIndexDelete) {
scene_manager_next_scene(nfc->scene_manager, NfcSceneDelete); scene_manager_next_scene(nfc->scene_manager, NfcSceneDelete);
consumed = true; consumed = true;

View File

@@ -31,10 +31,18 @@ bool nfc_scene_set_uid_on_event(void* context, SceneManagerEvent event) {
if(event.type == SceneManagerEventTypeCustom) { if(event.type == SceneManagerEventTypeCustom) {
if(event.event == NfcCustomEventByteInputDone) { if(event.event == NfcCustomEventByteInputDone) {
DOLPHIN_DEED(DolphinDeedNfcAdd); DOLPHIN_DEED(DolphinDeedNfcAdd);
if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSavedMenu)) {
nfc->dev->dev_data.nfc_data = nfc->dev_edit_data;
if(nfc_device_save(nfc->dev, nfc->dev->dev_name)) {
scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveSuccess);
consumed = true;
}
} else {
scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName);
consumed = true; consumed = true;
} }
} }
}
return consumed; return consumed;
} }

View File

@@ -23,6 +23,8 @@ typedef struct {
uint8_t sector_current; uint8_t sector_current;
uint8_t keys_total; uint8_t keys_total;
uint8_t keys_found; uint8_t keys_found;
uint16_t dict_keys_total;
uint16_t dict_keys_current;
} DictAttackViewModel; } DictAttackViewModel;
static void dict_attack_draw_callback(Canvas* canvas, void* model) { static void dict_attack_draw_callback(Canvas* canvas, void* model) {
@@ -38,8 +40,15 @@ static void dict_attack_draw_callback(Canvas* canvas, void* model) {
canvas_set_font(canvas, FontPrimary); canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(canvas, 64, 2, AlignCenter, AlignTop, string_get_cstr(m->header)); canvas_draw_str_aligned(canvas, 64, 2, AlignCenter, AlignTop, string_get_cstr(m->header));
canvas_set_font(canvas, FontSecondary); canvas_set_font(canvas, FontSecondary);
float progress = float dict_progress = m->dict_keys_total == 0 ?
m->sectors_total == 0 ? 0 : (float)(m->sector_current) / (float)(m->sectors_total); 0 :
(float)(m->dict_keys_current) / (float)(m->dict_keys_total);
float progress = m->sectors_total == 0 ? 0 :
((float)(m->sector_current) + dict_progress) /
(float)(m->sectors_total);
if(progress > 1.0) {
progress = 1.0;
}
elements_progress_bar(canvas, 5, 15, 120, progress); elements_progress_bar(canvas, 5, 15, 120, progress);
canvas_set_font(canvas, FontSecondary); canvas_set_font(canvas, FontSecondary);
snprintf(draw_str, sizeof(draw_str), "Keys found: %d/%d", m->keys_found, m->keys_total); snprintf(draw_str, sizeof(draw_str), "Keys found: %d/%d", m->keys_found, m->keys_total);
@@ -100,6 +109,8 @@ void dict_attack_reset(DictAttack* dict_attack) {
model->sector_current = 0; model->sector_current = 0;
model->keys_total = 0; model->keys_total = 0;
model->keys_found = 0; model->keys_found = 0;
model->dict_keys_total = 0;
model->dict_keys_current = 0;
string_reset(model->header); string_reset(model->header);
return false; return false;
}); });
@@ -171,6 +182,7 @@ void dict_attack_set_current_sector(DictAttack* dict_attack, uint8_t curr_sec) {
with_view_model( with_view_model(
dict_attack->view, (DictAttackViewModel * model) { dict_attack->view, (DictAttackViewModel * model) {
model->sector_current = curr_sec; model->sector_current = curr_sec;
model->dict_keys_current = 0;
return true; return true;
}); });
} }
@@ -181,6 +193,7 @@ void dict_attack_inc_current_sector(DictAttack* dict_attack) {
dict_attack->view, (DictAttackViewModel * model) { dict_attack->view, (DictAttackViewModel * model) {
if(model->sector_current < model->sectors_total) { if(model->sector_current < model->sectors_total) {
model->sector_current++; model->sector_current++;
model->dict_keys_current = 0;
} }
return true; return true;
}); });
@@ -196,3 +209,23 @@ void dict_attack_inc_keys_found(DictAttack* dict_attack) {
return true; return true;
}); });
} }
void dict_attack_set_total_dict_keys(DictAttack* dict_attack, uint16_t dict_keys_total) {
furi_assert(dict_attack);
with_view_model(
dict_attack->view, (DictAttackViewModel * model) {
model->dict_keys_total = dict_keys_total;
return true;
});
}
void dict_attack_inc_current_dict_key(DictAttack* dict_attack, uint16_t keys_tried) {
furi_assert(dict_attack);
with_view_model(
dict_attack->view, (DictAttackViewModel * model) {
if(model->dict_keys_current + keys_tried < model->dict_keys_total) {
model->dict_keys_current += keys_tried;
}
return true;
});
}

View File

@@ -34,3 +34,7 @@ void dict_attack_set_current_sector(DictAttack* dict_attack, uint8_t curr_sec);
void dict_attack_inc_current_sector(DictAttack* dict_attack); void dict_attack_inc_current_sector(DictAttack* dict_attack);
void dict_attack_inc_keys_found(DictAttack* dict_attack); void dict_attack_inc_keys_found(DictAttack* dict_attack);
void dict_attack_set_total_dict_keys(DictAttack* dict_attack, uint16_t dict_keys_total);
void dict_attack_inc_current_dict_key(DictAttack* dict_attack, uint16_t keys_tried);

View File

@@ -57,7 +57,7 @@ BatteryTestApp* battery_test_alloc() {
battery_info_get_view(app->batery_info)); battery_info_get_view(app->batery_info));
app->dialog = dialog_ex_alloc(); app->dialog = dialog_ex_alloc();
dialog_ex_set_header(app->dialog, "Close battery test?", 64, 12, AlignCenter, AlignTop); dialog_ex_set_header(app->dialog, "Close Battery Test?", 64, 12, AlignCenter, AlignTop);
dialog_ex_set_left_button_text(app->dialog, "Exit"); dialog_ex_set_left_button_text(app->dialog, "Exit");
dialog_ex_set_right_button_text(app->dialog, "Stay"); dialog_ex_set_right_button_text(app->dialog, "Stay");
dialog_ex_set_result_callback(app->dialog, battery_test_dialog_callback); dialog_ex_set_result_callback(app->dialog, battery_test_dialog_callback);

View File

@@ -200,7 +200,7 @@ static void power_check_battery_level_change(Power* power) {
} }
int32_t power_srv(void* p) { int32_t power_srv(void* p) {
(void)p; UNUSED(p);
Power* power = power_alloc(); Power* power = power_alloc();
power_update_info(power); power_update_info(power);
furi_record_create(RECORD_POWER, power); furi_record_create(RECORD_POWER, power);

View File

@@ -76,7 +76,7 @@ void power_settings_app_free(PowerSettingsApp* app) {
int32_t power_settings_app(void* p) { int32_t power_settings_app(void* p) {
uint32_t first_scene = PowerSettingsAppSceneStart; uint32_t first_scene = PowerSettingsAppSceneStart;
if(p && !strcmp(p, "off")) { if(p && strlen(p) && !strcmp(p, "off")) {
first_scene = PowerSettingsAppScenePowerOff; first_scene = PowerSettingsAppScenePowerOff;
} }
PowerSettingsApp* app = power_settings_app_alloc(first_scene); PowerSettingsApp* app = power_settings_app_alloc(first_scene);

View File

@@ -10,7 +10,7 @@ void power_settings_scene_power_off_on_enter(void* context) {
PowerSettingsApp* app = context; PowerSettingsApp* app = context;
DialogEx* dialog = app->dialog; DialogEx* dialog = app->dialog;
dialog_ex_set_header(dialog, "Turn off Device?", 64, 2, AlignCenter, AlignTop); dialog_ex_set_header(dialog, "Turn Off Device?", 64, 2, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog, " I will be\nwaiting for\n you here...", 78, 16, AlignLeft, AlignTop); dialog, " I will be\nwaiting for\n you here...", 78, 16, AlignLeft, AlignTop);
dialog_ex_set_icon(dialog, 21, 13, &I_Cry_dolph_55x52); dialog_ex_set_icon(dialog, 21, 13, &I_Cry_dolph_55x52);

View File

@@ -541,7 +541,7 @@ static void rpc_system_storage_md5sum_process(const PB_Main* request, void* cont
(void)md5sum_size; (void)md5sum_size;
furi_assert(hash_size <= ((md5sum_size - 1) / 2)); furi_assert(hash_size <= ((md5sum_size - 1) / 2));
for(uint8_t i = 0; i < hash_size; i++) { for(uint8_t i = 0; i < hash_size; i++) {
md5sum += sprintf(md5sum, "%02x", hash[i]); md5sum += snprintf(md5sum, md5sum_size, "%02x", hash[i]);
} }
free(hash); free(hash);

View File

@@ -78,6 +78,8 @@ static void rpc_system_system_device_info_callback(
furi_assert(value); furi_assert(value);
RpcSystemContext* ctx = context; RpcSystemContext* ctx = context;
furi_assert(key);
furi_assert(value);
char* str_key = strdup(key); char* str_key = strdup(key);
char* str_value = strdup(value); char* str_value = strdup(value);
@@ -232,6 +234,8 @@ static void rpc_system_system_power_info_callback(
furi_assert(value); furi_assert(value);
RpcSystemContext* ctx = context; RpcSystemContext* ctx = context;
furi_assert(key);
furi_assert(value);
char* str_key = strdup(key); char* str_key = strdup(key);
char* str_value = strdup(value); char* str_value = strdup(value);

View File

@@ -82,7 +82,7 @@ static void storage_cli_format(Cli* cli, string_t path) {
if(string_cmp_str(path, STORAGE_INT_PATH_PREFIX) == 0) { if(string_cmp_str(path, STORAGE_INT_PATH_PREFIX) == 0) {
storage_cli_print_error(FSE_NOT_IMPLEMENTED); storage_cli_print_error(FSE_NOT_IMPLEMENTED);
} else if(string_cmp_str(path, STORAGE_EXT_PATH_PREFIX) == 0) { } else if(string_cmp_str(path, STORAGE_EXT_PATH_PREFIX) == 0) {
printf("Formatting SD card, all data will be lost. Are you sure (y/n)?\r\n"); printf("Formatting SD card, All data will be lost! Are you sure (y/n)?\r\n");
char answer = cli_getc(cli); char answer = cli_getc(cli);
if(answer == 'y' || answer == 'Y') { if(answer == 'y' || answer == 'Y') {
Storage* api = furi_record_open(RECORD_STORAGE); Storage* api = furi_record_open(RECORD_STORAGE);
@@ -581,7 +581,7 @@ void storage_cli(Cli* cli, string_t args, void* context) {
static void storage_cli_factory_reset(Cli* cli, string_t args, void* context) { static void storage_cli_factory_reset(Cli* cli, string_t args, void* context) {
UNUSED(args); UNUSED(args);
UNUSED(context); UNUSED(context);
printf("All data will be lost. Are you sure (y/n)?\r\n"); printf("All data will be lost! Are you sure (y/n)?\r\n");
char c = cli_getc(cli); char c = cli_getc(cli);
if(c == 'y' || c == 'Y') { if(c == 'y' || c == 'Y') {
printf("Data will be wiped after reboot.\r\n"); printf("Data will be wiped after reboot.\r\n");

View File

@@ -75,7 +75,7 @@ static bool
static void storage_settings_scene_benchmark(StorageSettings* app) { static void storage_settings_scene_benchmark(StorageSettings* app) {
DialogEx* dialog_ex = app->dialog_ex; DialogEx* dialog_ex = app->dialog_ex;
uint8_t* bench_data; uint8_t* bench_data;
dialog_ex_set_header(dialog_ex, "Preparing data...", 64, 32, AlignCenter, AlignCenter); dialog_ex_set_header(dialog_ex, "Preparing Data...", 64, 32, AlignCenter, AlignCenter);
bench_data = malloc(BENCH_DATA_SIZE); bench_data = malloc(BENCH_DATA_SIZE);
for(size_t i = 0; i < BENCH_DATA_SIZE; i++) { for(size_t i = 0; i < BENCH_DATA_SIZE; i++) {
@@ -123,7 +123,7 @@ void storage_settings_scene_benchmark_on_enter(void* context) {
if(sd_status != FSE_OK) { if(sd_status != FSE_OK) {
dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51); dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51);
dialog_ex_set_header(dialog_ex, "SD card not mounted", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "SD Card Not Mounted", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop); dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop);
dialog_ex_set_center_button_text(dialog_ex, "Ok"); dialog_ex_set_center_button_text(dialog_ex, "Ok");

View File

@@ -24,7 +24,7 @@ void storage_settings_scene_factory_reset_on_enter(void* context) {
dialog_ex_set_header(dialog_ex, "Confirm Factory Reset", 64, 10, AlignCenter, AlignCenter); dialog_ex_set_header(dialog_ex, "Confirm Factory Reset", 64, 10, AlignCenter, AlignCenter);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, dialog_ex,
"Internal storage will be erased\r\nData and setting will be lost", "Internal storage will be erased\r\nData and setting will be lost!",
64, 64,
32, 32,
AlignCenter, AlignCenter,

View File

@@ -15,13 +15,13 @@ void storage_settings_scene_format_confirm_on_enter(void* context) {
if(sd_status == FSE_NOT_READY) { if(sd_status == FSE_NOT_READY) {
dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51); dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51);
dialog_ex_set_header(dialog_ex, "SD card not mounted", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "SD Card Not Mounted", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop); dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop);
dialog_ex_set_center_button_text(dialog_ex, "Ok"); dialog_ex_set_center_button_text(dialog_ex, "Ok");
} else { } else {
dialog_ex_set_header(dialog_ex, "Format SD card?", 64, 10, AlignCenter, AlignCenter); dialog_ex_set_header(dialog_ex, "Format SD Card?", 64, 10, AlignCenter, AlignCenter);
dialog_ex_set_text(dialog_ex, "All data will be lost", 64, 32, AlignCenter, AlignCenter); dialog_ex_set_text(dialog_ex, "All data will be lost!", 64, 32, AlignCenter, AlignCenter);
dialog_ex_set_left_button_text(dialog_ex, "Cancel"); dialog_ex_set_left_button_text(dialog_ex, "Cancel");
dialog_ex_set_right_button_text(dialog_ex, "Format"); dialog_ex_set_right_button_text(dialog_ex, "Format");
} }

View File

@@ -43,7 +43,7 @@ void storage_settings_scene_formatting_on_enter(void* context) {
dialog_ex_set_result_callback(dialog_ex, storage_settings_scene_formatting_dialog_callback); dialog_ex_set_result_callback(dialog_ex, storage_settings_scene_formatting_dialog_callback);
if(error != FSE_OK) { if(error != FSE_OK) {
dialog_ex_set_header(dialog_ex, "Cannot format SD Card", 64, 10, AlignCenter, AlignCenter); dialog_ex_set_header(dialog_ex, "Cannot Format SD Card", 64, 10, AlignCenter, AlignCenter);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, storage_error_get_desc(error), 64, 32, AlignCenter, AlignCenter); dialog_ex, storage_error_get_desc(error), 64, 32, AlignCenter, AlignCenter);
} else { } else {

View File

@@ -21,7 +21,7 @@ void storage_settings_scene_internal_info_on_enter(void* context) {
if(error != FSE_OK) { if(error != FSE_OK) {
dialog_ex_set_header( dialog_ex_set_header(
dialog_ex, "Internal storage error", 64, 10, AlignCenter, AlignCenter); dialog_ex, "Internal Storage Error", 64, 10, AlignCenter, AlignCenter);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, storage_error_get_desc(error), 64, 32, AlignCenter, AlignCenter); dialog_ex, storage_error_get_desc(error), 64, 32, AlignCenter, AlignCenter);
} else { } else {

View File

@@ -19,7 +19,7 @@ void storage_settings_scene_sd_info_on_enter(void* context) {
if(sd_status != FSE_OK) { if(sd_status != FSE_OK) {
dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51); dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51);
dialog_ex_set_header(dialog_ex, "SD card not mounted", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "SD Card Not Mounted", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop); dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop);
dialog_ex_set_center_button_text(dialog_ex, "Ok"); dialog_ex_set_center_button_text(dialog_ex, "Ok");

View File

@@ -15,12 +15,12 @@ void storage_settings_scene_unmount_confirm_on_enter(void* context) {
if(sd_status == FSE_NOT_READY) { if(sd_status == FSE_NOT_READY) {
dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51); dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51);
dialog_ex_set_header(dialog_ex, "SD card not mounted", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "SD Card Not Mounted", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop); dialog_ex, "Try to reinsert\nor format SD\ncard.", 3, 19, AlignLeft, AlignTop);
dialog_ex_set_center_button_text(dialog_ex, "Ok"); dialog_ex_set_center_button_text(dialog_ex, "Ok");
} else { } else {
dialog_ex_set_header(dialog_ex, "Unmount SD card?", 64, 10, AlignCenter, AlignCenter); dialog_ex_set_header(dialog_ex, "Unmount SD Card?", 64, 10, AlignCenter, AlignCenter);
dialog_ex_set_text( dialog_ex_set_text(
dialog_ex, "SD card will be\nunavailable", 64, 32, AlignCenter, AlignCenter); dialog_ex, "SD card will be\nunavailable", 64, 32, AlignCenter, AlignCenter);
dialog_ex_set_left_button_text(dialog_ex, "Cancel"); dialog_ex_set_left_button_text(dialog_ex, "Cancel");

View File

@@ -16,11 +16,11 @@ void storage_settings_scene_unmounted_on_enter(void* context) {
dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51); dialog_ex_set_icon(dialog_ex, 72, 14, &I_DolphinFirstStart8_56x51);
if(error == FSE_OK) { if(error == FSE_OK) {
dialog_ex_set_header(dialog_ex, "SD card unmounted", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "SD Card Unmounted", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text(dialog_ex, "You can remove\nSD card now.", 3, 22, AlignLeft, AlignTop); dialog_ex_set_text(dialog_ex, "You can remove\nSD card now.", 3, 22, AlignLeft, AlignTop);
notification_message(app->notification, &sequence_blink_green_100); notification_message(app->notification, &sequence_blink_green_100);
} else { } else {
dialog_ex_set_header(dialog_ex, "Cannot unmount SD Card", 64, 3, AlignCenter, AlignTop); dialog_ex_set_header(dialog_ex, "Cannot Unmount SD Card", 64, 3, AlignCenter, AlignTop);
dialog_ex_set_text(dialog_ex, storage_error_get_desc(error), 3, 22, AlignLeft, AlignTop); dialog_ex_set_text(dialog_ex, storage_error_get_desc(error), 3, 22, AlignLeft, AlignTop);
notification_message(app->notification, &sequence_blink_red_100); notification_message(app->notification, &sequence_blink_red_100);
} }

View File

@@ -73,8 +73,9 @@ static void subghz_scene_receiver_config_set_frequency(VariableItem* item) {
if(subghz->txrx->hopper_state == SubGhzHopperStateOFF) { if(subghz->txrx->hopper_state == SubGhzHopperStateOFF) {
char text_buf[10] = {0}; char text_buf[10] = {0};
sprintf( snprintf(
text_buf, text_buf,
sizeof(text_buf),
"%lu.%02lu", "%lu.%02lu",
subghz_setting_get_frequency(subghz->setting, index) / 1000000, subghz_setting_get_frequency(subghz->setting, index) / 1000000,
(subghz_setting_get_frequency(subghz->setting, index) % 1000000) / 10000); (subghz_setting_get_frequency(subghz->setting, index) % 1000000) / 10000);
@@ -106,8 +107,9 @@ static void subghz_scene_receiver_config_set_hopping_runing(VariableItem* item)
variable_item_set_current_value_text(item, hopping_text[index]); variable_item_set_current_value_text(item, hopping_text[index]);
if(hopping_value[index] == SubGhzHopperStateOFF) { if(hopping_value[index] == SubGhzHopperStateOFF) {
char text_buf[10] = {0}; char text_buf[10] = {0};
sprintf( snprintf(
text_buf, text_buf,
sizeof(text_buf),
"%lu.%02lu", "%lu.%02lu",
subghz_setting_get_default_frequency(subghz->setting) / 1000000, subghz_setting_get_default_frequency(subghz->setting) / 1000000,
(subghz_setting_get_default_frequency(subghz->setting) % 1000000) / 10000); (subghz_setting_get_default_frequency(subghz->setting) % 1000000) / 10000);
@@ -160,8 +162,9 @@ void subghz_scene_receiver_config_on_enter(void* context) {
subghz->scene_manager, SubGhzSceneReceiverConfig, (uint32_t)item); subghz->scene_manager, SubGhzSceneReceiverConfig, (uint32_t)item);
variable_item_set_current_value_index(item, value_index); variable_item_set_current_value_index(item, value_index);
char text_buf[10] = {0}; char text_buf[10] = {0};
sprintf( snprintf(
text_buf, text_buf,
sizeof(text_buf),
"%lu.%02lu", "%lu.%02lu",
subghz_setting_get_frequency(subghz->setting, value_index) / 1000000, subghz_setting_get_frequency(subghz->setting, value_index) / 1000000,
(subghz_setting_get_frequency(subghz->setting, value_index) % 1000000) / 10000); (subghz_setting_get_frequency(subghz->setting, value_index) % 1000000) / 10000);

View File

@@ -59,8 +59,8 @@ void subghz_scene_save_name_on_enter(void* context) {
MAX_TEXT_INPUT_LEN, // buffer size MAX_TEXT_INPUT_LEN, // buffer size
dev_name_empty); dev_name_empty);
ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( ValidatorIsFile* validator_is_file =
string_get_cstr(subghz->file_path), SUBGHZ_APP_EXTENSION, NULL); validator_is_file_alloc_init(string_get_cstr(subghz->file_path), SUBGHZ_APP_EXTENSION, "");
text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); text_input_set_validator(text_input, validator_is_file_callback, validator_is_file);
string_clear(file_name); string_clear(file_name);

View File

@@ -331,7 +331,7 @@ int32_t subghz_app(void* p) {
subghz_environment_load_keystore( subghz_environment_load_keystore(
subghz->txrx->environment, EXT_PATH("subghz/assets/keeloq_mfcodes_user")); subghz->txrx->environment, EXT_PATH("subghz/assets/keeloq_mfcodes_user"));
// Check argument and run corresponding scene // Check argument and run corresponding scene
if(p) { if(p && strlen(p)) {
uint32_t rpc_ctx = 0; uint32_t rpc_ctx = 0;
if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) { if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) {
subghz->rpc_ctx = (void*)rpc_ctx; subghz->rpc_ctx = (void*)rpc_ctx;

View File

@@ -189,8 +189,9 @@ static void clean_directory(Storage* fs_api, const char* clean_dir) {
FileInfo fileinfo; FileInfo fileinfo;
char* name = malloc(MAX_NAME_LENGTH + 1); char* name = malloc(MAX_NAME_LENGTH + 1);
while(storage_dir_read(dir, &fileinfo, name, MAX_NAME_LENGTH)) { while(storage_dir_read(dir, &fileinfo, name, MAX_NAME_LENGTH)) {
char* fullname = malloc(strlen(clean_dir) + strlen(name) + 1 + 1); size_t size = strlen(clean_dir) + strlen(name) + 1 + 1;
sprintf(fullname, "%s/%s", clean_dir, name); char* fullname = malloc(size);
snprintf(fullname, size, "%s/%s", clean_dir, name);
if(fileinfo.flags & FSF_DIRECTORY) { if(fileinfo.flags & FSF_DIRECTORY) {
clean_directory(fs_api, fullname); clean_directory(fs_api, fullname);
} }
@@ -420,11 +421,13 @@ static void
mu_check(result_msg_file->size == expected_msg_file->size); mu_check(result_msg_file->size == expected_msg_file->size);
mu_check(result_msg_file->type == expected_msg_file->type); mu_check(result_msg_file->type == expected_msg_file->type);
mu_check(!result_msg_file->data == !expected_msg_file->data); if(result_msg_file->data && result_msg_file->type != PB_Storage_File_FileType_DIR) {
mu_check(!result_msg_file->data == !expected_msg_file->data); // Zlo: WTF???
mu_check(result_msg_file->data->size == expected_msg_file->data->size); mu_check(result_msg_file->data->size == expected_msg_file->data->size);
for(int i = 0; i < result_msg_file->data->size; ++i) { for(int i = 0; i < result_msg_file->data->size; ++i) {
mu_check(result_msg_file->data->bytes[i] == expected_msg_file->data->bytes[i]); mu_check(result_msg_file->data->bytes[i] == expected_msg_file->data->bytes[i]);
} }
}
} }
static void test_rpc_compare_messages(PB_Main* result, PB_Main* expected) { static void test_rpc_compare_messages(PB_Main* result, PB_Main* expected) {
@@ -1224,7 +1227,7 @@ MU_TEST(test_storage_mkdir) {
mu_check(test_is_exists(TEST_DIR "dir2")); mu_check(test_is_exists(TEST_DIR "dir2"));
} }
static void test_storage_calculate_md5sum(const char* path, char* md5sum) { static void test_storage_calculate_md5sum(const char* path, char* md5sum, size_t md5sum_size) {
Storage* api = furi_record_open(RECORD_STORAGE); Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api); File* file = storage_file_alloc(api);
@@ -1245,7 +1248,7 @@ static void test_storage_calculate_md5sum(const char* path, char* md5sum) {
free(md5_ctx); free(md5_ctx);
for(uint8_t i = 0; i < hash_size; i++) { for(uint8_t i = 0; i < hash_size; i++) {
md5sum += sprintf(md5sum, "%02x", hash[i]); md5sum += snprintf(md5sum, md5sum_size, "%02x", hash[i]);
} }
free(hash); free(hash);
@@ -1297,9 +1300,9 @@ MU_TEST(test_storage_md5sum) {
test_create_file(TEST_DIR "file1.txt", 0); test_create_file(TEST_DIR "file1.txt", 0);
test_create_file(TEST_DIR "file2.txt", 1); test_create_file(TEST_DIR "file2.txt", 1);
test_create_file(TEST_DIR "file3.txt", 512); test_create_file(TEST_DIR "file3.txt", 512);
test_storage_calculate_md5sum(TEST_DIR "file1.txt", md5sum1); test_storage_calculate_md5sum(TEST_DIR "file1.txt", md5sum1, MD5SUM_SIZE * 2 + 1);
test_storage_calculate_md5sum(TEST_DIR "file2.txt", md5sum2); test_storage_calculate_md5sum(TEST_DIR "file2.txt", md5sum2, MD5SUM_SIZE * 2 + 1);
test_storage_calculate_md5sum(TEST_DIR "file3.txt", md5sum3); test_storage_calculate_md5sum(TEST_DIR "file3.txt", md5sum3, MD5SUM_SIZE * 2 + 1);
test_storage_md5sum_run(TEST_DIR "file1.txt", ++command_id, md5sum1, PB_CommandStatus_OK); test_storage_md5sum_run(TEST_DIR "file1.txt", ++command_id, md5sum1, PB_CommandStatus_OK);
test_storage_md5sum_run(TEST_DIR "file1.txt", ++command_id, md5sum1, PB_CommandStatus_OK); test_storage_md5sum_run(TEST_DIR "file1.txt", ++command_id, md5sum1, PB_CommandStatus_OK);
@@ -1346,8 +1349,7 @@ static void test_rpc_storage_rename_run(
} }
MU_TEST(test_storage_rename) { MU_TEST(test_storage_rename) {
test_rpc_storage_rename_run( test_rpc_storage_rename_run("", "", ++command_id, PB_CommandStatus_ERROR_STORAGE_INVALID_NAME);
NULL, NULL, ++command_id, PB_CommandStatus_ERROR_STORAGE_INVALID_NAME);
furi_check(!test_is_exists(TEST_DIR "empty.txt")); furi_check(!test_is_exists(TEST_DIR "empty.txt"));
test_create_file(TEST_DIR "empty.txt", 0); test_create_file(TEST_DIR "empty.txt", 0);

View File

@@ -34,7 +34,7 @@ static void
Updater* updater_alloc(const char* arg) { Updater* updater_alloc(const char* arg) {
Updater* updater = malloc(sizeof(Updater)); Updater* updater = malloc(sizeof(Updater));
if(arg) { if(arg && strlen(arg)) {
string_init_set_str(updater->startup_arg, arg); string_init_set_str(updater->startup_arg, arg);
string_replace_str(updater->startup_arg, ANY_PATH(""), EXT_PATH("")); string_replace_str(updater->startup_arg, ANY_PATH(""), EXT_PATH(""));
} else { } else {

View File

@@ -24,6 +24,19 @@ To build with FBT, call it specifying configuration options & targets to build.
To run cleanup (think of `make clean`) for specified targets, add `-c` option. To run cleanup (think of `make clean`) for specified targets, add `-c` option.
## VSCode integration
`fbt` includes basic development environment configuration for VSCode. To deploy it, run `./fbt vscode_dist`. That will copy initial environment configuration to `.vscode` folder. After that, you can use that configuration by starting VSCode and choosing firmware root folder in "File > Open Folder" menu.
* On first start, you'll be prompted to install recommended plug-ins. Please install them for best development experience. _You can find a list of them in `.vscode/extensions.json`._
* Basic build tasks are invoked in Ctrl+Shift+B menu.
* Debugging requires a supported probe. That includes:
* Wi-Fi devboard with stock firmware (blackmagic),
* ST-Link and compatible devices,
* J-Link for flashing and debugging (in VSCode only). _Note that J-Link tools are not included with our toolchain and you have to [download](https://www.segger.com/downloads/jlink/) them yourself and put on your system's PATH._
* Without a supported probe, you can install firmware on Flipper using USB installation method.
## FBT targets ## FBT targets
FBT keeps track of internal dependencies, so you only need to build the highest-level target you need, and FBT will make sure everything they depend on is up-to-date. FBT keeps track of internal dependencies, so you only need to build the highest-level target you need, and FBT will make sure everything they depend on is up-to-date.

View File

@@ -164,8 +164,6 @@ fwenv.AppendUnique(
"-Wl,--wrap,_free_r", "-Wl,--wrap,_free_r",
"-Wl,--wrap,_calloc_r", "-Wl,--wrap,_calloc_r",
"-Wl,--wrap,_realloc_r", "-Wl,--wrap,_realloc_r",
"-u",
"_printf_float",
"-n", "-n",
"-Xlinker", "-Xlinker",
"-Map=${TARGET}.map", "-Map=${TARGET}.map",
@@ -181,6 +179,7 @@ fwelf = fwenv["FW_ELF"] = fwenv.Program(
"${FIRMWARE_BUILD_CFG}", "${FIRMWARE_BUILD_CFG}",
sources, sources,
LIBS=[ LIBS=[
"print",
"flipper${TARGET_HW}", "flipper${TARGET_HW}",
"furi", "furi",
"freertos", "freertos",

View File

@@ -32,7 +32,7 @@ extern uint32_t SystemCoreClock;
#define configUSE_16_BIT_TICKS 0 #define configUSE_16_BIT_TICKS 0
#define configUSE_MUTEXES 1 #define configUSE_MUTEXES 1
#define configQUEUE_REGISTRY_SIZE 0 #define configQUEUE_REGISTRY_SIZE 0
#define configCHECK_FOR_STACK_OVERFLOW 2 #define configCHECK_FOR_STACK_OVERFLOW 0
#define configUSE_RECURSIVE_MUTEXES 1 #define configUSE_RECURSIVE_MUTEXES 1
#define configUSE_COUNTING_SEMAPHORES 1 #define configUSE_COUNTING_SEMAPHORES 1
#define configENABLE_BACKWARD_COMPATIBILITY 0 #define configENABLE_BACKWARD_COMPATIBILITY 0
@@ -145,3 +145,7 @@ standard names. */
#define USE_CUSTOM_SYSTICK_HANDLER_IMPLEMENTATION 1 #define USE_CUSTOM_SYSTICK_HANDLER_IMPLEMENTATION 1
#define configOVERRIDE_DEFAULT_TICK_CONFIGURATION \ #define configOVERRIDE_DEFAULT_TICK_CONFIGURATION \
1 /* required only for Keil but does not hurt otherwise */ 1 /* required only for Keil but does not hurt otherwise */
#define traceTASK_SWITCHED_IN() \
extern void furi_hal_mpu_set_stack_protection(uint32_t* stack); \
furi_hal_mpu_set_stack_protection((uint32_t*)pxCurrentTCB->pxStack)

View File

@@ -19,7 +19,7 @@ void flipper_boot_dfu_show_splash() {
u8g2_DrawXBM(fb, 0, 64 - 50, 128, 50, splash_data); u8g2_DrawXBM(fb, 0, 64 - 50, 128, 50, splash_data);
u8g2_SetFont(fb, u8g2_font_helvB08_tr); u8g2_SetFont(fb, u8g2_font_helvB08_tr);
u8g2_DrawStr(fb, 2, 8, "Update & Recovery Mode"); u8g2_DrawStr(fb, 2, 8, "Update & Recovery Mode");
u8g2_DrawStr(fb, 2, 21, "DFU started"); u8g2_DrawStr(fb, 2, 21, "DFU Started");
u8g2_SetPowerSave(fb, 0); u8g2_SetPowerSave(fb, 0);
u8g2_SendBuffer(fb); u8g2_SendBuffer(fb);
} }

View File

@@ -1,4 +1,5 @@
#include <furi_hal.h> #include <furi_hal.h>
#include <furi_hal_mpu.h>
#include <stm32wbxx_ll_cortex.h> #include <stm32wbxx_ll_cortex.h>
@@ -35,6 +36,7 @@ void furi_hal_deinit_early() {
} }
void furi_hal_init() { void furi_hal_init() {
furi_hal_mpu_init();
furi_hal_clock_init(); furi_hal_clock_init();
furi_hal_console_init(); furi_hal_console_init();
furi_hal_rtc_init(); furi_hal_rtc_init();
@@ -80,17 +82,6 @@ void furi_hal_init() {
// FatFS driver initialization // FatFS driver initialization
MX_FATFS_Init(); MX_FATFS_Init();
FURI_LOG_I(TAG, "FATFS OK"); FURI_LOG_I(TAG, "FATFS OK");
// Partial null pointer dereference protection
LL_MPU_Disable();
LL_MPU_ConfigRegion(
LL_MPU_REGION_NUMBER0,
0x00,
0x0,
LL_MPU_REGION_SIZE_1MB | LL_MPU_REGION_PRIV_RO_URO | LL_MPU_ACCESS_BUFFERABLE |
LL_MPU_ACCESS_CACHEABLE | LL_MPU_ACCESS_SHAREABLE | LL_MPU_TEX_LEVEL1 |
LL_MPU_INSTRUCTION_ACCESS_ENABLE);
LL_MPU_Enable(LL_MPU_CTRL_PRIVILEGED_DEFAULT);
} }
void furi_hal_switch(void* address) { void furi_hal_switch(void* address) {

View File

@@ -6,6 +6,7 @@
#include <stm32wbxx.h> #include <stm32wbxx.h>
#include <stm32wbxx_ll_tim.h> #include <stm32wbxx_ll_tim.h>
#include <stm32wbxx_ll_rcc.h> #include <stm32wbxx_ll_rcc.h>
#include <stm32wbxx_ll_cortex.h>
#define TAG "FuriHalInterrupt" #define TAG "FuriHalInterrupt"
@@ -95,6 +96,10 @@ void furi_hal_interrupt_init() {
LL_SYSCFG_DisableIT_FPU_IDC(); LL_SYSCFG_DisableIT_FPU_IDC();
LL_SYSCFG_DisableIT_FPU_IXC(); LL_SYSCFG_DisableIT_FPU_IXC();
LL_HANDLER_EnableFault(LL_HANDLER_FAULT_USG);
LL_HANDLER_EnableFault(LL_HANDLER_FAULT_BUS);
LL_HANDLER_EnableFault(LL_HANDLER_FAULT_MEM);
FURI_LOG_I(TAG, "Init OK"); FURI_LOG_I(TAG, "Init OK");
} }
@@ -241,6 +246,20 @@ void HardFault_Handler() {
} }
void MemManage_Handler() { void MemManage_Handler() {
if(FURI_BIT(SCB->CFSR, SCB_CFSR_MMARVALID_Pos)) {
uint32_t memfault_address = SCB->MMFAR;
if(memfault_address < (1024 * 1024)) {
// from 0x00 to 1MB, see FuriHalMpuRegionNULL
furi_crash("NULL pointer dereference");
} else {
// write or read of MPU region 1 (FuriHalMpuRegionStack)
furi_crash("MPU fault, possibly stack overflow");
}
} else if(FURI_BIT(SCB->CFSR, SCB_CFSR_MSTKERR_Pos)) {
// push to stack on MPU region 1 (FuriHalMpuRegionStack)
furi_crash("MemManage fault, possibly stack overflow");
}
furi_crash("MemManage"); furi_crash("MemManage");
} }

View File

@@ -0,0 +1,66 @@
#include <furi_hal_mpu.h>
#include <stm32wbxx_ll_cortex.h>
#define FURI_HAL_MPU_ATTRIBUTES \
(LL_MPU_ACCESS_BUFFERABLE | LL_MPU_ACCESS_CACHEABLE | LL_MPU_ACCESS_SHAREABLE | \
LL_MPU_TEX_LEVEL1 | LL_MPU_INSTRUCTION_ACCESS_ENABLE)
#define FURI_HAL_MPU_STACK_PROTECT_REGION FuriHalMPURegionSize32B
void furi_hal_mpu_init() {
furi_hal_mpu_enable();
// NULL pointer dereference protection
furi_hal_mpu_protect_no_access(FuriHalMpuRegionNULL, 0x00, FuriHalMPURegionSize1MB);
}
void furi_hal_mpu_enable() {
LL_MPU_Enable(LL_MPU_CTRL_PRIVILEGED_DEFAULT);
}
void furi_hal_mpu_disable() {
LL_MPU_Disable();
}
void furi_hal_mpu_protect_no_access(
FuriHalMpuRegion region,
uint32_t address,
FuriHalMPURegionSize size) {
uint32_t size_ll = size;
size_ll = size_ll << MPU_RASR_SIZE_Pos;
furi_hal_mpu_disable();
LL_MPU_ConfigRegion(
region, 0x00, address, FURI_HAL_MPU_ATTRIBUTES | LL_MPU_REGION_NO_ACCESS | size_ll);
furi_hal_mpu_enable();
}
void furi_hal_mpu_protect_read_only(
FuriHalMpuRegion region,
uint32_t address,
FuriHalMPURegionSize size) {
uint32_t size_ll = size;
size_ll = size_ll << MPU_RASR_SIZE_Pos;
furi_hal_mpu_disable();
LL_MPU_ConfigRegion(
region, 0x00, address, FURI_HAL_MPU_ATTRIBUTES | LL_MPU_REGION_PRIV_RO_URO | size_ll);
furi_hal_mpu_enable();
}
void furi_hal_mpu_protect_disable(FuriHalMpuRegion region) {
furi_hal_mpu_disable();
LL_MPU_DisableRegion(region);
furi_hal_mpu_enable();
}
void furi_hal_mpu_set_stack_protection(uint32_t* stack) {
// Protection area address must be aligned to region size
uint32_t stack_ptr = (uint32_t)stack;
uint32_t mask = ((1 << (FURI_HAL_MPU_STACK_PROTECT_REGION + 2)) - 1);
stack_ptr &= ~mask;
if(stack_ptr < (uint32_t)stack) stack_ptr += (mask + 1);
furi_hal_mpu_protect_read_only(
FuriHalMpuRegionStack, stack_ptr, FURI_HAL_MPU_STACK_PROTECT_REGION);
}

View File

@@ -0,0 +1,86 @@
/**
* @file furi_hal_light.h
* Light control HAL API
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
FuriHalMpuRegionNULL = 0x00, // region 0 used to protect null pointer dereference
FuriHalMpuRegionStack = 0x01, // region 1 used to protect stack
FuriHalMpuRegion2 = 0x02,
FuriHalMpuRegion3 = 0x03,
FuriHalMpuRegion4 = 0x04,
FuriHalMpuRegion5 = 0x05,
FuriHalMpuRegion6 = 0x06,
FuriHalMpuRegion7 = 0x07,
} FuriHalMpuRegion;
typedef enum {
FuriHalMPURegionSize32B = 0x04U,
FuriHalMPURegionSize64B = 0x05U,
FuriHalMPURegionSize128B = 0x06U,
FuriHalMPURegionSize256B = 0x07U,
FuriHalMPURegionSize512B = 0x08U,
FuriHalMPURegionSize1KB = 0x09U,
FuriHalMPURegionSize2KB = 0x0AU,
FuriHalMPURegionSize4KB = 0x0BU,
FuriHalMPURegionSize8KB = 0x0CU,
FuriHalMPURegionSize16KB = 0x0DU,
FuriHalMPURegionSize32KB = 0x0EU,
FuriHalMPURegionSize64KB = 0x0FU,
FuriHalMPURegionSize128KB = 0x10U,
FuriHalMPURegionSize256KB = 0x11U,
FuriHalMPURegionSize512KB = 0x12U,
FuriHalMPURegionSize1MB = 0x13U,
FuriHalMPURegionSize2MB = 0x14U,
FuriHalMPURegionSize4MB = 0x15U,
FuriHalMPURegionSize8MB = 0x16U,
FuriHalMPURegionSize16MB = 0x17U,
FuriHalMPURegionSize32MB = 0x18U,
FuriHalMPURegionSize64MB = 0x19U,
FuriHalMPURegionSize128MB = 0x1AU,
FuriHalMPURegionSize256MB = 0x1BU,
FuriHalMPURegionSize512MB = 0x1CU,
FuriHalMPURegionSize1GB = 0x1DU,
FuriHalMPURegionSize2GB = 0x1EU,
FuriHalMPURegionSize4GB = 0x1FU,
} FuriHalMPURegionSize;
/**
* @brief Initialize memory protection unit
*/
void furi_hal_mpu_init();
/**
* @brief Enable memory protection unit
*/
void furi_hal_mpu_enable();
/**
* @brief Disable memory protection unit
*/
void furi_hal_mpu_disable();
void furi_hal_mpu_protect_no_access(
FuriHalMpuRegion region,
uint32_t address,
FuriHalMPURegionSize size);
void furi_hal_mpu_protect_read_only(
FuriHalMpuRegion region,
uint32_t address,
FuriHalMPURegionSize size);
void furi_hal_mpu_protect_disable(FuriHalMpuRegion region);
#ifdef __cplusplus
}
#endif

View File

@@ -36,10 +36,8 @@ void* calloc(size_t count, size_t size) {
} }
char* strdup(const char* s) { char* strdup(const char* s) {
const char* s_null = s; // arg s marked as non-null, so we need hack to check for NULL
if(s_null == NULL) { furi_check(((uint32_t)s << 2) != 0);
return NULL;
}
size_t siz = strlen(s) + 1; size_t siz = strlen(s) + 1;
char* y = pvPortMalloc(siz); char* y = pvPortMalloc(siz);

View File

@@ -1,102 +0,0 @@
#include "stdglue.h"
#include "check.h"
#include "memmgr.h"
#include <FreeRTOS.h>
#include <task.h>
#include <furi_hal.h>
#include <m-dict.h>
DICT_DEF2(
FuriStdglueCallbackDict,
uint32_t,
M_DEFAULT_OPLIST,
FuriStdglueWriteCallback,
M_PTR_OPLIST)
typedef struct {
FuriMutex* mutex;
FuriStdglueCallbackDict_t thread_outputs;
} FuriStdglue;
static FuriStdglue* furi_stdglue = NULL;
static ssize_t stdout_write(void* _cookie, const char* data, size_t size) {
furi_assert(furi_stdglue);
bool consumed = false;
FuriThreadId task_id = furi_thread_get_current_id();
if(xTaskGetSchedulerState() == taskSCHEDULER_RUNNING && task_id &&
furi_mutex_acquire(furi_stdglue->mutex, FuriWaitForever) == FuriStatusOk) {
// We are in the thread context
// Handle thread callbacks
FuriStdglueWriteCallback* callback_ptr =
FuriStdglueCallbackDict_get(furi_stdglue->thread_outputs, (uint32_t)task_id);
if(callback_ptr) {
(*callback_ptr)(_cookie, data, size);
consumed = true;
}
furi_check(furi_mutex_release(furi_stdglue->mutex) == FuriStatusOk);
}
// Flush
if(data == 0) {
/*
* This means that we should flush internal buffers. Since we
* don't we just return. (Remember, "handle" == -1 means that all
* handles should be flushed.)
*/
return 0;
}
// Debug uart
if(!consumed) furi_hal_console_tx((const uint8_t*)data, size);
// All data consumed
return size;
}
void furi_stdglue_init() {
furi_stdglue = malloc(sizeof(FuriStdglue));
// Init outputs structures
furi_stdglue->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
furi_check(furi_stdglue->mutex);
FuriStdglueCallbackDict_init(furi_stdglue->thread_outputs);
// Prepare and set stdout descriptor
FILE* fp = fopencookie(
NULL,
"w",
(cookie_io_functions_t){
.read = NULL,
.write = stdout_write,
.seek = NULL,
.close = NULL,
});
setvbuf(fp, NULL, _IOLBF, 0);
stdout = fp;
}
bool furi_stdglue_set_thread_stdout_callback(FuriStdglueWriteCallback callback) {
furi_assert(furi_stdglue);
FuriThreadId task_id = furi_thread_get_current_id();
if(task_id) {
furi_check(furi_mutex_acquire(furi_stdglue->mutex, FuriWaitForever) == FuriStatusOk);
if(callback) {
FuriStdglueCallbackDict_set_at(
furi_stdglue->thread_outputs, (uint32_t)task_id, callback);
} else {
FuriStdglueCallbackDict_erase(furi_stdglue->thread_outputs, (uint32_t)task_id);
}
furi_check(furi_mutex_release(furi_stdglue->mutex) == FuriStatusOk);
return true;
} else {
return false;
}
}
void __malloc_lock(struct _reent* REENT) {
UNUSED(REENT);
vTaskSuspendAll();
}
void __malloc_unlock(struct _reent* REENT) {
UNUSED(REENT);
xTaskResumeAll();
}

View File

@@ -1,36 +0,0 @@
/**
* @file stdglue.h
* Furi: stdlibc glue
*/
#pragma once
#include <stdbool.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Write callback
* @param _cookie pointer to cookie (see stdio gnu extension)
* @param data pointer to data
* @param size data size @warnign your handler must consume everything
*/
typedef void (*FuriStdglueWriteCallback)(void* _cookie, const char* data, size_t size);
/** Initialized std library glue code */
void furi_stdglue_init();
/** Set STDOUT callback for your thread
*
* @param callback callback or NULL to clear
*
* @return true on success, otherwise fail
* @warning function is thread aware, use this API from the same thread
*/
bool furi_stdglue_set_thread_stdout_callback(FuriStdglueWriteCallback callback);
#ifdef __cplusplus
}
#endif

View File

@@ -4,12 +4,21 @@
#include "memmgr_heap.h" #include "memmgr_heap.h"
#include "check.h" #include "check.h"
#include "common_defines.h" #include "common_defines.h"
#include "mutex.h"
#include <task.h> #include <task.h>
#include <m-string.h> #include <m-string.h>
#include <furi_hal_console.h>
#define THREAD_NOTIFY_INDEX 1 // Index 0 is used for stream buffers #define THREAD_NOTIFY_INDEX 1 // Index 0 is used for stream buffers
typedef struct FuriThreadStdout FuriThreadStdout;
struct FuriThreadStdout {
FuriThreadStdoutWriteCallback write_callback;
string_t buffer;
};
struct FuriThread { struct FuriThread {
FuriThreadState state; FuriThreadState state;
int32_t ret; int32_t ret;
@@ -27,8 +36,13 @@ struct FuriThread {
TaskHandle_t task_handle; TaskHandle_t task_handle;
bool heap_trace_enabled; bool heap_trace_enabled;
size_t heap_size; size_t heap_size;
FuriThreadStdout output;
}; };
static size_t __furi_thread_stdout_write(FuriThread* thread, const char* data, size_t size);
static int32_t __furi_thread_stdout_flush(FuriThread* thread);
/** Catch threads that are trying to exit wrong way */ /** Catch threads that are trying to exit wrong way */
__attribute__((__noreturn__)) void furi_thread_catch() { __attribute__((__noreturn__)) void furi_thread_catch() {
asm volatile("nop"); // extra magic asm volatile("nop"); // extra magic
@@ -47,6 +61,10 @@ static void furi_thread_body(void* context) {
furi_assert(context); furi_assert(context);
FuriThread* thread = context; FuriThread* thread = context;
// store thread instance to thread local storage
furi_assert(pvTaskGetThreadLocalStoragePointer(NULL, 0) == NULL);
vTaskSetThreadLocalStoragePointer(NULL, 0, thread);
furi_assert(thread->state == FuriThreadStateStarting); furi_assert(thread->state == FuriThreadStateStarting);
furi_thread_set_state(thread, FuriThreadStateRunning); furi_thread_set_state(thread, FuriThreadStateRunning);
@@ -66,12 +84,18 @@ static void furi_thread_body(void* context) {
furi_assert(thread->state == FuriThreadStateRunning); furi_assert(thread->state == FuriThreadStateRunning);
furi_thread_set_state(thread, FuriThreadStateStopped); furi_thread_set_state(thread, FuriThreadStateStopped);
// clear thread local storage
__furi_thread_stdout_flush(thread);
furi_assert(pvTaskGetThreadLocalStoragePointer(NULL, 0) != NULL);
vTaskSetThreadLocalStoragePointer(NULL, 0, NULL);
vTaskDelete(thread->task_handle); vTaskDelete(thread->task_handle);
furi_thread_catch(); furi_thread_catch();
} }
FuriThread* furi_thread_alloc() { FuriThread* furi_thread_alloc() {
FuriThread* thread = malloc(sizeof(FuriThread)); FuriThread* thread = malloc(sizeof(FuriThread));
string_init(thread->output.buffer);
return thread; return thread;
} }
@@ -81,6 +105,8 @@ void furi_thread_free(FuriThread* thread) {
furi_assert(thread->state == FuriThreadStateStopped); furi_assert(thread->state == FuriThreadStateStopped);
if(thread->name) free((void*)thread->name); if(thread->name) free((void*)thread->name);
string_clear(thread->output.buffer);
free(thread); free(thread);
} }
@@ -88,7 +114,7 @@ void furi_thread_set_name(FuriThread* thread, const char* name) {
furi_assert(thread); furi_assert(thread);
furi_assert(thread->state == FuriThreadStateStopped); furi_assert(thread->state == FuriThreadStateStopped);
if(thread->name) free((void*)thread->name); if(thread->name) free((void*)thread->name);
thread->name = strdup(name); thread->name = name ? strdup(name) : NULL;
} }
void furi_thread_set_stack_size(FuriThread* thread, size_t stack_size) { void furi_thread_set_stack_size(FuriThread* thread, size_t stack_size) {
@@ -199,6 +225,12 @@ FuriThreadId furi_thread_get_current_id() {
return xTaskGetCurrentTaskHandle(); return xTaskGetCurrentTaskHandle();
} }
FuriThread* furi_thread_get_current() {
FuriThread* thread = pvTaskGetThreadLocalStoragePointer(NULL, 0);
furi_assert(thread != NULL);
return thread;
}
void furi_thread_yield() { void furi_thread_yield() {
furi_assert(!FURI_IS_IRQ_MODE()); furi_assert(!FURI_IS_IRQ_MODE());
taskYIELD(); taskYIELD();
@@ -408,3 +440,59 @@ uint32_t furi_thread_get_stack_space(FuriThreadId thread_id) {
return (sz); return (sz);
} }
static size_t __furi_thread_stdout_write(FuriThread* thread, const char* data, size_t size) {
if(thread->output.write_callback != NULL) {
thread->output.write_callback(data, size);
} else {
furi_hal_console_tx((const uint8_t*)data, size);
}
return size;
}
static int32_t __furi_thread_stdout_flush(FuriThread* thread) {
string_ptr buffer = thread->output.buffer;
size_t size = string_size(buffer);
if(size > 0) {
__furi_thread_stdout_write(thread, string_get_cstr(buffer), size);
string_reset(buffer);
}
return 0;
}
bool furi_thread_set_stdout_callback(FuriThreadStdoutWriteCallback callback) {
FuriThread* thread = furi_thread_get_current();
__furi_thread_stdout_flush(thread);
thread->output.write_callback = callback;
return true;
}
size_t furi_thread_stdout_write(const char* data, size_t size) {
FuriThread* thread = furi_thread_get_current();
if(size == 0 || data == NULL) {
return __furi_thread_stdout_flush(thread);
} else {
if(data[size - 1] == '\n') {
// if the last character is a newline, we can flush buffer and write data as is, wo buffers
__furi_thread_stdout_flush(thread);
__furi_thread_stdout_write(thread, data, size);
} else {
// string_cat doesn't work here because we need to write the exact size data
for(size_t i = 0; i < size; i++) {
string_push_back(thread->output.buffer, data[i]);
if(data[i] == '\n') {
__furi_thread_stdout_flush(thread);
}
}
}
}
return size;
}
int32_t furi_thread_stdout_flush() {
return __furi_thread_stdout_flush(furi_thread_get_current());
}

View File

@@ -42,6 +42,12 @@ typedef void* FuriThreadId;
*/ */
typedef int32_t (*FuriThreadCallback)(void* context); typedef int32_t (*FuriThreadCallback)(void* context);
/** Write to stdout callback
* @param data pointer to data
* @param size data size @warning your handler must consume everything
*/
typedef void (*FuriThreadStdoutWriteCallback)(const char* data, size_t size);
/** FuriThread state change calback called upon thread state change /** FuriThread state change calback called upon thread state change
* @param state new thread state * @param state new thread state
* @param context callback context * @param context callback context
@@ -177,6 +183,12 @@ int32_t furi_thread_get_return_code(FuriThread* thread);
*/ */
FuriThreadId furi_thread_get_current_id(); FuriThreadId furi_thread_get_current_id();
/** Get FuriThread instance for current thread
*
* @return FuriThread*
*/
FuriThread* furi_thread_get_current();
/** Return control to scheduler */ /** Return control to scheduler */
void furi_thread_yield(); void furi_thread_yield();
@@ -194,6 +206,29 @@ const char* furi_thread_get_name(FuriThreadId thread_id);
uint32_t furi_thread_get_stack_space(FuriThreadId thread_id); uint32_t furi_thread_get_stack_space(FuriThreadId thread_id);
/** Set STDOUT callback for thread
*
* @param callback callback or NULL to clear
*
* @return true on success, otherwise fail
*/
bool furi_thread_set_stdout_callback(FuriThreadStdoutWriteCallback callback);
/** Write data to buffered STDOUT
*
* @param data input data
* @param size input data size
*
* @return size_t written data size
*/
size_t furi_thread_stdout_write(const char* data, size_t size);
/** Flush data to STDOUT
*
* @return int32_t error code
*/
int32_t furi_thread_stdout_flush();
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@@ -8,7 +8,6 @@ void furi_init() {
furi_log_init(); furi_log_init();
furi_record_init(); furi_record_init();
furi_stdglue_init();
} }
void furi_run() { void furi_run() {

View File

@@ -14,7 +14,6 @@
#include <core/pubsub.h> #include <core/pubsub.h>
#include <core/record.h> #include <core/record.h>
#include <core/semaphore.h> #include <core/semaphore.h>
#include <core/stdglue.h>
#include <core/thread.h> #include <core/thread.h>
#include <core/timer.h> #include <core/timer.h>
#include <core/valuemutex.h> #include <core/valuemutex.h>

View File

@@ -15,7 +15,7 @@
- `microtar` - TAR archive support library - `microtar` - TAR archive support library
- `mlib` - Algorithms and containers - `mlib` - Algorithms and containers
- `nanopb` - Nano Protobuf library - `nanopb` - Nano Protobuf library
- `nfc_protocols` - Nfc protocols library - `nfc` - Nfc library
- `one_wire` - One wire library - `one_wire` - One wire library
- `qrcode` - Qr code generator library - `qrcode` - Qr code generator library
- `ST25RFAL002` - ST253916 driver and NFC hal - `ST25RFAL002` - ST253916 driver and NFC hal

View File

@@ -14,6 +14,7 @@ env.Append(
"lib/toolbox", "lib/toolbox",
"lib/u8g2", "lib/u8g2",
"lib/update_util", "lib/update_util",
"lib/print",
] ]
) )
@@ -60,6 +61,7 @@ libs = env.BuildModules(
[ [
"STM32CubeWB", "STM32CubeWB",
"freertos", "freertos",
"print",
"microtar", "microtar",
"toolbox", "toolbox",
"ST25RFAL002", "ST25RFAL002",

View File

@@ -116,7 +116,7 @@ FlipperFormat* flipper_format_string_alloc();
FlipperFormat* flipper_format_file_alloc(Storage* storage); FlipperFormat* flipper_format_file_alloc(Storage* storage);
/** /**
* Allocate FlipperFormat as file, buffered read-only mode. * Allocate FlipperFormat as file, buffered mode.
* @return FlipperFormat* pointer to a FlipperFormat instance * @return FlipperFormat* pointer to a FlipperFormat instance
*/ */
FlipperFormat* flipper_format_buffered_file_alloc(Storage* storage); FlipperFormat* flipper_format_buffered_file_alloc(Storage* storage);
@@ -131,7 +131,7 @@ FlipperFormat* flipper_format_buffered_file_alloc(Storage* storage);
bool flipper_format_file_open_existing(FlipperFormat* flipper_format, const char* path); bool flipper_format_file_open_existing(FlipperFormat* flipper_format, const char* path);
/** /**
* Open existing file, read-only with buffered read operations. * Open existing file, buffered mode.
* Use only if FlipperFormat allocated as a file. * Use only if FlipperFormat allocated as a file.
* @param flipper_format Pointer to a FlipperFormat instance * @param flipper_format Pointer to a FlipperFormat instance
* @param path File path * @param path File path

View File

@@ -6,6 +6,7 @@
#include <dialogs/dialogs.h> #include <dialogs/dialogs.h>
#include <furi_hal_nfc.h> #include <furi_hal_nfc.h>
#include <lib/nfc/helpers/mf_classic_dict.h>
#include <lib/nfc/protocols/emv.h> #include <lib/nfc/protocols/emv.h>
#include <lib/nfc/protocols/mifare_ultralight.h> #include <lib/nfc/protocols/mifare_ultralight.h>
#include <lib/nfc/protocols/mifare_classic.h> #include <lib/nfc/protocols/mifare_classic.h>
@@ -13,6 +14,7 @@
#define NFC_DEV_NAME_MAX_LEN 22 #define NFC_DEV_NAME_MAX_LEN 22
#define NFC_READER_DATA_MAX_SIZE 64 #define NFC_READER_DATA_MAX_SIZE 64
#define NFC_DICT_KEY_BATCH_SIZE 50
#define NFC_APP_FOLDER ANY_PATH("nfc") #define NFC_APP_FOLDER ANY_PATH("nfc")
#define NFC_APP_EXTENSION ".nfc" #define NFC_APP_EXTENSION ".nfc"
@@ -41,10 +43,17 @@ typedef struct {
uint16_t size; uint16_t size;
} NfcReaderRequestData; } NfcReaderRequestData;
typedef struct {
MfClassicDict* dict;
} NfcMfClassicDictAttackData;
typedef struct { typedef struct {
FuriHalNfcDevData nfc_data; FuriHalNfcDevData nfc_data;
NfcProtocol protocol; NfcProtocol protocol;
union {
NfcReaderRequestData reader_data; NfcReaderRequestData reader_data;
NfcMfClassicDictAttackData mf_classic_dict_attack_data;
};
union { union {
EmvData emv_data; EmvData emv_data;
MfUltralightData mf_ul_data; MfUltralightData mf_ul_data;

View File

@@ -101,10 +101,8 @@ int32_t nfc_worker_task(void* context) {
nfc_worker_emulate_mf_ultralight(nfc_worker); nfc_worker_emulate_mf_ultralight(nfc_worker);
} else if(nfc_worker->state == NfcWorkerStateMfClassicEmulate) { } else if(nfc_worker->state == NfcWorkerStateMfClassicEmulate) {
nfc_worker_emulate_mf_classic(nfc_worker); nfc_worker_emulate_mf_classic(nfc_worker);
} else if(nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) { } else if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) {
nfc_worker_mf_classic_dict_attack(nfc_worker, MfClassicDictTypeUser); nfc_worker_mf_classic_dict_attack(nfc_worker);
} else if(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack) {
nfc_worker_mf_classic_dict_attack(nfc_worker, MfClassicDictTypeFlipper);
} }
furi_hal_nfc_sleep(); furi_hal_nfc_sleep();
nfc_worker_change_state(nfc_worker, NfcWorkerStateReady); nfc_worker_change_state(nfc_worker, NfcWorkerStateReady);
@@ -397,11 +395,13 @@ void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker) {
} }
} }
void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType type) { void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker) {
furi_assert(nfc_worker); furi_assert(nfc_worker);
furi_assert(nfc_worker->callback); furi_assert(nfc_worker->callback);
MfClassicData* data = &nfc_worker->dev_data->mf_classic_data; MfClassicData* data = &nfc_worker->dev_data->mf_classic_data;
NfcMfClassicDictAttackData* dict_attack_data =
&nfc_worker->dev_data->mf_classic_dict_attack_data;
uint32_t total_sectors = mf_classic_get_total_sectors_num(data->type); uint32_t total_sectors = mf_classic_get_total_sectors_num(data->type);
uint64_t key = 0; uint64_t key = 0;
FuriHalNfcTxRxContext tx_rx = {}; FuriHalNfcTxRxContext tx_rx = {};
@@ -409,15 +409,17 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
bool card_removed_notified = false; bool card_removed_notified = false;
// Load dictionary // Load dictionary
MfClassicDict* dict = mf_classic_dict_alloc(type); MfClassicDict* dict = dict_attack_data->dict;
if(!dict) { if(!dict) {
FURI_LOG_E(TAG, "Dictionary not found"); FURI_LOG_E(TAG, "Dictionary not found");
nfc_worker->callback(NfcWorkerEventNoDictFound, nfc_worker->context); nfc_worker->callback(NfcWorkerEventNoDictFound, nfc_worker->context);
mf_classic_dict_free(dict);
return; return;
} }
FURI_LOG_D(TAG, "Start Dictionary attack"); FURI_LOG_D(
TAG,
"Start Dictionary attack, Key Count %d",
mf_classic_dict_get_total_keys(dict));
for(size_t i = 0; i < total_sectors; i++) { for(size_t i = 0; i < total_sectors; i++) {
FURI_LOG_I(TAG, "Sector %d", i); FURI_LOG_I(TAG, "Sector %d", i);
nfc_worker->callback(NfcWorkerEventNewSector, nfc_worker->context); nfc_worker->callback(NfcWorkerEventNewSector, nfc_worker->context);
@@ -425,7 +427,11 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
if(mf_classic_is_sector_read(data, i)) continue; if(mf_classic_is_sector_read(data, i)) continue;
bool is_key_a_found = mf_classic_is_key_found(data, i, MfClassicKeyA); bool is_key_a_found = mf_classic_is_key_found(data, i, MfClassicKeyA);
bool is_key_b_found = mf_classic_is_key_found(data, i, MfClassicKeyB); bool is_key_b_found = mf_classic_is_key_found(data, i, MfClassicKeyB);
uint16_t key_index = 0;
while(mf_classic_dict_get_next_key(dict, &key)) { while(mf_classic_dict_get_next_key(dict, &key)) {
if(++key_index % NFC_DICT_KEY_BATCH_SIZE == 0) {
nfc_worker->callback(NfcWorkerEventNewDictKeyBatch, nfc_worker->context);
}
furi_hal_nfc_sleep(); furi_hal_nfc_sleep();
if(furi_hal_nfc_activate_nfca(200, NULL)) { if(furi_hal_nfc_activate_nfca(200, NULL)) {
furi_hal_nfc_sleep(); furi_hal_nfc_sleep();
@@ -456,8 +462,7 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
} }
} }
if(is_key_a_found && is_key_b_found) break; if(is_key_a_found && is_key_b_found) break;
if(!((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) || if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack)
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)))
break; break;
} else { } else {
if(!card_removed_notified) { if(!card_removed_notified) {
@@ -465,20 +470,16 @@ void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType
card_removed_notified = true; card_removed_notified = true;
card_found_notified = false; card_found_notified = false;
} }
if(!((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) || if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack)
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)))
break; break;
} }
} }
if(!((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) || if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack)
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)))
break; break;
mf_classic_read_sector(&tx_rx, data, i); mf_classic_read_sector(&tx_rx, data, i);
mf_classic_dict_rewind(dict); mf_classic_dict_rewind(dict);
} }
mf_classic_dict_free(dict); if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) {
if((nfc_worker->state == NfcWorkerStateMfClassicUserDictAttack) ||
(nfc_worker->state == NfcWorkerStateMfClassicFlipperDictAttack)) {
nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context);
} else { } else {
nfc_worker->callback(NfcWorkerEventAborted, nfc_worker->context); nfc_worker->callback(NfcWorkerEventAborted, nfc_worker->context);

View File

@@ -14,8 +14,7 @@ typedef enum {
NfcWorkerStateUidEmulate, NfcWorkerStateUidEmulate,
NfcWorkerStateMfUltralightEmulate, NfcWorkerStateMfUltralightEmulate,
NfcWorkerStateMfClassicEmulate, NfcWorkerStateMfClassicEmulate,
NfcWorkerStateMfClassicUserDictAttack, NfcWorkerStateMfClassicDictAttack,
NfcWorkerStateMfClassicFlipperDictAttack,
// Debug // Debug
NfcWorkerStateEmulateApdu, NfcWorkerStateEmulateApdu,
NfcWorkerStateField, NfcWorkerStateField,
@@ -49,6 +48,7 @@ typedef enum {
// Mifare Classic events // Mifare Classic events
NfcWorkerEventNoDictFound, NfcWorkerEventNoDictFound,
NfcWorkerEventNewSector, NfcWorkerEventNewSector,
NfcWorkerEventNewDictKeyBatch,
NfcWorkerEventFoundKeyA, NfcWorkerEventFoundKeyA,
NfcWorkerEventFoundKeyB, NfcWorkerEventFoundKeyB,
} NfcWorkerEvent; } NfcWorkerEvent;

View File

@@ -13,7 +13,6 @@
#include <lib/nfc/protocols/mifare_desfire.h> #include <lib/nfc/protocols/mifare_desfire.h>
#include <lib/nfc/protocols/nfca.h> #include <lib/nfc/protocols/nfca.h>
#include "helpers/mf_classic_dict.h"
#include "helpers/nfc_debug_pcap.h" #include "helpers/nfc_debug_pcap.h"
struct NfcWorker { struct NfcWorker {
@@ -43,6 +42,6 @@ void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker);
void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker); void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker);
void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker, MfClassicDictType type); void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker);
void nfc_worker_emulate_apdu(NfcWorker* nfc_worker); void nfc_worker_emulate_apdu(NfcWorker* nfc_worker);

107
lib/print/SConscript Normal file
View File

@@ -0,0 +1,107 @@
Import("env")
wrapped_fn_list = [
#
# used by our firmware, so we provide their realizations
#
"fflush",
"printf",
"putc", # fallback from printf, thanks gcc
"putchar", # storage cli
"puts", # fallback from printf, thanks gcc
"snprintf",
"vsnprintf", # m-string
"__assert", # ???
"__assert_func", # ???
#
# wrap other functions to make sure they are not called
# realization is not provided
#
"setbuf",
"setvbuf",
"fprintf",
"vfprintf",
"vprintf",
"fputc",
"fputs",
"sprintf", # specially, because this function is dangerous
"asprintf",
"vasprintf",
"asiprintf",
"asniprintf",
"asnprintf",
"diprintf",
"fiprintf",
"iprintf",
"siprintf",
"sniprintf",
"vasiprintf",
"vasniprintf",
"vasnprintf",
"vdiprintf",
"vfiprintf",
"viprintf",
"vsiprintf",
"vsniprintf",
#
# Scanf is not implemented 4 now
#
# "fscanf",
# "scanf",
# "sscanf",
# "vsprintf",
# "fgetc",
# "fgets",
# "getc",
# "getchar",
# "gets",
# "ungetc",
# "vfscanf",
# "vscanf",
# "vsscanf",
# "fiscanf",
# "iscanf",
# "siscanf",
# "vfiscanf",
# "viscanf",
# "vsiscanf",
#
# File management
#
# "fclose",
# "freopen",
# "fread",
# "fwrite",
# "fgetpos",
# "fseek",
# "fsetpos",
# "ftell",
# "rewind",
# "feof",
# "ferror",
# "fopen",
# "remove",
# "rename",
# "fseeko",
# "ftello",
]
for wrapped_fn in wrapped_fn_list:
env.Append(
LINKFLAGS=[
"-Wl,--wrap," + wrapped_fn,
"-Wl,--wrap," + wrapped_fn + "_unlocked",
"-Wl,--wrap,_" + wrapped_fn + "_r",
"-Wl,--wrap,_" + wrapped_fn + "_unlocked_r",
]
)
libenv = env.Clone(FW_LIB_NAME="print")
libenv.ApplyLibFlags()
libenv.Append(CCFLAGS=["-Wno-double-promotion"])
sources = libenv.GlobRecursive("*.c*", ".")
lib = libenv.StaticLibrary("${FW_LIB_NAME}", sources)
libenv.Install("${LIB_DIST_DIR}", lib)
Return("lib")

1037
lib/print/printf_tiny.c Normal file

File diff suppressed because it is too large Load Diff

103
lib/print/printf_tiny.h Normal file
View File

@@ -0,0 +1,103 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on
// embedded systems with a very limited resources.
// Use this instead of bloated standard/newlib printf.
// These routines are thread safe and reentrant.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _PRINTF_H_
#define _PRINTF_H_
#include <stdarg.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Output a character to a custom device like UART, used by the printf() function
* This function is declared here only. You have to write your custom implementation somewhere
* \param character Character to output
*/
void _putchar(char character);
/**
* Tiny printf implementation
* You have to implement _putchar if you use printf()
* To avoid conflicts with the regular printf() API it is overridden by macro defines
* and internal underscore-appended functions like printf_() are used
* \param format A string that specifies the format of the output
* \return The number of characters that are written into the array, not counting the terminating null character
*/
int printf_(const char* format, ...);
/**
* Tiny sprintf implementation
* Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD!
* \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output!
* \param format A string that specifies the format of the output
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
int sprintf_(char* buffer, const char* format, ...);
/**
* Tiny snprintf/vsnprintf implementation
* \param buffer A pointer to the buffer where to store the formatted string
* \param count The maximum number of characters to store in the buffer, including a terminating null character
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that COULD have been written into the buffer, not counting the terminating
* null character. A value equal or larger than count indicates truncation. Only when the returned value
* is non-negative and less than count, the string has been completely written.
*/
int snprintf_(char* buffer, size_t count, const char* format, ...);
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va);
/**
* Tiny vprintf implementation
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
int vprintf_(const char* format, va_list va);
/**
* printf with output function
* You may use this as dynamic alternative to printf() with its fixed _putchar() output
* \param out An output function which takes one character and an argument pointer
* \param arg An argument pointer for user data passed to output function
* \param format A string that specifies the format of the output
* \return The number of characters that are sent to the output function, not counting the terminating null character
*/
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif // _PRINTF_H_

74
lib/print/wrappers.c Normal file
View File

@@ -0,0 +1,74 @@
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <furi/core/check.h>
#include <furi/core/thread.h>
#include <furi/core/common_defines.h>
#include <string.h>
#include "printf_tiny.h"
void _putchar(char character) {
furi_thread_stdout_write(&character, 1);
}
int __wrap_printf(const char* format, ...) {
va_list args;
va_start(args, format);
int ret = vprintf_(format, args);
va_end(args);
return ret;
}
int __wrap_vsnprintf(char* str, size_t size, const char* format, va_list args) {
return vsnprintf_(str, size, format, args);
}
int __wrap_puts(const char* str) {
size_t size = furi_thread_stdout_write(str, strlen(str));
size += furi_thread_stdout_write("\n", 1);
return size;
}
int __wrap_putchar(int ch) {
size_t size = furi_thread_stdout_write((char*)&ch, 1);
return size;
}
int __wrap_putc(int ch, FILE* stream) {
UNUSED(stream);
size_t size = furi_thread_stdout_write((char*)&ch, 1);
return size;
}
int __wrap_snprintf(char* str, size_t size, const char* format, ...) {
va_list args;
va_start(args, format);
int ret = __wrap_vsnprintf(str, size, format, args);
va_end(args);
return ret;
}
int __wrap_fflush(FILE* stream) {
UNUSED(stream);
furi_thread_stdout_flush();
return 0;
}
__attribute__((__noreturn__)) void __wrap___assert(const char* file, int line, const char* e) {
UNUSED(file);
UNUSED(line);
// TODO: message file and line number
furi_crash(e);
}
__attribute__((__noreturn__)) void
__wrap___assert_func(const char* file, int line, const char* func, const char* e) {
UNUSED(file);
UNUSED(line);
UNUSED(func);
// TODO: message file and line number
furi_crash(e);
}

View File

@@ -37,7 +37,7 @@ void set_random_name(char* name, uint8_t max_name_size) {
uint8_t prefix_i = rand() % COUNT_OF(prefix); uint8_t prefix_i = rand() % COUNT_OF(prefix);
uint8_t suffix_i = rand() % COUNT_OF(suffix); uint8_t suffix_i = rand() % COUNT_OF(suffix);
sniprintf(name, max_name_size, "%s_%s", prefix[prefix_i], suffix[suffix_i]); snprintf(name, max_name_size, "%s_%s", prefix[prefix_i], suffix[suffix_i]);
// Set first symbol to upper case // Set first symbol to upper case
name[0] = name[0] - 0x20; name[0] = name[0] - 0x20;
} }

View File

@@ -1,6 +1,5 @@
#include "buffered_file_stream.h" #include "buffered_file_stream.h"
#include "core/check.h"
#include "stream_i.h" #include "stream_i.h"
#include "file_stream.h" #include "file_stream.h"
#include "stream_cache.h" #include "stream_cache.h"
@@ -9,6 +8,7 @@ typedef struct {
Stream stream_base; Stream stream_base;
Stream* file_stream; Stream* file_stream;
StreamCache* cache; StreamCache* cache;
bool sync_pending;
} BufferedFileStream; } BufferedFileStream;
static void buffered_file_stream_free(BufferedFileStream* stream); static void buffered_file_stream_free(BufferedFileStream* stream);
@@ -27,6 +27,9 @@ static bool buffered_file_stream_delete_and_insert(
StreamWriteCB write_callback, StreamWriteCB write_callback,
const void* ctx); const void* ctx);
static bool buffered_file_stream_flush(BufferedFileStream* stream);
static bool buffered_file_stream_unread(BufferedFileStream* stream);
const StreamVTable buffered_file_stream_vtable = { const StreamVTable buffered_file_stream_vtable = {
.free = (StreamFreeFn)buffered_file_stream_free, .free = (StreamFreeFn)buffered_file_stream_free,
.eof = (StreamEOFFn)buffered_file_stream_eof, .eof = (StreamEOFFn)buffered_file_stream_eof,
@@ -39,13 +42,12 @@ const StreamVTable buffered_file_stream_vtable = {
.delete_and_insert = (StreamDeleteAndInsertFn)buffered_file_stream_delete_and_insert, .delete_and_insert = (StreamDeleteAndInsertFn)buffered_file_stream_delete_and_insert,
}; };
static bool buffered_file_stream_unread(BufferedFileStream* stream);
Stream* buffered_file_stream_alloc(Storage* storage) { Stream* buffered_file_stream_alloc(Storage* storage) {
BufferedFileStream* stream = malloc(sizeof(BufferedFileStream)); BufferedFileStream* stream = malloc(sizeof(BufferedFileStream));
stream->file_stream = file_stream_alloc(storage); stream->file_stream = file_stream_alloc(storage);
stream->cache = stream_cache_alloc(); stream->cache = stream_cache_alloc();
stream->sync_pending = false;
stream->stream_base.vtable = &buffered_file_stream_vtable; stream->stream_base.vtable = &buffered_file_stream_vtable;
return (Stream*)stream; return (Stream*)stream;
@@ -58,7 +60,6 @@ bool buffered_file_stream_open(
FS_OpenMode open_mode) { FS_OpenMode open_mode) {
furi_assert(_stream); furi_assert(_stream);
BufferedFileStream* stream = (BufferedFileStream*)_stream; BufferedFileStream* stream = (BufferedFileStream*)_stream;
stream_cache_drop(stream->cache);
furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable); furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable);
return file_stream_open(stream->file_stream, path, access_mode, open_mode); return file_stream_open(stream->file_stream, path, access_mode, open_mode);
} }
@@ -67,7 +68,22 @@ bool buffered_file_stream_close(Stream* _stream) {
furi_assert(_stream); furi_assert(_stream);
BufferedFileStream* stream = (BufferedFileStream*)_stream; BufferedFileStream* stream = (BufferedFileStream*)_stream;
furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable); furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable);
return file_stream_close(stream->file_stream); bool success = false;
do {
if(!(stream->sync_pending ? buffered_file_stream_flush(stream) :
buffered_file_stream_unread(stream)))
break;
if(!file_stream_close(stream->file_stream)) break;
success = true;
} while(false);
return success;
}
bool buffered_file_stream_sync(Stream* _stream) {
furi_assert(_stream);
BufferedFileStream* stream = (BufferedFileStream*)_stream;
furi_check(stream->stream_base.vtable == &buffered_file_stream_vtable);
return stream->sync_pending ? buffered_file_stream_flush(stream) : true;
} }
FS_Error buffered_file_stream_get_error(Stream* _stream) { FS_Error buffered_file_stream_get_error(Stream* _stream) {
@@ -85,10 +101,23 @@ static void buffered_file_stream_free(BufferedFileStream* stream) {
} }
static bool buffered_file_stream_eof(BufferedFileStream* stream) { static bool buffered_file_stream_eof(BufferedFileStream* stream) {
return stream_cache_at_end(stream->cache) && stream_eof(stream->file_stream); bool ret;
const bool file_stream_eof = stream_eof(stream->file_stream);
const bool cache_at_end = stream_cache_at_end(stream->cache);
if(!stream->sync_pending) {
ret = file_stream_eof && cache_at_end;
} else {
const size_t remaining_size =
stream_size(stream->file_stream) - stream_tell(stream->file_stream);
ret = stream_cache_size(stream->cache) >=
(remaining_size ? cache_at_end : file_stream_eof);
}
return ret;
} }
static void buffered_file_stream_clean(BufferedFileStream* stream) { static void buffered_file_stream_clean(BufferedFileStream* stream) {
// Not syncing because data will be deleted anyway
stream->sync_pending = false;
stream_cache_drop(stream->cache); stream_cache_drop(stream->cache);
stream_clean(stream->file_stream); stream_clean(stream->file_stream);
} }
@@ -97,7 +126,7 @@ static bool buffered_file_stream_seek(
BufferedFileStream* stream, BufferedFileStream* stream,
int32_t offset, int32_t offset,
StreamOffset offset_type) { StreamOffset offset_type) {
bool success = false; bool success = true;
int32_t new_offset = offset; int32_t new_offset = offset;
if(offset_type == StreamOffsetFromCurrent) { if(offset_type == StreamOffsetFromCurrent) {
@@ -108,47 +137,71 @@ static bool buffered_file_stream_seek(
} }
if((new_offset != 0) || (offset_type != StreamOffsetFromCurrent)) { if((new_offset != 0) || (offset_type != StreamOffsetFromCurrent)) {
stream_cache_drop(stream->cache); if(stream->sync_pending) {
success = stream_seek(stream->file_stream, new_offset, offset_type); success = buffered_file_stream_sync((Stream*)stream);
} else { } else {
success = true; stream_cache_drop(stream->cache);
}
if(success) {
success = stream_seek(stream->file_stream, new_offset, offset_type);
}
} }
return success; return success;
} }
static size_t buffered_file_stream_tell(BufferedFileStream* stream) { static size_t buffered_file_stream_tell(BufferedFileStream* stream) {
return stream_tell(stream->file_stream) + stream_cache_pos(stream->cache) - size_t pos = stream_tell(stream->file_stream) + stream_cache_pos(stream->cache);
stream_cache_size(stream->cache); if(!stream->sync_pending) {
pos -= stream_cache_size(stream->cache);
}
return pos;
} }
static size_t buffered_file_stream_size(BufferedFileStream* stream) { static size_t buffered_file_stream_size(BufferedFileStream* stream) {
return stream_cache_size(stream->cache) + stream_size(stream->file_stream); size_t size = stream_size(stream->file_stream);
if(stream->sync_pending) {
const size_t remaining_size = size - stream_tell(stream->file_stream);
const size_t cache_size = stream_cache_size(stream->cache);
if(cache_size > remaining_size) {
size += (cache_size - remaining_size);
}
}
return size;
} }
static size_t static size_t
buffered_file_stream_write(BufferedFileStream* stream, const uint8_t* data, size_t size) { buffered_file_stream_write(BufferedFileStream* stream, const uint8_t* data, size_t size) {
size_t need_to_write = size; size_t need_to_write = size;
do { do {
if(!stream->sync_pending) {
if(!buffered_file_stream_unread(stream)) break; if(!buffered_file_stream_unread(stream)) break;
need_to_write -= stream_write(stream->file_stream, data, size); }
while(need_to_write) {
stream->sync_pending = true;
need_to_write -=
stream_cache_write(stream->cache, data + (size - need_to_write), need_to_write);
if(need_to_write) {
stream->sync_pending = false;
if(!stream_cache_flush(stream->cache, stream->file_stream)) break;
}
}
} while(false); } while(false);
return size - need_to_write; return size - need_to_write;
} }
static size_t buffered_file_stream_read(BufferedFileStream* stream, uint8_t* data, size_t size) { static size_t buffered_file_stream_read(BufferedFileStream* stream, uint8_t* data, size_t size) {
size_t need_to_read = size; size_t need_to_read = size;
while(need_to_read) { while(need_to_read) {
need_to_read -= need_to_read -=
stream_cache_read(stream->cache, data + (size - need_to_read), need_to_read); stream_cache_read(stream->cache, data + (size - need_to_read), need_to_read);
if(need_to_read) { if(need_to_read) {
if(!stream_cache_fill(stream->cache, stream->file_stream)) { if(stream->sync_pending) {
break; if(!buffered_file_stream_flush(stream)) break;
}
if(!stream_cache_fill(stream->cache, stream->file_stream)) break;
} }
} }
}
return size - need_to_read; return size - need_to_read;
} }
@@ -157,19 +210,43 @@ static bool buffered_file_stream_delete_and_insert(
size_t delete_size, size_t delete_size,
StreamWriteCB write_callback, StreamWriteCB write_callback,
const void* ctx) { const void* ctx) {
return buffered_file_stream_unread(stream) && bool success = false;
stream_delete_and_insert(stream->file_stream, delete_size, write_callback, ctx); do {
if(!(stream->sync_pending ? buffered_file_stream_flush(stream) :
buffered_file_stream_unread(stream)))
break;
if(!stream_delete_and_insert(stream->file_stream, delete_size, write_callback, ctx)) break;
success = true;
} while(false);
return success;
}
// Write the cache into the underlying stream and adjust seek position
static bool buffered_file_stream_flush(BufferedFileStream* stream) {
bool success = false;
do {
const int32_t offset = stream_cache_size(stream->cache) - stream_cache_pos(stream->cache);
if(!stream_cache_flush(stream->cache, stream->file_stream)) break;
if(offset > 0) {
if(!stream_seek(stream->file_stream, -offset, StreamOffsetFromCurrent)) break;
}
success = true;
} while(false);
stream->sync_pending = false;
return success;
} }
// Drop read cache and adjust the underlying stream seek position // Drop read cache and adjust the underlying stream seek position
static bool buffered_file_stream_unread(BufferedFileStream* stream) { static bool buffered_file_stream_unread(BufferedFileStream* stream) {
bool success = true; bool success = true;
const size_t cache_size = stream_cache_size(stream->cache); const size_t cache_size = stream_cache_size(stream->cache);
if(cache_size > 0) {
const size_t cache_pos = stream_cache_pos(stream->cache); const size_t cache_pos = stream_cache_pos(stream->cache);
if(cache_pos < cache_size) { if(cache_pos < cache_size) {
const int32_t offset = cache_size - cache_pos; const int32_t offset = cache_size - cache_pos;
success = stream_seek(stream->file_stream, -offset, StreamOffsetFromCurrent); success = stream_seek(stream->file_stream, -offset, StreamOffsetFromCurrent);
} }
stream_cache_drop(stream->cache); stream_cache_drop(stream->cache);
}
return success; return success;
} }

View File

@@ -19,7 +19,7 @@ Stream* buffered_file_stream_alloc(Storage* storage);
* @param path path to file * @param path path to file
* @param access_mode access mode from FS_AccessMode * @param access_mode access mode from FS_AccessMode
* @param open_mode open mode from FS_OpenMode * @param open_mode open mode from FS_OpenMode
* @return success flag. You need to close the file even if the open operation failed. * @return True on success, False on failure. You need to close the file even if the open operation failed.
*/ */
bool buffered_file_stream_open( bool buffered_file_stream_open(
Stream* stream, Stream* stream,
@@ -29,12 +29,18 @@ bool buffered_file_stream_open(
/** /**
* Closes the file. * Closes the file.
* @param stream * @param stream pointer to file stream object.
* @return true * @return True on success, False on failure.
* @return false
*/ */
bool buffered_file_stream_close(Stream* stream); bool buffered_file_stream_close(Stream* stream);
/**
* Forces write from cache to the underlying file.
* @param stream pointer to file stream object.
* @return True on success, False on failure.
*/
bool buffered_file_stream_sync(Stream* stream);
/** /**
* Retrieves the error id from the file object * Retrieves the error id from the file object
* @param stream pointer to stream object. * @param stream pointer to stream object.

Some files were not shown because too many files have changed in this diff Show More