Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

finetune: Prevent fc overflow #304

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

finetune: Prevent fc overflow #304

wants to merge 1 commit into from

Conversation

howey
Copy link

@howey howey commented Oct 19, 2023

fc is a int16, check limits before setting.

I have a watch with a really bad oscillator, and setting with finetune will actually go beyond int16 and roll over to negative. I was confused for a while until I finally realized the problem. Added a check in finetune to prevent this from happening. I believe my watch has too big of an error for FREQCORR to correct, but that is another issue.

fc is a int16, check limits before setting.
@@ -197,7 +198,14 @@ bool finetune_face_loop(movement_event_t event, movement_settings_t *settings, v
finetune_adjust_subseconds(250);
} else if (finetune_page == 2 && finetune_get_hours_passed() >= 6) {
// Applying ppm correction, only if >6 hours passed
nanosec_state.freq_correction += (int)round(finetune_get_correction() * 100);
int32_t f = nanosec_state.freq_correction + (int)round(finetune_get_correction() * 100);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a cleaner approach is something like:

int correction = (int)round(finetune_get_correction() * 100);
if (nanosec_state.freq_correction > 0 && correction > SHRT_MAX - nanosec_state.freq_correction) {
    nanosec_state.freq_correction = SHRT_MAX;
} else if (nanosec_state.freq_correction < 0 && correction < SHRT_MIN - nanosec_state.freq_correction) {
    nanosec_state.freq_correction = SHRT_MIN;
} else {
    nanosec_state.freq_correction += correction;
}

since it avoids the need for a intermediate variable. Does that look right to you?

@matheusmoreira
Copy link
Collaborator

Possible solution: get the compiler to do this for us by using integer overflow builtins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants