Skip to content

Commit 7d41913

Browse files
committed
Add timing_alt.c for POSIX
1 parent ca408c4 commit 7d41913

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

mrbgems/picoruby-mbedtls/mrbgem.rake

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,7 @@ MRuby::Gem::Specification.new('picoruby-mbedtls') do |spec|
3636
if build.posix?
3737
cc.defines << "PICORB_PLATFORM_POSIX"
3838
end
39+
40+
spec.posix
3941
end
4042

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <time.h>
2+
#include <stdint.h>
3+
#include <sys/time.h>
4+
5+
typedef struct {
6+
struct timespec end_time;
7+
int int_ms;
8+
int fin_ms;
9+
int active;
10+
} timing_delay_context;
11+
12+
void
13+
mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms)
14+
{
15+
timing_delay_context *ctx = (timing_delay_context *)data;
16+
17+
ctx->int_ms = (int)int_ms;
18+
ctx->fin_ms = (int)fin_ms;
19+
ctx->active = 1;
20+
21+
if (fin_ms == 0) {
22+
// Cancel
23+
ctx->active = 0;
24+
return;
25+
}
26+
27+
// current time + fin_ms = end_time
28+
struct timespec now;
29+
clock_gettime(CLOCK_MONOTONIC, &now);
30+
ctx->end_time.tv_sec = now.tv_sec + fin_ms / 1000;
31+
ctx->end_time.tv_nsec = now.tv_nsec + (fin_ms % 1000) * 1000000;
32+
if (ctx->end_time.tv_nsec >= 1000000000) {
33+
ctx->end_time.tv_sec += 1;
34+
ctx->end_time.tv_nsec -= 1000000000;
35+
}
36+
}
37+
38+
int
39+
mbedtls_timing_get_delay(void *data)
40+
{
41+
timing_delay_context *ctx = (timing_delay_context *)data;
42+
43+
if (ctx->fin_ms == 0 || !ctx->active) return -1;
44+
45+
struct timespec now;
46+
clock_gettime(CLOCK_MONOTONIC, &now);
47+
48+
int64_t elapsed_ms = (ctx->end_time.tv_sec - now.tv_sec) * 1000 +
49+
(ctx->end_time.tv_nsec - now.tv_nsec) / 1000000;
50+
51+
if (elapsed_ms <= -ctx->fin_ms) {
52+
return 2; // Final delay has passed
53+
} else if (elapsed_ms <= -ctx->int_ms) {
54+
return 1; // Intermediate delay has passed
55+
} else {
56+
return 0; // Still active, but no delay
57+
}
58+
}
59+
60+
// Stub
61+
unsigned long
62+
mbedtls_timing_hardclock(void)
63+
{
64+
static unsigned long counter = 0;
65+
return ++counter;
66+
}
67+

0 commit comments

Comments
 (0)