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 = {
22 : ScdMemoryRemoteRead
23 : };
24 :
25 450 : void ScdMemoryInitLocal(ScdMemory *memory)
26 : {
27 450 : memory->handlers.read = ScdMemoryLocalRead;
28 450 : memory->data = 0;
29 450 : memory->size = 0;
30 450 : }
31 :
32 0 : void ScdMemoryInitRemote(ScdMemory *memory)
33 : {
34 0 : memory->handlers.read = ScdMemoryRemoteRead;
35 0 : memory->data = 0;
36 0 : memory->size = 0;
37 0 : }
38 :
39 50048 : size_t ScdMemoryRead(ScdMemory *memory, uintptr_t addr, void *dst, size_t size)
40 : {
41 50048 : if (memory == NULL) {
42 49872 : return SCD_MEMORY_HANDLE.read(addr, dst, size);
43 : }
44 176 : if (addr < memory->data || addr >= memory->data + memory->size) {
45 16 : SCD_DLOG_ERR("Invalid address, addr 0x%llx out of memory range[0x%llx, 0x%llx],",
46 : addr, memory->data, memory->data + memory->size);
47 16 : return 0;
48 : }
49 160 : return memory->handlers.read(addr, dst, size);
50 : }
51 :
52 64 : void *ScdMemoryGetAddr(ScdMemory *memory, uintptr_t offset, size_t size)
53 : {
54 64 : if (offset + size > memory->size) {
55 32 : SCD_DLOG_ERR("read memory failed, read size is out of memory range.");
56 32 : return NULL;
57 : }
58 32 : return (void *)(memory->data + offset);
59 : }
60 :
61 3 : size_t ScdMemoryReadString(ScdMemory *memory, uintptr_t addr, char *dst, size_t size)
62 : {
63 3 : if ((memory == NULL) || (dst == NULL) || (size <= 1U)) {
64 3 : return 0;
65 : }
66 :
67 0 : size_t i = 0;
68 0 : while (i < size) {
69 0 : char *value = ScdMemoryGetAddr(memory, addr + i, 1U);
70 0 : if ((value == NULL) || (*value == '\0')) {
71 0 : dst[i] = '\0';
72 0 : return i;
73 : }
74 0 : dst[i] = *value;
75 0 : i++;
76 : }
77 0 : dst[size - 1U] = '\0';
78 0 : return size - 1U;
79 : }
|