Cleanup c programs (#1620)

Cleanup C programs
This commit is contained in:
jackcmay
2018-10-26 19:38:07 -07:00
committed by GitHub
parent 9a6a399a29
commit 3488ea7d1c
27 changed files with 629 additions and 786 deletions

1
programs/bpf/c/README.md Normal file
View File

@ -0,0 +1 @@
Place holder, will hold instructions on how to setup and build C-based BPF programs

96
programs/bpf/c/makefile Normal file
View File

@ -0,0 +1,96 @@
_@ :=@
INC_DIRS := -I.
SRC_DIR := ./src
OUT_DIR := ./out
LLVM_DIR := /usr/local/opt/llvm/bin
CC = $(LLVM_DIR)/clang
CC_FLAGS = \
-Werror \
-target \
bpf -O2 \
-emit-llvm \
-fno-builtin
LD = $(LLVM_DIR)/llc
LD_FLAGS = \
-march=bpf \
-filetype=obj \
-function-sections
OBJ_DUMP = $(LLVM_DIR)/llvm-objdump
OBJ_DUMP_FLAGS = \
-color \
-source \
-disassemble
help:
@echo 'BPF Program makefile'
@echo ''
@echo 'This makefile will build BPF Programs from C source files into ELFs'
@echo ''
@echo 'Assumptions:'
@echo ' - Programs are a single .c source file (may include headers)'
@echo ' - Programs are located in the source directory: $(SRC_DIR)'
@echo ' - Programs are named by their basename (eg. file name:foo.c -> program name:foo)'
@echo ' - Output files will be placed in the directory: $(OUT_DIR)'
@echo ''
@echo 'User settings'
@echo ' - The following setting are overridable on the command line, default values shown'
@echo ' - Verbosity, for verbose: '_@=':'
@echo ' - _@=$(_@)'
@echo ' - List of include dirs:'
@echo ' INC_DIRS=$(INC_DIRS)'
@echo ' - Location of source files:'
@echo ' SRC_DIR=$(SRC_DIR)'
@echo ' - Location to place output files:'
@echo ' OUT_DIR=$(OUT_DIR)'
@echo ' - Location of LLVM:'
@echo ' LLVM_DIR=$(LLVM_DIR)'
@echo ''
@echo 'Usage:'
@echo ' - make help - This help message'
@echo ' - make all - Builds all the programs in the directory: $(SRC_DIR)'
@echo ' - make clean - Cleans all programs'
@echo ' - make dump_<program name> - Dumps the contents of the program to stdout'
@echo ' - make <program name> - Build a single program by name'
@echo ''
@echo 'Available programs:'
$(foreach name, $(PROGRAM_NAMES), @echo ' - $(name)'$(\n))
@echo ''
@echo 'Example:'
@echo ' - Assuming a programed named foo (src/foo.c)'
@echo ' - make foo INC_DIRS='-I. -Isrc''
@echo ' - make dump_foo'
.PRECIOUS: $(OUT_DIR)/%.bc
$(OUT_DIR)/%.bc: $(SRC_DIR)/%.c
$(_@)mkdir -p $(OUT_DIR)
$(_@)$(CC) $(CC_FLAGS) $(INC_DIRS) -o $@ -c $< -MMD -MF $(@:.bc=.d)
.PRECIOUS: $(OUT_DIR)/%.o
$(OUT_DIR)/%.o: $(OUT_DIR)/%.bc
$(_@)$(LD) $(LD_FLAGS) -o $@ $<
-include $(wildcard $(OUT_DIR)/*.d)
PROGRAM_NAMES := $(notdir $(basename $(wildcard src/*.c)))
define \n
endef
%: $(addprefix $(OUT_DIR)/, %.o)
@echo $@ up to date
.PHONY: help all dump clean
all: $(PROGRAM_NAMES)
dump_%: %
$(_@)$(OBJ_DUMP) $(OBJ_DUMP_FLAGS) $(addprefix $(OUT_DIR)/, $(addsuffix .o, $<))
clean:
$(_@)rm -rf $(OUT_DIR)

261
programs/bpf/c/sol_bpf_c.h Normal file
View File

@ -0,0 +1,261 @@
#ifndef SOL_BPF_C_H
#define SOL_BPF_C_H
/**
* @brief Solana C-based BPF program utility functions and types
*/
/**
* Numberic types
*/
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed int int16_t;
typedef unsigned int uint16_t;
typedef signed long int int32_t;
typedef unsigned long int uint32_t;
typedef signed long long int int64_t;
typedef unsigned long long int uint64_t;
/**
* Boolean type
*/
typedef enum { false = 0, true } bool;
/**
* Built-in helper functions
* @{
* The BPF VM makes a limited number of helper functions available to BPF
* programs. They are resolved at run-time and identified by a function index.
* Calling any of these functions results in `Call` instruction out of the
* user's BPF program.
*
* The helper functions all follow the same signature:
*
* int helper(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t)
*
* The meaning of each argument and return value is dependent on the particular
* helper function being called.
*/
/**
* Helper function that prints to stdout
*
* Prints the hexadecimal representation of each parameter
*/
#define BPF_TRACE_PRINTK_IDX 6
static int (*sol_print)(uint64_t, uint64_t, uint64_t, uint64_t,
uint64_t) = (void *)BPF_TRACE_PRINTK_IDX;
/**@}*/
/**
* Prefix for all BPF functions
*
* This prefix should be used for functions in order to facilitate
* interopability with BPF representation
*/
#define SOL_FN_PREFIX __attribute__((always_inline)) static
/**
* Size of Public key in bytes
*/
#define SIZE_PUBKEY 32
/**
* Public key
*/
typedef struct {
uint8_t x[SIZE_PUBKEY];
} SolPubkey;
/**
* Compares two public keys
*
* @param one First public key
* @param two Second public key
* @return True if the same
*/
SOL_FN_PREFIX bool SolPubkey_same(SolPubkey *one, SolPubkey *two) {
for (int i = 0; i < SIZE_PUBKEY; i++) {
if (one->x[i] != two->x[i]) {
return false;
}
}
return true;
}
/**
* Keyed Accounts
*/
typedef struct {
SolPubkey *key; /** Public Key of the account owner */
int64_t *tokens; /** Numer of tokens owned by this account */
uint64_t userdata_len; /** Length of userdata in bytes */
uint8_t *userdata; /** On-chain data owned by this account */
SolPubkey *program_id; /** Program that owns this account */
} SolKeyedAccounts;
/**
* Copies memory
*/
SOL_FN_PREFIX void sol_memcpy(void *dst, void *src, int len) {
for (int i = 0; i < len; i++) {
*((uint8_t *)dst + i) = *((uint8_t *)src + i);
}
}
/**
* Panics
*
* Prints the line number where the panic occurred and then causes
* the BPF VM to immediately halt execution. No accounts' userdata are updated
*/
#define sol_panic() _sol_panic(__LINE__)
SOL_FN_PREFIX void _sol_panic(uint64_t line) {
sol_print(0xFF, 0xFF, 0xFF, 0xFF, line);
uint8_t *pv = (uint8_t *)1;
*pv = 1;
}
/**
* Asserts
*/
#define sol_assert(expr) \
if (!(expr)) { \
_sol_panic(__LINE__); \
}
/**
* De-serializes the input parameters into usable types
*
* Use this function to deserialize the buffer passed to the program entrypoint
* into usable types. This function does not perform copy deserialization,
* instead it populates the pointers and lengths in SolKeyedAccounts and data so
* that any modification to tokens or account data take place on the original
* buffer. Doing so also eliminates the need to serialize back into the buffer
* at program end.
*
* @param input Source buffer containing serialized input parameters
* @param num_ka Numer of SolKeyedAccounts to fill
* @param ka Pointer to an array of SolKeyedAccounts to deserialize into
* @param data On return, a pointer to the instruction data
* @param data_len On return, the length in bytes of the instruction data
* @return Boolan True if successful
*/
SOL_FN_PREFIX bool sol_deserialize(uint8_t *input, uint64_t num_ka,
SolKeyedAccounts *ka, uint8_t **data,
uint64_t *data_len) {
if (num_ka != *(uint64_t *)input) {
return false;
}
input += sizeof(uint64_t);
for (int i = 0; i < num_ka; i++) {
// key
ka[i].key = (SolPubkey *)input;
input += SIZE_PUBKEY;
// tokens
ka[i].tokens = (int64_t *)input;
input += sizeof(int64_t);
// account userdata
ka[i].userdata_len = *(uint64_t *)input;
input += sizeof(uint64_t);
ka[i].userdata = input;
input += ka[i].userdata_len;
// program_id
ka[i].program_id = (SolPubkey *)input;
input += SIZE_PUBKEY;
}
// instruction data
*data_len = *(uint64_t *)input;
input += sizeof(uint64_t);
*data = input;
return true;
}
/**
* Debugging utilities
* @{
*/
/**
* Prints the hexadecimal representation of a public key
*
* @param key The public key to print
*/
SOL_FN_PREFIX void sol_print_key(SolPubkey *key) {
for (int j = 0; j < SIZE_PUBKEY; j++) {
sol_print(0, 0, 0, j, key->x[j]);
}
}
/**
* Prints the hexadecimal representation of an array
*
* @param array The array to print
*/
SOL_FN_PREFIX void sol_print_array(uint8_t *array, int len) {
for (int j = 0; j < len; j++) {
sol_print(0, 0, 0, j, array[j]);
}
}
/**
* Prints the hexadecimal representation of the program's input parameters
*
* @param num_ka Numer of SolKeyedAccounts to print
* @param ka A pointer to an array of SolKeyedAccounts to print
* @param data A pointer to the instruction data to print
* @param data_len The length in bytes of the instruction data
*/
SOL_FN_PREFIX void sol_print_params(uint64_t num_ka, SolKeyedAccounts *ka,
uint8_t *data, uint64_t data_len) {
sol_print(0, 0, 0, 0, num_ka);
for (int i = 0; i < num_ka; i++) {
sol_print_key(ka[i].key);
sol_print(0, 0, 0, 0, *ka[i].tokens);
sol_print_array(ka[i].userdata, ka[i].userdata_len);
sol_print_key(ka[i].program_id);
}
sol_print_array(data, data_len);
}
/**@}*/
/**
* Program entrypoint
* @{
*
* The following is An example of a simple program that prints the input
* parameters it received:
*
* #define NUM_KA 1
*
* bool entrypoint(uint8_t *input) {
* SolKeyedAccounts ka[NUM_KA];
* uint8_t *data;
* uint64_t data_len;
*
* if (1 != sol_deserialize((uint8_t *)buf, NUM_KA, ka, &data, &data_len)) {
* return false;
* }
* print_params(1, ka, data, data_len);
* return true;
* }
*/
/**
* Program entrypoint signature
*
* @param input An array containing serialized input parameters
* @return True if successful
*/
extern bool entrypoint(uint8_t *input);
/**@}*/
#endif // SOL_BPF_C_H

View File

@ -0,0 +1,32 @@
/**
* @brief Example C-based BPF program that moves funds from one account to
* another
*/
#include "sol_bpf_c.h"
/**
* Numer of SolKeyedAccounts expected. The program should bail if an
* unexpected number of accounts are passed to the program's entrypoint
*/
#define NUM_KA 3
extern bool entrypoint(uint8_t *input) {
SolKeyedAccounts ka[NUM_KA];
uint8_t *data;
uint64_t data_len;
if (!sol_deserialize((uint8_t *)input, NUM_KA, ka, &data, &data_len)) {
return false;
}
int64_t tokens = *(int64_t *)data;
if (*ka[0].tokens >= tokens) {
*ka[0].tokens -= tokens;
*ka[2].tokens += tokens;
// sol_print(0, 0, *ka[0].tokens, *ka[2].tokens, tokens);
} else {
// sol_print(0, 0, 0xFF, *ka[0].tokens, tokens);
}
return true;
}

24
programs/bpf/c/src/noop.c Normal file
View File

@ -0,0 +1,24 @@
/**
* @brief Example C-based BPF program that prints out the parameters
* passed to it
*/
#include "sol_bpf_c.h"
/**
* Numer of SolKeyedAccounts expected. The program should bail if an
* unexpected number of accounts are passed to the program's entrypoint
*/
#define NUM_KA 1
extern bool entrypoint(uint8_t *input) {
SolKeyedAccounts ka[NUM_KA];
uint8_t *data;
uint64_t data_len;
if (!sol_deserialize((uint8_t *)input, NUM_KA, ka, &data, &data_len)) {
return false;
}
sol_print_params(1, ka, data, data_len);
return true;
}

View File

@ -0,0 +1,232 @@
/**
* @brief TicTacToe Dashboard C-based BPF program
*/
#include "sol_bpf_c.h"
#include "tictactoe.h"
typedef enum {
Result_Ok,
Result_Panic,
Result_GameInProgress,
Result_InvalidArguments,
Result_InvalidMove,
Result_InvalidUserdata,
Result_InvalidTimestamp,
Result_NoGame,
Result_NotYourTurn,
Result_PlayerNotFound,
Result_UserdataTooSmall,
} Result;
typedef enum {
Command_Init = 0,
Command_Join,
Command_KeepAlive,
Command_Move,
} Command;
SOL_FN_PREFIX void game_dump_board(Game *self) {
sol_print(0x9, 0x9, 0x9, 0x9, 0x9);
sol_print(0, 0, self->board[0], self->board[1], self->board[2]);
sol_print(0, 0, self->board[3], self->board[4], self->board[5]);
sol_print(0, 0, self->board[6], self->board[7], self->board[8]);
sol_print(0x9, 0x9, 0x9, 0x9, 0x9);
}
SOL_FN_PREFIX void game_create(Game *self, SolPubkey *player_x) {
// account memory is zero-initialized
sol_memcpy(self->player_x.x, player_x, SIZE_PUBKEY);
self->state = State_Waiting;
for (int i = 0; i < 9; i++) {
self->board[i] = BoardItem_F;
}
}
SOL_FN_PREFIX Result game_join(Game *self, SolPubkey *player_o,
int64_t timestamp) {
if (self->state == State_Waiting) {
sol_memcpy(self->player_o.x, player_o, SIZE_PUBKEY);
self->state = State_XMove;
if (timestamp <= self->keep_alive[1]) {
return Result_InvalidTimestamp;
} else {
self->keep_alive[1] = timestamp;
return Result_Ok;
}
}
return Result_GameInProgress;
}
SOL_FN_PREFIX bool game_same(BoardItem x_or_o, BoardItem one, BoardItem two,
BoardItem three) {
if (x_or_o == one && x_or_o == two && x_or_o == three) {
return true;
}
return false;
}
SOL_FN_PREFIX bool game_same_player(SolPubkey *one, SolPubkey *two) {
for (int i = 0; i < SIZE_PUBKEY; i++) {
if (one->x[i] != two->x[i]) {
return false;
}
}
return true;
}
SOL_FN_PREFIX Result game_next_move(Game *self, SolPubkey *player, int x,
int y) {
int board_index = y * 3 + x;
if (board_index >= 9 || self->board[board_index] != BoardItem_F) {
return Result_InvalidMove;
}
BoardItem x_or_o;
State won_state;
switch (self->state) {
case State_XMove:
if (!game_same_player(player, &self->player_x)) {
return Result_PlayerNotFound;
}
self->state = State_OMove;
x_or_o = BoardItem_X;
won_state = State_XWon;
break;
case State_OMove:
if (!game_same_player(player, &self->player_o)) {
return Result_PlayerNotFound;
}
self->state = State_XMove;
x_or_o = BoardItem_O;
won_state = State_OWon;
break;
default:
return Result_NotYourTurn;
}
self->board[board_index] = x_or_o;
// game_dump_board(self);
bool winner =
// Check rows
game_same(x_or_o, self->board[0], self->board[1], self->board[2]) ||
game_same(x_or_o, self->board[3], self->board[4], self->board[5]) ||
game_same(x_or_o, self->board[6], self->board[7], self->board[8]) ||
// Check columns
game_same(x_or_o, self->board[0], self->board[3], self->board[6]) ||
game_same(x_or_o, self->board[1], self->board[4], self->board[7]) ||
game_same(x_or_o, self->board[2], self->board[5], self->board[8]) ||
// Check both diagonals
game_same(x_or_o, self->board[0], self->board[4], self->board[8]) ||
game_same(x_or_o, self->board[2], self->board[4], self->board[6]);
if (winner) {
self->state = won_state;
}
{
int draw = true;
for (int i = 0; i < 9; i++) {
if (BoardItem_F == self->board[i]) {
draw = false;
break;
}
}
if (draw) {
self->state = State_Draw;
}
}
return Result_Ok;
}
SOL_FN_PREFIX Result game_keep_alive(Game *self, SolPubkey *player,
int64_t timestamp) {
switch (self->state) {
case State_Waiting:
case State_XMove:
case State_OMove:
if (game_same_player(player, &self->player_x)) {
if (timestamp <= self->keep_alive[0]) {
return Result_InvalidTimestamp;
}
self->keep_alive[0] = timestamp;
} else if (game_same_player(player, &self->player_o)) {
if (timestamp <= self->keep_alive[1]) {
return Result_InvalidTimestamp;
}
self->keep_alive[1] = timestamp;
} else {
return Result_PlayerNotFound;
}
break;
default:
break;
}
return Result_Ok;
}
/**
* Numer of SolKeyedAccounts expected. The program should bail if an
* unexpected number of accounts are passed to the program's entrypoint
*
* accounts[0] On Init must be player X, after that doesn't matter,
* anybody can cause a dashboard update
* accounts[1] must be a TicTacToe state account
* accounts[2] must be account of current player, only Pubkey is used
*/
#define NUM_KA 3
extern bool entrypoint(uint8_t *input) {
SolKeyedAccounts ka[NUM_KA];
uint8_t *data;
uint64_t data_len;
int err = 0;
if (!sol_deserialize((uint8_t *)input, NUM_KA, ka, &data, &data_len)) {
return false;
}
if (sizeof(Game) > ka[1].userdata_len) {
sol_print(0, 0, 0xFF, sizeof(Game), ka[2].userdata_len);
return false;
}
Game game;
sol_memcpy(&game, ka[1].userdata, sizeof(game));
Command command = *data;
switch (command) {
case Command_Init:
game_create(&game, ka[2].key);
break;
case Command_Join:
err = game_join(&game, ka[2].key, *((int64_t *)(data + 4)));
break;
case Command_KeepAlive:
err = game_keep_alive(&game, ka[2].key, /*TODO*/ 0);
break;
case Command_Move:
err = game_next_move(&game, ka[2].key, data[4], data[5]);
break;
default:
return false;
}
sol_memcpy(ka[1].userdata, &game, sizeof(game));
sol_print(0, 0, 0, err, game.state);
if (Result_Ok != err) {
return false;
}
return true;
}

View File

@ -0,0 +1,36 @@
#ifndef TICTACTOE_H
#define TICTACTOE_H
/**
* @brief Definitions common to tictactoe and tictactoe_dashboard
*/
typedef enum {
State_Waiting,
State_XMove,
State_OMove,
State_XWon,
State_OWon,
State_Draw,
} State;
typedef enum { BoardItem_F, BoardItem_X, BoardItem_O } BoardItem;
/**
* Game state
*
* This structure is stored in the owner's account userdata
*
* Board Coordinates
* | 0,0 | 1,0 | 2,0 |
* | 0,1 | 1,1 | 2,1 |
* | 0,2 | 1,2 | 2,2 |
*/
typedef struct {
SolPubkey player_x; /** Player who initialized the game */
SolPubkey player_o; /** Player who joined the game */
State state; /** Current state of the game */
BoardItem board[9]; /** Tracks the player moves */
int64_t keep_alive[2]; /** Keep Alive for each player */
} Game;
#endif // TICTACTOE_H

View File

@ -0,0 +1,99 @@
/**
* @brief TicTacToe C-based BPF program
*/
#include "sol_bpf_c.h"
#include "tictactoe.h"
#define MAX_GAMES_TRACKED 5
/**
* Dashboard state
*
* This structure is stored in the owner's account userdata
*/
typedef struct {
SolPubkey pending; /** Latest pending game */
SolPubkey completed[MAX_GAMES_TRACKED]; /** Last N completed games (0 is the
latest) */
uint32_t latest_game; /** Index into completed pointing to latest game completed */
uint32_t total; /** Total number of completed games */
} Dashboard;
SOL_FN_PREFIX bool update(Dashboard *self, Game *game, SolPubkey *game_pubkey) {
switch (game->state) {
case State_Waiting:
sol_memcpy(&self->pending, game_pubkey, SIZE_PUBKEY);
break;
case State_XMove:
case State_OMove:
// Nothing to do. In progress games are not managed by the dashboard
break;
case State_XWon:
case State_OWon:
case State_Draw:
for (int i = 0; i < MAX_GAMES_TRACKED; i++) {
if (SolPubkey_same(&self->completed[i], game_pubkey)) {
// TODO: Once the PoH height is exposed to programs, it could be used
// to ensure
// that old games are not being re-added and causing total to
// increment incorrectly.
return false;
}
}
self->total += 1;
self->latest_game = (self->latest_game + 1) % MAX_GAMES_TRACKED;
sol_memcpy(self->completed[self->latest_game].x, game_pubkey,
SIZE_PUBKEY);
break;
default:
break;
}
return true;
}
/**
* Numer of SolKeyedAccounts expected. The program should bail if an
* unexpected number of accounts are passed to the program's entrypoint
*
* accounts[0] doesn't matter, anybody can cause a dashboard update
* accounts[1] must be a Dashboard account
* accounts[2] must be a Game account
*/
#define NUM_KA 3
extern bool entrypoint(uint8_t *input) {
SolKeyedAccounts ka[NUM_KA];
uint8_t *data;
uint64_t data_len;
int err = 0;
if (!sol_deserialize((uint8_t *)input, NUM_KA, ka, &data, &data_len)) {
return false;
}
// TODO check dashboard and game program ids (how to check now that they are
// not known values)
// TODO check validity of dashboard and game structures contents
if (sizeof(Dashboard) > ka[1].userdata_len) {
sol_print(0, 0, 0xFF, sizeof(Dashboard), ka[2].userdata_len);
return false;
}
Dashboard dashboard;
sol_memcpy(&dashboard, ka[1].userdata, sizeof(dashboard));
if (sizeof(Game) > ka[2].userdata_len) {
sol_print(0, 0, 0xFF, sizeof(Game), ka[2].userdata_len);
return false;
}
Game game;
sol_memcpy(&game, ka[2].userdata, sizeof(game));
if (true != update(&dashboard, &game, ka[2].key)) {
return false;
}
sol_memcpy(ka[1].userdata, &dashboard, sizeof(dashboard));
return true;
}