1 /*
2 * Copyright 2023, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20
21 #include "apf_interpreter.h"
22 #include "test_buf_allocator.h"
23
24 packet_buffer *head = NULL;
25 packet_buffer *tail = NULL;
26 uint8_t apf_test_tx_dscp;
27
28 /**
29 * Test implementation of apf_allocate_buffer()
30 *
31 * This is a reference apf_allocate_buffer() implementation for testing purpose.
32 * It supports being called multiple times for each apf_run().
33 * Allocate a new buffer and attach next to the current buffer, then move the current to it.
34 * Return the pointer to beginning of the allocated buffer region.
35 */
apf_allocate_buffer(void * ctx,uint32_t size)36 uint8_t* apf_allocate_buffer(__attribute__ ((unused)) void* ctx, uint32_t size) {
37 if (size > BUFFER_SIZE) {
38 return NULL;
39 }
40
41 packet_buffer* ptr = (packet_buffer *) malloc(sizeof(packet_buffer));
42 if (!ptr) {
43 fprintf(stderr, "failed to allocate buffer!\n");
44 return NULL;
45 }
46
47 memset(ptr->data, 0xff, sizeof(ptr->data));
48 ptr->next = NULL;
49 ptr->len = 0;
50
51 if (!head) {
52 // the first buffer allocated
53 head = ptr;
54 tail = head;
55 } else {
56 // append allocated buffer, and move current to the next
57 tail->next = ptr;
58 tail = tail->next;
59 }
60
61 return ptr->data;
62 }
63
64 /**
65 * Test implementation of apf_transmit_buffer()
66 *
67 * This is a reference apf_transmit_buffer() implementation for testing purpose.
68 * Update the buffer length and dscp value from the transmit packet.
69 */
apf_transmit_buffer(void * ctx,uint8_t * ptr,uint32_t len,uint8_t dscp)70 int apf_transmit_buffer(__attribute__((unused)) void* ctx, uint8_t* ptr,
71 uint32_t len, uint8_t dscp) {
72 if (len && len < ETH_HLEN) return -1;
73 if (!tail || (ptr != tail->data)) return -1;
74
75 tail->len = len;
76 apf_test_tx_dscp = dscp;
77 return 0;
78 }
79