osal-rs 1.0.1

Operating System Abstraction Layer for Rust with support for FreeRTOS and POSIX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/***************************************************************************
 *
 * osal-rs
 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
 *
 ***************************************************************************/

//! Ported 1:1 from osal-rs-tests' FreeRTOS suite (`thread_tests.rs`) to run
//! against the POSIX backend. `posix::Thread::spawn`/`spawn_simple` are
//! currently stubs — the callback is stored but never actually executed on
//! a real OS thread — so assertions that depend on the callback running
//! (`test_thread_with_param`, `test_thread_notification`,
//! `test_thread_spawn_simple_with_shared_data`) fail until a real
//! implementation lands in `src/posix/thread.rs`.

#![cfg(feature = "posix")]

use std::sync::Arc;
use core::any::Any;
use core::sync::atomic::{AtomicU32, Ordering};
use core::time::Duration;
use osal_rs::os::*;
use osal_rs::utils::Result;
use osal_rs::{log_debug, log_info};

const TAG: &str = "ThreadTests";

struct FixedPriority(types::UBaseType);

impl ToPriority for FixedPriority {
    fn to_priority(&self) -> types::UBaseType {
        self.0
    }
}

#[test]
fn test_thread_creation() -> Result<()> {
    log_info!(TAG, "Starting test_thread_creation");
    let thread = Thread::new(
        "test_thread",
        1024,
        5
    );

    let metadata = thread.get_metadata();
    log_debug!(TAG, "Thread metadata: name={}, stack={}, priority={}", metadata.name, metadata.stack_depth, metadata.priority);
    assert!(!metadata.name.is_empty());
    assert_eq!(metadata.stack_depth, 1024);
    assert_eq!(metadata.priority, 5);
    log_info!(TAG, "test_thread_creation PASSED");
    Ok(())
}

#[test]
fn test_thread_spawn() -> Result<()> {
    log_info!(TAG, "Starting test_thread_spawn");
    let mut thread = Thread::new(
        "spawn_test",
        1024,
        5
    );

    let result = thread.spawn(None, |_thread, _param| {
        Ok(_param.unwrap_or_else(|| Arc::new(())))
    });
    assert!(result.is_ok());

    if let Ok(spawned) = result {
        let metadata = spawned.get_metadata();
        log_debug!(TAG, "Spawned thread handle: {:?}", metadata.thread);
        assert!(metadata.thread != 0);
        spawned.delete();
        log_debug!(TAG, "Thread deleted successfully");
    }
    log_info!(TAG, "test_thread_spawn PASSED");
    Ok(())
}

#[test]
fn test_thread_with_param() -> Result<()> {
    log_info!(TAG, "Starting test_thread_with_param");
    let test_value: u32 = 42;
    let param: Arc<dyn Any + Send + Sync> = Arc::new(test_value);

    let mut thread = Thread::new(
        "param_test",
        1024,
        5
    );

    let result = thread.spawn(Some(param), |_thread, param| {
        if let Some(p) = param.as_ref() {
            if let Some(val) = p.downcast_ref::<u32>() {
                assert_eq!(*val, 42);
            }
        }
        Ok(param.unwrap_or_else(|| Arc::new(())))
    });
    assert!(result.is_ok());

    if let Ok(spawned) = result {
        log_debug!(TAG, "Thread spawned with parameter");
        System::delay(Duration::from_millis(50).to_ticks());
        spawned.delete();
    }
    log_info!(TAG, "test_thread_with_param PASSED");
    Ok(())
}

#[test]
fn test_thread_suspend_resume() -> Result<()> {
    log_info!(TAG, "Starting test_thread_suspend_resume");
    let mut thread = Thread::new(
        "suspend_test",
        1024,
        5
    );

    let spawned = thread.spawn(None, |_thread, _param| {
        System::delay(Duration::from_millis(100).to_ticks());
        Ok(_param.unwrap_or_else(|| Arc::new(())))
    })?;

    log_debug!(TAG, "Suspending thread...");
    spawned.suspend();
    System::delay(Duration::from_millis(10).to_ticks());
    log_debug!(TAG, "Resuming thread...");
    spawned.resume();
    System::delay(Duration::from_millis(50).to_ticks());
    spawned.delete();
    log_info!(TAG, "test_thread_suspend_resume PASSED");
    Ok(())
}

#[test]
fn test_thread_get_metadata() -> Result<()> {
    log_info!(TAG, "Starting test_thread_get_metadata");
    let mut thread = Thread::new(
        "metadata_test",
        1024,
        5
    );

    let spawned = thread.spawn(None, |_thread, _param| {
        System::delay(Duration::from_millis(50).to_ticks());
        Ok(_param.unwrap_or_else(|| Arc::new(())))
    })?;

    let metadata = spawned.get_metadata();

    log_debug!(TAG, "Metadata - name: {}, priority: {}", metadata.name, metadata.priority);
    assert_eq!(metadata.name.as_str(), "metadata_test");
    assert_eq!(metadata.priority, 5);

    spawned.delete();
    log_info!(TAG, "test_thread_get_metadata PASSED");
    Ok(())
}

