hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
b568f0acb550a3777d901c62d1910ecc70fd45bd
124
h
C
00_usefull/SimpleLEDStrip/include/secrets.h
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
00_usefull/SimpleLEDStrip/include/secrets.h
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
00_usefull/SimpleLEDStrip/include/secrets.h
r0oland/Baltopia
a772733a73fd54ad837f079b525bf8c7c09712bf
[ "MIT" ]
null
null
null
#ifndef SECRETS #define SECRETS const char* ssid = "Kassiopeia"; const char* password = "SternbilddesNordhimmels"; #endif
15.5
49
0.758065
24464ab508b879ee27dde1802f12fba5429b4f09
3,118
h
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/fma_main.h
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/fma_main.h
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/fma_main.h
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
#ifndef fma_main #define fma_main #if DEBUG #include <stdio.h> #endif TYPE m1[32] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }; TYPE m2[32] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }; TYPE m3[32] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 }; TYPE m4[32]; int test_fails = 0; void compare_result(char * title, TYPE *res) { int i; int good = 1; for (i =0; i < 32; i++) if (m4[i] != res[i]) { if (good) { #if DEBUG printf ("!!!! %s miscompare\n", title); #endif good = 0; } #if DEBUG printf ("res[%d] = %d, must be %d\n", i, (int)res[i], (int) m4[i]); #endif } if (!good) test_fails = 1; } static void fma_test () { int i; for (i=0; i <32; i++) m4[i] = test_noneg_add_noneg_add (m1[i], m2[i], m3[i]); compare_result ("test0000", res_test0000); for (i=0; i <32; i++) m4[i] = test_noneg_add_noneg_sub (m1[i], m2[i], m3[i]); compare_result ("test0001", res_test0001); for (i=0; i <32; i++) m4[i] = test_noneg_add_neg_add (m1[i], m2[i], m3[i]); compare_result ("test0010", res_test0010); for (i=0; i <32; i++) m4[i] = test_noneg_add_neg_sub (m1[i], m2[i], m3[i]); compare_result ("test0011", res_test0011); for (i=0; i <32; i++) m4[i] = test_noneg_sub_noneg_add (m1[i], m2[i], m3[i]); compare_result ("test0100", res_test0100); for (i=0; i <32; i++) m4[i] = test_noneg_sub_noneg_sub (m1[i], m2[i], m3[i]); compare_result ("test0101", res_test0101); for (i=0; i <32; i++) m4[i] = test_noneg_sub_neg_add (m1[i], m2[i], m3[i]); compare_result ("test0110", res_test0110); for (i=0; i <32; i++) m4[i] = test_noneg_sub_neg_sub (m1[i], m2[i], m3[i]); compare_result ("test0111", res_test0111); for (i=0; i <32; i++) m4[i] = test_neg_add_noneg_add (m1[i], m2[i], m3[i]); compare_result ("test1000", res_test1000); for (i=0; i <32; i++) m4[i] = test_neg_add_noneg_sub (m1[i], m2[i], m3[i]); compare_result ("test1001", res_test1001); for (i=0; i <32; i++) m4[i] = test_neg_add_neg_add (m1[i], m2[i], m3[i]); compare_result ("test1010", res_test1010); for (i=0; i <32; i++) m4[i] = test_neg_add_neg_sub (m1[i], m2[i], m3[i]); compare_result ("test1011", res_test1011); for (i=0; i <32; i++) m4[i] = test_neg_sub_noneg_add (m1[i], m2[i], m3[i]); compare_result ("test1100", res_test1100); for (i=0; i <32; i++) m4[i] = test_neg_sub_noneg_sub (m1[i], m2[i], m3[i]); compare_result ("test1101", res_test1101); for (i=0; i <32; i++) m4[i] = test_neg_sub_neg_add (m1[i], m2[i], m3[i]); compare_result ("test1110", res_test1110); for (i=0; i <32; i++) m4[i] = test_neg_sub_neg_sub (m1[i], m2[i], m3[i]); compare_result ("test1111", res_test1111); if (test_fails) abort (); } #endif
26.423729
75
0.550032
68634b70c050ee196ba1df4625574b2d1ef14565
702
h
C
Settings.h
Lunafyy/CPP-CommandLine
6b5da7392f60c66bff0d2c5087482eaa0b44568f
[ "Apache-2.0" ]
null
null
null
Settings.h
Lunafyy/CPP-CommandLine
6b5da7392f60c66bff0d2c5087482eaa0b44568f
[ "Apache-2.0" ]
null
null
null
Settings.h
Lunafyy/CPP-CommandLine
6b5da7392f60c66bff0d2c5087482eaa0b44568f
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> // Console Stuff std::string CONSOLE_PREFIX = "[username]@[machine]$~[directory]>"; // Commands std::string COMMAND_OUTPUT = "echo"; std::string COMMAND_CD = "cd"; std::string COMMAND_LOC = "loc"; std::string COMMAND_MAKE_NEW_DIRECTORY = "mkdir"; std::string COMMAND_REMOVE_DIRECTORY = "rmdir"; std::string COMMAND_LIST_DIRECTORY = "ls"; std::string COMMAND_CLEAR = "cls"; // Errors std::string COMMAND_UNKNOWN = "'[command]' is not recognized as an internal or external command."; std::string COMMAND_CD_INVALID_DIRECTORY = "The system cannot find the path specified."; std::string COMMAND_INVALID_SYNTAX = "The syntax of the command is incorrect.";
36.947368
99
0.730769
68bc9a97d0b680c6218aa7d04410dbc87e4abb1a
14,751
c
C
tools/player.c
ChenThread/ice2
b722e235533653396d1c4610d184da844be271bd
[ "MIT" ]
5
2016-06-20T13:42:33.000Z
2018-08-27T11:13:59.000Z
tools/player.c
ChenThread/ice2
b722e235533653396d1c4610d184da844be271bd
[ "MIT" ]
null
null
null
tools/player.c
ChenThread/ice2
b722e235533653396d1c4610d184da844be271bd
[ "MIT" ]
1
2021-09-16T04:03:45.000Z
2021-09-16T04:03:45.000Z
#define VIDSCALE 1 #define VIDOUTSCALE 2 #define AUDIO_RING_BUF (256*1024) #define AUDIO_SKIP_UPPER (32*1024) #define AUDIO_SKIP_LOWER (28*1024) #define AUDIO_TARGET_LATENCY (8*1024) #define SOFTWARE_BLIT_MODE #ifndef CONST_PREC #define CONST_PREC 10 #endif #ifndef CONST_POSTFILT #define CONST_POSTFILT 140 #endif #include <assert.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <SDL.h> SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; #ifdef SOFTWARE_BLIT_MODE SDL_Texture *texblit = NULL; #else SDL_Texture *texlist[2] = {NULL, NULL}; int curtex = 0; #endif uint8_t aring_data[AUDIO_RING_BUF]; int aring_beg = 0; // Thread: audio int aring_end = 0; // Thread: main SDL_atomic_t aring_used; uint16_t ocpal[256]; int vidw, vidh; uint16_t *scrbuf; uint8_t input_audio[0x10000*8]; uint8_t dfpwm_tmp_buffer[0x10000*8]; __attribute__((noreturn)) void abort_msg(const char *msg) { fprintf(stderr, "ERROR: %s\n", msg); fflush(stderr); abort(); } int audecmp_fq = 0; int audecmp_q = 0; int audecmp_s = 0; int audecmp_lt = -128; void au_decompress(int *fq, int *q, int *s, int *lt, int fs, int len, uint8_t *outbuf, uint8_t *inbuf) { int i,j; uint8_t d; for(i = 0; i < len; i++) { // get bits d = *(inbuf++); for(j = 0; j < 8; j++) { // set target int t = ((d&1) ? 127 : -128); d >>= 1; // adjust charge int nq = *q + ((*s * (t-*q) + (1<<(CONST_PREC-1)))>>CONST_PREC); if(nq == *q && nq != t) *q += (t == 127 ? 1 : -1); int lq = *q; *q = nq; // adjust strength int st = (t != *lt ? 0 : (1<<CONST_PREC)-1); int ns = *s; if(ns != st) ns += (st != 0 ? 1 : -1); #if CONST_PREC > 8 if(ns < 1+(1<<(CONST_PREC-8))) ns = 1+(1<<(CONST_PREC-8)); #endif *s = ns; // FILTER: perform antijerk int ov = (t != *lt ? (nq+lq)>>1 : nq); // FILTER: perform LPF *fq += ((fs*(ov-*fq) + 0x80)>>8); ov = *fq; // output sample ov += 128; ov &= 0xFF; *(outbuf++) = ov; *lt = t; } } } int has_fired = 0; void authread(void *ud, Uint8 *stream, int len) { // Clear buf memset(stream, 128, len); /* stream[0] = 255; stream[1] = 255; stream[2] = 255; stream[3] = 255; */ // Check how much of the buffer is available int bufsz = SDL_AtomicGet(&aring_used); //fprintf(stderr, "tick %d aring %d\n", len, aring_used); // If we haven't fired, we need to wait for the buffer to fill) if(!has_fired) { //if(bufsz <= 16384) return; has_fired = 1; } // If there's nothing, copy nothing if(bufsz <= 0) { has_fired = 0; return; } // Clamp to output buffer size int prebufsz = bufsz; if(bufsz > len) bufsz = len; int realbufsz = bufsz; // Copy Uint8 *sout = stream; if(aring_beg + bufsz >= AUDIO_RING_BUF) { memcpy(sout, aring_data + aring_beg, (AUDIO_RING_BUF - aring_beg)); int bufdec = AUDIO_RING_BUF - aring_beg; bufsz -= bufdec; sout += bufdec; aring_beg = 0; } assert(bufsz >= 0); // Copy remainder if(bufsz > 0) { memcpy(sout, aring_data + aring_beg, bufsz); aring_beg += bufsz; } // advance + decrement used space if(prebufsz >= AUDIO_SKIP_UPPER) { int skip_amt = prebufsz+AUDIO_SKIP_UPPER-AUDIO_SKIP_LOWER; aring_beg = (aring_beg + skip_amt) % AUDIO_RING_BUF; realbufsz += skip_amt; } realbufsz = SDL_AtomicAdd(&aring_used, -realbufsz); //fprintf(stderr, "honk %d\n", realbufsz); // ensure this is correct assert(realbufsz >= 0); /* stream[0] = 255; stream[1] = 255; stream[2] = 255; stream[3] = 255; */ } void pal_to_rgb(int pal, int *r, int *g, int *b) { assert(pal >= 0 && pal <= 255); if(pal < 16) { #define GREY_RAMP 64 *r = *g = *b = ((pal+1)*255)/(GREY_RAMP-1); //fprintf(stderr, "%i %02X\n", pal, *r); } else { pal -= 16; *g = ((pal%8)*255)/7; *r = (((pal/8)%6)*255)/5; *b = (((pal/8)/6)*255)/4; } assert(*r >= 0 && *r <= 255); assert(*g >= 0 && *g <= 255); assert(*b >= 0 && *b <= 255); } void do_mocomp(int mocx, int mocy) { int y; // Do mocomp copy if(mocx != 0 || mocy != 0) { int mocw = vidw-(mocx<0?-mocx:mocx); int moch = vidh-(mocy<0?-mocy:mocy); #ifdef SOFTWARE_BLIT_MODE int srcx=(mocx<0?-mocx:0); int srcy=(mocy<0?-mocy:0); int dstx=(mocx>0? mocx:0); int dsty=(mocy>0? mocy:0); if(mocy < 0) { for(y = 0; y < moch; y++) { memcpy( scrbuf + dstx + (y+dsty)*vidw, scrbuf + srcx + (y+srcy)*vidw, mocw*2); } } else if(mocy > 0) { for(y = moch-1; y >= 0; y--) { memcpy( scrbuf + dstx + (y+dsty)*vidw, scrbuf + srcx + (y+srcy)*vidw, mocw*2); } } else { for(y = 0; y < moch; y++) { memmove( scrbuf + dstx + (y+dsty)*vidw, scrbuf + srcx + (y+srcy)*vidw, mocw*2); } } #else SDL_Rect srcrect = {.x=(mocx<0?-mocx:0), .y=(mocy<0?-mocy:0), .w=mocw*VIDSCALE, .h=moch*VIDSCALE}; SDL_Rect dstrect = {.x=(mocx>0? mocx:0)*VIDSCALE, .y=(mocy>0? mocy:0)*VIDSCALE, .w=mocw*VIDSCALE, .h=moch*VIDSCALE}; SDL_RenderCopy(renderer, texlist[curtex], &srcrect, &dstrect); #endif } } int main(int argc, char *argv[]) { int x, y, i; // Open file FILE *fp = fopen(argv[1], "rb"); fprintf(stderr, "File open %s %p\n", argv[1], fp); // Read header if(fgetc(fp) != 'I') abort_msg("not a valid ICE2 video"); if(fgetc(fp) != 'C') abort_msg("not a valid ICE2 video"); if(fgetc(fp) != 'E') abort_msg("not a valid ICE2 video"); if(fgetc(fp) != '2') abort_msg("not a valid ICE2 video"); int fcls = fgetc(fp); if(fcls != 0x01) abort_msg("format class not supported"); int fscls = fgetc(fp); if(fscls != 0x01 && fscls != 0x02) abort_msg("format subclass not supported"); int fver = fgetc(fp); fver |= fgetc(fp)<<8; if(fver != 0x01) abort_msg("format version not supported"); vidw = fgetc(fp); vidw |= fgetc(fp)<<8; vidh = fgetc(fp); vidh |= fgetc(fp)<<8; if(vidw < 1) abort_msg("invalid width"); if(vidh < 1) abort_msg("invalid height"); // For OC mode, use double-height to get proper aspect ratio if(fscls == 0x01) { vidh *= 2; // Upscale further anyway vidw *= 4; vidh *= 4; } int fps = fgetc(fp); if(fps < 1) abort_msg("invalid framerate"); fgetc(fp); fgetc(fp); fgetc(fp); fprintf(stderr, "size: %i x %i\n", vidw, vidh); fprintf(stderr, "framerate: %i FPS\n", fps); // Read audio data int aufmt = fgetc(fp); int auchns = fgetc(fp); if(aufmt != 0x00 && aufmt != 0x01 && aufmt != 0x0A) abort_msg("ERROR: only U8 or DFPWM1a supported"); if(auchns != (aufmt == 0 ? 0 : 1)) abort_msg("ERROR: only mono audio supported"); fgetc(fp); fgetc(fp); int aufreq = fgetc(fp); aufreq |= fgetc(fp)<<8; aufreq |= fgetc(fp)<<16; aufreq |= fgetc(fp)<<24; assert(aufreq >= 0); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fgetc(fp); fprintf(stderr, "Header loaded, setting up SDL + audio\n"); // Init SDL if(aufmt != 0) { SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_AUDIO); SDL_AtomicSet(&aring_used, 0); SDL_AudioSpec auspec; memset(&auspec, 0, sizeof(SDL_AudioSpec)); fprintf(stderr, "output freq = %i\n", aufreq); fprintf(stderr, "channels = %i\n", auchns); auspec.freq = aufreq; auspec.format = AUDIO_U8; auspec.channels = auchns; auspec.samples = 2048; auspec.callback = authread; int err = SDL_OpenAudio(&auspec, NULL); fprintf(stderr, "open audio err: %d\n", err); assert(err >= 0); SDL_PauseAudio(0); } else { fprintf(stderr, "No audio\n"); SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); } fprintf(stderr, "Setting up palette\n"); // Set up OC palette if fmt subclass is 0x01 if(fscls == 0x01) { for(i = 0; i < 256; i++) { int r, g, b; pal_to_rgb(i, &r, &g, &b); r >>= 3; g >>= 2; b >>= 3; ocpal[i] = (r<<11)|(g<<5)|b; } } // Set up window + renderer window = SDL_CreateWindow("- intelligent cirno experience - player -" , SDL_WINDOWPOS_UNDEFINED , SDL_WINDOWPOS_UNDEFINED , vidw*VIDSCALE*VIDOUTSCALE, vidh*VIDSCALE*VIDOUTSCALE , 0); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); #ifdef SOFTWARE_BLIT_MODE // Set up texture for streaming texblit = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, vidw, vidh); #else // Set up textures as render targets texlist[0] = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_UNKNOWN, SDL_TEXTUREACCESS_TARGET, vidw*VIDSCALE, vidh*VIDSCALE); texlist[1] = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_UNKNOWN, SDL_TEXTUREACCESS_TARGET, vidw*VIDSCALE, vidh*VIDSCALE); #endif Uint32 ticks_now = SDL_GetTicks(); Uint32 ticks_later = ticks_now; int ticks_resid = 0; int ticks_resid_inc = 1000000/fps; #ifdef SOFTWARE_BLIT_MODE scrbuf = malloc(vidw*vidh*2); memset(scrbuf, 0, vidw*vidh*2); #endif // Now draw things! int fgcol = 0; int bgcol = 0; for(;;) { #ifndef SOFTWARE_BLIT_MODE // Set render target curtex ^= 1; SDL_SetRenderTarget(renderer, texlist[curtex]); curtex ^= 1; // Do straight copy SDL_RenderCopy(renderer, texlist[curtex], NULL, NULL); #endif int mocx = 0, mocy = 0; if(fscls != 0x01) { // Get mocomp info mocx = (int)(int8_t)fgetc(fp); mocy = (int)(int8_t)fgetc(fp); do_mocomp(mocx, mocy); } #ifndef SOFTWARE_BLIT_MODE curtex ^= 1; #endif // Draw rectangles //fprintf(stderr, "begrect %i %i\n", mocx, mocy); for(;;) { int offs, rw, rh, rx, ry; uint16_t col; if(fscls == 0x01) { // OC mode rh = fgetc(fp); assert(rh > 0); if(rh == 0xFF) break; if((rh & 0x80) != 0) { // Get mocomp info // XXX: this doesn't use the full featureset of a copy! // (it assumes largest possible rect for a given mocomp) fgetc(fp); fgetc(fp); fgetc(fp); int mocx = (int)(int8_t)fgetc(fp); int mocy = (int)(int8_t)fgetc(fp); do_mocomp(mocx*4, mocy*2*4); continue; } // Get remainder of rect ry = fgetc(fp); rw = fgetc(fp); rx = fgetc(fp); // Get colour if((rh & 0x40) != 0) { if((ry & 0x40) != 0) bgcol = fgetc(fp); col = ocpal[bgcol]; } else { if((ry & 0x40) != 0) fgcol = fgetc(fp); col = ocpal[fgcol]; } // Clear flag bits ry &= ~0x40; rh &= ~0x40; // Double-height rh *= 2; ry *= 2; // Further upscaling rx *= 4; ry *= 4; rw *= 4; rh *= 4; // Get offset offs = rx + ry*vidw; assert(offs >= 0); assert(offs < vidw*vidh); assert(rx >= 0); assert(ry >= 0); assert(rx+rw <= vidw); assert(ry+rh <= vidh); } else { // GBA+RPi mode // Get dims if(vidh >= 248 || vidw >= 256) { // 16-bit size mode rh = fgetc(fp); rh |= fgetc(fp)<<8; assert(rh > 0); if((rh>>8) == 0xFF) break; rw = fgetc(fp); rw |= fgetc(fp)<<8; assert(rw > 0); } else { // 8-bit size mode rh = fgetc(fp); assert(rh > 0); rw = fgetc(fp); if(rh == 0xFF) break; assert(rw > 0); } assert(rw <= vidw); assert(rh <= vidh); // Get offs offs = fgetc(fp); offs |= fgetc(fp)<<8; if(vidw*vidh >= 0x10000) { // 32-bit offset mode offs |= fgetc(fp)<<16; offs |= fgetc(fp)<<24; } assert(offs >= 0); assert(offs < vidw*vidh); // Turn offs into coords rx = offs%vidw; ry = offs/vidw; //fprintf(stderr, "%i %i %i %i %i\n", rx, ry, rw, rh, offs); assert(rx+rw <= vidw); assert(ry+rh <= vidh); // Get colour col = fgetc(fp); col |= fgetc(fp)<<8; // Convert to 16bpp + R/B swap col = (col & 0x001F)|((col & ~0x001F)<<1); col = (col & 0x07E0)|(col>>11)|(col<<11); } #ifdef SOFTWARE_BLIT_MODE // Expand to 32 bits uint32_t col32 = col; col32 |= col32<<16; // Do left border if(offs & 1) { for(y = 0; y < rh; y++) scrbuf[offs+y*vidw] = col; offs++; rw--; } // Do right border if(rw & 1) { for(y = 0; y < rh; y++) scrbuf[offs+(rw-1)+y*vidw] = col; rw--; } // Do centre uint32_t *p = (uint32_t *)&scrbuf[offs]; for(y = 0; y < rh; y++, p += (vidw>>1)) { for(x = 0; x < (rw>>1); x++) p[x] = col32; } #else // Split into RGB int cr = ((col>>11)&31)<<3; int cg = ((col>>5)&63)<<2; int cb = ((col>>0)&31)<<3; // Draw rect SDL_Rect r = {.x=rx*VIDSCALE, .y=ry*VIDSCALE, .w=rw*VIDSCALE, .h=rh*VIDSCALE}; SDL_SetRenderDrawColor(renderer, cr, cg, cb, SDL_ALPHA_OPAQUE); SDL_RenderFillRect(renderer, &r); #endif } // Parse audio if(aufmt != 0) { int ablen = fgetc(fp); ablen |= fgetc(fp)<<8; assert(ablen >= 0); if(ablen != 0) { fread(input_audio, ablen, 1, fp); uint8_t *insrc = input_audio; if(aufmt == 0x0A) { // Decompress DFPWM1a if(ablen > 0) { memcpy(dfpwm_tmp_buffer, input_audio, ablen); //assert(ablen <= 0x8000); au_decompress(&audecmp_fq, &audecmp_q, &audecmp_s, &audecmp_lt, CONST_POSTFILT, ablen, input_audio, dfpwm_tmp_buffer); ablen <<= 3; } } int realablen = ablen; if(ablen >= AUDIO_RING_BUF - aring_end) { // Read until buffer end int bufdec = (AUDIO_RING_BUF - aring_end); memcpy(aring_data + aring_end, insrc, bufdec); insrc += bufdec; // Wrap values ablen -= bufdec; aring_end = 0; } // Read remaining data if(ablen > 0) { memcpy(aring_data + aring_end, insrc, ablen); aring_end += ablen; } // Add to audio ring buffer int incr = SDL_AtomicAdd(&aring_used, realablen); assert(incr < AUDIO_RING_BUF); // Align if((realablen & 1) != 0) fgetc(fp); } } // Blit #ifdef SOFTWARE_BLIT_MODE uint16_t *targ = NULL; int pitch = 0; SDL_LockTexture(texblit, NULL, (void **)&targ, &pitch); assert(targ != NULL); if(pitch == vidw*2) { memcpy(targ, scrbuf, 2*vidw*vidh); } else { for(y = 0; y < vidh; y++) memcpy(targ + y*(pitch>>1), scrbuf + y*vidw, 2*vidw); } SDL_UnlockTexture(texblit); SDL_RenderCopy(renderer, texblit, NULL, NULL); #else SDL_SetRenderTarget(renderer, NULL); SDL_RenderCopy(renderer, texlist[curtex], NULL, NULL); #endif SDL_RenderPresent(renderer); // Wait ticks_resid += ticks_resid_inc; ticks_later += (ticks_resid/10000)*10; ticks_resid %= 10000; ticks_now = SDL_GetTicks(); if((int32_t)(ticks_later - ticks_now) >= 10) SDL_Delay(ticks_later - ticks_now); //fprintf(stderr, "%.3f\n", ticks_now/1000.0); // Poll int doret = 0; SDL_Event ev; while(SDL_PollEvent(&ev)) switch(ev.type) { case SDL_QUIT: doret = 1; break; } if(doret) break; } #ifdef SOFTWARE_BLIT_MODE free(scrbuf); #endif return 0; }
20.630769
102
0.588977
bebb4bfdd8d27af2f15edb40a520dccb10778f6b
178
h
C
spiflash/src/test_spi.h
Bergi84/vihaltests
f338e6aff3e389501dc8a018f1dbde862b7971a1
[ "BSD-2-Clause" ]
null
null
null
spiflash/src/test_spi.h
Bergi84/vihaltests
f338e6aff3e389501dc8a018f1dbde862b7971a1
[ "BSD-2-Clause" ]
null
null
null
spiflash/src/test_spi.h
Bergi84/vihaltests
f338e6aff3e389501dc8a018f1dbde862b7971a1
[ "BSD-2-Clause" ]
2
2022-01-05T01:53:54.000Z
2022-03-14T19:58:29.000Z
/* * test_spi.h * * Created on: Oct 7, 2021 * Author: vitya */ #ifndef SRC_TEST_SPI_H_ #define SRC_TEST_SPI_H_ void test_spiflash(); #endif /* SRC_TEST_SPI_H_ */
11.125
28
0.651685
849096fec34c45ac4863637bb6d3886af4c66144
10,767
h
C
osprey/libu/util/targlib.h
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/libu/util/targlib.h
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/libu/util/targlib.h
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ /* USMID @(#) libu/util/targlib.h 92.2 11/24/99 14:11:55 */ #ifdef _UNICOS typedef long LL_int; #else typedef long long LL_int; #endif #ifdef _UNICOS typedef unsigned long int ULL_int; #else /* Sun */ typedef unsigned long long int ULL_int; #endif /* primary machine types: */ /* should match order in array pmt[] */ #define PM_HOST 0 #define PM_TARGET 1 #define PM_IOP 2 #define PM_CRAY_YMP 3 #define PM_CRAY_C90 4 #define PM_CRAY_T3D 5 #define PM_CRAY_EL 6 #define PM_CRAY_TS 7 #define PM_CRAY_T3E 8 #define PM_CRAY_J90 9 #define PM_CRAY_JSE 10 #define PM_CRAY_SV1 11 #define PM_CRAY_SV2 12 #ifndef _UNICOS #define PM_SPARC 13 #endif #define PM_STARHOST (sizeof(pmt)/sizeof(struct pmttab) -2) #define PM_STARTARGET (sizeof(pmt)/sizeof(struct pmttab) -1) #define PMTYPES PM_STARHOST /* Number of primary machine types (not counting *host and *target) */ #define BLANK ((int) ' ') /* Values for pmttab.mtype */ /* This is an internal value - it is used to determine */ /* whether a particular characteristic is valid on a machine type */ #define MPPTYPE 04 /* mpp */ #define IOPTYPE 010 /* iop */ #define YMPTYPE 020 /* cray-ymp */ #define C90TYPE 040 /* cray-c90 */ #define TSTYPE 0100 /* Cray-ts */ #define UNKNOWNTYP 0200 /* Unknown */ #define SPARCTYPE 0400 /* Sparc */ #define SV1TYPE 01000 /* cray-sv1 (primary type) */ #define SV2TYPE 02000 /* cray-sv2 */ /* machine names: */ struct pmttab { char *name; /* machine name */ long mtype; /* machine type */ }; #ifdef _UNICOS #ifdef _CRAY1 #define HOSTTYPE UNKNOWNTYP #endif #ifdef _CRAYMPP #define HOSTTYPE MPPTYPE #endif #ifndef HOSTTYPE #error UNKNOWN TARGET MACHINE #endif #else /* Sun */ #define HOSTTYPE SPARCTYPE #endif /* ASCII machine names for mctable */ #define MAKE_NAME(C1, C2, C3, C4, C5, C6, C7, C8) \ (((ULL_int)C1)<<56 | ((ULL_int)C2)<<48 | \ ((ULL_int)C3)<<40 | ((ULL_int)C4)<<32 | \ ((ULL_int)C5)<<24 | ((ULL_int)C6)<<16 | \ ((ULL_int)C7)<<8 | ((ULL_int)C8)) #define HOST_NAME MAKE_NAME('H','O','S','T','\0','\0','\0','\0') #define TARGET_NAME MAKE_NAME('T','A','R','G','E','T','\0','\0') #define CRAY_YMP_NAME MAKE_NAME('C','R','A','Y','-','Y','M','P') #define CRAY_C90_NAME MAKE_NAME('C','R','A','Y','-','C','9','0') #define CRAY_T3D_NAME MAKE_NAME('C','R','A','Y','-','T','3','D') #define CRAY_TS_NAME MAKE_NAME('C','R','A','Y','-','T','S','\0') #define CRAY_T3E_NAME MAKE_NAME('C','R','A','Y','-','T','3','E') #define CRAY_SV1_NAME MAKE_NAME('C','R','A','Y','-','S','V','1') #define CRAY_SV2_NAME MAKE_NAME('C','R','A','Y','-','S','V','2') #define IOP_NAME MAKE_NAME('I','O','P','\0','\0','\0','\0','\0') #define SPARC_NAME MAKE_NAME('S','P','A','R','C','\0','\0','\0') #define CRAY_NAME MAKE_NAME('C','R','A','Y','\0','\0','\0','\0') #define CRAY_EL_SUBTYPE MAKE_NAME('C','R','A','Y','-','E','L','\0') #define CRAY_J90_SUBTYPE MAKE_NAME('C','R','A','Y','-','J','9','0') #define CRAY_JSE_SUBTYPE MAKE_NAME('C','R','A','Y','-','J','S','E') #define CRAY_SV1_SUBTYPE MAKE_NAME('C','R','A','Y','-','S','V','1') #define CRAY_TSIEEE_SUBTYPE0 MAKE_NAME('C','R','A','Y','-','T','S','-') #define CRAY_TSIEEE_SUBTYPE1 MAKE_NAME('I','E','E','E','\0','\0','\0','\0') /* machine characteristics: */ /* should match mcoffs */ #define PRIMARY 0 #define BANKS 1 #define NUMCPUS 2 #define IBUFSIZE 3 #define MEMSIZE 4 #define MEMSPEED 5 #define CLOCKTIM 6 #define NUMCLSTR 7 #define BANKBUSY 8 #define SUBTYPE 9 #define EMA 10 #define NOEMA 11 #define CIGS 12 #define NOCIGS 13 #define VPOP 14 #define NOVPOP 15 #define PC 16 #define NOPC 17 #define READVL 18 #define NOREADVL 19 #define VRECUR 20 #define NOVRECUR 21 #define AVL 22 #define NOAVL 23 #define HPM 24 #define NOHPM 25 #define BDM 26 #define NOBDM 27 #define STATRG 28 #define NOSTATRG 29 #define CORI 30 #define NOCORI 31 #define ADDR32 32 #define NOADDR32 33 #define XEA 34 #define NOXEA 35 #define BMM 36 #define NOBMM 37 #define AVPOP 38 #define NOAVPOP 39 #define FULLSECT 40 /* Deprecated */ #define NOFULLSECT 41 /* Deprecated */ #define IEEE 42 #define NOIEEE 43 #define CMRREQ 44 /* Deprecated */ #define NOCMRREQ 45 /* Deprecated */ #define CACHE 46 /* Deprecated */ #define NOCACHE 47 /* Deprecated */ #define NUMMCHARS 44 /* Number of machine characteristics. Do not */ /* count the deprecated characteristics that. */ /* follow the last usable characteristic. */ #define T ((ULL_int) -1) #define F 0 struct mctable{ /* 128-word machine characteristics table */ /* numeric machine characteristics */ ULL_int mcpmt; ULL_int mcbank; ULL_int mcncpu; ULL_int mcibsz; ULL_int mcmsz; ULL_int mcmspd; ULL_int mcclk; ULL_int mcncl; ULL_int mcbbsy; ULL_int mcclktck; ULL_int mcserial; ULL_int mcrls; ULL_int mc_c_option_rev; ULL_int mc_i_option_rev; ULL_int mc_r_option_rev; ULL_int mc_m_option_rev_0; ULL_int mc_m_option_rev_1; ULL_int mc_m_option_rev_2; ULL_int mc_m_option_rev_3; ULL_int mcsubt[2]; ULL_int numeric_unused[43]; /* logical machine characteristics */ union { struct { ULL_int mcema; ULL_int mccigs; ULL_int mcvpop; ULL_int mcpc; ULL_int mcrdvl; ULL_int mcvrcr; ULL_int mcavl; ULL_int mchpm; ULL_int mcbdm; ULL_int mcstr; ULL_int mccori; ULL_int mcaddr32; ULL_int mcxea; ULL_int mcbmm; ULL_int mcavpop; ULL_int mcfullsect; /* Deprecated. Do not reuse, as this */ /* may be set for Cray-ts by some older */ /* compilers. */ ULL_int mcieee; ULL_int mccmrreq; /* Deprecated. Do not reuse. */ ULL_int mccache; /* Deprecated. Do not reuse. */ ULL_int logical_unused[45]; } mctblxy; } mctlog; }; #define MC500K 524288 #define MC1MEG 1048576 #define MC2MEG MC1MEG*2 #define MC4MEG MC1MEG*4 #define MC8MEG MC1MEG*8 #define MC16MEG MC1MEG*16 #define MC32MEG MC1MEG*32 #define MC64MEG MC1MEG*64 #define MC256MEG MC1MEG*256 #define MC1024MEG MC1MEG*1024 struct pdttable{ #ifdef _UNICOS unsigned : 48 ; /* unused-reserved by CRI */ #else unsigned : 32 ; /* unused-reserved by CRI */ unsigned : 16 ; /* unused-reserved by CRI */ #endif unsigned length : 16 ; /* word size of machine type */ ULL_int machine ; /* basic machine type-ASCII */ union{ struct { unsigned unused_1 : 15 ; /* unused "and" bits - reserved */ /* by CRI */ unsigned bdmsafe : 1 ; /* bidirectional memory "safe" */ /* Settable only by compilers */ unsigned unused_2 : 16 ; /* unused-reserved by CRI */ unsigned unused_3 : 12 ; /* unused-reserved by CRI */ unsigned cache : 1 ; /* cache. Deprecated */ unsigned cmrreq : 1 ; /* CMR required. Deprecated */ unsigned ieee : 1 ; /* IEEE arithmetic */ unsigned fullsect : 1 ; /* full memory section. Deprecated */ unsigned avpop : 1 ; /* additional vector pop count */ unsigned bmm : 1 ; /* bit matrix multiply unit */ unsigned addr32 : 1 ; /* YMP 32-bit addressing require*/ unsigned cori : 1 ; /* control operand range intrpts*/ unsigned clsreq : 1 ; /* cluster registers required */ unsigned str : 1 ; /* status register required */ unsigned bdm : 1 ; /* bidirectional memory flag */ unsigned hpm : 1 ; /* hardware performance flag */ unsigned avl : 1 ; /* additional vector unit */ unsigned nvrcr : 1 ; /* no vector recursion */ unsigned vrcr : 1 ; /* vector recursion */ unsigned rdvl : 1 ; /* can read vector length */ unsigned pc : 1 ; /* programmable clock flag */ unsigned cigs : 1 ; /* compress/index gather/scatter*/ unsigned ema : 1 ; /* extended addressing required */ unsigned vpop : 1 ; /* vector pop count required */ } pdtxy; struct { unsigned andmask : 16 ; unsigned unused_1 : 16 ; /* unused-reserved by CRI */ unsigned mask : 32 ; } pdtmask; } word2; }; /* PDTORBITS indicates which bits in pdttable.pdtxy can be or'ed together */ /* in VALTMC */ #define PDTORBITS 03377637 struct mcoffs { int wrd; /* word in pdt containing this field */ int strt; /* starting bit position of field in PDT*/ int len; /* length in bits in pdt */ int indx; /* offset to word in machine char. table*/ int type; /* logical or numeric (1 = logical) */ int def; /* default value */ long mach; /* bit mask defining where this is a valid char. */ long canset; /* bit mask defining where this can be set */ char *mcname; /* name of characteristic */ }; #define C1TYPE (C90TYPE | YMPTYPE | SV1TYPE | TSTYPE ) #define C90_XY_TYPE (C90TYPE | YMPTYPE | SV1TYPE ) #define ALLTYPE (C1TYPE | MPPTYPE | IOPTYPE | SPARCTYPE | SV2TYPE) void _setsubtype(int ipm, struct mctable *mctable); void __setsv1type(struct mctable *mctable); void _setsubtype2(int ipm, struct mctable *mctable);
32.430723
76
0.630816
41e2419fc4f45ff7d2187f915fe69bbb700f86a3
588
h
C
hls/triangle_intersect.h
justingallagher/fpga-trace
53ac2dd9ea1bff7e78b1de6d097d477e3d956463
[ "MIT" ]
25
2016-11-14T23:23:53.000Z
2020-12-17T08:29:41.000Z
hls/triangle_intersect.h
justingallagher/fpga-trace
53ac2dd9ea1bff7e78b1de6d097d477e3d956463
[ "MIT" ]
null
null
null
hls/triangle_intersect.h
justingallagher/fpga-trace
53ac2dd9ea1bff7e78b1de6d097d477e3d956463
[ "MIT" ]
1
2020-03-22T12:04:52.000Z
2020-03-22T12:04:52.000Z
/** * @file triangle_intersect.h * @brief High level logic for the Triangle Intersection IP used in the FPGA * design. * @author Justin Gallagher (jrgallag) * @since 05-05-2016 */ #ifndef _HLS_TRIANGLE_INTERSECT_H_ #define _HLS_TRIANGLE_INTERSECT_H_ #include "ap_int.h" #define PARALLEL_TESTS 2 typedef struct { float data; ap_uint<4> keep; ap_uint<4> strb; ap_uint<1> user; ap_uint<1> last; ap_uint<1> id; ap_uint<1> dest; } data_t; // Performs a triangle intersection void tri_intersect(data_t ins[15], data_t outs[3]); #endif /* _HLS_TRIANGLE_INTERSECT_H_ */
19.6
76
0.72619
70f6bd74982708486f0c60a16fdb02d9bfe3a814
1,323
c
C
src/free.c
AdrianWR/push_swap
f3ee34f544375b314c4b5e6ec0f952ece4476686
[ "MIT" ]
7
2021-05-23T23:03:09.000Z
2022-03-26T22:18:38.000Z
src/free.c
AdrianWR/push_swap
f3ee34f544375b314c4b5e6ec0f952ece4476686
[ "MIT" ]
null
null
null
src/free.c
AdrianWR/push_swap
f3ee34f544375b314c4b5e6ec0f952ece4476686
[ "MIT" ]
2
2021-12-23T13:26:54.000Z
2022-03-12T10:45:29.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aroque <aroque@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/06 20:59:32 by aroque #+# #+# */ /* Updated: 2021/05/02 19:33:50 by aroque ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "libft.h" #include "stack.h" void free_array(void **array) { size_t i; i = 0; while (array[i]) free(array[i++]); free(array); } void free_stack(t_stack *stack) { free(stack->array); free(stack); } void message_and_exit(t_stack *stack, char **ops, int status) { if (stack) free_stack(stack); if (ops) free_array((void **)ops); ft_putstr_fd("Error\n", STDERR_FILENO); exit(status); }
31.5
80
0.28647
cb6295a7524aad8cbceca997a5d3f8e62a702020
641
h
C
Library/UILib/combobox.h
ysm1180/NewJojoGame
d46be6e979642ed3f139ad7905c983ac03356dd2
[ "MIT" ]
6
2018-10-12T08:06:35.000Z
2019-01-20T12:53:35.000Z
Library/UILib/combobox.h
ysm1180/ThreeKingdoms-Caocao
d46be6e979642ed3f139ad7905c983ac03356dd2
[ "MIT" ]
2
2018-10-12T08:09:05.000Z
2019-01-20T12:55:27.000Z
Library/UILib/combobox.h
ysm1180/NewJojoGame
d46be6e979642ed3f139ad7905c983ac03356dd2
[ "MIT" ]
2
2018-05-19T17:49:23.000Z
2018-10-15T03:10:57.000Z
#pragma once #include <vector> #include "text_font.h" #include "child_control.h" namespace three_kingdoms { class CComboBoxControl : public CWindowChildControl { public: static void RegisterFunctions(lua_State *L); CComboBoxControl(); virtual ~CComboBoxControl(); void AddItem(std::wstring item); bool Create() override; static WNDPROC GetOriginalProc(); static LRESULT CALLBACK OnControlProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); private: CTextFont _font; std::vector<std::wstring> _items; static WNDPROC s_originalProc; }; } // namespace three_kingdoms
21.366667
75
0.705148
b9d71fe4199dd5948e27316582cc6b9249ab60de
477
h
C
Bwl.Hardware.MotorControllerTwo.Fw/pwm.h
Lifemotion/Bwl.Hardware.MotorControllers
3fd9746e46dc14ec897acb1a1358cc3a2dd77757
[ "Apache-2.0" ]
1
2021-07-21T03:55:42.000Z
2021-07-21T03:55:42.000Z
Bwl.Hardware.MotorControllerTwo.Fw/pwm.h
Lifemotion/Bwl.Hardware.MotorControllers
3fd9746e46dc14ec897acb1a1358cc3a2dd77757
[ "Apache-2.0" ]
null
null
null
Bwl.Hardware.MotorControllerTwo.Fw/pwm.h
Lifemotion/Bwl.Hardware.MotorControllers
3fd9746e46dc14ec897acb1a1358cc3a2dd77757
[ "Apache-2.0" ]
1
2021-07-21T03:55:43.000Z
2021-07-21T03:55:43.000Z
#ifndef PWM_H_ #define PWM_H_ #define PWM_CHANNELS 8 #define PWM_TOP 50 #define SERVO_CHANNELS 8 #define SERVO_TOP 400 #define SERVO_START SERVO_TOP*0.050 #define SERVO_END SERVO_TOP*0.100 typedef unsigned char byte; //must be defined void servo_set_out(byte channel, byte state); void pwm_set_out(byte channel, byte state); //can net used void pwm_set(byte channel, byte value); void servo_set(byte channel, byte value); void pwm(); void servo(); #endif /* PWM_H_ */
19.08
45
0.763103
7d02d1cb0f32456aea58350bef367ab071afbcd1
6,640
h
C
statechart/platform/test_util.h
google/statechar
d283cefab5a051a91c21be46d97bc18407fd7628
[ "Apache-2.0" ]
93
2018-05-02T06:31:13.000Z
2022-03-30T07:32:47.000Z
statechart/platform/test_util.h
google/statechar
d283cefab5a051a91c21be46d97bc18407fd7628
[ "Apache-2.0" ]
2
2019-07-10T18:15:27.000Z
2022-01-01T19:41:18.000Z
statechart/platform/test_util.h
google/statechar
d283cefab5a051a91c21be46d97bc18407fd7628
[ "Apache-2.0" ]
31
2018-06-03T08:31:54.000Z
2021-10-16T22:52:44.000Z
/* * Copyright 2018 The StateChart Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef STATECHART_PLATFORM_TEST_UTIL_H_ #define STATECHART_PLATFORM_TEST_UTIL_H_ #include <string> #include <type_traits> #include "statechart/platform/protobuf.h" #include <glog/logging.h> #include <glog/log_severity.h> #include <gmock/gmock.h> //namespace proto2 { //namespace contrib { //namespace parse_proto { // //template <typename T> //T ParseTextOrDie(const string& input) { // T result; // CHECK(proto2::TextFormat::ParseFromString(input, &result)); // return result; //} // //} // namespace parse_proto //} // namespace contrib //} // namespace proto2 namespace base_logging { using ::google::INFO; using ::google::WARNING; using ::google::ERROR; using ::google::FATAL; using ::google::NUM_SEVERITIES; } // namespace base_logging namespace testing { namespace proto { template<typename T> T IgnoringRepeatedFieldOrdering(T t) { return t; } } // namespace proto MATCHER_P(EqualsProto, expected_str, "") { proto2::util::MessageDifferencer differencer; string diff; differencer.ReportDifferencesToString(&diff); // We must put 'expected' as the first argument here, as Compare() // reports the diff in terms of how the protobuf changes from the // first argument to the second argument. const auto expected = ::proto2::contrib::parse_proto::ParseTextOrDie<typename std::remove_cv< typename std::remove_reference<arg_type>::type>::type>(expected_str); bool same = differencer.Compare(expected, arg); if (!same) { *result_listener << diff; } return same; } MATCHER_P(EqualsProtobuf, expected, "") { proto2::util::MessageDifferencer differencer; string diff; differencer.ReportDifferencesToString(&diff); // We must put 'expected' as the first argument here, as Compare() // reports the diff in terms of how the protobuf changes from the // first argument to the second argument. bool same = differencer.Compare(expected, arg); if (!same) { *result_listener << diff; } return same; } enum LogCapturingState_ { kDoNotCaptureLogsYet }; class ScopedMockLog : public ::google::LogSink { public: // When a ScopedMockLog object is constructed, it starts to // intercept logs. ScopedMockLog() { ::google::AddLogSink(this); } explicit ScopedMockLog(LogCapturingState_ /* dummy */) {} // When the object is destructed, it stops intercepting logs. virtual ~ScopedMockLog() { ::google::RemoveLogSink(this); } void StartCapturingLogs() { ::google::AddLogSink(this); } // Implements the mock method: // // void Log(LogSeverity severity, const string& file_path, // const string& message); // // The second argument to Send() is the full path of the source file // in which the LOG() was issued. // // Note, that in a multi-threaded environment, all LOG() messages from a // single thread will be handled in sequence, but that cannot be guaranteed // for messages from different threads. In fact, if the same or multiple // expectations are matched on two threads concurrently, their actions will // be executed concurrently as well and may interleave. MOCK_METHOD3(Log, void(::google::LogSeverity severity, const std::string& file_path, const std::string& message)); private: // Implements the send() virtual function in class LogSink. // Whenever a LOG() statement is executed, this function will be // invoked with information presented in the LOG(). // // The method argument list is long and carries much information a // test usually doesn't care about, so we trim the list before // forwarding the call to Log(), which is much easier to use in // tests. // // We still cannot call Log() directly, as it may invoke other LOG() // messages, either due to Invoke, or due to an error logged in // Google C++ Mocking Framework code, which would trigger a deadlock // since a lock is held during send(). // // Hence, we save the message for WaitTillSent() which will be called after // the lock on send() is released, and we'll call Log() inside // WaitTillSent(). Since while a single send() call may be running at a // time, multiple WaitTillSent() calls (along with the one send() call) may // be running simultaneously, we ensure thread-safety of the exchange between // send() and WaitTillSent(), and that for each message, LOG(), send(), // WaitTillSent() and Log() are executed in the same thread. virtual void send(::google::LogSeverity severity, const char* full_filename, const char* /*base_filename*/, int /*line*/, const tm* /*tm_time*/, const char* message, size_t message_len) { // We are only interested in the log severity, full file name, and // log message. message_info_.severity = severity; message_info_.file_path = full_filename; message_info_.message = std::string(message, message_len); } // Implements the WaitTillSent() virtual function in class LogSink. // It will be executed after send() and after the global logging lock is // released, so calls within it (or rather within the Log() method called // within) may also issue LOG() statements. // // LOG(), send(), WaitTillSent() and Log() will occur in the same thread for // a given log message. virtual void WaitTillSent() { // First, and very importantly, we save a copy of the message being // processed before calling Log(), since Log() may indirectly call send() // and WaitTillSent() in the same thread again. MessageInfo message_info = message_info_; Log(message_info.severity, message_info.file_path, message_info.message); } // All relevant information about a logged message that needs to be passed // from send() to WaitTillSent(). struct MessageInfo { ::google::LogSeverity severity; std::string file_path; std::string message; }; MessageInfo message_info_; }; } // namespace testing #endif // SRC_PLATFORM_PROTOBUF_MATCHER_H_
34.764398
79
0.700753
f1f75260e34b58e626be4ee1e1fef22e1cb9c5f5
351
h
C
iPhone/Classes/L0DraggableNavigationBar.h
davgit/diceshaker
5c99c8a8ce3044eabc7281b0dcfc965d11b5af27
[ "BSD-3-Clause" ]
1
2019-06-27T11:55:09.000Z
2019-06-27T11:55:09.000Z
iPhone/Classes/L0DraggableNavigationBar.h
deminew/diceshaker
5c99c8a8ce3044eabc7281b0dcfc965d11b5af27
[ "BSD-3-Clause" ]
null
null
null
iPhone/Classes/L0DraggableNavigationBar.h
deminew/diceshaker
5c99c8a8ce3044eabc7281b0dcfc965d11b5af27
[ "BSD-3-Clause" ]
null
null
null
// // L0DraggableNavigationBar.h // Diceshaker // // Created by ∞ on 13/02/09. // Copyright 2009 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface L0DraggableNavigationBar : UINavigationBar { IBOutlet id touchTarget; SEL touchAction; } @property (assign) id touchTarget; @property (assign) SEL touchAction; @end
16.714286
58
0.732194
35016d5435961bf9b9ceda6efc92a72856c21108
711
h
C
src/util/qml/qmlconfig.h
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/util/qml/qmlconfig.h
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/util/qml/qmlconfig.h
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #pragma once #include <QtGlobal> #if defined(leechcraft_util_qml_EXPORTS) || defined(leechcraft_util_qml_qt5_EXPORTS) # define UTIL_QML_API Q_DECL_EXPORT #else # define UTIL_QML_API Q_DECL_IMPORT #endif /** @defgroup QmlUtil The QML utilities * * @brief Common QML-related classes and functions. */
30.913043
84
0.611814
75c2df0b1ab3460a9f88ff34bd0a3d144bfc45d6
230
c
C
ports/polish/libgadu/dragonfly/patch-examples_conn-async.c
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
31
2015-02-06T17:06:37.000Z
2022-03-08T19:53:28.000Z
ports/polish/libgadu/dragonfly/patch-examples_conn-async.c
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
236
2015-06-29T19:51:17.000Z
2021-12-16T22:46:38.000Z
ports/polish/libgadu/dragonfly/patch-examples_conn-async.c
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
52
2015-02-06T17:05:36.000Z
2021-10-21T12:13:06.000Z
--- examples/conn-async.c.orig 2017-01-21 17:57:03 UTC +++ examples/conn-async.c @@ -27,6 +27,7 @@ #include <errno.h> #include <string.h> #include <time.h> +#include <sys/select.h> #include "libgadu.h" #include "network.h"
20.909091
54
0.647826
784147a8d766649252a35f90a2d7f2af5182e2bb
1,224
h
C
repo/iOSBinaryDump/Headers/PokemonGO-1.7.0-Headers/GIDGoogleUser.h
kallism/kallism.github.io
7c75f69a870b44a87d6ec5654212cf616880d7bb
[ "Apache-2.0" ]
2
2016-09-15T09:39:42.000Z
2020-12-27T23:11:08.000Z
repo/iOSBinaryDump/Headers/PokemonGO-1.7.0-Headers/GIDGoogleUser.h
kallism/kallism.github.io
7c75f69a870b44a87d6ec5654212cf616880d7bb
[ "Apache-2.0" ]
null
null
null
repo/iOSBinaryDump/Headers/PokemonGO-1.7.0-Headers/GIDGoogleUser.h
kallism/kallism.github.io
7c75f69a870b44a87d6ec5654212cf616880d7bb
[ "Apache-2.0" ]
7
2015-07-30T22:02:41.000Z
2020-01-16T10:16:15.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" #import "NSCoding.h" @class GIDAuthentication, GIDProfileData, NSArray, NSString; @interface GIDGoogleUser : NSObject <NSCoding> { NSString *_userID; GIDProfileData *_profile; GIDAuthentication *_authentication; NSArray *_accessibleScopes; NSString *_hostedDomain; NSString *_serverAuthCode; } @property(readonly, nonatomic) NSString *serverAuthCode; // @synthesize serverAuthCode=_serverAuthCode; @property(readonly, nonatomic) NSString *hostedDomain; // @synthesize hostedDomain=_hostedDomain; @property(readonly, nonatomic) NSArray *accessibleScopes; // @synthesize accessibleScopes=_accessibleScopes; @property(readonly, nonatomic) GIDAuthentication *authentication; // @synthesize authentication=_authentication; @property(readonly, nonatomic) GIDProfileData *profile; // @synthesize profile=_profile; @property(readonly, nonatomic) NSString *userID; // @synthesize userID=_userID; - (void).cxx_destruct; - (void)encodeWithCoder:(id)arg1; - (id)initWithCoder:(id)arg1; - (id)initWithAuthentication:(id)arg1 scopes:(id)arg2; @end
34
112
0.762255
a3eeecce8fe9b5f9490c278048e4ea90d4ae1a1b
9,261
c
C
src/test-multipart-parser.c
jow-/lucihttp
3dc89af443410c9eae7a0ff091bd7fb4c5d48f41
[ "MIT" ]
1
2019-08-15T07:43:22.000Z
2019-08-15T07:43:22.000Z
src/test-multipart-parser.c
Lmagic200/lucihttp
a34a17d501c0e23f0a91dd9d3e87697347c861ba
[ "MIT" ]
2
2018-05-09T01:59:06.000Z
2020-01-03T09:55:23.000Z
src/test-multipart-parser.c
Lmagic200/lucihttp
a34a17d501c0e23f0a91dd9d3e87697347c861ba
[ "MIT" ]
3
2018-11-09T06:49:05.000Z
2022-02-22T06:29:11.000Z
/* * lucihttp - HTTP utility library - multipart parser tester * * Copyright 2018 Jo-Philipp Wich <jo@mein.io> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <lucihttp/multipart-parser.h> #include <lucihttp/utils.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <libgen.h> #include <dirent.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> struct test_context { bool is_file; char *header; char *expect_error; char *expect_pname; char *expect_pvalue; char *expect_hname; char *expect_hvalue; bool matched_error; bool matched_pname; bool matched_pvalue; bool matched_hname; bool matched_hvalue; size_t bufsize; const char *dumpprefix; unsigned int dumpcount; int dumpfd; }; static void xfree(void *p) { if (p) free(p); } static char *memdup(const char *data, char **copy, size_t len) { xfree(*copy); if (!data || !len) return NULL; *copy = calloc(1, len + 1); if (!*copy) return NULL; memcpy(*copy, data, len); return *copy; } static bool test_callback(struct lh_mpart *p, enum lh_mpart_callback_type type, const char *buffer, size_t length, void *priv) { char *tok = NULL, *name = NULL, *file = NULL; struct test_context *ctx = priv; char path[1024]; switch (type) { case LH_MP_CB_HEADER_NAME: memdup(buffer, &ctx->header, length); if (ctx->header && ctx->expect_hname && !strcasecmp(ctx->header, ctx->expect_hname)) ctx->matched_hname = true; break; case LH_MP_CB_HEADER_VALUE: if (ctx->header && !strcasecmp(ctx->header, "content-disposition")) { tok = lh_header_attribute(buffer, length, NULL, NULL); if (!strcasecmp(tok, "form-data")) { name = lh_header_attribute(buffer, length, "name", NULL); file = lh_header_attribute(buffer, length, "filename", NULL); if (name && ctx->expect_pname && !strcmp(name, ctx->expect_pname)) ctx->matched_pname = true; ctx->is_file = !!file; if (ctx->is_file && ctx->dumpprefix) { snprintf(path, sizeof(path), "%s.%u", ctx->dumpprefix, ctx->dumpcount); ctx->dumpfd = open(path, O_WRONLY|O_CREAT|O_EXCL, 0644); if (ctx->dumpfd < 0) fprintf(stderr, "Unable to create file %s: %s\n", path, strerror(errno)); else ctx->dumpcount++; } xfree(name); xfree(file); } xfree(tok); } if (buffer && ctx->expect_hvalue && length == strlen(ctx->expect_hvalue) && !memcmp(buffer, ctx->expect_hvalue, strlen(ctx->expect_hvalue))) ctx->matched_hvalue = true; break; case LH_MP_CB_PART_BEGIN: /* only buffer non-file data */ return !ctx->is_file; case LH_MP_CB_PART_DATA: if (buffer && ctx->dumpfd >= 0) write(ctx->dumpfd, buffer, length); else if (buffer && ctx->expect_pvalue && length == strlen(ctx->expect_pvalue) && !memcmp(buffer, ctx->expect_pvalue, strlen(ctx->expect_pvalue))) ctx->matched_pvalue = true; break; case LH_MP_CB_PART_END: if (ctx->dumpfd >= 0) { close(ctx->dumpfd); ctx->dumpfd = -1; } break; case LH_MP_CB_ERROR: if (buffer && ctx->expect_error && !strcmp(buffer, ctx->expect_error)) ctx->matched_error = true; break; default: break; } return true; } static int run_test(FILE *trace, const char *path, const char *dumpprefix, size_t bufsize) { struct test_context ctx = { .bufsize = bufsize ? bufsize : 128, .dumpprefix = dumpprefix, .dumpfd = -1 }; struct lh_mpart *p = NULL; bool ok = true; char line[4096]; int rv = -1; FILE *file; size_t i; printf("Testing %-40s ... ", basename((char *)path)); file = fopen(path, "r"); if (!file) { fprintf(stderr, "Unable to open file: %s\n", strerror(errno)); goto out; } p = lh_mpart_new(trace); if (!p) { fprintf(stderr, "Out of memory\n"); goto out; } while (fgets(line, sizeof(line), file)) { if (!strncmp(line, "Content-Type: ", 14) && !lh_mpart_parse_boundary(p, line + 14, NULL)) { fprintf(stderr, "Invalid boundary header\n"); goto out; } else if (!bufsize && !strncmp(line, "X-Buffer-Size: ", 15)) { unsigned int n = 0; char *p = NULL; n = strtoul(line + 15, &p, 0); if (line + 15 == p || *p != '\r' || n < 1 || n > sizeof(line)) { fprintf(stderr, "Invalid buffer size\n"); goto out; } ctx.bufsize = n; } else if (!strncmp(line, "X-Expect-", 9)) { char *p = NULL, **q = NULL; if (!strncmp(line + 9, "Error:", 6)) { p = line + 9 + 6; q = &ctx.expect_error; } else if (!strncmp(line + 9, "Part-Name:", 10)) { p = line + 9 + 10; q = &ctx.expect_pname; } else if (!strncmp(line + 9, "Part-Value:", 11)) { p = line + 9 + 11; q = &ctx.expect_pvalue; } else if (!strncmp(line + 9, "Header-Name:", 12)) { p = line + 9 + 12; q = &ctx.expect_hname; } else if (!strncmp(line + 9, "Header-Value:", 13)) { p = line + 9 + 13; q = &ctx.expect_hvalue; } if (p && q) { while (*p == ' ' || *p == '\t') p++; for (i = strlen(p) - 1; i > 0; i--) if (p[i] != ' ' && p[i] != '\t' && p[i] != '\r' && p[i] != '\n') break; p[i + 1] = 0; if (!strncmp(p, "urlencoded:", 11)) *q = lh_urldecode(p + 11, strlen(p + 11), NULL, 0); else *q = strdup(p); } } else if (!strcmp(line, "\r\n")) { break; } } lh_mpart_set_callback(p, test_callback, &ctx); while ((i = fread(line, 1, ctx.bufsize, file)) > 0) { ok = lh_mpart_parse(p, line, i); if (!ok) break; } if (ok) lh_mpart_parse(p, NULL, 0); if (!ctx.expect_error && p->error) { printf("ERROR: Expected parser to finish but got error:\n [%s]\n", p->error); goto out; } else if (ctx.expect_error && !p->error) { printf("ERROR: Expected parser to error with\n [%s]\n" "but it finished instead\n", ctx.expect_error); goto out; } else if (ctx.expect_error && !ctx.matched_error) { printf("ERROR: Expected parser to error with\n [%s]\n" "but got\n [%s]\ninstead\n", ctx.expect_error, p->error); goto out; } else if (ctx.expect_pname && !ctx.matched_pname) { printf("ERROR: Did not find expected part name [%s]\n", ctx.expect_pname); goto out; } else if (ctx.expect_pvalue && !ctx.matched_pvalue) { printf("ERROR: Did not find expected part value [%s]\n", ctx.expect_pvalue); goto out; } else if (ctx.expect_hname && !ctx.matched_hname) { printf("ERROR: Did not find expected header name [%s]\n", ctx.expect_hname); goto out; } else if (ctx.expect_hvalue && !ctx.matched_hvalue) { printf("ERROR: Did not find expected header value [%s]\n", ctx.expect_hvalue); goto out; } printf("OK\n"); rv = 0; out: if (p) lh_mpart_free(p); xfree(ctx.header); xfree(ctx.expect_error); xfree(ctx.expect_pname); xfree(ctx.expect_pvalue); xfree(ctx.expect_hname); xfree(ctx.expect_hvalue); return rv; } static int run_tests(FILE *trace, const char *dir, size_t bufsize) { DIR *tests; char path[128]; struct dirent *entry; int fails = 0; tests = opendir(dir); if (!tests) { fprintf(stderr, "Unable to open tests: %s\n", strerror(errno)); return -1; } while ((entry = readdir(tests)) != NULL) { if (entry->d_type == DT_REG) { snprintf(path, sizeof(path), "%s/%s", dir, entry->d_name); if (run_test(trace, path, NULL, bufsize)) fails++; } } closedir(tests); if (fails) printf("\n%d test cases FAILED!\n", fails); else printf("\nAll test cases OK!\n"); return fails; } int main(int argc, char **argv) { const char *testfile = NULL; const char *testdir = NULL; const char *dumpprefix = NULL; size_t bufsize = 0; FILE *trace = NULL; int opt; while ((opt = getopt(argc, argv, "vb:d:f:x:")) != -1) { switch (opt) { case 'v': trace = stderr; break; case 'b': bufsize = strtoul(optarg, NULL, 0); if (bufsize == 0 || bufsize > 4096) { fprintf(stderr, "Invalid buffer size\n"); return 1; } break; case 'd': testdir = optarg; break; case 'f': testfile = optarg; break; case 'x': dumpprefix = optarg; break; default: fprintf(stderr, "Usage: %s [-v] [-b #] {-d <dir>|[-x pfx] -f <file>}\n", argv[0]); return 1; } } if (testdir) { return run_tests(trace, testdir, bufsize); } else if (testfile) { return run_test(trace, testfile, dumpprefix, bufsize); } fprintf(stderr, "One of -d or -f is required\n"); return 1; }
21.537209
75
0.609653
150b62e05964c19a91fc8586c1896dc47cca00dc
1,103
h
C
XRADGUI/QtGUIAPI/DataDisplayWindow/MouseDrag.h
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
1
2021-04-02T16:47:00.000Z
2021-04-02T16:47:00.000Z
XRADGUI/QtGUIAPI/DataDisplayWindow/MouseDrag.h
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
null
null
null
XRADGUI/QtGUIAPI/DataDisplayWindow/MouseDrag.h
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
3
2021-08-30T11:26:23.000Z
2021-09-23T09:39:56.000Z
/* Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine All rights reserved. This file is licensed under BSD-3-Clause license. See LICENSE file for details. */ #ifndef XRAD__MouseDrag_h #define XRAD__MouseDrag_h //-------------------------------------------------------------- // // created: 2014/03/17 // created: 17.3.2014 10:35 // author: KNS // //-------------------------------------------------------------- #include <XRADGUI/Sources/Internal/std.h> #include <XRADBasic/Sources/Containers/SpaceCoordinates.h> namespace XRAD_GUI { XRAD_USING class ChartZoom; class MouseDrag : public QObject { Q_OBJECT private: virtual bool eventFilter(QObject *,QEvent *); // обработчик событий от мыши virtual void procMouseEvent(QEvent *){} protected: MouseDrag(ChartZoom &in_zoom); ChartZoom &zoom; // Опекаемый менеджер масштабирования point2_I32 start_cursor_position; // Положение курсора в момент начала преобразования // (в пикселах относительно канвы графика) range2_F64 scale_at_start; }; }//namespace XRAD_GUI #endif // XRAD__MouseDrag_h
21.627451
80
0.657298
d21f63136fe924028ef8a484cc100ad5e0d0073e
579
h
C
storage/browser/quota/quota_macros.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
storage/browser/quota/quota_macros.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
storage/browser/quota/quota_macros.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef STORAGE_BROWSER_QUOTA_QUOTA_MACROS_H_ #define STORAGE_BROWSER_QUOTA_QUOTA_MACROS_H_ #include "base/metrics/histogram_macros.h" #define UMA_HISTOGRAM_MBYTES(name, sample) \ UMA_HISTOGRAM_CUSTOM_COUNTS((name), static_cast<int>((sample) / kMBytes), 1, \ 10 * 1024 * 1024 /* 10TB */, 100) #endif // STORAGE_BROWSER_QUOTA_QUOTA_MACROS_H_
38.6
80
0.690846
cfb75617ef933f66c2e447f81d85817723dee080
164,888
c
C
lib/TCP.c
JDevlieghere/SORTES-Clock
f392697d8d6d2d8d259ac852ebb3a00859fa218d
[ "MIT" ]
2
2016-01-02T11:20:21.000Z
2016-12-08T09:40:48.000Z
lib/TCP.c
JDevlieghere/SORTES-Clock
f392697d8d6d2d8d259ac852ebb3a00859fa218d
[ "MIT" ]
null
null
null
lib/TCP.c
JDevlieghere/SORTES-Clock
f392697d8d6d2d8d259ac852ebb3a00859fa218d
[ "MIT" ]
null
null
null
/********************************************************************* * * Transmission Control Protocol (TCP) Communications Layer * Module for Microchip TCP/IP Stack * -Provides reliable, handshaked transport of application stream * oriented data with flow control * -Reference: RFC 793 * ********************************************************************* * FileName: TCP.c * Dependencies: IP, Tick, Ethernet/WiFi (ENC28J60.c, ETH97J60.c, * ENCX24J600.c, or ZG2100.c), ARP (optional), * DNS (optional) * Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32 * Compiler: Microchip C32 v1.05 or higher * Microchip C30 v3.12 or higher * Microchip C18 v3.30 or higher * HI-TECH PICC-18 PRO 9.63PL2 or higher * Company: Microchip Technology, Inc. * * Software License Agreement * * Copyright (C) 2002-2009 Microchip Technology Inc. All rights * reserved. * * Microchip licenses to you the right to use, modify, copy, and * distribute: * (i) the Software when embedded on a Microchip microcontroller or * digital signal controller product ("Device") which is * integrated into Licensee's product; or * (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h, * ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device * used in conjunction with a Microchip ethernet controller for * the sole purpose of interfacing with the ethernet controller. * * You should refer to the license agreement accompanying this * Software for additional information regarding your rights and * obligations. * * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL * MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE. * * * Author Date Comment *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Nilesh Rajbharti 5/8/01 Original (Rev 1.0) * Howard Schlunder 12/11/06 Changed almost everything to * better meet RFC 793. ********************************************************************/ #define __TCP_C #include "TCPIP Stack/TCPIP.h" #if defined(STACK_USE_TCP) /**************************************************************************** Section: Configuration Parameters ***************************************************************************/ // Starting port for client sockets #define LOCAL_PORT_START_NUMBER (1024u) // End port for client sockets #define LOCAL_PORT_END_NUMBER (5000u) // For debugging only. Normal applications should never enable these //#define DEBUG_GENERATE_TX_LOSS 31129 //#define DEBUG_GENERATE_RX_LOSS 32113 // A lot of pointer dereference code can be removed if you // locally copy TCBStubs to an absolute memory location. // If you define TCP_OPTIMIZE_FOR_SIZE, local caching will // occur and will substantially decrease the entire TCP ROM // footprint (up to 35%). If you leave TCP_OPTIMIZE_FOR_SIZE // undefined, the local caching will be disabled. On PIC18 // products, this will improve TCP performance/throughput by // approximately 15%. #define TCP_OPTIMIZE_FOR_SIZE // For smallest size and best throughput, TCP_OPTIMIZE_FOR_SIZE // should always be enabled on PIC24/dsPIC products. On PIC32 // products there is very little difference and depnds on compiler // optimization level #if defined(__C30__) && !defined(TCP_OPTIMIZE_FOR_SIZE) #define TCP_OPTIMIZE_FOR_SIZE #elif defined(__C32__) && defined(TCP_OPTIMIZE_FOR_SIZE) #undef TCP_OPTIMIZE_FOR_SIZE #endif // TCP Maximum Segment Size (TX and RX) #define TCP_MAX_SEG_SIZE (536u) // TCP Timeout and retransmit numbers #define TCP_START_TIMEOUT_VAL ((TICK)TICK_SECOND*1) // Timeout to retransmit unacked data #define TCP_DELAYED_ACK_TIMEOUT ((TICK)TICK_SECOND/10) // Timeout for delayed-acknowledgement algorithm #define TCP_FIN_WAIT_2_TIMEOUT ((TICK)TICK_SECOND*5) // Timeout for FIN WAIT 2 state #define TCP_KEEP_ALIVE_TIMEOUT ((TICK)TICK_SECOND*10) // Timeout for keep-alive messages when no traffic is sent #define TCP_CLOSE_WAIT_TIMEOUT ((TICK)TICK_SECOND/5) // Timeout for the CLOSE_WAIT state #define TCP_MAX_RETRIES (5u) // Maximum number of retransmission attempts #define TCP_MAX_UNACKED_KEEP_ALIVES (6u) // Maximum number of keep-alive messages that can be sent without receiving a response before automatically closing the connection #define TCP_MAX_SYN_RETRIES (2u) // Smaller than all other retries to reduce SYN flood DoS duration #define TCP_AUTO_TRANSMIT_TIMEOUT_VAL (TICK_SECOND/25ull) // Timeout before automatically tranmitting unflushed data #define TCP_SYN_QUEUE_MAX_ENTRIES (3u) // Number of TCP RX SYN packets to save if they cannot be serviced immediately #define TCP_SYN_QUEUE_TIMEOUT ((TICK)TICK_SECOND*3) // Timeout for when SYN queue entries are deleted if unserviceable /**************************************************************************** Section: TCP Header Data Types ***************************************************************************/ #define FIN (0x01) // FIN Flag as defined in RFC #define SYN (0x02) // SYN Flag as defined in RFC #define RST (0x04) // Reset Flag as defined in RFC #define PSH (0x08) // Push Flag as defined in RFC #define ACK (0x10) // Acknowledge Flag as defined in RFC #define URG (0x20) // Urgent Flag as defined in RFC // TCP Header Data Structure typedef struct _TCP_HEADER { WORD SourcePort; // Local port number WORD DestPort; // Remote port number DWORD SeqNumber; // Local sequence number DWORD AckNumber; // Acknowledging remote sequence number struct { unsigned char Reserved3 : 4; unsigned char Val : 4; } DataOffset; // Data offset flags nibble union { struct { unsigned char flagFIN : 1; unsigned char flagSYN : 1; unsigned char flagRST : 1; unsigned char flagPSH : 1; unsigned char flagACK : 1; unsigned char flagURG : 1; unsigned char Reserved2 : 2; } bits; BYTE byte; } Flags; // TCP Flags as defined in RFC WORD Window; // Local free RX buffer window WORD Checksum; // Data payload checksum WORD UrgentPointer; // Urgent pointer } TCP_HEADER; #define TCP_OPTIONS_END_OF_LIST (0x00u) // End of List TCP Option Flag #define TCP_OPTIONS_NO_OP (0x01u) // No Op TCP Option #define TCP_OPTIONS_MAX_SEG_SIZE (0x02u) // Maximum segment size TCP flag typedef struct _TCP_OPTIONS { BYTE Kind; // Type of option BYTE Length; // Length WORD_VAL MaxSegSize; // Maximum segment size } TCP_OPTIONS; // TCP Options data structure // Structure containing all the important elements of an incomming // SYN packet in order to establish a connection at a future time // if all sockets on the listening port are already connected to // someone typedef struct { NODE_INFO niSourceAddress;// Remote IP address and MAC address WORD wSourcePort; // Remote TCP port number that the response SYN needs to be sent to DWORD dwSourceSEQ; // Remote TCP SEQuence number that must be ACKnowledged when we send our response SYN WORD wDestPort; // Local TCP port which the original SYN was destined for WORD wTimestamp; // Timer to expire old SYN packets that can't be serviced at all } TCP_SYN_QUEUE; #if defined(STACK_CLIENT_MODE) static WORD NextPort __attribute__((persistent)); // Tracking variable for next local client port number #endif /**************************************************************************** Section: TCB Definitions ***************************************************************************/ // Determines the number of defined TCP sockets #define TCP_SOCKET_COUNT (sizeof(TCPSocketInitializer)/sizeof(TCPSocketInitializer[0])) #if defined(HI_TECH_C) // The initializer forces this large array out of the bss section // so we can link correctly. #pragma psect bigdata=TCB_uRAM_BIG #pragma psect data=TCB_uRAM static TCB_STUB TCBStubs[TCP_SOCKET_COUNT] = {'\0'}; #pragma psect data=ordinary_data_sect #pragma psect bigdata=ordinary_data_sect_big #else // The TCB array is very large. With the C18 compiler, one must // modify the linker script to make an array that spans more than // one memory bank. To do this, make the necessary changes to your // processor's linker script (.lkr). Here is an example showing // gpr11 and 128 bytes of gpr12 being combined into one 384 byte // block used exclusively by the TCB_uRAM data section: // ... // //DATABANK NAME=gpr11 START=0xB00 END=0xBFF // //DATABANK NAME=gpr12 START=0xC00 END=0xCFF // DATABANK NAME=gpr11b START=0xB00 END=0xC7F PROTECTED // DATABANK NAME=gpr12 START=0xC80 END=0xCFF // ... // SECTION NAME=TCB_uRAM RAM=gpr11b // ... #if defined(__18CXX) && !defined(HI_TECH_C) #pragma udata TCB_uRAM #endif static TCB_STUB TCBStubs[TCP_SOCKET_COUNT]; #if defined(__18CXX) && !defined(HI_TECH_C) #pragma udata // Return to any other RAM section #endif #endif static TCB MyTCB; // Currently loaded TCB static TCP_SOCKET hCurrentTCP = INVALID_SOCKET; // Current TCP socket #if TCP_SYN_QUEUE_MAX_ENTRIES #if defined(__18CXX) && !defined(HI_TECH_C) #pragma udata SYN_QUEUE_RAM_SECT #endif static TCP_SYN_QUEUE SYNQueue[TCP_SYN_QUEUE_MAX_ENTRIES]; // Array of saved incoming SYN requests that need to be serviced later #if defined(__18CXX) && !defined(HI_TECH_C) #pragma udata #endif #endif /**************************************************************************** Section: Function Prototypes ***************************************************************************/ static void TCPRAMCopy(PTR_BASE wDest, BYTE vDestType, PTR_BASE wSource, BYTE vSourceType, WORD wLength); #if defined(__18CXX) static void TCPRAMCopyROM(PTR_BASE wDest, BYTE wDestType, ROM BYTE* wSource, WORD wLength); #else #define TCPRAMCopyROM(a,b,c,d) TCPRAMCopy(a,b,c,TCP_PIC_RAM,d) #endif static void SendTCP(BYTE vTCPFlags, BYTE vSendFlags); static void HandleTCPSeg(TCP_HEADER* h, WORD len); static BOOL FindMatchingSocket(TCP_HEADER* h, NODE_INFO* remote); static void SwapTCPHeader(TCP_HEADER* header); static void CloseSocket(void); static void SyncTCB(void); // Indicates if this packet is a retransmission (no reset) or a new packet (reset required) #define SENDTCP_RESET_TIMERS 0x01 // Instead of transmitting normal data, a garbage octet is transmitted according to RFC 1122 section 4.2.3.6 #define SENDTCP_KEEP_ALIVE 0x02 /**************************************************************************** Section: TCB Optimization Configuration ***************************************************************************/ #if defined(TCP_OPTIMIZE_FOR_SIZE) static TCB_STUB MyTCBStub; // Flushes MyTCBStub cache and loads up the specified TCB_STUB. // Does nothing on cache hit. static void SyncTCBStub(TCP_SOCKET hTCP) { if(hCurrentTCP == hTCP) return; if(hCurrentTCP != INVALID_SOCKET) { // Save the current TCB stub memcpy((void*)&TCBStubs[hCurrentTCP], (void*)&MyTCBStub, sizeof(MyTCBStub)); } hCurrentTCP = hTCP; if(hTCP == INVALID_SOCKET) return; // Load up the new TCB stub memcpy((void*)&MyTCBStub, (void*)&TCBStubs[hTCP], sizeof(MyTCBStub)); } #else // Flushes MyTCBStub cache and loads up the specified TCB_STUB. // Does nothing on cache hit. #define SyncTCBStub(a) hCurrentTCP = (a) // Alias to current TCP stub. #define MyTCBStub TCBStubs[hCurrentTCP] #endif // Flushes MyTCB cache and loads up the specified TCB. // Does nothing on cache hit. static void SyncTCB(void) { static TCP_SOCKET hLastTCB = INVALID_SOCKET; if(hLastTCB == hCurrentTCP) return; if(hLastTCB != INVALID_SOCKET) { // Save the current TCB TCPRAMCopy(TCBStubs[hLastTCB].bufferTxStart - sizeof(MyTCB), TCBStubs[hLastTCB].vMemoryMedium, (PTR_BASE)&MyTCB, TCP_PIC_RAM, sizeof(MyTCB)); } // Load up the new TCB hLastTCB = hCurrentTCP; TCPRAMCopy((PTR_BASE)&MyTCB, TCP_PIC_RAM, MyTCBStub.bufferTxStart - sizeof(MyTCB), MyTCBStub.vMemoryMedium, sizeof(MyTCB)); } /***************************************************************************** Function: void TCPInit(void) Summary: Initializes the TCP module. Description: Initializes the TCP module. This function sets up the TCP buffers in memory and initializes each socket to the CLOSED state. If insufficient memory was allocated for the TCP sockets, the function will hang here to be captured by the debugger. Precondition: None Parameters: None Returns: None Remarks: This function is called only one during lifetime of the application. ***************************************************************************/ void TCPInit(void) { BYTE i; BYTE vSocketsAllocated; WORD wTXSize, wRXSize; PTR_BASE ptrBaseAddress; BYTE vMedium; #if TCP_ETH_RAM_SIZE > 0 WORD wCurrentETHAddress = TCP_ETH_RAM_BASE_ADDRESS; #endif #if TCP_PIC_RAM_SIZE > 0 PTR_BASE ptrCurrentPICAddress = TCP_PIC_RAM_BASE_ADDRESS; #endif #if TCP_SPI_RAM_SIZE > 0 WORD wCurrentSPIAddress = TCP_SPI_RAM_BASE_ADDRESS; #endif #if defined(STACK_CLIENT_MODE) // Initialize NextPort to a random value if it is zero (such as after // reset on a PIC32 or PIC18 when the static memory initializer is // used). By starting with a random number, we decrease the risk of // reusing a port number that was previously used if the user power // cycles the device. if(NextPort == 0u) NextPort = (((WORD)GenerateRandomDWORD()) & 0x07FFu) + LOCAL_PORT_START_NUMBER; #endif // Mark all SYN Queue entries as invalid by zeroing the memory #if TCP_SYN_QUEUE_MAX_ENTRIES memset((void*)SYNQueue, 0x00, sizeof(SYNQueue)); #endif // Allocate all socket FIFO addresses vSocketsAllocated = 0; for(i = 0; i < TCP_SOCKET_COUNT; i++) { // Generate all needed sockets of each type (TCP_PURPOSE_*) SyncTCBStub(i); vMedium = TCPSocketInitializer[i].vMemoryMedium; wTXSize = TCPSocketInitializer[i].wTXBufferSize; wRXSize = TCPSocketInitializer[i].wRXBufferSize; switch(vMedium) { #if TCP_ETH_RAM_SIZE > 0 case TCP_ETH_RAM: ptrBaseAddress = wCurrentETHAddress; wCurrentETHAddress += sizeof(TCB) + wTXSize+1 + wRXSize+1; // Do a sanity check to ensure that we aren't going to use memory that hasn't been allocated to us. // If your code locks up right here, it means you've incorrectly allocated your TCP socket buffers in TCPIPConfig.h. See the TCP memory allocation section. More RAM needs to be allocated to the base memory mediums, or the individual sockets TX and RX FIFOS and socket quantiy needs to be shrunken. while(wCurrentETHAddress > TCP_ETH_RAM_BASE_ADDRESS + TCP_ETH_RAM_SIZE); break; #endif #if TCP_PIC_RAM_SIZE > 0 case TCP_PIC_RAM: ptrBaseAddress = ptrCurrentPICAddress; ptrCurrentPICAddress += sizeof(TCB) + wTXSize+1 + wRXSize+1; // Do a sanity check to ensure that we aren't going to use memory that hasn't been allocated to us. // If your code locks up right here, it means you've incorrectly allocated your TCP socket buffers in TCPIPConfig.h. See the TCP memory allocation section. More RAM needs to be allocated to the base memory mediums, or the individual sockets TX and RX FIFOS and socket quantiy needs to be shrunken. while(ptrCurrentPICAddress > TCP_PIC_RAM_BASE_ADDRESS + TCP_PIC_RAM_SIZE); break; #endif #if TCP_SPI_RAM_SIZE > 0 case TCP_SPI_RAM: ptrBaseAddress = wCurrentSPIAddress; wCurrentSPIAddress += sizeof(TCB) + wTXSize+1 + wRXSize+1; // Do a sanity check to ensure that we aren't going to use memory that hasn't been allocated to us. // If your code locks up right here, it means you've incorrectly allocated your TCP socket buffers in TCPIPConfig.h. See the TCP memory allocation section. More RAM needs to be allocated to the base memory mediums, or the individual sockets TX and RX FIFOS and socket quantiy needs to be shrunken. while(wCurrentSPIAddress > TCP_SPI_RAM_BASE_ADDRESS + TCP_SPI_RAM_SIZE); break; #endif default: while(1); // Undefined allocation medium. Go fix your TCPIPConfig.h TCP memory allocations. } MyTCBStub.vMemoryMedium = vMedium; MyTCBStub.bufferTxStart = ptrBaseAddress + sizeof(TCB); MyTCBStub.bufferRxStart = MyTCBStub.bufferTxStart + wTXSize + 1; MyTCBStub.bufferEnd = MyTCBStub.bufferRxStart + wRXSize; MyTCBStub.smState = TCP_CLOSED; MyTCBStub.Flags.bServer = FALSE; #if defined(STACK_USE_SSL) MyTCBStub.sslStubID = SSL_INVALID_ID; #endif SyncTCB(); MyTCB.vSocketPurpose = TCPSocketInitializer[i].vSocketPurpose; CloseSocket(); } } /**************************************************************************** Section: Connection Management Functions ***************************************************************************/ /**************************************************************************** Function: TCP_SOCKET TCPOpen(DWORD dwRemoteHost, BYTE vRemoteHostType, WORD wPort, BYTE vSocketPurpose) Summary: Opens a TCP socket for listening or as a client. Description: Provides a unified method for opening TCP sockets. This function can open both client and server sockets. For client sockets, it can accept host name string to query in DNS, and IP address as a string, an IP address in binary form, or a previously resolved NODE_INFO structure. When a host name or IP address only is provided, the TCP module will internally perform the necessary DNS and/or ARP resolution steps before reporting that the TCP socket is connected (via a call to TCPISConnected returning TRUE). Server sockets ignore this destination parameter and listen only on the indicated port. The vSocketPurpose field allows sockets to be opened with varying buffer size parameters and memory storage mediums. This field corresponds to pre-defined sockets types in TCPIPConfig.h or the TCPIPConfig utility. Sockets are statically allocated on boot, but can be claimed with this \function and freed using TCPDisconnect (for client sockets). Server sockets are opened permanently for the duration of the application. Calls to TCPDisconnect will only release the socket to the listening state. Conditions: TCP is initialized. Input: dwRemoteHost - For client sockets only. Provide a pointer to a null\-terminated string of the remote host name (ex\: "www.microchip.com" or "192.168.1.123"), a literal destination IP address (ex\: 0x7B01A8C0 or an IP_ADDR data type), or a pointer to a NODE_INFO structure with the remote IP address and remote node or gateway MAC address specified. If a string is provided, note that it must be statically allocated in memory and cannot be modified or deallocated until TCPIsConnected returns TRUE. This parameter is ignored for server sockets. vRemoteHostType - TCP_OPEN_SERVER, TCP_OPEN_RAM_HOST, TCP_OPEN_ROM_HOST, TCP_OPEN_IP_ADDRESS, or TCP_OPEN_NODE_INFO. wPort - For client sockets, the remote TCP port to which a connection should be made. For server sockets, the local TCP port on which to listen for connections. vSocketPurpose - Any of the TCP_PURPOSE_* constants defined in TCPIPConfig.h or the TCPIPConfig utility. Return Values: INVALID_SOCKET - No sockets of the specified type were available to be opened. Otherwise - A TCP_SOCKET handle. Save this handle and use it when calling all other TCP APIs. Remarks: This function replaces the old TCPConnect and TCPListen functions. If TCP_OPEN_RAM_HOST or TCP_OPEN_ROM_HOST are used for the destination type, the DNS client module must also be enabled. Example: <code> // Open a server socket skt = TCPOpen(NULL, TCP_OPEN_SERVER, HTTP_PORT, TCP_PURPOSE_HTTP_SERVER); // Open a client socket to www.microchip.com // The double cast here prevents compiler warnings skt = TCPOpen((DWORD)(PTR_BASE)"www.microchip.com", TCP_OPEN_ROM_HOST, 80, TCP_PURPOSE_DEFAULT); // Reopen a client socket without repeating DNS or ARP SOCKET_INFO cache = TCPGetSocketInfo(skt); // Call with the old socket skt = TCPOpen((DWORD)(PTR_BASE)&cache.remote, TCP_OPEN_NODE_INFO, cache.remotePort.Val, TCP_PURPOSE_DEFAULT); </code> ****************************************************************************/ TCP_SOCKET TCPOpen(DWORD dwRemoteHost, BYTE vRemoteHostType, WORD wPort, BYTE vSocketPurpose) { TCP_SOCKET hTCP; // Find an available socket that matches the specified socket type for(hTCP = 0; hTCP < TCP_SOCKET_COUNT; hTCP++) { SyncTCBStub(hTCP); // Sockets that are in use will be in a non-closed state if(MyTCBStub.smState != TCP_CLOSED) continue; SyncTCB(); // See if this socket matches the desired type if(MyTCB.vSocketPurpose != vSocketPurpose) continue; // See if this is a server socket if(vRemoteHostType == TCP_OPEN_SERVER) { MyTCB.localPort.Val = wPort; MyTCBStub.Flags.bServer = TRUE; MyTCBStub.smState = TCP_LISTEN; MyTCBStub.remoteHash.Val = wPort; #if defined(STACK_USE_SSL_SERVER) MyTCB.localSSLPort.Val = 0; #endif } // Handle all the client mode socket types else { #if defined(STACK_CLIENT_MODE) { // Each new socket that is opened by this node, gets the // next sequential local port number. if(NextPort < LOCAL_PORT_START_NUMBER || NextPort > LOCAL_PORT_END_NUMBER) NextPort = LOCAL_PORT_START_NUMBER; // Set the non-zero TCB fields MyTCB.localPort.Val = NextPort++; MyTCB.remotePort.Val = wPort; // Flag to start the DNS, ARP, SYN processes MyTCBStub.eventTime = TickGet(); MyTCBStub.Flags.bTimerEnabled = 1; switch(vRemoteHostType) { #if defined(STACK_USE_DNS) case TCP_OPEN_RAM_HOST: case TCP_OPEN_ROM_HOST: MyTCB.remote.dwRemoteHost = dwRemoteHost; MyTCB.flags.bRemoteHostIsROM = (vRemoteHostType == TCP_OPEN_ROM_HOST); MyTCBStub.smState = TCP_GET_DNS_MODULE; break; #endif case TCP_OPEN_IP_ADDRESS: // dwRemoteHost is a literal IP address. This // doesn't need DNS and can skip directly to the // Gateway ARPing step. MyTCBStub.remoteHash.Val = (((DWORD_VAL*)&dwRemoteHost)->w[1]+((DWORD_VAL*)&dwRemoteHost)->w[0] + wPort) ^ MyTCB.localPort.Val; MyTCB.remote.niRemoteMACIP.IPAddr.Val = dwRemoteHost; MyTCB.retryCount = 0; MyTCB.retryInterval = (TICK_SECOND/4)/256; MyTCBStub.smState = TCP_GATEWAY_SEND_ARP; break; case TCP_OPEN_NODE_INFO: MyTCBStub.remoteHash.Val = (((NODE_INFO*)(PTR_BASE)dwRemoteHost)->IPAddr.w[1]+((NODE_INFO*)(PTR_BASE)dwRemoteHost)->IPAddr.w[0] + wPort) ^ MyTCB.localPort.Val; memcpy((void*)(BYTE*)&MyTCB.remote, (void*)(BYTE*)(PTR_BASE)dwRemoteHost, sizeof(NODE_INFO)); MyTCBStub.smState = TCP_SYN_SENT; SendTCP(SYN, SENDTCP_RESET_TIMERS); break; } } #else { return INVALID_SOCKET; } #endif } return hTCP; } // If there is no socket available, return error. return INVALID_SOCKET; } /***************************************************************************** Function: BOOL TCPWasReset(TCP_SOCKET hTCP) Summary: Self-clearing semaphore inidicating socket reset. Description: This function is a self-clearing semaphore indicating whether or not a socket has been disconnected since the previous call. This function works for all possible disconnections: a call to TCPDisconnect, a FIN from the remote node, or an acknowledgement timeout caused by the loss of a network link. It also returns TRUE after the first call to TCPInit. Applications should use this function to reset their state machines. This function was added due to the possibility of an error when relying on TCPIsConnected returing FALSE to check for a condition requiring a state machine reset. If a socket is closed (due to a FIN ACK) and then immediately reopened (due to a the arrival of a new SYN) in the same cycle of the stack, calls to TCPIsConnected by the application will never return FALSE even though the socket has been disconnected. This can cause errors for protocols such as HTTP in which a client will immediately open a new connection upon closing of a prior one. Relying on this function instead allows applications to trap those conditions and properly reset their internal state for the new connection. Precondition: TCP is initialized. Parameters: hTCP - The socket to check. Return Values: TRUE - The socket has been disconnected since the previous call. FALSE - The socket has not been disconnected since the previous call. ***************************************************************************/ BOOL TCPWasReset(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); if(MyTCBStub.Flags.bSocketReset) { MyTCBStub.Flags.bSocketReset = 0; return TRUE; } return FALSE; } /***************************************************************************** Function: BOOL TCPIsConnected(TCP_SOCKET hTCP) Summary: Determines if a socket has an established connection. Description: This function determines if a socket has an established connection to a remote node. Call this function after calling TCPOpen to determine when the connection is set up and ready for use. This function was historically used to check for disconnections, but TCPWasReset is now a more appropriate solution. Precondition: TCP is initialized. Parameters: hTCP - The socket to check. Return Values: TRUE - The socket has an established connection to a remote node. FALSE - The socket is not currently connected. Remarks: A socket is said to be connected only if it is in the TCP_ESTABLISHED state. Sockets in the process of opening or closing will return FALSE. ***************************************************************************/ BOOL TCPIsConnected(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); return (MyTCBStub.smState == TCP_ESTABLISHED); } /***************************************************************************** Function: void TCPDisconnect(TCP_SOCKET hTCP) Summary: Disconnects an open socket. Description: This function closes a connection to a remote node by sending a FIN (if currently connected). The function can be called a second time to force a socket closed by sending a RST packet. This is useful when the application knows that the remote node will not send an ACK (if it has crashed or lost its link), or when the application needs to reuse the socket immediately regardless of whether or not the remote node would like to transmit more data before closing. For client mode sockets, upon return, the hTCP handle is relinquished to the TCP/IP stack and must no longer be used by the application (except for an immediate subsequent call to TCPDisconnect() to force a RST transmission, if needed). For server mode sockets, upon return, the hTCP handle is NOT relinquished to the TCP/IP stack. After closing, the socket returns to the listening state allowing future connection requests to be serviced. This leaves the hTCP handle in a valid state and must be retained for future operations on the socket. If you want to close the server and relinquish the socket back to the TCP/IP stack, call the TCPClose() API instead of TCPDisconnect(). Precondition: None Parameters: hTCP - Handle of the socket to disconnect. Returns: None Remarks: If the socket is using SSL, a CLOSE_NOTIFY record will be transmitted first to allow the SSL session to be resumed at a later time. ***************************************************************************/ void TCPDisconnect(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); // Delete all data in the RX FIFO // In this stack's API, the application TCP handle is // immediately invalid after calling this function, so there // is no longer any way to receive data from the TCP RX FIFO, // even though the data is still there. Leaving the data there // could interfere with the remote node sending us a FIN if our // RX window is zero MyTCBStub.rxTail = MyTCBStub.rxHead; switch(MyTCBStub.smState) { #if defined(STACK_CLIENT_MODE) && defined(STACK_USE_DNS) case TCP_DNS_RESOLVE: DNSEndUsage(); // Release the DNS module, since the user is aborting CloseSocket(); break; #endif case TCP_GET_DNS_MODULE: case TCP_GATEWAY_SEND_ARP: case TCP_GATEWAY_GET_ARP: case TCP_SYN_SENT: CloseSocket(); break; case TCP_SYN_RECEIVED: case TCP_ESTABLISHED: #if defined(STACK_USE_SSL) // When disconnecting SSL sockets, send a close_notify so we can resume later if(MyTCBStub.sslStubID != SSL_INVALID_ID) { // Flush pending data and send close_notify SSLTxRecord(hTCP, MyTCBStub.sslStubID, SSL_APPLICATION); SSLTxMessage(hTCP, MyTCBStub.sslStubID, SSL_ALERT_CLOSE_NOTIFY); } #endif // Send the FIN. This is done in a loop to ensure that if we have // more data wating in the TX FIFO than can be sent in a single // packet (due to the TCP_MAX_SEG_SIZE packet size limit), we will // keep generating more packets until either all data gets // transmitted or the remote node's receive window fills up. do { SendTCP(FIN | ACK, SENDTCP_RESET_TIMERS); if(MyTCB.remoteWindow == 0u) break; } while(MyTCBStub.txHead != MyTCB.txUnackedTail); MyTCBStub.smState = TCP_FIN_WAIT_1; break; case TCP_CLOSE_WAIT: // Send the FIN. This is done in a loop to ensure that if we have // more data wating in the TX FIFO than can be sent in a single // packet (due to the TCP_MAX_SEG_SIZE packet size limit), we will // keep generating more packets until either all data gets // transmitted or the remote node's receive window fills up. do { SendTCP(FIN | ACK, SENDTCP_RESET_TIMERS); if(MyTCB.remoteWindow == 0u) break; } while(MyTCBStub.txHead != MyTCB.txUnackedTail); MyTCBStub.smState = TCP_LAST_ACK; break; // These states are all already closed or don't need explicit disconnecting -- they will disconnect by themselves after a while //case TCP_CLOSED: //case TCP_LISTEN: //case TCP_CLOSING: //case TCP_TIME_WAIT: // return; case TCP_CLOSED_BUT_RESERVED: MyTCBStub.smState = TCP_CLOSED; break; // These states will close themselves after some delay, however, // this is handled so that the user can call TCPDisconnect() // twice to immediately close a socket (using an RST) without // having to get an ACK back from the remote node. This is // great for instance when the application determines that // the remote node has been physically disconnected and // already knows that no ACK will be returned. Alternatively, // if the application needs to immediately reuse the socket // regardless of what the other node's state is in (half open). case TCP_FIN_WAIT_1: case TCP_FIN_WAIT_2: case TCP_LAST_ACK: default: SendTCP(RST | ACK, 0); CloseSocket(); break; } } /***************************************************************************** Function: void TCPClose(TCP_SOCKET hTCP) Summary: Disconnects an open socket and destroys the socket handle, including server mode socket handles. Description: Disconnects an open socket and destroys the socket handle, including server mode socket handles. This function performs identically to the TCPDisconnect() function, except that both client and server mode socket handles are relinquished to the TCP/IP stack upon return. Precondition: None Parameters: hTCP - Handle to the socket to disconnect and close. Returns: None ***************************************************************************/ void TCPClose(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); MyTCBStub.Flags.bServer = FALSE; TCPDisconnect(hTCP); } /***************************************************************************** Function: SOCKET_INFO* TCPGetRemoteInfo(TCP_SOCKET hTCP) Summary: Obtains information about a currently open socket. Description: Returns the SOCKET_INFO structure associated with this socket. This contains the NODE_INFO structure with IP and MAC address (or gateway MAC) and the remote port. Precondition: TCP is initialized and the socket is connected. Parameters: hTCP - The socket to check. Returns: The SOCKET_INFO structure associated with this socket. This structure is allocated statically by the function and is valid only until the next time TCPGetRemoteInfo() is called. ***************************************************************************/ SOCKET_INFO* TCPGetRemoteInfo(TCP_SOCKET hTCP) { static SOCKET_INFO RemoteInfo; SyncTCBStub(hTCP); SyncTCB(); memcpy((void*)&RemoteInfo.remote, (void*)&MyTCB.remote, sizeof(NODE_INFO)); RemoteInfo.remotePort.Val = MyTCB.remotePort.Val; return &RemoteInfo; } /**************************************************************************** Section: Transmit Functions ***************************************************************************/ /***************************************************************************** Function: void TCPFlush(TCP_SOCKET hTCP) Summary: Immediately transmits all pending TX data. Description: This function immediately transmits all pending TX data with a PSH flag. If this function is not called, data will automatically be sent when either a) the TX buffer is half full or b) the TCP_AUTO_TRANSMIT_TIMEOUT_VAL (default: 40ms) has elapsed. Precondition: TCP is initialized and the socket is connected. Parameters: hTCP - The socket whose data is to be transmitted. Returns: None Remarks: SSL application data is automatically flushed, so this function has no effect for SSL sockets. ***************************************************************************/ void TCPFlush(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); SyncTCB(); // NOTE: Pending SSL data will NOT be transferred here if(MyTCBStub.txHead != MyTCB.txUnackedTail) { // Send the TCP segment with all unacked bytes SendTCP(ACK, SENDTCP_RESET_TIMERS); } } /***************************************************************************** Function: WORD TCPIsPutReady(TCP_SOCKET hTCP) Summary: Determines how much free space is available in the TCP TX buffer. Description: Call this function to determine how many bytes can be written to the TCP TX buffer. If this function returns zero, the application must return to the main stack loop before continuing in order to transmit more data. Precondition: TCP is initialized. Parameters: hTCP - The socket to check. Returns: The number of bytes available to be written in the TCP TX buffer. ***************************************************************************/ WORD TCPIsPutReady(TCP_SOCKET hTCP) { BYTE i; SyncTCBStub(hTCP); i = MyTCBStub.smState; // Unconnected sockets shouldn't be transmitting anything. if(!( (i == (BYTE)TCP_ESTABLISHED) || (i == (BYTE)TCP_CLOSE_WAIT) )) return 0; // Calculate the free space in this socket's TX FIFO #if defined(STACK_USE_SSL) if(MyTCBStub.sslStubID != SSL_INVALID_ID) {// Use sslTxHead as the head pointer when SSL is active WORD rem; // Find out raw free space if(MyTCBStub.sslTxHead >= MyTCBStub.txTail) rem = (MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart - 1) - (MyTCBStub.sslTxHead - MyTCBStub.txTail); else rem = MyTCBStub.txTail - MyTCBStub.sslTxHead - 1; // Reserve space for a new MAC and header if(rem > 22u) return rem - 22; else return 0; } #endif if(MyTCBStub.txHead >= MyTCBStub.txTail) return (MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart - 1) - (MyTCBStub.txHead - MyTCBStub.txTail); else return MyTCBStub.txTail - MyTCBStub.txHead - 1; } /***************************************************************************** Function: BOOL TCPPut(TCP_SOCKET hTCP, BYTE byte) Description: Writes a single byte to a TCP socket. Precondition: TCP is initialized. Parameters: hTCP - The socket to which data is to be written. byte - The byte to write. Return Values: TRUE - The byte was written to the transmit buffer. FALSE - The transmit buffer was full, or the socket is not connected. ***************************************************************************/ BOOL TCPPut(TCP_SOCKET hTCP, BYTE byte) { WORD wFreeTXSpace; SyncTCBStub(hTCP); wFreeTXSpace = TCPIsPutReady(hTCP); if(wFreeTXSpace == 0u) return FALSE; else if(wFreeTXSpace == 1u) // About to run out of space, lets transmit so the remote node might send an ACK back faster TCPFlush(hTCP); // Send all current bytes if we are crossing half full // This is required to improve performance with the delayed // acknowledgement algorithm if((!MyTCBStub.Flags.bHalfFullFlush) && (wFreeTXSpace <= ((MyTCBStub.bufferRxStart-MyTCBStub.bufferTxStart)>>1))) { TCPFlush(hTCP); MyTCBStub.Flags.bHalfFullFlush = TRUE; } #if defined(STACK_USE_SSL) if(MyTCBStub.sslStubID != SSL_INVALID_ID) { TCPRAMCopy(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)&byte, TCP_PIC_RAM, sizeof(byte)); if(++MyTCBStub.sslTxHead >= MyTCBStub.bufferRxStart) MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } else { TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)&byte, TCP_PIC_RAM, sizeof(byte)); if(++MyTCBStub.txHead >= MyTCBStub.bufferRxStart) MyTCBStub.txHead = MyTCBStub.bufferTxStart; } #else TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)&byte, TCP_PIC_RAM, sizeof(byte)); if(++MyTCBStub.txHead >= MyTCBStub.bufferRxStart) MyTCBStub.txHead = MyTCBStub.bufferTxStart; #endif // Send the last byte as a separate packet (likely will make the remote node send back ACK faster) if(wFreeTXSpace == 1u) { TCPFlush(hTCP); } // If not already enabled, start a timer so this data will // eventually get sent even if the application doens't call // TCPFlush() else if(!MyTCBStub.Flags.bTimer2Enabled) { MyTCBStub.Flags.bTimer2Enabled = TRUE; MyTCBStub.eventTime2 = (WORD)TickGetDiv256() + TCP_AUTO_TRANSMIT_TIMEOUT_VAL/256ull; } return TRUE; } /***************************************************************************** Function: WORD TCPPutArray(TCP_SOCKET hTCP, BYTE* data, WORD len) Description: Writes an array from RAM to a TCP socket. Precondition: TCP is initialized. Parameters: hTCP - The socket to which data is to be written. data - Pointer to the array to be written. len - Number of bytes to be written. Returns: The number of bytes written to the socket. If less than len, the buffer became full or the socket is not conected. ***************************************************************************/ WORD TCPPutArray(TCP_SOCKET hTCP, BYTE* data, WORD len) { WORD wActualLen; WORD wFreeTXSpace; WORD wRightLen = 0; SyncTCBStub(hTCP); wFreeTXSpace = TCPIsPutReady(hTCP); if(wFreeTXSpace == 0u) { TCPFlush(hTCP); return 0; } wActualLen = wFreeTXSpace; if(wFreeTXSpace > len) wActualLen = len; // Send all current bytes if we are crossing half full // This is required to improve performance with the delayed // acknowledgement algorithm if((!MyTCBStub.Flags.bHalfFullFlush) && (wFreeTXSpace <= ((MyTCBStub.bufferRxStart-MyTCBStub.bufferTxStart)>>1))) { TCPFlush(hTCP); MyTCBStub.Flags.bHalfFullFlush = TRUE; } #if defined(STACK_USE_SSL) if(MyTCBStub.sslStubID != SSL_INVALID_ID) { // See if we need a two part put if(MyTCBStub.sslTxHead + wActualLen >= MyTCBStub.bufferRxStart) { wRightLen = MyTCBStub.bufferRxStart-MyTCBStub.sslTxHead; TCPRAMCopy(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)data, TCP_PIC_RAM, wRightLen); data += wRightLen; wActualLen -= wRightLen; MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } TCPRAMCopy(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)data, TCP_PIC_RAM, wActualLen); MyTCBStub.sslTxHead += wActualLen; } else { // See if we need a two part put if(MyTCBStub.txHead + wActualLen >= MyTCBStub.bufferRxStart) { wRightLen = MyTCBStub.bufferRxStart-MyTCBStub.txHead; TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)data, TCP_PIC_RAM, wRightLen); data += wRightLen; wActualLen -= wRightLen; MyTCBStub.txHead = MyTCBStub.bufferTxStart; } TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)data, TCP_PIC_RAM, wActualLen); MyTCBStub.txHead += wActualLen; } #else // See if we need a two part put if(MyTCBStub.txHead + wActualLen >= MyTCBStub.bufferRxStart) { wRightLen = MyTCBStub.bufferRxStart-MyTCBStub.txHead; TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)data, TCP_PIC_RAM, wRightLen); data += wRightLen; wActualLen -= wRightLen; MyTCBStub.txHead = MyTCBStub.bufferTxStart; } TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)data, TCP_PIC_RAM, wActualLen); MyTCBStub.txHead += wActualLen; #endif // Send these bytes right now if we are out of TX buffer space if(wFreeTXSpace <= len) { TCPFlush(hTCP); } // If not already enabled, start a timer so this data will // eventually get sent even if the application doens't call // TCPFlush() else if(!MyTCBStub.Flags.bTimer2Enabled) { MyTCBStub.Flags.bTimer2Enabled = TRUE; MyTCBStub.eventTime2 = (WORD)TickGetDiv256() + TCP_AUTO_TRANSMIT_TIMEOUT_VAL/256ull; } return wActualLen + wRightLen; } /***************************************************************************** Function: WORD TCPPutROMArray(TCP_SOCKET hTCP, ROM BYTE* data, WORD len) Description: Writes an array from ROM to a TCP socket. Precondition: TCP is initialized. Parameters: hTCP - The socket to which data is to be written. data - Pointer to the array to be written. len - Number of bytes to be written. Returns: The number of bytes written to the socket. If less than len, the buffer became full or the socket is not conected. Remarks: This function is aliased to TCPPutArray on non-PIC18 platforms. ***************************************************************************/ #if defined(__18CXX) WORD TCPPutROMArray(TCP_SOCKET hTCP, ROM BYTE* data, WORD len) { WORD wActualLen; WORD wFreeTXSpace; WORD wRightLen = 0; SyncTCBStub(hTCP); wFreeTXSpace = TCPIsPutReady(hTCP); if(wFreeTXSpace == 0u) { TCPFlush(hTCP); return 0; } // Send all current bytes if we are crossing half full // This is required to improve performance with the delayed // acknowledgement algorithm if((!MyTCBStub.Flags.bHalfFullFlush) && (wFreeTXSpace <= ((MyTCBStub.bufferRxStart-MyTCBStub.bufferTxStart)>>1))) { TCPFlush(hTCP); MyTCBStub.Flags.bHalfFullFlush = TRUE; } wActualLen = wFreeTXSpace; if(wFreeTXSpace > len) wActualLen = len; #if defined(STACK_USE_SSL) if(MyTCBStub.sslStubID != SSL_INVALID_ID) { // See if we need a two part put if(MyTCBStub.sslTxHead + wActualLen >= MyTCBStub.bufferRxStart) { wRightLen = MyTCBStub.bufferRxStart-MyTCBStub.sslTxHead; TCPRAMCopyROM(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, data, wRightLen); data += wRightLen; wActualLen -= wRightLen; MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } TCPRAMCopyROM(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, data, wActualLen); MyTCBStub.sslTxHead += wActualLen; } else { // See if we need a two part put if(MyTCBStub.txHead + wActualLen >= MyTCBStub.bufferRxStart) { wRightLen = MyTCBStub.bufferRxStart-MyTCBStub.txHead; TCPRAMCopyROM(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, data, wRightLen); data += wRightLen; wActualLen -= wRightLen; MyTCBStub.txHead = MyTCBStub.bufferTxStart; } TCPRAMCopyROM(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, data, wActualLen); MyTCBStub.txHead += wActualLen; } #else // See if we need a two part put if(MyTCBStub.txHead + wActualLen >= MyTCBStub.bufferRxStart) { wRightLen = MyTCBStub.bufferRxStart-MyTCBStub.txHead; TCPRAMCopyROM(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, data, wRightLen); data += wRightLen; wActualLen -= wRightLen; MyTCBStub.txHead = MyTCBStub.bufferTxStart; } TCPRAMCopyROM(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, data, wActualLen); MyTCBStub.txHead += wActualLen; #endif // Send these bytes right now if we are out of TX buffer space if(wFreeTXSpace <= len) { TCPFlush(hTCP); } // If not already enabled, start a timer so this data will // eventually get sent even if the application doens't call // TCPFlush() else if(!MyTCBStub.Flags.bTimer2Enabled) { MyTCBStub.Flags.bTimer2Enabled = TRUE; MyTCBStub.eventTime2 = (WORD)TickGetDiv256() + TCP_AUTO_TRANSMIT_TIMEOUT_VAL/256ull; } return wActualLen + wRightLen; } #endif /***************************************************************************** Function: BYTE* TCPPutString(TCP_SOCKET hTCP, BYTE* data) Description: Writes a null-terminated string from RAM to a TCP socket. The null-terminator is not copied to the socket. Precondition: TCP is initialized. Parameters: hTCP - The socket to which data is to be written. data - Pointer to the string to be written. Returns: Pointer to the byte following the last byte written to the socket. If this pointer does not dereference to a NUL byte, the buffer became full or the socket is not connected. Remarks: The return value of this function differs from that of TCPPutArray. To write long strings in a single state, initialize the *data pointer to the first byte, then call this function repeatedly (breaking to the main stack loop after each call) until the return value dereferences to a NUL byte. Save the return value as the new starting *data pointer otherwise. ***************************************************************************/ BYTE* TCPPutString(TCP_SOCKET hTCP, BYTE* data) { return data + TCPPutArray(hTCP, data, strlen((char*)data)); } /***************************************************************************** Function: BYTE* TCPPutROMString(TCP_SOCKET hTCP, ROM BYTE* data) Description: Writes a null-terminated string from ROM to a TCP socket. The null-terminator is not copied to the socket. Precondition: TCP is initialized. Parameters: hTCP - The socket to which data is to be written. data - Pointer to the string to be written. Returns: Pointer to the byte following the last byte written to the socket. If this pointer does not dereference to a NUL byte, the buffer became full or the socket is not connected. Remarks: The return value of this function differs from that of TCPPutArray. To write long strings in a single state, initialize the *data pointer to the first byte, then call this function repeatedly (breaking to the main stack loop after each call) until the return value dereferences to a NUL byte. Save the return value as the new starting *data pointer otherwise. This function is aliased to TCPPutString on non-PIC18 platforms. ***************************************************************************/ #if defined(__18CXX) ROM BYTE* TCPPutROMString(TCP_SOCKET hTCP, ROM BYTE* data) { return data + TCPPutROMArray(hTCP, data, strlenpgm((ROM char*)data)); } #endif /***************************************************************************** Function: WORD TCPGetTxFIFOFull(TCP_SOCKET hTCP) Description: Determines how many bytes are pending in the TCP TX FIFO. Precondition: TCP is initialized. Parameters: hTCP - The socket to check. Returns: Number of bytes pending to be flushed in the TCP TX FIFO. ***************************************************************************/ WORD TCPGetTxFIFOFull(TCP_SOCKET hTCP) { WORD wDataLen; WORD wFIFOSize; SyncTCBStub(hTCP); // Calculate total usable FIFO size wFIFOSize = MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart - 1; // Find out how many data bytes are free in the TX FIFO wDataLen = TCPIsPutReady(hTCP); return wFIFOSize - wDataLen; } /**************************************************************************** Section: Receive Functions ***************************************************************************/ /***************************************************************************** Function: void TCPDiscard(TCP_SOCKET hTCP) Description: Discards any pending data in the TCP RX FIFO. Precondition: TCP is initialized. Parameters: hTCP - The socket whose RX FIFO is to be cleared. Returns: None ***************************************************************************/ void TCPDiscard(TCP_SOCKET hTCP) { if(TCPIsGetReady(hTCP)) { SyncTCBStub(hTCP); // Delete all data in the RX buffer MyTCBStub.rxTail = MyTCBStub.rxHead; // Send a Window update message to the remote node SendTCP(ACK, SENDTCP_RESET_TIMERS); } } /***************************************************************************** Function: void WORD TCPIsGetReady(TCP_SOCKET hTCP) Summary: Determines how many bytes can be read from the TCP RX buffer. Description: Call this function to determine how many bytes can be read from the TCP RX buffer. If this function returns zero, the application must return to the main stack loop before continuing in order to wait for more data to arrive. Precondition: TCP is initialized. Parameters: hTCP - The socket to check. Returns: The number of bytes available to be read from the TCP RX buffer. ***************************************************************************/ WORD TCPIsGetReady(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); if(MyTCBStub.rxHead >= MyTCBStub.rxTail) return MyTCBStub.rxHead - MyTCBStub.rxTail; else return (MyTCBStub.bufferEnd - MyTCBStub.rxTail + 1) + (MyTCBStub.rxHead - MyTCBStub.bufferRxStart); } /***************************************************************************** Function: BOOL TCPGet(TCP_SOCKET hTCP, BYTE* byte) Description: Retrieves a single byte to a TCP socket. Precondition: TCP is initialized. Parameters: hTCP - The socket from which to read. byte - Pointer to location in which the read byte should be stored. Return Values: TRUE - A byte was read from the buffer. FALSE - The buffer was empty, or the socket is not connected. ***************************************************************************/ BOOL TCPGet(TCP_SOCKET hTCP, BYTE* byte) { WORD wGetReadyCount; // See if there is any data which can be read wGetReadyCount = TCPIsGetReady(hTCP); if(wGetReadyCount == 0u) return FALSE; SyncTCBStub(hTCP); if(byte) TCPRAMCopy((PTR_BASE)byte, TCP_PIC_RAM, MyTCBStub.rxTail, MyTCBStub.vMemoryMedium, 1); if(++MyTCBStub.rxTail > MyTCBStub.bufferEnd) MyTCBStub.rxTail = MyTCBStub.bufferRxStart; // Send a window update if we've run out of data if(wGetReadyCount == 1u) { MyTCBStub.Flags.bTXASAPWithoutTimerReset = 1; } // If not already enabled, start a timer so a window // update will get sent to the remote node at some point else if(!MyTCBStub.Flags.bTimer2Enabled) { MyTCBStub.Flags.bTimer2Enabled = TRUE; MyTCBStub.eventTime2 = (WORD)TickGetDiv256() + TCP_AUTO_TRANSMIT_TIMEOUT_VAL/256ull; } return TRUE; } /***************************************************************************** Function: WORD TCPGetArray(TCP_SOCKET hTCP, BYTE* data, WORD len) Description: Reads an array from a TCP socket. Precondition: TCP is initialized. Parameters: hTCP - The socket from which data is to be read. data - Pointer to the array to store data that was read. len - Number of bytes to be read. Returns: The number of bytes read from the socket. If less than len, the buffer became empty or the socket is not conected. ***************************************************************************/ WORD TCPGetArray(TCP_SOCKET hTCP, BYTE* buffer, WORD len) { WORD wGetReadyCount; WORD RightLen = 0; // See if there is any data which can be read wGetReadyCount = TCPIsGetReady(hTCP); if(wGetReadyCount == 0u) return 0x0000u; SyncTCBStub(hTCP); // Make sure we don't try to read more data than is available if(len > wGetReadyCount) len = wGetReadyCount; // See if we need a two part get if(MyTCBStub.rxTail + len > MyTCBStub.bufferEnd) { RightLen = MyTCBStub.bufferEnd - MyTCBStub.rxTail + 1; if(buffer) { TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, MyTCBStub.rxTail, MyTCBStub.vMemoryMedium, RightLen); buffer += RightLen; } len -= RightLen; MyTCBStub.rxTail = MyTCBStub.bufferRxStart; } if(buffer) TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, MyTCBStub.rxTail, MyTCBStub.vMemoryMedium, len); MyTCBStub.rxTail += len; len += RightLen; // Send a window update if we've run low on data if(wGetReadyCount - len <= len) { MyTCBStub.Flags.bTXASAPWithoutTimerReset = 1; } else if(!MyTCBStub.Flags.bTimer2Enabled) // If not already enabled, start a timer so a window // update will get sent to the remote node at some point { MyTCBStub.Flags.bTimer2Enabled = TRUE; MyTCBStub.eventTime2 = (WORD)TickGetDiv256() + TCP_AUTO_TRANSMIT_TIMEOUT_VAL/256ull; } return len; } /***************************************************************************** Function: WORD TCPGetRxFIFOFree(TCP_SOCKET hTCP) Description: Determines how many bytes are free in the RX FIFO. Precondition: TCP is initialized. Parameters: hTCP - The socket to check. Returns: The number of bytes free in the TCP RX FIFO. If zero, no additional data can be received until the application removes some data using one of the TCPGet family functions. ***************************************************************************/ WORD TCPGetRxFIFOFree(TCP_SOCKET hTCP) { WORD wDataLen; WORD wFIFOSize; SyncTCBStub(hTCP); // Calculate total usable FIFO size wFIFOSize = MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart; #if defined(STACK_USE_SSL) { PTR_BASE SSLtemp = MyTCBStub.rxHead; // Move SSL pointer to determine full buffer size if(MyTCBStub.sslStubID != SSL_INVALID_ID) MyTCBStub.rxHead = MyTCBStub.sslRxHead; // Find out how many data bytes are actually in the RX FIFO wDataLen = TCPIsGetReady(hTCP); // Move SSL pointer back to proper location (if we changed it) MyTCBStub.rxHead = SSLtemp; } #else { // Find out how many data bytes are actually in the RX FIFO wDataLen = TCPIsGetReady(hTCP); } #endif // Perform the calculation return wFIFOSize - wDataLen; } /***************************************************************************** Function: WORD TCPPeekArray(TCP_SOCKET hTCP, BYTE *vBuffer, WORD wLen, WORD wStart) Summary: Reads a specified number of data bytes from the TCP RX FIFO without removing them from the buffer. Description: Reads a specified number of data bytes from the TCP RX FIFO without removing them from the buffer. No TCP control actions are taken as a result of this function (ex: no window update is sent to the remote node). Precondition: TCP is initialized. Parameters: hTCP - The socket to peak from (read without removing from stream). vBuffer - Destination to write the peeked data bytes. wLen - Length of bytes to peak from the RX FIFO and copy to vBuffer. wStart - Zero-indexed starting position within the FIFO to start peeking from. Return Values: Number of bytes actually peeked from the stream and copied to vBuffer. This value can be less than wLen if wStart + wLen is greater than the deepest possible character in the RX FIFO. Remarks: None ***************************************************************************/ WORD TCPPeekArray(TCP_SOCKET hTCP, BYTE *vBuffer, WORD wLen, WORD wStart) { PTR_BASE ptrRead; WORD w; WORD wBytesUntilWrap; if(wLen == 0u) return 0u; SyncTCBStub(hTCP); // Find out how many bytes are in the RX FIFO and decrease read length // if the start offset + read length is beyond the end of the FIFO w = TCPIsGetReady(hTCP); if(wStart + wLen > w) wLen = w - wStart; // Find the read start location ptrRead = MyTCBStub.rxTail + wStart; if(ptrRead > MyTCBStub.bufferEnd) ptrRead -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; // Calculate how many bytes can be read in a single go wBytesUntilWrap = MyTCBStub.bufferEnd - ptrRead + 1; if(wLen <= wBytesUntilWrap) { // Read all at once TCPRAMCopy((PTR_BASE)vBuffer, TCP_PIC_RAM, ptrRead, MyTCBStub.vMemoryMedium, wLen); } else { // Read all bytes up to the wrap position and then read remaining bytes // at the start of the buffer TCPRAMCopy((PTR_BASE)vBuffer, TCP_PIC_RAM, ptrRead, MyTCBStub.vMemoryMedium, wBytesUntilWrap); TCPRAMCopy((PTR_BASE)vBuffer+wBytesUntilWrap, TCP_PIC_RAM, MyTCBStub.bufferRxStart, MyTCBStub.vMemoryMedium, wLen - wBytesUntilWrap); } return wLen; } /***************************************************************************** Function: BYTE TCPPeek(TCP_SOCKET hTCP, WORD wStart) Summary: Peaks at one byte in the TCP RX FIFO without removing it from the buffer. Description: Peaks at one byte in the TCP RX FIFO without removing it from the buffer. Precondition: TCP is initialized. Parameters: hTCP - The socket to peak from (read without removing from stream). wStart - Zero-indexed starting position within the FIFO to peek from. Return Values: Byte peeked from the RX FIFO. If there is no data in the buffer or an illegal wStart starting offset is given, then an indeterminate value is returned. The caller must ensure that valid parameters are passed to avoid (i.e ensure that TCPIsGetReady() returns a number that is less than wStart before calling TCPPeek()). Remarks: Use the TCPPeekArray() function to read more than one byte. It will perform better than calling TCPPeek() in a loop. ***************************************************************************/ BYTE TCPPeek(TCP_SOCKET hTCP, WORD wStart) { BYTE i; TCPPeekArray(hTCP, &i, 1, wStart); return i; } /**************************************************************************** Section: Search Functions ***************************************************************************/ /***************************************************************************** Function: WORD TCPFindArrayEx(TCP_SOCKET hTCP, BYTE* cFindArray, WORD wLen, WORD wStart, WORD wSearchLen, BOOL bTextCompare) Summary: Searches for a string in the TCP RX buffer. Description: This function finds the first occurrance of an array of bytes in the TCP RX buffer. It can be used by an application to abstract searches out of their own application code. For increased efficiency, the function is capable of limiting the scope of search to a specific range of bytes. It can also perform a case-insensitive search if required. For example, if the buffer contains "I love PIC MCUs!" and the search array is "love" with a length of 4, a value of 2 will be returned. Precondition: TCP is initialized. Parameters: hTCP - The socket to search within. cFindArray - The array of bytes to find in the buffer. wLen - Length of cFindArray. wStart - Zero-indexed starting position within the buffer. wSearchLen - Length from wStart to search in the buffer. bTextCompare - TRUE for case-insensitive text search, FALSE for binary search Return Values: 0xFFFF - Search array not found Otherwise - Zero-indexed position of the first occurrance Remarks: Since this function usually must transfer data from external storage to internal RAM for comparison, its performance degrades significantly when the buffer is full and the array is not found. For better performance, try to search for characters that are expected to exist or limit the scope of the search as much as possible. The HTTP2 module, for example, uses this function to parse headers. However, it searches for newlines, then the separating colon, then reads the header name to RAM for final comparison. This has proven to be significantly faster than searching for full header name strings outright. ***************************************************************************/ WORD TCPFindArrayEx(TCP_SOCKET hTCP, BYTE* cFindArray, WORD wLen, WORD wStart, WORD wSearchLen, BOOL bTextCompare) { PTR_BASE ptrRead; WORD wDataLen; WORD wBytesUntilWrap; PTR_BASE ptrLocation; WORD wLenStart; BYTE *cFindArrayStart; BYTE i, j, k; BOOL isFinding; BYTE buffer[32]; if(wLen == 0u) return 0u; SyncTCBStub(hTCP); // Find out how many bytes are in the RX FIFO and return // immediately if we won't possibly find a match wDataLen = TCPIsGetReady(hTCP) - wStart; if(wDataLen < wLen) return 0xFFFFu; if(wSearchLen && (wDataLen > wSearchLen)) wDataLen = wSearchLen; ptrLocation = MyTCBStub.rxTail + wStart; if(ptrLocation > MyTCBStub.bufferEnd) ptrLocation -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; ptrRead = ptrLocation; wBytesUntilWrap = MyTCBStub.bufferEnd - ptrLocation + 1; ptrLocation = wStart; wLenStart = wLen; cFindArrayStart = cFindArray; j = *cFindArray++; isFinding = FALSE; if(bTextCompare) { if(j >= 'a' && j <= 'z') j += 'A'-'a'; } // Search for the array while(1) { // Figure out how big of a chunk to read k = sizeof(buffer); if(k > wBytesUntilWrap) k = wBytesUntilWrap; if((WORD)k > wDataLen) k = wDataLen; // Read a chunk of data into the buffer TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, ptrRead, MyTCBStub.vMemoryMedium, (WORD)k); ptrRead += k; wBytesUntilWrap -= k; if(wBytesUntilWrap == 0u) { ptrRead = MyTCBStub.bufferRxStart; wBytesUntilWrap = 0xFFFFu; } // Convert everything to uppercase if(bTextCompare) { for(i = 0; i < k; i++) { if(buffer[i] >= 'a' && buffer[i] <= 'z') buffer[i] += 'A'-'a'; if(j == buffer[i]) { if(--wLen == 0u) return ptrLocation-wLenStart + i + 1; j = *cFindArray++; isFinding = TRUE; if(j >= 'a' && j <= 'z') j += 'A'-'a'; } else { wLen = wLenStart; if(isFinding) { cFindArray = cFindArrayStart; j = *cFindArray++; if(j >= 'a' && j <= 'z') j += 'A'-'a'; isFinding = FALSE; } } } } else // Compare as is { for(i = 0; i < k; i++) { if(j == buffer[i]) { if(--wLen == 0u) return ptrLocation-wLenStart + i + 1; j = *cFindArray++; isFinding = TRUE; } else { wLen = wLenStart; if(isFinding) { cFindArray = cFindArrayStart; j = *cFindArray++; isFinding = FALSE; } } } } // Check to see if it is impossible to find a match wDataLen -= k; if(wDataLen < wLen) return 0xFFFFu; ptrLocation += k; } } /***************************************************************************** Function: WORD TCPFindROMArrayEx(TCP_SOCKET hTCP, BYTE* cFindArray, WORD wLen, WORD wStart, WORD wSearchLen, BOOL bTextCompare) Summary: Searches for a ROM string in the TCP RX buffer. Description: This function finds the first occurrance of an array of bytes in the TCP RX buffer. It can be used by an application to abstract searches out of their own application code. For increased efficiency, the function is capable of limiting the scope of search to a specific range of bytes. It can also perform a case-insensitive search if required. For example, if the buffer contains "I love PIC MCUs!" and the search array is "love" with a length of 4, a value of 2 will be returned. Precondition: TCP is initialized. Parameters: hTCP - The socket to search within. cFindArray - The array of bytes to find in the buffer. wLen - Length of cFindArray. wStart - Zero-indexed starting position within the buffer. wSearchLen - Length from wStart to search in the buffer. bTextCompare - TRUE for case-insensitive text search, FALSE for binary search Return Values: 0xFFFF - Search array not found Otherwise - Zero-indexed position of the first occurrance Remarks: Since this function usually must transfer data from external storage to internal RAM for comparison, its performance degrades significantly when the buffer is full and the array is not found. For better performance, try to search for characters that are expected to exist or limit the scope of the search as much as possible. The HTTP2 module, for example, uses this function to parse headers. However, it searches for newlines, then the separating colon, then reads the header name to RAM for final comparison. This has proven to be significantly faster than searching for full header name strings outright. This function is aliased to TCPFindArrayEx on non-PIC18 platforms. ***************************************************************************/ #if defined(__18CXX) WORD TCPFindROMArrayEx(TCP_SOCKET hTCP, ROM BYTE* cFindArray, WORD wLen, WORD wStart, WORD wSearchLen, BOOL bTextCompare) { PTR_BASE ptrRead; WORD wDataLen; WORD wBytesUntilWrap; PTR_BASE ptrLocation; WORD wLenStart; ROM BYTE *cFindArrayStart; BYTE i, j, k; BOOL isFinding; BYTE buffer[32]; if(wLen == 0u) return 0u; SyncTCBStub(hTCP); // Find out how many bytes are in the RX FIFO and return // immediately if we won't possibly find a match wDataLen = TCPIsGetReady(hTCP) - wStart; if(wDataLen < wLen) return 0xFFFFu; if(wSearchLen && (wDataLen > wSearchLen)) wDataLen = wSearchLen; ptrLocation = MyTCBStub.rxTail + wStart; if(ptrLocation > MyTCBStub.bufferEnd) ptrLocation -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; ptrRead = ptrLocation; wBytesUntilWrap = MyTCBStub.bufferEnd - ptrLocation + 1; ptrLocation = wStart; wLenStart = wLen; cFindArrayStart = cFindArray; j = *cFindArray++; isFinding = FALSE; if(bTextCompare) { if(j >= 'a' && j <= 'z') j += 'A'-'a'; } // Search for the array while(1) { // Figure out how big of a chunk to read k = sizeof(buffer); if(k > wBytesUntilWrap) k = wBytesUntilWrap; if((WORD)k > wDataLen) k = wDataLen; // Read a chunk of data into the buffer TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, ptrRead, MyTCBStub.vMemoryMedium, (WORD)k); ptrRead += k; wBytesUntilWrap -= k; if(wBytesUntilWrap == 0u) { ptrRead = MyTCBStub.bufferRxStart; wBytesUntilWrap = 0xFFFFu; } // Convert everything to uppercase if(bTextCompare) { for(i = 0; i < k; i++) { if(buffer[i] >= 'a' && buffer[i] <= 'z') buffer[i] += 'A'-'a'; if(j == buffer[i]) { if(--wLen == 0u) return ptrLocation-wLenStart + i + 1; j = *cFindArray++; isFinding = TRUE; if(j >= 'a' && j <= 'z') j += 'A'-'a'; } else { wLen = wLenStart; if(isFinding) { cFindArray = cFindArrayStart; j = *cFindArray++; if(j >= 'a' && j <= 'z') j += 'A'-'a'; isFinding = FALSE; } } } } else // Compare as is { for(i = 0; i < k; i++) { if(j == buffer[i]) { if(--wLen == 0u) return ptrLocation-wLenStart + i + 1; j = *cFindArray++; isFinding = TRUE; } else { wLen = wLenStart; if(isFinding) { cFindArray = cFindArrayStart; j = *cFindArray++; isFinding = FALSE; } } } } // Check to see if it is impossible to find a match wDataLen -= k; if(wDataLen < wLen) return 0xFFFFu; ptrLocation += k; } } #endif /***************************************************************************** Function: WORD TCPFindEx(TCP_SOCKET hTCP, BYTE cFind, WORD wStart, WORD wSearchLen, BOOL bTextCompare) Summary: Searches for a byte in the TCP RX buffer. Description: This function finds the first occurrance of a byte in the TCP RX buffer. It can be used by an application to abstract searches out of their own application code. For increased efficiency, the function is capable of limiting the scope of search to a specific range of bytes. It can also perform a case-insensitive search if required. For example, if the buffer contains "I love PIC MCUs!" and the cFind byte is ' ', a value of 1 will be returned. Precondition: TCP is initialized. Parameters: hTCP - The socket to search within. cFind - The byte to find in the buffer. wStart - Zero-indexed starting position within the buffer. wSearchLen - Length from wStart to search in the buffer. bTextCompare - TRUE for case-insensitive text search, FALSE for binary search Return Values: 0xFFFF - Search array not found Otherwise - Zero-indexed position of the first occurrance Remarks: Since this function usually must transfer data from external storage to internal RAM for comparison, its performance degrades significantly when the buffer is full and the array is not found. For better performance, try to search for characters that are expected to exist or limit the scope of the search as much as possible. The HTTP2 module, for example, uses this function to parse headers. However, it searches for newlines, then the separating colon, then reads the header name to RAM for final comparison. This has proven to be significantly faster than searching for full header name strings outright. ***************************************************************************/ WORD TCPFindEx(TCP_SOCKET hTCP, BYTE cFind, WORD wStart, WORD wSearchLen, BOOL bTextCompare) { return TCPFindArrayEx(hTCP, &cFind, sizeof(cFind), wStart, wSearchLen, bTextCompare); } /**************************************************************************** Section: Data Processing Functions ***************************************************************************/ /***************************************************************************** Function: void TCPTick(void) Summary: Performs periodic TCP tasks. Description: This function performs any required periodic TCP tasks. Each socket's state machine is checked, and any elapsed timeout periods are handled. Precondition: TCP is initialized. Parameters: None Returns: None ***************************************************************************/ void TCPTick(void) { TCP_SOCKET hTCP; BOOL bRetransmit; BOOL bCloseSocket; BYTE vFlags; WORD w; // Periodically all "not closed" sockets must perform timed operations for(hTCP = 0; hTCP < TCP_SOCKET_COUNT; hTCP++) { SyncTCBStub(hTCP); // Handle any SSL Processing and Message Transmission #if defined(STACK_USE_SSL) if(MyTCBStub.sslStubID != SSL_INVALID_ID) { // Handle any periodic tasks, such as RSA operations SSLPeriodic(hTCP, MyTCBStub.sslStubID); // If unsent data is waiting, transmit it as an application record if(MyTCBStub.sslTxHead != MyTCBStub.txHead && TCPSSLGetPendingTxSize(hTCP) != 0u) SSLTxRecord(hTCP, MyTCBStub.sslStubID, SSL_APPLICATION); // If an SSL message is requested, send it now if(MyTCBStub.sslReqMessage != SSL_NO_MESSAGE) SSLTxMessage(hTCP, MyTCBStub.sslStubID, MyTCBStub.sslReqMessage); } #endif vFlags = 0x00; bRetransmit = FALSE; bCloseSocket = FALSE; // Transmit ASAP data if the medium is available if(MyTCBStub.Flags.bTXASAP || MyTCBStub.Flags.bTXASAPWithoutTimerReset) { if(MACIsTxReady()) { vFlags = ACK; bRetransmit = MyTCBStub.Flags.bTXASAPWithoutTimerReset; } } // Perform any needed window updates and data transmissions if(MyTCBStub.Flags.bTimer2Enabled) { // See if the timeout has occured, and we need to send a new window update and pending data if((SHORT)(MyTCBStub.eventTime2 - (WORD)TickGetDiv256()) <= (SHORT)0) vFlags = ACK; } // Process Delayed ACKnowledgement timer if(MyTCBStub.Flags.bDelayedACKTimerEnabled) { // See if the timeout has occured and delayed ACK needs to be sent if((SHORT)(MyTCBStub.OverlappedTimers.delayedACKTime - (WORD)TickGetDiv256()) <= (SHORT)0) vFlags = ACK; } // Process TCP_CLOSE_WAIT timer if(MyTCBStub.smState == TCP_CLOSE_WAIT) { // Automatically close the socket on our end if the application // fails to call TCPDisconnect() is a reasonable amount of time. if((SHORT)(MyTCBStub.OverlappedTimers.closeWaitTime - (WORD)TickGetDiv256()) <= (SHORT)0) { vFlags = FIN | ACK; MyTCBStub.smState = TCP_LAST_ACK; } } // Process listening server sockets that might have a SYN waiting in the SYNQueue[] #if TCP_SYN_QUEUE_MAX_ENTRIES if(MyTCBStub.smState == TCP_LISTEN) { for(w = 0; w < TCP_SYN_QUEUE_MAX_ENTRIES; w++) { // Abort search if there are no more valid records if(SYNQueue[w].wDestPort == 0u) break; // Stop searching if this SYN queue entry can be used by this socket #if defined(STACK_USE_SSL_SERVER) if(SYNQueue[w].wDestPort == MyTCBStub.remoteHash.Val || SYNQueue[w].wDestPort == MyTCBStub.sslTxHead) #else if(SYNQueue[w].wDestPort == MyTCBStub.remoteHash.Val) #endif { // Set up our socket and generate a reponse SYN+ACK packet SyncTCB(); #if defined(STACK_USE_SSL_SERVER) // If this matches the SSL port, make sure that can be configured // before continuing. If not, break and leave this in the queue if(SYNQueue[w].wDestPort == MyTCBStub.sslTxHead && !TCPStartSSLServer(hTCP)) break; #endif memcpy((void*)&MyTCB.remote.niRemoteMACIP, (void*)&SYNQueue[w].niSourceAddress, sizeof(NODE_INFO)); MyTCB.remotePort.Val = SYNQueue[w].wSourcePort; MyTCB.RemoteSEQ = SYNQueue[w].dwSourceSEQ + 1; MyTCBStub.remoteHash.Val = (MyTCB.remote.niRemoteMACIP.IPAddr.w[1] + MyTCB.remote.niRemoteMACIP.IPAddr.w[0] + MyTCB.remotePort.Val) ^ MyTCB.localPort.Val; vFlags = SYN | ACK; MyTCBStub.smState = TCP_SYN_RECEIVED; // Delete this SYN from the SYNQueue and compact the SYNQueue[] array TCPRAMCopy((PTR_BASE)&SYNQueue[w], TCP_PIC_RAM, (PTR_BASE)&SYNQueue[w+1], TCP_PIC_RAM, (TCP_SYN_QUEUE_MAX_ENTRIES-1u-w)*sizeof(TCP_SYN_QUEUE)); SYNQueue[TCP_SYN_QUEUE_MAX_ENTRIES-1].wDestPort = 0u; break; } } } #endif if(vFlags) SendTCP(vFlags, bRetransmit ? 0 : SENDTCP_RESET_TIMERS); // The TCP_CLOSED, TCP_LISTEN, and sometimes the TCP_ESTABLISHED // state don't need any timeout events, so see if the timer is enabled if(!MyTCBStub.Flags.bTimerEnabled) { #if defined(TCP_KEEP_ALIVE_TIMEOUT) // Only the established state has any use for keep-alives if(MyTCBStub.smState == TCP_ESTABLISHED) { // If timeout has not occured, do not do anything. if((LONG)(TickGet() - MyTCBStub.eventTime) < (LONG)0) continue; // If timeout has occured and the connection appears to be dead (no // responses from remote node at all), close the connection so the // application doesn't sit around indefinitely with a useless socket // that it thinks is still open if(MyTCBStub.Flags.vUnackedKeepalives == TCP_MAX_UNACKED_KEEP_ALIVES) { vFlags = MyTCBStub.Flags.bServer; // Force an immediate FIN and RST transmission // Double calling TCPDisconnect() will also place us // back in the listening state immediately if a server socket. TCPDisconnect(hTCP); TCPDisconnect(hTCP); // Prevent client mode sockets from getting reused by other applications. // The application must call TCPDisconnect() with the handle to free this // socket (and the handle associated with it) if(!vFlags) MyTCBStub.smState = TCP_CLOSED_BUT_RESERVED; continue; } // Otherwise, if a timeout occured, simply send a keep-alive packet SyncTCB(); SendTCP(ACK, SENDTCP_KEEP_ALIVE); MyTCBStub.eventTime = TickGet() + TCP_KEEP_ALIVE_TIMEOUT; } #endif continue; } // If timeout has not occured, do not do anything. if((LONG)(TickGet() - MyTCBStub.eventTime) < (LONG)0) continue; // Load up extended TCB information SyncTCB(); // A timeout has occured. Respond to this timeout condition // depending on what state this socket is in. switch(MyTCBStub.smState) { #if defined(STACK_CLIENT_MODE) #if defined(STACK_USE_DNS) case TCP_GET_DNS_MODULE: if(DNSBeginUsage()) { MyTCBStub.smState = TCP_DNS_RESOLVE; if(MyTCB.flags.bRemoteHostIsROM) DNSResolveROM((ROM BYTE*)(ROM_PTR_BASE)MyTCB.remote.dwRemoteHost, DNS_TYPE_A); else DNSResolve((BYTE*)(PTR_BASE)MyTCB.remote.dwRemoteHost, DNS_TYPE_A); } break; case TCP_DNS_RESOLVE: { IP_ADDR ipResolvedDNSIP; // See if DNS resolution has finished. Note that if the DNS // fails, the &ipResolvedDNSIP will be written with 0x00000000. // MyTCB.remote.dwRemoteHost is unioned with // MyTCB.remote.niRemoteMACIP.IPAddr, so we can't directly write // the DNS result into MyTCB.remote.niRemoteMACIP.IPAddr. We // must copy it over only if the DNS is resolution step was // successful. if(DNSIsResolved(&ipResolvedDNSIP)) { if(DNSEndUsage()) { MyTCB.remote.niRemoteMACIP.IPAddr.Val = ipResolvedDNSIP.Val; MyTCBStub.smState = TCP_GATEWAY_SEND_ARP; MyTCBStub.remoteHash.Val = (MyTCB.remote.niRemoteMACIP.IPAddr.w[1]+MyTCB.remote.niRemoteMACIP.IPAddr.w[0] + MyTCB.remotePort.Val) ^ MyTCB.localPort.Val; MyTCB.retryCount = 0; MyTCB.retryInterval = (TICK_SECOND/4)/256; } else { MyTCBStub.eventTime = TickGet() + 10*TICK_SECOND; MyTCBStub.smState = TCP_GET_DNS_MODULE; } } break; } #endif // #if defined(STACK_USE_DNS) case TCP_GATEWAY_SEND_ARP: // Obtain the MAC address associated with the server's IP address (either direct MAC address on same subnet, or the MAC address of the Gateway machine) MyTCBStub.eventTime2 = (WORD)TickGetDiv256(); ARPResolve(&MyTCB.remote.niRemoteMACIP.IPAddr); MyTCBStub.smState = TCP_GATEWAY_GET_ARP; break; case TCP_GATEWAY_GET_ARP: // Wait for the MAC address to finish being obtained if(!ARPIsResolved(&MyTCB.remote.niRemoteMACIP.IPAddr, &MyTCB.remote.niRemoteMACIP.MACAddr)) { // Time out if too much time is spent in this state // Note that this will continuously send out ARP // requests for an infinite time if the Gateway // never responds if((WORD)TickGetDiv256() - MyTCBStub.eventTime2 > (WORD)MyTCB.retryInterval) { // Exponentially increase timeout until we reach 6 attempts then stay constant if(MyTCB.retryCount < 6u) { MyTCB.retryCount++; MyTCB.retryInterval <<= 1; } // Retransmit ARP request MyTCBStub.smState = TCP_GATEWAY_SEND_ARP; } break; } // Send out SYN connection request to remote node // This automatically disables the Timer from // continuously firing for this socket vFlags = SYN; bRetransmit = FALSE; MyTCBStub.smState = TCP_SYN_SENT; break; #endif // #if defined(STACK_CLIENT_MODE) case TCP_SYN_SENT: // Keep sending SYN until we hear from remote node. // This may be for infinite time, in that case // caller must detect it and do something. vFlags = SYN; bRetransmit = TRUE; break; case TCP_SYN_RECEIVED: // We must receive ACK before timeout expires. // If not, resend SYN+ACK. // Abort, if maximum attempts counts are reached. if(MyTCB.retryCount < TCP_MAX_SYN_RETRIES) { vFlags = SYN | ACK; bRetransmit = TRUE; } else { if(MyTCBStub.Flags.bServer) { vFlags = RST | ACK; bCloseSocket = TRUE; } else { vFlags = SYN; } } break; case TCP_ESTABLISHED: case TCP_CLOSE_WAIT: // Retransmit any unacknowledged data if(MyTCB.retryCount < TCP_MAX_RETRIES) { vFlags = ACK; bRetransmit = TRUE; } else { // No response back for too long, close connection // This could happen, for instance, if the communication // medium was lost MyTCBStub.smState = TCP_FIN_WAIT_1; vFlags = FIN | ACK; } break; case TCP_FIN_WAIT_1: if(MyTCB.retryCount < TCP_MAX_RETRIES) { // Send another FIN vFlags = FIN | ACK; bRetransmit = TRUE; } else { // Close on our own, we can't seem to communicate // with the remote node anymore vFlags = RST | ACK; bCloseSocket = TRUE; } break; case TCP_FIN_WAIT_2: // Close on our own, we can't seem to communicate // with the remote node anymore vFlags = RST | ACK; bCloseSocket = TRUE; break; case TCP_CLOSING: if(MyTCB.retryCount < TCP_MAX_RETRIES) { // Send another ACK+FIN (the FIN is retransmitted // automatically since it hasn't been acknowledged by // the remote node yet) vFlags = ACK; bRetransmit = TRUE; } else { // Close on our own, we can't seem to communicate // with the remote node anymore vFlags = RST | ACK; bCloseSocket = TRUE; } break; // case TCP_TIME_WAIT: // // Wait around for a while (2MSL) and then goto closed state // bCloseSocket = TRUE; // break; // case TCP_LAST_ACK: // Send some more FINs or close anyway if(MyTCB.retryCount < TCP_MAX_RETRIES) { vFlags = FIN | ACK; bRetransmit = TRUE; } else { vFlags = RST | ACK; bCloseSocket = TRUE; } break; default: break; } if(vFlags) { if(bRetransmit) { // Set the appropriate retry time MyTCB.retryCount++; MyTCB.retryInterval <<= 1; // Transmit all unacknowledged data over again // Roll back unacknowledged TX tail pointer to cause retransmit to occur MyTCB.MySEQ -= (LONG)(SHORT)(MyTCB.txUnackedTail - MyTCBStub.txTail); if(MyTCB.txUnackedTail < MyTCBStub.txTail) MyTCB.MySEQ -= (LONG)(SHORT)(MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart); MyTCB.txUnackedTail = MyTCBStub.txTail; SendTCP(vFlags, 0); } else SendTCP(vFlags, SENDTCP_RESET_TIMERS); } if(bCloseSocket) CloseSocket(); } #if TCP_SYN_QUEUE_MAX_ENTRIES // Process SYN Queue entry timeouts for(w = 0; w < TCP_SYN_QUEUE_MAX_ENTRIES; w++) { // Abort search if there are no more valid records if(SYNQueue[w].wDestPort == 0u) break; // See if this SYN has timed out if((WORD)TickGetDiv256() - SYNQueue[w].wTimestamp > (WORD)(TCP_SYN_QUEUE_TIMEOUT/256ull)) { // Delete this SYN from the SYNQueue and compact the SYNQueue[] array TCPRAMCopy((PTR_BASE)&SYNQueue[w], TCP_PIC_RAM, (PTR_BASE)&SYNQueue[w+1], TCP_PIC_RAM, (TCP_SYN_QUEUE_MAX_ENTRIES-1u-w)*sizeof(TCP_SYN_QUEUE)); SYNQueue[TCP_SYN_QUEUE_MAX_ENTRIES-1].wDestPort = 0u; // Since we deleted an entry, we need to roll back one // index so next loop will process the correct record w--; } } #endif } /***************************************************************************** Function: BOOL TCPProcess(NODE_INFO* remote, IP_ADDR* localIP, WORD len) Summary: Handles incoming TCP segments. Description: This function handles incoming TCP segments. When a segment arrives, it is compared to open sockets using a hash of the remote port and IP. On a match, the data is passed to HandleTCPSeg for further processing. Precondition: TCP is initialized and a TCP segment is ready in the MAC buffer. Parameters: remote - Remote NODE_INFO structure localIP - This stack's IP address (for header checking) len - Total length of the waiting TCP segment Return Values: TRUE - the segment was properly handled. FALSE - otherwise ***************************************************************************/ BOOL TCPProcess(NODE_INFO* remote, IP_ADDR* localIP, WORD len) { TCP_HEADER TCPHeader; PSEUDO_HEADER pseudoHeader; WORD_VAL checksum1; WORD_VAL checksum2; BYTE optionsSize; // Calculate IP pseudoheader checksum. pseudoHeader.SourceAddress = remote->IPAddr; pseudoHeader.DestAddress = *localIP; pseudoHeader.Zero = 0x0; pseudoHeader.Protocol = IP_PROT_TCP; pseudoHeader.Length = len; SwapPseudoHeader(pseudoHeader); checksum1.Val = ~CalcIPChecksum((BYTE*)&pseudoHeader, sizeof(pseudoHeader)); // Now calculate TCP packet checksum in NIC RAM - should match // pesudo header checksum checksum2.Val = CalcIPBufferChecksum(len); // Compare checksums. if(checksum1.Val != checksum2.Val) { MACDiscardRx(); return TRUE; } #if defined(DEBUG_GENERATE_RX_LOSS) // Throw RX packets away randomly if(rand() > DEBUG_GENERATE_RX_LOSS) { MACDiscardRx(); return TRUE; } #endif // Retrieve TCP header. IPSetRxBuffer(0); MACGetArray((BYTE*)&TCPHeader, sizeof(TCPHeader)); SwapTCPHeader(&TCPHeader); // Skip over options to retrieve data bytes optionsSize = (BYTE)((TCPHeader.DataOffset.Val << 2)- sizeof(TCPHeader)); len = len - optionsSize - sizeof(TCPHeader); // Find matching socket. if(FindMatchingSocket(&TCPHeader, remote)) { #if defined(STACK_USE_SSL) PTR_BASE prevRxHead; // For SSL connections, show HandleTCPSeg() the full data buffer prevRxHead = MyTCBStub.rxHead; if(MyTCBStub.sslStubID != SSL_INVALID_ID) MyTCBStub.rxHead = MyTCBStub.sslRxHead; #endif HandleTCPSeg(&TCPHeader, len); #if defined(STACK_USE_SSL) if(MyTCBStub.sslStubID != SSL_INVALID_ID) { // Restore the buffer state MyTCBStub.sslRxHead = MyTCBStub.rxHead; MyTCBStub.rxHead = prevRxHead; // Process the new SSL data, using the currently loaded stub TCPSSLHandleIncoming(hCurrentTCP); } #endif } // else // { // // NOTE: RFC 793 specifies that if the socket is closed and a segment // // arrives, we should send back a RST if the RST bit in the incoming // // packet is not set. Instead, we will just silently ignore such a // // packet since this is what firewalls do on purpose to enhance // // security. // //if(!TCPHeader.Flags.bits.flagRST) // // SendTCP(RST, SENDTCP_RESET_TIMERS); // } // Finished with this packet, discard it and free the Ethernet RAM for new packets MACDiscardRx(); return TRUE; } /***************************************************************************** Function: static void SendTCP(BYTE vTCPFlags, BYTE vSendFlags) Summary: Transmits a TPC segment. Description: This function assembles and transmits a TCP segment, including any pending data. It also supports retransmissions, keep-alives, and other packet types. Precondition: TCP is initialized. Parameters: vTCPFlags - Additional TCP flags to include vSendFlags - Any combinations of SENDTCP_* constants to modify the transmit behavior or contents. Returns: None ***************************************************************************/ static void SendTCP(BYTE vTCPFlags, BYTE vSendFlags) { WORD_VAL wVal; TCP_HEADER header; TCP_OPTIONS options; PSEUDO_HEADER pseudoHeader; WORD len; WORD wEffectiveWindow; SyncTCB(); // FINs must be handled specially if(vTCPFlags & FIN) { MyTCBStub.Flags.bTXFIN = 1; vTCPFlags &= ~FIN; } // Status will now be synched, disable automatic future // status transmissions MyTCBStub.Flags.bTimer2Enabled = 0; MyTCBStub.Flags.bDelayedACKTimerEnabled = 0; MyTCBStub.Flags.bOneSegmentReceived = 0; MyTCBStub.Flags.bTXASAP = 0; MyTCBStub.Flags.bTXASAPWithoutTimerReset = 0; MyTCBStub.Flags.bHalfFullFlush = 0; // Make sure that we can write to the MAC transmit area while(!IPIsTxReady()); // Put all socket application data in the TX space if(vTCPFlags & (SYN | RST)) { // Don't put any data in SYN and RST messages len = 0; } else { // Begin copying any application data over to the TX space if(MyTCBStub.txHead == MyTCB.txUnackedTail) { // All caught up on data TX, no real data for this packet len = 0; // If we are to transmit a FIN, make sure we can put one in this packet if(MyTCBStub.Flags.bTXFIN) { if(MyTCB.remoteWindow) vTCPFlags |= FIN; } } else if(MyTCBStub.txHead > MyTCB.txUnackedTail) { len = MyTCBStub.txHead - MyTCB.txUnackedTail; wEffectiveWindow = MyTCB.remoteWindow; if(MyTCB.txUnackedTail >= MyTCBStub.txTail) wEffectiveWindow -= MyTCB.txUnackedTail - MyTCBStub.txTail; else wEffectiveWindow -= (MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart) - (MyTCBStub.txTail - MyTCB.txUnackedTail); if(len > wEffectiveWindow) len = wEffectiveWindow; if(len > TCP_MAX_SEG_SIZE) { len = TCP_MAX_SEG_SIZE; MyTCBStub.Flags.bTXASAPWithoutTimerReset = 1; } // If we are to transmit a FIN, make sure we can put one in this packet if(MyTCBStub.Flags.bTXFIN) { if((len != wEffectiveWindow) && (len != TCP_MAX_SEG_SIZE)) vTCPFlags |= FIN; } // Copy application data into the raw TX buffer TCPRAMCopy(BASE_TX_ADDR+sizeof(ETHER_HEADER)+sizeof(IP_HEADER)+sizeof(TCP_HEADER), TCP_ETH_RAM, MyTCB.txUnackedTail, MyTCBStub.vMemoryMedium, len); MyTCB.txUnackedTail += len; } else { pseudoHeader.Length = MyTCBStub.bufferRxStart - MyTCB.txUnackedTail; len = pseudoHeader.Length + MyTCBStub.txHead - MyTCBStub.bufferTxStart; wEffectiveWindow = MyTCB.remoteWindow; if(MyTCB.txUnackedTail >= MyTCBStub.txTail) wEffectiveWindow -= MyTCB.txUnackedTail - MyTCBStub.txTail; else wEffectiveWindow -= (MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart) - (MyTCBStub.txTail - MyTCB.txUnackedTail); if(len > wEffectiveWindow) len = wEffectiveWindow; if(len > TCP_MAX_SEG_SIZE) { len = TCP_MAX_SEG_SIZE; MyTCBStub.Flags.bTXASAPWithoutTimerReset = 1; } // If we are to transmit a FIN, make sure we can put one in this packet if(MyTCBStub.Flags.bTXFIN) { if((len != wEffectiveWindow) && (len != TCP_MAX_SEG_SIZE)) vTCPFlags |= FIN; } if(pseudoHeader.Length > len) pseudoHeader.Length = len; // Copy application data into the raw TX buffer TCPRAMCopy(BASE_TX_ADDR+sizeof(ETHER_HEADER)+sizeof(IP_HEADER)+sizeof(TCP_HEADER), TCP_ETH_RAM, MyTCB.txUnackedTail, MyTCBStub.vMemoryMedium, pseudoHeader.Length); pseudoHeader.Length = len - pseudoHeader.Length; // Copy any left over chunks of application data over if(pseudoHeader.Length) { TCPRAMCopy(BASE_TX_ADDR+sizeof(ETHER_HEADER)+sizeof(IP_HEADER)+sizeof(TCP_HEADER)+(MyTCBStub.bufferRxStart-MyTCB.txUnackedTail), TCP_ETH_RAM, MyTCBStub.bufferTxStart, MyTCBStub.vMemoryMedium, pseudoHeader.Length); } MyTCB.txUnackedTail += len; if(MyTCB.txUnackedTail >= MyTCBStub.bufferRxStart) MyTCB.txUnackedTail -= MyTCBStub.bufferRxStart-MyTCBStub.bufferTxStart; } } // Ensure that all packets with data of some kind are // retransmitted by TCPTick() until acknowledged // Pure ACK packets with no data are not ACKed back in TCP if(len || (vTCPFlags & (SYN | FIN))) { // Push (PSH) all data for enhanced responsiveness on // the remote end, especially with GUIs if(len) vTCPFlags |= PSH; if(vSendFlags & SENDTCP_RESET_TIMERS) { MyTCB.retryCount = 0; MyTCB.retryInterval = TCP_START_TIMEOUT_VAL; } MyTCBStub.eventTime = TickGet() + MyTCB.retryInterval; MyTCBStub.Flags.bTimerEnabled = 1; } else if(vSendFlags & SENDTCP_KEEP_ALIVE) { // Increment Keep Alive TX counter to handle disconnection if not response is returned MyTCBStub.Flags.vUnackedKeepalives++; // Generate a dummy byte MyTCB.MySEQ -= 1; len = 1; } else if(MyTCBStub.Flags.bTimerEnabled) { // If we have data to transmit, but the remote RX window is zero, // so we aren't transmitting any right now then make sure to not // extend the retry counter or timer. This will stall our TX // with a periodic ACK sent to the remote node. if(!(vSendFlags & SENDTCP_RESET_TIMERS)) { // Roll back retry counters since we can't send anything, // but only if we incremented it in the first place if(MyTCB.retryCount) { MyTCB.retryCount--; MyTCB.retryInterval >>= 1; } } MyTCBStub.eventTime = TickGet() + MyTCB.retryInterval; } header.SourcePort = MyTCB.localPort.Val; header.DestPort = MyTCB.remotePort.Val; header.SeqNumber = MyTCB.MySEQ; header.AckNumber = MyTCB.RemoteSEQ; header.Flags.bits.Reserved2 = 0; header.DataOffset.Reserved3 = 0; header.Flags.byte = vTCPFlags; header.UrgentPointer = 0; // Update our send sequence number and ensure retransmissions // of SYNs and FINs use the right sequence number MyTCB.MySEQ += (DWORD)len; if(vTCPFlags & SYN) { // SEG.ACK needs to be zero for the first SYN packet for compatibility // with certain paranoid TCP/IP stacks, even though the ACK flag isn't // set (indicating that the AckNumber field is unused). if(!(vTCPFlags & ACK)) header.AckNumber = 0x00000000; if(MyTCB.flags.bSYNSent) header.SeqNumber--; else { MyTCB.MySEQ++; MyTCB.flags.bSYNSent = 1; } } if(vTCPFlags & FIN) { if(MyTCB.flags.bFINSent) header.SeqNumber--; else { MyTCB.MySEQ++; MyTCB.flags.bFINSent = 1; } } // Calculate the amount of free space in the RX buffer area of this socket if(MyTCBStub.rxHead >= MyTCBStub.rxTail) header.Window = (MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart) - (MyTCBStub.rxHead - MyTCBStub.rxTail); else header.Window = MyTCBStub.rxTail - MyTCBStub.rxHead - 1; // Calculate the amount of free space in the MAC RX buffer area and adjust window if needed wVal.Val = MACGetFreeRxSize()-64; if((SHORT)wVal.Val < (SHORT)0) wVal.Val = 0; // Force the remote node to throttle back if we are running low on general RX buffer space if(header.Window > wVal.Val) header.Window = wVal.Val; SwapTCPHeader(&header); len += sizeof(header); header.DataOffset.Val = sizeof(header) >> 2; // Insert the MSS (Maximum Segment Size) TCP option if this is SYN packet if(vTCPFlags & SYN) { len += sizeof(options); options.Kind = TCP_OPTIONS_MAX_SEG_SIZE; options.Length = 0x04; // Load MSS and swap to big endian options.MaxSegSize.Val = (((TCP_MAX_SEG_SIZE-4)&0x00FF)<<8) | (((TCP_MAX_SEG_SIZE-4)&0xFF00)>>8); header.DataOffset.Val += sizeof(options) >> 2; } // Calculate IP pseudoheader checksum. pseudoHeader.SourceAddress = AppConfig.MyIPAddr; pseudoHeader.DestAddress = MyTCB.remote.niRemoteMACIP.IPAddr; pseudoHeader.Zero = 0x0; pseudoHeader.Protocol = IP_PROT_TCP; pseudoHeader.Length = len; SwapPseudoHeader(pseudoHeader); header.Checksum = ~CalcIPChecksum((BYTE*)&pseudoHeader, sizeof(pseudoHeader)); // Write IP header MACSetWritePtr(BASE_TX_ADDR + sizeof(ETHER_HEADER)); IPPutHeader(&MyTCB.remote.niRemoteMACIP, IP_PROT_TCP, len); MACPutArray((BYTE*)&header, sizeof(header)); if(vTCPFlags & SYN) MACPutArray((BYTE*)&options, sizeof(options)); // Update the TCP checksum MACSetReadPtr(BASE_TX_ADDR + sizeof(ETHER_HEADER) + sizeof(IP_HEADER)); wVal.Val = CalcIPBufferChecksum(len); #if defined(DEBUG_GENERATE_TX_LOSS) // Damage TCP checksums on TX packets randomly if(rand() > DEBUG_GENERATE_TX_LOSS) { wVal.Val++; } #endif MACSetWritePtr(BASE_TX_ADDR + sizeof(ETHER_HEADER) + sizeof(IP_HEADER) + 16); MACPutArray((BYTE*)&wVal, sizeof(WORD)); // Physically start the packet transmission over the network MACFlush(); } /***************************************************************************** Function: static BOOL FindMatchingSocket(TCP_HEADER* h, NODE_INFO* remote) Summary: Finds a suitable socket for a TCP segment. Description: This function searches through the sockets and attempts to match one with a given TCP header and NODE_INFO structure. If a socket is found, its index is saved in hCurrentTCP and the associated MyTCBStub and MyTCB are loaded. Otherwise, INVALID_SOCKET is placed in hCurrentTCP. Precondition: TCP is initialized. Parameters: h - TCP header to be matched against remote - The remote node who sent this header Return Values: TRUE - A match was found and is loaded in hCurrentTCP FALSE - No suitable socket was found and hCurrentTCP is INVALID_SOCKET ***************************************************************************/ static BOOL FindMatchingSocket(TCP_HEADER* h, NODE_INFO* remote) { TCP_SOCKET hTCP; TCP_SOCKET partialMatch; WORD hash; // Prevent connections on invalid port 0 if(h->DestPort == 0u) return FALSE; partialMatch = INVALID_SOCKET; hash = (remote->IPAddr.w[1]+remote->IPAddr.w[0] + h->SourcePort) ^ h->DestPort; // Loop through all sockets looking for a socket that is expecting this // packet or can handle it. for(hTCP = 0; hTCP < TCP_SOCKET_COUNT; hTCP++ ) { SyncTCBStub(hTCP); if(MyTCBStub.smState == TCP_CLOSED) { continue; } else if(MyTCBStub.smState == TCP_LISTEN) {// For listening ports, check if this is the correct port if(MyTCBStub.remoteHash.Val == h->DestPort) partialMatch = hTCP; #if defined(STACK_USE_SSL_SERVER) // Check the SSL port as well for SSL Servers // 0 is defined as an invalid port number if(MyTCBStub.sslTxHead == h->DestPort) partialMatch = hTCP; #endif continue; } else if(MyTCBStub.remoteHash.Val != hash) {// Ignore if the hash doesn't match continue; } SyncTCB(); if( h->DestPort == MyTCB.localPort.Val && h->SourcePort == MyTCB.remotePort.Val && remote->IPAddr.Val == MyTCB.remote.niRemoteMACIP.IPAddr.Val) { return TRUE; } } // If there is a partial match, then a listening socket is currently // available. Set up the extended TCB with the info needed // to establish a connection and return this socket to the // caller. if(partialMatch != INVALID_SOCKET) { SyncTCBStub(partialMatch); SyncTCB(); // For SSL ports, begin the SSL Handshake #if defined(STACK_USE_SSL_SERVER) if(MyTCBStub.sslTxHead == h->DestPort) { // Try to start an SSL session. If no stubs are available, // we can't service this request right now, so ignore it. if(!TCPStartSSLServer(partialMatch)) partialMatch = INVALID_SOCKET; } #endif // Make sure the above check didn't fail (this is unfortunately // redundant for non-SSL sockets). Otherwise, fall out to below // and add to the SYN queue. if(partialMatch != INVALID_SOCKET) { MyTCBStub.remoteHash.Val = hash; memcpy((void*)&MyTCB.remote, (void*)remote, sizeof(NODE_INFO)); MyTCB.remotePort.Val = h->SourcePort; MyTCB.localPort.Val = h->DestPort; MyTCB.txUnackedTail = MyTCBStub.bufferTxStart; // All done, and we have a match return TRUE; } } // No available sockets are listening on this port. (Or, for // SSL requests, perhaps no SSL sessions were available. However, // there may be a server socket which is currently busy but // could handle this packet, so we should check. #if TCP_SYN_QUEUE_MAX_ENTRIES { WORD wQueueInsertPos; // See if this is a SYN packet if(!h->Flags.bits.flagSYN) return FALSE; // See if there is space in our SYN queue if(SYNQueue[TCP_SYN_QUEUE_MAX_ENTRIES-1].wDestPort) return FALSE; // See if we have this SYN already in our SYN queue. // If not already in the queue, find out where we // should insert this SYN to the queue for(wQueueInsertPos = 0; wQueueInsertPos < TCP_SYN_QUEUE_MAX_ENTRIES; wQueueInsertPos++) { // Exit loop if we found a free record if(SYNQueue[wQueueInsertPos].wDestPort == 0u) break; // Check if this SYN packet is already in the SYN queue if(SYNQueue[wQueueInsertPos].wDestPort != h->DestPort) continue; if(SYNQueue[wQueueInsertPos].wSourcePort != h->SourcePort) continue; if(SYNQueue[wQueueInsertPos].niSourceAddress.IPAddr.Val != remote->IPAddr.Val) continue; // SYN matches SYN queue entry. Update timestamp and do nothing. SYNQueue[wQueueInsertPos].wTimestamp = TickGetDiv256(); return FALSE; } // Check to see if we have any server sockets which // are currently connected, but could handle this SYN // request at a later time if the client disconnects. for(hTCP = 0; hTCP < TCP_SOCKET_COUNT; hTCP++) { SyncTCBStub(hTCP); if(!MyTCBStub.Flags.bServer) continue; SyncTCB(); #if defined(STACK_USE_SSL_SERVER) if((MyTCB.localPort.Val != h->DestPort) && (MyTCB.localSSLPort.Val != h->DestPort)) #else if(MyTCB.localPort.Val != h->DestPort) #endif continue; // Generate the SYN queue entry memcpy((void*)&SYNQueue[wQueueInsertPos].niSourceAddress, (void*)remote, sizeof(NODE_INFO)); SYNQueue[wQueueInsertPos].wSourcePort = h->SourcePort; SYNQueue[wQueueInsertPos].dwSourceSEQ = h->SeqNumber; SYNQueue[wQueueInsertPos].wDestPort = h->DestPort; SYNQueue[wQueueInsertPos].wTimestamp = TickGetDiv256(); return FALSE; } } #endif return FALSE; } /***************************************************************************** Function: static void SwapTCPHeader(TCP_HEADER* header) Summary: Swaps endian-ness of a TCP header. Description: This function swaps the endian-ness of a given TCP header for comparison. Precondition: None Parameters: header - The TCP header that is to be swapped Returns: None ***************************************************************************/ static void SwapTCPHeader(TCP_HEADER* header) { header->SourcePort = swaps(header->SourcePort); header->DestPort = swaps(header->DestPort); header->SeqNumber = swapl(header->SeqNumber); header->AckNumber = swapl(header->AckNumber); header->Window = swaps(header->Window); header->Checksum = swaps(header->Checksum); header->UrgentPointer = swaps(header->UrgentPointer); } /***************************************************************************** Function: static void CloseSocket(void) Summary: Closes a TCP socket. Description: This function closes a TCP socket. All socket state information is reset, and any buffered bytes are discarded. The socket is no longer accessible by the application after this point. Precondition: The TCPStub corresponding to the socket to be closed is synced. Parameters: None Returns: None ***************************************************************************/ static void CloseSocket(void) { SyncTCB(); MyTCBStub.remoteHash.Val = MyTCB.localPort.Val; MyTCBStub.txHead = MyTCBStub.bufferTxStart; MyTCBStub.txTail = MyTCBStub.bufferTxStart; MyTCBStub.rxHead = MyTCBStub.bufferRxStart; MyTCBStub.rxTail = MyTCBStub.bufferRxStart; MyTCBStub.smState = MyTCBStub.Flags.bServer ? TCP_LISTEN : TCP_CLOSED; MyTCBStub.Flags.vUnackedKeepalives = 0; MyTCBStub.Flags.bTimerEnabled = 0; MyTCBStub.Flags.bTimer2Enabled = 0; MyTCBStub.Flags.bDelayedACKTimerEnabled = 0; MyTCBStub.Flags.bOneSegmentReceived = 0; MyTCBStub.Flags.bHalfFullFlush = 0; MyTCBStub.Flags.bTXASAP = 0; MyTCBStub.Flags.bTXASAPWithoutTimerReset = 0; MyTCBStub.Flags.bTXFIN = 0; MyTCBStub.Flags.bSocketReset = 1; #if defined(STACK_USE_SSL) // If SSL is active, then we need to close it if(MyTCBStub.sslStubID != SSL_INVALID_ID) { SSLTerminate(MyTCBStub.sslStubID); MyTCBStub.sslStubID = SSL_INVALID_ID; // Swap the SSL port and local port back to proper values MyTCBStub.remoteHash.Val = MyTCB.localSSLPort.Val; MyTCB.localSSLPort.Val = MyTCB.localPort.Val; MyTCB.localPort.Val = MyTCBStub.remoteHash.Val; } // Reset the SSL buffer pointers MyTCBStub.sslRxHead = MyTCBStub.bufferRxStart; MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; #endif #if defined(STACK_USE_SSL_SERVER) MyTCBStub.sslTxHead = MyTCB.localSSLPort.Val; #endif MyTCB.flags.bFINSent = 0; MyTCB.flags.bSYNSent = 0; MyTCB.flags.bRXNoneACKed1 = 0; MyTCB.flags.bRXNoneACKed2 = 0; MyTCB.txUnackedTail = MyTCBStub.bufferTxStart; ((DWORD_VAL*)(&MyTCB.MySEQ))->w[0] = rand(); ((DWORD_VAL*)(&MyTCB.MySEQ))->w[1] = rand(); MyTCB.sHoleSize = -1; MyTCB.remoteWindow = 1; } /***************************************************************************** Function: static void HandleTCPSeg(TCP_HEADER* h, WORD len) Summary: Processes an incoming TCP segment. Description: Once an incoming segment has been matched to a socket, this function performs the necessary processing with the data. Depending on the segment and the state, this may include copying data to the TCP buffer, re-assembling out-of order packets, continuing an initialization or closing handshake, or closing the socket altogether. Precondition: TCP is initialized and the current TCP stub is already synced. Parameters: h - The TCP header for this packet len - The total buffer length of this segment Returns: None ***************************************************************************/ static void HandleTCPSeg(TCP_HEADER* h, WORD len) { DWORD dwTemp; PTR_BASE wTemp; LONG lMissingBytes; WORD wMissingBytes; WORD wFreeSpace; BYTE localHeaderFlags; DWORD localAckNumber; DWORD localSeqNumber; WORD wSegmentLength; BOOL bSegmentAcceptable; // Cache a few variables in local RAM. // PIC18s take a fair amount of code and execution time to // dereference pointers frequently. localHeaderFlags = h->Flags.byte; localAckNumber = h->AckNumber; localSeqNumber = h->SeqNumber; // We received a packet, reset the keep alive timer and count #if defined(TCP_KEEP_ALIVE_TIMEOUT) MyTCBStub.Flags.vUnackedKeepalives = 0; if(!MyTCBStub.Flags.bTimerEnabled) MyTCBStub.eventTime = TickGet() + TCP_KEEP_ALIVE_TIMEOUT; #endif // Handle TCP_LISTEN and TCP_SYN_SENT states // Both of these states will return, so code following this // state machine need not check explicitly for these two // states. switch(MyTCBStub.smState) { case TCP_LISTEN: // First: check RST flag if(localHeaderFlags & RST) { CloseSocket(); // Unbind remote IP address/port info return; } // Second: check ACK flag, which would be invalid if(localHeaderFlags & ACK) { // Use a believable sequence number and reset the remote node MyTCB.MySEQ = localAckNumber; SendTCP(RST, 0); CloseSocket(); // Unbind remote IP address/port info return; } // Third: check for SYN flag, which is what we're looking for if(localHeaderFlags & SYN) { // We now have a sequence number for the remote node MyTCB.RemoteSEQ = localSeqNumber + 1; // Set Initial Send Sequence (ISS) number // Nothing to do on this step... ISS already set in CloseSocket() // Respond with SYN + ACK SendTCP(SYN | ACK, SENDTCP_RESET_TIMERS); MyTCBStub.smState = TCP_SYN_RECEIVED; } else { CloseSocket(); // Unbind remote IP address/port info } // Fourth: check for other text and control // Nothing to do since we don't support this return; case TCP_SYN_SENT: // Second: check the RST bit // This is out of order because this stack has no API for // notifying the application that the connection seems to // be failing. Instead, the application must time out and // the stack will just keep trying in the mean time. if(localHeaderFlags & RST) return; // First: check ACK bit if(localHeaderFlags & ACK) { if(localAckNumber != MyTCB.MySEQ) { // Send a RST packet with SEQ = SEG.ACK, but retain our SEQ // number for arivial of any other SYN+ACK packets localSeqNumber = MyTCB.MySEQ; // Save our original SEQ number MyTCB.MySEQ = localAckNumber; // Set SEQ = SEG.ACK SendTCP(RST, SENDTCP_RESET_TIMERS); // Send the RST MyTCB.MySEQ = localSeqNumber; // Restore original SEQ number return; } } // Third: check the security and precedence // No such feature in this stack. We want to accept all connections. // Fourth: check the SYN bit if(localHeaderFlags & SYN) { // We now have an initial sequence number and window size MyTCB.RemoteSEQ = localSeqNumber + 1; MyTCB.remoteWindow = h->Window; if(localHeaderFlags & ACK) { SendTCP(ACK, SENDTCP_RESET_TIMERS); MyTCBStub.smState = TCP_ESTABLISHED; MyTCBStub.Flags.bTimerEnabled = 0; } else { SendTCP(SYN | ACK, SENDTCP_RESET_TIMERS); MyTCBStub.smState = TCP_SYN_RECEIVED; } } // Fifth: drop the segment if neither SYN or RST is set return; default: break; } // // First: check the sequence number // wSegmentLength = len; if(localHeaderFlags & FIN) wSegmentLength++; if(localHeaderFlags & SYN) wSegmentLength++; // Calculate the RX FIFO space if(MyTCBStub.rxHead >= MyTCBStub.rxTail) wFreeSpace = (MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart) - (MyTCBStub.rxHead - MyTCBStub.rxTail); else wFreeSpace = MyTCBStub.rxTail - MyTCBStub.rxHead - 1; // Calculate the number of bytes ahead of our head pointer this segment skips lMissingBytes = localSeqNumber - MyTCB.RemoteSEQ; wMissingBytes = (WORD)lMissingBytes; // Run TCP acceptability tests to verify that this packet has a valid sequence number bSegmentAcceptable = FALSE; if(wSegmentLength) { // Check to see if we have free space, and if so, if any of the data falls within the freespace if(wFreeSpace) { // RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND if((lMissingBytes >= (LONG)0) && (wFreeSpace > (DWORD)lMissingBytes)) bSegmentAcceptable = TRUE; else { // RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND if((lMissingBytes + (LONG)wSegmentLength > (LONG)0) && (lMissingBytes <= (LONG)(SHORT)(wFreeSpace - wSegmentLength))) bSegmentAcceptable = TRUE; } if((lMissingBytes < (LONG)wFreeSpace) && ((SHORT)wMissingBytes + (SHORT)wSegmentLength > (SHORT)0)) bSegmentAcceptable = TRUE; } // Segments with data are not acceptable if we have no free space } else { // Zero length packets are acceptable if they fall within our free space window // SEG.SEQ = RCV.NXT if(lMissingBytes == 0) { bSegmentAcceptable = TRUE; } else { // RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND if((lMissingBytes >= (LONG)0) && (wFreeSpace > (DWORD)lMissingBytes)) bSegmentAcceptable = TRUE; } } if(!bSegmentAcceptable) { // Unacceptable segment, drop it and respond appropriately if(!(localHeaderFlags & RST)) SendTCP(ACK, SENDTCP_RESET_TIMERS); return; } // // Second: check the RST bit // // // Fourth: check the SYN bit // // Note, that since the third step is not implemented, we can // combine this second and fourth step into a single operation. if(localHeaderFlags & (RST | SYN)) { CloseSocket(); return; } // // Third: check the security and precedence // // Feature not supported. Let's process this segment. // // Fifth: check the ACK bit // if(!(localHeaderFlags & ACK)) return; switch(MyTCBStub.smState) { case TCP_SYN_RECEIVED: if(localAckNumber != MyTCB.MySEQ) { // Send a RST packet with SEQ = SEG.ACK, but retain our SEQ // number for arivial of any other correct packets localSeqNumber = MyTCB.MySEQ; // Save our original SEQ number MyTCB.MySEQ = localAckNumber; // Set SEQ = SEG.ACK SendTCP(RST, SENDTCP_RESET_TIMERS); // Send the RST MyTCB.MySEQ = localSeqNumber; // Restore original SEQ number return; } MyTCBStub.smState = TCP_ESTABLISHED; // No break case TCP_ESTABLISHED: case TCP_FIN_WAIT_1: case TCP_FIN_WAIT_2: case TCP_CLOSE_WAIT: case TCP_CLOSING: // Calculate what the highest possible SEQ number in our TX FIFO is wTemp = MyTCBStub.txHead - MyTCB.txUnackedTail; if((SHORT)wTemp < (SHORT)0) wTemp += MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart; dwTemp = MyTCB.MySEQ + (DWORD)wTemp; // Drop the packet if it ACKs something we haven't sent if((LONG)(dwTemp - localAckNumber) < (LONG)0) { SendTCP(ACK, 0); return; } // Throw away all ACKnowledged TX data: // Calculate what the last acknowledged sequence number was (ignoring any FINs we sent) dwTemp = MyTCB.MySEQ - (LONG)(SHORT)(MyTCB.txUnackedTail - MyTCBStub.txTail); if(MyTCB.txUnackedTail < MyTCBStub.txTail) dwTemp -= MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart; // Calcluate how many bytes were ACKed with this packet dwTemp = localAckNumber - dwTemp; if(((LONG)(dwTemp) > (LONG)0) && (dwTemp <= MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart)) { MyTCB.flags.bRXNoneACKed1 = 0; MyTCB.flags.bRXNoneACKed2 = 0; MyTCBStub.Flags.bHalfFullFlush = FALSE; // Bytes ACKed, free up the TX FIFO space wTemp = MyTCBStub.txTail; MyTCBStub.txTail += dwTemp; if(MyTCB.txUnackedTail >= wTemp) { if(MyTCB.txUnackedTail < MyTCBStub.txTail) { MyTCB.MySEQ += MyTCBStub.txTail - MyTCB.txUnackedTail; MyTCB.txUnackedTail = MyTCBStub.txTail; } } else { wTemp = MyTCB.txUnackedTail + (MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart); if(wTemp < MyTCBStub.txTail) { MyTCB.MySEQ += MyTCBStub.txTail - wTemp; MyTCB.txUnackedTail = MyTCBStub.txTail; } } if(MyTCBStub.txTail >= MyTCBStub.bufferRxStart) MyTCBStub.txTail -= MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart; if(MyTCB.txUnackedTail >= MyTCBStub.bufferRxStart) MyTCB.txUnackedTail -= MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart; } else { // See if we have outstanding TX data that is waiting for an ACK if(MyTCBStub.txTail != MyTCB.txUnackedTail) { if(MyTCB.flags.bRXNoneACKed1) { if(MyTCB.flags.bRXNoneACKed2) { // Set up to perform a fast retransmission // Roll back unacknowledged TX tail pointer to cause retransmit to occur MyTCB.MySEQ -= (LONG)(SHORT)(MyTCB.txUnackedTail - MyTCBStub.txTail); if(MyTCB.txUnackedTail < MyTCBStub.txTail) MyTCB.MySEQ -= (LONG)(SHORT)(MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart); MyTCB.txUnackedTail = MyTCBStub.txTail; MyTCBStub.Flags.bTXASAPWithoutTimerReset = 1; } MyTCB.flags.bRXNoneACKed2 = 1; } MyTCB.flags.bRXNoneACKed1 = 1; } } // No need to keep our retransmit timer going if we have nothing that needs ACKing anymore if(MyTCBStub.txTail == MyTCBStub.txHead) { // Make sure there isn't a "FIN byte in our TX FIFO" if(MyTCBStub.Flags.bTXFIN == 0u) { MyTCBStub.Flags.bTimerEnabled = 0; } else { // "Throw away" FIN byte from our TX FIFO if it has been ACKed if(MyTCB.MySEQ == localAckNumber) { MyTCBStub.Flags.bTimerEnabled = 0; MyTCBStub.Flags.bTXFIN = 0; MyTCB.flags.bFINSent = 0; } } } // Update the local stored copy of the RemoteWindow // If previously we had a zero window, and now we don't // immediately send whatever was pending if((MyTCB.remoteWindow == 0u) && h->Window) MyTCBStub.Flags.bTXASAP = 1; MyTCB.remoteWindow = h->Window; // A couple of states must do all of the TCP_ESTABLISHED stuff, but also a little more if(MyTCBStub.smState == TCP_FIN_WAIT_1) { // Check to see if our FIN has been ACKnowledged if(MyTCB.MySEQ == localAckNumber) { // Reset our timer for forced closure if the remote node // doesn't send us a FIN in a timely manner. MyTCBStub.eventTime = TickGet() + TCP_FIN_WAIT_2_TIMEOUT; MyTCBStub.Flags.bTimerEnabled = 1; MyTCBStub.smState = TCP_FIN_WAIT_2; } } else if(MyTCBStub.smState == TCP_FIN_WAIT_2) { // RFC noncompliance: // The remote node should not keep sending us data // indefinitely after we send a FIN to it. // However, some bad stacks may still keep sending // us data indefinitely after ACKing our FIN. To // prevent this from locking up our socket, let's // send a RST right now and close forcefully on // our side. if(!(localHeaderFlags & FIN)) { MyTCB.MySEQ = localAckNumber; // Set SEQ = SEG.ACK SendTCP(RST | ACK, 0); CloseSocket(); return; } } else if(MyTCBStub.smState == TCP_CLOSING) { // Check to see if our FIN has been ACKnowledged if(MyTCB.MySEQ == localAckNumber) { // RFC not recommended: We should be going to // the TCP_TIME_WAIT state right here and // starting a 2MSL timer, but since we have so // few precious sockets, we can't afford to // leave a socket waiting around doing nothing // for a long time. If the remote node does // not recieve this ACK, it'll have to figure // out on it's own that the connection is now // closed. CloseSocket(); } return; } break; case TCP_LAST_ACK: // Check to see if our FIN has been ACKnowledged if(MyTCB.MySEQ == localAckNumber) CloseSocket(); return; // case TCP_TIME_WAIT: // // Nothing is supposed to arrive here. If it does, reset the quiet timer. // SendTCP(ACK, SENDTCP_RESET_TIMERS); // return; default: break; } // // Sixth: Check the URG bit // // Urgent packets are not supported in this stack, so we // will throw them away instead if(localHeaderFlags & URG) return; // // Seventh: Process the segment text // // Throw data away if in a state that doesn't accept data if(MyTCBStub.smState == TCP_CLOSE_WAIT) return; if(MyTCBStub.smState == TCP_CLOSING) return; if(MyTCBStub.smState == TCP_LAST_ACK) return; // if(MyTCBStub.smState == TCP_TIME_WAIT) // return; // Copy any valid segment data into our RX FIFO, if any if(len) { // See if there are bytes we must skip if((SHORT)wMissingBytes <= 0) { // Position packet read pointer to start of useful data area. IPSetRxBuffer((h->DataOffset.Val << 2) - wMissingBytes); len += wMissingBytes; // Truncate packets that would overflow our TCP RX FIFO // and request a retransmit by sending a duplicate ACK if(len > wFreeSpace) len = wFreeSpace; MyTCB.RemoteSEQ += (DWORD)len; // Copy the application data from the packet into the socket RX FIFO // See if we need a two part copy (spans bufferEnd->bufferRxStart) if(MyTCBStub.rxHead + len > MyTCBStub.bufferEnd) { wTemp = MyTCBStub.bufferEnd - MyTCBStub.rxHead + 1; TCPRAMCopy(MyTCBStub.rxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, wTemp); TCPRAMCopy(MyTCBStub.bufferRxStart, MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, len - wTemp); MyTCBStub.rxHead = MyTCBStub.bufferRxStart + (len - wTemp); } else { TCPRAMCopy(MyTCBStub.rxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, len); MyTCBStub.rxHead += len; } // See if we have a hole and other data waiting already in the RX FIFO if(MyTCB.sHoleSize != -1) { MyTCB.sHoleSize -= len; wTemp = MyTCB.wFutureDataSize + MyTCB.sHoleSize; // See if we just closed up a hole, and if so, advance head pointer if((SHORT)wTemp < (SHORT)0) { MyTCB.sHoleSize = -1; } else if(MyTCB.sHoleSize <= 0) { MyTCB.RemoteSEQ += wTemp; MyTCBStub.rxHead += wTemp; if(MyTCBStub.rxHead > MyTCBStub.bufferEnd) MyTCBStub.rxHead -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; MyTCB.sHoleSize = -1; } } } // This packet is out of order or we lost a packet, see if we can generate a hole to accomodate it else if((SHORT)wMissingBytes > 0) { // Truncate packets that would overflow our TCP RX FIFO if(len + wMissingBytes > wFreeSpace) len = wFreeSpace - wMissingBytes; // Position packet read pointer to start of useful data area. IPSetRxBuffer(h->DataOffset.Val << 2); // See if we need a two part copy (spans bufferEnd->bufferRxStart) if(MyTCBStub.rxHead + wMissingBytes + len > MyTCBStub.bufferEnd) { // Calculate number of data bytes to copy before wraparound wTemp = MyTCBStub.bufferEnd - MyTCBStub.rxHead + 1 - wMissingBytes; if((SHORT)wTemp >= 0) { TCPRAMCopy(MyTCBStub.rxHead + wMissingBytes, MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, wTemp); TCPRAMCopy(MyTCBStub.bufferRxStart, MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, len - wTemp); } else { TCPRAMCopy(MyTCBStub.rxHead + wMissingBytes - (MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1), MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, len); } } else { TCPRAMCopy(MyTCBStub.rxHead + wMissingBytes, MyTCBStub.vMemoryMedium, (PTR_BASE)-1, TCP_ETH_RAM, len); } // Record the hole is here if(MyTCB.sHoleSize == -1) { MyTCB.sHoleSize = wMissingBytes; MyTCB.wFutureDataSize = len; } else { // We already have a hole, see if we can shrink the hole // or extend the future data size if(wMissingBytes < (WORD)MyTCB.sHoleSize) { if((wMissingBytes + len > (WORD)MyTCB.sHoleSize + MyTCB.wFutureDataSize) || (wMissingBytes + len < (WORD)MyTCB.sHoleSize)) MyTCB.wFutureDataSize = len; else MyTCB.wFutureDataSize = (WORD)MyTCB.sHoleSize + MyTCB.wFutureDataSize - wMissingBytes; MyTCB.sHoleSize = wMissingBytes; } else if(wMissingBytes + len > (WORD)MyTCB.sHoleSize + MyTCB.wFutureDataSize) { // Make sure that there isn't a second hole between // our future data and this TCP segment's future data if(wMissingBytes <= (WORD)MyTCB.sHoleSize + MyTCB.wFutureDataSize) MyTCB.wFutureDataSize += wMissingBytes + len - (WORD)MyTCB.sHoleSize - MyTCB.wFutureDataSize; } } } } // Send back an ACK of the data (+SYN | FIN) we just received, // if any. To minimize bandwidth waste, we are implementing // the delayed acknowledgement algorithm here, only sending // back an immediate ACK if this is the second segment received. // Otherwise, a 200ms timer will cause the ACK to be transmitted. if(wSegmentLength) { // For non-established sockets, let's delete all data in // the RX buffer immediately after receiving it. This is // not really how TCP was intended to operate since a // socket cannot receive any response after it sends a FIN, // but our TCP application API doesn't readily accomodate // receiving data after calling TCPDisconnect(), which // invalidates the application TCP handle. By deleting all // data, we'll ensure that the RX window is nonzero and // the remote node will be able to send us a FIN response, // which needs an RX window of at least 1. if(MyTCBStub.smState != TCP_ESTABLISHED) MyTCBStub.rxTail = MyTCBStub.rxHead; if(MyTCBStub.Flags.bOneSegmentReceived) { SendTCP(ACK, SENDTCP_RESET_TIMERS); SyncTCB(); // bOneSegmentReceived is cleared in SendTCP(), so no need here } else { MyTCBStub.Flags.bOneSegmentReceived = TRUE; // Do not send an ACK immediately back. Instead, we will // perform delayed acknowledgements. To do this, we will // just start a timer if(!MyTCBStub.Flags.bDelayedACKTimerEnabled) { MyTCBStub.Flags.bDelayedACKTimerEnabled = 1; MyTCBStub.OverlappedTimers.delayedACKTime = (WORD)TickGetDiv256() + (WORD)((TCP_DELAYED_ACK_TIMEOUT)>>8); } } } // // Eighth: check the FIN bit // if(localHeaderFlags & FIN) { // Note: Since we don't have a good means of storing "FIN bytes" // in our TCP RX FIFO, we must ensure that FINs are processed // in-order. if(MyTCB.RemoteSEQ + 1 == localSeqNumber + (DWORD)wSegmentLength) { // FINs are treated as one byte of data for ACK sequencing MyTCB.RemoteSEQ++; switch(MyTCBStub.smState) { case TCP_SYN_RECEIVED: // RFC in exact: Our API has no need for the user // to explicitly close a socket that never really // got opened fully in the first place, so just // transmit a FIN automatically and jump to // TCP_LAST_ACK MyTCBStub.smState = TCP_LAST_ACK; SendTCP(FIN | ACK, SENDTCP_RESET_TIMERS); return; case TCP_ESTABLISHED: // Go to TCP_CLOSE_WAIT state MyTCBStub.smState = TCP_CLOSE_WAIT; // For legacy applications that don't call // TCPDisconnect() as needed and expect the TCP/IP // Stack to automatically close sockets when the // remote node sends a FIN, let's start a timer so // that we will eventually close the socket automatically MyTCBStub.OverlappedTimers.closeWaitTime = (WORD)TickGetDiv256() + (WORD)((TCP_CLOSE_WAIT_TIMEOUT)>>8); break; case TCP_FIN_WAIT_1: if(MyTCB.MySEQ == localAckNumber) { // RFC not recommended: We should be going to // the TCP_TIME_WAIT state right here and // starting a 2MSL timer, but since we have so // few precious sockets, we can't afford to // leave a socket waiting around doing nothing // for a long time. If the remote node does // not recieve this ACK, it'll have to figure // out on it's own that the connection is now // closed. SendTCP(ACK, 0); CloseSocket(); return; } else { MyTCBStub.smState = TCP_CLOSING; } break; case TCP_FIN_WAIT_2: // RFC not recommended: We should be going to // the TCP_TIME_WAIT state right here and // starting a 2MSL timer, but since we have so // few precious sockets, we can't afford to // leave a socket waiting around doing nothing // for a long time. If the remote node does // not recieve this ACK, it'll have to figure // out on it's own that the connection is now // closed. SendTCP(ACK, 0); CloseSocket(); return; default: break; } // Acknowledge receipt of FIN SendTCP(ACK, SENDTCP_RESET_TIMERS); } } } /**************************************************************************** Section: Buffer Management Functions ***************************************************************************/ /***************************************************************************** Function: BOOL TCPAdjustFIFOSize(TCP_SOCKET hTCP, WORD wMinRXSize, WORD wMinTXSize, BYTE vFlags) Summary: Adjusts the relative sizes of the RX and TX buffers. Description: This function can be used to adjust the relative sizes of the RX and TX FIFO depending on the immediate needs of an application. Since a larger FIFO can allow more data to be sent in a given packet, adjusting the relative sizes on the fly can allow for optimal transmission speed for one-sided application protocols. For example, HTTP typically begins by receiving large amounts of data from the client, then switches to serving large amounts of data back. Adjusting the FIFO at these points can increase performance substantially. Once the FIFO is adjusted, a window update is sent. If neither or both of TCP_ADJUST_GIVE_REST_TO_TX and TCP_ADJUST_GIVE_REST_TO_RX are set, the function distributes the remaining space equally. Received data can be preserved as long as the buffer is expanding and has not wrapped. Precondition: TCP is initialized. Parameters: hTCP - The socket to be adjusted wMinRXSize - Minimum number of byte for the RX FIFO wMinTXSize - Minimum number of bytes for the RX FIFO vFlags - Any combination of TCP_ADJUST_GIVE_REST_TO_RX, TCP_ADJUST_GIVE_REST_TO_TX, TCP_ADJUST_PRESERVE_RX. TCP_ADJUST_PRESERVE_TX is not currently supported. Return Values: TRUE - The FIFOs were adjusted successfully FALSE - Minimum RX, Minimum TX, or flags couldn't be accommodated and therefore the socket was left unchanged. Side Effects: Any unacknowledged or untransmitted data in the TX FIFO is always deleted. Remarks: At least one byte must always be allocated to the RX buffer so that a FIN can be received. The function automatically corrects for this. ***************************************************************************/ BOOL TCPAdjustFIFOSize(TCP_SOCKET hTCP, WORD wMinRXSize, WORD wMinTXSize, BYTE vFlags) { PTR_BASE ptrTemp, ptrHead; WORD wTXAllocation; // Load up info on this socket SyncTCBStub(hTCP); // RX has to be at least 1 byte to receive SYN and FIN bytes // from the remote node, even if they aren't stored in the RX FIFO if(wMinRXSize == 0u) wMinRXSize = 1; // SSL connections need to be able to send or receive at least // a full Alert record, MAC, and FIN #if defined(STACK_USE_SSL) if(TCPIsSSL(hTCP) && wMinRXSize < 25u) wMinRXSize = 25; if(TCPIsSSL(hTCP) && wMinTXSize < 25u) wMinTXSize = 25; #endif // Make sure space is available for minimums ptrTemp = MyTCBStub.bufferEnd - MyTCBStub.bufferTxStart - 1; if(wMinRXSize + wMinTXSize > ptrTemp) return FALSE; SyncTCB(); // Set both allocation flags if none set if(!(vFlags & (TCP_ADJUST_GIVE_REST_TO_TX | TCP_ADJUST_GIVE_REST_TO_RX))) vFlags |= TCP_ADJUST_GIVE_REST_TO_TX | TCP_ADJUST_GIVE_REST_TO_RX; // Allocate minimums wTXAllocation = wMinTXSize; ptrTemp -= wMinRXSize + wMinTXSize; // Allocate extra if(vFlags & TCP_ADJUST_GIVE_REST_TO_TX) { if(vFlags & TCP_ADJUST_GIVE_REST_TO_RX) { // Do a 50%/50% split with any odd byte always going to the RX FIFO wTXAllocation += ptrTemp>>1; } else { wTXAllocation += ptrTemp; } } // Calculate new bufferRxStart pointer ptrTemp = MyTCBStub.bufferTxStart + wTXAllocation + 1; // Find the head pointer to use ptrHead = MyTCBStub.rxHead; #if defined(STACK_USE_SSL) if(TCPIsSSL(hTCP)) ptrHead = MyTCBStub.sslRxHead; #endif // If there's out-of-order data pending, adjust the head pointer to compensate if(MyTCB.sHoleSize != -1) { ptrHead += MyTCB.sHoleSize + MyTCB.wFutureDataSize; if(ptrHead > MyTCBStub.bufferEnd) ptrHead -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; } // Determine if resizing will lose any RX data if(MyTCBStub.rxTail < ptrHead) { if(ptrTemp > MyTCBStub.rxTail) { if(vFlags & TCP_ADJUST_PRESERVE_RX) return FALSE; else { MyTCBStub.rxTail = ptrTemp; MyTCBStub.rxHead = ptrTemp; #if defined(STACK_USE_SSL) MyTCBStub.sslRxHead = ptrTemp; #endif } } } else if(MyTCBStub.rxTail > ptrHead) { if(ptrTemp > MyTCBStub.bufferRxStart) { if(vFlags & TCP_ADJUST_PRESERVE_RX) return FALSE; else { MyTCBStub.rxTail = ptrTemp; MyTCBStub.rxHead = ptrTemp; #if defined(STACK_USE_SSL) MyTCBStub.sslRxHead = ptrTemp; #endif } } } else { // No data to preserve, but we may need to move // the pointers to stay in the RX space MyTCBStub.rxTail = ptrTemp; MyTCBStub.rxHead = ptrTemp; #if defined(STACK_USE_SSL) MyTCBStub.sslRxHead = ptrTemp; #endif } // If we need to preserve data that wrapped in the ring, we must copy if(ptrHead < MyTCBStub.rxTail && (vFlags & TCP_ADJUST_PRESERVE_RX)) { TCPRAMCopy(ptrTemp, MyTCBStub.vMemoryMedium, MyTCBStub.bufferRxStart, MyTCBStub.vMemoryMedium, ptrHead - MyTCBStub.bufferRxStart); // Move the pointers if they were in front of the tail #if defined(STACK_USE_SSL) if(TCPIsSSL(hTCP) && MyTCBStub.sslRxHead < MyTCBStub.rxTail) MyTCBStub.sslRxHead -= MyTCBStub.bufferRxStart - ptrTemp; #endif if(MyTCBStub.rxHead < MyTCBStub.rxTail) MyTCBStub.rxHead -= MyTCBStub.bufferRxStart - ptrTemp; } // Move the RX buffer pointer - it's the one that divides the two MyTCBStub.bufferRxStart = ptrTemp; // Empty the TX buffer MyTCB.txUnackedTail = MyTCBStub.bufferTxStart; MyTCBStub.txTail = MyTCBStub.bufferTxStart; MyTCBStub.txHead = MyTCBStub.bufferTxStart; #if defined(STACK_USE_SSL) if(TCPIsSSL(hTCP)) MyTCBStub.sslTxHead = MyTCBStub.txHead + 5; #endif // Send a window update to notify remote node of change if(MyTCBStub.smState == TCP_ESTABLISHED) SendTCP(ACK, SENDTCP_RESET_TIMERS); return TRUE; } /***************************************************************************** Function: static void TCPRAMCopy(PTR_BASE ptrDest, BYTE vDestType, PTR_BASE ptrSource, BYTE vSourceType, WORD wLength) Summary: Copies data to/from various memory mediums. Description: This function copies data between memory mediums (PIC RAM, SPI RAM, and Ethernet buffer RAM). Precondition: TCP is initialized. Parameters: ptrDest - Address to write to vDestType - Destination meidum (TCP_PIC_RAM, TCP_ETH_RAM, TCP_SPI_RAM) ptrSource - Address to copy from vSourceType - Source medium (TCP_PIC_RAM, TCP_ETH_RAM, or TCP_SPI_RAM) wLength - Number of bytes to copy Returns: None Remarks: Copying to a destination region that overlaps with the source address is supported only if the destination start address is at a lower memory address (closer to 0x0000) than the source pointer. However, if they do overlap there must be at least 4 bytes of non-overlap to ensure correct results due to hardware DMA requirements. ***************************************************************************/ static void TCPRAMCopy(PTR_BASE ptrDest, BYTE vDestType, PTR_BASE ptrSource, BYTE vSourceType, WORD wLength) { #if defined(SPIRAM_CS_TRIS) BYTE vBuffer[16]; WORD w; #endif switch(vSourceType) { case TCP_PIC_RAM: switch(vDestType) { case TCP_PIC_RAM: memcpy((void*)(BYTE*)ptrDest, (void*)(BYTE*)ptrSource, wLength); break; case TCP_ETH_RAM: if(!((WORD_VAL*)&ptrDest)->bits.b15) MACSetWritePtr((WORD)ptrDest); MACPutArray((BYTE*)ptrSource, wLength); break; #if defined(SPIRAM_CS_TRIS) case TCP_SPI_RAM: SPIRAMPutArray(ptrDest, (BYTE*)ptrSource, wLength); break; #endif } break; case TCP_ETH_RAM: switch(vDestType) { case TCP_PIC_RAM: if(!((WORD_VAL*)&ptrSource)->bits.b15) MACSetReadPtr(ptrSource); MACGetArray((BYTE*)ptrDest, wLength); break; case TCP_ETH_RAM: MACMemCopyAsync(ptrDest, ptrSource, wLength); while(!MACIsMemCopyDone()); break; #if defined(SPIRAM_CS_TRIS) case TCP_SPI_RAM: if(!((WORD_VAL*)&ptrSource)->bits.b15) MACSetReadPtr(ptrSource); w = sizeof(vBuffer); while(wLength) { if(w > wLength) w = wLength; // Read and write a chunk MACGetArray(vBuffer, w); SPIRAMPutArray(ptrDest, vBuffer, w); ptrDest += w; wLength -= w; } break; #endif } break; #if defined(SPIRAM_CS_TRIS) case TCP_SPI_RAM: switch(vDestType) { case TCP_PIC_RAM: SPIRAMGetArray(ptrSource, (BYTE*)ptrDest, wLength); break; case TCP_ETH_RAM: if(!((WORD_VAL*)&ptrDest)->bits.b15) MACSetWritePtr(ptrDest); w = sizeof(vBuffer); while(wLength) { if(w > wLength) w = wLength; // Read and write a chunk SPIRAMGetArray(ptrSource, vBuffer, w); ptrSource += w; MACPutArray(vBuffer, w); wLength -= w; } break; case TCP_SPI_RAM: // Copy all of the data over in chunks w = sizeof(vBuffer); while(wLength) { if(w > wLength) w = wLength; SPIRAMGetArray(ptrSource, vBuffer, w); SPIRAMPutArray(ptrDest, vBuffer, w); ptrSource += w; ptrDest += w; wLength -= w; } break; } break; #endif } } /***************************************************************************** Function: static void TCPRAMCopyROM(PTR_BASE wDest, BYTE wDestType, ROM BYTE* wSource, WORD wLength) Summary: Copies data to/from various memory mediums. Description: This function copies data between memory mediums (PIC RAM, SPI RAM, and Ethernet buffer RAM). This function is to be used when copying from ROM. Precondition: TCP is initialized. Parameters: wDest - Address to write to wDestType - Destination meidum (TCP_PIC_RAM, TCP_ETH_RAM, TCP_SPI_RAM) wSource - Address to copy from wLength - Number of bytes to copy Returns: None Remarks: Copying to a destination region that overlaps with the source address is supported only if the destination start address is at a lower memory address (closer to 0x0000) than the source pointer. This function is aliased to TCPRAMCopy on non-PIC18 platforms. ***************************************************************************/ #if defined(__18CXX) static void TCPRAMCopyROM(PTR_BASE wDest, BYTE wDestType, ROM BYTE* wSource, WORD wLength) { BYTE vBuffer[16]; WORD w; switch(wDestType) { case TCP_PIC_RAM: memcpypgm2ram((void*)(BYTE*)wDest, (ROM void*)wSource, wLength); break; case TCP_ETH_RAM: if(!((WORD_VAL*)&wDest)->bits.b15) MACSetWritePtr(wDest); w = sizeof(vBuffer); while(wLength) { if(w > wLength) w = wLength; // Read and write a chunk memcpypgm2ram(vBuffer, (ROM void*)wSource, w); MACPutArray(vBuffer, w); wSource += w; wLength -= w; } break; #if defined(SPIRAM_CS_TRIS) case TCP_SPI_RAM: w = sizeof(vBuffer); while(wLength) { if(w > wLength) w = wLength; // Read and write a chunk memcpypgm2ram(vBuffer, (ROM void*)wSource, w); SPIRAMPutArray(wDest, vBuffer, w); wDest += w; wSource += w; wLength -= w; } break; #endif } } #endif /**************************************************************************** Section: SSL Functions ***************************************************************************/ /***************************************************************************** Function: BOOL TCPStartSSLClient(TCP_SOCKET hTCP, BYTE* host) Summary: Begins an SSL client session. Description: This function escalates the current connection to an SSL secured connection by initiating an SSL client handshake. Precondition: TCP is initialized and hTCP is already connected. Parameters: hTCP - TCP connection to secure host - Expected host name on certificate (currently ignored) Return Values: TRUE - an SSL connection was initiated FALSE - Insufficient SSL resources (stubs) were available Remarks: The host parameter is currently ignored and is not validated. ***************************************************************************/ #if defined(STACK_USE_SSL_CLIENT) BOOL TCPStartSSLClient(TCP_SOCKET hTCP, BYTE* host) { BYTE i; SyncTCBStub(hTCP); // Make sure SSL is not established already if(MyTCBStub.sslStubID != SSL_INVALID_ID) return FALSE; // Try to start the session MyTCBStub.sslStubID = SSLStartSession(hTCP); // Make sure a session stub was obtained if(MyTCBStub.sslStubID == SSL_INVALID_ID) return FALSE; // Mark connection as handshaking and return MyTCBStub.sslReqMessage = SSL_CLIENT_HELLO; MyTCBStub.sslRxHead = MyTCBStub.rxHead; MyTCBStub.sslTxHead = MyTCBStub.txHead; MyTCBStub.Flags.bSSLHandshaking = 1; for(i = 0; i < 5u; i++) {// Skip first 5 bytes in TX for the record header if(++MyTCBStub.sslTxHead >= MyTCBStub.bufferRxStart) MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } return TRUE; } #endif // SSL Client /***************************************************************************** Function: BOOL TCPStartSSLServer(TCP_SOCKET hTCP) Summary: Begins an SSL server session. Description: This function sets up an SSL server session when a new connection is established on an SSL port. Precondition: TCP is initialized and hTCP is already connected. Parameters: hTCP - TCP connection to secure Return Values: TRUE - an SSL connection was initiated FALSE - Insufficient SSL resources (stubs) were available ***************************************************************************/ #if defined(STACK_USE_SSL_SERVER) BOOL TCPStartSSLServer(TCP_SOCKET hTCP) { BYTE i; SyncTCBStub(hTCP); SyncTCB(); // Make sure SSL is not established already if(MyTCBStub.sslStubID != SSL_INVALID_ID) return TRUE; // Try to start the session MyTCBStub.sslStubID = SSLStartSession(hTCP); // Make sure a session stub was obtained if(MyTCBStub.sslStubID == SSL_INVALID_ID) return FALSE; // Swap the localPort and localSSLPort MyTCBStub.remoteHash.Val = MyTCB.localPort.Val; MyTCB.localPort.Val = MyTCB.localSSLPort.Val; MyTCB.localSSLPort.Val = MyTCBStub.remoteHash.Val; // Mark connection as handshaking and return MyTCBStub.sslReqMessage = SSL_NO_MESSAGE; MyTCBStub.sslRxHead = MyTCBStub.rxHead; MyTCBStub.sslTxHead = MyTCBStub.txHead; MyTCBStub.Flags.bSSLHandshaking = 1; for(i = 0; i < 5u; i++) {// Skip first 5 bytes in TX for the record header if(++MyTCBStub.sslTxHead >= MyTCBStub.bufferRxStart) MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } return TRUE; } #endif // SSL Client /***************************************************************************** Function: BOOL TCPAddSSLListener(TCP_SOCKET hTCP, WORD port) Summary: Listens for SSL connection on a specific port. Description: This function adds an additional listening port to a TCP connection. Connections made on this alternate port will be secured via SSL. Precondition: TCP is initialized and hTCP is listening. Parameters: hTCP - TCP connection to secure port - SSL port to listen on Return Values: TRUE - SSL port was added. FALSE - The socket was not a listening socket. ***************************************************************************/ #if defined(STACK_USE_SSL_SERVER) BOOL TCPAddSSLListener(TCP_SOCKET hTCP, WORD port) { SyncTCBStub(hTCP); if(MyTCBStub.smState != TCP_LISTEN) return FALSE; SyncTCB(); MyTCB.localSSLPort.Val = port; MyTCBStub.sslTxHead = port; return TRUE; } #endif // SSL Server /***************************************************************************** Function: BOOL TCPRequestSSLMessage(TCP_SOCKET hTCP, BYTE msg) Summary: Requests an SSL message to be transmitted. Description: This function is called to request that a specific SSL message be transmitted. This message should only be called by the SSL module. Precondition: TCP is initialized. Parameters: hTCP - TCP connection to use msg - One of the SSL_MESSAGE types to transmit. Return Values: TRUE - The message was requested. FALSE - Another message is already pending transmission. ***************************************************************************/ #if defined(STACK_USE_SSL) BOOL TCPRequestSSLMessage(TCP_SOCKET hTCP, BYTE msg) { SyncTCBStub(hTCP); if(msg == SSL_NO_MESSAGE || MyTCBStub.sslReqMessage == SSL_NO_MESSAGE) { MyTCBStub.sslReqMessage = msg; return TRUE; } return FALSE; } #endif // SSL /***************************************************************************** Function: BOOL TCPSSLIsHandshaking(TCP_SOCKET hTCP) Summary: Determines if an SSL session is still handshaking. Description: Call this function after calling TCPStartSSLClient until FALSE is returned. Then your application may continue with its normal data transfer (which is now secured). Precondition: TCP is initialized and hTCP is connected. Parameters: hTCP - TCP connection to check Return Values: TRUE - SSL handshake is still progressing FALSE - SSL handshake has completed ***************************************************************************/ #if defined(STACK_USE_SSL) BOOL TCPSSLIsHandshaking(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); return MyTCBStub.Flags.bSSLHandshaking; } #endif // SSL /***************************************************************************** Function: BOOL TCPIsSSL(TCP_SOCKET hTCP) Summary: Determines if a TCP connection is secured with SSL. Description: Call this function to determine whether or not a TCP connection is secured with SSL. Precondition: TCP is initialized and hTCP is connected. Parameters: hTCP - TCP connection to check Return Values: TRUE - Connection is secured via SSL FALSE - Connection is not secured ***************************************************************************/ #if defined(STACK_USE_SSL) BOOL TCPIsSSL(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); if(MyTCBStub.sslStubID == SSL_INVALID_ID) return FALSE; return TRUE; } #endif // SSL /***************************************************************************** Function: void TCPSSLHandshakeComplete(TCP_SOCKET hTCP) Summary: Clears the SSL handshake flag. Description: This function clears the flag indicating that an SSL handshake is complete. Precondition: TCP is initialized and hTCP is connected. Parameters: hTCP - TCP connection to set Returns: None Remarks: This function should never be called by an application. It is used only by the SSL module itself. ***************************************************************************/ #if defined(STACK_USE_SSL) void TCPSSLHandshakeComplete(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); MyTCBStub.Flags.bSSLHandshaking = 0; } #endif // SSL /***************************************************************************** Function: void TCPSSLDecryptMAC(TCP_SOCKET hTCP, ARCFOUR_CTX* ctx, WORD len) Summary: Decrypts and MACs data arriving via SSL. Description: This function decrypts data in the TCP buffer and calculates the MAC over the data. All data is left in the exact same location in the TCP buffer. It is called to help process incoming SSL records. Precondition: TCP is initialized, hTCP is connected, and ctx's Sbox is loaded. Parameters: hTCP - TCP connection to decrypt in ctx - ARCFOUR encryption context to use len - Number of bytes to crypt inPlace - TRUE to write back in place, FALSE to write at end of currently visible data. Returns: None Remarks: This function should never be called by an application. It is used only by the SSL module itself. ***************************************************************************/ #if defined(STACK_USE_SSL) void TCPSSLDecryptMAC(TCP_SOCKET hTCP, ARCFOUR_CTX* ctx, WORD len) { PTR_BASE wSrc, wDest, wBlockLen, wTemp; BYTE buffer[32]; // Set up the pointers SyncTCBStub(hTCP); wSrc = MyTCBStub.rxTail; wDest = wSrc; // Handle 32 bytes at a time while(len) { // Determine how many bytes we can read wBlockLen = sizeof(buffer); if(wBlockLen > len) // Don't do more than we should wBlockLen = len; // Read those bytes to a buffer if(wSrc + wBlockLen > MyTCBStub.bufferEnd) {// Two part read wTemp = MyTCBStub.bufferEnd - wSrc + 1; TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, wSrc, MyTCBStub.vMemoryMedium, wTemp); TCPRAMCopy((PTR_BASE)buffer+wTemp, TCP_PIC_RAM, MyTCBStub.bufferRxStart, MyTCBStub.vMemoryMedium, wBlockLen - wTemp); wSrc = MyTCBStub.bufferRxStart + wBlockLen - wTemp; } else { TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, wSrc, MyTCBStub.vMemoryMedium, wBlockLen); wSrc += wBlockLen; } // Decrypt and hash ARCFOURCrypt(ctx, buffer, wBlockLen); SSLMACAdd(buffer, wBlockLen); // Write decrypted bytes back if(wDest + wBlockLen > MyTCBStub.bufferEnd) {// Two part write wTemp = MyTCBStub.bufferEnd - wDest + 1; TCPRAMCopy(wDest, MyTCBStub.vMemoryMedium, (PTR_BASE)buffer, TCP_PIC_RAM, wTemp); TCPRAMCopy(MyTCBStub.bufferRxStart, MyTCBStub.vMemoryMedium, (PTR_BASE)buffer+wTemp, TCP_PIC_RAM, wBlockLen - wTemp); wDest = MyTCBStub.bufferRxStart + wBlockLen - wTemp; } else { TCPRAMCopy(wDest, MyTCBStub.vMemoryMedium, (PTR_BASE)buffer, TCP_PIC_RAM, wBlockLen); wDest += wBlockLen; } // Update the length remaining len -= wBlockLen; } } #endif // SSL /***************************************************************************** Function: void TCPSSLInPlaceMACEncrypt(TCP_SOCKET hTCP, ARCFOUR_CTX* ctx, BYTE* MACSecret, WORD len) Summary: Encrypts and MACs data in place in the TCP TX buffer. Description: This function encrypts data in the TCP buffer while calcuating a MAC. When encryption is finished, the MAC is appended to the buffer and the record will be ready to transmit. Precondition: TCP is initialized, hTCP is connected, and ctx's Sbox is loaded. Parameters: hTCP - TCP connection to encrypt in ctx - ARCFOUR encryption context to use MACSecret - MAC encryption secret to use len - Number of bytes to crypt Returns: None Remarks: This function should never be called by an application. It is used only by the SSL module itself. ***************************************************************************/ #if defined(STACK_USE_SSL) void TCPSSLInPlaceMACEncrypt(TCP_SOCKET hTCP, ARCFOUR_CTX* ctx, BYTE* MACSecret, WORD len) { PTR_BASE pos; WORD blockLen; BYTE buffer[32]; // Set up the pointers SyncTCBStub(hTCP); pos = MyTCBStub.txHead; for(blockLen = 0; blockLen < 5u; blockLen++) {// Skips first 5 bytes for the header if(++pos >= MyTCBStub.bufferRxStart) pos = MyTCBStub.bufferTxStart; } // Handle 32 bytes at a time while(len) { // Determine how many bytes we can read blockLen = sizeof(buffer); if(blockLen > len) // Don't do more than we should blockLen = len; if(blockLen > MyTCBStub.bufferRxStart - pos) // Don't pass the end blockLen = MyTCBStub.bufferRxStart - pos; // Read those bytes to a buffer TCPRAMCopy((PTR_BASE)buffer, TCP_PIC_RAM, pos, MyTCBStub.vMemoryMedium, blockLen); // Hash and encrypt SSLMACAdd(buffer, blockLen); ARCFOURCrypt(ctx, buffer, blockLen); // Put them back TCPRAMCopy(pos, MyTCBStub.vMemoryMedium, (PTR_BASE)buffer, TCP_PIC_RAM, blockLen); // Update the pointers pos += blockLen; len -= blockLen; if(pos >= MyTCBStub.bufferRxStart) pos = MyTCBStub.bufferTxStart; } // Calculate and add the MAC SSLMACCalc(MACSecret, buffer); ARCFOURCrypt(ctx, buffer, 16); // Write the MAC to the TX FIFO // Can't use TCPPutArray here because TCPIsPutReady() saves 16 bytes for the MAC // TCPPut* functions use this to prevent writing too much data. Therefore, the // functionality is duplicated here. len = 16; blockLen = 0; // See if we need a two part put if(MyTCBStub.sslTxHead + len >= MyTCBStub.bufferRxStart) { blockLen = MyTCBStub.bufferRxStart-MyTCBStub.sslTxHead; TCPRAMCopy(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)buffer, TCP_PIC_RAM, blockLen); len -= blockLen; MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } TCPRAMCopy(MyTCBStub.sslTxHead, MyTCBStub.vMemoryMedium, (PTR_BASE)&buffer[blockLen], TCP_PIC_RAM, len); MyTCBStub.sslTxHead += len; } #endif // SSL /***************************************************************************** Function: void TCPSSLPutRecordHeader(TCP_SOCKET hTCP, BYTE* hdr, BOOL recDone) Summary: Writes an SSL record header and sends an SSL record. Description: This function writes an SSL record header to the pending TCP SSL data, then indicates that the data is ready to be sent by moving the txHead pointer. If the record is complete, set recDone to TRUE. The sslTxHead pointer will be moved forward 5 bytes to leave space for a future record header. If the record is only partially sent, use FALSE and to leave the pointer where it is so that more data can be added to the record. Partial records can only be used for the SERVER_CERTIFICATE handshake message. Precondition: TCP is initialized, and hTCP is connected with an active SSL session. Parameters: hTCP - TCP connection to write the header and transmit with hdr - Record header (5 bytes) to send or NULL to just move the pointerctx recDone - TRUE if the record is done, FALSE otherwise Returns: None Remarks: This function should never be called by an application. It is used only by the SSL module itself. ***************************************************************************/ #if defined(STACK_USE_SSL) void TCPSSLPutRecordHeader(TCP_SOCKET hTCP, BYTE* hdr, BOOL recDone) { BYTE i; // Set up the pointers SyncTCBStub(hTCP); // Write the header if needed if(hdr) {// This is a new record, so insert the header for(i = 0; i < 5u; i++) { TCPRAMCopy(MyTCBStub.txHead, MyTCBStub.vMemoryMedium, (PTR_BASE)hdr+i, TCP_PIC_RAM, sizeof(BYTE)); if(++MyTCBStub.txHead >= MyTCBStub.bufferRxStart) MyTCBStub.txHead = MyTCBStub.bufferTxStart; } } // Move the txHead pointer to indicate what data is ready // Also, flush just the header, then all the data. This shotguns two // packets down the line, therefore causing immediate ACKs by the // remote node. Reconnect handshakes are as much as 60% faster now. TCPFlush(hTCP); MyTCBStub.txHead = MyTCBStub.sslTxHead; TCPFlush(hTCP); // If this record is done, move the sslTxHead forward // to accomodate the next record header if(recDone) { for(i = 0; i < 5u; i++) {// Skip first 5 bytes in TX for the record header if(++MyTCBStub.sslTxHead >= MyTCBStub.bufferRxStart) MyTCBStub.sslTxHead = MyTCBStub.bufferTxStart; } } } #endif // SSL /***************************************************************************** Function: WORD TCPSSLGetPendingTxSize(TCP_SOCKET hTCP) Summary: Determines how many bytes are pending for a future SSL record. Description: This function determines how many bytes are pending for a future SSL record. Precondition: TCP is initialized, and hTCP is connected with an active SSL connection. Parameters: hTCP - TCP connection to check Returns: None ***************************************************************************/ #if defined(STACK_USE_SSL) WORD TCPSSLGetPendingTxSize(TCP_SOCKET hTCP) { SyncTCBStub(hTCP); // Non-SSL connections have no pending SSL data //if(MyTCBStub.sslStubID == SSL_INVALID_ID) // return 0; // Determine how many bytes are waiting to be written in this record if(MyTCBStub.sslTxHead > MyTCBStub.txHead) return MyTCBStub.sslTxHead - MyTCBStub.txHead - 5; else return (MyTCBStub.bufferRxStart - MyTCBStub.bufferTxStart - 1) - (MyTCBStub.txHead - MyTCBStub.sslTxHead - 1) - 5; } #endif /***************************************************************************** Function: void TCPSSLHandleIncoming(TCP_SOCKET hTCP) Summary: Hands newly arrive TCP data to the SSL module for processing. Description: This function processes incoming TCP data as an SSL record and performs any necessary repositioning and decrypting. Precondition: TCP is initialized, and hTCP is connected with an active SSL session. Parameters: hTCP - TCP connection to handle incoming data on Returns: None Remarks: This function should never be called by an application. It is used only by the SSL module itself. ***************************************************************************/ #if defined(STACK_USE_SSL) void TCPSSLHandleIncoming(TCP_SOCKET hTCP) { PTR_BASE prevRxTail, nextRxHead, startRxTail, wSrc, wDest; WORD wToMove, wLen, wSSLBytesThatPoofed, wDecryptedBytes; // Sync the stub SyncTCBStub(hTCP); // If new data is waiting if(MyTCBStub.sslRxHead != MyTCBStub.rxHead) { // Reconfigure pointers for SSL use prevRxTail = MyTCBStub.rxTail; nextRxHead = MyTCBStub.rxHead; MyTCBStub.rxTail = MyTCBStub.rxHead; MyTCBStub.rxHead = MyTCBStub.sslRxHead; do { startRxTail = MyTCBStub.rxTail; // Handle incoming data. This function performs deframing of the // SSL records, decryption, and MAC verification. wSSLBytesThatPoofed = TCPIsGetReady(hTCP); wDecryptedBytes = SSLRxRecord(hTCP, MyTCBStub.sslStubID); wSSLBytesThatPoofed -= TCPIsGetReady(hTCP); // Now need to move data to fill the SSL header/MAC/padding hole, // if there is one if(wSSLBytesThatPoofed) { // Sync the TCP so we can see if there is a TCP hole SyncTCB(); // Calculate how big the SSL hole is if(MyTCB.sHoleSize == -1) {// Just need to move pending SSL data wToMove = TCPIsGetReady(hTCP); } else {// A TCP hole exists, so move all data wToMove = TCPIsGetReady(hTCP) + MyTCB.sHoleSize + MyTCB.wFutureDataSize; } // Start with the destination as the startRxTail and source as current rxTail wDest = startRxTail; wSrc = MyTCBStub.rxTail; // If data exists between the end of the buffer and // the destination, then move it forward if(wSrc > wDest) { wLen = MyTCBStub.bufferEnd - wSrc + 1; if(wLen > wToMove) wLen = wToMove; TCPRAMCopy(wDest, MyTCBStub.vMemoryMedium, wSrc, MyTCBStub.vMemoryMedium, wLen); wDest += wLen; wSrc = MyTCBStub.bufferRxStart; wToMove -= wLen; } // If data remains to be moved, fill in to end of buffer if(wToMove) { wLen = MyTCBStub.bufferEnd - wDest + 1; if(wLen > wToMove) wLen = wToMove; TCPRAMCopy(wDest, MyTCBStub.vMemoryMedium, wSrc, MyTCBStub.vMemoryMedium, wLen); wDest = MyTCBStub.bufferRxStart; wSrc += wLen; wToMove -= wLen; } // If data still remains, copy from from front + len to front if(wToMove) { TCPRAMCopy(wDest, MyTCBStub.vMemoryMedium, wSrc, MyTCBStub.vMemoryMedium, wToMove); } // Since bytes poofed, we need to move the head pointers // backwards by an equal amount. MyTCBStub.rxHead -= wSSLBytesThatPoofed; if(MyTCBStub.rxHead < MyTCBStub.bufferRxStart) MyTCBStub.rxHead += MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; MyTCBStub.sslRxHead = MyTCBStub.rxHead; } // Move tail pointer forward by the number of decrypted bytes ready // for the application (but not poofed bytes) MyTCBStub.rxTail = startRxTail + wDecryptedBytes; if(MyTCBStub.rxTail > MyTCBStub.bufferEnd) MyTCBStub.rxTail -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; nextRxHead += wDecryptedBytes; // Loop until SSLRxRecord() runs out of data and stops doing // anything } while(wSSLBytesThatPoofed || (startRxTail != MyTCBStub.rxTail)); // Restore TCP buffer pointers to point to the decrypted application data // only if(nextRxHead > MyTCBStub.bufferEnd) nextRxHead -= MyTCBStub.bufferEnd - MyTCBStub.bufferRxStart + 1; MyTCBStub.rxTail = prevRxTail; MyTCBStub.rxHead = nextRxHead; } } #endif #endif //#if defined(STACK_USE_TCP)
31.636224
304
0.64639
3200d28b6f941a265a311ffa5f774a1335592d42
5,223
h
C
include/gf/Spatial_RStarTree.h
jylm6d/gf
33151311479f3e067c7525f29e4a4948ec4230c4
[ "Zlib" ]
191
2016-07-19T07:54:06.000Z
2022-03-26T16:49:20.000Z
include/gf/Spatial_RStarTree.h
jylm6d/gf
33151311479f3e067c7525f29e4a4948ec4230c4
[ "Zlib" ]
46
2016-07-19T08:23:51.000Z
2021-06-19T20:52:27.000Z
include/gf/Spatial_RStarTree.h
jylm6d/gf
33151311479f3e067c7525f29e4a4948ec4230c4
[ "Zlib" ]
46
2016-07-19T08:04:41.000Z
2021-09-28T17:18:37.000Z
/* * Gamedev Framework (gf) * Copyright (C) 2016-2021 Julien Bernard * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef GF_SPATIAL_R_STAR_TREE_H #define GF_SPATIAL_R_STAR_TREE_H #include <cassert> #include <vector> #include <boost/container/static_vector.hpp> #include "BlockAllocator.h" #include "CoreApi.h" #include "Handle.h" #include "Rect.h" #include "SpatialTypes.h" namespace gf { #ifndef DOXYGEN_SHOULD_SKIP_THIS inline namespace v1 { #endif /** * @ingroup core_spatial * @brief An implemntation of a R* tree * * More precisely, this class implements the [Revised R* tree](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.367.7273&rep=rep1&type=pdf). * * @sa gf::QuadTree * @sa [R* tree - Wikipedia](https://en.wikipedia.org/wiki/R*_tree) */ class GF_CORE_API RStarTree { public: static constexpr std::size_t MaxSize = 16; static constexpr std::size_t MinSize = 4; /** * @brief Constructor */ RStarTree(); /** * @brief Insert an object in the tree * * @param handle A handle that represents the object to insert * @param bounds The bounds of the object * @returns A spatial id */ SpatialId insert(Handle handle, const RectF& bounds); /** * @brief Modify the bounds of an object * * @param id The spatial id of the object * @param bounds The new bounds of the object */ void modify(SpatialId id, RectF bounds); /** * @brief Query objects in the tree * * @param bounds The bounds of the query * @param callback The callback to apply to found objects * @param kind The kind of spatial query * @returns The number of objects found */ std::size_t query(const RectF& bounds, SpatialQueryCallback callback, SpatialQuery kind = SpatialQuery::Intersect); /** * @brief Remove an object from the tree * * @param id The spatial id of the object */ void remove(SpatialId id); /** * @brief Remove all the objects from the tree */ void clear(); /** * @brief Get the handle associated to a spatial id * * @param id The spatial id of the object */ Handle operator[](SpatialId id); private: std::size_t allocateEntry(); void disposeEntry(std::size_t index); std::size_t allocateNode(); void disposeNode(std::size_t index); RectF computeBounds(std::size_t nodeIndex); void updateBoundsForChild(std::size_t parentIndex, const RectF& bounds, std::size_t childIndex); void doInsert(std::size_t entryIndex, const RectF& bounds); std::size_t chooseSubtree(std::size_t nodeIndex, const RectF& bounds); std::size_t chooseNode(std::size_t nodeIndex, const RectF& bounds); std::size_t searchForCoveringNode(std::size_t nodeIndex, const RectF& bounds); bool existsEmptyVolumeExtension(std::size_t nodeIndex, const RectF& bounds); struct Candidate { std::size_t index; float overlap; bool isCandidate; }; template<typename OverlapEnlargement> std::size_t findCandidates(std::size_t nodeIndex, std::size_t t, std::size_t p, const RectF& bounds, std::vector<Candidate>& candidates); std::size_t doInsertInLeaf(std::size_t nodeIndex, std::size_t entryIndex, const RectF& entryBounds); std::size_t doInsertInBranch(std::size_t nodeIndex, std::size_t childIndex, const RectF& childBounds); std::size_t doQuery(std::size_t nodeIndex, const RectF& bounds, SpatialQueryCallback callback, SpatialQuery kind); void getEntriesAndDispose(std::size_t nodeIndex, std::vector<std::size_t>& eliminated); void doRemove(std::size_t entryIndex); void validate() const; std::size_t validateNode(std::size_t nodeIndex) const; private: static constexpr std::size_t Size = MaxSize + 1; struct Entry { Handle handle; RectF bounds; std::size_t node; }; BlockAllocator<Entry> m_entries; struct Member { RectF bounds; std::size_t index; }; struct Node { enum NodeType { Branch, Leaf, }; RectF bounds; std::size_t parent; NodeType type; boost::container::static_vector<Member, Size> members; }; BlockAllocator<Node> m_nodes; std::size_t m_root; }; #ifndef DOXYGEN_SHOULD_SKIP_THIS } #endif } #endif // GF_SPATIAL_R_STAR_TREE_H
29.016667
150
0.68409
5cdb4a69d277c49e04a1967cec9ea9e713f0e3ad
3,078
c
C
net/ipv6/netfilter/ip6t_SYNPROXY.c
xqdzn/linux-bpi-p2z-dev
fc302d86fb16fff3a25894efd3d5dd9e8e379a82
[ "MIT" ]
null
null
null
net/ipv6/netfilter/ip6t_SYNPROXY.c
xqdzn/linux-bpi-p2z-dev
fc302d86fb16fff3a25894efd3d5dd9e8e379a82
[ "MIT" ]
null
null
null
net/ipv6/netfilter/ip6t_SYNPROXY.c
xqdzn/linux-bpi-p2z-dev
fc302d86fb16fff3a25894efd3d5dd9e8e379a82
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2013 Patrick McHardy <kaber@trash.net> */ #include <linux/netfilter_ipv6/ip6_tables.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_SYNPROXY.h> #include <net/netfilter/nf_synproxy.h> static unsigned int synproxy_tg6(struct sk_buff *skb, const struct xt_action_param *par) { const struct xt_synproxy_info *info = par->targinfo; struct net *net = xt_net(par); struct synproxy_net *snet = synproxy_pernet(net); struct synproxy_options opts = {}; struct tcphdr *th, _th; if (nf_ip6_checksum(skb, xt_hooknum(par), par->thoff, IPPROTO_TCP)) return NF_DROP; th = skb_header_pointer(skb, par->thoff, sizeof(_th), &_th); if (th == NULL) return NF_DROP; if (!synproxy_parse_options(skb, par->thoff, th, &opts)) return NF_DROP; if (th->syn && !(th->ack || th->fin || th->rst)) { /* Initial SYN from client */ this_cpu_inc(snet->stats->syn_received); if (th->ece && th->cwr) opts.options |= XT_SYNPROXY_OPT_ECN; opts.options &= info->options; opts.mss_encode = opts.mss; opts.mss = info->mss; if (opts.options & XT_SYNPROXY_OPT_TIMESTAMP) synproxy_init_timestamp_cookie(info, &opts); else opts.options &= ~(XT_SYNPROXY_OPT_WSCALE | XT_SYNPROXY_OPT_SACK_PERM | XT_SYNPROXY_OPT_ECN); synproxy_send_client_synack_ipv6(net, skb, th, &opts); consume_skb(skb); return NF_STOLEN; } else if (th->ack && !(th->fin || th->rst || th->syn)) { /* ACK from client */ if (synproxy_recv_client_ack_ipv6(net, skb, th, &opts, ntohl(th->seq))) { consume_skb(skb); return NF_STOLEN; } else { return NF_DROP; } } return XT_CONTINUE; } static int synproxy_tg6_check(const struct xt_tgchk_param *par) { struct synproxy_net *snet = synproxy_pernet(par->net); const struct ip6t_entry *e = par->entryinfo; int err; if (!(e->ipv6.flags & IP6T_F_PROTO) || e->ipv6.proto != IPPROTO_TCP || e->ipv6.invflags & XT_INV_PROTO) return -EINVAL; err = nf_ct_netns_get(par->net, par->family); if (err) return err; err = nf_synproxy_ipv6_init(snet, par->net); if (err) { nf_ct_netns_put(par->net, par->family); return err; } return err; } static void synproxy_tg6_destroy(const struct xt_tgdtor_param *par) { struct synproxy_net *snet = synproxy_pernet(par->net); nf_synproxy_ipv6_fini(snet, par->net); nf_ct_netns_put(par->net, par->family); } static struct xt_target synproxy_tg6_reg __read_mostly = { .name = "SYNPROXY", .family = NFPROTO_IPV6, .hooks = (1 << NF_INET_LOCAL_IN) | (1 << NF_INET_FORWARD), .target = synproxy_tg6, .targetsize = sizeof(struct xt_synproxy_info), .checkentry = synproxy_tg6_check, .destroy = synproxy_tg6_destroy, .me = THIS_MODULE, }; static int __init synproxy_tg6_init(void) { return xt_register_target(&synproxy_tg6_reg); } static void __exit synproxy_tg6_exit(void) { xt_unregister_target(&synproxy_tg6_reg); } module_init(synproxy_tg6_init); module_exit(synproxy_tg6_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
24.822581
68
0.709877
fde47b72d6e0e69d05eaee092d28434b83de25cf
778
h
C
lib/AerisCoreUI.xcframework/tvos-arm64_x86_64-simulator/AerisCoreUI.framework/Headers/AWFSpringAnimation.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
lib/AerisCoreUI.xcframework/tvos-arm64_x86_64-simulator/AerisCoreUI.framework/Headers/AWFSpringAnimation.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
lib/AerisCoreUI.xcframework/tvos-arm64_x86_64-simulator/AerisCoreUI.framework/Headers/AWFSpringAnimation.h
aerisweather/aerisweather-ios
a1d6dcb02b0f4a26edfa1829f4161f21ddc5e5e0
[ "BSD-3-Clause" ]
null
null
null
// // AWFSpringAnimation.h // AerisCoreUI // // Created by Nicholas Shipes on 11/25/15. // Copyright © 2015 AerisWeather, LLC. All rights reserved. // // Internal adapted version of JNWSpringAnimation: https://github.com/jwilling/JNWSpringAnimation // Copyright (c) 2013, Jonathan Willing. All rights reserved. // Licensed under the MIT license <http://opensource.org/licenses/MIT> // #import <QuartzCore/QuartzCore.h> @interface AWFSpringAnimation : CAKeyframeAnimation @property (assign, nonatomic) CGFloat stiffness; @property (assign, nonatomic) CGFloat damping; @property (assign, nonatomic) CGFloat mass; @property (nonatomic, strong) id fromValue; @property (nonatomic, strong) id toValue; @property (readonly, assign, nonatomic) CFTimeInterval duration; @end
31.12
98
0.762211
fdfc700d98dca6b0303210c8987189818968b6bb
680
c
C
shotgun/lib/io.c
tqrg-bot/rubinius
beb0fe3968ea7ff3c09e192605eef066136105c8
[ "BSD-3-Clause" ]
null
null
null
shotgun/lib/io.c
tqrg-bot/rubinius
beb0fe3968ea7ff3c09e192605eef066136105c8
[ "BSD-3-Clause" ]
null
null
null
shotgun/lib/io.c
tqrg-bot/rubinius
beb0fe3968ea7ff3c09e192605eef066136105c8
[ "BSD-3-Clause" ]
null
null
null
#include "shotgun.h" #include "subtend/ffi.h" #include <fcntl.h> #include <unistd.h> void io_initialize(STATE, int fd) { int flags; return; /* FIXME: do some error checking. */ if(!isatty(fd)) { flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); } } OBJECT io_wrap(STATE, OBJECT io, int fd, const char *mode) { io_set_descriptor(io, I2N(fd)); // io_set_descriptor(io, ffi_new_pointer(state, (void*)fdopen(fd, mode))); io_initialize(state, fd); return io; } OBJECT io_new(STATE, int fd, const char *mode) { OBJECT io; io = io_allocate_with_extra(state, 1); io_wrap(state, io, fd, mode); return io; }
20
76
0.648529
65781bc2dfc89943b855ebab9e93982ea764bca6
11,101
h
C
remote/uwp/SampleRemoteApp.h
NPohl-MSFT/MixedReality-HolographicRemoting-Samples
753fec3d7a4beaa996fe38ac4e2de92b8facba8b
[ "Apache-2.0" ]
1
2021-06-15T08:03:54.000Z
2021-06-15T08:03:54.000Z
remote/uwp/SampleRemoteApp.h
NPohl-MSFT/MixedReality-HolographicRemoting-Samples
753fec3d7a4beaa996fe38ac4e2de92b8facba8b
[ "Apache-2.0" ]
null
null
null
remote/uwp/SampleRemoteApp.h
NPohl-MSFT/MixedReality-HolographicRemoting-Samples
753fec3d7a4beaa996fe38ac4e2de92b8facba8b
[ "Apache-2.0" ]
null
null
null
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #pragma once #include <holographic/IRemoteAppHolographic.h> #include <holographic/DeviceResources.h> #include <holographic/SpatialInputHandler.h> #include <holographic/SpatialInputRenderer.h> #include <holographic/Speech.h> #include <holographic/SpinningCubeRenderer.h> #include <content/QRCodeRenderer.h> #include <content/SceneUnderstandingRenderer.h> #include <content/SpatialSurfaceMeshRenderer.h> #include <memory> #include <winrt/Microsoft.Holographic.AppRemoting.h> #define INITIAL_WINDOW_WIDTH 1280 #define INITIAL_WINDOW_HEIGHT 720 #define TITLE_TEXT L"SampleRemoteHolographic" #define TITLE_SEPARATOR L" | " #define TITLE_CONNECT_TEXT L"Press Space To Connect" #define TITLE_DISCONNECT_TEXT L"Press D to Disconnect" #define TITLE_ENABLE_PREVIEW_TEXT L"Preview Disabled (press P to enable)" #define TITLE_DISABLE_PREVIEW_TEXT L"Preview Enabled (press P to disable)" // #define ENABLE_CUSTOM_DATA_CHANNEL_SAMPLE class SampleRemoteApp : public std::enable_shared_from_this<SampleRemoteApp>, public IRemoteAppHolographic, public Speech::IRemoteSpeechReceiver, public DXHelper::IDeviceNotify { public: struct Options { std::wstring hostname; uint16_t port = 0; uint16_t transportPort = 0; bool ephemeralPort = false; bool showPreview = true; bool listen = false; bool autoReconnect = true; }; public: SampleRemoteApp(); ~SampleRemoteApp(); // IRemoteAppHolographic methods virtual void SetWindow(RemoteWindowHolographic* window) override; virtual void Tick() override; virtual void OnKeyPress(char key) override; virtual void OnResize(int width, int height) override; virtual void ParseLaunchArguments(std::wstring_view arguments) override; // IRemoteSpeechReceiver methods // Responds to speech recognition results. virtual void OnRecognizedSpeech(const winrt::hstring& recognizedText) override; // SampleRemoteApp methods // Creates a HolographicFrame and updates the content. winrt::Windows::Graphics::Holographic::HolographicFrame Update(); // Renders the current frame to each holographic camera and presents it. void Render(winrt::Windows::Graphics::Holographic::HolographicFrame holographicFrame); const std::shared_ptr<DXHelper::DeviceResources>& GetDeviceResources() { return m_deviceResources; } // Initialize SampleRemoteApp for remote rendering targeting a HolographicRemotingPlayer. void ConfigureRemoting(const Options& options); // Initialize SampleRemoteApp for local rendering targeting HoloLens or Windows Mixed Reality headsets. void InitializeStandalone(); // IDeviceNotify methods virtual void OnDeviceLost(); virtual void OnDeviceRestored(); // Initializes the RemoteContext and starts connecting or listening to the currently set network address void InitializeRemoteContextAndConnectOrListen(); private: // Initializes the HolographicSpace and creates graphics device dependent resources void CreateHolographicSpaceAndDeviceResources(); // Connects to or listens on the currently set network address void ConnectOrListen(); // Loads the currently saved position of the spinning cube. void LoadPosition(); // Saves the position of the spinning cube. void SavePosition(); // Exports a test anchor via SpatialAnchorExporter. winrt::fire_and_forget ExportPosition(); // Triggers all the capability requests and creates the SpatialSurfaceMeshRenderer. void InitializeAccessToFeatures(); // Request access for eyes pose data. void RequestEyesPoseAccess(); // Request access for scene observer data. winrt::fire_and_forget RequestSceneObserverAccess(); // Request updates for qr code watcher data. winrt::fire_and_forget RequestQRCodeWatcherUpdates(); // Compute scene update and toggle rendering mode. void ToggleSceneUnderstanding(); // Clears event registration state. Used when changing to a new HolographicSpace // and when tearing down SampleRemoteApp. void UnregisterHolographicEventHandlers(); // Shuts down the RemoteContext (which will also disconnect, if currently connected) void ShutdownRemoteContext(); // Creates a SwapChain for the host window void WindowCreateSwapChain(const winrt::com_ptr<ID3D11Device1>& device); // Presents the SwapChain of the host window void WindowPresentSwapChain(); // Updates the title of the host window void WindowUpdateTitle(); // Asynchronously creates resources for new holographic cameras. void OnCameraAdded( const winrt::Windows::Graphics::Holographic::HolographicSpace& sender, const winrt::Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs& args); // Synchronously releases resources for holographic cameras that are no longer // attached to the system. void OnCameraRemoved( const winrt::Windows::Graphics::Holographic::HolographicSpace& sender, const winrt::Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs& args); // Used to notify the app when the positional tracking state changes. void OnLocatabilityChanged( const winrt::Windows::Perception::Spatial::SpatialLocator& sender, const winrt::Windows::Foundation::IInspectable& args); // Used to notify the app when a connection was successfully established void OnConnected(); // Used to notify the app when an established connection ended or when a connection attempt failed void OnDisconnected(winrt::Microsoft::Holographic::AppRemoting::ConnectionFailureReason failureReason); // Used to notify the app when a frame is about to be sent to the Player void OnSendFrame(const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface& texture); #ifdef ENABLE_CUSTOM_DATA_CHANNEL_SAMPLE // Used to notify the app when the custom data channel received a data packet void OnCustomDataChannelDataReceived(winrt::array_view<const uint8_t> dataView); // Used to notify the app when the custom data channel was closed void OnCustomDataChannelClosed(); #endif private: bool m_isInitialized = false; std::chrono::high_resolution_clock::time_point m_startTime = std::chrono::high_resolution_clock::now(); // Lock to serialize remote context operations and event handlers std::recursive_mutex m_remoteContextAccess; // RemoteContext used to connect with a Holographic Remoting player and display rendered frames winrt::Microsoft::Holographic::AppRemoting::RemoteContext m_remoteContext = nullptr; // Whether a disconnect is currently pending. bool m_disconnectPending{false}; // Represents the holographic space around the user. winrt::Windows::Graphics::Holographic::HolographicSpace m_holographicSpace = nullptr; // The interaction manager provides an event that informs the app when spatial interactions are detected. winrt::Windows::UI::Input::Spatial::SpatialInteractionManager m_interactionManager = nullptr; // Cached pointer to device resources. std::shared_ptr<DXHelper::DeviceResources> m_deviceResources; // SpatialLocator that is attached to the primary camera. winrt::Windows::Perception::Spatial::SpatialLocator m_locator = nullptr; // A reference frame that is positioned in the world. winrt::Windows::Perception::Spatial::SpatialStationaryFrameOfReference m_referenceFrame = nullptr; // Renders a colorful holographic cube that's 20 centimeters wide. This sample content // is used to demonstrate world-locked rendering. std::unique_ptr<SpinningCubeRenderer> m_spinningCubeRenderer; // Renders the surface observed in the user's surroundings. std::unique_ptr<SpatialSurfaceMeshRenderer> m_spatialSurfaceMeshRenderer; // Listens for the Pressed spatial input event. std::shared_ptr<SpatialInputHandler> m_spatialInputHandler; std::shared_ptr<SpatialInputRenderer> m_spatialInputRenderer; // Renders scene objects. std::atomic<bool> m_hasSceneObserverAccess = false; std::shared_ptr<SceneUnderstandingRenderer> m_sceneUnderstandingRenderer; // Renders qr codes. std::unique_ptr<QRCodeRenderer> m_qrCodeRenderer; // Event registration tokens. winrt::event_token m_cameraAddedToken; winrt::event_token m_cameraRemovedToken; winrt::event_token m_locatabilityChangedToken; // Event registration revokers winrt::Microsoft::Holographic::AppRemoting::IRemoteContext::OnConnected_revoker m_onConnectedEventRevoker; winrt::Microsoft::Holographic::AppRemoting::IRemoteContext::OnDisconnected_revoker m_onDisconnectedEventRevoker; winrt::Microsoft::Holographic::AppRemoting::IRemoteContext::OnSendFrame_revoker m_onSendFrameEventRevoker; winrt::Microsoft::Holographic::AppRemoting::IRemoteContext::OnDataChannelCreated_revoker m_onDataChannelCreatedEventRevoker; winrt::Microsoft::Holographic::AppRemoting::IRemoteSpeech::OnRecognizedSpeech_revoker m_onRecognizedSpeechRevoker; // Host options Options m_options = {}; // Host window related variables RemoteWindowHolographic* m_window = nullptr; int m_width = INITIAL_WINDOW_WIDTH; int m_height = INITIAL_WINDOW_HEIGHT; std::chrono::high_resolution_clock::time_point m_windowTitleUpdateTime; uint32_t m_framesPerSecond = 0; std::recursive_mutex m_deviceLock; winrt::com_ptr<IDXGISwapChain1> m_swapChain; winrt::com_ptr<ID3D11Texture2D> m_spTexture; bool m_canCommitDirect3D11DepthBuffer = false; bool m_commitDirect3D11DepthBuffer = true; bool m_isStandalone = false; uint32_t m_depthDownscale = 2; #ifdef ENABLE_CUSTOM_DATA_CHANNEL_SAMPLE std::recursive_mutex m_customDataChannelLock; winrt::Microsoft::Holographic::AppRemoting::IDataChannel2 m_customDataChannel = nullptr; winrt::Microsoft::Holographic::AppRemoting::IDataChannel2::OnDataReceived_revoker m_customChannelDataReceivedEventRevoker; winrt::Microsoft::Holographic::AppRemoting::IDataChannel2::OnClosed_revoker m_customChannelClosedEventRevoker; std::chrono::high_resolution_clock::time_point m_customDataChannelSendTime = std::chrono::high_resolution_clock::now(); #endif winrt::Microsoft::MixedReality::QR::QRCodeWatcher m_qrWatcher{nullptr}; winrt::Microsoft::MixedReality::QR::QRCodeWatcher::Added_revoker m_qrAddedRevoker; winrt::Microsoft::MixedReality::QR::QRCodeWatcher::Updated_revoker m_qrUpdatedRevoker; };
39.931655
129
0.753806
6582e1393a9ce43d52546000676f46a9b46abeba
3,093
h
C
ThirdParty/CGAL/includes/CGAL/Random_convex_set_traits_2.h
wangluo2028/Cgal_Plugin
ccdf12f8af4d26db585105671ff743456778523e
[ "MIT" ]
23
2017-05-26T06:09:25.000Z
2021-11-17T06:26:28.000Z
3rd_party/cgal_4.9/include/cgal/Random_convex_set_traits_2.h
nimzi/CGALViewer
25e28196a9192c2b7174a5656f441f97b9c94bd8
[ "MIT" ]
2
2017-07-10T10:32:04.000Z
2018-09-28T03:12:57.000Z
3rd_party/cgal_4.9/include/cgal/Random_convex_set_traits_2.h
nimzi/CGALViewer
25e28196a9192c2b7174a5656f441f97b9c94bd8
[ "MIT" ]
8
2016-11-23T10:36:18.000Z
2020-09-21T06:41:53.000Z
// Copyright (c) 1998 // Utrecht University (The Netherlands), // ETH Zurich (Switzerland), // INRIA Sophia-Antipolis (France), // Max-Planck-Institute Saarbruecken (Germany), // and Tel-Aviv University (Israel). All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Michael Hoffmann <hoffmann@inf.ethz.ch> #ifndef CGAL_RANDOM_CONVEX_SET_TRAITS_2_H #define CGAL_RANDOM_CONVEX_SET_TRAITS_2_H 1 #include <CGAL/Point_2.h> namespace CGAL { template < class Kernel > struct Random_convex_set_traits_2 : public Kernel { typedef typename Kernel::Point_2 Point_2; typedef typename Kernel::Direction_2 Direction_2; typedef typename Kernel::FT FT; Random_convex_set_traits_2() : _origin( ORIGIN) {} const Point_2 & origin() const { return _origin; } struct Max_coordinate : public std::unary_function< Point_2, FT > { FT operator()( const Point_2& p) const { return (std::max)( CGAL_NTS abs( p.x()), CGAL_NTS abs( p.y())); } }; struct Sum : public std::binary_function< Point_2, Point_2, Point_2 > { Point_2 operator()( const Point_2& p, const Point_2& q) const { return p + (q - ORIGIN); } }; struct Scale : public std::binary_function< Point_2, FT, Point_2 > { Point_2 operator()( const Point_2& p, const FT& k) const { return ORIGIN + (p - ORIGIN) * k; } }; struct Angle_less : public std::binary_function< Point_2, Point_2, bool > { bool operator()( const Point_2& p, const Point_2& q) const { return Direction_2( p - ORIGIN) < Direction_2( q - ORIGIN); } }; private: Point_2 _origin; }; template <class Kernel> struct Random_convex_set_traits : public Random_convex_set_traits_2<Kernel> {}; template < class OutputIterator, class Point_generator > inline OutputIterator random_convex_set_2( std::size_t n, OutputIterator o, const Point_generator& pg) { typedef typename Point_generator::value_type Point_2; return CGAL_random_convex_set_2(n, o, pg, reinterpret_cast<Point_2*>(0)); } template < class OutputIterator, class Point_generator, class R > inline OutputIterator CGAL_random_convex_set_2( std::size_t n, OutputIterator o, const Point_generator& pg, Point_2< R >*) { return random_convex_set_2( n, o, pg, Random_convex_set_traits_2< R >()); } } //namespace CGAL #endif // ! (CGAL_RANDOM_CONVEX_SET_TRAITS_2_H)
26.435897
79
0.679599
aa1f7072b3740344113d613c5b63777b141dfd46
1,771
h
C
connectivity/FEATURE_BLE/libraries/cordio_stack/wsf/include/util/crc32.h
heuisam/mbed-os
eb32b25c8abb37f0aab505451074448e7e420517
[ "Apache-2.0" ]
3,897
2015-09-04T13:42:23.000Z
2022-03-30T16:53:07.000Z
connectivity/FEATURE_BLE/libraries/cordio_stack/wsf/include/util/crc32.h
heuisam/mbed-os
eb32b25c8abb37f0aab505451074448e7e420517
[ "Apache-2.0" ]
13,030
2015-09-17T10:30:05.000Z
2022-03-31T13:36:44.000Z
connectivity/FEATURE_BLE/libraries/cordio_stack/wsf/include/util/crc32.h
heuisam/mbed-os
eb32b25c8abb37f0aab505451074448e7e420517
[ "Apache-2.0" ]
2,950
2015-09-08T19:07:05.000Z
2022-03-31T13:37:23.000Z
/*************************************************************************************************/ /*! * \file crc32.h * * \brief CRC-32 utilities. * * Copyright (c) 2010-2018 Arm Ltd. All Rights Reserved. * * Copyright (c) 2019-2020 Packetcraft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*************************************************************************************************/ #ifndef CRC32_H #define CRC32_H #ifdef __cplusplus extern "C" { #endif /*! \addtogroup WSF_UTIL_API * \{ */ /*************************************************************************************************/ /*! * \brief Calculate the CRC-32 of the given buffer. * * \param crcInit Initial value of the CRC. * \param len Length of the buffer. * \param pBuf Buffer to compute the CRC. * * This routine was originally generated with crcmod.py using the following parameters: * - polynomial 0x104C11DB7 * - bit reverse algorithm */ /*************************************************************************************************/ uint32_t CalcCrc32(uint32_t crcInit, uint32_t len, const uint8_t *pBuf); /*! \} */ /* WSF_UTIL_API */ #ifdef __cplusplus }; #endif #endif /* CRC32_H */
31.625
99
0.52795
a60de6e7a3f733ff7d130d4dcaa90cd2603b9189
1,318
h
C
System/Library/PrivateFrameworks/Preferences.framework/PSKeychainSyncPhoneNumber.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/Preferences.framework/PSKeychainSyncPhoneNumber.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/Preferences.framework/PSKeychainSyncPhoneNumber.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:35:57 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/Preferences.framework/Preferences * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @class NSString, KeychainSyncCountryInfo; @interface PSKeychainSyncPhoneNumber : NSObject { NSString* _digits; KeychainSyncCountryInfo* _countryInfo; } @property (nonatomic,retain) NSString * digits; //@synthesize digits=_digits - In the implementation block @property (nonatomic,retain) KeychainSyncCountryInfo * countryInfo; //@synthesize countryInfo=_countryInfo - In the implementation block +(id)phoneNumberWithDigits:(id)arg1 countryInfo:(id)arg2 ; -(NSString *)digits; -(id)formattedString; -(KeychainSyncCountryInfo *)countryInfo; -(void)setCountryInfo:(KeychainSyncCountryInfo *)arg1 ; -(void)setDigits:(NSString *)arg1 ; -(id)_stringByAddingDialingPrefixToString:(id)arg1 ; -(id)formattedStringWithDialingPrefix; -(id)formattedAndObfuscatedString; @end
41.1875
149
0.681335
10e36a5dbe4b0d0eda96b9532e261cf75ba0ad6f
17,697
c
C
src/flickrms.c
patrickjennings/FlickrMS
b321f9ec82015d3c2bb26bd25e5936479811c0af
[ "Apache-2.0" ]
25
2015-05-30T15:40:33.000Z
2018-06-16T20:16:16.000Z
src/flickrms.c
patrickjennings/FlickrMS
b321f9ec82015d3c2bb26bd25e5936479811c0af
[ "Apache-2.0" ]
9
2015-06-14T03:21:38.000Z
2017-06-10T02:45:06.000Z
src/flickrms.c
patrickjennings/FlickrMS
b321f9ec82015d3c2bb26bd25e5936479811c0af
[ "Apache-2.0" ]
2
2016-08-04T04:30:43.000Z
2018-11-18T19:41:13.000Z
#define FUSE_USE_VERSION 30 #define _XOPEN_SOURCE 500 #include <fuse.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <time.h> #include <ftw.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wconversion" #pragma GCC diagnostic ignored "-Wfloat-conversion" #pragma GCC diagnostic ignored "-Wsign-conversion" #include <wand/magick_wand.h> #pragma GCC diagnostic pop #include "cache.h" #include "wget.h" #define PERMISSIONS 0755 /* Cached file permissions. */ #define TMP_DIR_NAME ".flickrms" /* Where to place cached photos. */ #define PHOTO_TIMEOUT 14400 /* In seconds. */ /* Determines whether to report the true file size in getattr before the file * has been downloaded locally. The true file size will always be set and cached * after a file has been downloaded (which happens when opening a file). If this * option is set, Flickrms will query the remote server to get only the file * size for each photo from the response headers but not download the photo. * Using the true photo size is recommended for GUI applications as they tend to * stat the file before opening. * Using a fake file size will be much faster for command line usage. */ #define USE_TRUE_PHOTO_SIZE 1 /* 1 will use the true size. 0 will use a fake size. */ #define FAKE_PHOTO_SIZE 1024 /* Only used when USE_TRUE_PHOTO_SIZE is set. */ /* Whether to clean the temporary directory on unmount. * The filesystem does not keep track of files that cannot be uploaded to Flickr, * such as lock and hidden files created by file browsers, after the file system * has been destroyed. This option clears the temp dir used for cached files. */ #define CLEAN_TMP_DIR_UMOUNT 1 /* 1 or 0. */ static uid_t uid; /* The user id of the user that mounted the filesystem */ static gid_t gid; /* The group id of the user */ static char *tmp_path; /** * Helper functions **/ /* * Returns the first index of a '/' or negative if non exists in the * path supplied. */ static size_t get_slash_index(const char *path, unsigned short *found) { size_t i; *found = 0; if(!path) return 0; for(i = 0; i < strlen(path); i++) { if(path[i] == '/') { *found = 1; break; } } return i; } /* * Internal method for splitting a path of the format: * "/photosetname/photoname" * into: photoset = "photosetname" and photo = "photoname" */ static int get_photoset_photo_from_path(const char *path, char **photoset, char **photo) { size_t i; unsigned short found; char *path_dup; path_dup = strdup(path + 1); i = get_slash_index(path_dup, &found); if(!path || !photoset || !photo || !path_dup) return FAIL; if(found) { path_dup[i] = '\0'; *photoset = strdup(path_dup); *photo = strdup(path_dup + i + 1); } else { *photoset = strdup(""); *photo = strdup(path_dup); } free(path_dup); return SUCCESS; } /* * Sets the uid/gid variables to the user's (who mounted the filesystem) * uid/gid. Want to only give the user access to their flickr account. */ static inline int set_user_variables() { uid = getuid(); gid = getgid(); return SUCCESS; } /* * Set the path to the directory that will be used to get the image * data from Flickr. */ static inline int set_tmp_path() { char *home; if(!(home = getenv("HOME"))) return FAIL; tmp_path = (char *)malloc(strlen(home) + strlen(TMP_DIR_NAME) + 2); if(!tmp_path) return FAIL; strcpy(tmp_path, home); strcat(tmp_path, "/"); strcat(tmp_path, TMP_DIR_NAME); return 0 - mkdir(tmp_path, PERMISSIONS); } static int remove_tmp_file(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { (void)sb; (void)typeflag; if(ftwbuf->level == 0) return SUCCESS; return remove(fpath); } static inline void remove_tmp_path() { nftw(tmp_path, remove_tmp_file, 64, FTW_DEPTH | FTW_PHYS); free(tmp_path); } static inline void imagemagick_init() { MagickWandGenesis(); } static inline void imagemagick_destroy() { MagickWandTerminus(); } /** * File system functions **/ static inline void set_stbuf(struct stat *stbuf, mode_t mode, uid_t uid, gid_t gid, off_t size, time_t time, nlink_t nlink) { stbuf->st_mode = mode; stbuf->st_uid = uid; stbuf->st_gid = gid; stbuf->st_size = size; stbuf->st_mtime = time; stbuf->st_nlink = nlink; } /* * Get photo size if needed. */ static int process_photo(const char *photoset, const char *photo, cached_information *ci) { if(ci->size == PHOTO_SIZE_UNSET && ci->uri) { int photo_size = FAKE_PHOTO_SIZE; if(USE_TRUE_PHOTO_SIZE) { photo_size = get_url_content_length(ci->uri); if(photo_size < 0) return FAIL; } ci->size = (unsigned int)photo_size; } else { /* Possibly dirty. Try stating cached directory. */ struct stat st_buf; char *cached_path = (char *)malloc(strlen(photoset) + strlen(photo) + strlen(tmp_path) + 3); strcpy(cached_path, tmp_path); if(strcmp(photoset,"")) { strcat(cached_path, "/"); strcat(cached_path, photoset); } strcat(cached_path, "/"); strcat(cached_path, photo); if(!stat(cached_path, &st_buf)) { ci->size = (unsigned int)st_buf.st_size; } free(cached_path); } set_photo_size(photoset, photo, ci->size); return SUCCESS; } static int prime_photo_size_cache(const char *photoset, char **names, unsigned int num_names) { unsigned int i; #pragma omp parallel for for(i = 0; i < num_names; i++) { cached_information *ci = photo_lookup(photoset, names[i]); if(ci) { process_photo(photoset, names[i], ci); free_cached_info(ci); } } return SUCCESS; } /* * Gets the attributes (stat) of the node at path. */ static int fms_getattr(const char *path, struct stat *stbuf) { int retval = -ENOENT; memset((void *)stbuf, 0, sizeof(struct stat)); if(!strcmp(path, "/")) { /* Path is mount directory */ /* FIXME: Total size of all files... or leave at 0? */ set_stbuf(stbuf, S_IFDIR | PERMISSIONS, uid, gid, 0, 0, 1); retval = SUCCESS; } else { cached_information *ci = NULL; /* Point to charcter after root directory */ const char *lookup_path = path + 1; unsigned short found; size_t index = get_slash_index(lookup_path, &found); /* Look up first forward slash */ /* If forward slash doesn't exist, we are looking at a photo without a photoset or a photoset. */ if(!found) { if((ci = photoset_lookup(lookup_path))) { /* See if path is to a photoset (i.e. a directory ) */ set_stbuf(stbuf, S_IFDIR | PERMISSIONS, uid, gid, ci->size, ci->time, 1); retval = SUCCESS; } else if((ci = photo_lookup("", lookup_path))) { /* See if path is to a photo (i.e. a file ) */ process_photo("", lookup_path, ci); set_stbuf(stbuf, S_IFREG | PERMISSIONS, uid, gid, ci->size, ci->time, 1); retval = SUCCESS; } } else { /* If forward slash does exist, it means that we have a photo with a photoset (the chars before * the slash are the photoset name and the chars after the slash are the photo name. */ char *photoset = (char *)malloc(index + 1); if(!photoset) retval = -ENOMEM; else { strncpy(photoset, lookup_path, index); /* Extract the photoset from the path */ photoset[index] = '\0'; ci = photo_lookup(photoset, lookup_path + index + 1); /* Look for the photo */ if(ci) { process_photo(photoset, lookup_path + index + 1, ci); set_stbuf(stbuf, S_IFREG | PERMISSIONS, uid, gid, ci->size, ci->time, 1); retval = SUCCESS; } free(photoset); } } if(ci) free_cached_info(ci); } return retval; } /* Read directory */ static int fms_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { unsigned int num_names, i; char **names; (void)offset; (void)fi; filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); if(!strcmp(path, "/")) { /* Path is to mounted directory */ num_names = get_photoset_names(&names); /* Report photoset names */ for(i = 0; i < num_names; i++) { filler(buf, names[i], NULL, 0); free(names[i]); } if(num_names > 0) free(names); num_names = get_photo_names("", &names); /* Get all photo names with no photoset attached */ } else num_names = get_photo_names(path + 1, &names); /* Get the names of photos in the photoset */ if(num_names > 0) prime_photo_size_cache(path + 1, names, num_names); for(i = 0; i < num_names; i++) { filler(buf, names[i], NULL, 0); free(names[i]); } free(names); return SUCCESS; } static int fms_rename(const char *old_path, const char *new_path) { char *old_photo; char *old_photoset; char *new_photo; char *new_photoset; if(get_photoset_photo_from_path(old_path, &old_photoset, &old_photo)) return FAIL; if(get_photoset_photo_from_path(new_path, &new_photoset, &new_photo)) return FAIL; if(strcmp(old_photo, new_photo)) { if(set_photo_name(old_photoset, old_photo, new_photo)) { if(set_photoset_name(old_path + 1, new_path + 1)) return FAIL; } else { free(old_photo); old_photo = strdup(new_photo); } } if(strcmp(old_photoset, new_photoset)) if(set_photo_photoset(old_photoset, old_photo, new_photoset)) return FAIL; free(old_photo); free(old_photoset); free(new_photo); free(new_photoset); return SUCCESS; } static inline void set_photoset_tmp_dir(char *dir_path, const char *tmp_path, const char *photoset) { strcpy(dir_path, tmp_path); strcat(dir_path, "/"); strcat(dir_path, photoset); } static int fms_open(const char *path, struct fuse_file_info *fi) { char *photo; char *photoset; char *uri; char *wget_path; int fd; struct stat st_buf; #define RET(ret) free(wget_path); free(uri); free(photo); free(photoset); return ret; if(get_photoset_photo_from_path(path, &photoset, &photo)) return FAIL; wget_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); set_photoset_tmp_dir(wget_path, tmp_path, photoset); uri = get_photo_uri(photoset, photo); if(uri) { mkdir(wget_path, PERMISSIONS); /* Create photoset temp directory if it doesn't exist */ strcpy(wget_path, tmp_path); strcat(wget_path, path); if(access(wget_path, F_OK)) { /* Get the image from flickr and put it into the temp dir if it doesn't already exist. */ if(wget(uri, wget_path) < 0) { RET(FAIL) } } } else { /* Photo dirty? Try to open anyway. */ strcpy(wget_path, tmp_path); strcat(wget_path, path); } if(stat(wget_path, &st_buf)) { RET(FAIL) } if((time(NULL) - st_buf.st_mtime) > PHOTO_TIMEOUT) { if(uri && wget(uri, wget_path) < 0) { RET(FAIL) } } fd = open(wget_path, fi->flags); if(fd < 0) { RET(-errno) } fi->fh = (uint64_t)fd; set_photo_size(photoset, photo, (unsigned int)st_buf.st_size); RET(SUCCESS) } static int fms_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { (void)path; ssize_t ret = pread((int)fi->fh, buf, size, offset); return (ret < 0) ? -errno : (int)ret; } static int fms_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { (void)path; char *photoset, *photo; ssize_t ret; if(get_photoset_photo_from_path(path, &photoset, &photo)) return FAIL; set_photo_dirty(photoset, photo, DIRTY); free(photoset); free(photo); ret = pwrite((int)fi->fh, buf, size, offset); return (ret < 0) ? -errno : (int)ret; } static int fms_flush(const char *path, struct fuse_file_info *fi) { (void)path; (void)fi; return SUCCESS; } static int fms_release(const char *path, struct fuse_file_info *fi) { (void)fi; char *photoset, *photo; char *temp_scratch_path; if(get_photoset_photo_from_path(path, &photoset, &photo)) return FAIL; temp_scratch_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); strcpy(temp_scratch_path, tmp_path); strcat(temp_scratch_path, path); if(get_photo_dirty(photoset, photo) == DIRTY) { MagickWand *mw = NewMagickWand(); if(!mw) return FAIL; if(MagickPingImage(mw, temp_scratch_path)) upload_photo(photoset, photo, temp_scratch_path); DestroyMagickWand(mw); } free(temp_scratch_path); free(photoset); free(photo); int ret = close((int)fi->fh); return (ret < 0) ? -errno : SUCCESS; } static int fms_create(const char *path, mode_t mode, struct fuse_file_info *fi) { int fd; char *photoset, *photo; char *temp_scratch_path; if(get_photoset_photo_from_path(path, &photoset, &photo)) return FAIL; int retval = create_empty_photo(photoset, photo); free(photoset); free(photo); if(retval) return FAIL; temp_scratch_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); strcpy(temp_scratch_path, tmp_path); strcat(temp_scratch_path, path); fd = creat(temp_scratch_path, mode); fi->fh = (uint64_t)fd; free(temp_scratch_path); return (fd < 0) ? -errno : SUCCESS; } /* Only called after create. For new files. */ static int fms_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi) { (void)path; int ret = fstat((int)fi->fh, stbuf); return (ret < 0) ? -errno : SUCCESS; } static int fms_mkdir(const char *path, mode_t mode) { (void)mode; char *temp_scratch_path; const char *photoset = path + 1; unsigned short found; get_slash_index(photoset, &found); if(found) // Can only mkdir on first level return FAIL; if(create_empty_photoset(photoset)) return FAIL; temp_scratch_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); strcpy(temp_scratch_path, tmp_path); strcat(temp_scratch_path, path); mkdir(temp_scratch_path, PERMISSIONS); // Create photoset tmp directory free(temp_scratch_path); return SUCCESS; } int fms_statfs(const char *path, struct statvfs* stbuf) { (void)path; return statvfs(tmp_path, stbuf); } int fms_chmod(const char *path, mode_t mode) { char *temp_scratch_path; int retval = FAIL; temp_scratch_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); strcpy(temp_scratch_path, tmp_path); strcat(temp_scratch_path, path); retval = chmod(temp_scratch_path, mode); free(temp_scratch_path); return retval; } int fms_chown(const char *path, uid_t uid, gid_t gid) { char *temp_scratch_path; int retval = FAIL; temp_scratch_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); strcpy(temp_scratch_path, tmp_path); strcat(temp_scratch_path, path); retval = chown(temp_scratch_path, uid, gid); free(temp_scratch_path); return retval; } int fms_unlink(const char *path) { char *photoset, *photo; char *temp_scratch_path; int retval = FAIL; if(get_photoset_photo_from_path(path, &photoset, &photo)) return FAIL; if(remove_photo_from_cache(photoset, photo)) { free(photoset); free(photo); return FAIL; } temp_scratch_path = (char *)malloc(strlen(tmp_path) + strlen(path) + 1); strcpy(temp_scratch_path, tmp_path); strcat(temp_scratch_path, path); retval = unlink(temp_scratch_path); free(temp_scratch_path); free(photoset); free(photo); return retval; } /** * Main function **/ static struct fuse_operations flickrms_oper = { .getattr = fms_getattr, .readdir = fms_readdir, .open = fms_open, .read = fms_read, .write = fms_write, .flush = fms_flush, .release = fms_release, .rename = fms_rename, .create = fms_create, .fgetattr = fms_fgetattr, .mkdir = fms_mkdir, .statfs = fms_statfs, .chmod = fms_chmod, .chown = fms_chown, .unlink = fms_unlink }; int main(int argc, char *argv[]) { int ret; if((ret = set_user_variables())) return ret; if((ret = set_tmp_path()) == FAIL) return ret; if((ret = flickr_cache_init())) return ret; if((ret = wget_init())) return ret; imagemagick_init(); ret = fuse_main(argc, argv, &flickrms_oper, NULL); flickr_cache_kill(); wget_destroy(); imagemagick_destroy(); if(CLEAN_TMP_DIR_UMOUNT) remove_tmp_path(); return ret; }
27.142638
110
0.618014
437f02ab68d30eb0a5176e598b9fe83082ea1dc6
16,792
h
C
openexr-c/include.in/imf_flatimagechannel.h
vfx-rs/openexr-bind
ee4fd6010beedb0247737a39ee61ffb87c586448
[ "BSD-3-Clause" ]
7
2021-06-04T20:59:16.000Z
2022-02-11T01:00:42.000Z
openexr-c/include.in/imf_flatimagechannel.h
vfx-rs/openexr-bind
ee4fd6010beedb0247737a39ee61ffb87c586448
[ "BSD-3-Clause" ]
35
2021-05-14T04:28:22.000Z
2021-12-30T12:08:40.000Z
openexr-c/include.in/imf_flatimagechannel.h
vfx-rs/openexr-bind
ee4fd6010beedb0247737a39ee61ffb87c586448
[ "BSD-3-Clause" ]
5
2021-05-15T04:02:56.000Z
2021-07-02T05:38:01.000Z
#pragma once #include "openexr-api-export.h" #include <imf_channellist.h> #include <imf_framebuffer.h> #include <imf_pixeltype.h> #include <stdbool.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif typedef struct Imf_3_0__ImageLevel_t_s Imf_3_0__ImageLevel_t; typedef Imf_3_0__ImageLevel_t Imf_ImageLevel_t; typedef struct Imf_3_0__FlatImageLevel_t_s Imf_3_0__FlatImageLevel_t; typedef Imf_3_0__FlatImageLevel_t Imf_FlatImageLevel_t; typedef struct Imath_3_0__half_t_s Imath_3_0__half_t; typedef Imath_3_0__half_t Imath_half_t; typedef struct Imf_3_0__FlatImageChannel_t_s { char _unused; } OPENEXR_CPPMM_ALIGN(8) Imf_3_0__FlatImageChannel_t; typedef Imf_3_0__FlatImageChannel_t Imf_FlatImageChannel_t; typedef struct Imf_3_0__TypedFlatImageChannel_half__t_s { char _unused; } OPENEXR_CPPMM_ALIGN(8) Imf_3_0__TypedFlatImageChannel_half__t; typedef Imf_3_0__TypedFlatImageChannel_half__t Imf_FlatHalfChannel_t; typedef struct Imf_3_0__TypedFlatImageChannel_float__t_s { char _unused; } OPENEXR_CPPMM_ALIGN(8) Imf_3_0__TypedFlatImageChannel_float__t; typedef Imf_3_0__TypedFlatImageChannel_float__t Imf_FlatFloatChannel_t; typedef struct Imf_3_0__TypedFlatImageChannel_unsignedint__t_s { char _unused; } OPENEXR_CPPMM_ALIGN(8) Imf_3_0__TypedFlatImageChannel_unsignedint__t; typedef Imf_3_0__TypedFlatImageChannel_unsignedint__t Imf_FlatUIntChannel_t; OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_pixelType( Imf_FlatImageChannel_t const * this_ , Imf_PixelType * return_); #define Imf_FlatImageChannel_pixelType Imf_3_0__FlatImageChannel_pixelType OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_channel( Imf_FlatImageChannel_t const * this_ , Imf_Channel_t * return_); #define Imf_FlatImageChannel_channel Imf_3_0__FlatImageChannel_channel OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_xSampling( Imf_FlatImageChannel_t const * this_ , int * return_); #define Imf_FlatImageChannel_xSampling Imf_3_0__FlatImageChannel_xSampling OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_ySampling( Imf_FlatImageChannel_t const * this_ , int * return_); #define Imf_FlatImageChannel_ySampling Imf_3_0__FlatImageChannel_ySampling OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_pLinear( Imf_FlatImageChannel_t const * this_ , _Bool * return_); #define Imf_FlatImageChannel_pLinear Imf_3_0__FlatImageChannel_pLinear OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_pixelsPerRow( Imf_FlatImageChannel_t const * this_ , int * return_); #define Imf_FlatImageChannel_pixelsPerRow Imf_3_0__FlatImageChannel_pixelsPerRow OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_pixelsPerColumn( Imf_FlatImageChannel_t const * this_ , int * return_); #define Imf_FlatImageChannel_pixelsPerColumn Imf_3_0__FlatImageChannel_pixelsPerColumn OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_numPixels( Imf_FlatImageChannel_t const * this_ , size_t * return_); #define Imf_FlatImageChannel_numPixels Imf_3_0__FlatImageChannel_numPixels OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_level( Imf_FlatImageChannel_t * this_ , Imf_ImageLevel_t * * return_); #define Imf_FlatImageChannel_level Imf_3_0__FlatImageChannel_level OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_level_1( Imf_FlatImageChannel_t const * this_ , Imf_ImageLevel_t const * * return_); #define Imf_FlatImageChannel_level_1 Imf_3_0__FlatImageChannel_level_1 OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_slice( Imf_FlatImageChannel_t const * this_ , Imf_Slice_t * return_); #define Imf_FlatImageChannel_slice Imf_3_0__FlatImageChannel_slice OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_flatLevel( Imf_FlatImageChannel_t * this_ , Imf_FlatImageLevel_t * * return_); #define Imf_FlatImageChannel_flatLevel Imf_3_0__FlatImageChannel_flatLevel OPENEXR_CPPMM_API unsigned int Imf_3_0__FlatImageChannel_flatLevel_1( Imf_FlatImageChannel_t const * this_ , Imf_FlatImageLevel_t const * * return_); #define Imf_FlatImageChannel_flatLevel_1 Imf_3_0__FlatImageChannel_flatLevel_1 OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__pixelType( Imf_FlatHalfChannel_t const * this_ , Imf_PixelType * return_); #define Imf_FlatHalfChannel_pixelType Imf_3_0__TypedFlatImageChannel_half__pixelType OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__channel( Imf_FlatHalfChannel_t const * this_ , Imf_Channel_t * return_); #define Imf_FlatHalfChannel_channel Imf_3_0__TypedFlatImageChannel_half__channel OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__xSampling( Imf_FlatHalfChannel_t const * this_ , int * return_); #define Imf_FlatHalfChannel_xSampling Imf_3_0__TypedFlatImageChannel_half__xSampling OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__ySampling( Imf_FlatHalfChannel_t const * this_ , int * return_); #define Imf_FlatHalfChannel_ySampling Imf_3_0__TypedFlatImageChannel_half__ySampling OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__pLinear( Imf_FlatHalfChannel_t const * this_ , _Bool * return_); #define Imf_FlatHalfChannel_pLinear Imf_3_0__TypedFlatImageChannel_half__pLinear OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__pixelsPerRow( Imf_FlatHalfChannel_t const * this_ , int * return_); #define Imf_FlatHalfChannel_pixelsPerRow Imf_3_0__TypedFlatImageChannel_half__pixelsPerRow OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__pixelsPerColumn( Imf_FlatHalfChannel_t const * this_ , int * return_); #define Imf_FlatHalfChannel_pixelsPerColumn Imf_3_0__TypedFlatImageChannel_half__pixelsPerColumn OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__numPixels( Imf_FlatHalfChannel_t const * this_ , size_t * return_); #define Imf_FlatHalfChannel_numPixels Imf_3_0__TypedFlatImageChannel_half__numPixels OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__slice( Imf_FlatHalfChannel_t const * this_ , Imf_Slice_t * return_); #define Imf_FlatHalfChannel_slice Imf_3_0__TypedFlatImageChannel_half__slice OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__flatLevel( Imf_FlatHalfChannel_t * this_ , Imf_FlatImageLevel_t * * return_); #define Imf_FlatHalfChannel_flatLevel Imf_3_0__TypedFlatImageChannel_half__flatLevel OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__flatLevel_const( Imf_FlatHalfChannel_t const * this_ , Imf_FlatImageLevel_t const * * return_); #define Imf_FlatHalfChannel_flatLevel_const Imf_3_0__TypedFlatImageChannel_half__flatLevel_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__index( Imf_FlatHalfChannel_t * this_ , Imath_half_t * * return_ , int x , int y); #define Imf_FlatHalfChannel_index Imf_3_0__TypedFlatImageChannel_half__index OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__index_const( Imf_FlatHalfChannel_t const * this_ , Imath_half_t const * * return_ , int x , int y); #define Imf_FlatHalfChannel_index_const Imf_3_0__TypedFlatImageChannel_half__index_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__at( Imf_FlatHalfChannel_t * this_ , Imath_half_t * * return_ , int x , int y); #define Imf_FlatHalfChannel_at Imf_3_0__TypedFlatImageChannel_half__at OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__at_const( Imf_FlatHalfChannel_t const * this_ , Imath_half_t const * * return_ , int x , int y); #define Imf_FlatHalfChannel_at_const Imf_3_0__TypedFlatImageChannel_half__at_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__row( Imf_FlatHalfChannel_t * this_ , Imath_half_t * * return_ , int r); #define Imf_FlatHalfChannel_row Imf_3_0__TypedFlatImageChannel_half__row OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_half__row_const( Imf_FlatHalfChannel_t const * this_ , Imath_half_t const * * return_ , int r); #define Imf_FlatHalfChannel_row_const Imf_3_0__TypedFlatImageChannel_half__row_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__pixelType( Imf_FlatFloatChannel_t const * this_ , Imf_PixelType * return_); #define Imf_FlatFloatChannel_pixelType Imf_3_0__TypedFlatImageChannel_float__pixelType OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__channel( Imf_FlatFloatChannel_t const * this_ , Imf_Channel_t * return_); #define Imf_FlatFloatChannel_channel Imf_3_0__TypedFlatImageChannel_float__channel OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__xSampling( Imf_FlatFloatChannel_t const * this_ , int * return_); #define Imf_FlatFloatChannel_xSampling Imf_3_0__TypedFlatImageChannel_float__xSampling OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__ySampling( Imf_FlatFloatChannel_t const * this_ , int * return_); #define Imf_FlatFloatChannel_ySampling Imf_3_0__TypedFlatImageChannel_float__ySampling OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__pLinear( Imf_FlatFloatChannel_t const * this_ , _Bool * return_); #define Imf_FlatFloatChannel_pLinear Imf_3_0__TypedFlatImageChannel_float__pLinear OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__pixelsPerRow( Imf_FlatFloatChannel_t const * this_ , int * return_); #define Imf_FlatFloatChannel_pixelsPerRow Imf_3_0__TypedFlatImageChannel_float__pixelsPerRow OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__pixelsPerColumn( Imf_FlatFloatChannel_t const * this_ , int * return_); #define Imf_FlatFloatChannel_pixelsPerColumn Imf_3_0__TypedFlatImageChannel_float__pixelsPerColumn OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__numPixels( Imf_FlatFloatChannel_t const * this_ , size_t * return_); #define Imf_FlatFloatChannel_numPixels Imf_3_0__TypedFlatImageChannel_float__numPixels OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__slice( Imf_FlatFloatChannel_t const * this_ , Imf_Slice_t * return_); #define Imf_FlatFloatChannel_slice Imf_3_0__TypedFlatImageChannel_float__slice OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__flatLevel( Imf_FlatFloatChannel_t * this_ , Imf_FlatImageLevel_t * * return_); #define Imf_FlatFloatChannel_flatLevel Imf_3_0__TypedFlatImageChannel_float__flatLevel OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__flatLevel_const( Imf_FlatFloatChannel_t const * this_ , Imf_FlatImageLevel_t const * * return_); #define Imf_FlatFloatChannel_flatLevel_const Imf_3_0__TypedFlatImageChannel_float__flatLevel_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__index( Imf_FlatFloatChannel_t * this_ , float * * return_ , int x , int y); #define Imf_FlatFloatChannel_index Imf_3_0__TypedFlatImageChannel_float__index OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__index_const( Imf_FlatFloatChannel_t const * this_ , float const * * return_ , int x , int y); #define Imf_FlatFloatChannel_index_const Imf_3_0__TypedFlatImageChannel_float__index_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__at( Imf_FlatFloatChannel_t * this_ , float * * return_ , int x , int y); #define Imf_FlatFloatChannel_at Imf_3_0__TypedFlatImageChannel_float__at OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__at_const( Imf_FlatFloatChannel_t const * this_ , float const * * return_ , int x , int y); #define Imf_FlatFloatChannel_at_const Imf_3_0__TypedFlatImageChannel_float__at_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__row( Imf_FlatFloatChannel_t * this_ , float * * return_ , int r); #define Imf_FlatFloatChannel_row Imf_3_0__TypedFlatImageChannel_float__row OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_float__row_const( Imf_FlatFloatChannel_t const * this_ , float const * * return_ , int r); #define Imf_FlatFloatChannel_row_const Imf_3_0__TypedFlatImageChannel_float__row_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__pixelType( Imf_FlatUIntChannel_t const * this_ , Imf_PixelType * return_); #define Imf_FlatUIntChannel_pixelType Imf_3_0__TypedFlatImageChannel_unsignedint__pixelType OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__channel( Imf_FlatUIntChannel_t const * this_ , Imf_Channel_t * return_); #define Imf_FlatUIntChannel_channel Imf_3_0__TypedFlatImageChannel_unsignedint__channel OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__xSampling( Imf_FlatUIntChannel_t const * this_ , int * return_); #define Imf_FlatUIntChannel_xSampling Imf_3_0__TypedFlatImageChannel_unsignedint__xSampling OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__ySampling( Imf_FlatUIntChannel_t const * this_ , int * return_); #define Imf_FlatUIntChannel_ySampling Imf_3_0__TypedFlatImageChannel_unsignedint__ySampling OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__pLinear( Imf_FlatUIntChannel_t const * this_ , _Bool * return_); #define Imf_FlatUIntChannel_pLinear Imf_3_0__TypedFlatImageChannel_unsignedint__pLinear OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__pixelsPerRow( Imf_FlatUIntChannel_t const * this_ , int * return_); #define Imf_FlatUIntChannel_pixelsPerRow Imf_3_0__TypedFlatImageChannel_unsignedint__pixelsPerRow OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__pixelsPerColumn( Imf_FlatUIntChannel_t const * this_ , int * return_); #define Imf_FlatUIntChannel_pixelsPerColumn Imf_3_0__TypedFlatImageChannel_unsignedint__pixelsPerColumn OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__numPixels( Imf_FlatUIntChannel_t const * this_ , size_t * return_); #define Imf_FlatUIntChannel_numPixels Imf_3_0__TypedFlatImageChannel_unsignedint__numPixels OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__slice( Imf_FlatUIntChannel_t const * this_ , Imf_Slice_t * return_); #define Imf_FlatUIntChannel_slice Imf_3_0__TypedFlatImageChannel_unsignedint__slice OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__flatLevel( Imf_FlatUIntChannel_t * this_ , Imf_FlatImageLevel_t * * return_); #define Imf_FlatUIntChannel_flatLevel Imf_3_0__TypedFlatImageChannel_unsignedint__flatLevel OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__flatLevel_const( Imf_FlatUIntChannel_t const * this_ , Imf_FlatImageLevel_t const * * return_); #define Imf_FlatUIntChannel_flatLevel_const Imf_3_0__TypedFlatImageChannel_unsignedint__flatLevel_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__index( Imf_FlatUIntChannel_t * this_ , unsigned int * * return_ , int x , int y); #define Imf_FlatUIntChannel_index Imf_3_0__TypedFlatImageChannel_unsignedint__index OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__index_const( Imf_FlatUIntChannel_t const * this_ , unsigned int const * * return_ , int x , int y); #define Imf_FlatUIntChannel_index_const Imf_3_0__TypedFlatImageChannel_unsignedint__index_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__at( Imf_FlatUIntChannel_t * this_ , unsigned int * * return_ , int x , int y); #define Imf_FlatUIntChannel_at Imf_3_0__TypedFlatImageChannel_unsignedint__at OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__at_const( Imf_FlatUIntChannel_t const * this_ , unsigned int const * * return_ , int x , int y); #define Imf_FlatUIntChannel_at_const Imf_3_0__TypedFlatImageChannel_unsignedint__at_const OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__row( Imf_FlatUIntChannel_t * this_ , unsigned int * * return_ , int r); #define Imf_FlatUIntChannel_row Imf_3_0__TypedFlatImageChannel_unsignedint__row OPENEXR_CPPMM_API unsigned int Imf_3_0__TypedFlatImageChannel_unsignedint__row_const( Imf_FlatUIntChannel_t const * this_ , unsigned int const * * return_ , int r); #define Imf_FlatUIntChannel_row_const Imf_3_0__TypedFlatImageChannel_unsignedint__row_const #ifdef __cplusplus } #endif
36.583878
103
0.848916
3189dc273afa0d23fca5b5eb257276a2a0353a55
3,605
c
C
boards/arm/stm32/olimex-stm32-h405/src/stm32_usb.c
alvin1991/incubator-nuttx
b4fe0422624cfdc5a1925696f6ca7191a6d45326
[ "Apache-2.0" ]
1,006
2019-12-17T23:45:41.000Z
2022-03-31T19:42:44.000Z
boards/arm/stm32/olimex-stm32-h405/src/stm32_usb.c
alvin1991/incubator-nuttx
b4fe0422624cfdc5a1925696f6ca7191a6d45326
[ "Apache-2.0" ]
2,661
2019-12-21T15:16:09.000Z
2022-03-31T22:30:04.000Z
boards/arm/stm32/olimex-stm32-h405/src/stm32_usb.c
alvin1991/incubator-nuttx
b4fe0422624cfdc5a1925696f6ca7191a6d45326
[ "Apache-2.0" ]
613
2019-12-21T10:17:37.000Z
2022-03-28T09:42:20.000Z
/**************************************************************************** * boards/arm/stm32/olimex-stm32-h405/src/stm32_usb.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <sched.h> #include <errno.h> #include <debug.h> #include <nuttx/usb/usbdev.h> #include <nuttx/usb/usbdev_trace.h> #include "stm32.h" #include "stm32_otgfs.h" #include "olimex-stm32-h405.h" #ifdef CONFIG_STM32_OTGFS /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #if defined(CONFIG_USBDEV) # define HAVE_USB 1 #else # warning "CONFIG_STM32_OTGFS is enabled but not CONFIG_USBDEV" # undef HAVE_USB #endif /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: stm32_usbinitialize * * Description: * Called from stm32_usbinitialize very early in inialization to setup * USB-related GPIO pins for the STM32F4Discovery board. * ****************************************************************************/ void stm32_usbinitialize(void) { /* The OTG FS has an internal soft pull-up. * No GPIO configuration is required */ /* Configure the OTG FS VBUS sensing GPIO */ #ifdef CONFIG_STM32_OTGFS stm32_configgpio(GPIO_OTGFS_VBUS); #endif } /**************************************************************************** * Name: stm32_usbsuspend * * Description: * Board logic must provide the stm32_usbsuspend logic if the USBDEV * driver is used. This function is called whenever the USB enters or * leaves suspend mode. * This is an opportunity for the board logic to shutdown clocks, power, * etc. while the USB is suspended. * ****************************************************************************/ #ifdef CONFIG_USBDEV void stm32_usbsuspend(FAR struct usbdev_s *dev, bool resume) { uinfo("resume: %d\n", resume); } #endif #endif /* CONFIG_STM32_OTGFS */
34.009434
78
0.482663
4e0e8ba3bf5c10fe905929880a9abf7b6be4322a
17,779
c
C
nshlib/nsh_routecmds.c
codebje/incubator-nuttx-apps
d66bc2c1070cdbbb7c8e00ffa727a8515cf26eff
[ "Apache-2.0" ]
5
2020-07-04T06:28:06.000Z
2022-03-17T06:46:44.000Z
nshlib/nsh_routecmds.c
codebje/incubator-nuttx-apps
d66bc2c1070cdbbb7c8e00ffa727a8515cf26eff
[ "Apache-2.0" ]
7
2021-07-15T13:08:26.000Z
2021-08-04T17:15:29.000Z
nshlib/nsh_routecmds.c
codebje/incubator-nuttx-apps
d66bc2c1070cdbbb7c8e00ffa727a8515cf26eff
[ "Apache-2.0" ]
14
2020-06-12T09:54:24.000Z
2022-03-21T15:27:54.000Z
/**************************************************************************** * apps/nshlib/nsh_routecmds.c * * Copyright (C) 2013, 2017 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <net/route.h> #include <netinet/in.h> #include <arpa/inet.h> #include "netutils/netlib.h" #include "nsh.h" #include "nsh_console.h" #if defined(CONFIG_NET) && defined(CONFIG_NET_ROUTE) /**************************************************************************** * Private Functions ****************************************************************************/ static int slash_notation(FAR char *arg) { FAR char *sptr; FAR char *ptr; /* If an address contains a /, then the netmask is imply by the following * numeric value. */ sptr = strchr(arg, '/'); if (sptr != NULL) { /* Make sure that everything following the slash is a decimal digit. */ ptr = sptr + 1; while (isdigit(*ptr)) { ptr++; } /* There should be nothing be digits after the slash and up to the * NULL terminator. */ if (*ptr == '\0') { *sptr++ = '\0'; return atoi(sptr); } } return ERROR; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: cmd_addroute * * nsh> addroute <target> [<netmask>] <router> * ****************************************************************************/ #ifndef CONFIG_NSH_DISABLE_ADDROUTE int cmd_addroute(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv) { union { #ifdef CONFIG_NET_IPv4 struct sockaddr_in ipv4; #endif #ifdef CONFIG_NET_IPv6 struct sockaddr_in6 ipv6; #endif } target; union { #ifdef CONFIG_NET_IPv4 struct sockaddr_in ipv4; #endif #ifdef CONFIG_NET_IPv6 struct sockaddr_in6 ipv6; #endif } netmask; union { #ifdef CONFIG_NET_IPv4 struct sockaddr_in ipv4; #endif #ifdef CONFIG_NET_IPv6 struct sockaddr_in6 ipv6; #endif } router; union { #ifdef CONFIG_NET_IPv4 struct in_addr ipv4; #endif #ifdef CONFIG_NET_IPv6 struct in6_addr ipv6; #endif } inaddr; sa_family_t family; int rtrndx; int shift; int sockfd; int ret; /* First, check if we are setting the default route */ if (strcmp(argv[1], "default") == 0) { /* We are expecting an ip and an interface name to follow. */ if (argc < 4) { nsh_error(vtbl, g_fmtargrequired, argv[0]); goto errout; } else if (argc > 4) { nsh_error(vtbl, g_fmttoomanyargs, argv[0]); goto errout; } /* Convert the target IP address string into its binary form */ #ifdef CONFIG_NET_IPv4 family = PF_INET; ret = inet_pton(AF_INET, argv[2], &inaddr.ipv4); if (ret != 1) #endif { #ifdef CONFIG_NET_IPv6 family = PF_INET6; ret = inet_pton(AF_INET6, argv[2], &inaddr.ipv6); if (ret != 1) #endif { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout; } } #ifdef CONFIG_NET_IPv4 if (family == PF_INET) { ret = netlib_set_dripv4addr(argv[3], &inaddr.ipv4); if (ret != 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0]); goto errout; } } #endif #ifdef CONFIG_NET_IPv6 if (family == PF_INET6) { ret = netlib_set_dripv6addr(argv[3], &inaddr.ipv6); if (ret != 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0]); goto errout; } } #endif return OK; } /* Check if slash notation is used with the target address */ shift = slash_notation(argv[1]); /* There will be 2 or 3 arguments, depending on if slash notation is * used. */ if (shift > 0 && argc != 3) { nsh_error(vtbl, g_fmttoomanyargs, argv[0]); goto errout; } else if (shift < 0 && argc != 4) { nsh_error(vtbl, g_fmtargrequired, argv[0]); goto errout; } /* Convert the target IP address string into its binary form */ #ifdef CONFIG_NET_IPv4 family = PF_INET; ret = inet_pton(AF_INET, argv[1], &inaddr.ipv4); if (ret != 1) #endif { #ifdef CONFIG_NET_IPv6 family = PF_INET6; ret = inet_pton(AF_INET6, argv[1], &inaddr.ipv6); if (ret != 1) #endif { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout; } } /* We need to have a socket (any socket) in order to perform the ioctl */ sockfd = socket(family, NETLIB_SOCK_TYPE, 0); if (sockfd < 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "socket", NSH_ERRNO); goto errout; } /* Format the target sockaddr instance */ memset(&target, 0, sizeof(target)); #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { target.ipv4.sin_family = AF_INET; target.ipv4.sin_addr = inaddr.ipv4; } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { target.ipv6.sin6_family = AF_INET6; memcpy(&target.ipv6.sin6_addr, &inaddr.ipv6, sizeof(struct in6_addr)); } #endif /* Convert the netmask IP address string into its binary form */ if (shift >= 0) { #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { /* /0 -> 0x00000000 * /8 -> 0xff000000 * /24 -> 0xffffff00 * /32 -> 0xffffffff */ if (shift > 32) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } inaddr.ipv4.s_addr = htonl(0xffffffff << (32 - shift)); } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { int i; /* /0 -> 0000:0000:0000:0000:0000:0000:0000:0000 * /16 -> ffff:0000:0000:0000:0000:0000:0000:0000 * /32 -> ffff:ffff:0000:0000:0000:0000:0000:0000 * ... * /128 -> ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff */ memset(&inaddr.ipv6, 0, sizeof(struct sockaddr_in6)); for (i = 0; i < 8 && shift >= 16; i++, shift -= 16) { inaddr.ipv6.s6_addr16[i] = 0xffff; } if (shift > 16 || (shift > 0 && i >= 8)) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } /* /0 -> 0x0000 * /1 -> 0x8000 * /2 -> 0xc000 * ... * /16 -> 0xffff */ if (shift > 0) { inaddr.ipv6.s6_addr16[i] = htons(0xffff << (16 - shift)); } } #endif rtrndx = 2; } else { /* Slash notation not used.. mask should follow the target address */ ret = inet_pton(family, argv[2], &inaddr); if (ret != 1) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } rtrndx = 3; } /* Format the netmask sockaddr instance */ memset(&netmask, 0, sizeof(netmask)); #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { netmask.ipv4.sin_family = AF_INET; netmask.ipv4.sin_addr = inaddr.ipv4; } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { netmask.ipv6.sin6_family = AF_INET6; memcpy(&netmask.ipv6.sin6_addr, &inaddr.ipv6, sizeof(struct in6_addr)); } #endif /* Convert the router IP address string into its binary form */ ret = inet_pton(family, argv[rtrndx], &inaddr); if (ret != 1) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } /* Format the router sockaddr instance */ memset(&router, 0, sizeof(router)); #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { router.ipv4.sin_family = AF_INET; router.ipv4.sin_addr = inaddr.ipv4; } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { router.ipv6.sin6_family = AF_INET6; memcpy(&router.ipv6.sin6_addr, &inaddr.ipv6, sizeof(struct in6_addr)); } #endif /* Then add the route */ ret = addroute(sockfd, (FAR struct sockaddr_storage *)&target, (FAR struct sockaddr_storage *)&netmask, (FAR struct sockaddr_storage *)&router); if (ret < 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "addroute", NSH_ERRNO); goto errout_with_sockfd; } close(sockfd); return OK; errout_with_sockfd: close(sockfd); errout: return ERROR; } #endif /* !CONFIG_NSH_DISABLE_ADDROUTE */ /**************************************************************************** * Name: cmd_delroute * * nsh> delroute <target> [<netmask>] * ****************************************************************************/ #ifndef CONFIG_NSH_DISABLE_DELROUTE int cmd_delroute(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv) { union { #ifdef CONFIG_NET_IPv4 struct sockaddr_in ipv4; #endif #ifdef CONFIG_NET_IPv6 struct sockaddr_in6 ipv6; #endif } target; union { #ifdef CONFIG_NET_IPv4 struct sockaddr_in ipv4; #endif #ifdef CONFIG_NET_IPv6 struct sockaddr_in6 ipv6; #endif } netmask; union { #ifdef CONFIG_NET_IPv4 struct in_addr ipv4; #endif #ifdef CONFIG_NET_IPv6 struct in6_addr ipv6; #endif } inaddr; sa_family_t family; int shift; int sockfd; int ret; /* Check if slash notation is used with the target address */ shift = slash_notation(argv[1]); /* There will be 1 or 2 arguments, depending on if slash notation is * used. */ if (shift > 0 && argc != 2) { nsh_error(vtbl, g_fmttoomanyargs, argv[0]); goto errout; } else if (shift < 0 && argc != 3) { nsh_error(vtbl, g_fmtargrequired, argv[0]); goto errout; } /* Convert the target IP address string into its binary form */ #ifdef CONFIG_NET_IPv4 family = PF_INET; ret = inet_pton(AF_INET, argv[1], &inaddr.ipv4); if (ret != 1) #endif { #ifdef CONFIG_NET_IPv6 family = PF_INET6; ret = inet_pton(AF_INET6, argv[1], &inaddr.ipv6); if (ret != 1) #endif { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout; } } /* We need to have a socket (any socket) in order to perform the ioctl */ sockfd = socket(family, NETLIB_SOCK_TYPE, 0); if (sockfd < 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "socket", NSH_ERRNO); goto errout; } /* Format the target sockaddr instance */ memset(&target, 0, sizeof(target)); #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { target.ipv4.sin_family = AF_INET; target.ipv4.sin_addr = inaddr.ipv4; } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { target.ipv6.sin6_family = AF_INET6; memcpy(&target.ipv6.sin6_addr, &inaddr.ipv6, sizeof(struct in6_addr)); } #endif /* Convert the netmask IP address string into its binary form */ if (shift >= 0) { #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { /* /0 -> 0x00000000 * /8 -> 0xff000000 * /24 -> 0xffffff00 * /32 -> 0xffffffff */ if (shift > 32) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } inaddr.ipv4.s_addr = htonl(0xffffffff << (32 - shift)); } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { int i; /* /0 -> 0000:0000:0000:0000:0000:0000:0000:0000 * /16 -> ffff:0000:0000:0000:0000:0000:0000:0000 * /32 -> ffff:ffff:0000:0000:0000:0000:0000:0000 * ... * /128 -> ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff */ memset(&inaddr.ipv6, 0, sizeof(struct sockaddr_in6)); for (i = 0; i < 8 && shift >= 16; i++, shift -= 16) { inaddr.ipv6.s6_addr16[i] = 0xffff; } if (shift > 16 || (shift > 0 && i >= 8)) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } /* /0 -> 0x0000 * /1 -> 0x8000 * /2 -> 0xc000 * ... * /16 -> 0xffff */ if (shift > 0) { inaddr.ipv6.s6_addr16[i] = htons(0xffff << (16 - shift)); } } #endif } else { /* Slash notation not used.. mask should follow the target address */ ret = inet_pton(family, argv[2], &inaddr); if (ret != 1) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); goto errout_with_sockfd; } } /* Format the netmask sockaddr instance */ memset(&netmask, 0, sizeof(netmask)); #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (family == PF_INET) #endif { netmask.ipv4.sin_family = AF_INET; netmask.ipv4.sin_addr = inaddr.ipv4; } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { netmask.ipv6.sin6_family = AF_INET6; memcpy(&netmask.ipv6.sin6_addr, &inaddr.ipv6, sizeof(struct in6_addr)); } #endif /* Then delete the route */ ret = delroute(sockfd, (FAR struct sockaddr_storage *)&target, (FAR struct sockaddr_storage *)&netmask); if (ret < 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "delroute", NSH_ERRNO); goto errout_with_sockfd; } close(sockfd); return OK; errout_with_sockfd: close(sockfd); errout: return ERROR; } #endif /* !CONFIG_NSH_DISABLE_DELROUTE */ /**************************************************************************** * Name: cmd_route * * nsh> route <ipv4|ipv6> * ****************************************************************************/ #ifndef CONFIG_NSH_DISABLE_ROUTE int cmd_route(FAR struct nsh_vtbl_s *vtbl, int argc, char **argv) { #if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6) bool ipv6 = false; #endif /* If both IPv4 and IPv6 and defined then there will be exactly one * argument. Otherwise no arguments are required, but an addition * argument is accepted. */ #if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6) if (strcmp(argv[1], "ipv4") == 0) { ipv6 = false; } else if (strcmp(argv[1], "ipv6") == 0) { ipv6 = true; } else { nsh_error(vtbl, g_fmtarginvalid, argv[0]); return ERROR; } #elif defined(CONFIG_NET_IPv4) if (argc == 2 && strcmp(argv[1], "ipv4") != 0) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); return ERROR; } #else if (argc == 2 && strcmp(argv[1], "ipv6") != 0) { nsh_error(vtbl, g_fmtarginvalid, argv[0]); return ERROR; } #endif /* Then just cat the procfs file containing the routing table info */ #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (!ipv6) #endif { return nsh_catfile(vtbl, argv[0], CONFIG_NSH_PROC_MOUNTPOINT "/net/route/ipv4"); } #endif #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { return nsh_catfile(vtbl, argv[0], CONFIG_NSH_PROC_MOUNTPOINT "/net/route/ipv6"); } #endif return ERROR; /* Shouldn't get here */ } #endif #endif /* CONFIG_NET && CONFIG_NET_ROUTE */
23
78
0.555374
ec7630d427a784348d3be0d7c61a9c5c4e218ce0
1,494
h
C
IMFoundation.framework/IMRemoteObject.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
IMFoundation.framework/IMRemoteObject.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
IMFoundation.framework/IMRemoteObject.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
1
2021-10-08T07:40:53.000Z
2021-10-08T07:40:53.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/IMFoundation.framework/IMFoundation */ @interface IMRemoteObject : NSObject { id _internal; } @property (nonatomic, readonly) NSObject<OS_xpc_object> *connection; @property (nonatomic, readonly) bool isValid; @property (nonatomic) int pid; @property (nonatomic, readonly) NSString *portName; @property (nonatomic, retain) NSString *processName; + (void)_registerIMRemoteObject:(id)arg1; + (id)_remoteObjects; + (void)_unregisterIMRemoteObject:(id)arg1; + (void)initialize; - (void)_cleanupMachBitsCanPost:(bool)arg1; - (id)_initWithConnection:(id)arg1 portName:(id)arg2 protocol:(id)arg3 alreadyConfigured:(bool)arg4 forceSecureCoding:(bool)arg5; - (void)_portDidBecomeInvalid; - (id)_queue; - (void)_systemShutdown:(id)arg1; - (id)connection; - (void)dealloc; - (id)description; - (void)forwardInvocation:(id)arg1; - (unsigned long long)forwardXPCObject:(id)arg1 messageContext:(id)arg2; - (id)initWithConnection:(id)arg1 protocol:(id)arg2; - (id)initWithConnection:(id)arg1 protocol:(id)arg2 alreadyConfigured:(bool)arg3; - (id)initWithConnection:(id)arg1 protocol:(id)arg2 alreadyConfigured:(bool)arg3 forceSecureCoding:(bool)arg4; - (id)initWithPortName:(id)arg1 protocol:(id)arg2; - (void)invalidate; - (bool)isValid; - (id)methodSignatureForSelector:(SEL)arg1; - (int)pid; - (id)portName; - (id)processName; - (void)setPid:(int)arg1; - (void)setPortName:(id)arg1; - (void)setProcessName:(id)arg1; @end
33.2
129
0.761044
ea89cb93f55ae69473801d7e89630a50b945d012
15,946
h
C
mi8/drivers/power/supply/qcom/fg-core.h
wqk317/mi8_kernel_source
e3482d1a7ea6021de2fc8f3178496b4b043bb727
[ "MIT" ]
null
null
null
mi8/drivers/power/supply/qcom/fg-core.h
wqk317/mi8_kernel_source
e3482d1a7ea6021de2fc8f3178496b4b043bb727
[ "MIT" ]
null
null
null
mi8/drivers/power/supply/qcom/fg-core.h
wqk317/mi8_kernel_source
e3482d1a7ea6021de2fc8f3178496b4b043bb727
[ "MIT" ]
null
null
null
/* Copyright (c) 2016-2018, The Linux Foundation. All rights reserved. * Copyright (C) 2019 XiaoMi, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __FG_CORE_H__ #define __FG_CORE_H__ #include <linux/alarmtimer.h> #include <linux/atomic.h> #include <linux/bitops.h> #include <linux/debugfs.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/err.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/alarmtimer.h> #include <linux/power_supply.h> #include <linux/regmap.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/string_helpers.h> #include <linux/types.h> #include <linux/uaccess.h> #include <linux/pmic-voter.h> #define fg_dbg(chip, reason, fmt, ...) \ do { \ if (*chip->debug_mask & (reason)) \ pr_info(fmt, ##__VA_ARGS__); \ else \ pr_debug(fmt, ##__VA_ARGS__); \ } while (0) #define is_between(left, right, value) \ (((left) >= (right) && (left) >= (value) \ && (value) >= (right)) \ || ((left) <= (right) && (left) <= (value) \ && (value) <= (right))) /* Awake votable reasons */ #define SRAM_READ "fg_sram_read" #define SRAM_WRITE "fg_sram_write" #define PROFILE_LOAD "fg_profile_load" #define TTF_PRIMING "fg_ttf_priming" #define FG_ESR_VOTER "fg_esr_voter" /* Delta BSOC irq votable reasons */ #define DELTA_BSOC_IRQ_VOTER "fg_delta_bsoc_irq" /* Battery missing irq votable reasons */ #define BATT_MISS_IRQ_VOTER "fg_batt_miss_irq" #define ESR_FCC_VOTER "fg_esr_fcc" #define DEBUG_PRINT_BUFFER_SIZE 64 /* 3 byte address + 1 space character */ #define ADDR_LEN 4 /* Format is 'XX ' */ #define CHARS_PER_ITEM 3 /* 4 data items per line */ #define ITEMS_PER_LINE 4 #define MAX_LINE_LENGTH (ADDR_LEN + (ITEMS_PER_LINE * \ CHARS_PER_ITEM) + 1) \ #define NUM_PARTITIONS 3 #define FG_SRAM_ADDRESS_MAX 255 #define FG_SRAM_LEN 504 #define PROFILE_LEN 224 #define PROFILE_COMP_LEN 148 #define BUCKET_COUNT 8 #define BUCKET_SOC_PCT (256 / BUCKET_COUNT) #define KI_COEFF_MAX 62200 #define KI_COEFF_SOC_LEVELS 3 #define SLOPE_LIMIT_COEFF_MAX 31 #define BATT_THERM_NUM_COEFFS 3 #define MAX_CC_STEPS 20 #define VBAT_RESTART_FG_EMPTY_UV 3700000 #define TEMP_THR_RESTART_FG 150 #define RESTART_FG_START_WORK_MS 1000 #define RESTART_FG_WORK_MS 2000 enum prof_load_status { PROFILE_MISSING, PROFILE_LOADED, PROFILE_SKIPPED, PROFILE_NOT_LOADED, }; /* Debug flag definitions */ enum fg_debug_flag { FG_IRQ = BIT(0), /* Show interrupts */ FG_STATUS = BIT(1), /* Show FG status changes */ FG_POWER_SUPPLY = BIT(2), /* Show POWER_SUPPLY */ FG_SRAM_WRITE = BIT(3), /* Show SRAM writes */ FG_SRAM_READ = BIT(4), /* Show SRAM reads */ FG_BUS_WRITE = BIT(5), /* Show REGMAP writes */ FG_BUS_READ = BIT(6), /* Show REGMAP reads */ FG_CAP_LEARN = BIT(7), /* Show capacity learning */ FG_TTF = BIT(8), /* Show time to full */ }; enum awake_reasons { FG_SW_ESR_WAKE = BIT(0), FG_STATUS_NOTIFY_WAKE = BIT(1), }; /* SRAM access */ enum sram_access_flags { FG_IMA_DEFAULT = 0, FG_IMA_ATOMIC = BIT(0), FG_IMA_NO_WLOCK = BIT(1), }; /* JEITA */ enum jeita_levels { JEITA_COLD = 0, JEITA_COOL, JEITA_WARM, JEITA_HOT, NUM_JEITA_LEVELS, }; /* FG irqs */ enum fg_irq_index { MSOC_FULL_IRQ = 0, MSOC_HIGH_IRQ, MSOC_EMPTY_IRQ, MSOC_LOW_IRQ, MSOC_DELTA_IRQ, BSOC_DELTA_IRQ, SOC_READY_IRQ, SOC_UPDATE_IRQ, BATT_TEMP_DELTA_IRQ, BATT_MISSING_IRQ, ESR_DELTA_IRQ, VBATT_LOW_IRQ, VBATT_PRED_DELTA_IRQ, DMA_GRANT_IRQ, MEM_XCP_IRQ, IMA_RDY_IRQ, FG_IRQ_MAX, }; /* * List of FG_SRAM parameters. Please add a parameter only if it is an entry * that will be used either to configure an entity (e.g. termination current) * which might need some encoding (or) it is an entry that will be read from * SRAM and decoded (e.g. CC_SOC_SW) for SW to use at various places. For * generic read/writes to SRAM registers, please use fg_sram_read/write APIs * directly without adding an entry here. */ enum fg_sram_param_id { FG_SRAM_BATT_SOC = 0, FG_SRAM_FULL_SOC, FG_SRAM_VOLTAGE_PRED, FG_SRAM_OCV, FG_SRAM_ESR, FG_SRAM_RSLOW, FG_SRAM_ALG_FLAGS, FG_SRAM_CC_SOC, FG_SRAM_CC_SOC_SW, FG_SRAM_ACT_BATT_CAP, FG_SRAM_TIMEBASE, /* Entries below here are configurable during initialization */ FG_SRAM_CUTOFF_VOLT, FG_SRAM_EMPTY_VOLT, FG_SRAM_VBATT_LOW, FG_SRAM_FLOAT_VOLT, FG_SRAM_VBATT_FULL, FG_SRAM_ESR_TIMER_DISCHG_MAX, FG_SRAM_ESR_TIMER_DISCHG_INIT, FG_SRAM_ESR_TIMER_CHG_MAX, FG_SRAM_ESR_TIMER_CHG_INIT, FG_SRAM_ESR_PULSE_THRESH, FG_SRAM_SYS_TERM_CURR, FG_SRAM_CHG_TERM_CURR, FG_SRAM_CHG_TERM_BASE_CURR, FG_SRAM_CUTOFF_CURR, FG_SRAM_DELTA_MSOC_THR, FG_SRAM_DELTA_BSOC_THR, FG_SRAM_RECHARGE_SOC_THR, FG_SRAM_SYNC_SLEEP_THR, FG_SRAM_RECHARGE_VBATT_THR, FG_SRAM_KI_COEFF_LOW_DISCHG, FG_SRAM_KI_COEFF_MED_DISCHG, FG_SRAM_KI_COEFF_HI_DISCHG, FG_SRAM_KI_COEFF_HI_CHG, FG_SRAM_KI_COEFF_FULL_SOC, FG_SRAM_ESR_TIGHT_FILTER, FG_SRAM_ESR_BROAD_FILTER, FG_SRAM_SLOPE_LIMIT, FG_SRAM_MAX, }; struct fg_sram_param { u16 addr_word; int addr_byte; u8 len; int value; int numrtr; int denmtr; int offset; void (*encode)(struct fg_sram_param *sp, enum fg_sram_param_id id, int val, u8 *buf); int (*decode)(struct fg_sram_param *sp, enum fg_sram_param_id id, int val); }; struct fg_dma_address { /* Starting word address of the partition */ u16 partition_start; /* Last word address of the partition */ u16 partition_end; /* * Byte offset in the FG_DMA peripheral that maps to the partition_start * in SRAM */ u16 spmi_addr_base; }; enum fg_alg_flag_id { ALG_FLAG_SOC_LT_OTG_MIN = 0, ALG_FLAG_SOC_LT_RECHARGE, ALG_FLAG_IBATT_LT_ITERM, ALG_FLAG_IBATT_GT_HPM, ALG_FLAG_IBATT_GT_UPM, ALG_FLAG_VBATT_LT_RECHARGE, ALG_FLAG_VBATT_GT_VFLOAT, ALG_FLAG_MAX, }; struct fg_alg_flag { char *name; u8 bit; bool invalid; }; enum wa_flags { PMI8998_V1_REV_WA = BIT(0), PM660_TSMC_OSC_WA = BIT(1), }; enum slope_limit_status { LOW_TEMP_DISCHARGE = 0, LOW_TEMP_CHARGE, HIGH_TEMP_DISCHARGE, HIGH_TEMP_CHARGE, SLOPE_LIMIT_NUM_COEFFS, }; enum esr_filter_status { ROOM_TEMP = 1, LOW_TEMP, RELAX_TEMP, }; enum esr_timer_config { TIMER_RETRY = 0, TIMER_MAX, NUM_ESR_TIMERS, }; enum ttf_mode { TTF_MODE_NORMAL = 0, TTF_MODE_QNOVO, }; struct optimize_sram_data { int addr; int offset; int val; }; /* DT parameters for FG device */ struct fg_dt_props { bool force_load_profile; bool hold_soc_while_full; bool linearize_soc; bool auto_recharge_soc; bool use_esr_sw; bool disable_esr_pull_dn; bool disable_fg_twm; int cutoff_volt_mv; int empty_volt_mv; int vbatt_low_thr_mv; int chg_term_curr_ma; int chg_term_base_curr_ma; int sys_term_curr_ma; int cutoff_curr_ma; int delta_soc_thr; int recharge_soc_thr; int recharge_volt_thr_mv; int rsense_sel; int esr_timer_charging[NUM_ESR_TIMERS]; int esr_timer_awake[NUM_ESR_TIMERS]; int esr_timer_asleep[NUM_ESR_TIMERS]; int esr_timer_shutdown[NUM_ESR_TIMERS]; int rconn_mohms; int esr_clamp_mohms; int cl_start_soc; int cl_max_temp; int cl_min_temp; int cl_max_cap_inc; int cl_max_cap_dec; int cl_max_cap_limit; int cl_min_cap_limit; int jeita_hyst_temp; int batt_temp_delta; int esr_flt_switch_temp; int esr_tight_flt_upct; int esr_broad_flt_upct; int esr_tight_lt_flt_upct; int esr_broad_lt_flt_upct; int esr_flt_rt_switch_temp; int esr_tight_rt_flt_upct; int esr_broad_rt_flt_upct; int slope_limit_temp; int esr_pulse_thresh_ma; int esr_meas_curr_ma; int sync_sleep_threshold_ma; int bmd_en_delay_ms; bool optimize_sram; struct optimize_sram_data *optimize_sram_seq; int optimize_sram_seq_len; int ki_coeff_full_soc_dischg; int ki_coeff_hi_chg; int jeita_thresholds[NUM_JEITA_LEVELS]; int ki_coeff_soc[KI_COEFF_SOC_LEVELS]; int ki_coeff_low_dischg[KI_COEFF_SOC_LEVELS]; int ki_coeff_med_dischg[KI_COEFF_SOC_LEVELS]; int ki_coeff_hi_dischg[KI_COEFF_SOC_LEVELS]; int slope_limit_coeffs[SLOPE_LIMIT_NUM_COEFFS]; u8 batt_therm_coeffs[BATT_THERM_NUM_COEFFS]; }; /* parameters from battery profile */ struct fg_batt_props { const char *batt_type_str; char *batt_profile; int float_volt_uv; int vbatt_full_mv; int fastchg_curr_ma; int nom_cap_uah; }; struct fg_cyc_ctr_data { bool en; bool started[BUCKET_COUNT]; u16 count[BUCKET_COUNT]; u8 last_soc[BUCKET_COUNT]; char counter[BUCKET_COUNT * 8]; int id; struct mutex lock; }; struct fg_cap_learning { bool active; int init_cc_soc_sw; int64_t nom_cap_uah; int64_t init_cc_uah; int64_t final_cc_uah; int64_t learned_cc_uah; struct mutex lock; }; struct fg_irq_info { const char *name; const irq_handler_t handler; bool wakeable; int irq; }; struct fg_circ_buf { int arr[10]; int size; int head; }; struct fg_cc_step_data { int arr[MAX_CC_STEPS]; int sel; }; struct fg_pt { s32 x; s32 y; }; struct ttf { struct fg_circ_buf ibatt; struct fg_circ_buf vbatt; struct fg_cc_step_data cc_step; struct mutex lock; int mode; int last_ttf; s64 last_ms; }; static const struct fg_pt fg_ln_table[] = { { 1000, 0 }, { 2000, 693 }, { 4000, 1386 }, { 6000, 1792 }, { 8000, 2079 }, { 16000, 2773 }, { 32000, 3466 }, { 64000, 4159 }, { 128000, 4852 }, }; /* each tuple is - <temperature in degC, Timebase> */ static const struct fg_pt fg_tsmc_osc_table[] = { { -20, 395064 }, { -10, 398114 }, { 0, 401669 }, { 10, 404641 }, { 20, 408856 }, { 25, 412449 }, { 30, 416532 }, { 40, 420289 }, { 50, 425020 }, { 60, 430160 }, { 70, 434175 }, { 80, 439475 }, { 90, 444992 }, }; #define BATT_MA_AVG_SAMPLES 8 struct batt_params { bool update_now; int batt_raw_soc; int batt_soc; int samples_num; int samples_index; int batt_ma_avg_samples[BATT_MA_AVG_SAMPLES]; int batt_ma_avg; int batt_ma_prev; int batt_ma; int batt_mv; int batt_temp; struct timespec last_soc_change_time; }; struct fg_saved_data { union power_supply_propval val; unsigned long last_req_expires; }; struct fg_chip { struct thermal_zone_device *tz_dev; struct device *dev; struct pmic_revid_data *pmic_rev_id; struct regmap *regmap; struct dentry *dfs_root; struct power_supply *fg_psy; struct power_supply *batt_psy; struct power_supply *usb_psy; struct power_supply *dc_psy; struct power_supply *parallel_psy; struct power_supply *pc_port_psy; struct iio_channel *batt_id_chan; struct iio_channel *die_temp_chan; struct fg_irq_info *irqs; struct votable *awake_votable; struct votable *delta_bsoc_irq_en_votable; struct votable *batt_miss_irq_en_votable; struct votable *pl_disable_votable; struct fg_sram_param *sp; struct fg_dma_address *addr_map; struct fg_alg_flag *alg_flags; int *debug_mask; char batt_profile[PROFILE_LEN]; struct fg_dt_props dt; struct fg_batt_props bp; struct fg_cyc_ctr_data cyc_ctr; struct notifier_block nb; struct notifier_block twm_nb; struct fg_cap_learning cl; struct alarm esr_sw_timer; struct ttf ttf; struct mutex bus_lock; struct mutex sram_rw_lock; struct mutex charge_full_lock; struct mutex qnovo_esr_ctrl_lock; spinlock_t awake_lock; spinlock_t suspend_lock; u32 batt_soc_base; u32 batt_info_base; u32 mem_if_base; u32 rradc_base; u32 wa_flags; u32 esr_wakeup_ms; u32 awake_status; int batt_id_ohms; int ki_coeff_full_soc; int charge_status; int prev_charge_status; int charge_done; int charge_type; int online_status; int last_soc; int last_batt_temp; int health; int maint_soc; int delta_soc; int last_msoc; int last_recharge_volt_mv; int delta_temp_irq_count; int esr_timer_charging_default[NUM_ESR_TIMERS]; enum slope_limit_status slope_limit_sts; enum esr_filter_status esr_flt_sts; bool profile_available; bool profile_loaded; enum prof_load_status profile_load_status; bool battery_missing; bool fg_restarting; bool charge_full; bool recharge_soc_adjusted; bool ki_coeff_dischg_en; bool esr_fcc_ctrl_en; bool soc_reporting_ready; bool esr_flt_cold_temp_en; bool slope_limit_en; bool use_ima_single_mode; bool usb_present; bool twm_state; bool report_full; bool use_dma; bool qnovo_enable; bool empty_restart_fg; bool suspended; struct batt_params param; struct delayed_work soc_monitor_work; struct completion soc_update; struct completion soc_ready; struct delayed_work profile_load_work; struct work_struct status_change_work; struct work_struct esr_sw_work; struct delayed_work ttf_work; struct delayed_work esr_timer_config_work; struct delayed_work sram_dump_work; struct delayed_work soc_work; struct delayed_work pl_enable_work; struct work_struct esr_filter_work; struct alarm esr_filter_alarm; ktime_t last_delta_temp_time; struct delayed_work empty_restart_fg_work; struct fg_saved_data saved_data[POWER_SUPPLY_PROP_MAX]; }; /* Debugfs data structures are below */ /* Log buffer */ struct fg_log_buffer { size_t rpos; size_t wpos; size_t len; char data[0]; }; /* transaction parameters */ struct fg_trans { struct fg_chip *chip; struct mutex fg_dfs_lock; /* Prevent thread concurrency */ struct fg_log_buffer *log; u32 cnt; u16 addr; u32 offset; u8 *data; }; struct fg_dbgfs { struct debugfs_blob_wrapper help_msg; struct fg_chip *chip; struct dentry *root; u32 cnt; u32 addr; }; extern int fg_sram_write(struct fg_chip *chip, u16 address, u8 offset, u8 *val, int len, int flags); extern int fg_sram_read(struct fg_chip *chip, u16 address, u8 offset, u8 *val, int len, int flags); extern int fg_sram_masked_write(struct fg_chip *chip, u16 address, u8 offset, u8 mask, u8 val, int flags); extern int fg_interleaved_mem_read(struct fg_chip *chip, u16 address, u8 offset, u8 *val, int len); extern int fg_interleaved_mem_write(struct fg_chip *chip, u16 address, u8 offset, u8 *val, int len, bool atomic_access); extern int fg_direct_mem_read(struct fg_chip *chip, u16 address, u8 offset, u8 *val, int len); extern int fg_direct_mem_write(struct fg_chip *chip, u16 address, u8 offset, u8 *val, int len, bool atomic_access); extern int fg_read(struct fg_chip *chip, int addr, u8 *val, int len); extern int fg_write(struct fg_chip *chip, int addr, u8 *val, int len); extern int fg_masked_write(struct fg_chip *chip, int addr, u8 mask, u8 val); extern int fg_dump_regs(struct fg_chip *chip); extern int fg_ima_init(struct fg_chip *chip); extern int fg_dma_init(struct fg_chip *chip); extern int fg_clear_ima_errors_if_any(struct fg_chip *chip, bool check_hw_sts); extern int fg_clear_dma_errors_if_any(struct fg_chip *chip); extern int fg_debugfs_create(struct fg_chip *chip); extern void fill_string(char *str, size_t str_len, u8 *buf, int buf_len); extern void dump_sram(u8 *buf, int addr, int len); extern int64_t twos_compliment_extend(int64_t val, int s_bit_pos); extern s64 fg_float_decode(u16 val); extern bool is_input_present(struct fg_chip *chip); extern bool is_qnovo_en(struct fg_chip *chip); extern void fg_circ_buf_add(struct fg_circ_buf *buf, int val); extern void fg_circ_buf_clr(struct fg_circ_buf *buf); extern int fg_circ_buf_avg(struct fg_circ_buf *buf, int *avg); extern int fg_circ_buf_median(struct fg_circ_buf *buf, int *median); extern int fg_lerp(const struct fg_pt *pts, size_t tablesize, s32 input, s32 *output); void fg_stay_awake(struct fg_chip *chip, int awake_reason); void fg_relax(struct fg_chip *chip, int awake_reason); #endif
25.111811
79
0.75693
c192c71a0c279f0cb0705ffc1498d916c5017c30
26,881
h
C
src/inc/quic_platform_winkernel.h
wfurt/msquic
507ac821992037ea3980b0908be7574006ab0339
[ "MIT" ]
1
2021-02-20T02:46:16.000Z
2021-02-20T02:46:16.000Z
src/inc/quic_platform_winkernel.h
zhxxzhf/msquic
587a6cee33847f0d454dfba191b87b697cfdb632
[ "MIT" ]
null
null
null
src/inc/quic_platform_winkernel.h
zhxxzhf/msquic
587a6cee33847f0d454dfba191b87b697cfdb632
[ "MIT" ]
null
null
null
/*++ Copyright (c) Microsoft Corporation. Licensed under the MIT License. Abstract: This file contains Windows Kernel Mode implementations of the QUIC Platform Interfaces. Environment: Windows kernel mode --*/ #pragma once #ifndef CX_PLATFORM_TYPE #error "Must be included from quic_platform.h" #endif #ifndef _KERNEL_MODE #error "Incorrectly including Windows Kernel Platform Header" #endif #pragma warning(push) // Don't care about OACR warnings in publics #pragma warning(disable:26036) #pragma warning(disable:26061) #pragma warning(disable:26071) #pragma warning(disable:28118) #pragma warning(disable:28196) #pragma warning(disable:28252) #pragma warning(disable:28253) #pragma warning(disable:28309) #include <ntifs.h> #include <ntverp.h> #include <ntstrsafe.h> #include <wdf.h> #include <netioapi.h> #include <wsk.h> #include <bcrypt.h> #include <intrin.h> #include <msquic_winkernel.h> #pragma warning(pop) #if defined(__cplusplus) extern "C" { #endif _IRQL_requires_max_(PASSIVE_LEVEL) NTSYSAPI NTSTATUS NTAPI ZwClose( _In_ HANDLE Handle ); _IRQL_requires_max_(PASSIVE_LEVEL) NTSYSAPI NTSTATUS NTAPI ZwQueryInformationThread ( _In_ HANDLE ThreadHandle, _In_ THREADINFOCLASS ThreadInformationClass, _In_ PVOID ThreadInformation, _In_ ULONG ThreadInformationLength, _Out_opt_ PULONG ReturnLength ); #if DBG #define DEBUG 1 #endif #if _WIN64 #define QUIC_64BIT 1 #else #define QUIC_32BIT 1 #endif #ifndef KRTL_INIT_SEGMENT #define KRTL_INIT_SEGMENT "INIT" #endif #ifndef KRTL_PAGE_SEGMENT #define KRTL_PAGE_SEGMENT "PAGE" #endif #ifndef KRTL_NONPAGED_SEGMENT #define KRTL_NONPAGED_SEGMENT ".text" #endif // Use on code in the INIT segment. (Code is discarded after DriverEntry returns.) #define INITCODE __declspec(code_seg(KRTL_INIT_SEGMENT)) // Use on pageable functions. #define PAGEDX __declspec(code_seg(KRTL_PAGE_SEGMENT)) #define QUIC_CACHEALIGN DECLSPEC_CACHEALIGN // // Library Initialization // // // Called in DLLMain or DriverEntry. // INITCODE _IRQL_requires_max_(PASSIVE_LEVEL) void CxPlatSystemLoad( _In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath ); // // Called in DLLMain or DriverUnload. // PAGEDX _IRQL_requires_max_(PASSIVE_LEVEL) void CxPlatSystemUnload( void ); // // Initializes the PAL library. Calls to this and // CxPlatformUninitialize must be serialized and cannot overlap. // PAGEDX _IRQL_requires_max_(PASSIVE_LEVEL) QUIC_STATUS CxPlatInitialize( void ); // // Uninitializes the PAL library. Calls to this and // CxPlatformInitialize must be serialized and cannot overlap. // PAGEDX _IRQL_requires_max_(PASSIVE_LEVEL) void CxPlatUninitialize( void ); // // Static Analysis Interfaces // #define QUIC_NO_SANITIZE(X) #if defined(_PREFAST_) // _Analysis_assume_ will never result in any code generation for _exp, // so using it will not have runtime impact, even if _exp has side effects. #define CXPLAT_ANALYSIS_ASSUME(_exp) _Analysis_assume_(_exp) #else // _PREFAST_ // CXPLAT_ANALYSIS_ASSUME ensures that _exp is parsed in non-analysis compile. // On DEBUG, it's guaranteed to be parsed as part of the normal compile, but // with non-DEBUG, use __noop to ensure _exp is parseable but without code // generation. #if DEBUG #define CXPLAT_ANALYSIS_ASSUME(_exp) ((void) 0) #else // DEBUG #define CXPLAT_ANALYSIS_ASSUME(_exp) __noop(_exp) #endif // DEBUG #endif // _PREFAST_ #define CXPLAT_STATIC_ASSERT(X,Y) static_assert(X,Y) #define CXPLAT_ANALYSIS_ASSERT(X) __analysis_assert(X) // // Assertion Interfaces _IRQL_requires_max_(DISPATCH_LEVEL) void CxPlatLogAssert( _In_z_ const char* File, _In_ int Line, _In_z_ const char* Expr ); #define CXPLAT_WIDE_STRING(_str) L##_str #define CXPLAT_ASSERT_NOOP(_exp, _msg) \ (CXPLAT_ANALYSIS_ASSUME(_exp), 0) #define CXPLAT_ASSERT_LOG(_exp, _msg) \ (CXPLAT_ANALYSIS_ASSUME(_exp), \ ((!(_exp)) ? (CxPlatLogAssert(__FILE__, __LINE__, #_exp), FALSE) : TRUE)) #define CXPLAT_ASSERT_CRASH(_exp, _msg) \ (CXPLAT_ANALYSIS_ASSUME(_exp), \ ((!(_exp)) ? \ (CxPlatLogAssert(__FILE__, __LINE__, #_exp), \ __annotation(L"Debug", L"AssertFail", _msg), \ DbgRaiseAssertionFailure(), FALSE) : \ TRUE)) // // MsQuic uses three types of asserts: // // CXPLAT_DBG_ASSERT - Asserts that are too expensive to evaluate all the time. // CXPLAT_TEL_ASSERT - Asserts that are acceptable to always evaluate, but not // always crash the system. // CXPLAT_FRE_ASSERT - Asserts that must always crash the system. // #if DEBUG #define CXPLAT_DBG_ASSERT(_exp) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(#_exp)) #define CXPLAT_DBG_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg)) #else #define CXPLAT_DBG_ASSERT(_exp) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(#_exp)) #define CXPLAT_DBG_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(_msg)) #endif #if DEBUG #define CXPLAT_TEL_ASSERT(_exp) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(#_exp)) #define CXPLAT_TEL_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg)) #define CXPLAT_TEL_ASSERTMSG_ARGS(_exp, _msg, _origin, _bucketArg1, _bucketArg2) \ CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg)) #elif QUIC_TELEMETRY_ASSERTS #define CXPLAT_TEL_ASSERT(_exp) CXPLAT_ASSERT_LOG(_exp, CXPLAT_WIDE_STRING(#_exp)) #define CXPLAT_TEL_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_LOG(_exp, CXPLAT_WIDE_STRING(_msg)) #define CXPLAT_TEL_ASSERTMSG_ARGS(_exp, _msg, _origin, _bucketArg1, _bucketArg2) \ CXPLAT_ASSERT_LOG(_exp, CXPLAT_WIDE_STRING(_msg)) #else #define CXPLAT_TEL_ASSERT(_exp) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(#_exp)) #define CXPLAT_TEL_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(_msg)) #define CXPLAT_TEL_ASSERTMSG_ARGS(_exp, _msg, _origin, _bucketArg1, _bucketArg2) \ CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(_msg)) #endif #define CXPLAT_FRE_ASSERT(_exp) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(#_exp)) #define CXPLAT_FRE_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg)) // // Verifier is enabled. // #define CxPlatVerifierEnabled(Flags) NT_SUCCESS(MmIsVerifierEnabled((PULONG)&Flags)) #define CxPlatVerifierEnabledByAddr(Address) MmIsDriverVerifyingByAddress(Address) // // Debugger check. // #define CxPlatDebuggerPresent() KD_DEBUGGER_ENABLED // // Interrupt ReQuest Level // #define CXPLAT_IRQL() KeGetCurrentIrql() #define CXPLAT_PASSIVE_CODE() CXPLAT_DBG_ASSERT(CXPLAT_IRQL() == PASSIVE_LEVEL) // // Allocation/Memory Interfaces // extern uint64_t CxPlatTotalMemory; #define CXPLAT_ALLOC_PAGED(Size, Tag) ExAllocatePool2(POOL_FLAG_PAGED | POOL_FLAG_UNINITIALIZED, Size, Tag) #define CXPLAT_ALLOC_NONPAGED(Size, Tag) ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_UNINITIALIZED, Size, Tag) #define CXPLAT_FREE(Mem, Tag) ExFreePoolWithTag((void*)Mem, Tag) typedef LOOKASIDE_LIST_EX CXPLAT_POOL; #define CxPlatPoolInitialize(IsPaged, Size, Tag, Pool) \ ExInitializeLookasideListEx( \ Pool, \ NULL, \ NULL, \ (IsPaged) ? PagedPool : NonPagedPoolNx, \ 0, \ Size, \ Tag, \ 0) #define CxPlatPoolUninitialize(Pool) ExDeleteLookasideListEx(Pool) #define CxPlatPoolAlloc(Pool) ExAllocateFromLookasideListEx(Pool) #define CxPlatPoolFree(Pool, Entry) ExFreeToLookasideListEx(Pool, Entry) #define CxPlatZeroMemory RtlZeroMemory #define CxPlatCopyMemory RtlCopyMemory #define CxPlatMoveMemory RtlMoveMemory #define CxPlatSecureZeroMemory RtlSecureZeroMemory #define CxPlatByteSwapUint16 RtlUshortByteSwap #define CxPlatByteSwapUint32 RtlUlongByteSwap #define CxPlatByteSwapUint64 RtlUlonglongByteSwap // // Locking Interfaces // // // The following declares several currently unpublished shared locking // functions from Windows. // __drv_maxIRQL(APC_LEVEL) __drv_mustHoldCriticalRegion NTKERNELAPI VOID FASTCALL ExfAcquirePushLockExclusive( __inout __deref __drv_acquiresExclusiveResource(ExPushLockType) PEX_PUSH_LOCK PushLock ); __drv_maxIRQL(APC_LEVEL) __drv_mustHoldCriticalRegion NTKERNELAPI VOID FASTCALL ExfAcquirePushLockShared( __inout __deref __drv_acquiresExclusiveResource(ExPushLockType) PEX_PUSH_LOCK PushLock ); __drv_maxIRQL(DISPATCH_LEVEL) __drv_mustHoldCriticalRegion NTKERNELAPI VOID FASTCALL ExfReleasePushLockExclusive( __inout __deref __drv_releasesExclusiveResource(ExPushLockType) PEX_PUSH_LOCK PushLock ); __drv_maxIRQL(DISPATCH_LEVEL) __drv_mustHoldCriticalRegion NTKERNELAPI VOID FASTCALL ExfReleasePushLockShared( __inout __deref __drv_releasesExclusiveResource(ExPushLockType) PEX_PUSH_LOCK PushLock ); typedef EX_PUSH_LOCK CXPLAT_LOCK; #define CxPlatLockInitialize(Lock) ExInitializePushLock(Lock) #define CxPlatLockUninitialize(Lock) #define CxPlatLockAcquire(Lock) KeEnterCriticalRegion(); ExfAcquirePushLockExclusive(Lock) #define CxPlatLockRelease(Lock) ExfReleasePushLockExclusive(Lock); KeLeaveCriticalRegion() typedef struct CXPLAT_DISPATCH_LOCK { KSPIN_LOCK SpinLock; KIRQL PrevIrql; } CXPLAT_DISPATCH_LOCK; #define CxPlatDispatchLockInitialize(Lock) KeInitializeSpinLock(&(Lock)->SpinLock) #define CxPlatDispatchLockUninitialize(Lock) #if defined(_AMD64_) || defined(_ARM64_) #define CxPlatDispatchLockAcquire(Lock) (Lock)->PrevIrql = KeAcquireSpinLockRaiseToDpc(&(Lock)->SpinLock) #else #define CxPlatDispatchLockAcquire(Lock) KeAcquireSpinLock(&(Lock)->SpinLock, &(Lock)->PrevIrql) #endif #define CxPlatDispatchLockRelease(Lock) KeReleaseSpinLock(&(Lock)->SpinLock, (Lock)->PrevIrql) typedef EX_PUSH_LOCK CXPLAT_RW_LOCK; #define CxPlatRwLockInitialize(Lock) ExInitializePushLock(Lock) #define CxPlatRwLockUninitialize(Lock) #define CxPlatRwLockAcquireShared(Lock) KeEnterCriticalRegion(); ExfAcquirePushLockShared(Lock) #define CxPlatRwLockAcquireExclusive(Lock) KeEnterCriticalRegion(); ExfAcquirePushLockExclusive(Lock) #define CxPlatRwLockReleaseShared(Lock) ExfReleasePushLockShared(Lock); KeLeaveCriticalRegion() #define CxPlatRwLockReleaseExclusive(Lock) ExfReleasePushLockExclusive(Lock); KeLeaveCriticalRegion() typedef struct CXPLAT_DISPATCH_RW_LOCK { EX_SPIN_LOCK SpinLock; KIRQL PrevIrql; } CXPLAT_DISPATCH_RW_LOCK; #define CxPlatDispatchRwLockInitialize(Lock) (Lock)->SpinLock = 0 #define CxPlatDispatchRwLockUninitialize(Lock) #define CxPlatDispatchRwLockAcquireShared(Lock) (Lock)->PrevIrql = ExAcquireSpinLockShared(&(Lock)->SpinLock) #define CxPlatDispatchRwLockAcquireExclusive(Lock) (Lock)->PrevIrql = ExAcquireSpinLockExclusive(&(Lock)->SpinLock) #define CxPlatDispatchRwLockReleaseShared(Lock) ExReleaseSpinLockShared(&(Lock)->SpinLock, (Lock)->PrevIrql) #define CxPlatDispatchRwLockReleaseExclusive(Lock) ExReleaseSpinLockExclusive(&(Lock)->SpinLock, (Lock)->PrevIrql) // // Reference Count Interface // #if defined(_X86_) || defined(_AMD64_) #define QuicBarrierAfterInterlock() #elif defined(_ARM64_) #define QuicBarrierAfterInterlock() __dmb(_ARM64_BARRIER_ISH) #elif defined(_ARM_) #define QuicBarrierAfterInterlock() __dmb(_ARM_BARRIER_ISH) #else #error Unsupported architecture. #endif #if defined (_WIN64) #define QuicIncrementLongPtrNoFence InterlockedIncrementNoFence64 #define QuicDecrementLongPtrRelease InterlockedDecrementRelease64 #define QuicCompareExchangeLongPtrNoFence InterlockedCompareExchangeNoFence64 #define QuicReadLongPtrNoFence ReadNoFence64 #else #define QuicIncrementLongPtrNoFence InterlockedIncrementNoFence #define QuicDecrementLongPtrRelease InterlockedDecrementRelease #define QuicCompareExchangeLongPtrNoFence InterlockedCompareExchangeNoFence #define QuicReadLongPtrNoFence ReadNoFence #endif typedef LONG_PTR CXPLAT_REF_COUNT; inline void CxPlatRefInitialize( _Out_ CXPLAT_REF_COUNT* RefCount ) { *RefCount = 1; } #define CxPlatRefUninitialize(RefCount) inline void CxPlatRefIncrement( _Inout_ CXPLAT_REF_COUNT* RefCount ) { if (QuicIncrementLongPtrNoFence(RefCount) > 1) { return; } __fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT); } inline BOOLEAN CxPlatRefIncrementNonZero( _Inout_ volatile CXPLAT_REF_COUNT *RefCount, _In_ ULONG Bias ) { CXPLAT_REF_COUNT NewValue; CXPLAT_REF_COUNT OldValue; PrefetchForWrite(RefCount); OldValue = QuicReadLongPtrNoFence(RefCount); for (;;) { NewValue = OldValue + Bias; if ((ULONG_PTR)NewValue > Bias) { NewValue = QuicCompareExchangeLongPtrNoFence(RefCount, NewValue, OldValue); if (NewValue == OldValue) { return TRUE; } OldValue = NewValue; } else if ((ULONG_PTR)NewValue == Bias) { return FALSE; } else { __fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT); return FALSE; } } } inline BOOLEAN CxPlatRefDecrement( _Inout_ CXPLAT_REF_COUNT* RefCount ) { CXPLAT_REF_COUNT NewValue; // // A release fence is required to ensure all guarded memory accesses are // complete before any thread can begin destroying the object. // NewValue = QuicDecrementLongPtrRelease(RefCount); if (NewValue > 0) { return FALSE; } else if (NewValue == 0) { // // An acquire fence is required before object destruction to ensure // that the destructor cannot observe values changing on other threads. // QuicBarrierAfterInterlock(); return TRUE; } __fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT); return FALSE; } // // Event Interfaces // typedef KEVENT CXPLAT_EVENT; #define CxPlatEventInitialize(Event, ManualReset, InitialState) \ KeInitializeEvent(Event, ManualReset ? NotificationEvent : SynchronizationEvent, InitialState) #define CxPlatEventUninitialize(Event) UNREFERENCED_PARAMETER(Event) #define CxPlatEventSet(Event) KeSetEvent(&(Event), IO_NO_INCREMENT, FALSE) #define CxPlatEventReset(Event) KeResetEvent(&(Event)) #define CxPlatEventWaitForever(Event) \ KeWaitForSingleObject(&(Event), Executive, KernelMode, FALSE, NULL) inline NTSTATUS _CxPlatEventWaitWithTimeout( _In_ CXPLAT_EVENT* Event, _In_ uint32_t TimeoutMs ) { LARGE_INTEGER Timeout100Ns; Timeout100Ns.QuadPart = Int32x32To64(TimeoutMs, -10000); return KeWaitForSingleObject(Event, Executive, KernelMode, FALSE, &Timeout100Ns); } #define CxPlatEventWaitWithTimeout(Event, TimeoutMs) \ (STATUS_SUCCESS == _CxPlatEventWaitWithTimeout(&Event, TimeoutMs)) // // Time Measurement Interfaces // // // Returns the worst-case system timer resolution (in us). // inline uint64_t CxPlatGetTimerResolution() { ULONG MaximumTime, MinimumTime, CurrentTime; ExQueryTimerResolution(&MaximumTime, &MinimumTime, &CurrentTime); return NS100_TO_US(MaximumTime); } // // Performance counter frequency. // extern uint64_t CxPlatPerfFreq; // // Returns the current time in platform specific time units. // inline uint64_t QuicTimePlat( void ) { return (uint64_t)KeQueryPerformanceCounter(NULL).QuadPart; } // // Converts platform time to microseconds. // inline uint64_t QuicTimePlatToUs64( uint64_t Count ) { // // Multiply by a big number (1000000, to convert seconds to microseconds) // and divide by a big number (CxPlatPerfFreq, to convert counts to secs). // // Avoid overflow with separate multiplication/division of the high and low // bits. Taken from TcpConvertPerformanceCounterToMicroseconds. // uint64_t High = (Count >> 32) * 1000000; uint64_t Low = (Count & 0xFFFFFFFF) * 1000000; return ((High / CxPlatPerfFreq) << 32) + ((Low + ((High % CxPlatPerfFreq) << 32)) / CxPlatPerfFreq); } // // Converts microseconds to platform time. // inline uint64_t CxPlatTimeUs64ToPlat( uint64_t TimeUs ) { uint64_t High = (TimeUs >> 32) * CxPlatPerfFreq; uint64_t Low = (TimeUs & 0xFFFFFFFF) * CxPlatPerfFreq; return ((High / 1000000) << 32) + ((Low + ((High % 1000000) << 32)) / 1000000); } #define CxPlatTimeUs64() QuicTimePlatToUs64(QuicTimePlat()) #define CxPlatTimeUs32() (uint32_t)CxPlatTimeUs64() #define CxPlatTimeMs64() US_TO_MS(CxPlatTimeUs64()) #define CxPlatTimeMs32() (uint32_t)CxPlatTimeMs64() #define UNIX_EPOCH_AS_FILE_TIME 0x19db1ded53e8000ll inline int64_t CxPlatTimeEpochMs64( ) { LARGE_INTEGER SystemTime; KeQuerySystemTime(&SystemTime); return NS100_TO_MS(SystemTime.QuadPart - UNIX_EPOCH_AS_FILE_TIME); } // // Returns the difference between two timestamps. // inline uint64_t CxPlatTimeDiff64( _In_ uint64_t T1, // First time measured _In_ uint64_t T2 // Second time measured ) { // // Assume no wrap around. // return T2 - T1; } // // Returns the difference between two timestamps. // inline uint32_t CxPlatTimeDiff32( _In_ uint32_t T1, // First time measured _In_ uint32_t T2 // Second time measured ) { if (T2 > T1) { return T2 - T1; } else { // Wrap around case. return T2 + (0xFFFFFFFF - T1) + 1; } } // // Returns TRUE if T1 came before T2. // inline BOOLEAN CxPlatTimeAtOrBefore64( _In_ uint64_t T1, _In_ uint64_t T2 ) { // // Assume no wrap around. // return T1 <= T2; } // // Returns TRUE if T1 came before T2. // inline BOOLEAN CxPlatTimeAtOrBefore32( _In_ uint32_t T1, _In_ uint32_t T2 ) { return (int32_t)(T1 - T2) <= 0; } _IRQL_requires_max_(PASSIVE_LEVEL) inline void CxPlatSleep( _In_ uint32_t DurationMs ) { CXPLAT_DBG_ASSERT(DurationMs != (uint32_t)-1); KTIMER SleepTimer; LARGE_INTEGER TimerValue; KeInitializeTimerEx(&SleepTimer, SynchronizationTimer); TimerValue.QuadPart = Int32x32To64(DurationMs, -10000); KeSetTimer(&SleepTimer, TimerValue, NULL); KeWaitForSingleObject(&SleepTimer, Executive, KernelMode, FALSE, NULL); } // // Create Thread Interfaces // typedef struct CXPLAT_THREAD_CONFIG { uint16_t Flags; uint16_t IdealProcessor; _Field_z_ const char* Name; KSTART_ROUTINE* Callback; void* Context; } CXPLAT_THREAD_CONFIG; typedef struct _ETHREAD *CXPLAT_THREAD; #define CXPLAT_THREAD_CALLBACK(FuncName, CtxVarName) \ _Function_class_(KSTART_ROUTINE) \ _IRQL_requires_same_ \ void \ FuncName( \ _In_ void* CtxVarName \ ) #define CXPLAT_THREAD_RETURN(Status) PsTerminateSystemThread(Status) inline QUIC_STATUS CxPlatThreadCreate( _In_ CXPLAT_THREAD_CONFIG* Config, _Out_ CXPLAT_THREAD* Thread ) { QUIC_STATUS Status; HANDLE ThreadHandle; Status = PsCreateSystemThread( &ThreadHandle, THREAD_ALL_ACCESS, NULL, NULL, NULL, Config->Callback, Config->Context); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { *Thread = NULL; goto Error; } Status = ObReferenceObjectByHandle( ThreadHandle, THREAD_ALL_ACCESS, *PsThreadType, KernelMode, (void**)Thread, NULL); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { *Thread = NULL; goto Cleanup; } PROCESSOR_NUMBER Processor, IdealProcessor; Status = KeGetProcessorNumberFromIndex( Config->IdealProcessor, &Processor); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { goto Cleanup; } IdealProcessor = Processor; if (Config->Flags & CXPLAT_THREAD_FLAG_SET_AFFINITIZE) { GROUP_AFFINITY Affinity; CxPlatZeroMemory(&Affinity, sizeof(Affinity)); Affinity.Group = Processor.Group; Affinity.Mask = (1ull << Processor.Number); Status = ZwSetInformationThread( ThreadHandle, ThreadGroupInformation, &Affinity, sizeof(Affinity)); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { goto Cleanup; } } else { // NUMA Node Affinity SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX Info; ULONG InfoLength = sizeof(Info); Status = KeQueryLogicalProcessorRelationship( &Processor, RelationNumaNode, &Info, &InfoLength); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { goto Cleanup; } Status = ZwSetInformationThread( ThreadHandle, ThreadGroupInformation, &Info.NumaNode.GroupMask, sizeof(GROUP_AFFINITY)); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { goto Cleanup; } } if (Config->Flags & CXPLAT_THREAD_FLAG_SET_IDEAL_PROC) { Status = ZwSetInformationThread( ThreadHandle, ThreadIdealProcessorEx, &IdealProcessor, // Don't pass in Processor because this overwrites on output. sizeof(IdealProcessor)); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); if (QUIC_FAILED(Status)) { goto Cleanup; } } if (Config->Flags & CXPLAT_THREAD_FLAG_HIGH_PRIORITY) { KeSetBasePriorityThread( (PKTHREAD)(*Thread), IO_NETWORK_INCREMENT + 1); } if (Config->Name) { DECLARE_UNICODE_STRING_SIZE(UnicodeName, 64); ULONG UnicodeNameLength = 0; Status = RtlUTF8ToUnicodeN( UnicodeName.Buffer, UnicodeName.MaximumLength, &UnicodeNameLength, Config->Name, (ULONG)strnlen(Config->Name, 64)); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); UnicodeName.Length = (USHORT)UnicodeNameLength; #define ThreadNameInformation ((THREADINFOCLASS)38) Status = ZwSetInformationThread( ThreadHandle, ThreadNameInformation, &UnicodeName, sizeof(UNICODE_STRING)); CXPLAT_DBG_ASSERT(QUIC_SUCCEEDED(Status)); Status = QUIC_STATUS_SUCCESS; } Cleanup: ZwClose(ThreadHandle); Error: return Status; } #define CxPlatThreadDelete(Thread) ObDereferenceObject(*(Thread)) #define CxPlatThreadWait(Thread) \ KeWaitForSingleObject( \ *(Thread), \ Executive, \ KernelMode, \ FALSE, \ NULL) typedef ULONG_PTR CXPLAT_THREAD_ID; #define CxPlatCurThreadID() ((CXPLAT_THREAD_ID)PsGetCurrentThreadId()) // // Processor Count and Index // #define CxPlatProcMaxCount() KeQueryMaximumProcessorCountEx(ALL_PROCESSOR_GROUPS) #define CxPlatProcActiveCount() KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS) #define CxPlatProcCurrentNumber() KeGetCurrentProcessorIndex() // // Rundown Protection Interfaces // typedef EX_RUNDOWN_REF CXPLAT_RUNDOWN_REF; #define CxPlatRundownInitialize(Rundown) ExInitializeRundownProtection(Rundown) #define CxPlatRundownInitializeDisabled(Rundown) (Rundown)->Count = EX_RUNDOWN_ACTIVE #define CxPlatRundownReInitialize(Rundown) ExReInitializeRundownProtection(Rundown) #define CxPlatRundownUninitialize(Rundown) #define CxPlatRundownAcquire(Rundown) ExAcquireRundownProtection(Rundown) #define CxPlatRundownRelease(Rundown) ExReleaseRundownProtection(Rundown) #define CxPlatRundownReleaseAndWait(Rundown) ExWaitForRundownProtectionRelease(Rundown) // // Crypto Interfaces // // // Returns cryptographically random bytes. // _IRQL_requires_max_(DISPATCH_LEVEL) QUIC_STATUS CxPlatRandom( _In_ uint32_t BufferLen, _Out_writes_bytes_(BufferLen) void* Buffer ); // // Silo interfaces // #define QUIC_SILO PESILO #define QUIC_SILO_INVALID ((PESILO)(void*)(LONG_PTR)-1) #define QuicSiloGetCurrentServer() PsGetCurrentServerSilo() #define QuicSiloAddRef(Silo) if (Silo != NULL) { ObReferenceObjectWithTag(Silo, QUIC_POOL_SILO); } #define QuicSiloRelease(Silo) if (Silo != NULL) { ObDereferenceObjectWithTag(Silo, QUIC_POOL_SILO); } #define QuicSiloAttach(Silo) PsAttachSiloToCurrentThread(Silo) #define QuicSiloDetatch(PrevSilo) PsDetachSiloFromCurrentThread(PrevSilo) // // Network Compartment ID interfaces // #define QUIC_COMPARTMENT_ID COMPARTMENT_ID #define QUIC_UNSPECIFIED_COMPARTMENT_ID UNSPECIFIED_COMPARTMENT_ID #define QUIC_DEFAULT_COMPARTMENT_ID DEFAULT_COMPARTMENT_ID COMPARTMENT_ID NdisGetThreadObjectCompartmentId( IN PETHREAD ThreadObject ); NTSTATUS NdisSetThreadObjectCompartmentId( IN PETHREAD ThreadObject, IN NET_IF_COMPARTMENT_ID CompartmentId ); inline QUIC_STATUS CxPlatSetCurrentThreadProcessorAffinity( _In_ uint16_t ProcessorIndex ) { PROCESSOR_NUMBER ProcInfo; QUIC_STATUS Status = KeGetProcessorNumberFromIndex( ProcessorIndex, &ProcInfo); if (QUIC_FAILED(Status)) { return Status; } GROUP_AFFINITY Affinity = {0}; Affinity.Mask = (KAFFINITY)(1ull << ProcInfo.Number); Affinity.Group = ProcInfo.Group; return ZwSetInformationThread( ZwCurrentThread(), ThreadGroupInformation, &Affinity, sizeof(Affinity)); } inline QUIC_STATUS CxPlatSetCurrentThreadGroupAffinity( _In_ uint16_t ProcessorGroup ) { GROUP_AFFINITY Affinity = {0}; GROUP_AFFINITY ExistingAffinity = {0}; QUIC_STATUS Status; if (QUIC_FAILED( Status = ZwQueryInformationThread( ZwCurrentThread(), ThreadGroupInformation, &ExistingAffinity, sizeof(ExistingAffinity), NULL))) { return Status; } Affinity.Mask = ExistingAffinity.Mask; Affinity.Group = ProcessorGroup; return ZwSetInformationThread( ZwCurrentThread(), ThreadGroupInformation, &Affinity, sizeof(Affinity)); } #define QuicCompartmentIdGetCurrent() NdisGetThreadObjectCompartmentId(PsGetCurrentThread()) #define QuicCompartmentIdSetCurrent(CompartmentId) \ NdisSetThreadObjectCompartmentId(PsGetCurrentThread(), CompartmentId) #define CXPLAT_CPUID(FunctionId, eax, ebx, ecx, dx) #if defined(__cplusplus) } #endif
27.097782
115
0.715673
1834246f3081dda474271f7ea98d5291f73d8b3b
9,664
c
C
common/cmd_fpga.c
beyondhenry/u-boot100askII
10ed681b7cc5dbcafe7bfb0e723e9ff92a799c4b
[ "Intel", "Unlicense" ]
2
2017-10-30T12:25:44.000Z
2019-08-25T09:01:38.000Z
common/cmd_fpga.c
beyondhenry/u-boot100askII
10ed681b7cc5dbcafe7bfb0e723e9ff92a799c4b
[ "Intel", "Unlicense" ]
null
null
null
common/cmd_fpga.c
beyondhenry/u-boot100askII
10ed681b7cc5dbcafe7bfb0e723e9ff92a799c4b
[ "Intel", "Unlicense" ]
4
2017-12-19T10:52:20.000Z
2019-08-25T09:01:40.000Z
/* * (C) Copyright 2000, 2001 * Rich Ireland, Enterasys Networks, rireland@enterasys.com. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ /* * FPGA support */ #include <common.h> #include <command.h> #if defined(CONFIG_CMD_NET) #include <net.h> #endif #include <fpga.h> #include <malloc.h> /* Local functions */ static int fpga_get_op (char *opstr); /* Local defines */ #define FPGA_NONE -1 #define FPGA_INFO 0 #define FPGA_LOAD 1 #define FPGA_LOADB 2 #define FPGA_DUMP 3 #define FPGA_LOADMK 4 /* Convert bitstream data and load into the fpga */ int fpga_loadbitstream(unsigned long dev, char* fpgadata, size_t size) { #if defined(CONFIG_FPGA_XILINX) unsigned int length; unsigned int swapsize; char buffer[80]; unsigned char *dataptr; unsigned int i; int rc; dataptr = (unsigned char *)fpgadata; /* skip the first bytes of the bitsteam, their meaning is unknown */ length = (*dataptr << 8) + *(dataptr+1); dataptr+=2; dataptr+=length; /* get design name (identifier, length, string) */ length = (*dataptr << 8) + *(dataptr+1); dataptr+=2; if (*dataptr++ != 0x61) { debug("%s: Design name identifier not recognized " "in bitstream\n", __func__); return FPGA_FAIL; } length = (*dataptr << 8) + *(dataptr+1); dataptr+=2; for(i=0;i<length;i++) buffer[i] = *dataptr++; printf(" design filename = \"%s\"\n", buffer); /* get part number (identifier, length, string) */ if (*dataptr++ != 0x62) { printf("%s: Part number identifier not recognized " "in bitstream\n", __func__); return FPGA_FAIL; } length = (*dataptr << 8) + *(dataptr+1); dataptr+=2; for(i=0;i<length;i++) buffer[i] = *dataptr++; printf(" part number = \"%s\"\n", buffer); /* get date (identifier, length, string) */ if (*dataptr++ != 0x63) { printf("%s: Date identifier not recognized in bitstream\n", __func__); return FPGA_FAIL; } length = (*dataptr << 8) + *(dataptr+1); dataptr+=2; for(i=0;i<length;i++) buffer[i] = *dataptr++; printf(" date = \"%s\"\n", buffer); /* get time (identifier, length, string) */ if (*dataptr++ != 0x64) { printf("%s: Time identifier not recognized in bitstream\n", __func__); return FPGA_FAIL; } length = (*dataptr << 8) + *(dataptr+1); dataptr+=2; for(i=0;i<length;i++) buffer[i] = *dataptr++; printf(" time = \"%s\"\n", buffer); /* get fpga data length (identifier, length) */ if (*dataptr++ != 0x65) { printf("%s: Data length identifier not recognized in bitstream\n", __func__); return FPGA_FAIL; } swapsize = ((unsigned int) *dataptr <<24) + ((unsigned int) *(dataptr+1) <<16) + ((unsigned int) *(dataptr+2) <<8 ) + ((unsigned int) *(dataptr+3) ) ; dataptr+=4; printf(" bytes in bitstream = %d\n", swapsize); rc = fpga_load(dev, dataptr, swapsize); return rc; #else printf("Bitstream support only for Xilinx devices\n"); return FPGA_FAIL; #endif } /* ------------------------------------------------------------------------- */ /* command form: * fpga <op> <device number> <data addr> <datasize> * where op is 'load', 'dump', or 'info' * If there is no device number field, the fpga environment variable is used. * If there is no data addr field, the fpgadata environment variable is used. * The info command requires no data address field. */ int do_fpga (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) { int op, dev = FPGA_INVALID_DEVICE; size_t data_size = 0; void *fpga_data = NULL; char *devstr = getenv ("fpga"); char *datastr = getenv ("fpgadata"); int rc = FPGA_FAIL; int wrong_parms = 0; #if defined (CONFIG_FIT) const char *fit_uname = NULL; ulong fit_addr; #endif if (devstr) dev = (int) simple_strtoul (devstr, NULL, 16); if (datastr) fpga_data = (void *) simple_strtoul (datastr, NULL, 16); switch (argc) { case 5: /* fpga <op> <dev> <data> <datasize> */ data_size = simple_strtoul (argv[4], NULL, 16); case 4: /* fpga <op> <dev> <data> */ #if defined(CONFIG_FIT) if (fit_parse_subimage (argv[3], (ulong)fpga_data, &fit_addr, &fit_uname)) { fpga_data = (void *)fit_addr; debug("* fpga: subimage '%s' from FIT image " "at 0x%08lx\n", fit_uname, fit_addr); } else #endif { fpga_data = (void *) simple_strtoul (argv[3], NULL, 16); debug("* fpga: cmdline image address = 0x%08lx\n", (ulong)fpga_data); } debug("%s: fpga_data = 0x%x\n", __func__, (uint) fpga_data); case 3: /* fpga <op> <dev | data addr> */ dev = (int) simple_strtoul (argv[2], NULL, 16); debug("%s: device = %d\n", __func__, dev); /* FIXME - this is a really weak test */ if ((argc == 3) && (dev > fpga_count ())) { /* must be buffer ptr */ debug("%s: Assuming buffer pointer in arg 3\n", __func__); #if defined(CONFIG_FIT) if (fit_parse_subimage (argv[2], (ulong)fpga_data, &fit_addr, &fit_uname)) { fpga_data = (void *)fit_addr; debug("* fpga: subimage '%s' from FIT image " "at 0x%08lx\n", fit_uname, fit_addr); } else #endif { fpga_data = (void *) dev; debug("* fpga: cmdline image address = " "0x%08lx\n", (ulong)fpga_data); } debug("%s: fpga_data = 0x%x\n", __func__, (uint) fpga_data); dev = FPGA_INVALID_DEVICE; /* reset device num */ } case 2: /* fpga <op> */ op = (int) fpga_get_op (argv[1]); break; default: debug("%s: Too many or too few args (%d)\n", __func__, argc); op = FPGA_NONE; /* force usage display */ break; } if (dev == FPGA_INVALID_DEVICE) { puts("FPGA device not specified\n"); op = FPGA_NONE; } switch (op) { case FPGA_NONE: case FPGA_INFO: break; case FPGA_LOAD: case FPGA_LOADB: case FPGA_DUMP: if (!fpga_data || !data_size) wrong_parms = 1; break; case FPGA_LOADMK: if (!fpga_data) wrong_parms = 1; break; } if (wrong_parms) { puts("Wrong parameters for FPGA request\n"); op = FPGA_NONE; } switch (op) { case FPGA_NONE: return CMD_RET_USAGE; case FPGA_INFO: rc = fpga_info (dev); break; case FPGA_LOAD: rc = fpga_load (dev, fpga_data, data_size); break; case FPGA_LOADB: rc = fpga_loadbitstream(dev, fpga_data, data_size); break; case FPGA_LOADMK: switch (genimg_get_format (fpga_data)) { case IMAGE_FORMAT_LEGACY: { image_header_t *hdr = (image_header_t *)fpga_data; ulong data; data = (ulong)image_get_data (hdr); data_size = image_get_data_size (hdr); rc = fpga_load (dev, (void *)data, data_size); } break; #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: { const void *fit_hdr = (const void *)fpga_data; int noffset; const void *fit_data; if (fit_uname == NULL) { puts ("No FIT subimage unit name\n"); return 1; } if (!fit_check_format (fit_hdr)) { puts ("Bad FIT image format\n"); return 1; } /* get fpga component image node offset */ noffset = fit_image_get_node (fit_hdr, fit_uname); if (noffset < 0) { printf ("Can't find '%s' FIT subimage\n", fit_uname); return 1; } /* verify integrity */ if (!fit_image_check_hashes (fit_hdr, noffset)) { puts ("Bad Data Hash\n"); return 1; } /* get fpga subimage data address and length */ if (fit_image_get_data (fit_hdr, noffset, &fit_data, &data_size)) { puts ("Could not find fpga subimage data\n"); return 1; } rc = fpga_load (dev, fit_data, data_size); } break; #endif default: puts ("** Unknown image type\n"); rc = FPGA_FAIL; break; } break; case FPGA_DUMP: rc = fpga_dump (dev, fpga_data, data_size); break; default: printf ("Unknown operation\n"); return CMD_RET_USAGE; } return (rc); } /* * Map op to supported operations. We don't use a table since we * would just have to relocate it from flash anyway. */ static int fpga_get_op (char *opstr) { int op = FPGA_NONE; if (!strcmp ("info", opstr)) { op = FPGA_INFO; } else if (!strcmp ("loadb", opstr)) { op = FPGA_LOADB; } else if (!strcmp ("load", opstr)) { op = FPGA_LOAD; } else if (!strcmp ("loadmk", opstr)) { op = FPGA_LOADMK; } else if (!strcmp ("dump", opstr)) { op = FPGA_DUMP; } if (op == FPGA_NONE) { printf ("Unknown fpga operation \"%s\"\n", opstr); } return op; } U_BOOT_CMD (fpga, 6, 1, do_fpga, "loadable FPGA image support", "[operation type] [device number] [image address] [image size]\n" "fpga operations:\n" " dump\t[dev]\t\t\tLoad device to memory buffer\n" " info\t[dev]\t\t\tlist known device information\n" " load\t[dev] [address] [size]\tLoad device from memory buffer\n" " loadb\t[dev] [address] [size]\t" "Load device from bitstream buffer (Xilinx only)\n" " loadmk [dev] [address]\tLoad device generated with mkimage" #if defined(CONFIG_FIT) "\n" "\tFor loadmk operating on FIT format uImage address must include\n" "\tsubimage unit name in the form of addr:<subimg_uname>" #endif );
25.166667
79
0.637107
4b82244ea03114d073e5fbed38501a00e4e1c5f3
2,591
h
C
altern_mass/include/equilibration.h
cmendl/hardpoint-systems
25c094270d6ebbf330a89b0ce071d70a3b19d530
[ "BSD-2-Clause" ]
1
2015-01-03T20:31:39.000Z
2015-01-03T20:31:39.000Z
altern_mass/include/equilibration.h
cmendl/hardpoint-systems
25c094270d6ebbf330a89b0ce071d70a3b19d530
[ "BSD-2-Clause" ]
null
null
null
altern_mass/include/equilibration.h
cmendl/hardpoint-systems
25c094270d6ebbf330a89b0ce071d70a3b19d530
[ "BSD-2-Clause" ]
2
2016-04-24T05:54:53.000Z
2020-10-26T21:05:21.000Z
// Equilibration of the lattice field variables: initialize elongations // and momenta randomly according to (micro-)canonical ensemble statistics. // // Copyright (c) 2014, Christian B. Mendl // All rights reserved. // http://christian.mendl.net // // This program is free software; you can redistribute it and/or // modify it under the terms of the Simplified BSD License // http://www.opensource.org/licenses/bsd-license.php // // References: // - Christian B. Mendl, Herbert Spohn // Current fluctuations for anharmonic chains in thermal equilibrium // arXiv:1412.4609 // // - Christian B. Mendl, Herbert Spohn // Equilibrium time-correlation functions for one-dimensional hard-point systems // Phys. Rev. E 90, 012147 (2014), arXiv:1403.0213 // // - Christian B. Mendl, Herbert Spohn // Dynamic correlators of Fermi-Pasta-Ulam chains and nonlinear fluctuating hydrodynamics // Phys. Rev. Lett. 111, 230601 (2013), arXiv:1305.1209 // // - Herbert Spohn // Nonlinear fluctuating hydrodynamics for anharmonic chains // J. Stat. Phys. 154, 1191-1227 (2014), arXiv:1305.6412 //_______________________________________________________________________________________________________________________ // #ifndef EQUILIBRATION_H #define EQUILIBRATION_H #include "field.h" #include "random.h" //_______________________________________________________________________________________________________________________ /// /// \brief Canonical ensemble parameters used for the fast evaluation of the /// inverse cumulative distribution function (CDF) of the spatial part, /// and the Gaussian distribution for the momentum /// typedef struct { double inv_q; //!< 1 / (pressure * beta) double sigma[2]; //!< 1 / sqrt(mass_i * beta), variance of the Gaussian distribution for the velocity } ensemble_params_t; void EnsembleParams_Fill(const double pressure, const double beta, const double mass[2], ensemble_params_t *params); double ElongationInverseCDF(const ensemble_params_t *params, const double t); double AverageElongation(const double pressure, const double beta); double AverageEnergy(const double beta); void EquilibrateCanonical(const double pressure, const double beta, randseed_t *seed, field_t *f); //_______________________________________________________________________________________________________________________ // double AveragePressure(const double elongation, const double energy); double AverageBeta(const double energy); void EquilibrateMicrocanonical(const double elongation, const double energy, randseed_t *seed, field_t *f); #endif
33.649351
121
0.784639
7674a557aa9fc9a85d77ba5fb065ee8d36b11fe2
1,243
h
C
src/bot/Malware/SharedKernel/Processors/startattackprocessor.h
jsdelivrbot/eductional-botnet
7cd021c176331cc0642f4b92a5a7b598df610c37
[ "MIT" ]
8
2017-05-01T19:37:15.000Z
2021-08-05T04:03:38.000Z
src/bot/Malware/SharedKernel/Processors/startattackprocessor.h
jsdelivrbot/eductional-botnet
7cd021c176331cc0642f4b92a5a7b598df610c37
[ "MIT" ]
null
null
null
src/bot/Malware/SharedKernel/Processors/startattackprocessor.h
jsdelivrbot/eductional-botnet
7cd021c176331cc0642f4b92a5a7b598df610c37
[ "MIT" ]
4
2018-01-25T19:26:02.000Z
2021-05-14T14:37:38.000Z
#ifndef STARTATTACKPROCESSOR_H #define STARTATTACKPROCESSOR_H #include <functional> #include "../Network/Messages/Server/startattackmessage.h" #include "../Workers/attackworkerbase.h" #include "messageprocessor.h" namespace processors { /** * @brief The class represents how the message AskInformationMessage is handled by the client. */ class StartAttackProcessor : public MessageProcessor<network::messages::server::StartAttackMessage> { Q_OBJECT public: /** * @brief Processes the given \e message. * @param message The message to process. * @param serverAdapter A reference to the server adapter. */ void process(std::shared_ptr<network::messages::server::StartAttackMessage> message, network::ServerAdapter &serverAdapter) override; private: /** * @brief Finds the method of attack based on the message. * @param methodOfAttack The name of the method of attack. * @return The return value is a functor that instantiates a child class of AttackWorkerBase. */ std::function<workers::AttackWorkerBase*(QUrl)> findAttackMethod(QString methodOfAttack); }; } #endif // STARTATTACKPROCESSOR_H
32.710526
141
0.693484
0addb2406e08423966f1f1a7b140cb96668ec39c
349
h
C
Chapter02/Signals_Slots/mainwindow.h
thacngoc/Qt5-CPP-GUI-Programming-Cookbook-Second-Edition
0c8ab6efb2c6c18782b2e85c6d8c7bbd22098bd8
[ "MIT" ]
94
2019-04-05T09:44:13.000Z
2022-03-29T04:04:37.000Z
Chapter02/Signals_Slots/mainwindow.h
thacngoc/Qt5-CPP-GUI-Programming-Cookbook-Second-Edition
0c8ab6efb2c6c18782b2e85c6d8c7bbd22098bd8
[ "MIT" ]
5
2019-10-28T10:21:27.000Z
2020-08-18T05:42:04.000Z
Chapter02/Signals_Slots/mainwindow.h
thacngoc/Qt5-CPP-GUI-Programming-Cookbook-Second-Edition
0c8ab6efb2c6c18782b2e85c6d8c7bbd22098bd8
[ "MIT" ]
54
2019-03-27T11:52:45.000Z
2022-03-24T09:21:51.000Z
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "myclass.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); signals: void doNow(); private slots: void on_pushButton_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
12.034483
42
0.733524
17eb1900d1500c909ae8aaa22300f2d10c0a2394
949
h
C
src/qt/robbieconaddressvalidator.h
robbiecon/RobbieCon
5d1a289ff69d5311db218c876a05b783d1d2adfd
[ "MIT" ]
null
null
null
src/qt/robbieconaddressvalidator.h
robbiecon/RobbieCon
5d1a289ff69d5311db218c876a05b783d1d2adfd
[ "MIT" ]
null
null
null
src/qt/robbieconaddressvalidator.h
robbiecon/RobbieCon
5d1a289ff69d5311db218c876a05b783d1d2adfd
[ "MIT" ]
null
null
null
// Copyright (c) 2011-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef ROBBIECON_QT_ROBBIECONADDRESSVALIDATOR_H #define ROBBIECON_QT_ROBBIECONADDRESSVALIDATOR_H #include <QValidator> /** Base58 entry widget validator, checks for valid characters and * removes some whitespace. */ class RobbieconAddressEntryValidator : public QValidator { Q_OBJECT public: explicit RobbieconAddressEntryValidator(QObject *parent); State validate(QString &input, int &pos) const; }; /** Robbiecon address widget validator, checks for a valid robbiecon address. */ class RobbieconAddressCheckValidator : public QValidator { Q_OBJECT public: explicit RobbieconAddressCheckValidator(QObject *parent); State validate(QString &input, int &pos) const; }; #endif // ROBBIECON_QT_ROBBIECONADDRESSVALIDATOR_H
26.361111
77
0.785037
a59640dd076051a86804b016fe3c62f15bf4f3f9
27,873
c
C
tinyc/lib/armeabi.c
alexnask/Nim
269b957e2968345a4c9a5037ab97ab726135a921
[ "MIT" ]
32
2018-05-14T23:26:54.000Z
2020-06-14T10:13:20.000Z
tinyc/lib/armeabi.c
alexnask/Nim
269b957e2968345a4c9a5037ab97ab726135a921
[ "MIT" ]
79
2018-08-01T11:50:45.000Z
2020-11-17T13:40:06.000Z
tinyc/lib/armeabi.c
alexnask/Nim
269b957e2968345a4c9a5037ab97ab726135a921
[ "MIT" ]
14
2021-01-08T05:05:19.000Z
2022-03-27T14:56:56.000Z
/* TCC ARM runtime EABI Copyright (C) 2013 Thomas Preud'homme Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifdef __TINYC__ #define INT_MIN (-2147483647 - 1) #define INT_MAX 2147483647 #define UINT_MAX 0xffffffff #define LONG_MIN (-2147483647L - 1) #define LONG_MAX 2147483647L #define ULONG_MAX 0xffffffffUL #define LLONG_MAX 9223372036854775807LL #define LLONG_MIN (-9223372036854775807LL - 1) #define ULLONG_MAX 0xffffffffffffffffULL #else #include <limits.h> #endif /* We rely on the little endianness and EABI calling convention for this to work */ typedef struct double_unsigned_struct { unsigned low; unsigned high; } double_unsigned_struct; typedef struct unsigned_int_struct { unsigned low; int high; } unsigned_int_struct; #define REGS_RETURN(name, type) \ void name ## _return(type ret) {} /* Float helper functions */ #define FLOAT_EXP_BITS 8 #define FLOAT_FRAC_BITS 23 #define DOUBLE_EXP_BITS 11 #define DOUBLE_FRAC_BITS 52 #define ONE_EXP(type) ((1 << (type ## _EXP_BITS - 1)) - 1) REGS_RETURN(unsigned_int_struct, unsigned_int_struct) REGS_RETURN(double_unsigned_struct, double_unsigned_struct) /* float -> integer: (sign) 1.fraction x 2^(exponent - exp_for_one) */ /* float to [unsigned] long long conversion */ #define DEFINE__AEABI_F2XLZ(name, with_sign) \ void __aeabi_ ## name(unsigned val) \ { \ int exp, high_shift, sign; \ double_unsigned_struct ret; \ \ /* compute sign */ \ sign = val >> 31; \ \ /* compute real exponent */ \ exp = val >> FLOAT_FRAC_BITS; \ exp &= (1 << FLOAT_EXP_BITS) - 1; \ exp -= ONE_EXP(FLOAT); \ \ /* undefined behavior if truncated value cannot be represented */ \ if (with_sign) { \ if (exp > 62) /* |val| too big, double cannot represent LLONG_MAX */ \ return; \ } else { \ if ((sign && exp >= 0) || exp > 63) /* if val < 0 || val too big */ \ return; \ } \ \ val &= (1 << FLOAT_FRAC_BITS) - 1; \ if (exp >= 32) { \ ret.high = 1 << (exp - 32); \ if (exp - 32 >= FLOAT_FRAC_BITS) { \ ret.high |= val << (exp - 32 - FLOAT_FRAC_BITS); \ ret.low = 0; \ } else { \ high_shift = FLOAT_FRAC_BITS - (exp - 32); \ ret.high |= val >> high_shift; \ ret.low = val << (32 - high_shift); \ } \ } else { \ ret.high = 0; \ ret.low = 1 << exp; \ if (exp > FLOAT_FRAC_BITS) \ ret.low |= val << (exp - FLOAT_FRAC_BITS); \ else \ ret.low |= val >> (FLOAT_FRAC_BITS - exp); \ } \ \ /* encode negative integer using 2's complement */ \ if (with_sign && sign) { \ ret.low = ~ret.low; \ ret.high = ~ret.high; \ if (ret.low == UINT_MAX) { \ ret.low = 0; \ ret.high++; \ } else \ ret.low++; \ } \ \ double_unsigned_struct_return(ret); \ } /* float to unsigned long long conversion */ DEFINE__AEABI_F2XLZ(f2ulz, 0) /* float to long long conversion */ DEFINE__AEABI_F2XLZ(f2lz, 1) /* double to [unsigned] long long conversion */ #define DEFINE__AEABI_D2XLZ(name, with_sign) \ void __aeabi_ ## name(double_unsigned_struct val) \ { \ int exp, high_shift, sign; \ double_unsigned_struct ret; \ \ /* compute sign */ \ sign = val.high >> 31; \ \ /* compute real exponent */ \ exp = (val.high >> (DOUBLE_FRAC_BITS - 32)); \ exp &= (1 << DOUBLE_EXP_BITS) - 1; \ exp -= ONE_EXP(DOUBLE); \ \ /* undefined behavior if truncated value cannot be represented */ \ if (with_sign) { \ if (exp > 62) /* |val| too big, double cannot represent LLONG_MAX */ \ return; \ } else { \ if ((sign && exp >= 0) || exp > 63) /* if val < 0 || val too big */ \ return; \ } \ \ val.high &= (1 << (DOUBLE_FRAC_BITS - 32)) - 1; \ if (exp >= 32) { \ ret.high = 1 << (exp - 32); \ if (exp >= DOUBLE_FRAC_BITS) { \ high_shift = exp - DOUBLE_FRAC_BITS; \ ret.high |= val.high << high_shift; \ ret.high |= val.low >> (32 - high_shift); \ ret.low = val.low << high_shift; \ } else { \ high_shift = DOUBLE_FRAC_BITS - exp; \ ret.high |= val.high >> high_shift; \ ret.low = val.high << (32 - high_shift); \ ret.low |= val.low >> high_shift; \ } \ } else { \ ret.high = 0; \ ret.low = 1 << exp; \ if (exp > DOUBLE_FRAC_BITS - 32) { \ high_shift = exp - DOUBLE_FRAC_BITS - 32; \ ret.low |= val.high << high_shift; \ ret.low |= val.low >> (32 - high_shift); \ } else \ ret.low |= val.high >> (DOUBLE_FRAC_BITS - 32 - exp); \ } \ \ /* encode negative integer using 2's complement */ \ if (with_sign && sign) { \ ret.low = ~ret.low; \ ret.high = ~ret.high; \ if (ret.low == UINT_MAX) { \ ret.low = 0; \ ret.high++; \ } else \ ret.low++; \ } \ \ double_unsigned_struct_return(ret); \ } /* double to unsigned long long conversion */ DEFINE__AEABI_D2XLZ(d2ulz, 0) /* double to long long conversion */ DEFINE__AEABI_D2XLZ(d2lz, 1) /* long long to float conversion */ #define DEFINE__AEABI_XL2F(name, with_sign) \ unsigned __aeabi_ ## name(unsigned long long v) \ { \ int s /* shift */, flb /* first lost bit */, sign = 0; \ unsigned p = 0 /* power */, ret; \ double_unsigned_struct val; \ \ /* fraction in negative float is encoded in 1's complement */ \ if (with_sign && (v & (1ULL << 63))) { \ sign = 1; \ v = ~v + 1; \ } \ val.low = v; \ val.high = v >> 32; \ /* fill fraction bits */ \ for (s = 31, p = 1 << 31; p && !(val.high & p); s--, p >>= 1); \ if (p) { \ ret = val.high & (p - 1); \ if (s < FLOAT_FRAC_BITS) { \ ret <<= FLOAT_FRAC_BITS - s; \ ret |= val.low >> (32 - (FLOAT_FRAC_BITS - s)); \ flb = (val.low >> (32 - (FLOAT_FRAC_BITS - s - 1))) & 1; \ } else { \ flb = (ret >> (s - FLOAT_FRAC_BITS - 1)) & 1; \ ret >>= s - FLOAT_FRAC_BITS; \ } \ s += 32; \ } else { \ for (s = 31, p = 1 << 31; p && !(val.low & p); s--, p >>= 1); \ if (p) { \ ret = val.low & (p - 1); \ if (s <= FLOAT_FRAC_BITS) { \ ret <<= FLOAT_FRAC_BITS - s; \ flb = 0; \ } else { \ flb = (ret >> (s - FLOAT_FRAC_BITS - 1)) & 1; \ ret >>= s - FLOAT_FRAC_BITS; \ } \ } else \ return 0; \ } \ if (flb) \ ret++; \ \ /* fill exponent bits */ \ ret |= (s + ONE_EXP(FLOAT)) << FLOAT_FRAC_BITS; \ \ /* fill sign bit */ \ ret |= sign << 31; \ \ return ret; \ } /* unsigned long long to float conversion */ DEFINE__AEABI_XL2F(ul2f, 0) /* long long to float conversion */ DEFINE__AEABI_XL2F(l2f, 1) /* long long to double conversion */ #define __AEABI_XL2D(name, with_sign) \ void __aeabi_ ## name(unsigned long long v) \ { \ int s /* shift */, high_shift, sign = 0; \ unsigned tmp, p = 0; \ double_unsigned_struct val, ret; \ \ /* fraction in negative float is encoded in 1's complement */ \ if (with_sign && (v & (1ULL << 63))) { \ sign = 1; \ v = ~v + 1; \ } \ val.low = v; \ val.high = v >> 32; \ \ /* fill fraction bits */ \ for (s = 31, p = 1 << 31; p && !(val.high & p); s--, p >>= 1); \ if (p) { \ tmp = val.high & (p - 1); \ if (s < DOUBLE_FRAC_BITS - 32) { \ high_shift = DOUBLE_FRAC_BITS - 32 - s; \ ret.high = tmp << high_shift; \ ret.high |= val.low >> (32 - high_shift); \ ret.low = val.low << high_shift; \ } else { \ high_shift = s - (DOUBLE_FRAC_BITS - 32); \ ret.high = tmp >> high_shift; \ ret.low = tmp << (32 - high_shift); \ ret.low |= val.low >> high_shift; \ if ((val.low >> (high_shift - 1)) & 1) { \ if (ret.low == UINT_MAX) { \ ret.high++; \ ret.low = 0; \ } else \ ret.low++; \ } \ } \ s += 32; \ } else { \ for (s = 31, p = 1 << 31; p && !(val.low & p); s--, p >>= 1); \ if (p) { \ tmp = val.low & (p - 1); \ if (s <= DOUBLE_FRAC_BITS - 32) { \ high_shift = DOUBLE_FRAC_BITS - 32 - s; \ ret.high = tmp << high_shift; \ ret.low = 0; \ } else { \ high_shift = s - (DOUBLE_FRAC_BITS - 32); \ ret.high = tmp >> high_shift; \ ret.low = tmp << (32 - high_shift); \ } \ } else { \ ret.high = ret.low = 0; \ double_unsigned_struct_return(ret); \ } \ } \ \ /* fill exponent bits */ \ ret.high |= (s + ONE_EXP(DOUBLE)) << (DOUBLE_FRAC_BITS - 32); \ \ /* fill sign bit */ \ ret.high |= sign << 31; \ \ double_unsigned_struct_return(ret); \ } /* unsigned long long to double conversion */ __AEABI_XL2D(ul2d, 0) /* long long to double conversion */ __AEABI_XL2D(l2d, 1) /* Long long helper functions */ /* TODO: add error in case of den == 0 (see §4.3.1 and §4.3.2) */ #define define_aeabi_xdivmod_signed_type(basetype, type) \ typedef struct type { \ basetype quot; \ unsigned basetype rem; \ } type #define define_aeabi_xdivmod_unsigned_type(basetype, type) \ typedef struct type { \ basetype quot; \ basetype rem; \ } type #define AEABI_UXDIVMOD(name,type, rettype, typemacro) \ static inline rettype aeabi_ ## name (type num, type den) \ { \ rettype ret; \ type quot = 0; \ \ /* Increase quotient while it is less than numerator */ \ while (num >= den) { \ type q = 1; \ \ /* Find closest power of two */ \ while ((q << 1) * den <= num && q * den <= typemacro ## _MAX / 2) \ q <<= 1; \ \ /* Compute difference between current quotient and numerator */ \ num -= q * den; \ quot += q; \ } \ ret.quot = quot; \ ret.rem = num; \ return ret; \ } #define __AEABI_XDIVMOD(name, type, uiname, rettype, urettype, typemacro) \ void __aeabi_ ## name(type numerator, type denominator) \ { \ unsigned type num, den; \ urettype uxdiv_ret; \ rettype ret; \ \ if (numerator >= 0) \ num = numerator; \ else \ num = 0 - numerator; \ if (denominator >= 0) \ den = denominator; \ else \ den = 0 - denominator; \ uxdiv_ret = aeabi_ ## uiname(num, den); \ /* signs differ */ \ if ((numerator & typemacro ## _MIN) != (denominator & typemacro ## _MIN)) \ ret.quot = 0 - uxdiv_ret.quot; \ else \ ret.quot = uxdiv_ret.quot; \ if (numerator < 0) \ ret.rem = 0 - uxdiv_ret.rem; \ else \ ret.rem = uxdiv_ret.rem; \ \ rettype ## _return(ret); \ } define_aeabi_xdivmod_signed_type(long long, lldiv_t); define_aeabi_xdivmod_unsigned_type(unsigned long long, ulldiv_t); define_aeabi_xdivmod_signed_type(int, idiv_t); define_aeabi_xdivmod_unsigned_type(unsigned, uidiv_t); REGS_RETURN(lldiv_t, lldiv_t) REGS_RETURN(ulldiv_t, ulldiv_t) REGS_RETURN(idiv_t, idiv_t) REGS_RETURN(uidiv_t, uidiv_t) AEABI_UXDIVMOD(uldivmod, unsigned long long, ulldiv_t, ULLONG) __AEABI_XDIVMOD(ldivmod, long long, uldivmod, lldiv_t, ulldiv_t, LLONG) void __aeabi_uldivmod(unsigned long long num, unsigned long long den) { ulldiv_t_return(aeabi_uldivmod(num, den)); } void __aeabi_llsl(double_unsigned_struct val, int shift) { double_unsigned_struct ret; if (shift >= 32) { val.high = val.low; val.low = 0; shift -= 32; } if (shift > 0) { ret.low = val.low << shift; ret.high = (val.high << shift) | (val.low >> (32 - shift)); double_unsigned_struct_return(ret); return; } double_unsigned_struct_return(val); } #define aeabi_lsr(val, shift, fill, type) \ type ## _struct ret; \ \ if (shift >= 32) { \ val.low = val.high; \ val.high = fill; \ shift -= 32; \ } \ if (shift > 0) { \ ret.high = val.high >> shift; \ ret.low = (val.high << (32 - shift)) | (val.low >> shift); \ type ## _struct_return(ret); \ return; \ } \ type ## _struct_return(val); void __aeabi_llsr(double_unsigned_struct val, int shift) { aeabi_lsr(val, shift, 0, double_unsigned); } void __aeabi_lasr(unsigned_int_struct val, int shift) { aeabi_lsr(val, shift, val.high >> 31, unsigned_int); } /* Integer division functions */ AEABI_UXDIVMOD(uidivmod, unsigned, uidiv_t, UINT) int __aeabi_idiv(int numerator, int denominator) { unsigned num, den; uidiv_t ret; if (numerator >= 0) num = numerator; else num = 0 - numerator; if (denominator >= 0) den = denominator; else den = 0 - denominator; ret = aeabi_uidivmod(num, den); if ((numerator & INT_MIN) != (denominator & INT_MIN)) /* signs differ */ ret.quot *= -1; return ret.quot; } unsigned __aeabi_uidiv(unsigned num, unsigned den) { return aeabi_uidivmod(num, den).quot; } __AEABI_XDIVMOD(idivmod, int, uidivmod, idiv_t, uidiv_t, INT) void __aeabi_uidivmod(unsigned num, unsigned den) { uidiv_t_return(aeabi_uidivmod(num, den)); }
55.523904
79
0.292828
77b06abc0f5e1a40fef5e4cbd1749c3d98db4467
4,002
c
C
common/read_peer_msg.c
nakajo2011/lightning
efa38875b2e06fb2ac0966034bcb94359a865c6d
[ "MIT" ]
1
2019-10-08T07:31:09.000Z
2019-10-08T07:31:09.000Z
common/read_peer_msg.c
nakajo2011/lightning
efa38875b2e06fb2ac0966034bcb94359a865c6d
[ "MIT" ]
1
2020-11-02T15:42:03.000Z
2020-11-09T21:24:19.000Z
common/read_peer_msg.c
nakajo2011/lightning
efa38875b2e06fb2ac0966034bcb94359a865c6d
[ "MIT" ]
4
2020-11-02T15:40:09.000Z
2022-02-08T11:10:40.000Z
#include <common/crypto_sync.h> #include <common/peer_failed.h> #include <common/read_peer_msg.h> #include <common/status.h> #include <common/type_to_string.h> #include <common/utils.h> #include <common/wire_error.h> #include <errno.h> #include <gossipd/gen_gossip_peerd_wire.h> #include <sys/select.h> #include <wire/peer_wire.h> #include <wire/wire_sync.h> u8 *peer_or_gossip_sync_read(const tal_t *ctx, int peer_fd, int gossip_fd, struct crypto_state *cs, bool *from_gossipd) { fd_set readfds; u8 *msg; FD_ZERO(&readfds); FD_SET(peer_fd, &readfds); FD_SET(gossip_fd, &readfds); select(peer_fd > gossip_fd ? peer_fd + 1 : gossip_fd + 1, &readfds, NULL, NULL, NULL); if (FD_ISSET(gossip_fd, &readfds)) { msg = wire_sync_read(ctx, gossip_fd); if (!msg) status_failed(STATUS_FAIL_GOSSIP_IO, "Error reading gossip msg: %s", strerror(errno)); *from_gossipd = true; return msg; } msg = sync_crypto_read(ctx, cs, peer_fd); *from_gossipd = false; return msg; } bool is_peer_error(const tal_t *ctx, const u8 *msg, const struct channel_id *channel_id, char **desc, bool *all_channels) { struct channel_id err_chanid; if (fromwire_peektype(msg) != WIRE_ERROR) return false; *desc = sanitize_error(ctx, msg, &err_chanid); /* BOLT #1: * * The channel is referred to by `channel_id`, unless `channel_id` is * 0 (i.e. all bytes are 0), in which case it refers to all channels. * ... * The receiving node: * - upon receiving `error`: * - MUST fail the channel referred to by the error message, if that * channel is with the sending node. * - if no existing channel is referred to by the message: * - MUST ignore the message. */ *all_channels = channel_id_is_all(&err_chanid); if (!*all_channels && !channel_id_eq(&err_chanid, channel_id)) *desc = tal_free(*desc); return true; } bool is_wrong_channel(const u8 *msg, const struct channel_id *expected, struct channel_id *actual) { if (!extract_channel_id(msg, actual)) return false; return !channel_id_eq(expected, actual); } void handle_gossip_msg(int peer_fd, struct crypto_state *cs, const u8 *msg TAKES) { u8 *gossip; if (!fromwire_gossipd_send_gossip(tmpctx, msg, &gossip)) { status_broken("Got bad message from gossipd: %s", tal_hex(msg, msg)); peer_failed_connection_lost(); } /* Gossipd can send us gossip messages, OR errors */ if (is_msg_for_gossipd(gossip)) { sync_crypto_write(cs, peer_fd, gossip); } else if (fromwire_peektype(gossip) == WIRE_ERROR) { status_debug("Gossipd told us to send error"); sync_crypto_write(cs, peer_fd, gossip); peer_failed_connection_lost(); } else { status_broken("Gossipd gave us bad send_gossip message %s", tal_hex(msg, msg)); peer_failed_connection_lost(); } if (taken(msg)) tal_free(msg); } bool handle_peer_gossip_or_error(int peer_fd, int gossip_fd, struct crypto_state *cs, const struct channel_id *channel_id, const u8 *msg TAKES) { char *err; bool all_channels; struct channel_id actual; if (is_msg_for_gossipd(msg)) { wire_sync_write(gossip_fd, msg); /* wire_sync_write takes, so don't take again. */ return true; } if (is_peer_error(tmpctx, msg, channel_id, &err, &all_channels)) { if (err) peer_failed_received_errmsg(peer_fd, gossip_fd, cs, err, all_channels ? NULL : channel_id); /* Ignore unknown channel errors. */ goto handled; } /* They're talking about a different channel? */ if (is_wrong_channel(msg, channel_id, &actual)) { status_trace("Rejecting %s for unknown channel_id %s", wire_type_name(fromwire_peektype(msg)), type_to_string(tmpctx, struct channel_id, &actual)); sync_crypto_write(cs, peer_fd, take(towire_errorfmt(NULL, &actual, "Multiple channels" " unsupported"))); goto handled; } return false; handled: if (taken(msg)) tal_free(msg); return true; }
25.987013
81
0.688906
850cefa754bd16d63998082fb996b6a347682319
21,864
c
C
gempak/source/nxmlib/NxmEnhw.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
gempak/source/nxmlib/NxmEnhw.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
gempak/source/nxmlib/NxmEnhw.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
#include "geminc.h" #include "gemprm.h" #include "Nxm.h" /* * maximum number of enhancement tables */ #define ENHANCE_NAME 40 #define FNAME_LEN 256 #define VISIBLE_ITEM 15 #define ENHANCE_TBL "enhance.tbl" struct enhance_t{ int type; /* type of color bank, 1=sat, 2=rad */ char name[ENHANCE_NAME];/* title name shown in enhance list */ }; static struct enhance_t *_enhanceTbl; static Widget _enhanceW; /* color enhancement popup */ static Widget _enhList; /* color enhancement popup */ static int _enhCount; /* total # of records in the table */ static int _enhType; /* last enhancement type */ static char _curLutSAT[ENHANCE_NAME]; /* current lutfile name */ static char _curLutRAD[ENHANCE_NAME]; /* current lutfile name */ /* * Private functions */ void NxmEnhw_closeCb ( Widget, XtPointer, XtPointer ); void NxmEnhw_singleCb ( Widget, XtPointer, XmListCallbackStruct* ); void (*_subEnhFunc)(void) = NULL; /* additional func called with singleCb */ void (*_subEnhFunc2)(char *) = NULL; /* second additional func called with singleCb */ /************************************************************************ * NxmEnhw.c * * * * This module creates the color enhancement popup and defines the * * callback functions. * * * * CONTENTS: * * NxmEnhw_create() creates color enhancement popup window. * * NxmEnhw_popup() pops up the enhancement list. * * NxmEnhw_update() updates the enhancement list. * * NxmEnhw_setLutfile() sets the lookup table name. * * * * NxmEnhw_getLutfile() return the current lutfil name. * * * * NxmEnhw_singleCb() callback for the single click in the list. * * NxmEnhw_closeCb() callback for the close button. * ***********************************************************************/ /*=====================================================================*/ Widget NxmEnhw_create ( Widget parent, void (*func)(void), void (*func2)(char *) ) /************************************************************************ * NxmEnhw_create * * * * This function creates a color enhancement popup window. * * * * Widget NxmEnhw_create(parent, func, func2) * * * * Input parameters: * * parent Widget parent widget ID * * *func() void additional func called with singleCb * * *func2() void second additional func called with singleCb * * * * Output parameters: * * NONE * * Return parameters: * * NxmEnhw_create Widget Widget ID of the enhance popup * * * ** * * Log: * * Chien Lin/EAI 05/93 * * Chien Lin/EAI 07/95 clean up in freeing xm_string * * Chien Lin/EAI 09/95 modify layout of enhance list popup * * C. Lin/EAI 12/95 clean up * * C. Lin/EAI 06/96 make it Nxm library function * * C. Lin/EAI 01/97 increase fname size(S. Chiswell/Unidata)* * C. Lin/EAI 04/97 initialize _curLutfile * * C. Lin/EAI 12/97 rewrite for adding radar enhance * * I. Durham/GSC 05/98 changed underscore decl. to an include * * S. Jacobs/NCEP 10/99 Added second function to call * * T. Piper/SAIC 07/06 Changed i to ii to aid maintenance * ***********************************************************************/ { Widget frame, button; char buffer[256]; FILE *fp; int ii, count, ier; Cardinal argcnt; Arg args[10]; XmString xmstr2; char message[] = "Enhancement table is missing."; /*---------------------------------------------------------------------*/ _enhanceW = XmCreateFormDialog(parent, "enhance_list_toplevel", NULL, 0); /* * read in the enhancement table file */ fp = cfl_tbop(ENHANCE_TBL, "luts", &ier); if (ier != 0) { NxmWarn_show(XtParent(_enhanceW), message); } else { /* * figure out the total # of records */ count = 0; while ( !feof(fp) ) { cfl_trln(fp, 256, buffer, &ier); if ( ier == 0 ) count++; } } _enhCount = count; if ( count > 0 ) { _enhanceTbl = (struct enhance_t *) malloc((size_t)count * sizeof(struct enhance_t)); rewind(fp); ii = 0; while ( ii < count ) { cfl_trln(fp, 256, buffer, &ier); if ( ier == 0 ) { sscanf(buffer, "%d %s", &(_enhanceTbl[ii].type), _enhanceTbl[ii].name); ii++; } } } if ( fp ) fclose(fp); frame = XtVaCreateWidget("enhanceClose", xmFrameWidgetClass, _enhanceW, XmNtopAttachment, XmATTACH_FORM, XmNleftAttachment, XmATTACH_FORM, XmNleftOffset, 5, XmNrightAttachment, XmATTACH_FORM, XmNrightOffset, 5, NULL); /* * create a scrolled list for enhancement table * only a single selection is allowed */ argcnt = 0; XtSetArg(args[argcnt], XmNselectionPolicy, XmSINGLE_SELECT); argcnt++; _enhList = XmCreateScrolledList(frame, "enhanceList", args, argcnt); XtManageChild(_enhList); XtAddCallback(_enhList, XmNsingleSelectionCallback, (XtCallbackProc)NxmEnhw_singleCb, NULL); XtManageChild(frame); /* * create close button */ xmstr2 = XmStringCreateLocalized("Close"); button = XtVaCreateManagedWidget("enhanceClose", xmPushButtonWidgetClass, _enhanceW, XmNlabelString, xmstr2, XmNtopAttachment, XmATTACH_WIDGET, XmNtopWidget, frame, XmNtopOffset, 10, XmNleftAttachment, XmATTACH_FORM, XmNleftOffset, 10, XmNbottomAttachment, XmATTACH_FORM, XmNbottomOffset, 10, NULL); XmStringFree(xmstr2); XtAddCallback(button, XmNactivateCallback, (XtCallbackProc)NxmEnhw_closeCb, (XtPointer)NULL); if (func) _subEnhFunc = func; if (func2) _subEnhFunc2 = func2; /* * set the initial color lookup table name (lutfile) */ strcpy(_curLutSAT, "gray"); strcpy(_curLutRAD, "DEFAULT"); _enhType = 0; return(_enhanceW); } /*=====================================================================*/ void NxmEnhw_popup ( int ityp ) /************************************************************************ * NxmEnhw_popup * * * * This function pops up the color enhancement popup window. * * * * void NxmEnhw_popup(ityp) * * * * Input parameters: * * ityp int data type 1=SAT, 2=RAD * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * Chien Lin/EAI 05/96 * * Chien Lin/EAI 12/97 add ityp and modification for RADAR * * T. Piper/SAIC 07/06 Changed i to ii to aid maintenance * * T. Piper/SAIC 07/06 Changed n to nn to aid maintenance * ***********************************************************************/ { int ii, nn, ivis; XmStringTable xm_strs; XmString xmstr; /*---------------------------------------------------------------------*/ if ( _enhCount <= 0 ) return; if ( ityp != _enhType ) { xm_strs = (XmStringTable)XtMalloc((size_t)_enhCount*sizeof(XmString)); nn = 0; for ( ii = 0; ii < _enhCount; ii++ ) { if ( ityp == _enhanceTbl[ii].type ) { xm_strs[nn] = XmStringCreateLocalized(_enhanceTbl[ii].name); nn++; } } if ( nn < VISIBLE_ITEM ) ivis = nn; else ivis = VISIBLE_ITEM; XmListDeleteAllItems(_enhList); XtVaSetValues(_enhList, XmNvisibleItemCount, ivis, XmNitemCount, nn, XmNitems, xm_strs, NULL); for ( ii = 0 ; ii < nn; ii++ ) { XmStringFree(xm_strs[ii]); } XtFree( (XtPointer)xm_strs); _enhType = ityp; } /* * redisplay the selected item */ XmListDeselectAllItems(_enhList); if ( ityp == 1 ) xmstr = XmStringCreateLocalized(_curLutSAT); else xmstr = XmStringCreateLocalized(_curLutRAD); XmListSelectItem(_enhList, xmstr, FALSE); XmListSetBottomItem(_enhList, xmstr); XmStringFree(xmstr); XtManageChild(_enhanceW); } /*=====================================================================*/ void NxmEnhw_update ( int ityp ) /************************************************************************ * NxmEnhw_update * * * * This function updates the enhancement popup window if it is up. * * * * void NxmEnhw_update(ityp) * * * * Input parameters: * * ityp int data type 1=SAT, 2=RAD * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * Chien Lin/EAI 12/97 * * S. Jacobs/NCEP 10/99 Added redisplay of widget for type=1 * ***********************************************************************/ { XmString xmstr; /*---------------------------------------------------------------------*/ if ( ! XtIsManaged(_enhanceW) ) return; if ( ityp != _enhType ) { XtUnmanageChild(_enhanceW); NxmEnhw_popup(ityp); } else if ( ityp == 1 ) { /* * redisplay the selected item */ XmListDeselectAllItems(_enhList); xmstr = XmStringCreateLocalized(_curLutSAT); XmListSelectItem(_enhList, xmstr, FALSE); XmStringFree(xmstr); } else if ( ityp == 2 ) { /* * redisplay the selected item */ XmListDeselectAllItems(_enhList); xmstr = XmStringCreateLocalized(_curLutRAD); XmListSelectItem(_enhList, xmstr, FALSE); XmStringFree(xmstr); } } /*=====================================================================*/ void NxmEnhw_setLutfile ( int ityp, char *lutfile ) /************************************************************************ * NxmEnhw_setLutfile * * * * This function returns the current lookup table file name. * * * * void NxmEnhw_setLutfile(ityp, lutfile) * * * * Input parameters: * * ityp int data type, 1 = SAT, 2 = RAD * * *lutfile char color lookup table file name * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * C. Lin/EAI 12/97 * * S. Jacobs/NCEP 11/99 Added check for DEFAULT lut * * H. Zeng/EAI 10/02 Added check for DEFAULT lut for SAT * * T. Lee/SAIC 06/04 Checked return code for im_qlut * * T. Piper/SAIC 07/06 Added call to ST_NULL after im_qlut * * T. Piper/SAIC 07/06 Added cst_uclc after second im_qlut * ***********************************************************************/ { int ier, lens; char newlut[FNAME_LEN], *ptr; /*---------------------------------------------------------------------*/ if ( ityp == 1 ) { if ( strncasecmp(lutfile, "def", 3) == 0 ) { im_qlut ( newlut, &ier, sizeof(newlut) ); if ( ier == 0 ) { st_null(newlut, newlut, &lens, &ier, sizeof(newlut), sizeof(newlut)); cst_uclc(newlut, newlut, &ier); ptr = strchr ( newlut, '.' ); if ( ptr != NULL ) { *ptr = '\0'; } strcpy ( _curLutSAT, newlut ); } } else { strcpy(_curLutSAT, lutfile); } } else { if ( strncasecmp(lutfile, "def", 3) == 0 ) { im_qlut ( newlut, &ier, sizeof(newlut) ); if ( ier == 0 ) { st_null(newlut, newlut, &lens, &ier, sizeof(newlut), sizeof(newlut)); cst_uclc(newlut, newlut, &ier); ptr = strchr ( newlut, '.' ); if ( ptr != NULL ) { *ptr = '\0'; } strcpy ( _curLutRAD, newlut ); } } else { strcpy(_curLutRAD, lutfile); } } } /*=====================================================================*/ void NxmEnhw_getLutfile ( int ityp, char *lutfile ) /************************************************************************ * NxmEnhw_getLutfile * * * * This function returns the current lookup table file name. * * * * void NxmEnhw_getLutfile(ityp, lutfile) * * * * Input parameters: * * ityp int data type, 1 = SAT, 2 = RAD * * * * Output parameters: * * *lutfile char color lookup table file name * * * * Return parameters: * * NONE * * * ** * * Log: * * C. Lin/EAI 04/97 * * C. Lin/EAI 12/97 add ityp for RADAR * ***********************************************************************/ { if ( ityp == 1 ) strcpy(lutfile, _curLutSAT); else strcpy(lutfile, _curLutRAD); } /*=====================================================================*/ /* ARGSUSED */ void NxmEnhw_singleCb ( Widget wdgt, XtPointer clnt, XmListCallbackStruct *list ) /************************************************************************ * NxmEnhw_singleCb * * * * Callback function for single clicking in color enhancement list. * * * * void NxmEnhw_singleCb(wdgt, clnt, list) * * * * Input parameters: * * wdgt Widget widget ID * * clnt XtPointer client data, not used * * *list XmListCallbackStruct callback data struct * * * * Output parameters: * * NONE * * * * Return parameters: * * NONE * * * ** * * Log: * * C. Lin/EAI 02/93 * * C. Lin/EAI 08/95 use im_lutf * * C. Lin/EAI 12/95 clean up * * C. Lin/EAI 01/97 increase lutfile array size * * C. Lin/EAI 04/97 save the current lutfile name * * C. Lin/EAI 12/97 modified for RADAR * * S. Jacobs/NCEP 10/99 Added call to second additional func * * E. Safford/SAIC 01/04 Moved _subEnhFunc2 to after lutfile save* ***********************************************************************/ { int iret; char *tmpstr, lutfile[FNAME_LEN]; /*---------------------------------------------------------------------*/ XmStringGetLtoR(list->item, XmFONTLIST_DEFAULT_TAG, &tmpstr); if ( strncasecmp(tmpstr, "gray", 4) == 0 ) strcpy( lutfile, "gray" ); else sprintf( lutfile, "%s.tbl", tmpstr ); im_lutf( lutfile, &iret, strlen(lutfile) ); /* * Save the lutfile */ if ( _enhType == 1 ) strcpy( _curLutSAT, tmpstr ); else strcpy( _curLutRAD, tmpstr ); XtFree(tmpstr); /* * Call the event funcs */ if (_subEnhFunc2) { _subEnhFunc2(lutfile); } if (_subEnhFunc) { _subEnhFunc(); } } /*=====================================================================*/ /* ARGSUSED */ void NxmEnhw_closeCb ( Widget wdgt, XtPointer clnt, XtPointer call ) /************************************************************************ * NxmEnhw_closeCb * * * * Callback function for close button in color enhancement popup window.* * * * void NxmEnhw_closeCb(wdgt, clnt, call) * * * * Input parameters: * * wdgt Widget widget ID * * clnt XtPointer not used * * call XtPointer not used * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * C. Lin/EAI 02/93 * * C. Lin/EAI 12/95 clean up * ***********************************************************************/ { XtUnmanageChild(_enhanceW); }
40.488889
80
0.352726
e2348b5ddf7a16c22fb6511c4ecc656672b495be
3,092
h
C
Tester/Controllers/QueryParamController.h
mnaumanali94/ObjC
d471fe8518540732cd1800e122e0cfc162af4828
[ "MIT" ]
null
null
null
Tester/Controllers/QueryParamController.h
mnaumanali94/ObjC
d471fe8518540732cd1800e122e0cfc162af4828
[ "MIT" ]
null
null
null
Tester/Controllers/QueryParamController.h
mnaumanali94/ObjC
d471fe8518540732cd1800e122e0cfc162af4828
[ "MIT" ]
null
null
null
// // QueryParamController.h // Tester // // This file was automatically generated for Stamplay by APIMATIC v2.0 ( https://apimatic.io ) on 06/23/2016 // #import <Foundation/Foundation.h> #import "Configuration.h" #import "APIHelper.h" #import "APIError.h" #import "BaseController.h" #import "UnirestClient.h" #import "HttpContext.h" #import "ServerResponse.h" #import "Days.h" #import "DaysHelper.h" #import "SuiteCode.h" #import "SuiteCodeHelper.h" @interface QueryParamController : BaseController /** * Completion block definition for asynchronous call to SimpleQuery */ typedef void (^CompletedGetSimpleQuery)(BOOL success, HttpContext* context, ServerResponse* response, NSError* error); /** * TODO: type endpoint description here * @param boolean Required parameter: Example: * @param number Required parameter: Example: * @param string Required parameter: Example: * @param queryParameters Additional optional query parameters are supported by this endpoint */ - (void) simpleQueryAsyncWithBoolean:(BOOL) boolean number:(int) number string:(NSString*) string queryParameters:(NSDictionary*) queryParameters completionBlock:(CompletedGetSimpleQuery) onCompleted; /** * Completion block definition for asynchronous call to Number Array */ typedef void (^CompletedGetNumberArray)(BOOL success, HttpContext* context, ServerResponse* response, NSError* error); /** * TODO: type endpoint description here * @param integers Required parameter: Example: */ - (void) numberArrayAsyncWithIntegers:(NSArray*) integers completionBlock:(CompletedGetNumberArray) onCompleted; /** * Completion block definition for asynchronous call to String Array */ typedef void (^CompletedGetStringArray)(BOOL success, HttpContext* context, ServerResponse* response, NSError* error); /** * TODO: type endpoint description here * @param strings Required parameter: Example: */ - (void) stringArrayAsyncWithStrings:(NSArray*) strings completionBlock:(CompletedGetStringArray) onCompleted; /** * Completion block definition for asynchronous call to String Enum Array */ typedef void (^CompletedGetStringEnumArray)(BOOL success, HttpContext* context, ServerResponse* response, NSError* error); /** * TODO: type endpoint description here * @param days Required parameter: Example: */ - (void) stringEnumArrayAsyncWithDays:(NSArray<NSNumber*>*) days completionBlock:(CompletedGetStringEnumArray) onCompleted; /** * Completion block definition for asynchronous call to Integer Enum Array */ typedef void (^CompletedGetIntegerEnumArray)(BOOL success, HttpContext* context, ServerResponse* response, NSError* error); /** * TODO: type endpoint description here * @param suites Required parameter: Example: */ - (void) integerEnumArrayAsyncWithSuites:(NSArray<NSNumber*>*) suites completionBlock:(CompletedGetIntegerEnumArray) onCompleted; @end
37.253012
124
0.717982
8b5cdcf86ce99938575ab848902431272a963559
1,225
h
C
testing/SWRender/DemoContext.h
HinTak/darling-cocotron
1a430280c118c75b5256195aef8579cfb350af79
[ "MIT" ]
null
null
null
testing/SWRender/DemoContext.h
HinTak/darling-cocotron
1a430280c118c75b5256195aef8579cfb350af79
[ "MIT" ]
null
null
null
testing/SWRender/DemoContext.h
HinTak/darling-cocotron
1a430280c118c75b5256195aef8579cfb350af79
[ "MIT" ]
1
2021-06-29T03:09:28.000Z
2021-06-29T03:09:28.000Z
#import <Foundation/Foundation.h> @interface DemoContext : NSObject @end @interface DemoContext (subclass) - (size_t) pixelsWide; - (size_t) pixelsHigh; - (size_t) bitsPerComponent; - (size_t) bitsPerPixel; - (size_t) bytesPerRow; - (CGBitmapInfo) bitmapInfo; - (void *) bytes; - (void) setStrokeColor: (float) r: (float) g:(float) b:(float) a; - (void) setFillColor: (float) r: (float) g:(float) b:(float) a; - (void) setBlendMode: (CGBlendMode) mode; - (void) setShadowBlur: (float) value; - (void) setShadowOffsetX: (float) value; - (void) setShadowOffsetY: (float) value; - (void) setShadowColor: (float) r: (float) g:(float) b:(float) a; - (void) setPathDrawingMode: (CGPathDrawingMode) mode; - (void) setLineWidth: (float) width; - (void) setDashPhase: (float) phase; - (void) setDashLength: (float) value; - (void) setFlatness: (float) value; - (void) setScaleX: (float) value; - (void) setScaleY: (float) value; - (void) setRotation: (float) value; - (void) setShouldAntialias: (BOOL) value; - (void) setInterpolationQuality: (CGInterpolationQuality) value; - (void) setImageData: (NSData *) data; - (void) setPDFData: (NSData *) data; - (void) drawClassic; - (void) drawBitmapImageRep; - (void) drawPDF; @end
29.166667
66
0.69551
8bac37e6ffb30490ee2674e1464cff9d8b338a9f
6,720
h
C
test/featurespace/weighed_impl.h
JuergenSimon/meanie3D
776890f6b63d735153566fecc5a76c68a23ef333
[ "MIT" ]
null
null
null
test/featurespace/weighed_impl.h
JuergenSimon/meanie3D
776890f6b63d735153566fecc5a76c68a23ef333
[ "MIT" ]
5
2016-09-17T13:46:23.000Z
2020-07-01T16:31:29.000Z
test/featurespace/weighed_impl.h
JuergenSimon/meanie3D
776890f6b63d735153566fecc5a76c68a23ef333
[ "MIT" ]
3
2016-04-18T13:13:28.000Z
2020-06-18T12:30:05.000Z
#ifndef M3D_TEST_FS_WEIGHED_IMPL_H #define M3D_TEST_FS_WEIGHED_IMPL_H template<class T> void FSWeighedTest2D<T>::create_uniform_distribution_recursive(const NcVar &var, size_t modulo, size_t dimensionIndex, typename CoordinateSystem<T>::GridPoint &gridpoint) { using namespace netCDF; NcDim dim = var.getDim(dimensionIndex); if (dimensionIndex < (var.getDimCount() - 1)) { for (int index = 0; index < dim.getSize(); index++) { gridpoint[dimensionIndex] = index; if (gridpoint[dimensionIndex] % modulo == 0) { create_uniform_distribution_recursive(var, modulo, dimensionIndex + 1, gridpoint); } } } else { for (int index = 0; index < dim.getSize(); index++) { gridpoint[dimensionIndex] = index; vector <size_t> count(gridpoint.size(), 1); if (gridpoint[dimensionIndex] % modulo == 0) { this->m_pointCount++; typename CoordinateSystem<T>::Coordinate coordinate = this->coordinate_system()->newCoordinate(); this->coordinate_system()->lookup(gridpoint, coordinate); T value = (T) m_distribution(coordinate); vector <size_t> gp(gridpoint.begin(), gridpoint.end()); var.putVar(gp, value); } } } } /** Creates a distribution of points every modulo grid points, * where all values are 1.0 */ template<class T> void FSWeighedTest2D<T>::create_uniform_distribution(const NcVar &var, size_t modulo) { // homogenous point distribution in N-D, every modulo grid point is used typename CoordinateSystem<T>::GridPoint gridpoint(this->coordinate_system()->rank(), 0); this->m_pointCount = 0; INFO << "Creating uniform distribution with data every " << modulo << " nodes ..."; create_uniform_distribution_recursive(var, modulo, 0, gridpoint); if (INFO_ENABLED) cout << "done. (" << this->m_pointCount << " points)" << endl; this->m_totalPointCount += this->m_pointCount; } template<class T> void FSWeighedTest2D<T>::SetUp() { FSTestBase<T>::SetUp(); // Set the bandwidths size_t bw_size = this->m_settings->fs_dim(); this->m_bandwidths.push_back(vector<T>(bw_size, 1.0)); this->m_bandwidths.push_back(vector<T>(bw_size, 2.0)); this->m_bandwidths.push_back(vector<T>(bw_size, 3.0)); this->m_bandwidths.push_back(vector<T>(bw_size, 4.0)); // Figure out the bandwidth maximum vector<float> max_h(this->m_settings->fs_dim(), 0.0); for (size_t i = 0; i < this->m_bandwidths.size(); i++) { vector <T> h = this->m_bandwidths.at(i); assert(h.size() == bw_size); for (size_t j = 0; j < bw_size; j++) { assert(h[j] > 0); if (h[j] > max_h[j]) { max_h[j] = h[j]; } } } // Make the actual values 1.1 times bigger, so that in graphical // representations there is some boundary max_h *= 1.1f; this->m_settings->set_axis_bound_values(max_h); // Generate dimensions and dimension variables according to // the current settings this->generate_dimensions(); // Create a variable // test case 1 : ellipsis for unweighed sample mean NcVar var = this->add_variable("weighed_test", 0.0, 3 * FS_VALUE_MAX); create_uniform_distribution(var, 1); FSTestBase<T>::generate_featurespace(); } template<class T> void FSWeighedTest2D<T>::TearDown() { FSTestBase<T>::TearDown(); } #pragma mark - #pragma mark Test parameterization template<class T> FSWeighedTest2D<T>::FSWeighedTest2D() : FSTestBase<T>() { this->m_settings = new FSTestSettings(2, 1, NUMBER_OF_GRIDPOINTS, FSTestBase<T>::filename_from_current_testcase()); } template<class T> FSWeighedTest3D<T>::FSWeighedTest3D() : FSWeighedTest2D<T>() { this->m_settings = new FSTestSettings(3, 1, NUMBER_OF_GRIDPOINTS, FSTestBase<T>::filename_from_current_testcase()); } // 2D #if RUN_2D TYPED_TEST_CASE(FSWeighedTest2D, DataTypes); TYPED_TEST(FSWeighedTest2D, FS_WeighedSample_2D_Test) { vector<TypeParam> x(this->m_settings->fs_dim(), 0); x[ x.size() - 1 ] = FS_VALUE_MAX; // G'is a kernel Kernel<TypeParam> *kernel = new EpanechnikovKernel<TypeParam>(1.0f); vector< vector<TypeParam> > origins; vector< vector<TypeParam> > vectors; // iterate over the bandwidths MeanshiftOperation<TypeParam> op(this->m_featureSpace, this->m_featureSpaceIndex); for (size_t i = 0; i < this->m_bandwidths.size(); i++) { vector<TypeParam> h = this->m_bandwidths.at(i); RangeSearchParams<TypeParam> *params = new RangeSearchParams<TypeParam>(h); vector<TypeParam> m = op.meanshift(x, params, kernel, 0); origins.push_back(x); vectors.push_back(m); // calculate only the spatial shift size_t dims = this->m_coordinate_system->rank(); vector<TypeParam> c(dims); for (size_t k = 0; k < dims; k++) { c[k] = m[k]; } // spatial shift should be within grid resolution close to zero. EXPECT_NEAR(vector_norm(c), 0.0, this->coordinate_system()->resolution_norm()); } delete kernel; } #endif // 3D #if RUN_3D TYPED_TEST_CASE(FSWeighedTest3D, DataTypes); TYPED_TEST(FSWeighedTest3D, FS_WeighedSample_3D_Test) { vector<TypeParam> x(this->m_settings->fs_dim(), 0); x[ x.size() - 1 ] = FS_VALUE_MAX; // G'is a kernel Kernel<TypeParam> *kernel = new GaussianNormalKernel<TypeParam>(1.0f); vector< vector<TypeParam> > origins; vector< vector<TypeParam> > vectors; // iterate over the bandwidths MeanshiftOperation<TypeParam> op(this->m_featureSpace, this->m_featureSpaceIndex); for (size_t i = 0; i < this->m_bandwidths.size(); i++) { vector<TypeParam> h = this->m_bandwidths.at(i); RangeSearchParams<TypeParam> *params = new RangeSearchParams<TypeParam>(h); vector<TypeParam> m = op.meanshift(x, params, kernel, 0); origins.push_back(x); vectors.push_back(m); // calculate only the spatial shift size_t dims = this->m_coordinate_system->rank(); vector<TypeParam> c(dims); for (size_t k = 0; k < dims; k++) { c[k] = m[k]; } // spatial shift should be within grid resolution close to zero. EXPECT_NEAR(vector_norm(c), 0.0, this->coordinate_system()->resolution_norm()); } delete kernel; } #endif #endif
27.768595
119
0.623958
6bcf34b47b7a72b65ffdd373fa13d73639f394d4
287
h
C
YunWebView/Pods/Headers/Public/YunKits/NSString+YunAdd.h
lizishiye/YunWebView
80d84dd29d111709f56a596d38c469b89219093f
[ "MIT" ]
5
2018-04-18T15:01:01.000Z
2019-10-09T07:40:11.000Z
YunWebView/Pods/Headers/Public/YunKits/NSString+YunAdd.h
lizishiye/YunWebView
80d84dd29d111709f56a596d38c469b89219093f
[ "MIT" ]
1
2019-03-14T06:28:02.000Z
2019-03-14T06:28:02.000Z
YunWebView/Pods/Headers/Public/YunKits/NSString+YunAdd.h
lizishiye/YunWebView
80d84dd29d111709f56a596d38c469b89219093f
[ "MIT" ]
1
2019-03-14T06:18:37.000Z
2019-03-14T06:18:37.000Z
// // Created by yun on 16/10/8. // Copyright (c) 2017 yun. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (YunAdd) // 如果 str 为 nil 或者@"",则取 ctn - (NSString *)strByDefCtn:(NSString *)ctn; // 查询str 中子字段的个数 - (NSInteger)calSubCount:(NSString *)str; @end
17.9375
47
0.679443
ac50808a5723f6adbca3c0e408c51d442e91793d
33,841
h
C
source/canpie-fd/canpie.h
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
36
2016-08-23T13:05:02.000Z
2022-02-13T07:11:05.000Z
source/canpie-fd/canpie.h
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
19
2017-01-30T08:59:40.000Z
2018-10-30T07:55:33.000Z
source/canpie-fd/canpie.h
canpie/canpie
330acb5e041bee7e7a865e3242fd89c9fe07f5ce
[ "Apache-2.0" ]
16
2016-06-02T11:15:02.000Z
2020-07-10T11:49:12.000Z
//============================================================================// // File: canpie.h // // Description: General CAN driver definitions and structures // // // // Copyright 2017 MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // Redistribution and use in source and binary forms, with or without // // modification, are permitted provided that the following conditions // // are met: // // 1. Redistributions of source code must retain the above copyright // // notice, this list of conditions, the following disclaimer and // // the referenced file 'LICENSE'. // // 2. Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // 3. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // //============================================================================// #ifndef CANPIE_H_ #define CANPIE_H_ //----------------------------------------------------------------------------- /*! ** \file canpie.h ** \brief %CANpie constants, structures and enumerations ** ** This file holds constants and structures used within %CANpie FD. ** All functions, structures, defines and constants in %CANpie FD ** have the prefix "Cp". The following table shows the used nomenclature: ** ** <div class="function" style="width:400px"> **<table class="function" style="width:400px"> **<tr class="head"> **<td class="entry" style="width:50%"><b>%CANpie code</b></td> **<td class="desc"><b>Nomenclature</b></td> **</tr> **<tr class="odd"> **<td class="entry" style="width:50%">Core functions</td> **<td class="desc">CpCore<Name></td> **</tr> **<tr> **<td class="entry" style="width:50%">Message access functions</td> **<td class="desc">CpMsg<Name></td> **</tr> **<tr class="odd"> **<td class="entry" style="width:50%">Structures</td> **<td class="desc">Cp<Name>_ts</td> **</tr> **<tr> **<td class="entry" style="width:25%">Definitions</td> **<td class="desc">CP_<NAME></td> **</tr> **<tr class="odd"> **<td class="entry" style="width:50%">Enumerations</td> **<td class="desc">eCP_<NAME></td> **</tr> **</table> **</div> */ /*----------------------------------------------------------------------------*\ ** Include files ** ** ** \*----------------------------------------------------------------------------*/ #ifndef CP_PLATFORM #include "mc_compiler.h" #include "cp_platform.h" // Architecture dependent definitions #endif /*----------------------------------------------------------------------------*\ ** Definitions & Enumerations ** ** ** \*----------------------------------------------------------------------------*/ //----------------------------------------------------------------------------- /*! ** \defgroup CP_CONF CANpie configuration options ** ** The %CANpie FD driver can be configured during compile time ** via several configuration options. They are typically defined in the ** \c cp_platform.h configuration file. ** <p> ** If symbols are not defined, they get a default value which is ** assigned in the \c canpie.h header file. */ /*-------------------------------------------------------------------*/ /*! ** \def CP_AUTOBAUD ** \ingroup CP_CONF ** ** This symbol enables or disables the automatic bit-rate detection ** feature of the CAN driver. The default value is 0 (disabled). ** ** - 0 = disable bit-rate detection (not supported by hardware) ** - 1 = enable bit-rate detection */ #ifndef CP_AUTOBAUD #define CP_AUTOBAUD 0 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_BUFFER_MAX ** \ingroup CP_CONF ** ** This symbol defines the number of message buffers (mailboxes) ** of a CAN controller. In case the controller has no message buffers, ** it is also possible to emulate these. A value of 0 is not allowed ** for this symbol. */ #ifndef CP_BUFFER_MAX #define CP_BUFFER_MAX 8 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_CAN_FD ** \ingroup CP_CONF ** ** This symbol defines if ISO CAN FD support is enabled. ** - 0 = disable ISO CAN FD support ** - 1 = enable ISO CAN FD support */ #ifndef CP_CAN_FD #define CP_CAN_FD 0 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_CAN_MSG_MACRO ** \ingroup CP_CONF ** ** This symbol defines if access to the CAN message structure ** CpCanMsg_s is done via macros or via functions. ** - 0 = access via functions ** - 1 = access via macros */ #ifndef CP_CAN_MSG_MACRO #define CP_CAN_MSG_MACRO 1 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_CAN_MSG_MARKER ** \ingroup CP_CONF ** ** This symbol defines if the CAN message structure CpCanMsg_s ** has a marker field. ** - 0 = no marker field (not supported by hardware / driver) ** - 1 = include marker field */ #ifndef CP_CAN_MSG_MARKER #define CP_CAN_MSG_MARKER 0 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_CAN_MSG_TIME ** \ingroup CP_CONF ** ** This symbol defines if the CAN message structure CpCanMsg_s ** has a time-stamp field. ** - 0 = no time-stamp field (not supported by hardware / driver) ** - 1 = include time-stamp field */ #ifndef CP_CAN_MSG_TIME #define CP_CAN_MSG_TIME 0 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_CAN_MSG_USER ** \ingroup CP_CONF ** ** This symbol defines if the CAN message structure CpCanMsg_s ** has a user-defined field. ** - 0 = no user-defined field (not supported by driver) ** - 1 = include user-defined field */ #ifndef CP_CAN_MSG_USER #define CP_CAN_MSG_USER 1 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_CHANNEL_MAX ** \ingroup CP_CONF ** ** This symbol defines the total number of physical CAN interfaces ** supported by the driver. For a LPC2294 microcontroller the value ** would be 4 (4 CAN channels). */ #ifndef CP_CHANNEL_MAX #define CP_CHANNEL_MAX 1 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_SMALL_CODE ** \ingroup CP_CONF ** ** This symbol is used to control the usage of the \c ptsPortV ** parameter in the core functions during compilation time. For ** microcontrollers with small resources and only one CAN channel ** the port parameter can be omitted. ** - 0 = use \c ptsPortV parameter in core functions ** - 1 = do not use \c ptsPortV parameter in core functions */ #ifndef CP_SMALL_CODE #define CP_SMALL_CODE 0 #endif /*-------------------------------------------------------------------*/ /*! ** \def CP_STATISTIC ** \ingroup CP_CONF ** ** This symbol defines if the driver support statistic information. ** A value of 0 denotes that no statistic information is available. ** This also means that the function CpCoreStatistic() returns the ** error code #eCP_ERR_NOT_SUPPORTED. ** - 0 = no statistic information (not supported by driver) ** - 1 = enable statistic information */ #ifndef CP_STATISTIC #define CP_STATISTIC 0 #endif //----------------------------------------------------------------------------- /*! ** \defgroup CP_VERSION CANpie version information ** ** The %CANpie FD version information read during run-time via the ** function CpCoreHDI(). */ /*-------------------------------------------------------------------*/ /*! ** \def CP_VERSION_MAJOR ** \ingroup CP_VERSION ** ** This symbol defines the driver version major value. */ #define CP_VERSION_MAJOR 3 /*-------------------------------------------------------------------*/ /*! ** \def CP_VERSION_MINOR ** \ingroup CP_VERSION ** ** This symbol defines the driver version minor value. */ #define CP_VERSION_MINOR 8 //----------------------------------------------------------------------------- /*! ** \defgroup CP_MASK Mask values for CAN messages ** ** The following definitions are used in combination with the ** structure CpCanMsg_s. */ /*-------------------------------------------------------------------*/ /*! ** \def CP_MASK_STD_FRAME ** \ingroup CP_MASK ** ** Mask for standard frame (11 bits), used in combination with ** the CpCanMsg_s::ulIdentifier. */ #define CP_MASK_STD_FRAME ((uint32_t) 0x000007FF) /*-------------------------------------------------------------------*/ /*! ** \def CP_MASK_EXT_FRAME ** \ingroup CP_MASK ** ** Mask for extended frame (29 bits), used in combination with ** the CpCanMsg_s::ulIdentifier. */ #define CP_MASK_EXT_FRAME ((uint32_t) 0x1FFFFFFF) /*-------------------------------------------------------------------*/ /*! ** \def CP_MASK_MSG_FORMAT ** \ingroup CP_MASK ** ** Mask for message format, used in combination with \c ubMsgCtrl field ** of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). ** This mask covers #CP_MSG_FORMAT_CBFF, #CP_MSG_FORMAT_CEFF, ** #CP_MSG_FORMAT_FBFF and #CP_MSG_FORMAT_FEFF control flags. */ #define CP_MASK_MSG_FORMAT ((uint8_t) 0x03) //----------------------------------------------------------------------------- /*! ** \defgroup CP_MSG_CTRL Bit mask for message control ** ** The following definitions are used in combination with the ** structure CpCanMsg_s::ubMsgCtrl. */ /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_EXT_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the EXT bit (extended frame) in the \c ubMsgCtrl ** field of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_EXT_BIT ((uint8_t) 0x01) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_FDF_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the FDF bit (ISO CAN FD, Fast Data format) in ** the \c ubMsgCtrl field of the CpCanMsg_ts structure ** (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_FDF_BIT ((uint8_t) 0x02) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_RTR_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the RTR bit (remote frame) in the \c ubMsgCtrl ** field of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_RTR_BIT ((uint8_t) 0x04) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_OVR_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the OVR bit (overrun) in the \c ubMsgCtrl ** field of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_OVR_BIT ((uint8_t) 0x08) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_RPC_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the RPC (Remote Procedure Call) bit in the ** \c ubMsgCtrl field of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_RPC_BIT ((uint8_t) 0x10) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_BRS_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the BRS bit (ISO CAN FD, bit-rate switch) in the ** \c ubMsgCtrl field of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_BRS_BIT ((uint8_t) 0x40) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_CTRL_ESI_BIT ** \ingroup CP_MSG_CTRL ** ** Bit mask for the ESI bit (ISO CAN FD, error state indicator) in the ** \c ubMsgCtrl field of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_CTRL_ESI_BIT ((uint8_t) 0x80) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_FORMAT_CBFF ** \ingroup CP_MSG_CTRL ** ** Bit definition for a Classical CAN frame with Standard Identifier ** (CBFF: Classical base frame format) in the \c ubMsgCtrl field of ** the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_FORMAT_CBFF ((uint8_t) 0x00) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_FORMAT_CEFF ** \ingroup CP_MSG_CTRL ** ** Bit definition for a Classical CAN frame with Extended Identifier ** (CEFF: Classical extended frame format) in the \c ubMsgCtrl field ** of the CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_FORMAT_CEFF (CP_MSG_CTRL_EXT_BIT) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_FORMAT_FBFF ** \ingroup CP_MSG_CTRL ** ** Bit definition for an ISO CAN FD frame with Standard Identifier ** (FBFF: FD base frame format) in the \c ubMsgCtrl field of the ** CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_FORMAT_FBFF (CP_MSG_CTRL_FDF_BIT) /*-------------------------------------------------------------------*/ /*! ** \def CP_MSG_FORMAT_FEFF ** \ingroup CP_MSG_CTRL ** ** Bit definition for an ISO CAN FD frame with Extended Identifier ** (FEFF: FD extended frame format) in the \c ubMsgCtrl field of the ** CpCanMsg_ts structure (CpCanMsg_s::ubMsgCtrl). */ #define CP_MSG_FORMAT_FEFF (CP_MSG_CTRL_FDF_BIT | CP_MSG_CTRL_EXT_BIT) /*-------------------------------------------------------------------*/ /*! ** \def CP_DATA_SIZE ** ** The symbol CP_DATA_SIZE defines the maximum number of bytes ** which are transferred inside the data field of a CAN message. ** For classic CAN frames the maximum number of bytes is 8, for ** CAN FD frames the maximum number of bytes is 64. */ #if CP_CAN_FD == 0 #define CP_DATA_SIZE ((uint8_t) 8) #else #define CP_DATA_SIZE ((uint8_t) 64) #endif /*----------------------------------------------------------------------------*/ /*! ** \enum CpErr_e ** \brief CANpie Error codes ** ** All functions that may cause an error condition will return an ** error code. The CANpie error codes are within the value range from ** 0 to 127. The designer of the core functions might extend the error code ** table with hardware specific error codes, which must be in the range ** from 128 to 255. */ enum CpErr_e { /*! No error (00dec / 00hex) */ eCP_ERR_NONE = 0, /*! Error not specified (01dec / 01hex) */ eCP_ERR_GENERIC = 1, /*! Hardware failure (02dec / 02hex) */ eCP_ERR_HARDWARE = 2, /*! Initialisation failure (03dec / 03hex) */ eCP_ERR_INIT_FAIL = 3, /*! Channel is initialised, ready to run (04dec / 04hex) */ eCP_ERR_INIT_READY = 4, /*! CAN channel was not initialised (05dec / 05hex) */ eCP_ERR_INIT_MISSING = 5, /*! Receive buffer is empty (06dec / 06hex) */ eCP_ERR_RCV_EMPTY = 6, /*! Receive buffer overrun (07dec / 07hex) */ eCP_ERR_RCV_OVERRUN = 7, /*! Transmit buffer is full (08dec / 08hex) */ eCP_ERR_TRM_FULL = 8, /*! CAN message has wrong format (10dec / 0Ahex) */ eCP_ERR_CAN_MESSAGE = 10, /*! CAN identifier not valid (11dec / 0Bhex) */ eCP_ERR_CAN_ID = 11, /*! CAN data length code not valid (12dec / 0Chex) */ eCP_ERR_CAN_DLC = 12, /*! FIFO is empty (20dec / 14hex) */ eCP_ERR_FIFO_EMPTY = 20, /*! Message is waiting in FIFO (21dec / 15hex) */ eCP_ERR_FIFO_WAIT = 21, /*! FIFO is full (22dec / 16hex) */ eCP_ERR_FIFO_FULL = 22, /*! FIFO size is out of range (23dec / 17hex) */ eCP_ERR_FIFO_SIZE = 23, /*! Parameter of FIFO function is out of range (24dec / 18hex) */ eCP_ERR_FIFO_PARAM = 24, /*! Controller is in error passive (30dec / 1Ehex) */ eCP_ERR_BUS_PASSIVE = 30, /*! Controller is in bus off (31dec / 1Fhex) */ eCP_ERR_BUS_OFF = 31, /*! Controller is in warning status (32dec / 20hex) */ eCP_ERR_BUS_WARNING = 32, /*! Channel out of range (40dec / 28hex) */ eCP_ERR_CHANNEL = 40, /*! Register address out of range (41dec / 29hex) */ eCP_ERR_REGISTER = 41, /*! bit-rate out of range (42dec / 2Ahex) */ eCP_ERR_BITRATE = 42, /*! Buffer number out of range (43dec / 2Bhex) */ eCP_ERR_BUFFER = 43, /*! Parameter number out of range (44dec / 2Chex) */ eCP_ERR_PARAM = 44, /*! Function is not supported (50dec / 32hex) */ eCP_ERR_NOT_SUPPORTED = 50 }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpCallback_e ** \brief Callback Return Codes ** ** These return values are used by the callback functions that can be ** installed by the function CpCoreIntFunctions(). <p> ** \b Example ** \code ** uint8_t MyCallback(CpCanMsg_ts * ptsCanMsgV, uint8_t ubBufferIdxV) ** { ** // Do something with IDs < 100 ** if( CpMsgGetIdentifier(ptsCanMsgV) < 100) ** { ** //..... ** return(eCP_CALLBACK_PROCESSED) ** } ** ** // Put all other messages into the FIFO ** return (eCP_CALLBACK_PUSH_FIFO); ** } ** \endcode ** <br> ** */ enum CpCallback_e { /*! ** Message was processed by callback and should not inserted in the FIFO */ eCP_CALLBACK_PROCESSED = 0, /*! ** Message was not processed by callback and must be inserted in the FIFO */ eCP_CALLBACK_PUSH_FIFO }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpBitrate_e ** \brief Fixed bit-rates ** ** The values of the enumeration CpBitrate_e are used as parameter for the ** function CpCoreBitrate(). */ enum CpBitrate_e { /*! ** No bit-rate defined */ eCP_BITRATE_NONE = -1, /*! ** bit-rate 10 kBit/s */ eCP_BITRATE_10K = 0, /*! ** bit-rate 20 kBit/s */ eCP_BITRATE_20K = 1, /*! ** bit-rate 50 kBit/s */ eCP_BITRATE_50K = 2, /*! ** bit-rate 100 kBit/s */ eCP_BITRATE_100K = 3, /*! ** bit-rate 125 kBit/s */ eCP_BITRATE_125K = 4, /*! ** bit-rate 250 kBit/s */ eCP_BITRATE_250K = 5, /*! ** bit-rate 500 kBit/s */ eCP_BITRATE_500K = 6, /*! ** bit-rate 800 kBit/s */ eCP_BITRATE_800K = 7, /*! ** bit-rate 1 MBit/s */ eCP_BITRATE_1M = 8, /*! ** bit-rate 2 MBit/s (ISO CAN FD, data phase) */ eCP_BITRATE_2M = 10, /*! ** bit-rate 4 MBit/s (ISO CAN FD, data phase) */ eCP_BITRATE_4M = 11, /*! ** bit-rate 5 MBit/s (ISO CAN FD, data phase) */ eCP_BITRATE_5M = 12, /*! ** Use automatic bit-rate detection ** \internal Do not change the value of this enumerator in order ** to keep compatibility. */ eCP_BITRATE_AUTO = 9, eCP_BITRATE_MAX = eCP_BITRATE_AUTO }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpChannel_e ** \brief Channel definition ** ** The physical CAN interfaces are numbered from 1 .. N (N: total ** number of physical CAN interfaces on the target system). The enumeration ** CpChannel_e lists up to 8 physical interfaces. The enumeration value ** eCP_CHANNEL_NONE denotes an invalid channel value. */ enum CpChannel_e { /*! CAN interface invalid */ eCP_CHANNEL_NONE = 0, /*! CAN interface 1 */ eCP_CHANNEL_1, /*! CAN interface 2 */ eCP_CHANNEL_2, /*! CAN interface 3 */ eCP_CHANNEL_3, /*! CAN interface 4 */ eCP_CHANNEL_4, /*! CAN interface 5 */ eCP_CHANNEL_5, /*! CAN interface 6 */ eCP_CHANNEL_6, /*! CAN interface 7 */ eCP_CHANNEL_7, /*! CAN interface 8 */ eCP_CHANNEL_8 }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpMode_e ** \brief Mode of CAN controller ** ** These values are used as parameter for the function CpCoreCanMode() in ** order to change the state of the CAN controller. */ enum CpMode_e { /*! Set controller in 'Initialization' mode (no reception or ** transmission possible) */ eCP_MODE_INIT = 0, eCP_MODE_STOP = 0, // deprecated definition /*! Set controller into 'Operation' mode */ eCP_MODE_OPERATION = 1, eCP_MODE_START = 1, // deprecated definition /*! Set controller into 'Listen-only' mode */ eCP_MODE_LISTEN_ONLY = 2, /*! Set controller into 'Sleep' (power-down) mode */ eCP_MODE_SLEEP = 3, /*! Set controller into 'Self-test' mode */ eCP_MODE_SELF_TEST = 4 }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpState_e ** \brief State of CAN controller ** ** These values are used as return value for the function CpCoreCanState(). */ enum CpState_e { /*! ** CAN controller is in stopped mode */ eCP_STATE_INIT = 0, eCP_STATE_STOPPED = 0, // deprecated definition /*! ** CAN controller is in Sleep mode */ eCP_STATE_SLEEPING = 1, /*! ** CAN controller is error active */ eCP_STATE_BUS_ACTIVE = 2, /*! ** CAN controller is active, warning level is reached */ eCP_STATE_BUS_WARN = 3, /*! ** CAN controller is error passive */ eCP_STATE_BUS_PASSIVE = 4, /*! ** CAN controller went into Bus Off */ eCP_STATE_BUS_OFF = 5, /*! ** General failure of physical layer detected (if supported by hardware) */ eCP_STATE_PHY_FAULT = 10, /*! ** Fault on CAN-H detected (Low Speed CAN) */ eCP_STATE_PHY_H = 11, /*! ** Fault on CAN-L detected (Low Speed CAN) */ eCP_STATE_PHY_L = 12 }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpErrType_e ** \brief Error type ** ** These values are used as return value for the function CpCoreCanState(). */ enum CpErrType_e { /*! No error */ eCP_ERR_TYPE_NONE = 0, /*! Bit 0 error */ eCP_ERR_TYPE_BIT0, /*! Bit 1 error */ eCP_ERR_TYPE_BIT1, /*! Stuff error */ eCP_ERR_TYPE_STUFF, /*! Format error */ eCP_ERR_TYPE_FORM, /*! CRC error */ eCP_ERR_TYPE_CRC, /*! Acknowledge error */ eCP_ERR_TYPE_ACK }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpBuffer_e ** \brief Buffer definition ** ** The enumeration CpBuffer_e is used to define a message buffer inside a ** FullCAN controller. The index for the first buffer starts at 0. */ enum CpBuffer_e { /*! Buffer number 1 */ eCP_BUFFER_1 = 0, /*! Buffer number 2 */ eCP_BUFFER_2, /*! Buffer number 3 .. */ eCP_BUFFER_3, eCP_BUFFER_4, eCP_BUFFER_5, eCP_BUFFER_6, eCP_BUFFER_7, eCP_BUFFER_8, eCP_BUFFER_9, eCP_BUFFER_10, eCP_BUFFER_11, eCP_BUFFER_12, eCP_BUFFER_13, eCP_BUFFER_14, eCP_BUFFER_15, /*! Buffer number 16 */ eCP_BUFFER_16 }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpBufferDir_e ** \brief Buffer direction definition ** ** The enumeration CpBufferDir_e is used to define the direction of ** a message buffer (transmit or receive). The enumeration values are ** used by the function CpCoreBufferConfig(). ** */ enum CpBufferDir_e { /*! Message buffer direction is receive */ eCP_BUFFER_DIR_RCV = 0, /*! Message buffer direction is transmit */ eCP_BUFFER_DIR_TRM }; /*----------------------------------------------------------------------------*/ /*! ** \enum CpRpc_e ** \brief Remote Procedure Call definition ** ** The enumeration CpRpc_e is used to define different Remote Procedure ** Calls. The enumeration values are used by the function #CpMsgRpcType() to ** identify a Remote Procedure Call upon reception. */ enum CpRpc_e { /*! RPC for no operation */ eCP_RPC_NOOP = 0, /*! RPC for #CpCoreCanMode() */ eCP_RPC_MODE, /*! RPC for CpCoreBitrate() */ eCP_RPC_BITRATE, eCP_RPC_MAX }; /*----------------------------------------------------------------------------*\ ** Structures ** ** ** \*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /*! ** \struct CpTime_s canpie.h ** \brief CAN time structure ** */ typedef struct CpTime_s { /*! ** Seconds since the year 1970 */ uint32_t ulSec1970; /*! ** Nano-seconds, with an overflow value of 999999999 */ uint32_t ulNanoSec; } CpTime_ts; /*----------------------------------------------------------------------------*/ /*! ** \struct CpCanMsg_s ** \brief CAN message structure ** ** For transmission and reception of CAN messages a structure which holds ** all necessary informations is used. The structure has the following ** data fields: */ typedef struct CpCanMsg_s { /*! ** The identifier field may have 11 bits for standard frames ** (CAN specification 2.0A) or 29 bits for extended frames ** (CAN specification 2.0B). The three most significant bits ** are reserved (always read 0). ** \see CP_MASK */ uint32_t ulIdentifier; /*! ** The data field has up to 8 bytes (for classic CAN) or ** 64 bytes (for ISO CAN FD) of message data. ** The number of used bytes is described via the structure ** member \c ubMsgDLC. */ union { /*! byte access, array of bytes */ uint8_t aubByte[CP_DATA_SIZE]; /*! 16 bit access, array of words */ uint16_t auwWord[CP_DATA_SIZE / 2]; /*! 32 bit access, array of longs */ uint32_t aulLong[CP_DATA_SIZE / 4]; /*! 64 bit access, array of quadwords */ #if CPP_DATA_SIZE > 32 uint64_t auqQuad[CP_DATA_SIZE / 8]; #endif } tuMsgData; /*! ** The data length code denotes the number of data bytes ** which are transmitted by a message. ** The possible value range for the data length code is ** from 0 to 8 for classic CAN and 0 to 15 for ISO CAN FD. */ uint8_t ubMsgDLC; /*! ** The structure member \c ubMsgCtrl defines the ** different data frames (2.0A / 2.0B) and the RTR frames. ** <ul> ** <li>Bit 0: Std. / Ext. Frame ** <li>Bit 1: ISO CAN FD: value of FDF bit ** <li>Bit 2: Remote Frame ** <li>Bit 3: Overload Frame ** <li>Bit 4: Remote Procedure Call ** <li>Bit 5: reserved, always 0 ** <li>Bit 6: ISO CAN FD: value of BRS bit ** <li>Bit 7: ISO CAN FD: value of ESI bit ** </ul> ** \see CP_MSG_CTRL */ uint8_t ubMsgCtrl; #if CP_CAN_MSG_TIME == 1 /*! ** The time stamp field defines the time when a CAN message ** was received by the CAN controller. This is an optional ** field (available if #CP_CAN_MSG_TIME is set to 1). */ CpTime_ts tsMsgTime; #endif #if CP_CAN_MSG_USER == 1 /*! ** The field user data can hold a 32 bit value, which is ** defined by the user. This is an optional field ** (available if #CP_CAN_MSG_USER is set to 1). */ uint32_t ulMsgUser; #endif #if CP_CAN_MSG_MARKER == 1 /*! ** The field message marker can hold a 32 bit value, which is ** defined by the application. This is an optional field ** (available if #CP_CAN_MSG_MARKER is set to 1). */ uint32_t ulMsgMarker; #endif } CpCanMsg_ts; /*----------------------------------------------------------------------------*/ /*! ** \struct CpHdi_s canpie.h ** \brief Hardware description interface ** ** The Hardware Description Interface provides a method to gather ** information about the CAN hardware and the functionality of the driver. ** The hardware description structure is available for every physical ** CAN channel. */ typedef struct CpHdi_s { /*! ** Major version number of CANpie API */ uint8_t ubVersionMajor; /*! ** Minor version number of CANpie API */ uint8_t ubVersionMinor; /*! ** The element \a ubCanFeatures defines the capabilities of the CAN ** controller. Reserved bit values are read as 0. ** <ul> ** <li>Bit 0: 0 = 2.0A support, 1 = 2.0B support ** <li>Bit 1: 0 = Classic CAN , 1 = ISO CAN FD ** <li>Bit 2: reserved ** <li>Bit 3: reserved ** <li>Bit 4: reserved ** <li>Bit 5: reserved ** <li>Bit 6: reserved ** <li>Bit 7: reserved ** </ul> */ uint8_t ubCanFeatures; /*! ** The element \a ubDriverFeatures defines the capabilities of the ** software driver. Reserved bit values are read as 0. ** <ul> ** <li>Bit 0: 0 = no time stamp, 1 = time stamp support ** <li>Bit 1: 0 = no user data , 1 = user data support ** <li>Bit 2: reserved ** <li>Bit 3: reserved ** <li>Bit 4: reserved ** <li>Bit 5: reserved ** <li>Bit 6: reserved ** <li>Bit 7: reserved ** </ul> */ uint8_t ubDriverFeatures; /*! ** The element \a ubBufferMax defines the total number of CAN ** message buffers (mailboxes). */ uint8_t ubBufferMax; /*! ** Major version number of driver */ uint8_t ubDriverMajor; /*! ** Minor version number of driver */ uint8_t ubDriverMinor; /*! ** reserved element (alignment) */ uint8_t ubReserved[1]; /*! ** Resolution of optional time stamp in nano-seconds. */ uint32_t ulTimeStampRes; /*! ** Clock rate of CAN controller in Hertz. */ uint32_t ulCanClock; /*! ** The element \a ulBitRateMin defines the lowest configurable bit-rate ** in bits-per-second (bps). The value is specified through the used CAN ** transceiver. */ uint32_t ulBitRateMin; /*! ** The element \a ulBitRateMax defines the highest configurable bit-rate ** in bits-per-second (bps). The value is specified through the used ** CAN transceiver. */ uint32_t ulBitRateMax; /*! ** The element \a slNomBitRate defines the actual configured bit-rate ** of the CAN controller in bits-per-second (bps). For ISO CAN FD ** the value defines the bit-rate of the arbitration phase. */ int32_t slNomBitRate; /*! ** The element slDatBitRate is only valid for ISO CAN FD controller. ** The value defines the actual configured bit-rate of the data phase ** in bits-per-second (bps). */ int32_t slDatBitRate; } CpHdi_ts; /*----------------------------------------------------------------------------*/ /*! ** \struct CpStatistic_s canpie.h ** \brief CAN statistic structure ** */ typedef struct CpStatistic_s { /*! Total number of received data & remote frames */ uint32_t ulRcvMsgCount; /*! Total number of transmitted data & remote frames */ uint32_t ulTrmMsgCount; /*! Total number of error frames */ uint32_t ulErrMsgCount; } CpStatistic_ts; /*----------------------------------------------------------------------------*/ /*! ** \struct CpState_s canpie.h ** \brief CAN state structure ** */ typedef struct CpState_s { /*! CAN error state ** Value should correspond to values from #CpState_e */ uint8_t ubCanErrState; /*! Last error type occurred ** Value should correspond to values from #CpErrType_e */ uint8_t ubCanErrType; /*! receive error counter */ uint8_t ubCanRcvErrCnt; /*! transmit error counter */ uint8_t ubCanTrmErrCnt; } CpState_ts; #endif /* CANPIE_H_ */
26.541961
80
0.538075
5ff8191cabed05792aa7abeb9dd80ddf8cea3574
3,850
h
C
gpio/gpio.h
mikejac/esp-open-rtos.gpio.esp8266-nonos.cpp
bc329410fe9a9d6070707f56141570281bcf8125
[ "MIT" ]
null
null
null
gpio/gpio.h
mikejac/esp-open-rtos.gpio.esp8266-nonos.cpp
bc329410fe9a9d6070707f56141570281bcf8125
[ "MIT" ]
null
null
null
gpio/gpio.h
mikejac/esp-open-rtos.gpio.esp8266-nonos.cpp
bc329410fe9a9d6070707f56141570281bcf8125
[ "MIT" ]
null
null
null
/** esp_iomux.h * * GPIO functions. * * Part of esp-open-rtos * Copyright (C) 2015 Superhouse Automation Pty Ltd * BSD Licensed as described in the file LICENSE */ #ifndef _ESP_GPIO_H #define _ESP_GPIO_H #include <stdbool.h> #include "gpio_regs.h" #include "iomux.h" //#include "esp/cpu.h" //#include "xtensa_interrupts.h" #ifdef __cplusplus extern "C" { #endif typedef enum { GPIO_INPUT, GPIO_OUTPUT, /* "Standard" push-pull output */ GPIO_OUT_OPEN_DRAIN, /* Open drain output */ GPIO_INPUT_PULLUP, } gpio_direction_t; #define INLINED inline static __attribute__((always_inline)) __attribute__((unused)) /* Enable GPIO on the specified pin, and set it to input/output/ with * pullup as needed */ INLINED void gpio_enable(const uint8_t gpio_num, const gpio_direction_t direction) { uint32_t iomux_flags = 0; switch(direction) { case GPIO_INPUT: iomux_flags = 0; break; case GPIO_OUTPUT: iomux_flags = IOMUX_PIN_OUTPUT_ENABLE; break; case GPIO_OUT_OPEN_DRAIN: iomux_flags = IOMUX_PIN_OUTPUT_ENABLE; break; case GPIO_INPUT_PULLUP: iomux_flags = IOMUX_PIN_PULLUP; break; } iomux_set_gpio_function(gpio_num, iomux_flags); if(direction == GPIO_OUT_OPEN_DRAIN) GPIO.CONF[gpio_num] |= GPIO_CONF_OPEN_DRAIN; else GPIO.CONF[gpio_num] &= ~GPIO_CONF_OPEN_DRAIN; if (iomux_flags & IOMUX_PIN_OUTPUT_ENABLE) GPIO.ENABLE_OUT_SET = BIT(gpio_num); else GPIO.ENABLE_OUT_CLEAR = BIT(gpio_num); } /* Disable GPIO on the specified pin, and set it Hi-Z. * * If later muxing this pin to a different function, make sure to set * IOMUX_PIN_OUTPUT_ENABLE if necessary to enable the output buffer. */ INLINED void gpio_disable(const uint8_t gpio_num) { GPIO.ENABLE_OUT_CLEAR = BIT(gpio_num); *gpio_iomux_reg(gpio_num) &= ~IOMUX_PIN_OUTPUT_ENABLE; } /* Set output of a pin high or low. * * Only works if pin has been set to GPIO_OUTPUT via gpio_enable() */ INLINED void gpio_write(const uint8_t gpio_num, const bool set) { if(set) GPIO.OUT_SET = BIT(gpio_num); else GPIO.OUT_CLEAR = BIT(gpio_num); } /* Toggle output of a pin * * Only works if pin has been set to GPIO_OUTPUT via gpio_enable() */ INLINED void gpio_toggle(const uint8_t gpio_num) { /* Why implement like this instead of GPIO_OUT_REG ^= xxx? Concurrency. If an interrupt or higher priority task writes to GPIO_OUT between reading and writing, only the gpio_num pin can get an invalid value. Prevents one task from clobbering another task's pins, without needing to disable/enable interrupts. */ if(GPIO.OUT & BIT(gpio_num)) GPIO.OUT_CLEAR = BIT(gpio_num); else GPIO.OUT_SET = BIT(gpio_num); } /* Read input value of a GPIO pin. * * If pin is set as an input, this reads the value on the pin. * If pin is set as an output, this reads the last value written to the pin. */ INLINED bool gpio_read(const uint8_t gpio_num) { return GPIO.IN & BIT(gpio_num); } extern void gpio_interrupt_handler(void); /* Set the interrupt type for a given pin * * If int_type is not GPIO_INTTYPE_NONE, the gpio_interrupt_handler will be attached and unmasked. */ #if 0 INLINED void gpio_set_interrupt(const uint8_t gpio_num, const gpio_inttype_t int_type) { GPIO.CONF[gpio_num] = SET_FIELD(GPIO.CONF[gpio_num], GPIO_CONF_INTTYPE, int_type); if(int_type != GPIO_INTTYPE_NONE) { _xt_isr_attach(INUM_GPIO, gpio_interrupt_handler); _xt_isr_unmask(1<<INUM_GPIO); } } #endif /* Return the interrupt type set for a pin */ INLINED gpio_inttype_t gpio_get_interrupt(const uint8_t gpio_num) { return (gpio_inttype_t)FIELD2VAL(GPIO_CONF_INTTYPE, GPIO.CONF[gpio_num]); } #ifdef __cplusplus } #endif #endif
27.304965
98
0.706234
16b6b9665d8085f92e832ca3ce6223e96bcc89c1
332
h
C
pebble/src/seatop_point.h
ntbrock/seatop-watch-pebble
a5de50b1a7a39e967ad6e0557369a7877fcc49d2
[ "MIT" ]
null
null
null
pebble/src/seatop_point.h
ntbrock/seatop-watch-pebble
a5de50b1a7a39e967ad6e0557369a7877fcc49d2
[ "MIT" ]
null
null
null
pebble/src/seatop_point.h
ntbrock/seatop-watch-pebble
a5de50b1a7a39e967ad6e0557369a7877fcc49d2
[ "MIT" ]
null
null
null
#pragma once #include <pebble.h> // Global Singleton values SeatopPointSummary channel1_summary; SeatopPointSummary channel2_summary; SeatopPointDistro channel1_distro; SeatopPointDistro channel2_distro; int on_inbox_received_seatop_message ( Tuple *t ); void on_point_summary_recv( int channel, SeatopPointSummary *summary );
23.714286
71
0.837349
7590d190e9966fe648a049ac2a66590d6a7df395
977
c
C
usr.bin/uucp/uucico/chksum.c
weiss/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
114
2015-01-18T22:55:52.000Z
2022-02-17T10:45:02.000Z
usr.bin/uucp/uucico/chksum.c
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
null
null
null
usr.bin/uucp/uucico/chksum.c
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
29
2015-11-03T22:05:22.000Z
2022-02-08T15:36:37.000Z
/*- * Copyright (c) 1985, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.proprietary.c% */ #ifndef lint static char sccsid[] = "@(#)chksum.c 8.1 (Berkeley) 06/06/93"; #endif /* not lint */ #ifndef pdp11 chksum (s, n) register char *s; register n; { register long sum, x, t; sum = 0xffff; x = 0; do { /* Rotate left, copying bit 15 to bit 0 */ sum <<= 1; if (sum & 0x10000) sum ^= 0x10001; t = sum; sum = (sum + (*s++ & 0377)) & 0xffff; x += sum ^ n; if (sum <= t) sum = (sum ^ x) & 0xffff; } while (--n > 0); return (long) (short) sum; } #else pdp11 chksum(s,n) register char *s; register n; { register unsigned sum, t; register x; sum = -1; x = 0; do { if (sum&0x8000) { sum <<= 1; sum++; } else sum <<= 1; t = sum; sum += (unsigned)*s++ & 0377; x += sum^n; if ((sum&0xffff) <= (t&0xffff)) { sum ^= x; } } while (--n > 0); return sum & 0xffff; } #endif pdp11
15.265625
69
0.544524
ce1310c3220fce1cc46b62ccefb7d1d61c419947
2,453
h
C
TheEngineSample/RoomRayModel.h
natalieagus/Original-Binaural-Reverb
15cb56203c432d7768f6674b8e80ea3902c2ff11
[ "Zlib" ]
null
null
null
TheEngineSample/RoomRayModel.h
natalieagus/Original-Binaural-Reverb
15cb56203c432d7768f6674b8e80ea3902c2ff11
[ "Zlib" ]
null
null
null
TheEngineSample/RoomRayModel.h
natalieagus/Original-Binaural-Reverb
15cb56203c432d7768f6674b8e80ea3902c2ff11
[ "Zlib" ]
1
2018-12-16T15:03:53.000Z
2018-12-16T15:03:53.000Z
// // RoomRayModel.h // TheEngineSample // // Created by Hans on 6/11/15. // Copyright © 2015 A Tasty Pixel. All rights reserved. // #ifndef RoomRayModel_h #define RoomRayModel_h #include <stdio.h> #include "Vector3D.hpp" #include "mactypes.h" #define RRM_MAX_CORNERS 100 class RoomRayModel { private: Vector3D corners[RRM_MAX_CORNERS]; Vector3D wallOrientations[RRM_MAX_CORNERS]; float wallLengths[RRM_MAX_CORNERS]; size_t numCorners; float totalWallLength; void setBouncePoints(Vector3D* bouncePoints, Vector3D wallOrientation, Vector3D wallStart, float wallLength, size_t numPoints, float* outputGains2, float* inputGains2, Vector3D* BP); Vector3D getBP(float pointSpacing, Vector3D wallStart, size_t i, Vector3D wallOrientation, float randFlt); //original integration method float getGain(Vector3D start, Vector3D end, Vector3D loc); float integrate(Vector3D start, Vector3D end, float t, Vector3D loc, Vector3D vn); //Simple integration method float integrationSimple(Vector3D loc, float x, bool listLoc); Vector3D align(Vector3D point, Vector3D wallvector); float xAlignedIntegration(Vector3D loc, Vector3D ptStart, Vector3D ptEnd, bool listLoc); void setFloorBouncePointsGain(Vector3D* bouncePoints, float* inputGain, float* outputGain, size_t floorTaps); void gridBP(Vector3D* floorBouncePoints, size_t floorTaps); float pythagorasGain(Vector3D loc, Vector3D* bouncePoint, float height); Vector3D soundSourceLoc; Vector3D listenerLoc; size_t floorTapsPerDimension; float getMaxGain(float xLower, float xUpper, float yLower, float yUpper); float calcMaxGain(float x, float y); float maxFloorGain = 1.55463f; float gridArea; float numWallPoints; public: RoomRayModel(); void setRoomGeometry(Vector3D* corners, size_t numCorners); void setLocation(float* rayLengths,size_t numTaps, Vector3D listenerLocation, Vector3D soundSourceLocation, Vector3D* bouncePoints, float* outputGains2, float* inputGains2, size_t floorTaps, Vector3D* BP); void setRayTracingPoints(Vector3D* bouncePoints, Vector3D ssLocation, float rheight, float rwidth, int numpoints, float* outputGains, float* inputGains,Vector3D listloc); // void setRayTracingPoints(Vector3D* bouncePoints, Vector3D ssLoc, float rheight, float rwidth, int numpoints,Vector3D listloc); }; #endif /* RoomRayModel_h */
37.738462
209
0.753363
385c6a128ab47eae6510d35cb7f2646e7d4be1d2
731
h
C
Pods/WHC_AutoLayoutKit/WHC_AutoLayoutKit/Util/WHC_AutoLayoutUtilities.h
lobular/noun
5c6c4c087bfa788533ba8247ba1a40a84c213128
[ "MIT" ]
990
2016-03-02T05:43:28.000Z
2022-03-22T03:16:53.000Z
Pods/WHC_AutoLayoutKit/WHC_AutoLayoutKit/Util/WHC_AutoLayoutUtilities.h
lobular/noun
5c6c4c087bfa788533ba8247ba1a40a84c213128
[ "MIT" ]
25
2016-03-16T08:46:16.000Z
2021-08-04T02:24:54.000Z
Pods/WHC_AutoLayoutKit/WHC_AutoLayoutKit/Util/WHC_AutoLayoutUtilities.h
lobular/noun
5c6c4c087bfa788533ba8247ba1a40a84c213128
[ "MIT" ]
181
2016-03-02T05:44:29.000Z
2021-08-14T01:25:11.000Z
// // WHC_AutoLayoutUtilities.h // WHC_AutoLayoutKit // // Created by WHC on 17/4/12. // Copyright © 2017年 WHC. All rights reserved. // #import <Foundation/Foundation.h> #if TARGET_OS_IPHONE || TARGET_OS_TV #define WHC_CLASS_VIEW UIView #define WHC_CLASS_LGUIDE UILayoutGuide #define WHC_VIEW NSObject #define WHC_LayoutPriority UILayoutPriority #define WHC_ConstraintAxis UILayoutConstraintAxis #define WHC_COLOR UIColor #import <UIKit/UIKit.h> #elif TARGET_OS_MAC #define WHC_CLASS_VIEW NSView #define WHC_CLASS_LGUIDE NSLayoutGuide #define WHC_VIEW NSObject #define WHC_LayoutPriority NSLayoutPriority #define WHC_ConstraintAxis NSLayoutConstraintOrientation #define WHC_COLOR NSColor #import <AppKit/AppKit.h> #endif
22.84375
56
0.818057
cd9f146f67c136dd6c7766eb6ba5b461804ccd52
3,494
c
C
sys/src/cmd/rx.c
Plan9-Archive/plan9-2e
ce6d0434246216e848babe4f56919dc28981ad04
[ "MIT" ]
1
2021-03-23T22:40:43.000Z
2021-03-23T22:40:43.000Z
sys/src/cmd/rx.c
Plan9-Archive/plan9-2e
ce6d0434246216e848babe4f56919dc28981ad04
[ "MIT" ]
null
null
null
sys/src/cmd/rx.c
Plan9-Archive/plan9-2e
ce6d0434246216e848babe4f56919dc28981ad04
[ "MIT" ]
1
2021-12-21T06:19:58.000Z
2021-12-21T06:19:58.000Z
#include <u.h> #include <libc.h> #include <auth.h> int eof; /* send an eof if true */ char *note = "die: yankee dog"; void rex(int, char*); void dkexec(int, char*, char*); void tcpexec(int, char*, char*); int call(char *, char*, char*, char**); char *buildargs(char*[]); int send(int); void error(char*, char*); void usage(void) { fprint(2, "usage: %s [-e] net!host command...\n", argv0); exits("usage"); } void main(int argc, char *argv[]) { char *host, *addr, *args; int fd; eof = 1; ARGBEGIN{ case 'e': eof = 0; break; default: usage(); }ARGEND if(argc < 2) usage(); host = argv[0]; args = buildargs(&argv[1]); /* generic attempts */ fd = call(0, host, "rexexec", &addr); if(fd >= 0) rex(fd, args); fd = call(0, host, "exec", &addr); if(fd >= 0) dkexec(fd, addr, args); /* specific attempts */ fd = call("tcp", host, "shell", &addr); tcpexec(fd, addr, args); fd = call("dk", host, "exec", &addr); if(fd >= 0) dkexec(fd, addr, args); error("can't dial", host); exits(0); } int call(char *net, char *host, char *service, char **na) { *na = netmkaddr(host, net, service); return dial(*na, 0, 0, 0); } void rex(int fd, char *cmd) { char buf[4096]; int kid, n; if(auth(fd) < 0){ close(fd); error("authenticate fails", 0); } write(fd, cmd, strlen(cmd)+1); kid = send(fd); while((n=read(fd, buf, sizeof buf))>0) if(write(1, buf, n)!=n) error("write error", 0); sleep(250); postnote(PNPROC, kid, note);/**/ exits(0); } void dkexec(int fd, char *addr, char *cmd) { char buf[4096]; int kid, n; if(read(fd, buf, 1)!=1 || *buf!='O' || read(fd, buf, 1)!=1 || *buf!='K'){ close(fd); error("can't authenticate to", addr); } write(fd, cmd, strlen(cmd)+1); kid = send(fd); while((n=read(fd, buf, sizeof buf))>0) if(write(1, buf, n)!=n) error("write error", 0); sleep(250); postnote(PNPROC, kid, note);/**/ exits(0); } void tcpexec(int fd, char *addr, char *cmd) { char *u, buf[4096]; int kid, n; /* * do the ucb authentication and send command */ u = getuser(); if(write(fd, "", 1)<0 || write(fd, u, strlen(u)+1)<0 || write(fd, u, strlen(u)+1)<0 || write(fd, cmd, strlen(cmd)+1)<0){ close(fd); error("can't authenticate to", addr); } /* * get authentication reply */ if(read(fd, buf, 1) != 1){ close(fd); error("can't authenticate to", addr); } if(buf[0] != 0){ while(read(fd, buf, 1) == 1){ write(2, buf, 1); if(buf[0] == '\n') break; } close(fd); error("rejected by", addr); } kid = send(fd); while((n=read(fd, buf, sizeof buf))>0) if(write(1, buf, n)!=n) error("write error", 0); sleep(250); postnote(PNPROC, kid, note);/**/ exits(0); } int send(int fd) { char buf[4096]; int n; int kid; switch(kid = fork()){ case -1: error("fork error", 0); case 0: break; default: return kid; } while((n=read(0, buf, sizeof buf))>0) if(write(fd, buf, n)!=n) exits("write error"); if(eof) write(fd, buf, 0); exits(0); return 0; /* to keep compiler happy */ } void error(char *s, char *z) { if(z == 0) fprint(2, "%s: %s: %r\n", argv0, s); else fprint(2, "%s: %s %s: %r\n", argv0, s, z); exits(s); } char * buildargs(char *argv[]) { char *args; int m, n; args = malloc(1); args[0] = '\0'; n = 0; while(*argv){ m = strlen(*argv) + 1; args = realloc(args, n+m +1); if(args == 0) error("malloc fail", 0); args[n] = ' '; /* smashes old null */ strcpy(args+n+1, *argv); n += m; argv++; } return args; }
16.717703
68
0.560103
e06e408f5287121175bb38e12e10fcc22fea7a58
356
h
C
project/src/mountainpeakfeature.h
ebirenbaum/yurtcraft
4d5ee607e902dfa7db60e7e0b6736cd6d4704e70
[ "MIT" ]
null
null
null
project/src/mountainpeakfeature.h
ebirenbaum/yurtcraft
4d5ee607e902dfa7db60e7e0b6736cd6d4704e70
[ "MIT" ]
null
null
null
project/src/mountainpeakfeature.h
ebirenbaum/yurtcraft
4d5ee607e902dfa7db60e7e0b6736cd6d4704e70
[ "MIT" ]
null
null
null
#ifndef MOUNTAINPEAKFEATURE_H #define MOUNTAINPEAKFEATURE_H #include "terrainfeature.h" class MountainPeakFeature : public TerrainFeature { public: MountainPeakFeature(); MountainPeakFeature* clone(Vector3 _pos, BiomeGenInfo *_baseInfo); unsigned char generateBlock(Vector3 _address, BiomeGenInfo *_info); }; #endif // MOUNTAINPEAKFEATURE_H
23.733333
71
0.797753
a319168688af6ed617587414a22fcb40b0a7627f
1,676
h
C
src/frontend/Experimental_OpenFortranParser_ROSE_Connection/UntypedTraversal.h
mschordan/rose
4db6f809299d13bd00b0a73e1c781094b852288f
[ "BSD-3-Clause" ]
1
2021-02-05T21:47:27.000Z
2021-02-05T21:47:27.000Z
src/frontend/Experimental_OpenFortranParser_ROSE_Connection/UntypedTraversal.h
mschordan/rose
4db6f809299d13bd00b0a73e1c781094b852288f
[ "BSD-3-Clause" ]
null
null
null
src/frontend/Experimental_OpenFortranParser_ROSE_Connection/UntypedTraversal.h
mschordan/rose
4db6f809299d13bd00b0a73e1c781094b852288f
[ "BSD-3-Clause" ]
null
null
null
#ifndef UNTYPED_TRAVERSAL_H #define UNTYPED_TRAVERSAL_H //----------------------------------------------------------------------------------- // The SgUntyped::UntypedTraversal class is used to traverse SgUntypedNodes and // convert them to regular SgNodes. //----------------------------------------------------------------------------------- namespace Fortran { namespace Untyped { typedef SgScopeStatement* InheritedAttribute; typedef SgExpression* SynthesizedAttribute; class UntypedTraversal : public SgTopDownBottomUpProcessing<InheritedAttribute,SynthesizedAttribute> { public: virtual InheritedAttribute evaluateInheritedAttribute (SgNode* n, InheritedAttribute inheritedAttribute ); virtual SynthesizedAttribute evaluateSynthesizedAttribute (SgNode* n, InheritedAttribute inheritedAttribute , SynthesizedAttributesList childAttrs ); static SgExpression* convert_SgUntypedExpression (SgUntypedExpression* untyped_expression); static SgValueExp* convert_SgUntypedValueExpression (SgUntypedValueExpression* untyped_value); static SgUnaryOp* convert_SgUntypedUnaryOperator (SgUntypedUnaryOperator* untyped_operator, SgExpression* expr); static SgBinaryOp* convert_SgUntypedBinaryOperator(SgUntypedBinaryOperator* untyped_operator, SgExpression* lhs, SgExpression* rhs); UntypedTraversal(SgSourceFile* sourceFile); private: SgSourceFile* p_source_file; static void initialize_global_scope(SgSourceFile* file); }; } // namespace Fortran } // namespace Untyped // endif for UNTYPED_TRAVERSAL_H #endif
38.090909
138
0.683174
ef78bcf21fbb67983228d78a0191ac02db278eeb
85
h
C
natives/colors.h
Tetracyl/esmBot
7248621048e11c85097ee5d946f552ce0c36ffd4
[ "MIT" ]
197
2020-09-05T22:10:34.000Z
2022-03-30T08:37:22.000Z
natives/colors.h
Tetracyl/esmBot
7248621048e11c85097ee5d946f552ce0c36ffd4
[ "MIT" ]
214
2020-09-04T04:26:29.000Z
2022-03-29T14:28:40.000Z
natives/colors.h
Tetracyl/esmBot
7248621048e11c85097ee5d946f552ce0c36ffd4
[ "MIT" ]
122
2020-09-08T00:10:00.000Z
2022-03-29T09:23:36.000Z
#pragma once #include <napi.h> Napi::Value Colors(const Napi::CallbackInfo& info);
14.166667
51
0.729412
dce21cfe3d4f998e6fc29ff2400092a482cc8188
14,434
c
C
src/lossy/main.c
isaacmorneau/7005-asn4
946fc73efba58be2afd6f9b1330c6ff3582046e9
[ "MIT" ]
null
null
null
src/lossy/main.c
isaacmorneau/7005-asn4
946fc73efba58be2afd6f9b1330c6ff3582046e9
[ "MIT" ]
null
null
null
src/lossy/main.c
isaacmorneau/7005-asn4
946fc73efba58be2afd6f9b1330c6ff3582046e9
[ "MIT" ]
null
null
null
/* * ===================================================================================== * * Filename: main.c * * Project: 7005-asn4-lossy * * Description: This file is the implementation of the lossy server's command parsing * and epoll implementation. * * Functions: print_help(); * __iter_div_u64_rem(); * timespec_add_ns(); * main(); * * * Version: 1.0 * Created: 12/02/2017 03:27:32 PM * Revision: none * * Author: Isaac Morneau (im), isaacmorneau@gmail.com * * ===================================================================================== */ #include <stdlib.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <time.h> #include "wrapper.h" #include "errors.h" #define SOCKOPTS "p:f:t:a:e:h" #define MAXEVENTS 64 #define ERROR_DROP 0 #define ERROR_BER 1 #define ERROR_WAIT 2 #define MICRO_IN_SEC 1000ul * 1000ul #define NANO_IN_SEC 1000ul * MICRO_IN_SEC /* * === FUNCTION ====================================================================== * Name: print_help * Description: print the help message for the program * Parameters: void * Return: void * ===================================================================================== */ static inline void print_help() { printf("usage options:\n" "\t [p]ort <1-65535> - the port to listen to\n" "\t [f]orward <1-65535> - the port to forward to\n" "\t [a]ddress <url || ip> - the address forward to\n" "\t [e]rror <percentage> - the error rate, default is no errors\n" "\t [t]ype <D || B || W[microseconds]> - the type of error to have\n" "\t\t D is to drop packets, default type\n" "\t\t B is BER to corrupt packets in percent such as B5.0\n" "\t\t W is time to wait in microseconds such as W100\n" "\t [h]elp - this message\n" ); } /* * === FUNCTION ====================================================================== * Name: __iter_div_u64_rem * Description: quickly adds remainer and fall over to two numbers * thanks to https://eastskykang.wordpress.com/2015/03/24/138/ * Parameters: uint64_t dividend - the dividend * uint32_t divisor - the divisor * uint64_t *remainder - where to store the remainder * Return: uint32_t - the main un overflowed int * ===================================================================================== */ static inline uint32_t __iter_div_u64_rem(uint64_t dividend, uint32_t divisor, uint64_t *remainder) { uint32_t ret = 0; while (dividend >= divisor) { /* The following asm() prevents the compiler from optimising this loop into a modulo operation. */ __asm__("": "+rm"(dividend)); dividend -= divisor; ret++; } *remainder = dividend; return ret; } /* * === FUNCTION ====================================================================== * Name: timespec_add_ns * Description: add time to timespec struct * Parameters: struct timespec * a - the structure to add to * uint64_t ns - nanoseconds to add * Return: void * ===================================================================================== */ static inline void timespec_add_ns(struct timespec *a, uint64_t ns) { a->tv_sec += __iter_div_u64_rem(a->tv_nsec + ns, NANO_IN_SEC, &ns); a->tv_nsec = ns; } /* * === FUNCTION ====================================================================== * Name: main * Description: the main funtion of the program and the entry point * initializes error rate as well as starting and running the lossy * server * Parameters: int argc - the number of arguments * char ** argv - the array of arguments * Return: int - the return value of the program * ===================================================================================== */ int main(int argc, char ** argv) { char * port= 0; char * forward = 0; char * address = 0; char * drop = 0; int handshake_delay = 4; int error_type = 0; int delay = 0; struct timespec time_to_wait; int BER_rate = 0, BER_loop = 1; errors er; er.loop = -1; //handle the arguments in its own scope { int c; for (;;) { int option_index = 0; static struct option long_options[] = { {"port", required_argument, 0, 'p'}, {"forward", required_argument, 0, 'f'}, {"address", required_argument, 0, 'a'}, {"error", required_argument, 0, 'e'}, {"type", required_argument, 0, 't'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, SOCKOPTS, long_options, &option_index); if (c == -1) { break; } switch (c) { case 'p': port = optarg; break; case 'f': forward = optarg; break; case 'a': address = optarg; break; case 'e': drop = optarg; errors_init(&er, drop); break; case 't': switch (*optarg) { case 'B': error_type = ERROR_BER; if (optarg[1] == '\0') { print_help(); return 1; } dec_to_frac(optarg+1, &BER_rate, &BER_loop); break; case 'W': error_type = ERROR_WAIT; if (optarg[1] == '\0') { print_help(); return 1; } delay = atoi(optarg+1); break; case 'D': default: error_type = ERROR_DROP; break; } break; case 'h': case '?': default: print_help(); return 0; } } if (!port || !address) { print_help(); return 1; } if (!forward) { forward = port; } } int sfd, s; int efd; struct epoll_event event; struct epoll_event *events; epoll_data * data; //make and bind the socket sfd = make_bound(port); if (sfd == -1) { return 2; } //start listening s = listen(sfd, SOMAXCONN); if (s == -1) { perror("listen"); return 3; } //register the epoll structure efd = epoll_create1(0); if (efd == -1) { perror ("epoll_create1"); return 4; } data = calloc(1, sizeof(epoll_data)); epoll_data_init(data, sfd); event.data.ptr = data; event.events = EPOLLIN | EPOLLET | EPOLLEXCLUSIVE; s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event); if (s == -1) { perror("epoll_ctl"); return 5; } // Buffer where events are returned (no more that 64 at the same time) events = calloc(MAXEVENTS, sizeof(event)); while (1) { int n, i; n = epoll_wait(efd, events, MAXEVENTS, -1); for (i = 0; i < n; i++) { if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP)) { //connection closed epoll_data_close(((epoll_data *)events[i].data.ptr)->link); free(((epoll_data *)events[i].data.ptr)->link); epoll_data_close((epoll_data *)events[i].data.ptr); free(events[i].data.ptr); continue; } else if((events[i].events & EPOLLIN)) { if (sfd == ((epoll_data *)events[i].data.ptr)->fd) { // We have a notification on the listening socket, which // means one or more incoming connections. while (1) { struct sockaddr in_addr; socklen_t in_len; int infd, outfd; char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; epoll_data * in_data; epoll_data * out_data; in_len = sizeof in_addr; infd = accept(sfd, &in_addr, &in_len); if (infd == -1) { if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { // We have processed all incoming // connections. break; } else { perror("accept"); break; } } s = getnameinfo(&in_addr, in_len, hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV); if (s == 0) { printf("Accepted connection on descriptor %d " "(host=%s, port=%s)\n", infd, hbuf, sbuf); } outfd = make_connected(address, forward); if (outfd == -1) { fprintf(stderr, "Failed to establish bridged connection\n"); close(infd); continue; } // Make the incoming socket non-blocking and add it to the // list of fds to monitor. s = make_non_blocking(infd); if (s == -1) { abort(); } s = make_non_blocking(outfd); if (s == -1) { abort(); } //create the epoll structures in_data = calloc(1, sizeof(epoll_data)); out_data = calloc(1, sizeof(epoll_data)); epoll_data_init(in_data, infd); epoll_data_init(out_data, outfd); //link the bridged connections in_data->link = out_data; out_data->link = in_data; event.events = EPOLLIN | EPOLLOUT; event.data.ptr = in_data; s = epoll_ctl(efd, EPOLL_CTL_ADD, infd, &event); if (s == -1) { perror("epoll_ctl"); abort(); } event.data.ptr = out_data; s = epoll_ctl(efd, EPOLL_CTL_ADD, outfd, &event); if (s == -1) { perror("epoll_ctl"); abort(); } } continue; } else { //read in the length of the packet and then the rest of the packet and loop on reading packets to ensure you got them all //then drop the ones due to the error rates //then send the rest on to the other side raw_packet pkt; if (packet_read((epoll_data *)events[i].data.ptr, &pkt) == 1) { if (handshake_delay-- > 0 || !errors_checkdrop(&er)) { packet_send(((epoll_data *)events[i].data.ptr)->link, &pkt); printf("packet sent %d: %d->%d\n", pkt.length, ((epoll_data *)events[i].data.ptr)->fd, ((epoll_data *)events[i].data.ptr)->link->fd); } else { switch (error_type) { case ERROR_DROP: printf("packet dropped %d: %d->%d\n", pkt.length, ((epoll_data *)events[i].data.ptr)->fd, ((epoll_data *)events[i].data.ptr)->link->fd); break; case ERROR_WAIT: //I hate using sleeps but for a blocking wait theres not a better alternative //if you grep for this again im sorry to use it. printf("packet delayed %d: %d->%d\n", pkt.length, ((epoll_data *)events[i].data.ptr)->fd, ((epoll_data *)events[i].data.ptr)->link->fd); memset(&time_to_wait, 0, sizeof(struct timespec)); timespec_add_ns(&time_to_wait, delay); nanosleep(&time_to_wait, 0); packet_send(((epoll_data *)events[i].data.ptr)->link, &pkt); break; case ERROR_BER: printf("packet corrupted %d: %d->%d\n", pkt.length, ((epoll_data *)events[i].data.ptr)->fd, ((epoll_data *)events[i].data.ptr)->link->fd); damage_packet(&pkt, BER_rate, BER_loop); packet_send(((epoll_data *)events[i].data.ptr)->link, &pkt); break; } } } } } } } errors_close(&er); free(events); close(sfd); return 0; }
38.084433
174
0.410697
472274ddf7ea8eb17cf80f679b501474157ff23e
11,480
h
C
GameFramework_ThirdParty/FCollada/FCollada/FColladaPlugin.h
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
8
2017-10-26T14:26:55.000Z
2022-01-07T07:35:39.000Z
GameFramework_ThirdParty/FCollada/FCollada/FColladaPlugin.h
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2018-01-27T19:21:07.000Z
2018-01-31T13:55:09.000Z
GameFramework_ThirdParty/FCollada/FCollada/FColladaPlugin.h
GavWood/Game-Framework
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2021-07-21T17:37:33.000Z
2021-07-21T17:37:33.000Z
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ /** @file FColladaPlugin.h This file contains the various FCollada plug-in classes and the internal FColladaPluginManager class. */ #ifndef _FCOLLADA_PLUGIN_H_ #define _FCOLLADA_PLUGIN_H_ #ifndef _FU_PLUGIN_H_ #include "FUPlugin.h" #endif // _FU_PLUGIN_H_ class FUPluginManager; class FCDObject; class FCDENode; class FCDETechnique; /** A FCPExtraTechnique plug-in. We use the plug-in in FCollada to parse technique-specific informations. There are three techniques that FCollada handles directly but can be overriden using one or more plug-ins: "MAYA", "MAX3D" and "FCOLLADA". @see FUPlugin @ingroup FCollada */ class FCOLLADA_EXPORT FCPExtraTechnique : public FUPlugin { private: DeclareObjectType(FUPlugin); public: /** Retrieves the name of the technique profile that this plug-in handles. @return The name of the technique profile. */ virtual const char* GetProfileName() = 0; /** Replaces the extra tree node and generates the profile-specific object for it. A temporary extra tree is generated for archiving purposes and will be kept after this call only if this function returns NULL. @param techniqueNode The extra tree node for the profile-specific technique. @param parent The object that is creating this profile-specific object. @return An handle to the profile-specific object. When this handle is NULL, the FCollada extra tree will be kept. When the extra tree that contains this handle is released, the handle will also be released. If you use this handle elsewhere, make sure you correctly use the FUTrackedPtr, FUObjectRef, FUTrackedList and FUObjectContainer templates. */ virtual FUTrackable* ReadFromArchive(FCDETechnique* techniqueNode, FUObject* parent) = 0; /** Generate a temporary extra tree for the given handle for archiving purposes. After archiving is complete, all the temporary extra trees are released. @param techniqueNode The extra tree node to contain the profile-specific object. This node is in the form: \<technique profile="X"\> @param handle A custom object created by the ReadFromArchive function. */ virtual void WriteToArchive(FCDETechnique* techniqueNode, const FUTrackable* handle) const = 0; protected: /** Destructor. Don't destroy directly. Use the Release function. */ virtual ~FCPExtraTechnique() {} }; /** A FCollada content archiving plugin. FCollada utilizes these plugins to import from and export to different 3D formats. Aside from supporting the standard XML format, binary fomrats can also be supported(E.g. X3D, IFF, OpenFlight). @see FUPlugin @ingroup FCollada */ class FCOLLADA_EXPORT FCPArchive: public FUPlugin { private: DeclareObjectType(FUPlugin); public: /** Determine if this plug-in supports import into FCollada. @return Whether this plug-in supports import. */ virtual bool IsImportSupported() = 0; /** Determine if this plug-in supports export from FCollada. @return Whether this plug-in supports export. */ virtual bool IsExportSupported() = 0; /** Determine if this plug-in supports exporting part of the FCollada assets. @return Whether partial export is supported. */ virtual bool IsPartialExportSupported() = 0; /** Determine if this plug-in supports the given file extension. @param ext string for the file extension @return 'true' if the given file extension is supported by this plug-in. */ virtual bool IsExtensionSupported(const char* ext) = 0; /** Determine the number of file extension this plug-in supports @return number of supported file extensions. */ virtual int GetSupportedExtensionsCount() = 0; /** Retrieve one supported extension. @param index the index at which the extension is to be retrieved. Ideally to be less then that returned by GetSupportedExtensionsCount(). @return the string of the file extension at the given index. NULL is returned if the given index is invalid. */ virtual const char* GetSupportedExtensionAt(int index) = 0; /** Adds an extra extension to the list of supported extension by this plugin. @param ext The new extension to support. @return Whether the extension was added.*/ virtual bool AddExtraExtension(const char* /*ext*/){ return false; } /** Removes an extension that has previously been added to the extra extension list. @param ext The extension to remove. @return Whether the extension was supported and can be removed. */ virtual bool RemoveExtraExtension(const char* /*ext*/){ return false; } /** Import a file into FCollada. @param filePath full file path to the file to be imported. @param document an empty document to be filled with imported content. @return Whether the file is imported successfully. */ virtual bool ImportFile(const fchar* filePath, FCDocument* document) = 0; /** Import a file from the given memory address. It is the plugin managers duty to ensure that the appropriate plugin is selected based on the content of this memory address. @param document An empty document to load imported content into. @param contents The content to load into the document, in a format suitable to be read by this plugin. @param length The length of the content buffer. @return Whether the file is imported successfully. */ virtual bool ImportFileFromMemory(const fchar* filePath, FCDocument* document, const void* contents, size_t length) = 0; /** Export a file from FCollada. @param document a document to be be exported. @param filePath full file path to the file to be exported. @return Whether the file is exported successfully. */ virtual bool ExportFile(FCDocument* document, const fchar* filePath) = 0; /** Start exporting parts of the FCollada assets. Only valid if 'IsPartlyExportSupported()' returns 'true'. @param filePath A full file path specifying the location of the target path This is in order to process relative file paths correctly. If this parameter is NULL then all paths will be exported absolutely. @return Whether the operation succeeded. */ virtual bool StartExport(const fchar* absoluteFilePath) = 0; /** Export one object in FCollada. Only valid if 'IsPartlyExportSupported()' returns 'true'. @param document the FCDocument that contains the object to be exported. @param object the FCDObject to be exported to the file specified in 'StartExport()' @return Whether the given object is successfully exported. */ virtual bool ExportObject(FCDObject* object) = 0; /** End the export of the current document started by 'StartExport()'. Only valid if 'IsPartlyExportSupported()' returns 'true'. This function will release any resources associated with the export. @param outData [out] Void pointer to recieve a pointer to the memory chunk to write @return Whether the request is valid, and the outData has been filled. */ virtual bool EndExport(fm::vector<uint8>& outData) = 0; /** End the export of the current document started by 'StartExport()'. Only valid if 'IsPartlyExportSupported()' returns 'true'. This function will release any resources associated with the export. @param filePath A full file path specifying the location to write the currently exported document too. @return Whether the call is valid, and the file is written to disk without error. */ virtual bool EndExport(const fchar* filePath) = 0; /** Load the save data onto an object. This allows for loads of partial documents @param object The object to recieve the loaded data @param data The data to load @return Whether the load was successful */ virtual bool ImportObject(FCDObject* object, const fm::vector<uint8>& data) = 0; protected: /** Destructor. Don't destroy directly, use the Release function.*/ virtual ~FCPArchive() {} }; /** The FCollada plug-ins manager. */ class FCOLLADA_EXPORT FColladaPluginManager : public FUObject { private: DeclareObjectType(FColladaPluginManager); typedef FUObjectContainer<FCPExtraTechnique> FCPExtraList; typedef FUObjectContainer<FCPArchive> FCPArchiveList; FCPExtraList extraTechniquePlugins; FCPArchiveList archivePlugins; FUPluginManager* loader; public: /** Constructor. */ FColladaPluginManager(); /** Retrieve the number of archive plugins that are loaded. @return The number of archive plugins loaded. */ size_t GetArchivePluginsCount() { return archivePlugins.size(); } /** Retrieves the archive plugin specified by the given index. @param index The archive plugin index. @return The plugin pointer on success, NULL otherwise.*/ FCPArchive* GetArchivePlugin(size_t index){ FUAssert(index < archivePlugins.size(), return NULL); return archivePlugins[index]; } /** Manually registers a plugin. To manually un-register a plugin, use the plugin->Release() function. @param plugin The plugin to manually add to the plugin map. @return ?. */ bool RegisterPlugin(FUPlugin* plugin); DEPRECATED(3.05A, RegisterPlugin) inline bool AddPlugin(FCPExtraTechnique* plugin) { return RegisterPlugin(plugin); } /**< See above. */ DEPRECATED(3.05A, RegisterPlugin) inline bool AddArchivePlugin(FCPArchive* plugin) { return RegisterPlugin(plugin); } /**< See above. */ /** Load document to the given file. @param document the FCDocument which will be filled with loaded contents. @param filename The file name of the file to load. @return 'true' if the operation is successful. */ bool LoadDocumentFromFile(FCDocument* document, const fchar* filename); DEPRECATED(3.05A, LoadDocumentFromFile) inline bool LoadDocument(FCDocument* document, const fchar* filename) { return LoadDocumentFromFile(document, filename); } /**< See above. */ /** Load the given file from the provided memory address. @param filename The absolute filename for the data. Used to manage relative paths. @param document The FCollada document to fill in. @param data The memory buffer containing the raw document. @param length The length of the memory buffer. */ bool LoadDocumentFromMemory(const fchar* filename, FCDocument* document, void* data, size_t length); /** Save document to the given file. @param document the FCDocument whose contents are to be writtern in the file. @param filename the full path of the file to write. @return 'true' if the operation is successful. */ bool SaveDocumentToFile(FCDocument* document, const fchar* filename); DEPRECATED(3.05A, SaveDocumentToFile) inline bool SaveDocument(FCDocument* document, const fchar* filename) { return SaveDocumentToFile(document, filename); } /**< See above. */ private: /** Don't allow direct destruction. Call the Release() function instead. */ virtual ~FColladaPluginManager(); /** [INTERNAL] Find the correct plug-in to the document according to the file extension. */ FCPArchive* FindArchivePlugin(const fchar* filename); // Extra Technique plug-ins support typedef fm::pvector<FCDETechnique> FCDETechniqueList; void PostImportDocument(FCDocument* document); void PreExportDocument(FCDocument* document, FCDETechniqueList& techniques); void PostExportDocument(FCDocument* document, FCDETechniqueList& techniques); /** Make a processed map of CRC32 profile names vs plug-ins to handle them. */ typedef fm::map<uint32, FCPExtraTechnique*> FCPExtraMap; void CreateExtraTechniquePluginMap(FCPExtraMap& map); }; #endif // _FCOLLADA_PLUGIN_H_
42.996255
182
0.764634
b05c319456299b5670196bf40f9b35f6e7eca5eb
5,164
h
C
mth/mth_def.h
tuckerbabcock/core
f7b18849c9e2ee82daad44aa8696c27206556fba
[ "BSD-3-Clause" ]
null
null
null
mth/mth_def.h
tuckerbabcock/core
f7b18849c9e2ee82daad44aa8696c27206556fba
[ "BSD-3-Clause" ]
null
null
null
mth/mth_def.h
tuckerbabcock/core
f7b18849c9e2ee82daad44aa8696c27206556fba
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** Copyright 2015 Scientific Computation Research Center, Rensselaer Polytechnic Institute. All rights reserved. This work is open source software, licensed under the terms of the BSD license as described in the LICENSE file in the top-level directory. *******************************************************************************/ #ifndef MTH_DEF_H #define MTH_DEF_H #include "mth.h" namespace mth { template <class T, unsigned M> T norm(Vector<T,M> const& a) { return sqrt(a * a); } template <class T> Vector3<T> cross(Vector<T,3> const& a, Vector<T,3> const& b) { Vector3<T> r; r(0) = a(1)*b(2) - a(2)*b(1); r(1) = a(2)*b(0) - a(0)*b(2); r(2) = a(0)*b(1) - a(1)*b(0); return r; } template <class T> Matrix3x3<T> cross(Vector<T,3> const& a) { Matrix3x3<T> r( 0, -a(2), a(1), a(2), 0, -a(0), -a(1), a(0), 0); return r; } template <class T, unsigned N> Vector<T,N> project(Vector<T,N> const& a, Vector<T,N> const& b) { return b*((a*b)/(b*b)); } template <class T, unsigned N> Vector<T,N> reject(Vector<T,N> const& a, Vector<T,N> const& b) { return a - project(a, b); } template <class T, unsigned M, unsigned N> void transpose(Matrix<T,M,N> const& a, Matrix<T,N,M>& b) { unsigned m = a.rows(); unsigned n = a.rows(); b.resize(m, n); for (unsigned i=0; i < m; ++i) for (unsigned j=0; j < n; ++j) b(j,i) = a(i,j); } template <class T> T determinant(Matrix<T,2,2> const& a) { return a(0,0)*a(1,1) - a(1,0)*a(0,1); } template <class T> T determinant(Matrix<T,3,3> const& a) { return a(0,0) * (a(1,1)*a(2,2) - a(2,1)*a(1,2)) - a(0,1) * (a(1,0)*a(2,2) - a(2,0)*a(1,2)) + a(0,2) * (a(1,0)*a(2,1) - a(2,0)*a(1,1)); } template <class T> Matrix<T,2,2> inverse(Matrix<T,2,2> const& a) { Matrix<T,2,2> r; r(0,0) = a(1,1); r(0,1) = -a(0,1); r(1,0) = -a(1,0); r(1,1) = a(0,0); return r / determinant(a); } template <class T> Matrix<T,3,3> inverse(Matrix<T,3,3> const& a) { Matrix<T,3,3> r; Matrix<T,3,3> x = transpose(a); r[0] = cross(x[1], x[2]); r[1] = cross(x[2], x[0]); r[2] = cross(x[0], x[1]); return r / determinant(a); } template <class T> T trace(Tensor<T> const& a) { unsigned dim = a.dim(); T t = a(0,0); for (unsigned i=1; i < dim; ++i) t += a(i,i); return t; } template <class T> T norm(Tensor<T> const& a) { T n = 0.0; for (unsigned i=0; i < a.dim(); ++i) for (unsigned j=0; j < a.dim(); ++j) n += a(i,j)*a(i,j); return std::sqrt(n); } template <class T> T det2x2(Tensor<T> const& a) { return a(0,0)*a(1,1) - a(1,0)*a(0,1); } template <class T> T det3x3(Tensor<T> const& a) { return a(0,0) * (a(1,1)*a(2,2) - a(2,1)*a(1,2)) - a(0,1) * (a(1,0)*a(2,2) - a(2,0)*a(1,2)) + a(0,2) * (a(1,0)*a(2,1) - a(2,0)*a(1,1)); } template <class T> T determinant(Tensor<T> const& a) { T det = T(0.0); switch(a.dim()) { case 2: det = det2x2(a); break; case 3: det = det3x3(a); break; } return det; } template <class T> void transpose(Tensor<T> const& a, Tensor<T>& r) { r.resize(a.dim()); for (unsigned i=0; i < a.dim(); ++i) for (unsigned j=0; j < a.dim(); ++j) r(j,i) = a(i,j); } template <class T> void inverse2x2(Tensor<T> const& a, Tensor<T>& r) { r(0,0) = a(1,1); r(0,1) = -a(0,1); r(1,0) = -a(1,0); r(1,1) = a(0,0); r /= determinant(a); } template <class T> void inverse3x3(Tensor<T> const& a, Tensor<T>& r) { r(0,0) = a(2,2)*a(1,1) - a(2,1)*a(1,2); r(0,1) = a(2,1)*a(0,2) - a(2,2)*a(0,1); r(0,2) = a(1,2)*a(0,1) - a(1,1)*a(0,2); r(1,0) = a(2,0)*a(1,2) - a(2,2)*a(1,0); r(1,1) = a(2,2)*a(0,0) - a(2,0)*a(0,2); r(1,2) = a(1,0)*a(0,2) - a(1,2)*a(0,0); r(2,0) = a(2,1)*a(1,0) - a(2,0)*a(1,1); r(2,1) = a(2,0)*a(0,1) - a(2,1)*a(0,0); r(2,2) = a(1,1)*a(0,0) - a(1,0)*a(0,1); r /= determinant(a); } template <class T> void inverse(Tensor<T> const& a, Tensor<T>& r) { r.resize(a.dim()); switch(a.dim()) { case 2: inverse2x2(a, r); break; case 3: inverse3x3(a, r); break; } } template <class T> void deviatoric(Tensor<T> const& a, Tensor<T>& r) { r = a; T p = trace(a) / a.dim(); for (unsigned i=0; i < a.dim(); ++i) r(i,i) -= p; } template <class T> Tensor<T> eye(unsigned d) { Tensor<T> r(d); r.zero(); for (unsigned i=0; i < d; ++i) r(i,i) = 1.0; return r; } template <class T, unsigned M, unsigned N> void multiply(Matrix<T,M,N> const& a, Vector<T,N> const& b, Vector<T,M>& c) { unsigned m = a.rows(); unsigned n = a.cols(); c.resize(m); for (unsigned i = 0; i < m; ++i) { c(i) = 0; for (unsigned j = 0; j < n; ++j) c(i) += a(i,j) * b(j); } } template <class T, unsigned M, unsigned N, unsigned O> void multiply(Matrix<T,M,O> const& a, Matrix<T,O,N> const& b, Matrix<T,M,N>& c) { unsigned m = a.rows(); unsigned n = b.cols(); unsigned o = a.cols(); c.resize(m, n); for (unsigned i = 0; i < m; ++i) for (unsigned j = 0; j < n; ++j) { c(i,j) = 0; for (unsigned l = 0; l < o; ++l) c(i,j) += a(i,l) * b(l,j); } } } #endif
20.411067
80
0.506971
52c345399b051a404e3f8b95e02644a533f07a0f
3,659
c
C
Implementation_scripts/crypto_kem/frodokem640aes/m4/matrix_aes.c
Generic-SCA-CCA-Lattice-Schemes/Generic-SCA-CCA-Lattice-Schemes
d1cebd9d1addf098fd473bbce941004e51bc73f1
[ "CC0-1.0" ]
5
2020-11-19T07:56:02.000Z
2021-10-04T03:38:55.000Z
Implementation_scripts/crypto_kem/frodokem640aes/m4/matrix_aes.c
Generic-SCA-CCA-Lattice-Schemes/Generic-SCA-CCA-Lattice-Schemes
d1cebd9d1addf098fd473bbce941004e51bc73f1
[ "CC0-1.0" ]
null
null
null
Implementation_scripts/crypto_kem/frodokem640aes/m4/matrix_aes.c
Generic-SCA-CCA-Lattice-Schemes/Generic-SCA-CCA-Lattice-Schemes
d1cebd9d1addf098fd473bbce941004e51bc73f1
[ "CC0-1.0" ]
1
2021-07-10T10:06:02.000Z
2021-07-10T10:06:02.000Z
/******************************************************************************************** * FrodoKEM: Learning with Errors Key Encapsulation * * Abstract: matrix arithmetic functions used by the KEM *********************************************************************************************/ #include <stdint.h> #include <string.h> #include "aes.h" #include "api.h" #include "common.h" #include "params.h" extern uint16_t xs(const uint16_t *s, const int16_t *a_row); int mul_add_as_plus_e(uint16_t *out, const uint16_t *s, const uint8_t *seed_A) { // Generate-and-multiply: generate matrix A (N x N) row-wise, multiply by s on the right. // Inputs: s, e (N x N_BAR) // Output: out = A*s + e (N x N_BAR) int k; uint16_t i, j; int16_t a_row[4 * PARAMS_N]; int16_t a_row_temp[4 * PARAMS_N] = {0}; // Take four lines of A at once aes128ctx ctx128; aes128_keyexp(&ctx128, seed_A); for (j = 0; j < PARAMS_N; j += PARAMS_STRIPE_STEP) { a_row_temp[j + 1 + 0 * PARAMS_N] = UINT16_TO_LE(j); // Loading values in the little-endian order a_row_temp[j + 1 + 1 * PARAMS_N] = UINT16_TO_LE(j); a_row_temp[j + 1 + 2 * PARAMS_N] = UINT16_TO_LE(j); a_row_temp[j + 1 + 3 * PARAMS_N] = UINT16_TO_LE(j); } for (i = 0; i < PARAMS_N; i += 4) { for (j = 0; j < PARAMS_N; j += PARAMS_STRIPE_STEP) { // Go through A, four rows at a time a_row_temp[j + 0 * PARAMS_N] = UINT16_TO_LE(i + 0); // Loading values in the little-endian order a_row_temp[j + 1 * PARAMS_N] = UINT16_TO_LE(i + 1); a_row_temp[j + 2 * PARAMS_N] = UINT16_TO_LE(i + 2); a_row_temp[j + 3 * PARAMS_N] = UINT16_TO_LE(i + 3); } aes128_ecb((uint8_t *)a_row, (uint8_t *)a_row_temp, 4 * PARAMS_N * sizeof(int16_t) / AES_BLOCKBYTES, &ctx128); for (k = 0; k < 4 * PARAMS_N; k++) { a_row[k] = LE_TO_UINT16(a_row[k]); } for (k = 0; k < PARAMS_NBAR; k++) { out[k + (i + 0)*PARAMS_NBAR] += xs(s + k*PARAMS_N,a_row + 0*PARAMS_N); out[k + (i + 1)*PARAMS_NBAR] += xs(s + k*PARAMS_N,a_row + 1*PARAMS_N); out[k + (i + 2)*PARAMS_NBAR] += xs(s + k*PARAMS_N,a_row + 2*PARAMS_N); out[k + (i + 3)*PARAMS_NBAR] += xs(s + k*PARAMS_N,a_row + 3*PARAMS_N); } } return 1; } extern void sa(uint16_t *out, const uint16_t *s, const uint16_t *a); int mul_add_sa_plus_e(uint16_t *out, const uint16_t *s, const uint8_t *seed_A) { // Generate-and-multiply: generate matrix A (N x N) column-wise, multiply by s' on the left. // Inputs: s', e' (N_BAR x N) // Output: out = s'*A + e' (N_BAR x N) int i, j, kk; uint16_t a_cols[PARAMS_N*PARAMS_STRIPE_STEP] = {0}; uint16_t a_cols_temp[PARAMS_N*PARAMS_STRIPE_STEP] = {0}; aes128ctx roundkeys; aes128_keyexp(&roundkeys, seed_A); for (i = 0, j = 0; i < PARAMS_N; i++, j += PARAMS_STRIPE_STEP) { a_cols_temp[j] = i; // Loading values in the little-endian order } for (kk = 0; kk < PARAMS_N; kk += PARAMS_STRIPE_STEP) { for (i = 0; i < (PARAMS_N*PARAMS_STRIPE_STEP); i += PARAMS_STRIPE_STEP) { a_cols_temp[i + 1] = kk; // Loading values in the little-endian order } aes128_ecb((unsigned char *)a_cols, (unsigned char *)a_cols_temp, PARAMS_N*PARAMS_STRIPE_STEP*sizeof(int16_t) / AES_BLOCKBYTES, &roundkeys); for (i = 0; i < PARAMS_N; i += 8) { for (j = 0; j < PARAMS_STRIPE_STEP; j++) { sa(out+kk+j, s+i, a_cols+i*PARAMS_STRIPE_STEP+j); } } } return 1; }
40.655556
148
0.556983
dd7b78e8a6a628cff9e599ca5b52dd59e61f338a
35,213
c
C
sm64ex-nightly/levels/bbh/areas/1/18/model.inc.c
alex-free/sm64ex-creator
e7089df69fb43f266b2165078d94245b33b8e72a
[ "Intel", "X11", "Unlicense" ]
2
2022-03-12T08:27:53.000Z
2022-03-12T18:26:06.000Z
levels/bbh/areas/1/18/model.inc.c
Daviz00/sm64
fd2ed5e0e72d04732034919f8442f8d2cc40fd67
[ "Unlicense" ]
null
null
null
levels/bbh/areas/1/18/model.inc.c
Daviz00/sm64
fd2ed5e0e72d04732034919f8442f8d2cc40fd67
[ "Unlicense" ]
null
null
null
// 0x0700F8B8 - 0x0700F8D0 static const Lights1 bbh_seg7_lights_0700F8B8 = gdSPDefLights1( 0x65, 0x65, 0x38, 0xfe, 0xfe, 0x8c, 0x28, 0x28, 0x28 ); // 0x0700F8D0 - 0x0700F8E8 static const Lights1 bbh_seg7_lights_0700F8D0 = gdSPDefLights1( 0x20, 0x20, 0x20, 0x50, 0x50, 0x50, 0x28, 0x28, 0x28 ); // 0x0700F8E8 - 0x0700F900 static const Lights1 bbh_seg7_lights_0700F8E8 = gdSPDefLights1( 0x66, 0x66, 0x66, 0xff, 0xff, 0xff, 0x28, 0x28, 0x28 ); // 0x0700F900 - 0x0700F918 static const Lights1 bbh_seg7_lights_0700F900 = gdSPDefLights1( 0x33, 0x2c, 0x20, 0x80, 0x70, 0x52, 0x28, 0x28, 0x28 ); // 0x0700F918 - 0x0700F9F8 static const Vtx bbh_seg7_vertex_0700F918[] = { {{{ -818, 717, 0}, 0, { 0, 650}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -101, 717, 1024}, 0, { 990, 990}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -2252, 717, 1024}, 0, { 990, 0}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -818, 0, -255}, 0, { 0, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 0, -255}, 0, { 990, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 0, 1024}, 0, { 990, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -818, 0, 0}, 0, { 0, 786}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -101, 0, 0}, 0, { 0, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -818, 0, 0}, 0, { 0, 650}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -101, 0, 1024}, 0, { 990, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 717, -1535}, 0, { 0, 0}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -818, 717, -357}, 0, { 990, 990}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -2252, 717, -357}, 0, { 990, 0}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -818, 717, -1535}, 0, { 0, 990}, {0x00, 0x81, 0x00, 0xff}}}, }; // 0x0700F9F8 - 0x0700FA68 static const Vtx bbh_seg7_vertex_0700F9F8[] = { {{{ -818, 717, 0}, 0, { 0, 786}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -2252, 717, -255}, 0, { 990, 990}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -818, 717, -255}, 0, { 0, 990}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -818, 717, 0}, 0, { 0, 650}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -101, 717, 0}, 0, { 0, 990}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -101, 717, 1024}, 0, { 990, 990}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -2252, 717, 1024}, 0, { 990, 0}, {0x00, 0x81, 0x00, 0xff}}}, }; // 0x0700FA68 - 0x0700FAE8 static const Vtx bbh_seg7_vertex_0700FA68[] = { {{{ -101, 0, 717}, 0, { 0, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -50, 0, 563}, 0, { 478, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -101, 0, 563}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -50, 0, 717}, 0, { 478, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1945, 0, 1075}, 0, { 478, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2098, 0, 1024}, 0, { 0, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2098, 0, 1075}, 0, { 478, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1945, 0, 1024}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, }; // 0x0700FAE8 - 0x0700FBA8 static const Vtx bbh_seg7_vertex_0700FAE8[] = { {{{ -1125, 512, 922}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1740, 512, 1024}, 0, { 990, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1125, 512, 1024}, 0, { 990, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1740, 512, 922}, 0, { 0, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -101, 512, 0}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -716, 512, 102}, 0, { 990, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -101, 512, 102}, 0, { 990, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -716, 512, 0}, 0, { 0, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1637, 0, -1535}, 0, { 698, 990}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1484, 0, -1586}, 0, { 624, 1008}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1637, 0, -1586}, 0, { 698, 1008}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1484, 0, -1535}, 0, { 624, 990}, {0x00, 0x7f, 0x00, 0xff}}}, }; // 0x0700FBA8 - 0x0700FBE8 static const Vtx bbh_seg7_vertex_0700FBA8[] = { {{{ -1740, 72, 614}, 0, { -332, 1680}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1330, 102, 614}, 0, { 478, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1740, 102, 614}, 0, { -364, 1680}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1330, 72, 614}, 0, { 512, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, }; // 0x0700FBE8 - 0x0700FCA8 static const Vtx bbh_seg7_vertex_0700FBE8[] = { {{{ -1125, 0, 922}, 0, { 480, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1125, 512, 1024}, 0, { 0, 552}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1125, 0, 1024}, 0, { 0, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1125, 512, 922}, 0, { 480, 552}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1740, 0, 1024}, 0, { 480, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1740, 512, 922}, 0, { 0, 552}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1740, 0, 922}, 0, { 0, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1740, 512, 1024}, 0, { 478, 552}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -716, 0, 102}, 0, { 480, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -716, 512, 102}, 0, { 478, 552}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -716, 512, 0}, 0, { 0, 552}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -716, 0, 0}, 0, { 0, 2012}, {0x81, 0x00, 0x00, 0xff}}}, }; // 0x0700FCA8 - 0x0700FD68 static const Vtx bbh_seg7_vertex_0700FCA8[] = { {{{ -1689, 92, -255}, 0, { 608, 268}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1689, -9, -255}, 0, { 716, 268}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1689, -9, 563}, 0, { 58, 1576}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1689, 92, 563}, 0, { -48, 1576}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1689, 92, 563}, 0, { -48, 1576}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1689, -9, 563}, 0, { 58, 1576}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1381, -9, 563}, 0, { 482, 1744}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1381, 92, 563}, 0, { 372, 1744}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1381, 92, 563}, 0, { 372, 1744}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1381, -9, -255}, 0, { 1138, 436}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1381, 92, -255}, 0, { 1030, 436}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1381, -9, 563}, 0, { 482, 1744}, {0x7f, 0x00, 0x00, 0xff}}}, }; // 0x0700FD68 - 0x0700FE28 static const Vtx bbh_seg7_vertex_0700FD68[] = { {{{ -1330, 72, -255}, 0, { 274, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1330, 102, -255}, 0, { 0, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1330, 102, 614}, 0, { 0, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1330, 72, 614}, 0, { 274, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1740, 72, 614}, 0, { 274, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1740, 102, -255}, 0, { 0, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1740, 72, -255}, 0, { 274, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1740, 102, 614}, 0, { 0, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1330, 102, -255}, 0, { 2012, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1740, 102, -255}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1740, 102, 614}, 0, { 0, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1330, 102, 614}, 0, { 2012, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, }; // 0x0700FE28 - 0x0700FF28 static const Vtx bbh_seg7_vertex_0700FE28[] = { {{{ -2252, 102, -1535}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1842, 102, -1330}, 0, { 4056, 552}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1842, 102, -1535}, 0, { 4056, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2047, 102, -357}, 0, { 2012, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2047, 102, -1330}, 0, { 2012, 552}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 102, -357}, 0, { 0, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -818, 102, -1535}, 0, { 14276, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1023, 102, -1330}, 0, { 12232, 552}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1023, 102, -357}, 0, { 12232, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1228, 102, -1330}, 0, { 10188, 552}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1228, 102, -1535}, 0, { 10188, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -818, 102, -357}, 0, { 14276, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2149, 154, 717}, 0, { 990, 1500}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2149, 154, 614}, 0, { 990, 480}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 154, 512}, 0, { 0, 0}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 154, 819}, 0, { 0, 2012}, {0x00, 0x7f, 0x00, 0xff}}}, }; // 0x0700FF28 - 0x07010018 static const Vtx bbh_seg7_vertex_0700FF28[] = { {{{ -1228, 0, -1330}, 0, { 3034, 992}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1023, 0, -1330}, 0, { 4056, 992}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1023, 102, -1330}, 0, { 4056, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1842, 0, -1535}, 0, { -1052, 992}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1842, 102, -1535}, 0, { -1052, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1842, 102, -1330}, 0, { 0, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1842, 0, -1330}, 0, { 0, 992}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1228, 0, -1330}, 0, { 0, 992}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1228, 102, -1535}, 0, { -1052, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1228, 0, -1535}, 0, { -1052, 992}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1228, 102, -1330}, 0, { 0, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1842, 102, -1330}, 0, { 0, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2047, 102, -1330}, 0, { -1052, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2047, 0, -1330}, 0, { -1052, 988}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1842, 0, -1330}, 0, { 0, 988}, {0x00, 0x00, 0x7f, 0xff}}}, }; // 0x07010018 - 0x070100C8 static const Vtx bbh_seg7_vertex_07010018[] = { {{{ -1023, 0, -357}, 0, { 4822, 992}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1023, 102, -1330}, 0, { 0, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1023, 0, -1330}, 0, { 0, 992}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1228, 0, -1330}, 0, { 3034, 992}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1023, 102, -1330}, 0, { 4056, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1228, 102, -1330}, 0, { 3034, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2047, 0, -1330}, 0, { 0, 992}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2047, 102, -357}, 0, { 4822, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2047, 0, -357}, 0, { 4822, 992}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2047, 102, -1330}, 0, { 0, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1023, 102, -357}, 0, { 4822, 0}, {0x81, 0x00, 0x00, 0xff}}}, }; // 0x070100C8 - 0x070101A8 static const Vtx bbh_seg7_vertex_070100C8[] = { {{{ -1637, 256, -1535}, 0, { -1734, 1280}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 717, -1535}, 0, { 990, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2252, 717, -1535}, 0, { -3778, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1484, 256, -1535}, 0, { -1222, 1280}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2252, 0, -1535}, 0, { -3778, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1637, 0, -1535}, 0, { -1734, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 0, -1535}, 0, { 990, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1484, 0, -1535}, 0, { -1222, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -101, 256, 563}, 0, { -540, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 256, 717}, 0, { 0, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 717, 1024}, 0, { 990, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 717, 0}, 0, { -2414, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 0, 0}, 0, { -2414, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 0, 563}, 0, { -540, 2012}, {0x81, 0x00, 0x00, 0xff}}}, }; // 0x070101A8 - 0x07010298 static const Vtx bbh_seg7_vertex_070101A8[] = { {{{ -818, 717, -1535}, 0, { -4118, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -818, 0, -1535}, 0, { -4118, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -818, 0, 0}, 0, { 990, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 0, 717}, 0, { 0, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 717, 1024}, 0, { 990, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 256, 717}, 0, { 0, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -101, 0, 1024}, 0, { 990, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -2252, 0, -1535}, 0, { 8484, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2252, 717, 1024}, 0, { 0, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2252, 0, 1024}, 0, { 0, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2252, 717, -1535}, 0, { 8484, 0}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -101, 717, 0}, 0, { 2352, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 0, 0}, 0, { 0, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -101, 0, 0}, 0, { 2352, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 717, 0}, 0, { 0, 0}, {0x00, 0x00, 0x7f, 0xff}}}, }; // 0x07010298 - 0x07010388 static const Vtx bbh_seg7_vertex_07010298[] = { {{{ -101, 256, 717}, 0, { 0, 1280}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -50, 256, 717}, 0, { 0, 1280}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -50, 0, 717}, 0, { 0, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -818, 717, -1535}, 0, { -4118, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -818, 0, 0}, 0, { 990, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -818, 717, 0}, 0, { 990, 0}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1945, 0, 1024}, 0, { 6100, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1945, 256, 1024}, 0, { 6100, 1280}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -101, 0, 1024}, 0, { 0, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -101, 717, 1024}, 0, { 0, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2252, 717, 1024}, 0, { 7122, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2098, 256, 1024}, 0, { 6610, 1280}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2252, 0, 1024}, 0, { 7122, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2098, 0, 1024}, 0, { 6610, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -101, 0, 717}, 0, { 0, 2012}, {0x00, 0x00, 0x81, 0xff}}}, }; // 0x07010388 - 0x07010478 static const Vtx bbh_seg7_vertex_07010388[] = { {{{ -2098, 0, 1075}, 0, { 6610, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2098, 256, 1024}, 0, { 6610, 1280}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2098, 256, 1075}, 0, { 6610, 1280}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -50, 256, 563}, 0, { -542, 1280}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -101, 0, 563}, 0, { -542, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -50, 0, 563}, 0, { -542, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -101, 256, 563}, 0, { -542, 1280}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2098, 256, 1024}, 0, { 6610, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1945, 256, 1075}, 0, { 6100, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -2098, 256, 1075}, 0, { 6610, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1945, 256, 1024}, 0, { 6100, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1945, 256, 1024}, 0, { 6100, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1945, 0, 1075}, 0, { 6100, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1945, 256, 1075}, 0, { 6100, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1945, 0, 1024}, 0, { 6100, 2012}, {0x81, 0x00, 0x00, 0xff}}}, }; // 0x07010478 - 0x07010568 static const Vtx bbh_seg7_vertex_07010478[] = { {{{ -1637, 256, -1535}, 0, { -1734, 1280}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1637, 0, -1535}, 0, { -1734, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1637, 0, -1586}, 0, { -1734, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2098, 0, 1075}, 0, { 6610, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2098, 0, 1024}, 0, { 6610, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2098, 256, 1024}, 0, { 6610, 1280}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -101, 256, 563}, 0, { -542, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -50, 256, 563}, 0, { -542, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -50, 256, 717}, 0, { 0, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -101, 256, 717}, 0, { 0, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1484, 256, -1586}, 0, { -1222, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1484, 0, -1535}, 0, { -1222, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1484, 256, -1535}, 0, { -1222, 1280}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1484, 0, -1586}, 0, { -1222, 2012}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1637, 256, -1586}, 0, { -1734, 1280}, {0x7f, 0x00, 0x00, 0xff}}}, }; // 0x07010568 - 0x07010668 static const Vtx bbh_seg7_vertex_07010568[] = { {{{ -1637, 256, -1586}, 0, { -1734, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1484, 256, -1535}, 0, { -1222, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1637, 256, -1535}, 0, { -1734, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1484, 256, -1586}, 0, { -1222, 1280}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -2252, 0, 512}, 0, { 1672, 2012}, {0x59, 0x00, 0xa6, 0xff}}}, {{{ -2149, 154, 614}, 0, { 1330, 1572}, {0x59, 0x00, 0xa6, 0xff}}}, {{{ -2149, 0, 614}, 0, { 1330, 2012}, {0x59, 0x00, 0xa6, 0xff}}}, {{{ -2252, 154, 512}, 0, { 1672, 1572}, {0x59, 0x00, 0xa6, 0xff}}}, {{{ -2149, 0, 614}, 0, { 1330, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2149, 154, 614}, 0, { 1330, 1572}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2149, 154, 717}, 0, { 990, 1572}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2149, 0, 717}, 0, { 990, 2012}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -2149, 0, 717}, 0, { 990, 2012}, {0x59, 0x00, 0x5a, 0xff}}}, {{{ -2149, 154, 717}, 0, { 990, 1572}, {0x59, 0x00, 0x5a, 0xff}}}, {{{ -2252, 154, 819}, 0, { 650, 1572}, {0x59, 0x00, 0x5a, 0xff}}}, {{{ -2252, 0, 819}, 0, { 650, 2012}, {0x59, 0x00, 0x5a, 0xff}}}, }; // 0x07010668 - 0x07010768 static const Vtx bbh_seg7_vertex_07010668[] = { {{{ -1279, 614, -255}, 0, { 4822, 260}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 0, -255}, 0, { 7122, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 717, -255}, 0, { 7122, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2047, 102, -357}, 0, { 990, 1720}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1791, 614, -357}, 0, { -286, 260}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1791, 102, -357}, 0, { -286, 1720}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2252, 717, -357}, 0, { 2012, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2252, 102, -357}, 0, { 2012, 1720}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -2047, 0, -357}, 0, { 990, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -818, 717, -357}, 0, { -5140, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1279, 614, -357}, 0, { -2840, 260}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1023, 0, -357}, 0, { -4118, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1279, 102, -357}, 0, { -2840, 1720}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1023, 102, -357}, 0, { -4118, 1720}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -818, 102, -357}, 0, { -5140, 1720}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1279, 102, -255}, 0, { 4822, 1720}, {0x00, 0x00, 0x7f, 0xff}}}, }; // 0x07010768 - 0x07010858 static const Vtx bbh_seg7_vertex_07010768[] = { {{{ -818, 0, -255}, 0, { 7122, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1791, 102, -255}, 0, { 2268, 1720}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2252, 0, -255}, 0, { 0, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1279, 102, -255}, 0, { 4822, 1720}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1791, 614, -255}, 0, { 2268, 260}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -2252, 717, -255}, 0, { 0, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1279, 614, -255}, 0, { 4822, 260}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -818, 717, -255}, 0, { 7122, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1791, 614, -255}, 0, { 2778, 260}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1791, 614, -357}, 0, { 2778, 260}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1279, 614, -357}, 0, { 224, 260}, {0x00, 0x81, 0x00, 0xff}}}, {{{ -1791, 102, -255}, 0, { 2778, 1720}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1791, 614, -357}, 0, { 2778, 260}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1791, 614, -255}, 0, { 2778, 260}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1279, 614, -255}, 0, { 224, 260}, {0x00, 0x81, 0x00, 0xff}}}, }; // 0x07010858 - 0x07010908 static const Vtx bbh_seg7_vertex_07010858[] = { {{{ -1279, 102, -255}, 0, { 224, 1720}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1791, 102, -357}, 0, { 2778, 1720}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1791, 102, -255}, 0, { 2778, 1720}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -1791, 102, -255}, 0, { 2778, 1720}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1791, 102, -357}, 0, { 2778, 1720}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1791, 614, -357}, 0, { 2778, 260}, {0x7f, 0x00, 0x00, 0xff}}}, {{{ -1279, 614, -255}, 0, { 224, 260}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1279, 614, -357}, 0, { 224, 260}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1279, 102, -357}, 0, { 224, 1720}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1279, 102, -255}, 0, { 224, 1720}, {0x81, 0x00, 0x00, 0xff}}}, {{{ -1279, 102, -357}, 0, { 224, 1720}, {0x00, 0x7f, 0x00, 0xff}}}, }; // 0x07010908 - 0x07010988 static const Vtx bbh_seg7_vertex_07010908[] = { {{{ -1125, 0, 922}, 0, { 3034, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1740, 0, 922}, 0, { 0, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1740, 512, 922}, 0, { 0, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1125, 512, 922}, 0, { 3034, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -101, 512, 102}, 0, { 3034, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -716, 512, 102}, 0, { 0, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -716, 0, 102}, 0, { 0, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -101, 0, 102}, 0, { 3034, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, }; // 0x07010988 - 0x07010A08 static const Vtx bbh_seg7_vertex_07010988[] = { {{{ -1791, 614, -357}, 0, { 0, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1279, 102, -357}, 0, { 990, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1791, 102, -357}, 0, { 0, 2012}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1279, 614, -357}, 0, { 990, 0}, {0x00, 0x00, 0x81, 0xff}}}, {{{ -1279, 614, -255}, 0, { 990, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1791, 614, -255}, 0, { 0, 0}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1791, 102, -255}, 0, { 0, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, {{{ -1279, 102, -255}, 0, { 990, 2012}, {0x00, 0x00, 0x7f, 0xff}}}, }; // 0x07010A08 - 0x07010A48 static const Vtx bbh_seg7_vertex_07010A08[] = { {{{ -818, 0, -1535}, 0, { 8144, -3098}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 0, -1535}, 0, { -6160, -3098}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -2252, 0, -306}, 0, { -6160, 5076}, {0x00, 0x7f, 0x00, 0xff}}}, {{{ -818, 0, -306}, 0, { 8144, 5076}, {0x00, 0x7f, 0x00, 0xff}}}, }; // 0x07010A48 - 0x07010B58 static const Gfx bbh_seg7_dl_07010A48[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, spooky_09008800), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPLight(&bbh_seg7_lights_0700F8B8.l, 1), gsSPLight(&bbh_seg7_lights_0700F8B8.a, 2), gsSPVertex(bbh_seg7_vertex_0700F918, 14, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 5, 6, 3, 0x0, 5, 7, 8, 0x0), gsSP2Triangles( 5, 9, 7, 0x0, 10, 11, 12, 0x0), gsSP1Triangle(10, 13, 11, 0x0), gsSPVertex(bbh_seg7_vertex_0700F9F8, 7, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP1Triangle( 0, 6, 1, 0x0), gsSPLight(&bbh_seg7_lights_0700F8D0.l, 1), gsSPLight(&bbh_seg7_lights_0700F8D0.a, 2), gsSPVertex(bbh_seg7_vertex_0700FA68, 8, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSPLight(&bbh_seg7_lights_0700F8E8.l, 1), gsSPLight(&bbh_seg7_lights_0700F8E8.a, 2), gsSPVertex(bbh_seg7_vertex_0700FAE8, 12, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0), gsSPEndDisplayList(), }; // 0x07010B58 - 0x07010C30 static const Gfx bbh_seg7_dl_07010B58[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, spooky_09003800), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 64 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPLight(&bbh_seg7_lights_0700F8B8.l, 1), gsSPLight(&bbh_seg7_lights_0700F8B8.a, 2), gsSPVertex(bbh_seg7_vertex_0700FBA8, 4, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSPLight(&bbh_seg7_lights_0700F8E8.l, 1), gsSPLight(&bbh_seg7_lights_0700F8E8.a, 2), gsSPVertex(bbh_seg7_vertex_0700FBE8, 12, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 10, 11, 0x0), gsSPLight(&bbh_seg7_lights_0700F900.l, 1), gsSPLight(&bbh_seg7_lights_0700F900.a, 2), gsSPVertex(bbh_seg7_vertex_0700FCA8, 12, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0), gsSPEndDisplayList(), }; // 0x07010C30 - 0x07010D00 static const Gfx bbh_seg7_dl_07010C30[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, bbh_seg7_texture_07000000), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 64 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPLight(&bbh_seg7_lights_0700F8B8.l, 1), gsSPLight(&bbh_seg7_lights_0700F8B8.a, 2), gsSPVertex(bbh_seg7_vertex_0700FD68, 12, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 10, 11, 0x0), gsSPLight(&bbh_seg7_lights_0700F8E8.l, 1), gsSPLight(&bbh_seg7_lights_0700F8E8.a, 2), gsSPVertex(bbh_seg7_vertex_0700FE28, 16, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 4, 0x0), gsSP2Triangles( 0, 5, 3, 0x0, 0, 4, 1, 0x0), gsSP2Triangles( 6, 7, 8, 0x0, 6, 9, 7, 0x0), gsSP2Triangles( 6, 10, 9, 0x0, 6, 8, 11, 0x0), gsSP2Triangles(12, 13, 14, 0x0, 12, 14, 15, 0x0), gsSPEndDisplayList(), }; // 0x07010D00 - 0x07010D90 static const Gfx bbh_seg7_dl_07010D00[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, spooky_09005000), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 64 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPVertex(bbh_seg7_vertex_0700FF28, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 3, 5, 6, 0x0, 7, 8, 9, 0x0), gsSP2Triangles( 7, 10, 8, 0x0, 11, 12, 13, 0x0), gsSP1Triangle(11, 13, 14, 0x0), gsSPVertex(bbh_seg7_vertex_07010018, 11, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 6, 7, 8, 0x0, 6, 9, 7, 0x0), gsSP1Triangle( 0, 10, 1, 0x0), gsSPEndDisplayList(), }; // 0x07010D90 - 0x07011058 static const Gfx bbh_seg7_dl_07010D90[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, spooky_09000800), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 64 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPVertex(bbh_seg7_vertex_070100C8, 14, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 0, 0x0, 4, 0, 2, 0x0), gsSP2Triangles( 6, 1, 3, 0x0, 7, 6, 3, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 10, 11, 0x0), gsSP2Triangles(12, 8, 11, 0x0, 12, 13, 8, 0x0), gsSPVertex(bbh_seg7_vertex_070101A8, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 3, 6, 4, 0x0, 7, 8, 9, 0x0), gsSP2Triangles( 7, 10, 8, 0x0, 11, 12, 13, 0x0), gsSP1Triangle(11, 14, 12, 0x0), gsSPVertex(bbh_seg7_vertex_07010298, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 6, 7, 8, 0x0, 7, 9, 8, 0x0), gsSP2Triangles( 7, 10, 9, 0x0, 7, 11, 10, 0x0), gsSP2Triangles(12, 10, 11, 0x0, 12, 11, 13, 0x0), gsSP1Triangle( 0, 2, 14, 0x0), gsSPVertex(bbh_seg7_vertex_07010388, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 3, 6, 4, 0x0, 7, 8, 9, 0x0), gsSP2Triangles( 7, 10, 8, 0x0, 11, 12, 13, 0x0), gsSP1Triangle(11, 14, 12, 0x0), gsSPVertex(bbh_seg7_vertex_07010478, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 6, 7, 8, 0x0, 6, 8, 9, 0x0), gsSP2Triangles(10, 11, 12, 0x0, 10, 13, 11, 0x0), gsSP1Triangle( 0, 2, 14, 0x0), gsSPVertex(bbh_seg7_vertex_07010568, 16, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 8, 10, 11, 0x0), gsSP2Triangles(12, 13, 14, 0x0, 12, 14, 15, 0x0), gsSPVertex(bbh_seg7_vertex_07010668, 16, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 3, 6, 4, 0x0, 3, 7, 6, 0x0), gsSP2Triangles( 8, 3, 5, 0x0, 9, 4, 6, 0x0), gsSP2Triangles( 9, 10, 4, 0x0, 11, 5, 12, 0x0), gsSP2Triangles(11, 8, 5, 0x0, 13, 11, 12, 0x0), gsSP2Triangles(13, 12, 10, 0x0, 9, 13, 10, 0x0), gsSP2Triangles( 9, 14, 13, 0x0, 0, 15, 1, 0x0), gsSPVertex(bbh_seg7_vertex_07010768, 15, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 2, 1, 4, 0x0, 2, 4, 5, 0x0), gsSP2Triangles( 4, 6, 7, 0x0, 4, 7, 5, 0x0), gsSP2Triangles( 8, 9, 10, 0x0, 11, 12, 13, 0x0), gsSP1Triangle( 8, 10, 14, 0x0), gsSPVertex(bbh_seg7_vertex_07010858, 11, 0), gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0), gsSP2Triangles( 6, 7, 8, 0x0, 6, 8, 9, 0x0), gsSP1Triangle( 0, 10, 1, 0x0), gsSPEndDisplayList(), }; // 0x07011058 - 0x070110A0 static const Gfx bbh_seg7_dl_07011058[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, spooky_09002800), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 64 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPVertex(bbh_seg7_vertex_07010908, 8, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0), gsSPEndDisplayList(), }; // 0x070110A0 - 0x070110E8 static const Gfx bbh_seg7_dl_070110A0[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, bbh_seg7_texture_07002000), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 64 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)), gsSPVertex(bbh_seg7_vertex_07010988, 8, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0), gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0), gsSPEndDisplayList(), }; // 0x070110E8 - 0x07011120 static const Gfx bbh_seg7_dl_070110E8[] = { gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, spooky_09009000), gsDPLoadSync(), gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 64 * 32 - 1, CALC_DXT(64, G_IM_SIZ_16b_BYTES)), gsSPVertex(bbh_seg7_vertex_07010A08, 4, 0), gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0), gsSPEndDisplayList(), }; // 0x07011120 - 0x07011228 const Gfx bbh_seg7_dl_07011120[] = { gsDPPipeSync(), gsDPSetCombineMode(G_CC_MODULATERGB, G_CC_MODULATERGB), gsSPClearGeometryMode(G_SHADING_SMOOTH), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 0, 0, G_TX_LOADTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_CLAMP, 5, G_TX_NOLOD, G_TX_CLAMP, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(bbh_seg7_dl_07010A48), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_CLAMP, 6, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (64 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(bbh_seg7_dl_07010B58), gsSPDisplayList(bbh_seg7_dl_07010C30), gsSPDisplayList(bbh_seg7_dl_07010D00), gsSPDisplayList(bbh_seg7_dl_07010D90), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 6, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (64 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(bbh_seg7_dl_07011058), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_CLAMP, 6, G_TX_NOLOD, G_TX_CLAMP, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (64 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(bbh_seg7_dl_070110A0), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 16, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 6, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (64 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPDisplayList(bbh_seg7_dl_070110E8), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF), gsDPPipeSync(), gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE), gsSPSetGeometryMode(G_SHADING_SMOOTH), gsSPEndDisplayList(), };
57.72623
173
0.495811
1f87f50a0c92e576a96adac38800bc93a830adf1
25,216
h
C
System/Library/PrivateFrameworks/CoverSheet.framework/CSCombinedListViewController.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/PrivateFrameworks/CoverSheet.framework/CSCombinedListViewController.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/CoverSheet.framework/CSCombinedListViewController.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:52:10 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/CoverSheet.framework/CoverSheet * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <CoverSheet/CoverSheet-Structs.h> #import <CoverSheet/CSCoverSheetViewControllerBase.h> #import <libobjc.A.dylib/CSNotificationAdjunctListViewControllerDelegate.h> #import <libobjc.A.dylib/SBFMotionGestureObserver.h> #import <libobjc.A.dylib/NCNotificationStructuredListContentObserver.h> #import <libobjc.A.dylib/CSStatusBarBackgroundIntersecting.h> #import <libobjc.A.dylib/PTSettingsKeyObserver.h> #import <libobjc.A.dylib/CSHomeGestureParticipating.h> #import <libobjc.A.dylib/CSDNDBedtimeControllerObserver.h> #import <libobjc.A.dylib/DNDStateUpdateListener.h> #import <libobjc.A.dylib/CSDNDBedtimeGreetingDelegate.h> #import <libobjc.A.dylib/CSApplicationInformationObserving.h> #import <libobjc.A.dylib/NCNotificationStructuredListViewControllerDelegate.h> #import <libobjc.A.dylib/SBUICoronaAnimationControllerParticipant.h> #import <libobjc.A.dylib/_UIGestureStudyInteractionDelegate.h> #import <libobjc.A.dylib/CSProximitySensorProviderObserver.h> #import <libobjc.A.dylib/CSNotificationDestination.h> #import <libobjc.A.dylib/CSDateViewScrolling.h> #import <libobjc.A.dylib/CSAppearanceProviding.h> @protocol SBUIBiometricResource, BSInvalidatable, CSCombinedListViewControllerDelegate, CSApplicationInforming, CSNotificationDispatcher, CSPageViewControllerProtocol, CSHomeAffordanceControlling, CSUnlockRequesting, CSNotificationPresenting, SBFAuthenticationStatusProvider, CSProximitySensorProviding, CSDeviceOrientationProviding; @class NSString, NSSet, _UILegibilitySettings, UIColor, UIViewController, NCNotificationStructuredListViewController, SBFTouchPassThroughView, BSTimer, CSComponent, NSMutableSet, CSDNDBedtimeController, CSDNDBedtimeGreetingViewController, _UIGestureStudyInteraction, NSDate, CSLayoutStrategy, CSNotificationAdjunctListViewController, NCNotificationRequest, DNDEventBehaviorResolutionService, DNDStateService, CSLockScreenSettings, UIScrollView; @interface CSCombinedListViewController : CSCoverSheetViewControllerBase <CSNotificationAdjunctListViewControllerDelegate, SBFMotionGestureObserver, NCNotificationStructuredListContentObserver, CSStatusBarBackgroundIntersecting, PTSettingsKeyObserver, CSHomeGestureParticipating, CSDNDBedtimeControllerObserver, DNDStateUpdateListener, CSDNDBedtimeGreetingDelegate, CSApplicationInformationObserving, NCNotificationStructuredListViewControllerDelegate, SBUICoronaAnimationControllerParticipant, _UIGestureStudyInteractionDelegate, CSProximitySensorProviderObserver, CSNotificationDestination, CSDateViewScrolling, CSAppearanceProviding> { UIViewController* _captureOnlyMaterialViewController; NCNotificationStructuredListViewController* _structuredListViewController; SBFTouchPassThroughView* _clippingView; double _cachedAdjunctHeight; double _footerOffset; BOOL _listPresentingContent; BOOL _listDismissingContent; BOOL _listBeingLaidOut; BSTimer* _significantUserInteractionTimer; BOOL _listSuppressLongLookDismissal; CSComponent* _dateViewComponent; CSComponent* _statusBarBackgroundComponent; CSComponent* _proudLockComponent; CSComponent* _homeAffordanceComponent; CSComponent* _footerCallToActionLabelComponent; BOOL _hasUserInteraction; CSComponent* _statusBarComponent; NSMutableSet* _quickActionsHiddenReasons; CSComponent* _quickActionsComponent; CSDNDBedtimeController* _dndBedtimeController; CSDNDBedtimeGreetingViewController* _dndBedtimeGreetingViewController; NSMutableSet* _backgroundAnimationDisabledReasons; NSMutableSet* _footerCallToActionHiddenReasons; NSMutableSet* _notificationListHiddenReasons; NSMutableSet* _dismissGestureDisabledReasons; _UILegibilitySettings* _legibilitySettings; _UIGestureStudyInteraction* _gestureStudyInteraction; NSDate* _screenOnTime; BOOL _confirmedNotInPocket; BOOL _shouldPadBottomSpacingWhileDragging; id<SBUIBiometricResource> _biometricResource; id<BSInvalidatable> _faceDetectWantedAssertion; id<BSInvalidatable> _notificationLongPressProximitySensorAssertion; id<BSInvalidatable> _deviceWakeProximitySensorAssertion; BOOL _faceInView; BOOL _liftDetected; BOOL _homeButtonPressDetected; BOOL _lockButtonPressDetected; BOOL _screenOn; BOOL _coverSheetWasDismissed; BOOL _historyWasRevealed; BOOL _proximitySensorCoveredSinceWake; BOOL _hasProximitySensor; BOOL _dndNotificationDeliveryDelayActive; BOOL _dndDrivingModeActive; BOOL _disableScrolling; BOOL _disableBackgroundAnimation; BOOL _footerCallToActionLabelHidden; BOOL _notificationListHidden; BOOL _dismissGestureDisabled; BOOL _presentationDirtiedAppearance; id<CSCombinedListViewControllerDelegate> _delegate; id<CSApplicationInforming> _applicationInformer; id<CSNotificationDispatcher> _dispatcher; CSLayoutStrategy* _layoutStrategy; id<CSPageViewControllerProtocol> _page; id<CSHomeAffordanceControlling> _homeAffordanceController; id<CSUnlockRequesting> _unlockRequester; id<CSNotificationPresenting> _notificationPresenter; id<SBFAuthenticationStatusProvider> _authenticationStatusProvider; id<CSProximitySensorProviding> _proximitySensorProvider; id<CSDeviceOrientationProviding> _deviceOrientationProvider; CSNotificationAdjunctListViewController* _adjunctListViewController; NCNotificationRequest* _activeRaiseToListenNotificationRequest; DNDEventBehaviorResolutionService* _dndEventBehaviorResolutionService; DNDStateService* _dndStateService; CSLockScreenSettings* _lockScreenSettings; SBFTouchPassThroughView* _debugViewLeft; SBFTouchPassThroughView* _debugViewRight; } @property (nonatomic,readonly) UIViewController * notificationListViewController; @property (nonatomic,readonly) UIScrollView * notificationListScrollView; @property (nonatomic,retain) CSNotificationAdjunctListViewController * adjunctListViewController; //@synthesize adjunctListViewController=_adjunctListViewController - In the implementation block @property (nonatomic,retain) NCNotificationRequest * activeRaiseToListenNotificationRequest; //@synthesize activeRaiseToListenNotificationRequest=_activeRaiseToListenNotificationRequest - In the implementation block @property (nonatomic,retain) DNDEventBehaviorResolutionService * dndEventBehaviorResolutionService; //@synthesize dndEventBehaviorResolutionService=_dndEventBehaviorResolutionService - In the implementation block @property (nonatomic,retain) DNDStateService * dndStateService; //@synthesize dndStateService=_dndStateService - In the implementation block @property (assign,getter=isDndNotificationDeliveryDelayActive,nonatomic) BOOL dndNotificationDeliveryDelayActive; //@synthesize dndNotificationDeliveryDelayActive=_dndNotificationDeliveryDelayActive - In the implementation block @property (assign,getter=isDndDrivingModeActive,nonatomic) BOOL dndDrivingModeActive; //@synthesize dndDrivingModeActive=_dndDrivingModeActive - In the implementation block @property (nonatomic,retain) CSLockScreenSettings * lockScreenSettings; //@synthesize lockScreenSettings=_lockScreenSettings - In the implementation block @property (nonatomic,retain) SBFTouchPassThroughView * debugViewLeft; //@synthesize debugViewLeft=_debugViewLeft - In the implementation block @property (nonatomic,retain) SBFTouchPassThroughView * debugViewRight; //@synthesize debugViewRight=_debugViewRight - In the implementation block @property (assign,setter=_setHasUserInteraction:,getter=_hasUserInteraction,nonatomic) BOOL hasUserInteraction; //@synthesize hasUserInteraction=_hasUserInteraction - In the implementation block @property (assign,setter=_setDisableScrolling:,getter=_disableScrolling,nonatomic) BOOL disableScrolling; //@synthesize disableScrolling=_disableScrolling - In the implementation block @property (nonatomic,readonly) BOOL disableBackgroundAnimation; //@synthesize disableBackgroundAnimation=_disableBackgroundAnimation - In the implementation block @property (nonatomic,readonly) BOOL footerCallToActionLabelHidden; //@synthesize footerCallToActionLabelHidden=_footerCallToActionLabelHidden - In the implementation block @property (nonatomic,readonly) BOOL notificationListHidden; //@synthesize notificationListHidden=_notificationListHidden - In the implementation block @property (nonatomic,readonly) BOOL dismissGestureDisabled; //@synthesize dismissGestureDisabled=_dismissGestureDisabled - In the implementation block @property (assign,getter=hasPresentationDirtiedAppearance,nonatomic) BOOL presentationDirtiedAppearance; //@synthesize presentationDirtiedAppearance=_presentationDirtiedAppearance - In the implementation block @property (nonatomic,readonly) BOOL hasContent; //@synthesize listPresentingContent=_listPresentingContent - In the implementation block @property (nonatomic,readonly) BOOL hasVisibleContentToReveal; @property (getter=isShowingMediaControls,nonatomic,readonly) BOOL showingMediaControls; @property (nonatomic,readonly) NSString * listViewControllerBackgroundGroupName; @property (nonatomic,retain) CSLayoutStrategy * layoutStrategy; //@synthesize layoutStrategy=_layoutStrategy - In the implementation block @property (assign,nonatomic,__weak) id<CSCombinedListViewControllerDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block @property (assign,nonatomic,__weak) id<CSPageViewControllerProtocol> page; //@synthesize page=_page - In the implementation block @property (assign,nonatomic,__weak) id<SBFActionProviding> contentActionProvider; @property (assign,nonatomic,__weak) id<CSApplicationInforming> applicationInformer; //@synthesize applicationInformer=_applicationInformer - In the implementation block @property (assign,nonatomic,__weak) id<CSHomeAffordanceControlling> homeAffordanceController; //@synthesize homeAffordanceController=_homeAffordanceController - In the implementation block @property (assign,nonatomic,__weak) id<CSUnlockRequesting> unlockRequester; //@synthesize unlockRequester=_unlockRequester - In the implementation block @property (assign,nonatomic,__weak) id<CSNotificationPresenting> notificationPresenter; //@synthesize notificationPresenter=_notificationPresenter - In the implementation block @property (assign,nonatomic,__weak) id<SBFAuthenticationStatusProvider> authenticationStatusProvider; //@synthesize authenticationStatusProvider=_authenticationStatusProvider - In the implementation block @property (assign,nonatomic,__weak) id<CSProximitySensorProviding> proximitySensorProvider; //@synthesize proximitySensorProvider=_proximitySensorProvider - In the implementation block @property (assign,nonatomic,__weak) id<CSDeviceOrientationProviding> deviceOrientationProvider; //@synthesize deviceOrientationProvider=_deviceOrientationProvider - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,readonly) double distanceFromBarToContent; @property (nonatomic,readonly) double topContentInset; @property (assign,nonatomic,__weak) id<CSNotificationDispatcher> dispatcher; //@synthesize dispatcher=_dispatcher - In the implementation block @property (nonatomic,copy,readonly) NSString * coverSheetIdentifier; @property (nonatomic,readonly) long long participantState; @property (nonatomic,readonly) double clippingOffset; @property (nonatomic,copy,readonly) NSString * appearanceIdentifier; @property (nonatomic,readonly) long long backgroundStyle; @property (nonatomic,copy,readonly) NSSet * components; @property (nonatomic,readonly) _UILegibilitySettings * legibilitySettings; @property (nonatomic,readonly) UIColor * backgroundColor; -(void)updateNotificationRequest:(id)arg1 ; -(void)_addStateCaptureHandlers; -(void)postNotificationRequest:(id)arg1 ; -(void)setDispatcher:(id<CSNotificationDispatcher>)arg1 ; -(void)coronaAnimationController:(id)arg1 willAnimateCoronaTransitionWithAnimator:(id)arg2 ; -(long long)presentationPriority; -(id<SBFActionProviding>)contentActionProvider; -(void)updateForLegibilitySettings:(id)arg1 ; -(BOOL)disableBackgroundAnimation; -(void)setNotificationPresenter:(id<CSNotificationPresenting>)arg1 ; -(CSLockScreenSettings *)lockScreenSettings; -(void)withdrawNotificationRequest:(id)arg1 ; -(void)notificationStructuredListViewController:(id)arg1 presentingLongLook:(BOOL)arg2 ; -(id<CSDeviceOrientationProviding>)deviceOrientationProvider; -(BOOL)dismissNotificationInLongLookAnimated:(BOOL)arg1 ; -(long long)presentationTransition; -(void)setDndStateService:(DNDStateService *)arg1 ; -(long long)presentationType; -(void)notificationsLoadedForSectionIdentifier:(id)arg1 ; -(void)setPage:(id<CSPageViewControllerProtocol>)arg1 ; -(id<CSNotificationDispatcher>)dispatcher; -(void)setPresentationDirtiedAppearance:(BOOL)arg1 ; -(void)setLockScreenSettings:(CSLockScreenSettings *)arg1 ; -(void)viewWillDisappear:(BOOL)arg1 ; -(BOOL)isShowingMediaControls; -(void)updateNotificationSectionSettings:(id)arg1 previousSectionSettings:(id)arg2 ; -(BOOL)_allowNotificationsRevealPolicy; -(void)setAuthenticationStatusProvider:(id<SBFAuthenticationStatusProvider>)arg1 ; -(id<SBFAuthenticationStatusProvider>)authenticationStatusProvider; -(BOOL)isPresentingNotificationInLongLook; -(void)_updateDeviceWakeProximitySensorAssertion; -(double)topContentInset; -(BOOL)isNotificationContentExtensionVisible:(id)arg1 ; -(void)_setDisableScrolling:(BOOL)arg1 ; -(void)dndBedtimeControllerShowGreetingStateDidChange:(id)arg1 animated:(BOOL)arg2 ; -(void)aggregateBehavior:(id)arg1 ; -(void)_updateRaiseGestureDetectionForNotificationRequest:(id)arg1 ; -(void)setDeviceOrientationProvider:(id<CSDeviceOrientationProviding>)arg1 ; -(BOOL)notificationStructuredListViewController:(id)arg1 shouldAllowInteractionsForNotificationRequest:(id)arg2 ; -(CSNotificationAdjunctListViewController *)adjunctListViewController; -(NSString *)listViewControllerBackgroundGroupName; -(void)notificationStructuredListViewController:(id)arg1 requestsClearingNotificationRequests:(id)arg2 ; -(BOOL)_shouldFilterNotificationRequest:(id)arg1 ; -(CSLayoutStrategy *)layoutStrategy; -(id)settleHomeAffordanceAnimationBehaviorDescriptionForNotificationStructuredListViewController:(id)arg1 ; -(void)scrollViewWillEndDragging:(id)arg1 withVelocity:(CGPoint)arg2 targetContentOffset:(inout CGPoint*)arg3 ; -(id)notificationStructuredListViewController:(id)arg1 requestsSectionSettingsForSectionIdentifier:(id)arg2 ; -(double)interItemSpacingToMimicForAdjunctListViewController:(id)arg1 ; -(void)setLayoutStrategy:(CSLayoutStrategy *)arg1 ; -(void)_setQuickActionsHidden:(BOOL)arg1 forReason:(id)arg2 ; -(void)_handleBiometricEvent:(unsigned long long)arg1 ; -(id)initWithNibName:(id)arg1 bundle:(id)arg2 ; -(BOOL)notificationStructuredListViewControllerShouldAllowNotificationHistoryReveal:(id)arg1 ; -(BOOL)notificationStructuredListViewControllerShouldAllowLongPressGesture:(id)arg1 ; -(BOOL)_disableScrolling; -(void)migrateIncomingNotificationsToNotificationCenter; -(void)notificationStructuredListViewControllerDidScrollToRevealNotificationHistory:(id)arg1 ; -(BOOL)wouldHandleButtonEvent:(id)arg1 ; -(id<CSPageViewControllerProtocol>)page; -(void)setActiveRaiseToListenNotificationRequest:(NCNotificationRequest *)arg1 ; -(DNDStateService *)dndStateService; -(double)_minListHeightForPadding; -(void)_updateNotificationLongPressProximitySensorAssertion; -(void)_layoutListView; -(BOOL)interpretsViewAsContent:(id)arg1 ; -(BOOL)hasContent; -(void)setProximitySensorProvider:(id<CSProximitySensorProviding>)arg1 ; -(void)scrollViewDidScroll:(id)arg1 ; -(void)setAdjunctListViewController:(CSNotificationAdjunctListViewController *)arg1 ; -(BOOL)dismissGestureDisabled; -(UIScrollView *)notificationListScrollView; -(void)_updateFaceDetectAssertion; -(void)dealloc; -(void)viewDidAppear:(BOOL)arg1 ; -(void)_updateListViewContentInset; -(double)_statusBarHeight; -(void)settings:(id)arg1 changedValueForKey:(id)arg2 ; -(void)adjunctListViewController:(id)arg1 didUpdateWithSize:(CGSize)arg2 ; -(id)_identifierForNotificationRequest:(id)arg1 ; -(void)viewDidLoad; -(id)legibilitySettingsForNotificationStructuredListViewController:(id)arg1 ; -(NCNotificationRequest *)activeRaiseToListenNotificationRequest; -(BOOL)hasVisibleContentToReveal; -(void)dismissDNDBedtimeGreetingViewController:(id)arg1 animated:(BOOL)arg2 ; -(BOOL)notificationStructuredListViewControllerShouldHintForDefaultAction:(id)arg1 ; -(void)rebuildEverythingForReason:(id)arg1 ; -(id<CSHomeAffordanceControlling>)homeAffordanceController; -(void)setDebugViewRight:(SBFTouchPassThroughView *)arg1 ; -(void)_dismissDNDBedtimeGreetingViewAnimated:(BOOL)arg1 ; -(void)notificationStructuredListViewController:(id)arg1 requestPermissionToExecuteAction:(id)arg2 forNotificationRequest:(id)arg3 withParameters:(id)arg4 completion:(/*^block*/id)arg5 ; -(void)notificationStructuredListViewController:(id)arg1 requestsAuthenticationAndPerformBlock:(/*^block*/id)arg2 ; -(void)setHomeAffordanceController:(id<CSHomeAffordanceControlling>)arg1 ; -(double)defaultRestingOffsetExcludingAdjunct; -(double)distanceFromBarToContent; -(SBFTouchPassThroughView *)debugViewRight; -(BOOL)notificationStructuredListViewController:(id)arg1 isClockNotificationRequest:(id)arg2 ; -(BOOL)hasPresentationDirtiedAppearance; -(void)viewWillLayoutSubviews; -(double)clippingOffset; -(BOOL)notificationStructuredListViewController:(id)arg1 shouldFilterNotificationRequest:(id)arg2 ; -(DNDEventBehaviorResolutionService *)dndEventBehaviorResolutionService; -(void)_setFooterCallToActionLabelHidden:(BOOL)arg1 forReason:(id)arg2 ; -(CGSize)_adjunctListViewSize; -(id<CSNotificationPresenting>)notificationPresenter; -(CGRect)_suggestedListViewFrame; -(void)_requestAuthenticationWithCompletion:(/*^block*/id)arg1 ; -(void)notificationStructuredListViewController:(id)arg1 setDeliverQuietly:(BOOL)arg2 forSectionIdentifier:(id)arg3 ; -(id<CSApplicationInforming>)applicationInformer; -(void)_setHasUserInteraction:(BOOL)arg1 ; -(BOOL)shouldAutomaticallyForwardAppearanceMethods; -(BOOL)handleEvent:(id)arg1 ; -(void)setDebugViewLeft:(SBFTouchPassThroughView *)arg1 ; -(CGPoint)_determineMaxContentOffsetForContentInset:(UIEdgeInsets)arg1 ; -(void)aggregateAppearance:(id)arg1 ; -(void)_liftToWakeGestureDetected; -(void)setDelegate:(id<CSCombinedListViewControllerDelegate>)arg1 ; -(void)_setDismissGestureDisabled:(BOOL)arg1 forReason:(id)arg2 ; -(void)_stopScreenOnTimer; -(id)notificationStructuredListViewController:(id)arg1 keyboardAssertionForGestureWindow:(id)arg2 ; -(void)notificationStructuredListViewController:(id)arg1 didBeginUserInteractionWithNotificationViewController:(id)arg2 ; -(void)_testingCoalesceExpandedBundleForNotificationRequest:(id)arg1 withCompletion:(/*^block*/id)arg2 ; -(void)scrollViewWillBeginDragging:(id)arg1 ; -(void)notificationStructuredListViewController:(id)arg1 requestsClearingFromIncomingSectionNotificationRequests:(id)arg2 ; -(void)_updatePresentation; -(void)setApplicationInformer:(id<CSApplicationInforming>)arg1 ; -(void)notificationStructuredListViewController:(id)arg1 setAllowsNotifications:(BOOL)arg2 forSectionIdentifier:(id)arg3 ; -(void)viewWillTransitionToSize:(CGSize)arg1 withTransitionCoordinator:(id)arg2 ; -(CGSize)effectiveContentSizeForScrollView:(id)arg1 ; -(BOOL)_hasUserInteraction; -(void)performCustomTransitionToVisible:(BOOL)arg1 withAnimationSettings:(id)arg2 completion:(/*^block*/id)arg3 ; -(void)_performSelfCorrectingListViewAction:(/*^block*/id)arg1 ; -(id)unhideHomeAffordanceAnimationSettingsForNotificationStructuredListViewController:(id)arg1 ; -(id<CSUnlockRequesting>)unlockRequester; -(double)_minInsetsToPushDateOffScreen; -(id)groupNameBaseForAdjunctListViewController:(id)arg1 ; -(id<CSProximitySensorProviding>)proximitySensorProvider; -(BOOL)isDndDrivingModeActive; -(void)_setListHasContent:(BOOL)arg1 ; -(id)_threadIdentifierForNotificationRequest:(id)arg1 ; -(id)_updateProximitySensorAssertion:(id)arg1 wantsAssertion:(BOOL)arg2 forReason:(id)arg3 ; -(void)_setNotificationListHidden:(BOOL)arg1 forReason:(id)arg2 ; -(id)_testingNotificationRequestWithIdentifier:(id)arg1 sectionIdentifier:(id)arg2 ; -(void)_toggleGestureStudyInteractionIfNecessary; -(void)notificationStructuredListViewController:(id)arg1 didEndUserInteractionWithNotificationViewController:(id)arg2 ; -(void)proximitySensorProvider:(id)arg1 objectWithinProximityDidChange:(BOOL)arg2 ; -(BOOL)isDndNotificationDeliveryDelayActive; -(void)setDndEventBehaviorResolutionService:(DNDEventBehaviorResolutionService *)arg1 ; -(void)setDndNotificationDeliveryDelayActive:(BOOL)arg1 ; -(BOOL)_shouldScreenTimeSuppressNotificationsForBundleIdentifier:(id)arg1 ; -(void)forceNotificationHistoryRevealed:(BOOL)arg1 animated:(BOOL)arg2 ; -(void)_startScreenOnTimer; -(BOOL)notificationStructuredListViewController:(id)arg1 shouldDelayDeliveryOfNotificationRequest:(id)arg2 ; -(void)setUnlockRequester:(id<CSUnlockRequesting>)arg1 ; -(CGSize)sizeToMimicForAdjunctListViewController:(id)arg1 ; -(BOOL)_allowsDateViewOrProudLockScroll; -(void)updateAppearanceForHidden:(BOOL)arg1 offset:(CGPoint)arg2 ; -(void)notificationStructuredListViewController:(id)arg1 setAllowsCriticalAlerts:(BOOL)arg2 forSectionIdentifier:(id)arg3 ; -(id<CSCombinedListViewControllerDelegate>)delegate; -(id)notificationUsageTrackingStateForNotificationStructuredListViewController:(id)arg1 ; -(void)didReceiveRaiseGesture; -(void)notificationStructuredListViewController:(id)arg1 shouldFinishLongLookTransitionForNotificationRequest:(id)arg2 trigger:(long long)arg3 withCompletionBlock:(/*^block*/id)arg4 ; -(void)setDndDrivingModeActive:(BOOL)arg1 ; -(void)stateService:(id)arg1 didReceiveDoNotDisturbStateUpdate:(id)arg2 ; -(BOOL)_shouldPadBottomSpacing; -(void)notificationStructuredListViewController:(id)arg1 requestsClearingNotificationRequestsInSections:(id)arg2 ; -(void)viewWillAppear:(BOOL)arg1 ; -(void)setContentActionProvider:(id<SBFActionProviding>)arg1 ; -(double)_sanitizedContentOffset:(double)arg1 forContentInset:(UIEdgeInsets)arg2 ; -(void)resetContentOffset; -(void)_lockButtonPressDetected; -(SBFTouchPassThroughView *)debugViewLeft; -(void)homeGestureParticipantOwningHomeGestureDidChange:(id)arg1 ownsHomeGesture:(BOOL)arg2 ; -(void)notificationStructuredListViewController:(id)arg1 requestsExecuteAction:(id)arg2 forNotificationRequest:(id)arg3 requestAuthentication:(BOOL)arg4 withParameters:(id)arg5 completion:(/*^block*/id)arg6 ; -(void)updateAppearanceForStatusBarBackgroundHidden:(BOOL)arg1 ; -(void)notificationStructuredListViewControllerDidSignificantUserInteraction:(id)arg1 ; -(UIEdgeInsets)insetMarginsToMimicForAdjunctListViewController:(id)arg1 ; -(void)applicationInformer:(id)arg1 updatedApplications:(id)arg2 ; -(void)dndBedtimeControllerActiveStateDidChange:(id)arg1 ; -(void)layoutListView; -(BOOL)footerCallToActionLabelHidden; -(BOOL)notificationListHidden; -(void)_screenTimeExpirationApplicationsDidChange:(id)arg1 ; -(void)_setDisableBackgroundAnimation:(BOOL)arg1 forReason:(id)arg2 ; -(void)_updateCaptureOnlyMaterialView; -(UIViewController *)notificationListViewController; -(void)_testingExpandCoalescedBundleForNotificationRequest:(id)arg1 withCompletion:(/*^block*/id)arg2 ; -(BOOL)_isClockSnoozeAlarmNotificationRequest:(id)arg1 ; -(id)hideHomeAffordanceAnimationSettingsForNotificationStructuredListViewController:(id)arg1 ; -(void)_homeButtonPressDetected; -(void)_evaluateShouldShowGreeting:(id)arg1 animated:(BOOL)arg2 ; -(id)metadataForTriggeredInteraction:(id)arg1 ; -(void)structuredListContentChanged:(BOOL)arg1 ; -(UIEdgeInsets)_listViewDefaultContentInsets; -(BOOL)_shouldDNDDelayDeliveryOfNotificationRequest:(id)arg1 ; -(CGSize)_adjunctListViewSizeIncludingSpacing; @end
71.840456
638
0.815593
5adfea74237d039bb903c47c8221800974da1a51
682
h
C
YYCarouselView/YYCarouselView/YYCarouselViewFlowLayout.h
mofashy/YYCarouselView
7417863491223bde19e1a85697fac8718b227c81
[ "MIT" ]
null
null
null
YYCarouselView/YYCarouselView/YYCarouselViewFlowLayout.h
mofashy/YYCarouselView
7417863491223bde19e1a85697fac8718b227c81
[ "MIT" ]
null
null
null
YYCarouselView/YYCarouselView/YYCarouselViewFlowLayout.h
mofashy/YYCarouselView
7417863491223bde19e1a85697fac8718b227c81
[ "MIT" ]
null
null
null
// // YYCarouselViewFlowLayout.h // YYCarouselView // // Created by 沈永聪 on 2018/10/22. // Copyright © 2018 沈永聪. All rights reserved. // #import <UIKit/UIKit.h> #import "YYCarouselViewLayoutAttributes.h" NS_ASSUME_NONNULL_BEGIN @protocol YYCarouselViewAnimatorProtocol <NSObject> - (void)animate:(UICollectionView *)collectionView attributes:(YYCarouselViewLayoutAttributes *)attributes; @end @interface YYCarouselViewStackAnimator : NSObject <YYCarouselViewAnimatorProtocol> @property (assign, nonatomic) CGFloat percent; - (instancetype)initWithPercent:(CGFloat)percent; @end @interface YYCarouselViewFlowLayout : UICollectionViewFlowLayout @end NS_ASSUME_NONNULL_END
22.733333
107
0.804985
6ecc98f41af87b602f93cd0c9f07508160cfba8e
124
h
C
L2SW/src/endian.h
kamaboko123/salacia-forwarder
756c504e49fce5b8ff35f6671f7d2117660ae10b
[ "MIT" ]
2
2019-09-10T12:35:27.000Z
2022-03-24T02:41:23.000Z
L2SW/src/endian.h
kamaboko123/salacia-forwarder
756c504e49fce5b8ff35f6671f7d2117660ae10b
[ "MIT" ]
8
2017-12-12T14:36:57.000Z
2018-11-06T15:10:05.000Z
L2SW/src/endian.h
kamaboko123/salacia-forwarder
756c504e49fce5b8ff35f6671f7d2117660ae10b
[ "MIT" ]
null
null
null
#ifndef ENDIAN_H #define ENDIAN_H #include <stdint.h> uint32_t swap_32(uint32_t n); uint16_t swap_16(uint16_t n); #endif
12.4
29
0.766129
5411f1d696c0bb9d2d5aed6b50528dd34cbc569e
452
h
C
SHA-1/sha1.h
GeorgiosGerontakis/OpenCL-hash-cracker
56aee9a1a7257d0710006218bae59da44c658775
[ "CC-BY-4.0" ]
null
null
null
SHA-1/sha1.h
GeorgiosGerontakis/OpenCL-hash-cracker
56aee9a1a7257d0710006218bae59da44c658775
[ "CC-BY-4.0" ]
null
null
null
SHA-1/sha1.h
GeorgiosGerontakis/OpenCL-hash-cracker
56aee9a1a7257d0710006218bae59da44c658775
[ "CC-BY-4.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <memory.h> #include <string.h> #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/cl.h> #endif #ifndef uint32_t #define uint32_t unsigned int #endif #define MAX_SOURCE_SIZE 0x10000000 // Function prototypes. void loadSource(); void createDevice(); void createkernel(); void createCLobjs(); void sha1Init(cl_uint*, size_t, int, const char*, const int*, const int*, int*); void runKernel();
18.833333
80
0.738938
e187b4b21826e5121e1dc7bd022fd858fa390166
923
h
C
Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEProgramStatusCellView.h
kolinkrewinkel/Multiplex
00d85e2261eb2e754a92f8127aff3b5ab5fb9893
[ "MIT" ]
314
2015-10-20T06:23:00.000Z
2021-06-03T18:44:18.000Z
Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEProgramStatusCellView.h
kolinkrewinkel/Multiplex
00d85e2261eb2e754a92f8127aff3b5ab5fb9893
[ "MIT" ]
29
2015-10-20T18:53:19.000Z
2016-08-24T15:40:39.000Z
Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEProgramStatusCellView.h
kolinkrewinkel/Multiplex
00d85e2261eb2e754a92f8127aff3b5ab5fb9893
[ "MIT" ]
14
2015-10-20T18:23:31.000Z
2016-12-08T19:31:06.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "CDStructures.h" @class IDEAccountPrefsDeveloperAccountDetailViewController, NSButton; @interface IDEProgramStatusCellView : NSTableCellView { IDEAccountPrefsDeveloperAccountDetailViewController *_detailViewController; NSButton *_joinButton; } + (BOOL)isForIOS; @property(retain, nonatomic) NSButton *joinButton; // @synthesize joinButton=_joinButton; @property(nonatomic) __weak IDEAccountPrefsDeveloperAccountDetailViewController *detailViewController; // @synthesize detailViewController=_detailViewController; - (void)updateUI; - (id)isMemberImage; - (BOOL)shouldShowJoinButton; - (BOOL)hasMembership; - (void)setObjectValue:(id)arg1; - (id)teamDescription; - (void)rollOverChangedNote:(id)arg1; - (void)join:(id)arg1; - (id)URLForJoin; - (void)dealloc; @end
27.969697
161
0.773564
916177f86abcf8f6d92f515a1255445d2e33ad43
2,147
c
C
ds/statistics/moving_average/mv_avg_elm.c
mirazabal/alg_ds
c70b0ece10fff64625e0235a0f8ce86fc5fef572
[ "MIT" ]
null
null
null
ds/statistics/moving_average/mv_avg_elm.c
mirazabal/alg_ds
c70b0ece10fff64625e0235a0f8ce86fc5fef572
[ "MIT" ]
null
null
null
ds/statistics/moving_average/mv_avg_elm.c
mirazabal/alg_ds
c70b0ece10fff64625e0235a0f8ce86fc5fef572
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2021 Mikel Irazabal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "mv_avg_elm.h" #include <assert.h> #include "../../../alg/accumulate.h" void mv_avg_elm_init(mv_avg_elm_t* m, uint32_t elm) { assert(m != NULL); assert(elm > 0); seq_init(&m->val, sizeof(uint32_t)); m->elm = elm; m->avg = 0.0; } void mv_avg_elm_free(mv_avg_elm_t* m) { assert(m != NULL); void* value_semantic = NULL; seq_free(&m->val, value_semantic); } void mv_avg_elm_push_back(mv_avg_elm_t* m, uint32_t val) { assert(m != NULL); size_t const elm = seq_size(&m->val); seq_push_back(&m->val, (uint8_t*)&val, sizeof(val)); m->avg = (m->avg*elm + val)/(elm+1); //+ val/(elm+1); } double mv_avg_elm_val(mv_avg_elm_t* m) { assert(m != NULL); size_t const sz = seq_size(&m->val); if(sz > m->elm){ void* f_val = seq_front(&m->val); void* l_val = seq_at(&m->val, sz - m->elm); uint64_t const acc = accumulate_ring(&m->val,f_val, l_val); seq_erase(&m->val, f_val, l_val); assert(seq_size(&m->val) == m->elm && "Num. elm adjusted"); m->avg = (m->avg*sz - acc)/(m->elm); } return m->avg; }
27.525641
78
0.703773
f411fc1aac64ba5f9008940db4cf83bbece3c87e
2,199
c
C
Encryption/Cryptlib/cryptolib_1.2/cryptolib/tests/testrand.c
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
46
2017-05-15T11:15:08.000Z
2018-07-02T03:32:52.000Z
Cryptlib/cryptolib_1.2/cryptolib/tests/testrand.c
ab300819/applied-cryptography
3fddc4cda2e1874e978608259034d36c60a4dbba
[ "MIT", "Unlicense" ]
null
null
null
Cryptlib/cryptolib_1.2/cryptolib/tests/testrand.c
ab300819/applied-cryptography
3fddc4cda2e1874e978608259034d36c60a4dbba
[ "MIT", "Unlicense" ]
24
2017-05-17T03:26:17.000Z
2018-07-09T07:00:50.000Z
#include <stdio.h> #include "libcrypt.h" main(argc, argv) int argc; char *argv[]; { int numbytes, i, type; Bignum *n; unsigned char buf[1024], *pwseed; char *filename; FILE *fp; if (argc < 4) { printf("Usage: testrand numbytes type (PSEUDO or REALLY) (BYTES or BIGS) (optional: PASSPHRASE)\n"); printf("If BYTES are specified, 1024*1024 bytes ar written to /tmp/pseudorandbytes or /tmp/truerandbytes\n"); exit(0); } if (strcmp(argv[2], "PSEUDO") == 0) { if (argc == 5) { pwseed = argv[4]; seed_rng((unsigned char *)pwseed, strlen(pwseed)); printf("seed = %s\n", pwseed); } type = PSEUDO; } else if (strcmp(argv[2], "REALLY") == 0) type = REALLY; else { printf("Usage: testrand numbytes type (PSEUDO or REALLY) (BYTES or BIGS) (optional: PASSPHRASE)\n"); printf("If BYTES are specified, 1024*1024 bytes ar written to /tmp/pseudorandbytes or /tmp/truerandbytes\n"); exit(0); } if (strcmp(argv[3], "BYTES") == 0) goto _BYTES; else if (strcmp(argv[3], "BIGS") == 0) goto _BIGS; else { printf("Usage: testrand numbytes type (PSEUDO or REALLY) (BYTES or BIGS) (optional: PASSPHRASE)\n"); printf("If BYTES are specified, 1024*1024 bytes ar written to /tmp/pseudorandbytes or /tmp/truerandbytes\n"); exit(0); } _BIGS: numbytes = atoi(argv[1]); n = bigInit(0); /* This is just to remind user that it takes awhile for the first call to desRandom() inside bigRand. Normally you don't have to do this...the seeding happens by default unless you call seed_rng(unsigned char *seed, int seedlen) with seedlen = 64 bytes. */ if (type == PSEUDO) { printf("seeding RNG...\n"); bigRand(numbytes, n, type); printf("done.\n"); } for (i=0; i<10; i++) { bigRand(numbytes, n, type); bigprint(n); } freeBignum(n); exit(0); _BYTES: if (type == REALLY) filename = "/tmp/truerandbytes"; else filename = "/tmp/pseudorandbytes"; fp = fopen(filename, "w"); i = 1024; while (i--) { randomBytes(buf, 1024, type); fwrite(buf, 1, 1024, fp); } fclose(fp); return 1; }
24.164835
114
0.603001
1ee88b45339507f6063e015899b4c27c60ef60a7
22,096
c
C
src/rico/rico_program.c
dbechrd/RicoTech
cda909f40d7a3ec338e46488ae2e724395b72d2e
[ "MIT" ]
23
2018-02-18T08:02:33.000Z
2021-10-06T14:11:21.000Z
src/rico/rico_program.c
dbechrd/RicoTech
cda909f40d7a3ec338e46488ae2e724395b72d2e
[ "MIT" ]
null
null
null
src/rico/rico_program.c
dbechrd/RicoTech
cda909f40d7a3ec338e46488ae2e724395b72d2e
[ "MIT" ]
null
null
null
static program_attribs_helper program_attribs[PROG_COUNT] = { 0, program_pbr_attribs, program_shadow_texture_attribs, program_shadow_cubemap_attribs, program_primitive_attribs, program_text_attribs }; ///============================================================================= //| General-purpose ///============================================================================= static int make_program(GLuint vertex_shader, GLuint geometry_shader, GLuint fragment_shader, GLuint *_program) { GLint status; GLuint program = glCreateProgram(); glAttachShader(program, vertex_shader); if (geometry_shader) glAttachShader(program, geometry_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); glDetachShader(program, vertex_shader); if (geometry_shader) glDetachShader(program, geometry_shader); glDetachShader(program, fragment_shader); glGetProgramiv(program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { fprintf(stderr, "Failed to link shader program:\n"); show_info_log(program, glGetProgramiv, glGetProgramInfoLog); //Clean up glDeleteProgram(program); return RICO_ERROR(RIC_ERR_SHADER_LINK, "Failed to link shader %s", "UNKNOWN"); } *_program = program; return RIC_SUCCESS; } static void free_program(GLuint program) { if (program) glDeleteProgram(program); } static GLint program_get_attrib_location(GLuint program, const char* name) { GLint location = glGetAttribLocation(program, name); if (location < 0) { fprintf(stderr, "[Program %d] Location not found for attribute '%s'. " "Possibly optimized out.\n", program, name); } return location; } static GLint program_get_uniform_location(GLuint program, const char* name) { GLint location = glGetUniformLocation(program, name); if (location < 0) { fprintf(stderr, "[Program %d] Location not found for attribute '%s'. " "Possibly optimized out.\n", program, name); } return location; } ///============================================================================= //| PBR program ///============================================================================= static void program_pbr_get_locations(struct program_pbr *p) { // Vertex shader p->locations.vert.model = program_get_uniform_location(p->program.gl_id, "model"); p->locations.vert.view = program_get_uniform_location(p->program.gl_id, "view"); p->locations.vert.proj = program_get_uniform_location(p->program.gl_id, "proj"); p->locations.vert.light_space = program_get_uniform_location(p->program.gl_id, "light_space"); RICO_ASSERT(p->locations.vert.model >= 0); RICO_ASSERT(p->locations.vert.view >= 0); RICO_ASSERT(p->locations.vert.proj >= 0); //RICO_ASSERT(p->locations.vert.light_space >= 0); p->locations.vert.attrs.position = program_get_attrib_location(p->program.gl_id,"attr_position"); p->locations.vert.attrs.uv = program_get_attrib_location(p->program.gl_id, "attr_uv"); p->locations.vert.attrs.color = program_get_attrib_location(p->program.gl_id, "attr_color"); p->locations.vert.attrs.normal = program_get_attrib_location(p->program.gl_id, "attr_normal"); RICO_ASSERT(p->locations.vert.attrs.position == LOCATION_PBR_POSITION); RICO_ASSERT(p->locations.vert.attrs.uv == LOCATION_PBR_UV); // TODO: Turn these back on when they're being used //RICO_ASSERT(p->locations.vert.attrs.color == LOCATION_PBR_COLOR); //RICO_ASSERT(p->locations.vert.attrs.normal == LOCATION_PBR_NORMAL); // Fragment shader p->locations.frag.time = program_get_uniform_location(p->program.gl_id, "time"); p->locations.frag.camera.pos = program_get_uniform_location(p->program.gl_id, "camera.P"); p->locations.frag.material.tex0 = program_get_uniform_location(p->program.gl_id, "material.tex0"); p->locations.frag.material.tex1 = program_get_uniform_location(p->program.gl_id, "material.tex1"); p->locations.frag.material.tex2 = program_get_uniform_location(p->program.gl_id, "material.tex2"); #define LIGHT(i) \ p->locations.frag.lights[i].type = \ program_get_uniform_location(p->program.gl_id, "lights["#i"].type"); \ p->locations.frag.lights[i].on = \ program_get_uniform_location(p->program.gl_id, "lights["#i"].on"); \ p->locations.frag.lights[i].pos = \ program_get_uniform_location(p->program.gl_id, "lights["#i"].pos"); \ p->locations.frag.lights[i].col = \ program_get_uniform_location(p->program.gl_id, "lights["#i"].col"); \ p->locations.frag.lights[i].intensity = \ program_get_uniform_location(p->program.gl_id, "lights["#i"].intensity"); \ p->locations.frag.lights[i].dir = \ program_get_uniform_location(p->program.gl_id, "lights["#i"].dir"); LIGHT(0); LIGHT(1); LIGHT(2); LIGHT(3); LIGHT(4); RICO_ASSERT(5 == NUM_LIGHT_DIR + NUM_LIGHT_POINT); #undef POINT_LIGHT //RICO_ASSERT(p->locations.frag.time >= 0); RICO_ASSERT(p->locations.frag.camera.pos >= 0); RICO_ASSERT(p->locations.frag.material.tex0 >= 0); RICO_ASSERT(p->locations.frag.material.tex1 >= 0); RICO_ASSERT(p->locations.frag.material.tex2 >= 0); RICO_ASSERT(p->locations.frag.lights[0].type >= 0); RICO_ASSERT(p->locations.frag.lights[0].on >= 0); //RICO_ASSERT(p->locations.frag.lights[0].col >= 0); RICO_ASSERT(p->locations.frag.lights[0].pos >= 0); //RICO_ASSERT(p->locations.frag.lights[0].intensity >= 0); RICO_ASSERT(p->locations.frag.lights[0].dir >= 0); p->locations.frag.near_far = program_get_uniform_location(p->program.gl_id, "near_far"); #define SHADOW_TEXTURE(i) \ p->locations.frag.shadow_textures[i] = \ program_get_uniform_location(p->program.gl_id, "shadow_textures["#i"]"); SHADOW_TEXTURE(0); RICO_ASSERT(1 == NUM_LIGHT_DIR); //RICO_ASSERT(p->locations.frag.shadow_textures[0] >= 0); #undef SHADOW_TEXTURE #define SHADOW_CUBEMAP(i) \ p->locations.frag.shadow_cubemaps[i] = \ program_get_uniform_location(p->program.gl_id, "shadow_cubemaps["#i"]"); SHADOW_CUBEMAP(0); SHADOW_CUBEMAP(1); SHADOW_CUBEMAP(2); SHADOW_CUBEMAP(3); RICO_ASSERT(4 == NUM_LIGHT_POINT); //RICO_ASSERT(p->locations.frag.shadow_cubemaps[0] >= 0); #undef SHADOW_CUBEMAP } static void program_pbr_attribs() { glVertexAttribPointer(LOCATION_PBR_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(struct pbr_vertex), (GLvoid *)offsetof(struct pbr_vertex, pos)); glEnableVertexAttribArray(LOCATION_PBR_POSITION); glVertexAttribPointer(LOCATION_PBR_UV, 2, GL_FLOAT, GL_FALSE, sizeof(struct pbr_vertex), (GLvoid *)offsetof(struct pbr_vertex, uv)); glEnableVertexAttribArray(LOCATION_PBR_UV); glVertexAttribPointer(LOCATION_PBR_COLOR, 3, GL_FLOAT, GL_FALSE, sizeof(struct pbr_vertex), (GLvoid *)offsetof(struct pbr_vertex, col)); glEnableVertexAttribArray(LOCATION_PBR_COLOR); glVertexAttribPointer(LOCATION_PBR_NORMAL, 4, GL_FLOAT, GL_FALSE, sizeof(struct pbr_vertex), (GLvoid *)offsetof(struct pbr_vertex, normal)); glEnableVertexAttribArray(LOCATION_PBR_NORMAL); } static int make_program_pbr(struct program_pbr **_program) { static struct program_pbr *prog = NULL; enum ric_error err; if (prog != NULL) { *_program = prog; return RIC_SUCCESS; } GLuint vshader = 0; GLuint fshader = 0; GLuint program = 0; // Compile shaders err = make_shader(GL_VERTEX_SHADER, "shader/pbr_v.glsl", &vshader); if (err) goto cleanup; err = make_shader(GL_FRAGMENT_SHADER, "shader/pbr_f.glsl", &fshader); if (err) goto cleanup; // Link shader program err = make_program(vshader, 0, fshader, &program); if (err) goto cleanup; // Create program object prog = calloc(1, sizeof(*prog)); prog->program.type = PROG_PBR; prog->program.gl_id = program; // Query shader locations program_pbr_get_locations(prog); cleanup: free_shader(fshader); free_shader(vshader); *_program = prog; return err; } static void free_program_pbr(struct program_pbr **program) { //TODO: Handle error if ((*program)->program.ref_count > 0) { printf("Cannot delete a program in use!"); //TODO: crash; } glDeleteProgram((*program)->program.gl_id); free(*program); *program = NULL; } ///============================================================================= //| Shadow texture program ///============================================================================= static void program_shadow_texture_get_locations( struct program_shadow_texture *p) { // Vertex shader p->locations.vert.light_space = program_get_uniform_location(p->program.gl_id, "light_space"); p->locations.vert.model = program_get_uniform_location(p->program.gl_id, "model"); p->locations.vert.attrs.position = program_get_attrib_location(p->program.gl_id,"attr_position"); RICO_ASSERT(p->locations.vert.light_space >= 0); RICO_ASSERT(p->locations.vert.model >= 0); RICO_ASSERT(p->locations.vert.attrs.position == LOCATION_PBR_POSITION); // Fragment shader //Empty } static void program_shadow_texture_attribs() { glVertexAttribPointer(LOCATION_SHADOW_TEXTURE_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(struct pbr_vertex), (GLvoid *)offsetof(struct pbr_vertex, pos)); glEnableVertexAttribArray(LOCATION_SHADOW_TEXTURE_POSITION); } static int make_program_shadow_texture(struct program_shadow_texture **_program) { static struct program_shadow_texture *prog = NULL; enum ric_error err; if (prog != NULL) { *_program = prog; return RIC_SUCCESS; } GLuint vshader = 0; GLuint gshader = 0; GLuint fshader = 0; GLuint program = 0; // Compile shaders err = make_shader(GL_VERTEX_SHADER, "shader/shadow_texture_v.glsl", &vshader); if (err) goto cleanup; err = make_shader(GL_FRAGMENT_SHADER, "shader/shadow_texture_f.glsl", &fshader); if (err) goto cleanup; // Link shader program err = make_program(vshader, gshader, fshader, &program); if (err) goto cleanup; // Create program object prog = calloc(1, sizeof(*prog)); prog->program.type = PROG_SHADOW_TEXTURE; prog->program.gl_id = program; // Query shader locations program_shadow_texture_get_locations(prog); cleanup: free_shader(fshader); free_shader(gshader); free_shader(vshader); *_program = prog; return err; } static void free_program_shadow_texture(struct program_shadow_texture **program) { //TODO: Handle error if ((*program)->program.ref_count > 0) { printf("Cannot delete a program in use!"); //TODO: crash; } glDeleteProgram((*program)->program.gl_id); free(*program); *program = NULL; } ///============================================================================= //| Shadow cubemap program ///============================================================================= static void program_shadow_cubemap_get_locations( struct program_shadow_cubemap *p) { // Vertex shader p->locations.vert.model = program_get_uniform_location(p->program.gl_id, "model"); p->locations.vert.attrs.position = program_get_attrib_location(p->program.gl_id,"attr_position"); RICO_ASSERT(p->locations.vert.model >= 0); RICO_ASSERT(p->locations.vert.attrs.position == LOCATION_PBR_POSITION); // Geometry shader #define CUBEMAP_XFORM(i) \ p->locations.geom.cubemap_xforms[i] = \ program_get_uniform_location(p->program.gl_id, "cubemap_xforms["#i"]"); CUBEMAP_XFORM(0); CUBEMAP_XFORM(1); CUBEMAP_XFORM(2); CUBEMAP_XFORM(3); CUBEMAP_XFORM(4); CUBEMAP_XFORM(5); #undef CUBEMAP_XFORM RICO_ASSERT(p->locations.geom.cubemap_xforms[0] >= 0); RICO_ASSERT(p->locations.geom.cubemap_xforms[1] >= 0); RICO_ASSERT(p->locations.geom.cubemap_xforms[2] >= 0); RICO_ASSERT(p->locations.geom.cubemap_xforms[3] >= 0); RICO_ASSERT(p->locations.geom.cubemap_xforms[4] >= 0); RICO_ASSERT(p->locations.geom.cubemap_xforms[5] >= 0); // Fragment shader p->locations.frag.near_far = program_get_uniform_location(p->program.gl_id, "near_far"); p->locations.frag.light_pos = program_get_uniform_location(p->program.gl_id, "light_pos"); //RICO_ASSERT(p->locations.frag.near_far >= 0); //RICO_ASSERT(p->locations.frag.light_pos >= 0); } static void program_shadow_cubemap_attribs() { glVertexAttribPointer(LOCATION_SHADOW_CUBEMAP_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(struct pbr_vertex), (GLvoid *)offsetof(struct pbr_vertex, pos)); glEnableVertexAttribArray(LOCATION_SHADOW_CUBEMAP_POSITION); } static int make_program_shadow_cubemap(struct program_shadow_cubemap **_program) { static struct program_shadow_cubemap *prog = NULL; enum ric_error err; if (prog != NULL) { *_program = prog; return RIC_SUCCESS; } GLuint vshader = 0; GLuint gshader = 0; GLuint fshader = 0; GLuint program = 0; // Compile shaders err = make_shader(GL_VERTEX_SHADER, "shader/shadow_cubemap_v.glsl", &vshader); if (err) goto cleanup; err = make_shader(GL_GEOMETRY_SHADER, "shader/shadow_cubemap_g.glsl", &gshader); if (err) goto cleanup; err = make_shader(GL_FRAGMENT_SHADER, "shader/shadow_cubemap_f.glsl", &fshader); if (err) goto cleanup; // Link shader program err = make_program(vshader, gshader, fshader, &program); if (err) goto cleanup; // Create program object prog = calloc(1, sizeof(*prog)); prog->program.type = PROG_SHADOW_CUBEMAP; prog->program.gl_id = program; // Query shader locations program_shadow_cubemap_get_locations(prog); cleanup: free_shader(fshader); free_shader(gshader); free_shader(vshader); *_program = prog; return err; } static void free_program_shadow_cubemap(struct program_shadow_cubemap **program) { //TODO: Handle error if ((*program)->program.ref_count > 0) { printf("Cannot delete a program in use!"); //TODO: crash; } glDeleteProgram((*program)->program.gl_id); free(*program); *program = NULL; } ///============================================================================= //| Primitive program ///============================================================================= static void program_primitive_get_locations(struct program_primitive *p) { // Vertex shader p->locations.vert.proj = program_get_uniform_location(p->program.gl_id, "proj"); p->locations.vert.view = program_get_uniform_location(p->program.gl_id, "view"); p->locations.vert.model = program_get_uniform_location(p->program.gl_id, "model"); RICO_ASSERT(p->locations.vert.proj >= 0); RICO_ASSERT(p->locations.vert.view >= 0); RICO_ASSERT(p->locations.vert.model >= 0); p->locations.vert.attrs.position = program_get_attrib_location(p->program.gl_id, "attr_position"); p->locations.vert.attrs.uv = program_get_attrib_location(p->program.gl_id, "attr_uv"); p->locations.vert.attrs.color = program_get_attrib_location(p->program.gl_id, "attr_color"); RICO_ASSERT(p->locations.vert.attrs.position == LOCATION_PRIM_POSITION); // TODO: Turn these back on when they're being used //RICO_ASSERT(p->locations.vert.attrs.uv == LOCATION_PRIM_UV); //RICO_ASSERT(p->locations.vert.attrs.color == LOCATION_PRIM_COLOR); // Fragment shader p->locations.frag.color = program_get_uniform_location(p->program.gl_id, "color"); p->locations.frag.tex0 = program_get_uniform_location(p->program.gl_id, "tex"); // TODO: Turn these back on when they're being used //RICO_ASSERT(p->locations.frag.color >= 0); //RICO_ASSERT(p->locations.frag.tex >= 0); } static void program_primitive_attribs() { glVertexAttribPointer(LOCATION_PRIM_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(struct prim_vertex), (GLvoid *)offsetof(struct prim_vertex, pos)); glEnableVertexAttribArray(LOCATION_PRIM_POSITION); glVertexAttribPointer(LOCATION_PRIM_UV, 2, GL_FLOAT, GL_FALSE, sizeof(struct prim_vertex), (GLvoid *)offsetof(struct prim_vertex, uv)); glEnableVertexAttribArray(LOCATION_PRIM_UV); glVertexAttribPointer(LOCATION_PRIM_COLOR, 3, GL_FLOAT, GL_FALSE, sizeof(struct prim_vertex), (GLvoid *)offsetof(struct prim_vertex, col)); glEnableVertexAttribArray(LOCATION_PRIM_COLOR); } static int make_program_primitive(struct program_primitive **_program) { static struct program_primitive *prog = NULL; enum ric_error err; if (prog != NULL) { *_program = prog; return RIC_SUCCESS; } GLuint vshader = 0; GLuint fshader = 0; GLuint program = 0; // Compile shaders err = make_shader(GL_VERTEX_SHADER, "shader/prim_v.glsl", &vshader); if (err) goto cleanup; err = make_shader(GL_FRAGMENT_SHADER, "shader/prim_f.glsl", &fshader); if (err) goto cleanup; // Link shader program err = make_program(vshader, 0, fshader, &program); if (err) goto cleanup; // Create program object prog = calloc(1, sizeof(*prog)); prog->program.type = PROG_PRIMITIVE; prog->program.gl_id = program; // Query shader locations program_primitive_get_locations(prog); cleanup: free_shader(fshader); free_shader(vshader); *_program = prog; return err; } static void free_program_primitive(struct program_primitive **program) { glDeleteProgram((*program)->program.gl_id); free(*program); *program = NULL; } ///============================================================================= //| Text program ///============================================================================= static void program_text_get_locations(struct program_text *p) { // Vertex shader p->locations.vert.model = program_get_uniform_location(p->program.gl_id, "model"); p->locations.vert.view = program_get_uniform_location(p->program.gl_id, "view"); p->locations.vert.proj = program_get_uniform_location(p->program.gl_id, "proj"); RICO_ASSERT(p->locations.vert.model >= 0); RICO_ASSERT(p->locations.vert.view >= 0); RICO_ASSERT(p->locations.vert.proj >= 0); // Fragment shader p->locations.frag.color = program_get_uniform_location(p->program.gl_id, "u_color"); p->locations.frag.grayscale = program_get_uniform_location(p->program.gl_id, "u_grayscale"); p->locations.frag.tex0 = program_get_uniform_location(p->program.gl_id, "u_tex"); //RICO_ASSERT(p->locations.frag.color >= 0); //RICO_ASSERT(p->locations.frag.grayscale >= 0); //RICO_ASSERT(p->locations.frag.tex >= 0); } static void program_text_attribs() { glVertexAttribPointer(LOCATION_TEXT_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(struct text_vertex), (GLvoid *)offsetof(struct text_vertex, pos)); glEnableVertexAttribArray(LOCATION_TEXT_POSITION); glVertexAttribPointer(LOCATION_TEXT_UV, 2, GL_FLOAT, GL_FALSE, sizeof(struct text_vertex), (GLvoid *)offsetof(struct text_vertex, uv)); glEnableVertexAttribArray(LOCATION_TEXT_UV); glVertexAttribPointer(LOCATION_TEXT_COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(struct text_vertex), (GLvoid *)offsetof(struct text_vertex, col)); glEnableVertexAttribArray(LOCATION_TEXT_COLOR); } static int make_program_text(struct program_text **_program) { static struct program_text *prog = NULL; enum ric_error err; if (prog != NULL) { *_program = prog; return RIC_SUCCESS; } GLuint vshader = 0; GLuint fshader = 0; GLuint program = 0; // Compile shaders err = make_shader(GL_VERTEX_SHADER, "shader/text_v.glsl", &vshader); if (err) goto cleanup; err = make_shader(GL_FRAGMENT_SHADER, "shader/text_f.glsl", &fshader); if (err) goto cleanup; // Link shader program err = make_program(vshader, 0, fshader, &program); if (err) goto cleanup; // Create program object prog = calloc(1, sizeof(*prog)); prog->program.type = PROG_TEXT; prog->program.gl_id = program; // Query shader locations program_text_get_locations(prog); cleanup: free_shader(fshader); free_shader(vshader); *_program = prog; return err; } static void free_program_text(struct program_text **program) { glDeleteProgram((*program)->program.gl_id); free(*program); *program = NULL; }
34.906793
80
0.622963
f61fc0fa283ffb2087e2d2c3c28bc5e5a9a524c4
269
h
C
Shape Class/libraries.h
tj-dunham/CS1C_Project
2c8f329a67a142c2ee2f7426047f0c3f51656169
[ "MIT" ]
1
2021-09-22T20:38:14.000Z
2021-09-22T20:38:14.000Z
Shape Class/libraries.h
korieliaz/2D-Graphics-Modeler
2c8f329a67a142c2ee2f7426047f0c3f51656169
[ "MIT" ]
null
null
null
Shape Class/libraries.h
korieliaz/2D-Graphics-Modeler
2c8f329a67a142c2ee2f7426047f0c3f51656169
[ "MIT" ]
null
null
null
#ifndef LIBRARIES_H #define LIBRARIES_H #include <iostream> #include <string> #include <algorithm> #include <exception> #include <fstream> #include <limits> #include <ios> #include <math.h> #include <QPainter> #include "vector.h" #endif // LIBRARIES_H
16.8125
22
0.698885
86544dbb822d04f1d8029c42b9945c29ecfea322
8,782
h
C
include/layer/quad.h
wjakob/layerlab
3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3
[ "BSD-2-Clause" ]
89
2015-07-31T05:20:17.000Z
2022-02-05T13:21:33.000Z
include/layer/quad.h
wjakob/layerlab
3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3
[ "BSD-2-Clause" ]
2
2015-08-17T20:50:32.000Z
2019-10-07T11:27:04.000Z
include/layer/quad.h
wjakob/layerlab
3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3
[ "BSD-2-Clause" ]
23
2015-08-03T01:09:55.000Z
2021-12-25T15:45:42.000Z
/* quad.h -- Functions for numerical quadrature Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include <layer/math.h> #include <cassert> #include <stdexcept> #include <iostream> NAMESPACE_BEGIN(layer) NAMESPACE_BEGIN(quad) /** * \brief Computes the nodes and weights of a Gauss-Legendre quadrature * (aka "Gaussian quadrature") rule with the given number of evaluations. * * Integration is over the interval \f$[-1, 1]\f$. Gauss-Legendre quadrature * maximizes the order of exactly integrable polynomials achieves this up to * degree \f$2n-1\f$ (where \f$n\f$ is the number of function evaluations). * * This method is numerically well-behaved until about \f$n=200\f$ * and then becomes progressively less accurate. It is generally not a * good idea to go much higher---in any case, a composite or * adaptive integration scheme will be superior for large \f$n\f$. * * \param n * Desired number of evalution points * \param[out] nodes * Length-\c n array used to store the nodes of the quadrature rule * \param[out] nodes * Length-\c n array used to store the weights of the quadrature rule * \remark * In the Python API, the \c nodes and \c weights field are returned * as a tuple */ template <typename Scalar> void gaussLegendre(int n, Scalar *nodes, Scalar *weights) { if (n-- < 1) throw std::runtime_error("gaussLegendre(): n must be >= 1"); if (n == 0) { nodes[0] = 0; weights[0] = 2; } else if (n == 1) { nodes[0] = (Scalar) -std::sqrt(1.0 / 3.0); nodes[1] = -nodes[0]; weights[0] = weights[1] = 1; } int m = (n+1)/2; for (int i=0; i<m; ++i) { /* Initial guess for this root using that of a Chebyshev polynomial */ double x = -std::cos((double) (2*i + 1) / (double) (2*n + 2) * math::Pi_d); int it = 0; while (true) { if (++it > 20) throw std::runtime_error( "gaussLobatto(" + std::to_string(n) + "): did not converge after 20 iterations!"); /* Search for the interior roots of P_{n+1}(x) using Newton's method. */ std::pair<double, double> L = math::legendre_pd(n+1, x); double step = L.first / L.second; x -= step; if (std::abs(step) <= 4 * std::abs(x) * std::numeric_limits<double>::epsilon()) break; } std::pair<double, double> L = math::legendre_pd(n+1, x); weights[i] = weights[n - i] = (Scalar)(2 / ((1 - x * x) * (L.second * L.second))); nodes[i] = (Scalar) x; nodes[n - i] = (Scalar) -x; assert(i == 0 || x > nodes[i-1]); } if ((n % 2) == 0) { std::pair<double, double> L = math::legendre_pd(n+1, 0.0); weights[n/2] = (double) (2 / (L.second*L.second)); nodes[n/2] = 0; } } /** * \brief Computes the nodes and weights of a Gauss-Lobatto quadrature * rule with the given number of evaluations. * * Integration is over the interval \f$[-1, 1]\f$. Gauss-Lobatto quadrature * is preferable to Gauss-Legendre quadrature whenever the endpoints of the * integration domain should explicitly be included. It maximizes the order * of exactly integrable polynomials subject to this constraint and achieves * this up to degree \f$2n-3\f$ (where \f$n\f$ is the number of function * evaluations). * * This method is numerically well-behaved until about \f$n=200\f$ * and then becomes progressively less accurate. It is generally not a * good idea to go much higher---in any case, a composite or * adaptive integration scheme will be superior for large \f$n\f$. * * \param n * Desired number of evalution points * \param[out] nodes * Length-\c n array used to store the nodes of the quadrature rule * \param[out] nodes * Length-\c n array used to store the weights of the quadrature rule * \remark * In the Python API, the \c nodes and \c weights field are returned * as a tuple */ template <typename Scalar> void gaussLobatto(int n, Scalar *nodes, Scalar *weights) { if (n-- < 2) throw std::runtime_error("gaussLobatto(): n must be >= 1"); nodes[0] = -1; nodes[n] = 1; weights[0] = weights[n] = 2 / (Scalar) (n * (n+1)); int m = (n+1)/2; for (int i=1; i<m; ++i) { /* Initial guess for this root -- see "On the Legendre-Gauss-Lobatto Points and Weights" by Seymor V. Parter, Journal of Sci. Comp., Vol. 14, 4, 1999 */ double x = -std::cos((i + 0.25) * math::Pi_d / n - 3/(8*n*math::Pi_d * (i + 0.25))); int it = 0; while (true) { if (++it > 20) throw std::runtime_error( "gaussLobatto(" + std::to_string(n) + "): did not converge after 20 iterations!"); /* Search for the interior roots of P_n'(x) using Newton's method. The same roots are also shared by P_{n+1}-P_{n-1}, which is nicer to evaluate. */ std::pair<double, double> Q = math::legendre_pd_diff(n, x); double step = Q.first / Q.second; x -= step; if (std::abs(step) <= 4 * std::abs(x) * std::numeric_limits<double>::epsilon()) break; } double Ln = math::legendre_p(n, x); weights[i] = weights[n - i] = (Scalar) (2 / ((n * (n + 1)) * Ln * Ln)); nodes[i] = (Scalar) x; nodes[n - i] = (Scalar) -x; assert(x > nodes[i-1]); } if ((n % 2) == 0) { double Ln = math::legendre_p(n, 0.0); weights[n / 2] = (Scalar) (2 / ((n * (n + 1)) * Ln * Ln)); nodes[n/2] = 0; } } /** * \brief Computes the nodes and weights of a composite Simpson quadrature * rule with the given number of evaluations. * * Integration is over the interval \f$[-1, 1]\f$, which will be split into * \f$(n-1) / 2\f$ sub-intervals with overlapping endpoints. A 3-point * Simpson rule is applied per interval, which is exact for polynomials of * degree three or less. * * \param n * Desired number of evalution points. Must be an odd number bigger than 3. * \param[out] nodes * Length-\c n array used to store the nodes of the quadrature rule * \param[out] nodes * Length-\c n array used to store the weights of the quadrature rule * \remark * In the Python API, the \c nodes and \c weights field are returned * as a tuple */ template <typename Scalar> void compositeSimpson(int n, Scalar *nodes, Scalar *weights) { if (n % 2 != 1 || n < 3) throw std::runtime_error("compositeSimpson(): n must be >= 3 and odd"); n = (n - 1) / 2; Scalar h = (Scalar) 2 / (Scalar) (2 * n), weight = h * (Scalar) (1.0 / 3.0); for (int i = 0; i < n; ++i) { Float x = -1 + h * (2*i); nodes[2*i] = x; nodes[2*i+1] = x+h; weights[2*i] = (i == 0 ? 1 : 2) * weight; weights[2*i+1] = 4 * weight; } nodes[2*n] = 1; weights[2*n] = weight; } /** * \brief Computes the nodes and weights of a composite Simpson 3/8 quadrature * rule with the given number of evaluations. * * Integration is over the interval \f$[-1, 1]\f$, which will be split into * \f$(n-1) / 3\f$ sub-intervals with overlapping endpoints. A 4-point * Simpson rule is applied per interval, which is exact for polynomials of * degree four or less. * * \param n * Desired number of evalution points. Must be an odd number bigger than 3. * \param[out] nodes * Length-\c n array used to store the nodes of the quadrature rule * \param[out] nodes * Length-\c n array used to store the weights of the quadrature rule * \remark * In the Python API, the \c nodes and \c weights field are returned * as a tuple */ template <typename Scalar> void compositeSimpson38(int n, Scalar *nodes, Scalar *weights) { if ((n-1) % 3 != 0 || n < 4) throw std::runtime_error("compositeSimpson38(): n-1 must be divisible by 3"); n = (n - 1) / 3; Scalar h = (Scalar) 2 / (Scalar) (3 * n), weight = h * (Scalar) (3.0 / 8.0); for (int i = 0; i < n; ++i) { Float x = -1 + h * (3*i); nodes[3*i] = x; nodes[3*i+1] = x+h; nodes[3*i+2] = x+2*h; weights[3*i] = (i == 0 ? 1 : 2) * weight; weights[3*i+1] = 3 * weight; weights[3*i+2] = 3 * weight; } nodes[3*n] = 1; weights[3*n] = weight; } //! @} // ----------------------------------------------------------------------- NAMESPACE_END(quad) NAMESPACE_END(layer)
34.171206
92
0.576748
e5520114670bf1fa69cbe6976cfc353fae3eab56
4,274
h
C
dev/Code/CryEngine/CryCommon/stridedptr.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/CryEngine/CryCommon/stridedptr.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/CryEngine/CryCommon/stridedptr.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRYCOMMON_STRIDEDPTR_H #define CRYINCLUDE_CRYCOMMON_STRIDEDPTR_H #pragma once template<class dtype> class strided_pointer { public: strided_pointer() : data(0) , iStride(sizeof(dtype)) { } strided_pointer(dtype* pdata, int32 stride = sizeof(dtype)) : data(pdata) , iStride(stride) { } template<typename dtype1> strided_pointer(dtype1* pdata) { set(pdata, sizeof(dtype1)); } template<typename dtype1> strided_pointer(const strided_pointer<dtype1>& src) { set(src.data, src.iStride); } template<typename dtype1> ILINE strided_pointer& operator=(const strided_pointer<dtype1>& src) { set(src.data, src.iStride); return *this; } ILINE dtype& operator[](int32 idx) { return *(dtype*)((char*)data + idx * iStride); } ILINE const dtype& operator[](int32 idx) const { return *(const dtype*)((const char*)data + idx * iStride); } ILINE strided_pointer<dtype> operator+(int32 idx) const { return strided_pointer<dtype>((dtype*)((char*)data + idx * iStride), iStride); } ILINE strided_pointer<dtype> operator-(int32 idx) const { return strided_pointer<dtype>((dtype*)((char*)data - idx * iStride), iStride); } ILINE operator bool() const { return data != 0; } private: template<typename dtype1> ILINE void set(dtype1* pdata, int32 stride) { # if !defined(eLittleEndian) # error eLittleEndian is not defined, please include CryEndian.h. # endif COMPILE_TIME_ASSERT(metautils::is_const<dtype>::value || !metautils::is_const<dtype1>::value); // note: we allow xint32 -> xint16 converting COMPILE_TIME_ASSERT( (metautils::is_same<typename metautils::remove_const<dtype1>::type, typename metautils::remove_const<dtype>::type>::value || ((metautils::is_same<typename metautils::remove_const<dtype1>::type, sint32>::value || metautils::is_same<typename metautils::remove_const<dtype1>::type, uint32>::value || metautils::is_same<typename metautils::remove_const<dtype1>::type, sint16>::value || metautils::is_same<typename metautils::remove_const<dtype1>::type, uint16>::value) && (metautils::is_same<typename metautils::remove_const<dtype>::type, sint16>::value || metautils::is_same<typename metautils::remove_const<dtype>::type, uint16>::value)))); data = (dtype*)pdata + (sizeof(dtype1) / sizeof(dtype) - 1) * (int)eLittleEndian; iStride = stride; } private: // Prevents assignment of a structure member's address by mistake: // stridedPtrObject = &myStruct.member; // Use explicit constructor instead: // stridedPtrObject = strided_pointer<baseType>(&myStruct.member, sizeof(myStruct)); // // Keep it private and non-implemented. strided_pointer& operator=(dtype* pdata); // Prevents using the address directly by mistake: // memcpy(destination, stridedPtrObject, sizeof(baseType) * n); // Use address of the first element instead: // memcpy(destination, &stridedPtrObject[0], stridedPtrObject.iStride * n); // // Keep it private and non-implemented. operator void*() const; // Prevents direct dereferencing to avoid confusing it with "normal" pointers: // val = *stridedPtrObject; // Use operator [] instead: // val = stridedPtrObject[0]; // // Keep it private and non-implemented. dtype& operator*() const; public: dtype* data; int32 iStride; }; #endif // CRYINCLUDE_CRYCOMMON_STRIDEDPTR_H
36.220339
142
0.670566
c226dde522a4c9eeb2f22c5383a75982a3d26a08
573
h
C
engine/core/io/stream/FileHandleDataStream.h
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
675
2019-02-07T01:23:19.000Z
2022-03-28T05:45:10.000Z
engine/core/io/stream/FileHandleDataStream.h
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
843
2019-01-25T01:06:46.000Z
2022-03-16T11:15:53.000Z
engine/core/io/stream/FileHandleDataStream.h
Houkime/echo
d115ca55faf3a140bea04feffeb2efdedb0e7f82
[ "MIT" ]
83
2019-02-20T06:18:46.000Z
2022-03-20T09:36:09.000Z
#pragma once #include "DataStream.h" namespace Echo { class FileHandleDataStream : public DataStream { public: FileHandleDataStream(const String& name, ui32 accessMode = READ); ~FileHandleDataStream(); size_t read(void* buf, size_t count); size_t write(const void* buf, size_t count); void skip(long count); void seek(size_t pos, int origin = SEEK_SET); size_t tell(void) const; bool eof(void) const; void close(void); // is fail bool fail() { return m_fileHandle ? false : true; } protected: FILE* m_fileHandle; }; }
16.852941
67
0.677138
614400f015dd2a80ca9cfa34f0ed4d5ce4098a2e
2,785
h
C
src/base/text/InlineText.h
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
25
2016-05-27T11:53:58.000Z
2021-10-17T00:13:41.000Z
src/base/text/InlineText.h
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
1
2016-07-09T05:25:03.000Z
2016-07-09T05:25:03.000Z
src/base/text/InlineText.h
jumptohistory/jaymod
92d0a0334ac27da94b12280b0b42b615b8813c23
[ "Apache-2.0" ]
16
2016-05-28T23:06:50.000Z
2022-01-26T13:47:12.000Z
#ifndef BASE_TEXT_INLINETEXT_H #define BASE_TEXT_INLINETEXT_H /////////////////////////////////////////////////////////////////////////////// class InlineText { private: void compute( const string& ); ostringstream _oss; string _value; public: InlineText ( ); InlineText ( const InlineText& ); InlineText ( const ColorManipulator& ); InlineText ( bool ); InlineText ( float ); InlineText ( double ); InlineText ( int8 ); InlineText ( int16 ); InlineText ( int32 ); InlineText ( int64 ); InlineText ( uint8 ); InlineText ( uint16 ); InlineText ( uint32 ); InlineText ( uint64 ); InlineText ( const void* ); InlineText ( const char* ); InlineText ( const string& ); #if defined( JAYMOD_OSX ) InlineText ( size_t ); #endif // JAYMOD_OSX ~InlineText ( ); InlineText& operator=( const InlineText& ); InlineText& operator() ( bool ); InlineText& operator() ( float ); InlineText& operator() ( double ); InlineText& operator() ( int8 ); InlineText& operator() ( int16 ); InlineText& operator() ( int32 ); InlineText& operator() ( int64 ); InlineText& operator() ( uint8 ); InlineText& operator() ( uint16 ); InlineText& operator() ( uint32 ); InlineText& operator() ( uint64 ); InlineText& operator() ( const void* ); InlineText& operator() ( const char* ); InlineText& operator() ( const string& ); #if defined( JAYMOD_OSX ) InlineText& operator() ( size_t ); #endif // JAYMOD_OSX ColorManipulator color; ios::fmtflags flags; streamsize precision; streamsize width; string prefix; string prefixOutside; string suffix; string suffixOutside; const string& value; }; /////////////////////////////////////////////////////////////////////////////// class InlineVec3 : public InlineText { public: InlineVec3 ( ); InlineVec3 ( const InlineVec3& ); InlineVec3 ( const float* ); ~InlineVec3(); InlineVec3& operator()( const float* ); }; /////////////////////////////////////////////////////////////////////////////// extern InlineText xnone; extern InlineText xnormal; extern InlineText xbold; extern InlineText xdim; extern InlineText xpass; extern InlineText xfail; extern InlineText xwarning; extern InlineText xdebug; extern InlineText xdebugBOLD; extern InlineText xdebugDIM; extern InlineText xheader; extern InlineText xheaderBOLD; extern InlineText xheaderDIM; extern InlineText xvalue; extern InlineText xvalueBOLD; extern InlineText xvalueDIM; extern InlineVec3 xvec3; /////////////////////////////////////////////////////////////////////////////// #endif // BASE_TEXT_INLINETEXT_H
26.028037
79
0.580251
e8f5197c0cb587b478554d51da9eafde08ef4db9
10,162
c
C
tests/e2e/test-regressions.c
freewilll/wcc
532856ab8b03be89dd0d6457a7ed9626882c3f51
[ "MIT" ]
4
2021-04-05T08:21:10.000Z
2021-12-14T17:45:22.000Z
tests/e2e/test-regressions.c
freewilll/wcc
532856ab8b03be89dd0d6457a7ed9626882c3f51
[ "MIT" ]
null
null
null
tests/e2e/test-regressions.c
freewilll/wcc
532856ab8b03be89dd0d6457a7ed9626882c3f51
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include "../test-lib.h" int check_stack_alignment(); int verbose; int passes; int failures; struct csrs { int i; }; struct ups { int i, j; }; // Create an expression which undoubtedly will exhaust all registers, forcing // the spilling code into action void test_spilling_stress() { int i; i = 1; i = (i + 2) * (i + (i + 2) * (i + (i + 2) * (i + i + (i + 2) * (i + 3)))); assert_int(390, i, "spilling stress"); } int csr() { return 2; } // This test is a bit fragile. It does the job right now, but register // candidates will likely change. Currently, foo() uses rbx, which is also // used to store the lvalue for s->i. If rbx wasn't preserved, this code // would segfault. void test_callee_saved_registers() { struct csrs *s; s = malloc(sizeof(struct csrs)); s->i = csr(); assert_int(2, s->i, "callee saved registers"); } int set_rax(int i) { return i; } // Variadic functions have the number of floating point arguments passed in al. // Since floating point numbers isn't implemented, this should be set to zero. // A bug was present where this wasn't being set in sprintf. This code below // would segfault at the second sprintf. void test_variadic_arg_bug() { char *s; s = malloc(10); set_rax(0); sprintf(s, "1\n"); set_rax(1); sprintf(s, "2\n"); } void test_backwards_jumps() { int i, j, k; int *r; r = malloc(sizeof(int) * 3); i = 0; j = 0; for (i = 0; i < 3; i++) { j += 10; r[i] = j; k = j + 1; // Trigger register reuse in the buggy case } assert_int(10, r[0], "backwards jumps liveness 1"); assert_int(20, r[1], "backwards jumps liveness 2"); assert_int(30, r[2], "backwards jumps liveness 3"); } void test_first_declaration_in_if_in_for_liveness() { int i, j, k, l; i = 0; for (i = 0; i < 3; i++) { if (i == 0) j = 1; else k = j * 2; l = l + (l + (l + (l + (l + (l + (l + (l + (l + (l + (l + (l + (l + 1)))))))))))); } assert_int(2, k, "liveness extension for conditional declaration inside loop"); } void test_spilling_locals_to_stack_bug() { int i, j, k; int r1, r2, r3, r4, r5, r6, r7, r8, r9, r10; int q1, q2, q3, q4, q5, q6, q7, q8, q9, q10; r1 = r2 = r3 = r4 = r5 = r6 = r7 = r8 = r9 = r10 = 1; assert_int(1, r1, "Local stack spilling clobber bug 1"); assert_int(1, r2, "Local stack spilling clobber bug 2"); assert_int(1, r3, "Local stack spilling clobber bug 3"); assert_int(1, r4, "Local stack spilling clobber bug 4"); assert_int(1, r5, "Local stack spilling clobber bug 5"); assert_int(1, r6, "Local stack spilling clobber bug 6"); assert_int(1, r7, "Local stack spilling clobber bug 7"); assert_int(1, r8, "Local stack spilling clobber bug 8"); assert_int(1, r9, "Local stack spilling clobber bug 9"); assert_int(1, r10, "Local stack spilling clobber bug 10"); r10++; // This forces a spill of r10 } int sa0() { assert_int(0, check_stack_alignment(), "SA 0"); } int sa1(int i1) { assert_int(0, check_stack_alignment(), "SA 1"); } int sa2(int i1, int i2) { assert_int(0, check_stack_alignment(), "SA 2"); } int sa3(int i1, int i2, int i3) { assert_int(0, check_stack_alignment(), "SA 3"); } int sa4(int i1, int i2, int i3, int i4) { assert_int(0, check_stack_alignment(), "SA 4"); } int sa5(int i1, int i2, int i3, int i4, int i5) { assert_int(0, check_stack_alignment(), "SA 5"); } int sa6(int i1, int i2, int i3, int i4, int i5, int i6) { assert_int(0, check_stack_alignment(), "SA 6"); } int sa7(int i1, int i2, int i3, int i4, int i5, int i6, int i7) { assert_int(0, check_stack_alignment(), "SA 7"); } int sa8(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) { assert_int(0, check_stack_alignment(), "SA 8"); } int test_function_call_stack_alignment() { sa0(); sa1(1); sa2(1, 1); sa3(1, 1, 1); sa4(1, 1, 1, 1); sa4(1, 1, 1, 1); sa5(1, 1, 1, 1, 1); sa6(1, 1, 1, 1, 1, 1); sa7(1, 1, 1, 1, 1, 1, 1); sa8(1, 1, 1, 1, 1, 1, 1, 1); } void test_local_var_stack_alignment0() { assert_int(0, check_stack_alignment(), "Stack alignment 0"); } void test_local_var_stack_alignment1() { int i; assert_int(0, check_stack_alignment(), "Stack alignment 1"); } void test_local_var_stack_alignment2() { int i, j; assert_int(0, check_stack_alignment(), "Stack alignment 2"); } void test_local_var_stack_alignment() { test_local_var_stack_alignment0(); test_local_var_stack_alignment1(); test_local_var_stack_alignment2(); } void rssa1(int nt) { char *buf; buf = malloc(6); if (nt == 100) return; wasprintf(&buf, "nt%03d", nt); assert_string("nt001", buf, "Return statement stack alignment 1"); } void rssa2(int nt) { char *buf; buf = malloc(6); if (nt == 100) return; if (nt == 101) return; wasprintf(&buf, "nt%03d", nt); assert_string("nt001", buf, "Return statement stack alignment 1"); } void test_return_statement_stack_alignment() { // Test but where return statements would lead to an invalid push count rssa1(1); rssa2(1); } void test_ssa_label_merge_bug() { int i; if (0) i = 1; else if (1) i = 2; else if (0) i = 3; assert_int(2, i, "Label merge bug in three level if/else"); } void tsmab(int *i) {} void test_ssa_memory_alocation_bug() { int a, b; int i; i = 0; tsmab(&i); } int test_ssa_continue_with_statements_afterwards() { // A silly example, but a bug was leading to incorrect liveness, leading to // in correct register allocations. int i; i = 0; while (i++ < 3) { continue; i = 1; } } int test_ssa_break_with_statements_afterwards() { // A silly example, but a bug was leading to incorrect liveness, leading to // in correct register allocations. int i; i = 0; while (i++ < 3) { continue; i = 1; } } void test_ssa_arithmetic_optimizations() { int i; i = 10; assert_int( 0, i * 0, "Arithetic optimization i * 0"); assert_int(10, i * 1, "Arithetic optimization i * 1"); assert_int(20, i * 2, "Arithetic optimization i * 2"); assert_int(30, i * 3, "Arithetic optimization i * 3"); assert_int(40, i * 4, "Arithetic optimization i * 4"); assert_int(50, i * 5, "Arithetic optimization i * 5"); assert_int(60, i * 6, "Arithetic optimization i * 6"); assert_int(70, i * 7, "Arithetic optimization i * 7"); assert_int(80, i * 8, "Arithetic optimization i * 8"); } void test_bad_or_and_stack_consumption() { long ip; ip = 0; while ((1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1 || 1) && ip < 2) { ip += 1; } } void test_double_deref_assign_with_cast() { // This test is a bit bonkers. // stack contains longs, but they are really pointers to longs. long i, a, *sp, *stack; stack = malloc(32); sp = stack; i = 10; a = 20; // Assign a pointer to a long (i) to sp *sp = &i; // With explicit parentheses: // (*((long *) *sp))++ = a; // // 1. Dereference sp (which is a long, but is equal to &i) // 2. Cast it to a pointer to long (long *) // 3. Assign to the long*, which is &i, thus modifying the value of i // 4. Increment sp *(long *) *sp++ = a; assert_int(20, i, "double deref assign with a cast"); } char *ffrptcicj() { return (char *) 256; } void test_function_returning_pointer_to_char_in_conditional_jump() { char *c; int r; c = ffrptcicj(); r = c ? 1 : 0; assert_int(1, r, "Comparison with *char from function call in conditional jump"); } void test_unary_precedence() { struct ups *s; s = malloc(sizeof(struct ups)); s->i = 0; assert_int( 1, !s[0].i, "unary precedence !"); assert_int(-1, ~s[0].i, "unary precedence ~"); assert_int( 0, -s[0].i, "unary precedence -"); assert_int( 4, (long) &s[0].j - (long) &s[0], "unary precedence"); } void trr(int i) { i--; assert_int(1, i, "Register reuse in inc + function calls"); assert_int(1, i, "Register reuse in inc + function calls"); } void test_register_reuse_in_function_calls() { trr(2); } struct sl { int i; long a[1]; }; // This is a rather fragile test that ensures an offset isn't added twice; once by // the parser and another time by spill code. void _test_double_offset_bug(struct sl *psl) { assert_long(42, psl->a[0], "foo"); assert_long(42, psl->a[0], "foo"); int i, j, k, l, m, n, o, p, q, r, s; int z = i + j + k + l + m + n + o + p + q + r + s; } int test_double_offset_bug() { struct sl *sl = malloc(sizeof(struct sl)); sl->a[0] = 42; _test_double_offset_bug(sl); } int main(int argc, char **argv) { passes = 0; failures = 0; parse_args(argc, argv, &verbose); test_spilling_stress(); test_callee_saved_registers(); test_variadic_arg_bug(); test_backwards_jumps(); test_first_declaration_in_if_in_for_liveness(); test_spilling_locals_to_stack_bug(); test_local_var_stack_alignment(); test_function_call_stack_alignment(); test_return_statement_stack_alignment(); test_ssa_label_merge_bug(); test_ssa_memory_alocation_bug(); test_ssa_continue_with_statements_afterwards(); test_ssa_break_with_statements_afterwards(); test_ssa_arithmetic_optimizations(); test_bad_or_and_stack_consumption(); test_double_deref_assign_with_cast(); test_function_returning_pointer_to_char_in_conditional_jump(); test_unary_precedence(); test_register_reuse_in_function_calls(); test_double_offset_bug(); finalize(); }
28.706215
123
0.597619
b2da50e9a8d15b4004721dbb9c92f1c0e4774a5c
1,013
h
C
Example/iOSAppFramework/FMDB/TestRow.h
ItghostFan/iOSAppFramework
c8e253fece8f83e5860adb2fd4831d7122ab3012
[ "MIT" ]
1
2018-04-23T10:38:51.000Z
2018-04-23T10:38:51.000Z
Example/iOSAppFramework/FMDB/TestRow.h
ItghostFan/iOSAppFramework
c8e253fece8f83e5860adb2fd4831d7122ab3012
[ "MIT" ]
null
null
null
Example/iOSAppFramework/FMDB/TestRow.h
ItghostFan/iOSAppFramework
c8e253fece8f83e5860adb2fd4831d7122ab3012
[ "MIT" ]
null
null
null
// // TestRow.h // iOSAppFramework // // Created by FanChunxing on 2017/7/5. // Copyright © 2017年 ItghostFan. All rights reserved. // #import "iOSAppFramework/FMDBRow.h" @interface TestRow : FMDBRow @property (strong, nonatomic) NSString<FMDB_COLUMN(String)> *name; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(Double)> *columnDouble; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(Bool)> *columnBool; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(UInt8)> *columnUInt8; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(UInt16)> *columnUInt16; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(UInt32)> *columnUInt32; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(UInt64)> *columnUInt64; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(Int8)> *columnInt8; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(Int16)> *columnInt16; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(Int32)> *columnInt32; @property (strong, nonatomic) NSNumber<FMDB_COLUMN(Int64)> *columnInt64; @end
38.961538
74
0.772952
6f06bf93ac9d592d7505c22887c6737572c1ba81
790
h
C
System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PLResourceDataStoreKey.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PLResourceDataStoreKey.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PLResourceDataStoreKey.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:35:59 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @protocol PLResourceDataStoreKey <PLValidatesResourceModel,NSObject> @required -(id)fileURLForAssetID:(id)arg1; -(id)uniformTypeIdentifier; -(id)keyData; -(BOOL)isEqualToKey:(id)arg1; -(id)initWithKeyStruct:(const void*)arg1; -(id)descriptionForAssetID:(id)arg1; @end
37.619048
130
0.646835
194006c9ccd97b0d767b30db2df2e2a737e2ca8c
6,182
h
C
examples/vision_graph/networking_api/hcsim/hcsim_contexts.h
zoranzhao/NoSDSE
0e3148572e7cdf3a2d012c95c81863864da236d6
[ "MIT" ]
3
2019-01-26T20:35:47.000Z
2019-07-18T22:09:22.000Z
examples/vision_graph/networking_api/hcsim/hcsim_contexts.h
zoranzhao/NoSSim
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
[ "BSD-3-Clause" ]
null
null
null
examples/vision_graph/networking_api/hcsim/hcsim_contexts.h
zoranzhao/NoSSim
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
[ "BSD-3-Clause" ]
3
2017-09-08T22:13:28.000Z
2019-06-29T21:42:53.000Z
#ifndef HCSIM_CONTEXTS_H #define HCSIM_CONTEXTS_H #include <systemc> #include "HCSim.h" #include <cstdint> #include <string> #include <unordered_map> #define MAX_CORE_NUM 2 class sys_call_recv_if: virtual public sc_core::sc_interface{ public: virtual int get_node(int os_task_id) = 0; virtual int get_weight(int os_task_id) = 0; virtual int get_size(int os_task_id) = 0; virtual bool get_data(unsigned size, char* data, int os_task_id) = 0; }; class sys_call_send_if: virtual public sc_core::sc_interface{ public: virtual void set_node(int NodeID, int os_task_id) = 0; virtual void set_weight(int weight, int os_task_id) = 0; virtual void set_size(int size, int os_task_id) = 0; virtual void set_data(unsigned size, char* data, int os_task_id) = 0; }; class sys_call_recv_driver :public sc_core::sc_module ,virtual public sys_call_recv_if { public: /*--------------------------------------------------------- OS/HAL interface ----------------------------------------------------------*/ sc_core::sc_port< HCSim::IAmbaAhbBusMasterMacLink > mac_link_port; sc_core::sc_port< HCSim::receive_os_if > intr_ch; sys_call_recv_driver(const sc_core::sc_module_name name, unsigned long long addr) :sc_core::sc_module(name) { this->address = addr; } ~sys_call_recv_driver() { } virtual int get_node(int os_task_id){ int tmp; mac_link_port->masterRead(address+2, &tmp, sizeof(int)); return tmp; } virtual int get_weight(int os_task_id){ int tmp; intr_ch->receive(os_task_id); mac_link_port->masterRead(address+1, &tmp, sizeof(int)); return tmp; } virtual int get_size(int os_task_id){ int tmp; intr_ch->receive(os_task_id); mac_link_port->masterRead(address+1, &tmp, sizeof(int)); return tmp; } virtual bool get_data(unsigned size, char* data, int os_task_id){ intr_ch->receive(os_task_id); mac_link_port->masterRead(address+1, data, size*sizeof(char)); return true; } private: unsigned long long address; }; class sys_call_send_driver :public sc_core::sc_module ,virtual public sys_call_send_if { public: /*--------------------------------------------------------- OS/HAL interface ----------------------------------------------------------*/ sc_core::sc_port< HCSim::IAmbaAhbBusMasterMacLink > mac_link_port; sc_core::sc_port< HCSim::receive_os_if > intr_ch; sys_call_send_driver(const sc_core::sc_module_name name, unsigned long long addr) :sc_core::sc_module(name) { this->address = addr; } ~sys_call_send_driver() { } virtual void set_node(int NodeID, int os_task_id){ mac_link_port->masterWrite(address, &NodeID, sizeof(int)); } virtual void set_weight(int weight, int os_task_id){ mac_link_port->masterWrite(address, &weight, sizeof(int)); } virtual void set_size(int size, int os_task_id){ mac_link_port->masterWrite(address, &size, sizeof(int)); } virtual void set_data(unsigned size, char* data, int os_task_id){ mac_link_port->masterWrite(address, data, size*sizeof(char)); } private: unsigned long long address; }; class os_model_context{ public: int node_id; sc_core::sc_port<sys_call_recv_if> recv_port[MAX_CORE_NUM]; sc_core::sc_port<sys_call_send_if> send_port[MAX_CORE_NUM]; sc_core::sc_port< HCSim::OSAPI > os_port; int device_type; int core_num; os_model_context(){ } os_model_context(int node_id, sc_core::sc_vector< sc_core::sc_port< sys_call_recv_if > >& recv_port, sc_core::sc_vector< sc_core::sc_port< sys_call_send_if > >& send_port, sc_core::sc_port< HCSim::OSAPI >& os_port){ core_num = 2; device_type = 0; this->node_id = node_id; this->os_port(os_port); for(int i = 0; i < core_num; i++){ this->recv_port[i](recv_port[i]); this->send_port[i](send_port[i]); } } ~os_model_context(){} }; /*We also need a application context in order to capture app/lib-specific context data*/ class app_context{ /*TODO, probably we need use class derivation instead of void pointer to implement the polymorphism*/ std::unordered_map<std::string, void*> ctxt_list; public: /*For example, here we can have global data defined to hold application states*/ void add_context(std::string ctxt_name, void* ctxt){ ctxt_list[ctxt_name] = ctxt; } void* get_context(std::string ctxt_name){ return ctxt_list[ctxt_name]; } }; typedef struct sc_process_handler_context{ os_model_context* os_ctxt; app_context* app_ctxt; int task_id; } handler_context; class simulation_context{ std::vector< sc_core::sc_process_handle> handler_list; std::vector<handler_context> handler_context_list; public: simulation_context(){ std::cout << "Construct a new simulation context" << std::endl; } void register_task(os_model_context* os_ctxt, app_context* app_ctxt, int task_id, sc_core::sc_process_handle handler){ handler_context ctxt; ctxt.os_ctxt = os_ctxt; ctxt.app_ctxt = app_ctxt; ctxt.task_id = task_id; handler_list.push_back(handler); handler_context_list.push_back(ctxt); } handler_context get_handler_context(sc_core::sc_process_handle handler){ auto key = handler_list.begin(); auto item = handler_context_list.begin(); for(; key!=handler_list.end() && item!= handler_context_list.end(); key++, item++){ if(*key == handler) break; } return *item; } os_model_context* get_os_ctxt(sc_core::sc_process_handle handler){ handler_context ctxt = get_handler_context(handler); return ctxt.os_ctxt; } app_context* get_app_ctxt(sc_core::sc_process_handle handler){ handler_context ctxt = get_handler_context(handler); return ctxt.app_ctxt; } int get_task_id(sc_core::sc_process_handle handler){ handler_context ctxt = get_handler_context(handler); return ctxt.task_id; } }; extern simulation_context sim_ctxt; #endif
29.438095
121
0.66451
e5d98ae9bc8f69c069b9cdcf9bd16a53c4ab8a79
4,768
h
C
include/css/wifi_logo_gz.h
thorsten-l/ESP8266-WiFi-Socket-3
b40bcd1005a3f972a8fbec1a2949f5239fd6bc19
[ "Apache-2.0" ]
null
null
null
include/css/wifi_logo_gz.h
thorsten-l/ESP8266-WiFi-Socket-3
b40bcd1005a3f972a8fbec1a2949f5239fd6bc19
[ "Apache-2.0" ]
null
null
null
include/css/wifi_logo_gz.h
thorsten-l/ESP8266-WiFi-Socket-3
b40bcd1005a3f972a8fbec1a2949f5239fd6bc19
[ "Apache-2.0" ]
null
null
null
#ifndef __WIFI_LOGO_GZ_H__ #define __WIFI_LOGO_GZ_H__ #include <Arduino.h> const unsigned char wifi_logo_css_gz[] PROGMEM = { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x03, 0xd3, 0x2b, 0xcf, 0x4c, 0xcb, 0x34, 0xac, 0x4e, 0x4a, 0x4c, 0xce, 0x4e, 0x2f, 0xca, 0x2f, 0xcd, 0x4b, 0xb1, 0x2a, 0x2d, 0xca, 0xd1, 0x50, 0x4a, 0x49, 0x2c, 0x49, 0xb4, 0xca, 0xcc, 0x4d, 0x4c, 0x4f, 0xd5, 0x2f, 0x2e, 0x4b, 0xd7, 0xae, 0xc8, 0xcd, 0xb1, 0x2e, 0x2d, 0x49, 0xb3, 0xd0, 0xb1, 0x01, 0xf2, 0x14, 0xca, 0x32, 0x53, 0xcb, 0x9d, 0xf2, 0x2b, 0x6c, 0xd5, 0x0d, 0x14, 0x0c, 0x14, 0x0c, 0x0d, 0xc0, 0x58, 0x5d, 0x01, 0xa8, 0x26, 0xaf, 0xd8, 0x56, 0x3d, 0xa3, 0xa4, 0xa4, 0xc0, 0x4a, 0x5f, 0xbf, 0xbc, 0xbc, 0x5c, 0xaf, 0xdc, 0x58, 0x2f, 0xbf, 0x28, 0x5d, 0xdf, 0xc8, 0xc0, 0xc0, 0x00, 0x64, 0x8a, 0xba, 0x42, 0x5a, 0x66, 0x4e, 0x8e, 0x6e, 0x51, 0x69, 0x4e, 0xaa, 0xad, 0x7a, 0x6a, 0x59, 0x6a, 0x5e, 0x7e, 0x4a, 0x8a, 0xba, 0x42, 0x72, 0x4e, 0x66, 0x01, 0xba, 0x58, 0x71, 0x49, 0x51, 0x7e, 0x76, 0xaa, 0x6e, 0x4e, 0x66, 0x5e, 0x6a, 0x56, 0x7e, 0x66, 0x9e, 0xad, 0x3a, 0xd8, 0x65, 0xea, 0x0a, 0x50, 0xf1, 0xdc, 0xcc, 0x92, 0xd4, 0xa2, 0x9c, 0x4c, 0x20, 0x65, 0xab, 0x6e, 0xa4, 0x6e, 0x67, 0x53, 0x90, 0x58, 0x92, 0xa1, 0x90, 0x62, 0xab, 0xee, 0x6b, 0x69, 0xac, 0x67, 0x66, 0x66, 0xae, 0x60, 0x61, 0xa8, 0x67, 0x64, 0x68, 0x99, 0x6c, 0xa0, 0x60, 0xa4, 0x67, 0x61, 0x69, 0xa1, 0x6b, 0xa4, 0x67, 0x66, 0x6a, 0xa6, 0x60, 0xaa, 0x67, 0x64, 0x62, 0xa1, 0x6b, 0xaa, 0x67, 0x69, 0x6c, 0x0c, 0x61, 0x67, 0x00, 0x39, 0x26, 0xc6, 0x16, 0xc9, 0xba, 0xc6, 0x7a, 0x46, 0xe6, 0xe6, 0x0a, 0x06, 0x40, 0xae, 0xa5, 0xb1, 0x09, 0x50, 0xb5, 0xb1, 0x29, 0x94, 0x09, 0xd6, 0x12, 0x66, 0x68, 0x01, 0x94, 0x37, 0x4c, 0x36, 0x00, 0xca, 0x58, 0x58, 0x9a, 0x01, 0xcd, 0x04, 0x9a, 0x06, 0x54, 0x60, 0x64, 0x02, 0x32, 0x13, 0xa4, 0x03, 0xa4, 0xcc, 0x2c, 0xc3, 0x54, 0x0f, 0x64, 0x18, 0xc8, 0x2c, 0x33, 0x60, 0xa8, 0x40, 0xec, 0x31, 0xd2, 0x33, 0x36, 0xb1, 0x04, 0xda, 0x06, 0xb3, 0xd3, 0xac, 0xcc, 0xcc, 0x48, 0xcf, 0xd2, 0xc4, 0xa2, 0xca, 0xd7, 0xdc, 0x40, 0xcf, 0xc0, 0xd8, 0x10, 0xe4, 0x52, 0x63, 0x43, 0x0b, 0x88, 0x4b, 0x4d, 0x8c, 0x80, 0x36, 0x18, 0x1b, 0x81, 0x4c, 0x35, 0x04, 0xbb, 0xd4, 0xd0, 0xd2, 0x14, 0xa8, 0x17, 0xc8, 0xce, 0xd0, 0x35, 0xd3, 0x33, 0xb1, 0x34, 0x4e, 0x06, 0xca, 0x5b, 0x98, 0x59, 0x80, 0x5d, 0x6a, 0x68, 0x09, 0x76, 0xa9, 0x81, 0x39, 0xd0, 0x25, 0x20, 0xb6, 0xa9, 0x1e, 0x50, 0x5d, 0x98, 0xb1, 0x25, 0xd0, 0xa9, 0xe6, 0x10, 0xa7, 0x9a, 0x18, 0x03, 0x9d, 0x0a, 0x34, 0x0e, 0xa4, 0xc0, 0xc4, 0x02, 0x64, 0x10, 0x50, 0x0b, 0x58, 0x59, 0x06, 0xc4, 0x34, 0x60, 0xe0, 0x98, 0x59, 0x82, 0x9d, 0x0a, 0xb2, 0x08, 0xe8, 0x54, 0x03, 0xb0, 0x75, 0x30, 0x4b, 0xcb, 0x4c, 0x8c, 0xf4, 0x0c, 0x4c, 0x0c, 0xab, 0x7c, 0x4d, 0xcc, 0xf4, 0x2c, 0x0c, 0xc1, 0x81, 0x6a, 0x92, 0x68, 0xaa, 0x67, 0x60, 0x06, 0x52, 0x05, 0x22, 0x81, 0x91, 0x6f, 0x08, 0x34, 0x1c, 0xc4, 0x04, 0x09, 0x9b, 0x65, 0xe8, 0x9a, 0xeb, 0x19, 0x9a, 0x9b, 0x62, 0x57, 0x63, 0x02, 0x56, 0x69, 0x16, 0x66, 0x6a, 0xa1, 0x67, 0x66, 0x60, 0x09, 0x56, 0x63, 0x02, 0x74, 0x93, 0x81, 0x99, 0x09, 0xd0, 0x05, 0x06, 0x86, 0x20, 0x03, 0x20, 0x4a, 0x4c, 0x32, 0xb0, 0x9b, 0x02, 0x52, 0x01, 0xb1, 0xd9, 0x24, 0x0c, 0x18, 0xbf, 0x26, 0x55, 0x90, 0xd4, 0x64, 0xab, 0x5e, 0x9c, 0x99, 0x53, 0x96, 0x5a, 0x04, 0xe1, 0xe9, 0x42, 0xd2, 0x56, 0x5e, 0x7e, 0x5e, 0x55, 0x6a, 0x51, 0xbe, 0xba, 0x3e, 0x52, 0xd2, 0x30, 0x32, 0xd6, 0x33, 0x31, 0x33, 0x56, 0xb0, 0x30, 0xd6, 0x33, 0x30, 0x32, 0x06, 0x07, 0xb8, 0x21, 0x30, 0x9e, 0x8d, 0xf4, 0x8c, 0x80, 0x01, 0x6a, 0xac, 0x67, 0x61, 0x06, 0x8a, 0x73, 0x90, 0x6b, 0xc0, 0x6c, 0x90, 0x57, 0x0c, 0x8c, 0x4d, 0x41, 0x01, 0x6e, 0x6e, 0x09, 0x49, 0x1a, 0x40, 0x6f, 0xea, 0x1a, 0xea, 0x99, 0x1b, 0x83, 0xfd, 0x61, 0x0a, 0x4c, 0x33, 0x40, 0x2d, 0x61, 0xe6, 0x16, 0x7a, 0xe6, 0x90, 0x94, 0x61, 0x08, 0x4c, 0x55, 0x60, 0xc3, 0x74, 0x4d, 0xf4, 0x4c, 0x2c, 0x20, 0x5e, 0x33, 0x85, 0xb0, 0x81, 0x1e, 0x02, 0x99, 0x65, 0xa4, 0x07, 0x36, 0x0a, 0xea, 0x69, 0x60, 0x70, 0x9b, 0x1a, 0x41, 0xd9, 0x60, 0x1d, 0x65, 0x26, 0x7a, 0xc6, 0x86, 0xc6, 0x50, 0x5f, 0x61, 0xfa, 0x03, 0x94, 0x7f, 0xec, 0x94, 0x34, 0x6b, 0xc1, 0xd9, 0xd5, 0x68, 0x34, 0xbb, 0x82, 0x33, 0x01, 0x28, 0xf3, 0x81, 0x02, 0x12, 0x18, 0x27, 0x20, 0x26, 0x28, 0x1f, 0x5a, 0x8c, 0xf4, 0xec, 0x0a, 0xc9, 0x08, 0x44, 0x67, 0x8b, 0x41, 0x9a, 0xb9, 0x7d, 0x87, 0x53, 0x76, 0x35, 0x1e, 0xcd, 0xae, 0xf4, 0xcd, 0xae, 0x24, 0xe6, 0x81, 0xd1, 0xba, 0x18, 0x58, 0x0b, 0x83, 0xea, 0x57, 0xb2, 0xeb, 0xe2, 0x61, 0x95, 0x5d, 0x4d, 0x46, 0xb3, 0x2b, 0x7d, 0xb3, 0xeb, 0x68, 0x63, 0x18, 0xd4, 0xf0, 0x1c, 0xcd, 0x80, 0xc0, 0xe6, 0x2d, 0x17, 0x00, 0x43, 0xf6, 0x30, 0x37, 0x8f, 0x0e, 0x00, 0x00 }; const unsigned int wifi_logo_css_gz_len = 743; #endif
64.432432
73
0.654153
e5e474d6e9a6d716a772a3ed1f99755b689e1d9a
184
h
C
ButtonStyle-Primary-Radio-M_classes.h
NotDiscordOfficial/Fortnite_SDK
58f8da148256f99cb35518003306fffee33c4a21
[ "MIT" ]
null
null
null
ButtonStyle-Primary-Radio-M_classes.h
NotDiscordOfficial/Fortnite_SDK
58f8da148256f99cb35518003306fffee33c4a21
[ "MIT" ]
null
null
null
ButtonStyle-Primary-Radio-M_classes.h
NotDiscordOfficial/Fortnite_SDK
58f8da148256f99cb35518003306fffee33c4a21
[ "MIT" ]
1
2021-07-22T00:31:44.000Z
2021-07-22T00:31:44.000Z
// BlueprintGeneratedClass ButtonStyle-Primary-Radio-M.ButtonStyle-Primary-Radio-M_C // Size: 0x570 (Inherited: 0x570) struct UButtonStyle-Primary-Radio-M_C : UCommonButtonStyle { };
30.666667
84
0.798913
95df348b3f2dd251bcac88d5d08a43d8bbf668bc
458
h
C
old_version/old_version_0.1/epoll.h
wjxwjx/WebServer
e7c981b0ed3615b051eb541e65b9718ba9697280
[ "MIT" ]
5,035
2018-02-25T06:12:59.000Z
2022-03-31T06:29:23.000Z
old_version/old_version_0.1/epoll.h
Costwen/WebServer
52f26ac9769f49a0d57cbce602f71a0f42661c5c
[ "MIT" ]
131
2018-02-27T12:08:59.000Z
2022-03-05T07:35:37.000Z
old_version/old_version_0.1/epoll.h
Costwen/WebServer
52f26ac9769f49a0d57cbce602f71a0f42661c5c
[ "MIT" ]
1,858
2018-03-03T10:25:38.000Z
2022-03-31T13:24:05.000Z
#ifndef EVENTPOLL #define EVENTPOLL #include "requestData.h" const int MAXEVENTS = 5000; const int LISTENQ = 1024; int epoll_init(); int epoll_add(int epoll_fd, int fd, void *request, __uint32_t events); int epoll_mod(int epoll_fd, int fd, void *request, __uint32_t events); int epoll_del(int epoll_fd, int fd, void *request, __uint32_t events); int my_epoll_wait(int epoll_fd, struct epoll_event *events, int max_events, int timeout); #endif
32.714286
90
0.753275
bf048c1e0b27bbe0e49556e904cd0141429a24f8
18,239
c
C
mi8/drivers/char/diag/diag_pcie.c
wqk317/mi8_kernel_source
e3482d1a7ea6021de2fc8f3178496b4b043bb727
[ "MIT" ]
null
null
null
mi8/drivers/char/diag/diag_pcie.c
wqk317/mi8_kernel_source
e3482d1a7ea6021de2fc8f3178496b4b043bb727
[ "MIT" ]
null
null
null
mi8/drivers/char/diag/diag_pcie.c
wqk317/mi8_kernel_source
e3482d1a7ea6021de2fc8f3178496b4b043bb727
[ "MIT" ]
1
2020-03-28T11:26:15.000Z
2020-03-28T11:26:15.000Z
/* Copyright (c) 2018-2019, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/slab.h> #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/err.h> #include <linux/sched.h> #include <linux/ratelimit.h> #include <linux/workqueue.h> #include <linux/diagchar.h> #include <linux/delay.h> #include <linux/kmemleak.h> #include <linux/list.h> #include "diag_pcie.h" #include "diag_mux.h" #include "diagmem.h" #include "diag_ipc_logging.h" #define DIAG_LEGACY "DIAG_PCIE" struct diag_pcie_info diag_pcie[NUM_DIAG_PCIE_DEV] = { { .id = DIAG_PCIE_LOCAL, .name = DIAG_LEGACY, .enabled = {0}, .mempool = POOL_TYPE_MUX_APPS, .ops = NULL, .wq = NULL, .read_cnt = 0, .write_cnt = 0, .in_chan_attr = { .max_pkt_size = DIAG_MAX_PKT_SZ, .nr_trbs = 1, .read_buffer = NULL, }, .out_chan_attr = { .max_pkt_size = DIAG_MAX_PCIE_PKT_SZ, }, .in_chan = MHI_CLIENT_DIAG_OUT, .out_chan = MHI_CLIENT_DIAG_IN, } }; static void diag_pcie_event_notifier(struct mhi_dev_client_cb_reason *reason) { int i; struct diag_pcie_info *pcie_info = NULL; for (i = 0; i < NUM_DIAG_PCIE_DEV; i++) { pcie_info = &diag_pcie[i]; if (reason->reason == MHI_DEV_TRE_AVAILABLE) if (reason->ch_id == pcie_info->in_chan) { queue_work(pcie_info->wq, &pcie_info->read_work); break; } } } void diag_pcie_read_work_fn(struct work_struct *work) { struct mhi_req ureq; struct diag_pcie_info *pcie_info = container_of(work, struct diag_pcie_info, read_work); unsigned int bytes_avail = 0; if (!pcie_info || !atomic_read(&pcie_info->enabled) || !atomic_read(&pcie_info->diag_state)) return; ureq.chan = pcie_info->in_chan; ureq.client = pcie_info->in_handle; ureq.mode = IPA_DMA_SYNC; ureq.buf = pcie_info->in_chan_attr.read_buffer; ureq.len = pcie_info->in_chan_attr.read_buffer_size; ureq.transfer_len = 0; bytes_avail = mhi_dev_read_channel(&ureq); if (bytes_avail < 0) return; DIAG_LOG(DIAG_DEBUG_MUX, "read total bytes %d from chan:%d", bytes_avail, pcie_info->in_chan); pcie_info->read_cnt++; if (pcie_info->ops && pcie_info->ops->read_done) pcie_info->ops->read_done(pcie_info->in_chan_attr.read_buffer, ureq.transfer_len, pcie_info->ctxt); } static void diag_pcie_buf_tbl_remove(struct diag_pcie_info *pcie_info, unsigned char *buf) { struct diag_pcie_buf_tbl_t *temp = NULL; struct diag_pcie_buf_tbl_t *entry = NULL; list_for_each_entry_safe(entry, temp, &pcie_info->buf_tbl, track) { if (entry->buf == buf) { DIAG_LOG(DIAG_DEBUG_MUX, "ref_count-- for %pK\n", buf); atomic_dec(&entry->ref_count); /* * Remove reference from the table if it is the * only instance of the buffer */ if (atomic_read(&entry->ref_count) == 0) { list_del(&entry->track); kfree(entry); entry = NULL; } break; } } } static struct diag_pcie_buf_tbl_t *diag_pcie_buf_tbl_get( struct diag_pcie_info *pcie_info, unsigned char *buf) { struct diag_pcie_buf_tbl_t *temp = NULL; struct diag_pcie_buf_tbl_t *entry = NULL; list_for_each_entry_safe(entry, temp, &pcie_info->buf_tbl, track) { if (entry->buf == buf) { DIAG_LOG(DIAG_DEBUG_MUX, "ref_count-- for %pK\n", buf); atomic_dec(&entry->ref_count); return entry; } } return NULL; } void diag_pcie_write_complete_cb(void *req) { struct diag_pcie_context *ctxt = NULL; struct diag_pcie_info *ch; struct diag_pcie_buf_tbl_t *entry = NULL; struct mhi_req *ureq = req; unsigned long flags; if (!ureq) return; ctxt = (struct diag_pcie_context *)ureq->context; if (!ctxt) return; ch = ctxt->ch; if (!ch) return; spin_lock_irqsave(&ch->write_lock, flags); ch->write_cnt++; entry = diag_pcie_buf_tbl_get(ch, ctxt->buf); if (!entry) { pr_err_ratelimited("diag: In %s, unable to find entry %pK in the table\n", __func__, ctxt->buf); spin_unlock_irqrestore(&ch->write_lock, flags); return; } if (atomic_read(&entry->ref_count) != 0) { DIAG_LOG(DIAG_DEBUG_MUX, "partial write_done ref %d\n", atomic_read(&entry->ref_count)); diag_ws_on_copy_complete(DIAG_WS_MUX); spin_unlock_irqrestore(&ch->write_lock, flags); diagmem_free(driver, req, ch->mempool); kfree(ctxt); ctxt = NULL; return; } DIAG_LOG(DIAG_DEBUG_MUX, "full write_done, ctxt: %pK\n", ctxt->buf); list_del(&entry->track); kfree(entry); entry = NULL; if (ch->ops && ch->ops->write_done) ch->ops->write_done(ureq->buf, ureq->len, ctxt->buf_ctxt, DIAG_PCIE_MODE); spin_unlock_irqrestore(&ch->write_lock, flags); diagmem_free(driver, req, ch->mempool); kfree(ctxt); ctxt = NULL; } static int diag_pcie_buf_tbl_add(struct diag_pcie_info *pcie_info, unsigned char *buf, uint32_t len, int ctxt) { struct diag_pcie_buf_tbl_t *temp = NULL; struct diag_pcie_buf_tbl_t *entry = NULL; list_for_each_entry_safe(entry, temp, &pcie_info->buf_tbl, track) { if (entry->buf == buf) { atomic_inc(&entry->ref_count); return 0; } } /* New buffer, not found in the list */ entry = kzalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return -ENOMEM; entry->buf = buf; entry->ctxt = ctxt; entry->len = len; atomic_set(&entry->ref_count, 1); INIT_LIST_HEAD(&entry->track); list_add_tail(&entry->track, &pcie_info->buf_tbl); return 0; } static int diag_pcie_write_ext(struct diag_pcie_info *pcie_info, unsigned char *buf, int len, int ctxt) { int write_len = 0; int bytes_remaining = len; int offset = 0; struct mhi_req *req; struct diag_pcie_context *context; int bytes_to_write; unsigned long flags; if (!pcie_info || !buf || len <= 0) { pr_err_ratelimited("diag: In %s, pcie_info: %pK buf: %pK, len: %d\n", __func__, pcie_info, buf, len); return -EINVAL; } while (bytes_remaining > 0) { req = diagmem_alloc(driver, sizeof(struct mhi_req), pcie_info->mempool); if (!req) { pr_err_ratelimited("diag: In %s, cannot retrieve pcie write ptrs for pcie channel %s\n", __func__, pcie_info->name); return -ENOMEM; } write_len = (bytes_remaining > pcie_info->out_chan_attr.max_pkt_size) ? pcie_info->out_chan_attr.max_pkt_size : bytes_remaining; req->client = pcie_info->out_handle; context = kzalloc(sizeof(*context), GFP_KERNEL); if (!context) return -ENOMEM; context->ch = pcie_info; context->buf_ctxt = ctxt; context->buf = buf; req->context = context; req->buf = buf + offset; req->len = write_len; req->chan = pcie_info->out_chan; req->mode = IPA_DMA_ASYNC; req->client_cb = diag_pcie_write_complete_cb; req->snd_cmpl = 1; if (!pcie_info->out_handle || !atomic_read(&pcie_info->enabled) || !atomic_read(&pcie_info->diag_state)) { pr_debug_ratelimited("diag: pcie ch %s is not opened\n", pcie_info->name); kfree(req->context); diagmem_free(driver, req, pcie_info->mempool); return -ENODEV; } spin_lock_irqsave(&pcie_info->write_lock, flags); if (diag_pcie_buf_tbl_add(pcie_info, buf, len, ctxt)) { kfree(req->context); diagmem_free(driver, req, pcie_info->mempool); spin_unlock_irqrestore(&pcie_info->write_lock, flags); return -ENOMEM; } spin_unlock_irqrestore(&pcie_info->write_lock, flags); diag_ws_on_read(DIAG_WS_MUX, len); bytes_to_write = mhi_dev_write_channel(req); diag_ws_on_copy(DIAG_WS_MUX); if (bytes_to_write != write_len) { pr_err_ratelimited("diag: In %s, error writing to pcie channel %s, err: %d, write_len: %d\n", __func__, pcie_info->name, bytes_to_write, write_len); DIAG_LOG(DIAG_DEBUG_MUX, "ERR! unable to write to pcie, err: %d, write_len: %d\n", bytes_to_write, write_len); diag_ws_on_copy_fail(DIAG_WS_MUX); spin_lock_irqsave(&pcie_info->write_lock, flags); diag_pcie_buf_tbl_remove(pcie_info, buf); kfree(req->context); diagmem_free(driver, req, pcie_info->mempool); spin_unlock_irqrestore(&pcie_info->write_lock, flags); return -EINVAL; } offset += write_len; bytes_remaining -= write_len; DIAG_LOG(DIAG_DEBUG_MUX, "bytes_remaining: %d write_len: %d, len: %d\n", bytes_remaining, write_len, len); } DIAG_LOG(DIAG_DEBUG_MUX, "done writing!"); return 0; } int diag_pcie_write(int id, unsigned char *buf, int len, int ctxt) { struct mhi_req *req; struct diag_pcie_context *context; int bytes_to_write; struct diag_pcie_info *pcie_info; unsigned long flags; pcie_info = &diag_pcie[id]; if (len > pcie_info->out_chan_attr.max_pkt_size) { DIAG_LOG(DIAG_DEBUG_MUX, "len: %d, max_size: %zu\n", len, pcie_info->out_chan_attr.max_pkt_size); return diag_pcie_write_ext(pcie_info, buf, len, ctxt); } req = (struct mhi_req *)diagmem_alloc(driver, sizeof(struct mhi_req), pcie_info->mempool); if (!req) { pr_err_ratelimited("diag: In %s, cannot retrieve pcie write ptrs for pcie channel %s\n", __func__, pcie_info->name); return -ENOMEM; } req->client = pcie_info->out_handle; context = kzalloc(sizeof(struct diag_pcie_context), GFP_KERNEL); if (!context) return -ENOMEM; context->ch = &diag_pcie[id]; context->buf_ctxt = ctxt; context->buf = buf; req->context = context; req->buf = buf; req->len = len; req->chan = pcie_info->out_chan; req->mode = IPA_DMA_ASYNC; req->client_cb = diag_pcie_write_complete_cb; req->snd_cmpl = 1; if (!pcie_info->out_handle || !atomic_read(&pcie_info->enabled) || !atomic_read(&pcie_info->diag_state)) { pr_debug_ratelimited("diag: pcie ch %s is not opened\n", pcie_info->name); kfree(req->context); diagmem_free(driver, req, pcie_info->mempool); return -ENODEV; } spin_lock_irqsave(&pcie_info->write_lock, flags); if (diag_pcie_buf_tbl_add(pcie_info, buf, len, ctxt)) { DIAG_LOG(DIAG_DEBUG_MUX, "ERR! unable to add buf %pK to table\n", buf); kfree(req->context); diagmem_free(driver, req, pcie_info->mempool); spin_unlock_irqrestore(&pcie_info->write_lock, flags); return -ENOMEM; } spin_unlock_irqrestore(&pcie_info->write_lock, flags); diag_ws_on_read(DIAG_WS_MUX, len); bytes_to_write = mhi_dev_write_channel(req); diag_ws_on_copy(DIAG_WS_MUX); if (bytes_to_write != len) { pr_err_ratelimited("diag: In %s, error writing to pcie channel %s, err: %d len: %d\n", __func__, pcie_info->name, bytes_to_write, len); diag_ws_on_copy_fail(DIAG_WS_MUX); DIAG_LOG(DIAG_DEBUG_MUX, "ERR! unable to write to pcie, err: %d len: %d\n", bytes_to_write, len); spin_lock_irqsave(&pcie_info->write_lock, flags); diag_pcie_buf_tbl_remove(pcie_info, buf); spin_unlock_irqrestore(&pcie_info->write_lock, flags); kfree(req->context); diagmem_free(driver, req, pcie_info->mempool); return -EINVAL; } DIAG_LOG(DIAG_DEBUG_MUX, "wrote packet to pcie chan:%d, len:%d", pcie_info->out_chan, len); return 0; } static int pcie_init_read_chan(struct diag_pcie_info *ptr, enum mhi_client_channel chan) { int rc = 0; size_t buf_size; void *data_loc; if (ptr == NULL) { DIAG_LOG(DIAG_DEBUG_PERIPHERALS, "Bad Input data, quitting\n"); return -EINVAL; } buf_size = ptr->in_chan_attr.max_pkt_size; data_loc = kzalloc(buf_size, GFP_KERNEL); if (!data_loc) return -ENOMEM; kmemleak_not_leak(data_loc); ptr->in_chan_attr.read_buffer = data_loc; ptr->in_chan_attr.read_buffer_size = buf_size; return rc; } void diag_pcie_client_cb(struct mhi_dev_client_cb_data *cb_data) { struct diag_pcie_info *pcie_info = NULL; if (!cb_data) return; pcie_info = cb_data->user_data; if (!pcie_info) return; switch (cb_data->ctrl_info) { case MHI_STATE_CONNECTED: if (cb_data->channel == pcie_info->out_chan) { DIAG_LOG(DIAG_DEBUG_MUX, " Received connect event from MHI for %d", pcie_info->out_chan); if (atomic_read(&pcie_info->enabled)) return; queue_work(pcie_info->wq, &pcie_info->open_work); } break; case MHI_STATE_DISCONNECTED: if (cb_data->channel == pcie_info->out_chan) { DIAG_LOG(DIAG_DEBUG_MUX, " Received disconnect event from MHI for %d", pcie_info->out_chan); if (!atomic_read(&pcie_info->enabled)) return; queue_work(pcie_info->wq, &pcie_info->close_work); } break; default: break; } } static int diag_register_pcie_channels(struct diag_pcie_info *pcie_info) { int rc = 0; if (!pcie_info) return -EIO; pcie_info->event_notifier = diag_pcie_event_notifier; DIAG_LOG(DIAG_DEBUG_MUX, "Initializing inbound chan %d.\n", pcie_info->in_chan); rc = pcie_init_read_chan(pcie_info, pcie_info->in_chan); if (rc < 0) { DIAG_LOG(DIAG_DEBUG_MUX, "Failed to init inbound 0x%x, ret 0x%x\n", pcie_info->in_chan, rc); return rc; } /* Register for state change notifications from mhi*/ rc = mhi_register_state_cb(diag_pcie_client_cb, pcie_info, pcie_info->out_chan); if (rc < 0) return rc; return 0; } static void diag_pcie_connect(struct diag_pcie_info *ch) { if (!ch || !atomic_read(&ch->enabled)) return; if (ch->ops && ch->ops->open) if (atomic_read(&ch->diag_state)) ch->ops->open(ch->ctxt, DIAG_PCIE_MODE); /* As soon as we open the channel, queue a read */ queue_work(ch->wq, &(ch->read_work)); } void diag_pcie_open_work_fn(struct work_struct *work) { int rc = 0; struct diag_pcie_info *pcie_info = container_of(work, struct diag_pcie_info, open_work); if (!pcie_info || atomic_read(&pcie_info->enabled)) return; mutex_lock(&pcie_info->out_chan_lock); mutex_lock(&pcie_info->in_chan_lock); /* Open write channel*/ rc = mhi_dev_open_channel(pcie_info->out_chan, &pcie_info->out_handle, pcie_info->event_notifier); if (rc < 0) { DIAG_LOG(DIAG_DEBUG_PERIPHERALS, "Failed to open chan %d, ret %d\n", pcie_info->in_chan, rc); goto handle_not_rdy_err; } DIAG_LOG(DIAG_DEBUG_MUX, "opened write channel %d", pcie_info->out_chan); /* Open read channel*/ rc = mhi_dev_open_channel(pcie_info->in_chan, &pcie_info->in_handle, pcie_info->event_notifier); if (rc < 0) { DIAG_LOG(DIAG_DEBUG_PERIPHERALS, "Failed to open chan %d, ret 0x%x\n", pcie_info->in_chan, rc); goto handle_in_err; } DIAG_LOG(DIAG_DEBUG_MUX, "opened read channel %d", pcie_info->in_chan); mutex_unlock(&pcie_info->in_chan_lock); mutex_unlock(&pcie_info->out_chan_lock); atomic_set(&pcie_info->enabled, 1); atomic_set(&pcie_info->diag_state, 1); diag_pcie_connect(pcie_info); return; handle_in_err: mhi_dev_close_channel(pcie_info->out_handle); atomic_set(&pcie_info->enabled, 0); handle_not_rdy_err: mutex_unlock(&pcie_info->in_chan_lock); mutex_unlock(&pcie_info->out_chan_lock); } /* * This function performs pcie connect operations wrt Diag synchronously. It * doesn't translate to actual pcie connect. This is used when Diag switches * logging to pcie mode and wants to mimic pcie connection. */ void diag_pcie_connect_all(void) { int i = 0; struct diag_pcie_info *pcie_info = NULL; for (i = 0; i < NUM_DIAG_PCIE_DEV; i++) { pcie_info = &diag_pcie[i]; if (!atomic_read(&pcie_info->enabled)) continue; atomic_set(&pcie_info->diag_state, 1); diag_pcie_connect(pcie_info); } } static void diag_pcie_disconnect(struct diag_pcie_info *ch) { if (!ch) return; if (!atomic_read(&ch->enabled) && driver->pcie_connected && diag_mask_param()) diag_clear_masks(0); if (ch && ch->ops && ch->ops->close) ch->ops->close(ch->ctxt, DIAG_PCIE_MODE); } /* * This function performs pcie disconnect operations wrt Diag synchronously. * It doesn't translate to actual pcie disconnect. This is used when Diag * switches logging from pcie mode and want to mimic pcie disconnect. */ void diag_pcie_disconnect_all(void) { int i = 0; struct diag_pcie_info *pcie_info = NULL; for (i = 0; i < NUM_DIAG_PCIE_DEV; i++) { pcie_info = &diag_pcie[i]; if (!atomic_read(&pcie_info->enabled)) continue; atomic_set(&pcie_info->diag_state, 0); diag_pcie_disconnect(pcie_info); } } void diag_pcie_close_work_fn(struct work_struct *work) { int rc = 0; struct diag_pcie_info *pcie_info = container_of(work, struct diag_pcie_info, open_work); if (!pcie_info || !atomic_read(&pcie_info->enabled)) return; mutex_lock(&pcie_info->out_chan_lock); mutex_lock(&pcie_info->in_chan_lock); rc = mhi_dev_close_channel(pcie_info->in_handle); DIAG_LOG(DIAG_DEBUG_MUX, " closed in bound channel %d", pcie_info->in_chan); rc = mhi_dev_close_channel(pcie_info->out_handle); DIAG_LOG(DIAG_DEBUG_MUX, " closed out bound channel %d", pcie_info->out_chan); mutex_unlock(&pcie_info->in_chan_lock); mutex_unlock(&pcie_info->out_chan_lock); atomic_set(&pcie_info->enabled, 0); diag_pcie_disconnect(pcie_info); } int diag_pcie_register(int id, int ctxt, struct diag_mux_ops *ops) { struct diag_pcie_info *ch = NULL; int rc = 0; unsigned char wq_name[DIAG_PCIE_NAME_SZ + DIAG_PCIE_STRING_SZ]; if (id < 0 || id >= NUM_DIAG_PCIE_DEV) { pr_err("diag: Unable to register with PCIE, id: %d\n", id); return -EIO; } if (!ops) { pr_err("diag: Invalid operations for PCIE\n"); return -EIO; } ch = &diag_pcie[id]; ch->ops = ops; ch->ctxt = ctxt; atomic_set(&ch->diag_state, 0); atomic_set(&ch->enabled, 0); INIT_LIST_HEAD(&ch->buf_tbl); spin_lock_init(&ch->write_lock); INIT_WORK(&(ch->read_work), diag_pcie_read_work_fn); INIT_WORK(&(ch->open_work), diag_pcie_open_work_fn); INIT_WORK(&(ch->close_work), diag_pcie_close_work_fn); strlcpy(wq_name, "DIAG_PCIE_", sizeof(wq_name)); strlcat(wq_name, ch->name, sizeof(wq_name)); ch->wq = create_singlethread_workqueue(wq_name); if (!ch->wq) return -ENOMEM; diagmem_init(driver, ch->mempool); mutex_init(&ch->in_chan_lock); mutex_init(&ch->out_chan_lock); rc = diag_register_pcie_channels(ch); if (rc < 0) { if (ch->wq) destroy_workqueue(ch->wq); kfree(ch->in_chan_attr.read_buffer); return rc; } return 0; }
27.634848
96
0.71073
24634454c26142e6fbe939d58cc2e6e316f93873
962
h
C
LaunchKeyUI/LaunchKeyWhiteLabel/Views/SecurityFactorTableViewCell.h
iovation/launchkey-ios-whitelabel-sdk
90c1ed2808f9e2fa2282572828cc9aa21ddd3e7c
[ "MIT" ]
3
2021-03-26T16:55:55.000Z
2022-02-20T12:39:42.000Z
LaunchKeyUI/LaunchKeyWhiteLabel/Views/SecurityFactorTableViewCell.h
LaunchKey/launchkey-ios-whitelabel-sdk
90c1ed2808f9e2fa2282572828cc9aa21ddd3e7c
[ "MIT" ]
39
2016-07-18T21:43:23.000Z
2016-09-15T22:13:39.000Z
LaunchKeyUI/LaunchKeyWhiteLabel/Views/SecurityFactorTableViewCell.h
iovation/launchkey-ios-whitelabel-sdk
90c1ed2808f9e2fa2282572828cc9aa21ddd3e7c
[ "MIT" ]
1
2020-04-20T14:09:13.000Z
2020-04-20T14:09:13.000Z
// // SecurityFactorTableViewCell.h // WhiteLabel // // Created by ani on 11/15/16. // Copyright © 2016 LaunchKey. All rights reserved. // #import <UIKit/UIKit.h> @interface SecurityFactorTableViewCell : UITableViewCell /// This UIImage property is the image of the PIN Code auth method displayed in the Security View. */ @property UIImage *imagePINCodeFactor; /// This UIImage property is the image of the Circle Code auth method displayed in the Security View. */ @property UIImage *imageCircleCodeFactor; /// This UIImage property is the image of the Wearables auth method displayed in the Security View. */ @property UIImage *imageWearablesFactor; /// This UIImage property is the image of the Locations auth method displayed in the Security View. */ @property UIImage *imageLocationsFactor; /// This UIImage property is the image of the Fingerprint Scan auth method displayed in the Security View. */ @property UIImage *imageFingerprintFactor; @end
38.48
109
0.773389
5721d354a529db7889b0fc3d7507234ca236cd57
14,175
h
C
python/libvncxx/include/vn/newserialport.h
dawonn/vnproglib
a1444675049fef7a327ff9069fbad1560342fd4a
[ "MIT" ]
1
2017-08-23T18:52:21.000Z
2017-08-23T18:52:21.000Z
python/libvncxx/include/vn/newserialport.h
dawonn/vnproglib
a1444675049fef7a327ff9069fbad1560342fd4a
[ "MIT" ]
10
2018-05-30T15:49:45.000Z
2019-06-12T18:20:29.000Z
data_acquisition/ptu/libs/vectornav/libvncxx/include/vn/newserialport.h
HoliestCow/wind_daq
6a8b30ba6b14b3162f2fa3144b52cdf7ed17ec3a
[ "MIT" ]
null
null
null
#ifndef NEWSERIALPORT #define NEWSERIALPORT #if _NEW_SERIAL_PORT #include "int.h" #include "export.h" #include "port.h" #include "thread.h" #include <cstdint> #include <map> #include <queue> #include <string> #include <vector> #ifdef _WIN32 // Windows exclusive includes #include <Windows.h> #elif __linux__ || __APPLE__ || __CYGWIN__ || __QNXNTO__ #endif // Forward Declarations namespace vn { namespace protocol { namespace uart { struct Packet; } } namespace xplat { class CriticalSection; } } namespace vn { namespace xplat { class vn_proglib_DLLEXPORT NewSerialPort : public IPort, public NewThread { public: // Enumerations /// \brief Enumeration to identify which message group an incoming packet belongs to enum BinaryMessageGroup { NSPBMG_INVALID = 0, NSPBMG_GROUP1 = 0x01, NSPBMG_GROUP2 = 0x02, NSPBMG_GROUP3 = 0x04, NSPBMG_GROUP4 = 0x08, NSPBMG_GROUP5 = 0x10, NSPBMG_GROUP6 = 0x20, NSPBMG_GROUP7 = 0x40, NSPBMG_GROUP8 = 0x80, NSPBMG_NUM_GROUPS }; /// \brief Enumeration representing the stop bits used in serial communications enum StopBits { NSPSB_INVALID = -1, NSPSB_ONE, NSPSB_TWO }; /// \brief Maximum size of a binary packet static const size_t MaxBinaryPacketSize; /// \brief Maximum size of an ascii packet static const size_t MaxAsciiPacketSize; /// \brief Maximum size of a binary header static const size_t MaxBinaryHeaderSize; /// \brief Constant to hold the number of bytes to purge when a port is first opened static const size_t NumBytesToPurge; /// \brief Number of bytes to receive on each read request static const size_t ReceiveBufferSize; /// \brief The number of bytes each field in a binary message is. Used to calculate how large an /// incoming binary message is. static const std::map < NewSerialPort::BinaryMessageGroup, std::vector<uint8_t> > BinaryFieldLengthsMap; /// \brief Set of characters that indicate the start of an ascii packet static const std::vector<char> ASCIIStartSentinal; /// \brief Set of characters that indicate the end of an incoming ascii packet static const std::vector<char> ASCIIEndSentinal; /// \brief Set of characters that indicate the start of a binary packet static const std::vector<char> BinaryStartSentinal; /// \brief Constant to hold the number of miliseconds to wait with each read static const uint8_t ReadWaitTime; // General Functions /// \brief CTOR /// Constructs a SerialPort object with the input port name and baud rate /// \param aPortName Name of the port to connect to /// \param aBaudRate The baud rate in bits per second to connect at NewSerialPort(const std::string& aPortName, uint32_t aBaudRate); /// \DTOR ~NewSerialPort(); /// \brief Returns the current baud rate the port is connected at /// \return The current baud rate uint32_t baudRate(); /// \brief Sets the current baud rate to the input value /// \param aBaudRate The baud rate to set the port connection to void baudRate(uint32_t aBaudRate); /// \brief Signals to the serial port that it should close the connection down. void close(); /// \brief Searches the system for available serial ports and returns their names. /// This list is not guaranteed to be inclusive of all port names as some may be /// in use and will not be included in the list. /// \param aPortNames A vector of available port names static void getAvailablePortNames(std::vector<std::string>& aPortNames); /// \brief getNextPacket Packets are stored in queue form. This will pop the next /// packet off of the queue and return it to the caller. The caller then becomes /// the owner of the packet and is responsible for clean up. If the queue is empty /// this function returns a null pointer. /// \return A pointer to the next packet in the queue. protocol::uart::Packet* getNextPacket(); /// \brief Indicates if there is a packet on the queue without popping the packet. /// \return Flag indicating if a packet is on the queue. bool hasPacket(); /// \brief Indicates if the port is currently open. /// \return Flag to indicate if the port is open. bool isOpen(); /// \brief Tells the serial port to create a connection to the current port and /// at the current baud rate. void open(); /// \brief Returs the name of the port the object is connected to /// \return Name of the port. std::string port(); /// \brief Reads up to aNumOfBytesToRead and stores them in the input vector. The input /// buffer is cleared and a failure to read means the buffer will return empty. /// \param aDataBuffer vector to hold the data read from the serial port /// \param aNumOfBytesToRead The maximum number of bytes to read on this call void read(std::vector<char>& aDataBuffer, size_t aNumOfBytesToRead); /// \brief Writes the input data to the serial port and sends it. /// \param aDataBuffer A vector containing the data to send over the port. void write(const std::vector<char>& aDataBuffer); // DEPRICATED PUBLIC FUNCTIONS /// \deprecated Takes in the maximum number of bytes to read and returns the actual /// bytes read as well as the number read. This is to provide some backwards /// compatibility with software written against the older serial port and will /// eventually be removed. /// \param aDataBuffer vector to hold the data read from the serial port /// \param aNumOfBytesToRead The maximum number of bytes to read on this call /// \param aNumOfBytesActuallyRead The number of bytes actually read off of the /// serial port. This number can be less than aNumOfBytesToRead but never larger. void read(std::vector<char>& aDataBuffer, size_t aNumOfBytesToRead, size_t &aNumOfBytesActuallyRead); /// \deprecated This function takes in C-style inputs and will be removed in future /// releases /// Reads upto aNumOfBytesToRead bytes into the input aDataBuffer array. Sets /// aNumOfBytesActuallyRead to the number of bytes the port was able to read. This /// number can be less than aNumOfBytesToRead but never more. /// \param aDataBuffer Buffer to hold the data read from the serial port. It should be /// at least aNumOfBytesToRead in size. /// \param aNumOfBytesToRead The maximum number of bytes to read during this call /// \param aNumOfBytesActuallyRead The number of bytes read from the serial port. This /// number can be less than aNumOfBytesToRead but never more. void read(char aDataBuffer[], size_t aNumOfBytesToRead, size_t &aNumOfBytesActuallyRead); /// \deprecated This is for compatibility with the iPort template and should not be /// used as it does nothing. /// \param userData /// \param handler void registerDataReceivedHandler(void* userData, DataReceivedHandler handler) {} /// \deprecated This is for compatibility with the iPort template and should not be /// used as it does nothing. void unregisterDataReceivedHandler() {} /// \deprecated This function takes in C-style inputs and will be removed in future /// releases. /// Writes the data in the character array aData with length aLength to the serial /// port and sends it. /// \param aData Data to be sent over the serial port /// \param aLength Length of the data array to send void write(const char aData[], size_t aLength); protected: /// \brief Overridden function that contains the thread loop. This should only be /// called by the thread base class. virtual void run(); private: // General Variables /// \brief Flag indicating if the serial port is currently open bool m_isOpen; /// \brief CriticalSection to protect access to the packet vector CriticalSection* m_packetQueueCriticalSection; /// \brief CriticalSection to protect access to the read buffer CriticalSection* m_readBufferCriticalSection; /// \brief Queue that stores the packets after they are processed from data /// read from the port. std::queue<vn::protocol::uart::Packet*> m_packetQueue; /// \brief The name of the port to connect to std::string m_portName; /// \brief Vector of characters to store data read from the port for processing. All /// data read is appeneded to the end of the vector and is only removed if a packet is /// found. When a packet is found the packet's data, as well as all previous data, is /// removed. std::vector<char> m_readBuffer; /// \brief Number of stop bits the port should use StopBits m_stopBits; /// \brief The baud rate to connect the port at uint32_t m_baudRate; /// \brief The number of packets that has been received while the program is active. uint32_t m_packetCounter; #ifdef _WIN32 // Windows Based Variables /// \brief Handle to the serial port for reading and writing HANDLE m_serialPortHandle; #elif __linux__ || __APPLE__ || __CYGWIN__ || __QNXNTO__ #error "New SerialPort class does not yet support Unix systems" #else #error "Unknown System" #endif /// \brief CTOR /// Made private to enforce having at least a port name and baud rate before open /// can be called. NewSerialPort(); /// \brief Ensures that conditions are correct for processsing an ascii packet if one /// has been detected. If the conditions are met it passes the data to the packet class /// to process the ascii data. /// \param aAsciiStartItr Iterator to the start byte of the ascii packet /// \param aAsciiEndItr Iterator to the end byte of the ascii packet. This value may /// be invalid under certain conditions such as an incomplete packet. vn::protocol::uart::Packet* processASCIIData(std::vector<char>::iterator aAsciiStartItr, std::vector<char>::iterator aAsciiEndItr); /// \brief Ensures that conditions are correct for processing a binary packet if one /// has been detected. If the conditions are met it passes the data to the packet class /// to process the binary data. /// \param aBinaryItr Iterator to the start byte of the binary packet vn::protocol::uart::Packet* processBinaryData(std::vector<char>::iterator aBinaryItr); /// \brief This should be called every time data is appeneded to the m_readBuffer. This /// will do a preliminary search for binary and ascii packets and call the correct processing /// function to handle any that are possibly detected. void processData(); /// \brief Appends the input aDataBuffer data to the m_readBuffer. /// \param aDataBuffer vector of bytes to append to the m_readBuffer; this can be empty. void storeReadData(const std::vector<char>& aDataBuffer); }; class vn_proglib_DLLEXPORT NewSearcher : public NewThread { public: /// \brief Set of supported baud rates used when searching for a sensor. static const std::vector<uint32_t> TestBaudrates ; /// CTOR NewSearcher(); /// DTOR ~NewSearcher(); /// \brief Returns a flag to indicate if the searcher has finished searching the /// current list of ports. This differs from the searching function as this function /// indicates if the input ports have been searched already. /// \return Flag indicating if the searcher has finished searching. bool finished(); /// \brief Returns the number of sensors that have been detected by any of the search routines. /// This function returns a zero if a search has not been performed or if one is in progress. /// \return The number of detected sensors or zero if no search has been completed. size_t getNumSensors(); /// \brief Returns the port name and baudrate of the detected sensor at aIndex. /// Returns an empty string and a zero if a search has not yet completed or if aIndex /// is out of range. /// \param aIndex The index of the port/baud pair to return. /// \return A pair contining the port name and baudrate. std::pair<std::string, std::uint32_t> getSensor(size_t aIndex); /// \brief Resets the searcher and removes all previous results. void reset(); /// \brief Finds all available serial ports on the system and then searches them at various /// baud rates to see if a sensor exists. void search(); /// \brief Searches the port at aPortName at various baud rates to see if a sensor is /// attached to it. /// \param aPortName The name of the port to search void search(const std::string& aPortName); /// \brief Searches the input serial port names for sensors at various baud rates. /// \param aPortsToCheck Name of the ports to check for sensors. void search(const std::vector<std::string>& aPortsToCheck); /// Returns a flag that indicates if the searcher is still busy searching for sensors. /// This differs from the finish function as this function indicates if the thread /// loop is running. /// \return Flag indicating if the search thread is running. bool searching(); protected: virtual void run(); private: bool m_isMaster; NewSerialPort* m_port; std::vector<std::string> m_portList; std::vector<std::pair<std::string, uint32_t>> m_validPorts; /// CTOR /// \brief Takes port name and searches it for a sensor. NewSearcher(const std::string& aPortName); /// \brief This function is for slave objects only. It will search all /// known bauds to if a sensor is connected to its port. void searchBauds(); /// \brief This function is for master objects only. It will create a slave /// instance for each input port and have them search all known bauds to see /// if a sensor is connected. void searchPorts(); }; }} // End vn/xplat namespaces #endif #endif
44.716088
106
0.696649
b39d830a0fc8e58df6733765b65842c0a732261f
1,227
h
C
32blit-stm32/Inc/CDCDataStream.h
chcbaram/32blit-sdk
419c480683b0d21fd7415036cdbb031c4ec170e6
[ "MIT" ]
88
2019-11-27T13:15:27.000Z
2021-02-03T19:39:25.000Z
32blit-stm32/Inc/CDCDataStream.h
chcbaram/32blit-sdk
419c480683b0d21fd7415036cdbb031c4ec170e6
[ "MIT" ]
496
2019-11-27T13:24:44.000Z
2021-02-10T15:45:46.000Z
32blit-stm32/Inc/CDCDataStream.h
chcbaram/32blit-sdk
419c480683b0d21fd7415036cdbb031c4ec170e6
[ "MIT" ]
57
2019-11-27T13:25:25.000Z
2021-02-10T09:03:54.000Z
/* * CDCDataStream.h * * Created on: 17 Jan 2020 * Author: andrewcapon */ #ifndef SRC_CDCDATASTREAM_H_ #define SRC_CDCDATASTREAM_H_ #include "stm32h7xx_hal.h" #include <cstring> #include <streambuf> #include <istream> class CDCDataStream { public: CDCDataStream() : m_pData(NULL), m_uLen(0) { } bool AddData(uint8_t *pData, uint32_t uLen) { if(m_uLen) memmove(buf, m_pData, m_uLen); memcpy(buf + m_uLen, pData, uLen); m_pData = buf; m_uLen += uLen; return true; } void Clear() { m_uLen = 0; } uint32_t GetStreamLength(void) { return m_uLen; } bool GetDataOfLength(void *pData, uint8_t uLen) { bool bResult = false; uint8_t *pByteData = (uint8_t *)pData; if(m_uLen >= uLen) { while(uLen--) { bResult = true; *pByteData++ = *m_pData++; m_uLen--; } } return bResult; } bool Get(uint32_t &uValue) { return GetDataOfLength(&uValue, 4); } bool Get(uint16_t &uValue) { return GetDataOfLength(&uValue, 2); } bool Get(uint8_t &uValue) { return GetDataOfLength(&uValue, 1); } private: uint8_t *m_pData; uint32_t m_uLen; uint8_t buf[64 + 4]; // slightly larger than a FIFO element }; #endif /* SRC_CDCDATASTREAM_H_ */
13.943182
60
0.647922
831c2cd31dbf9aef91d8a12cc95f92312f5795cc
698
h
C
bindgen/ir/LiteralDefine.h
ekrich/scala-native-bindgen
df13474833c2fe01691e63e57c2cd9d1a623db20
[ "BSD-3-Clause" ]
8
2018-05-18T19:09:55.000Z
2018-07-02T14:42:07.000Z
bindgen/ir/LiteralDefine.h
ekrich/scala-native-bindgen
df13474833c2fe01691e63e57c2cd9d1a623db20
[ "BSD-3-Clause" ]
111
2018-05-24T18:50:22.000Z
2018-08-22T12:54:42.000Z
bindgen/ir/LiteralDefine.h
ekrich/scala-native-bindgen
df13474833c2fe01691e63e57c2cd9d1a623db20
[ "BSD-3-Clause" ]
1
2018-06-25T20:00:15.000Z
2018-06-25T20:00:15.000Z
#ifndef SCALA_NATIVE_BINDGEN_LITERALDEFINE_H #define SCALA_NATIVE_BINDGEN_LITERALDEFINE_H #include "Define.h" #include "types/Type.h" #include <llvm/Support/raw_ostream.h> class LiteralDefine : public Define { public: LiteralDefine(std::string name, std::string literal, std::shared_ptr<const Type> type); std::string getDefinition(const LocationManager &locationManager) const; bool usesType(const std::shared_ptr<const Type> &type, bool stopOnTypeDefs, std::vector<std::shared_ptr<const Type>> &visitedTypes) const; private: std::string literal; std::shared_ptr<const Type> type; }; #endif // SCALA_NATIVE_BINDGEN_LITERALDEFINE_H
29.083333
80
0.730659
044673f3b5f280ff09f33d7c5a5826d42e8e542c
12,285
h
C
mysql-server/plugin/group_replication/include/gcs_event_handlers.h
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/plugin/group_replication/include/gcs_event_handlers.h
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/plugin/group_replication/include/gcs_event_handlers.h
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2014, 2020, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GCS_EVENT_HANDLERS_INCLUDE #define GCS_EVENT_HANDLERS_INCLUDE #include <set> #include <vector> #include "plugin/group_replication/include/applier.h" #include "plugin/group_replication/include/compatibility_module.h" #include "plugin/group_replication/include/gcs_plugin_messages.h" #include "plugin/group_replication/include/gcs_view_modification_notifier.h" #include "plugin/group_replication/include/plugin_constants.h" #include "plugin/group_replication/include/plugin_handlers/read_mode_handler.h" #include "plugin/group_replication/include/plugin_messages/group_action_message.h" #include "plugin/group_replication/include/plugin_messages/recovery_message.h" #include "plugin/group_replication/include/plugin_messages/single_primary_message.h" #include "plugin/group_replication/include/recovery.h" #include "plugin/group_replication/include/services/notification/notification.h" #include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/gcs_communication_event_listener.h" #include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/gcs_control_event_listener.h" /** Group_member_info_pointer_comparator to guarantee uniqueness */ struct Group_member_info_pointer_comparator { bool operator()(Group_member_info *one, Group_member_info *other) const { return one->has_lower_uuid(other); } }; /* @class Plugin_gcs_events_handler Implementation of all GCS event handlers to the plugin */ class Plugin_gcs_events_handler : public Gcs_communication_event_listener, public Gcs_control_event_listener { public: /** Plugin_gcs_events_handler constructor It receives, via the constructor, all the necessary dependencies to work. */ Plugin_gcs_events_handler(Applier_module_interface *applier_module, Recovery_module *recovery_module, Compatibility_module *compatibility_manager, ulong components_stop_timeout); ~Plugin_gcs_events_handler() override; /* Implementation of all callback methods */ void on_message_received(const Gcs_message &message) const override; void on_view_changed(const Gcs_view &new_view, const Exchanged_data &exchanged_data) const override; Gcs_message_data *get_exchangeable_data() const override; void on_suspicions( const std::vector<Gcs_member_identifier> &members, const std::vector<Gcs_member_identifier> &unreachable) const override; /** Sets the component stop timeout. @param[in] timeout the timeout */ void set_stop_wait_timeout(ulong timeout) { stop_wait_timeout = timeout; } /** This function disable read-only mode when member version is compatible with group. @param[in] force_check Compatibility is mandatory re-checked */ void disable_read_mode_for_compatible_members(bool force_check = false) const; private: /* Individual handling methods for all possible message types received via on_message_received(...) */ void handle_transactional_message(const Gcs_message &message) const; void handle_transactional_with_guarantee_message( const Gcs_message &message) const; void handle_transaction_prepared_message(const Gcs_message &message) const; void handle_sync_before_execution_message(const Gcs_message &message) const; void handle_certifier_message(const Gcs_message &message) const; void handle_recovery_message(Plugin_gcs_message *message) const; void handle_stats_message(const Gcs_message &message) const; void handle_single_primary_message( Plugin_gcs_message *processed_message) const; void handle_group_action_message(const Gcs_message &message) const; /** This method passes the message to message listeners @param plugin_message A pointer to the processed plugin gcs message @param message_origin A id of the message originating member @return true if the message should be skipped, false otherwise */ bool pre_process_message(Plugin_gcs_message *plugin_message, const std::string &message_origin) const; /* Methods to act upon members after a on_view_change(...) is called */ int update_group_info_manager(const Gcs_view &new_view, const Exchanged_data &exchanged_data, bool is_joining, bool is_leaving) const; void handle_joining_members(const Gcs_view &new_view, bool is_joining, bool is_leaving) const; void handle_leaving_members(const Gcs_view &new_view, bool is_joining, bool is_leaving) const; /** This method updates the status of the members in the list according to the given parameters. @param members the vector with members to change the status to @param status the status to change to. @param old_equal_to change if the old status is equal to @param old_different_from change if the old status if different from @note When not using the old_equal_to and old_different_from parameters, you can pass the Group_member_info::MEMBER_END value. */ void update_member_status( const std::vector<Gcs_member_identifier> &members, Group_member_info::Group_member_status status, Group_member_info::Group_member_status old_equal_to, Group_member_info::Group_member_status old_different_from) const; /** This method handles the election of a new primary node when the plugin runs in single primary mode. @param election_mode election type @param suggested_primary what should be the next primary to elect @note This function unsets the super read only mode on primary node and sets it on secondary nodes */ void handle_leader_election_if_needed( enum_primary_election_mode election_mode, std::string &suggested_primary) const; int process_local_exchanged_data(const Exchanged_data &exchanged_data, bool is_joining) const; /** Verifies if a certain Vector of Member Ids contains a given member id. @param members the vector with members to verify @param member_id the member to check if it contained. @return true if member_id occurs in members. */ bool is_member_on_vector(const std::vector<Gcs_member_identifier> &members, const Gcs_member_identifier &member_id) const; /** Checks the compatibility of the member with the group. It checks: 1) If the number of members was exceeded 2) If member version is compatible with the group 3) If the gtid_assignment_block_size is equal to the group 4) If the hash algorithm used is equal to the group 5) If the member has more known transactions than the group @param number_of_members the number of members in the new view @retval 0 compatible @retval >0 not compatible with the group */ int check_group_compatibility(size_t number_of_members) const; /** When the member is joining, cycle through all members on group and see if it is compatible with them. @return the compatibility with the group @retval INCOMPATIBLE //Versions not compatible @retval COMPATIBLE //Versions compatible @retval READ_COMPATIBLE //Member can read but not write */ st_compatibility_types check_version_compatibility_with_group() const; /** Method that compares the group's aggregated GTID set against the joiner GTID set. These sets contain executed and received GTIDs present in the relay log files belonging to each member plugin applier channel. @return if the joiner has more GTIDs then the group. @retval 0 Joiner has less GTIDs than the group @retval >0 Joiner has more GTIDS than the group @retval <0 Error when processing GTID information */ int compare_member_transaction_sets() const; /** This method takes all the group executed sets and adds those belonging to non recovering member to the view change packet @param[in] view_packet the view change packet */ void collect_members_executed_sets(View_change_packet *view_packet) const; /** Method that compares the member options with the value of the same option on all other members. It compares: 1) GTID assignment block size 2) Write set hash algorithm @retval 0 Joiner has the same value as all other members @retval !=0 Otherwise */ int compare_member_option_compatibility() const; /** Check if a member is not entering a group where an action is running @retval false no group action is running @retval true a group action is running */ bool is_group_running_a_configuration_change() const; /** Check if the group is running a primary election @retval false no primary election is running @retval true a primary election is running */ bool is_group_running_a_primary_election() const; /** This method checks if member was expelled from the group due to network failures. @param[in] view the view delivered by the GCS @retval true the member was expelled @retval false otherwise */ bool was_member_expelled_from_group(const Gcs_view &view) const; /** Logs member joining message to error logs from view. @param[in] new_view the view delivered by the GCS */ void log_members_joining_message(const Gcs_view &new_view) const; /** Logs member leaving message to error logs from view. @param[in] new_view the view delivered by the GCS */ void log_members_leaving_message(const Gcs_view &new_view) const; /** This function return all members present in vector of Gcs_member_identifier in HOST:PORT format separated by comma. Function also return PRIMARY member if any in HOST:PORT format. @param[in] members joining or leaving members for this view @param[out] all_hosts host and port of all members from view @param[out] primary_host primary member hosts and port of all members from view */ void get_hosts_from_view(const std::vector<Gcs_member_identifier> &members, std::string &all_hosts, std::string &primary_host) const; Applier_module_interface *applier_module; Recovery_module *recovery_module; /* Holds, until view can be installed, all Member information received from other members */ std::set<Group_member_info *, Group_member_info_pointer_comparator> *temporary_states; Compatibility_module *compatibility_manager; /**The status of this member when it joins*/ st_compatibility_types *joiner_compatibility_status; /* Component stop timeout on shutdown */ ulong stop_wait_timeout; #ifndef DBUG_OFF bool set_number_of_members_on_view_changed_to_10; #endif /** The notification context for the GCS delivery thread. */ mutable Notification_context m_notification_ctx; }; #endif /* GCS_EVENT_HANDLERS_INCLUDE */
38.510972
100
0.735368
788fc7573ead5830d19d6faf9eb0493e0c569f44
635
h
C
Wuerfeln.h
gmoehler/wuerfel
1213a0e716d4adb137af54b5deca6502e48af44f
[ "MIT" ]
null
null
null
Wuerfeln.h
gmoehler/wuerfel
1213a0e716d4adb137af54b5deca6502e48af44f
[ "MIT" ]
null
null
null
Wuerfeln.h
gmoehler/wuerfel
1213a0e716d4adb137af54b5deca6502e48af44f
[ "MIT" ]
null
null
null
#ifndef Wuerfeln_h #define Wuerfeln_h #include "Arduino.h" #include <ClickEncoder.h> class Wuerfeln { public: Wuerfeln(); void setup(); void wuerfeln(ClickEncoder::Button b); bool isWuerfelnFinished(); void start(); private: void wuerfeln(); void flimmern(); int zufallszahl(int von, int bis); void alle_aus(); int min_pin; int max_pin; int punkt_mitte; int punkte_diagonal1; int punkte_diagonal2; int punkte_mitte_aussen; // leerer analog pin fuer zufallszahl int analog_input_leer; int wuerfeln_phase; unsigned long pressed_start; }; #endif
16.282051
42
0.669291
925c7b1d91a3a69893f0a9e4860679a25da4ef0a
748
h
C
src/9/ec.h
szhilkin/opensrx-7.0
15482b597c5f4991464150ff01383e7eb2d9675c
[ "BSD-2-Clause" ]
null
null
null
src/9/ec.h
szhilkin/opensrx-7.0
15482b597c5f4991464150ff01383e7eb2d9675c
[ "BSD-2-Clause" ]
null
null
null
src/9/ec.h
szhilkin/opensrx-7.0
15482b597c5f4991464150ff01383e7eb2d9675c
[ "BSD-2-Clause" ]
null
null
null
int ecream(int, char *, int, uvlong, uvlong, int, int); int ecattach(int, char *, uvlong, int, long (*)(Chan *, void *, long, vlong, int), long (*)(int, void *, long, vlong, int, int)); int ecpeek(int, int, uvlong, int); uvlong ecage(int, int, uvlong, int); int ecwrite(int, uvlong, void *, int, int); int ecwritel(int, int, uvlong, void *, int, int); int ecread(int, uvlong, void *, int, int); int ecreadl(int, int, uvlong, void *, int, int); void ecreadopen(int); int ecrdback(int, int *, uvlong *, void *, int, int *, ulong *); int ecclosedev(int, char *); void ecclose(int); void ecinval(int, int); void ecreclaim(int,int); void ecpoison(int); void ecpriority(int, int, int, int); char *eccheck(void); int ecgetbsize(int level, vlong length);
37.4
91
0.667112
435f53134f4344c438451fa43a7cbb632ea6298e
7,227
h
C
Sources_Common/Application/Preferences/CAuthenticator.h
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Sources_Common/Application/Preferences/CAuthenticator.h
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Sources_Common/Application/Preferences/CAuthenticator.h
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // CAuthenticator.h // Class that holds authentication mechanism #ifndef __CAUTHENTICATOR__MULBERRY__ #define __CAUTHENTICATOR__MULBERRY__ #include "CFutureItems.h" #include "cdstring.h" class CAuthPlugin; class CAuthenticator { public: enum EAuthenticators { eNone = 0, ePlainText, eSSL, ePlugin }; CAuthenticator(bool letter = false); CAuthenticator(const CAuthenticator& copy); virtual ~CAuthenticator(); CAuthenticator& operator=(const CAuthenticator& copy); // Assignment with same type int operator==(const CAuthenticator& comp) const; // Compare with same type virtual EAuthenticators GetAuthenticatorType(void) const { return mType; } virtual void SetAuthenticatorType(EAuthenticators type); virtual void ResetAuthenticatorType(EAuthenticators type); virtual cdstring GetSASLID() const; virtual const cdstring& GetDescriptor() const { return mDescriptor; } virtual void SetDescriptor(const cdstring& desc); virtual CAuthenticator* GetAuthenticator(void) const { return mAuthenticator; } virtual CAuthPlugin* GetPlugin() const; virtual bool RequiresUserPswd(void) const { return mAuthenticator->RequiresUserPswd(); } virtual bool RequiresKerberos(void) const { return mAuthenticator->RequiresKerberos(); } virtual cdstring GetUniqueness(void) const // Get string that defines 'uniqueness' of authenticator { return mAuthenticator->GetUniqueness(); } virtual const cdstring& GetActualUID() const { return cdstring::null_str; } virtual cdstring GetInfo(void) const; virtual bool SetInfo(char_stream& info, NumVersion vers_prefs); private: EAuthenticators mType; cdstring mDescriptor; CAuthenticator* mAuthenticator; }; class CAuthenticatorNone : public CAuthenticator { public: CAuthenticatorNone() : CAuthenticator(true) {} CAuthenticatorNone(const CAuthenticatorNone& copy) : CAuthenticator(copy), mFuture(copy.mFuture) { } virtual ~CAuthenticatorNone() {} int operator==(const CAuthenticatorNone& comp) const // Compare with same type { return true; } virtual bool RequiresUserPswd(void) const { return false; } virtual bool RequiresKerberos(void) const { return false; } virtual cdstring GetUniqueness(void) const // Get string that defines 'uniqueness' of authenticator { return cdstring::null_str; } virtual cdstring GetInfo(void) const; virtual bool SetInfo(char_stream& info, NumVersion vers_prefs); private: CFutureItems mFuture; }; class CAuthenticatorUserPswd : public CAuthenticator { public: CAuthenticatorUserPswd() : CAuthenticator(true) { mSaveUID = false; mSavePswd = false; } CAuthenticatorUserPswd(const CAuthenticatorUserPswd& copy) : CAuthenticator(copy), mFuture(copy.mFuture) { mUID = copy.mUID; mPswd = copy.mPswd; mSaveUID = copy.mSaveUID; mSavePswd = copy.mSavePswd; } virtual ~CAuthenticatorUserPswd() {} int operator==(const CAuthenticatorUserPswd& comp) const // Compare with same type { return (mUID == comp.mUID) && (mSaveUID == comp.mSaveUID) && (mSavePswd == comp.mSavePswd); } virtual bool RequiresUserPswd(void) const { return true; } virtual bool RequiresKerberos(void) const { return false; } virtual const cdstring& GetUID(void) const { return mUID; } virtual void SetUID(const cdstring& uid) { if (mUID != uid) {mUID = uid; mPswd = cdstring::null_str; }} // Reset password if UID changes virtual const cdstring& GetPswd(void) const { return mPswd; } virtual void SetPswd(const cdstring& pswd) { mPswd = pswd; } virtual bool GetSaveUID(void) const { return mSaveUID; } virtual void SetSaveUID(bool save_uid) { mSaveUID = save_uid; } virtual bool GetSavePswd(void) const { return mSavePswd; } virtual void SetSavePswd(bool save_pswd) { mSavePswd = save_pswd; } virtual cdstring GetUniqueness(void) const // Get string that defines 'uniqueness' of authenticator { return mUID; } virtual const cdstring& GetActualUID() const { return mUID; } virtual cdstring GetInfo(void) const; virtual bool SetInfo(char_stream& info, NumVersion vers_prefs); private: cdstring mUID; cdstring mPswd; bool mSaveUID; bool mSavePswd; CFutureItems mFuture; // Future preference items }; class CAuthenticatorKerberos : public CAuthenticator { public: CAuthenticatorKerberos() : CAuthenticator(true) { mDefaultPrincipal = true; mDefaultUID = true; } CAuthenticatorKerberos(const CAuthenticatorKerberos& copy) : CAuthenticator(copy), mFuture(copy.mFuture) { mDefaultPrincipal = copy.mDefaultPrincipal; mServerPrincipal = copy.mServerPrincipal; mDefaultUID = copy.mDefaultUID; mUID = copy.mUID; } virtual ~CAuthenticatorKerberos() {} int operator==(const CAuthenticatorKerberos& comp) const // Compare with same type { return (mDefaultPrincipal == comp.mDefaultPrincipal) && (mServerPrincipal == comp.mServerPrincipal) && (mDefaultUID == comp.mDefaultUID) && (mUID == comp.mUID); } virtual bool RequiresUserPswd(void) const { return false; } virtual bool RequiresKerberos(void) const { return true; } virtual bool GetDefaultPrincipal(void) const { return mDefaultPrincipal; } virtual void SetUsePrincipal(bool use_default) { mDefaultPrincipal = use_default; } virtual const cdstring& GetServerPrincipal(void) const { return mServerPrincipal; } virtual void SetServerPrincipal(const cdstring& principal) { mServerPrincipal = principal; } virtual bool GetDefaultUID(void) const { return mDefaultUID; } virtual void SetUseUID(bool use_default) { mDefaultUID = use_default; } virtual const cdstring& GetUID(void) const { return mUID; } virtual void SetUID(const cdstring& uid) { mUID = uid; } virtual const cdstring& GetRecoveredUID() const { return mRecoveredUID; } virtual void SetRecoveredUID(const cdstring& uid) { mRecoveredUID = uid; } virtual cdstring GetUniqueness(void) const // Get string that defines 'uniqueness' of authenticator { return mServerPrincipal + (mDefaultPrincipal ? "1" : "0") + mUID + (mDefaultUID ? "1" : "0"); } virtual const cdstring& GetActualUID() const { return mRecoveredUID; } virtual cdstring GetInfo(void) const; virtual bool SetInfo(char_stream& info, NumVersion vers_prefs); private: bool mDefaultPrincipal; // Use default principal? cdstring mServerPrincipal; // Kerberos Principal bool mDefaultUID; // Use default user id? cdstring mUID; // Server user ID cdstring mRecoveredUID; // UID returned by plugin CFutureItems mFuture; // Future preference items }; #endif
31.285714
108
0.739311
2b1d6d22c89916add1476661b095d706aedb48fb
1,571
c
C
list.c
suraj2439/BigInt-Binary_Calculator
4a2de41799542c439810c0c02c8057df65d97b20
[ "MIT" ]
1
2022-02-03T19:16:03.000Z
2022-02-03T19:16:03.000Z
list.c
suraj2439/BigInt-Binary_Calculator
4a2de41799542c439810c0c02c8057df65d97b20
[ "MIT" ]
null
null
null
list.c
suraj2439/BigInt-Binary_Calculator
4a2de41799542c439810c0c02c8057df65d97b20
[ "MIT" ]
1
2022-02-05T15:11:41.000Z
2022-02-05T15:11:41.000Z
#include "list.h" void init(list *l) { *l = NULL; return; } int isempty(list l){ if(l == NULL) return 1; else return 0; } void destroy_list(list *l){ list_node *p = *l; list_node * q; q = p; while(p){ p = p->next; free(q); } *l = NULL; return ; } void traverse(list l){ printf("["); list_node *p; p = l; while(p){ printf("%d ", p->data); p = p->next; } printf("]\n"); return; } int get_next(list *l){ /*removes and returns 1st element*/ list p = *l; if(!p) return INT_MAX; int k = p->data; *l = p->next; free(p); return k; } int touch(list l) { if(!l) return INT_MAX; return l->data; } void insert_beg(list *l, int d){ list newnode; newnode = (list_node*)malloc(sizeof(list_node)); if(newnode){ newnode->data = d; newnode->next = NULL; } else return; newnode->next = *l; *l = newnode; return; } void append(list *l, int d){ list p, newnode; newnode = (list_node*)malloc(sizeof(list_node)); if(newnode){ newnode->data = d; newnode->next = NULL; } else return; if(*l == NULL){ *l = newnode; return; } p = *l; while(p -> next) { p = p->next; } p->next = newnode; return; } /* int main() { list L1, L2; init(&L1); int ch; while ((ch = getchar()) != '\n') { append(&L1, ch); } traverse(L1); printf("%d\n", peek(L1)); return 0; }*/
15.105769
58
0.47613
9494c5d71af16a238128a1e09ae2b61033aa0f0f
642
h
C
poolfs/poolfs/includes/nonpagedpool_utils.h
cbwang505/poolfengshui
5ed2c49fe54b66af7718b05d9699aebd2fb45a54
[ "Apache-2.0" ]
52
2021-12-31T05:18:39.000Z
2022-01-25T21:21:26.000Z
poolfs/poolfs/includes/nonpagedpool_utils.h
ALEHACKsp/poolfengshui
5ed2c49fe54b66af7718b05d9699aebd2fb45a54
[ "Apache-2.0" ]
null
null
null
poolfs/poolfs/includes/nonpagedpool_utils.h
ALEHACKsp/poolfengshui
5ed2c49fe54b66af7718b05d9699aebd2fb45a54
[ "Apache-2.0" ]
16
2021-12-31T05:19:21.000Z
2022-03-10T01:57:53.000Z
#ifndef NONPAGEDPOOL_UTILS_H #define NONPAGEDPOOL_UTILS_H #include "exploit.h" #include "pipe_utils.h" int npp_get_leak(xploit_t * xploit, pipe_spray_t * respray); void npp_setup_ghost_overwrite(xploit_t * xploit, char * ghost_overwrite_buf); void npp_alloc_ghost_chunk(xploit_t * xploit, char * buffer); void npp_alloc_fake_eprocess(xploit_t * xploit, char * fake_eprocess_buf); void npp_exploit_arbitrary_read(xploit_t * xploit, uintptr_t where, char * out, size_t size); void npp_free_ghost_chunk(xploit_t * xploit); void npp_setup_final_write(xploit_t * xploit, char * buffer); uintptr_t npp_find_file_object(xploit_t * xploit); #endif
40.125
93
0.809969
9ee5be2472b118c0e374079e93d7ec54ba4919f2
6,434
h
C
System/Library/PrivateFrameworks/PhotosGraph.framework/PGPotentialMemory.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
5
2021-04-29T04:31:43.000Z
2021-08-19T18:59:58.000Z
System/Library/PrivateFrameworks/PhotosGraph.framework/PGPotentialMemory.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/PhotosGraph.framework/PGPotentialMemory.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
1
2022-03-19T11:16:23.000Z
2022-03-19T11:16:23.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 28, 2021 at 9:12:08 PM Mountain Standard Time * Operating System: Version 14.5 (Build 18L204) * Image Source: /System/Library/PrivateFrameworks/PhotosGraph.framework/PhotosGraph * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @class PHAssetCollection, PGGraphMomentNode, NSSet, NSDate, CLLocation, NSString, NSDictionary, PGMemoryGenerator; @interface PGPotentialMemory : NSObject { PHAssetCollection* _assetCollection; PGGraphMomentNode* _momentNode; NSSet* _momentNodes; long long _sourceType; unsigned long long _category; unsigned long long _subcategory; double _score; NSDate* _localDate; CLLocation* _location; NSSet* _peopleUUIDs; NSString* _eventName; double _contentScore; NSDate* _localStartDate; NSDate* _localEndDate; NSDate* _universalStartDate; NSDate* _universalEndDate; NSSet* _features; NSSet* _momentIDs; NSDictionary* _numberOfAssetsByMomentIDs; PGPotentialMemory* _upgradedPotentialMemory; PGMemoryGenerator* _upgradedMemoryGenerator; } @property (retain) PHAssetCollection * assetCollection; //@synthesize assetCollection=_assetCollection - In the implementation block @property (retain) PGGraphMomentNode * momentNode; //@synthesize momentNode=_momentNode - In the implementation block @property (retain) NSSet * momentNodes; //@synthesize momentNodes=_momentNodes - In the implementation block @property (assign) long long sourceType; //@synthesize sourceType=_sourceType - In the implementation block @property (assign) unsigned long long category; //@synthesize category=_category - In the implementation block @property (assign) unsigned long long subcategory; //@synthesize subcategory=_subcategory - In the implementation block @property (assign) double score; //@synthesize score=_score - In the implementation block @property (retain) NSDate * localDate; //@synthesize localDate=_localDate - In the implementation block @property (retain) CLLocation * location; //@synthesize location=_location - In the implementation block @property (retain) NSSet * peopleUUIDs; //@synthesize peopleUUIDs=_peopleUUIDs - In the implementation block @property (retain) NSString * eventName; //@synthesize eventName=_eventName - In the implementation block @property (assign) double contentScore; //@synthesize contentScore=_contentScore - In the implementation block @property (retain) NSSet * features; //@synthesize features=_features - In the implementation block @property (readonly) NSDate * localStartDate; //@synthesize localStartDate=_localStartDate - In the implementation block @property (readonly) NSDate * localEndDate; //@synthesize localEndDate=_localEndDate - In the implementation block @property (readonly) NSDate * universalStartDate; //@synthesize universalStartDate=_universalStartDate - In the implementation block @property (readonly) NSDate * universalEndDate; //@synthesize universalEndDate=_universalEndDate - In the implementation block @property (readonly) NSSet * momentIDs; //@synthesize momentIDs=_momentIDs - In the implementation block @property (readonly) NSDictionary * numberOfAssetsByMomentIDs; //@synthesize numberOfAssetsByMomentIDs=_numberOfAssetsByMomentIDs - In the implementation block @property (nonatomic,retain) PGPotentialMemory * upgradedPotentialMemory; //@synthesize upgradedPotentialMemory=_upgradedPotentialMemory - In the implementation block @property (nonatomic,retain) PGMemoryGenerator * upgradedMemoryGenerator; //@synthesize upgradedMemoryGenerator=_upgradedMemoryGenerator - In the implementation block -(unsigned long long)category; -(void)setCategory:(unsigned long long)arg1 ; -(double)score; -(long long)sourceType; -(NSSet *)features; -(CLLocation *)location; -(void)setLocation:(CLLocation *)arg1 ; -(void)setScore:(double)arg1 ; -(void)setFeatures:(NSSet *)arg1 ; -(NSString *)eventName; -(void)setEventName:(NSString *)arg1 ; -(void)setSourceType:(long long)arg1 ; -(unsigned long long)subcategory; -(void)setSubcategory:(unsigned long long)arg1 ; -(NSDate *)localStartDate; -(NSDate *)localEndDate; -(NSDate *)universalStartDate; -(NSDate *)universalEndDate; -(PHAssetCollection *)assetCollection; -(void)setAssetCollection:(PHAssetCollection *)arg1 ; -(void)setContentScore:(double)arg1 ; -(double)contentScore; -(NSSet *)momentIDs; -(NSSet *)peopleUUIDs; -(NSSet *)momentNodes; -(void)setMomentNodes:(NSSet *)arg1 ; -(NSDate *)localDate; -(void)setLocalDate:(NSDate *)arg1 ; -(NSDictionary *)numberOfAssetsByMomentIDs; -(PGGraphMomentNode *)momentNode; -(id)initWithCategory:(unsigned long long)arg1 subcategory:(unsigned long long)arg2 momentNodes:(id)arg3 sourceType:(long long)arg4 ; -(void)setMomentNode:(PGGraphMomentNode *)arg1 ; -(void)setPeopleUUIDs:(NSSet *)arg1 ; -(id)initWithCategory:(unsigned long long)arg1 subcategory:(unsigned long long)arg2 ; -(id)initWithCategory:(unsigned long long)arg1 subcategory:(unsigned long long)arg2 momentNode:(id)arg3 ; -(void)_prepareForOverlapCheck; -(void)_resetOverlapCheck; -(double)computeContentScoreUsingMemoryController:(id)arg1 ; -(id)buildAssetCollectionUsingMemoryController:(id)arg1 withMinimumNumberOfAssets:(unsigned long long)arg2 ; -(PGPotentialMemory *)upgradedPotentialMemory; -(void)setUpgradedPotentialMemory:(PGPotentialMemory *)arg1 ; -(PGMemoryGenerator *)upgradedMemoryGenerator; -(void)setUpgradedMemoryGenerator:(PGMemoryGenerator *)arg1 ; @end
61.865385
183
0.681536
9ef25230c1995400de4149cf8b91989e0e933d56
61,459
c
C
linux-5.2/drivers/crypto/s5p-sss.c
TakuKitamura/expirefile-syscall
2b91994a7fe984e146d090fc7d80fa1a698025aa
[ "MIT" ]
1
2022-01-30T20:01:25.000Z
2022-01-30T20:01:25.000Z
linux-5.2/drivers/crypto/s5p-sss.c
TakuKitamura/expirefile-syscall
2b91994a7fe984e146d090fc7d80fa1a698025aa
[ "MIT" ]
null
null
null
linux-5.2/drivers/crypto/s5p-sss.c
TakuKitamura/expirefile-syscall
2b91994a7fe984e146d090fc7d80fa1a698025aa
[ "MIT" ]
1
2019-10-11T07:35:58.000Z
2019-10-11T07:35:58.000Z
// SPDX-License-Identifier: GPL-2.0 // // Cryptographic API. // // Support for Samsung S5PV210 and Exynos HW acceleration. // // Copyright (C) 2011 NetUP Inc. All rights reserved. // Copyright (c) 2017 Samsung Electronics Co., Ltd. All rights reserved. // // Hash part based on omap-sham.c driver. #include <linux/clk.h> #include <linux/crypto.h> #include <linux/dma-mapping.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/scatterlist.h> #include <crypto/ctr.h> #include <crypto/aes.h> #include <crypto/algapi.h> #include <crypto/scatterwalk.h> #include <crypto/hash.h> #include <crypto/md5.h> #include <crypto/sha.h> #include <crypto/internal/hash.h> #define _SBF(s, v) ((v) << (s)) /* Feed control registers */ #define SSS_REG_FCINTSTAT 0x0000 #define SSS_FCINTSTAT_HPARTINT BIT(7) #define SSS_FCINTSTAT_HDONEINT BIT(5) #define SSS_FCINTSTAT_BRDMAINT BIT(3) #define SSS_FCINTSTAT_BTDMAINT BIT(2) #define SSS_FCINTSTAT_HRDMAINT BIT(1) #define SSS_FCINTSTAT_PKDMAINT BIT(0) #define SSS_REG_FCINTENSET 0x0004 #define SSS_FCINTENSET_HPARTINTENSET BIT(7) #define SSS_FCINTENSET_HDONEINTENSET BIT(5) #define SSS_FCINTENSET_BRDMAINTENSET BIT(3) #define SSS_FCINTENSET_BTDMAINTENSET BIT(2) #define SSS_FCINTENSET_HRDMAINTENSET BIT(1) #define SSS_FCINTENSET_PKDMAINTENSET BIT(0) #define SSS_REG_FCINTENCLR 0x0008 #define SSS_FCINTENCLR_HPARTINTENCLR BIT(7) #define SSS_FCINTENCLR_HDONEINTENCLR BIT(5) #define SSS_FCINTENCLR_BRDMAINTENCLR BIT(3) #define SSS_FCINTENCLR_BTDMAINTENCLR BIT(2) #define SSS_FCINTENCLR_HRDMAINTENCLR BIT(1) #define SSS_FCINTENCLR_PKDMAINTENCLR BIT(0) #define SSS_REG_FCINTPEND 0x000C #define SSS_FCINTPEND_HPARTINTP BIT(7) #define SSS_FCINTPEND_HDONEINTP BIT(5) #define SSS_FCINTPEND_BRDMAINTP BIT(3) #define SSS_FCINTPEND_BTDMAINTP BIT(2) #define SSS_FCINTPEND_HRDMAINTP BIT(1) #define SSS_FCINTPEND_PKDMAINTP BIT(0) #define SSS_REG_FCFIFOSTAT 0x0010 #define SSS_FCFIFOSTAT_BRFIFOFUL BIT(7) #define SSS_FCFIFOSTAT_BRFIFOEMP BIT(6) #define SSS_FCFIFOSTAT_BTFIFOFUL BIT(5) #define SSS_FCFIFOSTAT_BTFIFOEMP BIT(4) #define SSS_FCFIFOSTAT_HRFIFOFUL BIT(3) #define SSS_FCFIFOSTAT_HRFIFOEMP BIT(2) #define SSS_FCFIFOSTAT_PKFIFOFUL BIT(1) #define SSS_FCFIFOSTAT_PKFIFOEMP BIT(0) #define SSS_REG_FCFIFOCTRL 0x0014 #define SSS_FCFIFOCTRL_DESSEL BIT(2) #define SSS_HASHIN_INDEPENDENT _SBF(0, 0x00) #define SSS_HASHIN_CIPHER_INPUT _SBF(0, 0x01) #define SSS_HASHIN_CIPHER_OUTPUT _SBF(0, 0x02) #define SSS_HASHIN_MASK _SBF(0, 0x03) #define SSS_REG_FCBRDMAS 0x0020 #define SSS_REG_FCBRDMAL 0x0024 #define SSS_REG_FCBRDMAC 0x0028 #define SSS_FCBRDMAC_BYTESWAP BIT(1) #define SSS_FCBRDMAC_FLUSH BIT(0) #define SSS_REG_FCBTDMAS 0x0030 #define SSS_REG_FCBTDMAL 0x0034 #define SSS_REG_FCBTDMAC 0x0038 #define SSS_FCBTDMAC_BYTESWAP BIT(1) #define SSS_FCBTDMAC_FLUSH BIT(0) #define SSS_REG_FCHRDMAS 0x0040 #define SSS_REG_FCHRDMAL 0x0044 #define SSS_REG_FCHRDMAC 0x0048 #define SSS_FCHRDMAC_BYTESWAP BIT(1) #define SSS_FCHRDMAC_FLUSH BIT(0) #define SSS_REG_FCPKDMAS 0x0050 #define SSS_REG_FCPKDMAL 0x0054 #define SSS_REG_FCPKDMAC 0x0058 #define SSS_FCPKDMAC_BYTESWAP BIT(3) #define SSS_FCPKDMAC_DESCEND BIT(2) #define SSS_FCPKDMAC_TRANSMIT BIT(1) #define SSS_FCPKDMAC_FLUSH BIT(0) #define SSS_REG_FCPKDMAO 0x005C /* AES registers */ #define SSS_REG_AES_CONTROL 0x00 #define SSS_AES_BYTESWAP_DI BIT(11) #define SSS_AES_BYTESWAP_DO BIT(10) #define SSS_AES_BYTESWAP_IV BIT(9) #define SSS_AES_BYTESWAP_CNT BIT(8) #define SSS_AES_BYTESWAP_KEY BIT(7) #define SSS_AES_KEY_CHANGE_MODE BIT(6) #define SSS_AES_KEY_SIZE_128 _SBF(4, 0x00) #define SSS_AES_KEY_SIZE_192 _SBF(4, 0x01) #define SSS_AES_KEY_SIZE_256 _SBF(4, 0x02) #define SSS_AES_FIFO_MODE BIT(3) #define SSS_AES_CHAIN_MODE_ECB _SBF(1, 0x00) #define SSS_AES_CHAIN_MODE_CBC _SBF(1, 0x01) #define SSS_AES_CHAIN_MODE_CTR _SBF(1, 0x02) #define SSS_AES_MODE_DECRYPT BIT(0) #define SSS_REG_AES_STATUS 0x04 #define SSS_AES_BUSY BIT(2) #define SSS_AES_INPUT_READY BIT(1) #define SSS_AES_OUTPUT_READY BIT(0) #define SSS_REG_AES_IN_DATA(s) (0x10 + (s << 2)) #define SSS_REG_AES_OUT_DATA(s) (0x20 + (s << 2)) #define SSS_REG_AES_IV_DATA(s) (0x30 + (s << 2)) #define SSS_REG_AES_CNT_DATA(s) (0x40 + (s << 2)) #define SSS_REG_AES_KEY_DATA(s) (0x80 + (s << 2)) #define SSS_REG(dev, reg) ((dev)->ioaddr + (SSS_REG_##reg)) #define SSS_READ(dev, reg) __raw_readl(SSS_REG(dev, reg)) #define SSS_WRITE(dev, reg, val) __raw_writel((val), SSS_REG(dev, reg)) #define SSS_AES_REG(dev, reg) ((dev)->aes_ioaddr + SSS_REG_##reg) #define SSS_AES_WRITE(dev, reg, val) __raw_writel((val), \ SSS_AES_REG(dev, reg)) /* HW engine modes */ #define FLAGS_AES_DECRYPT BIT(0) #define FLAGS_AES_MODE_MASK _SBF(1, 0x03) #define FLAGS_AES_CBC _SBF(1, 0x01) #define FLAGS_AES_CTR _SBF(1, 0x02) #define AES_KEY_LEN 16 #define CRYPTO_QUEUE_LEN 1 /* HASH registers */ #define SSS_REG_HASH_CTRL 0x00 #define SSS_HASH_USER_IV_EN BIT(5) #define SSS_HASH_INIT_BIT BIT(4) #define SSS_HASH_ENGINE_SHA1 _SBF(1, 0x00) #define SSS_HASH_ENGINE_MD5 _SBF(1, 0x01) #define SSS_HASH_ENGINE_SHA256 _SBF(1, 0x02) #define SSS_HASH_ENGINE_MASK _SBF(1, 0x03) #define SSS_REG_HASH_CTRL_PAUSE 0x04 #define SSS_HASH_PAUSE BIT(0) #define SSS_REG_HASH_CTRL_FIFO 0x08 #define SSS_HASH_FIFO_MODE_DMA BIT(0) #define SSS_HASH_FIFO_MODE_CPU 0 #define SSS_REG_HASH_CTRL_SWAP 0x0C #define SSS_HASH_BYTESWAP_DI BIT(3) #define SSS_HASH_BYTESWAP_DO BIT(2) #define SSS_HASH_BYTESWAP_IV BIT(1) #define SSS_HASH_BYTESWAP_KEY BIT(0) #define SSS_REG_HASH_STATUS 0x10 #define SSS_HASH_STATUS_MSG_DONE BIT(6) #define SSS_HASH_STATUS_PARTIAL_DONE BIT(4) #define SSS_HASH_STATUS_BUFFER_READY BIT(0) #define SSS_REG_HASH_MSG_SIZE_LOW 0x20 #define SSS_REG_HASH_MSG_SIZE_HIGH 0x24 #define SSS_REG_HASH_PRE_MSG_SIZE_LOW 0x28 #define SSS_REG_HASH_PRE_MSG_SIZE_HIGH 0x2C #define SSS_REG_HASH_IV(s) (0xB0 + ((s) << 2)) #define SSS_REG_HASH_OUT(s) (0x100 + ((s) << 2)) #define HASH_BLOCK_SIZE 64 #define HASH_REG_SIZEOF 4 #define HASH_MD5_MAX_REG (MD5_DIGEST_SIZE / HASH_REG_SIZEOF) #define HASH_SHA1_MAX_REG (SHA1_DIGEST_SIZE / HASH_REG_SIZEOF) #define HASH_SHA256_MAX_REG (SHA256_DIGEST_SIZE / HASH_REG_SIZEOF) /* * HASH bit numbers, used by device, setting in dev->hash_flags with * functions set_bit(), clear_bit() or tested with test_bit() or BIT(), * to keep HASH state BUSY or FREE, or to signal state from irq_handler * to hash_tasklet. SGS keep track of allocated memory for scatterlist */ #define HASH_FLAGS_BUSY 0 #define HASH_FLAGS_FINAL 1 #define HASH_FLAGS_DMA_ACTIVE 2 #define HASH_FLAGS_OUTPUT_READY 3 #define HASH_FLAGS_DMA_READY 4 #define HASH_FLAGS_SGS_COPIED 5 #define HASH_FLAGS_SGS_ALLOCED 6 /* HASH HW constants */ #define BUFLEN HASH_BLOCK_SIZE #define SSS_HASH_DMA_LEN_ALIGN 8 #define SSS_HASH_DMA_ALIGN_MASK (SSS_HASH_DMA_LEN_ALIGN - 1) #define SSS_HASH_QUEUE_LENGTH 10 /** * struct samsung_aes_variant - platform specific SSS driver data * @aes_offset: AES register offset from SSS module's base. * @hash_offset: HASH register offset from SSS module's base. * @clk_names: names of clocks needed to run SSS IP * * Specifies platform specific configuration of SSS module. * Note: A structure for driver specific platform data is used for future * expansion of its usage. */ struct samsung_aes_variant { unsigned int aes_offset; unsigned int hash_offset; const char *clk_names[2]; }; struct s5p_aes_reqctx { unsigned long mode; }; struct s5p_aes_ctx { struct s5p_aes_dev *dev; u8 aes_key[AES_MAX_KEY_SIZE]; u8 nonce[CTR_RFC3686_NONCE_SIZE]; int keylen; }; /** * struct s5p_aes_dev - Crypto device state container * @dev: Associated device * @clk: Clock for accessing hardware * @ioaddr: Mapped IO memory region * @aes_ioaddr: Per-varian offset for AES block IO memory * @irq_fc: Feed control interrupt line * @req: Crypto request currently handled by the device * @ctx: Configuration for currently handled crypto request * @sg_src: Scatter list with source data for currently handled block * in device. This is DMA-mapped into device. * @sg_dst: Scatter list with destination data for currently handled block * in device. This is DMA-mapped into device. * @sg_src_cpy: In case of unaligned access, copied scatter list * with source data. * @sg_dst_cpy: In case of unaligned access, copied scatter list * with destination data. * @tasklet: New request scheduling jib * @queue: Crypto queue * @busy: Indicates whether the device is currently handling some request * thus it uses some of the fields from this state, like: * req, ctx, sg_src/dst (and copies). This essentially * protects against concurrent access to these fields. * @lock: Lock for protecting both access to device hardware registers * and fields related to current request (including the busy field). * @res: Resources for hash. * @io_hash_base: Per-variant offset for HASH block IO memory. * @hash_lock: Lock for protecting hash_req, hash_queue and hash_flags * variable. * @hash_flags: Flags for current HASH op. * @hash_queue: Async hash queue. * @hash_tasklet: New HASH request scheduling job. * @xmit_buf: Buffer for current HASH request transfer into SSS block. * @hash_req: Current request sending to SSS HASH block. * @hash_sg_iter: Scatterlist transferred through DMA into SSS HASH block. * @hash_sg_cnt: Counter for hash_sg_iter. * * @use_hash: true if HASH algs enabled */ struct s5p_aes_dev { struct device *dev; struct clk *clk; struct clk *pclk; void __iomem *ioaddr; void __iomem *aes_ioaddr; int irq_fc; struct ablkcipher_request *req; struct s5p_aes_ctx *ctx; struct scatterlist *sg_src; struct scatterlist *sg_dst; struct scatterlist *sg_src_cpy; struct scatterlist *sg_dst_cpy; struct tasklet_struct tasklet; struct crypto_queue queue; bool busy; spinlock_t lock; struct resource *res; void __iomem *io_hash_base; spinlock_t hash_lock; /* protect hash_ vars */ unsigned long hash_flags; struct crypto_queue hash_queue; struct tasklet_struct hash_tasklet; u8 xmit_buf[BUFLEN]; struct ahash_request *hash_req; struct scatterlist *hash_sg_iter; unsigned int hash_sg_cnt; bool use_hash; }; /** * struct s5p_hash_reqctx - HASH request context * @dd: Associated device * @op_update: Current request operation (OP_UPDATE or OP_FINAL) * @digcnt: Number of bytes processed by HW (without buffer[] ones) * @digest: Digest message or IV for partial result * @nregs: Number of HW registers for digest or IV read/write * @engine: Bits for selecting type of HASH in SSS block * @sg: sg for DMA transfer * @sg_len: Length of sg for DMA transfer * @sgl[]: sg for joining buffer and req->src scatterlist * @skip: Skip offset in req->src for current op * @total: Total number of bytes for current request * @finup: Keep state for finup or final. * @error: Keep track of error. * @bufcnt: Number of bytes holded in buffer[] * @buffer[]: For byte(s) from end of req->src in UPDATE op */ struct s5p_hash_reqctx { struct s5p_aes_dev *dd; bool op_update; u64 digcnt; u8 digest[SHA256_DIGEST_SIZE]; unsigned int nregs; /* digest_size / sizeof(reg) */ u32 engine; struct scatterlist *sg; unsigned int sg_len; struct scatterlist sgl[2]; unsigned int skip; unsigned int total; bool finup; bool error; u32 bufcnt; u8 buffer[0]; }; /** * struct s5p_hash_ctx - HASH transformation context * @dd: Associated device * @flags: Bits for algorithm HASH. * @fallback: Software transformation for zero message or size < BUFLEN. */ struct s5p_hash_ctx { struct s5p_aes_dev *dd; unsigned long flags; struct crypto_shash *fallback; }; static const struct samsung_aes_variant s5p_aes_data = { .aes_offset = 0x4000, .hash_offset = 0x6000, .clk_names = { "secss", }, }; static const struct samsung_aes_variant exynos_aes_data = { .aes_offset = 0x200, .hash_offset = 0x400, .clk_names = { "secss", }, }; static const struct samsung_aes_variant exynos5433_slim_aes_data = { .aes_offset = 0x400, .hash_offset = 0x800, .clk_names = { "pclk", "aclk", }, }; static const struct of_device_id s5p_sss_dt_match[] = { { .compatible = "samsung,s5pv210-secss", .data = &s5p_aes_data, }, { .compatible = "samsung,exynos4210-secss", .data = &exynos_aes_data, }, { .compatible = "samsung,exynos5433-slim-sss", .data = &exynos5433_slim_aes_data, }, { }, }; MODULE_DEVICE_TABLE(of, s5p_sss_dt_match); static inline const struct samsung_aes_variant *find_s5p_sss_version (const struct platform_device *pdev) { if (IS_ENABLED(CONFIG_OF) && (pdev->dev.of_node)) { const struct of_device_id *match; match = of_match_node(s5p_sss_dt_match, pdev->dev.of_node); return (const struct samsung_aes_variant *)match->data; } return (const struct samsung_aes_variant *) platform_get_device_id(pdev)->driver_data; } static struct s5p_aes_dev *s5p_dev; static void s5p_set_dma_indata(struct s5p_aes_dev *dev, const struct scatterlist *sg) { SSS_WRITE(dev, FCBRDMAS, sg_dma_address(sg)); SSS_WRITE(dev, FCBRDMAL, sg_dma_len(sg)); } static void s5p_set_dma_outdata(struct s5p_aes_dev *dev, const struct scatterlist *sg) { SSS_WRITE(dev, FCBTDMAS, sg_dma_address(sg)); SSS_WRITE(dev, FCBTDMAL, sg_dma_len(sg)); } static void s5p_free_sg_cpy(struct s5p_aes_dev *dev, struct scatterlist **sg) { int len; if (!*sg) return; len = ALIGN(dev->req->nbytes, AES_BLOCK_SIZE); free_pages((unsigned long)sg_virt(*sg), get_order(len)); kfree(*sg); *sg = NULL; } static void s5p_sg_copy_buf(void *buf, struct scatterlist *sg, unsigned int nbytes, int out) { struct scatter_walk walk; if (!nbytes) return; scatterwalk_start(&walk, sg); scatterwalk_copychunks(buf, &walk, nbytes, out); scatterwalk_done(&walk, out, 0); } static void s5p_sg_done(struct s5p_aes_dev *dev) { struct ablkcipher_request *req = dev->req; struct s5p_aes_reqctx *reqctx = ablkcipher_request_ctx(req); if (dev->sg_dst_cpy) { dev_dbg(dev->dev, "Copying %d bytes of output data back to original place\n", dev->req->nbytes); s5p_sg_copy_buf(sg_virt(dev->sg_dst_cpy), dev->req->dst, dev->req->nbytes, 1); } s5p_free_sg_cpy(dev, &dev->sg_src_cpy); s5p_free_sg_cpy(dev, &dev->sg_dst_cpy); if (reqctx->mode & FLAGS_AES_CBC) memcpy_fromio(req->info, dev->aes_ioaddr + SSS_REG_AES_IV_DATA(0), AES_BLOCK_SIZE); else if (reqctx->mode & FLAGS_AES_CTR) memcpy_fromio(req->info, dev->aes_ioaddr + SSS_REG_AES_CNT_DATA(0), AES_BLOCK_SIZE); } /* Calls the completion. Cannot be called with dev->lock hold. */ static void s5p_aes_complete(struct ablkcipher_request *req, int err) { req->base.complete(&req->base, err); } static void s5p_unset_outdata(struct s5p_aes_dev *dev) { dma_unmap_sg(dev->dev, dev->sg_dst, 1, DMA_FROM_DEVICE); } static void s5p_unset_indata(struct s5p_aes_dev *dev) { dma_unmap_sg(dev->dev, dev->sg_src, 1, DMA_TO_DEVICE); } static int s5p_make_sg_cpy(struct s5p_aes_dev *dev, struct scatterlist *src, struct scatterlist **dst) { void *pages; int len; *dst = kmalloc(sizeof(**dst), GFP_ATOMIC); if (!*dst) return -ENOMEM; len = ALIGN(dev->req->nbytes, AES_BLOCK_SIZE); pages = (void *)__get_free_pages(GFP_ATOMIC, get_order(len)); if (!pages) { kfree(*dst); *dst = NULL; return -ENOMEM; } s5p_sg_copy_buf(pages, src, dev->req->nbytes, 0); sg_init_table(*dst, 1); sg_set_buf(*dst, pages, len); return 0; } static int s5p_set_outdata(struct s5p_aes_dev *dev, struct scatterlist *sg) { if (!sg->length) return -EINVAL; if (!dma_map_sg(dev->dev, sg, 1, DMA_FROM_DEVICE)) return -ENOMEM; dev->sg_dst = sg; return 0; } static int s5p_set_indata(struct s5p_aes_dev *dev, struct scatterlist *sg) { if (!sg->length) return -EINVAL; if (!dma_map_sg(dev->dev, sg, 1, DMA_TO_DEVICE)) return -ENOMEM; dev->sg_src = sg; return 0; } /* * Returns -ERRNO on error (mapping of new data failed). * On success returns: * - 0 if there is no more data, * - 1 if new transmitting (output) data is ready and its address+length * have to be written to device (by calling s5p_set_dma_outdata()). */ static int s5p_aes_tx(struct s5p_aes_dev *dev) { int ret = 0; s5p_unset_outdata(dev); if (!sg_is_last(dev->sg_dst)) { ret = s5p_set_outdata(dev, sg_next(dev->sg_dst)); if (!ret) ret = 1; } return ret; } /* * Returns -ERRNO on error (mapping of new data failed). * On success returns: * - 0 if there is no more data, * - 1 if new receiving (input) data is ready and its address+length * have to be written to device (by calling s5p_set_dma_indata()). */ static int s5p_aes_rx(struct s5p_aes_dev *dev/*, bool *set_dma*/) { int ret = 0; s5p_unset_indata(dev); if (!sg_is_last(dev->sg_src)) { ret = s5p_set_indata(dev, sg_next(dev->sg_src)); if (!ret) ret = 1; } return ret; } static inline u32 s5p_hash_read(struct s5p_aes_dev *dd, u32 offset) { return __raw_readl(dd->io_hash_base + offset); } static inline void s5p_hash_write(struct s5p_aes_dev *dd, u32 offset, u32 value) { __raw_writel(value, dd->io_hash_base + offset); } /** * s5p_set_dma_hashdata() - start DMA with sg * @dev: device * @sg: scatterlist ready to DMA transmit */ static void s5p_set_dma_hashdata(struct s5p_aes_dev *dev, const struct scatterlist *sg) { dev->hash_sg_cnt--; SSS_WRITE(dev, FCHRDMAS, sg_dma_address(sg)); SSS_WRITE(dev, FCHRDMAL, sg_dma_len(sg)); /* DMA starts */ } /** * s5p_hash_rx() - get next hash_sg_iter * @dev: device * * Return: * 2 if there is no more data and it is UPDATE op * 1 if new receiving (input) data is ready and can be written to device * 0 if there is no more data and it is FINAL op */ static int s5p_hash_rx(struct s5p_aes_dev *dev) { if (dev->hash_sg_cnt > 0) { dev->hash_sg_iter = sg_next(dev->hash_sg_iter); return 1; } set_bit(HASH_FLAGS_DMA_READY, &dev->hash_flags); if (test_bit(HASH_FLAGS_FINAL, &dev->hash_flags)) return 0; return 2; } static irqreturn_t s5p_aes_interrupt(int irq, void *dev_id) { struct platform_device *pdev = dev_id; struct s5p_aes_dev *dev = platform_get_drvdata(pdev); struct ablkcipher_request *req; int err_dma_tx = 0; int err_dma_rx = 0; int err_dma_hx = 0; bool tx_end = false; bool hx_end = false; unsigned long flags; u32 status, st_bits; int err; spin_lock_irqsave(&dev->lock, flags); /* * Handle rx or tx interrupt. If there is still data (scatterlist did not * reach end), then map next scatterlist entry. * In case of such mapping error, s5p_aes_complete() should be called. * * If there is no more data in tx scatter list, call s5p_aes_complete() * and schedule new tasklet. * * Handle hx interrupt. If there is still data map next entry. */ status = SSS_READ(dev, FCINTSTAT); if (status & SSS_FCINTSTAT_BRDMAINT) err_dma_rx = s5p_aes_rx(dev); if (status & SSS_FCINTSTAT_BTDMAINT) { if (sg_is_last(dev->sg_dst)) tx_end = true; err_dma_tx = s5p_aes_tx(dev); } if (status & SSS_FCINTSTAT_HRDMAINT) err_dma_hx = s5p_hash_rx(dev); st_bits = status & (SSS_FCINTSTAT_BRDMAINT | SSS_FCINTSTAT_BTDMAINT | SSS_FCINTSTAT_HRDMAINT); /* clear DMA bits */ SSS_WRITE(dev, FCINTPEND, st_bits); /* clear HASH irq bits */ if (status & (SSS_FCINTSTAT_HDONEINT | SSS_FCINTSTAT_HPARTINT)) { /* cannot have both HPART and HDONE */ if (status & SSS_FCINTSTAT_HPARTINT) st_bits = SSS_HASH_STATUS_PARTIAL_DONE; if (status & SSS_FCINTSTAT_HDONEINT) st_bits = SSS_HASH_STATUS_MSG_DONE; set_bit(HASH_FLAGS_OUTPUT_READY, &dev->hash_flags); s5p_hash_write(dev, SSS_REG_HASH_STATUS, st_bits); hx_end = true; /* when DONE or PART, do not handle HASH DMA */ err_dma_hx = 0; } if (err_dma_rx < 0) { err = err_dma_rx; goto error; } if (err_dma_tx < 0) { err = err_dma_tx; goto error; } if (tx_end) { s5p_sg_done(dev); if (err_dma_hx == 1) s5p_set_dma_hashdata(dev, dev->hash_sg_iter); spin_unlock_irqrestore(&dev->lock, flags); s5p_aes_complete(dev->req, 0); /* Device is still busy */ tasklet_schedule(&dev->tasklet); } else { /* * Writing length of DMA block (either receiving or * transmitting) will start the operation immediately, so this * should be done at the end (even after clearing pending * interrupts to not miss the interrupt). */ if (err_dma_tx == 1) s5p_set_dma_outdata(dev, dev->sg_dst); if (err_dma_rx == 1) s5p_set_dma_indata(dev, dev->sg_src); if (err_dma_hx == 1) s5p_set_dma_hashdata(dev, dev->hash_sg_iter); spin_unlock_irqrestore(&dev->lock, flags); } goto hash_irq_end; error: s5p_sg_done(dev); dev->busy = false; req = dev->req; if (err_dma_hx == 1) s5p_set_dma_hashdata(dev, dev->hash_sg_iter); spin_unlock_irqrestore(&dev->lock, flags); s5p_aes_complete(req, err); hash_irq_end: /* * Note about else if: * when hash_sg_iter reaches end and its UPDATE op, * issue SSS_HASH_PAUSE and wait for HPART irq */ if (hx_end) tasklet_schedule(&dev->hash_tasklet); else if (err_dma_hx == 2) s5p_hash_write(dev, SSS_REG_HASH_CTRL_PAUSE, SSS_HASH_PAUSE); return IRQ_HANDLED; } /** * s5p_hash_read_msg() - read message or IV from HW * @req: AHASH request */ static void s5p_hash_read_msg(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); struct s5p_aes_dev *dd = ctx->dd; u32 *hash = (u32 *)ctx->digest; unsigned int i; for (i = 0; i < ctx->nregs; i++) hash[i] = s5p_hash_read(dd, SSS_REG_HASH_OUT(i)); } /** * s5p_hash_write_ctx_iv() - write IV for next partial/finup op. * @dd: device * @ctx: request context */ static void s5p_hash_write_ctx_iv(struct s5p_aes_dev *dd, const struct s5p_hash_reqctx *ctx) { const u32 *hash = (const u32 *)ctx->digest; unsigned int i; for (i = 0; i < ctx->nregs; i++) s5p_hash_write(dd, SSS_REG_HASH_IV(i), hash[i]); } /** * s5p_hash_write_iv() - write IV for next partial/finup op. * @req: AHASH request */ static void s5p_hash_write_iv(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); s5p_hash_write_ctx_iv(ctx->dd, ctx); } /** * s5p_hash_copy_result() - copy digest into req->result * @req: AHASH request */ static void s5p_hash_copy_result(struct ahash_request *req) { const struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); if (!req->result) return; memcpy(req->result, ctx->digest, ctx->nregs * HASH_REG_SIZEOF); } /** * s5p_hash_dma_flush() - flush HASH DMA * @dev: secss device */ static void s5p_hash_dma_flush(struct s5p_aes_dev *dev) { SSS_WRITE(dev, FCHRDMAC, SSS_FCHRDMAC_FLUSH); } /** * s5p_hash_dma_enable() - enable DMA mode for HASH * @dev: secss device * * enable DMA mode for HASH */ static void s5p_hash_dma_enable(struct s5p_aes_dev *dev) { s5p_hash_write(dev, SSS_REG_HASH_CTRL_FIFO, SSS_HASH_FIFO_MODE_DMA); } /** * s5p_hash_irq_disable() - disable irq HASH signals * @dev: secss device * @flags: bitfield with irq's to be disabled */ static void s5p_hash_irq_disable(struct s5p_aes_dev *dev, u32 flags) { SSS_WRITE(dev, FCINTENCLR, flags); } /** * s5p_hash_irq_enable() - enable irq signals * @dev: secss device * @flags: bitfield with irq's to be enabled */ static void s5p_hash_irq_enable(struct s5p_aes_dev *dev, int flags) { SSS_WRITE(dev, FCINTENSET, flags); } /** * s5p_hash_set_flow() - set flow inside SecSS AES/DES with/without HASH * @dev: secss device * @hashflow: HASH stream flow with/without crypto AES/DES */ static void s5p_hash_set_flow(struct s5p_aes_dev *dev, u32 hashflow) { unsigned long flags; u32 flow; spin_lock_irqsave(&dev->lock, flags); flow = SSS_READ(dev, FCFIFOCTRL); flow &= ~SSS_HASHIN_MASK; flow |= hashflow; SSS_WRITE(dev, FCFIFOCTRL, flow); spin_unlock_irqrestore(&dev->lock, flags); } /** * s5p_ahash_dma_init() - enable DMA and set HASH flow inside SecSS * @dev: secss device * @hashflow: HASH stream flow with/without AES/DES * * flush HASH DMA and enable DMA, set HASH stream flow inside SecSS HW, * enable HASH irq's HRDMA, HDONE, HPART */ static void s5p_ahash_dma_init(struct s5p_aes_dev *dev, u32 hashflow) { s5p_hash_irq_disable(dev, SSS_FCINTENCLR_HRDMAINTENCLR | SSS_FCINTENCLR_HDONEINTENCLR | SSS_FCINTENCLR_HPARTINTENCLR); s5p_hash_dma_flush(dev); s5p_hash_dma_enable(dev); s5p_hash_set_flow(dev, hashflow & SSS_HASHIN_MASK); s5p_hash_irq_enable(dev, SSS_FCINTENSET_HRDMAINTENSET | SSS_FCINTENSET_HDONEINTENSET | SSS_FCINTENSET_HPARTINTENSET); } /** * s5p_hash_write_ctrl() - prepare HASH block in SecSS for processing * @dd: secss device * @length: length for request * @final: true if final op * * Prepare SSS HASH block for processing bytes in DMA mode. If it is called * after previous updates, fill up IV words. For final, calculate and set * lengths for HASH so SecSS can finalize hash. For partial, set SSS HASH * length as 2^63 so it will be never reached and set to zero prelow and * prehigh. * * This function does not start DMA transfer. */ static void s5p_hash_write_ctrl(struct s5p_aes_dev *dd, size_t length, bool final) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(dd->hash_req); u32 prelow, prehigh, low, high; u32 configflags, swapflags; u64 tmplen; configflags = ctx->engine | SSS_HASH_INIT_BIT; if (likely(ctx->digcnt)) { s5p_hash_write_ctx_iv(dd, ctx); configflags |= SSS_HASH_USER_IV_EN; } if (final) { /* number of bytes for last part */ low = length; high = 0; /* total number of bits prev hashed */ tmplen = ctx->digcnt * 8; prelow = (u32)tmplen; prehigh = (u32)(tmplen >> 32); } else { prelow = 0; prehigh = 0; low = 0; high = BIT(31); } swapflags = SSS_HASH_BYTESWAP_DI | SSS_HASH_BYTESWAP_DO | SSS_HASH_BYTESWAP_IV | SSS_HASH_BYTESWAP_KEY; s5p_hash_write(dd, SSS_REG_HASH_MSG_SIZE_LOW, low); s5p_hash_write(dd, SSS_REG_HASH_MSG_SIZE_HIGH, high); s5p_hash_write(dd, SSS_REG_HASH_PRE_MSG_SIZE_LOW, prelow); s5p_hash_write(dd, SSS_REG_HASH_PRE_MSG_SIZE_HIGH, prehigh); s5p_hash_write(dd, SSS_REG_HASH_CTRL_SWAP, swapflags); s5p_hash_write(dd, SSS_REG_HASH_CTRL, configflags); } /** * s5p_hash_xmit_dma() - start DMA hash processing * @dd: secss device * @length: length for request * @final: true if final op * * Update digcnt here, as it is needed for finup/final op. */ static int s5p_hash_xmit_dma(struct s5p_aes_dev *dd, size_t length, bool final) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(dd->hash_req); unsigned int cnt; cnt = dma_map_sg(dd->dev, ctx->sg, ctx->sg_len, DMA_TO_DEVICE); if (!cnt) { dev_err(dd->dev, "dma_map_sg error\n"); ctx->error = true; return -EINVAL; } set_bit(HASH_FLAGS_DMA_ACTIVE, &dd->hash_flags); dd->hash_sg_iter = ctx->sg; dd->hash_sg_cnt = cnt; s5p_hash_write_ctrl(dd, length, final); ctx->digcnt += length; ctx->total -= length; /* catch last interrupt */ if (final) set_bit(HASH_FLAGS_FINAL, &dd->hash_flags); s5p_set_dma_hashdata(dd, dd->hash_sg_iter); /* DMA starts */ return -EINPROGRESS; } /** * s5p_hash_copy_sgs() - copy request's bytes into new buffer * @ctx: request context * @sg: source scatterlist request * @new_len: number of bytes to process from sg * * Allocate new buffer, copy data for HASH into it. If there was xmit_buf * filled, copy it first, then copy data from sg into it. Prepare one sgl[0] * with allocated buffer. * * Set bit in dd->hash_flag so we can free it after irq ends processing. */ static int s5p_hash_copy_sgs(struct s5p_hash_reqctx *ctx, struct scatterlist *sg, unsigned int new_len) { unsigned int pages, len; void *buf; len = new_len + ctx->bufcnt; pages = get_order(len); buf = (void *)__get_free_pages(GFP_ATOMIC, pages); if (!buf) { dev_err(ctx->dd->dev, "alloc pages for unaligned case.\n"); ctx->error = true; return -ENOMEM; } if (ctx->bufcnt) memcpy(buf, ctx->dd->xmit_buf, ctx->bufcnt); scatterwalk_map_and_copy(buf + ctx->bufcnt, sg, ctx->skip, new_len, 0); sg_init_table(ctx->sgl, 1); sg_set_buf(ctx->sgl, buf, len); ctx->sg = ctx->sgl; ctx->sg_len = 1; ctx->bufcnt = 0; ctx->skip = 0; set_bit(HASH_FLAGS_SGS_COPIED, &ctx->dd->hash_flags); return 0; } /** * s5p_hash_copy_sg_lists() - copy sg list and make fixes in copy * @ctx: request context * @sg: source scatterlist request * @new_len: number of bytes to process from sg * * Allocate new scatterlist table, copy data for HASH into it. If there was * xmit_buf filled, prepare it first, then copy page, length and offset from * source sg into it, adjusting begin and/or end for skip offset and * hash_later value. * * Resulting sg table will be assigned to ctx->sg. Set flag so we can free * it after irq ends processing. */ static int s5p_hash_copy_sg_lists(struct s5p_hash_reqctx *ctx, struct scatterlist *sg, unsigned int new_len) { unsigned int skip = ctx->skip, n = sg_nents(sg); struct scatterlist *tmp; unsigned int len; if (ctx->bufcnt) n++; ctx->sg = kmalloc_array(n, sizeof(*sg), GFP_KERNEL); if (!ctx->sg) { ctx->error = true; return -ENOMEM; } sg_init_table(ctx->sg, n); tmp = ctx->sg; ctx->sg_len = 0; if (ctx->bufcnt) { sg_set_buf(tmp, ctx->dd->xmit_buf, ctx->bufcnt); tmp = sg_next(tmp); ctx->sg_len++; } while (sg && skip >= sg->length) { skip -= sg->length; sg = sg_next(sg); } while (sg && new_len) { len = sg->length - skip; if (new_len < len) len = new_len; new_len -= len; sg_set_page(tmp, sg_page(sg), len, sg->offset + skip); skip = 0; if (new_len <= 0) sg_mark_end(tmp); tmp = sg_next(tmp); ctx->sg_len++; sg = sg_next(sg); } set_bit(HASH_FLAGS_SGS_ALLOCED, &ctx->dd->hash_flags); return 0; } /** * s5p_hash_prepare_sgs() - prepare sg for processing * @ctx: request context * @sg: source scatterlist request * @nbytes: number of bytes to process from sg * @final: final flag * * Check two conditions: (1) if buffers in sg have len aligned data, and (2) * sg table have good aligned elements (list_ok). If one of this checks fails, * then either (1) allocates new buffer for data with s5p_hash_copy_sgs, copy * data into this buffer and prepare request in sgl, or (2) allocates new sg * table and prepare sg elements. * * For digest or finup all conditions can be good, and we may not need any * fixes. */ static int s5p_hash_prepare_sgs(struct s5p_hash_reqctx *ctx, struct scatterlist *sg, unsigned int new_len, bool final) { unsigned int skip = ctx->skip, nbytes = new_len, n = 0; bool aligned = true, list_ok = true; struct scatterlist *sg_tmp = sg; if (!sg || !sg->length || !new_len) return 0; if (skip || !final) list_ok = false; while (nbytes > 0 && sg_tmp) { n++; if (skip >= sg_tmp->length) { skip -= sg_tmp->length; if (!sg_tmp->length) { aligned = false; break; } } else { if (!IS_ALIGNED(sg_tmp->length - skip, BUFLEN)) { aligned = false; break; } if (nbytes < sg_tmp->length - skip) { list_ok = false; break; } nbytes -= sg_tmp->length - skip; skip = 0; } sg_tmp = sg_next(sg_tmp); } if (!aligned) return s5p_hash_copy_sgs(ctx, sg, new_len); else if (!list_ok) return s5p_hash_copy_sg_lists(ctx, sg, new_len); /* * Have aligned data from previous operation and/or current * Note: will enter here only if (digest or finup) and aligned */ if (ctx->bufcnt) { ctx->sg_len = n; sg_init_table(ctx->sgl, 2); sg_set_buf(ctx->sgl, ctx->dd->xmit_buf, ctx->bufcnt); sg_chain(ctx->sgl, 2, sg); ctx->sg = ctx->sgl; ctx->sg_len++; } else { ctx->sg = sg; ctx->sg_len = n; } return 0; } /** * s5p_hash_prepare_request() - prepare request for processing * @req: AHASH request * @update: true if UPDATE op * * Note 1: we can have update flag _and_ final flag at the same time. * Note 2: we enter here when digcnt > BUFLEN (=HASH_BLOCK_SIZE) or * either req->nbytes or ctx->bufcnt + req->nbytes is > BUFLEN or * we have final op */ static int s5p_hash_prepare_request(struct ahash_request *req, bool update) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); bool final = ctx->finup; int xmit_len, hash_later, nbytes; int ret; if (update) nbytes = req->nbytes; else nbytes = 0; ctx->total = nbytes + ctx->bufcnt; if (!ctx->total) return 0; if (nbytes && (!IS_ALIGNED(ctx->bufcnt, BUFLEN))) { /* bytes left from previous request, so fill up to BUFLEN */ int len = BUFLEN - ctx->bufcnt % BUFLEN; if (len > nbytes) len = nbytes; scatterwalk_map_and_copy(ctx->buffer + ctx->bufcnt, req->src, 0, len, 0); ctx->bufcnt += len; nbytes -= len; ctx->skip = len; } else { ctx->skip = 0; } if (ctx->bufcnt) memcpy(ctx->dd->xmit_buf, ctx->buffer, ctx->bufcnt); xmit_len = ctx->total; if (final) { hash_later = 0; } else { if (IS_ALIGNED(xmit_len, BUFLEN)) xmit_len -= BUFLEN; else xmit_len -= xmit_len & (BUFLEN - 1); hash_later = ctx->total - xmit_len; /* copy hash_later bytes from end of req->src */ /* previous bytes are in xmit_buf, so no overwrite */ scatterwalk_map_and_copy(ctx->buffer, req->src, req->nbytes - hash_later, hash_later, 0); } if (xmit_len > BUFLEN) { ret = s5p_hash_prepare_sgs(ctx, req->src, nbytes - hash_later, final); if (ret) return ret; } else { /* have buffered data only */ if (unlikely(!ctx->bufcnt)) { /* first update didn't fill up buffer */ scatterwalk_map_and_copy(ctx->dd->xmit_buf, req->src, 0, xmit_len, 0); } sg_init_table(ctx->sgl, 1); sg_set_buf(ctx->sgl, ctx->dd->xmit_buf, xmit_len); ctx->sg = ctx->sgl; ctx->sg_len = 1; } ctx->bufcnt = hash_later; if (!final) ctx->total = xmit_len; return 0; } /** * s5p_hash_update_dma_stop() - unmap DMA * @dd: secss device * * Unmap scatterlist ctx->sg. */ static void s5p_hash_update_dma_stop(struct s5p_aes_dev *dd) { const struct s5p_hash_reqctx *ctx = ahash_request_ctx(dd->hash_req); dma_unmap_sg(dd->dev, ctx->sg, ctx->sg_len, DMA_TO_DEVICE); clear_bit(HASH_FLAGS_DMA_ACTIVE, &dd->hash_flags); } /** * s5p_hash_finish() - copy calculated digest to crypto layer * @req: AHASH request */ static void s5p_hash_finish(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); struct s5p_aes_dev *dd = ctx->dd; if (ctx->digcnt) s5p_hash_copy_result(req); dev_dbg(dd->dev, "hash_finish digcnt: %lld\n", ctx->digcnt); } /** * s5p_hash_finish_req() - finish request * @req: AHASH request * @err: error */ static void s5p_hash_finish_req(struct ahash_request *req, int err) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); struct s5p_aes_dev *dd = ctx->dd; unsigned long flags; if (test_bit(HASH_FLAGS_SGS_COPIED, &dd->hash_flags)) free_pages((unsigned long)sg_virt(ctx->sg), get_order(ctx->sg->length)); if (test_bit(HASH_FLAGS_SGS_ALLOCED, &dd->hash_flags)) kfree(ctx->sg); ctx->sg = NULL; dd->hash_flags &= ~(BIT(HASH_FLAGS_SGS_ALLOCED) | BIT(HASH_FLAGS_SGS_COPIED)); if (!err && !ctx->error) { s5p_hash_read_msg(req); if (test_bit(HASH_FLAGS_FINAL, &dd->hash_flags)) s5p_hash_finish(req); } else { ctx->error = true; } spin_lock_irqsave(&dd->hash_lock, flags); dd->hash_flags &= ~(BIT(HASH_FLAGS_BUSY) | BIT(HASH_FLAGS_FINAL) | BIT(HASH_FLAGS_DMA_READY) | BIT(HASH_FLAGS_OUTPUT_READY)); spin_unlock_irqrestore(&dd->hash_lock, flags); if (req->base.complete) req->base.complete(&req->base, err); } /** * s5p_hash_handle_queue() - handle hash queue * @dd: device s5p_aes_dev * @req: AHASH request * * If req!=NULL enqueue it on dd->queue, if FLAGS_BUSY is not set on the * device then processes the first request from the dd->queue * * Returns: see s5p_hash_final below. */ static int s5p_hash_handle_queue(struct s5p_aes_dev *dd, struct ahash_request *req) { struct crypto_async_request *async_req, *backlog; struct s5p_hash_reqctx *ctx; unsigned long flags; int err = 0, ret = 0; retry: spin_lock_irqsave(&dd->hash_lock, flags); if (req) ret = ahash_enqueue_request(&dd->hash_queue, req); if (test_bit(HASH_FLAGS_BUSY, &dd->hash_flags)) { spin_unlock_irqrestore(&dd->hash_lock, flags); return ret; } backlog = crypto_get_backlog(&dd->hash_queue); async_req = crypto_dequeue_request(&dd->hash_queue); if (async_req) set_bit(HASH_FLAGS_BUSY, &dd->hash_flags); spin_unlock_irqrestore(&dd->hash_lock, flags); if (!async_req) return ret; if (backlog) backlog->complete(backlog, -EINPROGRESS); req = ahash_request_cast(async_req); dd->hash_req = req; ctx = ahash_request_ctx(req); err = s5p_hash_prepare_request(req, ctx->op_update); if (err || !ctx->total) goto out; dev_dbg(dd->dev, "handling new req, op_update: %u, nbytes: %d\n", ctx->op_update, req->nbytes); s5p_ahash_dma_init(dd, SSS_HASHIN_INDEPENDENT); if (ctx->digcnt) s5p_hash_write_iv(req); /* restore hash IV */ if (ctx->op_update) { /* HASH_OP_UPDATE */ err = s5p_hash_xmit_dma(dd, ctx->total, ctx->finup); if (err != -EINPROGRESS && ctx->finup && !ctx->error) /* no final() after finup() */ err = s5p_hash_xmit_dma(dd, ctx->total, true); } else { /* HASH_OP_FINAL */ err = s5p_hash_xmit_dma(dd, ctx->total, true); } out: if (err != -EINPROGRESS) { /* hash_tasklet_cb will not finish it, so do it here */ s5p_hash_finish_req(req, err); req = NULL; /* * Execute next request immediately if there is anything * in queue. */ goto retry; } return ret; } /** * s5p_hash_tasklet_cb() - hash tasklet * @data: ptr to s5p_aes_dev */ static void s5p_hash_tasklet_cb(unsigned long data) { struct s5p_aes_dev *dd = (struct s5p_aes_dev *)data; if (!test_bit(HASH_FLAGS_BUSY, &dd->hash_flags)) { s5p_hash_handle_queue(dd, NULL); return; } if (test_bit(HASH_FLAGS_DMA_READY, &dd->hash_flags)) { if (test_and_clear_bit(HASH_FLAGS_DMA_ACTIVE, &dd->hash_flags)) { s5p_hash_update_dma_stop(dd); } if (test_and_clear_bit(HASH_FLAGS_OUTPUT_READY, &dd->hash_flags)) { /* hash or semi-hash ready */ clear_bit(HASH_FLAGS_DMA_READY, &dd->hash_flags); goto finish; } } return; finish: /* finish curent request */ s5p_hash_finish_req(dd->hash_req, 0); /* If we are not busy, process next req */ if (!test_bit(HASH_FLAGS_BUSY, &dd->hash_flags)) s5p_hash_handle_queue(dd, NULL); } /** * s5p_hash_enqueue() - enqueue request * @req: AHASH request * @op: operation UPDATE (true) or FINAL (false) * * Returns: see s5p_hash_final below. */ static int s5p_hash_enqueue(struct ahash_request *req, bool op) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); struct s5p_hash_ctx *tctx = crypto_tfm_ctx(req->base.tfm); ctx->op_update = op; return s5p_hash_handle_queue(tctx->dd, req); } /** * s5p_hash_update() - process the hash input data * @req: AHASH request * * If request will fit in buffer, copy it and return immediately * else enqueue it with OP_UPDATE. * * Returns: see s5p_hash_final below. */ static int s5p_hash_update(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); if (!req->nbytes) return 0; if (ctx->bufcnt + req->nbytes <= BUFLEN) { scatterwalk_map_and_copy(ctx->buffer + ctx->bufcnt, req->src, 0, req->nbytes, 0); ctx->bufcnt += req->nbytes; return 0; } return s5p_hash_enqueue(req, true); /* HASH_OP_UPDATE */ } /** * s5p_hash_shash_digest() - calculate shash digest * @tfm: crypto transformation * @flags: tfm flags * @data: input data * @len: length of data * @out: output buffer */ static int s5p_hash_shash_digest(struct crypto_shash *tfm, u32 flags, const u8 *data, unsigned int len, u8 *out) { SHASH_DESC_ON_STACK(shash, tfm); shash->tfm = tfm; return crypto_shash_digest(shash, data, len, out); } /** * s5p_hash_final_shash() - calculate shash digest * @req: AHASH request */ static int s5p_hash_final_shash(struct ahash_request *req) { struct s5p_hash_ctx *tctx = crypto_tfm_ctx(req->base.tfm); struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); return s5p_hash_shash_digest(tctx->fallback, req->base.flags, ctx->buffer, ctx->bufcnt, req->result); } /** * s5p_hash_final() - close up hash and calculate digest * @req: AHASH request * * Note: in final req->src do not have any data, and req->nbytes can be * non-zero. * * If there were no input data processed yet and the buffered hash data is * less than BUFLEN (64) then calculate the final hash immediately by using * SW algorithm fallback. * * Otherwise enqueues the current AHASH request with OP_FINAL operation op * and finalize hash message in HW. Note that if digcnt!=0 then there were * previous update op, so there are always some buffered bytes in ctx->buffer, * which means that ctx->bufcnt!=0 * * Returns: * 0 if the request has been processed immediately, * -EINPROGRESS if the operation has been queued for later execution or is set * to processing by HW, * -EBUSY if queue is full and request should be resubmitted later, * other negative values denotes an error. */ static int s5p_hash_final(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); ctx->finup = true; if (ctx->error) return -EINVAL; /* uncompleted hash is not needed */ if (!ctx->digcnt && ctx->bufcnt < BUFLEN) return s5p_hash_final_shash(req); return s5p_hash_enqueue(req, false); /* HASH_OP_FINAL */ } /** * s5p_hash_finup() - process last req->src and calculate digest * @req: AHASH request containing the last update data * * Return values: see s5p_hash_final above. */ static int s5p_hash_finup(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); int err1, err2; ctx->finup = true; err1 = s5p_hash_update(req); if (err1 == -EINPROGRESS || err1 == -EBUSY) return err1; /* * final() has to be always called to cleanup resources even if * update() failed, except EINPROGRESS or calculate digest for small * size */ err2 = s5p_hash_final(req); return err1 ?: err2; } /** * s5p_hash_init() - initialize AHASH request contex * @req: AHASH request * * Init async hash request context. */ static int s5p_hash_init(struct ahash_request *req) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); struct s5p_hash_ctx *tctx = crypto_ahash_ctx(tfm); ctx->dd = tctx->dd; ctx->error = false; ctx->finup = false; ctx->bufcnt = 0; ctx->digcnt = 0; ctx->total = 0; ctx->skip = 0; dev_dbg(tctx->dd->dev, "init: digest size: %d\n", crypto_ahash_digestsize(tfm)); switch (crypto_ahash_digestsize(tfm)) { case MD5_DIGEST_SIZE: ctx->engine = SSS_HASH_ENGINE_MD5; ctx->nregs = HASH_MD5_MAX_REG; break; case SHA1_DIGEST_SIZE: ctx->engine = SSS_HASH_ENGINE_SHA1; ctx->nregs = HASH_SHA1_MAX_REG; break; case SHA256_DIGEST_SIZE: ctx->engine = SSS_HASH_ENGINE_SHA256; ctx->nregs = HASH_SHA256_MAX_REG; break; default: ctx->error = true; return -EINVAL; } return 0; } /** * s5p_hash_digest - calculate digest from req->src * @req: AHASH request * * Return values: see s5p_hash_final above. */ static int s5p_hash_digest(struct ahash_request *req) { return s5p_hash_init(req) ?: s5p_hash_finup(req); } /** * s5p_hash_cra_init_alg - init crypto alg transformation * @tfm: crypto transformation */ static int s5p_hash_cra_init_alg(struct crypto_tfm *tfm) { struct s5p_hash_ctx *tctx = crypto_tfm_ctx(tfm); const char *alg_name = crypto_tfm_alg_name(tfm); tctx->dd = s5p_dev; /* Allocate a fallback and abort if it failed. */ tctx->fallback = crypto_alloc_shash(alg_name, 0, CRYPTO_ALG_NEED_FALLBACK); if (IS_ERR(tctx->fallback)) { pr_err("fallback alloc fails for '%s'\n", alg_name); return PTR_ERR(tctx->fallback); } crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm), sizeof(struct s5p_hash_reqctx) + BUFLEN); return 0; } /** * s5p_hash_cra_init - init crypto tfm * @tfm: crypto transformation */ static int s5p_hash_cra_init(struct crypto_tfm *tfm) { return s5p_hash_cra_init_alg(tfm); } /** * s5p_hash_cra_exit - exit crypto tfm * @tfm: crypto transformation * * free allocated fallback */ static void s5p_hash_cra_exit(struct crypto_tfm *tfm) { struct s5p_hash_ctx *tctx = crypto_tfm_ctx(tfm); crypto_free_shash(tctx->fallback); tctx->fallback = NULL; } /** * s5p_hash_export - export hash state * @req: AHASH request * @out: buffer for exported state */ static int s5p_hash_export(struct ahash_request *req, void *out) { const struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); memcpy(out, ctx, sizeof(*ctx) + ctx->bufcnt); return 0; } /** * s5p_hash_import - import hash state * @req: AHASH request * @in: buffer with state to be imported from */ static int s5p_hash_import(struct ahash_request *req, const void *in) { struct s5p_hash_reqctx *ctx = ahash_request_ctx(req); struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); struct s5p_hash_ctx *tctx = crypto_ahash_ctx(tfm); const struct s5p_hash_reqctx *ctx_in = in; memcpy(ctx, in, sizeof(*ctx) + BUFLEN); if (ctx_in->bufcnt > BUFLEN) { ctx->error = true; return -EINVAL; } ctx->dd = tctx->dd; ctx->error = false; return 0; } static struct ahash_alg algs_sha1_md5_sha256[] = { { .init = s5p_hash_init, .update = s5p_hash_update, .final = s5p_hash_final, .finup = s5p_hash_finup, .digest = s5p_hash_digest, .export = s5p_hash_export, .import = s5p_hash_import, .halg.statesize = sizeof(struct s5p_hash_reqctx) + BUFLEN, .halg.digestsize = SHA1_DIGEST_SIZE, .halg.base = { .cra_name = "sha1", .cra_driver_name = "exynos-sha1", .cra_priority = 100, .cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK, .cra_blocksize = HASH_BLOCK_SIZE, .cra_ctxsize = sizeof(struct s5p_hash_ctx), .cra_alignmask = SSS_HASH_DMA_ALIGN_MASK, .cra_module = THIS_MODULE, .cra_init = s5p_hash_cra_init, .cra_exit = s5p_hash_cra_exit, } }, { .init = s5p_hash_init, .update = s5p_hash_update, .final = s5p_hash_final, .finup = s5p_hash_finup, .digest = s5p_hash_digest, .export = s5p_hash_export, .import = s5p_hash_import, .halg.statesize = sizeof(struct s5p_hash_reqctx) + BUFLEN, .halg.digestsize = MD5_DIGEST_SIZE, .halg.base = { .cra_name = "md5", .cra_driver_name = "exynos-md5", .cra_priority = 100, .cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK, .cra_blocksize = HASH_BLOCK_SIZE, .cra_ctxsize = sizeof(struct s5p_hash_ctx), .cra_alignmask = SSS_HASH_DMA_ALIGN_MASK, .cra_module = THIS_MODULE, .cra_init = s5p_hash_cra_init, .cra_exit = s5p_hash_cra_exit, } }, { .init = s5p_hash_init, .update = s5p_hash_update, .final = s5p_hash_final, .finup = s5p_hash_finup, .digest = s5p_hash_digest, .export = s5p_hash_export, .import = s5p_hash_import, .halg.statesize = sizeof(struct s5p_hash_reqctx) + BUFLEN, .halg.digestsize = SHA256_DIGEST_SIZE, .halg.base = { .cra_name = "sha256", .cra_driver_name = "exynos-sha256", .cra_priority = 100, .cra_flags = CRYPTO_ALG_KERN_DRIVER_ONLY | CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK, .cra_blocksize = HASH_BLOCK_SIZE, .cra_ctxsize = sizeof(struct s5p_hash_ctx), .cra_alignmask = SSS_HASH_DMA_ALIGN_MASK, .cra_module = THIS_MODULE, .cra_init = s5p_hash_cra_init, .cra_exit = s5p_hash_cra_exit, } } }; static void s5p_set_aes(struct s5p_aes_dev *dev, const u8 *key, const u8 *iv, const u8 *ctr, unsigned int keylen) { void __iomem *keystart; if (iv) memcpy_toio(dev->aes_ioaddr + SSS_REG_AES_IV_DATA(0), iv, AES_BLOCK_SIZE); if (ctr) memcpy_toio(dev->aes_ioaddr + SSS_REG_AES_CNT_DATA(0), ctr, AES_BLOCK_SIZE); if (keylen == AES_KEYSIZE_256) keystart = dev->aes_ioaddr + SSS_REG_AES_KEY_DATA(0); else if (keylen == AES_KEYSIZE_192) keystart = dev->aes_ioaddr + SSS_REG_AES_KEY_DATA(2); else keystart = dev->aes_ioaddr + SSS_REG_AES_KEY_DATA(4); memcpy_toio(keystart, key, keylen); } static bool s5p_is_sg_aligned(struct scatterlist *sg) { while (sg) { if (!IS_ALIGNED(sg->length, AES_BLOCK_SIZE)) return false; sg = sg_next(sg); } return true; } static int s5p_set_indata_start(struct s5p_aes_dev *dev, struct ablkcipher_request *req) { struct scatterlist *sg; int err; dev->sg_src_cpy = NULL; sg = req->src; if (!s5p_is_sg_aligned(sg)) { dev_dbg(dev->dev, "At least one unaligned source scatter list, making a copy\n"); err = s5p_make_sg_cpy(dev, sg, &dev->sg_src_cpy); if (err) return err; sg = dev->sg_src_cpy; } err = s5p_set_indata(dev, sg); if (err) { s5p_free_sg_cpy(dev, &dev->sg_src_cpy); return err; } return 0; } static int s5p_set_outdata_start(struct s5p_aes_dev *dev, struct ablkcipher_request *req) { struct scatterlist *sg; int err; dev->sg_dst_cpy = NULL; sg = req->dst; if (!s5p_is_sg_aligned(sg)) { dev_dbg(dev->dev, "At least one unaligned dest scatter list, making a copy\n"); err = s5p_make_sg_cpy(dev, sg, &dev->sg_dst_cpy); if (err) return err; sg = dev->sg_dst_cpy; } err = s5p_set_outdata(dev, sg); if (err) { s5p_free_sg_cpy(dev, &dev->sg_dst_cpy); return err; } return 0; } static void s5p_aes_crypt_start(struct s5p_aes_dev *dev, unsigned long mode) { struct ablkcipher_request *req = dev->req; u32 aes_control; unsigned long flags; int err; u8 *iv, *ctr; /* This sets bit [13:12] to 00, which selects 128-bit counter */ aes_control = SSS_AES_KEY_CHANGE_MODE; if (mode & FLAGS_AES_DECRYPT) aes_control |= SSS_AES_MODE_DECRYPT; if ((mode & FLAGS_AES_MODE_MASK) == FLAGS_AES_CBC) { aes_control |= SSS_AES_CHAIN_MODE_CBC; iv = req->info; ctr = NULL; } else if ((mode & FLAGS_AES_MODE_MASK) == FLAGS_AES_CTR) { aes_control |= SSS_AES_CHAIN_MODE_CTR; iv = NULL; ctr = req->info; } else { iv = NULL; /* AES_ECB */ ctr = NULL; } if (dev->ctx->keylen == AES_KEYSIZE_192) aes_control |= SSS_AES_KEY_SIZE_192; else if (dev->ctx->keylen == AES_KEYSIZE_256) aes_control |= SSS_AES_KEY_SIZE_256; aes_control |= SSS_AES_FIFO_MODE; /* as a variant it is possible to use byte swapping on DMA side */ aes_control |= SSS_AES_BYTESWAP_DI | SSS_AES_BYTESWAP_DO | SSS_AES_BYTESWAP_IV | SSS_AES_BYTESWAP_KEY | SSS_AES_BYTESWAP_CNT; spin_lock_irqsave(&dev->lock, flags); SSS_WRITE(dev, FCINTENCLR, SSS_FCINTENCLR_BTDMAINTENCLR | SSS_FCINTENCLR_BRDMAINTENCLR); SSS_WRITE(dev, FCFIFOCTRL, 0x00); err = s5p_set_indata_start(dev, req); if (err) goto indata_error; err = s5p_set_outdata_start(dev, req); if (err) goto outdata_error; SSS_AES_WRITE(dev, AES_CONTROL, aes_control); s5p_set_aes(dev, dev->ctx->aes_key, iv, ctr, dev->ctx->keylen); s5p_set_dma_indata(dev, dev->sg_src); s5p_set_dma_outdata(dev, dev->sg_dst); SSS_WRITE(dev, FCINTENSET, SSS_FCINTENSET_BTDMAINTENSET | SSS_FCINTENSET_BRDMAINTENSET); spin_unlock_irqrestore(&dev->lock, flags); return; outdata_error: s5p_unset_indata(dev); indata_error: s5p_sg_done(dev); dev->busy = false; spin_unlock_irqrestore(&dev->lock, flags); s5p_aes_complete(req, err); } static void s5p_tasklet_cb(unsigned long data) { struct s5p_aes_dev *dev = (struct s5p_aes_dev *)data; struct crypto_async_request *async_req, *backlog; struct s5p_aes_reqctx *reqctx; unsigned long flags; spin_lock_irqsave(&dev->lock, flags); backlog = crypto_get_backlog(&dev->queue); async_req = crypto_dequeue_request(&dev->queue); if (!async_req) { dev->busy = false; spin_unlock_irqrestore(&dev->lock, flags); return; } spin_unlock_irqrestore(&dev->lock, flags); if (backlog) backlog->complete(backlog, -EINPROGRESS); dev->req = ablkcipher_request_cast(async_req); dev->ctx = crypto_tfm_ctx(dev->req->base.tfm); reqctx = ablkcipher_request_ctx(dev->req); s5p_aes_crypt_start(dev, reqctx->mode); } static int s5p_aes_handle_req(struct s5p_aes_dev *dev, struct ablkcipher_request *req) { unsigned long flags; int err; spin_lock_irqsave(&dev->lock, flags); err = ablkcipher_enqueue_request(&dev->queue, req); if (dev->busy) { spin_unlock_irqrestore(&dev->lock, flags); return err; } dev->busy = true; spin_unlock_irqrestore(&dev->lock, flags); tasklet_schedule(&dev->tasklet); return err; } static int s5p_aes_crypt(struct ablkcipher_request *req, unsigned long mode) { struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req); struct s5p_aes_reqctx *reqctx = ablkcipher_request_ctx(req); struct s5p_aes_ctx *ctx = crypto_ablkcipher_ctx(tfm); struct s5p_aes_dev *dev = ctx->dev; if (!IS_ALIGNED(req->nbytes, AES_BLOCK_SIZE) && ((mode & FLAGS_AES_MODE_MASK) != FLAGS_AES_CTR)) { dev_err(dev->dev, "request size is not exact amount of AES blocks\n"); return -EINVAL; } reqctx->mode = mode; return s5p_aes_handle_req(dev, req); } static int s5p_aes_setkey(struct crypto_ablkcipher *cipher, const u8 *key, unsigned int keylen) { struct crypto_tfm *tfm = crypto_ablkcipher_tfm(cipher); struct s5p_aes_ctx *ctx = crypto_tfm_ctx(tfm); if (keylen != AES_KEYSIZE_128 && keylen != AES_KEYSIZE_192 && keylen != AES_KEYSIZE_256) return -EINVAL; memcpy(ctx->aes_key, key, keylen); ctx->keylen = keylen; return 0; } static int s5p_aes_ecb_encrypt(struct ablkcipher_request *req) { return s5p_aes_crypt(req, 0); } static int s5p_aes_ecb_decrypt(struct ablkcipher_request *req) { return s5p_aes_crypt(req, FLAGS_AES_DECRYPT); } static int s5p_aes_cbc_encrypt(struct ablkcipher_request *req) { return s5p_aes_crypt(req, FLAGS_AES_CBC); } static int s5p_aes_cbc_decrypt(struct ablkcipher_request *req) { return s5p_aes_crypt(req, FLAGS_AES_DECRYPT | FLAGS_AES_CBC); } static int s5p_aes_ctr_crypt(struct ablkcipher_request *req) { return s5p_aes_crypt(req, FLAGS_AES_CTR); } static int s5p_aes_cra_init(struct crypto_tfm *tfm) { struct s5p_aes_ctx *ctx = crypto_tfm_ctx(tfm); ctx->dev = s5p_dev; tfm->crt_ablkcipher.reqsize = sizeof(struct s5p_aes_reqctx); return 0; } static struct crypto_alg algs[] = { { .cra_name = "ecb(aes)", .cra_driver_name = "ecb-aes-s5p", .cra_priority = 100, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY, .cra_blocksize = AES_BLOCK_SIZE, .cra_ctxsize = sizeof(struct s5p_aes_ctx), .cra_alignmask = 0x0f, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = s5p_aes_cra_init, .cra_u.ablkcipher = { .min_keysize = AES_MIN_KEY_SIZE, .max_keysize = AES_MAX_KEY_SIZE, .setkey = s5p_aes_setkey, .encrypt = s5p_aes_ecb_encrypt, .decrypt = s5p_aes_ecb_decrypt, } }, { .cra_name = "cbc(aes)", .cra_driver_name = "cbc-aes-s5p", .cra_priority = 100, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY, .cra_blocksize = AES_BLOCK_SIZE, .cra_ctxsize = sizeof(struct s5p_aes_ctx), .cra_alignmask = 0x0f, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = s5p_aes_cra_init, .cra_u.ablkcipher = { .min_keysize = AES_MIN_KEY_SIZE, .max_keysize = AES_MAX_KEY_SIZE, .ivsize = AES_BLOCK_SIZE, .setkey = s5p_aes_setkey, .encrypt = s5p_aes_cbc_encrypt, .decrypt = s5p_aes_cbc_decrypt, } }, { .cra_name = "ctr(aes)", .cra_driver_name = "ctr-aes-s5p", .cra_priority = 100, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC | CRYPTO_ALG_KERN_DRIVER_ONLY, .cra_blocksize = AES_BLOCK_SIZE, .cra_ctxsize = sizeof(struct s5p_aes_ctx), .cra_alignmask = 0x0f, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = s5p_aes_cra_init, .cra_u.ablkcipher = { .min_keysize = AES_MIN_KEY_SIZE, .max_keysize = AES_MAX_KEY_SIZE, .ivsize = AES_BLOCK_SIZE, .setkey = s5p_aes_setkey, .encrypt = s5p_aes_ctr_crypt, .decrypt = s5p_aes_ctr_crypt, } }, }; static int s5p_aes_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; int i, j, err = -ENODEV; const struct samsung_aes_variant *variant; struct s5p_aes_dev *pdata; struct resource *res; unsigned int hash_i; if (s5p_dev) return -EEXIST; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return -ENOMEM; variant = find_s5p_sss_version(pdev); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); /* * Note: HASH and PRNG uses the same registers in secss, avoid * overwrite each other. This will drop HASH when CONFIG_EXYNOS_RNG * is enabled in config. We need larger size for HASH registers in * secss, current describe only AES/DES */ if (IS_ENABLED(CONFIG_CRYPTO_DEV_EXYNOS_HASH)) { if (variant == &exynos_aes_data) { res->end += 0x300; pdata->use_hash = true; } } pdata->res = res; pdata->ioaddr = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(pdata->ioaddr)) { if (!pdata->use_hash) return PTR_ERR(pdata->ioaddr); /* try AES without HASH */ res->end -= 0x300; pdata->use_hash = false; pdata->ioaddr = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(pdata->ioaddr)) return PTR_ERR(pdata->ioaddr); } pdata->clk = devm_clk_get(dev, variant->clk_names[0]); if (IS_ERR(pdata->clk)) { dev_err(dev, "failed to find secss clock %s\n", variant->clk_names[0]); return -ENOENT; } err = clk_prepare_enable(pdata->clk); if (err < 0) { dev_err(dev, "Enabling clock %s failed, err %d\n", variant->clk_names[0], err); return err; } if (variant->clk_names[1]) { pdata->pclk = devm_clk_get(dev, variant->clk_names[1]); if (IS_ERR(pdata->pclk)) { dev_err(dev, "failed to find clock %s\n", variant->clk_names[1]); err = -ENOENT; goto err_clk; } err = clk_prepare_enable(pdata->pclk); if (err < 0) { dev_err(dev, "Enabling clock %s failed, err %d\n", variant->clk_names[0], err); goto err_clk; } } else { pdata->pclk = NULL; } spin_lock_init(&pdata->lock); spin_lock_init(&pdata->hash_lock); pdata->aes_ioaddr = pdata->ioaddr + variant->aes_offset; pdata->io_hash_base = pdata->ioaddr + variant->hash_offset; pdata->irq_fc = platform_get_irq(pdev, 0); if (pdata->irq_fc < 0) { err = pdata->irq_fc; dev_warn(dev, "feed control interrupt is not available.\n"); goto err_irq; } err = devm_request_threaded_irq(dev, pdata->irq_fc, NULL, s5p_aes_interrupt, IRQF_ONESHOT, pdev->name, pdev); if (err < 0) { dev_warn(dev, "feed control interrupt is not available.\n"); goto err_irq; } pdata->busy = false; pdata->dev = dev; platform_set_drvdata(pdev, pdata); s5p_dev = pdata; tasklet_init(&pdata->tasklet, s5p_tasklet_cb, (unsigned long)pdata); crypto_init_queue(&pdata->queue, CRYPTO_QUEUE_LEN); for (i = 0; i < ARRAY_SIZE(algs); i++) { err = crypto_register_alg(&algs[i]); if (err) goto err_algs; } if (pdata->use_hash) { tasklet_init(&pdata->hash_tasklet, s5p_hash_tasklet_cb, (unsigned long)pdata); crypto_init_queue(&pdata->hash_queue, SSS_HASH_QUEUE_LENGTH); for (hash_i = 0; hash_i < ARRAY_SIZE(algs_sha1_md5_sha256); hash_i++) { struct ahash_alg *alg; alg = &algs_sha1_md5_sha256[hash_i]; err = crypto_register_ahash(alg); if (err) { dev_err(dev, "can't register '%s': %d\n", alg->halg.base.cra_driver_name, err); goto err_hash; } } } dev_info(dev, "s5p-sss driver registered\n"); return 0; err_hash: for (j = hash_i - 1; j >= 0; j--) crypto_unregister_ahash(&algs_sha1_md5_sha256[j]); tasklet_kill(&pdata->hash_tasklet); res->end -= 0x300; err_algs: if (i < ARRAY_SIZE(algs)) dev_err(dev, "can't register '%s': %d\n", algs[i].cra_name, err); for (j = 0; j < i; j++) crypto_unregister_alg(&algs[j]); tasklet_kill(&pdata->tasklet); err_irq: if (pdata->pclk) clk_disable_unprepare(pdata->pclk); err_clk: clk_disable_unprepare(pdata->clk); s5p_dev = NULL; return err; } static int s5p_aes_remove(struct platform_device *pdev) { struct s5p_aes_dev *pdata = platform_get_drvdata(pdev); int i; if (!pdata) return -ENODEV; for (i = 0; i < ARRAY_SIZE(algs); i++) crypto_unregister_alg(&algs[i]); tasklet_kill(&pdata->tasklet); if (pdata->use_hash) { for (i = ARRAY_SIZE(algs_sha1_md5_sha256) - 1; i >= 0; i--) crypto_unregister_ahash(&algs_sha1_md5_sha256[i]); pdata->res->end -= 0x300; tasklet_kill(&pdata->hash_tasklet); pdata->use_hash = false; } if (pdata->pclk) clk_disable_unprepare(pdata->pclk); clk_disable_unprepare(pdata->clk); s5p_dev = NULL; return 0; } static struct platform_driver s5p_aes_crypto = { .probe = s5p_aes_probe, .remove = s5p_aes_remove, .driver = { .name = "s5p-secss", .of_match_table = s5p_sss_dt_match, }, }; module_platform_driver(s5p_aes_crypto); MODULE_DESCRIPTION("S5PV210 AES hw acceleration support."); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Vladimir Zapolskiy <vzapolskiy@gmail.com>"); MODULE_AUTHOR("Kamil Konieczny <k.konieczny@partner.samsung.com>");
25.629274
86
0.713435
cfd9715833465bd3efd883cad429dea8d7ea9106
3,530
h
C
cbits/include/SIL.h
sfultong/stand-in-language
f664dbdf676200927beed1dd6cb4994a6aabf9e0
[ "Apache-2.0" ]
26
2017-01-26T23:18:09.000Z
2021-02-14T02:39:47.000Z
cbits/include/SIL.h
sfultong/stand-in-language
f664dbdf676200927beed1dd6cb4994a6aabf9e0
[ "Apache-2.0" ]
30
2018-06-12T20:33:29.000Z
2021-06-24T21:00:24.000Z
cbits/include/SIL.h
sfultong/stand-in-language
f664dbdf676200927beed1dd6cb4994a6aabf9e0
[ "Apache-2.0" ]
8
2017-09-07T14:07:33.000Z
2022-01-06T09:47:47.000Z
#ifndef SIL_GUARD #define SIL_GUARD /** * @file SIL.h * @author Mateusz Kłoczko * @date 27 Apr 2018 * @brief Stand-in-language C representation. */ #ifdef __cplusplus extern "C" { #endif // Tags for SIL grammar #define SIL_ZERO (0) #define SIL_PAIR (1) #define SIL_ENV (2) #define SIL_SETENV (3) #define SIL_DEFER (4) #define SIL_TWIDDLE (5) #define SIL_ABORT (6) #define SIL_GATE (7) #define SIL_PLEFT (8) #define SIL_PRIGHT (9) #define SIL_TRACE (10) typedef unsigned char sil_type; //Representation for dynamic construction /* Note [C AST and SIL_Root] * ~~~~~~~~~~~~~~~~~~~~~~~~~ * * The C AST representation is designed to be somewhat memory efficient. * Each expression is a struct, which contains the type and pointer * to next expressions. * * That's why we needed to have SIL_Root - initial entry point, * pointing to the top-most node. */ /** * @brief Stores the top-most expression. Does not exist in grammar. */ typedef struct SIL_Root{ sil_type type; void * value; } SIL_Root; typedef struct SIL_Zero{} SIL_Zero; typedef struct SIL_Pair{ sil_type left_type; sil_type right_type; void * left_value; void * right_value; } SIL_Pair; typedef struct SIL_Env{} SIL_Env; typedef struct SIL_SetEnv{ sil_type type; void * value; } SIL_SetEnv; typedef struct SIL_Defer{ sil_type type; void * value; } SIL_Defer; typedef struct SIL_Twiddle{ sil_type type; void * value; } SIL_Twiddle; typedef struct SIL_Abort{ sil_type type; void * value; } SIL_Abort; typedef struct SIL_Gate{ sil_type type; void * value; } SIL_Gate; typedef struct SIL_PLeft{ sil_type type; void * value; } SIL_PLeft; typedef struct SIL_PRight{ sil_type type; void * value; } SIL_PRight; typedef struct SIL_Trace{ sil_type type; void * value; } SIL_Trace; /** * @brief SIL_Stack nodes. * * Used in sil_traverse, sil_serialize and sil_deserialize */ typedef struct SIL_Stack{ struct SIL_Stack * next; sil_type type; void * value; } SIL_Stack; SIL_Stack* sil_stack_new(sil_type type, void * val); void sil_stack_add(SIL_Stack ** stack, sil_type type, void * val); void sil_stack_pop(SIL_Stack ** stack); /** * @brief Traverse each node and perform a computation based on the node type. Does not change the AST. */ void sil_traverse(SIL_Root * root, void (*fn)(sil_type, void*), void * state); /** * @brief Checks for equality between two ASTs. */ unsigned char sil_equal(SIL_Root * root1, SIL_Root *root2); /** * @brief Count the number of nodes in AST. */ unsigned long sil_count(SIL_Root * root); /** * @brief Delete the memory under SIL AST */ void sil_free(SIL_Root * root); /** * @brief Serialized representation of SIL. * * The representation is somewhat static - it's not possible to * add new nodes. */ typedef struct SIL_Serialized{ unsigned long size; sil_type storage[]; } SIL_Serialized; /** * @brief Serializer state, modified through sil_traverse. Used by sil_serialize. */ typedef struct SIL_Serializer_State{ unsigned long count; SIL_Serialized * serialized; } SIL_Serializer_State; SIL_Serialized * sil_serialize(SIL_Root * root); /** * @brief Deserialize into SIL AST. * * Assumes correct input. Undefined behaviour otherwise. */ SIL_Root * sil_deserialize(SIL_Serialized * serialized); /** * @brief Count the number of nodes in AST. */ unsigned long sil_count_old(SIL_Root * root); #ifdef __cplusplus } #endif #endif
21.26506
103
0.696034
36eb3716ffb005795d39638ba4c6ea385087bf93
3,601
c
C
drivers/clk/bcm/clk-bcm53573-ilp.c
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
drivers/clk/bcm/clk-bcm53573-ilp.c
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
5
2020-04-04T09:24:09.000Z
2020-04-19T12:33:55.000Z
drivers/clk/bcm/clk-bcm53573-ilp.c
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
30
2018-05-02T08:43:27.000Z
2022-01-23T03:25:54.000Z
/* * Copyright (C) 2016 Rafał Miłecki <rafal@milecki.pl> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/clk-provider.h> #include <linux/err.h> #include <linux/io.h> #include <linux/mfd/syscon.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/regmap.h> #include <linux/slab.h> #define PMU_XTAL_FREQ_RATIO 0x66c #define XTAL_ALP_PER_4ILP 0x00001fff #define XTAL_CTL_EN 0x80000000 #define PMU_SLOW_CLK_PERIOD 0x6dc struct bcm53573_ilp { struct clk_hw hw; struct regmap *regmap; }; static int bcm53573_ilp_enable(struct clk_hw *hw) { struct bcm53573_ilp *ilp = container_of(hw, struct bcm53573_ilp, hw); regmap_write(ilp->regmap, PMU_SLOW_CLK_PERIOD, 0x10199); regmap_write(ilp->regmap, 0x674, 0x10000); return 0; } static void bcm53573_ilp_disable(struct clk_hw *hw) { struct bcm53573_ilp *ilp = container_of(hw, struct bcm53573_ilp, hw); regmap_write(ilp->regmap, PMU_SLOW_CLK_PERIOD, 0); regmap_write(ilp->regmap, 0x674, 0); } static unsigned long bcm53573_ilp_recalc_rate(struct clk_hw *hw, unsigned long parent_rate) { struct bcm53573_ilp *ilp = container_of(hw, struct bcm53573_ilp, hw); struct regmap *regmap = ilp->regmap; u32 last_val, cur_val; int sum = 0, num = 0, loop_num = 0; int avg; /* Enable measurement */ regmap_write(regmap, PMU_XTAL_FREQ_RATIO, XTAL_CTL_EN); /* Read initial value */ regmap_read(regmap, PMU_XTAL_FREQ_RATIO, &last_val); last_val &= XTAL_ALP_PER_4ILP; /* * At minimum we should loop for a bit to let hardware do the * measurement. This isn't very accurate however, so for a better * precision lets try getting 20 different values for and use average. */ while (num < 20) { regmap_read(regmap, PMU_XTAL_FREQ_RATIO, &cur_val); cur_val &= XTAL_ALP_PER_4ILP; if (cur_val != last_val) { /* Got different value, use it */ sum += cur_val; num++; loop_num = 0; last_val = cur_val; } else if (++loop_num > 5000) { /* Same value over and over, give up */ sum += cur_val; num++; break; } cpu_relax(); } /* Disable measurement to save power */ regmap_write(regmap, PMU_XTAL_FREQ_RATIO, 0x0); avg = sum / num; return parent_rate * 4 / avg; } static const struct clk_ops bcm53573_ilp_clk_ops = { .enable = bcm53573_ilp_enable, .disable = bcm53573_ilp_disable, .recalc_rate = bcm53573_ilp_recalc_rate, }; static void bcm53573_ilp_init(struct device_node *np) { struct bcm53573_ilp *ilp; struct clk_init_data init = { }; const char *parent_name; int err; ilp = kzalloc(sizeof(*ilp), GFP_KERNEL); if (!ilp) return; parent_name = of_clk_get_parent_name(np, 0); if (!parent_name) { err = -ENOENT; goto err_free_ilp; } ilp->regmap = syscon_node_to_regmap(of_get_parent(np)); if (IS_ERR(ilp->regmap)) { err = PTR_ERR(ilp->regmap); goto err_free_ilp; } init.name = np->name; init.ops = &bcm53573_ilp_clk_ops; init.parent_names = &parent_name; init.num_parents = 1; ilp->hw.init = &init; err = clk_hw_register(NULL, &ilp->hw); if (err) goto err_free_ilp; err = of_clk_add_hw_provider(np, of_clk_hw_simple_get, &ilp->hw); if (err) goto err_clk_hw_unregister; return; err_clk_hw_unregister: clk_hw_unregister(&ilp->hw); err_free_ilp: kfree(ilp); pr_err("Failed to init ILP clock: %d\n", err); } /* We need it very early for arch code, before device model gets ready */ CLK_OF_DECLARE(bcm53573_ilp_clk, "brcm,bcm53573-ilp", bcm53573_ilp_init);
24.167785
73
0.718689
d6435bb4283e30c898e6ea6d9accc6bac0008ba1
2,787
h
C
include/engine/interface/ButtonBase.h
smithy545/engine
1818a1acafdbc2550b10ef74a215aa41d94edf0f
[ "MIT" ]
null
null
null
include/engine/interface/ButtonBase.h
smithy545/engine
1818a1acafdbc2550b10ef74a215aa41d94edf0f
[ "MIT" ]
null
null
null
include/engine/interface/ButtonBase.h
smithy545/engine
1818a1acafdbc2550b10ef74a215aa41d94edf0f
[ "MIT" ]
null
null
null
// // Created by Philip Smith on 7/15/21. // #ifndef ENGINE_BUTTONELEMENT_H #define ENGINE_BUTTONELEMENT_H #include "InterfaceEntity.h" #include <engine/BoxComponent.h> #include <engine/entity.h> #include <engine/input_events.h> #include <engine/InstanceList.h> #include <engine/sprite/ShapeSprite.h> namespace engine { template<typename DownEvent, typename UpEvent> class ButtonBase : public BoxComponent, public InterfaceEntity, public MouseButtonEventSink { public: PTR(ButtonBase); ButtonBase(float x, float y, float width, float height) : InterfaceEntity(Point_2(x + width * 0.5, y + height * 0.5)), BoxComponent(x, y, width, height) {} entt::entity register_with(entt::registry& registry) override { ShapeSprite sprite; sprite.vertices.emplace_back(min.x, min.y); sprite.colors.emplace_back(0,1,1); sprite.vertices.emplace_back(min.x, max.y); sprite.colors.emplace_back(1,0,1); sprite.vertices.emplace_back(max.x, max.y); sprite.colors.emplace_back(1,1,0); sprite.vertices.emplace_back(max.x, min.y); sprite.colors.emplace_back(1,1,1); sprite.indices.push_back(0); sprite.indices.push_back(1); sprite.indices.push_back(2); sprite.indices.push_back(2); sprite.indices.push_back(3); sprite.indices.push_back(0); if(m_entity == entt::null) m_entity = registry.create(); registry.emplace_or_replace<ShapeSprite>(m_entity, sprite); registry.patch<InstanceList>(m_entity, [](auto &instance_list) { instance_list.add_instance(glm::mat4(1)); }); return m_entity; } void handle(MouseButtonEvent& event, InterfaceView& emitter) override { if (m_down) { m_down = event.pressed; if(!m_down) { auto* event_ptr = build_up_event(event, emitter); emitter.publish<UpEvent*>(event_ptr); delete event_ptr; } } else if(collides(event.x, event.y)) { m_down = event.pressed; if(m_down) { auto* event_ptr = build_down_event(event, emitter); emitter.publish<DownEvent*>(event_ptr); delete event_ptr; } } } virtual UpEvent* build_up_event(MouseButtonEvent &event, InterfaceView &emitter) = 0; virtual DownEvent* build_down_event(MouseButtonEvent &event, InterfaceView &emitter) = 0; protected: bool m_down{false}; }; } // namespace engine #endif //ENGINE_BUTTONELEMENT_H
33.178571
101
0.595981
aafc865ab4095a3b48380dac7cd71152339895be
1,428
h
C
gui/main_window/search_contacts/results/FoundContacts.h
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
1
2019-12-02T08:37:10.000Z
2019-12-02T08:37:10.000Z
gui/main_window/search_contacts/results/FoundContacts.h
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
null
null
null
gui/main_window/search_contacts/results/FoundContacts.h
ERPShuen/ICQ1
f319a72ad60aae4809eef0e4eb362f4d69292296
[ "Apache-2.0" ]
null
null
null
#pragma once namespace Logic { class contact_profile; } namespace Ui { class FlowLayout; class ContactWidget; typedef std::list<std::shared_ptr<Logic::contact_profile>> profiles_list; class FoundContacts : public QWidget { Q_OBJECT Q_SIGNALS: void needMore(int _skipCount); void addContact(QString _contact); void msgContact(QString _contact); void callContact(QString _contact); void contactInfo(QString _contact); private Q_SLOTS: void onAvatarLoaded(QString _aimid); void onAddContact(QString _contact); void onMsgContact(QString _contact); void onCallContact(QString _contact); void onContactInfo(QString _contact); private: QScrollArea* area_; FlowLayout* contactsLayout_; QVBoxLayout* rootLayout_; int prevHScrollValue_; int prevVScrollValue_; std::map<QString, ContactWidget*> items_; std::map<QString, QString> countries_; void hookScroll(); public: int insertItems(const profiles_list& _profiles); void contactAddResult(const QString& _contact, bool _res); void clear(); bool empty(); FoundContacts(QWidget* _parent); virtual ~FoundContacts(void); }; }
23.409836
78
0.602241
c58b0e04b44a2c07529fd87c4d31a574d0958637
671
h
C
src/playground/explosion.h
Cat-Lord/ppgso_project
fa2fc3fc16e3e20a656d87bfec865d629b197d00
[ "MIT" ]
null
null
null
src/playground/explosion.h
Cat-Lord/ppgso_project
fa2fc3fc16e3e20a656d87bfec865d629b197d00
[ "MIT" ]
null
null
null
src/playground/explosion.h
Cat-Lord/ppgso_project
fa2fc3fc16e3e20a656d87bfec865d629b197d00
[ "MIT" ]
null
null
null
#pragma once #include <ppgso/ppgso.h> #include "object.h" /*! * Simple explosion object that will render expanding transparent geometry in the scene with additive blending */ class Explosion final : public Object { private: float age{0.0f}; float maxAge{0.2f}; glm::vec3 rotMomentum; public: glm::vec3 speed; /*! * Create new Explosion */ Explosion(); /*! * Update explosion * @param scene Scene to update * @param dt Time delta * @return true to delete the object */ bool update(Scene &scene, float dt) override; /*! * Render explosion * @param scene Scene to render in */ void render(Scene &scene) override; };
18.135135
110
0.663189
65b8cbb7f42c619c5fd7da7cf0320fef5985a8e2
3,467
h
C
public/oriutil/lrucache.h
pipcet/ori
61ea9b76db2a9eddb46f6d938e2b2266f2434f86
[ "0BSD" ]
21
2015-01-06T11:07:41.000Z
2021-01-18T17:29:46.000Z
public/oriutil/lrucache.h
pipcet/ori
61ea9b76db2a9eddb46f6d938e2b2266f2434f86
[ "0BSD" ]
null
null
null
public/oriutil/lrucache.h
pipcet/ori
61ea9b76db2a9eddb46f6d938e2b2266f2434f86
[ "0BSD" ]
8
2017-06-16T17:04:57.000Z
2021-03-20T19:08:57.000Z
/* * Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __LRUCACHE_H__ #define __LRUCACHE_H__ #include <assert.h> #include <list> #include <utility> #include <stdexcept> #include <unordered_map> #include "debug.h" #include "rwlock.h" template <class K, class V, int MAX> class LRUCache { public: typedef std::list<K> lru_list; typedef std::unordered_map<K, std::pair<V, typename lru_list::iterator> > lru_cache; LRUCache() : numItems(0) { } ~LRUCache() { } void put(K key, V value) { RWKey::sp ckey = lock.writeLock(); typename lru_cache::iterator it = cache.find(key); if (numItems >= MAX && it == cache.end()) evict(ckey); if (it != cache.end()) { lru.erase((*it).second.second); numItems--; } assert(numItems == lru.size()); typename lru_list::iterator p = lru.insert(lru.end(), key); cache[key] = std::make_pair(value, p); numItems++; } const V &get(K key) { RWKey::sp ckey = lock.writeLock(); typename lru_cache::iterator it = cache.find(key); if (it != cache.end()) { lru.splice(lru.end(), lru, (*it).second.second); return (*it).second.first; } throw std::runtime_error("Key doesn't exist!"); } /// Atomic get which returns true if key is cached (and value returned) bool get(K key, V &value) { RWKey::sp ckey = lock.writeLock(); typename lru_cache::iterator it = cache.find(key); if (it == cache.end()) { return false; } else { lru.splice(lru.end(), lru, (*it).second.second); value = (*it).second.first; return true; } } bool hasKey(K key) { RWKey::sp ckey = lock.readLock(); typename lru_cache::iterator it = cache.find(key); return it != cache.end(); } void invalidate(K key) { RWKey::sp ckey = lock.writeLock(); typename lru_cache::iterator it = cache.find(key); if (it == cache.end()) return; lru.erase((*it).second.second); cache.erase(it); numItems--; } void clear() { RWKey::sp ckey = lock.writeLock(); lru.clear(); cache.clear(); numItems = 0; } private: void evict(RWKey::sp ckey) { typename lru_cache::iterator it = cache.find(lru.front()); assert(!lru.empty()); cache.erase(it); lru.pop_front(); numItems--; } lru_list lru; lru_cache cache; RWLock lock; // Because std::list::size() on GCC is O(N) uint32_t numItems; }; #endif /* __LRUCACHE_H__ */
25.681481
77
0.591289