From 7bf0716a9cab302eadb8bcd34cdf268333b609ea Mon Sep 17 00:00:00 2001 From: dekutree64 <54822734+dekutree64@users.noreply.github.com> Date: Thu, 9 Apr 2026 18:01:26 -0500 Subject: [PATCH 1/2] Fix potential undefined behavior in sin/cos --- src/common/foc_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/foc_utils.cpp b/src/common/foc_utils.cpp index 7ae372f7..1af1d424 100644 --- a/src/common/foc_utils.cpp +++ b/src/common/foc_utils.cpp @@ -10,7 +10,7 @@ __attribute__((weak)) float _sin(float a){ // resulting precision compared to stdlib sine is 0.00006480 (RMS difference in range -PI,PI for 3217 steps) static uint16_t sine_array[65] = {0,804,1608,2411,3212,4011,4808,5602,6393,7180,7962,8740,9512,10279,11039,11793,12540,13279,14010,14733,15447,16151,16846,17531,18205,18868,19520,20160,20788,21403,22006,22595,23170,23732,24279,24812,25330,25833,26320,26791,27246,27684,28106,28511,28899,29269,29622,29957,30274,30572,30853,31114,31357,31581,31786,31972,32138,32286,32413,32522,32610,32679,32729,32758,32768}; int32_t t1, t2; - unsigned int i = (unsigned int)(a * (64*4*256.0f/_2PI)); + int i = (int)(a * (64*4*256.0f/_2PI)); int frac = i & 0xff; i = (i >> 8) & 0xff; if (i < 64) { From fd34b4a5f4dfc9675e8e80562eb3c8e8220c1d40 Mon Sep 17 00:00:00 2001 From: dekutree64 <54822734+dekutree64@users.noreply.github.com> Date: Thu, 9 Apr 2026 18:49:51 -0500 Subject: [PATCH 2/2] Fix for potential float-to-int16 conversion problem --- src/common/foc_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/foc_utils.cpp b/src/common/foc_utils.cpp index 1af1d424..66caa8b8 100644 --- a/src/common/foc_utils.cpp +++ b/src/common/foc_utils.cpp @@ -10,7 +10,7 @@ __attribute__((weak)) float _sin(float a){ // resulting precision compared to stdlib sine is 0.00006480 (RMS difference in range -PI,PI for 3217 steps) static uint16_t sine_array[65] = {0,804,1608,2411,3212,4011,4808,5602,6393,7180,7962,8740,9512,10279,11039,11793,12540,13279,14010,14733,15447,16151,16846,17531,18205,18868,19520,20160,20788,21403,22006,22595,23170,23732,24279,24812,25330,25833,26320,26791,27246,27684,28106,28511,28899,29269,29622,29957,30274,30572,30853,31114,31357,31581,31786,31972,32138,32286,32413,32522,32610,32679,32729,32758,32768}; int32_t t1, t2; - int i = (int)(a * (64*4*256.0f/_2PI)); + int i = (int)(int32_t)(a * (64*4*256.0f/_2PI)); // Initial conversion to 32-bit int to avoid saturation int frac = i & 0xff; i = (i >> 8) & 0xff; if (i < 64) {