repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
sethcoder/cc65
src/cc65/coptneg.c
/*****************************************************************************/ /* */ /* coptneg.c */ /* */ /* Optimize negation sequences */ /* */ /* */ /* */ /* (C) 2001-2012, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptneg.h" /*****************************************************************************/ /* bnega optimizations */ /*****************************************************************************/ unsigned OptBNegA1 (CodeSeg* S) /* Check for ** ** ldx #$00 ** lda .. ** jsr bnega ** ** Remove the ldx if the lda does not use it. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for a ldx */ if (E->OPC == OP65_LDX && E->AM == AM65_IMM && (E->Flags & CEF_NUMARG) != 0 && E->Num == 0 && CS_GetEntries (S, L, I+1, 2) && L[0]->OPC == OP65_LDA && (L[0]->Use & REG_X) == 0 && !CE_HasLabel (L[0]) && CE_IsCallTo (L[1], "bnega") && !CE_HasLabel (L[1])) { /* Remove the ldx instruction */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegA2 (CodeSeg* S) /* Check for ** ** lda .. ** jsr bnega ** jeq/jne .. ** ** Adjust the conditional branch and remove the call to the subroutine. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if ((E->OPC == OP65_ADC || E->OPC == OP65_AND || E->OPC == OP65_DEA || E->OPC == OP65_EOR || E->OPC == OP65_INA || E->OPC == OP65_LDA || E->OPC == OP65_ORA || E->OPC == OP65_PLA || E->OPC == OP65_SBC || E->OPC == OP65_TXA || E->OPC == OP65_TYA) && CS_GetEntries (S, L, I+1, 2) && CE_IsCallTo (L[0], "bnega") && !CE_HasLabel (L[0]) && (L[1]->Info & OF_ZBRA) != 0 && !CE_HasLabel (L[1])) { /* Invert the branch */ CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC)); /* Delete the subroutine call */ CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* bnegax optimizations */ /*****************************************************************************/ unsigned OptBNegAX1 (CodeSeg* S) /* On a call to bnegax, if X is zero, the result depends only on the value in ** A, so change the call to a call to bnega. This will get further optimized ** later if possible. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to bnegax, and if X is known and zero */ if (E->RI->In.RegX == 0 && CE_IsCallTo (E, "bnegax")) { CodeEntry* X = NewCodeEntry (OP65_JSR, AM65_ABS, "bnega", 0, E->LI); CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegAX2 (CodeSeg* S) /* Search for the sequence: ** ** ldy #xx ** jsr ldaxysp ** jsr bnegax ** jne/jeq ... ** ** and replace it by ** ** ldy #xx ** lda (sp),y ** dey ** ora (sp),y ** jeq/jne ... */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CE_IsConstImm (L[0]) && !CS_RangeHasLabel (S, I+1, 3) && CS_GetEntries (S, L+1, I+1, 3) && CE_IsCallTo (L[1], "ldaxysp") && CE_IsCallTo (L[2], "bnegax") && (L[3]->Info & OF_ZBRA) != 0) { CodeEntry* X; /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+1); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, I+2); /* ora (sp),y */ X = NewCodeEntry (OP65_ORA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* Invert the branch */ CE_ReplaceOPC (L[3], GetInverseBranch (L[3]->OPC)); /* Delete the entries no longer needed. */ CS_DelEntries (S, I+4, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegAX3 (CodeSeg* S) /* Search for the sequence: ** ** lda xx ** ldx yy ** jsr bnegax ** jne/jeq ... ** ** and replace it by ** ** lda xx ** ora xx+1 ** jeq/jne ... */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_LDA && CS_GetEntries (S, L, I+1, 3) && L[0]->OPC == OP65_LDX && !CE_HasLabel (L[0]) && CE_IsCallTo (L[1], "bnegax") && !CE_HasLabel (L[1]) && (L[2]->Info & OF_ZBRA) != 0 && !CE_HasLabel (L[2])) { /* ldx --> ora */ CE_ReplaceOPC (L[0], OP65_ORA); /* Invert the branch */ CE_ReplaceOPC (L[2], GetInverseBranch (L[2]->OPC)); /* Delete the subroutine call */ CS_DelEntry (S, I+2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegAX4 (CodeSeg* S) /* Search for the sequence: ** ** jsr xxx ** jsr bnega(x) ** jeq/jne ... ** ** and replace it by: ** ** jsr xxx ** <boolean test> ** jne/jeq ... */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && CS_GetEntries (S, L, I+1, 2) && L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg,"bnega",5) == 0 && !CE_HasLabel (L[0]) && (L[1]->Info & OF_ZBRA) != 0 && !CE_HasLabel (L[1])) { CodeEntry* X; /* Check if we're calling bnega or bnegax */ int ByteSized = (strcmp (L[0]->Arg, "bnega") == 0); /* Insert apropriate test code */ if (ByteSized) { /* Test bytes */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, I+2); } else { /* Test words */ X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, L[0]->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_ORA, AM65_ZP, "tmp1", 0, L[0]->LI); CS_InsertEntry (S, X, I+3); } /* Delete the subroutine call */ CS_DelEntry (S, I+1); /* Invert the branch */ CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC)); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* negax optimizations */ /*****************************************************************************/ unsigned OptNegAX1 (CodeSeg* S) /* Search for a call to negax and replace it by ** ** eor #$FF ** clc ** adc #$01 ** ** if X isn't used later. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to negax, and if X isn't used later */ if (CE_IsCallTo (E, "negax") && !RegXUsed (S, I+1)) { CodeEntry* X; /* Add replacement code behind */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+1); X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_ADC, AM65_IMM, "$01", 0, E->LI); CS_InsertEntry (S, X, I+3); /* Delete the call to negax */ CS_DelEntry (S, I); /* Skip the generated code */ I += 2; /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptNegAX2 (CodeSeg* S) /* Search for a call to negax and replace it by ** ** ldx #$FF ** eor #$FF ** clc ** adc #$01 ** bne L1 ** inx ** L1: ** ** if X is known and zero on entry. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* P; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to negax, and if X is known and zero */ if (E->RI->In.RegX == 0 && CE_IsCallTo (E, "negax") && (P = CS_GetNextEntry (S, I)) != 0) { CodeEntry* X; CodeLabel* L; /* Add replacement code behind */ /* ldx #$FF */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+1); /* eor #$FF */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+2); /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+3); /* adc #$01 */ X = NewCodeEntry (OP65_ADC, AM65_IMM, "$01", 0, E->LI); CS_InsertEntry (S, X, I+4); /* Get the label attached to the insn following the call */ L = CS_GenLabel (S, P); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, X, I+5); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+6); /* Delete the call to negax */ CS_DelEntry (S, I); /* Skip the generated code */ I += 5; /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* complax optimizations */ /*****************************************************************************/ unsigned OptComplAX1 (CodeSeg* S) /* Search for a call to complax and replace it by ** ** eor #$FF ** ** if X isn't used later. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to negax, and if X isn't used later */ if (CE_IsCallTo (E, "complax") && !RegXUsed (S, I+1)) { CodeEntry* X; /* Add replacement code behind */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+1); /* Delete the call to negax */ CS_DelEntry (S, I); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
sethcoder/cc65
include/atmos.h
/*****************************************************************************/ /* */ /* atmos.h */ /* */ /* Oric Atmos system-specific definitions */ /* */ /* */ /* */ /* (C) 2002 <NAME>, <<EMAIL>> */ /* (C) 2003-2013 <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef _ATMOS_H #define _ATMOS_H /* Check for errors */ #if !defined(__ATMOS__) # error This module may only be used when compiling for the Oric Atmos! #endif /* Color defines */ #define COLOR_BLACK 0x00 #define COLOR_RED 0x01 #define COLOR_GREEN 0x02 #define COLOR_YELLOW 0x03 #define COLOR_BLUE 0x04 #define COLOR_MAGENTA 0x05 #define COLOR_CYAN 0x06 #define COLOR_WHITE 0x07 /* TGI color defines */ /* White and red are swapped, so that the pallete ** driver is compatible with black-and-white drivers. */ #define TGI_COLOR_BLACK COLOR_BLACK #define TGI_COLOR_WHITE 1 #define TGI_COLOR_GREEN COLOR_GREEN #define TGI_COLOR_YELLOW COLOR_YELLOW #define TGI_COLOR_BLUE COLOR_BLUE #define TGI_COLOR_MAGENTA COLOR_MAGENTA #define TGI_COLOR_CYAN COLOR_CYAN #define TGI_COLOR_RED 7 /* Define hardware */ #include <_6522.h> #define VIA (*(struct __6522*)0x300) /* These are defined to be FUNCT + NumberKey */ #define CH_F1 0xB1 #define CH_F2 0xB2 #define CH_F3 0xB3 #define CH_F4 0xB4 #define CH_F5 0xB5 #define CH_F6 0xB6 #define CH_F7 0xB7 #define CH_F8 0xB8 #define CH_F9 0xB9 #define CH_F10 0xB0 /* Character codes */ #define CH_ULCORNER '+' #define CH_URCORNER '+' #define CH_LLCORNER '+' #define CH_LRCORNER '+' #define CH_TTEE '+' #define CH_BTEE '+' #define CH_LTEE '+' #define CH_RTEE '+' #define CH_CROSS '+' #define CH_CURS_UP 11 #define CH_CURS_DOWN 10 #define CH_CURS_LEFT 8 #define CH_CURS_RIGHT 9 #define CH_DEL 127 #define CH_ENTER 13 #define CH_STOP 3 #define CH_LIRA 95 #define CH_ESC 27 /* Masks for joy_read */ #define JOY_UP_MASK 0x10 #define JOY_DOWN_MASK 0x08 #define JOY_LEFT_MASK 0x01 #define JOY_RIGHT_MASK 0x02 #define JOY_BTN_1_MASK 0x20 /* No support for dynamically loadable drivers */ #define DYN_DRV 0 /* The addresses of the static drivers */ extern void atmos_pase_joy[]; /* Referred to by joy_static_stddrv[] */ extern void atmos_ijk_joy[]; extern void atmos_acia_ser[]; extern void atmos_228_200_3_tgi[]; extern void atmos_240_200_2_tgi[]; /* Referred to by tgi_static_stddrv[] */ /*****************************************************************************/ /* Functions */ /*****************************************************************************/ void __fastcall__ atmos_load(const char* name); /* Load Atmos tape. */ void __fastcall__ atmos_save(const char* name, const void* start, const void* end); /* Save Atmos tape. */ void atmos_explode (void); /* Bomb sound effect */ void atmos_ping (void); /* Bell or ricochet sound effect */ void atmos_shoot (void); /* Pistol sound effect */ void atmos_tick (void); /* High-pitch click */ void atmos_tock (void); /* Low-pitch click */ void atmos_zap (void); /* Raygun sound effect */ /* End of atmos.h */ #endif
sethcoder/cc65
testcode/lib/strncmp-test.c
<reponame>sethcoder/cc65<gh_stars>1-10 #include <stdlib.h> #include <stdio.h> #include <string.h> static const char S1[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0', 'A' }; static const char S2[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0', 'B' }; int main (void) { char I; for (I = 0; I < 20; ++I) { printf ("%02d: %d\n", I, strncmp (S1, S2, I)); } return 0; }
sethcoder/cc65
libsrc/common/abort.c
<filename>libsrc/common/abort.c<gh_stars>1-10 /* ** abort.c ** ** <NAME>, 02.06.1998 */ #include <stdio.h> #include <stdlib.h> #include <signal.h> void abort (void) { raise (SIGABRT); fputs ("ABNORMAL PROGRAM TERMINATION\n", stderr); exit (3); }
sethcoder/cc65
testcode/lib/em-test.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <conio.h> #include <em.h> #define FORCE_ERROR1 0 #define FORCE_ERROR2 0 #define PAGE_SIZE 128 /* Size in words */ #define BUF_SIZE (PAGE_SIZE + PAGE_SIZE/2) static unsigned buf[BUF_SIZE]; static void cleanup (void) /* Remove the driver on exit */ { em_unload (); } static void fill (register unsigned* page, register unsigned char count, register unsigned num) { register unsigned char i; for (i = 0; i < count; ++i, ++page) { *page = num; } } static void cmp (unsigned page, register const unsigned* buf, register unsigned char count, register unsigned num) { register unsigned char i; for (i = 0; i < count; ++i, ++buf) { if (*buf != num) { cprintf ("\r\nData mismatch in page $%04X at $%04X\r\n" "Data is $%04X (should be $%04X)\r\n", page, buf, *buf, num); #ifdef __ATARI__ cgetc (); #endif exit (EXIT_FAILURE); } } } typedef struct emd_test_s { char key; char *displayname; char *drivername; } emd_test_t; static emd_test_t drivers[] = { #if defined(__APPLE2__) { '0', "Apple II auxiliary memory", "a2.auxmem.emd" }, #endif #if defined(__APPLE2ENH__) { '0', "Apple II auxiliary memory", "a2e.auxmem.emd" }, #endif #if defined(__ATARI__) { '0', "Atari 130XE memory", "atr130.emd" }, #endif #if defined(__ATARIXL__) { '0', "Atari 130XE memory", "atrx130.emd" }, #endif #if defined(__C16__) { '0', "C16 RAM above $8000", "c16-ram.emd" }, #endif #if defined(__C64__) { '0', "C64 RAM above $D000", "c64-ram.emd" }, { '1', "C64 256K", "c64-c256k.emd" }, { '2', "Double Quick Brown Box", "c64-dqbb.emd" }, { '3', "GEORAM", "c64-georam.emd" }, { '4', "Isepic", "c64-isepic.emd" }, { '5', "RamCart", "c64-ramcart.emd" }, { '6', "REU", "c64-reu.emd" }, { '7', "C128 VDC (in C64 mode)", "c64-vdc.emd" }, { '8', "C64DTV himem", "dtv-himem.emd" }, { '9', "65816 extra banks", "c64-65816.emd" }, #endif #if defined(__C128__) { '0', "C128 RAM in bank 1", "c128-ram.emd" }, { '1', "C128 RAM in banks 1, 2 & 3", "c128-ram2.emd" }, { '2', "GEORAM", "c128-georam.emd" }, { '3', "RamCart", "c128-ramcart.emd" }, { '4', "REU", "c128-reu.emd" }, { '5', "VDC", "c128-vdc.emd" }, { '6', "Internal Function RAM", "c128-ifnram.emd" }, { '7', "External Function RAM", "c128-efnram.emd" }, #endif #if defined(__CBM510__) { '0', "CBM5x0 RAM in bank 2", "cbm510-ram.emd" }, #endif #if defined(__CBM610__) { '0', "CBM6x0/7x0 RAM in bank 2", "cbm610-ram.emd" }, #endif { 0, NULL, NULL } }; int main (void) { unsigned char Res; unsigned I; unsigned Offs; unsigned PageCount; unsigned char X, Y; struct em_copy c; unsigned index; signed char valid_key = -1; char key; clrscr (); cputs ("Which RAM exp to test?\r\n\r\n"); for (index = 0; drivers[index].key; ++index) { cprintf("%c: %s\r\n", drivers[index].key, drivers[index].displayname); } while (valid_key < 0) { key = cgetc(); for (index = 0; drivers[index].key && valid_key < 0; ++index) { if (key == drivers[index].key) { valid_key = index; } } } clrscr (); Res = em_load_driver (drivers[valid_key].drivername); if (Res != EM_ERR_OK) { cprintf ("Error in em_load_driver: %u\r\n", Res); cprintf ("os: %u, %s\r\n", _oserror, _stroserror (_oserror)); #ifdef __ATARI__ cgetc (); #endif exit (EXIT_FAILURE); } atexit (cleanup); /* Get the number of available pages */ PageCount = em_pagecount (); cprintf ("Loaded ok, page count = $%04X\r\n", PageCount); /* TEST #1: em_map/em_use/em_commit */ cputs ("Testing em_map/em_use/em_commit"); /* Fill all pages */ cputs ("\r\n Filling "); X = wherex (); Y = wherey (); for (I = 0; I < PageCount; ++I) { /* Fill the buffer and copy it to em */ fill (em_use (I), PAGE_SIZE, I); em_commit (); /* Keep the user happy */ gotoxy (X, Y); cputhex16 (I); } #if FORCE_ERROR1 ((unsigned*) em_map (0x03))[0x73] = 0xFFFF; em_commit (); #endif /* Check all pages */ cputs ("\r\n Comparing "); X = wherex (); Y = wherey (); for (I = 0; I < PageCount; ++I) { /* Get the buffer and compare it */ cmp (I, em_map (I), PAGE_SIZE, I); /* Keep the user happy */ gotoxy (X, Y); cputhex16 (I); } /* TEST #2: em_copyfrom/em_copyto. */ cputs ("\r\nTesting em_copyfrom/em_copyto"); /* We're filling now 384 bytes per run to test the copy routines with ** other sizes. */ PageCount = (PageCount * 2) / 3; /* Setup the copy structure */ c.buf = buf; c.count = sizeof (buf); /* Fill again all pages */ cputs ("\r\n Filling "); X = wherex (); Y = wherey (); c.page = 0; c.offs = 0; for (I = 0; I < PageCount; ++I) { /* Fill the buffer and copy it to em */ fill (buf, BUF_SIZE, I ^ 0xFFFF); em_copyto (&c); /* Adjust the em offset */ Offs = c.offs + sizeof (buf); c.offs = (unsigned char) Offs; c.page += (Offs >> 8); /* Keep the user happy */ gotoxy (X, Y); cputhex16 (I); } #if FORCE_ERROR2 c.page = 0x03; em_copyfrom (&c); buf[0x73] = 0xFFFF; em_copyto (&c); #endif /* Check all pages */ cputs ("\r\n Comparing "); X = wherex (); Y = wherey (); c.page = 0; c.offs = 0; for (I = 0; I < PageCount; ++I) { /* Get the buffer and compare it */ em_copyfrom (&c); cmp (I, buf, BUF_SIZE, I ^ 0xFFFF); /* Adjust the em offset */ Offs = c.offs + sizeof (buf); c.offs = (unsigned char) Offs; c.page += (Offs >> 8); /* Keep the user happy */ gotoxy (X, Y); cputhex16 (I); } /* Success */ cprintf ("\r\nPassed!\r\n"); #ifdef __ATARI__ cgetc (); #endif return 0; }
sethcoder/cc65
include/apple2enh.h
/*****************************************************************************/ /* */ /* apple2enh.h */ /* */ /* enhanced Apple //e system specific definitions */ /* */ /* */ /* */ /* (C) 2004 <NAME>, <<EMAIL>> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef _APPLE2ENH_H #define _APPLE2ENH_H /* Check for errors */ #if !defined(__APPLE2ENH__) # error This module may only be used when compiling for the enhanced Apple //e! #endif #include <apple2.h> /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Characters codes */ #define CH_DEL 0x7F #define CH_CURS_UP 0x0B #define CH_CURS_DOWN 0x0A #define CH_HLINE 0x5F #define CH_VLINE 0xDF #define CH_ULCORNER 0x5F #define CH_URCORNER 0x20 #define CH_LLCORNER 0xD4 #define CH_LRCORNER 0xDF #define CH_TTEE 0x5F #define CH_BTEE 0xD4 #define CH_LTEE 0xD4 #define CH_RTEE 0xDF #define CH_CROSS 0xD4 /* These are defined to be OpenApple + NumberKey */ #define CH_F1 0xB1 #define CH_F2 0xB2 #define CH_F3 0xB3 #define CH_F4 0xB4 #define CH_F5 0xB5 #define CH_F6 0xB6 #define CH_F7 0xB7 #define CH_F8 0xB8 #define CH_F9 0xB9 #define CH_F10 0xB0 /* Video modes */ #define VIDEOMODE_40x24 0x0011 #define VIDEOMODE_80x24 0x0012 #define VIDEOMODE_40COL VIDEOMODE_40x24 #define VIDEOMODE_80COL VIDEOMODE_80x24 /*****************************************************************************/ /* Variables */ /*****************************************************************************/ /* The addresses of the static drivers */ extern void a2e_auxmem_emd[]; extern void a2e_stdjoy_joy[]; /* Referred to by joy_static_stddrv[] */ extern void a2e_stdmou_mou[]; /* Referred to by mouse_static_stddrv[] */ extern void a2e_ssc_ser[]; extern void a2e_hi_tgi[]; /* Referred to by tgi_static_stddrv[] */ extern void a2e_lo_tgi[]; /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned __fastcall__ videomode (unsigned mode); /* Set the video mode, return the old mode. Call with one of the VIDEOMODE_xx ** constants. */ /* End of apple2enh.h */ #endif
sethcoder/cc65
include/serial.h
<filename>include/serial.h /*****************************************************************************/ /* */ /* serial.h */ /* */ /* Serial communication API */ /* */ /* */ /* */ /* (C) 2003-2012, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef _SERIAL_H #define _SERIAL_H /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Baudrate settings */ #define SER_BAUD_45_5 0x00 #define SER_BAUD_50 0x01 #define SER_BAUD_75 0x02 #define SER_BAUD_110 0x03 #define SER_BAUD_134_5 0x04 #define SER_BAUD_150 0x05 #define SER_BAUD_300 0x06 #define SER_BAUD_600 0x07 #define SER_BAUD_1200 0x08 #define SER_BAUD_1800 0x09 #define SER_BAUD_2400 0x0A #define SER_BAUD_3600 0x0B #define SER_BAUD_4800 0x0C #define SER_BAUD_7200 0x0D #define SER_BAUD_9600 0x0E #define SER_BAUD_19200 0x0F #define SER_BAUD_38400 0x10 #define SER_BAUD_57600 0x11 #define SER_BAUD_115200 0x12 #define SER_BAUD_230400 0x13 #define SER_BAUD_31250 0x14 #define SER_BAUD_62500 0x15 #define SER_BAUD_56_875 0x16 /* Data bit settings */ #define SER_BITS_5 0x00 #define SER_BITS_6 0x01 #define SER_BITS_7 0x02 #define SER_BITS_8 0x03 /* Stop bit settings */ #define SER_STOP_1 0x00 /* One stop bit */ #define SER_STOP_2 0x01 /* Two stop bits */ /* Parity settings */ #define SER_PAR_NONE 0x00 #define SER_PAR_ODD 0x01 #define SER_PAR_EVEN 0x02 #define SER_PAR_MARK 0x03 #define SER_PAR_SPACE 0x04 /* Handshake settings. The latter two may be combined. */ #define SER_HS_NONE 0x00 /* No handshake */ #define SER_HS_HW 0x01 /* Hardware (RTS/CTS) handshake */ #define SER_HS_SW 0x02 /* Software handshake */ /* Bit masks to mask out things from the status returned by ser_status. ** These are 6551 specific and must be mapped by drivers for other chips. */ #define SER_STATUS_PE 0x01 /* Parity error */ #define SER_STATUS_FE 0x02 /* Framing error */ #define SER_STATUS_OE 0x04 /* Overrun error */ #define SER_STATUS_DCD 0x20 /* NOT data carrier detect */ #define SER_STATUS_DSR 0x40 /* NOT data set ready */ /* Error codes returned by all functions */ #define SER_ERR_OK 0x00 /* Not an error - relax */ #define SER_ERR_NO_DRIVER 0x01 /* No driver available */ #define SER_ERR_CANNOT_LOAD 0x02 /* Error loading driver */ #define SER_ERR_INV_DRIVER 0x03 /* Invalid driver */ #define SER_ERR_NO_DEVICE 0x04 /* Device (hardware) not found */ #define SER_ERR_BAUD_UNAVAIL 0x05 /* Baud rate not available */ #define SER_ERR_NO_DATA 0x06 /* Nothing to read */ #define SER_ERR_OVERFLOW 0x07 /* No room in send buffer */ #define SER_ERR_INIT_FAILED 0x08 /* Initialization failed */ #define SER_ERR_INV_IOCTL 0x09 /* IOCTL not supported */ #define SER_ERR_INSTALLED 0x0A /* A driver is already installed */ #define SER_ERR_NOT_OPEN 0x0B /* Driver is not open */ /* Struct containing parameters for the serial port */ struct ser_params { unsigned char baudrate; /* Baudrate */ unsigned char databits; /* Number of data bits */ unsigned char stopbits; /* Number of stop bits */ unsigned char parity; /* Parity setting */ unsigned char handshake; /* Type of handshake to use */ }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned char __fastcall__ ser_load_driver (const char* driver); /* Load and install a serial driver. Return an error code. */ unsigned char ser_unload (void); /* Uninstall, then unload the currently loaded driver. */ unsigned char __fastcall__ ser_install (void* driver); /* Install an already loaded driver. Return an error code. */ unsigned char ser_uninstall (void); /* Uninstall the currently loaded driver and return an error code. ** Note: This call does not free allocated memory. */ unsigned char __fastcall__ ser_open (const struct ser_params* params); /* "Open" the port by setting the port parameters and enable interrupts. */ unsigned char ser_close (void); /* "Close" the port. Clear buffers and and disable interrupts. */ unsigned char __fastcall__ ser_get (char* b); /* Get a character from the serial port. If no characters are available, the ** function will return SER_ERR_NO_DATA, so this is not a fatal error. */ unsigned char __fastcall__ ser_put (char b); /* Send a character via the serial port. There is a transmit buffer, but ** transmitting is not done via interrupt. The function returns ** SER_ERR_OVERFLOW if there is no space left in the transmit buffer. */ unsigned char __fastcall__ ser_status (unsigned char* status); /* Return the serial port status. */ unsigned char __fastcall__ ser_ioctl (unsigned char code, void* data); /* Driver specific entry. */ /* End of serial.h */ #endif
sethcoder/cc65
include/limits.h
/*****************************************************************************/ /* */ /* limits.h */ /* */ /* Sizes of integer types */ /* */ /* */ /* */ /* (C) 1998-2002 <NAME> */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef _LIMITS_H #define _LIMITS_H #define CHAR_BIT 8 #define SCHAR_MIN ((signed char) 0x80) #define SCHAR_MAX 127 #define UCHAR_MAX 255 #define CHAR_MIN 0 #define CHAR_MAX 255 #define SHRT_MIN ((short) 0x8000) #define SHRT_MAX 32767 #define USHRT_MAX 65535U #define INT_MIN ((int) 0x8000) #define INT_MAX 32767 #define UINT_MAX 65535U #define LONG_MAX 2147483647L #define LONG_MIN ((long) 0x80000000) #define ULONG_MAX 4294967295UL /* End of limits.h */ #endif
sethcoder/cc65
testcode/lib/snprintf-test.c
/* ** Test a function that formats and writes characters into a string buffer. ** This program does not test formatting. It tests some behaviors that are ** specific to the buffer. It tests that certain conditions are handled ** properly. ** ** 2015-07-17, <NAME> */ #include <conio.h> #include <errno.h> #include <stdio.h> #include <string.h> static const char format[] = "1234567890\nabcdefghijklmnopqrstuvwxyz\n%u\n%s\n\n"; #define FORMAT_SIZE (sizeof format - 2u - 2u - 1u) #define arg1 12345u #define ARG1_SIZE (5u) static const char arg2[] = "!@#$%^&*()-+"; #define ARG2_SIZE (sizeof arg2 - 1u) #define STRING_SIZE (FORMAT_SIZE + ARG1_SIZE + ARG2_SIZE) static char buf[256]; static int size; static void fillbuf(void) { memset(buf, 0xFF, sizeof buf - 1u); buf[sizeof buf - 1u] = '\0'; } unsigned char main(void) { static unsigned char failures = 0; /* Show what sprintf() should create. */ if ((size = printf(format, arg1, arg2)) != STRING_SIZE) { ++failures; printf("printf() gave the wrong size: %d.\n", size); } /* Test the normal behavior of sprintf(). */ fillbuf(); size = sprintf(buf, format, arg1, arg2); fputs(buf, stdout); if (size != STRING_SIZE) { ++failures; printf("sprintf() gave the wrong size: %d.\n", size); } /* Test the normal behavior of snprintf(). */ fillbuf(); size = snprintf(buf, sizeof buf, format, arg1, arg2); fputs(buf, stdout); if (size != STRING_SIZE) { ++failures; printf("snprintf(sizeof buf) gave the wrong size:\n %d.\n", size); } /* Does snprintf() return the full-formatted size even when the buffer ** is short? Does it write beyond the end of that buffer? */ fillbuf(); size = snprintf(buf, STRING_SIZE - 5u, format, arg1, arg2); if (size != STRING_SIZE) { ++failures; printf("snprintf(STRING_SIZE-5) gave the wrong size:\n %d.\n", size); } if (buf[STRING_SIZE - 5u - 1u] != '\0' || buf[STRING_SIZE - 5u] != 0xFF) { ++failures; printf("snprintf(STRING_SIZE-5) wrote beyond\n the end of the buffer.\n"); } /* Does snprintf() detect a buffer size that is too big? */ fillbuf(); errno = 0; size = snprintf(buf, 0x8000, format, arg1, arg2); if (size >= 0) { ++failures; printf("snprintf(0x8000) didn't give an error:\n %d; errno=%d.\n", size, errno); } else { printf("snprintf(0x8000) did give an error:\n errno=%d.\n", errno); } if (buf[0] != 0xFF) { ++failures; printf("snprintf(0x8000) wrote into the buffer.\n"); } /* snprintf() must measure the length of the formatted output even when the ** buffer size is zero. But, it must not touch the buffer. */ fillbuf(); size = snprintf(buf, 0, format, arg1, arg2); if (size != STRING_SIZE) { ++failures; printf("snprintf(0) gave the wrong size:\n %d.\n", size); } if (buf[0] != 0xFF) { ++failures; printf("snprintf(0) wrote into the buffer.\n"); } /* Does sprintf() detect a zero buffer-pointer? */ errno = 0; size = sprintf(NULL, format, arg1, arg2); if (size >= 0) { ++failures; printf("sprintf(NULL) didn't give an error:\n %d; errno=%d.\n", size, errno); } else { printf("sprintf(NULL) did give an error:\n errno=%d.\n", errno); } /* snprintf() must measure the length of the formatted output even when the ** buffer size is zero. A zero pointer is not an error, in that case. */ size = snprintf(NULL, 0, format, arg1, arg2); if (size != STRING_SIZE) { ++failures; printf("snprintf(NULL,0) gave the wrong size:\n %d.\n", size); } if (failures != 0) { printf("There were %u", failures); } else { printf("There were no"); } printf(" failures.\nTap a key. "); cgetc(); return failures; }
sethcoder/cc65
src/ar65/library.c
/*****************************************************************************/ /* */ /* library.c */ /* */ /* Library data structures and helpers for the ar65 archiver */ /* */ /* */ /* */ /* (C) 1998-2013, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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 <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "cmdline.h" #include "exprdefs.h" #include "libdefs.h" #include "print.h" #include "symdefs.h" #include "xmalloc.h" /* ar65 */ #include "error.h" #include "exports.h" #include "fileio.h" #include "global.h" #include "library.h" #include "objdata.h" #include "objfile.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Name of the library file */ const char* LibName = 0; static char* NewLibName = 0; /* File descriptor for the library file */ static FILE* Lib = 0; static FILE* NewLib = 0; /* The library header */ static LibHeader Header = { LIB_MAGIC, LIB_VERSION, 0, 0 }; /*****************************************************************************/ /* Writing file data structures */ /*****************************************************************************/ static void ReadHeader (void) /* Read the header of a library file */ { /* Seek to position zero */ fseek (Lib, 0, SEEK_SET); /* Read the header fields, checking magic and version */ Header.Magic = Read32 (Lib); if (Header.Magic != LIB_MAGIC) { Error ("'%s' is not a valid library file", LibName); } Header.Version = Read16 (Lib); if (Header.Version != LIB_VERSION) { Error ("Wrong data version in '%s'", LibName); } Header.Flags = Read16 (Lib); Header.IndexOffs = Read32 (Lib); } static void ReadIndexEntry (void) /* Read one entry in the index */ { /* Create a new entry and insert it into the list */ ObjData* O = NewObjData (); /* Module name/flags/MTime/Start/Size */ O->Name = ReadStr (Lib); O->Flags = Read16 (Lib); O->MTime = Read32 (Lib); O->Start = Read32 (Lib); O->Size = Read32 (Lib); } static void ReadIndex (void) /* Read the index of a library file */ { unsigned Count, I; /* Seek to the start of the index */ fseek (Lib, Header.IndexOffs, SEEK_SET); /* Read the object file count and calculate the cross ref size */ Count = ReadVar (Lib); /* Read all entries in the index */ while (Count--) { ReadIndexEntry (); } /* Read basic object file data from the actual entries */ for (I = 0; I < CollCount (&ObjPool); ++I) { /* Get the object file entry */ ObjData* O = CollAtUnchecked (&ObjPool, I); /* Read data */ ObjReadData (Lib, O); } } /*****************************************************************************/ /* Writing file data structures */ /*****************************************************************************/ static void WriteHeader (void) /* Write the header to the library file */ { /* Seek to position zero */ fseek (NewLib, 0, SEEK_SET); /* Write the header fields */ Write32 (NewLib, Header.Magic); Write16 (NewLib, Header.Version); Write16 (NewLib, Header.Flags); Write32 (NewLib, Header.IndexOffs); } static void WriteIndexEntry (const ObjData* O) /* Write one index entry */ { /* Module name/flags/MTime/start/size */ WriteStr (NewLib, O->Name); Write16 (NewLib, O->Flags & ~OBJ_HAVEDATA); Write32 (NewLib, O->MTime); Write32 (NewLib, O->Start); Write32 (NewLib, O->Size); } static void WriteIndex (void) /* Write the index of a library file */ { unsigned I; /* Sync I/O in case the last operation was a read */ fseek (NewLib, 0, SEEK_CUR); /* Remember the current offset in the header */ Header.IndexOffs = ftell (NewLib); /* Write the object file count */ WriteVar (NewLib, CollCount (&ObjPool)); /* Write the object files */ for (I = 0; I < CollCount (&ObjPool); ++I) { WriteIndexEntry (CollConstAt (&ObjPool, I)); } } /*****************************************************************************/ /* High level stuff */ /*****************************************************************************/ void LibOpen (const char* Name, int MustExist, int NeedTemp) /* Open an existing library and a temporary copy. If MustExist is true, the ** old library is expected to exist. If NeedTemp is true, a temporary library ** is created. */ { /* Remember the name */ LibName = xstrdup (Name); /* Open the existing library for reading */ Lib = fopen (Name, "rb"); if (Lib == 0) { /* File does not exist */ if (MustExist) { Error ("Library '%s' does not exist", Name); } else { /* Announce the library's creation if ar65 is verbose. */ Print (stdout, 1, "%s: Library '%s' will be created.\n", ProgName, Name); } } else { /* We have an existing file: Read the header */ ReadHeader (); /* Now read the existing index */ ReadIndex (); } if (NeedTemp) { /* Create the temporary library name */ NewLibName = xmalloc (strlen (Name) + strlen (".temp") + 1); strcpy (NewLibName, Name); strcat (NewLibName, ".temp"); /* Create the temporary library */ NewLib = fopen (NewLibName, "w+b"); if (NewLib == 0) { Error ("Cannot create temporary library file: %s", strerror (errno)); } /* Write a dummy header to the temp file */ WriteHeader (); } } unsigned long LibCopyTo (FILE* F, unsigned long Bytes) /* Copy data from F to the temp library file, return the start position in ** the temporary library file. */ { unsigned char Buf [4096]; /* Remember the position */ unsigned long Pos = ftell (NewLib); /* Copy loop */ while (Bytes) { unsigned Count = (Bytes > sizeof (Buf))? sizeof (Buf) : Bytes; ReadData (F, Buf, Count); WriteData (NewLib, Buf, Count); Bytes -= Count; } /* Return the start position */ return Pos; } void LibCopyFrom (unsigned long Pos, unsigned long Bytes, FILE* F) /* Copy data from the library file into another file */ { unsigned char Buf [4096]; /* Seek to the correct position */ fseek (Lib, Pos, SEEK_SET); /* Copy loop */ while (Bytes) { unsigned Count = (Bytes > sizeof (Buf))? sizeof (Buf) : Bytes; ReadData (Lib, Buf, Count); WriteData (F, Buf, Count); Bytes -= Count; } } static void LibCheckExports (ObjData* O) /* Insert all exports from the given object file into the global list ** checking for duplicates. */ { unsigned I; /* Let the user know what we do */ Print (stdout, 2, "Module '%s' (%u exports):\n", O->Name, CollCount (&O->Exports)); /* Insert the exports into the global table */ for (I = 0; I < CollCount (&O->Exports); ++I) { /* Get the name of the export */ const char* Name = CollConstAt (&O->Exports, I); /* Insert the name into the hash table */ Print (stdout, 2, " %s\n", Name); ExpInsert (Name, O); } } void LibClose (void) /* Write remaining data, close both files and copy the temp file to the old ** filename */ { /* Do we have a temporary library? */ if (NewLib) { unsigned I; unsigned char Buf [4096]; size_t Count; /* Walk through the object file list, inserting exports into the ** export list checking for duplicates. Copy any data that is still ** in the old library into the new one. */ for (I = 0; I < CollCount (&ObjPool); ++I) { /* Get a pointer to the object */ ObjData* O = CollAtUnchecked (&ObjPool, I); /* Check exports, make global export table */ LibCheckExports (O); /* Copy data if needed */ if ((O->Flags & OBJ_HAVEDATA) == 0) { /* Data is still in the old library */ fseek (Lib, O->Start, SEEK_SET); O->Start = ftell (NewLib); LibCopyTo (Lib, O->Size); O->Flags |= OBJ_HAVEDATA; } } /* Write the index */ WriteIndex (); /* Write the updated header */ WriteHeader (); /* Close the file */ if (Lib && fclose (Lib) != 0) { Error ("Error closing library: %s", strerror (errno)); } /* Reopen the library and truncate it */ Lib = fopen (LibName, "wb"); if (Lib == 0) { Error ("Cannot open library '%s' for writing: %s", LibName, strerror (errno)); } /* Copy the temporary library to the new one */ fseek (NewLib, 0, SEEK_SET); while ((Count = fread (Buf, 1, sizeof (Buf), NewLib)) != 0) { if (fwrite (Buf, 1, Count, Lib) != Count) { Error ("Cannot write to '%s': %s", LibName, strerror (errno)); } } } /* Close both files */ if (Lib && fclose (Lib) != 0) { Error ("Problem closing '%s': %s", LibName, strerror (errno)); } if (NewLib && fclose (NewLib) != 0) { Error ("Problem closing temporary library file: %s", strerror (errno)); } if (NewLibName && remove (NewLibName) != 0) { Error ("Problem deleting temporary library file: %s", strerror (errno)); } }
sethcoder/cc65
include/_atarios.h
<reponame>sethcoder/cc65 /*****************************************************************************/ /* */ /* _atarios.h */ /* */ /* Internal include file, do not use directly */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef __ATARIOS_H #define __ATARIOS_H /* IOCB Command Codes */ #define IOCB_OPEN 0x03 /* open */ #define IOCB_GETREC 0x05 /* get record */ #define IOCB_GETCHR 0x07 /* get character(s) */ #define IOCB_PUTREC 0x09 /* put record */ #define IOCB_PUTCHR 0x0B /* put character(s) */ #define IOCB_CLOSE 0x0C /* close */ #define IOCB_STATIS 0x0D /* status */ #define IOCB_SPECIL 0x0E /* special */ #define IOCB_DRAWLN 0x11 /* draw line */ #define IOCB_FILLIN 0x12 /* draw line with right fill */ #define IOCB_RENAME 0x20 /* rename disk file */ #define IOCB_DELETE 0x21 /* delete disk file */ #define IOCB_LOCKFL 0x23 /* lock file (set to read-only) */ #define IOCB_UNLOCK 0x24 /* unlock file */ #define IOCB_POINT 0x25 /* point sector */ #define IOCB_NOTE 0x26 /* note sector */ #define IOCB_GETFL 0x27 /* get file length */ #define IOCB_CHDIR_MYDOS 0x29 /* change directory (MyDOS) */ #define IOCB_MKDIR 0x2A /* make directory (MyDOS/SpartaDOS) */ #define IOCB_RMDIR 0x2B /* remove directory (SpartaDOS) */ #define IOCB_CHDIR_SPDOS 0x2C /* change directory (SpartaDOS) */ #define IOCB_GETCWD 0x30 /* get current directory (MyDOS/SpartaDOS) */ #define IOCB_FORMAT 0xFE /* format */ /* Device control block */ struct __dcb { unsigned char ddevic; /* device id */ unsigned char dunit; /* unit number */ unsigned char dcomnd; /* command */ unsigned char dstats; /* command type / status return */ void *dbuf; /* pointer to buffer */ unsigned char dtimlo; /* device timeout in seconds */ unsigned char dunuse; /* - unused - */ unsigned int dbyt; /* # of bytes to transfer */ union { struct { unsigned char daux1; /* 1st command auxiliary byte */ unsigned char daux2; /* 2nd command auxiliary byte */ }; unsigned int daux; /* auxiliary as word */ }; }; typedef struct __dcb dcb_t; /* I/O control block */ struct __iocb { unsigned char handler; /* handler index number (0xff free) */ unsigned char drive; /* device number (drive) */ unsigned char command; /* command */ unsigned char status; /* status of last operation */ void* buffer; /* pointer to buffer */ void* put_byte; /* pointer to device's PUT BYTE routine */ unsigned int buflen; /* length of buffer */ unsigned char aux1; /* 1st auxiliary byte */ unsigned char aux2; /* 2nd auxiliary byte */ unsigned char aux3; /* 3rd auxiliary byte */ unsigned char aux4; /* 4th auxiliary byte */ unsigned char aux5; /* 5th auxiliary byte */ unsigned char spare; /* spare byte */ }; typedef struct __iocb iocb_t; /* DOS 2.x zeropage variables */ struct __dos2x { unsigned char* zbufp; /* points to user filename */ unsigned char* zdrva; /* points to serveral buffers (mostly VTOC) */ unsigned char* zsba; /* points to sector buffer */ unsigned char errno; /* number of occured error */ }; typedef struct __dos2x dos2x_t; /* A single device handler formed by it's routines */ struct __devhdl { void *open; /* address of OPEN routine -1 */ void *close; /* address of CLOSE routine -1 */ void *get; /* address of GET BYTE routine -1 */ void *put; /* address of PUT BYTE routine -1 */ void *status; /* address of GET STATUS routine -1 */ void *special; /* address od SPECIAL routine -1 */ void (*init)(void); /* init routine (JMP INIT) */ void *reserved; /* unused */ }; typedef struct __devhdl devhdl_t; /* List of device handlers, as managed in HATABS */ struct __hatabs { unsigned char id; /* ATASCII code of handler e.g. 'C','D','E','K','P','S','R' */ devhdl_t* devhdl; /* Pointer to routines of device */ }; typedef struct __hatabs hatabs_t; /* Floating point register */ struct __fpreg { #ifdef OS_REV2 unsigned char fr; unsigned char frm[5]; /* 5-byte register mantissa */ #else unsigned char fr[6]; /* 6 bytes for single register */ #endif }; typedef struct __fpreg fpreg_t; enum { /* enum for access of floating point registers */ FPIDX_R0 = 0, /* (to use as index) */ FPIDX_RE = 1, FPIDX_R1 = 2, FPIDX_R2 = 3 }; /* Define a structure with atari os register offsets */ struct __os { // --- Zero-Page --- #ifdef OSA unsigned char* linzbs; // = $00/$01 LINBUG RAM (WILL BE REPLACED BY MONITOR RAM) #else unsigned char linflg; // = $00 LNBUG FLAG (0 = NOT LNBUG) unsigned char ngflag; // = $01 MEMORY STATUS (0 = FAILURE) #endif unsigned char* casini; // = $02/$03 CASSETTE INIT LOCATION unsigned char* ramlo; // = $04/$05 RAM POINTER FOR MEMORY TEST #ifdef OSA unsigned char tramsz; // = $06 FLAG FOR LEFT CARTRIDGE unsigned char tstdat; // = $07 FLAG FOR RIGHT CARTRIDGE #else unsigned char trnsmz; // = $06 TEMPORARY REGISTER FOR RAM SIZE unsigned char tstdat; // = $07 UNUSED (NOT TOUCHED DURING RESET/COLD START) #endif // Cleared upon Coldstart only unsigned char warmst; // = $08 WARM START FLAG unsigned char bootq; // = $09 SUCCESSFUL BOOT FLAG void (*dosvec)(void); // = $0A/$0B DISK SOFTWARE START VECTOR void (*dosini)(void); // = $0C/$0D DISK SOFTWARE INIT ADDRESS unsigned char* appmhi; // = $0E/$0F APPLICATIONS MEMORY HI LIMIT // Cleared upon Coldstart or Warmstart unsigned char pokmsk; // = $10 SYSTEM MASK FOR POKEY IRQ ENABLE unsigned char brkkey; // = $11 BREAK KEY FLAG unsigned char rtclok[3]; // = $12-$14 REAL TIME CLOCK (IN 16 MSEC UNITS) unsigned char* bufadr; // = $15/$16 INDIRECT BUFFER ADDRESS REGISTER unsigned char iccomt; // = $17 COMMAND FOR VECTOR unsigned char* dskfms; // = $18/$19 DISK FILE MANAGER POINTER unsigned char* dskutl; // = $1A/$1B DISK UTILITIES POINTER #ifdef OSA unsigned char ptimot; // = $1C PRINTER TIME OUT REGISTER unsigned char pbpnt; // = $1D PRINT BUFFER POINTER unsigned char pbufsz; // = $1E PRINT BUFFER SIZE unsigned char ptemp; // = $1F TEMPORARY REGISTER #else unsigned char abufpt[4]; // = $1C-$1F ACMI BUFFER POINTER AREA #endif iocb_t ziocb; // = $20-$2F ZERO PAGE I/O CONTROL BLOCK unsigned char status; // = $30 INTERNAL STATUS STORAGE unsigned char chksum; // = $31 CHECKSUM (SINGLE BYTE SUM WITH CARRY) unsigned char* bufr; // = $32/$33 POINTER TO DATA BUFFER unsigned char* bfen; // = $34/$35 NEXT BYTE PAST END OF THE DATA BUFFER LO #ifdef OSA unsigned char cretry; // = $36 NUMBER OF COMMAND FRAME RETRIES unsigned char dretry; // = $37 NUMBER OF DEVICE RETRIES #else unsigned int ltemp; // = $36/$37 LOADER TEMPORARY #endif unsigned char bufrfl; // = $38 DATA BUFFER FULL FLAG unsigned char recvdn; // = $39 RECEIVE DONE FLAG unsigned char xmtdon; // = $3A TRANSMISSION DONE FLAG unsigned char chksnt; // = $3B CHECKSUM SENT FLAG unsigned char nocksm; // = $3C NO CHECKSUM FOLLOWS DATA FLAG unsigned char bptr; // = $3D CASSETTE BUFFER POINTER unsigned char ftype; // = $3E CASSETTE IRG TYPE unsigned char feof; // = $3F CASSETTE EOF FLAG (0 // = QUIET) unsigned char freq; // = $40 CASSETTE BEEP COUNTER unsigned char soundr; // = $41 NOISY I/0 FLAG. (ZERO IS QUIET) unsigned char critic; // = $42 DEFINES CRITICAL SECTION (CRITICAL IF NON-Z) dos2x_t fmszpg; // = $43-$49 DISK FILE MANAGER SYSTEM ZERO PAGE #ifdef OSA unsigned char ckey; // = $4A FLAG SET WHEN GAME START PRESSED unsigned char cassbt; // = $4B CASSETTE BOOT FLAG #else void* zchain; // = $4A/$4B HANDLER LINKAGE CHAIN POINTER #endif unsigned char dstat; // = $4C DISPLAY STATUS unsigned char atract; // = $4D ATRACT FLAG unsigned char drkmsk; // = $4E DARK ATRACT MASK unsigned char colrsh; // = $4F ATRACT COLOR SHIFTER (EOR'ED WITH PLAYFIELD unsigned char tmpchr; // = $50 TEMPORARY CHARACTER unsigned char hold1; // = $51 TEMPORARY unsigned char lmargn; // = $52 LEFT MARGIN (NORMALLY 2, CC65 C STARTUP CODE SETS IT TO 0) unsigned char rmargn; // = $53 RIGHT MARGIN (NORMALLY 39 IF NO XEP80 IS USED) unsigned char rowcrs; // = $54 1CURSOR ROW unsigned int colcrs; // = $55/$56 CURSOR COLUMN unsigned char dindex; // = $57 DISPLAY MODE unsigned char* savmsc; // = $58/$59 SAVED MEMORY SCAN COUNTER unsigned char oldrow; // = $5A PRIOR ROW unsigned int oldcol; // = $5B/$5C PRIOR COLUMN unsigned char oldchr; // = $5D DATA UNDER CURSOR unsigned char* oldadr; // = $5E/$5F SAVED CURSOR MEMORY ADDRESS #ifdef OSA unsigned char newrow; // = $60 POINT DRAW GOES TO unsigned int newcol; // = $61/$62 COLUMN DRAW GOES TO #else unsigned char* fkdef; // = $60/$61 FUNCTION KEY DEFINITION TABLE unsigned char palnts; // = $62 PAL/NTSC INDICATOR (0 // = NTSC) #endif unsigned char logcol; // = $63 POINTS AT COLUMN IN LOGICAL LINE unsigned char* adress; // = $64/$65 TEMPORARY ADDRESS unsigned int mlttmp; // = $66/$67 TEMPORARY / FIRST BYTE IS USED IN OPEN AS TEMP unsigned int savadr; // = $68/$69 SAVED ADDRESS unsigned char ramtop; // = $6A RAM SIZE DEFINED BY POWER ON LOGIC unsigned char bufcnt; // = $6B BUFFER COUNT unsigned char* bufstr; // = $6C/$6D EDITOR GETCH POINTER unsigned char bitmsk; // = $6E BIT MASK unsigned char shfamt; // = $6F SHIFT AMOUNT FOR PIXEL JUSTIFUCATION unsigned int rowac; // = $70/$71 DRAW WORKING ROW unsigned int colac; // = $72/$73 DRAW WORKING COLUMN unsigned char* endpt; // = $74/$75 END POINT unsigned char deltar; // = $76 ROW DIFFERENCE unsigned int deltac; // = $77/$78 COLUMN DIFFERENCE #ifdef OSA unsigned char rowinc; // = $79 ROWINC unsigned char colinc; // = $7A COLINC #else unsigned char* keydef; // = $79/$7A 2-BYTE KEY DEFINITION TABLE ADDRESS #endif unsigned char swpflg; // = $7B NON-0 1F TXT AND REGULAR RAM IS SWAPPED unsigned char holdch; // = $7C CH IS MOVED HERE IN KGETCH BEFORE CNTL & SH unsigned char insdat; // = $7D 1-BYTE TEMPORARY unsigned int countr; // = $7E/$7F 2-BYTE DRAW ITERATION COUNT unsigned char _free_1[0xD4-0x7F-1]; // USER SPACE // Floating Point Package Page Zero Address Equates fpreg_t fpreg[4]; // = $D4-$EB 4 REGSITERS, ACCCESS LIKE "fpreg[FPIDX_R0].fr" unsigned char frx; // = $EC 1-BYTE TEMPORARY unsigned char eexp; // = $ED VALUE OF EXP #ifdef OS_REV2 unsigned char frsign; // = $EE ##REV2## 1-BYTE FLOATING POINT SIGN unsigned char plycnt; // = $EF ##REV2## 1-BYTE POLYNOMIAL DEGREE unsigned char sgnflg; // = $F0 ##REV2## 1-BYTE SIGN FLAG unsigned char xfmflg; // = $F1 ##REV2## 1-BYTE TRANSFORM FLAG #else unsigned char nsign; // = $EE SIGN OF # unsigned char esign; // = $EF SIGN OF EXPONENT unsigned char fchrflg; // = $F0 1ST CHAR FLAG unsigned char digrt; // = $F1 # OF DIGITS RIGHT OF DECIMAL #endif unsigned char cix; // = $F2 CURRENT INPUT INDEX unsigned char* inbuff; // = $F3/$F4 POINTS TO USER'S LINE INPUT BUFFER unsigned int ztemp1; // = $F5/$F6 2-BYTE TEMPORARY unsigned int ztemp4; // = $F7/$F8 2-BYTE TEMPORARY unsigned int ztemp3; // = $F9/$FA 2-BYTE TEMPORARY union { unsigned char degflg; // = $FB ##OLD## SAME AS RADFLG unsigned char radflg; // = $FB ##OLD## 0=RADIANS, 6=DEGREES }; fpreg_t* flptr; // = $FC/$FD 2-BYTE FLOATING POINT NUMBER POINTER fpreg_t* fptr2; // = $FE/$FF 2-BYTE FLOATING POINT NUMBER POINTER // --- Page 1 --- unsigned char stack[0x100]; // STACK // --- Page 2 --- void (*vdslst)(void); // = $0200/$0201 DISPLAY LIST NMI VECTOR void (*vprced)(void); // = $0202/$0203 PROCEED LINE IRQ VECTOR void (*vinter)(void); // = $0204/$0205 INTERRUPT LINE IRQ VECTOR void (*vbreak)(void); // = $0206/$0207 SOFTWARE BREAK (00) INSTRUCTION IRQ VECTOR void (*vkeybd)(void); // = $0208/$0209 POKEY KEYBOARD IRQ VECTOR void (*vserin)(void); // = $020A/$020B POKEY SERIAL INPUT READY IRQ void (*vseror)(void); // = $020C/$020D POKEY SERIAL OUTPUT READY IRQ void (*vseroc)(void); // = $020E/$020F POKEY SERIAL OUTPUT COMPLETE IRQ void (*vtimr1)(void); // = $0210/$0201 POKEY TIMER 1 IRQ void (*vtimr2)(void); // = $0212/$0203 POKEY TIMER 2 IRQ void (*vtimr4)(void); // = $0214/$0205 POKEY TIMER 4 IRQ void (*vimirq)(void); // = $0216/$0207 IMMEDIATE IRQ VECTOR unsigned int cdtmv1; // = $0218/$0210 COUNT DOWN TIMER 1 unsigned int cdtmv2; // = $021A/$021B COUNT DOWN TIMER 2 unsigned int cdtmv3; // = $021C/$021D COUNT DOWN TIMER 3 unsigned int cdtmv4; // = $021E/$021F COUNT DOWN TIMER 4 unsigned int cdtmv5; // = $0220/$0221 COUNT DOWN TIMER 5 void (*vvblki)(void); // = $0222/$0223 IMMEDIATE VERTICAL BLANK NMI VECTOR void (*vvblkd)(void); // = $0224/$0224 DEFERRED VERTICAL BLANK NMI VECTOR void (*cdtma1)(void); // = $0226/$0227 COUNT DOWN TIMER 1 JSR ADDRESS void (*cdtma2)(void); // = $0228/$0229 COUNT DOWN TIMER 2 JSR ADDRESS unsigned char cdtmf3; // = $022A COUNT DOWN TIMER 3 FLAG unsigned char srtimr; // = $022B SOFTWARE REPEAT TIMER unsigned char cdtmf4; // = $022C COUNT DOWN TIMER 4 FLAG unsigned char intemp; // = $022D IAN'S TEMP unsigned char cdtmf5; // = $022E COUNT DOWN TIMER FLAG 5 unsigned char sdmctl; // = $022F SAVE DMACTL REGISTER union { struct { unsigned char sdlstl; // = $0230 SAVE DISPLAY LIST LOW BYTE unsigned char sdlsth; // = $0231 SAVE DISPLAY LIST HI BYTE }; void* sdlst; // = $0230/$0231 (same as above as pointer) }; unsigned char sskctl; // = $0232 SKCTL REGISTER RAM #ifdef OSA unsigned char _spare_1; // = $0233 No OS use. #else unsigned char lcount; // = $0233 ##1200xl## 1-byte relocating loader record #endif unsigned char lpenh; // = $0234 LIGHT PEN HORIZONTAL VALUE unsigned char lpenv; // = $0235 LIGHT PEN VERTICAL VALUE void (*brkky)(void); // = $0236/$0237 BREAK KEY VECTOR #ifdef OSA unsigned char spare2[2]; // = $0238/$0239 No OS use. #else void (*vpirq)(void); // = $0238/$0239 ##rev2## 2-byte parallel device IRQ vector #endif unsigned char cdevic; // = $023A COMMAND FRAME BUFFER - DEVICE unsigned char ccomnd; // = $023B COMMAND union { struct { unsigned char caux1; // = $023C COMMAND AUX BYTE 1 unsigned char caux2; // = $023D COMMAND AUX BYTE 2 }; unsigned int caux; // = $023C/$023D (same as above as word) }; unsigned char temp; // = $023E TEMPORARY RAM CELL unsigned char errflg; // = $023F ERROR FLAG - ANY DEVICE ERROR EXCEPT TIME OUT unsigned char dflags; // = $0240 DISK FLAGS FROM SECTOR ONE unsigned char dbsect; // = $0241 NUMBER OF DISK BOOT SECTORS unsigned char* bootad; // = $0242/$0243 ADDRESS WHERE DISK BOOT LOADER WILL BE PUT unsigned char coldst; // = $0244 COLDSTART FLAG (1=IN MIDDLE OF COLDSTART> #ifdef OSA unsigned char spare3; // = $0245 No OS use. #else unsigned char reclen; // = $0245 ##1200xl## 1-byte relocating loader record length #endif unsigned char dsktim; // = $0246 DISK TIME OUT REGISTER #ifdef OSA unsigned char linbuf[40]; // = $0247-$026E ##old## CHAR LINE BUFFER #else unsigned char pdvmsk; // = $0247 ##rev2## 1-byte parallel device selection mask unsigned char shpdvs; // = $0248 ##rev2## 1-byte PDVS (parallel device select) unsigned char pdimsk; // = $0249 ##rev2## 1-byte parallel device IRQ selection unsigned int reladr; // = $024A/$024B ##rev2## 2-byte relocating loader relative adr. unsigned char pptmpa; // = $024C ##rev2## 1-byte parallel device handler temporary unsigned char pptmpx; // = $024D ##rev2## 1-byte parallel device handler temporary unsigned char _reserved_1[29]; // = $024E-$026A RESERVED unsigned char chsalt; // = $026B ##1200xl## 1-byte character set alternate unsigned char vsflag; // = $026C ##1200xl## 1-byte fine vertical scroll count unsigned char keydis; // = $026D ##1200xl## 1-byte keyboard disable unsigned char fine; // = $026E ##1200xl## 1-byte fine scrolling mode #endif unsigned char gprior; // = $026F GLOBAL PRIORITY CELL unsigned char paddl0; // = $0270 1-BYTE POTENTIOMETER 0 unsigned char paddl1; // = $0271 1-BYTE POTENTIOMETER 1 unsigned char paddl2; // = $0272 1-BYTE POTENTIOMETER 2 unsigned char paddl3; // = $0273 1-BYTE POTENTIOMETER 3 unsigned char paddl4; // = $0274 1-BYTE POTENTIOMETER 4 unsigned char paddl5; // = $0275 1-BYTE POTENTIOMETER 5 unsigned char paddl6; // = $0276 1-BYTE POTENTIOMETER 6 unsigned char paddl7; // = $0277 1-BYTE POTENTIOMETER 7 unsigned char stick0; // = $0278 1-byte joystick 0 unsigned char stick1; // = $0279 1-byte joystick 1 unsigned char stick2; // = $027A 1-byte joystick 2 unsigned char stick3; // = $027B 1-byte joystick 3 unsigned char ptrig0; // = $027C 1-BYTE PADDLE TRIGGER 0 unsigned char ptrig1; // = $027D 1-BYTE PADDLE TRIGGER 1 unsigned char ptrig2; // = $027E 1-BYTE PADDLE TRIGGER 2 unsigned char ptrig3; // = $027F 1-BYTE PADDLE TRIGGER 3 unsigned char ptrig4; // = $0280 1-BYTE PADDLE TRIGGER 4 unsigned char ptrig5; // = $0281 1-BYTE PADDLE TRIGGER 5 unsigned char ptrig6; // = $0281 1-BYTE PADDLE TRIGGER 6 unsigned char ptrig7; // = $0283 1-BYTE PADDLE TRIGGER 7 unsigned char strig0; // = $0284 1-BYTE JOYSTICK TRIGGER 0 unsigned char strig1; // = $0285 1-BYTE JOYSTICK TRIGGER 1 unsigned char strig2; // = $0286 1-BYTE JOYSTICK TRIGGER 2 unsigned char strig3; // = $0287 1-BYTE JOYSTICK TRIGGER 3 #ifdef OSA unsigned char cstat; // = $0288 ##old## cassette status register #else unsigned char hibyte; // = $0288 ##1200xl## 1-byte relocating loader high byte #endif unsigned char wmode; // = $0289 1-byte cassette WRITE mode unsigned char blim; // = $028A 1-byte cassette buffer limit #ifdef OSA unsigned char _reserved_2[5]; // = $028B-$028F RESERVED #else unsigned char imask; // = $028B ##rev2## (not used) void (*jveck)(void); // = $028C/$028D 2-byte jump vector unsigned newadr; // = $028E/028F ##1200xl## 2-byte relocating address #endif unsigned char txtrow; // = $0290 TEXT ROWCRS unsigned txtcol; // = $0291/$0292 TEXT COLCRS unsigned char tindex; // = $0293 TEXT INDEX unsigned char* txtmsc; // = $0294/$0295 FOOLS CONVRT INTO NEW MSC unsigned char txtold[6]; // = $0296-$029B OLDROW & OLDCOL FOR TEXT (AND THEN SOME) #ifdef OSA unsigned char tmpx1; // = $029C ##old## 1--byte temporary register #else unsigned char cretry; // = $029C ##1200xl## 1-byte number of command frame retries #endif unsigned char hold3; // = $029D 1-byte temporary unsigned char subtmp; // = $029E 1-byte temporary unsigned char hold2; // = $029F 1-byte (not used) unsigned char dmask; // = $02A0 1-byte display (pixel location) mask unsigned char tmplbt; // = $02A1 1-byte (not used) unsigned char escflg; // = $02A2 ESCAPE FLAG unsigned char tabmap[15]; // = $02A3-$02B1 15-byte (120 bit) tab stop bit map unsigned char logmap[4]; // = $02B2-$02B5 LOGICAL LINE START BIT MAP unsigned char invflg; // = $02B6 INVERSE VIDEO FLAG (TOGGLED BY ATARI KEY) unsigned char filflg; // = $02B7 RIGHT FILL FLAG FOR DRAW unsigned char tmprow; // = $02B8 1-byte temporary row unsigned tmpcol; // = $02B9/$02BA 2-byte temporary column unsigned char scrflg; // = $02BB SET IF SCROLL OCCURS unsigned char hold4; // = $02BC TEMP CELL USED IN DRAW ONLY #ifdef OSA unsigned char hold5; // = $02BD ##old## DITTO #else unsigned char dretry; // = $02BD ##1200xl## 1-byte number of device retries #endif unsigned char shflok; // = $02BE 1-byte shift/control lock flags unsigned char botscr; // = $02BF BOTTOM OF SCREEN 24 NORM 4 SPLIT unsigned char pcolr0; // = $02C0 1-byte player-missile 0 color/luminance unsigned char pcolr1; // = $02C1 1-byte player-missile 1 color/luminance unsigned char pcolr2; // = $02C2 1-byte player-missile 2 color/luminance unsigned char pcolr3; // = $02C3 1-byte player-missile 3 color/luminance unsigned char color0; // = $02C4 1-byte playfield 0 color/luminance unsigned char color1; // = $02C5 1-byte playfield 1 color/luminance unsigned char color2; // = $02C6 1-byte playfield 2 color/luminance unsigned char color3; // = $02C7 1-byte playfield 3 color/luminance unsigned char color4; // = $02C8 1-byte background color/luminance #ifdef OSA unsigned char _spare_2[23]; // = $02C9-$02DF No OS use. #else union { unsigned char parmbl[6]; // = $02C9 ##rev2## 6-byte relocating loader parameter struct { void (*runadr)(void); // = $02C9 ##1200xl## 2-byte run address unsigned int hiused; // = $02CB ##1200xl## 2-byte highest non-zero page address unsigned int zhiuse; // = $02CD ##1200xl## 2-byte highest zero page address }; }; union { unsigned char oldpar[6]; // = $02CF ##rev2## 6-byte relocating loader parameter struct { void (*gbytea)(void); // = $02CF ##1200xl## 2-byte GET-BYTE routine address unsigned int loadad; // = $02D1 ##1200xl## 2-byte non-zero page load address unsigned int zloada; // = $02D3 ##1200xl## 2-byte zero page load address }; }; unsigned int dsctln; // = $02D5 ##1200xl## 2-byte disk sector length unsigned int acmisr; // = $02D7 ##1200xl## 2-byte ACMI interrupt service routine unsigned char krpdel; // = $02D9 ##1200xl## 1-byte auto-repeat delay unsigned char keyrep; // = $02DA ##1200xl## 1-byte auto-repeat rate unsigned char noclik; // = $02DB ##1200xl## 1-byte key click disable unsigned char helpfg; // = $02DC ##1200xl## 1-byte HELP key flag (0 = no HELP) unsigned char dmasav; // = $02DD ##1200xl## 1-byte SDMCTL save/restore unsigned char pbpnt; // = $02DE ##1200xl## 1-byte printer buffer pointer unsigned char pbufsz; // = $02DF ##1200xl## 1-byte printer buffer size #endif union { unsigned char glbabs[4]; // = $02E0-$02E3 byte global variables for non-DOS users struct { void (*runad)(void); // = $02E0 ##map## 2-byte binary file run address void (*initad)(void); // = $02E2 ##map## 2-byte binary file initialization address }; }; unsigned char ramsiz; // = $02E4 RAM SIZE (HI BYTE ONLY) void* memtop; // = $02E5 TOP OF AVAILABLE USER MEMORY void* memlo; // = $02E7 BOTTOM OF AVAILABLE USER MEMORY #ifdef OSA unsigned char _spare_3; // = $02E9 No OS use. #else unsigned char hndlod; // = $02E9 ##1200xl## 1-byte user load flag #endif unsigned char dvstat[4]; // = $02EA-$02ED STATUS BUFFER union { unsigned int cbaud; // = $02EE/$02EF 2-byte cassette baud rate struct { unsigned char cbaudl; // = $02EE 1-byte low cassette baud rate unsigned char cbaudh; // = $02EF 1-byte high cassette baud rate }; }; unsigned char crsinh; // = $02F0 CURSOR INHIBIT (00 = CURSOR ON) unsigned char keydel; // = $02F1 KEY DELAY unsigned char ch1; // = $02F2 1-byte prior keyboard character unsigned char chact; // = $02F3 CHACTL REGISTER RAM unsigned char chbas; // = $02F4 CHBAS REGISTER RAM #ifdef OSA unsigned char _spare_4[5]; // = $02F5-$02F9 No OS use. #else unsigned char newrow; // = $02F5 ##1200xl## 1-byte draw destination row unsigned int newcol; // = $02F6/$02F7 ##1200xl## 2-byte draw destination column unsigned char rowinc; // = $02F8 ##1200xl## 1-byte draw row increment unsigned char colinc; // = $02F9 ##1200xl## 1-byte draw column increment #endif unsigned char char_; // = $02FA 1-byte internal character (naming changed due to do keyword conflict) unsigned char atachr; // = $02FB ATASCII CHARACTER unsigned char ch; // = $02FC GLOBAL VARIABLE FOR KEYBOARD unsigned char fildat; // = $02FD RIGHT FILL DATA <DRAW> unsigned char dspflg; // = $02FE DISPLAY FLAG DISPLAY CNTLS IF NON-ZERO unsigned char ssflag; // = $02FF START/STOP FLAG FOR PAGING (CNTL 1). CLEARE // --- Page 3 --- dcb_t dcb; // = $0300-$030B DEVICE CONTROL BLOCK unsigned int timer1; // = $030C/$030D INITIAL TIMER VALUE #ifdef OSA unsigned char addcor; // = $030E ##old## ADDITION CORRECTION #else unsigned char jmpers; // = $030E ##1200xl## 1-byte jumper options #endif unsigned char casflg; // = $030F CASSETTE MODE WHEN SET unsigned int timer2; // = $0310/$0311 2-byte final baud rate timer value unsigned char temp1; // = $0312 TEMPORARY STORAGE REGISTER #ifdef OSA unsigned char _spare_5; // = $0313 unused unsigned char temp2; // = $0314 ##old## TEMPORARY STORAGE REGISTER #else unsigned char temp2; // = $0313 ##1200xl## 1-byte temporary unsigned char ptimot; // = $0314 ##1200xl## 1-byte printer timeout #endif unsigned char temp3; // = $0315 TEMPORARY STORAGE REGISTER unsigned char savio; // = $0316 SAVE SERIAL IN DATA PORT unsigned char timflg; // = $0317 TIME OUT FLAG FOR BAUD RATE CORRECTION unsigned char stackp; // = $0318 SIO STACK POINTER SAVE CELL unsigned char tstat; // = $0319 TEMPORARY STATUS HOLDER #ifdef OSA hatabs_t hatabs[12]; // = $031A-$033D handler address table unsigned int zeropad; // = $033E/$033F zero padding #else hatabs_t hatabs[11]; // = $031A-$033A handler address table unsigned int zeropad; // = $033B/$033C zero padding unsigned char pupbt1; // = $033D ##1200xl## 1-byte power-up validation byte 1 unsigned char pupbt2; // = $033E ##1200xl## 1-byte power-up validation byte 2 unsigned char pupbt3; // = $033F ##1200xl## 1-byte power-up validation byte 3 #endif iocb_t iocb[8]; // = $0340-$03BF 8 I/O Control Blocks unsigned char prnbuf[40]; // = $03C0-$3E7 PRINTER BUFFER #ifdef OSA unsigned char _spare_6[151]; // = $03E8-$047F unused #else unsigned char superf; // = $03E8 ##1200xl## 1-byte editor super function flag unsigned char ckey; // = $03E9 ##1200xl## 1-byte cassette boot request flag unsigned char cassbt; // = $03EA ##1200xl## 1-byte cassette boot flag unsigned char cartck; // = $03EB ##1200xl## 1-byte cartridge equivalence check unsigned char derrf; // = $03EC ##rev2## 1-byte screen OPEN error flag unsigned char acmvar[11]; // = $03ED-$03F7 ##1200xl## reserved for ACMI, not cleared upon reset unsigned char basicf; // = $03F8 ##rev2## 1-byte BASIC switch flag unsigned char mintlk; // = $03F9 ##1200xl## 1-byte ACMI module interlock unsigned char gintlk; // = $03FA ##1200xl## 1-byte cartridge interlock void* chlink; // = $03FB/$03FC ##1200xl## 2-byte loaded handler chain link unsigned char casbuf[131]; // = $03FD-$047F CASSETTE BUFFER #endif // --- Page 4 --- unsigned char usarea[128]; // = $0480 128 bytes reserved for application // --- Page 5 --- unsigned char _spare_7[126]; // = $0500-$057D reserved for FP package / unused unsigned char lbpr1; // = $057E LBUFF PREFIX 1 unsigned char lbpr2; // = $057F LBUFF PREFIX 2 unsigned char lbuff[128]; // = $0580-$05FF 128-byte line buffer }; /* Define a structure with the zero page atari basic register offsets */ struct __basic { void* lowmem; // = $80/$81 POINTER TO BASIC'S LOW MEMORY void* vntp; // = $82/$83 BEGINNING ADDRESS OF THE VARIABLE NAME TABLE void* vntd; // = $84/$85 POINTER TO THE ENDING ADDRESS OF THE VARIABLE NAME TABLE PLUS ONE void* vvtp; // = $86/$87 ADDRESS FOR THE VARIABLE VALUE TABLE void* stmtab; // = $88/$89 ADDRESS OF THE STATEMENT TABLE void* stmcur; // = $8A/$8B CURRENT BASIC STATEMENT POINTER void* starp; // = $8C/$8D ADDRESS FOR THE STRING AND ARRAY TABLE void* runstk; // = $8E/$8F ADDRESS OF THE RUNTIME STACK void* memtop; // = $90/$91 POINTER TO THE TOP OF BASIC MEMORY unsigned char _internal_1[0xBA-0x91-1]; // INTERNAL DATA unsigned int stopln; // = $BA/$BB LINE WHERE A PROGRAM WAS STOPPED unsigned char _internal_2[0xC3-0xBB-1]; // INTERNAL DATA unsigned char errsav; // = $C3 NUMBER OF THE ERROR CODE unsigned char _internal_3[0xC9-0xC3-1]; // INTERNAL DATA unsigned char ptabw; // = $C9 NUMBER OF COLUMNS BETWEEN TAB STOPS unsigned char loadflg; // = $CA LIST PROTECTION unsigned char _internal_4[0xD4-0xCA-1]; // INTERNAL DATA unsigned int binint; // = $D4/$D5 USR-CALL RETURN VALUE }; #endif
sethcoder/cc65
testcode/lib/signal-test.c
<reponame>sethcoder/cc65 #include <stdio.h> #include <string.h> #include <errno.h> #include <signal.h> void __fastcall__ sighandler (int sig) { printf ("Got signal #%d\n", sig); } int main (void) { if (signal (SIGSEGV, sighandler) == SIG_ERR) { printf ("signal failure %d: %s\n", errno, strerror (errno)); return 1; } printf ("About to raise SIGSEGV...\n"); raise (SIGSEGV); printf ("Back from signal handler\n"); printf ("About to raise SIGILL...\n"); raise (SIGILL); printf ("Back from signal handler\n"); return 0; }
sethcoder/cc65
src/cc65/stmt.h
<gh_stars>1-10 /*****************************************************************************/ /* */ /* stmt.h */ /* */ /* Parse a statement */ /* */ /* */ /* */ /* (C) 1998-2008 <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef STMT_H #define STMT_H /*****************************************************************************/ /* Code */ /*****************************************************************************/ int Statement (int* PendingToken); /* Statement parser. Returns 1 if the statement does a return/break, returns ** 0 otherwise. If the PendingToken pointer is not NULL, the function will ** not skip the terminating token of the statement (closing brace or ** semicolon), but store true if there is a pending token, and false if there ** is none. The token is always checked, so there is no need for the caller to ** check this token, it must be skipped, however. If the argument pointer is ** NULL, the function will skip the token. */ /* End of stmt.h */ #endif
sethcoder/cc65
include/stdlib.h
/*****************************************************************************/ /* */ /* stdlib.h */ /* */ /* General utilities */ /* */ /* */ /* */ /* (C) 1998-2011, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ #ifndef _STDLIB_H #define _STDLIB_H /* size_t is needed */ #ifndef _HAVE_size_t typedef unsigned size_t; #define _HAVE_size_t #endif /* Standard exit codes */ #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 /* Return type of the div function */ typedef struct { int rem; int quot; } div_t; /* Return type of the ldiv function (which currently doesn't exist) */ typedef struct { long rem; long quot; } ldiv_t; /* Memory management */ void* __fastcall__ malloc (size_t size); void* __fastcall__ calloc (size_t count, size_t size); void* __fastcall__ realloc (void* block, size_t size); void __fastcall__ free (void* block); /* Non standard memory management functions */ #if __CC65_STD__ == __CC65_STD_CC65__ int __fastcall__ posix_memalign (void** memptr, size_t alignment, size_t size); /* Allocate a block of memory with the given "size", which is aligned to a ** memory address that is a multiple of "alignment". "alignment" MUST NOT be ** zero, and MUST be a power of two; otherwise, this function will return ** EINVAL. The function returns ENOMEM if not enough memory is available ** to satisfy the request. "memptr" must point to a variable; that variable ** will return the address of the allocated memory. Use free() to release that ** allocated block. */ #endif void __fastcall__ _heapadd (void* mem, size_t size); /* Add a block to the heap */ size_t __fastcall__ _heapblocksize (const void* block); /* Return the size of an allocated block */ size_t _heapmemavail (void); /* Return the total free heap space */ size_t _heapmaxavail (void); /* Return the size of the largest free block on the heap */ /* Random numbers */ #define RAND_MAX 0x7FFF int rand (void); void __fastcall__ srand (unsigned seed); void _randomize (void); /* Non-standard */ /* Other standard stuff */ void abort (void) __attribute__ ((noreturn)); int __fastcall__ abs (int val); long __fastcall__ labs (long val); int __fastcall__ atoi (const char* s); long __fastcall__ atol (const char* s); int __fastcall__ atexit (void (*exitfunc) (void)); void* __fastcall__ bsearch (const void* key, const void* base, size_t n, size_t size, int __fastcall__ (* cmp) (const void*, const void*)); div_t __fastcall__ div (int numer, int denom); void __fastcall__ exit (int ret) __attribute__ ((noreturn)); char* __fastcall__ getenv (const char* name); void __fastcall__ qsort (void* base, size_t count, size_t size, int __fastcall__ (* compare) (const void*, const void*)); long __fastcall__ strtol (const char* nptr, char** endptr, int base); unsigned long __fastcall__ strtoul (const char* nptr, char** endptr, int base); int __fastcall__ system (const char* s); /* Non-ANSI functions */ void __fastcall__ _swap (void* p, void* q, size_t size); #if __CC65_STD__ == __CC65_STD_CC65__ char* __fastcall__ itoa (int val, char* buf, int radix); char* __fastcall__ utoa (unsigned val, char* buf, int radix); char* __fastcall__ ltoa (long val, char* buf, int radix); char* __fastcall__ ultoa (unsigned long val, char* buf, int radix); int __fastcall__ putenv (char* s); #endif /* End of stdlib.h */ #endif
sethcoder/cc65
src/da65/scanner.c
/*****************************************************************************/ /* */ /* scanner.c */ /* */ /* Configuration file scanner for the da65 disassembler */ /* */ /* */ /* */ /* (C) 2000-2005 <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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 <stdarg.h> #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "chartype.h" #include "xsprintf.h" #include "xmalloc.h" #include "strbuf.h" /* ld65 */ #include "global.h" #include "error.h" #include "scanner.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Current token and attributes */ unsigned InfoTok; char InfoSVal [CFG_MAX_IDENT_LEN+1]; long InfoIVal; /* Error location */ unsigned InfoErrorLine; unsigned InfoErrorCol; /* Input sources for the configuration */ static const char* InfoFile = 0; /* Other input stuff */ static int C = ' '; static unsigned InputLine = 1; static unsigned InputCol = 0; static FILE* InputFile = 0; static char* InputSrcName = 0; /*****************************************************************************/ /* Error handling */ /*****************************************************************************/ void InfoWarning (const char* Format, ...) /* Print a warning message adding file name and line number of the config file */ { char Buf [512]; va_list ap; va_start (ap, Format); xvsprintf (Buf, sizeof (Buf), Format, ap); va_end (ap); fprintf (stderr, "%s(%u): Warning: %s\n", InputSrcName, InfoErrorLine, Buf); } void InfoError (const char* Format, ...) /* Print an error message adding file name and line number of the config file */ { char Buf [512]; va_list ap; va_start (ap, Format); xvsprintf (Buf, sizeof (Buf), Format, ap); va_end (ap); fprintf (stderr, "%s(%u): Error: %s\n", InputSrcName, InfoErrorLine, Buf); exit (EXIT_FAILURE); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void NextChar (void) /* Read the next character from the input file */ { /* Read from the file */ C = getc (InputFile); /* Count columns */ if (C != EOF) { ++InputCol; } /* Count lines */ if (C == '\n') { ++InputLine; InputCol = 0; } } static unsigned DigitVal (int C) /* Return the value for a numeric digit */ { if (IsDigit (C)) { return C - '0'; } else { return toupper (C) - 'A' + 10; } } static void SkipBlanks (int SingleLine) { while (C != EOF && (!SingleLine || C != '\n') && IsSpace (C)) { NextChar (); } } static long GetDecimalToken (void) { long Value = 0; while (C != EOF && IsDigit (C)) { Value = Value * 10 + DigitVal (C); NextChar (); } return Value; } static int GetEncodedChar (char* Buf, unsigned* IPtr, unsigned Size) { char Decoded = 0; int Count; if (C == EOF) { return -1; } else if (C != '\\') { Decoded = C; NextChar (); goto Store; } NextChar (); /* consume '\\' */ if (C == EOF) { return -1; } else if (IsODigit (C)) { Count = 3; do { Decoded = Decoded * 8 + DigitVal (C); NextChar (); --Count; } while (Count > 0 && C != EOF && IsODigit (C)); } else if (C == 'x') { NextChar (); /* consume 'x' */ Count = 2; while (Count > 0 && C != EOF && IsXDigit (C)) { Decoded = Decoded * 16 + DigitVal (C); NextChar (); --Count; } } else { switch (C) { case '"': case '\'': case '\\': Decoded = C; break; case 't': Decoded = '\t'; break; case 'r': Decoded = '\r'; break; case 'n': Decoded = '\n'; break; default: return -1; } NextChar (); } Store: if (*IPtr < Size - 1) { Buf [(*IPtr)++] = Decoded; } Buf [*IPtr] = 0; return 0; } static void LineMarkerOrComment () /* Handle a line beginning with '#'. Possible interpretations are: ** - #line <lineno> ["<filename>"] (C preprocessor input) ** - # <lineno> "<filename>" [<flag>]... (gcc preprocessor output) ** - #<comment> */ { unsigned long LineNo = 0; int LineDirective = 0; StrBuf SrcNameBuf = AUTO_STRBUF_INITIALIZER; /* Skip the first "# " */ NextChar (); SkipBlanks (1); /* Check "line" */ if (C == 'l') { char MaybeLine [6]; unsigned I; for (I = 0; I < sizeof MaybeLine - 1 && C != EOF && IsAlNum (C); ++I) { MaybeLine [I] = C; NextChar (); } MaybeLine [I] = 0; if (strcmp (MaybeLine, "line") != 0) { goto NotMarker; } LineDirective = 1; SkipBlanks (1); } /* Get line number */ if (C == EOF || !IsDigit (C)) { goto NotMarker; } LineNo = GetDecimalToken (); SkipBlanks (1); /* Get the source file name */ if (C != '\"') { /* The source file name is missing */ if (LineDirective && C == '\n') { /* got #line <lineno> */ NextChar (); InputLine = LineNo; goto Last; } else { goto NotMarker; } } NextChar (); while (C != EOF && C != '\n' && C != '\"') { char DecodeBuf [2]; unsigned I = 0; if (GetEncodedChar (DecodeBuf, &I, sizeof DecodeBuf) < 0) { goto BadMarker; } SB_AppendBuf (&SrcNameBuf, DecodeBuf, I); } if (C != '\"') { goto BadMarker; } NextChar (); /* Ignore until the end of line */ while (C != EOF && C != '\n') { NextChar (); } /* Accepted a line marker */ SB_Terminate (&SrcNameBuf); xfree (InputSrcName); InputSrcName = SB_GetBuf (&SrcNameBuf); SB_Init (&SrcNameBuf); InputLine = (unsigned)LineNo; NextChar (); goto Last; BadMarker: InfoWarning ("Bad line marker"); NotMarker: while (C != EOF && C != '\n') { NextChar (); } NextChar (); Last: SB_Done (&SrcNameBuf); } void InfoNextTok (void) /* Read the next token from the input stream */ { unsigned I; char DecodeBuf [2]; Again: /* Skip whitespace */ SkipBlanks (0); /* Remember the current position */ InfoErrorLine = InputLine; InfoErrorCol = InputCol; /* Identifier? */ if (C == '_' || IsAlpha (C)) { /* Read the identifier */ I = 0; while (C == '_' || IsAlNum (C)) { if (I < CFG_MAX_IDENT_LEN) { InfoSVal [I++] = C; } NextChar (); } InfoSVal [I] = '\0'; InfoTok = INFOTOK_IDENT; return; } /* Hex number? */ if (C == '$') { NextChar (); if (!IsXDigit (C)) { InfoError ("Hex digit expected"); } InfoIVal = 0; while (IsXDigit (C)) { InfoIVal = InfoIVal * 16 + DigitVal (C); NextChar (); } InfoTok = INFOTOK_INTCON; return; } /* Decimal number? */ if (IsDigit (C)) { InfoIVal = GetDecimalToken (); InfoTok = INFOTOK_INTCON; return; } /* Other characters */ switch (C) { case '{': NextChar (); InfoTok = INFOTOK_LCURLY; break; case '}': NextChar (); InfoTok = INFOTOK_RCURLY; break; case ';': NextChar (); InfoTok = INFOTOK_SEMI; break; case '.': NextChar (); InfoTok = INFOTOK_DOT; break; case ',': NextChar (); InfoTok = INFOTOK_COMMA; break; case '=': NextChar (); InfoTok = INFOTOK_EQ; break; case ':': NextChar (); InfoTok = INFOTOK_COLON; break; case '\"': NextChar (); I = 0; InfoSVal[0] = '\0'; while (C != EOF && C != '\"') { if (GetEncodedChar (InfoSVal, &I, sizeof InfoSVal) < 0) { if (C == EOF) { InfoError ("Unterminated string"); } else { InfoError ("Invalid escape char: %c", C); } } } if (C != '\"') { InfoError ("Unterminated string"); } NextChar (); InfoTok = INFOTOK_STRCON; break; case '\'': NextChar (); if (C == EOF || IsControl (C) || C == '\'') { InfoError ("Invalid character constant"); } if (GetEncodedChar (DecodeBuf, &I, sizeof DecodeBuf) < 0 || I != 1) { InfoError ("Invalid character constant"); } InfoIVal = DecodeBuf [0]; if (C != '\'') { InfoError ("Unterminated character constant"); } NextChar (); InfoTok = INFOTOK_CHARCON; break; case '#': /* # lineno "sourcefile" or # comment */ if (SyncLines && InputCol == 1) { LineMarkerOrComment (); } else { do { NextChar (); } while (C != EOF && C != '\n'); NextChar (); } if (C != EOF) { goto Again; } InfoTok = INFOTOK_EOF; break; case '/': /* C++ style comment */ NextChar (); if (C != '/') { InfoError ("Invalid token '/'"); } do { NextChar (); } while (C != '\n' && C != EOF); if (C != EOF) { goto Again; } InfoTok = INFOTOK_EOF; break; case EOF: InfoTok = INFOTOK_EOF; break; default: InfoError ("Invalid character '%c'", C); } } void InfoConsume (unsigned T, const char* Msg) /* Skip a token, print an error message if not found */ { if (InfoTok != T) { InfoError (Msg); } InfoNextTok (); } void InfoConsumeLCurly (void) /* Consume a left curly brace */ { InfoConsume (INFOTOK_LCURLY, "'{' expected"); } void InfoConsumeRCurly (void) /* Consume a right curly brace */ { InfoConsume (INFOTOK_RCURLY, "'}' expected"); } void InfoConsumeSemi (void) /* Consume a semicolon */ { InfoConsume (INFOTOK_SEMI, "';' expected"); } void InfoConsumeColon (void) /* Consume a colon */ { InfoConsume (INFOTOK_COLON, "':' expected"); } void InfoOptionalComma (void) /* Consume a comma if there is one */ { if (InfoTok == INFOTOK_COMMA) { InfoNextTok (); } } void InfoOptionalAssign (void) /* Consume an equal sign if there is one */ { if (InfoTok == INFOTOK_EQ) { InfoNextTok (); } } void InfoAssureInt (void) /* Make sure the next token is an integer */ { if (InfoTok != INFOTOK_INTCON) { InfoError ("Integer constant expected"); } } void InfoAssureStr (void) /* Make sure the next token is a string constant */ { if (InfoTok != INFOTOK_STRCON) { InfoError ("String constant expected"); } } void InfoAssureChar (void) /* Make sure the next token is a char constant */ { if (InfoTok != INFOTOK_STRCON) { InfoError ("Character constant expected"); } } void InfoAssureIdent (void) /* Make sure the next token is an identifier */ { if (InfoTok != INFOTOK_IDENT) { InfoError ("Identifier expected"); } } void InfoRangeCheck (long Lo, long Hi) /* Check the range of InfoIVal */ { if (InfoIVal < Lo || InfoIVal > Hi) { InfoError ("Range error"); } } void InfoSpecialToken (const IdentTok* Table, unsigned Size, const char* Name) /* Map an identifier to one of the special tokens in the table */ { unsigned I; /* We need an identifier */ if (InfoTok == INFOTOK_IDENT) { /* Make it upper case */ I = 0; while (InfoSVal [I]) { InfoSVal [I] = toupper (InfoSVal [I]); ++I; } /* Linear search */ for (I = 0; I < Size; ++I) { if (strcmp (InfoSVal, Table [I].Ident) == 0) { InfoTok = Table [I].Tok; return; } } } /* Not found or no identifier */ InfoError ("%s expected", Name); } void InfoBoolToken (void) /* Map an identifier or integer to a boolean token */ { static const IdentTok Booleans [] = { { "YES", INFOTOK_TRUE }, { "NO", INFOTOK_FALSE }, { "TRUE", INFOTOK_TRUE }, { "FALSE", INFOTOK_FALSE }, { "ON", INFOTOK_TRUE }, { "OFF", INFOTOK_FALSE }, }; /* If we have an identifier, map it to a boolean token */ if (InfoTok == INFOTOK_IDENT) { InfoSpecialToken (Booleans, ENTRY_COUNT (Booleans), "Boolean"); } else { /* We expected an integer here */ if (InfoTok != INFOTOK_INTCON) { InfoError ("Boolean value expected"); } InfoTok = (InfoIVal == 0)? INFOTOK_FALSE : INFOTOK_TRUE; } } void InfoSetName (const char* Name) /* Set a name for a config file */ { InfoFile = Name; xfree(InputSrcName); InputSrcName = xstrdup(Name); } int InfoAvail () /* Return true if we have an info file given */ { return (InfoFile != 0); } void InfoOpenInput (void) /* Open the input file */ { /* Open the file */ InputFile = fopen (InfoFile, "r"); if (InputFile == 0) { Error ("Cannot open '%s': %s", InfoFile, strerror (errno)); } /* Initialize variables */ C = ' '; InputLine = 1; InputCol = 0; /* Start the ball rolling ... */ InfoNextTok (); } void InfoCloseInput (void) /* Close the input file if we have one */ { /* Close the input file if we had one */ if (InputFile) { (void) fclose (InputFile); InputFile = 0; } }
sethcoder/cc65
util/cbm/cbmcvt.c
/* cbmcvt.c -- PetSCII <--> ISO-8859-1 Conversion Filter Tool */ /* 2010-09-06, <NAME> */ #include <stdio.h> #include <unistd.h> /* Translation table ISO-8859-1 -> PetSCII */ static const unsigned char CTPET[256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x14,0x09,0x0D,0x11,0x93,0x0A,0x0E,0x0F, 0x10,0x0B,0x12,0x13,0x08,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0x5B,0xBF,0x5D,0x5E,0xA4, 0xAD,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0xB3,0xDD,0xAB,0xB1,0xDF, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x0C,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0x5F,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0x7D,0xAC,0x60,0xAE,0xAF, 0xB0,0x7E,0xB2,0x7B,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0x5C, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0xDC,0x7C,0xDE,0x7F, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF }; static unsigned char CTISO[256]; int main (int argc, char *argv[]) { int C; size_t I = 0u; if (isatty(fileno(stdin))) { fputs("cbmcvt v2.1 -- Conversion Filter (stdin --> stdout)\n" " -p converts ISO-8859-1 to PetSCII\n" " else, converts in other direction.\n", stderr); return 0; } if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'p') { while ((C = fgetc (stdin)) != EOF) { fputc (CTPET[C], stdout); } } else { /* Create translation table PetSCII -> ISO-8859-1 */ for (; I < sizeof CTPET; ++I) { CTISO[CTPET[I]] = I; } while ((C = fgetc (stdin)) != EOF) { fputc (CTISO[C], stdout); } } return 0; }
sethcoder/cc65
src/cc65/assignment.c
<filename>src/cc65/assignment.c /*****************************************************************************/ /* */ /* assignment.c */ /* */ /* Parse assignments */ /* */ /* */ /* */ /* (C) 2002-2009, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ /* cc65 */ #include "asmcode.h" #include "assignment.h" #include "codegen.h" #include "datatype.h" #include "error.h" #include "expr.h" #include "loadexpr.h" #include "scanner.h" #include "stdnames.h" #include "typecmp.h" #include "typeconv.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Assignment (ExprDesc* Expr) /* Parse an assignment */ { ExprDesc Expr2; Type* ltype = Expr->Type; /* We must have an lvalue for an assignment */ if (ED_IsRVal (Expr)) { Error ("Invalid lvalue in assignment"); } /* Check for assignment to const */ if (IsQualConst (ltype)) { Error ("Assignment to const"); } /* Skip the '=' token */ NextToken (); /* cc65 does not have full support for handling structs by value. Since ** assigning structs is one of the more useful operations from this ** family, allow it here. */ if (IsClassStruct (ltype)) { /* Get the size of the left hand side. */ unsigned Size = SizeOf (ltype); /* If the size is that of a basic type (char, int, long), we will copy ** the struct using the primary register, otherwise we use memcpy. In ** the former case, push the address only if really needed. */ int UseReg = 1; Type* stype; switch (Size) { case SIZEOF_CHAR: stype = type_uchar; break; case SIZEOF_INT: stype = type_uint; break; case SIZEOF_LONG: stype = type_ulong; break; default: stype = ltype; UseReg = 0; break; } if (UseReg) { PushAddr (Expr); } else { ED_MakeRVal (Expr); LoadExpr (CF_NONE, Expr); g_push (CF_PTR | CF_UNSIGNED, 0); } /* Get the expression on the right of the '=' into the primary */ hie1 (&Expr2); /* Check for equality of the structs */ if (TypeCmp (ltype, Expr2.Type) < TC_STRICT_COMPATIBLE) { Error ("Incompatible types"); } /* Check if the right hand side is an lvalue */ if (ED_IsLVal (&Expr2)) { /* We have an lvalue. Do we copy using the primary? */ if (UseReg) { /* Just use the replacement type */ Expr2.Type = stype; /* Load the value into the primary */ LoadExpr (CF_FORCECHAR, &Expr2); /* Store it into the new location */ Store (Expr, stype); } else { /* We will use memcpy. Push the address of the rhs */ ED_MakeRVal (&Expr2); LoadExpr (CF_NONE, &Expr2); /* Push the address (or whatever is in ax in case of errors) */ g_push (CF_PTR | CF_UNSIGNED, 0); /* Load the size of the struct into the primary */ g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, CheckedSizeOf (ltype), 0); /* Call the memcpy function */ g_call (CF_FIXARGC, Func_memcpy, 4); } } else { /* We have an rvalue. This can only happen if a function returns ** a struct, since there is no other way to generate an expression ** that has a struct as an rvalue result. We allow only 1, 2, and 4 ** byte sized structs, and do direct assignment. */ if (UseReg) { /* Do the store */ Store (Expr, stype); } else { /* Print a diagnostic */ Error ("Structs of this size are not supported"); /* Adjust the stack so we won't run in an internal error later */ pop (CF_PTR); } } } else if (ED_IsBitField (Expr)) { CodeMark AndPos; CodeMark PushPos; unsigned Mask; unsigned Flags; /* If the bit-field fits within one byte, do the following operations ** with bytes. */ if (Expr->BitOffs / CHAR_BITS == (Expr->BitOffs + Expr->BitWidth - 1) / CHAR_BITS) { Expr->Type = type_uchar; } /* Determine code generator flags */ Flags = TypeOf (Expr->Type); /* Assignment to a bit field. Get the address on stack for the store. */ PushAddr (Expr); /* Load the value from the location */ Expr->Flags &= ~E_BITFIELD; LoadExpr (CF_NONE, Expr); /* Mask unwanted bits */ Mask = (0x0001U << Expr->BitWidth) - 1U; GetCodePos (&AndPos); g_and (Flags | CF_CONST, ~(Mask << Expr->BitOffs)); /* Push it on stack */ GetCodePos (&PushPos); g_push (Flags, 0); /* Read the expression on the right side of the '=' */ MarkedExprWithCheck (hie1, &Expr2); /* Do type conversion if necessary. Beware: Do not use char type ** here! */ TypeConversion (&Expr2, ltype); /* Special treatment if the value is constant. */ /* Beware: Expr2 may contain side effects, so there must not be ** code generated for Expr2. */ if (ED_IsConstAbsInt (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) { /* Get the value and apply the mask */ unsigned Val = (unsigned) (Expr2.IVal & Mask); /* Since we will do the OR with a constant, we can remove the push */ RemoveCode (&PushPos); /* If the value is equal to the mask now, all bits are one, and we ** can remove the mask operation from above. */ if (Val == Mask) { RemoveCode (&AndPos); } /* Generate the or operation */ g_or (Flags | CF_CONST, Val << Expr->BitOffs); } else { /* If necessary, load the value into the primary register */ LoadExpr (CF_NONE, &Expr2); /* Apply the mask */ g_and (Flags | CF_CONST, Mask); /* Shift it into the right position */ g_asl (Flags | CF_CONST, Expr->BitOffs); /* Or both values */ g_or (Flags, 0); } /* Generate a store instruction */ Store (Expr, 0); /* Restore the expression type */ Expr->Type = ltype; } else { /* Get the address on stack if needed */ PushAddr (Expr); /* Read the expression on the right side of the '=' */ hie1 (&Expr2); /* Do type conversion if necessary */ TypeConversion (&Expr2, ltype); /* If necessary, load the value into the primary register */ LoadExpr (CF_NONE, &Expr2); /* Generate a store instruction */ Store (Expr, 0); } /* Value is still in primary and not an lvalue */ ED_MakeRValExpr (Expr); }
sethcoder/cc65
libsrc/geos-common/common/abort.c
/* ** abort.c ** ** Maciej 'YTM/Elysium' Witkowiak 15.7.2001 */ #include <stdlib.h> #include <geos.h> void abort (void) { ExitTurbo(); DlgBoxOk(CBOLDON "ABNORMAL PROGRAM", "TERMINATION." CPLAINTEXT); exit(3); }
sethcoder/cc65
testcode/lib/strpbrk-test.c
<reponame>sethcoder/cc65 #include <stdio.h> #include <string.h> static const char fox[] = "The quick brown fox jumped over the lazy dogs."; void main (void) { printf ("Testing strpbrk():\n"); if (strpbrk (fox, "qwerty") != &fox[2]) { printf ("\nThe first 'e' wasn't found.\n"); } if (strpbrk (fox, "QWERTY") != &fox[0]) { printf ("The 'T' wasn't found.\n"); } if (strpbrk (fox, "asdfg") != &fox[16]) { printf ("The 'f' wasn't found.\n"); } if (strpbrk (fox, "nxv,zmb") != &fox[10]) { printf ("The 'b' wasn't found.\n"); } if (strpbrk (fox, "!@#$%^&*()-+=[];:',/?<>.") != &fox[45]) { printf ("The '.' wasn't found.\n"); } printf ("\nFinished.\n"); }
sethcoder/cc65
include/telestrat.h
/*****************************************************************************/ /* */ /* telestrat.h */ /* */ /* Oric Telestrat system-specific definitions */ /* */ /* */ /* */ /* (C) 2017 <NAME>, <<EMAIL>> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ /* Color defines */ #define COLOR_BLACK 0x00 #define COLOR_RED 0x01 #define COLOR_GREEN 0x02 #define COLOR_YELLOW 0x03 #define COLOR_BLUE 0x04 #define COLOR_MAGENTA 0x05 #define COLOR_CYAN 0x06 #define COLOR_WHITE 0x07 /* TGI color defines */ /* White and red are swapped, so that the pallete ** driver is compatible with black-and-white drivers. */ #define TGI_COLOR_BLACK COLOR_BLACK #define TGI_COLOR_WHITE 1 #define TGI_COLOR_GREEN COLOR_GREEN #define TGI_COLOR_YELLOW COLOR_YELLOW #define TGI_COLOR_BLUE COLOR_BLUE #define TGI_COLOR_MAGENTA COLOR_MAGENTA #define TGI_COLOR_CYAN COLOR_CYAN #define TGI_COLOR_RED 7 extern void telestrat_228_200_3_tgi[]; extern void telestrat_240_200_2_tgi[]; /* Referred to by tgi_static_stddrv[] */ /* Define hardware */ #include <_6522.h> #define VIA (*(struct __6522*)0x300) /* These are defined to be FUNCT + NumberKey */ #define CH_F1 0xB1 #define CH_F2 0xB2 #define CH_F3 0xB3 #define CH_F4 0xB4 #define CH_F5 0xB5 #define CH_F6 0xB6 #define CH_F7 0xB7 #define CH_F8 0xB8 #define CH_F9 0xB9 #define CH_F10 0xB0 /* Character codes */ #define CH_ULCORNER '+' #define CH_URCORNER '+' #define CH_LLCORNER '+' #define CH_LRCORNER '+' #define CH_TTEE '+' #define CH_BTEE '+' #define CH_LTEE '+' #define CH_RTEE '+' #define CH_CROSS '+' #define CH_CURS_UP 11 #define CH_CURS_DOWN 10 #define CH_CURS_LEFT 8 #define CH_CURS_RIGHT 9 #define CH_DEL 127 #define CH_ENTER 13 #define CH_STOP 3 #define CH_LIRA 95 #define CH_ESC 27 void oups(); void ping(); void zap(); void shoot(); void explode(); void kbdclick1();
sethcoder/cc65
src/cc65/litpool.c
<filename>src/cc65/litpool.c /*****************************************************************************/ /* */ /* litpool.c */ /* */ /* Literal string handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2013, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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 <stdio.h> #include <string.h> /* common */ #include "attrib.h" #include "check.h" #include "coll.h" #include "tgttrans.h" #include "xmalloc.h" /* cc65 */ #include "asmlabel.h" #include "codegen.h" #include "error.h" #include "global.h" #include "litpool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Definition of a literal */ struct Literal { unsigned Label; /* Asm label for this literal */ int RefCount; /* Reference count */ int Output; /* True if output has been generated */ StrBuf Data; /* Literal data */ }; /* Definition of the literal pool */ struct LiteralPool { struct SymEntry* Func; /* Function that owns the pool */ Collection WritableLiterals; /* Writable literals in the pool */ Collection ReadOnlyLiterals; /* Readonly literals in the pool */ }; /* The global and current literal pool */ static LiteralPool* GlobalPool = 0; static LiteralPool* LP = 0; /* Stack that contains the nested literal pools. Since TOS is in LiteralPool ** and functions aren't nested in C, the maximum depth is 1. I'm using a ** collection anyway, so the code is prepared for nested functions or ** whatever. */ static Collection LPStack = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* struct Literal */ /*****************************************************************************/ static Literal* NewLiteral (const void* Buf, unsigned Len) /* Create a new literal and return it */ { /* Allocate memory */ Literal* L = xmalloc (sizeof (*L)); /* Initialize the fields */ L->Label = GetLocalLabel (); L->RefCount = 0; L->Output = 0; SB_Init (&L->Data); SB_AppendBuf (&L->Data, Buf, Len); /* Return the new literal */ return L; } static void FreeLiteral (Literal* L) /* Free a literal */ { /* Free the literal data */ SB_Done (&L->Data); /* Free the structure itself */ xfree (L); } static void OutputLiteral (Literal* L) /* Output one literal to the currently active data segment */ { /* Translate the literal into the target charset */ TranslateLiteral (L); /* Define the label for the literal */ g_defdatalabel (L->Label); /* Output the literal data */ g_defbytes (SB_GetConstBuf (&L->Data), SB_GetLen (&L->Data)); /* Mark the literal as output */ L->Output = 1; } Literal* UseLiteral (Literal* L) /* Increase the reference counter for the literal and return it */ { /* Increase the reference count */ ++L->RefCount; /* If --local-strings was given, immediately output the literal */ if (IS_Get (&LocalStrings)) { /* Switch to the proper data segment */ if (IS_Get (&WritableStrings)) { g_usedata (); } else { g_userodata (); } /* Output the literal */ OutputLiteral (L); } /* Return the literal */ return L; } void ReleaseLiteral (Literal* L) /* Decrement the reference counter for the literal */ { --L->RefCount; CHECK (L->RefCount >= 0); } void TranslateLiteral (Literal* L) /* Translate a literal into the target charset. */ { TgtTranslateBuf (SB_GetBuf (&L->Data), SB_GetLen (&L->Data)); } unsigned GetLiteralLabel (const Literal* L) /* Return the asm label for a literal */ { return L->Label; } const char* GetLiteralStr (const Literal* L) /* Return the data for a literal as pointer to char */ { return SB_GetConstBuf (&L->Data); } const StrBuf* GetLiteralStrBuf (const Literal* L) /* Return the data for a literal as pointer to the string buffer */ { return &L->Data; } unsigned GetLiteralSize (const Literal* L) /* Get the size of a literal string */ { return SB_GetLen (&L->Data); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static LiteralPool* NewLiteralPool (struct SymEntry* Func) /* Create a new literal pool and return it */ { /* Allocate memory */ LiteralPool* LP = xmalloc (sizeof (*LP)); /* Initialize the fields */ LP->Func = Func; InitCollection (&LP->WritableLiterals); InitCollection (&LP->ReadOnlyLiterals); /* Return the new pool */ return LP; } static void FreeLiteralPool (LiteralPool* LP) /* Free a LiteralPool structure */ { /* Free the collections contained within the struct */ DoneCollection (&LP->WritableLiterals); DoneCollection (&LP->ReadOnlyLiterals); /* Free the struct itself */ xfree (LP); } static int Compare (void* Data attribute ((unused)), const void* Left, const void* Right) /* Compare function used when sorting the literal pool */ { /* Larger strings are considered "smaller" */ return (int) GetLiteralSize (Right) - (int) GetLiteralSize (Left); } void InitLiteralPool (void) /* Initialize the literal pool */ { /* Create the global literal pool */ GlobalPool = LP = NewLiteralPool (0); } void PushLiteralPool (struct SymEntry* Func) /* Push the current literal pool onto the stack and create a new one */ { /* We must have a literal pool to push! */ PRECONDITION (LP != 0); /* Push the old pool */ CollAppend (&LPStack, LP); /* Create a new one */ LP = NewLiteralPool (Func); } LiteralPool* PopLiteralPool (void) /* Pop the last literal pool from TOS and activate it. Return the old ** literal pool. */ { /* Remember the current literal pool */ LiteralPool* Old = LP; /* Pop one from stack */ LP = CollPop (&LPStack); /* Return the old one */ return Old; } static void MoveLiterals (Collection* Source, Collection* Target) /* Move referenced literals from Source to Target, delete unreferenced ones */ { unsigned I; /* Move referenced literals, remove unreferenced ones */ for (I = 0; I < CollCount (Source); ++I) { /* Get the literal */ Literal* L = CollAt (Source, I); /* If it is referenced and not output, add it to the Target pool, ** otherwise free it */ if (L->RefCount && !L->Output) { CollAppend (Target, L); } else { FreeLiteral (L); } } } void MoveLiteralPool (LiteralPool* LocalPool) /* Move all referenced literals in LocalPool to the global literal pool. This ** function will free LocalPool after moving the used string literals. */ { /* Move the literals */ MoveLiterals (&LocalPool->WritableLiterals, &GlobalPool->WritableLiterals); MoveLiterals (&LocalPool->ReadOnlyLiterals, &GlobalPool->ReadOnlyLiterals); /* Free the local literal pool */ FreeLiteralPool (LocalPool); } static void OutputWritableLiterals (Collection* Literals) /* Output the given writable literals */ { unsigned I; /* If nothing there, exit... */ if (CollCount (Literals) == 0) { return; } /* Switch to the correct segment */ g_usedata (); /* Emit all literals that have a reference */ for (I = 0; I < CollCount (Literals); ++I) { /* Get a pointer to the literal */ Literal* L = CollAtUnchecked (Literals, I); /* Output this one, if it has references and wasn't already output */ if (L->RefCount > 0 && !L->Output) { OutputLiteral (L); } } } static void OutputReadOnlyLiterals (Collection* Literals) /* Output the given readonly literals merging (even partial) duplicates */ { unsigned I; /* If nothing there, exit... */ if (CollCount (Literals) == 0) { return; } /* Switch to the correct segment */ g_userodata (); /* Sort the literal pool by literal size. Larger strings go first */ CollSort (Literals, Compare, 0); /* Emit all literals that have a reference */ for (I = 0; I < CollCount (Literals); ++I) { unsigned J; Literal* C; /* Get the next literal */ Literal* L = CollAt (Literals, I); /* Ignore it, if it doesn't have references or was already output */ if (L->RefCount == 0 || L->Output) { continue; } /* Translate the literal into the target charset */ TranslateLiteral (L); /* Check if this literal is part of another one. Since the literals ** are sorted by size (larger ones first), it can only be part of a ** literal with a smaller index. ** Beware: Only check literals that have actually been referenced. */ C = 0; for (J = 0; J < I; ++J) { const void* D; /* Get a pointer to the compare literal */ Literal* L2 = CollAt (Literals, J); /* Ignore literals that have no reference */ if (L2->RefCount == 0) { continue; } /* Get a pointer to the data */ D = SB_GetConstBuf (&L2->Data) + SB_GetLen (&L2->Data) - SB_GetLen (&L->Data); /* Compare the data */ if (memcmp (D, SB_GetConstBuf (&L->Data), SB_GetLen (&L->Data)) == 0) { /* Remember the literal and terminate the loop */ C = L2; break; } } /* Check if we found a match */ if (C != 0) { /* This literal is part of a longer literal, merge them */ g_aliasdatalabel (L->Label, C->Label, GetLiteralSize (C) - GetLiteralSize (L)); } else { /* Define the label for the literal */ g_defdatalabel (L->Label); /* Output the literal data */ g_defbytes (SB_GetConstBuf (&L->Data), SB_GetLen (&L->Data)); } /* Mark the literal */ L->Output = 1; } } void OutputLiteralPool (void) /* Output the global literal pool */ { /* Output both sorts of literals */ OutputWritableLiterals (&GlobalPool->WritableLiterals); OutputReadOnlyLiterals (&GlobalPool->ReadOnlyLiterals); } Literal* AddLiteral (const char* S) /* Add a literal string to the literal pool. Return the literal. */ { return AddLiteralBuf (S, strlen (S) + 1); } Literal* AddLiteralBuf (const void* Buf, unsigned Len) /* Add a buffer containing a literal string to the literal pool. Return the ** literal. */ { /* Create a new literal */ Literal* L = NewLiteral (Buf, Len); /* Add the literal to the correct pool */ if (IS_Get (&WritableStrings)) { CollAppend (&LP->WritableLiterals, L); } else { CollAppend (&LP->ReadOnlyLiterals, L); } /* Return the new literal */ return L; } Literal* AddLiteralStr (const StrBuf* S) /* Add a literal string to the literal pool. Return the literal. */ { return AddLiteralBuf (SB_GetConstBuf (S), SB_GetLen (S)); }
sethcoder/cc65
test/bdiff.c
<filename>test/bdiff.c // minimal tool to compare two binaries #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { FILE *f1, *f2; if (argc < 3) { return EXIT_FAILURE; } f1 = fopen(argv[1], "rb"); f2 = fopen(argv[2], "rb"); if ((f1 == NULL) || (f2 == NULL)) { return EXIT_FAILURE; } for(;;) { if (feof(f1) && feof(f2)) { return EXIT_SUCCESS; } else if (feof(f1) || feof(f2)) { return EXIT_FAILURE; } if (fgetc(f1) != fgetc(f2)) { return EXIT_FAILURE; } } }
sethcoder/cc65
src/cc65/coptpush.c
/*****************************************************************************/ /* */ /* coptpush.c */ /* */ /* Optimize push sequences */ /* */ /* */ /* */ /* (C) 2001-2012, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed 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. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptpush.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptPush1 (CodeSeg* S) /* Given a sequence ** ** jsr ldaxysp ** jsr pushax ** ** If a/x are not used later, and Y is known, replace that by ** ** ldy #xx+2 ** jsr pushwysp ** ** saving 3 bytes and several cycles. */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxysp") && RegValIsKnown (L[0]->RI->In.RegY) && L[0]->RI->In.RegY < 0xFE && (L[1] = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "pushax") && !RegAXUsed (S, I+2)) { /* Insert new code behind the pushax */ const char* Arg; CodeEntry* X; /* ldy #xx+1 */ Arg = MakeHexArg (L[0]->RI->In.RegY+2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+2); /* jsr pushwysp */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "pushwysp", 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPush2 (CodeSeg* S) /* A sequence ** ** jsr ldaxidx ** jsr pushax ** ** may get replaced by ** ** jsr pushwidx */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxidx") && (L[1] = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "pushax")) { /* Insert new code behind the pushax */ CodeEntry* X; /* jsr pushwidx */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "pushwidx", 0, L[1]->LI); CS_InsertEntry (S, X, I+2); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
547/SWExtensions
Sources/SWExtensions.h
<filename>Sources/SWExtensions.h // // SWExtensions.h // SWExtensions // // Created by <NAME> on 2019/6/18. // Copyright © 2019 Seven. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for SWExtensions. FOUNDATION_EXPORT double SWExtensionsVersionNumber; //! Project version string for SWExtensions. FOUNDATION_EXPORT const unsigned char SWExtensionsVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SWExtensions/PublicHeader.h>
cenzuen/swiftAddressBook
swiftTest-10 AddressBook/ocModel/ocBaseModel.h
// // ocBaseModel.h // swiftTest-10 AddressBook // // Created by joey0824 on 2017/6/6. // Copyright © 2017年 JC. All rights reserved. // #import <Foundation/Foundation.h> @class LKDBHelper; @interface ocBaseModel : NSObject + (LKDBHelper *)getUsingLKDBHelper; @end
cenzuen/swiftAddressBook
Pods/Target Support Files/Pods-swiftTest-10 AddressBook/Pods-swiftTest-10 AddressBook-umbrella.h
<reponame>cenzuen/swiftAddressBook #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_swiftTest_10_AddressBookVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_swiftTest_10_AddressBookVersionString[];
cenzuen/swiftAddressBook
swiftTest-10 AddressBook/addressBook-Bridging-Header.h
// // addressBook-Bridging-Header.h // swiftTest-10 AddressBook // // Created by joey0824 on 2017/6/7. // Copyright © 2017年 JC. All rights reserved. // #ifndef addressBook_Bridging_Header_h #define addressBook_Bridging_Header_h #import "ocBaseModel.h" #endif
JianyiCheng/Lily58
mydesigns/mykeymap/keymap.c
/* Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) 2020 <NAME> * * You are free to: * * Share — copy and redistribute the material in any medium or format * Adapt — remix, transform, and build upon the material * for any purpose, even commercially. * * The licensor cannot revoke these freedoms as long as you follow the license terms. */ #include QMK_KEYBOARD_H extern uint8_t is_master; enum layers { _QWERTY, _LOWER, _RAISE, _ADJUST, }; enum custom_keycodes { QWERTY = SAFE_RANGE, LOWER, RAISE, ADJUST, }; const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { // [_QWERTY] = LAYOUT( // KC_GRV, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_BSPC, // KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, // KC_ESC, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, // KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_NO, KC_MUTE, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_SFTENT, // KC_LALT, KC_LGUI, MO(1), KC_SPC, KC_SPC, MO(2), KC_NUBS, KC_LCTL // ), // [_LOWER] = LAYOUT( // KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_DEL, // KC_TRNS, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_PGUP, KC_MINS, KC_EQL, KC_RBRC, // KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_NO, KC_HOME, KC_PGDN, KC_END, KC_NO, KC_NUHS, // KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_RO, KC_ENT, // KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS // ), // [_RAISE] = LAYOUT( // KC_TRNS, RALT(KC_1), RALT(KC_2), RALT(KC_3), RALT(KC_4), RALT(KC_5), RALT(KC_6), RALT(KC_7), RALT(KC_8), RALT(KC_9), RALT(KC_0), KC_DEL, // KC_TRNS, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_UP, KC_MINS, KC_EQL, KC_RBRC, // KC_ESC, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_LEFT, KC_DOWN, KC_RGHT, KC_NO, KC_NUHS, // KC_LSFT, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_NO, KC_VOLD, KC_VOLU, KC_MUTE, KC_RO, KC_SFTENT, // KC_RALT, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, RALT(KC_NUBS), KC_TRNS // ), // [_ADJUST] = LAYOUT( // XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, // XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, // XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, RGB_TOG, RGB_HUI, RGB_SAI, RGB_VAI, // XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, RGB_MOD, RGB_HUD, RGB_SAD, RGB_VAD, // _______, _______, _______, _______, _______, _______, _______, _______ // ) /* QWERTY * ,-----------------------------------------. ,-----------------------------------------. * | ESC | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 0 | ` | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | Tab | Q | W | E | R | T | | Y | U | I | O | P | BS | * |------+------+------+------+------+------| |------+------+------+------+------+------| * |LCTRL | A | S | D | F | G |-------. ,-------| H | J | K | L | ; | ' | * |------+------+------+------+------+------| MUTE | | [ |------+------+------+------+------+------| * |LShift| Z | X | C | V | B |-------| |-------| N | M | , | . | / | LOWER| * `-----------------------------------------/ / \ \-----------------------------------------' * | LOWER| Alt | WIN | /Space / \Enter \ | - | = | \ | * | | | |/ / \ \ | | | | * `----------------------------' '------''--------------------' */ // left fn could be the raise layer - todo [_QWERTY] = LAYOUT( KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_GRV, KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_BSPC, KC_LCTRL, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_KB_MUTE, KC_LBRC, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, MO(_LOWER), MO(_LOWER), KC_LALT, KC_LCMD, KC_SPC, KC_ENT, KC_MINS, KC_EQL, KC_BSLS ), /* LOWER * ,-----------------------------------------. ,-----------------------------------------. * | F1 | F2 | F3 | F4 | F5 | F6 | | F7 | F8 | F9 | F10 | F11 | F12 | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | cap | MOFT | MODN | MOUP | MORT | BT1 | | |prtscr|scrloc| pause| up | DEL | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | |VOLUP |VOLDN | MUTE |EJECT | |-------. ,-------| * | / | home | pgup | left | right| * |------+------+------+------+------+------| | | ] |------+------+------+------+------+------| * | |pretab|nxttab| swwin|swwin | |-------| |-------| + | _ | end | pgdn | down | | * `-----------------------------------------/ / \ \-----------------------------------------' * | | | | / / \ \ | |insert| stop | * | | | |/ / \ \ | | | | * `----------------------------' '------''--------------------' */ [_LOWER] = LAYOUT( KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, KC_CAPS, KC_MS_L, KC_MS_D, KC_MS_U, KC_MS_R, KC_BTN1, _______, KC_PSCR, KC_SCRL, KC_PAUS, KC_UP, KC_DEL, KC_RCTRL,KC_VOLD, KC_VOLU, KC_MUTE, KC_EJCT, KC_BTN2, KC_PAST, KC_PSLS, KC_HOME, KC_PGUP, KC_LEFT, KC_RGHT, KC_RSFT, S(C(KC_TAB)), C(KC_TAB), A(KC_TAB), G(KC_TAB), _______, _______, KC_RBRC, KC_PPLS, KC_PMNS, KC_END, KC_PGDN, KC_DOWN, _______, _______, _______, _______, _______, _______, _______, KC_INS, KC_STOP ), /* RAISE * ,-----------------------------------------. ,-----------------------------------------. * | | | | | | | | | | | | | | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | ` | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 0 | | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | F1 | F2 | F3 | F4 | F5 | F6 |-------. ,-------| | Left | Down | Up |Right | | * |------+------+------+------+------+------| [ | | ] |------+------+------+------+------+------| * | F7 | F8 | F9 | F10 | F11 | F12 |-------| |-------| + | - | = | [ | ] | \ | * `-----------------------------------------/ / \ \-----------------------------------------' * | LAlt | LGUI |LOWER | /Space / \Enter \ |RAISE |BackSP| RGUI | * | | | |/ / \ \ | | | | * `----------------------------' '------''--------------------' */ [_RAISE] = LAYOUT( XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, _______, _______, _______, _______, _______, _______, _______, _______ ), /* ADJUST * ,-----------------------------------------. ,-----------------------------------------. * | | | | | | | | | | | | | | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | | | | | | | | | | | | | | * |------+------+------+------+------+------| |------+------+------+------+------+------| * | | | | | | |-------. ,-------| | |RGB ON| HUE+ | SAT+ | VAL+ | * |------+------+------+------+------+------| | | |------+------+------+------+------+------| * | | | | | | |-------| |-------| | | MODE | HUE- | SAT- | VAL- | * `-----------------------------------------/ / \ \-----------------------------------------' * | LAlt | LGUI |LOWER | /Space / \Enter \ |RAISE |BackSP| RGUI | * | | | |/ / \ \ | | | | * `----------------------------' '------''--------------------' */ [_ADJUST] = LAYOUT( XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, XXXXXXX, _______, _______, _______, _______, _______, _______, _______, _______ ) }; int RGB_current_mode; void matrix_init_user(void) { #ifdef RGBLIGHT_ENABLE RGB_current_mode = rgblight_config.mode; #endif } //SSD1306 OLED update loop, make sure to enable OLED_ENABLE=yes in rules.mk #ifdef OLED_ENABLE oled_rotation_t oled_init_user(oled_rotation_t rotation) { if (!is_keyboard_master()) return OLED_ROTATION_180; // flips the display 180 degrees if offhand return rotation; } // When you add source files to SRC in rules.mk, you can use functions. const char *read_layer_state(void); const char *read_logo(void); void set_keylog(uint16_t keycode, keyrecord_t *record); //const char *read_keylog(void); //const char *read_keylogs(void); // const char *read_mode_icon(bool swap); // const char *read_host_led_state(void); // void set_timelog(void); // const char *read_timelog(void); bool oled_task_user(void) { if (is_keyboard_master()) { // If you want to change the display of OLED, you need to change here oled_write_ln(read_layer_state(), false); //oled_write_ln(read_keylog(), false); //oled_write_ln(read_keylogs(), false); //oled_write_ln(read_mode_icon(keymap_config.swap_lalt_lgui), false); //oled_write_ln(read_host_led_state(), false); //oled_write_ln(read_timelog(), false); } else { oled_write(read_logo(), false); } return false; } #endif // OLED_ENABLE bool process_record_user(uint16_t keycode, keyrecord_t *record) { if (record->event.pressed) { #ifdef OLED_ENABLE set_keylog(keycode, record); #endif // set_timelog(); } // switch (keycode) { // case QWERTY: // if (record->event.pressed) { // set_single_persistent_default_layer(_QWERTY); // } // return false; // break; // case LOWER: // if (record->event.pressed) { // layer_on(_LOWER); // } else { // layer_off(_LOWER); // } // update_tri_layer(_LOWER, _RAISE, _ADJUST); // return false; // break; // case RAISE: // if (record->event.pressed) { // layer_on(_RAISE); // } else { // layer_off(_RAISE); // } // update_tri_layer(_LOWER, _RAISE, _ADJUST); // return false; // break; // case ADJUST: // if (record->event.pressed) { // layer_on(_ADJUST); // } else { // layer_off(_ADJUST); // } // return false; // break; // } return true; } #ifdef ENCODER_ENABLE bool encoder_update_user(uint8_t index, bool clockwise) { // // index 1 == minion side // if (index == 1) { // if (clockwise) { // tap_code(KC_VOLD); // } else { // tap_code(KC_VOLU); // } // } uint8_t temp_mod = get_mods(); uint8_t temp_osm = get_oneshot_mods(); bool is_lower = (temp_mod | temp_osm) & MOD_BIT(MO(_LOWER)); bool is_shift = (temp_mod | temp_osm) & MOD_MASK_SHIFT; if (index == 0) { if (is_lower) { if (is_shift) { if (clockwise) { tap_code(KC_MS_D); } else { tap_code(KC_MS_U); } } else { if (clockwise) { tap_code(KC_MS_R); } else { tap_code(KC_MS_L); } } } else { if (clockwise) { tap_code(KC_WH_D); } else { tap_code(KC_WH_U); } } } return true; } #endif
JianyiCheng/Lily58
mydesigns/mykeymap/config.h
<gh_stars>0 /* Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) 2020 <NAME> * * You are free to: * * Share — copy and redistribute the material in any medium or format * Adapt — remix, transform, and build upon the material * for any purpose, even commercially. * * The licensor cannot revoke these freedoms as long as you follow the license terms. */ #pragma once //#define USE_MATRIX_I2C /* Select hand configuration */ #define MASTER_LEFT // #define MASTER_RIGHT // #define EE_HANDS #define USE_SERIAL_PD2 #define ENCODERS_PAD_A { F4 } #define ENCODERS_PAD_B { F5 } #define ENCODER_RESOLUTION 4 #define TAPPING_FORCE_HOLD #define TAPPING_TERM 180 #undef RGBLED_NUM #define RGBLIGHT_ANIMATIONS #define RGBLED_NUM 27 #define RGBLIGHT_LIMIT_VAL 120 #define RGBLIGHT_HUE_STEP 10 #define RGBLIGHT_SAT_STEP 17 #define RGBLIGHT_VAL_STEP 17 // Underglow /* #undef RGBLED_NUM #define RGBLED_NUM 14 // Number of LEDs #define RGBLIGHT_ANIMATIONS #define RGBLIGHT_SLEEP */
mpberk/cse531-projects
project03/sem_test.c
<filename>project03/sem_test.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "sem.h" #include "threads.h" #include "q.h" int id (q_element *item) { return *((int*)(item->payload)); } // ID counter for unique items being added to the queue int counter = 0; // Global Queue of ints q_element *Queue; // Semaphore for items in queue Semaphore_t *sem; // Number of consumers and producers int count_cons = 3; int count_prod = 1; // Easily modifiable function for sleep void go_to_sleep() { sleep(1); } // Consumer function to consume items from queue void consumer (void *arg) { int value = *(int*) arg; printf("Consumer C%02d created\n",value); while (1) { P(sem); q_element *item = DelQueue(&Queue); printf("C%02d: Consuming item %03d\n", value, id(item)); // Free item free(item->payload); FreeItem(item); go_to_sleep(); }; }; // Producer function to add items to queue void producer (void *arg) { int value = *(int*) arg; printf("Producer P%02d created\n",value); while (1) { printf("P%02d: Producing item %03d\n", value, counter); int *item_value = malloc(sizeof(int)); q_element *item = NewItem(); *item_value = counter; counter++; item->payload = (void*) item_value; AddQueue(&Queue, item); V(sem); go_to_sleep(); }; }; int main (int argc, char *argv[]) { int i; // for loop variable // Get consumer count if (argc >= 2) { count_cons = atoi(argv[1]); } // Get producer count if (argc >= 3) { count_prod = atoi(argv[2]); } // Set array for indices int *indices_cons; int *indices_prod; indices_cons = (int*) malloc(count_cons * sizeof(int)); indices_prod = (int*) malloc(count_prod * sizeof(int)); for (i = 0; i < count_cons; i++) { *(indices_cons+i) = i; }; for (i = 0; i < count_prod; i++) { *(indices_prod+i) = i; }; // Setup semaphore sem = CreateSem(0); // Setup Queue Queue = NewQueue(); // Setup Consumers first for (i = 0; i < count_cons; i++) { start_thread(consumer, (void*) (indices_cons+i)); } // Setup Producers next for (i = 0; i < count_prod; i++) { start_thread(producer, (void*) (indices_prod+i)); } run(); };
mpberk/cse531-projects
project01/part1/read_write_m.c
// (c) <NAME> 2009 // permission to use and distribute granted. #include <stdio.h> #include <string.h> #include <stdlib.h> #include "monitor.h" monitor_t read_write; monitor_cond_t r_cond, w_cond; int rwc = 0, wwc = 0, rc = 0, wc = 0, global_ID=0; void reader_entry(int ID) { printf("[reader: #%d]\ttrying to read\n", ID); monitor_entry(&read_write); if (wwc > 0 || wc > 0) { printf("[reader: #%d]\tblocking for writer\n", ID); rwc++; // increment waiting reader count. monitor_wait(&read_write, &r_cond); rwc--; } rc++; monitor_signal(&read_write, &r_cond); monitor_exit(&read_write); } void reader_exit(int ID) { monitor_entry(&read_write); rc--; // i'm no longer a reader if (rc==0) monitor_signal(&read_write, &w_cond); monitor_exit(&read_write); } void writer_entry(int ID) { printf("\t\t\t\t[writer: #%d]\ttrying to write\n", ID); monitor_entry(&read_write); if (rc > 0 || wc > 0) { printf("\t\t\t\t[writer: #%d] blocking for others\n"); wwc++; // increment waiting writers monitor_wait(&read_write, &w_cond); wwc--; // i'm no longer waiting } wc++; // increment writers monitor_exit(&read_write); } void writer_exit(int ID) { monitor_entry(&read_write); wc--; if (rwc > 0) // first, i let all the readers go. monitor_signal(&read_write, &r_cond); else monitor_signal(&read_write, &w_cond); monitor_exit(&read_write); } void reader(void) { int ID; monitor_entry(&read_write); ID = global_ID++; monitor_exit(&read_write); while(1){ reader_entry(ID); printf ("[reader #%d]\t****READING****\n", ID); sleep(1); reader_exit(ID); }; } void writer(void) { int ID; monitor_entry(&read_write); ID = global_ID++; monitor_exit(&read_write); while(1){ writer_entry(ID); printf ("\t\t\t\t[writer: #%d]\t&&&WRITING!&&&\n", ID); sleep(1); writer_exit(ID); }; } //------------------------------------------------------- int main() { init_monitor(&read_write); init_monitor_cond(&r_cond); init_monitor_cond(&w_cond); start_thread(reader, NULL); start_thread(reader, NULL); start_thread(reader, NULL); start_thread(reader, NULL); start_thread(writer, NULL); start_thread(writer, NULL); start_thread(writer, NULL); while (1) sleep(1); }
mpberk/cse531-projects
project01/part1/lock_test.c
<reponame>mpberk/cse531-projects<filename>project01/part1/lock_test.c // (c) <NAME> 2009 // permission to use and distribute granted. #include <stdio.h> #include <stdlib.h> #include "threads.h" typedef pthread_mutex_t lock_t; lock_t L1; void init_lock(lock_t *l) { pthread_mutex_init(l, NULL); } void lock(lock_t *l) { pthread_mutex_lock (l); } void unlock (lock_t *l) { pthread_mutex_unlock (l); pthread_yield(); } void function_1(void) { while (1){ lock(&L1); printf("Beginning of CS: func 1\n"); sleep(1); printf("End of CCS: func 1..\n"); sleep(1); unlock(&L1); } } void function_2(void) { while (1){ lock(&L1); printf("Beginning of CS: func 2\n"); sleep(1); printf("End of CCS: func 2..\n"); sleep(1); unlock(&L1); } } void function_3(void) { while (1){ lock(&L1); printf("Beginning of CS: func 3\n"); sleep(1); printf("End of CCS: func 3..\n"); sleep(1); unlock(&L1); } } int main() { init_lock(&L1); start_thread(function_1, NULL); start_thread(function_2, NULL); start_thread(function_3, NULL); while(1) sleep(1); return 0; }
mpberk/cse531-projects
project03/hongquy_Code/sem.h
<reponame>mpberk/cse531-projects<gh_stars>0 #ifndef SEM_H #define SEM_H #include "threads.h" typedef struct Semaphore_t{ int counter; TCB_t** Queue; } Semaphore_t; Semaphore_t* CreateSem(int InputValue){ Semaphore_t* newSem = (Semaphore_t*) malloc(sizeof(Semaphore_t)); newSem->counter = InputValue; newSem->Queue = newQueue(); return newSem; } void P(Semaphore_t* sem){ sem->counter--; if(sem->counter < 0){ TCB_t* storeThread = DelQueue(ReadyQ); AddQueue(sem->Queue, storeThread); swapcontext(&(storeThread->context), &((*ReadyQ)->context)); // swapcontext(&((*ReadyQ)->context), &(storeThread->context)); } } void V(Semaphore_t* sem){ sem->counter++; if(sem->counter < 0){ TCB_t* runThread = DelQueue(sem->Queue); AddQueue(ReadyQ, runThread); } yield(); } #endif
mpberk/cse531-projects
project01/part1/monitor.h
// (c) <NAME> 2009 // permission to use and distribute granted. #include "threads.h" typedef pthread_mutex_t monitor_t; typedef pthread_cond_t monitor_cond_t; void init_monitor(monitor_t *M) { pthread_mutex_init(M, NULL);} void init_monitor_cond(monitor_cond_t *monitor_cond) { pthread_cond_init(monitor_cond, NULL);} void monitor_entry(monitor_t *M) { pthread_mutex_lock (M); } void monitor_exit(monitor_t *M) { pthread_mutex_unlock (M); pthread_yield();} void monitor_wait(monitor_t *M, monitor_cond_t *monitor_cond) { pthread_cond_wait(monitor_cond, M); pthread_yield(); } void monitor_signal(monitor_t *M, monitor_cond_t *monitor_cond) { pthread_cond_signal(monitor_cond); pthread_yield(); }
mpberk/cse531-projects
project04/Hongquy_Code/msgs.h
<filename>project04/Hongquy_Code/msgs.h #include "sem.h" typedef struct message message; typedef struct port port; typedef struct set set; //message contains array of nums, and has next and prev struct message{ int nums[10]; message* next; message* prev; }; //port contains a queue of messages, a count to keep track of how many messages //a semaphore to block sending, and another semaphore to block recieving // and a mutex struct port{ message** messages; int count; Semaphore_t* sendS; Semaphore_t* recieveS; int mutex; }; struct set{ port arrayP[100]; }; //function to initialize ports port* initPort(){ port* newP = (port*) malloc(sizeof(port)); newP->messages = (message**) malloc(sizeof(message*)); newP->count = 0; newP->mutex = 1; newP->sendS = CreateSem(1); newP->recieveS = CreateSem(1); return newP; } //This function when called will send the msg to the port specified void send(port* Pt, message* msg){ //check if mutex is available if(Pt->mutex == 1){ Pt->mutex--; //if the buffer is full, then block if((Pt->count) >= 10){ //since send will be blocked, give the mutex back Pt->mutex = Pt->mutex + 1; //block P(Pt->sendS); } //Cases to send message to the port and add it to the port's queue if( (Pt->messages) == NULL){ printf("error, queue not made\n"); exit(1); } else if( (*(Pt->messages)) == NULL ){ *(Pt->messages) = msg; Pt->count++; } else if( (*(Pt->messages))->next == NULL){ (*(Pt->messages))->next = msg; (*(Pt->messages))->prev = msg; msg->prev = *(Pt->messages); msg->next = *(Pt->messages); Pt->count++; } else if((*(Pt->messages))->next != NULL){ message* tail = (*(Pt->messages))->prev; tail->next = msg; tail->next->next = *(Pt->messages); tail->next->prev = tail; (*(Pt->messages))->prev = tail->next; Pt->count++; } //give back mutex after sending the message Pt->mutex = Pt->mutex + 1; //unblock any reciving proccesses V(Pt->recieveS); } } //function to cause a server to recieve a message from a port void recieve(port* Pt, message** msgR){ //checks if the mutex is availiable if(Pt->mutex == 1){ Pt->mutex--; //if the buffer is empty, block the recieving process if(Pt->count <= 0){ //Give back the mutex since this process will be blocked Pt->mutex++; //block P(Pt->recieveS); } //Cases to acquire the message from the port's queue if(*(Pt->messages) == NULL){ printf("error, port empty\n"); exit(1); } else if((*(Pt->messages))->next == NULL){ *msgR = *(Pt->messages); *(Pt->messages) = NULL; Pt->count--; } else if((*(Pt->messages))->next != NULL && (*(Pt->messages))->next != (*(Pt->messages))){ *msgR = *(Pt->messages); message* tail = (*(Pt->messages))->prev; tail->next = (*(Pt->messages))->next; (*(Pt->messages))->next->prev = tail; (*(Pt->messages)) = (*(Pt->messages))->next; Pt->count--; } else if((*(Pt->messages))->next !=NULL && (*(Pt->messages))->next == (*(Pt->messages))){ *msgR = *(Pt->messages); *(Pt->messages) = NULL; Pt->count--; } //Give back the mutex Pt->mutex++; } }
mpberk/cse531-projects
project01/part1/prod_cons_s.c
<filename>project01/part1/prod_cons_s.c // (c) <NAME> 2009 // permission to use and distribute granted. #include <stdio.h> #include <stdlib.h> #include "sem.h" #define N 4 semaphore_t empty, full, mutex; int buffer[N]; int in = 0, out = 0, item_num=0, prod_delay = 1, cons_delay = 1; void prod (int *arg) { while (1){ printf("Producer %d: ready to produce\n", *arg); P(&empty); P(&mutex); printf("Producer %d: inserting item#%d, into slot #%d\n", *arg, item_num, in); buffer[in] = item_num++; in = (in+1) % N; V(&mutex); V(&full); sleep(prod_delay); } } void cons(int *arg) { while(1){ printf(" Consumer %d: ready to consume\n", *arg); P(&full); P(&mutex); printf(" Consumer %d: deleting item#%d, from slot #%d\n", *arg, buffer[out], out); out = (out+1) % N; V(&mutex); V(&empty); sleep(cons_delay); } } int main() { int id[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; init_sem(&full, 0); init_sem(&empty, N); init_sem(&mutex, 1); start_thread(prod, &id[0]); start_thread(cons, &id[1]); start_thread(prod, &id[2]); start_thread(cons, &id[3]); start_thread(prod, &id[4]); start_thread(cons, &id[5]); start_thread(prod, &id[6]); start_thread(cons, &id[7]); while (1) { scanf("%d %d", &prod_delay, &cons_delay); printf ("\n\n\t\t\t\tP=%d C=%d\n\n\n", prod_delay, cons_delay); }; }
mpberk/cse531-projects
project02/q_test.c
#include <stdio.h> #include <stdlib.h> #include "q.h" int id (q_element *item) { return *((int*)(item->payload)); } int main(int argc, char *argv[]) { int item1_value = 1; int item2_value = 2; int item3_value = 3; printf("Creating queue\n"); q_element *head = NewQueue(); printf("Creating item1\n"); q_element *item1 = NewItem(); printf("Freeing item1\n"); FreeItem(item1); printf("Creating item1\n"); item1 = NewItem(); printf("Updating payload of item1\n"); item1->payload = (void*) &item1_value; printf("Adding item1 to queue\n"); AddQueue(&head, item1); // Resulting queue should be 1 if (head != item1) printf("ERROR: Failed to add item1 to empty queue\n"); if ((head->next != head) || (head->prev != head)) printf("ERROR: Failed to setup next and prev pointers for queue with 1 item\n"); printf("Creating item2\n"); q_element *item2 = NewItem(); item2->payload = (void*) &item2_value; printf("Adding item2 to queue\n"); AddQueue(&head, item2); // Resulting queue should be 1->2 if (head != item1) printf("ERROR: Failed to add item2 to queue\n"); if (head->next != item2) printf("ERROR: Failed to setup head->next pointer. Exp: %d, Act: %d\n",id(item2),id(head->next)); if (head->prev != item2) printf("ERROR: Failed to setup head->prev pointer. Exp: %d, Act: %d\n",id(item2),id(head->prev)); q_element *item3 = NewItem(); item3->payload = (void*) &item3_value; printf("Adding item3 to queue\n"); AddQueue(&head, item3); // Resulting queue should be 1->2->3 if (head->next != item2) printf("ERROR: Failed to setup head->next pointer. Exp: %d, Act: %d\n",id(item2),id(head->next)); if (head->prev != item3) printf("ERROR: Failed to setup head->prev pointer. Exp: %d, Act: %d\n",id(item3),id(head->prev)); printf("Removing item from queue (item3)\n"); q_element *item1_removed = DelQueue(&head); // Resulting queue should be 2->3 if (item1_removed != item1) printf("ERROR: Removed incorrect item"); if (head != item2) printf("ERROR: New head is incorrect. Exp: %d, Act: %d",id(item2),id(head)); if (head->next != item3) printf("ERROR: Failed to setup head->next pointer. Exp: %d, Act: %d\n",id(item3),id(head->next)); if (head->prev != item3) printf("ERROR: Failed to setup head->prev pointer. Exp: %d, Act: %d\n",id(item3), id(head->prev)); printf("Removing item from queue (item2)\n"); q_element *item2_removed = DelQueue(&head); // Resulting queue should be 3 if (item2_removed != item2) printf("ERROR: Removed incorrect item"); if (head != item3) printf("ERROR: New head is incorrect. Exp: %d, Act: %d",id(item3),id(head)); };
mpberk/cse531-projects
project02/thread_test.c
// <NAME> // <NAME> // CSE 531 - Distributed and Multiprocessor Operating Systems // Project 02 // Due October 7, 2020 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "threads.h" // Number of children functions to run int count = 3; // Global variable int global = 0; // Easily modifiable function for sleep void go_to_sleep() { sleep(1); } // Child function to have multiple copies running void function (void *arg) { int value = *(int*) arg; int local = 0; while (1) { printf("Function %02d: global = %d, local = %d\n", value, global, local); go_to_sleep(); global++; local++; go_to_sleep(); printf("Function %02d: incremented, global = %d, local = %d\n", value, global, local); go_to_sleep(); yield(); } } int main (int argc, char *argv[]) { int i; // for loop variable // Get number of children from command line if (argc >= 2) { count = atoi(argv[1]); } // Setup array for indices int *indices; indices = (int*) malloc(count * sizeof(int)); for (i = 0; i < count; i++) { *(indices+i) = i; }; // Setup different threads for (i = 0; i < count; i++) { start_thread(function, (void*) (indices+i)); }; run(); };
mpberk/cse531-projects
project01/part2/proj-1.c
// CSE 531 - Distributed and Multiprocessor Operating Systems // Project 1 // Due September 23, 2020 // <NAME> // <NAME> // // Features: // Program runs without any parameters, but can take 1 argument for specifying the number of children running (default 3) // Semaphore synchronization scheme based on the solution to the Readers-Writers semaphore problem. // If the synchronization scheme fails, the program halts. // // Program description: // Main (parent) thread sets up array and semaphores // Parent creates 3 children // One of the children runs and starts the other children (using the start_children semaphore) // Once all of the children finish running (child_wait semaphore), the parent thread is started (start_parent semaphore) // Once the parent thread finishes running, the children are started // The process then repeats #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include "sem.h" int count = 3; int *x; int active_children = 0; semaphore_t mutex; // General mutex for critical sections semaphore_t start_children; // Start a child semaphore_t start_parent; // Start the parent semaphore_t child_wait; // Children waiting for other children to finish up int child (void *arg) { int index = *(int*) arg; while (1) { // Wait for signal to start children P(&start_children); // Critical section P(&mutex); // Increase number of active children active_children++; // Allow other children to start if still more left if (active_children < count) V(&start_children); V(&mutex); // Increment specific array entry *(x+index) = *(x+index) + 1; // Critical section P(&mutex); // On last child if (active_children == count) { // Continue all children V(&child_wait); active_children--; } V(&mutex); // Wait until all children are done P(&child_wait); // Critical section P(&mutex); // On all but last child if (active_children != 0) { // End another child (violent sounding...) V(&child_wait); active_children--; } else { // On last child, start parent V(&start_parent); } V(&mutex); } } int main(int argc, char *argv[]) { int i; // Get number of children from command line if (argc >= 2) { count = atoi(argv[1]); } // Setup array for incrementing and indices int *indices; x = calloc(count, sizeof(int)); indices = (int*) malloc(count * sizeof(int)); for (i = 0; i < count; i++) { *(indices+i) = i; } // Initialize semaphores init_sem(&mutex,1); init_sem(&start_children,1); init_sem(&start_parent,0); init_sem(&child_wait,0); // Setup and start pthreads pthread_t *pids; pids = (pthread_t*) malloc(count * sizeof(pthread_t)); for (i = 0; i < count; i++) pids[i] = start_thread(child, (void*) (indices+i)); int failure = 0; int j = 0; // Loop to wait for children then print while (1) { j = j + 1; // Wait for start_parent from children finishing up P(&start_parent); // print out array for (i = 0; i < count; i++) { printf("i: %d, x[%d] = %d\n", j, i, *(x+i)); // On failure of semaphores, break from loop and end program if (j != *(x+i)) failure = 1; if ((i == count - 1) && failure) break; } if (failure) break; // Start children V(&start_children); } }
mpberk/cse531-projects
project02/hongquy/threads.h
#ifndef THREADS_H #define THREADS_H #include "q.h" extern TCB_t** ReadyQ; extern TCB_t* Curr_Thread; int counter = 0; void start_thread(void (*function)(void)){ void* stack = malloc(8192); TCB_t* temp_tcb = NewItem(); init_TCB(temp_tcb, function, stack, 8192); temp_tcb->thread_id = counter; counter++; AddQueue(ReadyQ, temp_tcb); } void run(){ Curr_Thread = DelQueue(ReadyQ); // printf("Remove a function from the queue and put it into Curr_Thread\n"); ucontext_t parent; getcontext(&parent); // printf("Parent context acquired\n"); swapcontext(&parent, &(Curr_Thread->context)); } void printID(TCB_t* tcb){ printf(" thread ID:%d\n", tcb->thread_id); } void yield(){ TCB_t* Prev_Thread; AddQueue(ReadyQ, Curr_Thread); Prev_Thread = Curr_Thread; Curr_Thread = DelQueue(ReadyQ); // printID(Curr_Thread); swapcontext(&(Prev_Thread->context),&(Curr_Thread->context)); } #endif
mpberk/cse531-projects
project04/Hongquy_Code/msgs_test.c
<reponame>mpberk/cse531-projects<filename>project04/Hongquy_Code/msgs_test.c // CSE 531 - Distributed and Multiprocessor Operating Systems // Project 4 // Due November 11, 2020 // <NAME> // <NAME> #include "msgs.h" //global ports set* globalPorts; void client1(){ //Making a message. Message is 1111111111 message* newMessage = (message*) malloc(sizeof(message)); for (int i = 0; i < 10; i++){ newMessage->nums[i] = 1; } //Repeatedly sending the message while(1){ printf("In client 1\n"); sleep(1); send(&(globalPorts->arrayP[0]), newMessage); } } void client2(){ //Making a message. Messages is 0123456789 message* newMessage = (message*) malloc(sizeof(message)); for (int i = 0; i < 10; i++){ newMessage->nums[i] = i; } //Repeatedly sending the message while(1){ printf("In client 2\n"); sleep(1); send(&(globalPorts->arrayP[1]), newMessage); } } void server1(){ //message to recieve message** recievedM = (message**) malloc(sizeof(message*)); //Repeatedly read from port 0 while(1){ printf("In server 1\n"); recieve(&(globalPorts->arrayP[0]), recievedM); sleep(1); //Printing the message from port 0 printf("Printing message:\n"); for(int i = 0; i < 10; i++){ printf("%d", (*(recievedM))->nums[i]); } printf("\n"); sleep(1); V((&(globalPorts->arrayP[0]))->sendS); } } void server2(){ //message to recieve message** recievedM = (message**) malloc(sizeof(message*)); //Repeatedly read from port 1 while(1){ printf("In server 2\n"); recieve(&(globalPorts->arrayP[1]), recievedM); sleep(1); //printing the message from port 1 printf("Printing message:\n"); for(int i = 0; i < 10; i++){ printf("%d", (*(recievedM))->nums[i]); } printf("\n"); sleep(1); V((&(globalPorts->arrayP[1]))->sendS); } } //Declare globals TCB_t** ReadyQ; TCB_t* Curr_Thread; int counterID; void main(){ //global ports globalPorts = (set*) malloc(sizeof(set)); //initialize all the ports for(int i = 0; i < 100; i++){ globalPorts->arrayP[i] = *(initPort()); } //Allocate memory to globals ReadyQ = newQueue(); Curr_Thread = NewItem(); counterID = 0; start_thread(client1); start_thread(client2); start_thread(server1); start_thread(server2); run(); }
mpberk/cse531-projects
project01/part1/prod_cons_m.c
// (c) <NAME> 2009 // permission to use and distribute granted. #include <stdio.h> #include <stdlib.h> #include "monitor.h" #define N 4 monitor_t buff_mon; monitor_cond_t empty, full; int buffer[N]; int in = 0, out = 0, count=0, item_num=0, prod_delay = 1, cons_delay = 1; void prod (int *arg) { while (1){ printf("Producer %d: ready to produce\n", *arg); monitor_entry(&buff_mon); if (count>=N) monitor_wait(&buff_mon, &empty); printf("Producer %d: inserting item#%d, into slot #%d\n", *arg, item_num, in); buffer[in] = item_num++; in = (in+1) % N; count++; monitor_signal(&buff_mon, &full); monitor_exit(&buff_mon); sleep(prod_delay); } } void cons(int *arg) { while(1){ printf(" Consumer %d: ready to consume\n", *arg); monitor_entry(&buff_mon); if (count<=0) monitor_wait(&buff_mon, &full); printf(" Consumer %d: deleting item#%d, from slot #%d\n", *arg, buffer[out], out); out = (out+1) % N; count--; monitor_signal(&buff_mon, &empty); monitor_exit(&buff_mon); sleep(cons_delay); } } int main() { int id[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; init_monitor(&buff_mon); init_monitor_cond(&empty); init_monitor_cond(&full); start_thread(prod, &id[0]); start_thread(cons, &id[1]); start_thread(prod, &id[2]); start_thread(cons, &id[3]); start_thread(prod, &id[4]); start_thread(cons, &id[5]); start_thread(prod, &id[6]); start_thread(cons, &id[7]); while (1) { scanf("%d %d", &prod_delay, &cons_delay); printf ("\n\n\t\t\t\tP=%d C=%d\n\n\n", prod_delay, cons_delay); }; }
mpberk/cse531-projects
project02/hongquy/q_test.c
<filename>project02/hongquy/q_test.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include "q.h" int id (TCB_t *item) { return item->thread_id; } TCB_t** ReadyQ; TCB_t* Curr_Thread; int main(int argc, char *argv[]) { printf("Creating queue\n"); ReadyQ = newQueue(); // ReadyQ at this point should be {head} printf("Creating item1\n"); TCB_t *item1 = NewItem(); item1->thread_id = 1; printf("Adding item1 to queue\n"); AddQueue(ReadyQ, item1); // ReadyQ at this point should be {head,item1} // The head item should have both next and prev pointers point to item1 if (((*ReadyQ)->next != item1) || ((*ReadyQ)->prev != item1)) printf("ERROR: Failed to setup next and prev pointers for head\n"); // The item1 should have next and prev point to head if ((item1->next != (*ReadyQ)) || (item1->prev != (*ReadyQ))) printf("ERROR: Failed to setup next and prev pointers for item1\n"); printf("Creating item2\n"); TCB_t *item2 = NewItem(); item1->thread_id = 2; printf("Adding item2 to queue\n"); AddQueue(ReadyQ, item2); // ReadyQ at this point should be {head,item1,item2} // The head item should have next to item1 and prev to item2 if (((*ReadyQ)->next != item1) || ((*ReadyQ)->prev != item2)) printf("ERROR: Failed to setup pointers for head\n"); // The item1 should have next to item2 and prev to head if ((item1->next != item2) || (item1->prev != (*ReadyQ))) printf("ERROR: Failed to setup pointers for item1\n"); // The item2 should have next to head and prev to item1 if ((item2->next != (*ReadyQ)) || (item2->prev != item1)) printf("ERROR: Failed to setup pointers for item2\n"); printf("Creating item3\n"); TCB_t *item3 = NewItem(); item1->thread_id = 3; printf("Adding item3 to queue\n"); AddQueue(ReadyQ, item3); // ReadyQ at this point should be {head,item1,item2,item3} // The head item should have next to item1 and prev to item3 if (((*ReadyQ)->next != item1) || ((*ReadyQ)->prev != item3)) printf("ERROR: Failed to setup pointers for head\n"); // The item1 should have next to item2 and prev to head if ((item1->next != item2) || (item1->prev != (*ReadyQ))) printf("ERROR: Failed to setup pointers for item1\n"); // The item2 should have next to item3 and prev to item1 if ((item2->next != item3) || (item2->prev != item1)) printf("ERROR: Failed to setup pointers for item2\n"); // The item3 should have next to head and prev to item2 if ((item3->next != (*ReadyQ)) || (item3->prev != item2)) printf("ERROR: Failed to setup pointers for item3\n"); // Delete item from queue printf("Deleting item from queue\n"); TCB_t *item1_deleted = DelQueue(ReadyQ); // ReadyQ at this point should be {head,item2,item3} // The head item should have next to item2 and prev to item3 if (((*ReadyQ)->next != item2) || ((*ReadyQ)->prev != item3)) printf("ERROR: Failed to setup pointers for head\n"); // The item2 should have next to item3 and prev to head if ((item2->next != item3) || (item2->prev != (*ReadyQ))) printf("ERROR: Failed to setup pointers for item2\n"); // The item3 should have next to head and prev to item2 if ((item3->next != (*ReadyQ)) || (item3->prev != item2)) printf("ERROR: Failed to setup pointers for item3\n"); // Adding item1 back to queue printf("Adding item1 back to queue\n"); AddQueue(ReadyQ, item1); // ReadyQ at this point should be {head,item2,item3,item1} // The head item should have next to item2 and prev to item1 if (((*ReadyQ)->next != item2) || ((*ReadyQ)->prev != item1)) { printf("ERROR: Failed to setup pointers for head\n"); printf("ERROR: Next - Exp: %d, Act: %d\n",id(item2),id(((*ReadyQ)->next))); printf("ERROR: Prev - Exp: %d, Act: %d\n",id(item1),id(((*ReadyQ)->prev))); }; // The item1 should have next to head and prev to item3 if ((item1->next != (*ReadyQ)) || (item1->prev != item3)) { printf("ERROR: Failed to setup pointers for item1\n"); printf("ERROR: Next - Exp: %d, Act: %d\n",id((*ReadyQ)),id((item1->next))); printf("ERROR: Prev - Exp: %d, Act: %d\n",id(item3),id((item1->prev))); }; // The item2 should have next to item3 and prev to head if ((item2->next != item3) || (item2->prev != (*ReadyQ))) printf("ERROR: Failed to setup pointers for item2\n"); // The item3 should have next to item1 and prev to item2 if ((item3->next != item1) || (item3->prev != item2)) printf("ERROR: Failed to setup pointers for item3\n"); };
mpberk/cse531-projects
project04/Hongquy_Code/TCB.h
<filename>project04/Hongquy_Code/TCB.h<gh_stars>0 #ifndef TCB_H #define TCB_H #include <ucontext.h> #include <string.h> #include <stdio.h> typedef struct TCB_t TCB_t; struct TCB_t{ TCB_t* next; TCB_t* prev; ucontext_t context; int thread_id; }; void init_TCB(TCB_t* tcb, void* function, void* stackP, int stack_size){ memset(tcb, '\0', sizeof(TCB_t)); getcontext(&tcb->context); tcb->context.uc_stack.ss_sp = stackP; tcb->context.uc_stack.ss_size = (size_t) stack_size; makecontext(&tcb->context, function, 0); } #endif
mpberk/cse531-projects
project02/hongquy/q.h
<filename>project02/hongquy/q.h #ifndef Q_H #define Q_H #include <stdlib.h> #include <stdio.h> #include "TCB.h" TCB_t* NewItem(){ TCB_t* newPtr = (TCB_t*) malloc(sizeof(TCB_t)); newPtr->next = NULL; newPtr->prev = NULL; // newPtr->thread_id = NULL; getcontext(&(newPtr->context)); return newPtr; } TCB_t** newQueue(){ TCB_t** head = (TCB_t**) malloc(sizeof(TCB_t*)); return head; } void AddQueue(TCB_t** head, TCB_t* item){ if(head == NULL){ printf("error, queue not made\n"); exit(1); } else if(*head == NULL ){ *head = item; } else if((*head)->next == NULL){ (*head)->next = item; (*head)->prev = item; item->prev = (*head); item->next = (*head); // printf("Item added! 1\n"); } else if((*head)->next != NULL){ TCB_t* tail = (*head)->prev; tail->next = item; tail->next->next = (*head); tail->next->prev = tail; (*head)->prev = tail->next; // printf("Item added! 2\n"); } } TCB_t* DelQueue(TCB_t** head){ TCB_t* delEle = NULL; if((*head) == NULL){ printf("error, queue empty\n"); exit(1); } else if((*head)->next == NULL){ delEle = *head; (*head) = NULL; /// printf("Item deleted 1\n"); } else if((*head)->next != NULL && (*head)->next != (*head)){ delEle = *head; TCB_t* tail = (*head)->prev; tail->next = (*head)->next; (*head)->next->prev = tail; (*head) = (*head)->next; // printf("Item deleted 2\n"); } else if((*head)->next !=NULL && (*head)->next == *head){ delEle = *head; *head = NULL; // printf("Item deleted 3\n"); } return delEle; } #endif
mpberk/cse531-projects
project02/hongquy/thread_test.c
<reponame>mpberk/cse531-projects<filename>project02/hongquy/thread_test.c #ifndef THREAD_TEST #define THREAD_TEST #include "threads.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> int globVar = 0; void function1(){ int local = 0; while (1) { printf("In function 1\n"); sleep(1); globVar++; local++; printf("global value: %d, local value: %d\n", globVar, local); printf("yielding in function 1\n\n"); sleep(1); yield(); } } void function2(){ int local = 0; while(1) { printf("In function 2\n"); sleep(1); globVar++; local++; printf("global value: %d, local value: %d\n", globVar, local); printf("yielding in function 2\n\n"); sleep(1); yield(); } } void function3(){ int local = 0; while(1) { printf("In function 3\n"); sleep(1); globVar++; local++; printf("global value: %d, local value: %d\n", globVar, local); printf("yielding in function 3\n\n"); sleep(1); yield(); } } TCB_t** ReadyQ; TCB_t* Curr_Thread; int main(){ ReadyQ = newQueue(); // printf("this part works 1\n"); start_thread(function1); start_thread(function2); start_thread(function3); // printf("this part works 2\n"); run(); return 1; } #endif
mpberk/cse531-projects
project02/q.h
#ifndef Q_H #define Q_H #include <stdio.h> #include <stdlib.h> typedef struct q_element q_element; struct q_element { q_element *prev; q_element *next; void* payload; }; q_element *NewItem() { q_element *new_item = (q_element*) malloc(sizeof(q_element)); new_item->prev = NULL; new_item->next = NULL; return new_item; }; void FreeItem(q_element *item) { free(item); }; q_element *NewQueue() { q_element* head = NULL; return head; }; // Add to end of queue void AddQueue(q_element **head, q_element *item) { if (*head == NULL) { item->prev = item; item->next = item; *head = item; } else { item->next = (*head); item->prev = (*head)->prev; (*head)->prev->next = item; (*head)->prev = item; }; }; // Remove from head of queue q_element *DelQueue(q_element **head) { q_element *deleted_item; if (*head == NULL) { printf("ERROR: Attempted to delete item from empty queue\n"); } else { deleted_item = *head; (*head)->next->prev = (*head)->prev; (*head)->prev->next = (*head)->next; *head = (*head)->next; deleted_item->next = NULL; deleted_item->prev = NULL; }; return deleted_item; }; #endif
mpberk/cse531-projects
project01/part1/sem_test.c
// (c) <NAME> 2009 // permission to use and distribute granted. #include <stdio.h> #include <stdlib.h> #include "threads.h" typedef struct semaphore_t { pthread_mutex_t mutex; pthread_cond_t cond; int count; } semaphore_t; void init_sem(semaphore_t *s, int i) { s->count = i; pthread_mutex_init(&(s->mutex), NULL); pthread_cond_init(&(s->cond), NULL); } /* * The P routine decrements the semaphore, and if the value is less than * zero then blocks the process */ void P(semaphore_t *sem) { pthread_mutex_lock (&(sem->mutex)); sem->count--; if (sem->count < 0) pthread_cond_wait(&(sem->cond), &(sem->mutex)); pthread_mutex_unlock (&(sem->mutex)); } /* * The V routine increments the semaphore, and if the value is 0 or * negative, wakes up a process and yields */ void V(semaphore_t * sem) { pthread_mutex_lock (&(sem->mutex)); sem->count++; if (sem->count <= 0) { pthread_cond_signal(&(sem->cond)); } pthread_mutex_unlock (&(sem->mutex)); pthread_yield(); } semaphore_t mutex; void function_1(void) { while (1){ P(&mutex); printf("Beginning of CS: func 1\n"); sleep(1); printf("End of CCS: func 1..\n"); sleep(1); V(&mutex); } } void function_2(void) { while (1){ P(&mutex); printf("Beginning of CS: func 2\n"); sleep(1); printf("End of CCS: func 2..\n"); sleep(1); V(&mutex); } } void function_3(void) { while (1){ P(&mutex); printf("Beginning of CS: func 3\n"); sleep(1); printf("End of CCS: func 3..\n"); sleep(1); V(&mutex); } } int main() { init_sem(&mutex, 1); start_thread(function_1, NULL); start_thread(function_2, NULL); start_thread(function_3, NULL); while(1) sleep(1); return 0; }
mpberk/cse531-projects
project01/part2/threads.h
<reponame>mpberk/cse531-projects // (c) <NAME> 2009 // permission to use and distribute granted. #include <pthread.h> pthread_t start_thread(void *func, int *arg) { pthread_t thread_id; int rc; printf("In main: creating thread\n"); rc = pthread_create(&thread_id, NULL, func, arg); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } return(thread_id); }
mpberk/cse531-projects
project01/part1/race-p.c
<reponame>mpberk/cse531-projects<gh_stars>0 // (c) <NAME> 2009 // permission to use and distribute granted. #include <stdio.h> #include <stdlib.h> #include "threads.h" int x; func1() {int i = 0; printf("Thread 1 - running\n"); for (i=0; i<100000000; i++) x++; printf("Thread 1: x = %d\n", x); printf("Thread 1 - done\n"); } func2(void* arg) {int i = 0; printf(" Thread 2 - running\n"); for (i=0; i<100000000; i++) x++; printf(" Thread 2: x = %d\n", x); printf(" Thread 2 - done\n"); } main() { printf("starting\n"); pthread_t pid = start_thread(func2, NULL); printf("cloned: %ld\n", pid); func1(); sleep(1); printf("final value %d\n", x); }
mpberk/cse531-projects
project03/sem.h
<filename>project03/sem.h #ifndef SEM_H #define SEM_H #include "threads.h" typedef struct Semaphore_t { int counter; q_element *Queue; // Queue of TCB_t's } Semaphore_t; Semaphore_t *CreateSem(int InputValue) { // Mallocs a semaphore structure Semaphore_t* newSem = (Semaphore_t*) malloc(sizeof(Semaphore_t)); // initializes it to the InitValue newSem->counter = InputValue; // initialize Queue newSem->Queue = NewQueue(); // returns the pointer to the semaphore return newSem; }; void P(Semaphore_t * sem) { printf("P() was called\n"); // decrements the semaphore sem->counter--; // if the value is less than zero, then blocks the thread in the queue associated with the semaphore // Note: This is very similar to yield, but adds Prev_Thread to sem's queue instead if (sem->counter < 0) { printf("Hit C. Sem is at: %d\n",sem->counter); q_element *Prev_Thread; // Store the current context in the sem queue AddQueue(&(sem->Queue), Curr_Thread); // Grab next thread in global queue Prev_Thread = Curr_Thread; Curr_Thread = DelQueue(&ReadyQ); // Swap contexts swapcontext(get_context_ptr(Prev_Thread), get_context_ptr(Curr_Thread)); }; }; void V(Semaphore_t * sem) { printf("V() was called\n"); // increments the semaphore sem->counter++; // if the value is 0 or negative, then takes a TCB out the semaphore queue puts it into the ReadyQ // Note: If counter is less than 0, then a TCB must exist in the queue if (sem->counter <= 0) { printf("Hit V A. Sem is at: %d\n",sem->counter); // Get TCB_t from queue q_element *threadToAdd = DelQueue(&(sem->Queue)); // Add to global queue to be run printf("Hit V B\n"); AddQueue(&ReadyQ, threadToAdd); }; // Note: The V routine also "yields" to the next runnable thread printf("Hit V C\n"); yield(); ; }; #endif
mpberk/cse531-projects
project03/hongquy_Code/read_write.c
<filename>project03/hongquy_Code/read_write.c<gh_stars>0 // CSE 531 - Distributed and Multiprocessor Operating Systems // Project 3 // Due October 26, 2020 // <NAME> // <NAME> #include "sem.h" Semaphore_t* r_sem; Semaphore_t* w_sem; int rwc = 0, wwc = 0, rc = 0, wc = 0, global_ID = 0; void reader_entry(int ID){ printf("reader #%d trying to read\n" , ID); if(wwc > 0 || wc > 0) { printf("reader #%d is being blocked\n", ID); rwc++; P(r_sem); rwc--; } rc++; if (rwc > 0) { printf("Releasing waiting readers\n"); V(r_sem); } sleep(1); } void reader_exit(int ID){ printf("Reducing reader count\n"); rc--; if(rc == 0 && wwc > 0) { printf("Releasing waiting writers if there are no readers\n"); V(w_sem); } sleep(1); } void writer_entry(int ID){ printf("writer %d is trying to write\n", ID); if( rc > 0 || wc > 0){ printf("writer %d is being blocked\n", ID); wwc++; P(w_sem); wwc--; } wc++; sleep(1); } void writer_exit(int ID){ printf("decreasing writer count\n"); wc--; if (rwc > 0) { printf("If there are waiting readers, release them\n"); V(r_sem); } else if( wwc > 0) { printf("Releasing any waiting writers if there are no waiting readers\n"); V(w_sem); } } void reader(){ int ID; ID = global_ID; global_ID++; while(1){ P(r_sem); reader_entry(ID); printf("Reader #%d is running\n" , ID); sleep(1); reader_exit(ID); V(r_sem); } } void writer(){ int ID; ID = global_ID; global_ID++; while (1){ P(w_sem); writer_entry(ID); printf("Writer #%d is running\n", ID); sleep(1); writer_exit(ID); V(w_sem); } } TCB_t** ReadyQ; TCB_t* Curr_Thread; int counterID; void main(){ //printf("This is up to date\n"); w_sem = CreateSem(1); r_sem = CreateSem(1); ReadyQ = newQueue(); Curr_Thread = NewItem(); counterID = 0; printf("This part works 1\n"); start_thread(reader); start_thread(reader); start_thread(reader); start_thread(reader); start_thread(writer); start_thread(writer); printf("this part works 2\n"); run(); }
mpberk/cse531-projects
project01/part1/thread_test.c
<gh_stars>0 // (c) <NAME> 2009 // permission to use and distribute granted. #include <pthread.h> #include <stdio.h> #include <stdlib.h> int global=0; void function_1(int *arg) { int local = 0; while (1){ printf("XXXXPrinting from Function 1 [arg = %d] global = %d local = %d\n", *arg, global, local); sleep(1); global++; local ++; printf("Function 1 incremented .... global = %d local = %d\n", global, local); sleep(1); } } void function_2(int *arg) { int local = 0; while (1){ printf("XXXXPrinting from Function 2 [arg = %d] global = %d local = %d\n", *arg, global, local); sleep(1); global++; local ++; printf("Function 2 incremented .... global = %d local = %d\n", global, local); sleep(1); } } void function_3(int *arg) { int local = 0; while (1){ printf("XXXXPrinting from Function 3 [arg = %d] global = %d local = %d\n", *arg, global, local); sleep(1); global++; local ++; printf("Function 3 incremented .... global = %d local = %d\n", global, local); sleep(1); } } pthread_t start_thread(void *func, int *arg) { pthread_t thread_id; int rc; printf("In main: creating thread\n"); rc = pthread_create(&thread_id, NULL, func, arg); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } return(thread_id); } int main() { int arg; arg = 25; start_thread(function_1, &arg); arg = 50; start_thread(function_1, &arg); // there is a serious bug here, left it in for demo purposes arg = 100; start_thread(function_1, &arg); while(1) sleep(1); // infinite loop return 0; }
mpberk/cse531-projects
project01/part1/race-c.c
<filename>project01/part1/race-c.c // (c) <NAME> 2009 // permission to use and distribute granted. #include <sched.h> #include <stdio.h> #include <stdlib.h> void *stack; int x=1; func1() {int i = 0; printf("Thread 1 - running\n"); for (i=0; i<100000000; i++) x++; printf("Thread 1: x = %d\n", x); printf("Thread 1 - done\n"); } func2(void* arg) {int i = 0; printf(" Thread 2 - running\n"); for (i=0; i<100000000; i++) x++; printf(" Thread 2: x = %d\n", x); printf(" Thread 2 - done\n"); } main() { stack = malloc(60000); printf("starting\n"); int pid = clone(&func2, stack+10000, CLONE_VM|CLONE_FS, 0); printf("cloned: %d\n", pid); func1(); sleep(1); printf("final value %d\n", x); }
mpberk/cse531-projects
project03/threads.h
<gh_stars>0 #ifndef THREADS_H #define THREADS_H #include "q.h" #include "TCB.h" // Global queue of TCBs q_element *ReadyQ; // Global pointer to thread under execution q_element *Curr_Thread; // Global thread id count int id_count = 0; // Get ID of thread int get_id (q_element *thread) { return ((TCB_t*)(thread->payload))->thread_id; // thread : pointer to q_element // thread->payload : void pointer to tcb // (TCB_t*)(thread->payload) : TCB_t pointer to tcb // ((TCB_t*)(thread->payload))->thread_id : id }; // Get pointer to context from thread ucontext_t *get_context_ptr(q_element *item) { return &(((TCB_t*)(item->payload))->context); // item : pointer to q_element // item->payload : void pointer to tcb // (TCB_t*)(item->payload) : TCB_t pointer to tcb // ((TCB_t*)(item->payload))->context : context that exists in TCB // &(((TCB_t*)(item->payload))->context) : pointer to context }; void start_thread(void *function, void *args) { // allocate a stack (via malloc) of a certain size (choose 8192) int stack_size = 8192; void *stack = malloc(stack_size); // allocate a TCB (via malloc) TCB_t *tcb = (TCB_t*) malloc(sizeof(TCB_t)); q_element *thread = NewItem(); thread->payload = (void*) tcb; // call init_TCB with appropriate arguments init_TCB(tcb, function, args, stack, stack_size); // Add a thread_id (use a counter) tcb->thread_id = id_count; id_count++; // call addQ to add this TCB into the "ReadyQ" which is a global head pointer AddQueue(&ReadyQ, thread); }; void run() { Curr_Thread = DelQueue(&ReadyQ); ucontext_t parent; // get a place to store the main context, for faking getcontext(&parent); // magic sauce swapcontext(&parent, get_context_ptr(Curr_Thread)); // start the first round }; void yield() // similar to run { q_element *Prev_Thread; AddQueue(&ReadyQ, Curr_Thread); Prev_Thread = Curr_Thread; Curr_Thread = DelQueue(&ReadyQ); // swap the context, from Prev_Thread to the thread pointed to Curr_Thread swapcontext(get_context_ptr(Prev_Thread), get_context_ptr(Curr_Thread)); }; #endif
mpberk/cse531-projects
project03/TCB.h
#ifndef TCB_H #define TCB_H #include <string.h> #include <ucontext.h> typedef struct TCB_t { int thread_id; ucontext_t context; } TCB_t; void init_TCB (TCB_t *tcb, void *function, void *args, void *stackP, int stack_size) // arguments to init_TCB are // 1. pointer to the function, to be executed // 2. pointer to the thread stack // 3. size of the stack { memset(tcb, '\0', sizeof(TCB_t)); // wash, rinse getcontext(&tcb->context); // have to get parent context, else snow forms on hell tcb->context.uc_stack.ss_sp = stackP; tcb->context.uc_stack.ss_size = (size_t) stack_size; makecontext(&tcb->context, function, 1, args); // context is now cooked } #endif
mpberk/cse531-projects
project01/proj-1.c
#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> pthread_t startThread(void* func, int* arg){ pthread_t threadID; int rc; printf("\nIn main: creating thread\n"); rc = pthread_create(&threadID, NULL, func, arg); if(rc){ printf("Error, return code from pthread_create() is %d\n", rc); exit(-1); } return(threadID); } typedef struct semaphore_t { pthread_mutex_t mutex; pthread_cond_t cond; int count; } semaphore_t; void init_sem(semaphore_t* s, int i){ s->count = i; pthread_mutex_init(&(s->mutex), NULL); pthread_cond_init(&(s->cond), NULL); } void P(semaphore_t* sem){ pthread_mutex_lock(&(sem->mutex)); sem->count--; if(sem->count < 0){ pthread_cond_wait(&(sem->cond), &(sem->mutex)); } pthread_mutex_unlock(&(sem->mutex)); } void V(semaphore_t* sem){ pthread_mutex_lock (&(sem->mutex)); sem->count++; if(sem->count <= 0) { pthread_cond_signal(&(sem->cond)); } pthread_mutex_unlock(&(sem->mutex)); pthread_yield(NULL); } semaphore_t mutex; int childNum[3] = {0,0,0}; void child1(void){ while(1){ P(&mutex); printf("This is child1 start\n"); childNum[0] = childNum[0] + 1; printf("This is end of child1\n"); sleep(1); V(&mutex); } } void child2(void){ while(1){ P(&mutex); printf("This is child2 start\n"); childNum[1] = childNum[1] + 1; printf("This is end of child2\n"); sleep(1); V(&mutex); } } void child3(void){ while(1){ P(&mutex); printf("This is child3 start\n"); childNum[2] = childNum[2] + 1; printf("This is end of child3\n"); sleep(1); V(&mutex); } } int main(){ init_sem(&mutex, 1); startThread(child1, NULL); startThread(child2, NULL); startThread(child3, NULL); sleep(1); while (1){ P(&mutex); printf("value 1: %d\n value 2: %d\n value 3: %d\n\n",childNum[0],childNum[1], childNum[2]); V(&mutex); } return 0; }
shubhamsah/OpenEDU
C Programs/DS Programs/Sorting and Searching/QuickRand.c
/* Program to demonstrate Randomized quick sort (recursive) */ #include <stdio.h> #include <stdlib.h> #include <conio.h> void quick(int x[] , int lb , int ub) ; int partition(int x[] , int lb , int ub) ; void show(int x[] , int lb , int ub) ; void main() { int i , n , x[20] ; clrscr() ; printf("Enter the number of elements: ") ; scanf("%d",&n) ; printf("Enter the elements:\n") ; for(i=0;i<n;i++) scanf("%d",&x[i]) ; quick(x,0,n-1) ; printf("Sorted array is as shown:\n") ; for(i=0;i<n;i++) printf("%d ",x[i]) ; getch() ; } void quick(int x[] , int lb , int ub) { int j , k , temp ; if(lb<ub) { k=rand()%(ub-lb+1) + lb ; temp=x[k] ; x[k]=x[lb] ; x[lb]=temp ; j=partition(x,lb,ub) ; quick(x,lb,j-1) ; quick(x,j+1,ub) ; } } int partition(int x[] , int lb , int ub) { int a , down , up , temp ; a=x[lb] ; up=ub ; down=lb ; while(down<up) { while(x[down]<=a&&down<ub) down++ ; while(x[up]>a) up-- ; if(down<up) { temp=x[down] ; x[down]=x[up] ; x[up]=temp ; } } x[lb]=x[up] ; x[up]=a ; show(x,lb,ub) ; return up ; } void show(int x[] , int lb , int ub) { int i ; for(i=lb ; i<=ub ; i++) printf("%d ",x[i]) ; printf("\n\n") ; } /* The method show() is optional. It is written to show output of each pass. It may not be written in theory exam. It is required only in practical exams */
shubhamsah/OpenEDU
C Programs/Control Statements/P_111_333.c
<gh_stars>1-10 /* Pattern Problem - Program to generate all combinations of 1 2 3 using for loop. (Eg Print 111(Row 1), (112)(Row 2), (113)(Row 3)...(333)(Last Row)) */ #include <stdio.h> #include <conio.h> void main() { int i , j , k ; clrscr() ; printf("Required pattern is as follows:\n"); for(i=1 ; i<=3 ; i++) for(j=1 ; j<=3 ; j++) for(k=1 ; k<=3 ; k++) printf("%d %d %d \n" , i , j , k) ; getch(); } /* Output: Required pattern is as follows: 1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1 2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3 */
shubhamsah/OpenEDU
C Programs/Control Statements/ELECTRIC.c
/* An electric power distribution company charges its domestic consumer as follows: Consumption Units Rate of Charge 0-200 0.50 per unit 201-400 Rs. 100 plus Rs. 0.65 per unit excess of 200 401-600 Rs. 230 plus Rs. 0.85 per unit excess of 400 601-above Rs. 390 plus Rs. 1.00 per unit excess of 600 Program should read the units consumed for a customer and calculate the total bill. */ #include <stdio.h> #include <conio.h> void main() { int units ; float amt ; clrscr() ; printf("Enter consumption units: ") ; scanf("%d" , &units) ; if(units>=0 && units<=200) { amt = units * 0.50 ; printf("The total billing amount is %f" , amt) ; } else if(units>=201 && units<=400) { amt = 100 + (units-200) * 0.65 ; printf("The total billing amount is %f" , amt) ; } else if(units>=401 && units<=600) { amt = 230 + (units-400) * 0.85 ; printf("The total billing amount is %f" , amt) ; } else { amt = 390 + (units-600) * 1.00 ; printf("The total billing amount is %f" , amt) ; } getch() ; } /* Output 1: Enter consumption units: 300 The total billing amount is 165.000000 Output 2: Enter consumption units: 450 The total billing amount is 272.500000 Output 3: Enter consumption units: 620 The total billing amount is 410.000000 */
shubhamsah/OpenEDU
C Programs/DS Programs/Trees/pre_to.c
/* Program to construct an expression tree using a prefix expression. Then use the expression tree to display the postfix and infix form of same prefix expression */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #define NULL 0 #define STACKSIZE 50 struct node { char data ; struct node *left ; struct node *right ; } ; struct node *root=NULL ; struct stack { int top ; struct node* items[STACKSIZE] ; } ; void createtree(char e[]) ; int isoperand(char c) ; struct node* pop(struct stack *ps) ; void push(struct stack *ps , struct node* x) ; void postorder(struct node *root) ; void inorder(struct node *root) ; void main() { char e[50] ; clrscr() ; printf("Enter the expression in prefix form:\n") ; gets(e) ; createtree(e) ; printf("Expression in postfix form is: ") ; postorder(root) ; printf("\n") ; printf("Expression in infix form is: ") ; inorder(root) ; printf("\n") ; getch() ; } void createtree(char e[ ]) { int i , n ; struct node *pnode , *op1 , *op2 ; struct stack s ; s.top=-1 ; n=strlen(e) ; for(i=n-1 ; i>=0 ; i--) if(isoperand(e[i])) { pnode=(struct node*)malloc(sizeof(struct node)) ; pnode->data=e[i] ; pnode->left=pnode->right=NULL ; push(&s,pnode) ; } else { op1=pop(&s) ; op2=pop(&s) ; pnode=(struct node*)malloc(sizeof(struct node)) ; pnode->data=e[i] ; pnode->left=op1 ; pnode->right=op2 ; push(&s,pnode) ; } root=pop(&s) ; } void postorder(struct node *root) { if(root!=NULL) { postorder(root->left) ; postorder(root->right) ; printf("%c",root->data) ; } } void inorder(struct node *root) { if(root!=NULL) { inorder(root->left) ; printf("%c",root->data) ; inorder(root->right) ; } } int isoperand(char c) { if( c>='0'&&c<='9' || c>='A'&&c<='Z' || c>='a'&&c<='z' ) return 1 ; else return 0 ; } struct node* pop(struct stack *ps) { return (ps->items[ps->top--]) ; } void push(struct stack *ps , struct node* x) { ps->items[++(ps->top)]=x ; }
lucasnvp/CMakeListDirectoryStructure
app/src/suma/suma.h
// // Created by lucas on 11/06/19. // #ifndef CMAKEANDCUNIT_SUMA_H #define CMAKEANDCUNIT_SUMA_H int suma (); #endif //CMAKEANDCUNIT_SUMA_H
lucasnvp/CMakeListDirectoryStructure
app/test/Run_main_Tests.c
// // Created by lucas on 11/06/19. // #include "Run_main_Tests.h" int main () { CU_initialize_registry(); agregar_tests_suma(); CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); CU_cleanup_registry(); return CU_get_error(); }
lucasnvp/CMakeListDirectoryStructure
app/test/Test_Suma/Test_Suma.c
// // Created by lucas on 11/06/19. // #include "Test_Suma.h" void agregar_tests_suma() { CU_pSuite suma = CU_add_suite("Suma", inicializar_suma, limpiar_suma); CU_add_test(suma, "test_suma", test_suma); } int inicializar_suma () { return 0; } int limpiar_suma () { return 0; } void test_suma () { int resultado = suma(); CU_ASSERT_EQUAL(resultado, 10); }
lucasnvp/CMakeListDirectoryStructure
app/test/Run_main_Tests.h
// // Created by lucas on 11/06/19. // #ifndef CMAKEANDCUNIT_RUN_MAIN_TESTS_H #define CMAKEANDCUNIT_RUN_MAIN_TESTS_H #include <unistd.h> #include "CUnit/Basic.h" #include "Test_Suma/Test_Suma.h" #endif //CMAKEANDCUNIT_RUN_MAIN_TESTS_H
lucasnvp/CMakeListDirectoryStructure
app/test/Test_Suma/Test_Suma.h
// // Created by lucas on 11/06/19. // #ifndef CMAKEANDCUNIT_TEST_SUMA_H #define CMAKEANDCUNIT_TEST_SUMA_H #include <stdio.h> #include <stdlib.h> #include "CUnit/Basic.h" #include <suma/suma.h> void agregar_tests_suma(); int inicializar_suma(); int limpiar_suma(); void test_suma(); #endif //CMAKEANDCUNIT_TEST_SUMA_H
lucasnvp/CMakeListDirectoryStructure
app/src/suma/suma.c
<gh_stars>0 // // Created by lucas on 11/06/19. // #include "suma.h" int suma () { return 5 + 5; }
lucasnvp/CMakeListDirectoryStructure
app/src/main.c
<gh_stars>0 #include <stdio.h> #include "suma/suma.h" int main() { printf("Hello, World!\n"); int result = suma(); printf("La suma es: %d", result); return 0; }
jusic/energiador
src/energiador.h
<reponame>jusic/energiador #ifndef ENERGIADOR_H #define ENERGIADOR_H #include <sailfishapp.h> #include "worker.h" class Energiador : public QObject { Q_OBJECT Controller* contr; QTimer* timer; QVariantList* list; public: Energiador() { contr = new Controller; timer = new QTimer(this); list = new QVariantList(); contr->connect(contr, SIGNAL(resultReady(float,float,float)), this, SLOT(putresult(float,float,float))); timer->connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(250); //QDateTime endDate(QDate(2012, 7, 7), QTime(16, 30, 0)); } ~Energiador() { timer->stop(); delete timer; delete contr; delete list; } public slots: void update() { contr->operate(); } void putresult(float voltage, float current, float power) { static int count = 0; QString result = QString("P: ") + QString::number(voltage * current) + " W\n" "U: " + QString::number(voltage) + " V\n" "I: " + QString::number(current * 1000.) + " mA\n"; QVariantMap map; map.insert("date", QDateTime::currentDateTime()); map.insert("power", power); *list << map; // store only ~30s worth of data (120 data points) if (list->length() > 60*4*0.5) { list->pop_front(); } emit resultReady(result); if (count++ % 4 == 0) { // update gui only every 4th value emit updateList(*list); } } signals: void resultReady(const QString & result); void updateList(const QVariantList & list); }; #endif // ENERGIADOR_H
jusic/energiador
src/worker.h
#ifndef WORKER_H #define WORKER_H #include <QtQuick> #include <sailfishapp.h> class BatteryWorker : public QObject { Q_OBJECT QThread workerThread; public slots: void checkBatteryStatus() { // crude hacks to get instant data from the power sensor QFile f("/sys/devices/LNXSYSTM:00/device:00/PNP0A03:00/PNP0C0A:00/power_supply/BAT0"); if (f.exists()) { QProcess p; //p.start("sh", QStringList() << "-c" << "upower -d | grep updated; upower -d | grep rate"); p.start("sh", QStringList() << "-c" << "cat /sys/devices/LNXSYSTM:00/device:00/PNP0A03:00/PNP0C0A:00/power_supply/BAT0/power_now"); p.waitForFinished(-1); QString p_stdout = p.readAllStandardOutput(); QString p_stderr = p.readAllStandardError(); p.start("sh", QStringList() << "-c" << "cat /sys/devices/LNXSYSTM:00/device:00/PNP0A03:00/PNP0C0A:00/power_supply/BAT0/voltage_now"); p.waitForFinished(-1); QString p_stdout2 = p.readAllStandardOutput(); QString p_stderr2 = p.readAllStandardError(); float voltage = p_stdout2.toFloat() / 1e6; float power = p_stdout.toFloat() / 1e6; emit resultReady(voltage, power/voltage, power); } else { qDebug("reading"); QProcess p; //p.start("sh", QStringList() << "-c" << "upower -d | grep updated; upower -d | grep rate"); p.start("sh", QStringList() << "-c" << "cat /sys/devices/platform/msm_ssbi.0/pm8038-core/pm8921-charger/power_supply/battery/current_now"); p.waitForFinished(-1); QString p_stdout = p.readAllStandardOutput(); QString p_stderr = p.readAllStandardError(); p.start("sh", QStringList() << "-c" << "cat /sys/devices/platform/msm_ssbi.0/pm8038-core/pm8921-charger/power_supply/battery/voltage_now"); p.waitForFinished(-1); QString p_stdout2 = p.readAllStandardOutput(); QString p_stderr2 = p.readAllStandardError(); qDebug("reading done"); float voltage = p_stdout2.toFloat() / 1e6; float current = p_stdout.toFloat() / 1e6; emit resultReady(voltage, current, voltage*current); } } signals: void resultReady(float voltage, float current, float power); }; class Controller : public QObject { Q_OBJECT QThread workerThread; public: Controller() { BatteryWorker *worker = new BatteryWorker; worker->moveToThread(&workerThread); connect(this, SIGNAL(operate()), worker, SLOT(checkBatteryStatus())); connect(worker, SIGNAL(resultReady(float,float,float)), this, SLOT(handleResults(float,float,float))); workerThread.start(); } ~Controller() { workerThread.quit(); workerThread.wait(); } public slots: void handleResults(float v, float c, float p) { //qDebug("update"); //qDebug("%s", result.toUtf8().constData()); emit resultReady(v,c,p); } signals: void operate(); void resultReady(float,float,float); }; #endif // WORKER_H
daohu527/mtrace
trace.h
<filename>trace.h #include <string> class Trace { public: Trace(); ~Trace(); std::string GenerateTraceId(); private: std::string trace_id; };
daohu527/mtrace
trace_id_holder.h
<filename>trace_id_holder.h #include <string> class TraceIdHolder { public: void set(std::string trace_id); std::string get(); private: std::string trace_id; };
DrCrypto/darkcoin
src/instantx.h
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef INSTANTX_H #define INSTANTX_H #include "bignum.h" #include "sync.h" #include "net.h" #include "key.h" #include "core.h" #include "util.h" #include "script.h" #include "hashblock.h" #include "base58.h" #include "main.h" using namespace std; using namespace boost; class CConsensusVote; class CTransaction; class CTransactionLock; static const int MIN_INSTANTX_PROTO_VERSION = 70047; extern map<uint256, CTransaction> mapTxLockReq; extern map<uint256, CTransactionLock> mapTxLocks; void ProcessMessageInstantX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); //check if we need to vote on this transaction void DoConsensusVote(CTransaction& tx, bool approved, int64 nBlockHeight); //process consensus vote message void ProcessConsensusVote(CConsensusVote& ctx); // keep transaction locks in memory for an hour void CleanTransactionLocksList(); class CConsensusVote { public: CTxIn vinMasternode; bool approved; uint256 txHash; std::vector<unsigned char> vchMasterNodeSignature; int nBlockHeight; bool SignatureValid(); bool Sign(); IMPLEMENT_SERIALIZE ( READWRITE(txHash); READWRITE(vinMasternode); READWRITE(approved); READWRITE(vchMasterNodeSignature); READWRITE(nBlockHeight); ) }; class CTransactionLock { public: int nBlockHeight; CTransaction tx; std::vector<CConsensusVote> vecConsensusVotes; bool SignaturesValid(); int CountSignatures(); bool AllInFavor(); void AddSignature(CConsensusVote cv); uint256 GetHash() { return tx.GetHash(); } IMPLEMENT_SERIALIZE ( READWRITE(tx); READWRITE(nBlockHeight); READWRITE(vecConsensusVotes); ) }; #endif
Midhun-MP/MMP_DeviceInfo
MMPDeviceInfo/MMPDeviceInfo.h
/*! * @file MMPDeviceInfo.h * @class MMPDeviceInfo * MMPDeviceInfo * @author Created by Midhun on 13/01/15. * @copyright Copyright (c) 2015 Midhun. All rights reserved. * @discussion This class can be used for getting the details of the iOS device/Simulator */ #import <UIKit/UIKit.h> #pragma mark - Constants & Enums - /*! * Enum defines the available device types */ typedef NS_ENUM(NSInteger, DeviceType) { /*! * Device Type Unknown */ DeviceTypeUnknown = 0, /*! * Device Type iPad */ DeviceTypeiPad, /*! * Device Type iPhone */ DeviceTypeiPhone }; #pragma mark - Interface - @interface MMPDeviceInfo : NSObject #pragma mark - Device Info - /*! * Returns the platform information * @code * [MMPDeviceInfo getPlatformInfo]; * @endcode * @return NSString - Platform info */ + (NSString *)getPlatformInfo; /*! * Returns the OS Version * @code * [MMPDeviceInfo getDeviceOSInfo]; * @endcode * @return NSString - OS Version info */ + (NSString *)getDeviceOSInfo; /*! * Returns the device name specified in the settings app * @code * [MMPDeviceInfo getDeviceName]; * @endcode * @return NSString - Device Name */ + (NSString *)getDeviceName; /*! * Returns the model info * @code * [MMPDeviceInfo getModelInfo]; * @endcode * @return NSString - Value specifies the model information */ + (NSString *)getModelInfo; /*! * Returns the device type, iPad or iPhone * @code * [MMPDeviceInfo getDeviceType]; * @endcode * @return DeviceType - Enum value specifies whether it's an iPad or iPhone */ + (DeviceType)getDeviceType; #pragma mark - App Info - /*! * Returns the app name * @code * [MMPDeviceInfo getAppName]; * @endcode * @return NSString - Name of the application */ + (NSString *)getAppName; /*! * Returns the app version * @code * [MMPDeviceInfo getAppVersion]; * @endcode * @return NSString - Version of the application */ + (NSString *)getAppVersion; #pragma mark - Utility - /*! * Returns the details of device * @code * [MMPDeviceInfo getDeviceDetails]; * @endcode * @return NSDictionary - Contains all the details of device */ + (NSDictionary *)getDeviceDetails; /*! * Returns the details of application * @code * [MMPDeviceInfo getAppDetails]; * @endcode * @return NSDictionary - Contains all the details of application */ + (NSDictionary *)getAppDetails; /*! * Returns the all the details of device and application * @code * [MMPDeviceInfo getAllDetails]; * @endcode * @return NSDictionary - Contains all the details of device and application */ + (NSDictionary *)getAllDetails; @end
miyamotok0105/deeplearning-learning-sample
src/cuda_sample/sample1/sample.h
#ifndef SAMPLE_H #define SAMPLE_H void cuda_kernel_exec(int n); #endif /* SAMPLE_H */
miyamotok0105/deeplearning-learning-sample
src/cuda_sample/sample1/cuda_main.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <unistd.h> #include "sample.h" double gettimeofday_sec() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec * 1e-6; } int main(int argc, char *argv[]) { double t1,t2; int n = 100; if (argc > 1) { n = atoi( argv[1] ); } printf("n: %d\n", n); t1 = gettimeofday_sec(); cuda_kernel_exec(n); t2 = gettimeofday_sec(); printf("elapsed: %f sec.\n", t2-t1); return 0; }
bspar/eth-privatenet
tricky/oracle.c
/* * Inspired by https://jansson.readthedocs.io/en/latest/_downloads/github_commits.c * (MIT license) */ #define _GNU_SOURCE #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <sys/syscall.h> #include <jansson.h> #include <curl/curl.h> // I hate using so many escapes - effectively replaces "" delim with () // Using __VA_ARGS__ works around the comma/arg "problem" #define S(...) #__VA_ARGS__ #define BUFFER_SIZE (256 * 1024) /* 256 KB */ #define URL "http://public-node:8545/" #define FLAG1_LOC "flag1" #define DEBUG 1 #define NEWGUESS_TOPIC "0x8b4a1da1e9d54b88ebafc9ce4677a2ca4196693b1c8500b9d1fc58d96553c5fd" #define UPGRADE_TOPIC "0x450db8da6efbe9c22f2347f7c2021231df1fc58d3ae9a2fa75d39fa446199305" #define PUBLISH_HASH "0x979ea13b" #define GETCHAL_HASH "0x759014f0" #define SETFLAG_HASH "0x3438e82c" void error(const char *msg) { printf("Error: %s\n", msg); fflush(stdout); // exit(-1); } void debugfmt(const char *fmt, const char *arg) { if(DEBUG) { printf(fmt, arg); putchar('\n'); fflush(stdout); } } struct write_result { char *data; int pos; }; char *atohex(const char *ascii) { char *result = malloc(strlen(ascii)*2+4); result[0] = '0'; result[1] = 'x'; for(int i=0; i<strlen(ascii); i++) { sprintf(result+(i*2+2), "%x", ascii[i]); } return result; } char *btohex(char *data, int len) { char *result = malloc(len*2+5); result[0] = '0'; result[1] = 'x'; for(int i=0; i<len; i++) { sprintf(result+(i*2+2), "%02x", (unsigned)data[i]&0xffU); } result[len*2+3] = '\0'; return result; } int bincmp(char *data1, char *data2, int len) { for(int i=0; i<len; i++) { if(data1[i] != data2[i]) return 0; } return 1; } static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream) { struct write_result *result = (struct write_result *)stream; if(result->pos + size * nmemb >= BUFFER_SIZE - 1) { fprintf(stderr, "error: too small buffer\n"); return 0; } memcpy(result->data + result->pos, ptr, size * nmemb); result->pos += size * nmemb; return size * nmemb; } char *post(char *url, char *postdata) { CURL *curl = NULL; CURLcode status; struct curl_slist *headers = NULL; char *data = NULL; long code; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (!curl) error("Cannot init curl instance"); data = malloc(BUFFER_SIZE); if(!data) error("Cannot malloc data"); struct write_result write_result = { .data = data, .pos = 0 }; headers = curl_slist_append(headers, "content-type: application/json;"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, URL); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(postdata)); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result); status = curl_easy_perform(curl); if(status != 0) { fprintf(stderr, "error: unable to request data from %s:\n", url); fprintf(stderr, "%s\n", curl_easy_strerror(status)); error("Can't perform curl, bailing"); } curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code); if(code != 200) { fprintf(stderr, "error: server responded with code %ld\n", code); data[write_result.pos] = '\0'; debugfmt("data: %s", data); error("RPC error code, bailing"); } curl_easy_cleanup(curl); curl_slist_free_all(headers); curl_global_cleanup(); /* zero-terminate the result */ data[write_result.pos] = '\0'; debugfmt("sent: %s", postdata); debugfmt("recv: %s", data); return data; } char *getContractAddress() { FILE *fp = fopen("/root/shared/contract.txt", "r"); if(!fp) { error("Cannot get contract address from /root/shared/contract.txt"); return 0; } char *addr = malloc(128); fgets(addr, 128, fp); addr[strcspn(addr, "\r\n")] = 0; fclose(fp); return addr; } char *getMyAddress() { FILE *fp = fopen("/root/shared/account.txt", "r"); if(!fp) { error("Cannot get my address from /root/shared/account.txt"); return 0; } char *addr = malloc(128); fgets(addr, 128, fp); addr[strcspn(addr, "\r\n")] = 0; fclose(fp); return addr; } void getVersion() { char *data = S({"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":420}); char *text = post(URL, data); if(!text) error("Got no response from curl"); } const char *getSha3(char *data) { json_t *sha3, *root; json_error_t err; char *text; data = atohex(data); char *postdata = malloc(sizeof(char) * 256); if(!postdata) error("Cannot malloc postdata"); snprintf(postdata, sizeof(char)*256, S({"jsonrpc":"2.0","method":"web3_sha3","params":["%s"],"id":420}), data); text = post(URL, postdata); if(!text) error("Got no response from curl"); free(postdata); root = json_loads(text, 0, &err); free(text); sha3 = json_object_get(root, "result"); return json_string_value(sha3); } // returns account string char *unlockAccount(char *password) { FILE *fp = fopen("/root/shared/account.txt", "r"); if(!fp) { error("Cannot get address from /root/shared/account.txt"); return 0; } char *buf = malloc(sizeof(char) * 128); char *postdata = malloc(sizeof(char) * 256); fgets(buf, 68, fp); buf[strcspn(buf, "\r\n")] = 0; snprintf(postdata, sizeof(char)*256, S({"jsonrpc":"2.0","method":"personal_unlockAccount","params":["%s","%s"],"id":420}), buf, password); post(URL, postdata); free(postdata); fclose(fp); return buf; } char *getFunc(char *funcname) { char *func = malloc(sizeof(char) * 12); char *sha3 = getSha3(funcname); snprintf(func, 11, "%s", sha3); return func; } char *publishChallenge(char *myaddr, char *contaddr, char *secretsha3) { char *postdata = malloc(sizeof(char) * 512); char *randomdata = malloc(32); syscall(SYS_getrandom, randomdata, 32, 0); // docker doesn't have modern glibc char *randomhex = btohex(randomdata, 32)+2; // don't want '0x' snprintf(postdata, sizeof(char)*512, S({"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"%s", \ "to":"%s", "gasPrice":"0x430E23400", "data":"%s%s%s"}],"id":420}), myaddr, contaddr, PUBLISH_HASH, secretsha3+2, randomhex); post(URL, postdata); free(postdata); free(randomhex-2); return randomdata; } char *installFilter(char *topic, char *contaddr) { char *postdata = malloc(sizeof(char) * 1024); char *data; json_t *filterID, *root; json_error_t err; snprintf(postdata, sizeof(char)*1024, S({"jsonrpc":"2.0","method":"eth_newFilter","params":[{"address": \ "%s", "topics":["%s"], "fromBlock":"latest",\ "toBlock":"latest"}],"id":420}), contaddr, topic); data = post(URL, postdata); free(postdata); root = json_loads(data, 0, &err); free(data); filterID = json_object_get(root, "result"); return json_string_value(filterID); } json_t *getEvents(char *filterID) { char *postdata = malloc(sizeof(char) * 1024); char *data; json_t *root; json_error_t err; snprintf(postdata, sizeof(char)*1024, S({"jsonrpc":"2.0","method":"eth_getFilterChanges",\ "params":["%s"],"id":420}), filterID); data = post(URL, postdata); free(postdata); root = json_loads(data, 0, &err); free(data); return json_object_get(root, "result"); } char *getChallenge(char *contaddr, char *myaddr) { char *postdata = malloc(sizeof(char) * 1024); char *data; char *chal = malloc(sizeof(char) * 36); json_t *root; json_error_t err; snprintf(postdata, sizeof(char)*1024, S({"jsonrpc":"2.0", "method":"eth_call", "params":[{"from": \ "%s", "to": "%s", "data":"%s"}, "latest"], "id":420}), myaddr, contaddr, GETCHAL_HASH); data = post(URL, postdata); free(postdata); root = json_loads(data, 0, &err); free(data); data = json_string_value(json_object_get(root, "result")); for(int j=0; j<(strlen(data)/2-2); j++) { sscanf(data+(j*2+2), "%02hhx", chal+j); } json_decref(root); return chal; } int doGuessEvents(char *guessID, char *contaddr, char *myaddr, char *randomdata) { json_t *logs = getEvents(guessID); json_t *record; int i=0, j=0; char *data; char guess[36]; for(i=0; i<json_array_size(logs); i++) { record = json_array_get(logs, i); data = json_string_value(json_object_get(record, "data")); debugfmt("got a log: %s", data); for(j=0; j<(strlen(data)/2-2); j++) { sscanf(data+(j*2+2), "%02hhx", guess+j); } debugfmt("Sanity check log: %s", guess); if(bincmp(getChallenge(contaddr, myaddr), guess, 32)) { error("Someone won by brute force!"); return 1; } else { error("Someone won a challenge from a different publisher"); return 2; } } json_decref(logs); return 0; } void setFlag(char *location) { char *postdata = malloc(sizeof(char) * 1024); char dataIndex[65] = "0000000000000000000000000000000000000000000000000000000000000020"; char dataLen[65]; char rightPadding[65]; char *contaddr = getContractAddress(); char *myaddr = getMyAddress(); FILE *fp = fopen(location, "r"); if(!fp) { error("Cannot open flag1 or flag2"); exit(-1); } char *buf = malloc(sizeof(char) * 128); fgets(buf, 128, fp); buf[strcspn(buf, "\r\n")] = 0; snprintf(dataLen, 65, "00000000000000000000000000000000000000000000000000000000000000%02x", (unsigned int) strlen(buf)); for(int i=0; i<(32-strlen(buf)%32); i++) { rightPadding[i*2] = '0'; rightPadding[i*2+1] = '0'; } rightPadding[2*(32-strlen(buf)%32)] = '\0'; snprintf(postdata, sizeof(char)*1024, S({"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"%s", \ "to":"%s", "gasPrice":"0x430E23400", "data":"%s%s%s%s%s"}],"id":420}), myaddr, contaddr, SETFLAG_HASH, dataIndex, dataLen, atohex(buf)+2, rightPadding); post(URL, postdata); fclose(fp); free(buf); free(postdata); } char *doUpgradeEvents(char *guessID) { json_t *logs = getEvents(guessID); json_t *record; char *data; char *newcontaddr = 0; for(int i=0; i<json_array_size(logs); i++) { newcontaddr = malloc(68); record = json_array_get(logs, i); data = json_string_value(json_object_get(record, "data")); snprintf(newcontaddr, 68, "0x%s", data+26); debugfmt("got an upgrade request: %s", newcontaddr); } json_decref(logs); return newcontaddr; } void uninstallFilter(char *filterID) { char *postdata = malloc(sizeof(char) * 512); char *data; snprintf(postdata, sizeof(char)*512, S({"jsonrpc":"2.0","method":"eth_uninstallFilter","params":["%s"],"id":420}), filterID); free(post(URL, postdata)); free(postdata); return; } int main(int argc, char *argv[]) { const char *sha3; char *guessID, *upgradeID, *randomdata; char *contaddr = getContractAddress(); char *newcontaddr = 0; getVersion(); if(argc != 2) { error("usage: oracle SECRET"); exit(-1); } char *myaddr = unlockAccount(argv[1]); randomdata = publishChallenge(myaddr, contaddr, getSha3(argv[1])); debugfmt("filter topic 1: %s", NEWGUESS_TOPIC); debugfmt("filter topic 2: %s", UPGRADE_TOPIC); guessID = installFilter(NEWGUESS_TOPIC, contaddr); upgradeID = installFilter(UPGRADE_TOPIC, contaddr); for(int i=0; i < 18; i++) { sleep(10); if(doGuessEvents(guessID, contaddr, myaddr, randomdata)) { setFlag(FLAG1_LOC); } newcontaddr = doUpgradeEvents(upgradeID); if(newcontaddr) { free(contaddr); contaddr = newcontaddr; i = 0; debugfmt("Upgrading to new contract: %s", contaddr); guessID = installFilter(NEWGUESS_TOPIC, contaddr); upgradeID = installFilter(UPGRADE_TOPIC, contaddr); myaddr = unlockAccount(argv[1]); randomdata = publishChallenge(myaddr, contaddr, getSha3(argv[1])); newcontaddr = 0; } } // !!!! remove filter !!!! return 0; }
diablax2/bts
src/leveldb/include/leveldb/table.h
// Copyright (c) 2011 The LevelDB Authors. All rigBTS reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #ifndef STORAGE_LEVELDB_INCLUDE_TABLE_H_ #define STORAGE_LEVELDB_INCLUDE_TABLE_H_ #include <stdint.h> #include "leveldb/iterator.h" namespace leveldb { class Block; class BlockHandle; class Footer; struct Options; class RandomAccessFile; struct ReadOptions; class TableCache; // A Table is a sorted map from strings to strings. Tables are // immutable and persistent. A Table may be safely accessed from // multiple threads without external synchronization. class Table { public: // Attempt to open the table that is stored in bytes [0..file_size) // of "file", and read the metadata entries necessary to allow // retrieving data from the table. // // If successful, returns ok and sets "*table" to the newly opened // table. The client should delete "*table" when no longer needed. // If there was an error while initializing the table, sets "*table" // to NULL and returns a non-ok status. Does not take ownership of // "*source", but the client must ensure that "source" remains live // for the duration of the returned table's lifetime. // // *file must remain live while this Table is in use. static Status Open(const Options& options, RandomAccessFile* file, uint64_t file_size, Table** table); ~Table(); // Returns a new iterator over the table contents. // The result of NewIterator() is initially invalid (caller must // call one of the Seek methods on the iterator before using it). Iterator* NewIterator(const ReadOptions&) const; // Given a key, return an approximate byte offset in the file where // the data for that key begins (or would begin if the key were // present in the file). The returned value is in terms of file // bytes, and so includes effects like compression of the underlying data. // E.g., the approximate offset of the last key in the table will // be close to the file length. uint64_t ApproximateOffsetOf(const Slice& key) const; private: struct Rep; Rep* rep_; explicit Table(Rep* rep) { rep_ = rep; } static Iterator* BlockReader(void*, const ReadOptions&, const Slice&); // Calls (*handle_result)(arg, ...) with the entry found after a call // to Seek(key). May not make such a call if filter policy says // that key is not present. friend class TableCache; Status InternalGet( const ReadOptions&, const Slice& key, void* arg, void (*handle_result)(void* arg, const Slice& k, const Slice& v)); void ReadMeta(const Footer& footer); void ReadFilter(const Slice& filter_handle_value); // No copying allowed Table(const Table&); void operator=(const Table&); }; } // namespace leveldb #endif // STORAGE_LEVELDB_INCLUDE_TABLE_H_
nieldk/updiprog
link.h
#ifndef LINK_H #define LINK_H #include <stdint.h> #include <stdbool.h> uint8_t LINK_ldcs(uint8_t address); void LINK_stcs(uint8_t address, uint8_t value); bool LINK_Init(char *port, uint32_t baudrate, bool onDTR); bool LINK_SendKey(char *key, uint8_t size); uint8_t LINK_ld(uint16_t address); bool LINK_st(uint16_t address, uint8_t value); bool LINK_st16(uint16_t address, uint16_t value); void LINK_Repeat(uint16_t repeats); bool LINK_ld_ptr_inc(uint8_t *data, uint8_t size); bool LINK_ld_ptr_inc16(uint8_t *data, uint16_t words); bool LINK_st_ptr(uint16_t address); bool LINK_st_ptr_inc(uint8_t *data, uint16_t len); bool LINK_st_ptr_inc16(uint8_t *data, uint16_t len); #endif
nieldk/updiprog
app.c
#include <stdio.h> #include <unistd.h> #include "devices.h" #include "link.h" #include "log.h" #include "sleep.h" #include "updi.h" void APP_Reset(bool apply_reset) { //Applies or releases an UPDI reset condition if (apply_reset == true) { LOG_Print(LOG_LEVEL_INFO, "Apply reset"); LINK_stcs(UPDI_ASI_RESET_REQ, UPDI_RESET_REQ_VALUE); } else { LOG_Print(LOG_LEVEL_INFO, "Release reset"); LINK_stcs(UPDI_ASI_RESET_REQ, 0x00); } } bool APP_InProgMode(void) { //Checks whether the NVM PROG flag is up if (LINK_ldcs(UPDI_ASI_SYS_STATUS) & (1 << UPDI_ASI_SYS_STATUS_NVMPROG)) return true; return false; } bool APP_WaitUnlocked(uint16_t timeout_ms) { //Waits for the device to be unlocked. //All devices boot up as locked until proven otherwise while (timeout_ms-- > 0) { msleep(1); if (!(LINK_ldcs(UPDI_ASI_SYS_STATUS) & (1 << UPDI_ASI_SYS_STATUS_LOCKSTATUS))) return true; } LOG_Print(LOG_LEVEL_WARNING, "Timeout by waiting for device to unlock"); return false; } bool APP_EnterProgmode(void) { //Enters into NVM programming mode uint8_t key_status; //First check if NVM is already enabled if (APP_InProgMode() == true) { LOG_Print(LOG_LEVEL_WARNING, "Already in NVM programming mode"); return true; } LOG_Print(LOG_LEVEL_WARNING, "Entering NVM programming mode"); // Put in the key LINK_SendKey(UPDI_KEY_NVM, UPDI_KEY_64); // Check key status key_status = LINK_ldcs(UPDI_ASI_KEY_STATUS); LOG_Print(LOG_LEVEL_INFO, "Key status = 0x%02X", key_status); if (!(key_status & (1 << UPDI_ASI_KEY_STATUS_NVMPROG))) { LOG_Print(LOG_LEVEL_WARNING, "Key not accepted"); return false; } // Toggle reset APP_Reset(true); APP_Reset(false); // And wait for unlock if (!APP_WaitUnlocked(100)) { LOG_Print(LOG_LEVEL_ERROR, "Failed to enter NVM programming mode: device is locked"); return false; } // Check for NVMPROG flag if (APP_InProgMode() == false) { LOG_Print(LOG_LEVEL_ERROR, "Failed to enter NVM programming mode"); return false; } LOG_Print(LOG_LEVEL_INFO, "Now in NVM programming mode"); return true; } void APP_LeaveProgmode(void) { //Disables UPDI which releases any keys enabled LOG_Print(LOG_LEVEL_WARNING, "Leaving NVM programming mode"); APP_Reset(true); APP_Reset(false); LINK_stcs(UPDI_CS_CTRLB, (1 << UPDI_CTRLB_UPDIDIS_BIT) | (1 << UPDI_CTRLB_CCDETDIS_BIT)); } bool APP_Unlock(void) { //Unlock and erase uint8_t key_status; // Put in the key LINK_SendKey(UPDI_KEY_CHIPERASE, UPDI_KEY_64); // Check key status key_status = LINK_ldcs(UPDI_ASI_KEY_STATUS); LOG_Print(LOG_LEVEL_INFO, "Key status = 0x%02X", key_status); if (!(key_status & (1 << UPDI_ASI_KEY_STATUS_CHIPERASE))) { LOG_Print(LOG_LEVEL_WARNING, "Key not accepted"); return false; } // Toggle reset APP_Reset(true); APP_Reset(false); // And wait for unlock if (!APP_WaitUnlocked(100)) { LOG_Print(LOG_LEVEL_ERROR, "Failed to chip erase using key!"); return false; } return true; } bool APP_WaitFlashReady(void) { //Waits for the NVM controller to be ready uint8_t status; uint16_t timeout = 10000; // 10 sec timeout, just to be sure LOG_Print(LOG_LEVEL_INFO, "Wait flash ready"); while (timeout-- > 0) { msleep(1); status = LINK_ld(DEVICES_GetNvmctrlAddress() + UPDI_NVMCTRL_STATUS); if (status & (1 << UPDI_NVM_STATUS_WRITE_ERROR)) { LOG_Print(LOG_LEVEL_ERROR, "NVM error"); return false; } if (!(status & ((1 << UPDI_NVM_STATUS_EEPROM_BUSY) | (1 << UPDI_NVM_STATUS_FLASH_BUSY)))) return true; } LOG_Print(LOG_LEVEL_WARNING, "Waiting for flash ready timed out"); return false; } bool APP_ExecuteNvmCommand(uint8_t command) { //Executes an NVM COMMAND on the NVM CTRL //self.logger.info("NVMCMD {:d} executing".format(command)) LOG_Print(LOG_LEVEL_INFO, "NVMCMD %d executing", command); return LINK_st(DEVICES_GetNvmctrlAddress() + UPDI_NVMCTRL_CTRLA, command); } bool APP_ChipErase(void) { // Does a chip erase using the NVM controller // Note that on locked devices this it not possible // and the ERASE KEY has to be used instead LOG_Print(LOG_LEVEL_INFO, "Chip erase using NVM CTRL"); // Wait until NVM CTRL is ready to erase if (!APP_WaitFlashReady()) { LOG_Print(LOG_LEVEL_WARNING, "Timeout waiting for flash ready before erase "); return false; } // Erase APP_ExecuteNvmCommand(UPDI_NVMCTRL_CTRLA_CHIP_ERASE); // And wait for it if (!APP_WaitFlashReady()) { LOG_Print(LOG_LEVEL_WARNING, "Timeout by waiting for flash ready after erase"); return false; } return true; } bool APP_WriteDataWords(uint16_t address, uint8_t *data, uint16_t len) { //Writes a number of words to memory uint16_t value; // Special-case of 1 word if (len == 2) { value = (uint16_t)data[0] + (data[1] << 8); return LINK_st16(address, value); } // Range check if (len > (UPDI_MAX_REPEAT_SIZE + 1) << 1) { LOG_Print(LOG_LEVEL_WARNING, "Invalid length"); return false; } // Store the address LINK_st_ptr(address); // Fire up the repeat LINK_Repeat(len >> 1); return LINK_st_ptr_inc16(data, len); } bool APP_WriteData(uint16_t address, uint8_t *data, uint16_t len) { //Writes a number of bytes to memory // Special case of 1 byte if (len == 1) return LINK_st(address, data[0]); // Special case of 2 byte if (len == 2) { LINK_st(address, data[0]); return LINK_st(address + 1, data[1]); } // Range check if (len > (UPDI_MAX_REPEAT_SIZE + 1)) { LOG_Print(LOG_LEVEL_WARNING, "Invalid length"); return false; } // Store the address LINK_st_ptr(address); // Fire up the repeat LINK_Repeat(len); return LINK_st_ptr_inc(data, len); } bool APP_WriteNvm(uint16_t address, uint8_t *data, uint16_t len, bool use_word_access) { //Writes a page of data to NVM.APP_ExecuteNvmCommand //By default the PAGE_WRITE command is used, which //requires that the page is already erased. //By default word access is used (flash) // Check that NVM controller is ready if (!APP_WaitFlashReady()) { LOG_Print(LOG_LEVEL_WARNING, "Timeout by waiting for flash ready before page buffer clear "); return false; } // Clear the page buffer LOG_Print(LOG_LEVEL_INFO, "Clear page buffer"); APP_ExecuteNvmCommand(UPDI_NVMCTRL_CTRLA_PAGE_BUFFER_CLR); // Waif for NVM controller to be ready if (!APP_WaitFlashReady()) { LOG_Print(LOG_LEVEL_WARNING, "Timeout by waiting for flash ready after page buffer clear"); return false; } // Load the page buffer by writing directly to location if (use_word_access == true) APP_WriteDataWords(address, data, len); else APP_WriteData(address, data, len); // Write the page to NVM, maybe erase first LOG_Print(LOG_LEVEL_INFO, "Committing page"); APP_ExecuteNvmCommand(UPDI_NVMCTRL_CTRLA_WRITE_PAGE); // Wait for NVM controller to be ready again if (!APP_WaitFlashReady()) { LOG_Print(LOG_LEVEL_WARNING, "Timeout by waiting for flash ready after page write"); return false; } return true; } bool APP_ReadData(uint16_t address, uint8_t *data, uint16_t size) { //Reads a number of bytes of data from UPDI LOG_Print(LOG_LEVEL_INFO, "Reading %d bytes from 0x%04X", size, address); // Range check if (size > UPDI_MAX_REPEAT_SIZE + 1) { LOG_Print(LOG_LEVEL_ERROR, "Cant read that many bytes in one go"); return false; } // Store the address LINK_st_ptr(address); // Fire up the repeat if (size > 1) LINK_Repeat(size); // Do the read(s) return LINK_ld_ptr_inc(data, size); } bool APP_ReadDataWords(uint16_t address, uint8_t *data, uint16_t words) { //Reads a number of words of data from UPDI LOG_Print(LOG_LEVEL_INFO, "Reading %d words from 0x%04X", words, address); // Range check if (words > (UPDI_MAX_REPEAT_SIZE >> 1) + 1) { LOG_Print(LOG_LEVEL_ERROR, "Cant read that many words in one go"); return false; } // Store the address LINK_st_ptr(address); // Fire up the repeat if (words > 1) { LINK_Repeat(words); } // Do the read return LINK_ld_ptr_inc16(data, words); }
nieldk/updiprog
sleep.c
<reponame>nieldk/updiprog<gh_stars>10-100 #include "sleep.h" void msleep(uint32_t msec) { #ifdef __MINGW32__ SleepEx(msec, false); #endif // __MINGW32__ #ifdef __linux usleep(msec*1000); #endif // __linux }
nieldk/updiprog
phy.c
<filename>phy.c #include <unistd.h> #include "com.h" #include "log.h" #include "phy.h" #include "updi.h" #include "sleep.h" /** \brief Initialize physical interface * * \param [in] port Port name as string * \param [in] baudrate Transmission baudrate * \param [in] onDTR True if using DTR for power * \return true if success * */ bool PHY_Init(char *port, uint32_t baudrate, bool onDTR) { return COM_Open(port, baudrate, true, true); } /** \brief Sends a double break to reset the UPDI port * BREAK is actually just a slower zero frame * A double break is guaranteed to push the UPDI state * machine into a known state, albeit rather brutally * * \param [in] port Port name as string * \return true if success * */ bool PHY_DoBreak(char *port) { uint8_t buf[] = {UPDI_BREAK, UPDI_BREAK}; LOG_Print(LOG_LEVEL_INFO, "Sending double break"); COM_Close(); // Re-init at a lower baudrate // At 300 bauds, the break character will pull the line low for 30ms // Which is slightly above the recommended 24.6ms // no parity, one stop bit if (COM_Open(port, 300, false, false) != true) return false; // Send two break characters, with 1 stop bit in between COM_Write(buf, sizeof(buf)); // Wait for the double break end msleep(1000); // wait for 1 second if (COM_Read(buf, 2) != 2) LOG_Print(LOG_LEVEL_WARNING, "No answer received"); COM_Close(); return true; } /** \brief Send data to physical interface * * \param [in] data Buffer with data * \param [in] len Length of data buffer * \return true if success * */ bool PHY_Send(uint8_t *data, uint8_t len) { //uint8_t i; /*for (i = 0; i < len; i++) { COM_Write(&data[i], 1); }*/ COM_Write(data, len); // read echo //usleep(10); //msleep(COM_GetTransTime(len)); //Sleep(10); COM_Read(data, len); return true; } /** \brief Receive data from physical interface to data buffer * * \param [out] data Data buffer to write data in * \param [in] len Length of data to be received * \return true if success * */ bool PHY_Receive(uint8_t *data, uint16_t len) { int val = COM_Read(data, len); if ((val < 0) || (val != len)) return false; return true; } /** \brief Close physical interface * * \return Nothing * */ void PHY_Close(void) { COM_Close(); }
nieldk/updiprog
app.h
<reponame>nieldk/updiprog<filename>app.h #ifndef APP_H #define APP_H #include <stdint.h> #include <stdbool.h> bool APP_EnterProgmode(void); void APP_LeaveProgmode(void); bool APP_WaitFlashReady(void); bool APP_Unlock(void); bool APP_ChipErase(void); bool APP_ReadDataWords(uint16_t address, uint8_t *data, uint16_t words); bool APP_WriteData(uint16_t address, uint8_t *data, uint16_t len); bool APP_WriteNvm(uint16_t address, uint8_t *data, uint16_t len, bool use_word_access); #endif
nieldk/updiprog
log.h
<reponame>nieldk/updiprog<filename>log.h #ifndef LOG_H #define LOG_H #include <stdint.h> enum { LOG_LEVEL_INFO, LOG_LEVEL_WARNING, LOG_LEVEL_ERROR, LOG_LEVEL_LAST }; void LOG_Print(uint8_t level, char *msg, ...); void LOG_SetLevel(uint8_t level); #endif
nieldk/updiprog
sleep.h
<gh_stars>10-100 #ifndef SLEEP_H #define SLEEP_H #include <stdint.h> #include <stdbool.h> #ifdef __MINGW32__ #include <windows.h> #include <unistd.h> #endif // __MINGW32__ #ifdef __linux #include <unistd.h> #endif // __linux void msleep(uint32_t usec); #endif
nieldk/updiprog
ihex.c
<reponame>nieldk/updiprog #include <stdio.h> #include <ctype.h> #include <string.h> #include "ihex.h" static uint8_t crc; /** \brief Convert byte to string with HEX representation * * \param [in] byte One byte of data * \return HEX representation as string * */ static char* IHEX_AddByte(uint8_t byte) { static char res[3]; crc += byte; uint8_t n = (byte & 0xF0U) >> 4; // high nybble res[0] = IHEX_DIGIT(n); n = byte & 0x0FU; // low nybble res[1] = IHEX_DIGIT(n); res[2] = 0; return res; } /** \brief Write Intel HEX ending to a file * * \param [in] fp File handle * \return true if succeed * */ bool IHEX_WriteEnd(FILE *fp) { fwrite(IHEX_ENDFILE, strlen(IHEX_ENDFILE), 1, fp); fwrite(IHEX_NEWLINE, strlen(IHEX_NEWLINE), 1, fp); return true; } /** \brief Write data buffer to HEX file * * \param [in] fp File handle * \param [in] data Data buffer to write * \param [in] len Length of data buffer * \return error code as uint8_t * */ uint8_t IHEX_WriteFile(FILE *fp, uint8_t *data, uint16_t len) { uint16_t i; uint8_t x; uint8_t width; char str[128]; crc = 0; for (i = 0; i < len; i += IHEX_LINE_LENGTH) { strcpy(str, IHEX_START); // write length if (len - i >= IHEX_LINE_LENGTH) width = IHEX_LINE_LENGTH; else width = (uint8_t)(len - i); strcat(str, IHEX_AddByte(width)); // write address strcat(str, IHEX_AddByte((uint8_t)(i >> 8))); strcat(str, IHEX_AddByte((uint8_t)i)); // write type (data) strcat(str, IHEX_AddByte(IHEX_DATA_RECORD)); for (x = 0; x < width; x++) { strcat(str, IHEX_AddByte(*data++)); } crc = (uint8_t)(0x100 - crc); strcat(str, IHEX_AddByte(crc)); strcat(str, IHEX_NEWLINE); fwrite(str, strlen(str), 1, fp); crc = 0; } IHEX_WriteEnd(fp); return IHEX_ERROR_NONE; } /** \brief Get one nibble from char * * \param [in] c Char value * \return data nibble as uint8_t * */ uint8_t IHEX_GetNibble(char c) { if (c >= '0' && c <= '9') return (uint8_t)(c - '0'); else if (c >= 'A' && c <= 'F') return (uint8_t)(c - 'A' + 10); else if (c >= 'a' && c <= 'f') return (uint8_t)(c - 'a' + 10); else return 0; } /** \brief Get full byte from two chars * * \param [in] data Two chars as HEX representation * \return byte value as uint8_t * */ uint8_t IHEX_GetByte(char *data) { uint8_t res = IHEX_GetNibble(*data++) << 4; res += IHEX_GetNibble(*data); return res; } /** \brief Read Intel HEX file to a binary memory buffer * * \param [in] fp File handler * \param [out] data Data buffer to read data into * \param [in] maxlen Maximal data length * \param [out] max_addr Maximal address with non-empty data * \return error code as uint8_t * */ uint8_t IHEX_ReadFile(FILE *fp, uint8_t *data, uint16_t maxlen, uint16_t *max_addr) { uint16_t addr; uint8_t len; uint8_t type; uint16_t segment; uint8_t i; uint8_t byte; char str[128]; char *end; addr = 0; segment = 0; while (!feof(fp)) { if (fgets(str, sizeof(str), fp) == NULL) return IHEX_ERROR_FILE; // trim whitespace on the right end = str + strlen(str) - 1; while (end > str && isspace((unsigned char) *end)) end--; end[1] = '\0'; if (strlen(str) < IHEX_MIN_STRING) return IHEX_ERROR_FMT; len = IHEX_GetByte(&str[IHEX_OFFS_LEN]); addr = (IHEX_GetByte(&str[IHEX_OFFS_ADDR]) << 8) + IHEX_GetByte(&str[IHEX_OFFS_ADDR + 2]); if (addr + segment >= maxlen) return IHEX_ERROR_SIZE; type = IHEX_GetByte(&str[IHEX_OFFS_TYPE]); if (len * 2 + IHEX_MIN_STRING != strlen(str)) return IHEX_ERROR_FMT; switch (type) { case IHEX_DATA_RECORD: //if (addr + segment + len >= *address) // *address = addr + segment + len; for (i = 0; i < len; i++) { byte = IHEX_GetByte(&str[IHEX_OFFS_DATA + i * 2]); if (byte != 0xFF) *max_addr = addr + segment + i + 1; data[addr + segment + i] = byte; } break; case IHEX_END_OF_FILE_RECORD: return IHEX_ERROR_NONE; case IHEX_EXTENDED_SEGMENT_ADDRESS_RECORD: segment = ((IHEX_GetByte(&str[IHEX_OFFS_DATA]) << 8) + IHEX_GetByte(&str[IHEX_OFFS_DATA + 2])) << 4; break; case IHEX_START_SEGMENT_ADDRESS_RECORD: break; case IHEX_EXTENDED_LINEAR_ADDRESS_RECORD: break; case IHEX_START_LINEAR_ADDRESS_RECORD: break; default: return IHEX_ERROR_FMT; } } return IHEX_ERROR_NONE; }
nieldk/updiprog
progress.c
<filename>progress.c<gh_stars>10-100 #include <stdio.h> #include <string.h> #include "progress.h" /** \brief Print progress bar with prefix * * \param [in] iteration Current iteration * \param [in] total Total number of iterations * \param [in] prefix Prefix text * \param [in] fill Char to use for filling the bar * \return Noting * */ void PROGRESS_Print(uint16_t iteration, uint16_t total, char *prefix, char fill) { uint8_t filledLength; float percent; char bar[PROGRESS_BAR_LENGTH + 1]; char bar2[PROGRESS_BAR_LENGTH + 1]; memset(bar, fill, PROGRESS_BAR_LENGTH); bar[PROGRESS_BAR_LENGTH] = 0; memset(bar2, ' ', PROGRESS_BAR_LENGTH); bar2[PROGRESS_BAR_LENGTH] = 0; percent = (float)iteration / total * 100; filledLength = (uint8_t)(PROGRESS_BAR_LENGTH * iteration / total); printf("\r%s [%.*s%.*s] %.1f%%", prefix, filledLength, bar, PROGRESS_BAR_LENGTH - filledLength, bar2, percent); fflush(stdout); // Print New Line on Complete if (iteration >= total) printf("\n"); } /** \brief Do break in the output * * \return Nothing * */ void PROGRESS_Break(void) { printf("\n"); }
nieldk/updiprog
devices.c
<reponame>nieldk/updiprog #include <string.h> #include "devices.h" tDevice DEVICES_List[] = { { "mega480x", 0x4000, 48 * 1024, 128, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 11 }, { "mega320x", 0x4000, 32 * 1024, 128, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 11 }, { "mega160x", 0x4000, 16 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 11 }, { "mega80x", 0x4000, 8 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 11 }, { "tiny321x", 0x8000, 32 * 1024, 128, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny160x", 0x8000, 16 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny161x", 0x8000, 16 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny80x", 0x8000, 8 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny81x", 0x8000, 8 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny40x", 0x8000, 4 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny41x", 0x8000, 4 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 11 }, { "tiny20x", 0x8000, 2 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 }, { "tiny21x", 0x8000, 2 * 1024, 64, 0x0F00, 0x1000, 0x1100, 0x1280, 0x1300, 9 } }; static int8_t DEVICE_Id = DEVICE_UNKNOWN_ID; /** \brief Get device ID from name string * * \param [in] name Name to find as string * \return index of the found device or -1 as error * */ int8_t DEVICES_GetId(char *name) { uint8_t i; for (i = 0; i < sizeof(DEVICES_List) / sizeof(tDevice); i++) { if (strcmp(name, DEVICES_List[i].name) == 0) { DEVICE_Id = i; return i; } } DEVICE_Id = DEVICE_UNKNOWN_ID; return -1; } /** \brief Get flash memory length for selected device * * \return Size of the flash memory as uint16_t * */ uint16_t DEVICES_GetFlashLength(void) { if (DEVICE_Id == DEVICE_UNKNOWN_ID) return 0; else return DEVICES_List[DEVICE_Id].flash_size; } /** \brief Get flash start address for selected device * * \return Address of the flash area as uint16_t * */ uint16_t DEVICES_GetFlashStart(void) { if (DEVICE_Id == DEVICE_UNKNOWN_ID) return 0; else return DEVICES_List[DEVICE_Id].flash_start; } /** \brief Get flash page size for selected device * * \return Flash page size as uint16_t * */ uint16_t DEVICES_GetPageSize(void) { if (DEVICE_Id == DEVICE_UNKNOWN_ID) return 0; else return DEVICES_List[DEVICE_Id].flash_pagesize; } /** \brief Get NVM control registers address for selected device * * \return NVM registers adress as uint16_t * */ uint16_t DEVICES_GetNvmctrlAddress(void) { if (DEVICE_Id == DEVICE_UNKNOWN_ID) return 0; else return DEVICES_List[DEVICE_Id].nvmctrl_address; } /** \brief Get fuses address for selected device * * \return Fuses address as uint16_t * */ uint16_t DEVICES_GetFusesAddress(void) { if (DEVICE_Id == DEVICE_UNKNOWN_ID) return 0; else return DEVICES_List[DEVICE_Id].fuses_address; } /** \brief Get number of the fuses for selected device * * \return Number of the fuses as uint8_t * */ uint8_t DEVICES_GetFusesNumber(void) { if (DEVICE_Id == DEVICE_UNKNOWN_ID) return 0; else return DEVICES_List[DEVICE_Id].number_of_fuses; } /** \brief Get number of devices in the list * * \return Number of the devices as uint8_t * */ uint8_t DEVICES_GetNumber(void) { return (uint8_t)(sizeof(DEVICES_List) / sizeof(tDevice)); } /** \brief Get string name of the device by ID * * \return Device name as string * */ char *DEVICES_GetNameByNumber(uint8_t number) { if (number >= sizeof(DEVICES_List) / sizeof(tDevice)) number = 0; return DEVICES_List[number].name; }
nieldk/updiprog
com.h
<filename>com.h #ifndef COM_H #define COM_H #include <stdint.h> #include <stdbool.h> bool COM_Open(char *port, uint32_t baudrate, bool have_parity, bool two_stopbits); int COM_Write(uint8_t *data, uint16_t len); int COM_Read(uint8_t *data, uint16_t len); uint16_t COM_GetTransTime(uint16_t len); void COM_WaitForTransmit(void); void COM_Close(void); #endif
dreamflyforever/socket_file
client.c
<reponame>dreamflyforever/socket_file<filename>client.c /* * client send file name and receive file from server. * */ #include<netinet/in.h> #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define SERVER_PORT 6666 #define BUFFER_SIZE 1024 #define FILE_NAME_MAX_SIZE 512 #if 1 #define pf(format, ...) \ {printf("[%s : %s : %d] ", \ __FILE__, __func__, __LINE__); \ printf(format, ##__VA_ARGS__);} #else #define pf(format, ...) #endif int main(int argc, char **argv) { struct sockaddr_in client_addr; int client_socket; struct sockaddr_in server_addr; if (argc != 2) { printf("Usage: %s ServerIPAddress\n", argv[0]); exit(1); } bzero(&client_addr, sizeof(client_addr)); client_addr.sin_family = AF_INET; client_addr.sin_addr.s_addr = htons(INADDR_ANY); client_addr.sin_port = htons(0); client_socket = socket(AF_INET, SOCK_STREAM, 0); if (client_socket < 0) { printf("Create Socket Failed!\n"); exit(1); } if (bind(client_socket, (struct sockaddr*)&client_addr, sizeof(client_addr))) { printf("Client Bind Port Failed!\n"); exit(1); } bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; if (inet_aton(argv[1], &server_addr.sin_addr) == 0) { printf("Server IP Address Error!\n"); exit(1); } server_addr.sin_port = htons(SERVER_PORT); socklen_t server_addr_length = sizeof(server_addr); if (connect(client_socket, (struct sockaddr*)&server_addr, server_addr_length) < 0) { printf("Can Not Connect To %s!\n", argv[1]); exit(1); } char file_name[FILE_NAME_MAX_SIZE + 1]; bzero(file_name, sizeof(file_name)); printf("Please Input File Name On Server:"); scanf("%s", file_name); char buffer[BUFFER_SIZE]; bzero(buffer, sizeof(buffer)); strncpy(buffer, file_name, strlen(file_name) > BUFFER_SIZE ? BUFFER_SIZE : strlen(file_name)); printf("buffer: %s\n", buffer); send(client_socket, buffer, BUFFER_SIZE, 0); FILE *fp = fopen(file_name, "r"); if (fp == NULL) { printf("File:\t%s Not Found!\n", file_name); } else { bzero(buffer, BUFFER_SIZE); int file_block_length = 0; while ((file_block_length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0) { printf("file_block_length = %d\n", file_block_length); if (send(client_socket, buffer, file_block_length, 0) < 0) { printf("Send File:\t%s Failed!\n", file_name); break; } bzero(buffer, sizeof(buffer)); } fclose(fp); printf("File:\t%s Transfer Finished!\n", file_name); } printf("send File: %s to Server[%s] Finished!\n", file_name, argv[1]); close(client_socket); return 0; }
dreamflyforever/socket_file
server.c
<gh_stars>0 /* * server be sent file */ #include<netinet/in.h> #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include <unistd.h> #define SERVER_PORT 6666 #define LENGTH_OF_LISTEN_QUEUE 20 #define BUFFER_SIZE 1024 #define FILE_NAME_MAX_SIZE 512 int main(int argc, char **argv) { struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htons(INADDR_ANY); server_addr.sin_port = htons(SERVER_PORT); int server_socket = socket(PF_INET, SOCK_STREAM, 0); if (server_socket < 0) { printf("Create Socket Failed!\n"); exit(1); } if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr))) { printf("Server Bind Port: %d Failed!\n", SERVER_PORT); exit(1); } if (listen(server_socket, LENGTH_OF_LISTEN_QUEUE)) { printf("Server Listen Failed!\n"); exit(1); } while(1) { struct sockaddr_in client_addr; socklen_t length = sizeof(client_addr); int new_server_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length); if (new_server_socket < 0) { printf("Server Accept Failed!\n"); break; } char buffer[BUFFER_SIZE]; bzero(buffer, sizeof(buffer)); length = recv(new_server_socket, buffer, BUFFER_SIZE, 0); if (length < 0) { printf("Server Recieve Data Failed!\n"); break; } char file_name[FILE_NAME_MAX_SIZE + 1]; bzero(file_name, sizeof(file_name)); strncpy(file_name, buffer, strlen(buffer) > FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE : strlen(buffer)); FILE *fp = fopen(file_name, "w"); if (fp == NULL) { printf("File:\t%s Can Not Open To Write!\n", file_name); exit(1); } bzero(buffer, sizeof(buffer)); length = 0; while (length = recv(new_server_socket, buffer, BUFFER_SIZE, 0)) { if (length < 0) { printf("Recieve Data From Client Failed!\n"); break; } int write_length = fwrite(buffer, sizeof(char), length, fp); if (write_length < length) { printf("File:\t%s Write Failed!\n", file_name); break; } bzero(buffer, BUFFER_SIZE); } close(new_server_socket); printf("receive File: %s from client Finished!\n", file_name); fclose(fp); } close(server_socket); return 0; }
DYNXTSX/ESAIP_MobileBluetooth
Code/bluetooth.h
<gh_stars>0 #include<stdio.h> #include<string.h> #include<stdlib.h> int enovieMsg22(char *msg, char *port); int enovieMsg(char *msg, char *port); int main();
DYNXTSX/ESAIP_MobileBluetooth
Code/bluetooth.c
#include <stdlib.h> #include <stdio.h> #include <windows.h> #include <conio.h> #include <string.h> #include <unistd.h> #include "serialcom.h" /* Fonction envoieMsg(char *msg, char *port) : * =========================================== * ==> msg : correspond au message à envoyé par bluetooth * ==> port : correspond au port sur lequel est connecté notre arduino (COM3/4/...) */ int envoieMsg(char *msg, char *port){ /* Declaration des variables et structures : * ========================================= * HANDLE -> * DCB -> "Data Control Block" parametres pour le serial port */ HANDLE hSerial; DCB dcbSerialParams = {0}; COMMTIMEOUTS timeouts = {0}; // Open the highest available serial port number fprintf(stderr, "Ouverture du port..."); hSerial = CreateFile( port, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL ); if (hSerial == INVALID_HANDLE_VALUE) { fprintf(stderr, "Erreur port...\n"); return 1; } else fprintf(stderr, "Connexion faite !\n"); // Set device parameters (38400 baud, 1 start bit, // 1 stop bit, no parity) dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (GetCommState(hSerial, &dcbSerialParams) == 0) { fprintf(stderr, "Erreut arduino..\n"); CloseHandle(hSerial); return 1; } dcbSerialParams.BaudRate = CBR_38400; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if(SetCommState(hSerial, &dcbSerialParams) == 0) { fprintf(stderr, "Erreur paramètres connexion...\n"); CloseHandle(hSerial); return 1; } // Set COM port timeout settings timeouts.ReadIntervalTimeout = 50; timeouts.ReadTotalTimeoutConstant = 50; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; if(SetCommTimeouts(hSerial, &timeouts) == 0) { fprintf(stderr, "Erreur timeout\n"); CloseHandle(hSerial); return 1; } // Send specified text (remaining command line arguments) DWORD bytes_written, total_bytes_written = 0; fprintf(stderr, "Envoie du message..."); if(!WriteFile(hSerial, msg, 50, &bytes_written, NULL)) { fprintf(stderr, "Erreur\n"); CloseHandle(hSerial); return 1; } fprintf(stderr, "%d envoyé !\n", bytes_written); // Close serial port fprintf(stderr, "Fermeture serial port..."); if (CloseHandle(hSerial) == 0) { fprintf(stderr, "Erreur\n"); return 1; } fprintf(stderr, "Ferme !\n"); } int main() { //VARIABLES qui ne changeront pas char msg_on[6] = "on\r\n"; char msg_off[7] = "off\r\n"; char term; int OPTION=-1, SOUSOPTION=-1; //VARIABLES qui peut changer char port[10] = "COM4"; char nomAppairage[50] = "user_BasicUser_"; int heureDiff = 15; int minutesDiff = 45; //MENU while(OPTION != 0){ /* OPTION 1 : * ========== * Ce menu permet de configurer les donnees qui peuvent changer. Il y a un sous menu qui permet : * 1 -> se creer un nom qui sera afficher sur l'écran LCD pour confirmer la connection * 2 --> choisir l'heure de diffusion hebdomadaire * 3 ---> renseigner le port bluetooth sur lequel est connecté l'arduino (COM3/4/...) */ if(OPTION == 1){ while(SOUSOPTION!=0){ if(SOUSOPTION == 1){ char name[25]; char debUser[50] = "user_"; printf("Veuiller entrer votre nouveau nom d'appairage : "); scanf("%s", &name); strcat(debUser, name); //concatenation strcat(debUser, "_"); //concatenation strcpy(nomAppairage, debUser); //copie printf("Nouveau nom ==> %s\n", nomAppairage); } if(SOUSOPTION == 2){ printf("Veuiller choisir l'heure de diffusion (ex: 15:45) : "); while(scanf("%d%c%d",&heureDiff, &term, &minutesDiff) != 3 || term != ':' || heureDiff > 23 || heureDiff < 0 || minutesDiff > 59 || minutesDiff < 0){ printf("Veuiller choisir l'heure de diffusion (ex: 15:45) : "); while(getchar() != '\n'); } printf("Vous avez choisi unr heure de %d:%d\n", heureDiff, minutesDiff); } if(SOUSOPTION == 3){ char portInsert[25]; printf("Veuiller entrer votre port (generalement COM3/COM4) : "); scanf("%s", &portInsert); strcpy(port, portInsert); printf("Nouveau port ==> %s\n", port); } printf("=========================================\n"); printf("======= CONFIGURATIONS DONNEES =======\n"); printf("=========================================\n"); printf("|-> 0 - Quitter \n"); printf("|--> 1 - Nom d'appairage \n"); printf("|---> 2 - Heure de diffusion \n"); printf("|----> 3 - Port de connexion \n"); printf("=========================================\n"); printf("Saisir une sous-option : "); while(scanf("%d%c",&SOUSOPTION, &term) != 2 || term != '\n') { printf("=========================================\n"); printf("======= CONFIGURATIONS DONNEES =======\n"); printf("=========================================\n"); printf("|-> 0 - Quitter \n"); printf("|--> 1 - Nom d'appairage \n"); printf("|---> 2 - Heure de diffusion \n"); printf("|----> 3 - Port de connexion \n"); printf("=========================================\n"); printf("Saisir une sous-option : "); while(getchar() != '\n'); } } } /* OPTION 2 : * ========== * Cette fonctionnalité permet de s'assurer qu'on est bien connecté au diffuseur * 1 -> Vérifier que le port est bien renseigné * 2 --> Envoie le message et le port à la fonction envoieMsg qui s'occupe du reste */ else if(OPTION == 2){ if(port == "" || port == NULL){ printf("Veuillez configurer un port valide.."); }else{ int retourErreur = envoieMsg(nomAppairage, port); printf("Pas encore implemente.."); } } /* OPTION 3 : * ========== * Cette fonctionnalité permet de mettre à jours l'heure de diffusion pour le programme * 1 -> Définir le message qui va etre transmit à l'arduino contenant la nouvelle heure * 2 --> Envoie le message et le port à la fonction envoieMsg qui s'occupe du reste */ else if(OPTION == 3){ char heure[20] = "heures_"; char minutes[20] = "minutes_"; char heuresTransi[2]; sprintf(heuresTransi, "%d", heureDiff); strcat(heure, heuresTransi); strcat(heure, "_"); int retourErreurHeure = envoieMsg(heure, port); char MinutesTransi[2]; sprintf(MinutesTransi, "%d", minutesDiff); strcat(minutes, MinutesTransi); strcat(minutes, "_"); int retourErreurMinutes = envoieMsg(minutes, port); printf("Pas encore implemente.."); } /* OPTION 4 : * ========== * Cette fonctionnalité permet d'actionner le diffuseur un coup * 1 -> Vérifier que le port est bien renseigné * 2 --> Envoie le message et le port à la fonction envoieMsg qui s'occupe du reste */ else if(OPTION == 4){ if(port == "" || port == NULL){ printf("Veuillez configurer un port valide.."); }else{ int retourErreurPshit = envoieMsg("pshit_", port); printf("Pas encore implemente.."); } } printf("\n================== MENU =================\n"); printf("=== 1 - CONFIGURATIONS DONNEES ====\n"); printf("=== 2 - CONNEXION AU DIFFUSEUR ====\n"); printf("=== 3 - ENVOYER L'HEURE DE DIFFUSION ====\n"); printf("=== 4 - ACTIONNER LE DIFFUSEUR ====\n"); printf("=========================================\n"); printf("Saisir une option : "); SOUSOPTION=-1; while(scanf("%d%c",&OPTION, &term) != 2 || term != '\n'){ printf("\n================== MENU =================\n"); printf("=== 1 - CONFIGURATIONS DONNEES ====\n"); printf("=== 2 - CONNEXION AU DIFFUSEUR ====\n"); printf("=== 3 - ENVOYER L'HEURE DE DIFFUSION ====\n"); printf("=== 4 - ACTIONNER LE DIFFUSEUR ====\n"); printf("=========================================\n"); printf("Saisir une option : "); while(getchar() != '\n'); } } return 0; }
DYNXTSX/ESAIP_MobileBluetooth
Code/IHM/bluetooth.c
<filename>Code/IHM/bluetooth.c #include <stdlib.h> #include <stdio.h> #include <gtk/gtk.h> //gcc `pkg-config --cflags gtk+-3.0` -o programme bluetooth.c `pkg-config --libs gtk+-3.0` static GtkWidget *appareil, *label2; static GtkWidget *comboH, *comboM; void reloadBluetooth(GtkWidget* pWidget, gpointer data) { gchar *newText = "Appareil Bluetooth : <b>"; newText += "ABDEL"; newText += "</b>"; gtk_label_set_markup(GTK_LABEL(appareil), newText); } int main(int argc, char *argv[]) { GtkWidget *window; GtkWidget *table, *table2, *table3, *table4, *table5, *table6; GtkWidget *frame1, *frame2; GtkWidget *button1, *button2, *button3; GtkWidget *hbox, *hbox2; GtkWidget *halign, *halign2; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 300, 500); gtk_window_set_title(GTK_WINDOW(window), "GtkStatusbar"); gtk_container_set_border_width(GTK_CONTAINER(window), 10); table = gtk_table_new(2, 1, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table), 10); gtk_table_set_col_spacings(GTK_TABLE(table), 10); gtk_container_add(GTK_CONTAINER(window), table); // Creation des deux sections frame1 = gtk_frame_new("Partie Connection"); gtk_frame_set_shadow_type(GTK_FRAME(frame1), GTK_SHADOW_OUT); frame2 = gtk_frame_new("Partie Actionnement"); gtk_frame_set_shadow_type(GTK_FRAME(frame2), GTK_SHADOW_OUT); //Disposition des sections gtk_table_attach_defaults(GTK_TABLE(table), frame1, 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table), frame2, 0, 1, 1, 2); //Partie haute table2 = gtk_table_new(1, 1, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table2), 10); gtk_table_set_col_spacings(GTK_TABLE(table2), 10); gtk_container_add(frame1, table2); gchar *str = "Appareil Bluetooth : <b>ALEXANDRE</b>"; appareil = gtk_label_new(NULL); gtk_label_set_markup(GTK_LABEL(appareil), str); button3 = gtk_button_new_with_label("Actualiser"); gtk_widget_set_size_request(button3, 70, 50 ); gtk_table_attach_defaults(GTK_TABLE(table2), GTK_LABEL(appareil), 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table2), button3, 0, 1, 1, 2); //Partie basse table4 = gtk_table_new(2, 1, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table4), 10); gtk_table_set_col_spacings(GTK_TABLE(table4), 10); gtk_container_add(frame2, table4); table3 = gtk_table_new(1, 2, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table3), 10); gtk_table_set_col_spacings(GTK_TABLE(table3), 10); gtk_table_attach_defaults(GTK_TABLE(table4), GTK_TABLE(table3), 0, 1, 1, 2); table5 = gtk_table_new(1, 1, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table5), 10); gtk_table_set_col_spacings(GTK_TABLE(table5), 10); gtk_table_attach_defaults(GTK_TABLE(table4), GTK_TABLE(table5), 0, 1, 0, 1); gchar *str2 = "Heure Hebdomadaire : <b>15h30</b>"; label2 = gtk_label_new(NULL); gtk_label_set_markup(GTK_LABEL(label2), str2); gtk_table_attach_defaults(GTK_TABLE(table5), GTK_LABEL(label2), 0, 1, 0, 1); table6 = gtk_table_new(1, 2, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table6), 10); gtk_table_set_col_spacings(GTK_TABLE(table6), 10); gtk_table_attach_defaults(GTK_TABLE(table5), GTK_TABLE(table6), 0, 1, 1, 2); //716 comboH = gtk_combo_box_text_new(); gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(comboH), NULL, "Heure"); gtk_combo_box_set_active(GTK_COMBO_BOX(comboH), 0); comboM = gtk_combo_box_text_new(); gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(comboM), NULL, "Minutes"); gtk_combo_box_set_active(GTK_COMBO_BOX(comboM), 0); gtk_table_attach_defaults(GTK_TABLE(table6), comboH, 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table6), comboM, 1, 2, 0, 1); button1 = gtk_button_new_with_label("Mettre à jour"); gtk_widget_set_size_request(button1, 70, 50 ); button2 = gtk_button_new_with_label("Activer un coup"); gtk_widget_set_size_request(button2, 70, 50 ); gtk_table_attach_defaults(GTK_TABLE(table3), button1, 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table3), button2, 1, 2, 0, 1); //Signaux g_signal_connect((button3),"clicked",G_CALLBACK(reloadBluetooth),NULL); gtk_widget_show_all(window); gtk_main(); return 0; }
DYNXTSX/ESAIP_MobileBluetooth
Code/serialcom.h
<filename>Code/serialcom.h void serial_Write(char choice[]) { HANDLE hComm; // using the serial port char ComPortName[] = "\\\\.\\COM3"; // it depends on device BOOL Status; hComm = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); // opening the serial port if (hComm == INVALID_HANDLE_VALUE) { fprintf(stderr, "Error\n"); } else fprintf(stderr, "OK\n"); /* DCB dcbSerialParams = {0}; // setting the parameters for the serial port dcbSerialParams.DCBlength = sizeof(dcbSerialParams); // DCB = Data Control Block Status = GetCommState(hComm, &dcbSerialParams); // retrieving the current settings dcbSerialParams.BaudRate = CBR_9600; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; Status = SetCommState(hComm, &dcbSerialParams); // configuring the port according to dcb structures COMMTIMEOUTS timeouts = {0}; // setting timeouts timeouts.ReadIntervalTimeout = 50; timeouts.ReadTotalTimeoutConstant = 50; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; char lpBuffer[10]; // determining the data to be written to the serial port strcpy(lpBuffer, choice); DWORD dNoOFBytestoWrite; DWORD dNoOfBytesWritten = 0; dNoOFBytestoWrite = sizeof(lpBuffer); // calculating the amount of bytes Status = WriteFile(hComm, "ceciestuntest", dNoOFBytestoWrite, &dNoOfBytesWritten, NULL); // writing the data to the serial port CloseHandle(hComm); // closing the serial port */ }
DYNXTSX/ESAIP_MobileBluetooth
Code/TransmissionBluetooth/sendMsg.c
<filename>Code/TransmissionBluetooth/sendMsg.c #include<stdio.h> #include <windows.h> #include <conio.h> #include <string.h> int enovieMsg22(char *msg, char *port){ // Declare variables and structures HANDLE hSerial; DCB dcbSerialParams = {0}; COMMTIMEOUTS timeouts = {0}; // Open the highest available serial port number fprintf(stderr, "Opening serial port..."); hSerial = CreateFile( port, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (hSerial == INVALID_HANDLE_VALUE) { fprintf(stderr, "Error\n"); return 1; } else fprintf(stderr, "OK\n"); // Set device parameters (38400 baud, 1 start bit, // 1 stop bit, no parity) dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (GetCommState(hSerial, &dcbSerialParams) == 0) { fprintf(stderr, "Error getting device state\n"); CloseHandle(hSerial); return 1; } dcbSerialParams.BaudRate = CBR_38400; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if(SetCommState(hSerial, &dcbSerialParams) == 0) { fprintf(stderr, "Error setting device parameters\n"); CloseHandle(hSerial); return 1; } // Set COM port timeout settings timeouts.ReadIntervalTimeout = 50; timeouts.ReadTotalTimeoutConstant = 50; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; if(SetCommTimeouts(hSerial, &timeouts) == 0) { fprintf(stderr, "Error setting timeouts\n"); CloseHandle(hSerial); return 1; } // Send specified text (remaining command line arguments) DWORD bytes_written, total_bytes_written = 0; fprintf(stderr, "Sending bytes..."); if(!WriteFile(hSerial, msg, 50, &bytes_written, NULL)) { fprintf(stderr, "Error\n"); CloseHandle(hSerial); return 1; } fprintf(stderr, "%d bytes written\n", bytes_written); // Close serial port fprintf(stderr, "Closing serial port..."); if (CloseHandle(hSerial) == 0) { fprintf(stderr, "Error\n"); return 1; } fprintf(stderr, "OK\n"); } int main(int argc, char *argv[]) { // Define the five bytes to send ("hello") if(argc < 3) return 1; else{ char *message = argv[1]; strcat(message, "_"); char *port = argv[2]; enovieMsg22(message, port); } return 0; }
DYNXTSX/ESAIP_MobileBluetooth
Code/IHM/bluetooth.h
<reponame>DYNXTSX/ESAIP_MobileBluetooth void fglobale(void);
vbence/pwxe
src/php_pwxe.c
/* * This file is part of Pwxe, a PHP extension to stop execution * of writable files. * * Author: <NAME> <<EMAIL>> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_pwxe.h" #include "SAPI.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); static zend_compile_t *old_compile_file; static zend_function_entry pwxe_functions[] = { {NULL, NULL, NULL} }; zend_module_entry pwxe_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif PHP_PWXE_EXTNAME, pwxe_functions, PHP_MINIT(pwxe), PHP_MSHUTDOWN(pwxe), PHP_RINIT(pwxe), PHP_RSHUTDOWN(pwxe), PHP_MINFO(pwxe), #if ZEND_MODULE_API_NO >= 20010901 PHP_PWXE_VERSION, #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_PWXE ZEND_GET_MODULE(pwxe) #endif PHP_INI_BEGIN() PHP_INI_ENTRY("pwxe.filter", "1", PHP_INI_SYSTEM, NULL) PHP_INI_END() PHP_MINFO_FUNCTION(pwxe) { php_info_print_table_start(); php_info_print_table_row(2, "PHP Write Xor Execute Extension", "enabled"); php_info_print_table_row(2, "Version", PHP_PWXE_VERSION); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } PHP_MINIT_FUNCTION(pwxe) { REGISTER_INI_ENTRIES(); pwxe_zend_init(); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(pwxe) { pwxe_zend_shutdown(); UNREGISTER_INI_ENTRIES(); return SUCCESS; } PHP_RINIT_FUNCTION(pwxe) { return SUCCESS; } PHP_RSHUTDOWN_FUNCTION(pwxe) { return SUCCESS; } /* * Decide whether it is safe to run this file. */ static bool file_runnable(const char* filename) { // file is writable int writable = access(filename, W_OK); if (writable == 0) { return false; } // file is owned by current (effective) user struct stat fileinfo; stat(filename, &fileinfo); uid_t euid = geteuid(); if (fileinfo.st_uid == euid) { return false; } // all OK return true; } /* * We hook into zend_compile_file to abort file compilation if necessary. */ static zend_op_array* my_compile_file(zend_file_handle* h, int type TSRMLS_DC) { bool file_ok = INI_BOOL("pwxe.filter") ? file_runnable(h->filename) : true; if (file_ok) { return old_compile_file(h, type TSRMLS_CC); } else { zend_error(E_COMPILE_ERROR, "Writable (or owned) file blocked by PWXE: \"%s\".", h->filename); return FAILURE; } } /* * Set up hooks. */ void pwxe_zend_init(TSRMLS_D) { old_compile_file = zend_compile_file; zend_compile_file = my_compile_file; } /* * Remove hooks. */ void pwxe_zend_shutdown(TSRMLS_D) { zend_compile_file = old_compile_file; }
vbence/pwxe
src/php_pwxe.h
/* * This file is part of Pwxe, a PHP extension to stop execution * of writable files. * * Author: <NAME> <<EMAIL>> */ #ifndef PHP_PWXE_H #define PHP_PWXE_H 1 #define PHP_PWXE_VERSION "0.1" #define PHP_PWXE_EXTNAME "PWXE" extern void pwxe_zend_init(TSRMLS_D); extern void pwxe_zend_shutdown(TSRMLS_D); PHP_MINIT_FUNCTION(pwxe); PHP_MSHUTDOWN_FUNCTION(pwxe); PHP_RINIT_FUNCTION(pwxe); PHP_RSHUTDOWN_FUNCTION(pwxe); PHP_MINFO_FUNCTION(pwxe); extern zend_module_entry pwxe_module_entry; #define phpext_pwxe_ptr &pwxe_module_entry #endif
BingyangWu/6.828-2018
user/sh.c
<reponame>BingyangWu/6.828-2018<gh_stars>0 #include <inc/lib.h> #define BUFSIZ 1024 /* Find the buffer overrun bug! */ int debug = 0; // gettoken(s, 0) prepares gettoken for subsequent calls and returns 0. // gettoken(0, token) parses a shell token from the previously set string, // null-terminates that token, stores the token pointer in '*token', // and returns a token ID (0, '<', '>', '|', or 'w'). // Subsequent calls to 'gettoken(0, token)' will return subsequent // tokens from the string. int gettoken(char *s, char **token); // Parse a shell command from string 's' and execute it. // Do not return until the shell command is finished. // runcmd() is called in a forked child, // so it's OK to manipulate file descriptor state. #define MAXARGS 16 void runcmd(char* s) { char *argv[MAXARGS], *t, argv0buf[BUFSIZ]; int argc, c, i, r, p[2], fd, pipe_child; pipe_child = 0; gettoken(s, 0); again: argc = 0; while (1) { switch ((c = gettoken(0, &t))) { case 'w': // Add an argument if (argc == MAXARGS) { cprintf("too many arguments\n"); exit(); } argv[argc++] = t; break; case '<': // Input redirection // Grab the filename from the argument list if (gettoken(0, &t) != 'w') { cprintf("syntax error: < not followed by word\n"); exit(); } // Open 't' for reading as file descriptor 0 // (which environments use as standard input). // We can't open a file onto a particular descriptor, // so open the file as 'fd', // then check whether 'fd' is 0. // If not, dup 'fd' onto file descriptor 0, // then close the original 'fd'. // LAB 5: Your code here. if ((fd = open(t, O_RDONLY)) < 0) { cprintf("open %s for read: %e", t, fd); exit(); } if (fd != 1) { dup(fd, 0); close(fd); } break; case '>': // Output redirection // Grab the filename from the argument list if (gettoken(0, &t) != 'w') { cprintf("syntax error: > not followed by word\n"); exit(); } if ((fd = open(t, O_WRONLY|O_CREAT|O_TRUNC)) < 0) { cprintf("open %s for write: %e", t, fd); exit(); } if (fd != 1) { dup(fd, 1); close(fd); } break; case '|': // Pipe if ((r = pipe(p)) < 0) { cprintf("pipe: %e", r); exit(); } if (debug) cprintf("PIPE: %d %d\n", p[0], p[1]); if ((r = fork()) < 0) { cprintf("fork: %e", r); exit(); } if (r == 0) { if (p[0] != 0) { dup(p[0], 0); close(p[0]); } close(p[1]); goto again; } else { pipe_child = r; if (p[1] != 1) { dup(p[1], 1); close(p[1]); } close(p[0]); goto runit; } panic("| not implemented"); break; case 0: // String is complete // Run the current command! goto runit; default: panic("bad return %d from gettoken", c); break; } } runit: // Return immediately if command line was empty. if(argc == 0) { if (debug) cprintf("EMPTY COMMAND\n"); return; } // Clean up command line. // Read all commands from the filesystem: add an initial '/' to // the command name. // This essentially acts like 'PATH=/'. if (argv[0][0] != '/') { argv0buf[0] = '/'; strcpy(argv0buf + 1, argv[0]); argv[0] = argv0buf; } argv[argc] = 0; // Print the command. if (debug) { cprintf("[%08x] SPAWN:", thisenv->env_id); for (i = 0; argv[i]; i++) cprintf(" %s", argv[i]); cprintf("\n"); } // Spawn the command! if ((r = spawn(argv[0], (const char**) argv)) < 0) cprintf("spawn %s: %e\n", argv[0], r); // In the parent, close all file descriptors and wait for the // spawned command to exit. close_all(); if (r >= 0) { if (debug) cprintf("[%08x] WAIT %s %08x\n", thisenv->env_id, argv[0], r); wait(r); if (debug) cprintf("[%08x] wait finished\n", thisenv->env_id); } // If we were the left-hand part of a pipe, // wait for the right-hand part to finish. if (pipe_child) { if (debug) cprintf("[%08x] WAIT pipe_child %08x\n", thisenv->env_id, pipe_child); wait(pipe_child); if (debug) cprintf("[%08x] wait finished\n", thisenv->env_id); } // Done! exit(); } // Get the next token from string s. // Set *p1 to the beginning of the token and *p2 just past the token. // Returns // 0 for end-of-string; // < for <; // > for >; // | for |; // w for a word. // // Eventually (once we parse the space where the \0 will go), // words get nul-terminated. #define WHITESPACE " \t\r\n" #define SYMBOLS "<|>&;()" int _gettoken(char *s, char **p1, char **p2) { int t; if (s == 0) { if (debug > 1) cprintf("GETTOKEN NULL\n"); return 0; } if (debug > 1) cprintf("GETTOKEN: %s\n", s); *p1 = 0; *p2 = 0; while (strchr(WHITESPACE, *s)) *s++ = 0; if (*s == 0) { if (debug > 1) cprintf("EOL\n"); return 0; } if (strchr(SYMBOLS, *s)) { t = *s; *p1 = s; *s++ = 0; *p2 = s; if (debug > 1) cprintf("TOK %c\n", t); return t; } *p1 = s; while (*s && !strchr(WHITESPACE SYMBOLS, *s)) s++; *p2 = s; if (debug > 1) { t = **p2; **p2 = 0; cprintf("WORD: %s\n", *p1); **p2 = t; } return 'w'; } int gettoken(char *s, char **p1) { static int c, nc; static char* np1, *np2; if (s) { nc = _gettoken(s, &np1, &np2); return 0; } c = nc; *p1 = np1; nc = _gettoken(np2, &np1, &np2); return c; } void usage(void) { cprintf("usage: sh [-dix] [command-file]\n"); exit(); } void umain(int argc, char **argv) { int r, interactive, echocmds; struct Argstate args; interactive = '?'; echocmds = 0; argstart(&argc, argv, &args); while ((r = argnext(&args)) >= 0) switch (r) { case 'd': debug++; break; case 'i': interactive = 1; break; case 'x': echocmds = 1; break; default: usage(); } if (argc > 2) usage(); if (argc == 2) { close(0); if ((r = open(argv[1], O_RDONLY)) < 0) panic("open %s: %e", argv[1], r); assert(r == 0); } if (interactive == '?') interactive = iscons(0); while (1) { char *buf; buf = readline(interactive ? "$ " : NULL); if (buf == NULL) { if (debug) cprintf("EXITING\n"); exit(); // end of file } if (debug) cprintf("LINE: %s\n", buf); if (buf[0] == '#') continue; if (echocmds) printf("# %s\n", buf); if (debug) cprintf("BEFORE FORK\n"); if ((r = fork()) < 0) panic("fork: %e", r); if (debug) cprintf("FORK: %d\n", r); if (r == 0) { runcmd(buf); exit(); } else wait(r); } }