#[test]
fn test_thread_notification() -> Result<()> {
    log_info!(TAG, "Starting test_thread_notification");
    let mut thread = Thread::new(
        "notify_test",
        1024,
        5
    );

    let spawned = thread.spawn(None, |thread, _param| {
        let notification = thread.wait_notification(0, 0xFFFFFFFF, Duration::from_millis(1000).to_ticks())?;
        log_debug!(TAG, "Received notification: 0x{:X}", notification);
        assert_eq!(notification, 0x12345678);
        Ok(Arc::new(()))
    })?;

    System::delay(Duration::from_millis(10).to_ticks());
    log_debug!(TAG, "Sending notification: 0x12345678");
    let notify_result = spawned.notify(ThreadNotification::SetValueWithOverwrite(0x12345678));
    assert!(notify_result.is_ok());

    System::delay(Duration::from_millis(50).to_ticks());
    spawned.delete();
    log_info!(TAG, "test_thread_notification PASSED");
    Ok(())
}

#[test]
fn test_thread_get_current() -> Result<()> {
    log_info!(TAG, "Starting test_thread_get_current");
    let current = Thread::get_current();
    let metadata = current.get_metadata();
    log_debug!(TAG, "Current thread: {}", metadata.name);
    assert!(metadata.thread != 0);
    log_info!(TAG, "test_thread_get_current PASSED");
    Ok(())
}

#[test]
fn test_thread_spawn_simple() -> Result<()> {
    log_info!(TAG, "Starting test_thread_spawn_simple");
    let mut thread = Thread::new(
        "simple_test",
        1024,
        5
    );

    let result = thread.spawn_simple(|| {
        log_debug!(TAG, "Simple thread executing");
        System::delay(Duration::from_millis(10).to_ticks());
        Ok(Arc::new(()))
    });

    assert!(result.is_ok());

    if let Ok(spawned) = result {
        log_debug!(TAG, "Simple thread spawned successfully");
        System::delay(Duration::from_millis(50).to_ticks());
        spawned.delete();
    }
    log_info!(TAG, "test_thread_spawn_simple PASSED");
    Ok(())
}

#[test]
fn test_thread_spawn_simple_with_shared_data() -> Result<()> {
    log_info!(TAG, "Starting test_thread_spawn_simple_with_shared_data");

    let counter = Mutex::new_arc(0u32);
    let counter_clone = Arc::clone(&counter);

    let mut thread = Thread::new(
        "shared_data_test",
        1024,
        5
    );

    let result = thread.spawn_simple(move || {
        for _ in 0..5 {
            let mut num = counter_clone.lock().unwrap();
            *num += 1;
            log_debug!(TAG, "Counter: {}", *num);
        }
        Ok(Arc::new(()))
    });

    assert!(result.is_ok());

    if let Ok(spawned) = result {
        System::delay(Duration::from_millis(100).to_ticks());
        spawned.delete();
    }

    let final_count = *counter.lock().unwrap();
    log_debug!(TAG, "Final counter value: {}", final_count);
    assert_eq!(final_count, 5);

    log_info!(TAG, "test_thread_spawn_simple_with_shared_data PASSED");
    Ok(())
}

/// Exercises real two-thread synchronization via `ThreadFn::notify` /
/// `ThreadFn::wait_notification`, in both directions (see the FreeRTOS
/// counterpart in osal-rs-tests). Requires `posix::Thread::spawn` to
/// actually run the callback on a real thread, which it does not yet do —
/// expected to fail until `src/posix/thread.rs` is implemented for real.
#[test]
fn test_thread_two_thread_notification_sync() -> Result<()> {
    log_info!(TAG, "Starting test_thread_two_thread_notification_sync");
    static WORKER_RECEIVED: AtomicU32 = AtomicU32::new(0);

    let main_thread = Thread::get_current();

    let mut thread = Thread::new(
        "sync_worker",
        1024,
        5
    );

    let spawned = thread.spawn(None, move |thread, param| {
        // Blocks until the main thread wakes us up with a value.
        let value = thread.wait_notification(0, 0xFFFFFFFF, Duration::from_millis(1000).to_ticks())?;
        WORKER_RECEIVED.store(value, Ordering::SeqCst);

        // Rendezvous: tell the main thread we're done processing.
        main_thread.notify(ThreadNotification::SetValueWithOverwrite(0xA5A5))?;
        Ok(param.unwrap_or_else(|| Arc::new(())))
    })?;

    log_debug!(TAG, "Waking worker with 0xC0FFEE");
    spawned.notify(ThreadNotification::SetValueWithOverwrite(0xC0FFEE))?;

    log_debug!(TAG, "Waiting for worker's rendezvous reply");
    let reply = Thread::get_current().wait_notification(0, 0xFFFFFFFF, Duration::from_millis(1000).to_ticks())?;
    log_debug!(TAG, "Reply: 0x{:X}, worker received: 0x{:X}", reply, WORKER_RECEIVED.load(Ordering::SeqCst));
    assert_eq!(reply, 0xA5A5);
    assert_eq!(WORKER_RECEIVED.load(Ordering::SeqCst), 0xC0FFEE);

    spawned.delete();
    log_info!(TAG, "test_thread_two_thread_notification_sync PASSED");
    Ok(())
}

