Skip to content

Commit

Permalink
Add global variable example (#51)
Browse files Browse the repository at this point in the history
Signed-off-by: Alan Jowett <[email protected]>
  • Loading branch information
Alan-Jowett authored Dec 16, 2024
1 parent 69a84e1 commit b1ec1a2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ add_custom_target(samples ALL
${CMAKE_CURRENT_SOURCE_DIR}/build/dependent_read.o
${CMAKE_CURRENT_SOURCE_DIR}/build/exposeptr.o
${CMAKE_CURRENT_SOURCE_DIR}/build/exposeptr2.o
${CMAKE_CURRENT_SOURCE_DIR}/build/global_variable.o
${CMAKE_CURRENT_SOURCE_DIR}/build/loop.o
${CMAKE_CURRENT_SOURCE_DIR}/build/mapoverflow.o
${CMAKE_CURRENT_SOURCE_DIR}/build/mapunderflow.o
Expand Down Expand Up @@ -93,6 +94,10 @@ add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/build/exposeptr2.o
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/exposeptr2.c
COMMAND clang -g -target bpf -Wall -O2 -I ${libbpf_SOURCE_DIR}/src -c ${CMAKE_CURRENT_SOURCE_DIR}/src/exposeptr2.c -o ${CMAKE_CURRENT_SOURCE_DIR}/build/exposeptr2.o)

add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/build/global_variable.o
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/global_variable.c
COMMAND clang -g -target bpf -Wall -O2 -I ${libbpf_SOURCE_DIR}/src -c ${CMAKE_CURRENT_SOURCE_DIR}/src/global_variable.c -o ${CMAKE_CURRENT_SOURCE_DIR}/build/global_variable.o)

add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/build/loop.o
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/loop.c
COMMAND clang -g -target bpf -Wall -O2 -I ${libbpf_SOURCE_DIR}/src -c ${CMAKE_CURRENT_SOURCE_DIR}/src/loop.c -o ${CMAKE_CURRENT_SOURCE_DIR}/build/loop.o)
Expand Down
Binary file added build/global_variable.o
Binary file not shown.
19 changes: 19 additions & 0 deletions src/global_variable.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) Prevail Verifier contributors.
// SPDX-License-Identifier: MIT

#include "bpf.h"

// This sample demonstrates how to use global variables in BPF programs.
// Global variables are shared among all threads in the same BPF program and
// can be used to store global states. They must be declared as `volatile`
// to prevent the compiler from optimizing them away and must accessed
// using atomic operations to avoid race conditions.

static volatile uint32_t global_var = 0;
static volatile uint32_t global_var_2 = 0;

int func(void* ctx) {
__sync_fetch_and_add(&global_var, 1);
__sync_fetch_and_add(&global_var_2, 2);
return 0;
}

0 comments on commit b1ec1a2

Please sign in to comment.