repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
smwikipedia/EwokOS
kernel/arch/raspi2/src/hardware.c
#include <hardware.h> #include <mm/mmu.h> #include <mailbox.h> void hw_init() { mailboxInit(); } uint32_t get_phy_ram_size() { TagsInfoT info; if(mailboxGetBoardInfo(&info) == NULL) return 256*MB; return info.memory_arm_size+info.memory_vc_size; } uint32_t get_mmio_base_phy() { return 0x3F000000; } uint32_t get_initrd_base_phy() { return 0x08000000; } uint32_t get_initrd_size() { return 1*MB; } uint32_t get_mmio_mem_size() { return 4*MB; } uint32_t get_uart_irq() { return 25; } uint32_t get_timer_irq() { return 0; } #define CORE0_ROUTING 0x40000000 void arch_set_kernel_vm(page_dir_entry_t* vm) { uint32_t offset = CORE0_ROUTING - get_mmio_base_phy(); uint32_t vbase = MMIO_BASE + offset; uint32_t pbase = get_mmio_base_phy() +offset; map_pages(vm, vbase, pbase, pbase+16*KB, AP_RW_D); }
smwikipedia/EwokOS
rootfs/bin/echo/echo.c
<filename>rootfs/bin/echo/echo.c<gh_stars>0 #include <unistd.h> #include <stdio.h> int main() { init_cmain_arg(); const char* arg = read_cmain_arg(); arg = read_cmain_arg(); if(arg == NULL) return 0; printf("%s\n", arg); return 0; }
smwikipedia/EwokOS
kernel/arch/versatilepb/src/timer.c
#include <timer.h> #include <types.h> #include <mm/mmu.h> #include <hardware.h> /* The ARM Versatile 926EJS board contains two ARM SB804 dual timer modules [ARM Timers 2004]. Each timer module contains two timers, which are driven by the same clock. The base addresses of the timers are: Timer0: 0x101E2000, Timer1: 0x101E2020 Timer2: 0x101E3000, Timer3: 0x101E3020 */ #define TIMER ((volatile uint32_t*)(MMIO_BASE+0x001e2000)) #define TIMER_LOAD 0x00 #define TIMER_VALUE 0x01 #define TIMER_CONTROL 0x02 #define TIMER_INTCTL 0x03 #define TIMER_BGLOAD 0x06 void timer_set_interval(uint32_t intervalMicrosecond) { TIMER[TIMER_CONTROL] = 0; TIMER[TIMER_BGLOAD] = 0; TIMER[TIMER_LOAD] = intervalMicrosecond; TIMER[TIMER_CONTROL] = 0xe2; } void timer_clear_interrupt(void) { TIMER[TIMER_INTCTL] = 0xFFFFFFFF; } void timer_init() { }
smwikipedia/EwokOS
kernel/arch/raspi2/src/mailbox.h
#ifndef MAILBOX_H #define MAILBOX_H void mailboxInit(void); unsigned int mailboxRead(unsigned int channel); void mailboxWrite(unsigned int channel,unsigned int value); typedef struct { unsigned int tags_id; unsigned int vbuf_size; /* usually 8-bytes */ unsigned int req_res; /* req:0x00000000, res: 0x80000000 | value length */ unsigned int vbuffer[2]; /* most tag response is 8-bytes long */ } TagsHeadT; typedef struct { unsigned int info_status; unsigned int test, temp; volatile unsigned int *buff; /* hardware/board info */ unsigned int vc_revision; unsigned int board_model; unsigned int board_revision; unsigned int board_mac_addrl; /* 6-bytes actually! */ unsigned int board_mac_addrh; unsigned int board_serial_l; unsigned int board_serial_h; unsigned int memory_arm_base; unsigned int memory_arm_size; unsigned int memory_vc_base; unsigned int memory_vc_size; /* framebuffer info */ unsigned int fb_width, fb_height; unsigned int fb_vwidth, fb_vheight; unsigned int fb_depth, fb_pixel_order; unsigned int fb_alpha_mode, fb_pitch; unsigned int fb_vx_offset, fb_vy_offset; } TagsInfoT; unsigned int* mailboxGetBoardInfo(TagsInfoT* info); unsigned int* mailboxGetVideoInfo(TagsInfoT* info); #endif
smwikipedia/EwokOS
rootfs/lib/include/proto.h
#ifndef PROTO_H #define PROTO_H #include "types.h" #include "kstring.h" #define PROTO_BUFFER 128 typedef struct { void *data; uint32_t size; uint32_t totalSize; uint32_t offset; bool readOnly; }proto_t; void proto_init(proto_t* proto, void* data, uint32_t size); proto_t* proto_new(void* data, uint32_t size); void proto_add(proto_t* proto, void* item, uint32_t size); void proto_add_int(proto_t* proto, int32_t v); void proto_add_str(proto_t* proto, const char* v); void* proto_read(proto_t* proto, uint32_t *size); int32_t proto_read_int(proto_t* proto); const char* proto_read_str(proto_t* proto); void proto_clear(proto_t* proto); void proto_free(proto_t* proto); #endif
smwikipedia/EwokOS
kernel/include/mm/mmu.h
#ifndef MMU_H #define MMU_H #include <types.h> #define PAGE_SIZE (4*KB) #define PAGE_TABLE_SIZE (1*KB) #define PAGE_DIR_NUM 4096 #define PAGE_DIR_SIZE (PAGE_DIR_NUM*4) #define KERNEL_BASE 0x80000000 //=2G virtual address start base. #define MMIO_BASE (KERNEL_BASE + 1*GB) #define IPC_TASK_BASE (MMIO_BASE + 512*MB) #define INTERRUPT_VECTOR_BASE 0xffff0000 #define USER_STACK_BOTTOM (KERNEL_BASE - 2 * PAGE_SIZE) //#define KERNEL_STACK_BOTTOM (KERNEL_BASE - 3 * PAGE_SIZE) #define KMALLOC_BASE ((uint32_t)&_kernel_end + 256*KB) //256KB reserved for kernel pageDirTable(at least 16KB). #define KMALLOC_SIZE 4*MB // keep for kernel trunk memory, can only used by kernel(km_alloc/km_free). #define ALLOCATABLE_MEMORY_START (KMALLOC_BASE + KMALLOC_SIZE) #define INIT_RESERV_MEMORY_SIZE (8*MB) #define V2P(V) ((uint32_t)V - KERNEL_BASE) #define P2V(P) ((uint32_t)P + KERNEL_BASE) #define get32(addr) (*((volatile uint32_t *)(addr))) #define put32(addr, val) (*((volatile uint32_t *)(addr)) = (val)) #define get8(addr) (*((volatile uint8_t *)(addr))) #define put8(addr, val) (*((volatile uint8_t *)(addr)) = (val)) /* descriptor types */ #define PAGE_TYPE 2 #define PAGE_DIR_TYPE 1 /* access permissions */ #ifdef A_CORE #define AP_RW_D 0x5 #define AP_RW_R 0xa #define AP_RW_RW 0xf #else #define AP_RW_D 0x55 #define AP_RW_R 0xaa #define AP_RW_RW 0xff #endif #define PAGE_DIR_INDEX(x) ((uint32_t)x >> 20) #define PAGE_INDEX(x) (((uint32_t)x >> 12) & 255) #define PAGE_TABLE_TO_BASE(x) ((uint32_t)x >> 10) #define BASE_TO_PAGE_TABLE(x) ((void *) ((uint32_t)x << 10)) #define PAGE_TO_BASE(x) ((uint32_t)x >> 12) #ifndef __ASSEMBLER__ /* a 32-bit entry in hardware's PageDir table */ typedef struct { uint32_t type : 2; uint32_t : 3; uint32_t domain : 4; uint32_t : 1; uint32_t base : 22; } page_dir_entry_t; /* a 32-bit entry in hardware's page table */ typedef struct { uint32_t type : 2; uint32_t bufferable : 1; uint32_t cacheable : 1; uint32_t permissions : 8; uint32_t base : 20; } page_table_entry_t; void map_pages(page_dir_entry_t *vm, uint32_t vaddr, uint32_t pstart, uint32_t pend, int access_permissions); void map_page(page_dir_entry_t *vm, uint32_t virtual_addr, uint32_t physical, int access_permissions); void unmap_page(page_dir_entry_t *vm, uint32_t virtual_addr); void free_page_tables(page_dir_entry_t *vm); uint32_t resolve_phy_address(page_dir_entry_t *vm, uint32_t virtual); page_table_entry_t* get_page_table_entry(page_dir_entry_t *vm, uint32_t virtual); #endif #endif
smwikipedia/EwokOS
rootfs/test/test/test.c
<gh_stars>0 #include <types.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <syscall.h> #include <device.h> int main() { int i = 0; while(true) { printf("%d ", i++); usleep(1000000); } return 0; }
smwikipedia/EwokOS
kernel/src/printk.c
<gh_stars>0 #include "printk.h" #include "vprintf.h" #include "dev/basic_dev.h" static void outc(char c, void* p) { (void)p; dev_char_write(dev_typeid(DEV_UART, 0), &c, 1); } void printk(const char *format, ...) { va_list ap; va_start(ap, format); v_printf(outc, NULL, format, ap); va_end(ap); }
smwikipedia/EwokOS
rootfs/bin/ls/ls.c
#include <unistd.h> #include <stdio.h> #include <vfs/fs.h> #include <stdlib.h> #include <kstring.h> int main() { char name[NAME_MAX]; char pwd[NAME_MAX]; getcwd(pwd, NAME_MAX); init_cmain_arg(); const char* arg = read_cmain_arg(); arg = read_cmain_arg(); if(arg == NULL) { strcpy(name, pwd); } else if(arg[0] == '/') { strcpy(name, arg); } else { if(strcmp(pwd, "/") == 0) snprintf(name, NAME_MAX-1, "/%s", arg); else snprintf(name, NAME_MAX-1, "%s/%s", pwd, arg); } int fd = fs_open(name, 0); if(fd >= 0) { uint32_t num; fs_info_t* infos = fs_kids(fd, &num); if(infos != NULL) { for(uint32_t i=0; i<num; i++) { fs_info_t* info = &infos[i]; if(info->type == FS_TYPE_FILE) printf(" %16s -f- %4d %d\n", info->name, info->owner, info->size); else if(info->type == FS_TYPE_DIR) printf(" +%16s -d- %4d %d\n", info->name, info->owner, info->size); } free(infos); } fs_close(fd); } return 0; }
smwikipedia/EwokOS
lib/include/types.h
#ifndef TYPES_H #define TYPES_H #ifndef __ASSEMBLER__ #include <stdint.h> #ifndef NULL #define NULL ((void*) 0) #endif /* boolean */ #ifndef bool typedef int bool; #endif /* integer types */ /* typedef __signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef __signed char i8_t; typedef unsigned char u8_t; typedef short i16_t; typedef unsigned short u16_t; typedef int i32_t; typedef unsigned int u32_t; */ /* boolean constants */ #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #define KB 1024 #define MB (1024*KB) #define GB (1024*MB) #define CMD_MAX 128 #define NAME_MAX 256 #define DEV_NAME_MAX 64 #define ALIGN_DOWN(x, alignment) ((x) & ~(alignment - 1)) #define ALIGN_UP(x, alignment) (((x) + alignment - 1) & ~(alignment - 1)) typedef void (*free_func_t) (void* p); typedef void* (*malloc_func_t) (uint32_t size); #endif #endif
smwikipedia/EwokOS
rootfs/lib/src/graph/font.c
#include "graph/font.h" #include "kstring.h" extern font_t font_16x32; extern font_t font_12x24; extern font_t font_10x20; extern font_t font_12x16; extern font_t font_9x16; extern font_t font_8x16; extern font_t font_8x10; extern font_t font_9x8; extern font_t font_8x8; extern font_t font_7x9; extern font_t font_6x8; extern font_t font_5x12; extern font_t font_4x6; font_t* get_font(const char* name) { if(strcmp(name, "16x32") == 0) return &font_16x32; else if(strcmp(name, "12x24") == 0) return &font_12x24; else if(strcmp(name, "10x20") == 0) return &font_10x20; else if(strcmp(name, "12x16") == 0) return &font_12x16; else if(strcmp(name, "9x16") == 0) return &font_9x16; else if(strcmp(name, "8x16") == 0) return &font_8x16; else if(strcmp(name, "8x10") == 0) return &font_8x10; else if(strcmp(name, "9x8") == 0) return &font_9x8; else if(strcmp(name, "8x8") == 0) return &font_8x8; else if(strcmp(name, "7x9") == 0) return &font_7x9; else if(strcmp(name, "6x8") == 0) return &font_6x8; else if(strcmp(name, "5x12") == 0) return &font_5x12; else if(strcmp(name, "4x6") == 0) return &font_4x6; return NULL; }
smwikipedia/EwokOS
rootfs/sbin/vfsd/fstree.h
#ifndef FS_TREE_H #define FS_TREE_H #include "types.h" #include "tree.h" #include "fsinfo.h" void fs_tree_init(); void fs_tree_node_init(tree_node_t* node); tree_node_t* fs_new_node(); tree_node_t* fs_tree_simple_get(tree_node_t* father, const char* name); tree_node_t* fs_tree_get(tree_node_t* father, const char* name); tree_node_t* fs_tree_simple_add(tree_node_t* father, const char* name); #endif
smwikipedia/EwokOS
lib/src/kstring.c
<reponame>smwikipedia/EwokOS #include "kstring.h" /* * memcmp copies n bytes from the source buffer to the target buffer. It returns * the point32_ter to the target. */ extern void *__memcpy32(void *target, const void *source, uint32_t n); inline void *memcpy(void *target, const void *source, uint32_t n) { char *target_buffer = (char *) target; char *source_buffer = (char *) source; uint32_t m = (n / 32); if(m > 0) { m *= 32; __memcpy32(target_buffer, source_buffer, m); } while(m < n) { target_buffer[m] = source_buffer[m]; ++m; } return target; } /* memset fills the given target with given length with the given character. */ void* memset(void *target, int32_t c, uint32_t size) { char* dst = target; char value = (char)c; uint32_t align_value; align_value = (uint32_t)dst & 0x03; if(align_value) { align_value = 4 - align_value; if(size > align_value) { while(align_value) { *(uint8_t *)dst = value; dst += 1; align_value -= 1; size -= 1; } } else { while(size) { *(uint8_t *)dst = value; dst += 1; size -= 1; } return target; } } align_value = value | (value << 8); align_value = align_value | (align_value << 16); while(size >= 4) { *(uint32_t *)dst = align_value; dst += 4; size -= 4; } while(size) { *(uint8_t *)dst = value; dst += 1; size -= 1; } return target; } /* inline void *memset(void *target, int32_t c, uint32_t len) { char *target_buffer = (char *) target; register uint32_t i = 0; for (i = 0; i < len; i++) target_buffer[i] = (char) c; return target; } */ /* * strcpy copies the given null-terminated source string int32_to the given target. * It returns the point32_ter to the target. */ inline char *strcpy(char *target, const char *source) { char *result = target; while (*source) { *target = *source; target++; source++; } *target = '\0'; return result; } /* * strncpy copies source to the target with size n. At most n - 1 characters * will be copied and the resulting target will always be null-terminated. The * function returns strlen(source). If return value is >= n, then truncation * occured. */ inline uint32_t strncpy(char *target, const char *source, uint32_t n) { uint32_t source_len = 0; uint32_t i = 0; while (i < n && source[i] != '\0') { target[i] = source[i]; i++; } target[i] = '\0'; source_len = strlen(source); return source_len; } /* * strcmp compares the given input strings using the lexicographical order, and * returns 0 if s1 == s2, returns a negative number if s1 < s2, and returns a * positive number if s1 > s2. */ inline int32_t strcmp(const char *s1, const char *s2) { while (*s1 == *s2 && *s1 != '\0' && *s2 != '\0') { s1++; s2++; } return (*s1 - *s2); } /* * strncmp compares the given input strings upto n characters using the * lexicographical order. For return value, please see strcmp. */ inline int32_t strncmp(const char *s1, const char *s2, uint32_t n) { uint32_t i = 0; if (n == 0) return 0; while (*s1 == *s2 && *s1 != '\0' && *s2 != '\0' && i < n - 1) { s1++; s2++; i++; } return (*s1 - *s2); } /* * strchr returns a point32_ter to the first occurence of the given character in the * given string. If the character is not found, it returns NULL. */ inline char *strchr(const char *str, int32_t character) { while (*str != '\0' && *str != character) str++; if (*str == character) return (char *) str; else return NULL; } /* * strtok tokenizes the given string using the given delimiters. If str != NULL, * then it returns a point32_ter to the first token. If str == NULL, then it returns * the a point32_ter to the next token of the string used in previous calls. If no * more tokens are found, it returns NULL. * * WARNING: This function changes the original string. */ inline char *strtok(char *str, const char *delimiters) { static char *last = NULL; char *token = NULL; if (str != NULL) last = str; token = last; /* skip leading delimiters */ while (*token != '\0' && strchr(delimiters, *token) != NULL) token++; /* if there were no non-delimiter characters, return NULL */ if (*token == '\0') { last = NULL; return NULL; } /* scan to find where token ends */ while (*last != '\0' && strchr(delimiters, *last) == NULL) last++; /* terminate the token, and set where the scan of next token starts */ if (*last != '\0') { *last = '\0'; last++; } return token; } /* strlen returns the length of the given null-terminated string. */ inline uint32_t strlen(const char *str) { uint32_t length = 0; while (*str != '\0') { str++; length++; } return length; }
smwikipedia/EwokOS
kernel/arch/versatilepb/src/uart.c
#include <mm/mmu.h> #include <hardware.h> #include <dev/basic_dev.h> #include <system.h> #include <proc.h> /* memory mapping for the serial port */ #define UART0 ((volatile uint32_t*)(MMIO_BASE+0x001f1000)) /* serial port register offsets */ #define UART_DATA 0x00 #define UART_FLAGS 0x18 #define UART_INT_ENABLE 0x0e #define UART_INT_TARGET 0x0f #define UART_INT_CLEAR 0x11 /* serial port bitmasks */ #define UART_RECEIVE 0x10 #define UART_TRANSMIT 0x20 void uart_init(void) { UART0[UART_INT_ENABLE] = UART_RECEIVE; } void uart_trans(char c) { /* wait until transmit buffer is full */ while (UART0[UART_FLAGS] & UART_TRANSMIT); /* write the character */ UART0[UART_DATA] = c; } void uart_putch(int c) { if(c == '\r') c = '\n'; uart_trans(c); } bool uart_ready_to_recv(void) { return UART0[UART_INT_TARGET] & UART_RECEIVE; } int32_t uart_recv(void) { return UART0[UART_DATA]; } #define UART_BUF_SIZE 16 static char _buffer_data[UART_BUF_SIZE]; static dev_buffer_t _uart_buffer = { _buffer_data, UART_BUF_SIZE, 0, 0 }; static int32_t _uart_lock = 0; int32_t dev_uart_read(int16_t id, void* buf, uint32_t size) { (void)id; CRIT_IN(_uart_lock) char* p = (char*)buf; int32_t i = 0; while(i < (int32_t)size) { char c; if(dev_buffer_pop(&_uart_buffer, &c) != 0) break; p[i] = c; i++; } CRIT_OUT(_uart_lock) return i; } int32_t uart_getch() { char c; if(dev_uart_read(0, &c, 1) == 0) return 0; return (int32_t)c; } int32_t dev_uart_write(int16_t id, void* buf, uint32_t size) { (void)id; CRIT_IN(_uart_lock) char* p = (char*)buf; uint32_t i; for(i=0; i<size; i++) { uart_putch(p[i]); } CRIT_OUT(_uart_lock) return -1; } void uart_handle(void) { while (uart_ready_to_recv()) { int32_t data = uart_recv(); CRIT_IN(_uart_lock); dev_buffer_push(&_uart_buffer, (char)data, false); CRIT_OUT(_uart_lock); } }
smwikipedia/EwokOS
rootfs/lib/src/graph/graph.c
#include <graph/graph.h> #include <stdlib.h> #include <kstring.h> #include <vfs/fs.h> #include <fbinfo.h> #include <unistd.h> #include <shm.h> inline uint32_t rgb(uint32_t r, uint32_t g, uint32_t b) { return b << 16 | g << 8 | r; } uint32_t rgb_int(uint32_t c) { return rgb((c>>16)&0xff, (c>>8)&0xff, c&0xff); } graph_t* graph_open(const char* fname) { fb_info_t fbInfo; int fd = fs_open(fname, 0); if(fd < 0) { return NULL; } if(fs_ctrl(fd, 0, NULL, 0, &fbInfo, sizeof(fb_info_t)) != 0) { fs_close(fd); return NULL; } uint32_t sz; int shm_id = fs_dma(fd, &sz); if(shm_id < 0 || sz == 0) { fs_close(fd); return NULL; } void* p = shm_map(shm_id); if(p == NULL) { fs_close(fd); return NULL; } graph_t* ret = (graph_t*)malloc(sizeof(graph_t)); ret->w = fbInfo.width; ret->h = fbInfo.height; ret->buffer = p; ret->fd = fd; ret->shm_id = shm_id; return ret; } void graph_flush(graph_t* graph) { fs_flush(graph->fd); } void graph_close(graph_t* graph) { shm_unmap(graph->shm_id); fs_close(graph->fd); free(graph); } inline void pixel(graph_t* g, int32_t x, int32_t y, uint32_t color) { if(x < 0 || (uint32_t)x >= g->w || y < 0 || (uint32_t)y >= g->h) return; g->buffer[y * g->w + x] = color; } void clear(graph_t* g, uint32_t color) { uint8_t byte = color & 0xff; if(((color >> 8)&0xff) == byte && ((color >> 16)&0xff) == byte) { memset(g->buffer, byte, g->w*g->h*4); return 0; } if(g->w == 0 || g->w == 0) return; uint32_t i = 0; uint32_t sz = g->w * 4; while(i<g->w) { g->buffer[i] = color; ++i; } char* p = (char*)g->buffer; for(i=1; i<g->h; ++i) { memcpy(p+(i*sz), p, sz); } } void line(graph_t* g, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t color) { int32_t dx, dy, x, y, s1, s2, e, temp, swap, i; dy = y2 - y1; if (dy<0) { dy = -dy; s2 = -1; } else s2 = 1; dx = x2 - x1; if (dx<0) { dx = -dx; s1 = -1; } else s1 = 1; x = x1; y = y1; if (dy > dx) { temp=dx; dx=dy; dy=temp; swap=1; } else swap=0; e = 2 * dy - dx; for (i=0; i<=dx; i++) { pixel(g, x, y, color); while (e>=0) { if (swap==1) x += s1; else y += s2; e -= 2*dx; } if (swap==1) y += s2; else x += s1; e += 2*dy; } } void box(graph_t* g, int32_t x, int32_t y, uint32_t w, uint32_t h, uint32_t color) { line(g, x, y, x+w, y, color); line(g, x, y+1, x, y+h, color); line(g, x+1, y+h, x+w, y+h, color); line(g, x+w, y+1, x+w, y+h, color); } void fill(graph_t* g, int32_t x, int32_t y, uint32_t w, uint32_t h, uint32_t color) { int32_t ex, ey; ex = x + w; ey = y + h; for(; y < ey; y++) { int32_t sx = x; for(; sx < ex; sx++) { pixel(g, sx, y, color); } } } static void draw_char8(graph_t* g, int32_t x, int32_t y, char c, font_t* font, uint32_t color) { int32_t xchar, ychar, xpart, ypart, index, pmask; unsigned char *pdata = (unsigned char*) font->data, check; index = (int32_t)c * font->h; ypart = y; for(ychar=0; (uint32_t)ychar<font->h; ychar++) { xpart = x; pmask = 1 << (8-1); check = pdata[index+ychar]; for(xchar=0; (uint32_t)xchar<8; xchar++) { if(check&pmask) pixel(g, xpart, ypart, color); //else // pixel(g, xpart, ypart, bg); xpart++; pmask >>= 1; } ypart++; } } static void draw_char16(graph_t* g, int32_t x, int32_t y, char c, font_t* font, uint32_t color) { int32_t xchar, ychar, xpart, ypart, index, pmask; unsigned char *pdata = (unsigned char*) font->data, check; index = (int32_t)c * font->h * 2; ypart = y; for(ychar=0; (uint32_t)ychar<font->h; ychar++) { xpart = x; pmask = 1 << (8-1); check = pdata[index+ychar]; for(xchar=0; (uint32_t)xchar<8; xchar++) { if(check&pmask) pixel(g, xpart, ypart, color); //else // pixel(g, xpart, ypart, bg); xpart++; pmask >>= 1; } index++; check = pdata[index+ychar]; pmask = 1 << (8-1); for(xchar=0; (uint32_t)xchar<8; xchar++) { if(check&pmask) pixel(g, xpart, ypart, color); //else // pixel(g, xpart, ypart, bg); xpart++; pmask >>= 1; } ypart++; } } void draw_char(graph_t* g, int32_t x, int32_t y, char c, font_t* font, uint32_t color) { if(font->w <= 8) draw_char8(g, x, y, c, font, color); else if(font->w <= 16) draw_char16(g, x, y, c, font, color); } void draw_text(graph_t* g, int32_t x, int32_t y, const char* str, font_t* font, uint32_t color) { while(*str) { draw_char(g, x, y, *str, font, color); x += font->w; str++; } }
smwikipedia/EwokOS
kernel/include/dev/basic_dev.h
#ifndef BASIC_DEVICE_H #define BASIC_DEVICE_H #include <types.h> #include <device.h> bool dev_init(); bool conf_dev_init(); int32_t dev_info(int32_t type_id, void* info); int32_t dev_char_read(int32_t type_id, void* buf, uint32_t size); int32_t dev_char_write(int32_t type_id, void* buf, uint32_t size); int32_t dev_block_read(int32_t type_id, uint32_t block); int32_t dev_block_read_done(int32_t type_id, void* buf); int32_t dev_block_write(int32_t type_id, uint32_t block, void* buf); int32_t dev_block_write_done(int32_t type_id); #endif
smwikipedia/EwokOS
rootfs/lib/include/thread.h
<reponame>smwikipedia/EwokOS #ifndef THREAD_H #define THREAD_H #include <types.h> typedef void (*thread_func_t)(void*p); int32_t thread_raw(thread_func_t func, void* p); #endif
smwikipedia/EwokOS
lib/src/ext2.c
#include <ext2.h> #include <kstring.h> static int32_t search(INODE *ip, const char *name, read_block_func_t read_block, char* buf) { int32_t i; char c, *cp; DIR *dp; for (i=0; i<12; i++){ if ( ip->i_block[i] ){ read_block(ip->i_block[i], buf); dp = (DIR *)buf; cp = buf; while (cp < &buf[SDC_BLOCK_SIZE]){ c = dp->name[dp->name_len]; // save last byte dp->name[dp->name_len] = 0; if (strcmp(dp->name, name) == 0 ){ return(dp->inode); } dp->name[dp->name_len] = c; // restore that last byte cp += dp->rec_len; dp = (DIR *)cp; } } } return -1; } #define MAX_DIR_DEPTH 4 char* ext2_load(const char* filename, int32_t *sz, malloc_func_t mlc, read_block_func_t read_block, char* buf1, char* buf2) { int32_t depth, i, me, iblk, count, u, blk12; char name[MAX_DIR_DEPTH][64]; char *ret, *addr; uint32_t *up; GD *gp; INODE *ip; *sz = -1; depth = 0; while(true) { char* hold = name[depth]; u = 0; if(*filename == '/') filename++; //skip '/' while(*filename != '/') { hold[u] = *filename; u++; filename++; if(*filename == 0 || u >= 63) break; } hold[u] = 0; depth++; if(*filename != 0) filename++; else break; } /* read blk#2 to get group descriptor 0 */ if(read_block(2, buf1) != 0) return NULL; gp = (GD *)buf1; iblk = (uint16_t)gp->bg_inode_table; if(read_block(iblk, buf1) != 0) // read first inode block return NULL; ip = (INODE *)buf1 + 1; // ip->root inode #2 /* serach for system name */ for (i=0; i<depth; i++) { me = search(ip, name[i], read_block, buf2) - 1; if (me < 0) return NULL; if(read_block(iblk+(me/8), buf1) != 0) // read block inode of me return NULL; ip = (INODE *)buf1 + (me % 8); } *sz = ip->i_size; int32_t mlc_size = ALIGN_UP(*sz, SDC_BLOCK_SIZE); blk12 = ip->i_block[12]; addr = (char *)mlc(mlc_size); ret = addr; /* read indirect block into b2 */ count = 0; for (i=0; i<12 && count<(*sz); i++){ if (ip->i_block[i] == 0) break; read_block(ip->i_block[i], addr); addr += SDC_BLOCK_SIZE; count += SDC_BLOCK_SIZE; } if (blk12) { // only if file has indirect blocks read_block(blk12, buf1); up = (uint32_t *)buf1; while(*up && count < (*sz)){ read_block(*up, addr); addr += SDC_BLOCK_SIZE; up++; count += SDC_BLOCK_SIZE; } } return ret; }
smwikipedia/EwokOS
rootfs/sbin/vfsd/tree.c
#include <tree.h> #include <kstring.h> void tree_node_init(tree_node_t* node) { memset(node, 0, sizeof(tree_node_t)); } void tree_add(tree_node_t* father, tree_node_t* node) { if(father == NULL || node == NULL) return; node->father = father; if(father->eChild == NULL) { father->fChild = node; } else { father->eChild->next = node; node->prev = father->eChild; } father->size++; father->eChild = node; } void tree_del(tree_node_t* node, free_func_t fr) { if(node == NULL) return; /*free children*/ tree_node_t* c = node->fChild; while(c != NULL) { tree_node_t* next = c->next; tree_del(c, fr); c = next; } tree_node_t* father = node->father; if(father != NULL) { if(father->fChild == node) father->fChild = node->next; if(father->eChild == node) father->eChild = node->prev; father->size--; } if(node->next != NULL) node->next->prev = node->prev; if(node->prev != NULL) node->prev->next = node->next; /*free node content*/ if(node->data != NULL) fr(node->data); fr(node); }
smwikipedia/EwokOS
kernel/include/kfile.h
#ifndef KFILE_H #define KFILE_H #include <types.h> #include <fsinfo.h> typedef struct kfile { fs_info_t node_info; uint16_t ref_r; uint16_t ref_w; } kfile_t; void kf_init(); int32_t kf_open(fs_info_t* info, int32_t wr); void kf_close(int32_t fd); void kf_unref(kfile_t* kf, uint32_t wr); void kf_ref(kfile_t* kf, uint32_t wr); int32_t kf_get_ref(uint32_t node_addr, uint32_t wr); int32_t kf_node_info_by_fd(int32_t fd, fs_info_t* info); int32_t kf_node_info_by_addr(uint32_t node_addr, fs_info_t* info); int32_t kf_node_info_update(uint32_t node_addr, fs_info_t* info); #endif
smwikipedia/EwokOS
rootfs/bin/shell/shell.c
<gh_stars>0 #include <stdio.h> #include <kstring.h> #include <unistd.h> #include <vfs/fs.h> #include <syscall.h> #define KEY_BACKSPACE 127 #define KEY_LEFT 0x8 static void gets(char* buf, int len) { int i = 0; while(true) { if(i >= len) break; int c = getch(); if(c == 0) { sleep(0); continue; } if (c == KEY_BACKSPACE) { if (i > 0) { //delete last char putch(KEY_LEFT); putch(' '); putch(KEY_LEFT); i--; } } else if (c == 8) { if (i > 0) { //delete last char putch(c); i--; } } else { putch(c); if(c == '\r' || c == '\n') break; buf[i] = c; i++; } } buf[i] = 0; } static int cd(const char* dir) { char cwd[NAME_MAX]; if(getcwd(cwd, NAME_MAX) == NULL) return -1; if(strcmp(dir, ".") == 0) return 0; while(*dir == ' ') /*skip all space*/ dir++; if(dir[0] == 0) { chdir("/"); return 0; } if(strcmp(dir, "..") == 0) { if(strcmp(cwd, "/") == 0) return 0; int len = strlen(cwd) - 1; for(int i=len; i>=0; i--) { if(cwd[i] == '/') { cwd[i] = 0; break; } } if(cwd[0] == 0) { chdir("/"); return 0; } } else if(dir[0] == '/') { strncpy(cwd, dir, NAME_MAX); } else { int len = strlen(cwd); if(cwd[len-1] != '/') { cwd[len] = '/'; len++; } strcpy(cwd+len, dir); } fs_info_t info; if(fs_finfo(cwd, &info) != 0) printf("[%s] not exist!\n", dir); else if(info.type != FS_TYPE_DIR) printf("[%s] is not a directory!\n", dir); else chdir(cwd); return 0; } void export_all() { int32_t i=0; while(true) { char name[64], value[128]; if(syscall3(SYSCALL_GET_ENV_NAME, i, (int32_t)name, 63) != 0 || name[0] == 0) break; if(syscall3(SYSCALL_GET_ENV_VALUE, i, (int32_t)value, 127) != 0) break; printf("%s=%s\n", name, value); i++; } } void export_get(const char* arg) { char value[128]; if(syscall3(SYSCALL_GET_ENV, (int32_t)arg, (int32_t)value, 127) != 0) return; printf("%s=%s\n", arg, value); } void export_set(const char* arg) { char name[64]; char* v = strchr(arg, '='); if(v == NULL) return; strncpy(name, arg, v-arg); syscall2(SYSCALL_SET_ENV, (int32_t)name, (int32_t)(v+1)); } int export(const char* arg) { char* v = strchr(arg, '='); if(v == NULL) export_get(arg); else export_set(arg); return 0; } static int handle(const char* cmd) { if(strcmp(cmd, "cd") == 0) { return cd("/"); } else if(strncmp(cmd, "cd ", 3) == 0) { return cd(cmd + 3); } else if(strcmp(cmd, "export") == 0) { export_all(); return 0; } else if(strncmp(cmd, "export ", 7) == 0) { return export(cmd+7); } return -1; /*not shell internal command*/ } static int32_t find_exec(char* fname, char* cmd) { fs_info_t info; int32_t i = 0; char c = 0; while(cmd[i] != 0) { if(cmd[i] == ' ') { c = ' '; cmd[i] = 0; break; } i++; } if(cmd[0] == '/') { strcpy(fname, cmd); if(fs_finfo(fname, &info) == 0) { cmd[i] = c; strcpy(fname, cmd); return 0; } } snprintf(fname, NAME_MAX-1, "/sbin/%s", cmd); if(fs_finfo(fname, &info) == 0) { cmd[i] = c; snprintf(fname, NAME_MAX-1, "/sbin/%s", cmd); return 0; } snprintf(fname, NAME_MAX-1, "/bin/%s", cmd); if(fs_finfo(fname, &info) == 0) { cmd[i] = c; snprintf(fname, NAME_MAX-1, "/bin/%s", cmd); return 0; } snprintf(fname, NAME_MAX-1, "/usr/bin/%s", cmd); if(fs_finfo(fname, &info) == 0) { cmd[i] = c; snprintf(fname, NAME_MAX-1, "/usr/bin/%s", cmd); return 0; } return -1; } int main() { char cmd[CMD_MAX]; char cwd[NAME_MAX]; int uid = getuid(); while(1) { if(uid == 0) printf("ewok:%s.# ", getcwd(cwd, NAME_MAX)); else printf("ewok:%s.$ ", getcwd(cwd, NAME_MAX)); gets(cmd, CMD_MAX); if(cmd[0] == 0) continue; if(strcmp(cmd, "exit") == 0) break; if(handle(cmd) == 0) continue; int len = strlen(cmd); len -= 1; bool fg = true; if(cmd[len] == '&') { cmd[len] = 0; fg = false; } char fname[NAME_MAX]; if(find_exec(fname, cmd) != 0) { printf("'%s' not found!\n", cmd); continue; } int child_pid = fork(); if (child_pid == 0) { exec(fname); return 0; } else if(fg) { wait(child_pid); } cmd[0] = 0; } return 0; }
smwikipedia/EwokOS
rootfs/bin/pwd/pwd.c
<filename>rootfs/bin/pwd/pwd.c #include <unistd.h> #include <stdio.h> int main() { char pwd[NAME_MAX]; printf("%s\n", getcwd(pwd, NAME_MAX)); return 0; }
smwikipedia/EwokOS
rootfs/lib/src/stdio.c
#include <syscall.h> #include <kstring.h> #include <vprintf.h> #include <device.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int32_t _stdin =-1; int32_t _stdout = -1; #define STDOUT_BUF_SIZE 128 static char _out_buffer[STDOUT_BUF_SIZE]; static int32_t _out_size = 0; void init_stdio() { _stdin = _stdout = -1; _stdin = _stdout = open(getenv("STDIO_DEV"), 0); //_stdin = _stdout = open("/dev/tty0", 0); _out_size = 0; } static void stdout_flush() { if(_stdout < 0) syscall3(SYSCALL_DEV_CHAR_WRITE, dev_typeid(DEV_UART, 0), (int32_t)_out_buffer, _out_size); else write(_stdout, _out_buffer, _out_size); _out_size = 0; } void putch(int c) { _out_buffer[_out_size] = c; _out_size++; stdout_flush(); } int getch() { char buf[1]; buf[0] = 0; int32_t res = -1; while(true) { if(_stdin < 0) res = syscall3(SYSCALL_DEV_CHAR_READ, dev_typeid(DEV_UART, 0), (int32_t)buf, 1); else res = read(_stdin, buf, 1); if(res > 0) break; sleep(0); } return (int)buf[0]; } static void outc(char c, void* p) { (void)p; _out_buffer[_out_size] = c; _out_size++; if(_out_size >= STDOUT_BUF_SIZE || c == '\n' || c == '\r') { stdout_flush(); } } /* * printf_base formats and prints the given data. See vsprintf() for the format * flags currently supported. */ void printf(const char *format, ...) { va_list ap; va_start(ap, format); v_printf(outc, NULL, format, ap); stdout_flush(); va_end(ap); }
smwikipedia/EwokOS
rootfs/lib/src/dev/devserv.c
<filename>rootfs/lib/src/dev/devserv.c #include <dev/devserv.h> #include <kserv.h> #include <unistd.h> #include <ipc.h> #include <stdlib.h> #include <kstring.h> #include <vfs/vfs.h> #include <vfs/fs.h> #include <proto.h> #include <stdio.h> static void do_open(device_t* dev, package_t* pkg) { proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size); uint32_t node = (uint32_t)proto_read_int(proto); int32_t flags = proto_read_int(proto); proto_free(proto); if(node == 0) { ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); return; } int32_t ret = 0; if(dev->open != NULL) ret = dev->open(node, flags); ipc_send(pkg->id, pkg->type, &ret, 4); } static void do_close(device_t* dev, package_t* pkg) { uint32_t node = *(uint32_t*)get_pkg_data(pkg); if(node == 0) { return; } if(dev->close != NULL) dev->close(node); } static void do_dma(device_t* dev, package_t* pkg) { uint32_t node = *(uint32_t*)get_pkg_data(pkg); if(node == 0) { ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); return; } int32_t dma = 0; uint32_t size = 0; if(dev->dma != NULL) { dma = dev->dma(node, &size); } proto_t* proto = proto_new(NULL, 0); proto_add_int(proto, dma); proto_add_int(proto, (int32_t)size); ipc_send(pkg->id, pkg->type, proto->data, proto->size); proto_free(proto); } static void do_flush(device_t* dev, package_t* pkg) { uint32_t node = *(uint32_t*)get_pkg_data(pkg); if(node == 0) { return; } if(dev->flush != NULL) dev->flush(node); } static void do_add(device_t* dev, package_t* pkg) { proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size); uint32_t node = (uint32_t)proto_read_int(proto); const char* name = proto_read_str(proto); proto_free(proto); if(node == 0 || name[0] == 0) { ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); return; } int32_t ret = 0; if(dev->add != NULL) ret = dev->add(node, name); ipc_send(pkg->id, pkg->type, &ret, 4); } static void do_write(device_t* dev, package_t* pkg) { proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size); uint32_t node = (uint32_t)proto_read_int(proto); uint32_t size; void* p = proto_read(proto, &size); int32_t seek = proto_read_int(proto); proto_free(proto); if(node == 0) { ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); return; } int32_t ret = 0; if(dev->write != NULL) ret = dev->write(node, p, size, seek); ipc_send(pkg->id, pkg->type, &ret, 4); } static void do_read(device_t* dev, package_t* pkg) { proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size); uint32_t node = (uint32_t)proto_read_int(proto); uint32_t size = (uint32_t)proto_read_int(proto); uint32_t seek = (uint32_t)proto_read_int(proto); proto_free(proto); if(node == 0) { ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); return; } if(size == 0) { ipc_send(pkg->id, pkg->type, NULL, 0); return; } char* buf = (char*)malloc(size); int32_t ret = 0; if(dev->read != NULL) ret = dev->read(node, buf, size, seek); if(ret < 0) ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); else ipc_send(pkg->id, pkg->type, buf, ret); free(buf); } static void do_ctrl(device_t* dev, package_t* pkg) { proto_t* proto = proto_new(get_pkg_data(pkg), pkg->size); uint32_t node = (uint32_t)proto_read_int(proto); uint32_t cmd = (uint32_t)proto_read_int(proto); uint32_t size; void* p = proto_read(proto, &size); proto_free(proto); if(node == 0) { ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); return; } p = NULL; int32_t ret = -1; if(dev->ctrl != NULL) p = dev->ctrl(node, cmd, p, size, &ret); if(ret < 0) ipc_send(pkg->id, PKG_TYPE_ERR, NULL, 0); else ipc_send(pkg->id, pkg->type, p, ret); } static void handle(package_t* pkg, void* p) { device_t* dev = (device_t*)p; switch(pkg->type) { case FS_OPEN: do_open(dev, pkg); break; case FS_CLOSE: do_close(dev, pkg); break; case FS_WRITE: do_write(dev, pkg); break; case FS_READ: do_read(dev, pkg); break; case FS_CTRL: do_ctrl(dev, pkg); break; case FS_DMA: do_dma(dev, pkg); break; case FS_FLUSH: do_flush(dev, pkg); break; case FS_ADD: do_add(dev, pkg); break; } } void dev_run(device_t* dev, const char* dev_name, uint32_t index, const char* node_name, bool file) { if(kserv_get_pid(dev_name) >= 0) { printf("%s device service has been running!\n", dev_name); exit(0); } uint32_t node = vfs_mount(node_name, dev_name, index, file); if(node == 0) return; if(dev->mount != NULL) { if(dev->mount(node, index) != 0) return; } printf("(%s mounted to vfs:%s)\n", dev_name, node_name); kserv_run(dev_name, handle, dev); if(vfs_unmount(node) != 0) return; if(dev->unmount != NULL) { dev->unmount(node); } }
smwikipedia/EwokOS
kernel/arch/versatilepb/src/mailbox.c
<reponame>smwikipedia/EwokOS<gh_stars>0 #include <hardware.h>
smwikipedia/EwokOS
kernel/arch/raspi2/src/irq.c
<reponame>smwikipedia/EwokOS #include <irq.h> #include <mm/mmu.h> #include <kstring.h> #include <types.h> #include <timer.h> #include <dev/uart.h> #include <hardware.h> /* interrupt controller register offsets */ #define PIC_STATUS 2 #define PIC_INT_ENABLE 5 #define PIC_INT_DISABLE 9 #define PIC_BASE_OFF 0xB200 #define CORE0_TIMER__irqCNTL 0x40000040 void routing_core0cntv_to_core0irq(void) { uint32_t offset = CORE0_TIMER__irqCNTL-get_mmio_base_phy(); uint32_t vbase = MMIO_BASE+offset; mmio_write(vbase, 0x08); } #define CORE0__irq_SOURCE 0x40000060 uint32_t read_core0timer_pending(void) { uint32_t tmp; uint32_t offset = CORE0__irq_SOURCE - get_mmio_base_phy(); uint32_t vbase = MMIO_BASE+offset; tmp = mmio_read(vbase); return tmp; } extern uint32_t _timer_frq; void write_cntv_tval(uint32_t val) { __asm__ volatile ("mcr p15, 0, %0, c14, c3, 0" :: "r"(val) ); return; } void irq_init() { routing_core0cntv_to_core0irq(); } void enable_irq(uint32_t line) { volatile uint32_t* vpic = (volatile uint32_t*)(MMIO_BASE+PIC_BASE_OFF); vpic[PIC_INT_ENABLE] |= (1<<line); } void disable_irq(uint32_t line) { volatile uint32_t* vpic = (volatile uint32_t*)(MMIO_BASE+PIC_BASE_OFF); vpic[PIC_INT_DISABLE] |= (1<<line); } #define PINT_UART0 (1 << 25) void irq_handle() { volatile uint32_t* vpic = (volatile uint32_t*)(MMIO_BASE+PIC_BASE_OFF); volatile uint32_t pic_status = vpic[PIC_STATUS]; if (read_core0timer_pending() & 0x08 ) { write_cntv_tval(_timer_frq); // clear cntv interrupt and set next 1/100 sec timer. timer_handle(); } if((pic_status & PINT_UART0) != 0) { uart_handle(); } }
smwikipedia/EwokOS
rootfs/test/draw/draw.c
#include <types.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <kstring.h> #include <graph/graph.h> #include <graph/font.h> void fbtest() { font_t* font = get_font("16x32"); graph_t* g = graph_open("/dev/fb0"); if(g == NULL) { return; } int i = 0; char s[32]; while(i<200) { clear(g, rgb(100, 100, 200)); snprintf(s, 31, "Hello, MicroKernel OS! (%d)", i++); fill(g, 10, 10, font->w* strlen(s) + 20, font->h + 20, rgb(0, 0, 0)); draw_text(g, 20, 20, s, font, rgb(255, 255, 255)); graph_flush(g); sleep(0); } graph_close(g); } int main() { init_cmain_arg(); const char* arg = read_cmain_arg(); arg = read_cmain_arg(); if(arg == NULL) { fbtest(); } else { int i = 0; while(i++ < atoi(arg)) { int pid = fork(); if(pid == 0) { fbtest(); return 0; } } while(true) { sleep(0); } } return 0; }
smwikipedia/EwokOS
lib/include/sconf_parse.h
<filename>lib/include/sconf_parse.h #ifndef SIMPLE_CONFIG_PARSE_H #define SIMPLE_CONFIG_PARSE_H #include <types.h> #define S_CONF_NAME_MAX 32 #define S_CONF_VALUE_MAX 128 #define S_CONF_ITEM_MAX 32 typedef struct { char name[S_CONF_NAME_MAX]; char value[S_CONF_VALUE_MAX]; } sconf_item_t; typedef struct { sconf_item_t items[S_CONF_ITEM_MAX]; } sconf_t; sconf_t* sconf_parse(const char* str, malloc_func_t mlc); void sconf_free(sconf_t* conf, free_func_t fr); const char* sconf_get(sconf_t *conf, const char*name); #endif
smwikipedia/EwokOS
kernel/include/timer.h
#ifndef TIMER_H #define TIMER_H #include <types.h> void timer_init(); void timer_start(); void timer_set_interval(uint32_t intervalMicrosecond); void timer_clear_interrupt(void); void cpu_tick(uint32_t* sec, uint32_t* msec); void timer_handle(); #endif
smwikipedia/EwokOS
rootfs/sbin/vfsd/tree.h
#ifndef TREE_H #define TREE_H #include <types.h> typedef struct tree_node { uint32_t id; struct tree_node* father; struct tree_node* fChild; /*first child*/ struct tree_node* eChild; /*last child*/ struct tree_node* next; /*next brother*/ struct tree_node* prev; /*prev brother*/ uint32_t size; void* data; } tree_node_t; void tree_node_init(tree_node_t* node); void tree_add(tree_node_t* father, tree_node_t* node); void tree_del(tree_node_t* node, free_func_t fr); #endif
smwikipedia/EwokOS
rootfs/test/mouse/mouse.c
#include <device.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main() { printf("read mouse, click to quit.\n"); int fd = open("/dev/mouse0", 0); if(fd < 0) return -1; while(true) { int8_t ev[4]; int sz = read(fd, ev, 4); if(sz < 0) break; if(sz == 0) continue; printf("mouse: down:0x%x, rx:%d, ry:%d, rz:%d\n", ev[0], ev[1], ev[2], ev[3]); if(ev[0] == 1) break; } close(fd); return 0; }
smwikipedia/EwokOS
rootfs/lib/src/semaphore.c
#include <semaphore.h> #include <syscall.h> #include <unistd.h> int32_t semaphore_init(semaphore_t* s) { return syscall1(SYSCALL_SEMAPHORE_INIT, (int32_t)s); } int32_t semaphore_close(semaphore_t* s) { return syscall1(SYSCALL_SEMAPHORE_CLOSE, (int32_t)s); } int32_t semaphore_lock(semaphore_t* s) { //return syscall1(SYSCALL_SEMAPHORE_LOCK, (int32_t)s); while(syscall1(SYSCALL_SEMAPHORE_LOCK, (int32_t)s) < 0) sleep(0); return 0; } int32_t semaphore_unlock(semaphore_t* s) { return syscall1(SYSCALL_SEMAPHORE_UNLOCK, (int32_t)s); }
smwikipedia/EwokOS
kernel/src/semaphore.c
#include <semaphore.h> #include <system.h> #include <proc.h> static inline uint32_t semaphore_phy_addr(int32_t* s) { uint32_t paddr = resolve_phy_address(_current_proc->space->vm, (uint32_t)s); return paddr; } static int32_t _p_lock = 0; int32_t semaphore_init(int32_t *s) { if(s == NULL) return -1; CRIT_IN(_p_lock) *s = 0; CRIT_OUT(_p_lock) return 0; } int32_t semaphore_close(int32_t* s) { CRIT_IN(_p_lock) uint32_t paddr = semaphore_phy_addr(s); proc_unblock(paddr); *s = -1; CRIT_OUT(_p_lock) return 0; } int32_t semaphore_lock(int32_t* s) { CRIT_IN(_p_lock) if(s == NULL || (*s) < 0) { CRIT_OUT(_p_lock) return 0; } uint32_t paddr = semaphore_phy_addr(s); while(true) { if(*s > 0) {/*still locked by other process, put current process to block*/ _current_proc->state = BLOCK; _current_proc->slept_by = paddr; CRIT_OUT(_p_lock) //schedule(); return -1; } else { (*s)++; break; } } CRIT_OUT(_p_lock) return 0; } int32_t semaphore_unlock(int32_t* s) { CRIT_IN(_p_lock) if(s == NULL || (*s) <= 0) { CRIT_OUT(_p_lock) return 0; } (*s)--; if((*s) == 0) {/*if all locks cleared, wake up processed blocked by this semaphore*/ uint32_t paddr = semaphore_phy_addr(s); proc_unblock(paddr); } CRIT_OUT(_p_lock) return 0; }
smwikipedia/EwokOS
rootfs/bin/mkdir/mkdir.c
#include <unistd.h> #include <stdio.h> #include <cmain.h> #include <vfs/fs.h> int main() { init_cmain_arg(); const char* arg = read_cmain_arg(); arg = read_cmain_arg(); if(arg != NULL) { char cwd[NAME_MAX]; int fd = fs_open(getcwd(cwd, NAME_MAX), 0); if(fd >= 0) { fs_add(fd, arg); fs_close(fd); } } return 0; }
smwikipedia/EwokOS
rootfs/lib/src/proto.c
#include "proto.h" #include <kstring.h> #include <stdlib.h> void proto_init(proto_t* proto, void* data, uint32_t size) { proto->data = data; proto->size = size; proto->totalSize = size; proto->offset = 0; proto->readOnly = (data == NULL) ? false:true; } proto_t* proto_new(void* data, uint32_t size) { proto_t* ret = (proto_t*)malloc(sizeof(proto_t)); proto_init(ret, data, size); return ret; } void proto_add(proto_t* proto, void* item, uint32_t size) { if(proto->readOnly) return; uint32_t newSize = proto->size + size + 4; char* p = (char*)proto->data; if(proto->totalSize <= newSize) { newSize += PROTO_BUFFER; proto->totalSize = newSize; p = (char*)malloc(newSize); if(proto->data != NULL) { memcpy(p, proto->data, proto->size); free(proto->data); } proto->data = p; } memcpy(p+proto->size, &size, 4); if(size > 0 && item != NULL) memcpy(p+proto->size+4, item, size); proto->size += (size + 4); } inline void proto_add_int(proto_t* proto, int32_t v) { proto_add(proto, (void*)&v, 4); } inline void proto_add_str(proto_t* proto, const char* v) { proto_add(proto, (void*)v, strlen(v)+1); } void* proto_read(proto_t* proto, uint32_t *size) { if(proto->data == NULL || proto->size == 0 || proto->offset >= proto->size) return NULL; char* p = ((char*)proto->data) + proto->offset; uint32_t sz; memcpy(&sz, p, 4); proto->offset += (4 + sz); if(size != NULL) *size = sz; if(sz == 0) return NULL; return p+4; } inline int32_t proto_read_int(proto_t* proto) { void *p = proto_read(proto, NULL); if(p == NULL) return 0; return *(int*)p; } inline const char* proto_read_str(proto_t* proto) { return (const char*)proto_read(proto, NULL); } void proto_clear(proto_t* proto) { if(proto->readOnly) return; if(proto->data != NULL) free(proto->data); proto->data = NULL; proto->size = 0; proto->totalSize = 0; proto->offset = 0; proto->readOnly = false; } void proto_free(proto_t* proto) { proto_clear(proto); free(proto); }
smwikipedia/EwokOS
kernel/include/syscalls.h
#ifndef SYSCALLS_H #define SYSCALLS_H #include "types.h" int32_t handle_syscall(int32_t code, int32_t arg0, int32_t arg1, int32_t arg2); #endif
smwikipedia/EwokOS
rootfs/bin/kill/kill.c
#include <cmain.h> #include <stdlib.h> #include <syscall.h> int main() { init_cmain_arg(); const char* arg = read_cmain_arg(); arg = read_cmain_arg(); if(arg == NULL) { return -1; } int pid = atoi(arg); return syscall2(SYSCALL_SYSTEM_CMD, 3, pid); }
smwikipedia/EwokOS
kernel/arch/raspi2/src/timer.c
<reponame>smwikipedia/EwokOS<gh_stars>0 #include <timer.h> #include <types.h> #include <mm/mmu.h> #include <hardware.h> #include <irq.h> /*#define ARM_TIMER_OFF 0xB400 #define ARM_TIMER_CTRL_32BIT (1<<1) #define ARM_TIMER_CTRL_ENABLE (1<<7) #define ARM_TIMER_CTRL_IRQ_ENABLE (1<<5) #define ARM_TIMER_CTRL_PRESCALE_256 (2<<2) #define IRQ_ARM_TIMER_BIT 0 #define TIMER_LOAD 0x00 #define TIMER_CONTROL 0x02 #define TIMER_INTCTL 0x03 #define TIMER_BGLOAD 0x06 */ uint32_t read_cntfrq(void) { uint32_t val; __asm__ volatile ("mrc p15, 0, %0, c14, c0, 0" : "=r"(val) ); return val; } uint32_t _timer_frq = 0; extern void write_cntv_tval(uint32_t val); static void enable_cntv(void) { uint32_t cntv_ctl; cntv_ctl = 1; __asm__ volatile ("mcr p15, 0, %0, c14, c3, 1" :: "r"(cntv_ctl) ); // write CNTV_CTL } /*static void disable_cntv(void) { uint32_t cntv_ctl; cntv_ctl = 0; __asm__ volatile ("mcr p15, 0, %0, c14, c3, 1" :: "r"(cntv_ctl) ); // write CNTV_CTL } */ void timer_set_interval(uint32_t interval_microsecond) { if(interval_microsecond == 0) interval_microsecond = 1000; _timer_frq = (read_cntfrq() / interval_microsecond); write_cntv_tval(_timer_frq); enable_cntv(); } void timer_init() { } void timer_clear_interrupt(void) { }
smwikipedia/EwokOS
kernel/arch/versatilepb/src/hardware.c
#include <hardware.h> #include <mm/mmu.h> void hw_init() { } uint32_t get_phy_ram_size() { return 256*MB; } uint32_t get_mmio_base_phy() { return 0x10000000; } uint32_t get_mmio_mem_size() { return 4*MB; } void arch_set_kernel_vm(page_dir_entry_t* vm) { (void)vm; uint32_t fbBase = (uint32_t)V2P(_fb_start); //framebuffer addr map_pages(vm, fbBase, fbBase, fbBase+4*MB, AP_RW_D); }
smwikipedia/EwokOS
rootfs/dev/consoled/consoled.c
<filename>rootfs/dev/consoled/consoled.c #include <dev/devserv.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <syscall.h> #include <graph/graph.h> #include <graph/font.h> #include <basic_math.h> #include <sconf.h> #define T_W 2 /*tab width*/ static uint32_t _bg_color = 0x0; static uint32_t _fg_color = 0xffffffff; static font_t* _font = NULL; static graph_t* _graph = NULL; static int32_t _keyb_id = -1; typedef struct { uint32_t start_line; uint32_t line; uint32_t line_num; uint32_t line_w; uint32_t total; char* data; uint32_t size; } content_t; static content_t _content; static int32_t read_config() { sconf_t *conf = sconf_load("/etc/console.conf"); if(conf == NULL) return -1; const char* v = sconf_get(conf, "bg_color"); if(v[0] != 0) _bg_color = rgb_int(atoi_base(v, 16)); v = sconf_get(conf, "fg_color"); if(v[0] != 0) _fg_color = rgb_int(atoi_base(v, 16)); v = sconf_get(conf, "font"); if(v[0] != 0) _font = get_font(v); sconf_free(conf, free); return 0; } static int32_t console_mount(uint32_t node, int32_t index) { (void)node; (void)index; _bg_color = rgb(0x22, 0x22, 0x66); _fg_color = rgb(0xaa, 0xbb, 0xaa); _font = get_font("8x16"); if(_font == NULL) return -1; read_config(); _keyb_id = open("/dev/keyb0", 0); if(_keyb_id < 0) return -1; _graph = graph_open("/dev/fb0"); if(_graph == NULL) return -1; _content.size = 0; _content.start_line = 0; _content.line = 0; _content.line_w = div_u32(_graph->w, _font->w)-1; _content.line_num = div_u32(_graph->h, _font->h)-1; _content.total = _content.line_num * _content.line_w; _content.data = (char*)malloc(_content.line_num*_content.line_w); clear(_graph, _bg_color); return 0; } static int32_t console_unmount(uint32_t node) { (void)node; if(_graph == NULL) return -1; close(_keyb_id); free(_content.data); graph_close(_graph); _graph = NULL; _content.size = 0; _content.data = NULL; return 0; } static uint32_t get_at(uint32_t i) { uint32_t at = i + (_content.line_w * _content.start_line); if(at >= _content.total) at -= _content.total; return at; } static void refresh() { clear(_graph, _bg_color); uint32_t i=0; uint32_t x = 0; uint32_t y = 0; while(i < _content.size) { uint32_t at = get_at(i); char c = _content.data[at]; if(c != ' ') { draw_char(_graph, x*_font->w, y*_font->h, _content.data[at], _font, _fg_color); } x++; if(x >= _content.line_w) { y++; x = 0; } i++; } } static void move_line() { _content.line--; _content.start_line++; if(_content.start_line >= _content.line_num) _content.start_line = 0; _content.size -= _content.line_w; refresh(); } static void put_char(char c) { if(c == '\r') c = '\n'; if(c == 8) { //backspace if(_content.size > 0) { _content.size--; refresh(); } return; } else if(c == '\t') { uint32_t x = 0; while(x < T_W) { put_char(' '); x++; } return; } if(c == '\n') { //new line. uint32_t x = _content.size - (_content.line*_content.line_w); while(x < _content.line_w) { uint32_t at = get_at(_content.size); _content.data[at] = ' '; _content.size++; x++; } _content.line++; } else { uint32_t x = _content.size - (_content.line*_content.line_w) + 1; if(x == _content.line_w) { _content.line++; } } if((_content.line) >= _content.line_num) { move_line(); } if(c != '\n') { uint32_t at = get_at(_content.size); _content.data[at] = c; int32_t x = (_content.size - (_content.line*_content.line_w)) * _font->w; int32_t y = _content.line * _font->h; draw_char(_graph, x, y, c, _font, _fg_color); _content.size++; } } static void console_clear() { _content.size = 0; _content.start_line = 0; _content.line = 0; clear(_graph, _bg_color); } int32_t console_write(uint32_t node, void* buf, uint32_t size, int32_t seek) { (void)seek; (void)node; const char* p = (const char*)buf; for(uint32_t i=0; i<size; i++) { char c = p[i]; put_char(c); } graph_flush(_graph); return size; } int32_t console_read(uint32_t node, void* buf, uint32_t size, int32_t seek) { (void)node; (void)size; (void)seek; if(_keyb_id < 0) return -1; return read(_keyb_id, buf, 1); } void* console_ctrl(uint32_t node, int32_t cmd, void* data, uint32_t size, int32_t* ret) { (void)node; (void)data; (void)size; (void)ret; if(cmd == 0) { //clear. console_clear(); } return NULL; } int main() { device_t dev = {0}; dev.mount = console_mount; dev.unmount = console_unmount; dev.write = console_write; dev.read = console_read; dev.ctrl = console_ctrl; dev_run(&dev, "dev.console", 0, "/dev/console0", true); return 0; }
smwikipedia/EwokOS
rootfs/lib/include/sconf.h
#ifndef SIMPLE_CONFIG_H #define SIMPLE_CONFIG_H #include <sconf_parse.h> sconf_t* sconf_load(const char* fname); #endif
smwikipedia/EwokOS
kernel/include/scheduler.h
#ifndef SCHEDULER_H #define SCHEDULER_H extern void schedule(); #endif
smwikipedia/EwokOS
rootfs/lib/include/unistd.h
<filename>rootfs/lib/include/unistd.h #ifndef UNISTD_H #define UNISTD_H #include <types.h> #include <cmain.h> int chdir(const char* dir); char* getcwd(char* buf, uint32_t size); int fork(); int getpid(); int exec(const char* cmd); void exit(int code); void wait(int pid); int getuid(); unsigned int sleep(unsigned int secs); unsigned int usleep(unsigned int msecs); /*i/o functions*/ #define O_RDONLY 0 int open(const char* fname, int mode); int write(int fd, const void* buf, uint32_t mode); int read(int fd, void* buf, uint32_t mode); void close(int fd); #endif
smwikipedia/EwokOS
kernel/include/kserv.h
<gh_stars>0 #ifndef KSERV_H #define KSERV_H #include <proc.h> #define KSERV_NAME_MAX 16 typedef struct { char name[KSERV_NAME_MAX+1]; int32_t pid; } kserv_t; int32_t kserv_reg(const char* name); int32_t kserv_unreg(process_t* proc); int32_t kserv_get(const char* name); #endif
smwikipedia/EwokOS
lib/src/device.c
<filename>lib/src/device.c<gh_stars>0 #include <device.h> int32_t dev_buffer_push(dev_buffer_t *buffer, char c, bool loop) { if(buffer->buffer == NULL || buffer->buffer_size == 0) return -1; uint32_t at; if(buffer->size == buffer->buffer_size) { if(!loop) return -1; buffer->start++; if(buffer->start == buffer->buffer_size) buffer->start = 0; at = (buffer->start + buffer->size)-1; } else at = (buffer->start + buffer->size); if(at >= buffer->buffer_size) { at -= buffer->buffer_size; } ((char*)buffer->buffer)[at] = c; if(buffer->size < buffer->buffer_size) buffer->size++; return 0; } int32_t dev_buffer_pop(dev_buffer_t *buffer, char* c) { if(buffer->size == 0) return -1; *c = ((char*)buffer->buffer)[buffer->start]; buffer->start++; if(buffer->start == buffer->buffer_size) buffer->start = 0; buffer->size--; return 0; }
smwikipedia/EwokOS
rootfs/dev/procd/procd.c
<reponame>smwikipedia/EwokOS<filename>rootfs/dev/procd/procd.c<gh_stars>0 #include <dev/devserv.h> #include <unistd.h> #include <stdio.h> #include <kstring.h> #include <syscall.h> #include <vfs/vfs.h> #include <vfs/fs.h> static int32_t proc_mount(uint32_t node, int32_t index) { (void)index; vfs_add(node, "free_mem", 0, NULL); vfs_add(node, "total_mem", 0, NULL); vfs_add(node, "cpu_sec", 0, NULL); vfs_add(node, "cpu_msec", 0, NULL); return 0; } static int32_t proc_read(uint32_t node, void* buf, uint32_t size, int32_t seek) { int32_t ret = -1; if(size == 0) return 0; fs_info_t info; if(fs_ninfo(node, &info) != 0) return ret; const char* fname = info.name; if(strcmp(fname, "total_mem") == 0) { snprintf((char*)buf, size-1, "%d\n", syscall2(SYSCALL_SYSTEM_CMD, 0, 0)); ret = strlen((char*)buf); } else if(strcmp(fname, "free_mem") == 0) { snprintf((char*)buf, size-1, "%d\n", syscall2(SYSCALL_SYSTEM_CMD, 1, 0)); ret = strlen((char*)buf); } else if(strcmp(fname, "cpu_sec") == 0) { uint32_t sec; syscall3(SYSCALL_SYSTEM_CMD, 4, (int32_t)&sec, 0); snprintf((char*)buf, size-1, "%d\n", (int)sec); ret = strlen((char*)buf); } else if(strcmp(fname, "cpu_msec") == 0) { uint32_t msec; syscall3(SYSCALL_SYSTEM_CMD, 4, 0, (int32_t)&msec); snprintf((char*)buf, size-1, "%d\n", (int)msec); ret = strlen((char*)buf); } if(seek >= ret) ret = 0; return ret; } int main() { device_t dev = {0}; dev.mount = proc_mount; dev.read = proc_read; dev_run(&dev, "dev.proc", 0, "/proc", false); return 0; }
smwikipedia/EwokOS
rootfs/lib/include/cmain.h
#ifndef CMAIN_H #define CMAIN_H #include <types.h> void init_cmain_arg(); const char* read_cmain_arg(); extern int main(); #endif
smwikipedia/EwokOS
rootfs/lib/include/dev/mmio.h
#ifndef MMIO_H #define MMIO_H #include <types.h> int32_t mmio_get(uint32_t offset); int32_t mmio_put(uint32_t offset, int32_t val); #endif
smwikipedia/EwokOS
rootfs/bin/clear/clear.c
#include <unistd.h> #include <stdio.h> #include <vfs/fs.h> #include <stdlib.h> #include <kstring.h> int main() { int32_t fd = _stdout; if(fd < 0) return -1; int32_t cmd = 0; //clear console fs_ctrl(fd, cmd, NULL, 0, NULL, 0); return 0; }
smwikipedia/EwokOS
kernel/src/timer.c
#include <timer.h> #include <scheduler.h> #include <hardware.h> #include <irq.h> #define SCHEDULE_TIME 1000 /*0.001 sec*/ //static uint32_t _cpu_tick = 0; static uint32_t _cpu_msec = 0; static uint32_t _cpu_sec = 0; void timer_handle() { /* _cpu_tick++; if(_cpu_tick >= 10) { _cpu_msec++; } */ _cpu_msec++; if(_cpu_msec >= 1000) { _cpu_sec++; _cpu_msec = 0; } timer_clear_interrupt(); schedule(); } void timer_start(void) { timer_set_interval(SCHEDULE_TIME); } void cpu_tick(uint32_t* sec, uint32_t* msec) { if(sec != NULL) *sec = _cpu_sec; if(msec != NULL) *msec = _cpu_msec; }
smwikipedia/EwokOS
rootfs/dev/fbd/fbd.c
<filename>rootfs/dev/fbd/fbd.c #include <dev/devserv.h> #include <unistd.h> #include <syscall.h> #include <fbinfo.h> #include <shm.h> #include <device.h> static fb_info_t _fb_info; static int32_t _fb_buf_id = -1; static int32_t _fb_bufSize = 0; static void* _fb_buf = NULL; static int32_t fb_mount(uint32_t node, int32_t index) { (void)node; (void)index; if(syscall2(SYSCALL_DEV_INFO, dev_typeid(DEV_FRAME_BUFFER, 0), (int32_t)&_fb_info) != 0) return -1; _fb_bufSize = 4 *_fb_info.width * _fb_info.height; if(_fb_bufSize == 0) return -1; _fb_buf_id = shm_alloc(_fb_bufSize); if(_fb_buf_id < 0) return -1; _fb_buf = shm_map(_fb_buf_id); return 0; } int32_t fb_write(uint32_t node, void* buf, uint32_t size, int32_t seek) { (void)node; (void)seek; return syscall3(SYSCALL_DEV_CHAR_WRITE, dev_typeid(DEV_FRAME_BUFFER, 0), (int32_t)buf, (int32_t)size); } int32_t fb_flush(uint32_t node) { (void)node; return syscall3(SYSCALL_DEV_CHAR_WRITE, dev_typeid(DEV_FRAME_BUFFER, 0), (int32_t)_fb_buf, (int32_t)_fb_bufSize); } int32_t fb_dma(uint32_t node, uint32_t *size) { (void)node; *size = _fb_bufSize; return _fb_buf_id; } void* fb_ctrl(uint32_t node, int32_t cmd, void* data, uint32_t size, int32_t* ret) { (void)node; (void)data; (void)size; void* p = NULL; if(cmd == 0) {//getfbinfo p = &_fb_info; *ret = sizeof(fb_info_t); } return p; } int main() { device_t dev = {0}; dev.write = fb_write; dev.mount = fb_mount; dev.dma = fb_dma; dev.ctrl = fb_ctrl; dev.flush = fb_flush; dev_run(&dev, "dev.fb", 0, "/dev/fb0", true); shm_unmap(_fb_buf_id); return 0; }
d3zd3z/mcuboot
boot/zephyr/include/sysflash/sysflash.h
/* Manual version of auto-generated version. */ #ifndef __SYSFLASH_H__ #define __SYSFLASH_H__ #include <generated_dts_board.h> #include <mcuboot_config/mcuboot_config.h> extern uint8_t current_image; #if (MCUBOOT_IMAGE_NUMBER == 1) #define FLASH_AREA_IMAGE_PRIMARY DT_FLASH_AREA_IMAGE_0_ID #define FLASH_AREA_IMAGE_SECONDARY DT_FLASH_AREA_IMAGE_1_ID #elif (MCUBOOT_IMAGE_NUMBER == 2) /* MCUBoot currently supports only up to 2 updateable firmware images. * If the number of the current image is greater than MCUBOOT_IMAGE_NUMBER - 1 * then a dummy value will be assigned to the flash area macros. */ #define FLASH_AREA_IMAGE_PRIMARY ((current_image == 0) ? \ DT_FLASH_AREA_IMAGE_0_ID : \ (current_image == 1) ? \ DT_FLASH_AREA_IMAGE_2_ID : \ 255 ) #define FLASH_AREA_IMAGE_SECONDARY ((current_image == 0) ? \ DT_FLASH_AREA_IMAGE_1_ID : \ (current_image == 1) ? \ DT_FLASH_AREA_IMAGE_3_ID : \ 255 ) #else #error "Image slot and flash area mapping is not defined" #endif #define FLASH_AREA_IMAGE_SCRATCH DT_FLASH_AREA_IMAGE_SCRATCH_ID #endif /* __SYSFLASH_H__ */
harry624/reliable-data-transport-protocols
cse489589_assignment2/hwang67/src/abt.c
#include <stdio.h> #include <string.h> #include <stdlib.h> // #include "../include/queue.h" #include "../include/simulator.h" /* ****************************************************************** ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR: VERSION 1.1 J.F.Kurose This code should be used for PA2, unidirectional data transfer protocols (from A to B). Network properties: - one way network delay averages five time units (longer if there are other messages in the channel for GBN), but can be larger - packets can be corrupted (either the header or the data portion) or lost, according to user-defined probabilities - packets will be delivered in the order in which they were sent (although some can be lost). **********************************************************************/ /********* STUDENTS WRITE THE NEXT SIX ROUTINES *********/ /*0 (for A-side delivery) or 1 (for B-side delivery) */ #define TIMEOUT 20.0 struct pkt sendBuf[1000]; //buffer for application layer sending msg int pktsBufcnt; int nextPktInd; struct pkt tmpPkt; int seqnum; int acknum; int lastchecksum; int calculate_checksum(packet) struct pkt packet; { int checksum = 0; checksum += packet.seqnum; checksum += packet.acknum; int sizeOfArray = strlen(packet.payload); for(int i = 0; i < 20; i++){ checksum += packet.payload[i]; } //Perform bitwise inversion // checksum = ~checksum; // //Increment // checksum++; return checksum; } int vaildiate_checksum(packet) struct pkt packet; { int expectedChecksum = calculate_checksum(packet); // printf("expectedChecksum:%d, packetchecksum: %d\n", expectedChecksum, packet.checksum); return (expectedChecksum == packet.checksum); } //MAIN /* called from layer 5, passed the data to be sent to other side */ void A_output(message) struct msg message; { // printf("run A_output\n"); struct pkt sendingpkt; strncpy(sendingpkt.payload, message.data, 20); sendingpkt.seqnum = seqnum; sendingpkt.checksum = calculate_checksum(sendingpkt); seqnum = sendingpkt.seqnum == 0 ? 1: 0; //send the packet pktsBufcnt++; sendBuf[pktsBufcnt] = sendingpkt; // printf("A is sending : %20s, seq: %d, nextindex: %d\n", // sendBuf[pktsBufcnt].payload, sendBuf[pktsBufcnt].seqnum, nextPktInd); if(nextPktInd == pktsBufcnt){ tolayer3(0, sendBuf[nextPktInd]); // printf("A sent : %20s, seq: %d\n", // sendBuf[nextPktInd].payload, sendBuf[nextPktInd].seqnum); starttimer(0, TIMEOUT); } //printf("\n"); } /* called from layer 3, when a packet arrives for layer 4 */ void A_input(packet) struct pkt packet; { // printf("run A_input\n"); // printf("A receving ack: %d, nextseqnum: %d, bufcnt: %d\n", packet.acknum, nextPktInd, pktsBufcnt); if (packet.acknum == sendBuf[nextPktInd].seqnum){ nextPktInd++; stoptimer(0); if (nextPktInd <= pktsBufcnt){ tolayer3(0, sendBuf[nextPktInd]); starttimer(0, TIMEOUT); } } //printf("\n"); } /* called when A's timer goes off */ void A_timerinterrupt() { // printf("run A_timerinterrupt\n"); // printf("A resending : %20s, seq: %d, nextindex: %d\n", // sendBuf[nextPktInd].payload, sendBuf[nextPktInd].seqnum, nextPktInd); tolayer3(0, sendBuf[nextPktInd]); starttimer(0, TIMEOUT); //printf("\n"); } /* the following routine will be called once (only) before any other */ /* entity A routines are called. You can use it to do any initialization */ void A_init() { // printf("run A_init\n"); // memest(&tmp,0 ,sizeof(struct pkt)); seqnum = 0; pktsBufcnt = -1; nextPktInd = 0 ; } /* Note that with simplex transfer from a-to-B, there is no B_output() */ /* called from layer 3, when a packet arrives for layer 4 at B*/ void B_input(packet) struct pkt packet; { struct pkt ackPkt; // printf("run B_input\n"); // printf("B receving: %20s, seqnum: %d, current acknum: %d\n", packet.payload, packet.seqnum, acknum); //compare checksum int isCheckSumVaild = vaildiate_checksum(packet); if (isCheckSumVaild){ //receving packet //check if deplicate pkt if (packet.seqnum == acknum){ tolayer5(1, packet.payload); //send ack packet ackPkt.acknum = packet.seqnum; // printf("B sending ack: %d\n", ackPkt.acknum); tolayer3(1, ackPkt); acknum = acknum == 0 ? 1 : 0; }else{ //duplicate packet ackPkt.acknum = packet.seqnum; // printf("B sending ack: %d\n", ackPkt.acknum); tolayer3(1, ackPkt); // acknum = acknum == 0 ? 1 : 0; } } //printf("\n"); } /* the following routine will be called once (only) before any other */ /* entity B routines are called-> You can use it to do any initialization */ void B_init() { // printf("run B_init\n"); acknum = 0; }
harry624/reliable-data-transport-protocols
cse489589_assignment2/hwang67/src/sr.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "../include/simulator.h" /* ****************************************************************** ALTERNATING8BIT AND GO-BACK-N NETWORK EMULATOR: VERSION 1.1 J.F.Kurose This code should be used for PA2, unidirectional data transfer protocols (from A to B). Network properties: - one way network delay averages five time units (longer if there are other messages in the channel for GBN), but can be larger - packets can be corrupted (either the header or the data portion) or lost, according to user-defined probabilities - packets will be delivered in the order in which they were sent (although some can be lost). **********************************************************************/ #define TIMEOUT 20.0 //the base of the window int base; //the size of the window int N; int nextseqnum; int nextacknum; //the sending packet array on the A(sender) side struct pkt sndPkt[1000]; //the receving buffer array on the B(receiver) side struct pkt recvBufPkt[1000]; //array to save the timeout times based on the sim_time() float timeoutArray[1000]; /********* STUDENTS WRITE THE NEXT SEVEN ROUTINES *********/ int calculate_checksum(packet) struct pkt packet; { int checksum = 0; checksum += packet.seqnum; checksum += packet.acknum; int sizeOfArray = strlen(packet.payload); for(int i = 0; i < 20; i++){ checksum += packet.payload[i]; } return checksum; } int vaildiate_checksum(packet) struct pkt packet; { int expectedChecksum = calculate_checksum(packet); return (expectedChecksum == packet.checksum); } /* called from layer 5, passed the data to be sent to other side */ void A_output(message) struct msg message; { // printf("run A_output\n"); struct pkt sendingpkt; strncpy(sendingpkt.payload, message.data, 20); sendingpkt.seqnum = nextseqnum; sendingpkt.checksum = calculate_checksum(sendingpkt); sndPkt[nextseqnum] = sendingpkt; timeoutArray[nextseqnum] = get_sim_time() + 20.0; // printf("timeout sim time for pkt:%d is :%f\n", // nextseqnum, timeoutArray[nextseqnum]); // // printf("A sending: %s, seq: %d, base: %d\n", // sndPkt[nextseqnum].payload, sndPkt[nextseqnum].seqnum, base); if(nextseqnum < base + N){ tolayer3(0, sndPkt[nextseqnum]); if (nextseqnum == base){ starttimer(0, TIMEOUT); // printf("start timer for seq: %d\n", nextseqnum); // printf("cur time:%d\n", get_sim_time()); } } nextseqnum += 1; //printf("\n"); } /* called from layer 3, when a packet arrives for layer 4 */ void A_input(packet) struct pkt packet; { // printf("run A_input\n"); // printf("sim time:%f\n", get_sim_time()); // // printf("A receving ack: %d, nextseqnum is: %d, base: %d\n", // packet.acknum, nextseqnum, base); if (packet.acknum > nextseqnum){ return; } timeoutArray[packet.acknum] = 0.0; if (base == packet.acknum){ stoptimer(0); // printf("stop timer for seq: %d\n", base); base ++; for (int i = base; i < nextseqnum; i++){ if (timeoutArray[i] > 0){ starttimer(0, timeoutArray[i] - get_sim_time()); break; }else if(timeoutArray[i] == 0.0){ base = i + 1; } } } //printf("\n"); } /* called when A's timer goes off */ void A_timerinterrupt() { // printf("run A_timerinterrupt\n"); // printf("sim time:%f\n", get_sim_time()); starttimer(0, TIMEOUT); // printf("start timer for seq: %d\n", base); tolayer3(0, sndPkt[base]); // printf("A resending: %s, seq: %d\n", // sndPkt[base].payload, sndPkt[base].seqnum); //printf("\n"); } /* the following routine will be called once (only) before any other */ /* entity A routines are called. You can use it to do any initialization */ void A_init() { // printf("run A_init\n"); base = 0; N = getwinsize(); nextseqnum = 0; // printf("sim time:%f\n", get_sim_time()); for (int i = 0; i < 1000; i++){ timeoutArray[i] = -1.0; } } /* Note that with simplex transfer from a-to-B, there is no B_output() */ /* called from layer 3, when a packet arrives for layer 4 at B*/ void B_input(packet) struct pkt packet; { struct pkt ackPkt; // printf("run B_input\n"); // printf("B receving: %s, seqnum: %d, current acknum: %d\n", // packet.payload, packet.seqnum, nextacknum); //compare checksum int isCheckSumVaild = vaildiate_checksum(packet); if (isCheckSumVaild){ //receving packet //check if deplicate pkt /*if the packet seq is equal to nextacknum, check if there is buffer, if have, send the buffer to upper layer, and send back the acknum to A, if have no buffer, just send the packet to layer5 */ if (packet.seqnum == nextacknum){ tolayer5(1, packet.payload); // printf("sending :%d to layer5: %s\n", packet.seqnum, packet.payload); //check if there is buffer for (int i = packet.seqnum + 1; i < packet.seqnum + N && i < 1000; i++){ if (recvBufPkt[i].acknum < 0){ break; } if (recvBufPkt[i].acknum >= 0){ // printf("sending :%d to layer5: %s\n",i, recvBufPkt[i].payload); tolayer5(1, recvBufPkt[i].payload); nextacknum += 1; } } //send ack packet ackPkt.acknum = packet.seqnum; // printf("B sending ack: %d\n", ackPkt.acknum); tolayer3(1, ackPkt); nextacknum += 1; }else if (packet.seqnum > nextacknum){ // printf("B add buffer seq: %d\n", packet.seqnum); recvBufPkt[packet.seqnum] = packet; ackPkt.acknum = packet.seqnum; // printf("B sending ack: %d\n", ackPkt.acknum); tolayer3(1, ackPkt); }else{ //duplicate packet ackPkt.acknum = packet.seqnum; // printf("B sending ack: %d\n", ackPkt.acknum); tolayer3(1, ackPkt); } } //printf("\n"); } /* the following rouytine will be called once (only) before any other */ /* entity B routines are called. You can use it to do any initialization */ void B_init() { // printf("run B_init\n"); for (int i = 0; i < 1000; i++){ recvBufPkt[i].acknum = -1; } }
wesleyrodriguessantos/Teste-Delvo
lista1.c
#include <stdio.h> #define MAX 100 #define SUCESSO 1 #define FALHA -1 #define CHAVE_INVALIDA -1 #include <stdlib.h> typedef struct { unsigned int chave; unsigned int dado; } Celula; typedef struct { Celula celulas[MAX]; unsigned int tam; } ListaLinear; int criarListaVazia(ListaLinear *lls) { lls->tam = 0; printf("**Lista criada\n"); return (SUCESSO); } int criarListaVaziaL(ListaLinear *lls) { int i; for (i = 0; (i < MAX); i++) { lls->celulas[i].chave = CHAVE_INVALIDA; } lls->tam = 0; printf("-----Lista criada\n"); return (SUCESSO); } int criarListaChave(ListaLinear *lls, Celula celula) { int i; for (i = 0; i < MAX; i++) { lls->celulas[i].chave = CHAVE_INVALIDA; } lls->celulas[0] = celula; lls->tam = 1; return SUCESSO; } void mostrarCelula(Celula celula) { printf("%u", celula.chave); printf(" %u\n", celula.dado); } void mostrarLista(ListaLinear *lls) { int i; if (lls->tam == 0) { printf("\nLista vazia \n"); } else { //printf("A linear possui %u elementos \n", lls->tam); for (i = 0; i < lls->tam; i++) { //printf("Elemento n.: %u\n", (i + 1)); mostrarCelula(lls->celulas[i]); } } printf("\nfim da lista\n"); } int inserirInicio(ListaLinear *lls, Celula celula) { int i; if (lls->tam == MAX) return FALHA; else { for (i = lls->tam; i > 0; i--) { lls->celulas[i] = lls->celulas[i - 1]; } lls->celulas[0] = celula; lls->tam++; return SUCESSO; } } int inserirFinal(ListaLinear *lls, Celula celula) { int i; Celula aux; if (lls->tam == MAX) return FALHA; // a lista esta cheia (overflow) else { lls->celulas[lls->tam] = celula; // insere no final da lista lls->tam++; return SUCESSO; } } //retorna a celula que esta na posicao desejada // ou chave invalida se a posicao nao existe Celula consultaListaPosicao(ListaLinear *lls, int posicao) { Celula cResultado; if ((posicao > 0) && posicao <= lls->tam) cResultado = lls->celulas[posicao - 1]; else cResultado.chave = CHAVE_INVALIDA; return cResultado; } int tamanhoLista(ListaLinear *lls) { if (lls->tam >= 0) return lls->tam; else return FALHA; } // retorna a celula com a chave desejada //ou chave invalida se a chave nao existe na lista Celula consultaListaChave(ListaLinear *lls, Celula celula) { int i; for (i = 0; i < lls->tam; i++) if (lls->celulas[i].chave == celula.chave) return lls->celulas[i]; celula.chave = CHAVE_INVALIDA; return celula; } int main() { ListaLinear *lls; int resultado; lls = (ListaLinear *)malloc(sizeof(ListaLinear)); resultado = criarListaVaziaL(lls); Celula cls; int i; for (i = 0; i < 5; i++) { cls.chave = i; scanf("%d", &cls.dado); //mostrarCelula(cls); inserirInicio(lls, cls); } printf("Chave Dado\n"); mostrarLista(lls); Celula p; printf("\nposicao = %d %d", consultaListaPosicao(lls, 4), lls->celulas[4]); printf("\nchave = %d %d", consultaListaChave(lls, cls), lls->celulas[4].chave); printf("\ntamanho da lista = %d", tamanhoLista(lls)); printf("\n inserindo no final da lista\n"); for (i = 0; i < 5; i++) { cls.chave = i; scanf("%d", &cls.dado); //mostrarCelula(cls); inserirFinal(lls, cls); } printf("Chave Dado\n"); mostrarLista(lls); return 0; }
wesleyrodriguessantos/Teste-Delvo
listaLigada1.c
<reponame>wesleyrodriguessantos/Teste-Delvo #include <stdio.h> #include <stdlib.h> #include <malloc.h> #define false 0 #define true 1 /** * criei este tipo para se parecer com um boolean * utilizado na função com retorno int * e utilizar as define false e true * */ typedef int boolean; //typedef int TIPOCHAVE; /** * struct para armazenar os dados de um paciente * chave é o dado principal do paciente (identificador do paciente) * será usado para procuarar um paciente * aqui pode ser criado outros dados * pode inserir uma nova struct, ENDERECO por exemplo * */ typedef struct { int chave; int dado; // dado e uma informacao qualquer do paciente, aqui utilizei para ordenar a lista de pacientes // foi utilizado para localizar onde inserir um novo paciente ordenado // a ordenacao pode ocorrer por outro valor: chave, nome char nome[40]; } PACIENTE; /* essa struct aux contem um registro de um paciente e um ponteiro *prox que servirá para percorrer uma lista de pacientes */ typedef struct aux { PACIENTE p; struct aux *prox; } REGISTRO; /* PONT é um ponteiro para o inicio da lista */ typedef REGISTRO *PONT; typedef struct { PONT inicio; } LISTAPACIENTES; /* Inicializa a lista atribuindo NULL para o inicio da lista, ou seja, uma lista sem elementos */ void inicializarLista(LISTAPACIENTES *lst) { printf("Lista Criada!\n"); lst->inicio = NULL; } /* para mostrar o tamanho da lista */ int tamanho(LISTAPACIENTES *lst) { PONT end = lst->inicio; int tam = 0; while (end != NULL) { tam++; end = end->prox; } } /* Para exibir a lista de pacientes: aqui por enquanto a chave, o dado e o nome do paciente */ void exibirListaPacientes(LISTAPACIENTES *lst) { PONT end = lst->inicio; while (end != NULL) { printf("%i %d %s\n", end->p.chave, end->p.dado, end->p.nome); end = end->prox; } } PONT buscaSequencial(LISTAPACIENTES *lst, int ch) { PONT pos = lst->inicio; while (pos != NULL) { if (pos->p.chave == ch) return pos; } return NULL; } PONT buscaSeqencialOrdenada(LISTAPACIENTES *lst, int ch) { PONT pos = lst->inicio; while (pos != NULL && pos->p.chave == ch) return pos; return NULL; } /* localiza na lista de pacientes - aqui foi utilizado p.dado da struct paciente - qual posicao sera inserido o novo paciente * se o dado ja existir return NULL e nao insere o novo paciente com a chave repetida * precisa implementar um retorno informando que aquela chave (ou paciente) ja esta cadastrado */ PONT buscaSequencialExc(LISTAPACIENTES *lst, int d, PONT *ant) { *ant = NULL; PONT atual = lst->inicio; while ((atual != NULL) && (atual->p.dado < d)) { *ant = atual; atual = atual->prox; } if ((atual != NULL) && (atual->p.dado == d)) return atual; return NULL; } /* funcao que vai inserir um paciente na LISTAPACIENTES, recebe como parâmetros uma lista * e um registro completo de um paciente, ou seja todos os dados dentro da struct PACIENTE */ boolean inserirPacienteListaOrdenada(LISTAPACIENTES *lst, PACIENTE paciente) { int ch = paciente.chave; int d = paciente.dado; PONT ant, i; i = buscaSequencialExc(lst, d, &ant); if (i != NULL) return false; i = (PONT)malloc(sizeof(REGISTRO)); i->p = paciente; if (ant == NULL) { i->prox = lst->inicio; lst->inicio = i; } else { i->prox = ant->prox; ant->prox = i; } return true; } /*apaga toda a lista */ void reinicializarLista(LISTAPACIENTES *lst) { PONT fim = lst->inicio; while (fim != NULL) { PONT apagar = fim; fim = fim->prox; free(apagar); } lst->inicio = NULL; printf("\nLISTA VAZIA\n"); } /* exclui um paciente da lista e libera memoria * primeiro procura na lista se o paciente existe */ boolean excluirPacienteLista(LISTAPACIENTES *lst, int ch) { PONT ant, i; i = buscaSequencialExc(lst, ch, &ant); if (i == NULL) return false; if (ant == NULL) lst->inicio = i->prox; else ant->prox = i->prox; free(i); } int main() { LISTAPACIENTES *lst; inicializarLista(lst); PACIENTE p; int i; for (i = 1; i <= 5; i++) { p.chave = i; scanf("%d", &p.dado); scanf("%s", &p.nome); inserirPacienteListaOrdenada(lst, p); } printf("\nchave dado paciente\n"); exibirListaPacientes(lst); reinicializarLista(lst); exibirListaPacientes(lst); return 0; }
aniketsaha19/Hacktoberfest-KIIT
X-MAS_TREE_PATTERN.c
#include<stdio.h> void main() { int i,j,k; int height=3,width=4; int space=width*5; int r=1; int m=1; for(r=1;r<=height;r++) { for(i=m;i<=width;i++) { for(j=space;j>=i;j--) { printf(" "); } for(k=1;k<=i;k++) { printf("* ");//space after'*' } printf("\n"); } m+=2;width+=2; } for(i=1;i<=4;i++) { for(j=space-3;j>=1;j--) { printf(" "); } for(k=1;k<=4;k++) { printf("* ");//space after'*' } printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
diamond_pat.c
#include<stdio.h> void main() { int i,j; int n=9; int c1=(n-1)/2; int c2=3*n/2-1; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i+j<=c1||i-j>=c1||j-i>=c1||i+j>=c2) printf("*"); else printf(" "); } printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
Biswaroop Bhattacharjee/swap.c
#include<stdio.h> #include<stdlib.h> int main() { int r,c; printf("enter no.of rows and column "); scanf("%d %d",&r,&c); int* arr[r]; for(int i=0;i<r;i++) { arr[i]=(int*)malloc(c*sizeof(int)); } for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { scanf("%d",&arr[i][j]); } } for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { printf("%d ",arr[i][j]); } printf("\n"); } int temp; for(int i=0;i<r;i++) { for(int j=0;j<c/2;j++) { temp=arr[i][j]; arr[i][j]=arr[i][c-1-j]; arr[i][c-1-j]=temp; } } printf("The swapped matrix : \n"); for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { printf("%d ",arr[i][j]); } printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
wave_pat.c
<filename>wave_pat.c #include<stdio.h> void main() { int is=1; int os=2; int WL=5; int WH=5; int inc=1; int i,j,k; int jump=(WH*3)-(WH+1); int ch='Z'-WH+1; for(i=1;i<=WH;i++) { for(j=1;j<WL;j++) { for(k=1;k<=os;k++) { printf(" "); } printf("%c",ch); for(k=1;k<=is;k++) { printf(" "); } ch-=inc; if(ch<'A') ch=ch+26; printf("%c",ch); for(k=1;k<=os;k++) { printf(" "); } printf(" "); ch-=jump; if(ch<'A') ch=ch+26; } os=(i+1!=WH); is=(i+1!=WH)?3:5; ch='Z'-WH+i+1; inc=inc+2; jump-=2; printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
s_pattern.c
#include<stdio.h> void main() { int i,j; for(i=1;i<=15;i++) { for(j=1;j<=10;j++){ if(((i>=4 && i<=6) && (j>=4))||((i>=10 && i<=12)&&(j<=7))) { printf(" "); } else { printf("*"); } } printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
circle_pattern.c
<gh_stars>1-10 #include<stdio.h> void main() { int i,j,k,z,x; for(i=1;i<=9;i++) { switch(i) { case 1: case 9:x=6;z=4; break; case 2: case 8:x=8;z=2; break; case 3: case 7:x=9;z=1; break; default:x=10;z=0; } for(j=1;j<=z;j++){ printf(" "); } for(k=1;k<=x;k++) { printf("* "); } printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
Biswaroop Bhattacharjee/student.c
<reponame>aniketsaha19/Hacktoberfest-KIIT<filename>Biswaroop Bhattacharjee/student.c<gh_stars>1-10 #include <stdio.h> struct student { int r; char name[30]; float m1,m2,m3,m4,m5; }; int main() { struct student marks[5]; for(int i=1; i<=5; i++) { printf("Student %d\n",i+1); printf("Enter roll no. :\n"); scanf("%d", &marks[i].r); printf("Enter name :\n"); scanf("%s",marks[i].name); printf("Enter marks1 :\n"); scanf("%f", &marks[i].m1); printf("Enter marks2 :\n"); scanf("%f", &marks[i].m2); printf("Enter marks3 :\n"); scanf("%f", &marks[i].m3); printf("Enter marks4 :\n"); scanf("%f", &marks[i].m4); printf("Enter marks5 :\n"); scanf("%f", &marks[i].m5); } for(int i=1; i<=5; i++) { printf("Student %d\n",i+1); float percentage = (marks[i].m1 + marks[i].m2 + marks[i].m3+ marks[i].m4 + marks[i].m5)/500.0*100; printf("Percentage : %f\n", percentage); } return 0; }
aniketsaha19/Hacktoberfest-KIIT
Junaid Rahim/array_sum.c
<reponame>aniketsaha19/Hacktoberfest-KIIT // Sum of an array using recursion #include <stdio.h> int sum(int size, int arr[size]){ int arr_sum = 0; if(size == 1) return arr[0]; else { arr_sum = arr[size-1] + sum(--size, arr); return arr_sum; } } int main(){ int n; printf("Enter Size of Array: "); scanf("%d", &n); int arr[n]; printf("Enter elements of the array: "); for(int i=0; i<n; i++){ scanf("%d", &arr[i]); } printf("The sum of the array is %d\n", sum(n, arr)); return 0; }
aniketsaha19/Hacktoberfest-KIIT
heart_pattern.c
#include<stdio.h> void main() { int i,j; int n=5; for(i=n/2;i<=n;i+=2) { for(j=1;j<n-i;j+=2) { printf(" "); } for(j=1;j<=i;j++) { printf("*"); } for(j=1;j<=n-i;j++) { printf(" "); } for(j=1;j<=i;j++) { printf("*"); } printf("\n"); } for(i=n;i>=1;i--) { for(j=i;j<n;j++) { printf(" "); } for(j=1;j<=(i*2)-1;j++) { printf("*"); } printf("\n"); } }
aniketsaha19/Hacktoberfest-KIIT
disarium_num.c
#include<stdio.h> #include<math.h> int isDisarium(int); int digit_count(int); int main() { int i,limit; int sum=0,digit_count=0,pd; printf("Enter a number (upper limit)\n"); scanf("%d",&limit); printf("Disarium Number between 1 to %d\n",limit); for(i=1;i<=limit;i++) { if(isDisarium(i)==1) { printf("%d\n",i); } } return 0; } int isDisarium(int n) { int dc=digit_count(n); int pd; int sum=0; int t=n; while(t!=0) { pd=t%10; sum=sum+pow(pd,dc--); t=t/10; } if(sum==n) return 1; else return 0; } int digit_count(int n) { int count=0; while(n!=0) { n=n/10; count++; } return count; }
aniketsaha19/Hacktoberfest-KIIT
Junaid Rahim/prime_factors.c
<reponame>aniketsaha19/Hacktoberfest-KIIT // Prime Factors of a given number #include <stdio.h> int isPrime(int n){ for(int i=2; i<n; i++){ if(n % i == 0) return 0; } return 1; } void print_prime_factors(int *n){ for(int i=2; i<*n; i++){ if ((*n % i == 0) && (isPrime(i))) printf("%d ", i); } } int main(){ int number; printf("Enter number: "); scanf("%d", &number); print_prime_factors(&number); return 0; }
albin-johansson/SDL
test/testtheme.c
<filename>test/testtheme.c /* Copyright (C) 1997-2022 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely. */ /* Very simple test of theme detection. */ #include "SDL.h" static void report_theme(void) { const SDL_SystemTheme theme = SDL_GetSystemTheme(); SDL_Log("SDL-reported theme info...\n"); switch (theme) { case SDL_SYSTEM_THEME_LIGHT: SDL_Log("Appearance: Light"); break; case SDL_SYSTEM_THEME_DARK: SDL_Log("Appearance: Dark"); break; case SDL_SYSTEM_THEME_UNKNOWN: SDL_Log("Appearance: Unknown"); break; default: SDL_Log("Appearance: Unexpected value!"); break; } } int main(int argc, char *argv[]) { /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); if (SDL_Init(0) == -1) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError()); return 1; } report_theme(); SDL_Quit(); return 0; } /* end of testtheme.c ... */
albin-johansson/SDL
src/misc/windows/SDL_systheme.c
<reponame>albin-johansson/SDL<filename>src/misc/windows/SDL_systheme.c /* Simple DirectMedia Layer Copyright (C) 1997-2022 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #include "../../core/windows/SDL_windows.h" #include "SDL_video.h" SDL_SystemTheme SDL_GetSystemTheme(void) { SDL_SystemTheme retval = SDL_SYSTEM_THEME_UNKNOWN; LPCWSTR path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; HKEY hkey; if (RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) { DWORD data = 0; DWORD dataSize = sizeof(DWORD); DWORD type = REG_DWORD; LSTATUS res; res = RegQueryValueEx(hkey, L"SystemUsesLightTheme", NULL, &type, (LPBYTE) &data, &dataSize); if (res == ERROR_SUCCESS) { if (data == 0) { retval = SDL_SYSTEM_THEME_DARK; } else if (data == 1) { /* Use explicit check with 1 to avoid false positives */ retval = SDL_SYSTEM_THEME_LIGHT; } } RegCloseKey(hkey); } return retval; } /* vi: set ts=4 sw=4 expandtab: */
kurtjd/simon
brainpain.c
#ifdef WIN32 #include <windows.h> #include <curses.h> #define XSLEEP(time) Sleep(time) #else #include <ncurses.h> #define XSLEEP(time) nanosleep((struct timespec[]){{0, (time * 1000000L)}}, NULL) #endif #include <stdlib.h> #include <string.h> #include <time.h> #define QUAD_WIDTH 15 #define QUAD_HEIGHT 7 #define MEMCHAIN_LEN 1024 #define NUM_COLORS 4 // Initializes ncurses with some good settings. void init_ncurses(void); // A quadrant is just a colored section of the simon 'square'. void draw_quadrant(const int startx, const int starty, const int colorpair); // Draws 4 quadrants to make a board. void draw_game_board(const int startx, const int starty, const int highlight); // Draws the gameboard along with some other text. void draw_screen(const int boardx, const int boardy, const int highlight, const int score, const char message[]); /* Plays back the memory chain, highlighting each color quadrant. This is done by drawing each link as a game board. */ void simon_says(const int memchain[], const int startx, const int starty, const int score); // Adds a new random link in the memory chain. void add_mem_link(int memchain[], const int score); // Returns a random number between 1 and 4 which represents a color. int get_random_color(void); // Resets the game, basically by setting score and memchain to 0. void reset_game(const int boardx, const int boardy, int * const score, int memchain[]); // Does a little cleanup before exiting. void exit_game(void); int main() { /* Holds each successive color the user must select to keep the chain going. Only holds a value of 0, 1, 2, 3 or 4 with 0 representing no value and 1-4 representing a color. */ int memchain[MEMCHAIN_LEN] = {0}; // Player's score is increased each time the memory chained is played back successfully. int score = 0; int rows, cols; int reset; // 1 or 0, determines if game is about to be reset. // Initialize some stuff. srand(time(0)); init_ncurses(); getmaxyx(stdscr, rows, cols); // Used to center the gameboard on the screen. int boardx = (cols / 2) - QUAD_WIDTH; int boardy = (rows / 2) - QUAD_HEIGHT - 2; draw_screen(boardx, boardy, 0, score, "Press any key to start."); getch(); draw_screen(boardx, boardy, 0, score, "Prepare yourself!"); XSLEEP(999); while(1) { reset = 0; add_mem_link(memchain, score); simon_says(memchain, boardx, boardy, score); draw_screen(boardx, boardy, 0, score, "Do you remember?"); for(int i = 0; i <= score; ++i) { // Need to flush the input or else any key the user pressed while waiting will be returned by getch(). flushinp(); // getch() - '0' will return the actual integer value of the key pressed. int keyp = getch() - '0'; // If the player picked the incorrect color... if(keyp != memchain[i]) { draw_screen(boardx, boardy, 0, score, "Game over. Press any key to play again. Press <Q> to quit."); keyp = getch(); if(keyp == 'q') { exit_game(); return 0; } else { reset = 1; reset_game(boardx, boardy, &score, memchain); break; } } else { draw_screen(boardx, boardy, keyp, score, ""); XSLEEP(200); draw_screen(boardx, boardy, 0, score, ""); } } if(!reset) { draw_screen(boardx, boardy, 0, score, "Correct! Get ready..."); ++score; XSLEEP(999); } } exit_game(); return 0; } void init_ncurses(void) { initscr(); cbreak(); noecho(); keypad(stdscr, TRUE); curs_set(0); use_default_colors(); // Want to use default background color, '-1'. start_color(); // The different simon colors. init_pair(1, COLOR_GREEN, -1); init_pair(2, COLOR_RED, -1); init_pair(3, COLOR_YELLOW, -1); init_pair(4, COLOR_BLUE, -1); } void draw_quadrant(const int startx, const int starty, const int colorpair) { attron(COLOR_PAIR(colorpair)); for(int x = 0; x < QUAD_WIDTH; ++x) { for(int y = 0; y < QUAD_HEIGHT; ++y) mvaddch(starty + y, startx + x, ACS_CKBOARD); } attroff(COLOR_PAIR(colorpair)); } void draw_game_board(const int startx, const int starty, const int hightlight) { // Loop through the 4 color quadrants. for(int i = 1; i <= NUM_COLORS; ++i) { // Quadrants 1 and 3 have the same startx, as well as 2 and 4. int qx = (i % 2) ? startx : startx + QUAD_WIDTH; // Quadrants 1 and 2 have the same startx, as well as 3 and 4. int qy = (i <= 2) ? starty : starty + QUAD_HEIGHT; // Highlight this quadrant to make it 'flash'. if(hightlight == i) attron(A_STANDOUT); draw_quadrant(qx, qy, i); if(hightlight == i) attroff(A_STANDOUT); } } void draw_screen(const int boardx, const int boardy, const int highlight, const int score, const char message[]) { clear(); mvprintw(boardy - 1, boardx + 1, "Brain Pain v1.0"); mvprintw(boardy - 1, boardx + QUAD_WIDTH + 3, "Score: %d", score); draw_game_board(boardx, boardy, highlight); mvprintw(boardy + QUAD_HEIGHT * 2, boardx + 4, "Press:"); // Shows which key number is associated with which color. for(int i = 1; i <= NUM_COLORS; ++i) { attron(COLOR_PAIR(i)); printw(" [%d]", i); attroff(COLOR_PAIR(i)); } mvprintw(boardy + QUAD_HEIGHT * 2 + 2, (boardx + QUAD_WIDTH) - (strlen(message) / 2), message); refresh(); } void simon_says(const int memchain[], const int startx, const int starty, const int score) { // A value of 0 means no color, thus we haven't gotten to that point in the memchain yet. for(int i = 0; memchain[i] != 0; ++i) { // Draws a game board with the specified color highlighted. draw_screen(startx, starty, memchain[i], score, ""); XSLEEP(500); // Sleep briefly to let the user see. /* Do the above again but with no quadrant highlighted. We need this brief flash just in case the same quadrant is flashed twice in a row. */ draw_screen(startx, starty, 0, score, ""); XSLEEP(200); } } void add_mem_link(int memchain[], const int score) { memchain[score] = get_random_color(); } int get_random_color(void) { return (rand() % NUM_COLORS) + 1; } void reset_game(const int boardx, const int boardy, int * const score, int memchain[]) { // Originally had *score + 1 instead of MEMCHAIN_LEN. Didn't work for some reason though. memset(memchain, 0, MEMCHAIN_LEN); *score = 0; draw_screen(boardx, boardy, 0, *score, "Prepare yourself!"); XSLEEP(999); } void exit_game(void) { // Maybe I'll need to do more in the future... endwin(); }
simonwarn/ExecTime
ExecTime.h
<reponame>simonwarn/ExecTime #pragma once #include <chrono> class ExecTime { public:// time in ms ExecTime(); void Start(); double Print(); private: std::chrono::steady_clock::time_point start; };
TerrySoba/TinyPaddleGame
source/print.c
#include "print.h" #if defined(__WATCOMC__) extern void _printChar(char ch); #pragma aux _printChar = \ "mov ah, 02h" \ "int 21h" \ modify [ah] \ parm [dl]; #endif void printString(const char* str) { while (*str) { #if defined(__GNUC__) asm ( "mov $0x02, %%ah\n" // set ah to 02 == print character "int $0x21" // call dos interrupt 0x21 to print character : : "Rdl" (*str) // load character to print to dl : "ah" ); #endif #if defined(__WATCOMC__) _printChar(*str); #endif ++str; } }
TerrySoba/TinyPaddleGame
source/title.h
<gh_stars>0 #ifndef _TITLE_H_INCLUDED #define _TITLE_H_INCLUDED void drawTitle(); #endif
TerrySoba/TinyPaddleGame
source/print.h
#ifndef _INCLUDE_PRINT_H #define _INCLUDE_PRINT_H // Prints string // String has to be terminated with '$'. void printString(const char* str); #endif
TerrySoba/TinyPaddleGame
source/main.c
<gh_stars>0 #include <stdint.h> #include "vga.h" #include "draw_number.h" #include "keyboard.h" #include "sound_engine.h" #include "print.h" #include "compiler_version.h" #include "title.h" #define abs(x) ((x > 0)?(x):(-x)) #define TO_SUBPIXELS(val) ((val) << 4) #define FROM_SUBPIXELS(val) ((val) >> 4) typedef struct _Rectangle { int16_t x, y, w, h; } Rectangle; void drawRectangle(const Rectangle* rectangle, uint8_t color) { drawRect( FROM_SUBPIXELS(rectangle->x), FROM_SUBPIXELS(rectangle->y), FROM_SUBPIXELS(rectangle->w), FROM_SUBPIXELS(rectangle->h), color); } #define PLAYFIELD_H 180 #define PLAYFIELD_W 320 bool calculateCollision(const Rectangle* r1, const Rectangle* r2) { if ( r1->x < r2->x + r2->w && r1->x + r1->w > r2->x && r1->y < r2->y + r2->h && r1->y + r1->h > r2->y) { return true; } return false; } int main() { SoundContext soundContext; initSound(&soundContext); registerKeyboardHandler(); videoInit(0x13); Rectangle leftPaddle = {TO_SUBPIXELS(10),TO_SUBPIXELS(10),TO_SUBPIXELS(5),TO_SUBPIXELS(40)}; Rectangle rightPaddle = {TO_SUBPIXELS(300),TO_SUBPIXELS(10),TO_SUBPIXELS(5),TO_SUBPIXELS(40)}; int leftColor = 3; int rightColor = 4; int leftPaddleColor = leftColor; int rightPaddleColor = rightColor; clearScreen(); drawTitle(); printString("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Press <SPACEBAR> to start game\r\n or <ESC> to exit back to DOS."); while (!s_keyEsc && !s_keySpace); do { int leftScore = 0; int rightScore = 0; int leftScore_old = -1; int rightScore_old = -1; int16_t dx = TO_SUBPIXELS(1); int16_t dy = TO_SUBPIXELS(2); Rectangle ball = {TO_SUBPIXELS(PLAYFIELD_W) / 2, TO_SUBPIXELS(PLAYFIELD_H) / 2, TO_SUBPIXELS(3), TO_SUBPIXELS(3)}; clearScreen(); drawRect(0, 180, 320, 3, 8); do { processSound(&soundContext); waitForVSync(); // first delete old gfx drawRectangle(&ball, 0); drawRectangle(&leftPaddle, 0); drawRectangle(&rightPaddle, 0); // handle inputs if (s_keyQ) leftPaddle.y -= TO_SUBPIXELS(2); if (s_keyA) leftPaddle.y += TO_SUBPIXELS(2); if (leftPaddle.y < 0) leftPaddle.y = 0; if (leftPaddle.y > TO_SUBPIXELS(PLAYFIELD_H) - leftPaddle.h) leftPaddle.y = TO_SUBPIXELS(PLAYFIELD_H) - leftPaddle.h; if (s_keyUp) rightPaddle.y -= TO_SUBPIXELS(2); if (s_keyDown) rightPaddle.y += TO_SUBPIXELS(2); if (rightPaddle.y < 0) rightPaddle.y = 0; if (rightPaddle.y > TO_SUBPIXELS(PLAYFIELD_H) - rightPaddle.h) rightPaddle.y = TO_SUBPIXELS(PLAYFIELD_H) - rightPaddle.h; // now calculate physics ball.x += dx; ball.y += dy; if (calculateCollision(&ball, &rightPaddle)) { dx = -abs(dx) - 5; rightPaddleColor += 10; playNote(&soundContext, G4, 30); } if (ball.x + ball.w > TO_SUBPIXELS(PLAYFIELD_W)) { dx = -abs(dx); ball.x = TO_SUBPIXELS(PLAYFIELD_W) - ball.w; ++leftScore; playNote(&soundContext, D4b, 30); } if (calculateCollision(&ball, &leftPaddle)) { dx = abs(dx) + 5; leftPaddleColor += 10; playNote(&soundContext, G4b, 30); } if (ball.x < 0) { dx = abs(dx); ball.x = 0; ++rightScore; playNote(&soundContext, D4b, 30); } if (ball.y + ball.h > TO_SUBPIXELS(PLAYFIELD_H)) { dy = -abs(dy); ball.y = TO_SUBPIXELS(PLAYFIELD_H) - ball.h; } if (ball.y < 0) { dy = abs(dy); ball.y = 0; } if (rightPaddleColor > rightColor) --rightPaddleColor; if (leftPaddleColor > leftColor) --leftPaddleColor; // now draw gfx drawRectangle(&ball, 0xf); drawRectangle(&leftPaddle, leftPaddleColor); drawRectangle(&rightPaddle, rightPaddleColor); // now draw score if it changed if (leftScore != leftScore_old || rightScore != rightScore_old) { drawNumber(30, 185, 0, 1, leftScore_old); drawNumber(280, 185, 0, 1, rightScore_old); drawNumber(30, 185, leftColor, 1, leftScore); drawNumber(280, 185, rightColor, 1, rightScore); } leftScore_old = leftScore; rightScore_old = rightScore; } while (leftScore < 10 && rightScore < 10 && !s_keyEsc); int color; if (leftScore > rightScore) color = 3; else color = 4; drawNumber(70, 30, color, 10, 1); drawNumber(150, 30, color, 10, 0); while (!s_keyEsc && !s_keySpace); } while (!s_keyEsc); unRegisterKeyboardHandler(); videoInit(0x3); deInitSound(&soundContext); printString("Thanks for playing!\r\nBuilt using " COMPILER_VERSION "\r\n"); return 0; }
TerrySoba/TinyPaddleGame
source/draw_number.h
#ifndef _INCLUDE_DRAW_NUMBER_H #define _INCLUDE_DRAW_NUMBER_H #include <stdint.h> void drawNumber(uint16_t x, int16_t y, uint8_t color, uint8_t scale, int number); #endif
TerrySoba/TinyPaddleGame
source/title.c
#include "title.h" #include "vga.h" void drawTitle() { #include "title.inc" }
TerrySoba/TinyPaddleGame
source/adlib.h
<filename>source/adlib.h /* C Header File: ADLIB ***************************************************** Author: <NAME> Last Amended: 27th April, 1993 Description: Low-level interface to the Adlib (or compatible) FM sound card. All information gleaned from <NAME>. Lee's "Programming the Adlib/Sound Blaster FM Music Chips". See Lee's document for further information. Compiled succesfully under Turbo C, Borland C++, and Microsoft Quick C (all latest versions). ****************************************************************************/ #define MIN_REGISTER 0x01 #define MAX_REGISTER 0xF5 #define ADLIB_FM_ADDRESS 0x388 /* adlib address/status register */ #define ADLIB_FM_DATA 0x389 /* adlib data register */ #ifndef BYTE #define BYTE unsigned char #endif /* * FM Instrument definition for .SBI files - SoundBlaster instrument * - these are the important parts - we will skip the header, but since * I am not sure where it starts and ends so I have had to guess. * However it SEEMS! to work. Each array has two values, one for * each operator. */ typedef struct { BYTE SoundCharacteristic[2]; /* modulator frequency multiple... */ BYTE Level[2]; /* modulator frequency level... */ BYTE AttackDecay[2]; /* modulator attack/decay... */ BYTE SustainRelease[2]; /* modulator sustain/release... */ BYTE WaveSelect[2]; /* output waveform distortion */ BYTE Feedback; /* feedback algorithm and strength */ } FMInstrument; /* * Enumerated F-Numbers (in octave 4) for the chromatic scale. */ enum SCALE { D4b = 0x16B, D4 = 0x181, E4b = 0x198, E4 = 0x1B0, F4 = 0x1CA, G4b = 0x1E5, G4 = 0x202, A4b = 0x220, A4 = 0x241, B4b = 0x263, B4 = 0x287, C4 = 0x2AE }; /* function prototyping */ void WriteFM(int reg, int value); int ReadFM(void); int AdlibExists(void); void FMReset(void); void FMKeyOff(int voice); void FMKeyOn(int voice, int freq, int octave); void FMVoiceVolume(int voice, int vol); void FMSetVoice(int voiceNum, FMInstrument *ins); int LoadSBI(char filename[], FMInstrument *ins); // void adlibTest();
TerrySoba/TinyPaddleGame
source/adlib.c
/* C Source File: ADLIB ***************************************************** Author: <NAME> Last Amended: 27th March, 1993 Description: Low-level interface to the Adlib (or compatible) FM sound card. All information gleaned from <NAME>'s "Programming the Adlib/Sound Blaster FM Music Chips". See Lee's document for further information. Compiled succesfully under Turbo C, Borland C++, and Microsoft Quick C (all latest versions). ****************************************************************************/ #include <stdio.h> #include <conio.h> #include <time.h> #include <dos.h> #include "adlib.h" /* comment out this line if you don't want to test the routines */ // #define TEST /* local function */ void Wait(clock_t wait); /* Function: WriteFM ******************************************************** * * Parameters: reg - which FM register to write to. * value - value to write. * * Description: writes a value to the specified register and * waits for the "official" recommended periods. * */ void WriteFM(int reg, int value) { int i; outp(ADLIB_FM_ADDRESS, (BYTE)reg); /* set up the register */ for (i = 0; i < 6; i++) inp(ADLIB_FM_ADDRESS); /* wait 12 cycles */ outp(ADLIB_FM_DATA, (BYTE)value); /* write out the value */ for (i = 0; i < 35; i++) inp(ADLIB_FM_ADDRESS); /* wait 84 cycles */ } /* End of WriteFM */ /* Function: ReadFM ********************************************************* * * Returns: the value in the status register. * * Description: return a value in the status register. * */ int ReadFM(void) { return (inp(ADLIB_FM_ADDRESS)); } /* End of ReadFM */ /* Function: AdlibExists **************************************************** * * Returns: 1 (true) if an Adlib compatible sound card * is present, else 0 (false). * * Description: determines whether an Adlib (or compatible) * sound card is present. * */ int AdlibExists(void) { int stat1, stat2; WriteFM(0x04, 0x60); /* reset both timers */ WriteFM(0x04, 0x80); /* enable timer interrupts */ stat1 = ReadFM(); /* read status register */ WriteFM(0x02, 0xFF); WriteFM(0x04, 0x21); /* start timer 1 */ Wait(80); /* could do something useful*/ stat2 = ReadFM(); /* read status register */ WriteFM(0x04, 0x60); /* reset both timers */ WriteFM(0x04, 0x80); /* enable timer interrupts */ if (((stat1 & 0xE0) == 0x00) && ((stat2 & 0xE0) == 0xC0)) return (1); return (0); } /* End of AdlibExists */ /* Function: FMResest ******************************************************* * * Description: quick and dirty sound card reset (zeros all * registers). * */ void FMReset(void) { int i; /* zero all registers */ for (i = MIN_REGISTER; i < MAX_REGISTER + 1; i++) WriteFM(i, 0); /* allow FM chips to control the waveform of each operator */ WriteFM(0x01, 0x20); /* set rhythm enabled (6 melodic voices, 5 percussive) */ WriteFM(0xBD, 0x20); } /* End of FMReset */ /* Function: FMKeyOff ******************************************************* * * Parameters: voice - which voice to turn off. * * Description: turns off the specified voice. * */ void FMKeyOff(int voice) { int regNum; /* turn voice off */ regNum = 0xB0 + voice % 11; WriteFM(regNum, 0); } /* End of FMKeyOff */ /* Function: FMKeyOff ******************************************************* * * Parameters: voice - which voice to turn on. * freq - its frequency (note). * octave - its octave. * * Description: turns on a voice of specfied frequency and * octave. * */ void FMKeyOn(int voice, int freq, int octave) { int regNum, tmp; regNum = 0xA0 + voice % 11; WriteFM(regNum, freq & 0xff); regNum = 0xB0 + voice % 11; tmp = (freq >> 8) | (octave << 2) | 0x20; WriteFM(regNum, tmp); } /* End of FMKeyOn */ /* Function: FMVoiceVolume ************************************************** * * Parameters: voice - which voice to set volume of * vol - new volume value (experiment). * * Description: sets the volume of a voice to the specified * value in the range (0-63)? * */ void FMVoiceVolume(int voice, int vol) { int regNum; regNum = 0x40 + voice % 11; WriteFM(regNum, vol); } /* End of FMVoiceVolume */ /* Function: FMSetVoice ***************************************************** * * Parameters: voiceNum - which voice to set. * ins - instrument to set voice. * * Description: sets the instrument of a voice. * */ void FMSetVoice(int voiceNum, FMInstrument *ins) { int opCellNum, cellOffset, i; voiceNum %= 11; cellOffset = voiceNum % 3 + ((voiceNum / 3) << 3); /* set sound characteristic */ opCellNum = 0x20 + (char)cellOffset; WriteFM(opCellNum, ins->SoundCharacteristic[0]); opCellNum += 3; WriteFM(opCellNum, ins->SoundCharacteristic[1]); /* set level/output */ opCellNum = 0x40 + (char)cellOffset; WriteFM(opCellNum, ins->Level[0]); opCellNum += 3; WriteFM(opCellNum, ins->Level[1]); /* set Attack/Decay */ opCellNum = 0x60 + (char)cellOffset; WriteFM(opCellNum, ins->AttackDecay[0]); opCellNum += 3; WriteFM(opCellNum, ins->AttackDecay[1]); /* set Sustain/Release */ opCellNum = 0x80 + (char)cellOffset; WriteFM(opCellNum, ins->SustainRelease[0]); opCellNum += 3; WriteFM(opCellNum, ins->SustainRelease[1]); /* set Wave Select */ opCellNum = 0xE0 + (char)cellOffset; WriteFM(opCellNum, ins->WaveSelect[0]); opCellNum += 3; WriteFM(opCellNum, ins->WaveSelect[1]); /* set Feedback/Selectivity */ opCellNum = (BYTE)0xC0 + (BYTE)voiceNum; WriteFM(opCellNum, ins->Feedback); } /* End of FMSetVoice */ // void printInstrument(FMInstrument *ins) // { // printf("{\n"); // for (int i = 0; i < sizeof(FMInstrument); ++i) // { // printf("0x%02x, ", ((unsigned char*)ins)[i]); // } // printf("}\n"); // } /* Function: LoadSBI ******************************************************** * * Parameters: fileName - name of .SBI file. * ins - variable to place data in. * * Description: loads a .SBI into the instrument structure. * */ // int LoadSBI(char fileName[], FMInstrument *ins) // { // int i; // FILE *fp; // size_t structSize = sizeof(FMInstrument); // if ((fp = fopen(fileName, "rb")) == NULL) // return (0); // /* skip the header - or do we? */ // for (i = 0; i < 36; i++) // fgetc(fp); // /* read the data */ // fread(ins, structSize, 1, fp); // fclose(fp); // printInstrument(ins); // return (1); // } /* End of LoadSBI */ /* Function: Wait ********************************************************** * * Parameters: wait - time in microseconds * * Description: pauses for a specified number of microseconds. * */ void Wait(clock_t wait) { clock_t goal; if (!wait) return; goal = wait + clock(); while (goal > clock() && !kbhit()) ; } /* End of Wait */ /* test of the routines */ #ifdef TEST void adlibTest() { enum SCALE test[] = {D4, E4, F4, G4, A4, B4, C4}; static FMInstrument testInst = { 0x21, 0x31, 0x4F, 0x00, 0xF1, 0xF2, 0x11, 0x11, 0x00, 0x00, 0x06}; int i; printf("\nChecking for Adlib sound card..."); if (!AdlibExists()) { printf("not found.\n."); // exit(1); } printf("found.\n"); printf("Now playing tune...\n"); FMReset(); LoadSBI("MARIMBA.SBI", &testInst); FMSetVoice(0, &testInst); for (i = 0; i < 7; i++) { FMKeyOn(0, test[i], 4); Wait(25); FMKeyOff(0); Wait(1); } FMReset(); } #endif
TerrySoba/TinyPaddleGame
source/compiler_version.h
#ifndef _INCLUDE_COMPILER_VERSION_H_ #define _INCLUDE_COMPILER_VERSION_H_ #define xstr(s) str(s) #define str(s) #s #if defined(__GNUC__) #define COMPILER_VERSION "GCC " xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "." xstr(__GNUC_PATCHLEVEL__) #endif #if defined(__WATCOMC__) #define COMPILER_VERSION "OpenWatcom C " xstr(__WATCOMC__) #endif #endif
TerrySoba/TinyPaddleGame
source/sound_engine.c
#include "sound_engine.h" bool initSound(SoundContext* context) { if (!context) return false; if (!AdlibExists()) { context->soundInitialized = false; return false; } context->soundInitialized = true; context->soundRestTime = -1; FMReset(); FMInstrument instrument = { 0x05, 0x01, 0x4e, 0x00, 0xda, 0xf9, 0x25, 0x15, 0x00, 0x00, 0x0a }; instrument.AttackDecay[0] = 0; // LoadSBI("MARIMBA.SBI", &instrument); FMSetVoice(0, &instrument); // FMReset(); return true; } void deInitSound(SoundContext* context) { if (context && context->soundInitialized) { FMReset(); } } void playNote(SoundContext* context, enum SCALE note, int length) { if (context && context->soundInitialized) { FMKeyOn(0, note, 4); context->soundRestTime = length; } } void processSound(SoundContext* context) { if (context && context->soundInitialized) { if (context->soundRestTime > 0) { --context->soundRestTime; if (context->soundRestTime == 0) { FMKeyOff(0); } } } }
TerrySoba/TinyPaddleGame
source/vga.c
<filename>source/vga.c #include "vga.h" #if defined(__WATCOMC__) #include <conio.h> #include <string.h> #define inport(px) inpw(px) #define inportb(px) inp(px) #endif #define abs(val) (((val) > 0)?(val):-(val)) #if defined(__GNUC__) void videoInit(uint8_t mode) { asm("mov $0, %%ah\n" "int $0x10" : : "Ral" (mode) : "ah" ); } #endif #if defined(__WATCOMC__) extern void _videoInit(uint8_t mode); #pragma aux _videoInit = \ "mov ah, 0" \ "int 10h" \ modify [ax] \ parm [al]; void videoInit(uint8_t mode) { _videoInit(mode); } #endif #if defined(__WATCOMC__) extern void drawVLine(uint16_t x, uint8_t y, uint8_t h, uint8_t color); #pragma aux drawVLine = \ "mov ch, 20" \ "mul ch" \ "xor ch, ch" \ "add ax, 40960" \ "push ds" \ "mov ds, ax" \ "draw_loop:" \ "mov [bx], dl" \ "add bx, 320" \ "loop draw_loop" \ "pop ds" \ modify [ch ax] \ parm [bx] [al] [cl] [dl]; #endif #if defined(__GNUC__) inline void drawVLine(uint16_t x, uint8_t y, uint8_t h, uint8_t color) { asm ( "mov $20, %%ch\n" "mul %%ch\n" // multiply ax = al * ch "xor %%ch, %%ch\n" // ch = 0 "add $40960, %%ax\n" // $40960 is the address of the VGA graphics ram "mov %%ax, %%ds\n" // set segment register to VGA "%=:\n" "mov %%dl, (%%bx)\n" // draw pixel to vram "add $320, %%bx\n" // skip to next line (screen is 320 pixels wide) "loop %=b\n" // loop until cx is 0 (loop decrements cx each loop) : : "b" (x), "Ral" (y), "Rdl" (color), "Rcl" (h) : "ds", "ah", "ch" ); } inline void drawRectEven(uint16_t x, uint8_t y, uint16_t w, uint8_t h, uint8_t color) { uint16_t offset = 20 * y; asm ( "add $40960, %%bx\n" // $40960 is the address of the VGA graphics ram "mov %%bx, %%es\n" // set segment register to VGA "mov %%al, %%ah\n" // set color "cld\n" // set DF to 0 "shrw $1, %1\n" // divide length by 2 "%=:\n" "mov %0, %%di\n" // set offset to x "mov %1, %%cx\n" // set length to w "rep stosw\n" // copy ax -> es:di++ until cx-- == 0 "add $20, %%bx\n" // skip to next line (320 / 16 = 20) "mov %%bx, %%es\n" "dec %4\n" // decrement h "jnz %=b\n" // loop until h is 0 : : "r" (x), "m" (w), "b" (offset), "Ral" (color), "r" (h) : "es", "ah", "cx", "di" ); } inline void drawRectOdd(uint16_t x, uint8_t y, uint16_t w, uint8_t h, uint8_t color) { uint16_t offset = 20 * y; asm ( "add $40960, %%bx\n" // $40960 is the address of the VGA graphics ram "mov %%bx, %%es\n" // set segment register to VGA "mov %%al, %%ah\n" // set color "cld\n" // set DF to 0 "shrw $1, %1\n" // divide length by 2 "%=:\n" "mov %0, %%di\n" // set offset to x "mov %1, %%cx\n" // set length to w "rep stosw\n" // copy ax -> es:di++ until cx-- == 0 "stosb\n" // store an additional byte as width is odd "add $20, %%bx\n" // skip to next line (320 / 16 = 20) "mov %%bx, %%es\n" "dec %4\n" // decrement h "jnz %=b\n" // loop until h is 0 : : "r" (x), "m" (w), "b" (offset), "Ral" (color), "r" (h) : "es", "ah", "cx", "di" ); } void drawRect(uint16_t x, uint8_t y, uint16_t w, uint8_t h, uint8_t color) { if (w == 1) drawVLine(x,y,h,color); else if (w&1) drawRectOdd(x,y,w,h,color); else drawRectEven(x,y,w,h,color); } #endif #if defined(__WATCOMC__) void drawRect(uint16_t x, uint8_t y, uint16_t w, uint8_t h, uint8_t color) { if (w == 1) { drawVLine(x,y,h,color); } else { static char far* screen = (char far*)(0xA0000000L); char far* pos = screen + y * SCREEN_W + x; for (uint8_t i = 0; i < h; ++i) { _fmemset(pos, color, w); pos += SCREEN_W; } } } #endif void clearScreen() { drawRect(0, 0, SCREEN_W, SCREEN_H, 0); } void drawPixel(int x, int y, uint8_t color) { #if defined(__WATCOMC__) char far* screen = (char far*)(0xA0000000L); #elif defined(__GNUC__) char __far* screen = (char __far*)(0xA0000000L); #endif screen[y * 320 + x] = color; } void drawLine(int x0, int y0, int x1, int y1, uint8_t color) { int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1; int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1; int err = (dx>dy ? dx : -dy)/2, e2; for(;;){ drawPixel(x0,y0,color); if (x0==x1 && y0==y1) break; e2 = err; if (e2 >-dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += dx; y0 += sy; } } } void drawHLine(int16_t x, uint8_t y, int16_t length, uint8_t color) { #if defined(__GNUC__) uint16_t offset = 20 * y; asm ( "add $40960, %%bx\n" // $40960 is the address of the VGA graphics ram "mov %%bx, %%es\n" // set segment register to VGA "mov %%al, %%ah\n" // set color "cld\n" // set DF to 0 "shrw $1, %1\n" // divide length by 2 "mov %3, %%di\n" "rep stosw\n" // copy ax -> es:di++ until cx-- == 0 "jnc %=f\n" "stosb\n" // store an additional byte as width is odd "%=:\n" : : "b" (offset), "c" (length), "Ral" (color), "m" (x) : "ds", "ah", "di", "es" ); #elif defined(__WATCOMC__) char far* screen = (char far*)(0xA0000000L); screen += y * 320 + x; _fmemset(screen, color, length); #endif } void drawCircle(int x0, int y0, int radius, uint8_t color, bool filled) { int f = 1 - radius; int ddF_x = 0; int ddF_y = -2 * radius; int x = 0; int y = radius; drawPixel(x0, y0 + radius, color); drawPixel(x0, y0 - radius, color); drawPixel(x0 + radius, y0, color); drawPixel(x0 - radius, y0, color); if (filled) { drawHLine(x0 - radius, y0, 2 * radius + 1, color); } while(x < y) { if(f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x + 1; if (filled) { drawHLine(x0 - x, y0 + y, 2 * x + 1, color); drawHLine(x0 - x, y0 - y, 2 * x + 1, color); drawHLine(x0 - y, y0 + x, 2 * y + 1, color); drawHLine(x0 - y, y0 - x, 2 * y + 1, color); } else // not filled { drawPixel(x0 + x, y0 + y, color); drawPixel(x0 - x, y0 + y, color); drawPixel(x0 + x, y0 - y, color); drawPixel(x0 - x, y0 - y, color); drawPixel(x0 + y, y0 + x, color); drawPixel(x0 - y, y0 + x, color); drawPixel(x0 + y, y0 - x, color); drawPixel(x0 - y, y0 - x, color); } } } #if defined(__GNUC__) /* Input a byte from a port */ inline unsigned char inportb(unsigned int port) { unsigned char ret; asm volatile ("inb %%dx,%%al":"=a" (ret):"d" (port)); return ret; } /* Output a byte to a port */ /* July 6, 2001 added space between :: to make code compatible with gpp */ inline void outportb(unsigned int port,unsigned char value) { asm volatile ("outb %%al,%%dx": :"d" (port), "a" (value)); } #endif #define CGA_STATUS_REG 0x03DA #define VERTICAL_RETRACE_BIT 0x08 void waitForVSync() { while (inportb(CGA_STATUS_REG) & VERTICAL_RETRACE_BIT); while (!(inportb(CGA_STATUS_REG) & VERTICAL_RETRACE_BIT)); }
TerrySoba/TinyPaddleGame
source/sound_engine.h
<gh_stars>0 #ifndef _SOUND_ENGINE_INCLUDED #define _SOUND_ENGINE_INCLUDED #include <stdbool.h> #include "adlib.h" typedef struct _SoundContext { bool soundInitialized; // if set to false, then sound hardware was not found. int soundRestTime; // contains the time units that the sound will be played until it is turned off. } SoundContext; /** * Initializes the sound system. If successfull then true is returned. * In error case, e.g. if no sound hardware was found, false is returned. */ bool initSound(SoundContext* context); void deInitSound(SoundContext* context); /** * */ void playNote(SoundContext* context, enum SCALE note, int length); /** * This function needs to be called about 70 times per second. */ void processSound(SoundContext* context); #endif
TerrySoba/TinyPaddleGame
source/keyboard.c
#include "keyboard.h" #include <dos.h> #include <stdint.h> volatile uint8_t s_scancode; volatile uint8_t s_keyLeft; volatile uint8_t s_keyRight; volatile uint8_t s_keyUp; volatile uint8_t s_keyDown; volatile uint8_t s_keyCtrl; volatile uint8_t s_keyAlt; volatile uint8_t s_keySpace; volatile uint8_t s_keyEsc; volatile uint8_t s_keyA; volatile uint8_t s_keyQ; #define LEFT_KEY 0x4b #define RIGHT_KEY 0x4d #define UP_KEY 0x48 #define DOWN_KEY 0x50 #define CTRL_KEY 0x1d #define ALT_KEY 0x38 #define SPACE_KEY 0x39 #define ESC_KEY 0x01 #define Q_KEY 0x10 #define A_KEY 0x1e #define SCANCODE_MASK 127 #define PRESS_MASK 128 void __interrupt __far handleScancode( void ) { uint8_t code; #if defined(__GNUC__) asm volatile ("cli\n" "inb $0x60, %%al\n" /* read scan code */ "mov %%al, %0\n" "inb $0x61, %%al\n" /* read keyboard status */ "mov %%al, %%bl\n" "or $0x80, %%al\n" "outb %%al, $0x61\n" /* set bit 7 and write */ "mov %%bl, %%al\n" "out %%al, $0x61\n" /* write again, bit 7 clear */ "mov $0x20, %%al\n" /* reset PIC */ "out %%al, $0x20\n" /* end of re-set code */ "sti" : "=r" (code) : : "ax", "bx"); #endif #if defined(__WATCOMC__) __asm { cli in al, 060h /* read scan code */ mov code, al in al, 061h /* read keyboard status */ mov bl, al or al, 080h out 061h, al /* set bit 7 and write */ mov al, bl out 061h, al /* write again, bit 7 clear */ mov al, 020h /* reset PIC */ out 020h, al /* end of re-set code */ sti } #endif s_scancode = code; // printf("code: %d\n", code); switch (code & SCANCODE_MASK) { case LEFT_KEY: s_keyLeft = !(code & PRESS_MASK); break; case RIGHT_KEY: s_keyRight = !(code & PRESS_MASK); break; case UP_KEY: s_keyUp = !(code & PRESS_MASK); break; case DOWN_KEY: s_keyDown = !(code & PRESS_MASK); break; case CTRL_KEY: s_keyCtrl = !(code & PRESS_MASK); break; case ALT_KEY: s_keyAlt = !(code & PRESS_MASK); break; case SPACE_KEY: s_keySpace = !(code & PRESS_MASK); break; case ESC_KEY: s_keyEsc = !(code & PRESS_MASK); break; case A_KEY: s_keyA = !(code & PRESS_MASK); break; case Q_KEY: s_keyQ = !(code & PRESS_MASK); break; } } #define KEYBOARD_INTERRUPT 9 void __interrupt __far (*m_oldInterrupt)(); void registerKeyboardHandler() { s_keyLeft = 0; s_keyRight = 0; s_keyUp = 0; s_keyDown = 0; s_keyCtrl = 0; s_keyAlt = 0; s_keySpace = 0; s_keyEsc = 0; m_oldInterrupt = _dos_getvect(KEYBOARD_INTERRUPT); _dos_setvect(KEYBOARD_INTERRUPT, handleScancode); } void unRegisterKeyboardHandler() { _dos_setvect(KEYBOARD_INTERRUPT, m_oldInterrupt); }
TerrySoba/TinyPaddleGame
source/draw_number.c
#include "draw_number.h" #include "vga.h" void drawNumber(uint16_t x, int16_t y, uint8_t color, uint8_t scale, int number) { /// Seven segment style number drawing routine /// The numbers of the segments are shown in the /// diagram below. // // 5 // ###### // # # // 0 # # 4 // # 6 # // ###### // # # // 1 # # 3 // # # // ###### // 2 uint16_t elementLength = 4 * scale; uint16_t elementThickness = 1 * scale; uint16_t gapSize = 1 * scale; // segment 0 #define SEG_0 drawRect(x, y + gapSize, elementThickness, elementLength, color); // segment 1 #define SEG_1 drawRect(x, y + gapSize + elementLength + gapSize, elementThickness, elementLength, color); // segment 2 #define SEG_2 drawRect(x + gapSize, y + gapSize + elementLength + gapSize + elementLength, elementLength, elementThickness, color); // segment 3 #define SEG_3 drawRect(x + gapSize + elementLength, y + gapSize + elementLength + gapSize, elementThickness, elementLength, color); // segment 4 #define SEG_4 drawRect(x + gapSize + elementLength, y + gapSize, elementThickness, elementLength, color); // segment 5 #define SEG_5 drawRect(x + gapSize, y, elementLength, elementThickness, color); // segment 6 #define SEG_6 drawRect(x + gapSize, y + gapSize + elementLength, elementLength, elementThickness, color); switch (number) { case 0: SEG_0 SEG_1 SEG_2 SEG_3 SEG_4 SEG_5 break; case 1: SEG_3 SEG_4 break; case 2: SEG_1 SEG_2 SEG_4 SEG_5 SEG_6 break; case 3: SEG_2 SEG_3 SEG_4 SEG_5 SEG_6 break; case 4: SEG_0 SEG_3 SEG_4 SEG_6 break; case 5: SEG_0 SEG_2 SEG_3 SEG_5 SEG_6 break; case 6: SEG_0 SEG_1 SEG_2 SEG_3 SEG_5 SEG_6 break; case 7: SEG_3 SEG_4 SEG_5 break; case 8: SEG_0 SEG_1 SEG_2 SEG_3 SEG_4 SEG_5 SEG_6 break; case 9: SEG_0 SEG_3 SEG_4 SEG_5 SEG_6 break; } }
TerrySoba/TinyPaddleGame
source/vga.h
#ifndef _VGA_H_INCLUDED #define _VGA_H_INCLUDED #include <stdint.h> #include <stdbool.h> #define SCREEN_W 320 #define SCREEN_H 200 void videoInit(uint8_t mode); void drawRect(uint16_t x, uint8_t y, uint16_t w, uint8_t h, uint8_t color); void drawLine(int x0, int y0, int x1, int y1, uint8_t color); void drawHLine(int16_t x, uint8_t y, int16_t length, uint8_t color); void drawCircle(int centerX, int centerY, int radius, uint8_t color, bool filled); void clearScreen(); void waitForVSync(); #endif
lubomir/libmodulemd
modulemd/include/modulemd-1.0/private/modulemd-util.h
/* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #ifndef MODULEMD_UTIL_H #define MODULEMD_UTIL_H #include "modulemd.h" #include "glib.h" G_BEGIN_DECLS #define MODULEMD_ERROR modulemd_error_quark () GQuark modulemd_error_quark (void); enum ModulemdError { MODULEMD_ERROR_PROGRAMMING }; GHashTable * _modulemd_hash_table_deep_str_copy (GHashTable *orig); GHashTable * _modulemd_hash_table_deep_obj_copy (GHashTable *orig); GHashTable * _modulemd_hash_table_deep_variant_copy (GHashTable *orig); gint _modulemd_strcmp_sort (gconstpointer a, gconstpointer b); GPtrArray * _modulemd_ordered_str_keys (GHashTable *htable, GCompareFunc compare_func); GList * _modulemd_ordered_int64_keys (GHashTable *htable); void modulemd_variant_unref (void *ptr); gboolean modulemd_validate_nevra (const gchar *nevra); typedef struct _modulemd_tracer { gchar *function_name; } modulemd_tracer; modulemd_tracer * modulemd_trace_init (const gchar *function_name); void modulemd_trace_free (modulemd_tracer *tracer); G_DEFINE_AUTOPTR_CLEANUP_FUNC (modulemd_tracer, modulemd_trace_free); #define MODULEMD_INIT_TRACE \ g_autoptr (modulemd_tracer) tracer = modulemd_trace_init (__func__); \ do \ { \ (void)(tracer); \ } \ while (0); GPtrArray * _modulemd_index_serialize (GHashTable *index, GError **error); ModulemdTranslationEntry * _get_locale_entry (ModulemdTranslation *translation, const gchar *_locale); GHashTable * module_index_from_data (GPtrArray *data, GError **error); G_END_DECLS #endif /* MODULEMD_UTIL_H */
lubomir/libmodulemd
modulemd/include/modulemd-1.0/modulemd-defaults.h
<reponame>lubomir/libmodulemd /* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #ifndef MODULEMD_DEFAULTS_H #define MODULEMD_DEFAULTS_H #include <stdio.h> #include "modulemd-intent.h" #include "modulemd-simpleset.h" #include <glib-object.h> enum { MD_DEFAULTS_VERSION_UNSET = 0, MD_DEFAULTS_VERSION_1 = 1, MD_DEFAULTS_VERSION_MAX = G_MAXUINT64 }; #define MD_DEFAULTS_VERSION_LATEST MD_DEFAULTS_VERSION_1 G_BEGIN_DECLS /** * SECTION: modulemd-defaults * @title: Modulemd.Defaults * @short_description: Represents the default stream, profiles and other global * data for a module. */ #define MODULEMD_DEFAULTS_ERROR modulemd_defaults_error_quark () GQuark modulemd_defaults_error_quark (void); enum ModulemdDefaultsError { MODULEMD_DEFAULTS_ERROR_MISSING_CONTENT, MODULEMD_DEFAULTS_ERROR_CONFLICTING_STREAMS, MODULEMD_DEFAULTS_ERROR_CONFLICTING_PROFILES, MODULEMD_DEFAULTS_ERROR_CONFLICTING_INTENT_STREAM, MODULEMD_DEFAULTS_ERROR_CONFLICTING_INTENT_PROFILE }; #define MODULEMD_TYPE_DEFAULTS (modulemd_defaults_get_type ()) G_DECLARE_FINAL_TYPE ( ModulemdDefaults, modulemd_defaults, MODULEMD, DEFAULTS, GObject) /** * modulemd_defaults_new: * * Returns: (transfer full): A newly-allocated #ModulemdDefaults object. This * must be freed with g_object_unref(). * * Since: 1.1 */ ModulemdDefaults * modulemd_defaults_new (void); /** * modulemd_defaults_set_version: * @version: The metadata file format version * * Sets the version of the metadata in use. * * Since: 1.1 */ void modulemd_defaults_set_version (ModulemdDefaults *self, guint64 version); /** * modulemd_defaults_peek_version: * * Retrieves the metadata file format version. * * Returns: a 64-bit unsigned integer containing the file format version. * * Since: 1.1 */ guint64 modulemd_defaults_peek_version (ModulemdDefaults *self); /** * modulemd_defaults_set_module_name: * @name: The module name to which these defaults apply * * Sets the "module-name" property. * * Since: 1.1 */ void modulemd_defaults_set_module_name (ModulemdDefaults *self, const gchar *name); /** * modulemd_defaults_peek_module_name: * * Retrieves the module name to which these defaults apply. * * Returns: a string containing the "module-name" property. This string must * not be modified or freed. If you need to do so, use * modulemd_defaults_dup_module_name() instead. * * Since: 1.1 */ const gchar * modulemd_defaults_peek_module_name (ModulemdDefaults *self); /** * modulemd_defaults_dup_module_name: * * Retrieves the module name to which these defaults apply. * * Returns: a string containing the "module-name" property. This string must be * freed with g_free() when the caller is done with it. * * Since: 1.1 */ gchar * modulemd_defaults_dup_module_name (ModulemdDefaults *self); /** * modulemd_defaults_set_default_stream: * @stream: The default stream for this module * * Sets the "default-stream" property. * * Since: 1.1 */ void modulemd_defaults_set_default_stream (ModulemdDefaults *self, const gchar *stream); /** * modulemd_defaults_peek_default_stream: * * Retrieves the default stream. * * Returns: a string containing the "default-stream" property. This string * must not be modified or freed. If you need to do so, use * modulemd_defaults_dup_default_stream() instead. * * Since: 1.1 */ const gchar * modulemd_defaults_peek_default_stream (ModulemdDefaults *self); /** * modulemd_defaults_dup_default_stream: * * Retrieves the default stream. * * Returns: a string containing the "default-stream" property. This string must * be freed with g_free() when the caller is done with it. * * Since: 1.1 */ gchar * modulemd_defaults_dup_default_stream (ModulemdDefaults *self); /** * modulemd_defaults_set_profiles_for_stream: * @stream: The name of the stream getting default profiles * @profiles: (array zero-terminated=1) (transfer none): The set of profile * names to install by default when installing this stream of the module. * * Since: 1.1 */ void modulemd_defaults_set_profiles_for_stream (ModulemdDefaults *self, const gchar *stream, gchar **profiles); /** * modulemd_defaults_assign_profiles_for_stream: * @stream: The name of the stream getting default profiles * @profiles: A #ModulemdSimpleSet of profile names to install by default when * installing this stream of the module. * * Since: 1.1 */ void modulemd_defaults_assign_profiles_for_stream (ModulemdDefaults *self, const gchar *stream, ModulemdSimpleSet *profiles); /** * modulemd_defaults_set_profile_defaults: * @profile_defaults: (nullable) (element-type utf8 ModulemdSimpleSet) (transfer none): * * Assigns the hash table of streams and their default profiles * * Since: 1.1 */ void modulemd_defaults_set_profile_defaults (ModulemdDefaults *self, GHashTable *profile_defaults); /** * modulemd_defaults_dup_profiles_for_stream: * @stream: The name of the stream from which to retrieve defaults * * Returns: (array zero-terminated=1) (transfer full): A zero-terminated array * of strings that provides the list of profiles that should be installed by * default when this stream is specified. * * Since: 1.1 */ gchar ** modulemd_defaults_dup_profiles_for_stream (ModulemdDefaults *self, const gchar *stream); /** * modulemd_defaults_peek_profile_defaults: * * Retrieves a hash table of the profile defaults. * * Returns: (element-type utf8 ModulemdSimpleSet) (transfer none): A GHashTable * containing the set of profile defaults for streams of this module. This hash * table is maintained by the ModulemdDefaults object and must not be freed or * modified. If modification is necessary, use * modulemd_defaults_dup_profile_defaults() instead. * * Since: 1.1 */ GHashTable * modulemd_defaults_peek_profile_defaults (ModulemdDefaults *self); /** * modulemd_defaults_dup_profile_defaults: * * Retrieves a copy of the hash table of profile defaults. * * Returns: (element-type utf8 ModulemdSimpleSet) (transfer container): A * GHashTable containing the set of profile defaults for streams of this * module. This hash table is a copy and must be freed with * g_hash_table_unref() when the caller is finished with it. The elements it * contains are maintained by the hash table and will be automatically freed * when their key is removed or the hash table is freed. * * Since: 1.1 */ GHashTable * modulemd_defaults_dup_profile_defaults (ModulemdDefaults *self); /** * modulemd_defaults_add_intent: * @intent: (transfer none) (not nullable): The #ModulemdIntent to add to the * intents table. * * Adds an intent object to the hash table. * * Since: 1.5 */ void modulemd_defaults_add_intent (ModulemdDefaults *self, ModulemdIntent *intent); /** * modulemd_defaults_set_intents: * @intents: (element-type utf8 ModulemdIntent) (nullable) (transfer none): * A #GHashTable containing defaults for individual system intents. * * Since: 1.5 */ void modulemd_defaults_set_intents (ModulemdDefaults *self, GHashTable *intents); /** * modulemd_defaults_peek_intents: * * Get a pointer to the intents hash table. The returned table is managed by the * #ModulemdDefaults object and must not be modified or freed. * * Returns: (element-type utf8 ModulemdIntent) (transfer none): A pointer to the * intents hash table. * * Since: 1.5 */ GHashTable * modulemd_defaults_peek_intents (ModulemdDefaults *self); /** * modulemd_defaults_dup_intents: * * Get a copy of the intents hash table. The returned table is managed by the * caller and must be freed with g_hash_table_unref() * * Returns: (element-type utf8 ModulemdIntent) (transfer container): A copy of * the intents hash table. * * Since: 1.5 */ GHashTable * modulemd_defaults_dup_intents (ModulemdDefaults *self); /** * modulemd_defaults_new_from_file: * @yaml_file: A YAML file containing the module metadata and other related * information such as default streams. * @error: (out): A #GError containing additional information if this function * fails. * * Constructs a new #ModulemdDefaults object from the first valid * modulemd-defaults document in the given module stream. This will ignore any * documents of other types, malformed documents and defaults that appear later * in the stream. * * Returns: A #ModulemdDefaults object constructed the first valid * modulemd-defaults document in the given module stream. This must be freed * with g_object_unref() when no longer needed. * * Since: 1.2 */ ModulemdDefaults * modulemd_defaults_new_from_file (const gchar *yaml_file, GError **error); /** * modulemd_defaults_new_from_file_ext: * @yaml_file: A YAML file containing the module metadata and other related * information such as default streams. * @failures: (element-type ModulemdSubdocument) (transfer container) (out): * An array containing any subdocuments from the YAML file that failed to * parse. This must be freed with g_ptr_array_unref(). * @error: (out): A #GError containing additional information if this function * fails. * * Constructs a new #ModulemdDefaults object from the first valid * modulemd-defaults document in the given module stream. This will ignore any * documents of other types, malformed documents and defaults that appear later * in the stream. * * Returns: A #ModulemdDefaults object constructed the first valid * modulemd-defaults document in the given module stream. This must be freed * with g_object_unref() when no longer needed. * * Since: 1.4 */ ModulemdDefaults * modulemd_defaults_new_from_file_ext (const gchar *yaml_file, GPtrArray **failures, GError **error); /** * modulemd_defaults_new_from_string: * @yaml_string: A YAML string containing the module metadata and other related * information such as default streams. * @error: (out): A #GError containing additional information if this function * fails. * * Constructs a new #ModulemdDefaults object from the first valid * modulemd-defaults document in the given module stream. This will ignore any * documents of other types, malformed documents and defaults that appear later * in the stream. * * Returns: A #ModulemdDefaults object constructed the first valid * modulemd-defaults document in the given module stream. This must be freed * with g_object_unref() when no longer needed. * * Since: 1.2 */ ModulemdDefaults * modulemd_defaults_new_from_string (const gchar *yaml_string, GError **error); /** * modulemd_defaults_new_from_string_ext: * @yaml_string: A YAML string containing the module metadata and other related * information such as default streams. * @failures: (element-type ModulemdSubdocument) (transfer container) (out): * An array containing any subdocuments from the YAML file that failed to * parse. This must be freed with g_ptr_array_unref(). * @error: (out): A #GError containing additional information if this function * fails. * * Constructs a new #ModulemdDefaults object from the first valid * modulemd-defaults document in the given module stream. This will ignore any * documents of other types, malformed documents and defaults that appear later * in the stream. * * Returns: A #ModulemdDefaults object constructed the first valid * modulemd-defaults document in the given module stream. This must be freed * with g_object_unref() when no longer needed. * * Since: 1.4 */ ModulemdDefaults * modulemd_defaults_new_from_string_ext (const gchar *yaml_string, GPtrArray **failures, GError **error); /** * modulemd_defaults_new_from_stream: * @stream: A YAML stream containing the module metadata and other related * information such as default streams. * @error: (out): A #GError containing additional information if this function * fails. * * Constructs a new #ModulemdDefaults object from the first valid * modulemd-defaults document in the given module stream. This will ignore any * documents of other types, malformed documents and defaults that appear later * in the stream. * * Returns: A #ModulemdDefaults object constructed the first valid * modulemd-defaults document in the given module stream. This must be freed * with g_object_unref() when no longer needed. * * Since: 1.4 */ ModulemdDefaults * modulemd_defaults_new_from_stream (FILE *stream, GError **error); /** * modulemd_defaults_new_from_stream_ext: * @stream: A YAML stream containing the module metadata and other related * information such as default streams. * @failures: (element-type ModulemdSubdocument) (transfer container) (out): * An array containing any subdocuments from the YAML file that failed to * parse. This must be freed with g_ptr_array_unref(). * @error: (out): A #GError containing additional information if this function * fails. * * Constructs a new #ModulemdDefaults object from the first valid * modulemd-defaults document in the given module stream. This will ignore any * documents of other types, malformed documents and defaults that appear later * in the stream. * * Returns: A #ModulemdDefaults object constructed the first valid * modulemd-defaults document in the given module stream. This must be freed * with g_object_unref() when no longer needed. * * Since: 1.4 */ ModulemdDefaults * modulemd_defaults_new_from_stream_ext (FILE *stream, GPtrArray **failures, GError **error); /** * modulemd_defaults_dump: * @file_path: File path for exporting the YAML representation of this defaults * object * * Exports the YAML representation of this defaults object to a file. * * Since: 1.1 */ void modulemd_defaults_dump (ModulemdDefaults *self, const gchar *file_path); /** * modulemd_defaults_dumps: * @yaml_string: (out): File path for exporting the YAML representation of this defaults * object * * Exports the YAML representation of this defaults object to a string. The * caller is responsible for calling g_free() on this string when they are * finished with it. * * Since: 1.1 */ void modulemd_defaults_dumps (ModulemdDefaults *self, gchar **yaml_string); /** * modulemd_defaults_copy: * Returns a deep-copy of the defaults object. * * Returns: (transfer full): A deep-copied #ModulemdDefaults object. This * object must be freed with g_object_unref(). * * Since: 1.3 */ ModulemdDefaults * modulemd_defaults_copy (ModulemdDefaults *self); /** * modulemd_defaults_merge: * @first: A #ModulemdDefaults object providing the base for the merge. * @second: A #ModulemdDefaults object being merged onto @first. * @override: In the case of a conflict, should @second completely replace the * contents of @first. * * Returns: (transfer full): A merged or replaced #ModulemdDefaults object. In * case of unresolvable merge, NULL will be returned and an error will be set. * This object must be freed with g_object_unref(). * * Since: 1.3 */ ModulemdDefaults * modulemd_defaults_merge (ModulemdDefaults *first, ModulemdDefaults *second, gboolean override, GError **error); G_END_DECLS #endif /* MODULEMD_DEFAULTS_H */
lubomir/libmodulemd
modulemd/v1/modulemd-improvedmodule.c
/* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #include "modulemd.h" #include "modulemd-improvedmodule.h" #include "private/modulemd-improvedmodule-private.h" #include "private/modulemd-util.h" #include "private/modulemd-yaml.h" struct _ModulemdImprovedModule { GObject parent_instance; /* The name of this module */ gchar *name; /* Hash table of streams available in this module, indexed by stream name */ GHashTable *streams; /* The defaults for this module */ ModulemdDefaults *defaults; }; G_DEFINE_TYPE (ModulemdImprovedModule, modulemd_improvedmodule, G_TYPE_OBJECT) enum { PROP_0, PROP_NAME, PROP_DEFAULTS, N_PROPS }; static GParamSpec *properties[N_PROPS]; ModulemdImprovedModule * modulemd_improvedmodule_new (const gchar *name) { return g_object_new (MODULEMD_TYPE_IMPROVEDMODULE, "name", name, NULL); } static void modulemd_improvedmodule_finalize (GObject *object) { ModulemdImprovedModule *self = (ModulemdImprovedModule *)object; g_clear_pointer (&self->name, g_free); g_clear_pointer (&self->streams, g_hash_table_unref); g_clear_pointer (&self->defaults, g_object_unref); G_OBJECT_CLASS (modulemd_improvedmodule_parent_class)->finalize (object); } void modulemd_improvedmodule_set_name (ModulemdImprovedModule *self, const gchar *module_name) { g_return_if_fail (MODULEMD_IS_IMPROVEDMODULE (self)); g_clear_pointer (&self->name, g_free); self->name = g_strdup (module_name); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_NAME]); } gchar * modulemd_improvedmodule_get_name (ModulemdImprovedModule *self) { return g_strdup (self->name); } const gchar * modulemd_improvedmodule_peek_name (ModulemdImprovedModule *self) { return self->name; } void modulemd_improvedmodule_set_defaults (ModulemdImprovedModule *self, ModulemdDefaults *defaults) { g_return_if_fail (MODULEMD_IS_IMPROVEDMODULE (self)); g_return_if_fail (!defaults || MODULEMD_IS_DEFAULTS (defaults)); /* Return without making any changes if the module names don't match. */ if (defaults && g_strcmp0 (modulemd_defaults_peek_module_name (defaults), modulemd_improvedmodule_peek_name (self))) { g_warning ("Attempting to assign defaults for module %s to module %s", modulemd_defaults_peek_module_name (defaults), modulemd_improvedmodule_peek_name (self)); return; } g_clear_pointer (&self->defaults, g_object_unref); if (defaults) { self->defaults = modulemd_defaults_copy (defaults); } g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_DEFAULTS]); } ModulemdDefaults * modulemd_improvedmodule_get_defaults (ModulemdImprovedModule *self) { return modulemd_defaults_copy (self->defaults); } ModulemdDefaults * modulemd_improvedmodule_peek_defaults (ModulemdImprovedModule *self) { return self->defaults; } void modulemd_improvedmodule_add_stream (ModulemdImprovedModule *self, ModulemdModuleStream *stream) { g_autofree gchar *stream_name = NULL; g_return_if_fail (MODULEMD_IS_IMPROVEDMODULE (self)); g_return_if_fail (MODULEMD_IS_MODULESTREAM (stream)); if (g_strcmp0 (self->name, modulemd_modulestream_peek_name (stream))) { /* This stream doesn't match this module. Ignore it */ return; } stream_name = modulemd_modulestream_get_stream (stream); if (!stream_name) { /* The stream name is usually filled in by the build system, so if we're * handling a user-edited libmodulemd file, just fill this field with * unique placeholder data. */ stream_name = g_strdup_printf ("__unknown_%d__", g_hash_table_size (self->streams)); } g_hash_table_replace (self->streams, g_strdup (stream_name), modulemd_modulestream_copy (stream)); } ModulemdModuleStream * modulemd_improvedmodule_get_stream_by_name (ModulemdImprovedModule *self, const gchar *stream_name) { g_return_val_if_fail (MODULEMD_IS_IMPROVEDMODULE (self), NULL); if (!g_hash_table_contains (self->streams, stream_name)) { return NULL; } return modulemd_modulestream_copy ( g_hash_table_lookup (self->streams, stream_name)); } GHashTable * modulemd_improvedmodule_get_streams (ModulemdImprovedModule *self) { g_return_val_if_fail (MODULEMD_IS_IMPROVEDMODULE (self), NULL); return g_hash_table_ref (self->streams); } ModulemdImprovedModule * modulemd_improvedmodule_copy (ModulemdImprovedModule *self) { GHashTableIter iter; gpointer key, value; ModulemdImprovedModule *new_module = NULL; if (!self) return NULL; new_module = modulemd_improvedmodule_new (modulemd_improvedmodule_peek_name (self)); /* Copy all of the streams */ g_hash_table_iter_init (&iter, self->streams); while (g_hash_table_iter_next (&iter, &key, &value)) { g_hash_table_replace ( new_module->streams, g_strdup ((const gchar *)key), modulemd_modulestream_copy ((MODULEMD_MODULESTREAM (value)))); } /* Copy the defaults data */ modulemd_improvedmodule_set_defaults ( new_module, modulemd_improvedmodule_peek_defaults (self)); return new_module; } static void modulemd_improvedmodule_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { ModulemdImprovedModule *self = MODULEMD_IMPROVEDMODULE (object); switch (prop_id) { case PROP_NAME: g_value_take_string (value, modulemd_improvedmodule_get_name (self)); break; case PROP_DEFAULTS: g_value_take_object (value, modulemd_improvedmodule_get_defaults (self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); } } static void modulemd_improvedmodule_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { ModulemdImprovedModule *self = MODULEMD_IMPROVEDMODULE (object); switch (prop_id) { case PROP_NAME: modulemd_improvedmodule_set_name (self, g_value_get_string (value)); break; case PROP_DEFAULTS: modulemd_improvedmodule_set_defaults (self, g_value_get_object (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); } } static void modulemd_improvedmodule_class_init (ModulemdImprovedModuleClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = modulemd_improvedmodule_finalize; object_class->get_property = modulemd_improvedmodule_get_property; object_class->set_property = modulemd_improvedmodule_set_property; properties[PROP_NAME] = g_param_spec_string ( "name", "Module Name", "The name of this module", NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS); properties[PROP_DEFAULTS] = g_param_spec_object ("defaults", "Module Defaults", "Object describing the default stream and profiles " "for this module.", MODULEMD_TYPE_DEFAULTS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties (object_class, N_PROPS, properties); } static void modulemd_improvedmodule_init (ModulemdImprovedModule *self) { self->streams = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); } GPtrArray * modulemd_improvedmodule_serialize (ModulemdImprovedModule *self) { g_autoptr (GPtrArray) objects = NULL; g_autoptr (GPtrArray) keys = NULL; ModulemdModuleStream *stream = NULL; ModulemdTranslation *translation = NULL; g_return_val_if_fail (MODULEMD_IS_IMPROVEDMODULE (self), NULL); /* First export all of the ModuleStream objects */ keys = _modulemd_ordered_str_keys (self->streams, _modulemd_strcmp_sort); /* Preallocate the array to hold the full set of streams, plus the defaults */ objects = g_ptr_array_new_full (keys->len + 1, g_object_unref); for (gsize i = 0; i < keys->len; i++) { stream = modulemd_improvedmodule_get_stream_by_name ( self, g_ptr_array_index (keys, i)); g_ptr_array_add (objects, stream); /* If there are translated strings associated with this stream, make sure * to include those. */ translation = modulemd_modulestream_get_translation (stream); if (translation) g_ptr_array_add (objects, translation); } /* Then write out the default object if it exists */ if (modulemd_improvedmodule_peek_defaults (self)) { g_ptr_array_add (objects, modulemd_improvedmodule_get_defaults (self)); } return g_ptr_array_ref (objects); } void modulemd_improvedmodule_dump (ModulemdImprovedModule *self, const gchar *yaml_file, GError **error) { g_autoptr (GPtrArray) objects = NULL; g_return_if_fail (MODULEMD_IS_IMPROVEDMODULE (self)); objects = modulemd_improvedmodule_serialize (self); if (!emit_yaml_file (objects, yaml_file, error)) { g_debug ("Error emitting YAML file: %s", (*error)->message); } } gchar * modulemd_improvedmodule_dumps (ModulemdImprovedModule *self, GError **error) { gchar *yaml = NULL; g_autoptr (GPtrArray) objects = NULL; objects = modulemd_improvedmodule_serialize (self); if (!emit_yaml_string (objects, &yaml, error)) { g_debug ("Error emitting YAML string: %s", (*error)->message); g_clear_pointer (&yaml, g_free); } return yaml; }
lubomir/libmodulemd
modulemd/v1/modulemd-yaml-parser-modulemd.c
<gh_stars>0 /* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #include "modulemd.h" #include <glib.h> #include <glib/gstdio.h> #include <yaml.h> #include <errno.h> #include "private/modulemd-private.h" #include "private/modulemd-yaml.h" #include "private/modulemd-util.h" enum ModulemdReqType { MODULEMD_REQ_REQUIRES, MODULEMD_REQ_BUILDREQUIRES }; #define _yaml_parser_modulemd_recurse_down(fn) \ do \ { \ if (!fn (modulestream, parser, error)) \ { \ goto error; \ } \ } \ while (0) static gboolean _parse_modulemd_data (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_licenses (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_xmd (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_deps (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_refs (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_profiles (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_profile (yaml_parser_t *parser, const gchar *name, ModulemdProfile **_profile, GError **error); static gboolean _parse_modulemd_api (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_filters (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_buildopts (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_rpm_buildopts (ModulemdBuildopts *buildopts, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_components (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_rpm_components (yaml_parser_t *parser, GHashTable **_components, GError **error); static gboolean _parse_modulemd_rpm_component (yaml_parser_t *parser, const gchar *name, ModulemdComponentRpm **_components, GError **error); static gboolean _parse_modulemd_modulestream_components (yaml_parser_t *parser, GHashTable **_components, GError **error); static gboolean _parse_modulemd_modulestream_component (yaml_parser_t *parser, const gchar *name, ModulemdComponentModule **_components, GError **error); static gboolean _parse_modulemd_artifacts (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_servicelevels (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_servicelevel (yaml_parser_t *parser, const gchar *name, ModulemdServiceLevel **_servicelevel, GError **error); gboolean _parse_module_stream (yaml_parser_t *parser, GObject **object, guint64 version, GError **error) { MMD_INIT_YAML_EVENT (event); MMD_INIT_YAML_EVENT (value_event); gboolean done = FALSE; gboolean result = FALSE; guint64 mdversion; g_autoptr (ModulemdModuleStream) modulestream = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_module_stream"); modulestream = modulemd_modulestream_new (); /* Use the pre-processed mdversion */ if (version && version <= MD_VERSION_LATEST) { modulemd_modulestream_set_mdversion (modulestream, version); } else { /* No mdversion was discovered during pre-processing */ MMD_YAML_ERROR_RETURN (error, "Unknown modulemd version"); } /* Parse until the end of this document */ while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the main document content. */ break; case YAML_MAPPING_END_EVENT: /* This is the end of the main document content. */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Handle "document: modulemd" */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "document")) { g_debug ("TRACE: root entry [document]"); YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT || g_strcmp0 ((const gchar *)value_event.data.scalar.value, "modulemd")) { MMD_YAML_ERROR_RETURN (error, "Unknown document type"); } yaml_event_delete (&value_event); } /* Record the modulemd version for the parser */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "version")) { g_debug ("TRACE: root entry [mdversion]"); YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Unknown modulemd version"); } mdversion = g_ascii_strtoull ( (const gchar *)value_event.data.scalar.value, NULL, 10); if (!mdversion) { MMD_YAML_ERROR_RETURN (error, "Unknown modulemd version"); } yaml_event_delete (&value_event); if (mdversion != version) { /* Preprocessing and real parser don't match! * This should be impossible */ MMD_YAML_ERROR_RETURN ( error, "ModuleMD version doesn't match preprocessing"); } modulemd_modulestream_set_mdversion (modulestream, mdversion); } /* Process the data section */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "data")) { g_debug ("TRACE: root entry [data]"); _yaml_parser_modulemd_recurse_down (_parse_modulemd_data); } else { g_debug ("Unexpected key in root: %s", (const gchar *)event.data.scalar.value); MMD_YAML_ERROR_RETURN (error, "Unexpected key in root"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in root"); break; } yaml_event_delete (&event); } result = TRUE; *object = g_object_ref ((GObject *)modulestream); error: g_debug ("TRACE: exiting _parse_module_stream"); return result; } static gboolean _parse_modulemd_data (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); MMD_INIT_YAML_EVENT (value_event); gboolean done = FALSE; guint64 version; GDate *eol = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_data"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the data content. */ break; case YAML_MAPPING_END_EVENT: /* This is the end of the data content. */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Module name */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "name")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse module name"); } modulemd_modulestream_set_name ( modulestream, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } /* Module stream */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "stream")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse module stream"); } modulemd_modulestream_set_stream ( modulestream, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } /* Module version */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "version")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse module version"); } version = g_ascii_strtoull ( (const gchar *)value_event.data.scalar.value, NULL, 10); if (!version) { MMD_YAML_ERROR_RETURN (error, "Unknown module version"); } modulemd_modulestream_set_version (modulestream, version); yaml_event_delete (&value_event); } /* Module Context */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "context")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse module context"); } modulemd_modulestream_set_context ( modulestream, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } /* Module Artifact Architecture */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "arch")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN ( error, "Failed to parse module artifact architecture"); } modulemd_modulestream_set_arch ( modulestream, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } /* Module summary */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "summary")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse module summary"); } modulemd_modulestream_set_summary ( modulestream, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } /* Module description */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "description")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse module description"); } modulemd_modulestream_set_description ( modulestream, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } /* Module EOL (obsolete) */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "eol")) { if (modulemd_modulestream_get_mdversion (modulestream) > MD_VERSION_1) { /* EOL is not supported in v2 or later; use servicelevel */ MMD_YAML_ERROR_RETURN ( error, "EOL is not supported in v2 or later; use servicelevel"); } /* Get the EOL date */ if (!_parse_modulemd_date (parser, &eol, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Failed to parse module EOL date"); } modulemd_modulestream_set_eol (modulestream, eol); g_date_free (eol); } /* Service Levels */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "servicelevels")) { _yaml_parser_modulemd_recurse_down ( _parse_modulemd_servicelevels); } /* licenses */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "license")) { /* Process the module and content licenses */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_licenses); } /* xmd */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "xmd")) { /* Process the extensible metadata block */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_xmd); } /* dependencies */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "dependencies")) { /* Process the build and runtime dependencies of this module */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_deps); } /* references */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "references")) { /* Process the reference links for this module */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_refs); } /* profiles */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "profiles")) { /* Process the install profiles for this module */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_profiles); } /* api */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "api")) { /* Process the API list */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_api); } /* filter */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "filter")) { /* Process the filtered-out output components */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_filters); } /* buildopts */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "buildopts")) { /* Process special build options for this module */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_buildopts); } /* Components */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "components")) { /* Process the components that comprise this module */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_components); } /* Artifacts */ else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "artifacts")) { /* Process the output artifacts of this module */ _yaml_parser_modulemd_recurse_down (_parse_modulemd_artifacts); } else { g_debug ("Unexpected key in data: %s", (const gchar *)event.data.scalar.value); MMD_YAML_ERROR_RETURN (error, "Unexpected key in data"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in data"); break; } yaml_event_delete (&event); } result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_data"); return result; } static gboolean _parse_modulemd_licenses (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { MMD_INIT_YAML_EVENT (event); gboolean result = FALSE; gboolean done = FALSE; ModulemdSimpleSet *set = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_licenses"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the license content. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the license content */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Each scalar event represents a license type */ if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Invalid sequence"); } if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "module")) { modulemd_modulestream_set_module_licenses (modulestream, set); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "content")) { modulemd_modulestream_set_content_licenses (modulestream, set); } else { MMD_YAML_ERROR_RETURN (error, "Unknown license type"); } g_clear_pointer (&set, g_object_unref); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in licenses"); break; } yaml_event_delete (&event); } result = TRUE; error: g_clear_pointer (&set, g_object_unref); g_debug ("TRACE: exiting _parse_modulemd_licenses"); return result; } static gboolean _parse_modulemd_xmd (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; g_autoptr (GHashTable) xmd = NULL; MMD_INIT_YAML_EVENT (event); g_autoptr (GVariant) variant = NULL; GVariantIter iter; gchar *key; GVariant *value; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_xmd"); YAML_PARSER_PARSE_WITH_ERROR_RETURN (parser, &event, error, "Parser error"); if (!(event.type == YAML_MAPPING_START_EVENT)) { MMD_YAML_ERROR_RETURN (error, "Invalid mapping"); } yaml_event_delete (&event); if (!parse_raw_yaml_mapping (parser, &variant, error)) { MMD_YAML_ERROR_RETURN (error, "Invalid raw mapping"); } if (!g_variant_is_of_type (variant, G_VARIANT_TYPE_DICTIONARY)) { MMD_YAML_ERROR_RETURN (error, "XMD wasn't a dictionary"); } xmd = g_hash_table_new_full ( g_str_hash, g_str_equal, g_free, modulemd_variant_unref); g_variant_iter_init (&iter, variant); while (g_variant_iter_next (&iter, "{sv}", &key, &value)) { g_hash_table_insert (xmd, g_strdup (key), value); g_free (key); } /* Save this hash table as the xmd property */ modulemd_modulestream_set_xmd (modulestream, xmd); result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_xmd"); return result; } static gboolean _parse_modulemd_deps_v1 (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; GHashTable *reqs = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_deps_v1"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the dependency content. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the dependency content */ done = TRUE; break; case YAML_SCALAR_EVENT: if (!_hashtable_from_mapping (parser, &reqs, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Invalid mapping"); } if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "buildrequires")) { modulemd_modulestream_set_buildrequires (modulestream, reqs); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "requires")) { modulemd_modulestream_set_requires (modulestream, reqs); } else { MMD_YAML_ERROR_RETURN (error, "Unknown dependency type"); } g_clear_pointer (&reqs, g_hash_table_unref); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in deps"); break; } yaml_event_delete (&event); } result = TRUE; error: g_clear_pointer (&reqs, g_hash_table_unref); g_debug ("TRACE: exiting _parse_modulemd_deps_v1"); return result; } static gboolean _parse_modulemd_v2_dep (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error); static gboolean _parse_modulemd_deps_v2 (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_deps_v2"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_SEQUENCE_START_EVENT: /* This is the start of the dependency content. */ break; case YAML_SEQUENCE_END_EVENT: /* We're done processing the dependency content */ done = TRUE; break; case YAML_MAPPING_START_EVENT: if (!_parse_modulemd_v2_dep (modulestream, parser, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Failed to parse requires/buildrequires"); break; } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in deps"); break; } yaml_event_delete (&event); } result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_deps_v2"); return result; } static gboolean _parse_modulemd_v2_dep_map (ModulemdModuleStream *modulestream, yaml_parser_t *parser, enum ModulemdReqType reqtype, ModulemdDependencies *dep, GError **error); static gboolean _parse_modulemd_v2_dep (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; gboolean done = FALSE; MMD_INIT_YAML_EVENT (event); enum ModulemdReqType reqtype; g_autoptr (ModulemdDependencies) dep = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_v2_dep"); dep = modulemd_dependencies_new (); if (dep == NULL) { event.type = YAML_NO_EVENT; MMD_YAML_ERROR_RETURN ( error, "Could not allocate new Modulemd.Dependencies object"); } while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_END_EVENT: /* We've processed the whole map */ done = TRUE; break; case YAML_SCALAR_EVENT: if (g_strcmp0 ((const gchar *)event.data.scalar.value, "buildrequires") == 0) { reqtype = MODULEMD_REQ_BUILDREQUIRES; } else if (g_strcmp0 ((const gchar *)event.data.scalar.value, "requires") == 0) { reqtype = MODULEMD_REQ_REQUIRES; } else { MMD_YAML_ERROR_RETURN (error, "Dependency map had key other than " "'requires' or 'buildrequires'"); } if (!_parse_modulemd_v2_dep_map ( modulestream, parser, reqtype, dep, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Error processing dependency map."); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in v2_dep"); break; } yaml_event_delete (&event); } modulemd_modulestream_add_dependencies (modulestream, dep); result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_v2_dep"); return result; } static gboolean _parse_modulemd_v2_dep_map (ModulemdModuleStream *modulestream, yaml_parser_t *parser, enum ModulemdReqType reqtype, ModulemdDependencies *dep, GError **error) { gboolean result = FALSE; gboolean done = FALSE; gboolean in_map = FALSE; MMD_INIT_YAML_EVENT (event); gchar *module_name = NULL; ModulemdSimpleSet *set = NULL; const gchar **dep_set = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_v2_dep_map"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* Start processing the available modules and streams */ in_map = TRUE; break; case YAML_MAPPING_END_EVENT: /* We've received them all */ done = TRUE; in_map = FALSE; break; case YAML_SCALAR_EVENT: if (!in_map) { MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in v2_dep_map"); } module_name = g_strdup ((const gchar *)event.data.scalar.value); if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Could not parse set of streams"); } dep_set = (const gchar **)modulemd_simpleset_dup (set); switch (reqtype) { case MODULEMD_REQ_BUILDREQUIRES: modulemd_dependencies_add_buildrequires ( dep, module_name, dep_set); break; case MODULEMD_REQ_REQUIRES: modulemd_dependencies_add_requires (dep, module_name, dep_set); break; } g_clear_pointer (&module_name, g_free); for (gsize i = 0; i < modulemd_simpleset_size (set); i++) { g_clear_pointer (&dep_set[i], g_free); } g_clear_pointer (&dep_set, g_free); g_clear_pointer (&set, g_object_unref); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in v2_dep_map"); break; } yaml_event_delete (&event); } result = TRUE; error: g_clear_pointer (&module_name, g_free); g_debug ("TRACE: exiting _parse_modulemd_v2_dep_map"); return result; } static gboolean _parse_modulemd_deps (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_deps"); if (modulemd_modulestream_get_mdversion (modulestream) == MD_VERSION_1) { result = _parse_modulemd_deps_v1 (modulestream, parser, error); goto error; } else if (modulemd_modulestream_get_mdversion (modulestream) >= MD_VERSION_2) { result = _parse_modulemd_deps_v2 (modulestream, parser, error); goto error; } else { MMD_YAML_NOEVENT_ERROR_RETURN (error, "Incompatible modulemd version"); } error: g_debug ("TRACE: exiting _parse_modulemd_deps"); return result; } static gboolean _parse_modulemd_refs (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; GHashTable *refs = NULL; gpointer value; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_refs"); if (!_hashtable_from_mapping (parser, &refs, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Invalid mapping"); } if ((value = g_hash_table_lookup (refs, "community"))) { modulemd_modulestream_set_community (modulestream, (const gchar *)value); g_hash_table_remove (refs, "community"); } if ((value = g_hash_table_lookup (refs, "documentation"))) { modulemd_modulestream_set_documentation (modulestream, (const gchar *)value); g_hash_table_remove (refs, "documentation"); } if ((value = g_hash_table_lookup (refs, "tracker"))) { modulemd_modulestream_set_tracker (modulestream, (const gchar *)value); g_hash_table_remove (refs, "tracker"); } /* Make sure there were no other entries */ if (g_hash_table_size (refs) > 0) { MMD_YAML_ERROR_RETURN (error, "Unexpected key found in references."); } result = TRUE; error: g_clear_pointer (&refs, g_hash_table_unref); g_debug ("TRACE: exiting _parse_modulemd_refs"); return result; } static gboolean _parse_modulemd_profiles (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; GHashTable *profiles = NULL; gchar *name = NULL; ModulemdProfile *profile = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_profiles"); profiles = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the profiles. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the profiles */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Each entry is the key for a dictionary of ModulemdProfile * objects */ name = g_strdup ((const gchar *)event.data.scalar.value); if (!_parse_modulemd_profile (parser, name, &profile, error)) { g_free (name); MMD_YAML_ERROR_RETURN_RETHROW (error, "Invalid profile"); } g_hash_table_insert (profiles, name, profile); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in profiles"); break; } yaml_event_delete (&event); } modulemd_modulestream_set_profiles (modulestream, profiles); result = TRUE; error: g_hash_table_unref (profiles); g_debug ("TRACE: exiting _parse_modulemd_profiles"); return result; } static gboolean _parse_modulemd_profile (yaml_parser_t *parser, const gchar *name, ModulemdProfile **_profile, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); MMD_INIT_YAML_EVENT (value_event); gboolean done = FALSE; ModulemdSimpleSet *set = NULL; ModulemdProfile *profile = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_profile"); profile = modulemd_profile_new (); modulemd_profile_set_name (profile, name); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the profile content. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the profile content */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Each entry must be one of "rpms" or "description" */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rpms")) { /* Get the set of RPMs */ if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Could not parse profile RPMs"); } modulemd_profile_set_rpms (profile, set); g_object_unref (set); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "description")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "No value for description"); } modulemd_profile_set_description ( profile, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else { /* Unknown field in profile */ MMD_YAML_ERROR_RETURN (error, "Unknown key in profile body"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in profiles"); break; } yaml_event_delete (&event); } *_profile = g_object_ref (profile); result = TRUE; error: g_object_unref (profile); g_debug ("TRACE: exiting _parse_modulemd_profile"); return result; } static gboolean _parse_modulemd_api (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; ModulemdSimpleSet *set = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_api"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the API. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the API */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Currently, we only support "rpms" here */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rpms")) { if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Parse error in API"); } modulemd_modulestream_set_rpm_api (modulestream, set); } else { MMD_YAML_ERROR_RETURN (error, "Unknown API type"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in api"); break; } yaml_event_delete (&event); } result = TRUE; error: g_object_unref (set); g_debug ("TRACE: exiting _parse_modulemd_api"); return result; } static gboolean _parse_modulemd_filters (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; ModulemdSimpleSet *set = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_filters"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the filters. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the filters */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Currently, we only support "rpms" here */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rpms")) { if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Parse error in filters"); } modulemd_modulestream_set_rpm_filter (modulestream, set); } else { MMD_YAML_ERROR_RETURN (error, "Unknown filter type"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in filters"); break; } yaml_event_delete (&event); } result = TRUE; error: g_clear_pointer (&set, g_object_unref); g_debug ("TRACE: exiting _parse_modulemd_filters"); return result; } static gboolean _parse_modulemd_buildopts (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; g_autoptr (ModulemdBuildopts) buildopts = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_buildopts"); buildopts = modulemd_buildopts_new (); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the buildopts. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the buildopts */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Currently, we only support "rpms" here */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rpms")) { if (!_parse_modulemd_rpm_buildopts (buildopts, parser, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Parse error in RPM buildopts"); } } else { MMD_YAML_ERROR_RETURN (error, "Unknown buildopt type"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in buildopts"); break; } yaml_event_delete (&event); } modulemd_modulestream_set_buildopts (modulestream, buildopts); result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_buildopts"); return result; } static gboolean _parse_modulemd_rpm_buildopts (ModulemdBuildopts *buildopts, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); MMD_INIT_YAML_EVENT (value_event); gboolean done = FALSE; gboolean in_mapping = FALSE; g_autoptr (ModulemdSimpleSet) set = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_rpm_buildopts"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the RPM buildopts. */ in_mapping = TRUE; break; case YAML_MAPPING_END_EVENT: /* We're done processing the RPM buildopts */ done = TRUE; break; case YAML_SCALAR_EVENT: if (!in_mapping) { MMD_YAML_ERROR_RETURN ( error, "Received a scalar when a map was expected."); break; } if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "macros")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse RPM macros"); } modulemd_buildopts_set_rpm_macros ( buildopts, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "whitelist")) { if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Parse error in RPM whitelist"); } modulemd_buildopts_set_rpm_whitelist_simpleset (buildopts, set); } else { MMD_YAML_ERROR_RETURN (error, "Unknown RPM buildopt key"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in RPM buildopts"); break; } yaml_event_delete (&event); } result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_rpm_buildopts"); return result; } static gboolean _parse_modulemd_components (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; GHashTable *components = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_components"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the component content. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the component content */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Each key is a type of component */ g_debug ("Component type: %s", (const gchar *)event.data.scalar.value); if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rpms")) { if (!_parse_modulemd_rpm_components (parser, &components, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Could not parse RPM components"); } modulemd_modulestream_set_rpm_components (modulestream, components); g_hash_table_unref (components); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "modules")) { if (!_parse_modulemd_modulestream_components ( parser, &components, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Could not parse module components"); } modulemd_modulestream_set_module_components (modulestream, components); g_hash_table_unref (components); } else { MMD_YAML_ERROR_RETURN (error, "Unknown component type"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in components"); break; } yaml_event_delete (&event); } result = TRUE; error: g_debug ("TRACE: exiting _parse_modulemd_components"); return result; } static gboolean _parse_modulemd_rpm_components (yaml_parser_t *parser, GHashTable **_components, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; GHashTable *components = NULL; gchar *name = NULL; ModulemdComponentRpm *component = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_rpm_components"); components = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* The dictionary has begun */ break; case YAML_MAPPING_END_EVENT: /* We've processed the whole dictionary */ done = TRUE; break; case YAML_SCALAR_EVENT: name = g_strdup ((const gchar *)event.data.scalar.value); if (!_parse_modulemd_rpm_component (parser, name, &component, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Parse error in RPM component"); } /* Set this key and value to the hash table */ g_hash_table_insert (components, name, component); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in sequence"); break; } yaml_event_delete (&event); } *_components = g_hash_table_ref (components); result = TRUE; error: g_hash_table_unref (components); g_debug ("TRACE: exiting _parse_modulemd_rpm_components"); return result; } static gboolean _parse_modulemd_rpm_component (yaml_parser_t *parser, const gchar *name, ModulemdComponentRpm **_component, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); MMD_INIT_YAML_EVENT (value_event); gboolean done = FALSE; ModulemdComponentRpm *component = NULL; ModulemdSimpleSet *set = NULL; guint64 buildorder = 0; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_rpm_component"); component = modulemd_component_rpm_new (); modulemd_component_set_name (MODULEMD_COMPONENT (component), name); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* The dictionary has begun */ break; case YAML_MAPPING_END_EVENT: /* We've processed the whole dictionary */ done = TRUE; break; case YAML_SCALAR_EVENT: if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "buildorder")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse buildorder value"); } buildorder = g_ascii_strtoull ( (const gchar *)value_event.data.scalar.value, NULL, 10); modulemd_component_set_buildorder ( MODULEMD_COMPONENT (component), buildorder); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rationale")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse rationale value"); } modulemd_component_set_rationale ( MODULEMD_COMPONENT (component), (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "arches")) { if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Error parsing component arches"); } modulemd_component_rpm_set_arches (component, set); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "cache")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse cache value"); } modulemd_component_rpm_set_cache ( component, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "multilib")) { if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Error parsing multilib arches"); } modulemd_component_rpm_set_multilib (component, set); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "ref")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse ref value"); } modulemd_component_rpm_set_ref ( component, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "repository")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse repository value"); } modulemd_component_rpm_set_repository ( component, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else { MMD_YAML_ERROR_RETURN (error, "Unexpected key in component"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in component"); break; } g_clear_pointer (&set, g_object_unref); yaml_event_delete (&event); } *_component = g_object_ref (component); result = TRUE; error: g_object_unref (component); g_debug ("TRACE: exiting _parse_modulemd_modulestream_components"); return result; } static gboolean _parse_modulemd_modulestream_components (yaml_parser_t *parser, GHashTable **_components, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; GHashTable *components = NULL; gchar *name = NULL; ModulemdComponentModule *component = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_modulestream_components"); components = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* The dictionary has begun */ break; case YAML_MAPPING_END_EVENT: /* We've processed the whole dictionary */ done = TRUE; break; case YAML_SCALAR_EVENT: name = g_strdup ((const gchar *)event.data.scalar.value); if (!_parse_modulemd_modulestream_component ( parser, name, &component, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Parse error in module component"); } /* Set this key and value to the hash table */ g_hash_table_insert (components, name, component); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in sequence"); break; } yaml_event_delete (&event); } *_components = g_hash_table_ref (components); result = TRUE; error: g_hash_table_unref (components); g_debug ("TRACE: exiting _parse_modulemd_modulestream_components"); return result; } static gboolean _parse_modulemd_modulestream_component (yaml_parser_t *parser, const gchar *name, ModulemdComponentModule **_component, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); MMD_INIT_YAML_EVENT (value_event); gboolean done = FALSE; ModulemdComponentModule *component = NULL; guint64 buildorder = 0; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_rpm_component"); component = modulemd_component_module_new (); modulemd_component_set_name (MODULEMD_COMPONENT (component), name); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* The dictionary has begun */ break; case YAML_MAPPING_END_EVENT: /* We've processed the whole dictionary */ done = TRUE; break; case YAML_SCALAR_EVENT: if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "buildorder")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse buildorder value"); } buildorder = g_ascii_strtoull ( (const gchar *)value_event.data.scalar.value, NULL, 10); modulemd_component_set_buildorder ( MODULEMD_COMPONENT (component), buildorder); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rationale")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse rationale value"); } modulemd_component_set_rationale ( MODULEMD_COMPONENT (component), (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "ref")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse ref value"); } modulemd_component_module_set_ref ( component, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "repository")) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &value_event, error, "Parser error"); if (value_event.type != YAML_SCALAR_EVENT) { MMD_YAML_ERROR_RETURN (error, "Failed to parse repository value"); } modulemd_component_module_set_repository ( component, (const gchar *)value_event.data.scalar.value); yaml_event_delete (&value_event); } else { MMD_YAML_ERROR_RETURN (error, "Unexpected key in component"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in component"); break; } yaml_event_delete (&event); } *_component = g_object_ref (component); result = TRUE; error: g_object_unref (component); g_debug ("TRACE: exiting _parse_modulemd_modulestream_component"); return result; } static gboolean _parse_modulemd_artifacts (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; ModulemdSimpleSet *set = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_artifacts"); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the artifacts. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the artifacts */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Currently, we only support "rpms" here */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "rpms")) { if (!_simpleset_from_sequence (parser, &set, error)) { MMD_YAML_ERROR_RETURN_RETHROW (error, "Parse error in artifacts"); } if (!modulemd_simpleset_validate_contents ( set, modulemd_validate_nevra, NULL)) { MMD_YAML_ERROR_RETURN (error, "RPM artifacts not in NEVRA format"); } modulemd_modulestream_set_rpm_artifacts (modulestream, set); } else { MMD_YAML_ERROR_RETURN (error, "Unknown artifact type"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in artifacts"); break; } yaml_event_delete (&event); } result = TRUE; error: g_object_unref (set); g_debug ("TRACE: exiting _parse_modulemd_artifacts"); return result; } static gboolean _parse_modulemd_servicelevels (ModulemdModuleStream *modulestream, yaml_parser_t *parser, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; GHashTable *servicelevels = NULL; gchar *name = NULL; ModulemdServiceLevel *sl = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_servicelevels"); servicelevels = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the service levels. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the service levels. */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Each entry is the key for a dictionary of ModulemdServiceLevel * objects */ name = g_strdup ((const gchar *)event.data.scalar.value); if (!_parse_modulemd_servicelevel (parser, name, &sl, error)) { g_free (name); MMD_YAML_ERROR_RETURN_RETHROW (error, "Invalid service level"); } g_hash_table_insert (servicelevels, name, sl); break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in service levels"); break; } yaml_event_delete (&event); } modulemd_modulestream_set_servicelevels (modulestream, servicelevels); result = TRUE; error: g_hash_table_unref (servicelevels); g_debug ("TRACE: exiting _parse_modulemd_servicelevels"); return result; } static gboolean _parse_modulemd_servicelevel (yaml_parser_t *parser, const gchar *name, ModulemdServiceLevel **_servicelevel, GError **error) { gboolean result = FALSE; MMD_INIT_YAML_EVENT (event); gboolean done = FALSE; ModulemdServiceLevel *sl = NULL; GDate *eol = NULL; g_return_val_if_fail (error == NULL || *error == NULL, FALSE); g_debug ("TRACE: entering _parse_modulemd_servicelevel"); sl = modulemd_servicelevel_new (); modulemd_servicelevel_set_name (sl, name); while (!done) { YAML_PARSER_PARSE_WITH_ERROR_RETURN ( parser, &event, error, "Parser error"); switch (event.type) { case YAML_MAPPING_START_EVENT: /* This is the start of the service level content. */ break; case YAML_MAPPING_END_EVENT: /* We're done processing the service level content */ done = TRUE; break; case YAML_SCALAR_EVENT: /* Only "eol" is supported right now */ if (!g_strcmp0 ((const gchar *)event.data.scalar.value, "eol")) { /* Get the EOL date */ if (!_parse_modulemd_date (parser, &eol, error)) { MMD_YAML_ERROR_RETURN_RETHROW ( error, "Failed to parse EOL date in service level"); } modulemd_servicelevel_set_eol (sl, eol); g_date_free (eol); } else { /* Unknown field in service level */ MMD_YAML_ERROR_RETURN (error, "Unknown key in service level body"); } break; default: /* We received a YAML event we shouldn't expect at this level */ MMD_YAML_ERROR_RETURN (error, "Unexpected YAML event in service level"); break; } yaml_event_delete (&event); } *_servicelevel = g_object_ref (sl); result = TRUE; error: g_object_unref (sl); g_debug ("TRACE: exiting _parse_modulemd_servicelevel"); return result; }
lubomir/libmodulemd
modulemd/v1/tests/test-modulemd-yaml.c
/* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #define MMD_DISABLE_DEPRECATION_WARNINGS 1 #include "modulemd.h" #include "private/modulemd-yaml.h" #include "private/modulemd-util.h" #include <glib.h> #include <glib/gstdio.h> #include <locale.h> typedef struct _YamlFixture { } YamlFixture; static void modulemd_yaml_set_up (YamlFixture *fixture, gconstpointer user_data) { } static void modulemd_yaml_tear_down (YamlFixture *fixture, gconstpointer user_data) { } static void modulemd_yaml_test_parse_v1_file (YamlFixture *fixture, gconstpointer user_data) { gboolean result; GError *error = NULL; ModulemdModule **modules = NULL; GPtrArray *data = NULL; ModulemdSimpleSet *set = NULL; gchar *yaml_path = NULL; yaml_path = g_strdup_printf ("%s/test_data/good-v1.yaml", g_getenv ("MESON_SOURCE_ROOT")); result = parse_yaml_file (yaml_path, &data, NULL, &error); g_clear_pointer (&yaml_path, g_free); g_assert_true (result); modules = mmd_yaml_dup_modules (data); if (!modules) { fprintf (stderr, "Failed to parse: %s\n", error->message); g_clear_pointer (&error, g_error_free); } g_assert_nonnull (modules); g_assert_nonnull (modules[0]); g_assert_null (modules[1]); g_assert_cmpuint (modulemd_module_get_mdversion (modules[0]), ==, 1); g_assert_cmpstr (modulemd_module_get_name (modules[0]), ==, "foo"); g_assert_cmpstr (modulemd_module_get_stream (modules[0]), ==, "stream-name"); g_assert_cmpstr ( modulemd_module_get_summary (modules[0]), ==, "An example module"); set = modulemd_module_get_rpm_artifacts (modules[0]); g_assert_true (set); g_assert_true ( modulemd_simpleset_contains (set, "bar-0:1.23-1.module_deadbeef.x86_64")); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_clear_pointer (&modules, g_free); g_clear_pointer (&data, g_ptr_array_unref); yaml_path = g_strdup_printf ("%s/test_data/bad-document.yaml", g_getenv ("MESON_SOURCE_ROOT")); result = parse_yaml_file (yaml_path, &data, NULL, &error); g_clear_pointer (&yaml_path, g_free); g_assert_true (result); g_assert_null (error); g_assert_nonnull (data); g_assert_cmpuint (data->len, ==, 0); g_clear_pointer (&data, g_ptr_array_unref); /* Validate the official reference YAML */ g_info ("Reference YAML v1"); yaml_path = g_strdup_printf ("%s/spec.v1.yaml", g_getenv ("MESON_SOURCE_ROOT")); result = parse_yaml_file (yaml_path, &data, NULL, &error); g_free (yaml_path); g_assert_true (result); modules = mmd_yaml_dup_modules (data); g_assert_nonnull (modules); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_clear_pointer (&modules, g_free); g_clear_pointer (&data, g_ptr_array_unref); } static void modulemd_yaml_test_v1_load (YamlFixture *fixture, gconstpointer user_data) { ModulemdModule *module = NULL; ModulemdModule *copy = NULL; ModulemdModule **modules = NULL; gchar *yaml_path = NULL; GHashTable *buildrequires = NULL; gchar *value = NULL; yaml_path = g_strdup_printf ("%s/test_data/good-v1.yaml", g_getenv ("MESON_SOURCE_ROOT")); module = modulemd_module_new_from_file (yaml_path); g_assert_true (module); buildrequires = modulemd_module_get_buildrequires (module); g_assert_true (buildrequires); value = g_hash_table_lookup (buildrequires, "platform"); g_assert_cmpstr (value, ==, "and-its-stream-name"); /* Copy this module */ copy = modulemd_module_copy (module); g_assert_nonnull (copy); g_assert_cmpuint (modulemd_module_peek_mdversion (copy), ==, 1); g_object_unref (copy); g_object_unref (module); modulemd_module_new_all_from_file (yaml_path, &modules); g_clear_pointer (&yaml_path, g_free); g_assert_true (modules); g_assert_true (modules[0]); buildrequires = modulemd_module_get_buildrequires (modules[0]); g_assert_true (buildrequires); value = g_hash_table_lookup (buildrequires, "platform"); g_assert_cmpstr (value, ==, "and-its-stream-name"); /* Copy this module */ copy = modulemd_module_copy (modules[0]); g_assert_nonnull (copy); g_assert_cmpuint (modulemd_module_peek_mdversion (copy), ==, 1); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_free (modules); g_clear_pointer (&copy, g_object_unref); } static void modulemd_yaml_test_v2_load (YamlFixture *fixture, gconstpointer user_data) { gboolean result; ModulemdModule *module = NULL; ModulemdModule *copy = NULL; ModulemdModule **modules = NULL; GPtrArray *data = NULL; gchar *yaml_path = NULL; GError *error = NULL; yaml_path = g_strdup_printf ("%s/test_data/good-v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); module = modulemd_module_new_from_file (yaml_path); g_assert_true (module); g_object_unref (module); modulemd_module_new_all_from_file (yaml_path, &modules); g_assert_nonnull (modules); g_assert_nonnull (modules[0]); g_assert_nonnull (modules[1]); g_assert_nonnull (modules[2]); g_assert_null (modules[3]); /* Copy this module */ copy = modulemd_module_copy (modules[0]); g_assert_nonnull (copy); g_assert_cmpuint (modulemd_module_peek_mdversion (copy), ==, 2); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_clear_pointer (&modules, g_free); g_free (yaml_path); yaml_path = g_strdup_printf ("%s/test_data/mixed-v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); modulemd_module_new_all_from_file (yaml_path, &modules); g_assert_nonnull (modules); g_assert_nonnull (modules[0]); g_assert_nonnull (modules[1]); g_assert_null (modules[2]); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_free (modules); g_free (yaml_path); /* Validate the official reference YAML */ g_info ("Reference YAML v2"); yaml_path = g_strdup_printf ("%s/spec.v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); result = parse_yaml_file (yaml_path, &data, NULL, &error); g_free (yaml_path); g_assert_true (result); modules = mmd_yaml_dup_modules (data); g_assert_nonnull (modules); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_free (modules); g_clear_pointer (&data, g_ptr_array_unref); g_clear_pointer (&copy, g_object_unref); } static void modulemd_yaml_test_emit_v1_string (YamlFixture *fixture, gconstpointer user_data) { gchar *yaml = NULL; gchar *yaml2 = NULL; gboolean result; GError *error = NULL; GPtrArray *modules = NULL; GPtrArray *reloaded_modules = NULL; gchar *yaml_path = NULL; yaml_path = g_strdup_printf ("%s/test_data/good-v1.yaml", g_getenv ("MESON_SOURCE_ROOT")); modulemd_module_new_all_from_file_ext (yaml_path, &modules); g_clear_pointer (&yaml_path, g_free); result = emit_yaml_string (modules, &yaml, &error); g_assert_true (result); g_assert_true (yaml); g_debug ("YAML:\n%s", yaml); /* Load this string and emit it again. It must produce the same output. */ modulemd_module_new_all_from_string_ext (yaml, &reloaded_modules); result = emit_yaml_string (modules, &yaml2, &error); g_assert_true (result); g_assert_true (yaml2); g_assert_cmpstr (yaml, ==, yaml2); g_clear_pointer (&yaml, g_free); g_clear_pointer (&yaml2, g_free); g_ptr_array_unref (modules); g_ptr_array_unref (reloaded_modules); } static void modulemd_yaml_test_emit_v2_string (YamlFixture *fixture, gconstpointer user_data) { gchar *yaml = NULL; gchar *yaml2 = NULL; gboolean result; GError *error = NULL; GPtrArray *modules = NULL; GPtrArray *reloaded_modules = NULL; gchar *yaml_path = NULL; yaml_path = g_strdup_printf ("%s/test_data/good-v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); modulemd_module_new_all_from_file_ext (yaml_path, &modules); g_clear_pointer (&yaml_path, g_free); result = emit_yaml_string (modules, &yaml, &error); g_assert_true (result); g_assert_nonnull (yaml); g_debug ("YAML:\n%s", yaml); /* Emit the same string again to confirm that we haven't screwed up any of * the memory management. */ result = emit_yaml_string (modules, &yaml2, &error); g_assert_true (result); g_assert_nonnull (yaml2); g_assert_cmpstr (yaml, ==, yaml2); g_clear_pointer (&yaml2, g_free); /* Load this string and emit it again. It must produce the same output. */ modulemd_module_new_all_from_string_ext (yaml, &reloaded_modules); result = emit_yaml_string (reloaded_modules, &yaml2, &error); g_assert_true (result); g_assert_nonnull (yaml2); g_assert_cmpstr (yaml, ==, yaml2); g_clear_pointer (&yaml, g_free); g_clear_pointer (&yaml2, g_free); g_ptr_array_unref (modules); g_ptr_array_unref (reloaded_modules); } static void modulemd_yaml_test_v2_stream (YamlFixture *fixture, gconstpointer user_data) { gboolean result; ModulemdModule *module = NULL; ModulemdModule *copy = NULL; ModulemdModule **modules = NULL; GPtrArray *data = NULL; gchar *yaml_path = NULL; GError *error = NULL; FILE *stream = NULL; yaml_path = g_strdup_printf ("%s/test_data/good-v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); stream = g_fopen (yaml_path, "rb"); g_assert_nonnull (stream); module = modulemd_module_new_from_stream (stream, &error); g_assert_true (module); g_assert_null (error); g_object_unref (module); modulemd_module_new_all_from_file (yaml_path, &modules); g_assert_nonnull (modules); g_assert_nonnull (modules[0]); g_assert_nonnull (modules[1]); g_assert_nonnull (modules[2]); g_assert_null (modules[3]); /* Copy this module */ copy = modulemd_module_copy (modules[0]); g_assert_nonnull (copy); g_assert_cmpuint (modulemd_module_peek_mdversion (copy), ==, 2); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_clear_pointer (&modules, g_free); g_free (yaml_path); yaml_path = g_strdup_printf ("%s/test_data/mixed-v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); modulemd_module_new_all_from_file (yaml_path, &modules); g_assert_nonnull (modules); g_assert_nonnull (modules[0]); g_assert_nonnull (modules[1]); g_assert_null (modules[2]); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_free (modules); g_free (yaml_path); /* Validate the official reference YAML */ g_info ("Reference YAML v2"); yaml_path = g_strdup_printf ("%s/spec.v2.yaml", g_getenv ("MESON_SOURCE_ROOT")); result = parse_yaml_file (yaml_path, &data, NULL, &error); g_free (yaml_path); g_assert_true (result); modules = mmd_yaml_dup_modules (data); g_assert_nonnull (modules); for (gsize i = 0; modules[i]; i++) { g_object_unref (modules[i]); } g_free (modules); g_clear_pointer (&data, g_ptr_array_unref); g_clear_pointer (&copy, g_object_unref); } static void modulemd_yaml_test_validate_nevra (YamlFixture *fixture, gconstpointer user_data) { const gchar *good = "nodejs-devel-1:8.10.0-3.module_1572+d7ec111e.x86_64"; const gchar *garbage = "DEADBEEF"; const gchar *garbage2 = "DEAD.BEEF"; const gchar *garbage3 = "MORE-DEAD.BEEF"; const gchar *missing_epoch = "nodejs-devel-8.10.0-3.module_1572+d7ec111e.x86_64"; const gchar *nonint_epoch = "nodejs-devel-FOO:8.10.0-3.module_1572+d7ec111e.x86_64"; g_assert_true (modulemd_validate_nevra (good)); g_assert_false (modulemd_validate_nevra (garbage)); g_assert_false (modulemd_validate_nevra (garbage2)); g_assert_false (modulemd_validate_nevra (garbage3)); g_assert_false (modulemd_validate_nevra (missing_epoch)); g_assert_false (modulemd_validate_nevra (nonint_epoch)); } static void modulemd_yaml_test_artifact_validation (YamlFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_path = NULL; g_autoptr (GPtrArray) objects = NULL; g_autoptr (GPtrArray) failures = NULL; g_autoptr (GError) error = NULL; /* Attempt to read in a modulemd with a data.artifacts.rpm section * containing values without the Epoch included. */ yaml_path = g_strdup_printf ("%s/test_data/issue46.yaml", g_getenv ("MESON_SOURCE_ROOT")); objects = modulemd_objects_from_file_ext (yaml_path, &failures, &error); g_assert_nonnull (objects); g_assert_cmpint (objects->len, ==, 0); g_assert_null (error); g_assert_nonnull (failures); g_assert_cmpint (failures->len, ==, 1); g_assert_cmpstr ( modulemd_subdocument_get_gerror (g_ptr_array_index (failures, 0))->message, ==, "RPM artifacts not in NEVRA format"); } static void modulemd_yaml_test_index_from_file (YamlFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_path = NULL; g_autoptr (GHashTable) module_index = NULL; g_autoptr (GPtrArray) failures = NULL; g_autoptr (GError) error = NULL; ModulemdImprovedModule *module = NULL; yaml_path = g_strdup_printf ("%s/test_data/long-valid.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); module_index = parse_module_index_from_file (yaml_path, &failures, &error); g_assert_nonnull (module_index); g_assert_true (g_hash_table_contains (module_index, "nodejs")); module = g_hash_table_lookup (module_index, "nodejs"); g_assert_nonnull (module); g_assert_true (MODULEMD_IS_IMPROVEDMODULE (module)); g_assert_cmpstr (modulemd_improvedmodule_peek_name (module), ==, "nodejs"); g_assert_nonnull (modulemd_improvedmodule_peek_defaults (module)); } static void modulemd_yaml_test_index_from_string (YamlFixture *fixture, gconstpointer user_data) { const gchar *yaml_string = NULL; g_autoptr (GHashTable) module_index = NULL; g_autoptr (GPtrArray) failures = NULL; g_autoptr (GError) error = NULL; ModulemdImprovedModule *module = NULL; yaml_string = "document: modulemd\nversion: 2\ndata:\n name: Foo\n summary: Foo\n " " " "description: >\n Bar\n license:\n module:\n - " "MIT"; module_index = parse_module_index_from_string (yaml_string, &failures, &error); g_assert_nonnull (module_index); g_assert_true (g_hash_table_contains (module_index, "Foo")); module = g_hash_table_lookup (module_index, "Foo"); g_assert_nonnull (module); g_assert_true (MODULEMD_IS_IMPROVEDMODULE (module)); g_assert_cmpstr (modulemd_improvedmodule_peek_name (module), ==, "Foo"); g_assert_null (modulemd_improvedmodule_peek_defaults (module)); } static void modulemd_yaml_test_index_from_stream (YamlFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_path = NULL; g_autoptr (FILE) yaml_stream = NULL; g_autoptr (GHashTable) module_index = NULL; g_autoptr (GPtrArray) failures = NULL; g_autoptr (GError) error = NULL; ModulemdImprovedModule *module = NULL; yaml_path = g_strdup_printf ("%s/test_data/long-valid.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); yaml_stream = g_fopen (yaml_path, "rb"); g_assert_nonnull (yaml_stream); module_index = parse_module_index_from_stream (yaml_stream, &failures, &error); g_assert_nonnull (module_index); g_assert_true (g_hash_table_contains (module_index, "nodejs")); module = g_hash_table_lookup (module_index, "nodejs"); g_assert_nonnull (module); g_assert_true (MODULEMD_IS_IMPROVEDMODULE (module)); g_assert_cmpstr (modulemd_improvedmodule_peek_name (module), ==, "nodejs"); g_assert_nonnull (modulemd_improvedmodule_peek_defaults (module)); } int main (int argc, char *argv[]) { setlocale (LC_ALL, ""); g_test_init (&argc, &argv, NULL); g_test_bug_base ("https://bugzilla.redhat.com/show_bug.cgi?id="); // Define the tests. g_test_add ("/modulemd/yaml/test_parse_v1_file", YamlFixture, NULL, modulemd_yaml_set_up, modulemd_yaml_test_parse_v1_file, modulemd_yaml_tear_down); g_test_add ("/modulemd/yaml/test_emit_v1_string", YamlFixture, NULL, modulemd_yaml_set_up, modulemd_yaml_test_emit_v1_string, modulemd_yaml_tear_down); g_test_add ("/modulemd/yaml/test_v1_load", YamlFixture, NULL, modulemd_yaml_set_up, modulemd_yaml_test_v1_load, modulemd_yaml_tear_down); g_test_add ("/modulemd/yaml/test_v2_load", YamlFixture, NULL, modulemd_yaml_set_up, modulemd_yaml_test_v2_load, modulemd_yaml_tear_down); g_test_add ("/modulemd/yaml/test_emit_v2_string", YamlFixture, NULL, modulemd_yaml_set_up, modulemd_yaml_test_emit_v2_string, modulemd_yaml_tear_down); g_test_add ("/modulemd/yaml/test_v2_stream", YamlFixture, NULL, modulemd_yaml_set_up, modulemd_yaml_test_v2_stream, modulemd_yaml_tear_down); g_test_add ("/modulemd/yaml/test_validate_nevra", YamlFixture, NULL, NULL, modulemd_yaml_test_validate_nevra, NULL); g_test_add ("/modulemd/yaml/test_artifact_validation", YamlFixture, NULL, NULL, modulemd_yaml_test_artifact_validation, NULL); g_test_add ("/modulemd/yaml/test_index_from_file", YamlFixture, NULL, NULL, modulemd_yaml_test_index_from_file, NULL); g_test_add ("/modulemd/yaml/test_index_from_string", YamlFixture, NULL, NULL, modulemd_yaml_test_index_from_string, NULL); g_test_add ("/modulemd/yaml/test_index_from_stream", YamlFixture, NULL, NULL, modulemd_yaml_test_index_from_stream, NULL); return g_test_run (); }
lubomir/libmodulemd
modulemd/v1/modulemd-defaults.c
<filename>modulemd/v1/modulemd-defaults.c<gh_stars>0 /* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #include "modulemd.h" #include "modulemd-defaults.h" #include "modulemd-simpleset.h" #include "private/modulemd-yaml.h" GQuark modulemd_defaults_error_quark (void) { return g_quark_from_static_string ("modulemd-defaults-error-quark"); } struct _ModulemdDefaults { GObject parent_instance; /* == Members == */ guint64 version; gchar *module_name; gchar *default_stream; GHashTable *intents; GHashTable *profile_defaults; }; G_DEFINE_TYPE (ModulemdDefaults, modulemd_defaults, G_TYPE_OBJECT) enum { PROP_0, PROP_VERSION, PROP_MODULE_NAME, PROP_DEFAULT_STREAM, PROP_INTENTS, PROP_PROFILE_DEFAULTS, N_PROPS }; static GParamSpec *properties[N_PROPS]; ModulemdDefaults * modulemd_defaults_new (void) { return g_object_new (MODULEMD_TYPE_DEFAULTS, NULL); } static void modulemd_defaults_finalize (GObject *object) { ModulemdDefaults *self = (ModulemdDefaults *)object; g_clear_pointer (&self->module_name, g_free); g_clear_pointer (&self->default_stream, g_free); g_clear_pointer (&self->intents, g_hash_table_unref); g_clear_pointer (&self->profile_defaults, g_hash_table_unref); G_OBJECT_CLASS (modulemd_defaults_parent_class)->finalize (object); } void modulemd_defaults_set_version (ModulemdDefaults *self, guint64 version) { g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); if (self->version != version) { self->version = version; g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_VERSION]); } } guint64 modulemd_defaults_peek_version (ModulemdDefaults *self) { g_return_val_if_fail (self, MD_DEFAULTS_VERSION_UNSET); return self->version; } void modulemd_defaults_set_module_name (ModulemdDefaults *self, const gchar *name) { g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); if (g_strcmp0 (self->module_name, name) != 0) { g_free (self->module_name); self->module_name = g_strdup (name); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_MODULE_NAME]); } } const gchar * modulemd_defaults_peek_module_name (ModulemdDefaults *self) { g_return_val_if_fail (self, NULL); return self->module_name; } gchar * modulemd_defaults_dup_module_name (ModulemdDefaults *self) { g_return_val_if_fail (self, NULL); return g_strdup (self->module_name); } void modulemd_defaults_set_default_stream (ModulemdDefaults *self, const gchar *stream) { g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); if (g_strcmp0 (self->default_stream, stream) != 0) { g_free (self->default_stream); self->default_stream = g_strdup (stream); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_DEFAULT_STREAM]); } } const gchar * modulemd_defaults_peek_default_stream (ModulemdDefaults *self) { g_return_val_if_fail (self, NULL); return self->default_stream; } gchar * modulemd_defaults_dup_default_stream (ModulemdDefaults *self) { g_return_val_if_fail (self, NULL); return g_strdup (self->default_stream); } void modulemd_defaults_set_profiles_for_stream (ModulemdDefaults *self, const gchar *stream, gchar **profiles) { ModulemdSimpleSet *set = NULL; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); set = modulemd_simpleset_new (); modulemd_simpleset_set (set, profiles); g_hash_table_replace (self->profile_defaults, g_strdup (stream), set); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_PROFILE_DEFAULTS]); } void modulemd_defaults_assign_profiles_for_stream (ModulemdDefaults *self, const gchar *stream, ModulemdSimpleSet *profiles) { ModulemdSimpleSet *set = NULL; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); modulemd_simpleset_copy (profiles, &set); g_hash_table_replace (self->profile_defaults, g_strdup (stream), set); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_PROFILE_DEFAULTS]); } void modulemd_defaults_set_profile_defaults (ModulemdDefaults *self, GHashTable *profile_defaults) { GHashTableIter iter; gpointer key, value; ModulemdSimpleSet *set = NULL; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); g_hash_table_remove_all (self->profile_defaults); if (profile_defaults) { g_hash_table_iter_init (&iter, profile_defaults); while (g_hash_table_iter_next (&iter, &key, &value)) { modulemd_simpleset_copy ((ModulemdSimpleSet *)value, &set); g_hash_table_replace ( self->profile_defaults, g_strdup ((const gchar *)key), set); set = NULL; } } g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_PROFILE_DEFAULTS]); } gchar ** modulemd_defaults_dup_profiles_for_stream (ModulemdDefaults *self, const gchar *stream) { ModulemdSimpleSet *set = NULL; gchar **profiles = NULL; g_return_val_if_fail (MODULEMD_IS_DEFAULTS (self), NULL); set = g_hash_table_lookup (self->profile_defaults, stream); profiles = modulemd_simpleset_dup (set); g_clear_pointer (&set, g_object_unref); return profiles; } GHashTable * modulemd_defaults_peek_profile_defaults (ModulemdDefaults *self) { g_return_val_if_fail (MODULEMD_IS_DEFAULTS (self), NULL); return self->profile_defaults; } GHashTable * modulemd_defaults_dup_profile_defaults (ModulemdDefaults *self) { GHashTableIter iter; GHashTable *new; gpointer key, value; ModulemdSimpleSet *set = NULL; g_return_val_if_fail (MODULEMD_IS_DEFAULTS (self), NULL); new = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); g_hash_table_iter_init (&iter, self->profile_defaults); while (g_hash_table_iter_next (&iter, &key, &value)) { modulemd_simpleset_copy ((ModulemdSimpleSet *)value, &set); g_hash_table_replace (new, g_strdup ((const gchar *)key), set); set = NULL; } return new; } void modulemd_defaults_add_intent (ModulemdDefaults *self, ModulemdIntent *intent) { g_autoptr (ModulemdIntent) copy = NULL; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); g_return_if_fail (MODULEMD_IS_INTENT (intent)); copy = modulemd_intent_copy (intent); g_hash_table_replace (self->intents, g_strdup (modulemd_intent_peek_intent_name (intent)), g_object_ref (copy)); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_INTENTS]); } void modulemd_defaults_set_intents (ModulemdDefaults *self, GHashTable *intents) { GHashTableIter iter; gpointer key, value; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); g_hash_table_remove_all (self->intents); g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_INTENTS]); if (intents) { g_hash_table_iter_init (&iter, intents); while (g_hash_table_iter_next (&iter, &key, &value)) { modulemd_defaults_add_intent (self, MODULEMD_INTENT (value)); } } } GHashTable * modulemd_defaults_peek_intents (ModulemdDefaults *self) { g_return_val_if_fail (MODULEMD_IS_DEFAULTS (self), NULL); return self->intents; } GHashTable * modulemd_defaults_dup_intents (ModulemdDefaults *self) { g_autoptr (GHashTable) intents = NULL; ModulemdIntent *intent = NULL; gpointer key, value; GHashTableIter iter; g_return_val_if_fail (MODULEMD_IS_DEFAULTS (self), NULL); intents = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); g_hash_table_iter_init (&iter, self->intents); while (g_hash_table_iter_next (&iter, &key, &value)) { intent = MODULEMD_INTENT (value); g_hash_table_replace ( intents, g_strdup (modulemd_intent_peek_intent_name (intent)), modulemd_intent_copy (intent)); } return g_hash_table_ref (intents); } ModulemdDefaults * modulemd_defaults_new_from_file (const gchar *yaml_file, GError **error) { return modulemd_defaults_new_from_file_ext (yaml_file, NULL, error); } ModulemdDefaults * modulemd_defaults_new_from_file_ext (const gchar *yaml_file, GPtrArray **failures, GError **error) { GObject *object = NULL; GPtrArray *data = NULL; ModulemdDefaults *defaults = NULL; if (!parse_yaml_file (yaml_file, &data, failures, error)) { return NULL; } for (gsize i = 0; i < data->len; i++) { object = g_ptr_array_index (data, i); if (MODULEMD_IS_DEFAULTS (object)) { defaults = MODULEMD_DEFAULTS (g_object_ref (object)); break; } } if (!defaults) { g_set_error (error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_MISSING_CONTENT, "Provided YAML file contained no valid defaults objects"); } g_clear_pointer (&data, g_ptr_array_unref); return defaults; } ModulemdDefaults * modulemd_defaults_new_from_string (const gchar *yaml_string, GError **error) { return modulemd_defaults_new_from_string_ext (yaml_string, NULL, error); } ModulemdDefaults * modulemd_defaults_new_from_string_ext (const gchar *yaml_string, GPtrArray **failures, GError **error) { GObject *object = NULL; GPtrArray *data = NULL; ModulemdDefaults *defaults = NULL; if (!parse_yaml_string (yaml_string, &data, failures, error)) { return NULL; } for (gsize i = 0; i < data->len; i++) { object = g_ptr_array_index (data, i); if (MODULEMD_IS_DEFAULTS (object)) { defaults = MODULEMD_DEFAULTS (g_object_ref (object)); break; } } if (!defaults) { g_set_error (error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_MISSING_CONTENT, "Provided YAML file contained no valid defaults objects"); } g_clear_pointer (&data, g_ptr_array_unref); return defaults; } ModulemdDefaults * modulemd_defaults_new_from_stream (FILE *stream, GError **error) { return modulemd_defaults_new_from_stream_ext (stream, NULL, error); } ModulemdDefaults * modulemd_defaults_new_from_stream_ext (FILE *stream, GPtrArray **failures, GError **error) { GObject *object = NULL; g_autoptr (GPtrArray) data = NULL; ModulemdDefaults *defaults = NULL; if (!parse_yaml_stream (stream, &data, failures, error)) { return NULL; } for (gsize i = 0; i < data->len; i++) { object = g_ptr_array_index (data, i); if (MODULEMD_IS_DEFAULTS (object)) { defaults = MODULEMD_DEFAULTS (g_object_ref (object)); break; } } if (!defaults) { g_set_error (error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_MISSING_CONTENT, "Provided YAML stream contained no valid defaults objects"); } return defaults; } void modulemd_defaults_dump (ModulemdDefaults *self, const gchar *file_path) { GPtrArray *objects = NULL; GError *error = NULL; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); objects = g_ptr_array_new (); g_ptr_array_add (objects, self); if (!emit_yaml_file (objects, file_path, &error)) { g_debug ("Failed to export YAML: [%s]", error->message); } g_ptr_array_unref (objects); } void modulemd_defaults_dumps (ModulemdDefaults *self, gchar **yaml_string) { GPtrArray *objects = NULL; GError *error = NULL; g_return_if_fail (MODULEMD_IS_DEFAULTS (self)); objects = g_ptr_array_new (); g_ptr_array_add (objects, self); if (!emit_yaml_string (objects, yaml_string, &error)) { g_debug ("Failed to export YAML: [%s]", error->message); } g_ptr_array_unref (objects); } static void modulemd_defaults_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { ModulemdDefaults *self = MODULEMD_DEFAULTS (object); switch (prop_id) { case PROP_VERSION: g_value_set_uint64 (value, modulemd_defaults_peek_version (self)); break; case PROP_MODULE_NAME: g_value_set_string (value, modulemd_defaults_peek_module_name (self)); break; case PROP_DEFAULT_STREAM: g_value_set_string (value, modulemd_defaults_peek_default_stream (self)); break; case PROP_INTENTS: g_value_take_boxed (value, modulemd_defaults_dup_intents (self)); break; case PROP_PROFILE_DEFAULTS: g_value_take_boxed (value, modulemd_defaults_dup_profile_defaults (self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void modulemd_defaults_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { ModulemdDefaults *self = MODULEMD_DEFAULTS (object); switch (prop_id) { case PROP_VERSION: modulemd_defaults_set_version (self, g_value_get_uint64 (value)); break; case PROP_MODULE_NAME: modulemd_defaults_set_module_name (self, g_value_get_string (value)); break; case PROP_DEFAULT_STREAM: modulemd_defaults_set_default_stream (self, g_value_get_string (value)); break; case PROP_INTENTS: modulemd_defaults_set_intents (self, g_value_get_boxed (value)); break; case PROP_PROFILE_DEFAULTS: modulemd_defaults_set_profile_defaults (self, g_value_get_boxed (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void modulemd_defaults_class_init (ModulemdDefaultsClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = modulemd_defaults_finalize; object_class->get_property = modulemd_defaults_get_property; object_class->set_property = modulemd_defaults_set_property; properties[PROP_VERSION] = g_param_spec_uint64 ("version", "Module Defaults file format version", "An integer property representing the defaults file " "format used.", 0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_MODULE_NAME] = g_param_spec_string ( "module-name", "Module Name", "The name of the module to which these defaults apply.", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); properties[PROP_DEFAULT_STREAM] = g_param_spec_string ( "default-stream", "Default Stream", "The name of the stream that will be used by default for this module.", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); /** * ModulemdDefaults:profile-defaults: (type GLib.HashTable(utf8,ModulemdSimpleSet)) */ properties[PROP_PROFILE_DEFAULTS] = g_param_spec_boxed ( "profile-defaults", "Profile Defaults", "A hash table comprised of the set of profiles that act as the default " "for each available stream of the module.", G_TYPE_HASH_TABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); /** * ModulemdDefaults:intents: (type GLib.HashTable(utf8,ModulemdIntent)) */ properties[PROP_INTENTS] = g_param_spec_boxed ( "intents", "Intents", "A hash table describing divergent defaults based on the intent of the " "system.", G_TYPE_HASH_TABLE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties (object_class, N_PROPS, properties); } static void modulemd_defaults_init (ModulemdDefaults *self) { self->intents = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); self->profile_defaults = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); } ModulemdDefaults * modulemd_defaults_copy (ModulemdDefaults *self) { if (!self) return NULL; ModulemdDefaults *new_defaults = modulemd_defaults_new (); modulemd_defaults_set_version (new_defaults, modulemd_defaults_peek_version (self)); modulemd_defaults_set_module_name ( new_defaults, modulemd_defaults_peek_module_name (self)); modulemd_defaults_set_default_stream ( new_defaults, modulemd_defaults_peek_default_stream (self)); modulemd_defaults_set_profile_defaults ( new_defaults, modulemd_defaults_peek_profile_defaults (self)); modulemd_defaults_set_intents (new_defaults, modulemd_defaults_peek_intents (self)); return new_defaults; } ModulemdDefaults * modulemd_defaults_merge (ModulemdDefaults *first, ModulemdDefaults *second, gboolean override, GError **error) { g_autoptr (ModulemdDefaults) defaults = NULL; GHashTable *profile_defaults = NULL; g_autoptr (GHashTable) intents = NULL; ModulemdIntent *base_intent = NULL; ModulemdIntent *merge_intent = NULL; g_autoptr (ModulemdIntent) new_intent = NULL; g_autoptr (GHashTable) base_profiles = NULL; GHashTable *merge_profiles = NULL; const gchar *intent_name = NULL; ModulemdSimpleSet *profile = NULL; GHashTableIter iter, profile_iter; gpointer key, value, orig_value, prof_key, prof_value; g_return_val_if_fail (MODULEMD_IS_DEFAULTS (first), NULL); g_return_val_if_fail (MODULEMD_IS_DEFAULTS (second), NULL); if (override) { /* If override is set, then returning a copy of second is the * shortest path */ return modulemd_defaults_copy (second); } /* First check for incompatibilities with the streams */ if (g_strcmp0 (modulemd_defaults_peek_default_stream (first), modulemd_defaults_peek_default_stream (second))) { /* Default streams don't match and override is not set. * Return an error */ g_set_error ( error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_CONFLICTING_STREAMS, "Conflicting default streams when merging defaults for module %s", modulemd_defaults_peek_module_name (first)); return NULL; } defaults = modulemd_defaults_copy (first); /* Merge the profile defaults */ profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_hash_table_iter_init (&iter, modulemd_defaults_peek_profile_defaults (second)); while (g_hash_table_iter_next (&iter, &key, &value)) { orig_value = g_hash_table_lookup (profile_defaults, key); if (orig_value) { /* This key already exists in the first defaults object. * Check whether they have identical values */ if (!modulemd_simpleset_is_equal (orig_value, value)) { g_set_error (error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_CONFLICTING_PROFILES, "Conflicting profile defaults when merging " "defaults for module %s", modulemd_defaults_peek_module_name (first)); return NULL; } } else { /* This key is new. Add it */ g_hash_table_replace (profile_defaults, g_strdup (key), g_object_ref (MODULEMD_SIMPLESET (value))); } } /* Merge intents */ intents = modulemd_defaults_dup_intents (defaults); g_hash_table_iter_init (&iter, modulemd_defaults_peek_intents (second)); while (g_hash_table_iter_next (&iter, &key, &value)) { merge_intent = MODULEMD_INTENT (value); /* Check if this module name exists in the current table */ intent_name = modulemd_intent_peek_intent_name (merge_intent); base_intent = g_hash_table_lookup ( intents, modulemd_intent_peek_intent_name (merge_intent)); if (!base_intent) { /* This intent doesn't exist yet, so just add it completely. */ g_hash_table_insert (intents, g_strdup (intent_name), modulemd_intent_copy (merge_intent)); continue; } /* Compare the default stream for this intent */ if (g_strcmp0 (modulemd_intent_peek_default_stream (base_intent), modulemd_intent_peek_default_stream (merge_intent))) { /* The streams didn't match, so bail out */ g_set_error (error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_CONFLICTING_INTENT_STREAM, "Conflicting default stream for intent profile [%s]" "when merging defaults for module %s", (const gchar *)intent_name, modulemd_defaults_peek_module_name (first)); return NULL; } /* Construct a new Intent with the merged values which will replace * the existing one at the end */ new_intent = modulemd_intent_copy (base_intent); /* Merge the profile definitions for this intent */ base_profiles = modulemd_intent_dup_profile_defaults (new_intent); merge_profiles = modulemd_intent_peek_profile_defaults (merge_intent); g_hash_table_iter_init (&profile_iter, merge_profiles); while (g_hash_table_iter_next (&profile_iter, &prof_key, &prof_value)) { /* Check if this profile exists in this intent */ profile = g_hash_table_lookup (base_profiles, prof_key); if (!profile) { /* Add this profile to the intent */ modulemd_simpleset_copy (prof_value, &profile); g_hash_table_insert ( base_profiles, g_strdup ((const gchar *)prof_key), profile); continue; } if (!modulemd_simpleset_is_equal (profile, prof_value)) { /* If we get here, the sets were unequal, so we need to fail */ g_set_error (error, MODULEMD_DEFAULTS_ERROR, MODULEMD_DEFAULTS_ERROR_CONFLICTING_INTENT_PROFILE, "Conflicting intent profile [%s:%s] when merging " "defaults for module %s", (const gchar *)intent_name, (const gchar *)prof_key, modulemd_defaults_peek_module_name (first)); return NULL; } } modulemd_intent_set_profile_defaults (new_intent, base_profiles); g_clear_pointer (&base_profiles, g_hash_table_unref); g_hash_table_replace ( intents, g_strdup (intent_name), g_object_ref (new_intent)); g_clear_pointer (&new_intent, g_object_unref); } modulemd_defaults_set_intents (defaults, intents); return g_object_ref (defaults); }
lubomir/libmodulemd
modulemd/v1/tests/test-modulemd-defaults.c
/* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #define MMD_DISABLE_DEPRECATION_WARNINGS 1 #include "modulemd.h" #include "private/modulemd-yaml.h" #include <glib.h> #include <glib/gstdio.h> #include <locale.h> #include <inttypes.h> #include <time.h> typedef struct _DefaultsFixture { } DefaultsFixture; static void modulemd_defaults_test_good_ex1 (DefaultsFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_path = NULL; GPtrArray *objects = NULL; g_autoptr (ModulemdDefaults) defaults = NULL; g_autoptr (ModulemdDefaults) defaults_reread = NULL; GHashTable *profile_defaults = NULL; ModulemdSimpleSet *set = NULL; GError *error = NULL; gchar *yaml_string = NULL; const gchar *module_name = "httpd"; const gchar *default_stream = "2.6"; yaml_path = g_strdup_printf ("%s/mod-defaults/ex1.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); defaults = modulemd_defaults_new_from_file (yaml_path, &error); g_assert_nonnull (defaults); g_assert_null (error); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_true (g_hash_table_contains (profile_defaults, default_stream)); set = g_hash_table_lookup (profile_defaults, default_stream); g_assert_true (modulemd_simpleset_contains (set, "client")); g_assert_true (modulemd_simpleset_contains (set, "server")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); g_clear_pointer (&objects, g_ptr_array_unref); } static void modulemd_defaults_test_good_ex2 (DefaultsFixture *fixture, gconstpointer user_data) { gboolean result = FALSE; gchar *yaml_path = NULL; GPtrArray *objects = NULL; GObject *object = NULL; ModulemdDefaults *defaults = NULL; g_autoptr (ModulemdDefaults) defaults_reread = NULL; GHashTable *profile_defaults = NULL; ModulemdSimpleSet *set = NULL; GError *error = NULL; gchar *yaml_string = NULL; const gchar *module_name = "postgresql"; const gchar *default_stream = "8.0"; yaml_path = g_strdup_printf ("%s/mod-defaults/ex2.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); result = parse_yaml_file (yaml_path, &objects, NULL, &error); g_free (yaml_path); g_assert_true (result); g_assert_cmpint (objects->len, ==, 2); /* First of the two subdocuments */ object = g_ptr_array_index (objects, 0); g_assert_nonnull (object); g_assert_true (MODULEMD_IS_DEFAULTS (object)); defaults = MODULEMD_DEFAULTS (object); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_true (g_hash_table_contains (profile_defaults, default_stream)); set = g_hash_table_lookup (profile_defaults, default_stream); g_assert_true (modulemd_simpleset_contains (set, "server")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); /* Second of the two subdocuments */ module_name = "nodejs"; default_stream = "6.0"; object = g_ptr_array_index (objects, 1); g_assert_nonnull (object); g_assert_true (MODULEMD_IS_DEFAULTS (object)); defaults = MODULEMD_DEFAULTS (object); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_true (g_hash_table_contains (profile_defaults, default_stream)); set = g_hash_table_lookup (profile_defaults, default_stream); g_assert_true (modulemd_simpleset_contains (set, "default")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); g_clear_pointer (&objects, g_ptr_array_unref); } static void modulemd_defaults_test_good_ex3 (DefaultsFixture *fixture, gconstpointer user_data) { gboolean result = FALSE; gchar *yaml_path = NULL; GPtrArray *objects = NULL; GObject *object = NULL; ModulemdDefaults *defaults = NULL; g_autoptr (ModulemdDefaults) defaults_reread = NULL; GHashTable *profile_defaults = NULL; ModulemdSimpleSet *set = NULL; GError *error = NULL; gchar *yaml_string = NULL; const gchar *module_name = "httpd"; const gchar *default_stream = "2.2"; yaml_path = g_strdup_printf ("%s/mod-defaults/ex3.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); result = parse_yaml_file (yaml_path, &objects, NULL, &error); g_free (yaml_path); g_assert_true (result); g_assert_cmpint (objects->len, ==, 3); /* First of the three subdocuments */ object = g_ptr_array_index (objects, 0); g_assert_nonnull (object); g_assert_true (MODULEMD_IS_DEFAULTS (object)); defaults = MODULEMD_DEFAULTS (object); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_true (g_hash_table_contains (profile_defaults, default_stream)); set = g_hash_table_lookup (profile_defaults, default_stream); g_assert_true (modulemd_simpleset_contains (set, "client")); g_assert_true (modulemd_simpleset_contains (set, "server")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); /* Second of the three subdocuments */ module_name = "postgresql"; default_stream = "8.1"; object = g_ptr_array_index (objects, 1); g_assert_nonnull (object); g_assert_true (MODULEMD_IS_DEFAULTS (object)); defaults = MODULEMD_DEFAULTS (object); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_true (g_hash_table_contains (profile_defaults, default_stream)); set = g_hash_table_lookup (profile_defaults, default_stream); g_assert_true (modulemd_simpleset_contains (set, "client")); g_assert_true (modulemd_simpleset_contains (set, "server")); g_assert_true (modulemd_simpleset_contains (set, "foo")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); /* Third of the three subdocuments */ module_name = "nodejs"; default_stream = "8.0"; object = g_ptr_array_index (objects, 2); g_assert_nonnull (object); g_assert_true (MODULEMD_IS_DEFAULTS (object)); defaults = MODULEMD_DEFAULTS (object); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_true (g_hash_table_contains (profile_defaults, default_stream)); set = g_hash_table_lookup (profile_defaults, default_stream); g_assert_true (modulemd_simpleset_contains (set, "super")); set = g_hash_table_lookup (profile_defaults, "6.0"); g_assert_true (modulemd_simpleset_contains (set, "default")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); g_clear_pointer (&objects, g_ptr_array_unref); } static void modulemd_defaults_test_good_ex4 (DefaultsFixture *fixture, gconstpointer user_data) { gboolean result = FALSE; gchar *yaml_path = NULL; GPtrArray *objects = NULL; GObject *object = NULL; ModulemdDefaults *defaults = NULL; g_autoptr (ModulemdDefaults) defaults_reread = NULL; GHashTable *profile_defaults = NULL; ModulemdSimpleSet *set = NULL; GError *error = NULL; gchar *yaml_string = NULL; const gchar *module_name = "httpd"; const gchar *default_stream = NULL; yaml_path = g_strdup_printf ("%s/mod-defaults/ex4.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); result = parse_yaml_file (yaml_path, &objects, NULL, &error); g_free (yaml_path); g_assert_true (result); g_assert_cmpint (objects->len, ==, 1); object = g_ptr_array_index (objects, 0); g_assert_nonnull (object); g_assert_true (MODULEMD_IS_DEFAULTS (object)); defaults = MODULEMD_DEFAULTS (g_ptr_array_index (objects, 0)); g_assert_cmpint ( modulemd_defaults_peek_version (defaults), ==, MD_DEFAULTS_VERSION_1); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, module_name); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, default_stream); profile_defaults = modulemd_defaults_peek_profile_defaults (defaults); g_assert_nonnull (profile_defaults); set = g_hash_table_lookup (profile_defaults, "2.6"); g_assert_nonnull (set); g_assert_true (modulemd_simpleset_contains (set, "client")); g_assert_true (modulemd_simpleset_contains (set, "server")); /* Test emitting the YAML back out */ modulemd_defaults_dumps (defaults, &yaml_string); g_assert_nonnull (yaml_string); g_debug ("EX1 YAML:\n%s", yaml_string); /* Read the YAML back in from the string to ensure the output was valid */ defaults_reread = modulemd_defaults_new_from_string (yaml_string, &error); g_assert_nonnull (defaults_reread); g_clear_pointer (&defaults_reread, g_object_unref); g_clear_pointer (&yaml_string, g_free); g_clear_pointer (&objects, g_ptr_array_unref); } static void modulemd_defaults_test_copy (DefaultsFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_path = NULL; GError *error = NULL; g_autoptr (ModulemdDefaults) orig = NULL; g_autoptr (ModulemdDefaults) copy = NULL; yaml_path = g_strdup_printf ("%s/mod-defaults/spec.v1.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); orig = modulemd_defaults_new_from_file (yaml_path, &error); copy = modulemd_defaults_copy (orig); g_assert_nonnull (copy); g_assert_cmpstr (modulemd_defaults_peek_module_name (orig), ==, modulemd_defaults_peek_module_name (copy)); g_assert_cmpstr (modulemd_defaults_peek_default_stream (orig), ==, modulemd_defaults_peek_default_stream (copy)); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (orig)), ==, g_hash_table_size (modulemd_defaults_peek_profile_defaults (copy))); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_intents (orig)), ==, 2); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_intents (copy)), ==, 2); g_assert_true ( g_hash_table_contains (modulemd_defaults_peek_intents (orig), "desktop")); g_assert_true ( g_hash_table_contains (modulemd_defaults_peek_intents (copy), "desktop")); g_assert_true ( g_hash_table_contains (modulemd_defaults_peek_intents (orig), "server")); g_assert_true ( g_hash_table_contains (modulemd_defaults_peek_intents (copy), "server")); } static void modulemd_defaults_test_merging (DefaultsFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_path = NULL; g_autoptr (GPtrArray) objects = NULL; g_autoptr (GPtrArray) override_objects = NULL; g_autoptr (GPtrArray) merged_base = NULL; g_autoptr (GPtrArray) overridden = NULL; ModulemdDefaults *defaults = NULL; GError *error = NULL; yaml_path = g_strdup_printf ("%s/test_data/defaults/merging-base.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); objects = modulemd_objects_from_file (yaml_path, &error); g_clear_pointer (&yaml_path, g_free); g_assert_nonnull (objects); g_assert_cmpint (objects->len, ==, 7); merged_base = modulemd_merge_defaults (objects, NULL, FALSE, &error); if (!merged_base) { fprintf (stderr, "Error merging defaults: %s\n", error->message); } g_assert_nonnull (merged_base); g_assert_cmpint (merged_base->len, ==, 3); /* They should be in alphabetical order now */ /* HTTPD */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_base, 0)); g_assert_cmpstr (modulemd_defaults_peek_module_name (defaults), ==, "httpd"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "2.2"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 2); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "2.2")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "2.8")); /* NODEJS */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_base, 1)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "nodejs"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "8.0"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 3); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "6.0")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "8.0")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "9.0")); /* POSTGRESQL */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_base, 2)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "postgresql"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "8.1"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 2); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "8.1")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "8.2")); /* Now test overriding with a higher-priority repo */ yaml_path = g_strdup_printf ("%s/test_data/defaults/overriding.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_path); override_objects = modulemd_objects_from_file (yaml_path, &error); g_clear_pointer (&yaml_path, g_free); g_assert_nonnull (override_objects); g_assert_cmpint (override_objects->len, ==, 3); overridden = modulemd_merge_defaults (merged_base, override_objects, TRUE, &error); if (!overridden) { fprintf (stderr, "Error merging defaults: %s\n", error->message); } g_assert_nonnull (overridden); g_assert_cmpint (overridden->len, ==, 3); /* They should be in alphabetical order now */ /* HTTPD */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (overridden, 0)); g_assert_cmpstr (modulemd_defaults_peek_module_name (defaults), ==, "httpd"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "2.4"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 2); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "2.2")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "2.4")); g_assert_false (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "2.8")); /* NODEJS */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (overridden, 1)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "nodejs"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "9.0"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 3); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "6.0")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "8.0")); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "9.0")); /* POSTGRESQL */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (overridden, 2)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "postgresql"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "8.1"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 1); g_assert_true (g_hash_table_contains ( modulemd_defaults_peek_profile_defaults (defaults), "8.1")); } static void modulemd_defaults_test_prioritizer (DefaultsFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_base_path = NULL; g_autofree gchar *yaml_override_path = NULL; g_autoptr (GPtrArray) base_objects = NULL; g_autoptr (GPtrArray) override_objects = NULL; g_autoptr (GPtrArray) merged_objects = NULL; g_autoptr (ModulemdPrioritizer) prioritizer = NULL; g_autoptr (GError) error = NULL; GHashTable *htable = NULL; gint64 prio; ModulemdDefaults *defaults = NULL; gboolean result; yaml_base_path = g_strdup_printf ("%s/test_data/defaults/merging-base.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_base_path); base_objects = modulemd_objects_from_file (yaml_base_path, &error); g_assert_nonnull (base_objects); g_assert_cmpint (base_objects->len, ==, 7); yaml_override_path = g_strdup_printf ( "%s/test_data/defaults/overriding.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_override_path); override_objects = modulemd_objects_from_file (yaml_override_path, &error); g_assert_nonnull (override_objects); g_assert_cmpint (override_objects->len, ==, 3); /* Test that importing the base objects work. These objects include several * exact duplicates which will be cleaned up by this process. */ /* Pick a random number from 0-99 for the higher priority. * This will help exercise the sort function and make sure it doesn't * occasionally fail. */ prio = g_test_rand_int_range (0, 99); g_info ("Random low priority level: %" PRIi64 "\n", prio); prioritizer = modulemd_prioritizer_new (); result = modulemd_prioritizer_add (prioritizer, base_objects, prio, &error); if (!result) { fprintf (stderr, "Merge error: %s", error->message); } g_assert_true (result); /* * Test that importing the base objects works again. This will be a worst- * case scenario where all of the values being imported are duplicated. */ result = modulemd_prioritizer_add (prioritizer, base_objects, prio, &error); if (!result) { fprintf (stderr, "Merge error: %s", error->message); } g_assert_true (result); /* * Test that importing the overrides at the same priority level fails. * * These objects have several conflicts with the base objects that cannot be * merged. */ result = modulemd_prioritizer_add (prioritizer, override_objects, prio, &error); g_assert_false (result); g_assert_cmpstr ( g_quark_to_string (error->domain), ==, "modulemd-defaults-error-quark"); g_assert_cmpint ( error->code, ==, MODULEMD_DEFAULTS_ERROR_CONFLICTING_STREAMS); g_clear_pointer (&error, g_error_free); /* The object's internal state is undefined after an error, so delete it */ g_clear_pointer (&prioritizer, g_object_unref); /* Start over and add the base */ prioritizer = modulemd_prioritizer_new (); result = modulemd_prioritizer_add (prioritizer, base_objects, prio, &error); if (!result) { fprintf (stderr, "Merge error: %s", error->message); } g_assert_true (result); /* Test that importing the overrides at a higher priority level succeeds. */ /* Pick a random number from 100-999 for the higher priority. * This will help exercise the sort function and make sure it doesn't * occasionally fail. */ prio = g_test_rand_int_range (100, 999); g_info ("Random high priority level: %" PRIi64 "\n", prio); result = modulemd_prioritizer_add (prioritizer, override_objects, prio, &error); g_assert_true (result); /* * Test that re-importing the overrides at the same priority level * succeeds. */ result = modulemd_prioritizer_add (prioritizer, override_objects, prio, &error); g_assert_true (result); /* Merge all of the results together */ merged_objects = modulemd_prioritizer_resolve (prioritizer, &error); g_assert_nonnull (merged_objects); g_assert_cmpint (merged_objects->len, ==, 3); /* HTTPD */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_objects, 0)); g_assert_cmpstr (modulemd_defaults_peek_module_name (defaults), ==, "httpd"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "2.4"); htable = modulemd_defaults_peek_profile_defaults (defaults); g_assert_cmpint (g_hash_table_size (htable), ==, 2); g_assert_true (g_hash_table_contains (htable, "2.2")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.2"), "client")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.2"), "server")); g_assert_true (g_hash_table_contains (htable, "2.4")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.2"), "client")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.4"), "server")); g_assert_false (g_hash_table_contains (htable, "2.8")); /* NODEJS */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_objects, 1)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "nodejs"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "9.0"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 3); htable = modulemd_defaults_peek_profile_defaults (defaults); g_assert_cmpint (g_hash_table_size (htable), ==, 3); g_assert_true (g_hash_table_contains (htable, "6.0")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "6.0"), "default")); g_assert_true (g_hash_table_contains (htable, "8.0")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "8.0"), "minimal")); g_assert_true (g_hash_table_contains (htable, "9.0")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "9.0"), "supermegaultra")); /* POSTGRESQL */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_objects, 2)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "postgresql"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "8.1"); htable = modulemd_defaults_peek_profile_defaults (defaults); g_assert_cmpint (g_hash_table_size (htable), ==, 1); g_assert_true (g_hash_table_contains (htable, "8.1")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "8.1"), "client")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "8.1"), "server")); g_assert_true ( modulemd_simpleset_contains (g_hash_table_lookup (htable, "8.1"), "foo")); } static void modulemd_defaults_test_index_prioritizer (DefaultsFixture *fixture, gconstpointer user_data) { g_autofree gchar *yaml_base_path = NULL; g_autofree gchar *yaml_override_path = NULL; g_autoptr (GHashTable) index = NULL; g_autoptr (GHashTable) override_index = NULL; g_autoptr (GPtrArray) merged_objects = NULL; g_autoptr (ModulemdPrioritizer) prioritizer = NULL; g_autoptr (GError) error = NULL; GHashTable *htable = NULL; gint64 prio; ModulemdDefaults *defaults = NULL; gboolean result; yaml_base_path = g_strdup_printf ("%s/test_data/defaults/merging-base.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_base_path); index = modulemd_index_from_file (yaml_base_path, NULL, &error); g_assert_nonnull (index); g_assert_cmpint (g_hash_table_size (index), ==, 3); yaml_override_path = g_strdup_printf ( "%s/test_data/defaults/overriding.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_override_path); override_index = modulemd_index_from_file (yaml_override_path, NULL, &error); g_assert_nonnull (override_index); g_assert_cmpint (g_hash_table_size (index), ==, 3); /* Test that importing the base objects work. These objects include several * exact duplicates which will be cleaned up by this process. */ /* Pick a random number from 0-99 for the higher priority. * This will help exercise the sort function and make sure it doesn't * occasionally fail. */ prio = g_test_rand_int_range (0, 99); g_info ("Random low priority level: %" PRIi64 "\n", prio); prioritizer = modulemd_prioritizer_new (); result = modulemd_prioritizer_add_index (prioritizer, index, prio, &error); if (!result) { fprintf (stderr, "Merge error: %s", error->message); } g_assert_true (result); /* * Test that importing the base objects works again. This will be a worst- * case scenario where all of the values being imported are duplicated. */ result = modulemd_prioritizer_add_index (prioritizer, index, prio, &error); if (!result) { fprintf (stderr, "Merge error: %s", error->message); } g_assert_true (result); /* * Test that importing the overrides at the same priority level fails. * * These objects have several conflicts with the base objects that cannot be * merged. */ result = modulemd_prioritizer_add_index (prioritizer, override_index, prio, &error); g_assert_false (result); g_assert_cmpstr ( g_quark_to_string (error->domain), ==, "modulemd-defaults-error-quark"); g_assert_cmpint ( error->code, ==, MODULEMD_DEFAULTS_ERROR_CONFLICTING_STREAMS); g_clear_pointer (&error, g_error_free); /* The object's internal state is undefined after an error, so delete it */ g_clear_pointer (&prioritizer, g_object_unref); /* Start over and add the base */ prioritizer = modulemd_prioritizer_new (); result = modulemd_prioritizer_add_index (prioritizer, index, prio, &error); if (!result) { fprintf (stderr, "Merge error: %s", error->message); } g_assert_true (result); /* Test that importing the overrides at a higher priority level succeeds. */ /* Pick a random number from 100-999 for the higher priority. * This will help exercise the sort function and make sure it doesn't * occasionally fail. */ prio = g_test_rand_int_range (100, 999); g_info ("Random high priority level: %" PRIi64 "\n", prio); result = modulemd_prioritizer_add_index (prioritizer, override_index, prio, &error); g_assert_true (result); /* * Test that re-importing the overrides at the same priority level * succeeds. */ result = modulemd_prioritizer_add_index (prioritizer, override_index, prio, &error); g_assert_true (result); /* Merge all of the results together */ merged_objects = modulemd_prioritizer_resolve (prioritizer, &error); g_assert_nonnull (merged_objects); g_assert_cmpint (merged_objects->len, ==, 3); /* HTTPD */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_objects, 0)); g_assert_cmpstr (modulemd_defaults_peek_module_name (defaults), ==, "httpd"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "2.4"); htable = modulemd_defaults_peek_profile_defaults (defaults); g_assert_cmpint (g_hash_table_size (htable), ==, 2); g_assert_true (g_hash_table_contains (htable, "2.2")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.2"), "client")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.2"), "server")); g_assert_true (g_hash_table_contains (htable, "2.4")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.2"), "client")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "2.4"), "server")); g_assert_false (g_hash_table_contains (htable, "2.8")); /* NODEJS */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_objects, 1)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "nodejs"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "9.0"); g_assert_cmpint ( g_hash_table_size (modulemd_defaults_peek_profile_defaults (defaults)), ==, 3); htable = modulemd_defaults_peek_profile_defaults (defaults); g_assert_cmpint (g_hash_table_size (htable), ==, 3); g_assert_true (g_hash_table_contains (htable, "6.0")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "6.0"), "default")); g_assert_true (g_hash_table_contains (htable, "8.0")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "8.0"), "minimal")); g_assert_true (g_hash_table_contains (htable, "9.0")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "9.0"), "supermegaultra")); /* POSTGRESQL */ defaults = MODULEMD_DEFAULTS (g_ptr_array_index (merged_objects, 2)); g_assert_cmpstr ( modulemd_defaults_peek_module_name (defaults), ==, "postgresql"); g_assert_cmpstr ( modulemd_defaults_peek_default_stream (defaults), ==, "8.1"); htable = modulemd_defaults_peek_profile_defaults (defaults); g_assert_cmpint (g_hash_table_size (htable), ==, 1); g_assert_true (g_hash_table_contains (htable, "8.1")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "8.1"), "client")); g_assert_true (modulemd_simpleset_contains ( g_hash_table_lookup (htable, "8.1"), "server")); g_assert_true ( modulemd_simpleset_contains (g_hash_table_lookup (htable, "8.1"), "foo")); } static void modulemd_regressions_issue42 (DefaultsFixture *fixture, gconstpointer user_data) { g_autoptr (ModulemdPrioritizer) prioritizer = NULL; g_autoptr (GPtrArray) objects = NULL; g_autoptr (GError) error = NULL; prioritizer = modulemd_prioritizer_new (); /* Test that the prioritizer doesn't crash if it resolves zero documents */ objects = modulemd_prioritizer_resolve (prioritizer, &error); g_assert_null (objects); g_assert_nonnull (error); g_assert_cmpint ( error->code, ==, MODULEMD_PRIORITIZER_NOTHING_TO_PRIORITIZE); } static void modulemd_regressions_issue44 (DefaultsFixture *fixture, gconstpointer user_data) { gboolean result; g_autoptr (ModulemdPrioritizer) prioritizer = NULL; g_autoptr (GPtrArray) base_objects = NULL; g_autoptr (GPtrArray) conflicting_objects = NULL; g_autoptr (GError) error = NULL; g_autofree gchar *yaml_base_path = NULL; g_autofree gchar *yaml_conflicting_path = NULL; prioritizer = modulemd_prioritizer_new (); /* Get a simple document */ yaml_base_path = g_strdup_printf ("%s/test_data/defaults/issue44-1.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_base_path); base_objects = modulemd_objects_from_file (yaml_base_path, &error); g_assert_nonnull (base_objects); result = modulemd_prioritizer_add (prioritizer, base_objects, 0, &error); g_assert_true (result); /* Add another almost-identical document, except with a conflicting default * stream set. */ yaml_conflicting_path = g_strdup_printf ( "%s/test_data/defaults/issue44-2.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_conflicting_path); conflicting_objects = modulemd_objects_from_file (yaml_conflicting_path, &error); g_assert_nonnull (conflicting_objects); result = modulemd_prioritizer_add (prioritizer, conflicting_objects, 0, &error); g_assert_false (result); } static void modulemd_regressions_issue45 (DefaultsFixture *fixture, gconstpointer user_data) { gboolean ret; g_autoptr (ModulemdPrioritizer) prioritizer = NULL; g_autoptr (GPtrArray) objects = NULL; g_autoptr (GError) error = NULL; g_autofree gchar *yaml_base_path = NULL; prioritizer = modulemd_prioritizer_new (); yaml_base_path = g_strdup_printf ("%s/test_data/defaults/merging-base.yaml", g_getenv ("MESON_SOURCE_ROOT")); g_assert_nonnull (yaml_base_path); objects = modulemd_objects_from_file (yaml_base_path, &error); ret = modulemd_prioritizer_add ( prioritizer, objects, MODULEMD_PRIORITIZER_PRIORITY_MAX + 1, &error); g_assert_false (ret); g_assert_nonnull (error); g_assert_cmpint ( error->code, ==, MODULEMD_PRIORITIZER_PRIORITY_OUT_OF_RANGE); g_clear_pointer (&error, g_error_free); /* Test that the prioritizer throws an error on a negative priority */ ret = modulemd_prioritizer_add (prioritizer, objects, -1, &error); g_assert_false (ret); g_assert_nonnull (error); g_assert_cmpint ( error->code, ==, MODULEMD_PRIORITIZER_PRIORITY_OUT_OF_RANGE); } int main (int argc, char *argv[]) { setlocale (LC_ALL, ""); g_test_init (&argc, &argv, NULL); g_test_bug_base ("https://bugzilla.redhat.com/show_bug.cgi?id="); g_test_add ("/modulemd/defaults/modulemd_defaults_test_good_examples/ex1", DefaultsFixture, NULL, NULL, modulemd_defaults_test_good_ex1, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_good_examples/ex2", DefaultsFixture, NULL, NULL, modulemd_defaults_test_good_ex2, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_good_examples/ex3", DefaultsFixture, NULL, NULL, modulemd_defaults_test_good_ex3, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_good_examples/ex4", DefaultsFixture, NULL, NULL, modulemd_defaults_test_good_ex4, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_copy", DefaultsFixture, NULL, NULL, modulemd_defaults_test_copy, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_merging", DefaultsFixture, NULL, NULL, modulemd_defaults_test_merging, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_prioritizer", DefaultsFixture, NULL, NULL, modulemd_defaults_test_prioritizer, NULL); g_test_add ("/modulemd/defaults/modulemd_defaults_test_index_prioritizer", DefaultsFixture, NULL, NULL, modulemd_defaults_test_index_prioritizer, NULL); g_test_add ("/modulemd/defaults/modulemd_regressions_issue42", DefaultsFixture, NULL, NULL, modulemd_regressions_issue42, NULL); g_test_add ("/modulemd/defaults/modulemd_regressions_issue44", DefaultsFixture, NULL, NULL, modulemd_regressions_issue44, NULL); g_test_add ("/modulemd/defaults/modulemd_regressions_issue45", DefaultsFixture, NULL, NULL, modulemd_regressions_issue45, NULL); return g_test_run (); };
lubomir/libmodulemd
modulemd/include/modulemd-1.0/modulemd-modulestream.h
<gh_stars>0 /* * This file is part of libmodulemd * Copyright (C) 2017-2018 <NAME> * * Fedora-License-Identifier: MIT * SPDX-2.0-License-Identifier: MIT * SPDX-3.0-License-Identifier: MIT * * This program is free software. * For more information on the license, see COPYING. * For more information on free software, see <https://www.gnu.org/philosophy/free-sw.en.html>. */ #pragma once #include "modulemd-buildopts.h" #include "modulemd-component-module.h" #include "modulemd-component-rpm.h" #include "modulemd-defaults.h" #include "modulemd-dependencies.h" #include "modulemd-profile.h" #include "modulemd-servicelevel.h" #include "modulemd-simpleset.h" #include "modulemd-translation.h" #include <glib-object.h> G_BEGIN_DECLS /** * SECTION: modulemd-modulestream * @title: Modulemd.ModuleStream * @short_description: The data to represent a stream of a module as described * by a modulemd YAML document. */ #define MODULEMD_MODULESTREAM_ERROR modulemd_modulestream_error_quark () GQuark modulemd_modulestream_error_quark (void); enum ModulemdModuleStreamError { MODULEMD_MODULESTREAM_ERROR_MISSING_CONTENT, }; #define MODULEMD_TYPE_MODULESTREAM modulemd_modulestream_get_type () G_DECLARE_FINAL_TYPE ( ModulemdModuleStream, modulemd_modulestream, MODULEMD, MODULESTREAM, GObject) /** * modulemd_modulestream_new: * * Allocates a new #ModulemdModuleStream. * * Return value: a new #ModulemdModuleStream. * * Since: 1.6 */ ModulemdModuleStream * modulemd_modulestream_new (void); /** * modulemd_modulestream_copy: * * Make a copy of the current module * * Returns: (transfer full): A deep copy of this #ModulemdModuleStream * * Since: 1.1 */ ModulemdModuleStream * modulemd_modulestream_copy (ModulemdModuleStream *self); /** * modulemd_modulestream_import_from_file: * @yaml_file: A YAML file containing the module metadata. If this file * contains more than one subdocument, the entire document will be parsed but * only the first document will be returned, if it is a valid module. * @failures: (element-type ModulemdSubdocument) (transfer container) (out): * An array containing any subdocuments from the YAML file that failed to * parse. This must be freed with g_ptr_array_unref(). * * Populates this #ModulemdModuleStream with data from a YAML file. * * Return value: * False if a parse error occurred and sets @error and @failures. * False if the first subdocument was not a module and sets @error * * Since: 1.6 */ gboolean modulemd_modulestream_import_from_file (ModulemdModuleStream *self, const gchar *yaml_file, GPtrArray **failures, GError **error); /** * modulemd_modulestream_dump: * @yaml_file: A string containing the path to the output file * * Writes this module stream out to a YAML document on disk. * * Returns: False if the file could not be written and sets @error. * * Since: 1.6 */ gboolean modulemd_modulestream_dump (ModulemdModuleStream *self, const gchar *yaml_file, GError **error); /** * modulemd_modulestream_import_from_string: * @yaml_string: A YAML string containing the module metadata. If this string * contains more than one subdocument, the entire document will be parsed but * only the first document will be returned, if it is a valid module. * @failures: (element-type ModulemdSubdocument) (transfer container) (out): * An array containing any subdocuments from the YAML file that failed to * parse. This must be freed with g_ptr_array_unref(). * * Populates this #ModulemdModuleStream with data from a YAML string. * * Return value: * False if a parse error occurred and sets @error and @failures. * False if the first subdocument was not a module and sets @error * * Since: 1.6 */ gboolean modulemd_modulestream_import_from_string (ModulemdModuleStream *self, const gchar *yaml_string, GPtrArray **failures, GError **error); /** * modulemd_modulestream_dumps: * * Writes this module out to a YAML document string. * * Returns: (transfer full): The serialized YAML representation of this stream * document or NULL and sets @error appropriately. The returned string must be * freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_dumps (ModulemdModuleStream *self, GError **error); /** * modulemd_modulestream_import_from_stream: * @stream: A YAML stream containing the module metadata. If this stream * contains more than one subdocument, the entire document will be parsed but * only the first document will be returned, if it is a valid module. * @failures: (element-type ModulemdSubdocument) (transfer container) (out): * An array containing any subdocuments from the YAML file that failed to * parse. This must be freed with g_ptr_array_unref(). * * Populates this #ModulemdModuleStream with data from a YAML stream. * * Return value: * False if a parse error occurred and sets @error and @failures. * False if the first subdocument was not a module and sets @error * * Since: 1.6 */ gboolean modulemd_modulestream_import_from_stream (ModulemdModuleStream *self, FILE *stream, GPtrArray **failures, GError **error); /** * modulemd_modulestream_upgrade: * Upgrade the module to the latest supported version * * This function takes content imported from earlier versions of the modulemd * format and upgrades it into the most recent version. * * Return value: TRUE if the upgrade was performed successfully. If this * function returns FALSE, the internal state of the data is undefined and * should not be used further. * * Since: 1.6 */ gboolean modulemd_modulestream_upgrade (ModulemdModuleStream *self); /** * modulemd_modulestream_set_arch: * @arch: (nullable): the module artifact architecture. * * Sets the "arch" property. * * Since: 1.6 */ void modulemd_modulestream_set_arch (ModulemdModuleStream *self, const gchar *arch); /** * modulemd_modulestream_get_arch: * * Retrieves the "arch" for modulemd. * * Returns: (transfer full): A string containing the "arch" property. This * string must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_arch (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_arch: (skip) * * Retrieves the "arch" for modulemd. * * Returns: A string containing the "arch" property. This string must not be * modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_arch (ModulemdModuleStream *self); /** * modulemd_modulestream_set_buildopts: * @buildopts: (nullable) (transfer none): A #ModulemdBuildopts object * * Copies a #ModulemdBuildopts object into the module. This object contains * additional instructions to the build system required to build this module. * * Since: 1.6 */ void modulemd_modulestream_set_buildopts (ModulemdModuleStream *self, ModulemdBuildopts *buildopts); /** * modulemd_modulestream_get_buildopts: * * Get a copy of the #ModulemdBuildopts object * * Returns: (transfer full): a copy of the #ModulemdBuildopts object. This * object must be freed with g_object_unref() when the caller is finished with * it. This function will return NULL if no buildopts have been set. * * Since: 1.6 */ ModulemdBuildopts * modulemd_modulestream_get_buildopts (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_buildopts: (skip) * * Get a copy of the #ModulemdBuildopts object * * Returns: (transfer none): The #ModulemdBuildopts object. This * object must not be modified or freed. * This function will return NULL if no buildopts have been set. * * Since: 1.6 */ ModulemdBuildopts * modulemd_modulestream_peek_buildopts (ModulemdModuleStream *self); /** * modulemd_modulestream_set_buildrequires: * @buildrequires: (nullable) (element-type utf8 utf8) (transfer none): The * requirements to build this module. * * Sets the 'buildrequires' property. This function was deprecated and is not * valid for modulemd files of version 2 or later. * * Since: 1.6 */ void modulemd_modulestream_set_buildrequires (ModulemdModuleStream *self, GHashTable *buildrequires); /** * modulemd_modulestream_get_buildrequires: * * Retrieves the "buildrequires" for modulemd. * * Returns: (element-type utf8 utf8) (transfer container): A hash table * containing the "buildrequires" property. This table must be freed with * g_hash_table_unref(). * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_buildrequires (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_buildrequires: (skip) * * Retrieves the "buildrequires" for modulemd. * * Returns: (element-type utf8 utf8) (transfer none): A hash table * containing the "buildrequires" property. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_buildrequires (ModulemdModuleStream *self); /** * modulemd_modulestream_set_community: * @community: (nullable) (transfer none): the module community. * * Sets the "community" property. * * Since: 1.6 */ void modulemd_modulestream_set_community (ModulemdModuleStream *self, const gchar *community); /** * modulemd_modulestream_get_community: * * Retrieves the "community" for modulemd. * * Returns: (transfer full): A string containing the "community" property. This * string must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_community (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_community: (skip) * * Retrieves the "community" for modulemd. * * Returns: A string containing the "community" property. This string must not * be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_community (ModulemdModuleStream *self); /** * modulemd_modulestream_set_content_licenses: * @licenses: (nullable) (transfer none): A #ModuleSimpleSet: The licenses under * which the components of this module are released. * * Sets the content_licenses property. * * Since: 1.6 */ void modulemd_modulestream_set_content_licenses (ModulemdModuleStream *self, ModulemdSimpleSet *licenses); /** * modulemd_modulestream_get_content_licenses: * * Retrieves the "content_licenses" for modulemd * * Returns: (transfer full): a #SimpleSet containing the set of licenses in the * "content_licenses" property. The returned #SimpleSet must be freed with * g_object_unref(). * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_get_content_licenses (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_content_licenses: (skip) * * Retrieves the "content_licenses" for modulemd * * Returns: (transfer none): a #SimpleSet containing the set of licenses in the * "content_licenses" property. This #SimpleSet must not be modified or freed. * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_peek_content_licenses (ModulemdModuleStream *self); /** * modulemd_modulestream_set_context: * @context: (nullable) (transfer none): the module artifact architecture. * * Sets the "context" property. * * Since: 1.6 */ void modulemd_modulestream_set_context (ModulemdModuleStream *self, const gchar *context); /** * modulemd_modulestream_get_context: * * Retrieves the "context" for modulemd. * * Returns: (transfer full): A string containing the "context" property. This * string must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_context (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_context: (skip) * * Retrieves the "context" for modulemd. * * Returns: (transfer none): A string containing the "context" property. This * string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_context (ModulemdModuleStream *self); /** * modulemd_modulestream_set_dependencies: * @deps: (array zero-terminated=1) (element-type ModulemdDependencies) (transfer none) (nullable): * The list of #ModulemdDependencies for this module stream. * * Sets the list of #ModulemdDependencies objects for this module stream. * * Since: 1.6 */ void modulemd_modulestream_set_dependencies (ModulemdModuleStream *self, GPtrArray *deps); /** * modulemd_modulestream_add_dependencies: * @dep: (transfer none): A #ModulemdDependencies object to add to this module * * Helper function to populate the dependencies list * * Since: 1.6 */ void modulemd_modulestream_add_dependencies (ModulemdModuleStream *self, ModulemdDependencies *dep); /** * modulemd_modulestream_get_dependencies: * * Returns: (element-type ModulemdDependencies) (transfer container): The list * of dependency objects for this module. This list must be freed with * g_ptr_array_unref(). * * Since: 1.6 */ GPtrArray * modulemd_modulestream_get_dependencies (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_dependencies: (skip) * * Returns: (element-type ModulemdDependencies) (transfer none): The list * of dependency objects for this module. This list and its contents must not * be modified or freed. * * Since: 1.6 */ GPtrArray * modulemd_modulestream_peek_dependencies (ModulemdModuleStream *self); /** * modulemd_modulestream_set_description: * @description: (transfer none) (nullable): the module description. * * Sets the "description" property. * * Since: 1.6 */ void modulemd_modulestream_set_description (ModulemdModuleStream *self, const gchar *description); /** * modulemd_modulestream_get_description: * * Retrieves the "description" for modulemd. * * Returns: (transfer full): A string containing the "description" property. * This string must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_description (ModulemdModuleStream *self); /** * modulemd_modulestream_get_localized_description: * @locale: (transfer none) (nullable): Specify the locale for the description. * If NULL is passed, it will attempt to use the LC_MESSAGES locale. If "C" is * passed or if the locale has no translation available, it will treat it as * untranslated. * * Returns: (transfer full): A string containing the "description" property, * translated into the language specified by @locale if possible. This string * must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_localized_description (ModulemdModuleStream *self, const gchar *locale); /** * modulemd_modulestream_peek_description: (skip) * * Retrieves the "description" for modulemd. * * Returns: (transfer none): A string containing the "description" property. * This string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_description (ModulemdModuleStream *self); /** * modulemd_modulestream_set_documentation: * @documentation: (transfer none) (nullable): the module documentation. * * Sets the "documentation" property. * * Since: 1.6 */ void modulemd_modulestream_set_documentation (ModulemdModuleStream *self, const gchar *documentation); /** * modulemd_modulestream_get_documentation: * * Retrieves the "documentation" for modulemd. * * Returns: (transfer full): A string containing the "documentation" property. * This string must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_documentation (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_documentation: (skip) * * Retrieves the "documentation" for modulemd. * * Returns: (transfer none): A string containing the "documentation" property. * This string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_documentation (ModulemdModuleStream *self); /** * modulemd_modulestream_set_eol: * @date: (transfer none) (nullable): The end-of-life date of the module * * Sets the "eol" property. * * Note: This property is obsolete. Use "servicelevels" instead. This will fail * on modulemd files using the version 2 or later formats. * * Since: 1.6 */ void modulemd_modulestream_set_eol (ModulemdModuleStream *self, const GDate *date); /** * modulemd_modulestream_get_eol: * * Retrieves the "eol" property. * * Note: This property is obsolete. Use "servicelevels" instead. This will fail * on modulemd files using the version 2 or later formats. * * Returns: (transfer full): A #GDate containing the "EOL" date. * This #GDate must be freed with g_date_free(). * * Since: 1.6 */ GDate * modulemd_modulestream_get_eol (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_eol: (skip) * * Retrieves the "eol" property. * * Note: This property is obsolete. Use "servicelevels" instead. This will fail * on modulemd files using the version 2 or later formats. * * Returns: (transfer none): A #GDate containing the "EOL" date. This #GDate * must not be modified or freed. * * Since: 1.6 */ const GDate * modulemd_modulestream_peek_eol (ModulemdModuleStream *self); /** * modulemd_modulestream_set_mdversion * @mdversion: the metadata version * * Sets the "mdversion" property. * * Since: 1.6 */ void modulemd_modulestream_set_mdversion (ModulemdModuleStream *self, const guint64 mdversion); /** * modulemd_modulestream_get_mdversion: * * Retrieves the "mdversion" for modulemd. * * Returns: A 64-bit unsigned integer containing the "mdversion" property. * * Since: 1.6 */ guint64 modulemd_modulestream_get_mdversion (ModulemdModuleStream *self); /** * modulemd_modulestream_add_module_component: * @component: (transfer none): A #ModulemdComponentModule * * Adds a #ModulemdComponentModule to the "module_components" hash table. * * Since: 1.6 */ void modulemd_modulestream_add_module_component ( ModulemdModuleStream *self, ModulemdComponentModule *component); /** * modulemd_modulestream_clear_module_components: * * Remove all entries from the "module_components" hash table. * * Since: 1.6 */ void modulemd_modulestream_clear_module_components (ModulemdModuleStream *self); /** * modulemd_modulestream_set_module_components: * @components: (transfer none) (nullable) (element-type utf8 ModulemdComponentModule): * The hash table of module components that comprise this module. The keys are * the module name, the values are a #ModulemdComponentModule containing * information about that module. * * Sets the module_components property. * * Since: 1.6 */ void modulemd_modulestream_set_module_components (ModulemdModuleStream *self, GHashTable *components); /** * modulemd_modulestream_get_module_components: * * Retrieves the "module-components" for modulemd. * * Returns: (element-type utf8 ModulemdComponentModule) (transfer container): A hash * table containing the "module-components" property. This table must be freed * with g_hash_table_unref(). * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_module_components (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_module_components: (skip) * * Retrieves the "module-components" for modulemd. * * Returns: (element-type utf8 ModulemdComponentModule) (transfer none): A hash * table containing the "module-components" property. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_module_components (ModulemdModuleStream *self); /** * modulemd_modulestream_set_module_licenses: * @licenses: (transfer none) (nullable): A #ModuleSimpleSet: The licenses under * which the components of this module are released. * * Sets the module_licenses property. * * Since: 1.6 */ void modulemd_modulestream_set_module_licenses (ModulemdModuleStream *self, ModulemdSimpleSet *licenses); /** * modulemd_modulestream_get_module_licenses: * * Retrieves the "module_licenses" for modulemd * * Returns: (transfer full): a #ModulemdSimpleSet containing the set of * licenses in the "module_licenses" property. This #ModulemdSimpleSet must be * freed with g_object_unref(). * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_get_module_licenses (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_module_licenses: (skip) * * Retrieves the "module_licenses" for modulemd * * Returns: (transfer none): a #ModulemdSimpleSet containing the set of * licenses in the "module_licenses" property. * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_peek_module_licenses (ModulemdModuleStream *self); /** * modulemd_modulestream_set_name: * @name: (transfer none) (nullable): the module name. * * Sets the "name" property. * * Since: 1.6 */ void modulemd_modulestream_set_name (ModulemdModuleStream *self, const gchar *name); /** * modulemd_modulestream_get_name: * * Retrieves the "name" for modulemd. * * Returns: (transfer full): A string containing the "name" property. This string * must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_name (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_name: (skip) * * Retrieves the "name" for modulemd. * * Returns: (transfer none): A string containing the "name" property. This * string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_name (ModulemdModuleStream *self); /** * modulemd_modulestream_add_profile: * @profile: (transfer none): A #ModulemdProfile * * Adds a #ModulemdProfile definition to this module. * * Since: 1.6 */ void modulemd_modulestream_add_profile (ModulemdModuleStream *self, ModulemdProfile *profile); /** * modulemd_modulestream_clear_profiles: * * Remove all entries from the "profiles" hash table. * * Since: 1.6 */ void modulemd_modulestream_clear_profiles (ModulemdModuleStream *self); /** * modulemd_modulestream_set_profiles: * @profiles: (transfer none) (nullable) (element-type utf8 ModulemdProfile): * The profiles available for this module. * * Sets the 'profiles' property. * * Since: 1.6 */ void modulemd_modulestream_set_profiles (ModulemdModuleStream *self, GHashTable *profiles); /** * modulemd_modulestream_get_profiles: * * Retrieves the "profiles" for modulemd. * * Returns: (element-type utf8 ModulemdProfile) (transfer container): A hash * table containing the "profiles" property. This table must be freed with * g_hash_table_unref(). * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_profiles (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_profiles: (skip) * * Retrieves the "profiles" for modulemd. * * Returns: (element-type utf8 ModulemdProfile) (transfer none): A hash * table containing the "profiles" property. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_profiles (ModulemdModuleStream *self); /** * modulemd_modulestream_set_requires: * @requires: (transfer none) (nullable) (element-type utf8 utf8): The * requirements to run this module * * Sets the 'requires' property. This function was deprecated and is not * valid for modulemd files of version 2 or later. * * Since: 1.6 */ void modulemd_modulestream_set_requires (ModulemdModuleStream *self, GHashTable *requires); /** * modulemd_modulestream_get_requires: * * Retrieves the "requires" for modulemd. * * Returns: (element-type utf8 utf8) (transfer container): A hash table * containing the "requires" property. This function was deprecated and is not * valid for modulemd files of version 2 or later. This table must be freed with * g_hash_table_unref(). * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_requires (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_requires: (skip) * * Retrieves the "requires" for modulemd. * * Returns: (element-type utf8 utf8) (transfer none): A hash table * containing the "requires" property. This function was deprecated and is not * valid for modulemd files of version 2 or later. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_requires (ModulemdModuleStream *self); /** * modulemd_modulestream_set_rpm_api: * @apis: (transfer none) (nullable): A #ModuleSimpleSet: The set of binary RPM * packages that form the public API for this module. * * Sets the rpm_api property. * * Since: 1.6 */ void modulemd_modulestream_set_rpm_api (ModulemdModuleStream *self, ModulemdSimpleSet *apis); /** * modulemd_modulestream_get_rpm_api: * * Retrieves the "rpm_api" for modulemd * * Returns: (transfer full): a #ModulemdSimpleSet containing the set of binary * RPM packages in the "rpm_api" property. This #ModulemdSimpleSet must be freed * with g_object_unref(). * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_get_rpm_api (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_rpm_api: (skip) * * Retrieves the "rpm_api" for modulemd * * Returns: (transfer none): a #ModulemdSimpleSet containing the set of binary * RPM packages in the "rpm_api" property. This #ModulemdSimpleSet must not be * modified or freed. * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_peek_rpm_api (ModulemdModuleStream *self); /** * modulemd_modulestream_set_rpm_artifacts: * @artifacts: (transfer none) (nullable): A #ModuleSimpleSet: The set of binary * RPM packages that are contained in this module. Generally populated by the * module build service. * * Sets the rpm_artifacts property. * * Since: 1.6 */ void modulemd_modulestream_set_rpm_artifacts (ModulemdModuleStream *self, ModulemdSimpleSet *artifacts); /** * modulemd_modulestream_get_rpm_artifacts: * * Retrieves the "rpm_artifacts" for modulemd * * Returns: (transfer full): a #SimpleSet containing the set of binary RPMs * contained in this module. * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_get_rpm_artifacts (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_rpm_artifacts: (skip) * * Retrieves the "rpm_artifacts" for modulemd * * Returns: (transfer none): a #SimpleSet containing the set of binary RPMs * contained in this module. * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_peek_rpm_artifacts (ModulemdModuleStream *self); /** * modulemd_modulestream_add_rpm_component: * @component: (transfer none): A #ModulemdComponentRpm * * Adds a #ModulemdComponentRpm to the "rpm_components" hash table. * * Since: 1.6 */ void modulemd_modulestream_add_rpm_component (ModulemdModuleStream *self, ModulemdComponentRpm *component); /** * modulemd_modulestream_clear_rpm_components: * * Remove all entries from the "rpm_components" hash table. * * Since: 1.6 */ void modulemd_modulestream_clear_rpm_components (ModulemdModuleStream *self); /** * modulemd_modulestream_set_rpm_components: * @components: (transfer none) (nullable) (element-type utf8 ModulemdComponentRpm): * The hash table of module components that comprise this module. The keys are * the module name, the values are a #ModulemdComponentRpm containing * information about that module. * * Sets the rpm_components property. * * Since: 1.6 */ void modulemd_modulestream_set_rpm_components (ModulemdModuleStream *self, GHashTable *components); /** * modulemd_modulestream_get_rpm_components: * * Retrieves the "rpm-components" for modulemd. * * Returns: (element-type utf8 ModulemdComponentRpm) (transfer container): A hash * table containing the "rpm-components" property. This table must be freed with * g_hash_table_unref(). * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_rpm_components (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_rpm_components: (skip) * * Retrieves the "rpm-components" for modulemd. * * Returns: (element-type utf8 ModulemdComponentRpm) (transfer none): A hash * table containing the "rpm-components" property. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_rpm_components (ModulemdModuleStream *self); /** * modulemd_modulestream_set_rpm_filter: * @filter: (transfer none) (nullable): A #ModuleSimpleSet: The set of binary * RPM packages that are explicitly filtered out of this module. * * Sets the rpm_artifacts property. * * Since: 1.6 */ void modulemd_modulestream_set_rpm_filter (ModulemdModuleStream *self, ModulemdSimpleSet *filter); /** * modulemd_modulestream_get_rpm_filter: * * Retrieves the "rpm_filter" for modulemd * * Returns: (transfer full): a #ModulemdSimpleSet containing the set of binary * RPMs filtered out of this module. This #ModulemdSimpleSet must be freed with * g_object_unref(). * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_get_rpm_filter (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_rpm_filter: (skip) * * Retrieves the "rpm_filter" for modulemd * * Returns: (transfer none): a #ModulemdSimpleSet containing the set of binary * RPMs filtered out of this module. This #ModulemdSimpleSet must not be * modified or freed. * * Since: 1.6 */ ModulemdSimpleSet * modulemd_modulestream_peek_rpm_filter (ModulemdModuleStream *self); /** * modulemd_modulestream_clear_servicelevels: * * Remove all entries from the "servicelevels" hash table * * Since: 1.6 */ void modulemd_modulestream_clear_servicelevels (ModulemdModuleStream *self); /** * modulemd_modulestream_set_servicelevels: * @servicelevels: (transfer none) (nullable) (element-type utf8 ModulemdServiceLevel): * A hash table of #ModulemdServiceLevel objects * * Sets the service levels for the module. * * Since: 1.6 */ void modulemd_modulestream_set_servicelevels (ModulemdModuleStream *self, GHashTable *servicelevels); /** * modulemd_modulestream_add_servicelevel: * @servicelevel: (transfer none): A #ModulemdServiceLevel object to add to the hash table * * Adds a service levels to the module. If the name already exists, it will be * replaced by this entry and will release a reference on the previous entry. * * Since: 1.6 */ void modulemd_modulestream_add_servicelevel (ModulemdModuleStream *self, ModulemdServiceLevel *servicelevel); /** * modulemd_modulestream_get_servicelevels: * * Retrieves the service levels for the module * * Returns: (element-type utf8 ModulemdServiceLevel) (transfer container): A * hash table containing the service levels. This table must be freed with * g_hash_table_unref(). * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_servicelevels (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_servicelevels: (skip) * * Retrieves the service levels for the module * * Returns: (element-type utf8 ModulemdServiceLevel) (transfer none): A * hash table containing the service levels. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_servicelevels (ModulemdModuleStream *self); /** * modulemd_modulestream_set_stream: * @stream: (transfer none) (nullable): the module stream. * * Sets the "stream" property. * * Since: 1.6 */ void modulemd_modulestream_set_stream (ModulemdModuleStream *self, const gchar *stream); /** * modulemd_modulestream_get_stream: * * Retrieves the "stream" for modulemd. * * Returns: A string containing the "stream" property. This string must be freed * with g_free(). * * Deprecated: 1.1 * Use peek_stream() instead. * * Since: 1.6 */ gchar * modulemd_modulestream_get_stream (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_stream: (skip) * * Retrieves the "stream" for modulemd. * * Returns: (transfer none): A string containing the "stream" property. This * string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_stream (ModulemdModuleStream *self); /** * modulemd_modulestream_set_summary: * @summary: (transfer none) (nullable): the module summary. * * Sets the "summary" property. * * Since: 1.6 */ void modulemd_modulestream_set_summary (ModulemdModuleStream *self, const gchar *summary); /** * modulemd_modulestream_get_summary: * * Retrieves the "summary" for modulemd. * * Returns: A string containing the "summary" property. This string must be * freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_summary (ModulemdModuleStream *self); /** * modulemd_modulestream_get_localized_summary: * @locale: (transfer none) (nullable): Specify the locale for the summary. If * NULL is passed, it will attempt to use the LC_MESSAGES locale. If "C" is * passed or if the locale has no translation available, it will treat it as * untranslated. * * Returns: (transfer full): A string containing the "summary" property, * translated into the language specified by @locale if possible. This string * must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_localized_summary (ModulemdModuleStream *self, const gchar *locale); /** * modulemd_modulestream_peek_summary: (skip) * * Retrieves the "summary" for modulemd. * * Returns: (transfer none): A string containing the "summary" property. This * string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_summary (ModulemdModuleStream *self); /** * modulemd_modulestream_set_tracker: * @tracker: (transfer none) (nullable): the module tracker. * * Sets the "tracker" property. * * Since: 1.6 */ void modulemd_modulestream_set_tracker (ModulemdModuleStream *self, const gchar *tracker); /** * modulemd_modulestream_get_tracker: * * Retrieves the "tracker" for modulemd. * * Returns: (transfer full): A string containing the "tracker" property. This * string must be freed with g_free(). * * Since: 1.6 */ gchar * modulemd_modulestream_get_tracker (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_tracker: (skip) * * Retrieves the "tracker" for modulemd. * * Returns: (transfer none): A string containing the "tracker" property. This * string must not be modified or freed. * * Since: 1.6 */ const gchar * modulemd_modulestream_peek_tracker (ModulemdModuleStream *self); /** * modulemd_modulestream_set_translation: * @translation: (transfer none) (nullable): A #ModulemdTranslation associated * with this module and stream which provides translated strings. If the passed * #ModulemdTranslation does not match this module and stream, it will have no * effect, but a warning will be emitted. * * Since: 1.6 */ void modulemd_modulestream_set_translation (ModulemdModuleStream *self, ModulemdTranslation *translation); /** * modulemd_modulestream_get_translation: * * Returns: (transfer full): A #ModulemdTranslation object associated with this * module and stream. * * Since: 1.6 */ ModulemdTranslation * modulemd_modulestream_get_translation (ModulemdModuleStream *self); /** * modulemd_modulestream_set_version * @version: the module version * * Sets the "version" property. * * Since: 1.6 */ void modulemd_modulestream_set_version (ModulemdModuleStream *self, const guint64 version); /** * modulemd_modulestream_get_version: * * Retrieves the "version" for modulemd. * * Returns: A 64-bit unsigned integer containing the "version" property. * * Since: 1.6 */ guint64 modulemd_modulestream_get_version (ModulemdModuleStream *self); /** * modulemd_modulestream_set_xmd: * @xmd: (transfer none) (nullable) (element-type utf8 GVariant): Extensible * metadata block * * Sets the 'xmd' property. * * Since: 1.6 */ void modulemd_modulestream_set_xmd (ModulemdModuleStream *self, GHashTable *xmd); /** * modulemd_modulestream_get_xmd: * * Retrieves the "xmd" for modulemd. * * Returns: (element-type utf8 GVariant) (transfer container): A hash table * containing the "xmd" property. * * Since: 1.6 */ GHashTable * modulemd_modulestream_get_xmd (ModulemdModuleStream *self); /** * modulemd_modulestream_peek_xmd: (skip) * * Retrieves the "xmd" for modulemd. * * Returns: (element-type utf8 GVariant) (transfer none): A hash table * containing the "xmd" property. * * Since: 1.6 */ GHashTable * modulemd_modulestream_peek_xmd (ModulemdModuleStream *self); /** * modulemd_modulestream_get_nsvc: * * Return the unique module identifier. * * Returns: a string describing the unique module identifier in the form: * "NAME:STREAM:VERSION[:CONTEXT]". This string is owned by the caller and * must be freed with g_free(). */ gchar * modulemd_modulestream_get_nsvc (ModulemdModuleStream *self); G_END_DECLS
Kristopher38/LuaCPU
software/lua_on_nios2/lua/luaconf.h
/* ** $Id: luaconf.h,v 1.259.1.1 2017/04/19 17:29:57 roberto Exp $ ** Configuration file for Lua ** See Copyright Notice in lua.h */ #ifndef luaconf_h #define luaconf_h #include <limits.h> #include <stddef.h> /* ** =================================================================== ** Search for "@@" to find all configurable definitions. ** =================================================================== */ /* ** {==================================================================== ** System Configuration: macros to adapt (if needed) Lua to some ** particular platform, for instance compiling it with 32-bit numbers or ** restricting it to C89. ** ===================================================================== */ /* @@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. You ** can also define LUA_32BITS in the make file, but changing here you ** ensure that all software connected to Lua will be compiled with the ** same configuration. */ /* #define LUA_32BITS */ /* @@ LUA_USE_C89 controls the use of non-ISO-C89 features. ** Define it if you want Lua to avoid the use of a few C99 features ** or Windows-specific features on Windows. */ /* #define LUA_USE_C89 */ /* ** By default, Lua on Windows use (some) specific Windows features */ #if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) #define LUA_USE_WINDOWS /* enable goodies for regular Windows */ #endif #if defined(LUA_USE_WINDOWS) #define LUA_DL_DLL /* enable support for DLL */ #define LUA_USE_C89 /* broadly, Windows is C89 */ #endif #if defined(LUA_USE_LINUX) #define LUA_USE_POSIX #define LUA_USE_DLOPEN /* needs an extra library: -ldl */ #define LUA_USE_READLINE /* needs some extra libraries */ #endif #if defined(LUA_USE_MACOSX) #define LUA_USE_POSIX #define LUA_USE_DLOPEN /* MacOS does not need -ldl */ #define LUA_USE_READLINE /* needs an extra library: -lreadline */ #endif /* @@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for ** C89 ('long' and 'double'); Windows always has '__int64', so it does ** not need to use this case. */ #if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) #define LUA_C89_NUMBERS #endif /* @@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'. */ /* avoid undefined shifts */ #if ((INT_MAX >> 15) >> 15) >= 1 #define LUAI_BITSINT 32 #else /* 'int' always must have at least 16 bits */ #define LUAI_BITSINT 16 #endif /* @@ LUA_INT_TYPE defines the type for Lua integers. @@ LUA_FLOAT_TYPE defines the type for Lua floats. ** Lua should work fine with any mix of these options (if supported ** by your C compiler). The usual configurations are 64-bit integers ** and 'double' (the default), 32-bit integers and 'float' (for ** restricted platforms), and 'long'/'double' (for C compilers not ** compliant with C99, which may not have support for 'long long'). */ /* predefined options for LUA_INT_TYPE */ #define LUA_INT_INT 1 #define LUA_INT_LONG 2 #define LUA_INT_LONGLONG 3 /* predefined options for LUA_FLOAT_TYPE */ #define LUA_FLOAT_FLOAT 1 #define LUA_FLOAT_DOUBLE 2 #define LUA_FLOAT_LONGDOUBLE 3 #if defined(LUA_32BITS) /* { */ /* ** 32-bit integers and 'float' */ #if LUAI_BITSINT >= 32 /* use 'int' if big enough */ #define LUA_INT_TYPE LUA_INT_INT #else /* otherwise use 'long' */ #define LUA_INT_TYPE LUA_INT_LONG #endif #define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT #elif defined(LUA_C89_NUMBERS) /* }{ */ /* ** largest types available for C89 ('long' and 'double') */ #define LUA_INT_TYPE LUA_INT_LONG #define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE #endif /* } */ /* ** default configuration for 64-bit Lua ('long long' and 'double') */ #if !defined(LUA_INT_TYPE) #define LUA_INT_TYPE LUA_INT_LONGLONG #endif #if !defined(LUA_FLOAT_TYPE) #define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE #endif /* }================================================================== */ /* ** {================================================================== ** Configuration for Paths. ** =================================================================== */ /* ** LUA_PATH_SEP is the character that separates templates in a path. ** LUA_PATH_MARK is the string that marks the substitution points in a ** template. ** LUA_EXEC_DIR in a Windows path is replaced by the executable's ** directory. */ #define LUA_PATH_SEP ";" #define LUA_PATH_MARK "?" #define LUA_EXEC_DIR "!" /* @@ LUA_PATH_DEFAULT is the default path that Lua uses to look for ** Lua libraries. @@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for ** C libraries. ** CHANGE them if your machine has a non-conventional directory ** hierarchy or if you want to install your libraries in ** non-conventional directories. */ #define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR #if defined(_WIN32) /* { */ /* ** In Windows, any exclamation mark ('!') in the path is replaced by the ** path of the directory of the executable file of the current process. */ #define LUA_LDIR "!\\lua\\" #define LUA_CDIR "!\\" #define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" #define LUA_PATH_DEFAULT \ LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ ".\\?.lua;" ".\\?\\init.lua" #define LUA_CPATH_DEFAULT \ LUA_CDIR"?.dll;" \ LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ LUA_CDIR"loadall.dll;" ".\\?.dll" #else /* }{ */ #define LUA_ROOT "/usr/local/" #define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" #define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" #define LUA_PATH_DEFAULT \ LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ "./?.lua;" "./?/init.lua" #define LUA_CPATH_DEFAULT \ LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" #endif /* } */ /* @@ LUA_DIRSEP is the directory separator (for submodules). ** CHANGE it if your machine does not use "/" as the directory separator ** and is not Windows. (On Windows Lua automatically uses "\".) */ #if defined(_WIN32) #define LUA_DIRSEP "\\" #else #define LUA_DIRSEP "/" #endif /* }================================================================== */ /* ** {================================================================== ** Marks for exported symbols in the C code ** =================================================================== */ /* @@ LUA_API is a mark for all core API functions. @@ LUALIB_API is a mark for all auxiliary library functions. @@ LUAMOD_API is a mark for all standard library opening functions. ** CHANGE them if you need to define those functions in some special way. ** For instance, if you want to create one Windows DLL with the core and ** the libraries, you may want to use the following definition (define ** LUA_BUILD_AS_DLL to get it). */ #if defined(LUA_BUILD_AS_DLL) /* { */ #if defined(LUA_CORE) || defined(LUA_LIB) /* { */ #define LUA_API __declspec(dllexport) #else /* }{ */ #define LUA_API __declspec(dllimport) #endif /* } */ #else /* }{ */ #define LUA_API extern #endif /* } */ /* more often than not the libs go together with the core */ #define LUALIB_API LUA_API #define LUAMOD_API LUALIB_API /* @@ LUAI_FUNC is a mark for all extern functions that are not to be ** exported to outside modules. @@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables ** that are not to be exported to outside modules (LUAI_DDEF for ** definitions and LUAI_DDEC for declarations). ** CHANGE them if you need to mark them in some special way. Elf/gcc ** (versions 3.2 and later) mark them as "hidden" to optimize access ** when Lua is compiled as a shared library. Not all elf targets support ** this attribute. Unfortunately, gcc does not offer a way to check ** whether the target offers that support, and those without support ** give a warning about it. To avoid these warnings, change to the ** default definition. */ #if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ defined(__ELF__) /* { */ #define LUAI_FUNC __attribute__((visibility("hidden"))) extern #else /* }{ */ #define LUAI_FUNC extern #endif /* } */ #define LUAI_DDEC LUAI_FUNC #define LUAI_DDEF /* empty */ /* }================================================================== */ /* ** {================================================================== ** Compatibility with previous versions ** =================================================================== */ /* @@ LUA_COMPAT_5_2 controls other macros for compatibility with Lua 5.2. @@ LUA_COMPAT_5_1 controls other macros for compatibility with Lua 5.1. ** You can define it to get all options, or change specific options ** to fit your specific needs. */ #if defined(LUA_COMPAT_5_2) /* { */ /* @@ LUA_COMPAT_MATHLIB controls the presence of several deprecated ** functions in the mathematical library. */ #define LUA_COMPAT_MATHLIB /* @@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'. */ #define LUA_COMPAT_BITLIB /* @@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod. */ #define LUA_COMPAT_IPAIRS /* @@ LUA_COMPAT_APIINTCASTS controls the presence of macros for ** manipulating other integer types (lua_pushunsigned, lua_tounsigned, ** luaL_checkint, luaL_checklong, etc.) */ #define LUA_COMPAT_APIINTCASTS #endif /* } */ #if defined(LUA_COMPAT_5_1) /* { */ /* Incompatibilities from 5.2 -> 5.3 */ #define LUA_COMPAT_MATHLIB #define LUA_COMPAT_APIINTCASTS /* @@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'. ** You can replace it with 'table.unpack'. */ #define LUA_COMPAT_UNPACK /* @@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'. ** You can replace it with 'package.searchers'. */ #define LUA_COMPAT_LOADERS /* @@ macro 'lua_cpcall' emulates deprecated function lua_cpcall. ** You can call your C function directly (with light C functions). */ #define lua_cpcall(L,f,u) \ (lua_pushcfunction(L, (f)), \ lua_pushlightuserdata(L,(u)), \ lua_pcall(L,1,0,0)) /* @@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library. ** You can rewrite 'log10(x)' as 'log(x, 10)'. */ #define LUA_COMPAT_LOG10 /* @@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base ** library. You can rewrite 'loadstring(s)' as 'load(s)'. */ #define LUA_COMPAT_LOADSTRING /* @@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library. */ #define LUA_COMPAT_MAXN /* @@ The following macros supply trivial compatibility for some ** changes in the API. The macros themselves document how to ** change your code to avoid using them. */ #define lua_strlen(L,i) lua_rawlen(L, (i)) #define lua_objlen(L,i) lua_rawlen(L, (i)) #define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) #define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) /* @@ LUA_COMPAT_MODULE controls compatibility with previous ** module functions 'module' (Lua) and 'luaL_register' (C). */ #define LUA_COMPAT_MODULE #endif /* } */ /* @@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a @@ a float mark ('.0'). ** This macro is not on by default even in compatibility mode, ** because this is not really an incompatibility. */ /* #define LUA_COMPAT_FLOATSTRING */ /* }================================================================== */ /* ** {================================================================== ** Configuration for Numbers. ** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* ** satisfy your needs. ** =================================================================== */ /* @@ LUA_NUMBER is the floating-point type used by Lua. @@ LUAI_UACNUMBER is the result of a 'default argument promotion' @@ over a floating number. @@ l_mathlim(x) corrects limit name 'x' to the proper float type ** by prefixing it with one of FLT/DBL/LDBL. @@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. @@ LUA_NUMBER_FMT is the format for writing floats. @@ lua_number2str converts a float to a string. @@ l_mathop allows the addition of an 'l' or 'f' to all math operations. @@ l_floor takes the floor of a float. @@ lua_str2number converts a decimal numeric string to a number. */ /* The following definitions are good for most cases here */ #define l_floor(x) (l_mathop(floor)(x)) #define lua_number2str(s,sz,n) \ l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) /* @@ lua_numbertointeger converts a float number to an integer, or ** returns 0 if float is not within the range of a lua_Integer. ** (The range comparisons are tricky because of rounding. The tests ** here assume a two-complement representation, where MININTEGER always ** has an exact representation as a float; MAXINTEGER may not have one, ** and therefore its conversion to float may have an ill-defined value.) */ #define lua_numbertointeger(n,p) \ ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ (*(p) = (LUA_INTEGER)(n), 1)) /* now the variable definitions */ #if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ #define LUA_NUMBER float #define l_mathlim(n) (FLT_##n) #define LUAI_UACNUMBER double #define LUA_NUMBER_FRMLEN "" #define LUA_NUMBER_FMT "%.7g" #define l_mathop(op) op##f #define lua_str2number(s,p) strtof((s), (p)) #elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ #define LUA_NUMBER long double #define l_mathlim(n) (LDBL_##n) #define LUAI_UACNUMBER long double #define LUA_NUMBER_FRMLEN "L" #define LUA_NUMBER_FMT "%.19Lg" #define l_mathop(op) op##l #define lua_str2number(s,p) strtold((s), (p)) #elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ #define LUA_NUMBER double #define l_mathlim(n) (DBL_##n) #define LUAI_UACNUMBER double #define LUA_NUMBER_FRMLEN "" #define LUA_NUMBER_FMT "%.14g" #define l_mathop(op) op #define lua_str2number(s,p) strtod((s), (p)) #else /* }{ */ #error "numeric float type not defined" #endif /* } */ /* @@ LUA_INTEGER is the integer type used by Lua. ** @@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. ** @@ LUAI_UACINT is the result of a 'default argument promotion' @@ over a lUA_INTEGER. @@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. @@ LUA_INTEGER_FMT is the format for writing integers. @@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. @@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. @@ lua_integer2str converts an integer to a string. */ /* The following definitions are good for most cases here */ #define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" #define LUAI_UACINT LUA_INTEGER #define lua_integer2str(s,sz,n) \ l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) /* ** use LUAI_UACINT here to avoid problems with promotions (which ** can turn a comparison between unsigneds into a signed comparison) */ #define LUA_UNSIGNED unsigned LUAI_UACINT /* now the variable definitions */ #if LUA_INT_TYPE == LUA_INT_INT /* { int */ #define LUA_INTEGER int #define LUA_INTEGER_FRMLEN "" #define LUA_MAXINTEGER INT_MAX #define LUA_MININTEGER INT_MIN #elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ #define LUA_INTEGER long #define LUA_INTEGER_FRMLEN "l" #define LUA_MAXINTEGER LONG_MAX #define LUA_MININTEGER LONG_MIN #elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ /* use presence of macro LLONG_MAX as proxy for C99 compliance */ #if defined(LLONG_MAX) /* { */ /* use ISO C99 stuff */ #define LUA_INTEGER long long #define LUA_INTEGER_FRMLEN "ll" #define LUA_MAXINTEGER LLONG_MAX #define LUA_MININTEGER LLONG_MIN #elif defined(LUA_USE_WINDOWS) /* }{ */ /* in Windows, can use specific Windows types */ #define LUA_INTEGER __int64 #define LUA_INTEGER_FRMLEN "I64" #define LUA_MAXINTEGER _I64_MAX #define LUA_MININTEGER _I64_MIN #else /* }{ */ #error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" #endif /* } */ #else /* }{ */ #error "numeric integer type not defined" #endif /* } */ /* }================================================================== */ /* ** {================================================================== ** Dependencies with C99 and other C details ** =================================================================== */ /* @@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. ** (All uses in Lua have only one format item.) */ #if !defined(LUA_USE_C89) #define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) #else #define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) #endif /* @@ lua_strx2number converts an hexadecimal numeric string to a number. ** In C99, 'strtod' does that conversion. Otherwise, you can ** leave 'lua_strx2number' undefined and Lua will provide its own ** implementation. */ #if !defined(LUA_USE_C89) #define lua_strx2number(s,p) lua_str2number(s,p) #endif /* @@ lua_pointer2str converts a pointer to a readable string in a ** non-specified way. */ #define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) /* @@ lua_number2strx converts a float to an hexadecimal numeric string. ** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. ** Otherwise, you can leave 'lua_number2strx' undefined and Lua will ** provide its own implementation. */ #if !defined(LUA_USE_C89) #define lua_number2strx(L,b,sz,f,n) \ ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) #endif /* ** 'strtof' and 'opf' variants for math functions are not valid in ** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the ** availability of these variants. ('math.h' is already included in ** all files that use these macros.) */ #if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) #undef l_mathop /* variants not available */ #undef lua_str2number #define l_mathop(op) (lua_Number)op /* no variant */ #define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) #endif /* @@ LUA_KCONTEXT is the type of the context ('ctx') for continuation ** functions. It must be a numerical type; Lua will use 'intptr_t' if ** available, otherwise it will use 'ptrdiff_t' (the nearest thing to ** 'intptr_t' in C89) */ #define LUA_KCONTEXT ptrdiff_t #if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ __STDC_VERSION__ >= 199901L #include <stdint.h> #if defined(INTPTR_MAX) /* even in C99 this type is optional */ #undef LUA_KCONTEXT #define LUA_KCONTEXT intptr_t #endif #endif /* @@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). ** Change that if you do not want to use C locales. (Code using this ** macro must include header 'locale.h'.) */ #if !defined(lua_getlocaledecpoint) #define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) #endif /* }================================================================== */ /* ** {================================================================== ** Language Variations ** ===================================================================== */ /* @@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some ** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from ** numbers to strings. Define LUA_NOCVTS2N to turn off automatic ** coercion from strings to numbers. */ /* #define LUA_NOCVTN2S */ /* #define LUA_NOCVTS2N */ /* @@ LUA_USE_APICHECK turns on several consistency checks on the C API. ** Define it as a help when debugging C code. */ #if defined(LUA_USE_APICHECK) #include <assert.h> #define luai_apicheck(l,e) assert(e) #endif /* }================================================================== */ /* ** {================================================================== ** Macros that affect the API and must be stable (that is, must be the ** same when you compile Lua and when you compile code that links to ** Lua). You probably do not want/need to change them. ** ===================================================================== */ /* @@ LUAI_MAXSTACK limits the size of the Lua stack. ** CHANGE it if you need a different limit. This limit is arbitrary; ** its only purpose is to stop Lua from consuming unlimited stack ** space (and to reserve some numbers for pseudo-indices). */ #if LUAI_BITSINT >= 32 #define LUAI_MAXSTACK 1000000 #else #define LUAI_MAXSTACK 15000 #endif /* @@ LUA_EXTRASPACE defines the size of a raw memory area associated with ** a Lua state with very fast access. ** CHANGE it if you need a different size. */ #define LUA_EXTRASPACE (sizeof(void *)) /* @@ LUA_IDSIZE gives the maximum size for the description of the source @@ of a function in debug information. ** CHANGE it if you want a different size. */ #define LUA_IDSIZE 60 /* @@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. ** CHANGE it if it uses too much C-stack space. (For long double, ** 'string.format("%.99f", -1e4932)' needs 5034 bytes, so a ** smaller buffer would force a memory allocation for each call to ** 'string.format'.) */ #if LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE #define LUAL_BUFFERSIZE 8192 #else #define LUAL_BUFFERSIZE ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer))) #endif /* }================================================================== */ /* @@ LUA_QL describes how error messages quote program elements. ** Lua does not use these macros anymore; they are here for ** compatibility only. */ #define LUA_QL(x) "'" x "'" #define LUA_QS LUA_QL("%s") /* =================================================================== */ /* ** Local configuration. You can use this space to add your redefinitions ** without modifying the main part of the file. */ #endif
Kristopher38/LuaCPU
software/lua_on_nios2_bsp/drivers/src/altera_avalon_jtag_uart_ioctl.c
<gh_stars>100-1000 /****************************************************************************** * * * License Agreement * * * * Copyright (c) 2006 Altera Corporation, San Jose, California, USA. * * All rights reserved. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * * DEALINGS IN THE SOFTWARE. * * * * This agreement shall be governed in all respects by the laws of the State * * of California and by the laws of the United States of America. * * * ******************************************************************************/ #include <string.h> #include <fcntl.h> #include <errno.h> #include <limits.h> #include <sys/stat.h> #include "sys/ioctl.h" #include "alt_types.h" #include "altera_avalon_jtag_uart_regs.h" #include "altera_avalon_jtag_uart.h" #include "sys/alt_log_printf.h" #ifndef ALTERA_AVALON_JTAG_UART_SMALL /* ----------------------------------------------------------- */ /* ------------------------- FAST DRIVER --------------------- */ /* ----------------------------------------------------------- */ int altera_avalon_jtag_uart_ioctl(altera_avalon_jtag_uart_state* sp, int req, void* arg) { int rc = -ENOTTY; switch (req) { case TIOCSTIMEOUT: /* Set the time to wait until assuming host is not connected */ if (sp->timeout != INT_MAX) { int timeout = *((int *)arg); sp->timeout = (timeout >= 2 && timeout < INT_MAX) ? timeout : INT_MAX - 1; rc = 0; } break; case TIOCGCONNECTED: /* Find out whether host is connected */ if (sp->timeout != INT_MAX) { *((int *)arg) = (sp->host_inactive < sp->timeout) ? 1 : 0; rc = 0; } break; default: break; } return rc; } #endif /* !ALTERA_AVALON_JTAG_UART_SMALL */
Kristopher38/LuaCPU
software/lua_on_nios2/lua/common.h
#ifndef h_common #define h_common #if defined(__NIOS2__) || defined(VERILATOR_SIM) #define CUSTOM_LUA #endif #define SYNC_REGS(ci, base) { \ for (StkId slot = base; slot < ci->top; slot++) \ { \ ALT_CI_LUA_STOREVAL(slot, slot->value_); \ ALT_CI_LUA_STORETT(slot, slot->tt_); \ } \ } #ifdef __NIOS2__ #include "system.h" #define ALT_CI_LUA_EXEC(A,B) __builtin_custom_inpp(ALT_CI_LUA_CPU_0_N+0,(A),(B)) #define ALT_CI_LUA_STOREVALI(reg, val) __builtin_custom_npi(ALT_CI_LUA_CPU_0_N+(1&ALT_CI_LUA_CPU_0_N_MASK),(void*)(reg),(val)) #define ALT_CI_LUA_STOREVALF(reg, val) __builtin_custom_npf(ALT_CI_LUA_CPU_0_N+(1&ALT_CI_LUA_CPU_0_N_MASK),(void*)(reg),(val)) #define ALT_CI_LUA_STOREVALP(reg, val) __builtin_custom_npp(ALT_CI_LUA_CPU_0_N+(1&ALT_CI_LUA_CPU_0_N_MASK),(void*)(reg),(void*)(val)) #define ALT_CI_LUA_STOREVAL(reg, val) __asm__("custom 1,zero,%0,%1" :: "r" (reg), "r" (val)) #define ALT_CI_LUA_STORETT(reg, tt) __builtin_custom_npi(ALT_CI_LUA_CPU_0_N+(2&ALT_CI_LUA_CPU_0_N_MASK),(void*)(reg),(int)(tt)) #define ALT_CI_LUA_STOREBASE(base) { __builtin_custom_np(ALT_CI_LUA_CPU_0_N+(3&ALT_CI_LUA_CPU_0_N_MASK),(void*)(base)); SYNC_REGS(L->ci, base); } #elif VERILATOR_SIM #include "cpusim.h" #define ALT_CI_LUA_EXEC(A,B) luacpu_simulate(A, B); #define ALT_CI_LUA_STOREVALI(reg, val) luacpu_storeval((void*)reg, val) #define ALT_CI_LUA_STOREVALF(reg, val) luacpu_storeval((void*)reg, val) #define ALT_CI_LUA_STOREVALP(reg, val) luacpu_storeval((void*)reg, val) #define ALT_CI_LUA_STOREVAL(reg, val) luacpu_storeval((void*)reg, val) #define ALT_CI_LUA_STORETT(reg, tt) luacpu_storett((void*)reg, tt) #define ALT_CI_LUA_STOREBASE(base) { luacpu_storebase((void*)base); SYNC_REGS(L->ci, base); } #else #define ALT_CI_LUA_EXEC(A,B) (void)0 #define ALT_CI_LUA_STOREVALI(reg, val) (void)0 #define ALT_CI_LUA_STOREVALF(reg, val) (void)0 #define ALT_CI_LUA_STOREVALP(reg, val) (void)0 #define ALT_CI_LUA_STOREVAL(reg, val) (void)0 #define ALT_CI_LUA_STORETT(reg, tt) (void)0 #define ALT_CI_LUA_STOREBASE(base) (void)0 #endif #endif
Kristopher38/LuaCPU
software/lua_on_nios2_bsp/HAL/src/alt_remap_cached.c
<gh_stars>10-100 /****************************************************************************** * * * License Agreement * * * * Copyright (c) 2003,2007 Altera Corporation, San Jose, California, USA. * * All rights reserved. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * * DEALINGS IN THE SOFTWARE. * * * * This agreement shall be governed in all respects by the laws of the State * * of California and by the laws of the United States of America. * * * ******************************************************************************/ #include "sys/alt_warning.h" #include "sys/alt_cache.h" #include "system.h" /* * Convert a pointer to a block of uncached memory into a block of cached memory. * Return a pointer that should be used to access the cached memory. */ void* alt_remap_cached(volatile void* ptr, alt_u32 len) { #if ALT_CPU_DCACHE_SIZE > 0 #ifdef ALT_CPU_DCACHE_BYPASS_MASK return (void*) (((alt_u32)ptr) & ~ALT_CPU_DCACHE_BYPASS_MASK); #else /* No address mask option enabled. */ /* Generate a link time error, should this function ever be called. */ ALT_LINK_ERROR("alt_remap_cached() is not available because CPU is not configured to use bit 31 of address to bypass data cache"); return NULL; #endif /* No address mask option enabled. */ #else /* No data cache */ /* Nothing needs to be done to the pointer. */ return (void*) ptr; #endif /* No data cache */ }
Kristopher38/LuaCPU
hardware/soc_system/synthesis/submodules/sequencer/sequencer.pre.h
<reponame>Kristopher38/LuaCPU #ifndef _SEQUENCER_H_ #define _SEQUENCER_H_ /* * Copyright Altera Corporation (C) 2012-2014. All rights reserved * * SPDX-License-Identifier: BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Altera Corporation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ALTERA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if ENABLE_ASSERT #define ERR_IE_TEXT "Internal Error: Sub-system: %s, File: %s, Line: %d\n%s%s" extern void err_report_internal_error (const char* description, const char* module, const char* file, int line); #define ALTERA_INTERNAL_ERROR(string) {err_report_internal_error(string, "SEQ", __FILE__, __LINE__); exit(-1);} #define ALTERA_ASSERT(condition) \ if (!(condition)) { ALTERA_INTERNAL_ERROR(#condition); } #define ALTERA_INFO_ASSERT(condition,text) \ if (!(condition)) { ALTERA_INTERNAL_ERROR(text); } #else #define ALTERA_ASSERT(condition) #define ALTERA_INFO_ASSERT(condition,text) #endif #if RLDRAMII #define RW_MGR_NUM_DM_PER_WRITE_GROUP (1) #define RW_MGR_NUM_TRUE_DM_PER_WRITE_GROUP (1) #else #define RW_MGR_NUM_DM_PER_WRITE_GROUP (RW_MGR_MEM_DATA_MASK_WIDTH / RW_MGR_MEM_IF_WRITE_DQS_WIDTH) #define RW_MGR_NUM_TRUE_DM_PER_WRITE_GROUP (RW_MGR_TRUE_MEM_DATA_MASK_WIDTH / RW_MGR_MEM_IF_WRITE_DQS_WIDTH) #endif #define RW_MGR_NUM_DQS_PER_WRITE_GROUP (RW_MGR_MEM_IF_READ_DQS_WIDTH / RW_MGR_MEM_IF_WRITE_DQS_WIDTH) #define NUM_RANKS_PER_SHADOW_REG (RW_MGR_MEM_NUMBER_OF_RANKS / NUM_SHADOW_REGS) #define RW_MGR_RUN_SINGLE_GROUP BASE_RW_MGR #define RW_MGR_RUN_ALL_GROUPS BASE_RW_MGR + 0x0400 #if HARD_PHY #define RW_MGR_DI_BASE (BASE_RW_MGR + 0x0020) #else #define RW_MGR_DI_BASE (BASE_RW_MGR + 0x0010) #endif #if DDR3 #define DDR3_MR1_ODT_MASK 0xFFFFFD99 #define DDR3_MR2_ODT_MASK 0xFFFFF9FF #define DDR3_AC_MIRR_MASK 0x020A8 #if LRDIMM // USER RTT_NOM: bits {4,3,2} of the SPD = bits {9,6,2} of the MR #define LRDIMM_SPD_MR_RTT_NOM(spd_byte) \ ( (((spd_byte) & (1 << 4)) << (9-4)) \ | (((spd_byte) & (1 << 3)) << (6-3)) \ | (((spd_byte) & (1 << 2)) << (2-2))) // USER RTT_DRV: bits {1,0} of the SPD = bits {5,1} of the MR #define LRDIMM_SPD_MR_RTT_DRV(spd_byte) \ ( (((spd_byte) & (1 << 1)) << (5-1)) \ | (((spd_byte) & (1 << 0)) << (1-0))) // USER RTT_WR: bits {7,6} of the SPD = bits {10,9} of the MR #define LRDIMM_SPD_MR_RTT_WR(spd_byte) \ (((spd_byte) & (3 << 6)) << (9-6)) #endif // LRDIMM #endif // DDR3 #define RW_MGR_LOAD_CNTR_0 BASE_RW_MGR + 0x0800 #define RW_MGR_LOAD_CNTR_1 BASE_RW_MGR + 0x0804 #define RW_MGR_LOAD_CNTR_2 BASE_RW_MGR + 0x0808 #define RW_MGR_LOAD_CNTR_3 BASE_RW_MGR + 0x080C #define RW_MGR_LOAD_JUMP_ADD_0 BASE_RW_MGR + 0x0C00 #define RW_MGR_LOAD_JUMP_ADD_1 BASE_RW_MGR + 0x0C04 #define RW_MGR_LOAD_JUMP_ADD_2 BASE_RW_MGR + 0x0C08 #define RW_MGR_LOAD_JUMP_ADD_3 BASE_RW_MGR + 0x0C0C #define RW_MGR_RESET_READ_DATAPATH BASE_RW_MGR + 0x1000 #define RW_MGR_SOFT_RESET BASE_RW_MGR + 0x2000 #define RW_MGR_SET_CS_AND_ODT_MASK BASE_RW_MGR + 0x1400 #define RW_MGR_SET_ACTIVE_RANK BASE_RW_MGR + 0x2400 #define RW_MGR_LOOPBACK_MODE BASE_RW_MGR + 0x0200 #define RW_MGR_ENABLE_REFRESH BASE_RW_MGR + 0x3000 #define RW_MGR_RANK_NONE 0xFF #define RW_MGR_RANK_ALL 0x00 #define RW_MGR_ODT_MODE_OFF 0 #define RW_MGR_ODT_MODE_READ_WRITE 1 #define NUM_CALIB_REPEAT 1 #define NUM_READ_TESTS 7 #define NUM_READ_PB_TESTS 7 #define NUM_WRITE_TESTS 15 #define NUM_WRITE_PB_TESTS 31 #define PASS_ALL_BITS 1 #define PASS_ONE_BIT 0 /* calibration stages */ #define CAL_STAGE_NIL 0 #define CAL_STAGE_VFIFO 1 #define CAL_STAGE_WLEVEL 2 #define CAL_STAGE_LFIFO 3 #define CAL_STAGE_WRITES 4 #define CAL_STAGE_FULLTEST 5 #define CAL_STAGE_REFRESH 6 #define CAL_STAGE_CAL_SKIPPED 7 #define CAL_STAGE_CAL_ABORTED 8 #define CAL_STAGE_VFIFO_AFTER_WRITES 9 /* calibration substages */ #define CAL_SUBSTAGE_NIL 0 #define CAL_SUBSTAGE_GUARANTEED_READ 1 #define CAL_SUBSTAGE_DQS_EN_PHASE 2 #define CAL_SUBSTAGE_VFIFO_CENTER 3 #define CAL_SUBSTAGE_WORKING_DELAY 1 #define CAL_SUBSTAGE_LAST_WORKING_DELAY 2 #define CAL_SUBSTAGE_WLEVEL_COPY 3 #define CAL_SUBSTAGE_WRITES_CENTER 1 #define CAL_SUBSTAGE_READ_LATENCY 1 #define CAL_SUBSTAGE_REFRESH 1 #define MAX_RANKS (RW_MGR_MEM_NUMBER_OF_RANKS) #define MAX_DQS (RW_MGR_MEM_IF_WRITE_DQS_WIDTH > RW_MGR_MEM_IF_READ_DQS_WIDTH ? RW_MGR_MEM_IF_WRITE_DQS_WIDTH : RW_MGR_MEM_IF_READ_DQS_WIDTH) #define MAX_DQ (RW_MGR_MEM_DATA_WIDTH) #define MAX_DM (RW_MGR_MEM_DATA_MASK_WIDTH) /* length of VFIFO, from SW_MACROS */ #define VFIFO_SIZE (READ_VALID_FIFO_SIZE) /* Memory for data transfer between TCL scripts and NIOS. * * - First word is a command request. * - The remaining words are part of the transfer. */ /* Define the base address of each manager. */ /* MarkW: how should these base addresses be done for A-V? */ #define BASE_PTR_MGR SEQUENCER_PTR_MGR_INST_BASE #if HARD_PHY #define BASE_PHY_MGR (0x00088000) #define BASE_RW_MGR (0x00090000) #define BASE_DATA_MGR (0x00098000) #else #define BASE_PHY_MGR SEQUENCER_PHY_MGR_INST_BASE #define BASE_RW_MGR SEQUENCER_RW_MGR_INST_BASE #define BASE_DATA_MGR SEQUENCER_DATA_MGR_INST_BASE #endif #define BASE_SCC_MGR SEQUENCER_SCC_MGR_INST_BASE #define BASE_REG_FILE SEQUENCER_REG_FILE_INST_BASE #define BASE_TIMER SEQUENCER_TIMER_INST_BASE #define BASE_MMR (0x000C0000) #define BASE_TRK_MGR (0x000D0000) /* Register file addresses. */ #define REG_FILE_SIGNATURE (BASE_REG_FILE + 0x0000) #define REG_FILE_DEBUG_DATA_ADDR (BASE_REG_FILE + 0x0004) #define REG_FILE_CUR_STAGE (BASE_REG_FILE + 0x0008) #define REG_FILE_FOM (BASE_REG_FILE + 0x000C) #define REG_FILE_FAILING_STAGE (BASE_REG_FILE + 0x0010) #define REG_FILE_DEBUG1 (BASE_REG_FILE + 0x0014) #define REG_FILE_DEBUG2 (BASE_REG_FILE + 0x0018) #if TRACKING_WATCH_TEST || TRACKING_ERROR_TEST #define REG_FILE_TRK_SAMPLE_CHECK (BASE_REG_FILE + 0x003C) #elif MARGIN_VARIATION_TEST #define IO_DQS_EN_DELAY_OFFSET (IORD_32DIRECT(BASE_REG_FILE + 0x003C, 0)) #endif #if HHP_HPS #define REG_FILE_DTAPS_PER_PTAP (BASE_REG_FILE + 0x001C) #define REG_FILE_TRK_SAMPLE_COUNT (BASE_REG_FILE + 0x0020) #define REG_FILE_TRK_LONGIDLE (BASE_REG_FILE + 0x0024) #define REG_FILE_DELAYS (BASE_REG_FILE + 0x0028) #define REG_FILE_TRK_RW_MGR_ADDR (BASE_REG_FILE + 0x002C) #define REG_FILE_TRK_READ_DQS_WIDTH (BASE_REG_FILE + 0x0030) #define REG_FILE_TRK_RFSH (BASE_REG_FILE + 0x0034) #define CTRL_CONFIG_REG (BASE_MMR + 0x0000) #else /* Tracking slave addresses. */ #define TRK_DTAPS_PER_PTAP (BASE_TRK_MGR + 0x0000) #define TRK_SAMPLE_COUNT (BASE_TRK_MGR + 0x0004) #define TRK_LONGIDLE (BASE_TRK_MGR + 0x0008) #define TRK_DELAYS (BASE_TRK_MGR + 0x000C) #define TRK_RW_MGR_ADDR (BASE_TRK_MGR + 0x0010) #define TRK_READ_DQS_WIDTH (BASE_TRK_MGR + 0x0014) #define TRK_RFSH (BASE_TRK_MGR + 0x0018) #define TRK_STALL (BASE_TRK_MGR + 0x001C) #define TRK_V_POINTER (BASE_TRK_MGR + 0x0020) #define TRK_STALL_REQ_VAL (0x1) #define TRK_STALL_ACKED_VAL (0x80000000 | TRK_STALL_REQ_VAL) #endif // HHP_HPS /* PHY manager configuration registers. */ #define PHY_MGR_PHY_RLAT (BASE_PHY_MGR + 0x4000) #define PHY_MGR_RESET_MEM_STBL (BASE_PHY_MGR + 0x4004) #define PHY_MGR_MUX_SEL (BASE_PHY_MGR + 0x4008) #define PHY_MGR_CAL_STATUS (BASE_PHY_MGR + 0x400c) #define PHY_MGR_CAL_DEBUG_INFO (BASE_PHY_MGR + 0x4010) #define PHY_MGR_VFIFO_RD_EN_OVRD (BASE_PHY_MGR + 0x4014) #if CALIBRATE_BIT_SLIPS #define PHY_MGR_FR_SHIFT (BASE_PHY_MGR + 0x4020) #if MULTIPLE_AFI_WLAT #define PHY_MGR_AFI_WLAT (BASE_PHY_MGR + 0x4020 + 4*RW_MGR_MEM_IF_WRITE_DQS_WIDTH) #else #define PHY_MGR_AFI_WLAT (BASE_PHY_MGR + 0x4018) #endif #else #define PHY_MGR_AFI_WLAT (BASE_PHY_MGR + 0x4018) #endif #define PHY_MGR_AFI_RLAT (BASE_PHY_MGR + 0x401c) #define PHY_MGR_CAL_RESET (0) #define PHY_MGR_CAL_SUCCESS (1) #define PHY_MGR_CAL_FAIL (2) /* PHY manager command addresses. */ #define PHY_MGR_CMD_INC_VFIFO_FR (BASE_PHY_MGR + 0x0000) #define PHY_MGR_CMD_INC_VFIFO_HR (BASE_PHY_MGR + 0x0004) #define PHY_MGR_CMD_INC_VFIFO_HARD_PHY (BASE_PHY_MGR + 0x0004) #define PHY_MGR_CMD_FIFO_RESET (BASE_PHY_MGR + 0x0008) #define PHY_MGR_CMD_INC_VFIFO_FR_HR (BASE_PHY_MGR + 0x000C) #define PHY_MGR_CMD_INC_VFIFO_QR (BASE_PHY_MGR + 0x0010) /* PHY manager parameters. */ #define PHY_MGR_MAX_RLAT_WIDTH (BASE_PHY_MGR + 0x0000) #define PHY_MGR_MAX_AFI_WLAT_WIDTH (BASE_PHY_MGR + 0x0004) #define PHY_MGR_MAX_AFI_RLAT_WIDTH (BASE_PHY_MGR + 0x0008) #define PHY_MGR_CALIB_SKIP_STEPS (BASE_PHY_MGR + 0x000c) #define PHY_MGR_CALIB_VFIFO_OFFSET (BASE_PHY_MGR + 0x0010) #define PHY_MGR_CALIB_LFIFO_OFFSET (BASE_PHY_MGR + 0x0014) #define PHY_MGR_RDIMM (BASE_PHY_MGR + 0x0018) #define PHY_MGR_MEM_T_WL (BASE_PHY_MGR + 0x001c) #define PHY_MGR_MEM_T_RL (BASE_PHY_MGR + 0x0020) /* Data Manager */ #define DATA_MGR_DRAM_CFG (BASE_DATA_MGR + 0x0000) #define DATA_MGR_MEM_T_WL (BASE_DATA_MGR + 0x0004) #define DATA_MGR_MEM_T_ADD (BASE_DATA_MGR + 0x0008) #define DATA_MGR_MEM_T_RL (BASE_DATA_MGR + 0x000C) #define DATA_MGR_MEM_T_RFC (BASE_DATA_MGR + 0x0010) #define DATA_MGR_MEM_T_REFI (BASE_DATA_MGR + 0x0014) #define DATA_MGR_MEM_T_WR (BASE_DATA_MGR + 0x0018) #define DATA_MGR_MEM_T_MRD (BASE_DATA_MGR + 0x001C) #define DATA_MGR_COL_WIDTH (BASE_DATA_MGR + 0x0020) #define DATA_MGR_ROW_WIDTH (BASE_DATA_MGR + 0x0024) #define DATA_MGR_BANK_WIDTH (BASE_DATA_MGR + 0x0028) #define DATA_MGR_CS_WIDTH (BASE_DATA_MGR + 0x002C) #define DATA_MGR_ITF_WIDTH (BASE_DATA_MGR + 0x0030) #define DATA_MGR_DVC_WIDTH (BASE_DATA_MGR + 0x0034) #if HARD_PHY #define MEM_T_WL_ADD DATA_MGR_MEM_T_WL #define MEM_T_RL_ADD DATA_MGR_MEM_T_RL #else #define MEM_T_WL_ADD PHY_MGR_MEM_T_WL #define MEM_T_RL_ADD PHY_MGR_MEM_T_RL #endif #define CALIB_SKIP_DELAY_LOOPS (1 << 0) #define CALIB_SKIP_ALL_BITS_CHK (1 << 1) #define CALIB_SKIP_DELAY_SWEEPS (1 << 2) #define CALIB_SKIP_VFIFO (1 << 3) #define CALIB_SKIP_LFIFO (1 << 4) #define CALIB_SKIP_WLEVEL (1 << 5) #define CALIB_SKIP_WRITES (1 << 6) #define CALIB_SKIP_FULL_TEST (1 << 7) #define CALIB_SKIP_ALL (CALIB_SKIP_VFIFO | CALIB_SKIP_LFIFO | CALIB_SKIP_WLEVEL | CALIB_SKIP_WRITES | CALIB_SKIP_FULL_TEST) #define CALIB_IN_RTL_SIM (1 << 8) /* Scan chain manager command addresses */ #define WRITE_SCC_DQS_IN_DELAY(group, delay) IOWR_32DIRECT(SCC_MGR_DQS_IN_DELAY, (group) << 2, delay) #define WRITE_SCC_DQS_EN_DELAY(group, delay) IOWR_32DIRECT(SCC_MGR_DQS_EN_DELAY, (group) << 2, (delay) + IO_DQS_EN_DELAY_OFFSET) #define WRITE_SCC_DQS_EN_PHASE(group, phase) IOWR_32DIRECT(SCC_MGR_DQS_EN_PHASE, (group) << 2, phase) #define WRITE_SCC_DQDQS_OUT_PHASE(group, phase) IOWR_32DIRECT(SCC_MGR_DQDQS_OUT_PHASE, (group) << 2, phase) #define WRITE_SCC_OCT_OUT1_DELAY(group, delay) IOWR_32DIRECT(SCC_MGR_OCT_OUT1_DELAY, (group) << 2, delay) #if HHP_HPS #define WRITE_SCC_OCT_OUT2_DELAY(group, delay) #else #define WRITE_SCC_OCT_OUT2_DELAY(group, delay) IOWR_32DIRECT(SCC_MGR_OCT_OUT2_DELAY, (group) << 2, delay) #endif #if HHP_HPS #define WRITE_SCC_DQS_BYPASS(group, bypass) #else #define WRITE_SCC_DQS_BYPASS(group, bypass) IOWR_32DIRECT(SCC_MGR_DQS_BYPASS, (group) << 2, bypass) #endif #define WRITE_SCC_DQ_OUT1_DELAY(pin, delay) IOWR_32DIRECT(SCC_MGR_IO_OUT1_DELAY, (pin) << 2, delay) #if HHP_HPS #define WRITE_SCC_DQ_OUT2_DELAY(pin, delay) #else #define WRITE_SCC_DQ_OUT2_DELAY(pin, delay) IOWR_32DIRECT(SCC_MGR_IO_OUT2_DELAY, (pin) << 2, delay) #endif #define WRITE_SCC_DQ_IN_DELAY(pin, delay) IOWR_32DIRECT(SCC_MGR_IO_IN_DELAY, (pin) << 2, delay) #if HHP_HPS #define WRITE_SCC_DQ_BYPASS(pin, bypass) #else #define WRITE_SCC_DQ_BYPASS(pin, bypass) IOWR_32DIRECT(SCC_MGR_DQ_BYPASS, (pin) << 2, bypass) #endif #if HHP_HPS #define WRITE_SCC_RFIFO_MODE(pin, mode) #else #define WRITE_SCC_RFIFO_MODE(pin, mode) IOWR_32DIRECT(SCC_MGR_RFIFO_MODE, (pin) << 2, mode) #endif #if HHP_HPS #define WRITE_SCC_HHP_EXTRAS(value) IOWR_32DIRECT(SCC_MGR_HHP_GLOBALS, SCC_MGR_HHP_EXTRAS_OFFSET, value) #define WRITE_SCC_HHP_DQSE_MAP(value) IOWR_32DIRECT(SCC_MGR_HHP_GLOBALS, SCC_MGR_HHP_DQSE_MAP_OFFSET, value) #else #define WRITE_SCC_HHP_EXTRAS(value) #define WRITE_SCC_HHP_DQSE_MAP(value) #endif #define WRITE_SCC_DQS_IO_OUT1_DELAY(delay) IOWR_32DIRECT(SCC_MGR_IO_OUT1_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS) << 2, delay) #if HHP_HPS #define WRITE_SCC_DQS_IO_OUT2_DELAY(delay) #else #define WRITE_SCC_DQS_IO_OUT2_DELAY(delay) IOWR_32DIRECT(SCC_MGR_IO_OUT2_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS) << 2, delay) #endif #define WRITE_SCC_DQS_IO_IN_DELAY(delay) IOWR_32DIRECT(SCC_MGR_IO_IN_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS) << 2, delay) #define WRITE_SCC_DM_IO_OUT1_DELAY(pin, delay) IOWR_32DIRECT(SCC_MGR_IO_OUT1_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2, delay) #if HHP_HPS #define WRITE_SCC_DM_IO_OUT2_DELAY(pin, delay) #else #define WRITE_SCC_DM_IO_OUT2_DELAY(pin, delay) IOWR_32DIRECT(SCC_MGR_IO_OUT2_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2, delay) #endif #define WRITE_SCC_DM_IO_IN_DELAY(pin, delay) IOWR_32DIRECT(SCC_MGR_IO_IN_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2, delay) #if HHP_HPS #define WRITE_SCC_DM_BYPASS(pin, bypass) #else #define WRITE_SCC_DM_BYPASS(pin, bypass) IOWR_32DIRECT(SCC_MGR_DQ_BYPASS, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2, bypass) #endif #define READ_SCC_DQS_IN_DELAY(group) IORD_32DIRECT(SCC_MGR_DQS_IN_DELAY, (group) << 2) #define READ_SCC_DQS_EN_DELAY(group) (IORD_32DIRECT(SCC_MGR_DQS_EN_DELAY, (group) << 2) - IO_DQS_EN_DELAY_OFFSET) #define READ_SCC_DQS_EN_PHASE(group) IORD_32DIRECT(SCC_MGR_DQS_EN_PHASE, (group) << 2) #define READ_SCC_DQDQS_OUT_PHASE(group) IORD_32DIRECT(SCC_MGR_DQDQS_OUT_PHASE, (group) << 2) #define READ_SCC_OCT_OUT1_DELAY(group) IORD_32DIRECT(SCC_MGR_OCT_OUT1_DELAY, (group * RW_MGR_MEM_IF_READ_DQS_WIDTH / RW_MGR_MEM_IF_WRITE_DQS_WIDTH) << 2) #if HHP_HPS #define READ_SCC_OCT_OUT2_DELAY(group) 0 #else #define READ_SCC_OCT_OUT2_DELAY(group) IORD_32DIRECT(SCC_MGR_OCT_OUT2_DELAY, (group * RW_MGR_MEM_IF_READ_DQS_WIDTH / RW_MGR_MEM_IF_WRITE_DQS_WIDTH) << 2) #endif #if HHP_HPS #define READ_SCC_DQS_BYPASS(group) 0 #else #define READ_SCC_DQS_BYPASS(group) IORD_32DIRECT(SCC_MGR_DQS_BYPASS, (group) << 2) #endif #if HHP_HPS #define READ_SCC_DQS_BYPASS(group) 0 #else #define READ_SCC_DQS_BYPASS(group) IORD_32DIRECT(SCC_MGR_DQS_BYPASS, (group) << 2) #endif #define READ_SCC_DQ_OUT1_DELAY(pin) IORD_32DIRECT(SCC_MGR_IO_OUT1_DELAY, (pin) << 2) #if HHP_HPS #define READ_SCC_DQ_OUT2_DELAY(pin) 0 #else #define READ_SCC_DQ_OUT2_DELAY(pin) IORD_32DIRECT(SCC_MGR_IO_OUT2_DELAY, (pin) << 2) #endif #define READ_SCC_DQ_IN_DELAY(pin) IORD_32DIRECT(SCC_MGR_IO_IN_DELAY, (pin) << 2) #if HHP_HPS #define READ_SCC_DQ_BYPASS(pin) 0 #else #define READ_SCC_DQ_BYPASS(pin) IOWR_32DIRECT(SCC_MGR_DQ_BYPASS, (pin) << 2) #endif #if HHP_HPS #define READ_SCC_RFIFO_MODE(pin) 0 #else #define READ_SCC_RFIFO_MODE(pin) IOWR_32DIRECT(SCC_MGR_RFIFO_MODE, (pin) << 2) #endif #define READ_SCC_DQS_IO_OUT1_DELAY() IORD_32DIRECT(SCC_MGR_IO_OUT1_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS) << 2) #if HHP_HPS #define READ_SCC_DQS_IO_OUT2_DELAY() 0 #else #define READ_SCC_DQS_IO_OUT2_DELAY() IORD_32DIRECT(SCC_MGR_IO_OUT2_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS) << 2) #endif #define READ_SCC_DQS_IO_IN_DELAY() IORD_32DIRECT(SCC_MGR_IO_IN_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS) << 2) #define READ_SCC_DM_IO_OUT1_DELAY(pin) IORD_32DIRECT(SCC_MGR_IO_OUT1_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2) #if HHP_HPS #define READ_SCC_DM_IO_OUT2_DELAY(pin) 0 #else #define READ_SCC_DM_IO_OUT2_DELAY(pin) IORD_32DIRECT(SCC_MGR_IO_OUT2_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2) #endif #define READ_SCC_DM_IO_IN_DELAY(pin) IORD_32DIRECT(SCC_MGR_IO_IN_DELAY, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2) #if HHP_HPS #define READ_SCC_DM_BYPASS(pin) 0 #else #define READ_SCC_DM_BYPASS(pin) IOWR_32DIRECT(SCC_MGR_DQ_BYPASS, (RW_MGR_MEM_DQ_PER_WRITE_DQS + 1 + pin) << 2) #endif #define SCC_MGR_GROUP_COUNTER (BASE_SCC_MGR + 0x0000) #define SCC_MGR_DQS_IN_DELAY (BASE_SCC_MGR + 0x0100) #define SCC_MGR_DQS_EN_PHASE (BASE_SCC_MGR + 0x0200) #define SCC_MGR_DQS_EN_DELAY (BASE_SCC_MGR + 0x0300) #define SCC_MGR_DQDQS_OUT_PHASE (BASE_SCC_MGR + 0x0400) #define SCC_MGR_OCT_OUT1_DELAY (BASE_SCC_MGR + 0x0500) #if !HHP_HPS #define SCC_MGR_OCT_OUT2_DELAY (BASE_SCC_MGR + 0x0600) #endif #define SCC_MGR_IO_OUT1_DELAY (BASE_SCC_MGR + 0x0700) #if !HHP_HPS #define SCC_MGR_IO_OUT2_DELAY (BASE_SCC_MGR + 0x0800) #endif #define SCC_MGR_IO_IN_DELAY (BASE_SCC_MGR + 0x0900) #if !HHP_HPS /* ACV-specific commands */ #define SCC_MGR_DQS_BYPASS (BASE_SCC_MGR + 0x0A00) #define SCC_MGR_DQ_BYPASS (BASE_SCC_MGR + 0x0B00) #define SCC_MGR_RFIFO_MODE (BASE_SCC_MGR + 0x0C00) #endif #if HHP_HPS /* HHP-HPS-specific versions of some commands */ #define SCC_MGR_DQS_EN_DELAY_GATE (BASE_SCC_MGR + 0x0600) #define SCC_MGR_IO_OE_DELAY (BASE_SCC_MGR + 0x0800) #define SCC_MGR_HHP_GLOBALS (BASE_SCC_MGR + 0x0A00) #define SCC_MGR_HHP_RFILE (BASE_SCC_MGR + 0x0B00) #endif /* HHP-HPS-specific values */ #define SCC_MGR_HHP_EXTRAS_OFFSET 0 #define SCC_MGR_HHP_DQSE_MAP_OFFSET 1 #define SCC_MGR_DQS_ENA (BASE_SCC_MGR + 0x0E00) #define SCC_MGR_DQS_IO_ENA (BASE_SCC_MGR + 0x0E04) #define SCC_MGR_DQ_ENA (BASE_SCC_MGR + 0x0E08) #define SCC_MGR_DM_ENA (BASE_SCC_MGR + 0x0E0C) #define SCC_MGR_UPD (BASE_SCC_MGR + 0x0E20) #define SCC_MGR_ACTIVE_RANK (BASE_SCC_MGR + 0x0E40) #define SCC_MGR_AFI_CAL_INIT (BASE_SCC_MGR + 0x0D00) // PHY Debug mode flag constants #define PHY_DEBUG_IN_DEBUG_MODE 0x00000001 #define PHY_DEBUG_ENABLE_CAL_RPT 0x00000002 #define PHY_DEBUG_ENABLE_MARGIN_RPT 0x00000004 #define PHY_DEBUG_SWEEP_ALL_GROUPS 0x00000008 #define PHY_DEBUG_DISABLE_GUARANTEED_READ 0x00000010 #define PHY_DEBUG_ENABLE_NON_DESTRUCTIVE_CALIBRATION 0x00000020 // Init and Reset delay constants - Only use if defined by sequencer_defines.h, // otherwise, revert to defaults // Default for Tinit = (0+1) * ((202+1) * (2 * 131 + 1) + 1) = 53532 = 200.75us @ 266MHz #ifdef TINIT_CNTR0_VAL #define SEQ_TINIT_CNTR0_VAL TINIT_CNTR0_VAL #else #define SEQ_TINIT_CNTR0_VAL 0 #endif #ifdef TINIT_CNTR1_VAL #define SEQ_TINIT_CNTR1_VAL TINIT_CNTR1_VAL #else #define SEQ_TINIT_CNTR1_VAL 202 #endif #ifdef TINIT_CNTR2_VAL #define SEQ_TINIT_CNTR2_VAL TINIT_CNTR2_VAL #else #define SEQ_TINIT_CNTR2_VAL 131 #endif // Default for Treset = (2+1) * ((252+1) * (2 * 131 + 1) + 1) = 133563 = 500.86us @ 266MHz #ifdef TRESET_CNTR0_VAL #define SEQ_TRESET_CNTR0_VAL TRESET_CNTR0_VAL #else #define SEQ_TRESET_CNTR0_VAL 2 #endif #ifdef TRESET_CNTR1_VAL #define SEQ_TRESET_CNTR1_VAL TRESET_CNTR1_VAL #else #define SEQ_TRESET_CNTR1_VAL 252 #endif #ifdef TRESET_CNTR2_VAL #define SEQ_TRESET_CNTR2_VAL TRESET_CNTR2_VAL #else #define SEQ_TRESET_CNTR2_VAL 131 #endif /* Bitfield type changes depending on protocol */ #if QDRII typedef long long t_btfld; #else typedef alt_u32 t_btfld; #endif #define RW_MGR_INST_ROM_WRITE BASE_RW_MGR + 0x1800 #define RW_MGR_AC_ROM_WRITE BASE_RW_MGR + 0x1C00 extern const alt_u32 inst_rom_init_size; extern const alt_u32 inst_rom_init[]; extern const alt_u32 ac_rom_init_size; extern const alt_u32 ac_rom_init[]; /* parameter variable holder */ typedef struct param_type { t_btfld dm_correct_mask; t_btfld read_correct_mask; t_btfld read_correct_mask_vg; t_btfld write_correct_mask; t_btfld write_correct_mask_vg; /* set a particular entry to 1 if we need to skip a particular rank */ alt_u32 skip_ranks[MAX_RANKS]; /* set a particular entry to 1 if we need to skip a particular group */ alt_u32 skip_groups; /* set a particular entry to 1 if the shadow register (which represents a set of ranks) needs to be skipped */ alt_u32 skip_shadow_regs[NUM_SHADOW_REGS]; } param_t; /* global variable holder */ typedef struct gbl_type { alt_u32 phy_debug_mode_flags; /* current read latency */ alt_u32 curr_read_lat; /* current write latency */ alt_u32 curr_write_lat; /* error code */ alt_u32 error_substage; alt_u32 error_stage; alt_u32 error_group; /* figure-of-merit in, figure-of-merit out */ alt_u32 fom_in; alt_u32 fom_out; //USER Number of RW Mgr NOP cycles between write command and write data #if MULTIPLE_AFI_WLAT alt_u32 rw_wl_nop_cycles_per_group[RW_MGR_MEM_IF_WRITE_DQS_WIDTH]; #endif alt_u32 rw_wl_nop_cycles; } gbl_t; // External global variables extern gbl_t *gbl; extern param_t *param; // External functions alt_u32 rw_mgr_mem_calibrate_full_test (alt_u32 min_correct, t_btfld *bit_chk, alt_u32 test_dm); #if ENABLE_NON_DES_CAL extern alt_u32 run_mem_calibrate (alt_u32 enable_non_des_c); #else extern alt_u32 run_mem_calibrate (void); #endif extern void rw_mgr_mem_calibrate_eye_diag_aid (void); extern void rw_mgr_load_mrs_calib (void); extern void rw_mgr_load_mrs_exec (void); extern void rw_mgr_mem_initialize (void); extern void rw_mgr_mem_dll_lock_wait(void); extern inline void scc_mgr_set_dq_in_delay (alt_u32 write_group, alt_u32 dq_in_group, alt_u32 delay); extern inline void scc_mgr_set_dq_out1_delay (alt_u32 write_group, alt_u32 dq_in_group, alt_u32 delay); extern inline void scc_mgr_set_dq_out2_delay (alt_u32 write_group, alt_u32 dq_in_group, alt_u32 delay); extern inline void scc_mgr_load_dq (alt_u32 dq_in_group); extern inline void scc_mgr_set_dqs_bus_in_delay (alt_u32 read_group, alt_u32 delay); extern inline void scc_mgr_load_dqs (alt_u32 dqs); extern void scc_mgr_set_group_dqs_io_and_oct_out1_gradual (alt_u32 write_group, alt_u32 delay); extern void scc_mgr_set_group_dqs_io_and_oct_out2_gradual (alt_u32 write_group, alt_u32 delay); extern void scc_mgr_set_dqs_en_delay_all_ranks (alt_u32 read_group, alt_u32 delay); extern void scc_mgr_set_dqs_en_phase_all_ranks (alt_u32 read_group, alt_u32 phase); extern void scc_mgr_set_dqdqs_output_phase_all_ranks (alt_u32 write_group, alt_u32 phase); extern inline void scc_mgr_set_dm_out1_delay (alt_u32 write_group, alt_u32 dm, alt_u32 delay); extern inline void scc_mgr_set_dm_out2_delay (alt_u32 write_group, alt_u32 dm, alt_u32 delay); extern inline void scc_mgr_load_dm (alt_u32 dm); extern void rw_mgr_incr_vfifo_auto(alt_u32 grp); extern void rw_mgr_decr_vfifo_auto(alt_u32 grp); #if HPS_HW extern int sdram_calibration(void); #endif #endif
Kristopher38/LuaCPU
software/lua_on_nios2_bsp/HAL/inc/sys/alt_llist.h
<reponame>Kristopher38/LuaCPU #ifndef __ALT_LIST_H__ #define __ALT_LIST_H__ /****************************************************************************** * * * License Agreement * * * * Copyright (c) 2004 Altera Corporation, San Jose, California, USA. * * All rights reserved. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * * DEALINGS IN THE SOFTWARE. * * * * This agreement shall be governed in all respects by the laws of the State * * of California and by the laws of the United States of America. * * * * Altera does not recommend, suggest or require that this reference design * * file be used in conjunction or combination with any other product. * ******************************************************************************/ /****************************************************************************** * * * THIS IS A LIBRARY READ-ONLY SOURCE FILE. DO NOT EDIT. * * * ******************************************************************************/ #include "alt_types.h" /* * alt_llist.h defines structures and functions for use in manipulating linked * lists. A list is considered to be constructed from a chain of objects of * type alt_llist, with one object being defined to be the head element. * * A list is considered to be empty if it only contains the head element. */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * alt_llist is the structure used to represent an element within a linked * list. */ typedef struct alt_llist_s alt_llist; struct alt_llist_s { alt_llist* next; /* Pointer to the next element in the list. */ alt_llist* previous; /* Pointer to the previous element in the list. */ }; /* * ALT_LLIST_HEAD is a macro that can be used to create the head of a new * linked list. This is named "head". The head element is initialised to * represent an empty list. */ #define ALT_LLIST_HEAD(head) alt_llist head = {&head, &head} /* * ALT_LLIST_ENTRY is a macro used to define an uninitialised linked list * entry. This is used to reserve space in structure initialisation for * structures that inherit form alt_llist. */ #define ALT_LLIST_ENTRY {0, 0} /* * alt_llist_insert() insert adds the linked list entry "entry" as the * first entry in the linked list "list". "list" is the list head element. */ static ALT_INLINE void ALT_ALWAYS_INLINE alt_llist_insert(alt_llist* list, alt_llist* entry) { entry->previous = list; entry->next = list->next; list->next->previous = entry; list->next = entry; } /* * alt_llist_remove() is called to remove an element from a linked list. The * input argument is the element to remove. */ static ALT_INLINE void ALT_ALWAYS_INLINE alt_llist_remove(alt_llist* entry) { entry->next->previous = entry->previous; entry->previous->next = entry->next; /* * Set the entry to point to itself, so that any further calls to * alt_llist_remove() are harmless. */ entry->previous = entry; entry->next = entry; } #ifdef __cplusplus } #endif #endif /* __ALT_LLIST_H__ */