#[test]
fn test_thread_new_with_to_priority() -> Result<()> {
    log_info!(TAG, "Starting test_thread_new_with_to_priority");
    let mut thread = Thread::new_with_to_priority("priority_test", 1024, FixedPriority(3));

    let spawned = thread.spawn_simple(|| {
        System::delay(Duration::from_millis(50).to_ticks());
        Ok(Arc::new(()))
    })?;

    let metadata = spawned.get_metadata();
    log_debug!(TAG, "Spawned priority: {}", metadata.priority);
    assert_eq!(metadata.priority, 3);

    spawned.delete();
    log_info!(TAG, "test_thread_new_with_to_priority PASSED");
    Ok(())
}

#[test]
fn test_thread_handle_based_constructors() -> Result<()> {
    log_info!(TAG, "Starting test_thread_handle_based_constructors");

    let mut source = Thread::new("handle_source", 1024, 2);
    let spawned = source.spawn_simple(|| {
        System::delay(Duration::from_millis(50).to_ticks());
        Ok(Arc::new(()))
    })?;
    let handle = *spawned;

    let wrapped = Thread::new_with_handle_and_to_priority(handle, "wrapped", 1024, FixedPriority(6))?;
    assert_eq!(*wrapped, handle);

    let null_handle: types::ThreadHandle = 0;
    let null_result = Thread::new_with_handle_and_to_priority(null_handle, "invalid", 128, FixedPriority(1));
    assert!(null_result.is_err());

    let metadata = Thread::get_metadata_from_handle(handle);
    log_debug!(TAG, "Looked-up metadata for real handle: thread_null={}", metadata.thread == 0);
    assert!(metadata.thread != 0);

    spawned.delete();
    log_info!(TAG, "test_thread_handle_based_constructors PASSED");
    Ok(())
}

#[test]
fn test_thread_notify_from_isr_and_wait_with_to_tick() -> Result<()> {
    log_info!(TAG, "Starting test_thread_notify_from_isr_and_wait_with_to_tick");
    static WORKER_RECEIVED: AtomicU32 = AtomicU32::new(0);

    let main_thread = Thread::get_current();

    let mut thread = Thread::new("isr_notify_worker", 1024, 5);
    let spawned = thread.spawn(None, move |_thread, param| {
        let value = Thread::get_current().wait_notification_with_to_tick(0, 0xFFFFFFFF, Duration::from_millis(1000))?;
        WORKER_RECEIVED.store(value, Ordering::SeqCst);
        main_thread.notify(ThreadNotification::SetValueWithOverwrite(1))?;
        Ok(param.unwrap_or_else(|| Arc::new(())))
    })?;

    let mut higher_priority_task_woken: types::BaseType = 0;
    let notify_result = spawned.notify_from_isr(ThreadNotification::SetValueWithOverwrite(0x99), &mut higher_priority_task_woken);
    log_debug!(TAG, "notify_from_isr ok: {}", notify_result.is_ok());
    assert!(notify_result.is_ok());

    let reply = Thread::get_current().wait_notification(0, 0xFFFFFFFF, Duration::from_millis(1000).to_ticks())?;
    assert_eq!(reply, 1);
    assert_eq!(WORKER_RECEIVED.load(Ordering::SeqCst), 0x99);

    spawned.delete();
    log_info!(TAG, "test_thread_notify_from_isr_and_wait_with_to_tick PASSED");
    Ok(())
}

#[test]
fn test_thread_join() -> Result<()> {
    log_info!(TAG, "Starting test_thread_join");
    let mut thread = Thread::new("join_test", 1024, 5);
    let spawned = thread.spawn_simple(|| {
        System::delay(Duration::from_millis(10).to_ticks());
        Ok(Arc::new(()))
    })?;

    let join_result = spawned.join(core::ptr::null_mut());
    log_debug!(TAG, "join result: {:?}", join_result);
    assert!(join_result.is_ok());

    log_info!(TAG, "test_thread_join PASSED");
    Ok(())
}