SimpleKernel 1.17.0
Loading...
Searching...
No Matches
memory_test.cpp
Go to the documentation of this file.
1
5#include <cpu_io.h>
6
7#include <cstddef>
8#include <cstdint>
9
10#include "arch.h"
11#include "basic_info.hpp"
12#include "kernel.h"
13#include "kstd_cstring"
14#include "kstd_libcxx.h"
15#include "sk_stdlib.h"
16#include "system_test.h"
17
18extern "C" {
19void* malloc(size_t size);
20void free(void* ptr);
21void* aligned_alloc(size_t alignment, size_t size);
22}
23
24auto memory_test() -> bool {
25 klog::Info("memory_test: start");
26
27 // Test 1: malloc & free
28 size_t size = 1024;
29 void* ptr = malloc(size);
30 EXPECT_TRUE(ptr != nullptr, "memory_test: malloc failed");
31
32 // Write and read verification
33 auto* byte_ptr = static_cast<uint8_t*>(ptr);
34 for (size_t i = 0; i < size; ++i) {
35 byte_ptr[i] = static_cast<uint8_t>(i & 0xFF);
36 }
37
38 for (size_t i = 0; i < size; ++i) {
39 EXPECT_EQ(byte_ptr[i], static_cast<uint8_t>(i & 0xFF),
40 "memory_test: verify failed");
41 }
42
43 free(ptr);
44 klog::Info("memory_test: malloc/free passed");
45
46 // Test 2: aligned_alloc
47 size_t alignment = 256;
48 size_t aligned_size = 512;
49 void* aligned_ptr = aligned_alloc(alignment, aligned_size);
50 EXPECT_TRUE(aligned_ptr != nullptr, "memory_test: aligned_alloc failed");
51
52 EXPECT_EQ(reinterpret_cast<uintptr_t>(aligned_ptr) & (alignment - 1), 0,
53 "memory_test: aligned_alloc alignment failed");
54
55 free(aligned_ptr);
56 klog::Info("memory_test: aligned_alloc passed");
57
58 // Test 3: Multiple small allocations
59 const int count = 10;
60 void* ptrs[count];
61
62 for (int i = 0; i < count; ++i) {
63 ptrs[i] = malloc(128);
64 EXPECT_TRUE(ptrs[i] != nullptr, "memory_test: multi alloc failed");
65 // Fill
66 kstd::memset(ptrs[i], i, 128);
67 }
68
69 for (int i = 0; i < count; ++i) {
70 auto* p = static_cast<uint8_t*>(ptrs[i]);
71 for (int j = 0; j < 128; ++j) {
72 EXPECT_EQ(p[j], i, "memory_test: multi alloc verify failed");
73 }
74 free(ptrs[i]);
75 }
76 klog::Info("memory_test: multi alloc passed");
77
78 return true;
79}
void * aligned_alloc(size_t alignment, size_t size)
Definition memory.cpp:58
void * malloc(size_t size)
Definition memory.cpp:31
auto memory_test() -> bool
void free(void *ptr)
Definition memory.cpp:38
auto Info(etl::format_string< Args... > fmt, Args &&... args) -> void
以 INFO 级别记录日志
#define EXPECT_TRUE(cond, msg)
#define EXPECT_EQ(val1, val2, msg)