Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 :
11 : #include "scd_memory.h"
12 : #include <stdlib.h>
13 : #include "scd_log.h"
14 : #include "scd_memory_remote.h"
15 : #include "scd_memory_local.h"
16 :
17 : typedef struct {
18 : size_t (*read)(uintptr_t addr, void* dst, size_t size);
19 : } ScdMemoryHandler;
20 :
21 : static const ScdMemoryHandler SCD_MEMORY_HANDLE = {ScdMemoryRemoteRead};
22 :
23 520 : void ScdMemoryInitLocal(ScdMemory* memory)
24 : {
25 520 : memory->handlers.read = ScdMemoryLocalRead;
26 520 : memory->data = 0;
27 520 : memory->size = 0;
28 520 : }
29 :
30 0 : void ScdMemoryInitRemote(ScdMemory* memory)
31 : {
32 0 : memory->handlers.read = ScdMemoryRemoteRead;
33 0 : memory->data = 0;
34 0 : memory->size = 0;
35 0 : }
36 :
37 56312 : size_t ScdMemoryRead(ScdMemory* memory, uintptr_t addr, void* dst, size_t size)
38 : {
39 56312 : if (memory == NULL) {
40 56106 : return SCD_MEMORY_HANDLE.read(addr, dst, size);
41 : }
42 206 : if (addr < memory->data || addr >= memory->data + memory->size) {
43 18 : SCD_DLOG_ERR(
44 : "Invalid address, addr 0x%llx out of memory range[0x%llx, 0x%llx],", addr, memory->data,
45 : memory->data + memory->size);
46 18 : return 0;
47 : }
48 188 : return memory->handlers.read(addr, dst, size);
49 : }
50 :
51 12798 : void* ScdMemoryGetAddr(ScdMemory* memory, uintptr_t offset, size_t size)
52 : {
53 12798 : if (offset + size > memory->size) {
54 36 : SCD_DLOG_ERR("read memory failed, read size is out of memory range.");
55 36 : return NULL;
56 : }
57 12762 : return (void*)(memory->data + offset);
58 : }
59 :
60 310 : size_t ScdMemoryReadString(ScdMemory* memory, uintptr_t addr, char* dst, size_t size)
61 : {
62 310 : if ((memory == NULL) || (dst == NULL) || (size <= 1U)) {
63 12 : return 0;
64 : }
65 :
66 298 : size_t i = 0;
67 5676 : while (i < size) {
68 5676 : char* value = ScdMemoryGetAddr(memory, addr + i, 1U);
69 5676 : if ((value == NULL) || (*value == '\0')) {
70 298 : dst[i] = '\0';
71 298 : return i;
72 : }
73 5378 : dst[i] = *value;
74 5378 : i++;
75 : }
76 0 : dst[size - 1U] = '\0';
77 0 : return size - 1U;
78 : }
|