added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T18:39:48.637651+00:00
2021-03-13T11:59:19
093eb716e4bebcd1b9c3ff8dc309de69828bd80c
{ "blob_id": "093eb716e4bebcd1b9c3ff8dc309de69828bd80c", "branch_name": "refs/heads/main", "committer_date": "2021-03-13T11:59:19", "content_id": "ef6f2eea6016293c364f2bdab57cd7e01da9c6ba", "detected_licenses": [ "MIT" ], "directory_id": "9d94d5e6131b914d043730b34668e0a3aae5427a", "extension": "h", "filename": "Container.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 345493241, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2365, "license": "MIT", "license_type": "permissive", "path": "/Include/Game/Container.h", "provenance": "stackv2-0030.json.gz:3894", "repo_name": "andrewgasson/roguelike-7drl-2021", "revision_date": "2021-03-13T11:59:19", "revision_id": "1caaf3fcd89356172fc7d21c31d9d761ab121859", "snapshot_id": "80de54602da66802d587042c7d9cbf7bff8eb0c5", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/andrewgasson/roguelike-7drl-2021/1caaf3fcd89356172fc7d21c31d9d761ab121859/Include/Game/Container.h", "visit_date": "2023-03-20T16:58:55.164518" }
stackv2
#ifndef GAME_CONTAINER_H #define GAME_CONTAINER_H typedef enum ContainerType { CONTAINER_TYPE_CARCASS, CONTAINER_TYPE_CHEST, CONTAINER_TYPE_LOOT } ContainerType; #include "Game/Handle.h" #include "Raylib/raylib.h" #include "Raylib/terminal.h" void InitContainers(int capacity); int MaxContainers(void); bool IsContainerValid(Handle container); Handle SpawnContainer(ContainerType containerType); // Requires a sprite and inventory to be available void DestroyContainer(Handle container); void DestroyAllContainers(void); int CountContainers(void); Handle GetContainerAtPosition(Vector2 position); Handle GetContainerInventory(Handle container); Vector2 GetContainerPosition(Handle container); ContainerType GetContainerType(Handle container); void SetContainerPosition(Handle container, Vector2 position); TerminalTile GetCarcassContainerButcheredTile(Handle carcassContainer); int GetCarcassContainerDecayDuration(Handle carcassContainer); int GetCarcassContainerDecayTime(Handle carcassContainer); TerminalTile GetCarcassContainerTile(Handle carcassContainer); bool IsCarcassContainerButchered(Handle carcassContainer); void ResetCarcassContainerDecayTime(Handle carcassContainer); void SetCarcassContainerButchered(Handle carcassContainer, bool butchered); void SetCarcassContainerButcheredTile(Handle carcassContainer, TerminalTile butcheredTile); void SetCarcassContainerDecayDuration(Handle carcassContainer, int decayDuration); void SetCarcassContainerTile(Handle carcassContainer, TerminalTile tile); TerminalTile GetChestContainerClosedTile(Handle chestContainer); TerminalTile GetChestContainerOpenedTile(Handle chestContainer); bool IsChestContainerOpened(Handle chestContainer); void SetChestContainerClosedTile(Handle chestContainer, TerminalTile closedTile); void SetChestContainerOpenedTile(Handle chestContainer, TerminalTile openedTile); void SetChestContainerOpened(Handle chestContainer, bool opened); int GetLootContainerDecayDuration(Handle lootContainer); int GetLootContainerDecayTime(Handle lootContainer); TerminalTile GetLootContainerTile(Handle lootContainer); void ResetLootContainerDecayTime(Handle lootContainer); void SetLootContainerDecayDuration(Handle lootContainer, int decayDuration); void SetLootContainerTile(Handle lootContainer, TerminalTile tile); void RemoveDecayedContainers(void); #endif // GAME_CONTAINER_H
2.296875
2
2024-11-18T18:39:48.730649+00:00
2019-11-06T15:21:19
16d2388c7afcd88419979c360b88f1773b9f0616
{ "blob_id": "16d2388c7afcd88419979c360b88f1773b9f0616", "branch_name": "refs/heads/master", "committer_date": "2019-11-06T15:21:19", "content_id": "86f825179cf36c2b5e7e81551fa905fb7387b35a", "detected_licenses": [ "MIT" ], "directory_id": "d21cd7a935a6835ee9c3627df6a94e6d4fee1d40", "extension": "h", "filename": "freelistft.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 189271005, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1083, "license": "MIT", "license_type": "permissive", "path": "/include/al2o3_cadt/freelistft.h", "provenance": "stackv2-0030.json.gz:4023", "repo_name": "DeanoC/al2o3_cadt", "revision_date": "2019-11-06T15:21:19", "revision_id": "94772b23f047c6c22c68914717f8fd1325c20f3a", "snapshot_id": "52e5a6ecbb7909bc475b0e313f1a4e32d0219a27", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/DeanoC/al2o3_cadt/94772b23f047c6c22c68914717f8fd1325c20f3a/include/al2o3_cadt/freelistft.h", "visit_date": "2020-05-29T17:17:42.616467" }
stackv2
// License Summary: MIT see LICENSE file #pragma once #include "al2o3_platform/platform.h" #include "al2o3_thread/atomic.h" typedef struct CADT_FreeListFT { uint64_t elementSize; uint64_t maxBlocks; uint32_t elementsPerBlockMask; uint32_t elementsPerBlockShift; Thread_Atomic64_t freeListHead; Thread_AtomicPtr_t *blocks; Thread_Atomic64_t totalElementsAllocated; Thread_Atomic64_t currentAllocating; } CADT_FreeListFT; typedef struct CADT_FreeListFT *CADT_FreeListFTHandle; // free threaded (any thread can call at any time) AL2O3_EXTERN_C size_t CADT_FreeListFTElementSize(CADT_FreeListFTHandle handle); AL2O3_EXTERN_C void* CADT_FreeListFTAlloc(CADT_FreeListFTHandle fl); AL2O3_EXTERN_C void CADT_FreeListFTRelease(CADT_FreeListFTHandle handle, void* ptr); // not thread safe! AL2O3_EXTERN_C CADT_FreeListFTHandle CADT_FreeListFTCreate(size_t elementSize, size_t blockCount, size_t maxBlocks); AL2O3_EXTERN_C void CADT_FreeListFTDestroy(CADT_FreeListFTHandle handle); AL2O3_EXTERN_C void CADT_FreeListFTReset(CADT_FreeListFTHandle handle, bool freeAllocatedMemory);
2.140625
2
2024-11-18T18:39:48.816699+00:00
2017-08-05T03:03:11
459974b07d01f680c7aece405a0954200c5a52b9
{ "blob_id": "459974b07d01f680c7aece405a0954200c5a52b9", "branch_name": "refs/heads/master", "committer_date": "2017-08-05T03:03:11", "content_id": "dbe04757ef7151cbacc4a4929fb8330aade2392d", "detected_licenses": [ "MIT" ], "directory_id": "2349f4e5ad4adf2566f487e30caae046cacb88ba", "extension": "c", "filename": "Button.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 89644991, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1706, "license": "MIT", "license_type": "permissive", "path": "/main/src/hardware/Button.c", "provenance": "stackv2-0030.json.gz:4151", "repo_name": "dannyp11/han-gps", "revision_date": "2017-08-05T03:03:11", "revision_id": "7bd34edcd4c69682223a2b8ca464e2bb6d99592d", "snapshot_id": "53a208ae5220a8978c16dfe35b1ac4c210d3aa8a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dannyp11/han-gps/7bd34edcd4c69682223a2b8ca464e2bb6d99592d/main/src/hardware/Button.c", "visit_date": "2021-01-20T04:08:59.585075" }
stackv2
/* * Button.c * * Created on: Mar 9, 2017 * Author: dat */ #include <avr/io.h> #include <avr/interrupt.h> #include "Button.h" ButtonPressCallback mOkFunction = 0; ButtonPressCallback mCancelFunction = 0; ButtonPressCallback mUpFunction = 0; ButtonPressCallback mDownFunction = 0; void ButtonsInit() { //enable pullup PORTB |= ((1 << BUTTON_CANCEL) | (1 << BUTTON_OK) | (1 << BUTTON_DOWN)); PORTD |= (1 << BUTTON_UP); // set as input DDRB &= ~(1 << BUTTON_CANCEL); DDRB &= ~(1 << BUTTON_OK); DDRB &= ~(1 << BUTTON_DOWN); DDRD &= ~(1 << BUTTON_UP); // enable interrupt PCICR |= (1 << PCIE0) | (1 << PCIE2); PCMSK0 |= (1 << BUTTON_CANCEL) | (1 << BUTTON_OK) | (1 << BUTTON_DOWN); PCMSK2 |= (1 << BUTTON_UP); sei(); } ISR(PCINT0_vect) { if (mOkFunction && (PINB & (1 << BUTTON_OK))) { mOkFunction(); } else if (mCancelFunction && (PINB & (1 << BUTTON_CANCEL))) { mCancelFunction(); } else if (mDownFunction && (PINB & (1 << BUTTON_DOWN))) { mDownFunction(); } } ISR(PCINT2_vect) { if (mUpFunction && (PIND & (1 << BUTTON_UP))) { mUpFunction(); } } uint8_t ButtonOKSetCallback(ButtonPressCallback function) { if (mOkFunction) { return 1; } else { mOkFunction = function; } return 0; } uint8_t ButtonCancelSetCallback(ButtonPressCallback function) { if (mCancelFunction) { return 1; } else { mCancelFunction = function; } return 0; } uint8_t ButtonUpSetCallback(ButtonPressCallback function) { if (mUpFunction) { return 1; } else { mUpFunction = function; } return 0; } uint8_t ButtonDownSetCallback(ButtonPressCallback function) { if (mDownFunction) { return 1; } else { mDownFunction = function; } return 0; }
2.6875
3
2024-11-18T18:39:48.932846+00:00
2015-01-19T12:52:08
d21ebbcf7338ee09906dd9b40070429aa7d6d247
{ "blob_id": "d21ebbcf7338ee09906dd9b40070429aa7d6d247", "branch_name": "refs/heads/master", "committer_date": "2015-01-19T12:52:08", "content_id": "f1224bb6fd6932f478be6ef9ca6c3affb62414b1", "detected_licenses": [ "Unlicense" ], "directory_id": "33da7068ffac1b584d0c5cd5795d04966d5fe127", "extension": "c", "filename": "bdriver.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4126, "license": "Unlicense", "license_type": "permissive", "path": "/bdriver.c", "provenance": "stackv2-0030.json.gz:4279", "repo_name": "ewe2/cbw", "revision_date": "2015-01-19T12:52:08", "revision_id": "71dc02c6504fcf52d3504fb4913a8f916aa8634c", "snapshot_id": "ec1deadc754fc2d25aa398bd72b476c63caf4b68", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ewe2/cbw/71dc02c6504fcf52d3504fb4913a8f916aa8634c/bdriver.c", "visit_date": "2021-01-17T18:57:49.070351" }
stackv2
/* * Test driver for BIGRAM character guessing stuff. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "window.h" #include "specs.h" #include "cipher.h" #define NDOBLOCKS 2 /* Number of blocks to do. */ #define DEBUG FALSE ecinfo myecinfo; char plainbuf[BLOCKSIZE+1]; float accept_level; float prob_cutoff; extern int ec_best(); extern void ec_dplain(); extern void ec_dscipher(); extern void ec_dnext(); extern void ec_dsizetab(); extern void ec_dperm(); extern void ec_dpmap(); extern void ec_init(); extern void ec_cscore(); extern void lp_init(); extern int lp_best_char(); extern void lp_cscore(); extern void lp_accept(); extern int lp_best_pos(); extern void lp_dclasses(); extern char mcbuf[]; extern char *fname; /* Used by fillcbuf. */ void do_lp_block(); /* Test routine for equiv class info. */ int main(argc, argv) int argc; char *argv[]; { ecinfo *eci; FILE *inp; FILE *sout, *sin; int blknum; int maxblock; long filelength; char infile[100]; char inplain[100]; char *plain = ".txt"; char *code = ".cipher"; char *p, *q; sout = stdout; /* For use within debugger, dbx. */ sin = stdin; if (argc != 4) { printf("Usage: %s input_file_root acceptance_level prob_cutoff\n", argv[0]); exit(0); } p = inplain; q = argv[1]; while ((*p++ = *q++)); --p; q = plain; while ((*p++ = *q++)); p = infile; q = argv[1]; while ((*p++ = *q++)); --p; q = code; while ((*p++ = *q++)); if (sscanf(argv[2], "%f", &accept_level) != 1) { printf("Could not parse the acceptance level from %s.\n", argv[2]); exit(0); } if (sscanf(argv[3], "%f", &prob_cutoff) != 1) { printf("Could not parse the probability cutoff from %s.\n", argv[2]); exit(0); } printf("\t\tEquivalence Class Guessing\n\n"); printf("Filename = %s. Acceptance level = %4.2f\n",infile,accept_level); printf("Loading statistics ..."); printf(" 1"); load_1stats_from("mss.stats"); printf(" 2"); load_2stats_from("mss-bigram.stats"); printf(" done.\n"); eci = &myecinfo; if ((inp = fopen(infile, "r")) == NULL) { printf("\nCannot open %s for reading.\n", infile); exit(0); } fseek(inp, 0L, 2); filelength = ftell(inp); fclose(inp); maxblock = filelength / BLOCKSIZE; if (maxblock > (NDOBLOCKS-1)) maxblock = (NDOBLOCKS-1); for (blknum = 0 ; blknum <= maxblock ; blknum++) { do_lp_block(eci, blknum, infile, inplain); } return 0; } /* Do a block using the letter pair statistics. */ void do_lp_block(eci, blknum, cfile, plainfile) reg ecinfo *eci; int blknum; char *cfile, *plainfile; { int i; reg int c; int ntried; int naccepted, nwrong; reg int classpos; int charcount; int *permp, repeat; cipherfile = cfile; fillcbuf(blknum, mcbuf); cipherfile = plainfile; fillcbuf(blknum, plainbuf); lp_init(mcbuf, refperm(blknum), eci); for(repeat = 0 ; repeat < 3 ; repeat++) { naccepted = 0; nwrong = 0; ntried = 0; for (ntried = 0 ; ntried < BLOCKSIZE ; ntried++) { classpos = lp_best_pos(eci, 2); if (classpos == NONE) break; c = lp_best_char(eci, classpos, accept_level - ((repeat == 0) ? 0.0 : 0.0), prob_cutoff); if (c != NONE) { lp_accept(eci, classpos, c); naccepted++; #if DEBUG printf("ACCEPTED"); #endif if (plainbuf[classpos] != c) { nwrong++; #if DEBUG printf(" -- INCORRECT"); #endif } #if DEBUG printf("\n"); #endif } } /* decode(eci->ciphertext, eci->plaintext, eci->perm); */ for (i = 0 ; i < eci->nclasses ; i++) { eci->classlist[i].changed = TRUE; } charcount = 0; for (i = 0 ; i < BLOCKSIZE ; i++) { if (eci->plaintext[i] != NONE) charcount++; } printf("\n\nPlaintext for block %d using %d wires", blknum, naccepted); printf(" (%d wrong)", nwrong); printf(" yields %d characters.", charcount); printf("\nThere were %d classes and %d guess tries.",eci->nclasses,ntried); printf("\n\n"); ec_dplain(stdout, eci); } permp = refperm(blknum); for (i = 0 ; i < BLOCKSIZE ; i++) { permp[i] = eci->perm[i]; } } key u_getkey(void) { return 0; } keyer topktab[] ={{0, NULL}}; char *quitcmd(void) { return NULL; }
2.671875
3
2024-11-18T18:39:48.995960+00:00
2023-08-17T16:08:06
0075b91ac4a74452ea92a8eda4f8cb03e67520a6
{ "blob_id": "0075b91ac4a74452ea92a8eda4f8cb03e67520a6", "branch_name": "refs/heads/main", "committer_date": "2023-08-17T16:08:06", "content_id": "22c56d1395f5551e0e788ab010aa2baa792e13a1", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066", "extension": "c", "filename": "fcg.c", "fork_events_count": 169, "gha_created_at": "2013-03-10T20:55:21", "gha_event_created_at": "2023-03-29T11:02:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8691401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20072, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/ksp/ksp/impls/fcg/fcg.c", "provenance": "stackv2-0030.json.gz:4408", "repo_name": "petsc/petsc", "revision_date": "2023-08-17T16:08:06", "revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9", "snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969", "src_encoding": "UTF-8", "star_events_count": 341, "url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/ksp/ksp/impls/fcg/fcg.c", "visit_date": "2023-08-17T20:51:16.507070" }
stackv2
/* This file implements the FCG (Flexible Conjugate Gradient) method */ #include <../src/ksp/ksp/impls/fcg/fcgimpl.h> /*I "petscksp.h" I*/ extern PetscErrorCode KSPComputeExtremeSingularValues_CG(KSP, PetscReal *, PetscReal *); extern PetscErrorCode KSPComputeEigenvalues_CG(KSP, PetscInt, PetscReal *, PetscReal *, PetscInt *); #define KSPFCG_DEFAULT_MMAX 30 /* maximum number of search directions to keep */ #define KSPFCG_DEFAULT_NPREALLOC 10 /* number of search directions to preallocate */ #define KSPFCG_DEFAULT_VECB 5 /* number of search directions to allocate each time new direction vectors are needed */ #define KSPFCG_DEFAULT_TRUNCSTRAT KSP_FCD_TRUNC_TYPE_NOTAY static PetscErrorCode KSPAllocateVectors_FCG(KSP ksp, PetscInt nvecsneeded, PetscInt chunksize) { PetscInt i; KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscInt nnewvecs, nvecsprev; PetscFunctionBegin; /* Allocate enough new vectors to add chunksize new vectors, reach nvecsneedtotal, or to reach mmax+1, whichever is smallest */ if (fcg->nvecs < PetscMin(fcg->mmax + 1, nvecsneeded)) { nvecsprev = fcg->nvecs; nnewvecs = PetscMin(PetscMax(nvecsneeded - fcg->nvecs, chunksize), fcg->mmax + 1 - fcg->nvecs); PetscCall(KSPCreateVecs(ksp, nnewvecs, &fcg->pCvecs[fcg->nchunks], 0, NULL)); PetscCall(KSPCreateVecs(ksp, nnewvecs, &fcg->pPvecs[fcg->nchunks], 0, NULL)); fcg->nvecs += nnewvecs; for (i = 0; i < nnewvecs; ++i) { fcg->Cvecs[nvecsprev + i] = fcg->pCvecs[fcg->nchunks][i]; fcg->Pvecs[nvecsprev + i] = fcg->pPvecs[fcg->nchunks][i]; } fcg->chunksizes[fcg->nchunks] = nnewvecs; ++fcg->nchunks; } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPSetUp_FCG(KSP ksp) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscInt maxit = ksp->max_it; const PetscInt nworkstd = 2; PetscFunctionBegin; /* Allocate "standard" work vectors (not including the basis and transformed basis vectors) */ PetscCall(KSPSetWorkVecs(ksp, nworkstd)); /* Allocated space for pointers to additional work vectors note that mmax is the number of previous directions, so we add 1 for the current direction, and an extra 1 for the prealloc (which might be empty) */ PetscCall(PetscMalloc5(fcg->mmax + 1, &fcg->Pvecs, fcg->mmax + 1, &fcg->Cvecs, fcg->mmax + 1, &fcg->pPvecs, fcg->mmax + 1, &fcg->pCvecs, fcg->mmax + 2, &fcg->chunksizes)); /* If the requested number of preallocated vectors is greater than mmax reduce nprealloc */ if (fcg->nprealloc > fcg->mmax + 1) PetscCall(PetscInfo(NULL, "Requested nprealloc=%" PetscInt_FMT " is greater than m_max+1=%" PetscInt_FMT ". Resetting nprealloc = m_max+1.\n", fcg->nprealloc, fcg->mmax + 1)); /* Preallocate additional work vectors */ PetscCall(KSPAllocateVectors_FCG(ksp, fcg->nprealloc, fcg->nprealloc)); /* If user requested computations of eigenvalues then allocate work work space needed */ if (ksp->calc_sings) { /* get space to store tridiagonal matrix for Lanczos */ PetscCall(PetscMalloc4(maxit, &fcg->e, maxit, &fcg->d, maxit, &fcg->ee, maxit, &fcg->dd)); ksp->ops->computeextremesingularvalues = KSPComputeExtremeSingularValues_CG; ksp->ops->computeeigenvalues = KSPComputeEigenvalues_CG; } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPSolve_FCG(KSP ksp) { PetscInt i, k, idx, mi; KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscScalar alpha = 0.0, beta = 0.0, dpi, s; PetscReal dp = 0.0; Vec B, R, Z, X, Pcurr, Ccurr; Mat Amat, Pmat; PetscInt eigs = ksp->calc_sings; /* Variables for eigen estimation - START*/ PetscInt stored_max_it = ksp->max_it; PetscScalar alphaold = 0, betaold = 1.0, *e = NULL, *d = NULL; /* Variables for eigen estimation - FINISH */ PetscFunctionBegin; #define VecXDot(x, y, a) (((fcg->type) == (KSP_CG_HERMITIAN)) ? VecDot(x, y, a) : VecTDot(x, y, a)) #define VecXMDot(a, b, c, d) (((fcg->type) == (KSP_CG_HERMITIAN)) ? VecMDot(a, b, c, d) : VecMTDot(a, b, c, d)) X = ksp->vec_sol; B = ksp->vec_rhs; R = ksp->work[0]; Z = ksp->work[1]; PetscCall(PCGetOperators(ksp->pc, &Amat, &Pmat)); if (eigs) { e = fcg->e; d = fcg->d; e[0] = 0.0; } /* Compute initial residual needed for convergence check*/ ksp->its = 0; if (!ksp->guess_zero) { PetscCall(KSP_MatMult(ksp, Amat, X, R)); PetscCall(VecAYPX(R, -1.0, B)); /* r <- b - Ax */ } else { PetscCall(VecCopy(B, R)); /* r <- b (x is 0) */ } switch (ksp->normtype) { case KSP_NORM_PRECONDITIONED: PetscCall(KSP_PCApply(ksp, R, Z)); /* z <- Br */ PetscCall(VecNorm(Z, NORM_2, &dp)); /* dp <- dqrt(z'*z) = sqrt(e'*A'*B'*B*A*e) */ KSPCheckNorm(ksp, dp); break; case KSP_NORM_UNPRECONDITIONED: PetscCall(VecNorm(R, NORM_2, &dp)); /* dp <- sqrt(r'*r) = sqrt(e'*A'*A*e) */ KSPCheckNorm(ksp, dp); break; case KSP_NORM_NATURAL: PetscCall(KSP_PCApply(ksp, R, Z)); /* z <- Br */ PetscCall(VecXDot(R, Z, &s)); KSPCheckDot(ksp, s); dp = PetscSqrtReal(PetscAbsScalar(s)); /* dp <- sqrt(r'*z) = sqrt(e'*A'*B*A*e) */ break; case KSP_NORM_NONE: dp = 0.0; break; default: SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "%s", KSPNormTypes[ksp->normtype]); } /* Initial Convergence Check */ PetscCall(KSPLogResidualHistory(ksp, dp)); PetscCall(KSPMonitor(ksp, 0, dp)); ksp->rnorm = dp; if (ksp->normtype == KSP_NORM_NONE) { PetscCall(KSPConvergedSkip(ksp, 0, dp, &ksp->reason, ksp->cnvP)); } else { PetscCall((*ksp->converged)(ksp, 0, dp, &ksp->reason, ksp->cnvP)); } if (ksp->reason) PetscFunctionReturn(PETSC_SUCCESS); /* Apply PC if not already done for convergence check */ if (ksp->normtype == KSP_NORM_UNPRECONDITIONED || ksp->normtype == KSP_NORM_NONE) { PetscCall(KSP_PCApply(ksp, R, Z)); /* z <- Br */ } i = 0; do { ksp->its = i + 1; /* If needbe, allocate a new chunk of vectors in P and C */ PetscCall(KSPAllocateVectors_FCG(ksp, i + 1, fcg->vecb)); /* Note that we wrap around and start clobbering old vectors */ idx = i % (fcg->mmax + 1); Pcurr = fcg->Pvecs[idx]; Ccurr = fcg->Cvecs[idx]; /* number of old directions to orthogonalize against */ switch (fcg->truncstrat) { case KSP_FCD_TRUNC_TYPE_STANDARD: mi = fcg->mmax; break; case KSP_FCD_TRUNC_TYPE_NOTAY: mi = ((i - 1) % fcg->mmax) + 1; break; default: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unrecognized Truncation Strategy"); } /* Compute a new column of P (Currently does not support modified G-S or iterative refinement)*/ PetscCall(VecCopy(Z, Pcurr)); { PetscInt l, ndots; l = PetscMax(0, i - mi); ndots = i - l; if (ndots) { PetscInt j; Vec *Pold, *Cold; PetscScalar *dots; PetscCall(PetscMalloc3(ndots, &dots, ndots, &Cold, ndots, &Pold)); for (k = l, j = 0; j < ndots; ++k, ++j) { idx = k % (fcg->mmax + 1); Cold[j] = fcg->Cvecs[idx]; Pold[j] = fcg->Pvecs[idx]; } PetscCall(VecXMDot(Z, ndots, Cold, dots)); for (k = 0; k < ndots; ++k) dots[k] = -dots[k]; PetscCall(VecMAXPY(Pcurr, ndots, dots, Pold)); PetscCall(PetscFree3(dots, Cold, Pold)); } } /* Update X and R */ betaold = beta; PetscCall(VecXDot(Pcurr, R, &beta)); /* beta <- pi'*r */ KSPCheckDot(ksp, beta); PetscCall(KSP_MatMult(ksp, Amat, Pcurr, Ccurr)); /* w <- A*pi (stored in ci) */ PetscCall(VecXDot(Pcurr, Ccurr, &dpi)); /* dpi <- pi'*w */ alphaold = alpha; alpha = beta / dpi; /* alpha <- beta/dpi */ PetscCall(VecAXPY(X, alpha, Pcurr)); /* x <- x + alpha * pi */ PetscCall(VecAXPY(R, -alpha, Ccurr)); /* r <- r - alpha * wi */ /* Compute norm for convergence check */ switch (ksp->normtype) { case KSP_NORM_PRECONDITIONED: PetscCall(KSP_PCApply(ksp, R, Z)); /* z <- Br */ PetscCall(VecNorm(Z, NORM_2, &dp)); /* dp <- sqrt(z'*z) = sqrt(e'*A'*B'*B*A*e) */ KSPCheckNorm(ksp, dp); break; case KSP_NORM_UNPRECONDITIONED: PetscCall(VecNorm(R, NORM_2, &dp)); /* dp <- sqrt(r'*r) = sqrt(e'*A'*A*e) */ KSPCheckNorm(ksp, dp); break; case KSP_NORM_NATURAL: PetscCall(KSP_PCApply(ksp, R, Z)); /* z <- Br */ PetscCall(VecXDot(R, Z, &s)); KSPCheckDot(ksp, s); dp = PetscSqrtReal(PetscAbsScalar(s)); /* dp <- sqrt(r'*z) = sqrt(e'*A'*B*A*e) */ break; case KSP_NORM_NONE: dp = 0.0; break; default: SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "%s", KSPNormTypes[ksp->normtype]); } /* Check for convergence */ ksp->rnorm = dp; PetscCall(KSPLogResidualHistory(ksp, dp)); PetscCall(KSPMonitor(ksp, i + 1, dp)); PetscCall((*ksp->converged)(ksp, i + 1, dp, &ksp->reason, ksp->cnvP)); if (ksp->reason) break; /* Apply PC if not already done for convergence check */ if (ksp->normtype == KSP_NORM_UNPRECONDITIONED || ksp->normtype == KSP_NORM_NONE) { PetscCall(KSP_PCApply(ksp, R, Z)); /* z <- Br */ } /* Compute current C (which is W/dpi) */ PetscCall(VecScale(Ccurr, 1.0 / dpi)); /* w <- ci/dpi */ if (eigs) { if (i > 0) { PetscCheck(ksp->max_it == stored_max_it, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "Can not change maxit AND calculate eigenvalues"); e[i] = PetscSqrtReal(PetscAbsScalar(beta / betaold)) / alphaold; d[i] = PetscSqrtReal(PetscAbsScalar(beta / betaold)) * e[i] + 1.0 / alpha; } else { d[i] = PetscSqrtReal(PetscAbsScalar(beta)) * e[i] + 1.0 / alpha; } fcg->ned = ksp->its - 1; } ++i; } while (i < ksp->max_it); if (i >= ksp->max_it) ksp->reason = KSP_DIVERGED_ITS; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPDestroy_FCG(KSP ksp) { PetscInt i; KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; /* Destroy "standard" work vecs */ PetscCall(VecDestroyVecs(ksp->nwork, &ksp->work)); /* Destroy P and C vectors and the arrays that manage pointers to them */ if (fcg->nvecs) { for (i = 0; i < fcg->nchunks; ++i) { PetscCall(VecDestroyVecs(fcg->chunksizes[i], &fcg->pPvecs[i])); PetscCall(VecDestroyVecs(fcg->chunksizes[i], &fcg->pCvecs[i])); } } PetscCall(PetscFree5(fcg->Pvecs, fcg->Cvecs, fcg->pPvecs, fcg->pCvecs, fcg->chunksizes)); /* free space used for singular value calculations */ if (ksp->calc_sings) PetscCall(PetscFree4(fcg->e, fcg->d, fcg->ee, fcg->dd)); PetscCall(KSPDestroyDefault(ksp)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPView_FCG(KSP ksp, PetscViewer viewer) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscBool iascii, isstring; const char *truncstr; PetscFunctionBegin; PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii)); PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring)); if (fcg->truncstrat == KSP_FCD_TRUNC_TYPE_STANDARD) truncstr = "Using standard truncation strategy"; else if (fcg->truncstrat == KSP_FCD_TRUNC_TYPE_NOTAY) truncstr = "Using Notay's truncation strategy"; else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Undefined FCG truncation strategy"); if (iascii) { PetscCall(PetscViewerASCIIPrintf(viewer, " m_max=%" PetscInt_FMT "\n", fcg->mmax)); PetscCall(PetscViewerASCIIPrintf(viewer, " preallocated %" PetscInt_FMT " directions\n", PetscMin(fcg->nprealloc, fcg->mmax + 1))); PetscCall(PetscViewerASCIIPrintf(viewer, " %s\n", truncstr)); } else if (isstring) { PetscCall(PetscViewerStringSPrintf(viewer, "m_max %" PetscInt_FMT " nprealloc %" PetscInt_FMT " %s", fcg->mmax, fcg->nprealloc, truncstr)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@ KSPFCGSetMmax - set the maximum number of previous directions `KSPFCG` will store for orthogonalization Logically Collective Input Parameters: + ksp - the Krylov space context - mmax - the maximum number of previous directions to orthogonalize against Options Database Key: . -ksp_fcg_mmax <N> - maximum number of search directions Level: intermediate Note: mmax + 1 directions are stored (mmax previous ones along with a current one) and whether all are used in each iteration also depends on the truncation strategy (see KSPFCGSetTruncationType()) .seealso: [](ch_ksp), `KSPFCG`, `KSPFCGGetTruncationType()`, `KSPFCGGetNprealloc()`, `KSPFCGetMmax()` @*/ PetscErrorCode KSPFCGSetMmax(KSP ksp, PetscInt mmax) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; PetscValidHeaderSpecific(ksp, KSP_CLASSID, 1); PetscValidLogicalCollectiveInt(ksp, mmax, 2); fcg->mmax = mmax; PetscFunctionReturn(PETSC_SUCCESS); } /*@ KSPFCGGetMmax - get the maximum number of previous directions `KSPFCG` will store Not Collective Input Parameter: . ksp - the Krylov space context Output Parameter: . mmax - the maximum number of previous directions allowed for orthogonalization Level: intermediate Note: FCG stores mmax+1 directions at most (mmax previous ones, and one current one) .seealso: [](ch_ksp), `KSPFCG`, `KSPFCGGetTruncationType()`, `KSPFCGGetNprealloc()`, `KSPFCGSetMmax()` @*/ PetscErrorCode KSPFCGGetMmax(KSP ksp, PetscInt *mmax) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; PetscValidHeaderSpecific(ksp, KSP_CLASSID, 1); *mmax = fcg->mmax; PetscFunctionReturn(PETSC_SUCCESS); } /*@ KSPFCGSetNprealloc - set the number of directions to preallocate with `KSPFCG` Logically Collective Input Parameters: + ksp - the Krylov space context - nprealloc - the number of vectors to preallocate Options Database Key: . -ksp_fcg_nprealloc <N> - number of directions to preallocate Level: advanced .seealso: [](ch_ksp), `KSPFCG`, `KSPFCGGetTruncationType()`, `KSPFCGGetNprealloc()`, `KSPFCGSetMmax()`, `KSPFCGGetMmax()` @*/ PetscErrorCode KSPFCGSetNprealloc(KSP ksp, PetscInt nprealloc) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; PetscValidHeaderSpecific(ksp, KSP_CLASSID, 1); PetscValidLogicalCollectiveInt(ksp, nprealloc, 2); PetscCheck(nprealloc <= fcg->mmax + 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cannot preallocate more than m_max+1 vectors"); fcg->nprealloc = nprealloc; PetscFunctionReturn(PETSC_SUCCESS); } /*@ KSPFCGGetNprealloc - get the number of directions preallocate by `KSPFCG` Not Collective Input Parameter: . ksp - the Krylov space context Output Parameter: . nprealloc - the number of directions preallocated Level: advanced .seealso: [](ch_ksp), `KSPFCG`, `KSPFCGGetTruncationType()`, `KSPFCGSetNprealloc()`, `KSPFCGSetMmax()`, `KSPFCGGetMmax()` @*/ PetscErrorCode KSPFCGGetNprealloc(KSP ksp, PetscInt *nprealloc) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; PetscValidHeaderSpecific(ksp, KSP_CLASSID, 1); *nprealloc = fcg->nprealloc; PetscFunctionReturn(PETSC_SUCCESS); } /*@ KSPFCGSetTruncationType - specify how many of its stored previous directions `KSPFCG` uses during orthoganalization Logically Collective Input Parameters: + ksp - the Krylov space context - truncstrat - the choice of strategy .vb KSP_FCD_TRUNC_TYPE_STANDARD uses all (up to mmax) stored directions KSP_FCD_TRUNC_TYPE_NOTAY uses the last max(1,mod(i,mmax)) stored directions at iteration i=0,1,.. .ve Options Database Key: . -ksp_fcg_truncation_type <standard, notay> - specify how many of its stored previous directions `KSPFCG` uses during orthoganalization Level: intermediate .seealso: [](ch_ksp), `KSPFCDTruncationType`, `KSPFCGGetTruncationType`, `KSPFCGSetNprealloc()`, `KSPFCGSetMmax()`, `KSPFCGGetMmax()` @*/ PetscErrorCode KSPFCGSetTruncationType(KSP ksp, KSPFCDTruncationType truncstrat) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; PetscValidHeaderSpecific(ksp, KSP_CLASSID, 1); PetscValidLogicalCollectiveEnum(ksp, truncstrat, 2); fcg->truncstrat = truncstrat; PetscFunctionReturn(PETSC_SUCCESS); } /*@ KSPFCGGetTruncationType - get the truncation strategy employed by `KSPFCG` Not Collective Input Parameter: . ksp - the Krylov space context Output Parameter: . truncstrat - the strategy type Level: intermediate .seealso: [](ch_ksp), `KSPFCG`, `KSPFCGSetTruncationType`, `KSPFCDTruncationType`, `KSPFCGSetTruncationType()` @*/ PetscErrorCode KSPFCGGetTruncationType(KSP ksp, KSPFCDTruncationType *truncstrat) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscFunctionBegin; PetscValidHeaderSpecific(ksp, KSP_CLASSID, 1); *truncstrat = fcg->truncstrat; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode KSPSetFromOptions_FCG(KSP ksp, PetscOptionItems *PetscOptionsObject) { KSP_FCG *fcg = (KSP_FCG *)ksp->data; PetscInt mmax, nprealloc; PetscBool flg; PetscFunctionBegin; PetscOptionsHeadBegin(PetscOptionsObject, "KSP FCG Options"); PetscCall(PetscOptionsInt("-ksp_fcg_mmax", "Maximum number of search directions to store", "KSPFCGSetMmax", fcg->mmax, &mmax, &flg)); if (flg) PetscCall(KSPFCGSetMmax(ksp, mmax)); PetscCall(PetscOptionsInt("-ksp_fcg_nprealloc", "Number of directions to preallocate", "KSPFCGSetNprealloc", fcg->nprealloc, &nprealloc, &flg)); if (flg) PetscCall(KSPFCGSetNprealloc(ksp, nprealloc)); PetscCall(PetscOptionsEnum("-ksp_fcg_truncation_type", "Truncation approach for directions", "KSPFCGSetTruncationType", KSPFCDTruncationTypes, (PetscEnum)fcg->truncstrat, (PetscEnum *)&fcg->truncstrat, NULL)); PetscOptionsHeadEnd(); PetscFunctionReturn(PETSC_SUCCESS); } /*MC KSPFCG - Implements the Flexible Conjugate Gradient method (FCG). Unlike most `KSP` methods this allows the preconditioner to be nonlinear. [](sec_flexibleksp) Options Database Keys: + -ksp_fcg_mmax <N> - maximum number of search directions . -ksp_fcg_nprealloc <N> - number of directions to preallocate - -ksp_fcg_truncation_type <standard,notay> - truncation approach for directions Level: beginner Note: Supports left preconditioning only. Contributed by: Patrick Sanan References: + * - Notay, Y."Flexible Conjugate Gradients", SIAM J. Sci. Comput. 22:4, 2000 - * - Axelsson, O. and Vassilevski, P. S. "A Black Box Generalized Conjugate Gradient Solver with Inner Iterations and Variable step Preconditioning", SIAM J. Matrix Anal. Appl. 12:4, 1991 .seealso: [](ch_ksp), [](sec_flexibleksp), `KSPGCR`, `KSPFGMRES`, `KSPCG`, `KSPFCGSetMmax()`, `KSPFCGGetMmax()`, `KSPFCGSetNprealloc()`, `KSPFCGGetNprealloc()`, `KSPFCGSetTruncationType()`, `KSPFCGGetTruncationType()`, `KSPFCGGetTruncationType` M*/ PETSC_EXTERN PetscErrorCode KSPCreate_FCG(KSP ksp) { KSP_FCG *fcg; PetscFunctionBegin; PetscCall(PetscNew(&fcg)); #if !defined(PETSC_USE_COMPLEX) fcg->type = KSP_CG_SYMMETRIC; #else fcg->type = KSP_CG_HERMITIAN; #endif fcg->mmax = KSPFCG_DEFAULT_MMAX; fcg->nprealloc = KSPFCG_DEFAULT_NPREALLOC; fcg->nvecs = 0; fcg->vecb = KSPFCG_DEFAULT_VECB; fcg->nchunks = 0; fcg->truncstrat = KSPFCG_DEFAULT_TRUNCSTRAT; ksp->data = (void *)fcg; PetscCall(KSPSetSupportedNorm(ksp, KSP_NORM_PRECONDITIONED, PC_LEFT, 2)); PetscCall(KSPSetSupportedNorm(ksp, KSP_NORM_UNPRECONDITIONED, PC_LEFT, 1)); PetscCall(KSPSetSupportedNorm(ksp, KSP_NORM_NATURAL, PC_LEFT, 1)); PetscCall(KSPSetSupportedNorm(ksp, KSP_NORM_NONE, PC_LEFT, 1)); ksp->ops->setup = KSPSetUp_FCG; ksp->ops->solve = KSPSolve_FCG; ksp->ops->destroy = KSPDestroy_FCG; ksp->ops->view = KSPView_FCG; ksp->ops->setfromoptions = KSPSetFromOptions_FCG; ksp->ops->buildsolution = KSPBuildSolutionDefault; ksp->ops->buildresidual = KSPBuildResidualDefault; PetscFunctionReturn(PETSC_SUCCESS); }
2.46875
2
2024-11-18T18:39:49.256861+00:00
2015-02-03T09:26:07
9730be71c9a6a6d963b2b5a02e86b0d20b95ecce
{ "blob_id": "9730be71c9a6a6d963b2b5a02e86b0d20b95ecce", "branch_name": "refs/heads/master", "committer_date": "2015-02-03T09:26:07", "content_id": "16bcb6edcd71a6bc53ca5f17125c38d67b40508c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "40e85a95db8c30f3bd8999308efdf734fd887e85", "extension": "h", "filename": "stringold.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1151, "license": "Apache-2.0", "license_type": "permissive", "path": "/libc/include/stringold.h", "provenance": "stackv2-0030.json.gz:4664", "repo_name": "kissthink/os_sdk", "revision_date": "2015-02-03T09:26:07", "revision_id": "425d94ba21b3e9f6acd8106662d2e6281b3b2ccc", "snapshot_id": "ae210d55d5ae1cee7d333db0a2b434602a8e67c7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kissthink/os_sdk/425d94ba21b3e9f6acd8106662d2e6281b3b2ccc/libc/include/stringold.h", "visit_date": "2020-12-12T21:56:34.258391" }
stackv2
#ifndef STRING_H #define STRING_H #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> char * strdup(const char *_s); char *strcpy(char *to, const char *from); char *strchr(const char *s, int c); char *strrchr(const char *s, int c); int strcmp(const char *s1, const char *s2); size_t strcspn(const char *s1, const char *s2); int strcoll(const char *s1, const char *s2); size_t strspn(const char *s1, const char *s2); char *strstr(const char *s, const char *find); char *strncat(char *dst, const char *src, size_t n); char *strncpy(char *dst, const char *src, size_t n); int strncmp(const char *s1, const char *s2, size_t n); void* memset(void* dest, int c, size_t count); int strlen(const char*); void * memcpy(void *_dest, const void *_src, size_t _n); int strcasecmp(const char *_s1, const char *_s2); void qsort(void *_base, size_t _nelem, size_t _size, int (*_cmp)(const void *_e1, const void *_e2)); double cos( double angle ); double fabs( double __x ); double sin( double angle ); double sqrt( double x ); double tan( double __x ); void * calloc(size_t _nelem, size_t _size); #ifdef __cplusplus } #endif #endif
2.03125
2
2024-11-18T18:39:49.333727+00:00
2016-11-25T17:45:21
6abed1cbd8668dc9b0916e4939294c9a477c6a01
{ "blob_id": "6abed1cbd8668dc9b0916e4939294c9a477c6a01", "branch_name": "refs/heads/master", "committer_date": "2016-11-25T17:45:21", "content_id": "58ed3e903f17504578019e0b36edb952d0c6c9a0", "detected_licenses": [ "MIT" ], "directory_id": "239731234307c101d57f6f52922816a8a04659a0", "extension": "c", "filename": "3DTransforms.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 74777321, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4450, "license": "MIT", "license_type": "permissive", "path": "/Projeto/src/3DTransforms.c", "provenance": "stackv2-0030.json.gz:4792", "repo_name": "lellisls/CG-CatAndDog", "revision_date": "2016-11-25T17:45:21", "revision_id": "c89a24fc5bcd302e6295695f6ba0414e70039c86", "snapshot_id": "57b1a48e537fd323667d06c243ec9ad18125085b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lellisls/CG-CatAndDog/c89a24fc5bcd302e6295695f6ba0414e70039c86/Projeto/src/3DTransforms.c", "visit_date": "2020-06-21T18:24:43.434783" }
stackv2
#include "../inc/3DTransforms.h" #include "math.h" #include "stdio.h" #include "stdlib.h" void matrix4x4SetIdentity(Matrix4x4 matIdent4x4) { int row, col; for (row = 0; row < 4; ++row) for (col = 0; col < 4; ++col) matIdent4x4 [row][col] = (row == col); } void matrix4x4pPrint(Matrix4x4 mtx) { int row, col; for (row = 0; row < 4; ++row) { for (col = 0; col < 4; ++col) { printf("%.2f " , mtx[row][col]); } printf("\n"); } } void matrix4x4PreMultiply(Matrix4x4 m1, Matrix4x4 m2) { int row, col; Matrix4x4 matTemp; for (row = 0; row < 4; ++row) for (col = 0; col < 4; ++col) matTemp[row][col] = m1[row][0] * m2[0][col] + m1[row][1] * m2[1][col] + m1[row][2] * m2[2][col] + m1[row][3] * m2[3][col]; for (row = 0; row < 4; ++row) for (col = 0; col < 4; ++col) m2[row][col] = matTemp[row][col]; } void translate3D(GLfloat tx, GLfloat ty, GLfloat tz) { Matrix4x4 matTransl3D; matrix4x4SetIdentity(matTransl3D); matTransl3D [0][3] = tx; matTransl3D [1][3] = ty; matTransl3D [2][3] = tz; matrix4x4PreMultiply(matTransl3D, matComposite); } void rotateY(Pt3D p1, GLfloat radianAngle) { Matrix4x4 matQuatRot; float dx = 0, dy = 1, dz = 0; float axisVectLength = sqrt(dx * dx + dy * dy + dz * dz); float cosA = cosf(radianAngle); float oneC = 1 - cosA; float sinA = sinf(radianAngle); float ux = (dx) / axisVectLength; float uy = (dy) / axisVectLength; float uz = (dz) / axisVectLength; translate3D(-p1->x, -p1->y, -p1->z); matrix4x4SetIdentity(matQuatRot); matQuatRot[0][0] = ux * ux * oneC + cosA; matQuatRot[0][1] = ux * uy * oneC - uz * sinA; matQuatRot[0][2] = ux * uz * oneC + uy * sinA; matQuatRot[1][0] = uy * ux * oneC + uz * sinA; matQuatRot[1][1] = uy * uy * oneC + cosA; matQuatRot[1][2] = uy * uz * oneC - ux * sinA; matQuatRot[2][0] = uz * ux * oneC - uy * sinA; matQuatRot[2][1] = uz * uy * oneC + ux * sinA; matQuatRot[2][2] = uz * uz * oneC + cosA; matrix4x4PreMultiply(matQuatRot, matComposite); translate3D(p1->x, p1->y, p1->z); } void rotate3D( GLfloat radianAngle, GLfloat x, GLfloat y, GLfloat z ) { Pt3D ctr = CreatePt3D(0,0,0); Pt3D dir = CreatePt3D(x,y,z); rotate3Dv(ctr,dir,radianAngle); freePt3D(ctr); freePt3D(dir); } void rotate3Dv(Pt3D p1, Pt3D p2, GLfloat radianAngle) { Matrix4x4 matQuatRot; float dx = p2->x - p1->x, dy = p2->y - p1->y, dz = p2->z - p1->z; float axisVectLength = sqrt(dx * dx + dy * dy + dz * dz); float cosA = cosf(radianAngle); float oneC = 1 - cosA; float sinA = sinf(radianAngle); float ux = (dx) / axisVectLength; float uy = (dy) / axisVectLength; float uz = (dz) / axisVectLength; translate3D(-p1->x, -p1->y, -p1->z); matrix4x4SetIdentity(matQuatRot); matQuatRot[0][0] = ux * ux * oneC + cosA; matQuatRot[0][1] = ux * uy * oneC - uz * sinA; matQuatRot[0][2] = ux * uz * oneC + uy * sinA; matQuatRot[1][0] = uy * ux * oneC + uz * sinA; matQuatRot[1][1] = uy * uy * oneC + cosA; matQuatRot[1][2] = uy * uz * oneC - ux * sinA; matQuatRot[2][0] = uz * ux * oneC - uy * sinA; matQuatRot[2][1] = uz * uy * oneC + ux * sinA; matQuatRot[2][2] = uz * uz * oneC + cosA; matrix4x4PreMultiply(matQuatRot, matComposite); translate3D(p1->x, p1->y, p1->z); } void scale3D(GLfloat sx, GLfloat sy, GLfloat sz, Pt3D fixedPt) { Matrix4x4 matScale3D; matrix4x4SetIdentity(matScale3D); matScale3D[0][0] = sx; matScale3D[0][3] = (1 - sx) * fixedPt->x; matScale3D[1][1] = sy; matScale3D[1][3] = (1 - sy) * fixedPt->y; matScale3D[2][2] = sz; matScale3D[2][3] = (1 - sz) * fixedPt->z; matrix4x4PreMultiply(matScale3D, matComposite); } void resetTransformMatrix() { matrix4x4SetIdentity(matComposite); } void multiplyPt3DMtx4x4(Pt3D pt, Matrix4x4 mat) { Pt3D res = ZeroPt3D(); res->x = mat[0][0] * pt->x + mat[0][1] * pt->y + mat[0][2] * pt->z + mat[0][3]; res->y = mat[1][0] * pt->x + mat[1][1] * pt->y + mat[1][2] * pt->z + mat[1][3]; res->z = mat[2][0] * pt->x + mat[2][1] * pt->y + mat[2][2] * pt->z + mat[2][3]; pt->x = res->x; pt->y = res->y; pt->z = res->z; freePt3D(res); } void Pt3DTransform(Pt3D pt) { multiplyPt3DMtx4x4(pt, matComposite); }
2.765625
3
2024-11-18T18:39:49.579139+00:00
2019-10-26T15:16:00
4950fea6aed32a824deaa9830c33f7ee2ea7e33c
{ "blob_id": "4950fea6aed32a824deaa9830c33f7ee2ea7e33c", "branch_name": "refs/heads/master", "committer_date": "2019-10-26T15:16:00", "content_id": "def7ff120e4d01435fe29b94982002dc560af7de", "detected_licenses": [ "MIT" ], "directory_id": "04ce14d564d4ff804cfb0fca163a84804c107a2a", "extension": "c", "filename": "init.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 217726323, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1818, "license": "MIT", "license_type": "permissive", "path": "/Assignment-3/user/init.c", "provenance": "stackv2-0030.json.gz:5177", "repo_name": "Riyuzakii/CS330", "revision_date": "2019-10-26T15:16:00", "revision_id": "610fe9437aac57cbf603de51829b05a64fc585ad", "snapshot_id": "8109b88c13ff3cd9a15e04baf261bc23b5f57c68", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Riyuzakii/CS330/610fe9437aac57cbf603de51829b05a64fc585ad/Assignment-3/user/init.c", "visit_date": "2020-08-28T14:28:00.260650" }
stackv2
#include<init.h> static void exit(int); static int main(void); void init_start() { int retval = main(); exit(0); } /*Invoke system call with no additional arguments*/ static long _syscall0(int syscall_num) { asm volatile ( "int $0x80;" "leaveq;" "retq;" :::"memory"); return 0; /*gcc shutup!*/ } /*Invoke system call with one argument*/ static long _syscall1(int syscall_num, int exit_code) { asm volatile ( "int $0x80;" "leaveq;" "retq;" :::"memory"); return 0; /*gcc shutup!*/ } /*Invoke system call with two arguments*/ static long _syscall2(int syscall_num, u64 arg1, u64 arg2) { asm volatile ( "int $0x80;" "leaveq;" "retq;" :::"memory"); return 0; /*gcc shutup!*/ } static void exit(int code) { _syscall1(SYSCALL_EXIT, code); } static long getpid() { return(_syscall0(SYSCALL_GETPID)); } static long write(char *ptr, int size) { return(_syscall2(SYSCALL_WRITE, (u64)ptr, size)); } u64 signal(int num, void *handler) { return _syscall2(SYSCALL_SIGNAL, num, (u64)handler); } u64 sleep(int ticks) { return _syscall1(SYSCALL_SLEEP, ticks); } /* static void signal_handler(int signal) { write(HANDLER, sizeof(HANDLER)); exit(10); }*/ static int main() { unsigned long i, j; #define MSG_1 "------------- Gonna sleep for 10 ticks. Check for pid = 0. -------------\n" #define MSG_2 "------------- Gonna sleep for another 20 ticks. Check for pid = 0. ------------\n" #define MSG_W "------------- Woke up. The process should now exit. Give 2 marks. -------------\n" write(MSG_1, sizeof(MSG_1)); sleep(10); write(MSG_2, sizeof(MSG_2)); sleep(20); write(MSG_W, sizeof(MSG_W)); exit(10); return 0; }
2.828125
3
2024-11-18T18:39:49.864574+00:00
2020-11-14T03:18:45
70e0da748471862ea8bbd1e6356edc3c24ac10bf
{ "blob_id": "70e0da748471862ea8bbd1e6356edc3c24ac10bf", "branch_name": "refs/heads/main", "committer_date": "2020-11-14T03:18:45", "content_id": "d0f5d02bdd2c71ff9018ec42c87071a1c2b163b1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8bc631d6e5985db11c59490aaa25d4c633fcd2a5", "extension": "c", "filename": "arrayAdd.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 429, "license": "Apache-2.0", "license_type": "permissive", "path": "/20-8-18/arrayAdd.c", "provenance": "stackv2-0030.json.gz:5433", "repo_name": "tusarmahapatra/codesInC1.0", "revision_date": "2020-11-14T03:18:45", "revision_id": "b9737a626f662c8b2c18231104cd8a42a1f4f8f2", "snapshot_id": "38fb4b6c262df01d37e838c01929a85fe3649321", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tusarmahapatra/codesInC1.0/b9737a626f662c8b2c18231104cd8a42a1f4f8f2/20-8-18/arrayAdd.c", "visit_date": "2023-01-11T12:41:55.597367" }
stackv2
#include<stdio.h> void main() { int numbers[10]; int count=10; long sum=0L; float average=0.0f; printf("\nEnter the 10 numbers : \n"); int i; for(i=0;i<count;i++) { printf("%d>",i+1); scanf("%d",&numbers[i]); sum+=numbers[i]; } average=(float)sum/count; printf("\nAverage of the 10 numbers entered is : %f\n",average); }
3.234375
3
2024-11-18T18:39:50.456770+00:00
2022-10-09T01:08:00
db59257fe750b76f9bfb3ce96c80d4f37ecdb7cc
{ "blob_id": "db59257fe750b76f9bfb3ce96c80d4f37ecdb7cc", "branch_name": "refs/heads/master", "committer_date": "2022-10-09T01:08:00", "content_id": "4f05ff72e6aa0a45faa7cea3077268e213fd6f8e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7d761dcd9263ac6e5b9daede963f5e56c4fb3a36", "extension": "c", "filename": "iconv.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 45656899, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2179, "license": "Apache-2.0", "license_type": "permissive", "path": "/sys/netsmb/iconv.c", "provenance": "stackv2-0030.json.gz:5562", "repo_name": "execunix/vinos", "revision_date": "2022-10-09T01:08:00", "revision_id": "d2ecdb6a4f937fbce3bd82d2136b97e456ef4741", "snapshot_id": "dcb063eb045292c48f33362299e8398a0429777b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/execunix/vinos/d2ecdb6a4f937fbce3bd82d2136b97e456ef4741/sys/netsmb/iconv.c", "visit_date": "2022-11-05T19:45:46.443487" }
stackv2
/* $NetBSD: iconv.c,v 1.13.4.1 2014/12/01 09:31:40 martin Exp $ */ /* Public domain */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: iconv.c,v 1.13.4.1 2014/12/01 09:31:40 martin Exp $"); #include <sys/param.h> #include <sys/kernel.h> #include <sys/systm.h> #include <sys/errno.h> #include <netsmb/iconv.h> /* stubs for iconv functions */ int iconv_open_stub(const char *, const char *, void **); int iconv_close_stub(void *); int iconv_conv_stub(void *, const char **, size_t *, char **, size_t *); __weak_alias(iconv_open, iconv_open_stub); __weak_alias(iconv_close, iconv_close_stub); __weak_alias(iconv_conv, iconv_conv_stub); int iconv_open_stub(const char *to, const char *from, void **handle) { return 0; } int iconv_close_stub(void *handle) { return 0; } int iconv_conv_stub(void *handle, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft) { if (inbuf == NULL) return(0); /* initial shift state */ if (*inbytesleft > *outbytesleft) return(E2BIG); (void)memcpy(*outbuf, *inbuf, *inbytesleft); *outbytesleft -= *inbytesleft; *inbuf += *inbytesleft; *outbuf += *inbytesleft; *inbytesleft = 0; return 0; } char * iconv_convstr(void *handle, char *dst, const char *src, size_t l) { char *p = dst; size_t inlen, outlen; int error; if (handle == NULL) { strlcpy(dst, src, l); return dst; } inlen = strlen(src); outlen = l - 1; error = iconv_conv(handle, NULL, NULL, &p, &outlen); if (error) return NULL; error = iconv_conv(handle, &src, &inlen, &p, &outlen); if (error) return NULL; *p = 0; return dst; } void * iconv_convmem(void *handle, void *dst, const void *src, int size) { const char *s = src; char *d = dst; size_t inlen, outlen; int error; if (size == 0) return dst; if (handle == NULL) { memcpy(dst, src, size); return dst; } inlen = outlen = size; error = iconv_conv(handle, NULL, NULL, &d, &outlen); if (error) return NULL; error = iconv_conv(handle, &s, &inlen, &d, &outlen); if (error) return NULL; return dst; } int iconv_lookupcp(const char **cpp, const char *s) { for (; *cpp; cpp++) if (strcmp(*cpp, s) == 0) return 0; return ENOENT; }
2.375
2
2024-11-18T18:39:51.257672+00:00
2022-10-03T11:42:14
8dab4cac016334b955177ab073e563a470fbcb9b
{ "blob_id": "8dab4cac016334b955177ab073e563a470fbcb9b", "branch_name": "refs/heads/master", "committer_date": "2022-10-03T11:42:14", "content_id": "d385f2c6cb2804000e9a5f129cbc259e3c435c6c", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "ce88b141111ab438b07014912c5acc7d0893d568", "extension": "c", "filename": "encoder_base.c", "fork_events_count": 0, "gha_created_at": "2020-01-28T20:14:01", "gha_event_created_at": "2021-04-07T10:48:34", "gha_language": "C", "gha_license_id": null, "github_id": 236831544, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7146, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/include/lzip/encoder_base.c", "provenance": "stackv2-0030.json.gz:6332", "repo_name": "graphext/ejemplo_charla_webassembly", "revision_date": "2022-10-03T11:42:14", "revision_id": "29f578dcb8519abf3414313cff9e58262af06eae", "snapshot_id": "dd4727a18211c08bb072910a9e5f3b3a8933091e", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/graphext/ejemplo_charla_webassembly/29f578dcb8519abf3414313cff9e58262af06eae/include/lzip/encoder_base.c", "visit_date": "2022-11-12T14:06:47.315708" }
stackv2
/* Lzlib - Compression library for the lzip format Copyright (C) 2009-2019 Antonio Diaz Diaz. This library is free software. 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. This library 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. */ static bool Mb_normalize_pos( struct Matchfinder_base * const mb ) { if( mb->pos > mb->stream_pos ) { mb->pos = mb->stream_pos; return false; } if( !mb->at_stream_end ) { int i; /* offset is int32_t for the min below */ const int32_t offset = mb->pos - mb->before_size - mb->dictionary_size; const int size = mb->stream_pos - offset; memmove( mb->buffer, mb->buffer + offset, size ); mb->partial_data_pos += offset; mb->pos -= offset; /* pos = before_size + dictionary_size */ mb->stream_pos -= offset; for( i = 0; i < mb->num_prev_positions; ++i ) mb->prev_positions[i] -= min( mb->prev_positions[i], offset ); for( i = 0; i < mb->pos_array_size; ++i ) mb->pos_array[i] -= min( mb->pos_array[i], offset ); } return true; } static bool Mb_init( struct Matchfinder_base * const mb, const int before_size, const int dict_size, const int after_size, const int dict_factor, const int num_prev_positions23, const int pos_array_factor ) { const int buffer_size_limit = ( dict_factor * dict_size ) + before_size + after_size; unsigned size; int i; mb->partial_data_pos = 0; mb->before_size = before_size; mb->after_size = after_size; mb->pos = 0; mb->cyclic_pos = 0; mb->stream_pos = 0; mb->num_prev_positions23 = num_prev_positions23; mb->at_stream_end = false; mb->flushing = false; mb->buffer_size = max( 65536, buffer_size_limit ); mb->buffer = (uint8_t *)malloc( mb->buffer_size ); if( !mb->buffer ) return false; mb->saved_dictionary_size = dict_size; mb->dictionary_size = dict_size; mb->pos_limit = mb->buffer_size - after_size; size = 1 << max( 16, real_bits( mb->dictionary_size - 1 ) - 2 ); if( mb->dictionary_size > 1 << 26 ) /* 64 MiB */ size >>= 1; mb->key4_mask = size - 1; size += num_prev_positions23; mb->num_prev_positions = size; mb->pos_array_size = pos_array_factor * ( mb->dictionary_size + 1 ); size += mb->pos_array_size; if( size * sizeof mb->prev_positions[0] <= size ) mb->prev_positions = 0; else mb->prev_positions = (int32_t *)malloc( size * sizeof mb->prev_positions[0] ); if( !mb->prev_positions ) { free( mb->buffer ); return false; } mb->pos_array = mb->prev_positions + mb->num_prev_positions; for( i = 0; i < mb->num_prev_positions; ++i ) mb->prev_positions[i] = 0; return true; } static void Mb_adjust_array( struct Matchfinder_base * const mb ) { int size = 1 << max( 16, real_bits( mb->dictionary_size - 1 ) - 2 ); if( mb->dictionary_size > 1 << 26 ) /* 64 MiB */ size >>= 1; mb->key4_mask = size - 1; size += mb->num_prev_positions23; mb->num_prev_positions = size; mb->pos_array = mb->prev_positions + mb->num_prev_positions; } static void Mb_adjust_dictionary_size( struct Matchfinder_base * const mb ) { if( mb->stream_pos < mb->dictionary_size ) { mb->dictionary_size = max( min_dictionary_size, mb->stream_pos ); Mb_adjust_array( mb ); mb->pos_limit = mb->buffer_size; } } static void Mb_reset( struct Matchfinder_base * const mb ) { int i; if( mb->stream_pos > mb->pos ) memmove( mb->buffer, mb->buffer + mb->pos, mb->stream_pos - mb->pos ); mb->partial_data_pos = 0; mb->stream_pos -= mb->pos; mb->pos = 0; mb->cyclic_pos = 0; mb->at_stream_end = false; mb->flushing = false; mb->dictionary_size = mb->saved_dictionary_size; Mb_adjust_array( mb ); mb->pos_limit = mb->buffer_size - mb->after_size; for( i = 0; i < mb->num_prev_positions; ++i ) mb->prev_positions[i] = 0; } /* End Of Stream mark => (dis == 0xFFFFFFFFU, len == min_match_len) */ static void LZeb_try_full_flush( struct LZ_encoder_base * const eb ) { int i; const int pos_state = Mb_data_position( &eb->mb ) & pos_state_mask; const State state = eb->state; Lzip_trailer trailer; if( eb->member_finished || Cb_free_bytes( &eb->renc.cb ) < max_marker_size + eb->renc.ff_count + Lt_size ) return; eb->member_finished = true; Re_encode_bit( &eb->renc, &eb->bm_match[state][pos_state], 1 ); Re_encode_bit( &eb->renc, &eb->bm_rep[state], 0 ); LZeb_encode_pair( eb, 0xFFFFFFFFU, min_match_len, pos_state ); Re_flush( &eb->renc ); Lt_set_data_crc( trailer, LZeb_crc( eb ) ); Lt_set_data_size( trailer, Mb_data_position( &eb->mb ) ); Lt_set_member_size( trailer, Re_member_position( &eb->renc ) + Lt_size ); for( i = 0; i < Lt_size; ++i ) Cb_put_byte( &eb->renc.cb, trailer[i] ); } /* Sync Flush mark => (dis == 0xFFFFFFFFU, len == min_match_len + 1) */ static bool LZeb_sync_flush( struct LZ_encoder_base * const eb ) { int i; const int pos_state = Mb_data_position( &eb->mb ) & pos_state_mask; const State state = eb->state; if( eb->member_finished || Cb_free_bytes( &eb->renc.cb ) < (2 * max_marker_size) + eb->renc.ff_count ) return false; for( i = 0; i < 2; ++i ) /* 2 consecutive markers guarantee decoding */ { Re_encode_bit( &eb->renc, &eb->bm_match[state][pos_state], 1 ); Re_encode_bit( &eb->renc, &eb->bm_rep[state], 0 ); LZeb_encode_pair( eb, 0xFFFFFFFFU, min_match_len + 1, pos_state ); Re_flush( &eb->renc ); } return true; } static void LZeb_reset( struct LZ_encoder_base * const eb, const unsigned long long member_size ) { int i; Mb_reset( &eb->mb ); eb->member_size_limit = min( member_size, 0x0008000000000000ULL ) - Lt_size - max_marker_size; eb->crc = 0xFFFFFFFFU; Bm_array_init( eb->bm_literal[0], (1 << literal_context_bits) * 0x300 ); Bm_array_init( eb->bm_match[0], states * pos_states ); Bm_array_init( eb->bm_rep, states ); Bm_array_init( eb->bm_rep0, states ); Bm_array_init( eb->bm_rep1, states ); Bm_array_init( eb->bm_rep2, states ); Bm_array_init( eb->bm_len[0], states * pos_states ); Bm_array_init( eb->bm_dis_slot[0], len_states * (1 << dis_slot_bits) ); Bm_array_init( eb->bm_dis, modeled_distances - end_dis_model + 1 ); Bm_array_init( eb->bm_align, dis_align_size ); Lm_init( &eb->match_len_model ); Lm_init( &eb->rep_len_model ); Re_reset( &eb->renc, eb->mb.dictionary_size ); for( i = 0; i < num_rep_distances; ++i ) eb->reps[i] = 0; eb->state = 0; eb->member_finished = false; }
2.28125
2
2024-11-18T18:39:51.616347+00:00
2020-03-01T04:18:24
d0a38db4b69ad166c62db001b9b61c6c806c8f8b
{ "blob_id": "d0a38db4b69ad166c62db001b9b61c6c806c8f8b", "branch_name": "refs/heads/master", "committer_date": "2020-03-01T04:18:24", "content_id": "cfafea3eb2e5a2151bfae09cc8b0e9be42bf6c9a", "detected_licenses": [ "MIT" ], "directory_id": "d668647cb76b7d24e1f617f0b1a5b223f733c0c0", "extension": "c", "filename": "sprite.c", "fork_events_count": 0, "gha_created_at": "2020-03-01T04:07:16", "gha_event_created_at": "2020-03-01T04:07:17", "gha_language": null, "gha_license_id": "MIT", "github_id": 244084179, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7179, "license": "MIT", "license_type": "permissive", "path": "/src/mana/graphics/entities/sprite.c", "provenance": "stackv2-0030.json.gz:6972", "repo_name": "nathanmcmillan/mana", "revision_date": "2020-03-01T04:18:24", "revision_id": "79fec75536abcd6b1184c58d82858ef843487460", "snapshot_id": "bc3eb969ab8d9ab88e600cceb2b4462dd33a40b5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nathanmcmillan/mana/79fec75536abcd6b1184c58d82858ef843487460/src/mana/graphics/entities/sprite.c", "visit_date": "2021-02-07T22:40:25.290374" }
stackv2
#include "mana/graphics/entities/sprite.h" void calc_normal(vec3 p1, vec3 p2, vec3 p3, float* dest) { vec3 v1; glm_vec3_sub(p2, p1, v1); vec3 v2; glm_vec3_sub(p3, p1, v2); glm_vec3_crossn(v1, v2, dest); } int sprite_init(struct Sprite* sprite, struct VulkanRenderer* vulkan_renderer, struct Shader* shader) { sprite->image_mesh = calloc(1, sizeof(struct Mesh)); mesh_init(sprite->image_mesh); sprite->image_texture = calloc(1, sizeof(struct Texture)); texture_init(sprite->image_texture, vulkan_renderer, "./assets/textures/alpha.png"); vec3 pos1 = {-0.5f, -0.5f, 0.0f}; vec3 pos2 = {0.5f, -0.5f, 0.0f}; vec3 pos3 = {0.5f, 0.5f, 0.0f}; vec3 pos4 = {-0.5f, 0.5f, 0.0f}; vec3 norm1; calc_normal(pos1, pos2, pos3, norm1); vec3 norm2; calc_normal(pos2, pos3, pos4, norm2); vec2 uv1 = {1.0f, 0.0f}; vec2 uv2 = {0.0f, 0.0f}; vec2 uv3 = {0.0f, 1.0f}; vec2 uv4 = {1.0f, 1.0f}; // outNormal = mat3(ubo.model) * normalMatrix * inNormal; mesh_assign_vertex(sprite->image_mesh->vertices, pos1[0], pos1[1], pos1[2], norm1[0], norm1[1], norm1[2], uv1[0], uv1[1]); mesh_assign_vertex(sprite->image_mesh->vertices, pos2[0], pos2[1], pos2[2], norm1[0], norm1[1], norm1[2], uv2[0], uv2[1]); mesh_assign_vertex(sprite->image_mesh->vertices, pos3[0], pos3[1], pos3[2], norm1[0], norm1[1], norm1[2], uv3[0], uv3[1]); mesh_assign_vertex(sprite->image_mesh->vertices, pos4[0], pos4[1], pos4[2], norm2[0], norm2[1], norm2[2], uv4[0], uv4[1]); mesh_assign_indice(sprite->image_mesh->indices, 0); mesh_assign_indice(sprite->image_mesh->indices, 1); mesh_assign_indice(sprite->image_mesh->indices, 2); mesh_assign_indice(sprite->image_mesh->indices, 2); mesh_assign_indice(sprite->image_mesh->indices, 3); mesh_assign_indice(sprite->image_mesh->indices, 0); // Vertex buffer VkDeviceSize vertex_buffer_size = sprite->image_mesh->vertices->memory_size * sprite->image_mesh->vertices->size; VkBuffer vertex_staging_buffer = {0}; VkDeviceMemory vertex_staging_buffer_memory = {0}; graphics_utils_create_buffer(vulkan_renderer->device, vulkan_renderer->physical_device, vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &vertex_staging_buffer, &vertex_staging_buffer_memory); void* vertex_data; vkMapMemory(vulkan_renderer->device, vertex_staging_buffer_memory, 0, vertex_buffer_size, 0, &vertex_data); memcpy(vertex_data, sprite->image_mesh->vertices->items, vertex_buffer_size); vkUnmapMemory(vulkan_renderer->device, vertex_staging_buffer_memory); graphics_utils_create_buffer(vulkan_renderer->device, vulkan_renderer->physical_device, vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &sprite->vertex_buffer, &sprite->vertex_buffer_memory); copy_buffer(vulkan_renderer, vertex_staging_buffer, sprite->vertex_buffer, vertex_buffer_size); vkDestroyBuffer(vulkan_renderer->device, vertex_staging_buffer, NULL); vkFreeMemory(vulkan_renderer->device, vertex_staging_buffer_memory, NULL); // Index buffer VkDeviceSize index_buffer_size = sprite->image_mesh->indices->memory_size * sprite->image_mesh->indices->size; VkBuffer index_staging_buffer = {0}; VkDeviceMemory index_staging_buffer_memory = {0}; graphics_utils_create_buffer(vulkan_renderer->device, vulkan_renderer->physical_device, index_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &index_staging_buffer, &index_staging_buffer_memory); void* index_data; vkMapMemory(vulkan_renderer->device, index_staging_buffer_memory, 0, index_buffer_size, 0, &index_data); memcpy(index_data, sprite->image_mesh->indices->items, index_buffer_size); vkUnmapMemory(vulkan_renderer->device, index_staging_buffer_memory); graphics_utils_create_buffer(vulkan_renderer->device, vulkan_renderer->physical_device, index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &sprite->index_buffer, &sprite->index_buffer_memory); copy_buffer(vulkan_renderer, index_staging_buffer, sprite->index_buffer, index_buffer_size); vkDestroyBuffer(vulkan_renderer->device, index_staging_buffer, NULL); vkFreeMemory(vulkan_renderer->device, index_staging_buffer_memory, NULL); // Uniform buffer VkDeviceSize uniform_buffer_size = sizeof(struct SpriteUniformBufferObject); graphics_utils_create_buffer(vulkan_renderer->device, vulkan_renderer->physical_device, uniform_buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &sprite->uniform_buffer, &sprite->uniform_buffers_memory); // Descriptor sets VkDescriptorSetLayout layout = {0}; layout = shader->descriptor_set_layout; VkDescriptorSetAllocateInfo alloc_info = {0}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.descriptorPool = shader->descriptor_pool; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = &layout; if (vkAllocateDescriptorSets(vulkan_renderer->device, &alloc_info, &sprite->descriptor_set) != VK_SUCCESS) { fprintf(stderr, "failed to allocate descriptor sets!\n"); return 0; } VkDescriptorBufferInfo buffer_info = {0}; buffer_info.buffer = sprite->uniform_buffer; buffer_info.offset = 0; buffer_info.range = sizeof(struct SpriteUniformBufferObject); VkDescriptorImageInfo image_info = {0}; image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; image_info.imageView = sprite->image_texture->texture_image_view; image_info.sampler = sprite->image_texture->texture_sampler; VkWriteDescriptorSet dcs[2]; memset(dcs, 0, sizeof(dcs)); dcs[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; dcs[0].dstSet = sprite->descriptor_set; dcs[0].dstBinding = 0; dcs[0].dstArrayElement = 0; dcs[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; dcs[0].descriptorCount = 1; dcs[0].pBufferInfo = &buffer_info; dcs[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; dcs[1].dstSet = sprite->descriptor_set; dcs[1].dstBinding = 1; dcs[1].dstArrayElement = 0; dcs[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; dcs[1].descriptorCount = 1; dcs[1].pImageInfo = &image_info; vkUpdateDescriptorSets(vulkan_renderer->device, 2, dcs, 0, NULL); return SPRITE_SUCCESS; } void sprite_delete(struct Sprite* sprite, struct VulkanRenderer* vulkan_renderer) { vkDestroyBuffer(vulkan_renderer->device, sprite->index_buffer, NULL); vkFreeMemory(vulkan_renderer->device, sprite->index_buffer_memory, NULL); vkDestroyBuffer(vulkan_renderer->device, sprite->vertex_buffer, NULL); vkFreeMemory(vulkan_renderer->device, sprite->vertex_buffer_memory, NULL); vkDestroyBuffer(vulkan_renderer->device, sprite->uniform_buffer, NULL); vkFreeMemory(vulkan_renderer->device, sprite->uniform_buffers_memory, NULL); mesh_delete(sprite->image_mesh); free(sprite->image_mesh); texture_delete(vulkan_renderer, sprite->image_texture); free(sprite->image_texture); }
2.15625
2
2024-11-18T18:39:51.826831+00:00
2022-11-04T20:30:08
2305be8d5f0211fb61e46c140c941f34df254fba
{ "blob_id": "2305be8d5f0211fb61e46c140c941f34df254fba", "branch_name": "refs/heads/master", "committer_date": "2022-11-04T20:30:08", "content_id": "c2ba5dfd250dce6476d7cc68d9a462302fe8e990", "detected_licenses": [ "MIT" ], "directory_id": "4762c0b2b09414f357837cda4cc7cca7f58d7630", "extension": "h", "filename": "st-node.h", "fork_events_count": 0, "gha_created_at": "2022-03-22T06:21:02", "gha_event_created_at": "2022-03-22T06:21:02", "gha_language": null, "gha_license_id": "MIT", "github_id": 472638718, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2815, "license": "MIT", "license_type": "permissive", "path": "/src/st-node.h", "provenance": "stackv2-0030.json.gz:7357", "repo_name": "clarking/panda-smalltalk", "revision_date": "2022-11-04T20:30:08", "revision_id": "7a8624853cfcd6a0ee776e2c42667b65805fa97b", "snapshot_id": "5bd1b9e6d0675848017f2c1bdc228aa3dda4995e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/clarking/panda-smalltalk/7a8624853cfcd6a0ee776e2c42667b65805fa97b/src/st-node.h", "visit_date": "2023-05-12T21:24:47.866811" }
stackv2
/* * st-node.h * * Copyright (c) 2008 Vincent Geddes * * 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. */ #ifndef __ST_NODE_H__ #define __ST_NODE_H__ #include <st-types.h> #include <st-utils.h> typedef enum { ST_METHOD_NODE, ST_BLOCK_NODE, ST_VARIABLE_NODE, ST_ASSIGN_NODE, ST_RETURN_NODE, ST_MESSAGE_NODE, ST_CASCADE_NODE, ST_LITERAL_NODE, } st_node_type; typedef enum { ST_UNARY_PRECEDENCE, ST_BINARY_PRECEDENCE, ST_KEYWORD_PRECEDENCE, } STMessagePrecedence; typedef struct st_node st_node; struct st_node { st_node_type type; int line; st_node *next; union { struct { STMessagePrecedence precedence; int primitive; st_oop selector; st_node *statements; st_node *temporaries; st_node *arguments; } method; struct { STMessagePrecedence precedence; bool is_statement; st_oop selector; st_node *receiver; st_node *arguments; bool super_send; } message; struct { char *name; } variable; struct { st_oop value; } literal; struct { st_node *assignee; st_node *expression; } assign; struct { st_node *expression; } retrn; struct { st_node *statements; st_node *temporaries; st_node *arguments; } block; struct { st_node *receiver; st_list *messages; bool is_statement; } cascade; }; }; st_node *st_node_new (st_node_type type); st_node *st_node_list_append (st_node *list, st_node *node); st_node *st_node_list_at (st_node *list, st_uint index); st_uint st_node_list_length (st_node *list); void st_print_method_node (st_node *method); void st_node_destroy (st_node *node); #endif /* __ST_NODE_H__ */
2.046875
2
2024-11-18T18:39:52.006230+00:00
2022-10-19T02:39:49
e9e123ce972a4f529bf45d6e72017fe39038609c
{ "blob_id": "e9e123ce972a4f529bf45d6e72017fe39038609c", "branch_name": "refs/heads/main", "committer_date": "2022-10-19T02:39:49", "content_id": "fdcaa4f099db6e5dae096b16f4efeade523e11d5", "detected_licenses": [ "Unlicense" ], "directory_id": "577382a8fac5056e6180890955f1439e21721d5d", "extension": "c", "filename": "Exercise6.1.c", "fork_events_count": 20, "gha_created_at": "2013-05-04T04:48:00", "gha_event_created_at": "2023-03-25T01:58:04", "gha_language": "Objective-C", "gha_license_id": "Unlicense", "github_id": 9849474, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3051, "license": "Unlicense", "license_type": "permissive", "path": "/OpenCV/BookExercises/Exercise6.1.c", "provenance": "stackv2-0030.json.gz:7614", "repo_name": "drichardson/examples", "revision_date": "2022-10-19T02:39:49", "revision_id": "a56703ccdb9dee5bcd9aac6cd2f98951db0f63cb", "snapshot_id": "eb4d875efc07f9a2f26556162cb5fdf0b6e218e3", "src_encoding": "UTF-8", "star_events_count": 33, "url": "https://raw.githubusercontent.com/drichardson/examples/a56703ccdb9dee5bcd9aac6cd2f98951db0f63cb/OpenCV/BookExercises/Exercise6.1.c", "visit_date": "2023-04-07T09:42:12.941514" }
stackv2
// // Exercise6.1.c #include <stdio.h> #include <opencv2/highgui/highgui_c.h> #include <opencv2/imgproc/imgproc_c.h> #include <opencv2/core/core_c.h> static void PrintMat(const char* name, const CvMat* mat) { printf("%s: {\n", name); for(int r = 0; r < mat->rows; ++r) { float* rowFloats = (float*)(mat->data.ptr + mat->step * r); for(int c = 0; c < mat->cols; ++c) { if ( c == 0 ) { printf("\n "); } else { printf(", "); } printf("%f", rowFloats[c]); } } printf("\n}\n"); } int main (int argc, const char * argv[]) { if ( argc != 2 ) { fprintf(stderr, "Usage: <image>\n"); exit(1); } IplImage* image = cvLoadImage(argv[1], CV_LOAD_IMAGE_GRAYSCALE); if ( image == NULL ) { fprintf(stderr, "Couldn't load image %s\n", argv[1]); exit(1); } IplImage* dst = cvCloneImage(image); //cvSetZero(dst); CvMat* rotation = cvCreateMat(2, 3, CV_32FC1); #if 0 // Optimized for a finding 3 pixel wide lines. float zeroDegreeLineData[] = { -10, -10, -10, -10, -10, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, -10, -10, -10, -10, -10 }; #if 0 float zeroDegreeLineData[] = { 10, 10, 10, 10, 10, -3, -3, -3, -3, -3, -14, -14, -14, -14, -14, -3, -3, -3, -3, -3, 10, 10, 10, 10, 10 }; #endif CvMat zeroDegreeLine = cvMat(5, 5, CV_32FC1, zeroDegreeLineData); PrintMat("Zero Degree Line", &zeroDegreeLine); cv2DRotationMatrix(cvPoint2D32f(2,2), 60.0, 1.0, rotation); CvMat* kernel = cvCreateMat(5, 5, CV_32FC1); #else // Optimized for finding 1 pixel wide lines. The sum of all co-efficients is 0, so this kernel has // the tendency to send pixels towards zero #if 0 float zeroDegreeLineData[] = { 10, 10, 10, -20, -20, -20, 10, 10, 10 }; #elif 0 float zeroDegreeLineData[] = { -10, -10, -10, 20, 20, 20, -10, -10, -10 }; #else // Line detector optimized to find a horizontal line 1 pixel wide that is darker (smaller value) than it’s surrounding pixels. This works because darker (smaller value) horizontal 1 pixel wide lines will have a smaller magnitude negative // component, which means their convoluted value will be higher than surrounding pixels. See Convolution.numbers // for a simple example how this works. float zeroDegreeLineData[] = { 1, 1, 1, -2, -2, -2, 1, 1, 1 }; #endif CvMat zeroDegreeLine = cvMat(3, 3, CV_32FC1, zeroDegreeLineData); PrintMat("Zero Degree Line", &zeroDegreeLine); // Going to rotate the horizontal line detecting kernel by 60 degrees to that it will detect 60 degree lines. cv2DRotationMatrix(cvPoint2D32f(1,1), 60.0, 1.0, rotation); CvMat* kernel = cvCreateMat(3, 3, CV_32FC1); #endif PrintMat("Rotation", rotation); cvWarpAffine(&zeroDegreeLine, kernel, rotation, CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, cvScalarAll(0)); PrintMat("Kernel", kernel); cvFilter2D( image, dst, kernel, cvPoint(-1,-1)); cvNamedWindow("main", CV_WINDOW_NORMAL); cvShowImage("main", image); cvWaitKey(0); cvShowImage("main", dst); cvWaitKey(0); return 0; }
2.859375
3
2024-11-18T18:39:52.116984+00:00
2014-06-26T18:29:02
097b5870725a294f4cbbd345a2fa0be511ebcc95
{ "blob_id": "097b5870725a294f4cbbd345a2fa0be511ebcc95", "branch_name": "refs/heads/master", "committer_date": "2014-06-26T18:30:17", "content_id": "afbe96ab9e6cf7400d4c446bceebe99afe74e9df", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "45174048966842f751b22e9ee1355be9cb90e224", "extension": "c", "filename": "odp_buffer.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 23260564, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2465, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/platform/linux-generic/source/odp_buffer.c", "provenance": "stackv2-0030.json.gz:7742", "repo_name": "gonzopancho/odp-crypto", "revision_date": "2014-06-26T18:29:02", "revision_id": "c412fb0f79e578e00decc3624bfea6986c4bcb5f", "snapshot_id": "907042ccaec7edc52f91ebfc88fac298d654d63f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gonzopancho/odp-crypto/c412fb0f79e578e00decc3624bfea6986c4bcb5f/platform/linux-generic/source/odp_buffer.c", "visit_date": "2021-01-18T10:08:53.613103" }
stackv2
/* Copyright (c) 2013, Linaro Limited * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <odp_buffer.h> #include <odp_buffer_internal.h> #include <odp_buffer_pool_internal.h> #include <string.h> #include <stdio.h> void *odp_buffer_addr(odp_buffer_t buf) { odp_buffer_hdr_t *hdr = odp_buf_to_hdr(buf); return hdr->addr; } size_t odp_buffer_size(odp_buffer_t buf) { odp_buffer_hdr_t *hdr = odp_buf_to_hdr(buf); return hdr->size; } int odp_buffer_type(odp_buffer_t buf) { odp_buffer_hdr_t *hdr = odp_buf_to_hdr(buf); return hdr->type; } int odp_buffer_is_scatter(odp_buffer_t buf) { odp_buffer_hdr_t *hdr = odp_buf_to_hdr(buf); if (hdr->scatter.num_bufs == 0) return 0; else return 1; } int odp_buffer_is_valid(odp_buffer_t buf) { odp_buffer_bits_t handle; handle.u32 = buf; return (handle.index != ODP_BUFFER_INVALID_INDEX); } int odp_buffer_snprint(char *str, size_t n, odp_buffer_t buf) { odp_buffer_hdr_t *hdr; int len = 0; if (!odp_buffer_is_valid(buf)) { printf("Buffer is not valid.\n"); return len; } hdr = odp_buf_to_hdr(buf); len += snprintf(&str[len], n-len, "Buffer\n"); len += snprintf(&str[len], n-len, " pool %i\n", hdr->pool); len += snprintf(&str[len], n-len, " index %"PRIu32"\n", hdr->index); len += snprintf(&str[len], n-len, " phy_addr %"PRIu64"\n", hdr->phys_addr); len += snprintf(&str[len], n-len, " addr %p\n", hdr->addr); len += snprintf(&str[len], n-len, " size %zu\n", hdr->size); len += snprintf(&str[len], n-len, " cur_offset %zu\n", hdr->cur_offset); len += snprintf(&str[len], n-len, " ref_count %i\n", hdr->ref_count); len += snprintf(&str[len], n-len, " type %i\n", hdr->type); len += snprintf(&str[len], n-len, " Scatter list\n"); len += snprintf(&str[len], n-len, " num_bufs %i\n", hdr->scatter.num_bufs); len += snprintf(&str[len], n-len, " pos %i\n", hdr->scatter.pos); len += snprintf(&str[len], n-len, " total_len %zu\n", hdr->scatter.total_len); return len; } void odp_buffer_print(odp_buffer_t buf) { int max_len = 512; char str[max_len]; int len; len = odp_buffer_snprint(str, max_len-1, buf); str[len] = 0; printf("\n%s\n", str); } void odp_buffer_copy_scatter(odp_buffer_t buf_dst, odp_buffer_t buf_src) { (void)buf_dst; (void)buf_src; }
2.703125
3
2024-11-18T18:39:52.238450+00:00
2021-02-25T10:38:39
0e516f57ced47324651df6e7336e0cc05ad0c095
{ "blob_id": "0e516f57ced47324651df6e7336e0cc05ad0c095", "branch_name": "refs/heads/main", "committer_date": "2021-02-25T10:38:39", "content_id": "2d21f6a32b52cba98c6b1cd7a6eaabc90ee85fb5", "detected_licenses": [ "MIT" ], "directory_id": "ce6413ccb1c562e721376515d636c4284879fcd8", "extension": "c", "filename": "simpson-3-8-rule.c", "fork_events_count": 1, "gha_created_at": "2021-02-13T04:53:36", "gha_event_created_at": "2021-02-25T10:38:39", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 338499693, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1128, "license": "MIT", "license_type": "permissive", "path": "/c-solutions/simpson-3-8-rule.c", "provenance": "stackv2-0030.json.gz:7870", "repo_name": "nsn39/nm-solutions", "revision_date": "2021-02-25T10:38:39", "revision_id": "f4ad5af6c728f73ec313bb0015c753119d46667f", "snapshot_id": "d9f88ca3abe875f75cb3670d4193309894c9b3d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nsn39/nm-solutions/f4ad5af6c728f73ec313bb0015c753119d46667f/c-solutions/simpson-3-8-rule.c", "visit_date": "2023-03-11T15:02:23.071886" }
stackv2
#include <stdio.h> #include <math.h> double func3(double x){ return pow(3,x) + x*tan(x); } int main(){ double upper_limit, lower_limit; int sub_intervals; printf("For function 3^x + x*tan(x):\n"); printf("Enter the (upper_limit, lower_limit) for integration :"); scanf("%lf %lf", &upper_limit, &lower_limit); printf("Enter the number of sub-intervals :"); scanf("%d", &sub_intervals); if (sub_intervals % 3 != 0){ fprintf(stderr, "Number of sub-intervals must be a multiple of 3.\n"); return 1; } double step = (upper_limit - lower_limit)/sub_intervals; double integrate_value = func3(lower_limit) + func3(upper_limit); lower_limit += step; int index_count = 1; printf("x\t\ty=f(x)\n"); while(lower_limit < upper_limit){ if (index_count % 3 == 0) integrate_value += 2 * func3(lower_limit); else integrate_value += 3 * func3(lower_limit); printf("%lf\t%lf\n",lower_limit, func3(lower_limit)); lower_limit += step; index_count++; } integrate_value *= (3.0/8) * step; printf("The value of integration is : %lf\n", integrate_value); return 0; }
3.515625
4
2024-11-18T18:39:52.341974+00:00
2018-05-28T22:34:42
d5d4a42898b7f7c19a89ef8c26c3aba483d39a2c
{ "blob_id": "d5d4a42898b7f7c19a89ef8c26c3aba483d39a2c", "branch_name": "refs/heads/master", "committer_date": "2018-05-28T22:34:42", "content_id": "4c2aaff2523183df0ffc5f55efda6d1047c2e9d2", "detected_licenses": [ "MIT" ], "directory_id": "aea9456d090d539a46ea4f4bfa44da99f6235399", "extension": "c", "filename": "util.c", "fork_events_count": 0, "gha_created_at": "2018-06-10T09:07:02", "gha_event_created_at": "2018-06-10T09:07:02", "gha_language": null, "gha_license_id": "MIT", "github_id": 136794310, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3578, "license": "MIT", "license_type": "permissive", "path": "/src/cixl/util.c", "provenance": "stackv2-0030.json.gz:7998", "repo_name": "felixonmars/cixl", "revision_date": "2018-05-28T22:34:42", "revision_id": "39d0d29b02d417f68b6c9201279027d9c3fdbeb2", "snapshot_id": "e42f7d9a2d3cee1d336e9c88a3f2a6f091950c70", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/felixonmars/cixl/39d0d29b02d417f68b6c9201279027d9c3fdbeb2/src/cixl/util.c", "visit_date": "2020-03-19T18:06:47.815117" }
stackv2
#include <errno.h> #include <fcntl.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "cixl/cx.h" #include "cixl/error.h" #include "cixl/util.h" char *cx_vfmt(const char *spec, va_list args) { va_list size_args; va_copy(size_args, args); int len = vsnprintf(NULL, 0, spec, size_args); va_end(size_args); char *out = malloc(len+1); vsnprintf(out, len+1, spec, args); return out; } char *cx_fmt(const char *spec, ...) { va_list args; va_start(args, spec); char *res = cx_vfmt(spec, args); va_end(args); return res; } char *cx_get_dir(const char *in, char *out, size_t len) { const char *pos = strrchr(in, '/'); if (!pos) { pos = strrchr(in, '\\'); } if (!pos) { out[0] = 0; return out; } strncpy(out, in, cx_min(pos-in+1, len)); out[pos-in+1] = 0; return out; } bool cx_unblock(struct cx *cx, int fd) { if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK) == -1) { cx_error(cx, cx->row, cx->col, "Failed unblocking: %d", errno); return false; } return true; } bool cx_noexec(struct cx *cx, int fd) { if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) { cx_error(cx, cx->row, cx->col, "Failed noexec: %d", errno); return false; } return true; } size_t cx_str_dist(const char *x, const char *y) { const size_t x_max = strlen(x)+1, y_max = strlen(y)+1; int *d = calloc(x_max*y_max, sizeof(int)); size_t get_index(size_t i, size_t j) { return i*y_max + j; } for (size_t i=1; i < x_max; i++) { d[get_index(i, 0)] = i; } for (size_t j=1; j < y_max; j++) { d[get_index(0, j)] = j; } for (size_t i=1; i < x_max; i++) { for (size_t j=1; j < y_max; j++) { int sc = (x[i-1] == y[j-1]) ? 0 : 1; d[get_index(i, j)] = cx_min(d[get_index(i-1, j)]+1, cx_min(d[get_index(i, j-1)]+1, d[get_index(i-1, j-1)] + sc)); } } int res = d[get_index(x_max-1, y_max-1)]; free(d); return res; } void cx_reverse(char *s, size_t len) { for (char *i = s, *j = s+len-1; i < j; i++, j--) { char c = *i; *i = *j; *j = c; } } bool cx_get_line(char **out, size_t *len, FILE *in) { if (getline(out, len, in) == -1) { return false; } for (char *c = *out; c < *out+*len; c++) { if (!*c) { *(c-1) = 0; break; } } return true; } const char *cx_home_dir() { const char *d = getenv("HOME"); if (!d) { d = getpwuid(getuid())->pw_dir; } return d; } bool cx_make_dir(const char *path) { char *p = strdup(path); bool ok = false; for (char *c = p+1; *c; c++) { if (*c == '/') { *c = '\0'; if (mkdir(p, S_IRWXU) != 0 && errno != EEXIST) { goto exit; } *c = '/'; } } ok = mkdir(p, S_IRWXU) == 0 || errno == EEXIST; exit: free(p); return ok; } char cx_bin_hex(unsigned char in) { cx_test(in < 16); static const char *hex = "0123456789abcdef"; return hex[in]; } int cx_hex_bin(char in) { switch(in) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': return 10; case 'b': return 11; case 'c': return 12; case 'd': return 13; case 'e': return 14; case 'f': return 15; default: break; } return -1; } int64_t cx_rand(int64_t max) { if (max <= 0) { return 0; } int64_t out = 0; int32_t *p = (int *)&out; *p++ = rand(); *p = rand(); return out % max; }
2.515625
3
2024-11-18T18:39:52.625393+00:00
2018-04-22T14:47:29
bae2d55652b492c5aec46dffba8af018db126b55
{ "blob_id": "bae2d55652b492c5aec46dffba8af018db126b55", "branch_name": "refs/heads/master", "committer_date": "2018-04-22T14:47:29", "content_id": "8e5c1c307e67c265d05222f3dae323c32767d57e", "detected_licenses": [ "MIT" ], "directory_id": "0c7a22f6bf736b0a116f4fdcae597b97580f5dda", "extension": "c", "filename": "Special.StaticAllocDestructor-FreeVariants.win32_heap_free.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 130574946, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1913, "license": "MIT", "license_type": "permissive", "path": "/Special.StaticAllocDestructor-FreeVariants.win32_heap_free.c", "provenance": "stackv2-0030.json.gz:8383", "repo_name": "me4tw/StaticAllocDestructor", "revision_date": "2018-04-22T14:47:29", "revision_id": "b214a8cace451237dd42208ea43ba2ce433b9ebc", "snapshot_id": "a4c836a533b3a8977d370fcc1f7a987d908040cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/me4tw/StaticAllocDestructor/b214a8cace451237dd42208ea43ba2ce433b9ebc/Special.StaticAllocDestructor-FreeVariants.win32_heap_free.c", "visit_date": "2020-03-12T10:31:20.694159" }
stackv2
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "Everywhere.h" /** @file @brief a bit overengineered for what probably no one will use, maybe */ #include <Windows.h> #include <stdio.h> #include <fcntl.h> #include <io.h> void win32_heap_free(void*mem) { HANDLE theHeap = INVALID_HANDLE_VALUE; BOOL success = FALSE; if (!mem) return;//undefined behavour to heapfree on null theHeap = GetProcessHeap(); success = HeapFree(theHeap, 0, mem); if (!success) { DWORD error = GetLastError(); if (GetConsoleWindow() == NULL)//no console window, create one then { AllocConsole();//we want the user to actually see the message if (GetConsoleWindow() != NULL)//and messageboxA will interrupt program execution { HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((long)handle_out, _O_TEXT); FILE* hf_out = _fdopen(hCrt, "w"); setvbuf(hf_out, NULL, _IONBF, 1); *stdout = *hf_out; HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((long)handle_in, _O_TEXT); FILE* hf_in = _fdopen(hCrt, "r"); setvbuf(hf_in, NULL, _IONBF, 128); *stdin = *hf_in; } // use the console just like a normal one - printf(), getchar(), ... } fprintf(stderr, "\nerror occured doing HeapFree(): %u ", error); //add some details { LPSTR messageBuffer = NULL; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); if (messageBuffer) { fputs(messageBuffer,stderr); //Free the buffer. LocalFree(messageBuffer); } } fputc('\n', stderr); } }
2.28125
2
2024-11-18T18:39:52.720093+00:00
2015-11-11T21:54:02
71265346d3d9747402bcd4cc0d2dc812e8a06994
{ "blob_id": "71265346d3d9747402bcd4cc0d2dc812e8a06994", "branch_name": "refs/heads/master", "committer_date": "2015-11-11T21:54:02", "content_id": "bdb1efc68bb34247a28a14e33ee5b335df505e5a", "detected_licenses": [ "MIT" ], "directory_id": "3ee43a3ff9e550ec8985d2f1073bd6a316296cc0", "extension": "h", "filename": "task.h", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31962604, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 516, "license": "MIT", "license_type": "permissive", "path": "/kernel/include/kernel/task.h", "provenance": "stackv2-0030.json.gz:8512", "repo_name": "krinkinmu/auos", "revision_date": "2015-11-11T21:54:02", "revision_id": "3d53214b0b6c766ccf497c6b011a9fbef2791673", "snapshot_id": "b013a82c3d568e0899c2876a16e819f8ff68c9c1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/krinkinmu/auos/3d53214b0b6c766ccf497c6b011a9fbef2791673/kernel/include/kernel/task.h", "visit_date": "2021-01-23T06:39:08.798769" }
stackv2
#ifndef __KERNEL_TASK_H__ #define __KERNEL_TASK_H__ #include <kernel/list.h> #include <arch/memory.h> typedef int tid_t; struct task { struct list_head link; tid_t tid; }; static inline struct task *current_task(void) { unsigned long sp = ((unsigned long)&sp) & ~(KERNEL_STACK_ALIGN - 1); return (struct task *)sp; } struct task *alloc_task(void); void free_task(struct task *task); void task_init(struct task *task, void (*entry)(void)); void task_switch(struct task *task); #endif /*__KERNEL_TASK_H__*/
2.015625
2
2024-11-18T18:39:52.828640+00:00
2012-02-23T16:34:00
7d8980e8c652de617ad0cf359ee31c5abd75fa8b
{ "blob_id": "7d8980e8c652de617ad0cf359ee31c5abd75fa8b", "branch_name": "refs/heads/master", "committer_date": "2012-02-23T16:34:00", "content_id": "d737ac52b8541167dba37b6765809ad7bcfad40d", "detected_licenses": [ "BSL-1.0" ], "directory_id": "0a4dde19079a5028b1b0869b79b6c94d28749fad", "extension": "h", "filename": "bintree_root.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 868478, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2464, "license": "BSL-1.0", "license_type": "permissive", "path": "/c/bintree/bintree_root.h", "provenance": "stackv2-0030.json.gz:8640", "repo_name": "swelef/binary_tree", "revision_date": "2012-02-23T16:34:00", "revision_id": "b1e792a878c5324af4fa1f23c413b1a20a015e87", "snapshot_id": "b117012addf81dfc042facb924c97877b991067a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/swelef/binary_tree/b1e792a878c5324af4fa1f23c413b1a20a015e87/c/bintree/bintree_root.h", "visit_date": "2016-09-10T17:07:54.958600" }
stackv2
// Copyright Vladimir Marko 2005 - 2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef VMARKO_BINTREE_ROOT_H_INCLUDED #define VMARKO_BINTREE_ROOT_H_INCLUDED #include "bintree_impl_begin.h" // functions to query and modify the root of a binary tree /* * The class template bintree_root provides functions for querying and * modifying a binary tree whose links are described by the BINTREE_* macros, * see the description in bintree_base. * * The functions provided by the template are the getters front(.), back(.) * and top(.), with const versions prefixed by 'c', and setters set_front(.,.) * set_back(.,.) and set_top(.,.). * * Note that the functions provided by this template are for low level tree * manipulation and usually don't need external linkage, see the description * of the BINTREE_LINKAGE macro in bintree_base. */ // ---------------------------------------------------------------------------- // non-const functions // #if defined(BINTREE_POINTER) BINTREE_LKG_ BINTREE_POINTER BINTREE_MANGLE_(front)( BINTREE_TRPAR_ BINTREE_POINTER root_); BINTREE_LKG_ BINTREE_POINTER BINTREE_MANGLE_(back)( BINTREE_TRPAR_ BINTREE_POINTER root_); BINTREE_LKG_ BINTREE_POINTER BINTREE_MANGLE_(top)( BINTREE_TRPAR_ BINTREE_POINTER root_); BINTREE_LKG_ void BINTREE_MANGLE_(set_front)( BINTREE_TRPAR_ BINTREE_POINTER root_,BINTREE_POINTER new_); BINTREE_LKG_ void BINTREE_MANGLE_(set_back)( BINTREE_TRPAR_ BINTREE_POINTER root_,BINTREE_POINTER new_); BINTREE_LKG_ void BINTREE_MANGLE_(set_top)( BINTREE_TRPAR_ BINTREE_POINTER root_,BINTREE_POINTER new_); #endif // defined(BINTREE_POINTER) // ---------------------------------------------------------------------------- // const functions // #if defined(BINTREE_CONST_POINTER) BINTREE_LKG_ BINTREE_CONST_POINTER BINTREE_MANGLE_(cfront)( BINTREE_TRPAR_ BINTREE_CONST_POINTER root_); BINTREE_LKG_ BINTREE_CONST_POINTER BINTREE_MANGLE_(cback)( BINTREE_TRPAR_ BINTREE_CONST_POINTER root_); BINTREE_LKG_ BINTREE_CONST_POINTER BINTREE_MANGLE_(ctop)( BINTREE_TRPAR_ BINTREE_CONST_POINTER root_); #endif // defined(BINTREE_CONST_POINTER) #include "bintree_impl_end.h" #endif // #ifndef VMARKO_BINTREE_ROOT_H_INCLUDED
2
2
2024-11-18T18:39:52.888124+00:00
2023-08-28T23:30:43
b8114b2e816ef7e977d3c7b83479047a4f26070d
{ "blob_id": "b8114b2e816ef7e977d3c7b83479047a4f26070d", "branch_name": "refs/heads/master", "committer_date": "2023-08-28T23:30:43", "content_id": "7c25e28c12c0113561dc42d373a3834f0fa04b11", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "badb70a0b235c98ac034cfe5b4bfafda36647831", "extension": "c", "filename": "OcSerializeLib.c", "fork_events_count": 2999, "gha_created_at": "2019-04-03T19:14:29", "gha_event_created_at": "2023-09-10T18:29:53", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 179354282, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12577, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Library/OcSerializeLib/OcSerializeLib.c", "provenance": "stackv2-0030.json.gz:8768", "repo_name": "acidanthera/OpenCorePkg", "revision_date": "2023-08-28T23:30:43", "revision_id": "1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6", "snapshot_id": "f34a7d67b22c74fb5ab559e48519e5f5855b6751", "src_encoding": "UTF-8", "star_events_count": 13212, "url": "https://raw.githubusercontent.com/acidanthera/OpenCorePkg/1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6/Library/OcSerializeLib/OcSerializeLib.c", "visit_date": "2023-08-30T21:03:02.993659" }
stackv2
/** @file OcSerializeLib Copyright (c) 2018, vit9696 All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include <Library/OcSerializeLib.h> #include <Library/BaseLib.h> #include <Library/DebugLib.h> #if defined (MDEPKG_NDEBUG) #if defined (__GNUC__) || defined (__clang__) #define GetSchemaTypeName(expression) (NULL) #endif #else STATIC CONST CHAR8 * mSchemaTypeNames[] = { [OC_SCHEMA_VALUE_BOOLEAN] = "boolean", [OC_SCHEMA_VALUE_INTEGER] = "integer", [OC_SCHEMA_VALUE_DATA] = "data", [OC_SCHEMA_VALUE_STRING] = "string", [OC_SCHEMA_VALUE_MDATA] = "mdata" }; STATIC CONST CHAR8 * GetSchemaTypeName ( IN UINT32 Type ) { if (Type < ARRAY_SIZE (mSchemaTypeNames)) { return mSchemaTypeNames[Type]; } return "custom"; } #endif OC_SCHEMA * LookupConfigSchema ( IN OC_SCHEMA *SortedList, IN UINT32 Size, IN CONST CHAR8 *Name ) { UINT32 Start; UINT32 End; UINT32 Curr; INTN Cmp; if (Size == 0) { return NULL; } // // Classic binary search in a sorted string list. // Start = 0; End = Size - 1; while (Start <= End) { Curr = (Start + End) / 2; Cmp = AsciiStrCmp (SortedList[Curr].Name, Name); if (Cmp == 0) { return &SortedList[Curr]; } else if (Cmp < 0) { Start = Curr + 1; } else if (Curr > 0) { End = Curr - 1; } else { // // Even the first element does not match, required due to unsigned End. // return NULL; } } return NULL; } VOID ParseSerializedDict ( OUT VOID *Serialized, IN XML_NODE *Node, IN OC_SCHEMA_INFO *Info, IN CONST CHAR8 *Context OPTIONAL, IN OUT UINT32 *ErrorCount OPTIONAL ) { UINT32 DictSize; UINT32 Index; UINT32 Index2; CONST CHAR8 *CurrentKey; XML_NODE *CurrentValue; XML_NODE *OldValue; OC_SCHEMA *NewSchema; DictSize = PlistDictChildren (Node); for (Index = 0; Index < DictSize; Index++) { CurrentKey = PlistKeyValue (PlistDictChild (Node, Index, &CurrentValue)); if (CurrentKey == NULL) { DEBUG ((DEBUG_WARN, "OCS: No serialized key at %u index, context <%a>!\n", Index, Context)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } // // Skip comments. // if (CurrentKey[0] == '#') { continue; } DEBUG ((DEBUG_VERBOSE, "OCS: Parsing serialized at %a at %u index!\n", CurrentKey, Index)); // // We do not protect from duplicating serialized entries. // NewSchema = LookupConfigSchema (Info->Dict.Schema, Info->Dict.SchemaSize, CurrentKey); if (NewSchema == NULL) { DEBUG ((DEBUG_WARN, "OCS: No schema for %a at %u index, context <%a>!\n", CurrentKey, Index, Context)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } OldValue = CurrentValue; CurrentValue = PlistNodeCast (CurrentValue, NewSchema->Type); if (CurrentValue == NULL) { DEBUG (( DEBUG_WARN, "OCS: No type match for %a at %u index, expected type %a got %a, context <%a>!\n", CurrentKey, Index, GetSchemaTypeName (NewSchema->Type), XmlNodeName (OldValue), Context )); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } NewSchema->Apply (Serialized, CurrentValue, &NewSchema->Info, CurrentKey, ErrorCount); } DEBUG_CODE_BEGIN (); for (Index = 0; Index < Info->Dict.SchemaSize; ++Index) { if (Info->Dict.Schema[Index].Optional) { continue; } for (Index2 = 0; Index2 < DictSize; ++Index2) { CurrentKey = PlistKeyValue (PlistDictChild (Node, Index2, NULL)); if (CurrentKey == NULL) { continue; } if (AsciiStrCmp (CurrentKey, Info->Dict.Schema[Index].Name) == 0) { break; } } if (Index2 == DictSize) { DEBUG (( DEBUG_WARN, "OCS: Missing key %a, context <%a>!\n", Info->Dict.Schema[Index].Name, Context )); if (ErrorCount != NULL) { ++*ErrorCount; } } } DEBUG_CODE_END (); } VOID ParseSerializedValue ( OUT VOID *Serialized, IN XML_NODE *Node, IN OC_SCHEMA_INFO *Info, IN CONST CHAR8 *Context OPTIONAL, IN OUT UINT32 *ErrorCount OPTIONAL ) { BOOLEAN Result; VOID *Field; UINT32 Size; Result = FALSE; Field = OC_SCHEMA_FIELD (Serialized, VOID, Info->Value.Field); Size = Info->Value.FieldSize; switch (Info->Value.Type) { case OC_SCHEMA_VALUE_BOOLEAN: Result = PlistBooleanValue (Node, (BOOLEAN *)Field); break; case OC_SCHEMA_VALUE_INTEGER: Result = PlistIntegerValue (Node, Field, Size, FALSE); break; case OC_SCHEMA_VALUE_DATA: Result = PlistDataValue (Node, Field, &Size); break; case OC_SCHEMA_VALUE_STRING: Result = PlistStringValue (Node, Field, &Size); break; case OC_SCHEMA_VALUE_MDATA: Result = PlistMultiDataValue (Node, Field, &Size); break; } if (Result == FALSE) { DEBUG (( DEBUG_WARN, "OCS: Failed to parse %a field as value with type %a and <%a> contents, context <%a>!\n", XmlNodeName (Node), GetSchemaTypeName (Info->Value.Type), XmlNodeContent (Node) != NULL ? XmlNodeContent (Node) : "empty", Context )); if (ErrorCount != NULL) { ++*ErrorCount; } } } VOID ParseSerializedBlob ( OUT VOID *Serialized, IN XML_NODE *Node, IN OC_SCHEMA_INFO *Info, IN CONST CHAR8 *Context OPTIONAL, IN OUT UINT32 *ErrorCount OPTIONAL ) { BOOLEAN Result; VOID *Field; UINT32 Size; VOID *BlobMemory; UINT32 *BlobSize; Result = FALSE; switch (Info->Blob.Type) { case OC_SCHEMA_BLOB_DATA: Result = PlistDataSize (Node, &Size); break; case OC_SCHEMA_BLOB_STRING: Result = PlistStringSize (Node, &Size); break; case OC_SCHEMA_BLOB_MDATA: Result = PlistMultiDataSize (Node, &Size); break; } if (Result == FALSE) { DEBUG (( DEBUG_WARN, "OCS: Failed to calculate size of %a field containing <%a> as type %a, context <%a>!\n", XmlNodeName (Node), XmlNodeContent (Node) != NULL ? XmlNodeContent (Node) : "empty", GetSchemaTypeName (Info->Blob.Type), Context )); if (ErrorCount != NULL) { ++*ErrorCount; } return; } Field = OC_SCHEMA_FIELD (Serialized, VOID, Info->Blob.Field); BlobMemory = OcBlobAllocate (Field, Size, &BlobSize); if (BlobMemory == NULL) { DEBUG (( DEBUG_INFO, "OCS: Failed to allocate %u bytes %a field of type %a, context <%a>!\n", Size, XmlNodeName (Node), GetSchemaTypeName (Info->Value.Type), Context )); if (ErrorCount != NULL) { ++*ErrorCount; } return; } Result = FALSE; switch (Info->Blob.Type) { case OC_SCHEMA_BLOB_DATA: Result = PlistDataValue (Node, (UINT8 *)BlobMemory, BlobSize); break; case OC_SCHEMA_BLOB_STRING: Result = PlistStringValue (Node, (CHAR8 *)BlobMemory, BlobSize); break; case OC_SCHEMA_BLOB_MDATA: Result = PlistMultiDataValue (Node, (UINT8 *)BlobMemory, BlobSize); break; } if (Result == FALSE) { DEBUG (( DEBUG_WARN, "OCS: Failed to parse %a field as blob with type %a and <%a> contents, context <%a>!\n", XmlNodeName (Node), GetSchemaTypeName (Info->Value.Type), XmlNodeContent (Node) != NULL ? XmlNodeContent (Node) : "empty", Context )); if (ErrorCount != NULL) { ++*ErrorCount; } } } VOID ParseSerializedMap ( OUT VOID *Serialized, IN XML_NODE *Node, IN OC_SCHEMA_INFO *Info, IN CONST CHAR8 *Context OPTIONAL, IN OUT UINT32 *ErrorCount OPTIONAL ) { UINT32 DictSize; UINT32 Index; CONST CHAR8 *CurrentKey; UINT32 CurrentKeyLen; XML_NODE *ChildNode; VOID *NewValue; VOID *NewKey; VOID *NewKeyValue; BOOLEAN Success; DictSize = PlistDictChildren (Node); for (Index = 0; Index < DictSize; Index++) { CurrentKey = PlistKeyValue (PlistDictChild (Node, Index, &ChildNode)); CurrentKeyLen = CurrentKey != NULL ? (UINT32)(AsciiStrLen (CurrentKey) + 1) : 0; if (CurrentKeyLen == 0) { DEBUG ((DEBUG_INFO, "OCS: No get serialized key at %u index!\n", Index)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } // // Skip comments. // if (CurrentKey[0] == '#') { continue; } if (PlistNodeCast (ChildNode, Info->List.Schema->Type) == NULL) { DEBUG ((DEBUG_INFO, "OCS: No valid serialized value at %u index!\n", Index)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } Success = OcListEntryAllocate ( OC_SCHEMA_FIELD (Serialized, VOID, Info->List.Field), &NewValue, &NewKey ); if (Success == FALSE) { DEBUG ((DEBUG_INFO, "OCS: Couldn't insert dict serialized at %u index!\n", Index)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } NewKeyValue = OcBlobAllocate (NewKey, CurrentKeyLen, NULL); if (NewKeyValue != NULL) { AsciiStrnCpyS ((CHAR8 *)NewKeyValue, CurrentKeyLen, CurrentKey, CurrentKeyLen - 1); } else { DEBUG ((DEBUG_INFO, "OCS: Couldn't allocate key name at %u index!\n", Index)); if (ErrorCount != NULL) { ++*ErrorCount; } } Info->List.Schema->Apply (NewValue, ChildNode, &Info->List.Schema->Info, CurrentKey, ErrorCount); } } VOID ParseSerializedArray ( OUT VOID *Serialized, IN XML_NODE *Node, IN OC_SCHEMA_INFO *Info, IN CONST CHAR8 *Context OPTIONAL, IN OUT UINT32 *ErrorCount OPTIONAL ) { UINT32 ArraySize; UINT32 Index; XML_NODE *ChildNode; VOID *NewValue; BOOLEAN Success; ArraySize = XmlNodeChildren (Node); for (Index = 0; Index < ArraySize; Index++) { ChildNode = PlistNodeCast (XmlNodeChild (Node, Index), Info->List.Schema->Type); DEBUG ((DEBUG_VERBOSE, "OCS: Processing array %u/%u element\n", Index + 1, ArraySize)); if (ChildNode == NULL) { DEBUG ((DEBUG_INFO, "OCS: Couldn't get array serialized at %u index!\n", Index)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } Success = OcListEntryAllocate ( OC_SCHEMA_FIELD (Serialized, VOID, Info->List.Field), &NewValue, NULL ); if (Success == FALSE) { DEBUG ((DEBUG_INFO, "OCS: Couldn't insert array serialized at %u index!\n", Index)); if (ErrorCount != NULL) { ++*ErrorCount; } continue; } Info->List.Schema->Apply (NewValue, ChildNode, &Info->List.Schema->Info, Context, ErrorCount); } } BOOLEAN ParseSerialized ( OUT VOID *Serialized, IN OC_SCHEMA_INFO *RootSchema, IN VOID *PlistBuffer, IN UINT32 PlistSize, IN OUT UINT32 *ErrorCount OPTIONAL ) { XML_DOCUMENT *Document; XML_NODE *RootDict; Document = XmlDocumentParse (PlistBuffer, PlistSize, FALSE); if (Document == NULL) { DEBUG ((DEBUG_INFO, "OCS: Couldn't parse serialized file!\n")); if (ErrorCount != NULL) { ++*ErrorCount; } return FALSE; } RootDict = PlistNodeCast (PlistDocumentRoot (Document), PLIST_NODE_TYPE_DICT); if (RootDict == NULL) { DEBUG ((DEBUG_INFO, "OCS: Couldn't get serialized root!\n")); XmlDocumentFree (Document); if (ErrorCount != NULL) { ++*ErrorCount; } return FALSE; } ParseSerializedDict ( Serialized, RootDict, RootSchema, "root", ErrorCount ); XmlDocumentFree (Document); return TRUE; }
2.15625
2
2024-11-18T18:39:54.028628+00:00
2019-02-21T12:57:12
2ec3092294c50702852d8e2f686e05076a212c5d
{ "blob_id": "2ec3092294c50702852d8e2f686e05076a212c5d", "branch_name": "refs/heads/master", "committer_date": "2019-02-23T10:17:03", "content_id": "c485249ff6221243464a30883d5c58505bd8b5c7", "detected_licenses": [ "MIT" ], "directory_id": "861067c2e312d3f617a3f8fb655f83d5cb15c7cf", "extension": "h", "filename": "utils.h", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 77805001, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3264, "license": "MIT", "license_type": "permissive", "path": "/utils.h", "provenance": "stackv2-0030.json.gz:9280", "repo_name": "lissyx/sensorweb-nodeMCU-PMS3003", "revision_date": "2019-02-21T12:57:12", "revision_id": "7e72e8d79f040bc07763f72e603dfdb3aa65585d", "snapshot_id": "4cb838f4d96414d0f5e57d051e3b6c7c120ad1ba", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/lissyx/sensorweb-nodeMCU-PMS3003/7e72e8d79f040bc07763f72e603dfdb3aa65585d/utils.h", "visit_date": "2021-01-12T04:52:02.107753" }
stackv2
#ifndef PM25_NODEMCU_UTILS_H #define PM25_NODEMCU_UTILS_H // It is reported that deepsleep takes ~250ms and wakeup ~75ms const unsigned long bootTime = 250 + 75; // Will rely on ntpConfig->ntpTZOffset to compute proper UTC time // e.g. 2017-01-26 at 15:00:00 Paris Time, it is 2017-01-26T15:00:00.000Z == 2017-01-26T15:00:00.000+01:00 String date_ISO8601(time_t date, bool asUTC = false, bool withTZ = true) { char iso8601[30]; if (asUTC) { // 2016-11-18T11:04:15.790Z time_t utcDate = date - (SECS_PER_HOUR * NtpConfig::getInstance()->ntpTZOffset); sprintf(iso8601, "%04d-%02d-%02dT%02d:%02d:%02d.000Z", year(utcDate), month(utcDate), day(utcDate), hour(utcDate), minute(utcDate), second(utcDate)); } else { // 2016-11-18T11:04:15.790+XX:YY char tzSign = (NtpConfig::getInstance()->ntpTZOffset < 0) ? '-' : '+'; signed int tzOffsetMin = (NtpConfig::getInstance()->ntpTZOffset) * SECS_PER_MIN; unsigned int tzH = abs(floor(tzOffsetMin / SECS_PER_MIN)); unsigned int tzM = abs(floor(tzOffsetMin % SECS_PER_MIN)); if (withTZ) { sprintf(iso8601, "%04d-%02d-%02dT%02d:%02d:%02d.000%c%02d:%02d", year(date), month(date), day(date), hour(date), minute(date), second(date), tzSign, tzH, tzM); } else { sprintf(iso8601, "%04d-%02d-%02dT%02d:%02d:%02d.000", year(date), month(date), day(date), hour(date), minute(date), second(date)); } } return String(iso8601); } bool safelyWriteNewFile(String fileName, String fileContent) { /* try to read it from a file */ bool mounted = SPIFFS.begin(); int bytesWrote = -1; if (!mounted) { serialUdpIntDebug("FS: Unable to mount"); } else { // Previous file does not exists, let us populate it if (!SPIFFS.exists(fileName)) { File file = SPIFFS.open(fileName, "w"); if (!file) { serialUdpIntDebug("FS: Unable to write-open: " + String(fileName)); } else { bytesWrote = file.println(fileContent); file.close(); serialUdpIntDebug("FS: Wrote " + String(bytesWrote) + " to " + String(fileName)); } } if (bytesWrote == 0) { serialUdpIntDebug("FS: Remove empty " + String(fileName)); SPIFFS.remove(fileName); } } SPIFFS.end(); return (bytesWrote > 0); } bool safelyRemoveFile(String fileName) { bool mounted = SPIFFS.begin(); bool rv = false; if (!mounted) { serialUdpIntDebug("FS: Unable to mount"); } else { serialUdpIntDebug("FS: Remove empty " + String(fileName)); rv = SPIFFS.remove(fileName); } SPIFFS.end(); return rv; } String getSensorName() { return "NodeMCU-PMS3003"; } String prettifyMac() { String mac = WiFi.macAddress(); mac.replace(":", ""); return mac; } String getSensorPackageName() { return getSensorName() + ":" + prettifyMac(); } String getMeasureType() { return "Particulate Matter"; } String getMeasureShortType() { return "PM"; } String getUnitSymbol() { return "µg/m³"; } String getUnitName() { return "micrograms per cubic meter"; } String getSessionDescription() { return "PM2.5 autonomous Sensor, based on PMS3003"; } String getSessionTags() { return "pm2.5"; } String getSessionTitle() { return "PMS3003-PM2.5:" + prettifyMac(); } #endif // PM25_NODEMCU_UTILS_H
2.375
2
2024-11-18T18:39:54.901052+00:00
2014-03-03T04:23:29
79a9be416defda770ac9b656df28746468c4b2c2
{ "blob_id": "79a9be416defda770ac9b656df28746468c4b2c2", "branch_name": "refs/heads/master", "committer_date": "2014-03-03T04:23:29", "content_id": "16f423ca85bd2ffc33cfa5fb006e82893d0a6ba3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a92a91a02b97334487fd89deb29064dd109b965d", "extension": "c", "filename": "ite_convf900.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6590, "license": "Apache-2.0", "license_type": "permissive", "path": "/multimedia/imaging/ite_nmf/src/miscelious/ite_convf900.c", "provenance": "stackv2-0030.json.gz:10305", "repo_name": "AveHornet/vendor_st-ericsson_u8500", "revision_date": "2014-03-03T04:23:29", "revision_id": "5c3c8f4491a9996429c52ecc946bf76d3c4fc5a8", "snapshot_id": "4af9987f79cbe9bebd142c770cf10c36ac959fd7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AveHornet/vendor_st-ericsson_u8500/5c3c8f4491a9996429c52ecc946bf76d3c4fc5a8/multimedia/imaging/ite_nmf/src/miscelious/ite_convf900.c", "visit_date": "2021-01-21T09:07:00.004338" }
stackv2
/* * Copyright (C) ST-Ericsson SA 2010. All rights reserved. * This code is ST-Ericsson proprietary and confidential. * Any use of the code for whatever purpose is subject to * specific written permission of ST-Ericsson SA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Maximum values for 16-bit and 32-bit float exponents. */ #define MAX_EXPONENT_VALUE_16_BIT (unsigned char)0x3F #define MAX_EXPONENT_VALUE_32_BIT (unsigned char)0xFF /* Masks to extract the sign, exponent and mantissa of a 16-bit float. */ #define SIGN_16_BIT_MASK (unsigned short)0x8000 #define EXPONENT_16_BIT_MASK (unsigned short)0x7E00 #define MANTISSA_16_BIT_MASK (unsigned short)0x01FF /* Shifts to extract the sign, exponent and mantissa of a 16-bit float. */ #define SIGN_16_BIT_SHIFT 15 #define EXPONENT_16_BIT_SHIFT 9 #define MANTISSA_16_BIT_SHIFT 0 /* Mantissa of the special value NaN in the 16-bit hexadecimal format. */ #define MANTISSA_16_BIT_NAN (unsigned short)0x01FF /* Masks to extract the sign, exponent and mantissa of a 32-bit float. */ #define SIGN_32_BIT_MASK (unsigned long)0x80000000 #define EXPONENT_32_BIT_MASK (unsigned long)0x7F800000 #define MANTISSA_32_BIT_MASK (unsigned long)0x007FFFFF /* Shifts to extract the sign, exponent and mantissa of a 32-bit float. */ #define SIGN_32_BIT_SHIFT 31 #define EXPONENT_32_BIT_SHIFT 23 #define MANTISSA_32_BIT_SHIFT 0 /* Mantissa of the special value NaN in the 32-bit hexadecimal format. */ #define MANTISSA_32_BIT_NAN (unsigned long)0x007FFFFF /* Shift for renormalizing the mantissa between 16-bit and 32-bit formats. */ #define MANTISSA_RENORMALIZATION_SHIFT 14 /* Bounds which define the range within which a 32-bit float can be represented using a 16-bit float format (with a loss of precision for the mantissa). */ #define REPRESENTATION_LOWER_BOUND (unsigned char)0x61 #define REPRESENTATION_UPPER_BOUND (unsigned char)0x9E void ITE_ConvertTo32BitFloat(unsigned short fpIn, float* fpOut) { unsigned long* fpAux; /* Necessary to apply the masks on fpOut. */ unsigned long mantissa_16_bit; unsigned char sign_16_bit; unsigned char exponent_16_bit; fpAux = (unsigned long*)fpOut; sign_16_bit = (fpIn & SIGN_16_BIT_MASK) >> SIGN_16_BIT_SHIFT; //printf("sign_16_bit = 0x%x \n", sign_16_bit); exponent_16_bit = (fpIn & EXPONENT_16_BIT_MASK) >> EXPONENT_16_BIT_SHIFT; //printf("exponent_16_bit = 0x%x \n", exponent_16_bit); mantissa_16_bit = (fpIn & MANTISSA_16_BIT_MASK) >> MANTISSA_16_BIT_SHIFT; //printf("mantissa_16_bit = 0x%lx \n", mantissa_16_bit); if (exponent_16_bit == MAX_EXPONENT_VALUE_16_BIT) { /* Not a number, positive or negative infinity. */ exponent_16_bit = MAX_EXPONENT_VALUE_32_BIT; if (mantissa_16_bit != 0) { mantissa_16_bit = MANTISSA_32_BIT_NAN; } } else { if (exponent_16_bit == 0) { /* Original denormalized numbers are rounded off to zero. */ sign_16_bit = 0; mantissa_16_bit = 0; } else { /* Renormalization of the exponent into the 32-bit format. */ exponent_16_bit += REPRESENTATION_LOWER_BOUND - 1; /* Renormalization of the mantissa into the 32-bit format. */ mantissa_16_bit <<= MANTISSA_RENORMALIZATION_SHIFT; } } //printf("mantissa_16_bit = 0x%lx \n", mantissa_16_bit); *fpAux = ((sign_16_bit << SIGN_32_BIT_SHIFT) & SIGN_32_BIT_MASK) | ((exponent_16_bit << EXPONENT_32_BIT_SHIFT) & EXPONENT_32_BIT_MASK) | ((mantissa_16_bit << MANTISSA_32_BIT_SHIFT) & MANTISSA_32_BIT_MASK); //printf("*fpAux = 0x%lx \n", *fpAux); } void ITE_ConvertTo16BitFloat(volatile float fpIn, unsigned short* fpOut) { unsigned long* fpAux; /* Necessary to apply the masks on fpIn. */ unsigned long mantissa_32_bit; unsigned char sign_32_bit; unsigned char exponent_32_bit; fpAux = (unsigned long*)&fpIn; sign_32_bit = (*fpAux & SIGN_32_BIT_MASK) >> SIGN_32_BIT_SHIFT; //printf("sign_32_bit = 0x%x \n", sign_32_bit); exponent_32_bit = (*fpAux & EXPONENT_32_BIT_MASK) >> EXPONENT_32_BIT_SHIFT; //printf("exponent_32_bit = 0x%x \n", exponent_32_bit); mantissa_32_bit = (*fpAux & MANTISSA_32_BIT_MASK) >> MANTISSA_32_BIT_SHIFT; //printf("mantissa_32_bit = 0x%lx \n", mantissa_32_bit); if (exponent_32_bit == MAX_EXPONENT_VALUE_32_BIT) { /* Not a number, positive or negative infinity. */ exponent_32_bit = MAX_EXPONENT_VALUE_16_BIT; if (mantissa_32_bit != 0) { mantissa_32_bit = MANTISSA_16_BIT_NAN; } } else { if (exponent_32_bit < REPRESENTATION_LOWER_BOUND) { /* Original denormalized numbers as well as numbers whose exponent in the 32-bit format is inferior to the lower bound are rounded off to zero. */ sign_32_bit = 0; exponent_32_bit = 0; mantissa_32_bit = 0; } else { if (exponent_32_bit > REPRESENTATION_UPPER_BOUND) { /* Positive or negative infinity. */ exponent_32_bit = MAX_EXPONENT_VALUE_16_BIT; mantissa_32_bit = 0; } else { /* Renormalization of the exponent into the 16-bit format. */ exponent_32_bit -= REPRESENTATION_LOWER_BOUND - 1; /* Renormalization of the mantissa into the 16-bit format (approximation is by default). */ mantissa_32_bit >>= MANTISSA_RENORMALIZATION_SHIFT; } } } //printf("mantissa_32_bit = 0x%lx \n", mantissa_32_bit); *fpOut = ((sign_32_bit << SIGN_16_BIT_SHIFT) & SIGN_16_BIT_MASK) | ((exponent_32_bit << EXPONENT_16_BIT_SHIFT) & EXPONENT_16_BIT_MASK) | ((mantissa_32_bit << MANTISSA_16_BIT_SHIFT) & MANTISSA_16_BIT_MASK); //printf("*fpOut = 0x%x \n", *fpOut); } /* int main(void) { float f32; float fcheck; unsigned short f16; printf("Rentrer la valeur du flottant sur 32 bits (format decimal) : "); scanf("%f", &f32); FPAlu_ConvertTo16BitFloat(f32, &f16); printf("Valeur du flottant sur 16 bits (format hex.) : 0x%x \n", f16); FPAlu_ConvertTo32BitFloat(f16, &fcheck); printf("Valeur du flottant sur 32 bits (format decimal) : %.7f \n", fcheck); return 0; } */
2.875
3
2024-11-18T18:39:55.224594+00:00
2020-05-15T10:57:17
40a404db60a51b9a1ed590d50e396f7c01b4e430
{ "blob_id": "40a404db60a51b9a1ed590d50e396f7c01b4e430", "branch_name": "refs/heads/master", "committer_date": "2020-05-15T10:57:17", "content_id": "91f9a7a70c59762e1ab3a27b4532cd1ddeb6d5a5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "17df945db1899d1c5108f5280063fb9739b94922", "extension": "c", "filename": "test-nvme-rw.c", "fork_events_count": 0, "gha_created_at": "2020-02-27T13:14:29", "gha_event_created_at": "2020-05-15T10:57:18", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 243523056, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3630, "license": "Apache-2.0", "license_type": "permissive", "path": "/test/test-nvme-rw.c", "provenance": "stackv2-0030.json.gz:10690", "repo_name": "Benjaminmnoer/ox-ctrl", "revision_date": "2020-05-15T10:57:17", "revision_id": "49142abb4c729a7e1649549da2600324f6a8ef13", "snapshot_id": "533dd60fdb62890a8dae91383861683c98a3948c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Benjaminmnoer/ox-ctrl/49142abb4c729a7e1649549da2600324f6a8ef13/test/test-nvme-rw.c", "visit_date": "2021-02-01T16:59:15.039144" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <nvme-host.h> #define NVMEH_NUM_QUEUES 4 * (OXF_FULL_IFACES + 1) #define NVMEH_BUF_SIZE 1024 * 1024 * 8 /* 8 MB */ #define NVMEH_BLKSZ 4096 static volatile uint8_t done; /* This is an example context that identifies the completion */ struct nvme_test_context { uint64_t slba; uint64_t nlb; uint8_t is_write; }; void nvme_test_callback (void *ctx, uint16_t status) { struct nvme_test_context *my_ctx = (struct nvme_test_context *) ctx; printf ("Is write: %d, LBA %lu-%lu, size: %lu KB. Status -> %x\n", my_ctx->is_write, my_ctx->slba, my_ctx->slba + my_ctx->nlb, NVMEH_BLK_SZ * my_ctx->nlb / 1024, status); done++; } void nvme_test_read (void) { int ret; uint8_t *read_buffer; uint8_t *write_buffer; struct nvme_test_context ctx[2]; uint64_t slba; /* An example of write buffer */ write_buffer = malloc (NVMEH_BUF_SIZE); if (!write_buffer) { printf ("Memory allocation error.\n"); return; } memset (write_buffer, 0xca, NVMEH_BUF_SIZE); /* An example of read buffer */ read_buffer = malloc (NVMEH_BUF_SIZE); if (!read_buffer) { free (write_buffer); printf ("Memory allocation error.\n"); return; } /* Example of SLBA */ slba = 100; /* Sets the example context for write */ ctx[0].slba = slba; ctx[0].is_write = 1; ctx[0].nlb = NVMEH_BUF_SIZE / NVMEH_BLK_SZ; /* Submit the read command and define the callback function */ ret = nvmeh_write (write_buffer, NVMEH_BUF_SIZE, slba, nvme_test_callback, &ctx[0]); if (ret) { printf ("Write has failed.\n"); done++; } /* Wait until the write returns asynchronously */ while (done < 1) { usleep (100); } /* Sets the example for read */ ctx[1].slba = slba; ctx[1].is_write = 0; ctx[1].nlb = NVMEH_BUF_SIZE / NVMEH_BLK_SZ; /* Submit the read command and define the callback function */ ret = nvmeh_read (read_buffer, NVMEH_BUF_SIZE, slba, nvme_test_callback, &ctx[1]); if (ret) { printf ("Read has failed.\n"); done++; } /* Wait until the read returns asynchronously */ while (done < 2) { usleep (100); } if (memcmp (write_buffer, read_buffer, NVMEH_BUF_SIZE)) printf ("Data is NOT equal.\n"); else printf ("Data is equal.\n"); free (read_buffer); free (write_buffer); } int main (void) { int ret, q_id; ret = nvmeh_init (); if (ret) { printf ("Failed to initializing NVMe Host.\n"); return -1; } nvme_host_add_server_iface (OXF_ADDR_1, OXF_PORT_1); nvme_host_add_server_iface (OXF_ADDR_2, OXF_PORT_2); /* We just have 2 cables for now, for the real network setup */ #if OXF_FULL_IFACES nvme_host_add_server_iface (OXF_ADDR_3, OXF_PORT_3); nvme_host_add_server_iface (OXF_ADDR_4, OXF_PORT_4); #endif /* Create the NVMe queues. One additional queue for the admin queue */ for (q_id = 0; q_id < NVMEH_NUM_QUEUES + 1; q_id++) { if (nvme_host_create_queue (q_id)) { printf ("Failed to creating queue %d.\n", q_id); goto EXIT; } } done = 0; /* Read */ nvme_test_read (); /* Closes the application */ EXIT: while (q_id) { q_id--; nvme_host_destroy_queue (q_id); } nvmeh_exit (); return 0; }
2.40625
2
2024-11-18T18:39:55.392753+00:00
2021-03-20T14:31:58
1886724d0a8b43802832cb0c276ca7f16ba1af51
{ "blob_id": "1886724d0a8b43802832cb0c276ca7f16ba1af51", "branch_name": "refs/heads/main", "committer_date": "2021-03-20T14:38:24", "content_id": "f25bc6653d8b80ac66a8a3af993d10153b43b7f7", "detected_licenses": [ "MIT" ], "directory_id": "edf58351f7856e4d86739bd884ef92a7d3a2a404", "extension": "c", "filename": "rotor_sensor_analog.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3225, "license": "MIT", "license_type": "permissive", "path": "/esp32/rotor_sensor_analog.c", "provenance": "stackv2-0030.json.gz:10819", "repo_name": "laiqiqi/espFoC", "revision_date": "2021-03-20T14:31:58", "revision_id": "d0fc452fff2de3e5e899309747cd2bbc85893571", "snapshot_id": "384eeedbf5a7bb2075d39a3f217488be86207aa5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/laiqiqi/espFoC/d0fc452fff2de3e5e899309747cd2bbc85893571/esp32/rotor_sensor_analog.c", "visit_date": "2023-03-28T18:33:24.885778" }
stackv2
#include <unistd.h> #include <math.h> #include <sys/cdefs.h> #include "esp_heap_caps.h" #include "espFoC/rotor_sensor_analog.h" #include "esp_attr.h" typedef struct { float current_count; float previous_read; float counts_per_revolution; int adc_channel; float limit_high; float limit_low; esp_foc_rotor_sensor_t interface; }esp_foc_analog_rotor_sensor_t; static const adc_bits_width_t width = ADC_WIDTH_BIT_12; static const adc_atten_t atten = ADC_ATTEN_DB_0; IRAM_ATTR static float read_adc(int adc_channel) { return (float)(adc1_get_raw((adc1_channel_t)adc_channel)); } IRAM_ATTR static void set_to_zero(esp_foc_rotor_sensor_t *self) { esp_foc_analog_rotor_sensor_t *obj = __containerof(self,esp_foc_analog_rotor_sensor_t, interface); obj->current_count = 0.0f; obj->previous_read = read_adc(obj->adc_channel); } IRAM_ATTR static float get_counts_per_revolution(esp_foc_rotor_sensor_t *self) { esp_foc_analog_rotor_sensor_t *obj = __containerof(self,esp_foc_analog_rotor_sensor_t, interface); return obj->counts_per_revolution; } IRAM_ATTR static float read_counts(esp_foc_rotor_sensor_t *self) { esp_foc_analog_rotor_sensor_t *obj = __containerof(self,esp_foc_analog_rotor_sensor_t, interface); float raw = read_adc(obj->adc_channel); float delta = (raw - obj->previous_read); if(fabs(delta) > obj->counts_per_revolution) { obj->current_count = (delta < 0.0f) ? obj->current_count + obj->counts_per_revolution : obj->current_count + obj->counts_per_revolution; if(obj->current_count > obj->limit_high) { obj->current_count -= obj->limit_high; }else if (obj->current_count < obj->limit_low) { obj->current_count -= obj->limit_low; } } obj->previous_read = raw; return obj->current_count + raw; } IRAM_ATTR static void delay_ms(esp_foc_rotor_sensor_t *self, int ms) { (void)self; usleep(ms * 1000); } esp_err_t rotor_sensor_analog_init() { adc1_config_width(width); return ESP_OK; } esp_foc_rotor_sensor_t *rotor_sensor_analog_new(int adc_channel, int min_sensor_count, int max_sensor_count) { esp_foc_analog_rotor_sensor_t *obj = heap_caps_malloc( sizeof(esp_foc_analog_rotor_sensor_t), MALLOC_CAP_INTERNAL ); if(!obj) { return NULL; } obj->interface.get_counts_per_revolution = get_counts_per_revolution; obj->interface.read_counts = read_counts; obj->interface.set_to_zero = set_to_zero; obj->interface.delay_ms = delay_ms; obj->adc_channel = adc_channel; if(max_sensor_count < min_sensor_count) { obj->counts_per_revolution = min_sensor_count - max_sensor_count; } else { obj->counts_per_revolution = max_sensor_count - min_sensor_count; } obj->limit_high = 100.0f * obj->counts_per_revolution; obj->limit_low = -obj->limit_high; adc1_config_channel_atten(obj->adc_channel, atten); obj->previous_read = read_adc(obj->adc_channel); return &obj->interface; }
2.375
2
2024-11-18T18:39:56.016418+00:00
2019-01-09T22:01:35
9bbc7e86484223d1e73639ae4ca3700ddc5eb1f0
{ "blob_id": "9bbc7e86484223d1e73639ae4ca3700ddc5eb1f0", "branch_name": "refs/heads/master", "committer_date": "2019-01-09T22:01:35", "content_id": "d6ff2fe05f25a0da655e6e6707fa1242db01ed75", "detected_licenses": [ "MIT" ], "directory_id": "aa5fc85159f2d4373933259229cd374e99d9e6f5", "extension": "c", "filename": "video.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 150717184, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2932, "license": "MIT", "license_type": "permissive", "path": "/proj/code/video.c", "provenance": "stackv2-0030.json.gz:11203", "repo_name": "mbcsm/FEUP_LCOM", "revision_date": "2019-01-09T22:01:35", "revision_id": "fe1d84a30a93c36fb28912ea75e990ef213a6809", "snapshot_id": "2533a96a6eff7c1ed1c823df403c5a3cab5ebfdc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mbcsm/FEUP_LCOM/fe1d84a30a93c36fb28912ea75e990ef213a6809/proj/code/video.c", "visit_date": "2020-03-30T03:57:58.869740" }
stackv2
#include <lcom/lcf.h> #include "video.h" int(vg_start)(uint16_t mode) { lm_init(false); vbe_mode_info_t vbe_mode; vbe_get_mode_info(mode, &vbe_mode); v_res = vbe_mode.YResolution; h_res = vbe_mode.XResolution; bits_per_pixel = vbe_mode.BitsPerPixel; memory_model = vbe_mode.MemoryModel; BlueScreeMask = vbe_mode.BlueMaskSize; GreenScreeMask = vbe_mode.GreenMaskSize; RedScreeMask = vbe_mode.RedMaskSize; RedFieldPosition = vbe_mode.RedFieldPosition; BlueFieldPosition = vbe_mode.BlueFieldPosition; GreenFieldPosition = vbe_mode.GreenFieldPosition; int r_mem; struct minix_mem_range mr; unsigned int vram_size = h_res * v_res * (bits_per_pixel / 8); mr.mr_base = (phys_bytes) vbe_mode.PhysBasePtr; mr.mr_limit = mr.mr_base + vram_size; if (OK != (r_mem = sys_privctl(SELF, SYS_PRIV_ADD_MEM, &mr))) panic("sys_privctl (ADD_MEM) failed: %d\n", r_mem); /* Map memory */ video_mem = vm_map_phys(SELF, (void *) mr.mr_base, vram_size); if (video_mem == MAP_FAILED) panic("couldn’t map video memory"); back_buffer = malloc(vram_size); struct reg86u reg86; memset(&reg86, 0, sizeof(reg86)); /* zero the structure */ reg86.u.w.ax = 0x4F02; // VBE call, function 02 -- set VBE mode reg86.u.w.bx = (1 << 14) | mode; // set bit 14: linear framebuffer reg86.u.b.intno = 0x10; if (sys_int86(&reg86) != OK) { printf("set_vbe_mode: sys_int86() failed \n"); return 1; } return 0; } int(get_h_res)(){ return h_res; } int(get_v_res)(){ return v_res; } int(get_bits_per_pixel)(){ return bits_per_pixel; } void * (get_video_mem)(){ return video_mem; } void * (get_back_buffer)() { return back_buffer; } uint8_t (get_memory_model)(){ return memory_model; } uint8_t(get_blue_screen_mask)(){ return BlueScreeMask; } uint8_t(get_green_screen_mask)(){ return GreenScreeMask; } uint8_t(get_red_screen_mask)(){ return RedScreeMask; } uint8_t(get_blue_screen_mask_position)(){ return BlueFieldPosition; } uint8_t(get_green_screen_mask_position)(){ return GreenFieldPosition; } uint8_t(get_red_screen_mask_position)(){ return RedFieldPosition; } void (clearScreen)(){ for (unsigned i = 0; i < h_res; i++) for (unsigned j = 0; j < v_res; j++){ changePixel(i,j,0x0000); } } uint16_t (getpixel)(int x, int y){ uint16_t color; int h_res = get_h_res(); //int bits_per_pixel = get_bits_per_pixel(); void *video_mem = get_video_mem(); uint16_t *ptr_VM = (uint16_t*)video_mem; ptr_VM += (y * h_res + x); color = *ptr_VM; return color; } void (changePixel)(int x, int y, uint16_t color){ int h_res = get_h_res(); void *video_mem = get_video_mem(); uint16_t *ptr_VM = (uint16_t*)video_mem; ptr_VM += (y * h_res + x); *ptr_VM = color; /* void *vm = get_video_mem(); char *ptr_VM = vm; ptr_VM += (i + h_res * j) * (bits_per_pixel / 8); *ptr_VM = color;*/ }
2.421875
2
2024-11-18T18:39:56.086049+00:00
2020-03-25T16:51:01
086cc299fdebb757d3e3ba918a20835a8ae83679
{ "blob_id": "086cc299fdebb757d3e3ba918a20835a8ae83679", "branch_name": "refs/heads/master", "committer_date": "2020-03-25T16:51:01", "content_id": "f97842ed00bdf710bf6b91c2a9f375046599c204", "detected_licenses": [ "MIT" ], "directory_id": "1c129f4f6c908e3b6647485f40b76441b6d4a5cb", "extension": "c", "filename": "main (Robin).c", "fork_events_count": 0, "gha_created_at": "2020-03-24T16:42:46", "gha_event_created_at": "2020-03-24T16:42:47", "gha_language": null, "gha_license_id": "MIT", "github_id": 249762677, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2098, "license": "MIT", "license_type": "permissive", "path": "/src/main (Robin).c", "provenance": "stackv2-0030.json.gz:11332", "repo_name": "Das-ist-gutt/Tetris-Game-in-C", "revision_date": "2020-03-25T16:51:01", "revision_id": "46905fda6f4ca23e42c63f95bdd0d2a2e20d0be7", "snapshot_id": "18e4a07ee811b83510717e48ca222fe617f6cf5d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Das-ist-gutt/Tetris-Game-in-C/46905fda6f4ca23e42c63f95bdd0d2a2e20d0be7/src/main (Robin).c", "visit_date": "2021-04-21T07:55:30.206044" }
stackv2
/* ** EPITECH PROJECT, 2019 ** kawai ** File description: ** main */ #include <stdio.h> #include <stdlib.h> #include "tetris.h" int show_help(void) { my_putstr("Usage: ./tetris [options]\n"); my_putstr("Options:\n"); my_putstr("\t--help\tDisplay this help\n"); my_putstr("\t-L --level={num}\tStart Tetris at level num (def: 1)\n"); my_putstr("\t-l --key-left={K}\tMove the tetrimino LEFT "); my_putstr("using the K key (def: left arrow)\n"); my_putstr("\t-r --key-right={K}\tMove the tetrimino RIGHT "); my_putstr("using the K key (def: right arrow)\n"); my_putstr("\t-t --key-turn={K}\tTURN the tetrimino clockwise "); my_putstr("90d using the K key (def: top arrow)\n"); my_putstr("\t-d --key-drop={K}\tDROP the tetrimino "); my_putstr("using the K key (def: down arrow)\n\t-q --key-quit={K}"); my_putstr("\tQUIT the game using the K key (def: ‘q’ key)\n"); my_putstr("\t-p --key-pause={K}\tPAUSE/RESTART the "); my_putstr("game using the K key (def: space bar)\n"); my_putstr("\t--map-size={row,col}\tSet the "); my_putstr("numbers of rows and columns of the map (def: 20,10)\n"); my_putstr("\t-w --without-next\tHide next tetrimino (def: false)\n"); my_putstr("\t-D --debug\tDebug mode (def: false)\n"); return (0); } int main (int ac, char **argc) { arg_t **arg = NULL; config_t *config = NULL; game_t *game = load_game_struct(); tetri_t *tetrim = malloc(sizeof(tetri_t)); tetrim->next = NULL; if (ac > 1 && compare(argc[1], "--help")) show_help(); else if (ac > 1) arg = argument_parser(ac, argc); config = load_config(arg); load_tetr(&tetrim); if (config->debug == 1) debug(config); start_game(game, config); return (0); } game_t *load_game_struct(void) { game_t *game = malloc(sizeof(game_t)); return (game); } int start_game(game_t *game, config_t *config) { //initscr(); //clear(); //refresh(); //noecho(); //keypad(stdscr, TRUE); //clear(); //refresh(); //endwin(); return (0); }
2.796875
3
2024-11-18T18:39:56.436419+00:00
2023-08-11T18:10:35
2d171c52597c1cceec82143e59acff7e9f9cb2b3
{ "blob_id": "2d171c52597c1cceec82143e59acff7e9f9cb2b3", "branch_name": "refs/heads/master", "committer_date": "2023-08-11T18:10:35", "content_id": "e36283c55fa51b9efec59200fd7255bdaa571f52", "detected_licenses": [ "MIT" ], "directory_id": "31f5cddb9885fc03b5c05fba5f9727b2f775cf47", "extension": "c", "filename": "chipset.c", "fork_events_count": 102, "gha_created_at": "2018-03-10T04:07:35", "gha_event_created_at": "2021-06-11T14:29:03", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 124620874, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 124900, "license": "MIT", "license_type": "permissive", "path": "/thirdparty/google/cpuinfo/src/arm/linux/chipset.c", "provenance": "stackv2-0030.json.gz:11589", "repo_name": "timi-liuliang/echo", "revision_date": "2023-08-11T18:10:35", "revision_id": "d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24", "snapshot_id": "2935a34b80b598eeb2c2039d686a15d42907d6f7", "src_encoding": "UTF-8", "star_events_count": 822, "url": "https://raw.githubusercontent.com/timi-liuliang/echo/d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24/thirdparty/google/cpuinfo/src/arm/linux/chipset.c", "visit_date": "2023-08-17T05:35:08.104918" }
stackv2
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <arm/linux/api.h> #ifdef __ANDROID__ #include <arm/android/api.h> #endif #include <cpuinfo/log.h> #include <cpuinfo/common.h> static inline bool is_ascii_whitespace(char c) { switch (c) { case ' ': case '\t': case '\r': case '\n': return true; default: return false; } } static inline bool is_ascii_alphabetic(char c) { const char lower_c = c | '\x20'; return (uint8_t) (lower_c - 'a') <= (uint8_t) ('z' - 'a'); } static inline bool is_ascii_alphabetic_uppercase(char c) { return (uint8_t) (c - 'A') <= (uint8_t) ('Z' - 'A'); } static inline bool is_ascii_numeric(char c) { return (uint8_t) (c - '0') < 10; } static inline uint16_t load_u16le(const void* ptr) { #if defined(__ARM_ARCH_7A__) || defined(__aarch64__) return *((const uint16_t*) ptr); #else const uint8_t* byte_ptr = (const uint8_t*) ptr; return ((uint16_t) byte_ptr[1] << 8) | (uint16_t) byte_ptr[0]; #endif } static inline uint32_t load_u24le(const void* ptr) { #if defined(__ARM_ARCH_7A__) || defined(__aarch64__) return ((uint32_t) ((const uint8_t*) ptr)[2] << 16) | ((uint32_t) *((const uint16_t*) ptr)); #else const uint8_t* byte_ptr = (const uint8_t*) ptr; return ((uint32_t) byte_ptr[2] << 16) | ((uint32_t) byte_ptr[1] << 8) | (uint32_t) byte_ptr[0]; #endif } static inline uint32_t load_u32le(const void* ptr) { #if defined(__ARM_ARCH_7A__) || defined(__aarch64__) return *((const uint32_t*) ptr); #else return ((uint32_t) ((const uint8_t*) ptr)[3] << 24) | load_u24le(ptr); #endif } /* * Map from ARM chipset series ID to ARM chipset vendor ID. * This map is used to avoid storing vendor IDs in tables. */ static enum cpuinfo_arm_chipset_vendor chipset_series_vendor[cpuinfo_arm_chipset_series_max] = { [cpuinfo_arm_chipset_series_unknown] = cpuinfo_arm_chipset_vendor_unknown, [cpuinfo_arm_chipset_series_qualcomm_qsd] = cpuinfo_arm_chipset_vendor_qualcomm, [cpuinfo_arm_chipset_series_qualcomm_msm] = cpuinfo_arm_chipset_vendor_qualcomm, [cpuinfo_arm_chipset_series_qualcomm_apq] = cpuinfo_arm_chipset_vendor_qualcomm, [cpuinfo_arm_chipset_series_qualcomm_snapdragon] = cpuinfo_arm_chipset_vendor_qualcomm, [cpuinfo_arm_chipset_series_mediatek_mt] = cpuinfo_arm_chipset_vendor_mediatek, [cpuinfo_arm_chipset_series_samsung_exynos] = cpuinfo_arm_chipset_vendor_samsung, [cpuinfo_arm_chipset_series_hisilicon_k3v] = cpuinfo_arm_chipset_vendor_hisilicon, [cpuinfo_arm_chipset_series_hisilicon_hi] = cpuinfo_arm_chipset_vendor_hisilicon, [cpuinfo_arm_chipset_series_hisilicon_kirin] = cpuinfo_arm_chipset_vendor_hisilicon, [cpuinfo_arm_chipset_series_actions_atm] = cpuinfo_arm_chipset_vendor_actions, [cpuinfo_arm_chipset_series_allwinner_a] = cpuinfo_arm_chipset_vendor_allwinner, [cpuinfo_arm_chipset_series_amlogic_aml] = cpuinfo_arm_chipset_vendor_amlogic, [cpuinfo_arm_chipset_series_amlogic_s] = cpuinfo_arm_chipset_vendor_amlogic, [cpuinfo_arm_chipset_series_broadcom_bcm] = cpuinfo_arm_chipset_vendor_broadcom, [cpuinfo_arm_chipset_series_lg_nuclun] = cpuinfo_arm_chipset_vendor_lg, [cpuinfo_arm_chipset_series_leadcore_lc] = cpuinfo_arm_chipset_vendor_leadcore, [cpuinfo_arm_chipset_series_marvell_pxa] = cpuinfo_arm_chipset_vendor_marvell, [cpuinfo_arm_chipset_series_mstar_6a] = cpuinfo_arm_chipset_vendor_mstar, [cpuinfo_arm_chipset_series_novathor_u] = cpuinfo_arm_chipset_vendor_novathor, [cpuinfo_arm_chipset_series_nvidia_tegra_t] = cpuinfo_arm_chipset_vendor_nvidia, [cpuinfo_arm_chipset_series_nvidia_tegra_ap] = cpuinfo_arm_chipset_vendor_nvidia, [cpuinfo_arm_chipset_series_nvidia_tegra_sl] = cpuinfo_arm_chipset_vendor_nvidia, [cpuinfo_arm_chipset_series_pinecone_surge_s] = cpuinfo_arm_chipset_vendor_pinecone, [cpuinfo_arm_chipset_series_renesas_mp] = cpuinfo_arm_chipset_vendor_renesas, [cpuinfo_arm_chipset_series_rockchip_rk] = cpuinfo_arm_chipset_vendor_rockchip, [cpuinfo_arm_chipset_series_spreadtrum_sc] = cpuinfo_arm_chipset_vendor_spreadtrum, [cpuinfo_arm_chipset_series_telechips_tcc] = cpuinfo_arm_chipset_vendor_telechips, [cpuinfo_arm_chipset_series_texas_instruments_omap] = cpuinfo_arm_chipset_vendor_texas_instruments, [cpuinfo_arm_chipset_series_wondermedia_wm] = cpuinfo_arm_chipset_vendor_wondermedia, }; /** * Tries to match /(MSM|APQ)\d{4}([A-Z\-]*)/ signature (case-insensitive) for Qualcomm MSM and APQ chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board, ro.board.platform * or ro.chipname) to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board, ro.board.platform or * ro.chipname) to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_msm_apq( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect at least 7 symbols: 3 symbols "MSM" or "APQ" + 4 digits */ if (start + 7 > end) { return false; } /* Check that string starts with "MSM" or "APQ", case-insensitive. * The first three characters are loaded as 24-bit little endian word, binary ORed with 0x20 to convert to lower * case, and compared to "MSM" and "APQ" strings as integers. */ const uint32_t series_signature = UINT32_C(0x00202020) | load_u24le(start); enum cpuinfo_arm_chipset_series series; switch (series_signature) { case UINT32_C(0x6D736D): /* "msm" = reverse("msm") */ series = cpuinfo_arm_chipset_series_qualcomm_msm; break; case UINT32_C(0x717061): /* "qpa" = reverse("apq") */ series = cpuinfo_arm_chipset_series_qualcomm_apq; break; default: return false; } /* Sometimes there is a space ' ' following the MSM/APQ series */ const char* pos = start + 3; if (*pos == ' ') { pos++; /* Expect at least 4 more symbols (4-digit model number) */ if (pos + 4 > end) { return false; } } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 0; i < 4; i++) { const uint32_t digit = (uint32_t) (uint8_t) (*pos++) - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Suffix is optional, so if we got to this point, parsing is successful. Commit parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_qualcomm, .series = series, .model = model, }; /* Parse as many suffix characters as match the pattern [A-Za-z\-] */ for (uint32_t i = 0; i < CPUINFO_ARM_CHIPSET_SUFFIX_MAX; i++) { if (pos + i == end) { break; } const char c = pos[i]; if (is_ascii_alphabetic(c)) { /* Matched a letter [A-Za-z] */ chipset->suffix[i] = c & '\xDF'; } else if (c == '-') { /* Matched a dash '-' */ chipset->suffix[i] = c; } else { /* Neither of [A-Za-z\-] */ break; } } return true; } /** * Tries to match /SDM\d{3}$/ signature for Qualcomm Snapdragon chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_sdm( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 6 symbols: 3 symbols "SDM" + 3 digits */ if (start + 6 != end) { return false; } /* Check that string starts with "SDM". * The first three characters are loaded and compared as 24-bit little endian word. */ const uint32_t expected_sdm = load_u24le(start); if (expected_sdm != UINT32_C(0x004D4453) /* "MDS" = reverse("SDM") */) { return false; } /* Validate and parse 3-digit model number */ uint32_t model = 0; for (uint32_t i = 3; i < 6; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_qualcomm, .series = cpuinfo_arm_chipset_series_qualcomm_snapdragon, .model = model, }; return true; } /** * Tries to match /SM\d{4}$/ signature for Qualcomm Snapdragon chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_sm( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 6 symbols: 2 symbols "SM" + 4 digits */ if (start + 6 != end) { return false; } /* Check that string starts with "SM". * The first three characters are loaded and compared as 16-bit little endian word. */ const uint32_t expected_sm = load_u16le(start); if (expected_sm != UINT16_C(0x4D53) /* "MS" = reverse("SM") */) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 2; i < 6; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_qualcomm, .series = cpuinfo_arm_chipset_series_qualcomm_snapdragon, .model = model, }; return true; } /** * Tries to match /Samsung Exynos\d{4}$/ signature (case-insensitive) for Samsung Exynos chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_samsung_exynos( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* * Expect at 18-19 symbols: * - "Samsung" (7 symbols) + space + "Exynos" (6 symbols) + optional space 4-digit model number */ const size_t length = end - start; switch (length) { case 18: case 19: break; default: return false; } /* * Check that the string starts with "samsung exynos", case-insensitive. * Blocks of 4 characters are loaded and compared as little-endian 32-bit word. * Case-insensitive characters are binary ORed with 0x20 to convert them to lowercase. */ const uint32_t expected_sams = UINT32_C(0x20202000) | load_u32le(start); if (expected_sams != UINT32_C(0x736D6153) /* "smaS" = reverse("Sams") */) { return false; } const uint32_t expected_ung = UINT32_C(0x00202020) | load_u32le(start + 4); if (expected_ung != UINT32_C(0x20676E75) /* " ung" = reverse("ung ") */) { return false; } const uint32_t expected_exyn = UINT32_C(0x20202000) | load_u32le(start + 8); if (expected_exyn != UINT32_C(0x6E797845) /* "nyxE" = reverse("Exyn") */) { return false; } const uint16_t expected_os = UINT16_C(0x2020) | load_u16le(start + 12); if (expected_os != UINT16_C(0x736F) /* "so" = reverse("os") */) { return false; } const char* pos = start + 14; /* There can be a space ' ' following the "Exynos" string */ if (*pos == ' ') { pos++; /* If optional space if present, we expect exactly 19 characters */ if (length != 19) { return false; } } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 0; i < 4; i++) { const uint32_t digit = (uint32_t) (uint8_t) (*pos++) - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_samsung, .series = cpuinfo_arm_chipset_series_samsung_exynos, .model = model, }; return true; } /** * Tries to match /exynos\d{4}$/ signature for Samsung Exynos chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (ro.board.platform or ro.chipname) to match. * @param end - end of the platform identifier (ro.board.platform or ro.chipname) to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_exynos( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 10 symbols: "exynos" (6 symbols) + 4-digit model number */ if (start + 10 != end) { return false; } /* Load first 4 bytes as little endian 32-bit word */ const uint32_t expected_exyn = load_u32le(start); if (expected_exyn != UINT32_C(0x6E797865) /* "nyxe" = reverse("exyn") */ ) { return false; } /* Load next 2 bytes as little endian 16-bit word */ const uint16_t expected_os = load_u16le(start + 4); if (expected_os != UINT16_C(0x736F) /* "so" = reverse("os") */ ) { return false; } /* Check and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 6; i < 10; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_samsung, .series = cpuinfo_arm_chipset_series_samsung_exynos, .model = model, }; return true; } /** * Tries to match /universal\d{4}$/ signature for Samsung Exynos chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board or ro.chipname) * to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board or ro.chipname) * to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_universal( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 13 symbols: "universal" (9 symbols) + 4-digit model number */ if (start + 13 != end) { return false; } /* * Check that the string starts with "universal". * Blocks of 4 characters are loaded and compared as little-endian 32-bit word. * Case-insensitive characters are binary ORed with 0x20 to convert them to lowercase. */ const uint8_t expected_u = UINT8_C(0x20) | (uint8_t) start[0]; if (expected_u != UINT8_C(0x75) /* "u" */) { return false; } const uint32_t expected_nive = UINT32_C(0x20202020) | load_u32le(start + 1); if (expected_nive != UINT32_C(0x6576696E) /* "evin" = reverse("nive") */ ) { return false; } const uint32_t expected_ersa = UINT32_C(0x20202020) | load_u32le(start + 5); if (expected_ersa != UINT32_C(0x6C617372) /* "lasr" = reverse("rsal") */) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 9; i < 13; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_samsung, .series = cpuinfo_arm_chipset_series_samsung_exynos, .model = model, }; return true; } /** * Compares, case insensitively, a string to known values "SMDK4210" and "SMDK4x12" for Samsung Exynos chipsets. * If platform identifier matches one of the SMDK* values, extracts model information into \p chipset argument. * For "SMDK4x12" match, decodes the chipset name using number of cores. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string or ro.product.board) to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardware string or ro.product.board) to match. * @param cores - number of cores in the chipset. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_and_parse_smdk( const char* start, const char* end, uint32_t cores, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 8 symbols: "SMDK" (4 symbols) + 4-digit model number */ if (start + 8 != end) { return false; } /* * Check that string starts with "MT" (case-insensitive). * The first four characters are loaded as a 32-bit little endian word and converted to lowercase. */ const uint32_t expected_smdk = UINT32_C(0x20202020) | load_u32le(start); if (expected_smdk != UINT32_C(0x6B646D73) /* "kdms" = reverse("smdk") */) { return false; } /* * Check that string ends with "4210" or "4x12". * The last four characters are loaded and compared as a 32-bit little endian word. */ uint32_t model = 0; const uint32_t expected_model = load_u32le(start + 4); switch (expected_model) { case UINT32_C(0x30313234): /* "0124" = reverse("4210") */ model = 4210; break; case UINT32_C(0x32317834): /* "21x4" = reverse("4x12") */ switch (cores) { case 2: model = 4212; break; case 4: model = 4412; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core Exynos 4x12 chipset", cores); } } if (model == 0) { return false; } *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_samsung, .series = cpuinfo_arm_chipset_series_samsung_exynos, .model = model, }; return true; } /** * Tries to match /MTK?\d{4}[A-Z/]*$/ signature for MediaTek MT chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board, ro.board.platform, * ro.mediatek.platform, or ro.chipname) to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board, ro.board.platform, * ro.mediatek.platform, or ro.chipname) to match. * @param match_end - indicates if the function should attempt to match through the end of the string and fail if there * are unparsed characters in the end, or match only MTK signature, model number, and some of the * suffix characters (the ones that pass validation). * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_mt( const char* start, const char* end, bool match_end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect at least 6 symbols: "MT" (2 symbols) + 4-digit model number */ if (start + 6 > end) { return false; } /* * Check that string starts with "MT" (case-insensitive). * The first two characters are loaded as 16-bit little endian word and converted to lowercase. */ const uint16_t mt = UINT16_C(0x2020) | load_u16le(start); if (mt != UINT16_C(0x746D) /* "tm" */) { return false; } /* Some images report "MTK" rather than "MT" */ const char* pos = start + 2; if (((uint8_t) *pos | UINT8_C(0x20)) == (uint8_t) 'k') { pos++; /* Expect 4 more symbols after "MTK" (4-digit model number) */ if (pos + 4 > end) { return false; } } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 0; i < 4; i++) { const uint32_t digit = (uint32_t) (uint8_t) (*pos++) - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Record parsed chipset. This implicitly zeroes-out suffix, which will be parsed later. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_mediatek, .series = cpuinfo_arm_chipset_series_mediatek_mt, .model = model, }; if (match_end) { /* Check that the potential suffix does not exceed maximum length */ const size_t suffix_length = end - pos; if (suffix_length > CPUINFO_ARM_CHIPSET_SUFFIX_MAX) { return false; } /* Validate suffix characters and copy them to chipset structure */ for (size_t i = 0; i < suffix_length; i++) { const char c = (*pos++); if (is_ascii_alphabetic(c)) { /* Matched a letter [A-Za-z], convert to uppercase */ chipset->suffix[i] = c & '\xDF'; } else if (c == '/') { /* Matched a slash '/' */ chipset->suffix[i] = c; } else { /* Invalid suffix character (neither of [A-Za-z/]) */ return false; } } } else { /* Validate and parse as many suffix characters as we can */ for (size_t i = 0; i < CPUINFO_ARM_CHIPSET_SUFFIX_MAX; i++) { if (pos + i == end) { break; } const char c = pos[i]; if (is_ascii_alphabetic(c)) { /* Matched a letter [A-Za-z], convert to uppercase */ chipset->suffix[i] = c & '\xDF'; } else if (c == '/') { /* Matched a slash '/' */ chipset->suffix[i] = c; } else { /* Invalid suffix character (neither of [A-Za-z/]). This marks the end of the suffix. */ break; } } } /* All suffix characters successfully validated and copied to chipset data */ return true; } /** * Tries to match /[Kk]irin\s?\d{3}$/ signature for HiSilicon Kirin chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_kirin( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect 8-9 symbols: "Kirin" (5 symbols) + optional whitespace (1 symbol) + 3-digit model number */ const size_t length = end - start; switch (length) { case 8: case 9: break; default: return false; } /* Check that the string starts with "Kirin" or "kirin". */ if (((uint8_t) start[0] | UINT8_C(0x20)) != (uint8_t) 'k') { return false; } /* Symbols 1-5 are loaded and compared as little-endian 32-bit word. */ const uint32_t irin = load_u32le(start + 1); if (irin != UINT32_C(0x6E697269) /* "niri" = reverse("irin") */) { return false; } /* Check for optional whitespace after "Kirin" */ if (is_ascii_whitespace(start[5])) { /* When whitespace is present after "Kirin", expect 9 symbols total */ if (length != 9) { return false; } } /* Validate and parse 3-digit model number */ uint32_t model = 0; for (int32_t i = 0; i < 3; i++) { const uint32_t digit = (uint32_t) (uint8_t) end[i - 3] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* * Thats it, return parsed chipset. * Technically, Kirin 910T has a suffix, but it never appears in the form of "910T" string. * Instead, Kirin 910T devices report "hi6620oem" string (handled outside of this function). */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_hisilicon, .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = model, }; return true; } /** * Tries to match /rk\d{4}[a-z]?$/ signature for Rockchip RK chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string or ro.board.platform) to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardware string or ro.board.platform) to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_rk( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect 6-7 symbols: "RK" (2 symbols) + 4-digit model number + optional 1-letter suffix */ const size_t length = end - start; switch (length) { case 6: case 7: break; default: return false; } /* * Check that string starts with "RK" (case-insensitive). * The first two characters are loaded as 16-bit little endian word and converted to lowercase. */ const uint16_t expected_rk = UINT16_C(0x2020) | load_u16le(start); if (expected_rk != UINT16_C(0x6B72) /* "kr" = reverse("rk") */) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 2; i < 6; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Parse optional suffix */ char suffix = 0; if (length == 7) { /* Parse the suffix letter */ const char c = start[6]; if (is_ascii_alphabetic(c)) { /* Convert to upper case */ suffix = c & '\xDF'; } else { /* Invalid suffix character */ return false; } } /* Return parsed chipset */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_rockchip, .series = cpuinfo_arm_chipset_series_rockchip_rk, .model = model, .suffix = { [0] = suffix, }, }; return true; } /** * Tries to match, case-insentitively, /s[cp]\d{4}[a-z]*|scx15$/ signature for Spreadtrum SC chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board, * ro.board.platform, or ro.chipname) to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board, * ro.board.platform, or ro.chipname) to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_sc( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect at least 5 symbols: "scx15" */ if (start + 5 > end) { return false; } /* * Check that string starts with "S[CP]" (case-insensitive). * The first two characters are loaded as 16-bit little endian word and converted to lowercase. */ const uint16_t expected_sc_or_sp = UINT16_C(0x2020) | load_u16le(start); switch (expected_sc_or_sp) { case UINT16_C(0x6373): /* "cs" = reverse("sc") */ case UINT16_C(0x7073): /* "ps" = reverse("sp") */ break; default: return false; } /* Special case: "scx" prefix (SC7715 reported as "scx15") */ if ((start[2] | '\x20') == 'x') { /* Expect exactly 5 characters: "scx15" */ if (start + 5 != end) { return false; } /* Check that string ends with "15" */ const uint16_t expected_15 = load_u16le(start + 3); if (expected_15 != UINT16_C(0x3531) /* "51" = reverse("15") */ ) { return false; } *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_spreadtrum, .series = cpuinfo_arm_chipset_series_spreadtrum_sc, .model = 7715, }; return true; } /* Expect at least 6 symbols: "S[CP]" (2 symbols) + 4-digit model number */ if (start + 6 > end) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 2; i < 6; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Write parsed chipset */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_spreadtrum, .series = cpuinfo_arm_chipset_series_spreadtrum_sc, .model = model, }; /* Validate and copy suffix letters. If suffix is too long, truncate at CPUINFO_ARM_CHIPSET_SUFFIX_MAX letters. */ const char* suffix = start + 6; for (size_t i = 0; i < CPUINFO_ARM_CHIPSET_SUFFIX_MAX; i++) { if (suffix + i == end) { break; } const char c = suffix[i]; if (!is_ascii_alphabetic(c)) { /* Invalid suffix character */ return false; } /* Convert suffix letter to uppercase */ chipset->suffix[i] = c & '\xDF'; } return true; } /** * Tries to match /lc\d{4}[a-z]?$/ signature for Leadcore LC chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (ro.product.board or ro.board.platform) to match. * @param end - end of the platform identifier (ro.product.board or ro.board.platform) to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_lc( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect at 6-7 symbols: "lc" (2 symbols) + 4-digit model number + optional 1-letter suffix */ const size_t length = end - start; switch (length) { case 6: case 7: break; default: return false; } /* Check that string starts with "lc". The first two characters are loaded as 16-bit little endian word */ const uint16_t expected_lc = load_u16le(start); if (expected_lc != UINT16_C(0x636C) /* "cl" = reverse("lc") */) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 2; i < 6; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Parse optional suffix letter */ char suffix = 0; if (length == 7) { const char c = start[6]; if (is_ascii_alphabetic(c)) { /* Convert to uppercase */ chipset->suffix[0] = c & '\xDF'; } else { /* Invalid suffix character */ return false; } } /* Return parsed chipset */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_leadcore, .series = cpuinfo_arm_chipset_series_leadcore_lc, .model = model, .suffix = { [0] = suffix, }, }; return true; } /** * Tries to match /PXA(\d{3,4}|1L88)$/ signature for Marvell PXA chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the platform identifier (/proc/cpuinfo Hardware string, ro.product.board or ro.chipname) * to match. * @param end - end of the platform identifier (/proc/cpuinfo Hardaware string, ro.product.board or ro.chipname) to * match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_pxa( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect 6-7 symbols: "PXA" (3 symbols) + 3-4 digit model number */ const size_t length = end - start; switch (length) { case 6: case 7: break; default: return false; } /* Check that the string starts with "PXA". Symbols 1-3 are loaded and compared as little-endian 16-bit word. */ if (start[0] != 'P') { return false; } const uint16_t expected_xa = load_u16le(start + 1); if (expected_xa != UINT16_C(0x4158) /* "AX" = reverse("XA") */) { return false; } uint32_t model = 0; /* Check for a very common typo: "PXA1L88" for "PXA1088" */ if (length == 7) { /* Load 4 model "number" symbols as a little endian 32-bit word and compare to "1L88" */ const uint32_t expected_1L88 = load_u32le(start + 3); if (expected_1L88 == UINT32_C(0x38384C31) /* "88L1" = reverse("1L88") */) { model = 1088; goto write_chipset; } } /* Check and parse 3-4 digit model number */ for (uint32_t i = 3; i < length; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ write_chipset: *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_marvell, .series = cpuinfo_arm_chipset_series_marvell_pxa, .model = model, }; return true; } /** * Tries to match /BCM\d{4}$/ signature for Broadcom BCM chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_bcm( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 7 symbols: "BCM" (3 symbols) + 4-digit model number */ if (start + 7 != end) { return false; } /* Check that the string starts with "BCM". * The first three characters are loaded and compared as a 24-bit little endian word. */ const uint32_t expected_bcm = load_u24le(start); if (expected_bcm != UINT32_C(0x004D4342) /* "MCB" = reverse("BCM") */) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 3; i < 7; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_broadcom, .series = cpuinfo_arm_chipset_series_broadcom_bcm, .model = model, }; return true; } /** * Tries to match /OMAP\d{4}$/ signature for Texas Instruments OMAP chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_omap( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 8 symbols: "OMAP" (4 symbols) + 4-digit model number */ if (start + 8 != end) { return false; } /* Check that the string starts with "OMAP". Symbols 0-4 are loaded and compared as little-endian 32-bit word. */ const uint32_t expected_omap = load_u32le(start); if (expected_omap != UINT32_C(0x50414D4F) /* "PAMO" = reverse("OMAP") */) { return false; } /* Validate and parse 4-digit model number */ uint32_t model = 0; for (uint32_t i = 4; i < 8; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Return parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_texas_instruments, .series = cpuinfo_arm_chipset_series_texas_instruments_omap, .model = model, }; return true; } /** * Compares platform identifier string to known values for Broadcom chipsets. * If the string matches one of the known values, the function decodes Broadcom chipset from frequency and number of * cores into \p chipset argument. * * @param start - start of the platform identifier (ro.product.board or ro.board.platform) to match. * @param end - end of the platform identifier (ro.product.board or ro.board.platform) to match. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * @param[out] chipset - location where chipset information will be stored upon a successful match and decoding. * * @returns true if signature matched (even if exact model can't be decoded), false otherwise. */ static bool match_and_parse_broadcom( const char* start, const char* end, uint32_t cores, uint32_t max_cpu_freq_max, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect 4-6 symbols: "java" (4 symbols), "rhea" (4 symbols), "capri" (5 symbols), or "hawaii" (6 symbols) */ const size_t length = end - start; switch (length) { case 4: case 5: case 6: break; default: return false; } /* * Compare the platform identifier to known values for Broadcom chipsets: * - "rhea" * - "java" * - "capri" * - "hawaii" * Upon a successful match, decode chipset name from frequency and number of cores. */ uint32_t model = 0; char suffix = 0; const uint32_t expected_platform = load_u32le(start); switch (expected_platform) { case UINT32_C(0x61656872): /* "aehr" = reverse("rhea") */ if (length == 4) { /* * Detected "rhea" platform: * - 1 core @ 849999 KHz -> BCM21654 * - 1 core @ 999999 KHz -> BCM21654G */ if (cores == 1) { model = 21654; if (max_cpu_freq_max >= 999999) { suffix = 'G'; } } } break; case UINT32_C(0x6176616A): /* "avaj" = reverse("java") */ if (length == 4) { /* * Detected "java" platform: * - 4 cores -> BCM23550 */ if (cores == 4) { model = 23550; } } break; case UINT32_C(0x61776168): /* "awah" = reverse("hawa") */ if (length == 6) { /* Check that string equals "hawaii" */ const uint16_t expected_ii = load_u16le(start + 4); if (expected_ii == UINT16_C(0x6969) /* "ii" */ ) { /* * Detected "hawaii" platform: * - 1 core -> BCM21663 * - 2 cores @ 999999 KHz -> BCM21664 * - 2 cores @ 1200000 KHz -> BCM21664T */ switch (cores) { case 1: model = 21663; break; case 2: model = 21664; if (max_cpu_freq_max >= 1200000) { suffix = 'T'; } break; } } } break; case UINT32_C(0x72706163): /* "rpac" = reverse("capr") */ if (length == 5) { /* Check that string equals "capri" */ if (start[4] == 'i') { /* * Detected "capri" platform: * - 2 cores -> BCM28155 */ if (cores == 2) { model = 28155; } } } break; } if (model != 0) { /* Chipset was successfully decoded */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_broadcom, .series = cpuinfo_arm_chipset_series_broadcom_bcm, .model = model, .suffix = { [0] = suffix, }, }; } return model != 0; } struct sunxi_map_entry { uint8_t sunxi; uint8_t cores; uint8_t model; char suffix; }; static const struct sunxi_map_entry sunxi_map_entries[] = { #if CPUINFO_ARCH_ARM { /* ("sun4i", 1) -> "A10" */ .sunxi = 4, .cores = 1, .model = 10, }, { /* ("sun5i", 1) -> "A13" */ .sunxi = 5, .cores = 1, .model = 13, }, { /* ("sun6i", 4) -> "A31" */ .sunxi = 6, .cores = 4, .model = 31, }, { /* ("sun7i", 2) -> "A20" */ .sunxi = 7, .cores = 2, .model = 20, }, { /* ("sun8i", 2) -> "A23" */ .sunxi = 8, .cores = 2, .model = 23, }, { /* ("sun8i", 4) -> "A33" */ .sunxi = 8, .cores = 4, .model = 33, }, { /* ("sun8i", 8) -> "A83T" */ .sunxi = 8, .cores = 8, .model = 83, .suffix = 'T', }, { /* ("sun9i", 8) -> "A80" */ .sunxi = 9, .cores = 8, .model = 80, }, #endif /* CPUINFO_ARCH_ARM */ { /* ("sun50i", 4) -> "A64" */ .sunxi = 50, .cores = 4, .model = 64, }, }; /** * Tries to match /proc/cpuinfo Hardware string to Allwinner /sun\d+i/ signature. * If the string matches signature, the function decodes Allwinner chipset from the number in the signature and the * number of cores, and stores it in \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param cores - number of cores in the chipset. * @param[out] chipset - location where chipset information will be stored upon a successful match and decoding. * * @returns true if signature matched (even if exact model can't be decoded), false otherwise. */ static bool match_and_parse_sunxi( const char* start, const char* end, uint32_t cores, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect at least 5 symbols: "sun" (3 symbols) + platform id (1-2 digits) + "i" (1 symbol) */ if (start + 5 > end) { return false; } /* Compare the first 3 characters to "sun" */ if (start[0] != 's') { return false; } const uint16_t expected_un = load_u16le(start + 1); if (expected_un != UINT16_C(0x6E75) /* "nu" = reverse("un") */) { return false; } /* Check and parse the first (required) digit of the sunXi platform id */ uint32_t sunxi_platform = 0; { const uint32_t digit = (uint32_t) (uint8_t) start[3] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } sunxi_platform = digit; } /* Parse optional second digit of the sunXi platform id */ const char* pos = start + 4; { const uint32_t digit = (uint32_t) (uint8_t) (*pos) - '0'; if (digit < 10) { sunxi_platform = sunxi_platform * 10 + digit; if (++pos == end) { /* Expected one more character, final 'i' letter */ return false; } } } /* Validate the final 'i' letter */ if (*pos != 'i') { return false; } /* Compare sunXi platform id and number of cores to tabluted values to decode chipset name */ uint32_t model = 0; char suffix = 0; for (size_t i = 0; i < CPUINFO_COUNT_OF(sunxi_map_entries); i++) { if (sunxi_platform == sunxi_map_entries[i].sunxi && cores == sunxi_map_entries[i].cores) { model = sunxi_map_entries[i].model; suffix = sunxi_map_entries[i].suffix; break; } } if (model == 0) { cpuinfo_log_info("unrecognized %"PRIu32"-core Allwinner sun%"PRIu32" platform", cores, sunxi_platform); } /* Create chipset name from decoded data */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_allwinner, .series = cpuinfo_arm_chipset_series_allwinner_a, .model = model, .suffix = { [0] = suffix, }, }; return true; } /** * Compares /proc/cpuinfo Hardware string to "WMT" signature. * If the string matches signature, the function decodes WonderMedia chipset from frequency and number of cores into * \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * @param[out] chipset - location where chipset information will be stored upon a successful match and decoding. * * @returns true if signature matched (even if exact model can't be decoded), false otherwise. */ static bool match_and_parse_wmt( const char* start, const char* end, uint32_t cores, uint32_t max_cpu_freq_max, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expected 3 symbols: "WMT" */ if (start + 3 != end) { return false; } /* Compare string to "WMT" */ if (start[0] != 'W') { return false; } const uint16_t expected_mt = load_u16le(start + 1); if (expected_mt != UINT16_C(0x544D) /* "TM" = reverse("MT") */) { return false; } /* Decode chipset name from frequency and number of cores */ uint32_t model = 0; switch (cores) { case 1: switch (max_cpu_freq_max) { case 1008000: /* 1 core @ 1008000 KHz -> WM8950 */ model = 8950; break; case 1200000: /* 1 core @ 1200000 KHz -> WM8850 */ model = 8850; break; } break; case 2: if (max_cpu_freq_max == 1500000) { /* 2 cores @ 1500000 KHz -> WM8880 */ model = 8880; } break; } if (model == 0) { cpuinfo_log_info("unrecognized WonderMedia platform with %"PRIu32" cores at %"PRIu32" KHz", cores, max_cpu_freq_max); } *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_wondermedia, .series = cpuinfo_arm_chipset_series_wondermedia_wm, .model = model, }; return true; } struct huawei_map_entry { uint32_t platform; uint32_t model; }; static const struct huawei_map_entry huawei_platform_map[] = { { /* "ALP" -> Kirin 970 */ .platform = UINT32_C(0x00504C41), /* "\0PLA" = reverse("ALP\0") */ .model = 970, }, { /* "BAC" -> Kirin 659 */ .platform = UINT32_C(0x00434142), /* "\0CAB" = reverse("BAC\0") */ .model = 659, }, { /* "BLA" -> Kirin 970 */ .platform = UINT32_C(0x00414C42), /* "\0ALB" = reverse("BLA\0") */ .model = 970, }, { /* "BKL" -> Kirin 970 */ .platform = UINT32_C(0x004C4B42), /* "\0LKB" = reverse("BKL\0") */ .model = 970, }, { /* "CLT" -> Kirin 970 */ .platform = UINT32_C(0x00544C43), /* "\0TLC" = reverse("CLT\0") */ .model = 970, }, { /* "COL" -> Kirin 970 */ .platform = UINT32_C(0x004C4F43), /* "\0LOC" = reverse("COL\0") */ .model = 970, }, { /* "COR" -> Kirin 970 */ .platform = UINT32_C(0x00524F43), /* "\0ROC" = reverse("COR\0") */ .model = 970, }, { /* "DUK" -> Kirin 960 */ .platform = UINT32_C(0x004B5544), /* "\0KUD" = reverse("DUK\0") */ .model = 960, }, { /* "EML" -> Kirin 970 */ .platform = UINT32_C(0x004C4D45), /* "\0LME" = reverse("EML\0") */ .model = 970, }, { /* "EVA" -> Kirin 955 */ .platform = UINT32_C(0x00415645), /* "\0AVE" = reverse("EVA\0") */ .model = 955, }, { /* "FRD" -> Kirin 950 */ .platform = UINT32_C(0x00445246), /* "\0DRF" = reverse("FRD\0") */ .model = 950, }, { /* "INE" -> Kirin 710 */ .platform = UINT32_C(0x00454E49), /* "\0ENI" = reverse("INE\0") */ .model = 710, }, { /* "KNT" -> Kirin 950 */ .platform = UINT32_C(0x00544E4B), /* "\0TNK" = reverse("KNT\0") */ .model = 950, }, { /* "LON" -> Kirin 960 */ .platform = UINT32_C(0x004E4F4C), /* "\0NOL" = reverse("LON\0") */ .model = 960, }, { /* "LYA" -> Kirin 980 */ .platform = UINT32_C(0x0041594C), /* "\0AYL" = reverse("LYA\0") */ .model = 980, }, { /* "MCN" -> Kirin 980 */ .platform = UINT32_C(0x004E434D), /* "\0NCM" = reverse("MCN\0") */ .model = 980, }, { /* "MHA" -> Kirin 960 */ .platform = UINT32_C(0x0041484D), /* "\0AHM" = reverse("MHA\0") */ .model = 960, }, { /* "NEO" -> Kirin 970 */ .platform = UINT32_C(0x004F454E), /* "\0OEN" = reverse("NEO\0") */ .model = 970, }, { /* "NXT" -> Kirin 950 */ .platform = UINT32_C(0x0054584E), /* "\0TXN" = reverse("NXT\0") */ .model = 950, }, { /* "PAN" -> Kirin 980 */ .platform = UINT32_C(0x004E4150), /* "\0NAP" = reverse("PAN\0") */ .model = 980, }, { /* "PAR" -> Kirin 970 */ .platform = UINT32_C(0x00524150), /* "\0RAP" = reverse("PAR\0") */ .model = 970, }, { /* "RVL" -> Kirin 970 */ .platform = UINT32_C(0x004C5652), /* "\0LVR" = reverse("RVL\0") */ .model = 970, }, { /* "STF" -> Kirin 960 */ .platform = UINT32_C(0x00465453), /* "\0FTS" = reverse("STF\0") */ .model = 960, }, { /* "SUE" -> Kirin 980 */ .platform = UINT32_C(0x00455553), /* "\0EUS" = reverse("SUE\0") */ .model = 980, }, { /* "VIE" -> Kirin 955 */ .platform = UINT32_C(0x00454956), /* "\0EIV" = reverse("VIE\0") */ .model = 955, }, { /* "VKY" -> Kirin 960 */ .platform = UINT32_C(0x00594B56), /* "\0YKV" = reverse("VKY\0") */ .model = 960, }, { /* "VTR" -> Kirin 960 */ .platform = UINT32_C(0x00525456), /* "\0RTV" = reverse("VTR\0") */ .model = 960, }, }; /** * Tries to match ro.product.board string to Huawei /([A-Z]{3})(\-[A-Z]?L\d{2})$/ signature where \1 is one of the * known values for Huawei devices, which do not report chipset name elsewhere. * If the string matches signature, the function decodes chipset (always HiSilicon Kirin for matched devices) from * the Huawei platform ID in the signature and stores it in \p chipset argument. * * @param start - start of the ro.product.board string to match. * @param end - end of the ro.product.board string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match and decoding. * * @returns true if signature matched, false otherwise. */ static bool match_and_parse_huawei( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* * Expect length of either 3, 7 or 8, exactly: * - 3-letter platform identifier (see huawei_platform_map) * - 3-letter platform identifier + '-' + 'L' + two digits * - 3-letter platform identifier + '-' + capital letter + 'L' + two digits */ const size_t length = end - start; switch (length) { case 3: case 7: case 8: break; default: return false; } /* * Try to find the first three-letter substring in among the tabulated entries for Huawei devices. * The first three letters are loaded and compared as a little-endian 24-bit word. */ uint32_t model = 0; const uint32_t target_platform_id = load_u24le(start); for (uint32_t i = 0; i < CPUINFO_COUNT_OF(huawei_platform_map); i++) { if (huawei_platform_map[i].platform == target_platform_id) { model = huawei_platform_map[i].model; break; } } if (model == 0) { /* Platform does not match the tabulated Huawei entries */ return false; } if (length > 3) { /* * Check that: * - The symbol after platform id is a dash * - The symbol after it is an uppercase letter. For 7-symbol strings, the symbol is just 'L'. */ if (start[3] != '-' || !is_ascii_alphabetic_uppercase(start[4])) { return false; } /* Check that the last 3 entries are /L\d\d/ */ if (end[-3] != 'L' || !is_ascii_numeric(end[-2]) || !is_ascii_numeric(end[-1])) { return false; } } /* All checks succeeded, commit chipset name */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_hisilicon, .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = model, }; return true; } /** * Tries to match /tcc\d{3}x$/ signature for Telechips TCCXXXx chipsets. * If match successful, extracts model information into \p chipset argument. * * @param start - start of the /proc/cpuinfo Hardware string to match. * @param end - end of the /proc/cpuinfo Hardware string to match. * @param[out] chipset - location where chipset information will be stored upon a successful match. * * @returns true if signature matched, false otherwise. */ static bool match_tcc( const char* start, const char* end, struct cpuinfo_arm_chipset chipset[restrict static 1]) { /* Expect exactly 7 symbols: "tcc" (3 symbols) + 3-digit model number + fixed "x" suffix */ if (start + 7 != end) { return false; } /* Quick check for the first character */ if (start[0] != 't') { return false; } /* Load the next 2 bytes as little endian 16-bit word */ const uint16_t expected_cc = load_u16le(start + 1); if (expected_cc != UINT16_C(0x6363) /* "cc" */ ) { return false; } /* Check and parse 3-digit model number */ uint32_t model = 0; for (uint32_t i = 3; i < 6; i++) { const uint32_t digit = (uint32_t) (uint8_t) start[i] - '0'; if (digit >= 10) { /* Not really a digit */ return false; } model = model * 10 + digit; } /* Check the fixed 'x' suffix in the end */ if (start[6] != 'x') { return false; } /* Commit parsed chipset. */ *chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_telechips, .series = cpuinfo_arm_chipset_series_telechips_tcc, .model = model, .suffix = { [0] = 'X' }, }; return true; } /* * Compares ro.board.platform string to Nvidia Tegra signatures ("tegra" and "tegra3") * This check has effect on how /proc/cpuinfo Hardware string is interpreted. * * @param start - start of the ro.board.platform string to check. * @param end - end of the ro.board.platform string to check. * * @returns true if the string matches an Nvidia Tegra signature, and false otherwise */ static bool is_tegra(const char* start, const char* end) { /* Expect 5 ("tegra") or 6 ("tegra3") symbols */ const size_t length = end - start; switch (length) { case 5: case 6: break; default: return false; } /* Check that the first 5 characters match "tegra" */ if (start[0] != 't') { return false; } const uint32_t expected_egra = load_u32le(start + 1); if (expected_egra != UINT32_C(0x61726765) /* "arge" = reverse("egra") */) { return false; } /* Check if the string is either "tegra" (length = 5) or "tegra3" (length != 5) and last character is '3' */ return (length == 5 || start[5] == '3'); } struct special_map_entry { const char* platform; uint16_t model; uint8_t series; char suffix; }; static const struct special_map_entry special_hardware_map_entries[] = { #if CPUINFO_ARCH_ARM { /* "k3v2oem1" -> HiSilicon K3V2 */ .platform = "k3v2oem1", .series = cpuinfo_arm_chipset_series_hisilicon_k3v, .model = 2, }, { /* "hi6620oem" -> HiSilicon Kirin 910T */ .platform = "hi6620oem", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 910, .suffix = 'T' }, #endif /* CPUINFO_ARCH_ARM */ { /* "hi6250" -> HiSilicon Kirin 650 */ .platform = "hi6250", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 650, }, { /* "hi6210sft" -> HiSilicon Kirin 620 */ .platform = "hi6210sft", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 620, }, { /* "hi3751" -> HiSilicon Hi3751 */ .platform = "hi3751", .series = cpuinfo_arm_chipset_series_hisilicon_hi, .model = 3751, }, #if CPUINFO_ARCH_ARM { /* "hi3630" -> HiSilicon Kirin 920 */ .platform = "hi3630", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 920, }, #endif /* CPUINFO_ARCH_ARM */ { /* "hi3635" -> HiSilicon Kirin 930 */ .platform = "hi3635", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 930, }, #if CPUINFO_ARCH_ARM { /* "gs702a" -> Actions ATM7029 (Cortex-A5 + GC1000) */ .platform = "gs702a", .series = cpuinfo_arm_chipset_series_actions_atm, .model = 7029, }, { /* "gs702c" -> Actions ATM7029B (Cortex-A5 + SGX540) */ .platform = "gs702c", .series = cpuinfo_arm_chipset_series_actions_atm, .model = 7029, .suffix = 'B', }, { /* "gs703d" -> Actions ATM7039S */ .platform = "gs703d", .series = cpuinfo_arm_chipset_series_actions_atm, .model = 7039, .suffix = 'S', }, { /* "gs705a" -> Actions ATM7059A */ .platform = "gs705a", .series = cpuinfo_arm_chipset_series_actions_atm, .model = 7059, .suffix = 'A', }, { /* "Amlogic Meson8" -> Amlogic S812 */ .platform = "Amlogic Meson8", .series = cpuinfo_arm_chipset_series_amlogic_s, .model = 812, }, { /* "Amlogic Meson8B" -> Amlogic S805 */ .platform = "Amlogic Meson8B", .series = cpuinfo_arm_chipset_series_amlogic_s, .model = 805, }, { /* "mapphone_CDMA" -> Texas Instruments OMAP4430 */ .platform = "mapphone_CDMA", .series = cpuinfo_arm_chipset_series_texas_instruments_omap, .model = 4430, }, { /* "Superior" -> Texas Instruments OMAP4470 */ .platform = "Superior", .series = cpuinfo_arm_chipset_series_texas_instruments_omap, .model = 4470, }, { /* "Tuna" (Samsung Galaxy Nexus) -> Texas Instruments OMAP4460 */ .platform = "Tuna", .series = cpuinfo_arm_chipset_series_texas_instruments_omap, .model = 4460, }, { /* "Manta" (Samsung Nexus 10) -> Samsung Exynos 5250 */ .platform = "Manta", .series = cpuinfo_arm_chipset_series_samsung_exynos, .model = 5250, }, { /* "Odin" -> LG Nuclun 7111 */ .platform = "Odin", .series = cpuinfo_arm_chipset_series_lg_nuclun, .model = 7111, }, { /* "Madison" -> MStar 6A338 */ .platform = "Madison", .series = cpuinfo_arm_chipset_series_mstar_6a, .model = 338, }, #endif /* CPUINFO_ARCH_ARM */ }; static const struct special_map_entry tegra_hardware_map_entries[] = { #if CPUINFO_ARCH_ARM { /* "cardhu" (Nvidia Cardhu developer tablet) -> Tegra T30 */ .platform = "cardhu", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "kai" -> Tegra T30L */ .platform = "kai", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "p3" (Samsung Galaxy Tab 8.9) -> Tegra T20 */ .platform = "p3", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 20, }, { /* "n1" (Samsung Galaxy R / Samsung Captivate Glide) -> Tegra AP20H */ .platform = "n1", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 20, .suffix = 'H', }, { /* "SHW-M380S" (Samsung Galaxy Tab 10.1) -> Tegra T20 */ .platform = "SHW-M380S", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 20, }, { /* "m470" (Hisense Sero 7 Pro) -> Tegra T30L */ .platform = "m470", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "endeavoru" (HTC One X) -> Tegra AP33 */ .platform = "endeavoru", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 33, }, { /* "evitareul" (HTC One X+) -> Tegra T33 */ .platform = "evitareul", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 33, }, { /* "enrc2b" (HTC One X+) -> Tegra T33 */ .platform = "enrc2b", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 33, }, { /* "mozart" (Asus Transformer Pad TF701T) -> Tegra T114 */ .platform = "mozart", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "tegratab" (Tegra Note 7) -> Tegra T114 */ .platform = "tegratab", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "tn8" (Nvidia Shield Tablet K1) -> Tegra T124 */ .platform = "tn8", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 124, }, { /* "roth" (Nvidia Shield Portable) -> Tegra T114 */ .platform = "roth", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "pisces" (Xiaomi Mi 3) -> Tegra T114 */ .platform = "pisces", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "mocha" (Xiaomi Mi Pad) -> Tegra T124 */ .platform = "mocha", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 124, }, { /* "stingray" (Motorola XOOM) -> Tegra AP20H */ .platform = "stingray", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 20, .suffix = 'H', }, { /* "Ceres" (Wiko Highway 4G) -> Tegra SL460N */ .platform = "Ceres", .series = cpuinfo_arm_chipset_series_nvidia_tegra_sl, .model = 460, .suffix = 'N', }, { /* "MT799" (nabi 2 Tablet) -> Tegra T30 */ .platform = "MT799", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "t8400n" (nabi DreamTab HD8) -> Tegra T114 */ .platform = "t8400n", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "chagall" (Fujitsu Stylistic M532) -> Tegra T30 */ .platform = "chagall", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "ventana" (Asus Transformer TF101) -> Tegra T20 */ .platform = "ventana", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 20, }, { /* "bobsleigh" (Fujitsu Arrows Tab F-05E) -> Tegra T33 */ .platform = "bobsleigh", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 33, }, { /* "tegra_fjdev101" (Fujitsu Arrows X F-10D) -> Tegra AP33 */ .platform = "tegra_fjdev101", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 33, }, { /* "tegra_fjdev103" (Fujitsu Arrows V F-04E) -> Tegra T33 */ .platform = "tegra_fjdev103", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 33, }, { /* "nbx03" (Sony Tablet S) -> Tegra T20 */ .platform = "nbx03", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 20, }, { /* "txs03" (Sony Xperia Tablet S) -> Tegra T30L */ .platform = "txs03", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "x3" (LG Optimus 4X HD P880) -> Tegra AP33 */ .platform = "x3", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 33, }, { /* "vu10" (LG Optimus Vu P895) -> Tegra AP33 */ .platform = "vu10", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 33, }, { /* "BIRCH" (HP Slate 7 Plus) -> Tegra T30L */ .platform = "BIRCH", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "macallan" (HP Slate 8 Pro) -> Tegra T114 */ .platform = "macallan", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "maya" (HP SlateBook 10 x2) -> Tegra T114 */ .platform = "maya", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "antares" (Toshiba AT100) -> Tegra T20 */ .platform = "antares", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 20, }, { /* "tostab12AL" (Toshiba AT300SE "Excite 10 SE") -> Tegra T30L */ .platform = "tostab12AL", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "tostab12BL" (Toshiba AT10-A "Excite Pure") -> Tegra T30L */ .platform = "tostab12BL", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "sphinx" (Toshiba AT270 "Excite 7.7") -> Tegra T30 */ .platform = "sphinx", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "tostab11BS" (Toshiba AT570 "Regza 7.7") -> Tegra T30 */ .platform = "tostab11BS", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "tostab12BA" (Toshiba AT10-LE-A "Excite Pro") -> Tegra T114 */ .platform = "tostab12BA", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "vangogh" (Acer Iconia Tab A100) -> Tegra T20 */ .platform = "vangogh", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 20, }, { /* "a110" (Acer Iconia Tab A110) -> Tegra T30L */ .platform = "a110", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "picasso_e" (Acer Iconia Tab A200) -> Tegra AP20H */ .platform = "picasso_e", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 20, .suffix = 'H', }, { /* "picasso_e2" (Acer Iconia Tab A210) -> Tegra T30L */ .platform = "picasso_e2", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "picasso" (Acer Iconia Tab A500) -> Tegra AP20H */ .platform = "picasso", .series = cpuinfo_arm_chipset_series_nvidia_tegra_ap, .model = 20, .suffix = 'H', }, { /* "picasso_m" (Acer Iconia Tab A510) -> Tegra T30 */ .platform = "picasso_m", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "picasso_mf" (Acer Iconia Tab A700) -> Tegra T30 */ .platform = "picasso_mf", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "avalon" (Toshiba AT300 "Excite 10") -> Tegra T30L */ .platform = "avalon", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "NS_14T004" (iRiver NS-14T004) -> Tegra T30L */ .platform = "NS_14T004", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, { /* "WIKIPAD" (Wikipad) -> Tegra T30 */ .platform = "WIKIPAD", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, }, { /* "kb" (Pegatron Q00Q) -> Tegra T114 */ .platform = "kb", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, #endif /* CPUINFO_ARCH_ARM */ { /* "foster_e" (Nvidia Shield TV, Flash) -> Tegra T210 */ .platform = "foster_e", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 210, }, { /* "foster_e_hdd" (Nvidia Shield TV, HDD) -> Tegra T210 */ .platform = "foster_e_hdd", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 210, }, { /* "darcy" (Nvidia Shield TV 2017) -> Tegra T210 */ .platform = "darcy", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 210, }, }; /* * Decodes chipset name from /proc/cpuinfo Hardware string. * For some chipsets, the function relies frequency and on number of cores for chipset detection. * * @param[in] platform - /proc/cpuinfo Hardware string. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` vendor * and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_linux_decode_chipset_from_proc_cpuinfo_hardware( const char hardware[restrict static CPUINFO_HARDWARE_VALUE_MAX], uint32_t cores, uint32_t max_cpu_freq_max, bool is_tegra) { struct cpuinfo_arm_chipset chipset; const size_t hardware_length = strnlen(hardware, CPUINFO_HARDWARE_VALUE_MAX); const char* hardware_end = hardware + hardware_length; if (is_tegra) { /* * Nvidia Tegra-specific path: compare /proc/cpuinfo Hardware string to * tabulated Hardware values for popular chipsets/devices with Tegra chipsets. * This path is only used when ro.board.platform indicates a Tegra chipset * (albeit does not indicate which exactly Tegra chipset). */ for (size_t i = 0; i < CPUINFO_COUNT_OF(tegra_hardware_map_entries); i++) { if (strncmp(tegra_hardware_map_entries[i].platform, hardware, hardware_length) == 0 && tegra_hardware_map_entries[i].platform[hardware_length] == 0) { cpuinfo_log_debug( "found /proc/cpuinfo Hardware string \"%.*s\" in Nvidia Tegra chipset table", (int) hardware_length, hardware); /* Create chipset name from entry */ return (struct cpuinfo_arm_chipset) { .vendor = chipset_series_vendor[tegra_hardware_map_entries[i].series], .series = (enum cpuinfo_arm_chipset_series) tegra_hardware_map_entries[i].series, .model = tegra_hardware_map_entries[i].model, .suffix = { [0] = tegra_hardware_map_entries[i].suffix, }, }; } } } else { /* Generic path: consider all other vendors */ bool word_start = true; for (const char* pos = hardware; pos != hardware_end; pos++) { const char c = *pos; switch (c) { case ' ': case '\t': case ',': word_start = true; break; default: if (word_start && is_ascii_alphabetic(c)) { /* Check Qualcomm MSM/APQ signature */ if (match_msm_apq(pos, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm MSM/APQ signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check SDMxxx (Qualcomm Snapdragon) signature */ if (match_sdm(pos, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm SDM signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check SMxxxx (Qualcomm Snapdragon) signature */ if (match_sm(pos, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm SM signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check MediaTek MT signature */ if (match_mt(pos, hardware_end, true, &chipset)) { cpuinfo_log_debug( "matched MediaTek MT signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check HiSilicon Kirin signature */ if (match_kirin(pos, hardware_end, &chipset)) { cpuinfo_log_debug( "matched HiSilicon Kirin signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check Rockchip RK signature */ if (match_rk(pos, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Rockchip RK signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } } word_start = false; break; } } /* Check Samsung Exynos signature */ if (match_samsung_exynos(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Samsung Exynos signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check universalXXXX (Samsung Exynos) signature */ if (match_universal(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched UNIVERSAL (Samsung Exynos) signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } #if CPUINFO_ARCH_ARM /* Match /SMDK(4410|4x12)$/ */ if (match_and_parse_smdk(hardware, hardware_end, cores, &chipset)) { cpuinfo_log_debug( "matched SMDK (Samsung Exynos) signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } #endif /* Check Spreadtrum SC signature */ if (match_sc(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Spreadtrum SC signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } #if CPUINFO_ARCH_ARM /* Check Marvell PXA signature */ if (match_pxa(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Marvell PXA signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } #endif /* Match /sun\d+i/ signature and map to Allwinner chipset name */ if (match_and_parse_sunxi(hardware, hardware_end, cores, &chipset)) { cpuinfo_log_debug( "matched sunxi (Allwinner Ax) signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check Broadcom BCM signature */ if (match_bcm(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Broadcom BCM signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } #if CPUINFO_ARCH_ARM /* Check Texas Instruments OMAP signature */ if (match_omap(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Texas Instruments OMAP signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Check WonderMedia WMT signature and decode chipset from frequency and number of cores */ if (match_and_parse_wmt(hardware, hardware_end, cores, max_cpu_freq_max, &chipset)) { cpuinfo_log_debug( "matched WonderMedia WMT signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } #endif /* Check Telechips TCC signature */ if (match_tcc(hardware, hardware_end, &chipset)) { cpuinfo_log_debug( "matched Telechips TCC signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) hardware_length, hardware); return chipset; } /* Compare to tabulated Hardware values for popular chipsets/devices which can't be otherwise detected */ for (size_t i = 0; i < CPUINFO_COUNT_OF(special_hardware_map_entries); i++) { if (strncmp(special_hardware_map_entries[i].platform, hardware, hardware_length) == 0 && special_hardware_map_entries[i].platform[hardware_length] == 0) { cpuinfo_log_debug( "found /proc/cpuinfo Hardware string \"%.*s\" in special chipset table", (int) hardware_length, hardware); /* Create chipset name from entry */ return (struct cpuinfo_arm_chipset) { .vendor = chipset_series_vendor[special_hardware_map_entries[i].series], .series = (enum cpuinfo_arm_chipset_series) special_hardware_map_entries[i].series, .model = special_hardware_map_entries[i].model, .suffix = { [0] = special_hardware_map_entries[i].suffix, }, }; } } } return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; } #ifdef __ANDROID__ static const struct special_map_entry special_board_map_entries[] = { { /* "hi6250" -> HiSilicon Kirin 650 */ .platform = "hi6250", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 650, }, { /* "hi6210sft" -> HiSilicon Kirin 620 */ .platform = "hi6210sft", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 620, }, #if CPUINFO_ARCH_ARM { /* "hi3630" -> HiSilicon Kirin 920 */ .platform = "hi3630", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 920, }, #endif /* CPUINFO_ARCH_ARM */ { /* "hi3635" -> HiSilicon Kirin 930 */ .platform = "hi3635", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 930, }, { /* "hi3650" -> HiSilicon Kirin 950 */ .platform = "hi3650", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 950, }, { /* "hi3660" -> HiSilicon Kirin 960 */ .platform = "hi3660", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 960, }, #if CPUINFO_ARCH_ARM { /* "mp523x" -> Renesas MP5232 */ .platform = "mp523x", .series = cpuinfo_arm_chipset_series_renesas_mp, .model = 5232, }, #endif /* CPUINFO_ARCH_ARM */ { /* "BEETHOVEN" (Huawei MadiaPad M3) -> HiSilicon Kirin 950 */ .platform = "BEETHOVEN", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 950, }, #if CPUINFO_ARCH_ARM { /* "hws7701u" (Huawei MediaPad 7 Youth) -> Rockchip RK3168 */ .platform = "hws7701u", .series = cpuinfo_arm_chipset_series_rockchip_rk, .model = 3168, }, { /* "g2mv" (LG G2 mini LTE) -> Nvidia Tegra SL460N */ .platform = "g2mv", .series = cpuinfo_arm_chipset_series_nvidia_tegra_sl, .model = 460, .suffix = 'N', }, { /* "K00F" (Asus MeMO Pad 10) -> Rockchip RK3188 */ .platform = "K00F", .series = cpuinfo_arm_chipset_series_rockchip_rk, .model = 3188, }, { /* "T7H" (HP Slate 7) -> Rockchip RK3066 */ .platform = "T7H", .series = cpuinfo_arm_chipset_series_rockchip_rk, .model = 3066, }, { /* "tuna" (Samsung Galaxy Nexus) -> Texas Instruments OMAP4460 */ .platform = "tuna", .series = cpuinfo_arm_chipset_series_texas_instruments_omap, .model = 4460, }, { /* "grouper" (Asus Nexus 7 2012) -> Nvidia Tegra T30L */ .platform = "grouper", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 30, .suffix = 'L', }, #endif /* CPUINFO_ARCH_ARM */ { /* "flounder" (HTC Nexus 9) -> Nvidia Tegra T132 */ .platform = "flounder", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 132, }, { /* "dragon" (Google Pixel C) -> Nvidia Tegra T210 */ .platform = "dragon", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 210, }, { /* "sailfish" (Google Pixel) -> Qualcomm MSM8996PRO */ .platform = "sailfish", .series = cpuinfo_arm_chipset_series_qualcomm_msm, .model = 8996, .suffix = 'P', }, { /* "marlin" (Google Pixel XL) -> Qualcomm MSM8996PRO */ .platform = "marlin", .series = cpuinfo_arm_chipset_series_qualcomm_msm, .model = 8996, .suffix = 'P', }, }; /* * Decodes chipset name from ro.product.board Android system property. * For some chipsets, the function relies frequency and on number of cores for chipset detection. * * @param[in] platform - ro.product.board value. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` vendor * and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_android_decode_chipset_from_ro_product_board( const char ro_product_board[restrict static CPUINFO_BUILD_PROP_VALUE_MAX], uint32_t cores, uint32_t max_cpu_freq_max) { struct cpuinfo_arm_chipset chipset; const char* board = ro_product_board; const size_t board_length = strnlen(ro_product_board, CPUINFO_BUILD_PROP_VALUE_MAX); const char* board_end = ro_product_board + board_length; /* Check Qualcomm MSM/APQ signature */ if (match_msm_apq(board, board_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm MSM/APQ signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } /* Check universaXXXX (Samsung Exynos) signature */ if (match_universal(board, board_end, &chipset)) { cpuinfo_log_debug( "matched UNIVERSAL (Samsung Exynos) signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } #if CPUINFO_ARCH_ARM /* Check SMDK (Samsung Exynos) signature */ if (match_and_parse_smdk(board, board_end, cores, &chipset)) { cpuinfo_log_debug( "matched SMDK (Samsung Exynos) signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } #endif /* Check MediaTek MT signature */ if (match_mt(board, board_end, true, &chipset)) { cpuinfo_log_debug( "matched MediaTek MT signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } /* Check Spreadtrum SC signature */ if (match_sc(board, board_end, &chipset)) { cpuinfo_log_debug( "matched Spreadtrum SC signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } #if CPUINFO_ARCH_ARM /* Check Marvell PXA signature */ if (match_pxa(board, board_end, &chipset)) { cpuinfo_log_debug( "matched Marvell PXA signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } /* Check Leadcore LCxxxx signature */ if (match_lc(board, board_end, &chipset)) { cpuinfo_log_debug( "matched Leadcore LC signature in ro.product.board string \"%.*s\"", (int) board_length, board); return chipset; } /* * Compare to tabulated ro.product.board values for Broadcom chipsets and decode chipset from frequency and * number of cores. */ if (match_and_parse_broadcom(board, board_end, cores, max_cpu_freq_max, &chipset)) { cpuinfo_log_debug( "found ro.product.board string \"%.*s\" in Broadcom chipset table", (int) board_length, board); return chipset; } #endif /* Compare to tabulated ro.product.board values for Huawei devices which don't report chipset elsewhere */ if (match_and_parse_huawei(board, board_end, &chipset)) { cpuinfo_log_debug( "found ro.product.board string \"%.*s\" in Huawei chipset table", (int) board_length, board); return chipset; } /* Compare to tabulated ro.product.board values for popular chipsets/devices which can't be otherwise detected */ for (size_t i = 0; i < CPUINFO_COUNT_OF(special_board_map_entries); i++) { if (strncmp(special_board_map_entries[i].platform, board, board_length) == 0 && special_board_map_entries[i].platform[board_length] == 0) { cpuinfo_log_debug( "found ro.product.board string \"%.*s\" in special chipset table", (int) board_length, board); /* Create chipset name from entry */ return (struct cpuinfo_arm_chipset) { .vendor = chipset_series_vendor[special_board_map_entries[i].series], .series = (enum cpuinfo_arm_chipset_series) special_board_map_entries[i].series, .model = special_board_map_entries[i].model, .suffix = { [0] = special_board_map_entries[i].suffix, /* The suffix of MSM8996PRO is truncated at the first letter, reconstruct it here. */ [1] = special_board_map_entries[i].suffix == 'P' ? 'R' : 0, [2] = special_board_map_entries[i].suffix == 'P' ? 'O' : 0, }, }; } } return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; } struct amlogic_map_entry { char ro_board_platform[6]; uint16_t model; uint8_t series; char suffix[3]; }; static const struct amlogic_map_entry amlogic_map_entries[] = { #if CPUINFO_ARCH_ARM { /* "meson3" -> Amlogic AML8726-M */ .ro_board_platform = "meson3", .series = cpuinfo_arm_chipset_series_amlogic_aml, .model = 8726, .suffix = "-M", }, { /* "meson6" -> Amlogic AML8726-MX */ .ro_board_platform = "meson6", .series = cpuinfo_arm_chipset_series_amlogic_aml, .model = 8726, .suffix = "-MX", }, { /* "meson8" -> Amlogic S805 */ .ro_board_platform = "meson8", .series = cpuinfo_arm_chipset_series_amlogic_s, .model = 805, }, #endif /* CPUINFO_ARCH_ARM */ { /* "gxbaby" -> Amlogic S905 */ .ro_board_platform = "gxbaby", .series = cpuinfo_arm_chipset_series_amlogic_s, .model = 905, }, { /* "gxl" -> Amlogic S905X */ .ro_board_platform = "gxl", .series = cpuinfo_arm_chipset_series_amlogic_s, .model = 905, .suffix = "X", }, { /* "gxm" -> Amlogic S912 */ .ro_board_platform = "gxm", .series = cpuinfo_arm_chipset_series_amlogic_s, .model = 912, }, }; static const struct special_map_entry special_platform_map_entries[] = { #if CPUINFO_ARCH_ARM { /* "hi6620oem" -> HiSilicon Kirin 910T */ .platform = "hi6620oem", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 910, .suffix = 'T', }, #endif /* CPUINFO_ARCH_ARM */ { /* "hi6250" -> HiSilicon Kirin 650 */ .platform = "hi6250", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 650, }, { /* "hi6210sft" -> HiSilicon Kirin 620 */ .platform = "hi6210sft", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 620, }, #if CPUINFO_ARCH_ARM { /* "hi3630" -> HiSilicon Kirin 920 */ .platform = "hi3630", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 920, }, #endif /* CPUINFO_ARCH_ARM */ { /* "hi3635" -> HiSilicon Kirin 930 */ .platform = "hi3635", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 930, }, { /* "hi3650" -> HiSilicon Kirin 950 */ .platform = "hi3650", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 950, }, { /* "hi3660" -> HiSilicon Kirin 960 */ .platform = "hi3660", .series = cpuinfo_arm_chipset_series_hisilicon_kirin, .model = 960, }, #if CPUINFO_ARCH_ARM { /* "k3v2oem1" -> HiSilicon K3V2 */ .platform = "k3v2oem1", .series = cpuinfo_arm_chipset_series_hisilicon_k3v, .model = 2, }, { /* "k3v200" -> HiSilicon K3V2 */ .platform = "k3v200", .series = cpuinfo_arm_chipset_series_hisilicon_k3v, .model = 2, }, { /* "montblanc" -> NovaThor U8500 */ .platform = "montblanc", .series = cpuinfo_arm_chipset_series_novathor_u, .model = 8500, }, #endif /* CPUINFO_ARCH_ARM */ { /* "song" -> Pinecone Surge S1 */ .platform = "song", .series = cpuinfo_arm_chipset_series_pinecone_surge_s, .model = 1, }, #if CPUINFO_ARCH_ARM { /* "rk322x" -> RockChip RK3229 */ .platform = "rk322x", .series = cpuinfo_arm_chipset_series_rockchip_rk, .model = 3229, }, #endif /* CPUINFO_ARCH_ARM */ { /* "tegra132" -> Nvidia Tegra T132 */ .platform = "tegra132", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 132, }, { /* "tegra210_dragon" -> Nvidia Tegra T210 */ .platform = "tegra210_dragon", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 210, }, #if CPUINFO_ARCH_ARM { /* "tegra4" -> Nvidia Tegra T114 */ .platform = "tegra4", .series = cpuinfo_arm_chipset_series_nvidia_tegra_t, .model = 114, }, { /* "s5pc110" -> Samsung Exynos 3110 */ .platform = "s5pc110", .series = cpuinfo_arm_chipset_series_samsung_exynos, .model = 3110, }, #endif /* CPUINFO_ARCH_ARM */ }; /* * Decodes chipset name from ro.board.platform Android system property. * For some chipsets, the function relies frequency and on number of cores for chipset detection. * * @param[in] platform - ro.board.platform value. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` vendor * and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_android_decode_chipset_from_ro_board_platform( const char platform[restrict static CPUINFO_BUILD_PROP_VALUE_MAX], uint32_t cores, uint32_t max_cpu_freq_max) { struct cpuinfo_arm_chipset chipset; const size_t platform_length = strnlen(platform, CPUINFO_BUILD_PROP_VALUE_MAX); const char* platform_end = platform + platform_length; /* Check Qualcomm MSM/APQ signature */ if (match_msm_apq(platform, platform_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm MSM/APQ signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } /* Check exynosXXXX (Samsung Exynos) signature */ if (match_exynos(platform, platform_end, &chipset)) { cpuinfo_log_debug( "matched exynosXXXX (Samsung Exynos) signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } /* Check MediaTek MT signature */ if (match_mt(platform, platform_end, true, &chipset)) { cpuinfo_log_debug( "matched MediaTek MT signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } /* Check HiSilicon Kirin signature */ if (match_kirin(platform, platform_end, &chipset)) { cpuinfo_log_debug( "matched HiSilicon Kirin signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } /* Check Spreadtrum SC signature */ if (match_sc(platform, platform_end, &chipset)) { cpuinfo_log_debug( "matched Spreadtrum SC signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } /* Check Rockchip RK signature */ if (match_rk(platform, platform_end, &chipset)) { cpuinfo_log_debug( "matched Rockchip RK signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } #if CPUINFO_ARCH_ARM /* Check Leadcore LCxxxx signature */ if (match_lc(platform, platform_end, &chipset)) { cpuinfo_log_debug( "matched Leadcore LC signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return chipset; } #endif /* Compare to tabulated ro.board.platform values for Huawei devices which don't report chipset elsewhere */ if (match_and_parse_huawei(platform, platform_end, &chipset)) { cpuinfo_log_debug( "found ro.board.platform string \"%.*s\" in Huawei chipset table", (int) platform_length, platform); return chipset; } #if CPUINFO_ARCH_ARM /* * Compare to known ro.board.platform values for Broadcom devices and * detect chipset from frequency and number of cores */ if (match_and_parse_broadcom(platform, platform_end, cores, max_cpu_freq_max, &chipset)) { cpuinfo_log_debug( "found ro.board.platform string \"%.*s\" in Broadcom chipset table", (int) platform_length, platform); return chipset; } /* * Compare to ro.board.platform value ("omap4") for OMAP4xxx chipsets. * Upon successful match, detect OMAP4430 from frequency and number of cores. */ if (platform_length == 5 && cores == 2 && max_cpu_freq_max == 1008000 && memcmp(platform, "omap4", 5) == 0) { cpuinfo_log_debug( "matched Texas Instruments OMAP4 signature in ro.board.platform string \"%.*s\"", (int) platform_length, platform); return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_texas_instruments, .series = cpuinfo_arm_chipset_series_texas_instruments_omap, .model = 4430, }; } #endif /* * Compare to tabulated ro.board.platform values for Amlogic chipsets/devices which can't be otherwise detected. * The tabulated Amlogic ro.board.platform values have not more than 6 characters. */ if (platform_length <= 6) { for (size_t i = 0; i < CPUINFO_COUNT_OF(amlogic_map_entries); i++) { if (strncmp(amlogic_map_entries[i].ro_board_platform, platform, 6) == 0) { cpuinfo_log_debug( "found ro.board.platform string \"%.*s\" in Amlogic chipset table", (int) platform_length, platform); /* Create chipset name from entry */ return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_amlogic, .series = (enum cpuinfo_arm_chipset_series) amlogic_map_entries[i].series, .model = amlogic_map_entries[i].model, .suffix = { [0] = amlogic_map_entries[i].suffix[0], [1] = amlogic_map_entries[i].suffix[1], [2] = amlogic_map_entries[i].suffix[2], }, }; } } } /* Compare to tabulated ro.board.platform values for popular chipsets/devices which can't be otherwise detected */ for (size_t i = 0; i < CPUINFO_COUNT_OF(special_platform_map_entries); i++) { if (strncmp(special_platform_map_entries[i].platform, platform, platform_length) == 0 && special_platform_map_entries[i].platform[platform_length] == 0) { /* Create chipset name from entry */ cpuinfo_log_debug( "found ro.board.platform string \"%.*s\" in special chipset table", (int) platform_length, platform); return (struct cpuinfo_arm_chipset) { .vendor = chipset_series_vendor[special_platform_map_entries[i].series], .series = (enum cpuinfo_arm_chipset_series) special_platform_map_entries[i].series, .model = special_platform_map_entries[i].model, .suffix = { [0] = special_platform_map_entries[i].suffix, }, }; } } /* None of the ro.board.platform signatures matched, indicate unknown chipset */ return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; } /* * Decodes chipset name from ro.mediatek.platform Android system property. * * @param[in] platform - ro.mediatek.platform value. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` * vendor and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_android_decode_chipset_from_ro_mediatek_platform( const char platform[restrict static CPUINFO_BUILD_PROP_VALUE_MAX]) { struct cpuinfo_arm_chipset chipset; const char* platform_end = platform + strnlen(platform, CPUINFO_BUILD_PROP_VALUE_MAX); /* Check MediaTek MT signature */ if (match_mt(platform, platform_end, false, &chipset)) { return chipset; } return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; } /* * Decodes chipset name from ro.arch Android system property. * * The ro.arch property is matched only against Samsung Exynos signature. Systems with other chipset rarely * configure ro.arch Android system property, and can be decoded through other properties, but some Exynos * chipsets are identified only in ro.arch. * * @param[in] arch - ro.arch value. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` * vendor and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_android_decode_chipset_from_ro_arch( const char arch[restrict static CPUINFO_BUILD_PROP_VALUE_MAX]) { struct cpuinfo_arm_chipset chipset; const char* arch_end = arch + strnlen(arch, CPUINFO_BUILD_PROP_VALUE_MAX); /* Check Samsung exynosXXXX signature */ if (match_exynos(arch, arch_end, &chipset)) { return chipset; } return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; } /* * Decodes chipset name from ro.chipname or ro.hardware.chipname Android system property. * * @param[in] chipname - ro.chipname or ro.hardware.chipname value. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` vendor * and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_android_decode_chipset_from_ro_chipname( const char chipname[restrict static CPUINFO_BUILD_PROP_VALUE_MAX]) { struct cpuinfo_arm_chipset chipset; const size_t chipname_length = strnlen(chipname, CPUINFO_BUILD_PROP_VALUE_MAX); const char* chipname_end = chipname + chipname_length; /* Check Qualcomm MSM/APQ signatures */ if (match_msm_apq(chipname, chipname_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm MSM/APQ signature in ro.chipname string \"%.*s\"", (int) chipname_length, chipname); return chipset; } /* Check SMxxxx (Qualcomm Snapdragon) signature */ if (match_sm(chipname, chipname_end, &chipset)) { cpuinfo_log_debug( "matched Qualcomm SM signature in /proc/cpuinfo Hardware string \"%.*s\"", (int) chipname_length, chipname); return chipset; } /* Check exynosXXXX (Samsung Exynos) signature */ if (match_exynos(chipname, chipname_end, &chipset)) { cpuinfo_log_debug( "matched exynosXXXX (Samsung Exynos) signature in ro.chipname string \"%.*s\"", (int) chipname_length, chipname); return chipset; } /* Check universalXXXX (Samsung Exynos) signature */ if (match_universal(chipname, chipname_end, &chipset)) { cpuinfo_log_debug( "matched UNIVERSAL (Samsung Exynos) signature in ro.chipname Hardware string \"%.*s\"", (int) chipname_length, chipname); return chipset; } /* Check MediaTek MT signature */ if (match_mt(chipname, chipname_end, true, &chipset)) { cpuinfo_log_debug( "matched MediaTek MT signature in ro.chipname string \"%.*s\"", (int) chipname_length, chipname); return chipset; } /* Check Spreadtrum SC signature */ if (match_sc(chipname, chipname_end, &chipset)) { cpuinfo_log_debug( "matched Spreadtrum SC signature in ro.chipname string \"%.*s\"", (int) chipname_length, chipname); return chipset; } #if CPUINFO_ARCH_ARM /* Check Marvell PXA signature */ if (match_pxa(chipname, chipname_end, &chipset)) { cpuinfo_log_debug( "matched Marvell PXA signature in ro.chipname string \"%.*s\"", (int) chipname_length, chipname); return chipset; } /* Compare to ro.chipname value ("mp523x") for Renesas MP5232 which can't be otherwise detected */ if (chipname_length == 6 && memcmp(chipname, "mp523x", 6) == 0) { cpuinfo_log_debug( "matched Renesas MP5232 signature in ro.chipname string \"%.*s\"", (int) chipname_length, chipname); return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_renesas, .series = cpuinfo_arm_chipset_series_renesas_mp, .model = 5232, }; } #endif return (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; } #endif /* __ANDROID__ */ /* * Fix common bugs, typos, and renames in chipset name. * * @param[in,out] chipset - chipset name to fix. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. */ void cpuinfo_arm_fixup_chipset( struct cpuinfo_arm_chipset chipset[restrict static 1], uint32_t cores, uint32_t max_cpu_freq_max) { switch (chipset->series) { case cpuinfo_arm_chipset_series_qualcomm_msm: /* Check if there is suffix */ if (chipset->suffix[0] == 0) { /* No suffix, but the model may be misreported */ switch (chipset->model) { case 8216: /* MSM8216 was renamed to MSM8916 */ cpuinfo_log_info("reinterpreted MSM8216 chipset as MSM8916"); chipset->model = 8916; break; case 8916: /* Common bug: MSM8939 (Octa-core) reported as MSM8916 (Quad-core) */ switch (cores) { case 4: break; case 8: cpuinfo_log_info("reinterpreted MSM8916 chipset with 8 cores as MSM8939"); chipset->model = 8939; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core MSM%"PRIu32" chipset", cores, chipset->model); chipset->model = 0; } break; case 8937: /* Common bug: MSM8917 (Quad-core) reported as MSM8937 (Octa-core) */ switch (cores) { case 4: cpuinfo_log_info("reinterpreted MSM8937 chipset with 4 cores as MSM8917"); chipset->model = 8917; break; case 8: break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core MSM%"PRIu32" chipset", cores, chipset->model); chipset->model = 0; } break; case 8960: /* Common bug: APQ8064 (Quad-core) reported as MSM8960 (Dual-core) */ switch (cores) { case 2: break; case 4: cpuinfo_log_info("reinterpreted MSM8960 chipset with 4 cores as APQ8064"); chipset->series = cpuinfo_arm_chipset_series_qualcomm_apq; chipset->model = 8064; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core MSM%"PRIu32" chipset", cores, chipset->model); chipset->model = 0; } break; case 8996: /* Common bug: MSM8994 (Octa-core) reported as MSM8996 (Quad-core) */ switch (cores) { case 4: break; case 8: cpuinfo_log_info("reinterpreted MSM8996 chipset with 8 cores as MSM8994"); chipset->model = 8994; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core MSM%"PRIu32" chipset", cores, chipset->model); chipset->model = 0; } break; #if CPUINFO_ARCH_ARM case 8610: /* Common bug: MSM8612 (Quad-core) reported as MSM8610 (Dual-core) */ switch (cores) { case 2: break; case 4: cpuinfo_log_info("reinterpreted MSM8610 chipset with 4 cores as MSM8612"); chipset->model = 8612; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core MSM%"PRIu32" chipset", cores, chipset->model); chipset->model = 0; } break; #endif /* CPUINFO_ARCH_ARM */ } } else { /* Suffix may need correction */ const uint32_t suffix_word = load_u32le(chipset->suffix); if (suffix_word == UINT32_C(0x004D534D) /* "\0MSM" = reverse("MSM\0") */) { /* * Common bug: model name repeated twice, e.g. "MSM8916MSM8916" * In this case, model matching code parses the second "MSM" as a suffix */ chipset->suffix[0] = 0; chipset->suffix[1] = 0; chipset->suffix[2] = 0; } else { switch (chipset->model) { case 8976: /* MSM8976SG -> MSM8976PRO */ if (suffix_word == UINT32_C(0x00004753) /* "\0\0GS" = reverse("SG\0\0") */ ) { chipset->suffix[0] = 'P'; chipset->suffix[1] = 'R'; chipset->suffix[2] = 'O'; } break; case 8996: /* MSM8996PRO -> MSM8996PRO-AB or MSM8996PRO-AC */ if (suffix_word == UINT32_C(0x004F5250) /* "\0ORP" = reverse("PRO\0") */ ) { chipset->suffix[3] = '-'; chipset->suffix[4] = 'A'; chipset->suffix[5] = 'B' + (char) (max_cpu_freq_max >= 2188800); } break; } } } break; case cpuinfo_arm_chipset_series_qualcomm_apq: { /* Suffix may need correction */ const uint32_t expected_apq = load_u32le(chipset->suffix); if (expected_apq == UINT32_C(0x00515041) /* "\0QPA" = reverse("APQ\0") */) { /* * Common bug: model name repeated twice, e.g. "APQ8016APQ8016" * In this case, model matching code parses the second "APQ" as a suffix */ chipset->suffix[0] = 0; chipset->suffix[1] = 0; chipset->suffix[2] = 0; } break; } case cpuinfo_arm_chipset_series_samsung_exynos: switch (chipset->model) { #if CPUINFO_ARCH_ARM case 4410: /* Exynos 4410 was renamed to Exynos 4412 */ chipset->model = 4412; break; case 5420: /* Common bug: Exynos 5260 (Hexa-core) reported as Exynos 5420 (Quad-core) */ switch (cores) { case 4: break; case 6: cpuinfo_log_info("reinterpreted Exynos 5420 chipset with 6 cores as Exynos 5260"); chipset->model = 5260; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core Exynos 5420 chipset", cores); chipset->model = 0; } break; #endif /* CPUINFO_ARCH_ARM */ case 7580: /* Common bug: Exynos 7578 (Quad-core) reported as Exynos 7580 (Octa-core) */ switch (cores) { case 4: cpuinfo_log_info("reinterpreted Exynos 7580 chipset with 4 cores as Exynos 7578"); chipset->model = 7578; break; case 8: break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core Exynos 7580 chipset", cores); chipset->model = 0; } break; } break; case cpuinfo_arm_chipset_series_mediatek_mt: if (chipset->model == 6752) { /* Common bug: MT6732 (Quad-core) reported as MT6752 (Octa-core) */ switch (cores) { case 4: cpuinfo_log_info("reinterpreted MT6752 chipset with 4 cores as MT6732"); chipset->model = 6732; break; case 8: break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core MT6752 chipset", cores); chipset->model = 0; } } if (chipset->suffix[0] == 'T') { /* Normalization: "TURBO" and "TRUBO" (apparently a typo) -> "T" */ const uint32_t suffix_word = load_u32le(chipset->suffix + 1); switch (suffix_word) { case UINT32_C(0x4F425255): /* "OBRU" = reverse("URBO") */ case UINT32_C(0x4F425552): /* "OBUR" = reverse("RUBO") */ if (chipset->suffix[5] == 0) { chipset->suffix[1] = 0; chipset->suffix[2] = 0; chipset->suffix[3] = 0; chipset->suffix[4] = 0; } break; } } break; case cpuinfo_arm_chipset_series_rockchip_rk: if (chipset->model == 3288) { /* Common bug: Rockchip RK3399 (Hexa-core) always reported as RK3288 (Quad-core) */ switch (cores) { case 4: break; case 6: cpuinfo_log_info("reinterpreted RK3288 chipset with 6 cores as RK3399"); chipset->model = 3399; break; default: cpuinfo_log_warning("system reported invalid %"PRIu32"-core RK3288 chipset", cores); chipset->model = 0; } } break; default: break; } } /* Map from ARM chipset vendor ID to its string representation */ static const char* chipset_vendor_string[cpuinfo_arm_chipset_vendor_max] = { [cpuinfo_arm_chipset_vendor_unknown] = "Unknown", [cpuinfo_arm_chipset_vendor_qualcomm] = "Qualcomm", [cpuinfo_arm_chipset_vendor_mediatek] = "MediaTek", [cpuinfo_arm_chipset_vendor_samsung] = "Samsung", [cpuinfo_arm_chipset_vendor_hisilicon] = "HiSilicon", [cpuinfo_arm_chipset_vendor_actions] = "Actions", [cpuinfo_arm_chipset_vendor_allwinner] = "Allwinner", [cpuinfo_arm_chipset_vendor_amlogic] = "Amlogic", [cpuinfo_arm_chipset_vendor_broadcom] = "Broadcom", [cpuinfo_arm_chipset_vendor_lg] = "LG", [cpuinfo_arm_chipset_vendor_leadcore] = "Leadcore", [cpuinfo_arm_chipset_vendor_marvell] = "Marvell", [cpuinfo_arm_chipset_vendor_mstar] = "MStar", [cpuinfo_arm_chipset_vendor_novathor] = "NovaThor", [cpuinfo_arm_chipset_vendor_nvidia] = "Nvidia", [cpuinfo_arm_chipset_vendor_pinecone] = "Pinecone", [cpuinfo_arm_chipset_vendor_renesas] = "Renesas", [cpuinfo_arm_chipset_vendor_rockchip] = "Rockchip", [cpuinfo_arm_chipset_vendor_spreadtrum] = "Spreadtrum", [cpuinfo_arm_chipset_vendor_telechips] = "Telechips", [cpuinfo_arm_chipset_vendor_texas_instruments] = "Texas Instruments", [cpuinfo_arm_chipset_vendor_wondermedia] = "WonderMedia", }; /* Map from ARM chipset series ID to its string representation */ static const char* chipset_series_string[cpuinfo_arm_chipset_series_max] = { [cpuinfo_arm_chipset_series_unknown] = NULL, [cpuinfo_arm_chipset_series_qualcomm_qsd] = "QSD", [cpuinfo_arm_chipset_series_qualcomm_msm] = "MSM", [cpuinfo_arm_chipset_series_qualcomm_apq] = "APQ", [cpuinfo_arm_chipset_series_qualcomm_snapdragon] = "Snapdragon ", [cpuinfo_arm_chipset_series_mediatek_mt] = "MT", [cpuinfo_arm_chipset_series_samsung_exynos] = "Exynos ", [cpuinfo_arm_chipset_series_hisilicon_k3v] = "K3V", [cpuinfo_arm_chipset_series_hisilicon_hi] = "Hi", [cpuinfo_arm_chipset_series_hisilicon_kirin] = "Kirin ", [cpuinfo_arm_chipset_series_actions_atm] = "ATM", [cpuinfo_arm_chipset_series_allwinner_a] = "A", [cpuinfo_arm_chipset_series_amlogic_aml] = "AML", [cpuinfo_arm_chipset_series_amlogic_s] = "S", [cpuinfo_arm_chipset_series_broadcom_bcm] = "BCM", [cpuinfo_arm_chipset_series_lg_nuclun] = "Nuclun ", [cpuinfo_arm_chipset_series_leadcore_lc] = "LC", [cpuinfo_arm_chipset_series_marvell_pxa] = "PXA", [cpuinfo_arm_chipset_series_mstar_6a] = "6A", [cpuinfo_arm_chipset_series_novathor_u] = "U", [cpuinfo_arm_chipset_series_nvidia_tegra_t] = "Tegra T", [cpuinfo_arm_chipset_series_nvidia_tegra_ap] = "Tegra AP", [cpuinfo_arm_chipset_series_nvidia_tegra_sl] = "Tegra SL", [cpuinfo_arm_chipset_series_pinecone_surge_s] = "Surge S", [cpuinfo_arm_chipset_series_renesas_mp] = "MP", [cpuinfo_arm_chipset_series_rockchip_rk] = "RK", [cpuinfo_arm_chipset_series_spreadtrum_sc] = "SC", [cpuinfo_arm_chipset_series_telechips_tcc] = "TCC", [cpuinfo_arm_chipset_series_texas_instruments_omap] = "OMAP", [cpuinfo_arm_chipset_series_wondermedia_wm] = "WM", }; /* Convert chipset name represented by cpuinfo_arm_chipset structure to a string representation */ void cpuinfo_arm_chipset_to_string( const struct cpuinfo_arm_chipset chipset[restrict static 1], char name[restrict static CPUINFO_ARM_CHIPSET_NAME_MAX]) { enum cpuinfo_arm_chipset_vendor vendor = chipset->vendor; if (vendor >= cpuinfo_arm_chipset_vendor_max) { vendor = cpuinfo_arm_chipset_vendor_unknown; } enum cpuinfo_arm_chipset_series series = chipset->series; if (series >= cpuinfo_arm_chipset_series_max) { series = cpuinfo_arm_chipset_series_unknown; } const char* vendor_string = chipset_vendor_string[vendor]; const char* series_string = chipset_series_string[series]; const uint32_t model = chipset->model; if (model == 0) { if (series == cpuinfo_arm_chipset_series_unknown) { strncpy(name, vendor_string, CPUINFO_ARM_CHIPSET_NAME_MAX); } else { snprintf(name, CPUINFO_ARM_CHIPSET_NAME_MAX, "%s %s", vendor_string, series_string); } } else { const size_t suffix_length = strnlen(chipset->suffix, CPUINFO_ARM_CHIPSET_SUFFIX_MAX); snprintf(name, CPUINFO_ARM_CHIPSET_NAME_MAX, "%s %s%"PRIu32"%.*s", vendor_string, series_string, model, (int) suffix_length, chipset->suffix); } } #ifdef __ANDROID__ static inline struct cpuinfo_arm_chipset disambiguate_qualcomm_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_product_board_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_board_platform_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_chipname_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_hardware_chipname_chipset[restrict static 1]) { if (ro_hardware_chipname_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_hardware_chipname_chipset; } if (ro_chipname_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_chipname_chipset; } if (proc_cpuinfo_hardware_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *proc_cpuinfo_hardware_chipset; } if (ro_product_board_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_product_board_chipset; } return *ro_board_platform_chipset; } static inline struct cpuinfo_arm_chipset disambiguate_mediatek_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_product_board_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_board_platform_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_mediatek_platform_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_chipname_chipset[restrict static 1]) { if (ro_chipname_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_chipname_chipset; } if (proc_cpuinfo_hardware_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *proc_cpuinfo_hardware_chipset; } if (ro_product_board_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_product_board_chipset; } if (ro_board_platform_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_board_platform_chipset; } return *ro_mediatek_platform_chipset; } static inline struct cpuinfo_arm_chipset disambiguate_hisilicon_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_product_board_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_board_platform_chipset[restrict static 1]) { if (proc_cpuinfo_hardware_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *proc_cpuinfo_hardware_chipset; } if (ro_product_board_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_product_board_chipset; } return *ro_board_platform_chipset; } static inline struct cpuinfo_arm_chipset disambiguate_amlogic_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_board_platform_chipset[restrict static 1]) { if (proc_cpuinfo_hardware_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *proc_cpuinfo_hardware_chipset; } return *ro_board_platform_chipset; } static inline struct cpuinfo_arm_chipset disambiguate_marvell_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_product_board_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_chipname_chipset[restrict static 1]) { if (ro_chipname_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_chipname_chipset; } if (ro_product_board_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_product_board_chipset; } return *proc_cpuinfo_hardware_chipset; } static inline struct cpuinfo_arm_chipset disambiguate_rockchip_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_product_board_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_board_platform_chipset[restrict static 1]) { if (ro_product_board_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_product_board_chipset; } if (proc_cpuinfo_hardware_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *proc_cpuinfo_hardware_chipset; } return *ro_board_platform_chipset; } static inline struct cpuinfo_arm_chipset disambiguate_spreadtrum_chipset( const struct cpuinfo_arm_chipset proc_cpuinfo_hardware_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_product_board_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_board_platform_chipset[restrict static 1], const struct cpuinfo_arm_chipset ro_chipname_chipset[restrict static 1]) { if (ro_chipname_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_chipname_chipset; } if (ro_product_board_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *ro_product_board_chipset; } if (proc_cpuinfo_hardware_chipset->series != cpuinfo_arm_chipset_series_unknown) { return *proc_cpuinfo_hardware_chipset; } return *ro_board_platform_chipset; } /* * Decodes chipset name from Android system properties: * - /proc/cpuinfo Hardware string * - ro.product.board * - ro.board.platform * - ro.mediatek.platform * - ro.chipname * For some chipsets, the function relies frequency and on number of cores for chipset detection. * * @param[in] properties - structure with the Android system properties described above. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` vendor * and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_android_decode_chipset( const struct cpuinfo_android_properties properties[restrict static 1], uint32_t cores, uint32_t max_cpu_freq_max) { struct cpuinfo_arm_chipset chipset = { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; const bool tegra_platform = is_tegra( properties->ro_board_platform, properties->ro_board_platform + strnlen(properties->ro_board_platform, CPUINFO_BUILD_PROP_VALUE_MAX)); struct cpuinfo_arm_chipset chipsets[cpuinfo_android_chipset_property_max] = { [cpuinfo_android_chipset_property_proc_cpuinfo_hardware] = cpuinfo_arm_linux_decode_chipset_from_proc_cpuinfo_hardware( properties->proc_cpuinfo_hardware, cores, max_cpu_freq_max, tegra_platform), [cpuinfo_android_chipset_property_ro_product_board] = cpuinfo_arm_android_decode_chipset_from_ro_product_board( properties->ro_product_board, cores, max_cpu_freq_max), [cpuinfo_android_chipset_property_ro_board_platform] = cpuinfo_arm_android_decode_chipset_from_ro_board_platform( properties->ro_board_platform, cores, max_cpu_freq_max), [cpuinfo_android_chipset_property_ro_mediatek_platform] = cpuinfo_arm_android_decode_chipset_from_ro_mediatek_platform(properties->ro_mediatek_platform), [cpuinfo_android_chipset_property_ro_arch] = cpuinfo_arm_android_decode_chipset_from_ro_arch(properties->ro_arch), [cpuinfo_android_chipset_property_ro_chipname] = cpuinfo_arm_android_decode_chipset_from_ro_chipname(properties->ro_chipname), [cpuinfo_android_chipset_property_ro_hardware_chipname] = cpuinfo_arm_android_decode_chipset_from_ro_chipname(properties->ro_hardware_chipname), }; enum cpuinfo_arm_chipset_vendor vendor = cpuinfo_arm_chipset_vendor_unknown; for (size_t i = 0; i < cpuinfo_android_chipset_property_max; i++) { const enum cpuinfo_arm_chipset_vendor decoded_vendor = chipsets[i].vendor; if (decoded_vendor != cpuinfo_arm_chipset_vendor_unknown) { if (vendor == cpuinfo_arm_chipset_vendor_unknown) { vendor = decoded_vendor; } else if (vendor != decoded_vendor) { /* Parsing different system properties produces different chipset vendors. This situation is rare. */ cpuinfo_log_error( "chipset detection failed: different chipset vendors reported in different system properties"); goto finish; } } } if (vendor == cpuinfo_arm_chipset_vendor_unknown) { cpuinfo_log_warning( "chipset detection failed: none of the system properties matched known signatures"); goto finish; } /* Fix common bugs in reported chipsets */ for (size_t i = 0; i < cpuinfo_android_chipset_property_max; i++) { cpuinfo_arm_fixup_chipset(&chipsets[i], cores, max_cpu_freq_max); } /* * Propagate suffixes: consider all pairs of chipsets, if both chipsets in the pair are from the same series, * and one's suffix is a prefix of another's chipset suffix, use the longest suffix. */ for (size_t i = 0; i < cpuinfo_android_chipset_property_max; i++) { const size_t chipset_i_suffix_length = strnlen(chipsets[i].suffix, CPUINFO_ARM_CHIPSET_SUFFIX_MAX); for (size_t j = 0; j < i; j++) { if (chipsets[i].series == chipsets[j].series) { const size_t chipset_j_suffix_length = strnlen(chipsets[j].suffix, CPUINFO_ARM_CHIPSET_SUFFIX_MAX); if (chipset_i_suffix_length != chipset_j_suffix_length) { const size_t common_prefix_length = (chipset_i_suffix_length < chipset_j_suffix_length) ? chipset_i_suffix_length : chipset_j_suffix_length; if (common_prefix_length == 0 || memcmp(chipsets[i].suffix, chipsets[j].suffix, common_prefix_length) == 0) { if (chipset_i_suffix_length > chipset_j_suffix_length) { memcpy(chipsets[j].suffix, chipsets[i].suffix, chipset_i_suffix_length); } else { memcpy(chipsets[i].suffix, chipsets[j].suffix, chipset_j_suffix_length); } } } } } } for (size_t i = 0; i < cpuinfo_android_chipset_property_max; i++) { if (chipsets[i].series != cpuinfo_arm_chipset_series_unknown) { if (chipset.series == cpuinfo_arm_chipset_series_unknown) { chipset = chipsets[i]; } else if (chipsets[i].series != chipset.series || chipsets[i].model != chipset.model || strncmp(chipsets[i].suffix, chipset.suffix, CPUINFO_ARM_CHIPSET_SUFFIX_MAX) != 0) { cpuinfo_log_info( "different chipsets reported in different system properties; " "vendor-specific disambiguation heuristic would be used"); switch (vendor) { case cpuinfo_arm_chipset_vendor_qualcomm: return disambiguate_qualcomm_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_product_board], &chipsets[cpuinfo_android_chipset_property_ro_board_platform], &chipsets[cpuinfo_android_chipset_property_ro_chipname], &chipsets[cpuinfo_android_chipset_property_ro_hardware_chipname]); case cpuinfo_arm_chipset_vendor_mediatek: return disambiguate_mediatek_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_product_board], &chipsets[cpuinfo_android_chipset_property_ro_board_platform], &chipsets[cpuinfo_android_chipset_property_ro_mediatek_platform], &chipsets[cpuinfo_android_chipset_property_ro_chipname]); case cpuinfo_arm_chipset_vendor_hisilicon: return disambiguate_hisilicon_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_product_board], &chipsets[cpuinfo_android_chipset_property_ro_board_platform]); case cpuinfo_arm_chipset_vendor_amlogic: return disambiguate_amlogic_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_board_platform]); case cpuinfo_arm_chipset_vendor_marvell: return disambiguate_marvell_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_product_board], &chipsets[cpuinfo_android_chipset_property_ro_chipname]); case cpuinfo_arm_chipset_vendor_rockchip: return disambiguate_rockchip_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_product_board], &chipsets[cpuinfo_android_chipset_property_ro_board_platform]); case cpuinfo_arm_chipset_vendor_spreadtrum: return disambiguate_spreadtrum_chipset( &chipsets[cpuinfo_android_chipset_property_proc_cpuinfo_hardware], &chipsets[cpuinfo_android_chipset_property_ro_product_board], &chipsets[cpuinfo_android_chipset_property_ro_board_platform], &chipsets[cpuinfo_android_chipset_property_ro_chipname]); default: cpuinfo_log_error( "chipset detection failed: " "could not disambiguate different chipsets reported in different system properties"); /* chipset variable contains valid, but inconsistent chipset information, overwrite it */ chipset = (struct cpuinfo_arm_chipset) { .vendor = cpuinfo_arm_chipset_vendor_unknown, .series = cpuinfo_arm_chipset_series_unknown, }; goto finish; } } } } finish: return chipset; } #else /* !defined(__ANDROID__) */ /* * Fix commonly misreported Broadcom BCM models on Raspberry Pi boards. * * @param[in,out] chipset - chipset name to fix. * @param[in] revision - /proc/cpuinfo Revision string. */ void cpuinfo_arm_fixup_raspberry_pi_chipset( struct cpuinfo_arm_chipset chipset[restrict static 1], const char revision[restrict static CPUINFO_HARDWARE_VALUE_MAX]) { const size_t revision_length = strnlen(revision, CPUINFO_REVISION_VALUE_MAX); /* Parse revision codes according to https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md */ #if CPUINFO_ARCH_ARM if (revision_length == 4) { /* * Old-style revision codes. * All Raspberry Pi models with old-style revision code use Broadcom BCM2835. */ /* BCM2835 often misreported as BCM2708 */ if (chipset->model == 2708) { chipset->model = 2835; } return; } #endif if ((size_t) (revision_length - 5) <= (size_t) (8 - 5) /* 5 <= length(revision) <= 8 */) { /* New-style revision codes */ uint32_t model = 0; switch (revision[revision_length - 4]) { case '0': /* BCM2835 */ model = 2835; break; case '1': /* BCM2836 */ model = 2836; break; case '2': /* BCM2837 */ model = 2837; break; case '3': /* BCM2711 */ model = 2711; break; } if (model != 0) { chipset->model = model; chipset->suffix[0] = 0; } } } /* * Decodes chipset name from /proc/cpuinfo Hardware string. * For some chipsets, the function relies frequency and on number of cores for chipset detection. * * @param[in] hardware - /proc/cpuinfo Hardware string. * @param cores - number of cores in the chipset. * @param max_cpu_freq_max - maximum of /sys/devices/system/cpu/cpu<number>/cpofreq/cpu_freq_max values. * * @returns Decoded chipset name. If chipset could not be decoded, the resulting structure would use `unknown` vendor * and series identifiers. */ struct cpuinfo_arm_chipset cpuinfo_arm_linux_decode_chipset( const char hardware[restrict static CPUINFO_HARDWARE_VALUE_MAX], const char revision[restrict static CPUINFO_REVISION_VALUE_MAX], uint32_t cores, uint32_t max_cpu_freq_max) { struct cpuinfo_arm_chipset chipset = cpuinfo_arm_linux_decode_chipset_from_proc_cpuinfo_hardware( hardware, cores, max_cpu_freq_max, false); if (chipset.vendor == cpuinfo_arm_chipset_vendor_unknown) { cpuinfo_log_warning( "chipset detection failed: /proc/cpuinfo Hardware string did not match known signatures"); } else if (chipset.vendor == cpuinfo_arm_chipset_vendor_broadcom) { /* Raspberry Pi kernel reports bogus chipset models; detect chipset from RPi revision */ cpuinfo_arm_fixup_raspberry_pi_chipset(&chipset, revision); } else { cpuinfo_arm_fixup_chipset(&chipset, cores, max_cpu_freq_max); } return chipset; } #endif
2.265625
2
2024-11-18T18:39:56.712410+00:00
2016-02-09T02:21:16
8c0cdeff5f8a86fefead0bf7e2f3763a7842b4cc
{ "blob_id": "8c0cdeff5f8a86fefead0bf7e2f3763a7842b4cc", "branch_name": "refs/heads/master", "committer_date": "2016-02-09T02:21:16", "content_id": "fef25b0ae2cce8a9f3cdaafd66d721856f8f1184", "detected_licenses": [ "Apache-2.0" ], "directory_id": "800a1a35ef6bf3108377cb16c15a290ddff68796", "extension": "h", "filename": "ac_thread.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1550, "license": "Apache-2.0", "license_type": "permissive", "path": "/libs/incs/ac_thread.h", "provenance": "stackv2-0030.json.gz:11845", "repo_name": "cci-smoketests/sadie", "revision_date": "2016-02-09T02:21:16", "revision_id": "0ac7872225dcc874983216369c747c875f36bd0f", "snapshot_id": "27f5b9637347d13adc2e17eb93b01d5ba9d8bb21", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cci-smoketests/sadie/0ac7872225dcc874983216369c747c875f36bd0f/libs/incs/ac_thread.h", "visit_date": "2021-01-20T22:41:09.982980" }
stackv2
/* * Copyright 2015 Wink Saville * * 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 SADIE_PLATFORM_VERSATILEPB_LIBS_AC_CPU_PERF_INCS_AC_THREAD_H #define SADIE_PLATFORM_VERSATILEPB_LIBS_AC_CPU_PERF_INCS_AC_THREAD_H #include <ac_inttypes.h> #include <ac_thread_stack_min.h> /** * Initialize module */ void ac_thread_init(ac_u32 max_threads); /** * The current thread yeilds the CPU to the next * ready thread. */ void ac_thread_yield(void); /** * Create a thread and invoke the entry passing entry_arg. If * the entry routine returns the thread is considered dead * and will not be rescheduled and its stack is reclamined. * Any other global memory associated with the thread still * exists and is left untouched. * * @param stack_size is 0 a "default" stack size will be used. * @param entry is the routine to run * @param entry_arg is the argument passed to entry. * * @return 0 on success !0 if an error. */ ac_u32 ac_thread_create(ac_size_t stack_size, void*(*entry)(void*), void* entry_arg); #endif
2.03125
2
2024-11-18T18:39:57.864572+00:00
2019-06-10T14:32:00
52bcb4b7c0f4b9d2856b996265ed2ba615d59ca6
{ "blob_id": "52bcb4b7c0f4b9d2856b996265ed2ba615d59ca6", "branch_name": "refs/heads/master", "committer_date": "2019-06-10T14:32:00", "content_id": "2d772837cb53fb27b1839bd942bf3b955705649d", "detected_licenses": [ "MIT" ], "directory_id": "b54a93d0d8fa05e0481792e113e94b6a099c50bb", "extension": "c", "filename": "test-cas.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4799, "license": "MIT", "license_type": "permissive", "path": "/stbapi/test-cas.c", "provenance": "stackv2-0030.json.gz:12486", "repo_name": "boostrack-sat/MAG_Software_Portal", "revision_date": "2019-06-10T14:32:00", "revision_id": "691338ca2319c3dbb51d80a3ec62eed6c7753d46", "snapshot_id": "f1fedf12b151d67c9ce3d7e2137118b08904c36e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/boostrack-sat/MAG_Software_Portal/691338ca2319c3dbb51d80a3ec62eed6c7753d46/stbapi/test-cas.c", "visit_date": "2022-02-27T15:38:19.142173" }
stackv2
#include "MAG-CAS-plugin.h" #include "stdio.h" #define DEBUG(x...) {}//printf(x) #define DEBUG_CALL() DEBUG("Called function %s\n",__FUNCTION__) STB_MAG_Cas_t PluginInterface; STB_MAG_Cad_t DescramblerInterface = {NULL,NULL}; /** * Callback to be called by Player on PMT change */ void CAS_OnPmtChange(byte* buffer, int length) { DEBUG_CALL(); //extract some necessary information for decryption if needed //this function is used in CAS_Flags_PMT_ECM mode only return; }; /** * Callback to be called by Player on every ECM */ void CAS_OnEcm(byte* ecm, int length) { DEBUG_CALL(); //extract some necessary information for decryption if needed //this function is used in CAS_Flags_PMT_ECM mode only //for example set keys and algorithm if(DescramblerInterface.SetScramblingKey && DescramblerInterface.SetScramblingType) { DescramblerInterface.SetScramblingType(CAS_SCRAMBLING_TYPE_AES); char evenKey[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; char oddKey[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; DescramblerInterface.SetScramblingKey(evenKey,0); DescramblerInterface.SetScramblingKey(oddKey,1); } return; }; /** * Callback to be called by Player to decrypt transport stream * by CAS module. * in_buffer - pointer to encrypted data. * decrypted data will be put to the in_buffer * length - size of input data * * CAS plugin MUST clear Transport Scrambling Control bits after * decryption. * * Returns size of decrypted data */ int CAS_Decrypt(byte* in_buffer, int length) { DEBUG_CALL(); //this function is used in CAS_Flags_DecodeAll or CAS_Flags_DecodeAll_PMT mode //decrypt stream //For CAS_Flags_DecodeAll_PMT mode probably there should be pre-decryption of whole stream int offs = 0; for(offs = 0; offs < length; offs += 188) {//process single TS Packet //check scrambling control bits int sc = (in_buffer[offs+3]>>6)&0x3; if(sc == 0 || sc == 1) {//not encrypted continue; } if(sc == 2) { //decrypt packet using even key }else { //decrypt packet using odd key } //!!!!!!!!!DO NOT FORGET to clear scrambling control bits in_buffer[offs+3] = in_buffer[offs+3]&0x3f; } return length; }; /** * Free up CA module */ void CAS_Deinit(void) { DEBUG_CALL(); //release all resources allocated by CreateCas return; }; /** * Reset CAS context. Usually called to indicate that user has * switched to another stream */ void CAS_ResetStream(void) { DEBUG_CALL(); //decryption context has changed return; }; /** * Get CAS vendor SysID as defined in DVB. Useful only in * CAS_Flags_PMT_ECM mode */ int CAS_GetSysID(void) { DEBUG_CALL(); return 0; }; /** * Get CAS vendor SoID as defined in DVB. Useful only in * CAS_Flags_PMT_ECM mode */ int CAS_GetSoID(void) { DEBUG_CALL(); return 0; }; /** * Get CAS vendor specific flags * * @see CAS_Flags_e */ CAS_Flags_e CAS_GetCasFlags(void) { DEBUG_CALL(); return CAS_Flags_DecodeAll; }; /** * Get the format of ECM data expected by the plugin in * CAS_OnEcm */ ECM_Format_e CAS_GetEcmFormat(void) { DEBUG_CALL(); return ECM_FORMAT_SECTION; }; /** * Set some custom param to CAS plugin. * * name - param name always converted to upper case * value - param value */ void CAS_SetAdditionalParam(const char* name, const char* value) { DEBUG_CALL(); DEBUG("CAS Plugin param: name '%s' value '%s'\n",name,value); }; /* dynamic library will implement this */ STB_MAG_Cas_t* CreateCasPlugin(STB_MAG_Cad_t* mag_interface, const char* ini_filename) { if(mag_interface) { DescramblerInterface.SetScramblingKey = mag_interface->SetScramblingKey; DescramblerInterface.SetScramblingType = mag_interface->SetScramblingType; } PluginInterface.Decrypt = CAS_Decrypt; PluginInterface.Deinit = CAS_Deinit; PluginInterface.GetCasFlags = CAS_GetCasFlags; PluginInterface.GetEcmFormat = NULL; PluginInterface.GetSoID = NULL; PluginInterface.GetSysID = NULL; PluginInterface.OnEcm = NULL; PluginInterface.OnPmtChange = NULL; PluginInterface.ResetStream = CAS_ResetStream; PluginInterface.SetAdditionalParam = CAS_SetAdditionalParam; return &PluginInterface; }; /** * CAS API implementation version of the CAS vendor library * dynamic library will implement this * * @see CAS_API_VERSION */ int GetCasApiVersion(void) { return CAS_API_VERSION; }; /** * Get description of CAS plugin (e.i. Vendor, ...) */ const char* GetCasPluginDescription(void) { return "simple CAS plugin example in CAS_Flags_DecodeAll mode"; };
2.21875
2
2024-11-18T18:39:59.348972+00:00
2020-06-15T11:23:08
ef08fd90984d5988df787945d408348bb25bbb26
{ "blob_id": "ef08fd90984d5988df787945d408348bb25bbb26", "branch_name": "refs/heads/master", "committer_date": "2020-06-15T11:23:08", "content_id": "bd86e5926f88de5be8e28b0a88aa74436d5d789f", "detected_licenses": [ "MIT" ], "directory_id": "7b6057b1a13e528fd09c3a3b9d8b76a709e2eed4", "extension": "c", "filename": "lista_estatica_compara.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 244457708, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3304, "license": "MIT", "license_type": "permissive", "path": "/src/ECEP1/lista_estatica_compara.c", "provenance": "stackv2-0030.json.gz:13255", "repo_name": "dreis0/algoritmos-estrutura-dados", "revision_date": "2020-06-15T11:23:08", "revision_id": "dd570a7d8e4ec4b6ba5617b2861f9efee97ab912", "snapshot_id": "a0cf933a66ff1e640a26237f505c75a5eb002d77", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dreis0/algoritmos-estrutura-dados/dd570a7d8e4ec4b6ba5617b2861f9efee97ab912/src/ECEP1/lista_estatica_compara.c", "visit_date": "2021-02-11T05:09:15.648399" }
stackv2
#include <stdio.h> #include <stdlib.h> struct Lista { int *itens; int quantidade, tamanho; }; void criaLista(struct Lista *, int); int busca(struct Lista, int); void insere(struct Lista *, int); void exclui(struct Lista *, int); void mostra(struct Lista); int listaEstaContidaEmLista(struct Lista *, struct Lista *); int main(void) { struct Lista l1, l2; int operacoesL1, operacoesL2, x; char op; scanf("%d %d", &operacoesL1, &operacoesL2); criaLista(&l1, operacoesL1); criaLista(&l2, operacoesL2); while (operacoesL1--) { scanf("\n%c %d", &op, &x); if (op == 'I') { if (!busca(l1, x)) { insere(&l1, x); } } else if (op == 'E') { if (busca(l1, x)) { exclui(&l1, x); } } } while (operacoesL2--) { scanf("\n%c %d", &op, &x); if (op == 'I') { if (!busca(l2, x)) { insere(&l2, x); } } else if (op == 'E') { if (busca(l2, x)) { exclui(&l2, x); } } } if (listaEstaContidaEmLista(&l1, &l2) != 0) printf("SIM\n"); else printf("NAO\n"); free(l1.itens); free(l2.itens); return 0; } void criaLista(struct Lista *l, int n) { l->itens = (int *)malloc(n * sizeof(int)); l->quantidade = 0; l->tamanho = n; } void insere(struct Lista *lista, int chave) { int i = 0, achei = 0, j; while (i < lista->quantidade && !achei) { if (lista->itens[i] > chave) { achei = 1; } else { i++; } } if (achei) { for (j = lista->quantidade; j > i; j--) { lista->itens[j] = lista->itens[j - 1]; } } lista->itens[i] = chave; lista->quantidade++; } void exclui(struct Lista *lista, int chave) { int i = 0, achei = 0, j; while (i < lista->quantidade && !achei) { if (lista->itens[i] == chave) { achei = 1; } else { i++; } } if (achei) { for (j = i; j < lista->quantidade - 1; j++) { lista->itens[j] = lista->itens[j + 1]; } lista->quantidade--; } } int busca(struct Lista lista, int chave) { int esq = 0, dir = lista.quantidade - 1, meio; while (esq <= dir) { meio = (esq + dir) / 2; if (lista.itens[meio] == chave) { return 1; } else if (lista.itens[meio] > chave) { dir = meio - 1; } else { esq = meio + 1; } } return 0; } void mostra(struct Lista lista) { int i; for (i = 0; i < lista.quantidade; i++) { printf("%d\n", lista.itens[i]); } } int listaEstaContidaEmLista(struct Lista *l1, struct Lista *l2) { int valorEncontrado = 1, estaContido = 1; for (int i = 0; i < l1->quantidade; i++) { valorEncontrado = busca(*l2, l1->itens[i]); if (valorEncontrado == 0) estaContido = 0; } return estaContido; }
3.5625
4
2024-11-18T18:39:59.741825+00:00
2020-01-17T08:53:50
fd3d23d3f3e0fd03a3bbdb02988921d4b7baad63
{ "blob_id": "fd3d23d3f3e0fd03a3bbdb02988921d4b7baad63", "branch_name": "refs/heads/master", "committer_date": "2020-01-17T08:53:50", "content_id": "5f8835038693fb9a43cd469c47a098b80594c859", "detected_licenses": [ "MIT" ], "directory_id": "7c441af6a3f71dd766edfc34919182227cbd8815", "extension": "c", "filename": "to.c", "fork_events_count": 0, "gha_created_at": "2020-01-17T08:46:06", "gha_event_created_at": "2023-05-07T19:53:16", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 234507910, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1157, "license": "MIT", "license_type": "permissive", "path": "/mudlib/cmds/std/to.c", "provenance": "stackv2-0030.json.gz:13639", "repo_name": "angeluslove/es2", "revision_date": "2020-01-17T08:53:50", "revision_id": "9e24d6c0272231214f32699cbac23f4bbace370d", "snapshot_id": "a0c69e57522cb940346c6805fd85e19cc0bbbad1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/angeluslove/es2/9e24d6c0272231214f32699cbac23f4bbace370d/mudlib/cmds/std/to.c", "visit_date": "2023-05-26T04:21:12.032453" }
stackv2
// to.c // inherit F_CLEAN_UP; // Don't want this command be cleaned up while typing long string. int main(object me, string arg) { // me->edit( (: this_object(), ({ "do_to", me, arg }) :) ); return 1; } void do_to(object me, string arg, string str) { seteuid(getuid()); if(arg) me->force_me(arg + " " + str); else me->force_me(str); } int help(object me) { write(@HELP 指令格式 : to <指令> 可以一次输出多行以上的文字, <指令>通常是输出讯息的指令如 say , tell , describe , chat , reple ........等。 □例 : to say 结束离开用 '.',取消输入用 '~q',使用内建列编辑器用 '~e'。 ————————————————————————————— 东方神教教主 : 安尼席洛特尔 教主大夫人暨发呆部部长 : Elon 教主小老婆暨摸鱼部部长 : 梦忆柔 大弟子暨打混部部长 : 风火血舞 . 输出到萤幕上的结果则是 : 你说道:东方神教教主 : 安尼席洛特尔 教主大夫人暨发呆部部长 : Elon 教主小老婆暨摸鱼部部长 : 梦忆柔 大弟子暨打混部部长 : 风火血舞 HELP ); return 1; }
2.4375
2
2024-11-18T18:39:59.815502+00:00
2023-08-04T14:47:27
3ad3e0b3dd2b05d94f58b1b297a2411c66dd12dd
{ "blob_id": "3ad3e0b3dd2b05d94f58b1b297a2411c66dd12dd", "branch_name": "refs/heads/main", "committer_date": "2023-08-04T14:47:27", "content_id": "4983b9048d407a5e6e081b38b72f3303904cbad9", "detected_licenses": [ "MIT" ], "directory_id": "51e4ae3bc7e715c52be1021e734f9dd8ce62eace", "extension": "h", "filename": "color.h", "fork_events_count": 1, "gha_created_at": "2021-04-08T10:24:35", "gha_event_created_at": "2021-04-21T01:55:34", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 355860453, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1366, "license": "MIT", "license_type": "permissive", "path": "/src/bpy/3.6/scripts/addons/cycles/source/kernel/util/color.h", "provenance": "stackv2-0030.json.gz:13768", "repo_name": "RnoB/3DVisualSwarm", "revision_date": "2023-08-04T14:47:27", "revision_id": "4d5c304878c1e0018d97c1b07bcaa3981632265a", "snapshot_id": "831f5249337b3bbc04fec6a2a8b19144b096ebb4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RnoB/3DVisualSwarm/4d5c304878c1e0018d97c1b07bcaa3981632265a/src/bpy/3.6/scripts/addons/cycles/source/kernel/util/color.h", "visit_date": "2023-08-24T12:13:58.300397" }
stackv2
/* SPDX-License-Identifier: Apache-2.0 * Copyright 2011-2022 Blender Foundation */ #pragma once #include "util/color.h" CCL_NAMESPACE_BEGIN ccl_device float3 xyz_to_rgb(KernelGlobals kg, float3 xyz) { return make_float3(dot(float4_to_float3(kernel_data.film.xyz_to_r), xyz), dot(float4_to_float3(kernel_data.film.xyz_to_g), xyz), dot(float4_to_float3(kernel_data.film.xyz_to_b), xyz)); } ccl_device float3 xyz_to_rgb_clamped(KernelGlobals kg, float3 xyz) { return max(xyz_to_rgb(kg, xyz), zero_float3()); } ccl_device float3 rec709_to_rgb(KernelGlobals kg, float3 rec709) { return (kernel_data.film.is_rec709) ? rec709 : make_float3(dot(float4_to_float3(kernel_data.film.rec709_to_r), rec709), dot(float4_to_float3(kernel_data.film.rec709_to_g), rec709), dot(float4_to_float3(kernel_data.film.rec709_to_b), rec709)); } ccl_device float linear_rgb_to_gray(KernelGlobals kg, float3 c) { return dot(c, float4_to_float3(kernel_data.film.rgb_to_y)); } ccl_device_inline Spectrum rgb_to_spectrum(float3 rgb) { return rgb; } ccl_device_inline float3 spectrum_to_rgb(Spectrum s) { return s; } ccl_device float spectrum_to_gray(KernelGlobals kg, Spectrum c) { return linear_rgb_to_gray(kg, spectrum_to_rgb(c)); } CCL_NAMESPACE_END
2.15625
2
2024-11-18T18:40:00.127485+00:00
2018-05-07T13:47:33
1445ac7154aab15541bca4947353c3c7e98f5aa1
{ "blob_id": "1445ac7154aab15541bca4947353c3c7e98f5aa1", "branch_name": "refs/heads/master", "committer_date": "2018-05-07T13:47:33", "content_id": "b2e9b598db23c9a0287ec89be3a8865c0d2b42f5", "detected_licenses": [ "MIT" ], "directory_id": "15f2d5148f302f2ba716b49cc14ea6dec0fed98c", "extension": "c", "filename": "ais_cmdbuff.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11525, "license": "MIT", "license_type": "permissive", "path": "/msl_electronic_boards/mctrl/vmc_ais/system/ais_cmdbuff.c", "provenance": "stackv2-0030.json.gz:14153", "repo_name": "dasys-lab/cnc-msl", "revision_date": "2018-05-07T13:47:33", "revision_id": "e55f40a0baebc754283f5cf130c36e31abf8ee64", "snapshot_id": "20937039153e3335d36d2c45ac354bee471534e0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dasys-lab/cnc-msl/e55f40a0baebc754283f5cf130c36e31abf8ee64/msl_electronic_boards/mctrl/vmc_ais/system/ais_cmdbuff.c", "visit_date": "2021-09-28T18:59:18.962448" }
stackv2
////////////////////////////////////////////////////////////////////////////// /// \defgroup Communication Buffer for AISC167Board //@{ /// \file ais_combuff.c /// /// \brief Communication Buffer and Fetch&Validate Functions for AISC167 /// Communication /// /// \author Adam Cwientzek /// /// \version 0.8 /// /// \date 27.12.2005 /// /// \note none /// ////////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <reg167.h> #include <INTRINS.H> #include <stdlib.h> #include <intrins.h> #include <string.h> #include "system/ais_cmdbuff.h" #include "system/ais_astring.h" #include "comasc/ais_asccom.h" #include "system/ais_system.h" #include "can_stuff/ais_can.h" #include "motorctrl/ais_error.h" // needed to reset timeout - bad solution !! // Buffer struct CmdStruct cmdb_RX[_CMDB_RX_SIZE_]; struct CmdStruct cmdb_TX[_CMDB_RX_SIZE_]; // Index for Buffer, see _CMDB_LAST_/_CMDB_FIRST_ and // _CMDB_RX_ / _CMDB_TX_ VMC_UCHAR_8 cmdb_index[2][2] = { {0,0}, {0,0} }; // ################ Buffer PointerControl #################################### ////////////////////////////////////////////////////////////////////////////// /// Calucalte/Move Buffer-Indexes /// /// \param Buffer use constants to select Buffer : _CMDB_RX_ or _CMDB_TX_ /// /// \param Index use constants to select Index : _CMDB_FIRST_ or _CMDB_LAST_ /// ////////////////////////////////////////////////////////////////////////////// VMC_UCHAR_8 cmdb_move_next(VMC_UCHAR_8 Buffer, VMC_UCHAR_8 Index) { VMC_UINT_16 TmpIdx; // Get Index Value TmpIdx = cmdb_index[Buffer][Index] + 1; // Modulo Buffersize (ring Buffer) Differ Buffer, take appropriate size if ( Buffer == _CMDB_RX_ ) { TmpIdx = TmpIdx % _CMDB_RX_SIZE_; } else { TmpIdx = TmpIdx % _CMDB_TX_SIZE_; } switch ( Index ) { // For LAST Index: // when both Indexes are same, that means we have reached first entry again. // Buffer is full, first entry (oldest) will be discarded! case _CMDB_LAST_: if ( TmpIdx == cmdb_index[Buffer][_CMDB_FIRST_] ) cmdb_move_next(Buffer, _CMDB_FIRST_); // Move first, discard oldest Command!! break; // For Index FIRST: // Check if any Data is available, else do not move Pointer! case _CMDB_FIRST_: if ( cmdb_index[Buffer][_CMDB_FIRST_] == cmdb_index[Buffer][_CMDB_LAST_] ) return 0; } cmdb_index[Buffer][Index] = TmpIdx; return 1; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Count entries if RX Buffer /// /// \return /// /// ////////////////////////////////////////////////////////////////////////////// VMC_UCHAR_8 cmdb_count(VMC_UCHAR_8 Buffer) { // diff. between First ans last Position int count = cmdb_index[Buffer][_CMDB_LAST_] - cmdb_index[Buffer][_CMDB_FIRST_]; // needed for overflow in Index (Ring-Buffer!) if ( count < 0 ) switch ( Buffer ) { case _CMDB_RX_ : count += _CMDB_RX_SIZE_; break; case _CMDB_TX_ : count += _CMDB_TX_SIZE_; break; } return count; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Check if RX Buffer is empty /// /// \return /// /// ////////////////////////////////////////////////////////////////////////////// VMC_UCHAR_8 cmdb_isempty(VMC_UCHAR_8 Buffer) { return (cmdb_count(Buffer) == 0); } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Copy Data from Cmd1 to Cmd2 /// ////////////////////////////////////////////////////////////////////////////// void cmdb_CommandCopy(struct CmdStruct *Cmd1, struct CmdStruct *Cmd2) { VMC_UINT_16 i; (*Cmd2).rxaddr = (*Cmd1).rxaddr; (*Cmd2).txaddr = (*Cmd1).txaddr; (*Cmd2).count = (*Cmd1).count; (*Cmd2).sysinf = (*Cmd1).sysinf; (*Cmd2).datalen = (*Cmd1).datalen; (*Cmd2).channel = (*Cmd1).channel; (*Cmd2).cmdgrp = (*Cmd1).cmdgrp; (*Cmd2).cmd = (*Cmd1).cmd; for ( i=0; i<_CMDB_MAXDATA_; i++ ) { (*Cmd2).data[i] = (*Cmd1).data[i]; } } ////////////////////////////////////////////////////////////////////////////// // ################ TRIGGER FUNCTIONS ######################################## ////////////////////////////////////////////////////////////////////////////// /// Load one (oldest) or all Command from given (or all) channel(s). /// /// \param Channel: The Channel to look for new Commands. See ais_combuff.h /// for possible constants like _CMDB_CH_*_ /// For ASC0 use _CMDB_CH_ASC0_ /// To read all Channels use _CMDB_CH_ALL_ /// /// \param all: Use _CMDB_ALL_ if all Commands should be read /// Use _CMDB_ONE_ if only one (oldest) Command should be read /// /// \return 1 Command was loaded /// 0 No new Command loaded /// /// ////////////////////////////////////////////////////////////////////////////// VMC_UCHAR_8 cmdb_load_command(VMC_UCHAR_8 Channel, VMC_UCHAR_8 all) { VMC_UCHAR_8 loaded = 0; // struct CmdStruct temp_command; // Get new Data from ASC0 switch ( Channel ) { // Get Data from All Interfaces case _CMDB_CH_ALL_ : // Get Data from ASC0 case _CMDB_CH_ASC0_ : // New Command in ASC0 Buffer ? if ( asccom_getcmd( &cmdb_RX[ cmdb_index[_CMDB_RX_][_CMDB_LAST_] ] ) ) { // New Command copied to Buffer, mark buffer space as used cmdb_move_next(_CMDB_RX_, _CMDB_LAST_); loaded = 1; // Marke that one new command has been loaded reset_timeout(); // ? trouble ? if ( all ) cmdb_load_command(Channel, all); // Recursive Call } // HANDLE BUFFER OVERRUN! if ( asccom_buffer_overrun(ASC_BUF_IN) ) { // throw away rest of commands ! asccom_empty_buffer(ASC_BUF_IN); // Reset overrun flag asccom_buffer_r_overrun(ASC_BUF_IN); // SIGNAL OVERRUN ? ais_system_bufferError(); } // Break "switch" if single Channel selected, else go on if ( Channel != _CMDB_ALL_ ) break; } return loaded; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Send one (oldest) or all Commands from Buffer /// /// \return /// ////////////////////////////////////////////////////////////////////////////// VMC_UCHAR_8 cmdb_send_command(VMC_UCHAR_8 all) { if ( cmdb_isempty( _CMDB_TX_ ) ) { return 0; } else { // Get one Command from Buffer asccom_storecmd( &cmdb_TX[ cmdb_index[_CMDB_TX_][_CMDB_FIRST_] ] ); // Now next Command is first Buffer Entry cmdb_move_next(_CMDB_TX_, _CMDB_FIRST_); } if ( all ) return cmdb_send_command(all); // Recursive Call for all Buffer entries return 0; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Return oldest Command from RX Buffer /// /// \param *Command Pointer to Command Structure where Bufferdata will be copied /// to /// /// \return 1 if Data could be loaded from Buffer /// 0 if Buffer was empty (no data copied) /// /// ////////////////////////////////////////////////////////////////////////////// VMC_UCHAR_8 cmdb_get_command(struct CmdStruct *Command) { // Check if buffer is empty if ( cmdb_isempty( _CMDB_RX_ ) ) { return 0; } else { // f Data in buffer, copy it cmdb_CommandCopy( &cmdb_RX[ cmdb_index[_CMDB_RX_][_CMDB_FIRST_] ], Command); // Move buffer Index cmdb_move_next(_CMDB_RX_, _CMDB_FIRST_); // Return "Data copied" return 1; } } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Store Command in TX Buffer /// /// \param *Command Pointer to Command Structure that will be copied into Buf. /// ////////////////////////////////////////////////////////////////////////////// void cmdb_set_command(struct CmdStruct *Command) { // Sotre Data into Send-Buffer cmdb_CommandCopy( Command, &cmdb_TX[ cmdb_index[_CMDB_TX_][_CMDB_LAST_] ] ); // Move Index, overwrite old Data if full Buffer cmdb_move_next(_CMDB_TX_, _CMDB_LAST_); } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// \brief Add an Integer value as data to a command struct /// This function gets a pointer to a command struct and manipulates it directly /// It adds a Integer, split up into MSB and LSB to the data of the command and increases the datalen /// \param Command Pointer to the command struct /// \param param Integer value which should be add to the command ////////////////////////////////////////////////////////////////////////////// void cmdb_dataAppendStr(struct CmdStruct *Command,VMC_UCHAR_8 *string) { // loop counter VMC_UCHAR_8 i; // current datalen --> offset for new data VMC_UCHAR_8 offset = Command->datalen; // temp astring VMC_UCHAR_8 astemp[255]; // AString string_to_astring(astemp, string); for (i = 0; i < astemp[0]; i++) { Command->data[i + offset] = astemp[i+1]; Command->datalen++; } } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// \brief Add an Integer value as data to a command struct /// This function gets a pointer to a command struct and manipulates it directly /// It adds a Integer, split up into MSB and LSB to the data of the command and increases the datalen /// \param Command Pointer to the command struct /// \param param Integer value which should be add to the command ////////////////////////////////////////////////////////////////////////////// void cmdb_dataAppendChar(struct CmdStruct *Command, VMC_UCHAR_8 param) { // Function could be macro ? // write the next byte in the command and increase datalen Command->data[Command->datalen++] = param; } ////////////////////////////////////////////////////////////////////////////// void cmdb_dataAppendInt(struct CmdStruct *Command, VMC_UINT_16 param) { // Function could be macro ? // write the MSB to the next byte in the command and increase datalen Command->data[Command->datalen++] = param >> 8; // write the LSB to the next byte in the command and increase datalen Command->data[Command->datalen++] = param; } ////////////////////////////////////////////////////////////////////////////// void cmdb_dataAppendLong(struct CmdStruct *Command, TMC_ULONG_32 param) { // Function could be macro ? // write the MSB to the next byte in the command and increase datalen Command->data[Command->datalen++] = param >> 24; Command->data[Command->datalen++] = param >> 16; Command->data[Command->datalen++] = param >> 8; // write the LSB to the next byte in the command and increase datalen Command->data[Command->datalen++] = param; } ////////////////////////////////////////////////////////////////////////////// //@}
2.3125
2
2024-11-18T18:40:00.340383+00:00
2022-05-25T23:10:04
c88c9e01a98e88ed0e426f93c31c3c45e69cd56f
{ "blob_id": "c88c9e01a98e88ed0e426f93c31c3c45e69cd56f", "branch_name": "refs/heads/master", "committer_date": "2022-05-25T23:10:04", "content_id": "de9c8f753c034ccc9d37af93fdf360b37c0bcb1e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3e39e2fa31158d6d86a23773946084db17cd3317", "extension": "h", "filename": "esp_sysview_trace.h", "fork_events_count": 1, "gha_created_at": "2019-07-08T17:15:54", "gha_event_created_at": "2022-02-20T21:04:41", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 195855829, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2096, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/app_trace/include/esp_sysview_trace.h", "provenance": "stackv2-0030.json.gz:14540", "repo_name": "igrr/esp-idf", "revision_date": "2022-05-25T23:10:04", "revision_id": "4823bd824d4c5ccd050a061c3241da26cf768e47", "snapshot_id": "75455577353a3ca82a7e9009ab9d00b5687a1388", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/igrr/esp-idf/4823bd824d4c5ccd050a061c3241da26cf768e47/components/app_trace/include/esp_sysview_trace.h", "visit_date": "2022-06-10T08:00:11.179173" }
stackv2
/* * SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ESP_SYSVIEW_TRACE_H_ #define ESP_SYSVIEW_TRACE_H_ #ifdef __cplusplus extern "C" { #endif #include <stdarg.h> #include "esp_err.h" #include "SEGGER_RTT.h" // SEGGER_RTT_ESP_Flush #include "esp_app_trace_util.h" // ESP_APPTRACE_TMO_INFINITE /** * @brief Flushes remaining data in SystemView trace buffer to host. * * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. * * @return ESP_OK. */ static inline esp_err_t esp_sysview_flush(uint32_t tmo) { SEGGER_RTT_ESP_Flush(0, tmo); return ESP_OK; } /** * @brief vprintf-like function to sent log messages to the host. * * @param format Address of format string. * @param args List of arguments. * * @return Number of bytes written. */ int esp_sysview_vprintf(const char * format, va_list args); /** * @brief Starts SystemView heap tracing. * * @param tmo Timeout (in us) to wait for the host to be connected. Use -1 to wait forever. * * @return ESP_OK on success, ESP_ERR_TIMEOUT if operation has been timed out. */ esp_err_t esp_sysview_heap_trace_start(uint32_t tmo); /** * @brief Stops SystemView heap tracing. * * @return ESP_OK. */ esp_err_t esp_sysview_heap_trace_stop(void); /** * @brief Sends heap allocation event to the host. * * @param addr Address of allocated block. * @param size Size of allocated block. * @param callers Pointer to array with callstack addresses. * Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. */ void esp_sysview_heap_trace_alloc(void *addr, uint32_t size, const void *callers); /** * @brief Sends heap de-allocation event to the host. * * @param addr Address of de-allocated block. * @param callers Pointer to array with callstack addresses. * Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. */ void esp_sysview_heap_trace_free(void *addr, const void *callers); #ifdef __cplusplus } #endif #endif //ESP_SYSVIEW_TRACE_H_
2.046875
2
2024-11-18T18:40:00.534158+00:00
2021-10-05T15:03:54
db1b7384fa7861c94ebbdf2a0ea44cb375b32b6e
{ "blob_id": "db1b7384fa7861c94ebbdf2a0ea44cb375b32b6e", "branch_name": "refs/heads/master", "committer_date": "2021-10-05T15:03:54", "content_id": "a73c5b915bf3139ff78268344fcf7fec7c74163c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1d0e2b29fc7f3197ac2e83de56fc695d2635f664", "extension": "c", "filename": "quick_sort.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1252, "license": "Apache-2.0", "license_type": "permissive", "path": "/sorts/quick_sort.c", "provenance": "stackv2-0030.json.gz:14796", "repo_name": "kayarre/C", "revision_date": "2021-10-05T15:03:54", "revision_id": "96aa780466acc4805631220d7c8b4a34893c3c04", "snapshot_id": "5028a363abbe79f7f2864cb9f60d18c9cd6ac498", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kayarre/C/96aa780466acc4805631220d7c8b4a34893c3c04/sorts/quick_sort.c", "visit_date": "2023-08-05T01:45:38.647924" }
stackv2
#include <assert.h> #include <stdlib.h> #include <time.h> void swap(int *arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int partition(int *arr, int low, int high) { int pivot = arr[low]; while (low < high) { while (low < high && arr[high] >= pivot) { high--; } while (low < high && arr[low] <= pivot) { low++; } if (low < high) { swap(arr, low, high); low++; high--; } } arr[low] = pivot; return low; } void quickSort(int *arr, int low, int high) { if (low < high) { int pivotIndex = partition(arr, low, high); quickSort(arr, low, pivotIndex - 1); quickSort(arr, pivotIndex + 1, high); } } void test() { const int size = 10; int *arr = (int *) calloc(size, sizeof(int)); /* generate size random numbers from 0 to 100 */ for (int i = 0; i < size; i++) { arr[i] = rand() % 100; } quickSort(arr, 0, size - 1); for (int i = 0; i < size - 1; ++i) { assert(arr[i] <= arr[i + 1]); } free(arr); } int main() { /* initial random number generator */ srand(time(NULL)); test(); return 0; }
3.28125
3
2024-11-18T18:40:00.611132+00:00
2020-11-11T00:03:03
acd0d5c8d5b2a3965ecde9ec193c6b31b8b6d82d
{ "blob_id": "acd0d5c8d5b2a3965ecde9ec193c6b31b8b6d82d", "branch_name": "refs/heads/master", "committer_date": "2020-11-11T00:03:03", "content_id": "7e4f206eb3f368894cef92e059c9aa5ff4575d6a", "detected_licenses": [ "MIT" ], "directory_id": "878e856d2164cb65216fb3566d1b7b5c11bef0ae", "extension": "c", "filename": "gc.c", "fork_events_count": 33, "gha_created_at": "2017-03-23T20:03:34", "gha_event_created_at": "2020-11-02T16:20:42", "gha_language": "Coq", "gha_license_id": "MIT", "github_id": 85992369, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11707, "license": "MIT", "license_type": "permissive", "path": "/examples/containers/certicoq/gc.c", "provenance": "stackv2-0030.json.gz:14924", "repo_name": "antalsz/hs-to-coq", "revision_date": "2020-11-11T00:03:03", "revision_id": "cd62a35fff22cb6022a8935581746df658264f0f", "snapshot_id": "bb7dac5d47b11333d4b17cb20a24d6e3c8386e82", "src_encoding": "UTF-8", "star_events_count": 301, "url": "https://raw.githubusercontent.com/antalsz/hs-to-coq/cd62a35fff22cb6022a8935581746df658264f0f/examples/containers/certicoq/gc.c", "visit_date": "2021-01-23T02:31:29.451934" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include "config.h" #include "values.h" #include "gc.h" /* A "space" describes one generation of the generational collector. */ struct space { value *start, *next, *limit; }; /* Either start==NULL (meaning that this generation has not yet been created), or start <= next <= limit. The words in start..next are allocated and initialized, and the words from next..limit are available to allocate. */ #define MAX_SPACES 12 /* how many generations */ #ifndef RATIO #define RATIO 2 /* size of generation i+1 / size of generation i */ /* Using RATIO=2 is faster than larger ratios, empirically */ #endif #ifndef NURSERY_SIZE #define NURSERY_SIZE (1<<16) #endif /* The size of generation 0 (the "nursery") should approximately match the size of the level-2 cache of the machine, according to: Cache Performance of Fast-Allocating Programs, by Marcelo J. R. Goncalves and Andrew W. Appel. 7th Int'l Conf. on Functional Programming and Computer Architecture, pp. 293-305, ACM Press, June 1995. We estimate this as 256 kilobytes (which is the size of the Intel Core i7 per-core L2 cache). http://www.tomshardware.com/reviews/Intel-i7-nehalem-cpu,2041-10.html https://en.wikipedia.org/wiki/Nehalem_(microarchitecture) Empirical measurements show that 64k works well (or anything in the range from 32k to 128k). */ #ifndef DEPTH #define DEPTH 0 /* how much depth-first search to do */ #endif struct heap { /* A heap is an array of generations; generation 0 must be already-created */ struct space spaces[MAX_SPACES]; }; #ifdef DEBUG int in_heap(struct heap *h, value v) { int i; for (i=0; i<MAX_SPACES; i++) if (h->spaces[i].start != NULL) if (h->spaces[i].start <= (value*)v && (value *)v <= h->spaces[i].limit) return 1; return 0; } void printtree(FILE *f, struct heap *h, value v) { if(Is_block(v)) if (in_heap(h,v)) { header_t hd = Field(v,-1); int sz = Wosize_hd(hd); int i; fprintf(f,"%d(", Tag_hd(hd)); for(i=0; i<sz-1; i++) { printtree(f,h,Field(v,i)); fprintf(f,","); } if (i<sz) printtree(f,h,Field(v,i)); fprintf(f,")"); } else { fprintf(f,"%8x",v); } else fprintf(f,"%d",v>>1); } void printroots (FILE *f, struct heap *h, fun_info fi, /* which args contain live roots? */ struct thread_info *ti) /* where's the args array? */ { value *args; int n; uintnat i, *roots; roots = fi+2; n = fi[1]; args = ti->args; for(i = 0; i < n; i++) { fprintf(f,"%d[%8x]:",roots[i],args[roots[i]]); printtree(f, h, args[roots[i]]); fprintf(f,"\n"); } fprintf(f,"\n"); } #endif void abort_with(char *s) { fprintf(stderr, s); exit(1); } #define Is_from(from_start, from_limit, v) \ (from_start <= (value*)(v) && (value*)(v) < from_limit) /* Assuming v is a pointer (Is_block(v)), tests whether v points somewhere into the "from-space" defined by from_start and from_limit */ void forward (value *from_start, /* beginning of from-space */ value *from_limit, /* end of from-space */ value **next, /* next available spot in to-space */ value *p, /* location of word to forward */ int depth) /* how much depth-first search to do */ /* What it does: If *p is a pointer, AND it points into from-space, then make *p point at the corresponding object in to-space. If such an object did not already exist, create it at address *next (and increment *next by the size of the object). If *p is not a pointer into from-space, then leave it alone. The depth parameter may be set to 0 for ordinary breadth-first collection. Setting depth to a small integer (perhaps 10) may improve the cache locality of the copied graph. */ { value v = *p; if(Is_block(v)) { if(Is_from(from_start, from_limit, v)) { header_t hd = Hd_val(v); if(hd == 0) { /* already forwarded */ *p = Field(v,0); } else { int i; int sz; value *new; sz = Wosize_hd(hd); new = *next+1; *next = new+sz; for(i = -1; i < sz; i++) { Field(new, i) = Field(v, i); } Hd_val(v) = 0; Field(v, 0) = (value)new; *p = (value)new; if (depth>0) for (i=0; i<sz; i++) forward(from_start, from_limit, next, &Field(new,i), depth-1); } } } } void forward_roots (value *from_start, /* beginning of from-space */ value *from_limit, /* end of from-space */ value **next, /* next available spot in to-space */ fun_info fi, /* which args contain live roots? */ struct thread_info *ti) /* where's the args array? */ /* Forward each live root in the args array */ { value *args; int n; uintnat i; const uintnat *roots = fi+2; n = fi[1]; args = ti->args; for(i = 0; i < n; i++) { assert (roots[i] < MAX_ARGS); forward(from_start, from_limit, next, args+roots[i], DEPTH); } } #define No_scan_tag 251 #define No_scan(t) ((t) >= No_scan_tag) void do_scan(value *from_start, /* beginning of from-space */ value *from_limit, /* end of from-space */ value *scan, /* start of unforwarded part of to-space */ value **next) /* next available spot in to-space */ /* Forward each word in the to-space between scan and *next. In the process, next may increase, so keep doing it until scan catches up. Leave alone: header words, and "no_scan" (nonpointer) data. */ { value *s; s = scan; while(s < *next) { header_t hd = *s; mlsize_t sz = Wosize_hd(hd); int tag = Tag_hd(hd); if (!No_scan(tag)) { intnat j; for(j = 1; j <= sz; j++) { forward (from_start, from_limit, next, &Field(s, j), DEPTH); } } s += 1+sz; } } void do_generation (struct space *from, /* descriptor of from-space */ struct space *to, /* descriptor of to-space */ fun_info fi, /* which args contain live roots? */ struct thread_info *ti) /* where's the args array? */ /* Copy the live objects out of the "from" space, into the "to" space, using fi and ti to determine the roots of liveness. */ { value *p = to->next; assert(from->next-from->start <= to->limit-to->next); forward_roots(from->start, from->limit, &to->next, fi, ti); do_scan(from->start, from->limit, p, &to->next); if(0) fprintf(stderr,"%5.3f%% occupancy\n", (to->next-p)/(double)(from->next-from->start)); from->next=from->start; } #if 0 /* This "gensize" function is only useful if the desired ratio is >2, but empirical measurements show that ratio=2 is better than ratio>2. */ uintnat gensize(uintnat words) /* words is size of one generation; calculate size of the next generation */ { uintnat maxint = 0u-1u; uintnat n,d; /* The next few lines calculate a value "n" that's at least words*2, preferably words*RATIO, and without overflowing the size of an unsigned integer. */ /* minor bug: this assumes sizeof(uintnat)==sizeof(void*)==sizeof(value) */ if (words > maxint/(2*sizeof(value))) abort_with("Next generation would be too big for address space\n"); d = maxint/RATIO; if (words<d) d=words; n = d*RATIO; assert (n >= 2*words); return n; } #endif void create_space(struct space *s, /* which generation to create */ uintnat n) /* size of the generation */ /* malloc an array of words for generation "s", and set s->start and s->next to the beginning, and s->limit to the end. */ { value *p; p = (value *)malloc(n * sizeof(value)); if (p==NULL) abort_with ("Could not create the next generation\n"); /* fprintf(stderr, "Created a generation of %d words\n", n); */ s->start=p; s->next=p; s->limit = p+n; } struct heap *create_heap() /* To create a heap, first malloc the array of space-descriptors, then create only generation 0. */ { int i; struct heap *h = (struct heap *)malloc(sizeof (struct heap)); if (h==NULL) abort_with("Could not create the heap\n"); create_space(h->spaces+0, NURSERY_SIZE); for(i=1; i<MAX_SPACES; i++) { h->spaces[i].start = NULL; h->spaces[i].next = NULL; h->spaces[i].limit = NULL; } return h; } struct thread_info *make_tinfo(void) { struct heap *h; struct thread_info *tinfo; h = create_heap(); tinfo = (struct thread_info *)malloc(sizeof(struct thread_info)); if (!tinfo) { fprintf(stderr, "Could not allocate thread_info struct\n"); exit(1); } tinfo->heap=h; tinfo->alloc=h->spaces[0].start; tinfo->limit=h->spaces[0].limit; return tinfo; } void resume(fun_info fi, struct thread_info *ti) /* When the garbage collector is all done, it does not "return" to the mutator; instead, it uses this function (which does not return) to resume the mutator by invoking the continuation, fi->fun. But first, "resume" informs the mutator of the new values for the alloc and limit pointers. */ { struct heap *h = ti->heap; value *lo, *hi; uintnat num_allocs = fi[0]; assert (h); lo = h->spaces[0].start; hi = h->spaces[0].limit; if (hi-lo < num_allocs) abort_with ("Nursery is too small for function's num_allocs\n"); ti->alloc = lo; ti->limit = hi; } void garbage_collect(fun_info fi, struct thread_info *ti) /* See the header file for the interface-spec of this function. */ { struct heap *h = ti->heap; if (h==NULL) { /* If the heap has not yet been initialized, create it and resume */ h = create_heap(); ti->heap = h; resume(fi,ti); return; } else { int i; assert (h->spaces[0].limit == ti->limit); h->spaces[0].next = ti->alloc; /* this line is probably unnecessary */ for (i=0; i<MAX_SPACES-1; i++) { /* Starting with the youngest generation, collect each generation into the next-older generation. Usually, when doing that, there will be enough space left in the next-older generation so that we can break the loop by resuming the mutator. */ /* If the next generation does not yet exist, create it */ if (h->spaces[i+1].start==NULL) { int w = h->spaces[i].limit-h->spaces[i].start; create_space(h->spaces+(i+1), RATIO*w); } /* Copy all the objects in generation i, into generation i+1 */ if(0) fprintf(stderr, "Generation %d: ", i); do_generation(h->spaces+i, h->spaces+(i+1), fi, ti); /* If there's enough space in gen i+1 to guarantee that the NEXT collection into i+1 will succeed, we can stop here */ if (h->spaces[i].limit - h->spaces[i].start <= h->spaces[i+1].limit - h->spaces[i+1].next) { resume(fi,ti); return; } } /* If we get to i==MAX_SPACES, that's bad news */ abort_with("Ran out of generations\n"); } /* Can't reach this point */ assert(0); } /* REMARK. The generation-management policy in the garbage_collect function has a potential flaw. Whenever a record is copied, it is promoted to a higher generation. This is generally a good idea. But there is a bounded number of generations. A useful improvement would be: when it's time to collect the oldest generation (and we can tell it's the oldest, at least because create_space() fails), do some reorganization instead of failing. */ void reset_heap (struct heap *h) { fprintf(stderr, "Debug: in reset_heap\n"); int i; for (i=0; i<MAX_SPACES; i++) h->spaces[i].next = h->spaces[i].start; } void free_heap (struct heap *h) { fprintf(stderr, "Debug: in free_heap\n"); int i; for (i=0; i<MAX_SPACES; i++) { value *p = h->spaces[i].start; if (p!=NULL) free(p); } free (h); }
2.5625
3
2024-11-18T18:40:00.980258+00:00
2019-05-30T03:19:42
e4af18f0a86ed6bba524ca5a261ee0cbec39dd25
{ "blob_id": "e4af18f0a86ed6bba524ca5a261ee0cbec39dd25", "branch_name": "refs/heads/master", "committer_date": "2019-05-30T03:19:42", "content_id": "aa9fd8d71e4a3a7034c854ce14e495114816438f", "detected_licenses": [ "Unlicense" ], "directory_id": "b058c201472df07839de7ea90cf52ed18d938f44", "extension": "c", "filename": "Main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1260, "license": "Unlicense", "license_type": "permissive", "path": "/Source/Main.c", "provenance": "stackv2-0030.json.gz:15052", "repo_name": "zer0warm/Hetris", "revision_date": "2019-05-30T03:19:42", "revision_id": "9d90c07d780dccf811f22457a4a929599264d53d", "snapshot_id": "377c115410dbd3d646287d4b0f0edd894aaa1d01", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zer0warm/Hetris/9d90c07d780dccf811f22457a4a929599264d53d/Source/Main.c", "visit_date": "2022-01-07T20:48:28.455887" }
stackv2
/* * File: Main.c * Author: Hieu Do * Description: Contains the main() function. */ #include <ncurses.h> #include "GamePlay.h" #include "Menu.h" void initGame (void); void finnishAndQuit (void); int main (void) { initGame (); finnishAndQuit (); return 0; } void initGame (void) { initscr (); int maxWidth, maxHeight; getmaxyx (stdscr, maxHeight, maxWidth); if (maxWidth != MIN_SCREEN_WIDTH || maxHeight != MIN_SCREEN_HEIGHT) { endwin (); fprintf (stderr, "Current screen width = %i\n", maxWidth); fprintf (stderr, "Current screen height = %i\n", maxHeight); fprintf (stderr, "Require exactly (W x H) = (%i x %i) to operate\n", MIN_SCREEN_WIDTH, MIN_SCREEN_HEIGHT); exit (EXIT_FAILURE); } else { endwin (); runMenu (); } } void finnishAndQuit () { initscr (); cbreak (); noecho (); WINDOW *finnish = newwin (0, 0, 0, 0); int height, width; getmaxyx (finnish, height, width); height /= 2; width = width / 2 - 3; mvwprintw (finnish, height, width, "Good bye!"); wrefresh (finnish); halfdelay (6); wgetch (finnish); werase (finnish); delwin (finnish); endwin (); }
2.71875
3
2024-11-18T18:40:03.327647+00:00
2016-02-09T22:50:58
0dbe35fc3bd11b88500ef02e7ecb15e30745683a
{ "blob_id": "0dbe35fc3bd11b88500ef02e7ecb15e30745683a", "branch_name": "refs/heads/master", "committer_date": "2016-02-09T22:50:58", "content_id": "02365142c5c02ef8d6aa76eb3c290c00dada4368", "detected_licenses": [ "MIT" ], "directory_id": "f6059152eb62cfecaef8d1b6b4a71e85c97bb81d", "extension": "h", "filename": "shell.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50059335, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2138, "license": "MIT", "license_type": "permissive", "path": "/shell.h", "provenance": "stackv2-0030.json.gz:15181", "repo_name": "LeNiglo/42sh", "revision_date": "2016-02-09T22:50:58", "revision_id": "1f11de37366076c3dc68465b5e7acd16d68db234", "snapshot_id": "f75cb169ba3fa35a269724ed9c99987b2b500636", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LeNiglo/42sh/1f11de37366076c3dc68465b5e7acd16d68db234/shell.h", "visit_date": "2021-01-10T16:50:21.710437" }
stackv2
/* ** shell.h for 42SH in /afs/epitech.net/users/epitech_2017/lefran_g/public/42SH ** ** Made by guillaume lefrant ** Login <[email protected]> ** ** Started on Thu Apr 4 11:20:02 2013 guillaume lefrant ** Last update Wed May 22 15:17:01 2013 guillaume lefrant */ #ifndef SHELL_H_ # define SHELL_H_ # include <stdio.h> # include <stdlib.h> # include <unistd.h> # include <string.h> # include <sys/stat.h> # include <sys/wait.h> # include <sys/types.h> # include <fcntl.h> # include "sources/parseur/parseur.h" # include "sources/pipes/pipe.h" # include "sources/pipes/red.h" # define CHAR_READ (42000) typedef struct s_shell { char **env; int status; } t_shell; int my_strncmp(char *, char *, int); int my_strcmp(char *, char *); char *my_strcat(char *, char *); void aff_prompt(char *, char **); void my_putchar(char); void my_putstr(char *); void my_put2str(char **); int my_strlen(char *); /* ** main.c */ char *check_in_path(char **, char *); int check_builtins(char **cmd, t_shell *sh); int wait_instructions(t_param exe, char **envp); t_shell *ini_sh(char **envp); /* ** modif_setenv.c */ char **add_elem_envp(char **envp, char *new); /* ** my_str_word.c */ char **my_str_word(char *str, char delim, int start, int addmot); char *remp_str(char *str, char delim, int *pos, int addmot); int count_word_str(char *str, char delim); /* ** env_cd.c */ int do_setenv(char **foo, t_shell *sh); int do_unsetenv(char **foo, char **envp); int do_env(char **envp); int do_cd(char **foo, char **envp); char **help_do_cd(char **foo, char **envp); /* ** change_env.c */ char **change_env(char *add, char **envp); char *creat_new_adress(char *str1, char *str2); char *supr_adress(char *str1); char *add_adress(char *str1, char *str2); int find_pwd(char **envp); /* ** my_strtok.c */ char **my_strtok(char *, char, int); int nb_of_words_strtok(char *str, char delim); void complete_box_strtok(char *box, char *str, int size, char delim); char **my_strtok(char *str, char delim, int start); /* ** get_next_line.c */ char *get_next_line(int); #endif
2.125
2
2024-11-18T18:40:03.523067+00:00
2017-07-02T21:42:07
7a15568639e20a20793144198420b3e821542209
{ "blob_id": "7a15568639e20a20793144198420b3e821542209", "branch_name": "refs/heads/master", "committer_date": "2017-07-02T21:42:07", "content_id": "eef0e994cc331e92159a21fbd1a3c01f0af19a06", "detected_licenses": [ "MIT" ], "directory_id": "99fe247d07120864f14f8a984196418db98d3404", "extension": "h", "filename": "Globals.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 96050202, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1836, "license": "MIT", "license_type": "permissive", "path": "/Globals.h", "provenance": "stackv2-0030.json.gz:15437", "repo_name": "DavidOtano/WLProxy", "revision_date": "2017-07-02T21:42:07", "revision_id": "dcfd42c7a494d3c1fe60c6a97feb19cfffb47a4a", "snapshot_id": "7fa2c6fc6b4a61e9372c674e6e91b8d4d37437cb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DavidOtano/WLProxy/dcfd42c7a494d3c1fe60c6a97feb19cfffb47a4a/Globals.h", "visit_date": "2020-12-03T00:37:38.380474" }
stackv2
#ifndef __GLOBALS_H__ #define __GLOBALS_H__ #include <WinSock2.h> #include <Windows.h> /* you shouldn't have to touch the members of this structure the proxy server should handle everything for you, just pass the ptr to the provided functions */ typedef struct TAG_CLIENT { HWND hMain; SOCKET clientsock; SOCKET serversock; char startpoint_addr[64]; char endpoint_addr[64]; char server_name[64]; char char_name[16]; char* in_data; DWORD in_length; char* out_data; DWORD out_length; char* in_artificial; DWORD in_artificial_length; char* out_artificial; DWORD out_artificial_length; DWORD char_id; } CLIENT, *LPCLIENT; typedef struct TAG_PROCEDURES { //[[[[[ For the Plugin to call ]]]]] // Print to the log void (*LogPrintLine)(COLORREF, const char*); // Print an error to the log void (*LogPrintError)(const char*); // Fake packet sent from server to client void (*ArtificialServerToClient)(LPCLIENT, const char*, WORD); // Fake packet sent from client to server void (*ArtificialClientToServer)(LPCLIENT, const char*, WORD); //[[[[[ Callbacks for the EXE to call ]]]]] // On Connect (both startpoint/endpoint) void (*OnConnect)(LPCLIENT); // On Character Info (id/name) void (*OnCharacterInfo)(LPCLIENT); // On Send -> Server void (*OnSendToServer)(LPCLIENT, char*, WORD, bool*); // On Send -> Client void (*OnSendToClient)(LPCLIENT, char*, WORD, bool*); // On Login Complete void (*OnClientReadyState)(LPCLIENT); // On Disconnect void (*OnDisconnect)(LPCLIENT); // On Plugin Free void (*OnFree)(void); } PROCEDURES, *LPPROCEDURES; typedef bool (__cdecl *LPINITIALIZE)(LPPROCEDURES, char*); #define _xor(a, b) { \ int ___x; \ for(___x = 0; ___x < b; ++___x) { \ a[___x] = (BYTE)(a[___x] ^ 0xAD); \ } \ } #endif
2.25
2
2024-11-18T18:40:03.753245+00:00
2023-04-12T15:42:13
30ce2c22bec06616ea4d8ceb453c06c90caf4cfe
{ "blob_id": "30ce2c22bec06616ea4d8ceb453c06c90caf4cfe", "branch_name": "refs/heads/master", "committer_date": "2023-04-12T15:42:13", "content_id": "f50ca71ac02d96285ebcdcbe953f52be0f30a7ad", "detected_licenses": [ "MIT" ], "directory_id": "7271ede736cda055f3cee2da3b8c1395a404f9dc", "extension": "h", "filename": "ros.h", "fork_events_count": 3, "gha_created_at": "2019-05-09T07:04:05", "gha_event_created_at": "2023-04-12T15:40:59", "gha_language": "C", "gha_license_id": "MIT", "github_id": 185744771, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2090, "license": "MIT", "license_type": "permissive", "path": "/ros.h", "provenance": "stackv2-0030.json.gz:15693", "repo_name": "LeeReindeer/ROS", "revision_date": "2023-04-12T15:42:13", "revision_id": "a562d9c7742b6b058233f4ad6dc83f0baa96228f", "snapshot_id": "c68adfdfd39bec12c1493962e37f2a2f1c1591a4", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/LeeReindeer/ROS/a562d9c7742b6b058233f4ad6dc83f0baa96228f/ros.h", "visit_date": "2023-04-29T21:11:37.166234" }
stackv2
#ifndef __ROS_H__ #define __ROS_H__ #include "ros_port.h" #include "ros_timer.h" #ifdef __cplusplus extern "C" { #endif typedef enum { TASK_READY = 0, // TASK_RUNNING, TASK_BLOCKED, TASK_TERMINATED } Task_Status; /** * Task implementation function: * void task1(void *param) { * for(;;) { * // task code here * } * // should never return, once return the task will be deleted from the * ready list * } */ typedef void (*task_func)(); /** * Define the task control block using doubly linked list * while there is always a idle task in the list with priority 255. */ typedef struct ros_tcb { void *sp; Task_Status status; uint8_t priority; // 0~255 task_func task_entry; // ROS_TCB *prev_tcb; //need doubly-list? struct ros_tcb *next_tcb; } ROS_TCB; typedef uint8_t stack_t; #define STACK_POINT(A, SIZE) (&A[SIZE - 1]) // #define TRUE 1 // #define FALSE 0 #define MIN_TASK_PRIORITY 255 #define MAX_TASK_PRIORITY 0 /* Error codes */ typedef uint8_t status_t; #define ROS_OK 0U #define ROS_ERROR 1U #define ROS_ERR_PARAM 200U #define ROS_ERR_CONTEXT 201U #define ROS_ERR_TIMER 201U /*OS core functions: scheduler, context init, context switch and system tick*/ bool ros_init(); ROS_TCB *ros_current_tcb(); status_t ros_create_task(ROS_TCB *tcb, task_func task, uint8_t priority, stack_t *stack, int stack_size); void ros_schedule(); // list operations void ros_tcb_enqueue(ROS_TCB *tcb); ROS_TCB *ros_tcb_dequeue(uint8_t lowest_priority); // call the following three functions from ISR void ros_int_enter(); // define in ros_timer.c extern void ros_sys_tick(); void ros_int_exit(); /* Global values and functions */ extern bool ROS_STARTED; extern ROS_TCB *tcb_ready_list; // define in ros_port.c for porting extern void ros_init_timer(); extern void ros_idle_task(); extern void ros_task_context_init(ROS_TCB *tcb_ptr, task_func task_f, void *stack_top); extern void ros_switch_context(ROS_TCB *old_tcb, ROS_TCB *new_tcb); #ifdef __cplusplus } #endif #endif //__ROS_H__
2.375
2
2024-11-18T18:41:30.753622+00:00
2015-12-28T05:00:55
6bd1d17c41f9dcbee2a52f8384aabb68139c1efa
{ "blob_id": "6bd1d17c41f9dcbee2a52f8384aabb68139c1efa", "branch_name": "refs/heads/master", "committer_date": "2015-12-28T05:00:55", "content_id": "acb14fd88e5bfe4798e4f515b11227e5681b77ff", "detected_licenses": [ "MIT" ], "directory_id": "906e60284002aadcd44d85e1b08c061f4debc4fd", "extension": "c", "filename": "trainGMM.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43724667, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5972, "license": "MIT", "license_type": "permissive", "path": "/matlab/trainGMM.c", "provenance": "stackv2-0030.json.gz:17498", "repo_name": "snitish/libgmm", "revision_date": "2015-12-28T05:00:55", "revision_id": "0e987ce3de4770f2b4853d0ec111ee844ea299dc", "snapshot_id": "90f7e2d5c90cbd6c871592888d7ddc80a69e1706", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/snitish/libgmm/0e987ce3de4770f2b4853d0ec111ee844ea299dc/matlab/trainGMM.c", "visit_date": "2021-01-10T03:34:56.901092" }
stackv2
/* * trainGMM.c * * MEX wrapper for libgmm * * Usage: * [gmm] = trainGMM(X, k, varargin) */ #include "mex.h" #include "../gmm.h" #include <stdlib.h> #include <string.h> /* The gateway function */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* -------------------------------------------------- Validate input arguments */ // Make sure there are at least two input arguments if (nrhs < 2) { mexErrMsgIdAndTxt("trainGMM:nrhs", "At least two inputs required."); } // Make sure the first argument is a double matrix if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxGetNumberOfDimensions(prhs[0]) > 2) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "Training data (X) must be a 2D matrix of doubles."); } // Make sure the second argument is a scalar if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || mxGetNumberOfElements(prhs[1]) != 1) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "Number of components (k) must be a scalar."); } /* ------------------------------------------------- Validate output arguments */ // Make sure there is at most one output argument if (nlhs > 1) { mexErrMsgIdAndTxt("trainGMM:nlhs", "The function returns only one output variable."); } /* ------------------------------------------------------- Get input arguments */ double *X = mxGetPr(prhs[0]); int M = (int) (mxGetScalar(prhs[1]) + 0.5); int N = mxGetM(prhs[0]); int D = mxGetN(prhs[0]); // Get optional arguments double tol = 0.000001; double reg = 0.000001; int max_iter = 1000; char init_method[20]; strcpy(init_method, "random"); char cov_type[20]; strcpy(cov_type, "diagonal"); char error_msg[200]; if (nrhs > 2) { int i_rhs = 2; while (i_rhs < nrhs) { // Make sure prhs[i_rhs] is a string if (!mxIsChar(prhs[i_rhs])) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "Optional argument name must be a string."); } // Get argument name char arg_name[50]; mxGetString(prhs[i_rhs], arg_name, (mwSize) 50); // Make sure value argument exists if (i_rhs + 1 >= nrhs) { sprintf(error_msg, "Expecting value for parameter '%s'", arg_name); mexErrMsgIdAndTxt("trainGMM:argumentMissing", error_msg); } // Parse argument name and get value if (strcmp(arg_name, "RegularizationValue") == 0) { // Make sure argument value is a scalar if( !mxIsDouble(prhs[i_rhs + 1]) || mxIsComplex(prhs[i_rhs + 1]) || mxGetNumberOfElements(prhs[i_rhs + 1]) != 1) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "RegularizationValue must be a scalar."); } reg = mxGetScalar(prhs[i_rhs+1]); } else if (strcmp(arg_name, "ConvergenceTol") == 0) { // Make sure argument value is a scalar if( !mxIsDouble(prhs[i_rhs + 1]) || mxIsComplex(prhs[i_rhs + 1]) || mxGetNumberOfElements(prhs[i_rhs + 1]) != 1) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "ConvergenceTol must be a scalar."); } tol = mxGetScalar(prhs[i_rhs+1]); } else if (strcmp(arg_name, "MaxIter") == 0) { // Make sure argument value is a scalar if( !mxIsDouble(prhs[i_rhs + 1]) || mxIsComplex(prhs[i_rhs + 1]) || mxGetNumberOfElements(prhs[i_rhs + 1]) != 1) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "MaxIter must be a scalar."); } max_iter = mxGetScalar(prhs[i_rhs+1]); } else if (strcmp(arg_name, "InitMethod") == 0) { // Make sure argument value is a string if( !mxIsChar(prhs[i_rhs + 1])) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "InitMethod must be a string."); } mxGetString(prhs[i_rhs+1], init_method, (mwSize) 20); } else if (strcmp(arg_name, "CovType") == 0) { // Make sure argument value is a string if( !mxIsChar(prhs[i_rhs + 1])) { mexErrMsgIdAndTxt("trainGMM:invalidArgument", "CovType must be a string."); } mxGetString(prhs[i_rhs+1], cov_type, (mwSize) 20); } else { sprintf(error_msg, "Unknown parameter '%s'", arg_name); mexErrMsgIdAndTxt("trainGMM:invalidArgument", error_msg); } i_rhs += 2; } } /* ------------------------------------------------------------ Train the SGMM */ // Train the GMM GMM *gmm = gmm_new(M, D, cov_type); gmm_set_convergence_tol(gmm, tol); gmm_set_regularization_value(gmm, reg); gmm_set_max_iter(gmm, max_iter); gmm_set_initialization_method(gmm, init_method); gmm_fit(gmm, X, N); /* ------------------------------------------------ Build output GMM structure */ //Initialize structure with three fields const mwSize dims[2] = {1, 1}; const char *field_names[] = {"numComponents", "featureLength", "weights", "means", "covars"}; plhs[0] = mxCreateStructArray(2, dims, 5, field_names); // Add "numComponents" field to structure mxArray *mx_numComponents = mxCreateDoubleScalar(M); mxSetField(plhs[0], 0, "numComponents", mx_numComponents); // Add "featureLength" field to structure mxArray *mx_featureLength = mxCreateDoubleScalar(D); mxSetField(plhs[0], 0, "featureLength", mx_featureLength); // Add "weights" field to structure mxArray *mx_weights = mxCreateDoubleMatrix(M, 1, mxREAL); double *p = mxGetPr(mx_weights); memcpy(p, gmm->weights, M*sizeof(double)); mxSetField(plhs[0], 0, "weights", mx_weights); // Add "means" field to structure mxArray *mx_means = mxCreateDoubleMatrix(M, D, mxREAL); p = mxGetPr(mx_means); for (int k=0; k<M; k++) for (int i=0; i<D; i++) p[k+i*M] = gmm->means[k][i]; mxSetField(plhs[0], 0, "means", mx_means); // Add "covars" field to structure mxArray *mx_covars = mxCreateDoubleMatrix(M, 1, mxREAL); p = mxGetPr(mx_covars); int cov_len = (gmm->cov_type == SPHERICAL)? 1 : D; for (int k=0; k<M; k++) for (int i=0; i<cov_len; i++) p[k+i*M] = gmm->covars[k][i]; mxSetField(plhs[0], 0, "covars", mx_covars); /* ------------------------------------------------------------------- Cleanup */ // Free gmm gmm_free(gmm); }
2.40625
2
2024-11-18T18:41:30.830250+00:00
2017-01-07T10:18:33
47aa6a328ff0431e6843ba6ab4699e83e9d72805
{ "blob_id": "47aa6a328ff0431e6843ba6ab4699e83e9d72805", "branch_name": "refs/heads/master", "committer_date": "2017-01-07T10:18:33", "content_id": "45a2861ea40a6fbe606af5fb0562e691e45661a0", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "9cbe932ed9330c509456066171c7c502b8aaa3f8", "extension": "h", "filename": "version_compat.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 76177790, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4509, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/BladeRF/nuand/version_compat.h", "provenance": "stackv2-0030.json.gz:17627", "repo_name": "Cloud-SDR/CloudSDR_BladeRF", "revision_date": "2017-01-07T10:18:33", "revision_id": "ec25b2508d160bb24f26541f39e807a1a3a19a55", "snapshot_id": "fdd94b728211be6723959fec3523e65ca5feae6c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Cloud-SDR/CloudSDR_BladeRF/ec25b2508d160bb24f26541f39e807a1a3a19a55/BladeRF/nuand/version_compat.h", "visit_date": "2021-01-12T09:31:09.880273" }
stackv2
/** * This file is part of the bladeRF project: * http://www.github.com/nuand/bladeRF * * Copyright (C) 2014 Nuand LLC * * This library is free software; 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 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef VERSION_COMPAT_H_ #define VERSION_COMPAT_H_ #include "libbladeRF.h" /** * Check if device's firmware version is sufficient for the current libbladeRF * version. If it's not, the user will need to use the bootloader to flash * a newer version. * * @param dev Device handle * * @return 0 if the FW version is sufficient for normal operation, * BLADERF_ERR_UPDATE_FW if a firmware update is required, * other BLADERF_ERR_* values on unexpected errors */ int version_check_fw(const struct bladerf *dev); /** * Get the minimum required firmware version * * @param[in] dev Device to check * @param[in] by_fpga If true, this function returns the minimum firmware * version required by the FPGA. This assumes that * the device structure's FPGA version info is * filled in. If false, this function retrieves * the minimum required firmware version required * by libbladeRF. * @param[out] version Written with firmware version. `describe` field * will be NULL. */ void version_required_fw(const struct bladerf *dev, struct bladerf_version *version, bool by_fpga); /** * Check if device's FPGA version is sufficient, considering the current * library version and device's firmware version. Also test if loaded FPGA * requires a more recent firmware version. * * @param dev Device handle * * @return 0 if the FPGA version is sufficient for normal operation, * BLADERF_ERR_UPDATE_FPGA if the firmware requires a newer FPGA, * BLADERF_ERR_UPDATE_FW if a firmware update is required to support * the currently loaded FPGA, * other BLADERF_ERR_* values on unexpected errors */ int version_check_fpga(const struct bladerf *dev); /** * Get the minimum required FPGA version, based upon a device's firmware version * * @param[in] dev Device to check * @param[out] version Written with FPGA version. `describe` field * will be NULL. */ void version_required_fpga(struct bladerf *dev, struct bladerf_version *version); /** * Test if two versions are equal. The "describe" field is not checked * * @return true if equal, false otherwise */ bool version_equal(const struct bladerf_version *v1, const struct bladerf_version *v2); /** * Check if version in the provided structure is greater or equal to * the version specified by the provided major, minor, and patch values * * @param version Version structure to check * @param major Minor version * @param minor Minor version * @param patch Patch version * * @return true for greater or equal, false otherwise */ bool version_greater_or_equal(const struct bladerf_version *version, unsigned int major, unsigned int minor, unsigned int patch); /** * Check if version in the provided structure is less than * the version specied by the provided major, minor, and patch values * * @param version Version structure to check * @param major Minor version * @param minor Minor version * @param patch Patch version * * @return true for less than, false otherwise */ bool version_less_than(const struct bladerf_version *version, unsigned int major, unsigned int minor, unsigned int patch); #endif
2.3125
2
2024-11-18T18:41:30.880099+00:00
2020-07-09T06:06:50
2a56fcfb170a1e33e1241b63661b8c0734a92440
{ "blob_id": "2a56fcfb170a1e33e1241b63661b8c0734a92440", "branch_name": "refs/heads/master", "committer_date": "2020-07-09T06:06:50", "content_id": "f50d58dc1653d9a4700a6783f00a4d8b50aad3ae", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "8938c049736335ff7364494e70c2e8558d5afe51", "extension": "c", "filename": "poski_LoadMatrix_HB_to_CSR.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 245469368, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16650, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/external/poski/src/LoadMatrix/poski_LoadMatrix_HB_to_CSR.c", "provenance": "stackv2-0030.json.gz:17756", "repo_name": "kulinseth/spmv", "revision_date": "2020-07-09T06:06:50", "revision_id": "31b160d7831a481569f8f3e34db85aba41c7a9cd", "snapshot_id": "3785545df27ec8c2894cfcc53e0b4166f2e1cae9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kulinseth/spmv/31b160d7831a481569f8f3e34db85aba41c7a9cd/external/poski/src/LoadMatrix/poski_LoadMatrix_HB_to_CSR.c", "visit_date": "2022-11-23T04:55:43.291508" }
stackv2
/** * @file src/LoadMatrix/poski_LoadMatrix_HB_to_CSR.c * @brief Read the pattern of a file stored in Harwell-Boeing format. * * This module implements the routines to read the pattern of a file stored in Harwell-Boeing format. * Modified from the HB format loader routines written by Sam Williams \<[email protected]\>. * * @attention Called by * @ref poski_LoadMatrixHandler.c * * Also, refer * @ref poski_LoadMatrix_common.c */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <poski/poski_loadmatcommon.h> #include <poski/poski_malloc.h> #include <poski/poski_print.h> //----------------------------------------------------------------------------------------- // Internal functions /** * @internal * @brief [library's internal use] Read the decode format. * * @param[in,out] FMT Format * @param[in,out] num * @param[in,out] type * @param[in,out] characters * @param[in,out] mantissa */ static void poski_decode_format(char *FMT, poski_index_t *num, char *type, poski_index_t *characters, poski_index_t *mantissa) { poski_index_t i; char c; *num = -1; *type = '?'; *characters = -1; *mantissa = -1; if (sscanf(FMT,"%d%c%d%c%d.%d)",&i,&c,num,type,characters,mantissa)==6) { } else if(sscanf(FMT,"(%d%c%d.%d)",num,type,characters,mantissa)==4) { } else if(sscanf(FMT,"(%d%c%d)",num,type,characters,mantissa)==3) { } else { poski_error("poski_decode_format", "unknown format- '%s'\n", FMT); assert(0); } } /** * @brief Read the pattern of a file stored in Harwell-Boeing format. * * @internal * @param[in] fname File to read * @param[in] MakeUnsymmetric * * @return A sparse matrix in CSR format if success, or an error message otherwise. */ poski_sparse_matrix_t *poski_LoadMatrix_HBF_to_CSR(char *fname, poski_index_t MakeUnsymmetric) { FILE *fp; char temp[100]; poski_index_t i,j; poski_index_t ZerosInFile=0; poski_printMessage(2, "Matrix information...\n"); fp = fopen(fname,"r"); if(fp==NULL) { poski_error("poski_LoadMatrix_HBF_to_CSR", "can not open the file %s\n", fname); assert(0); } else { poski_printMessage(3, "Read %s HBF file into CSR format\n",fname); } poski_sparse_matrix_t *SpA = poski_malloc(poski_sparse_matrix_t, 1, 0); poski_InitSparseMatrix(SpA); // load Header ----------------------- poski_printMessage(3,"=> Header information\n"); char L1[100];fgets(L1,100,fp); char TITLE[100];temp[71-00+1]='\0';sscanf(strncpy(temp,L1+00,71-00+1),"%s", TITLE ); // 00..71 = TITLE char KEY[100];temp[79-72+1]='\0';sscanf(strncpy(temp,L1+72,79-72+1),"%s", KEY ); // 72..79 = KEY poski_printMessage(3, "\tTITLE='%s' KEY='%s'\n",TITLE,KEY); char L2[100];fgets(L2,100,fp); poski_index_t TOTLines;temp[13-00+1]='\0'; sscanf(strncpy(temp,L2+00,13-00+1),"%d",&TOTLines); // 00..13 = Total number of lines excluding header poski_index_t PTRLines;temp[27-14+1]='\0'; sscanf(strncpy(temp,L2+14,27-14+1),"%d",&PTRLines); // 14..27 = Number of lines for pointers poski_index_t INDLines;temp[41-28+1]='\0'; sscanf(strncpy(temp,L2+28,41-28+1),"%d",&INDLines); // 28..41 = Number of lines for row (or variable) indices poski_index_t VALLines;temp[55-42+1]='\0'; sscanf(strncpy(temp,L2+42,55-42+1),"%d",&VALLines); // 42..55 = Number of lines for numerical values poski_index_t RHSLines;temp[69-56+1]='\0';if(sscanf(strncpy(temp,L2+56,69-56+1),"%d",&RHSLines)==0)RHSLines=0;// 56..69 = Number of lines for right-hand sides if(strlen(L2)<=57)RHSLines=0; poski_printMessage(3, "\tTOTLines='%d' PTRLines='%d' INDLines='%d' VALLines='%d' RHSLines='%d'\n",TOTLines,PTRLines,INDLines,VALLines,RHSLines); char L3[100];fgets(L3,100,fp); char MXTYPE[100];temp[02-00+1]='\0';sscanf(strncpy(temp,L3+00,02-00+1),"%s", MXTYPE ); // 00 - 02 = Matrix type (see below) {RCP,SUHNZR,AE} poski_index_t NROW;temp[27-14+1]='\0';sscanf(strncpy(temp,L3+14,27-14+1),"%d",&NROW ); // 14 - 27 = Number of rows (or variables) poski_index_t NCOL;temp[41-28+1]='\0';sscanf(strncpy(temp,L3+28,41-28+1),"%d",&NCOL ); // 28 - 41 = Number of columns (or elements) poski_index_t NNZERO;temp[55-42+1]='\0';sscanf(strncpy(temp,L3+42,55-42+1),"%d",&NNZERO ); // 42 - 55 = Number of row (or variable) indices poski_index_t NELTVL;temp[69-56+1]='\0';sscanf(strncpy(temp,L3+56,69-56+1),"%d",&NELTVL ); // 56 - 69 = Number of elemental matrix entries poski_printMessage(3, "\tMXTYPE='%s' NROW='%d' NCOL='%d' NNZERO='%d' NELTVL='%d'\n",MXTYPE,NROW,NCOL,NNZERO,NELTVL); if( (MXTYPE[1] == 'U') || (MXTYPE[1] == 'u') ){MXTYPE[1]='U';} else if( (MXTYPE[1] == 'R') || (MXTYPE[1] == 'r') ){MXTYPE[1]='R';} else if( (MXTYPE[1] == 'S') || (MXTYPE[1] == 's') ){MXTYPE[1]='S';} else {poski_error("poski_LoadMatrix_HBF_to_CSR", "unknown matrix type - %s\n",MXTYPE);assert(0);} if( (MXTYPE[0] == 'P') || (MXTYPE[0] == 'p') ){MXTYPE[0]='P';} else if( (MXTYPE[0] == 'R') || (MXTYPE[0] == 'r') ){MXTYPE[0]='R';} else {poski_error("poski_LoadMatrix_HBF_to_CSR", "unknown matrix type - %s\n",MXTYPE);assert(0);} poski_index_t NRowsPadded = CacheLineSizeInDoubles*((NROW+CacheLineSizeInDoubles-1)/CacheLineSizeInDoubles); poski_index_t NColsPadded = CacheLineSizeInDoubles*((NCOL+CacheLineSizeInDoubles-1)/CacheLineSizeInDoubles); char L4[100];fgets(L4,100,fp); char PTRFMT[100];temp[15-00+1]='\0';sscanf(strncpy(temp,L4+00,15-00+1),"%s" , PTRFMT ); // 00..15 = Format for pointers - get rid of ()'s char INDFMT[100];temp[31-16+1]='\0';sscanf(strncpy(temp,L4+16,31-16+1),"%s" , INDFMT ); // 16..31 = Format for row (or variable) indices - get rid of ()'s char VALFMT[100];temp[51-32+1]='\0';sscanf(strncpy(temp,L4+32,51-32+1),"%s" , VALFMT ); // 32..51 = Format for numerical values of coefficient matrix - get rid of ()'s char RHSFMT[100];temp[71-52+1]='\0';sscanf(strncpy(temp,L4+52,71-52+1),"%s" , RHSFMT ); // 52..71 = Format for numerical values of right-hand sides - get rid of ()'s poski_printMessage(3, "\tPTRFMT='%s' INDFMT='%s' VALFMT='%s' RHSFMT='%s'\n",PTRFMT,INDFMT,VALFMT,RHSFMT); if(RHSLines) { char L5[100];fgets(L5,100,fp); char RHSType =L5[0]; //00..00 = Right-hand side type: (F=Full or M=same as Matrix) char RHSGuess=L5[1]; //01..01 = G if a starting vector(s) (Guess) is supplied. (RHSTYP) char RHSExact=L5[2]; //02..02 = X if an exact solution vector(s) is supplied. poski_index_t NRHS; temp[27-14+1]='\0';sscanf(strncpy(temp,L5+14,27-14+1),"%d",&NRHS ); //14..27 = Number of right-hand sides (NRHS) poski_index_t NRHSIX;temp[41-28+1]='\0';sscanf(strncpy(temp,L5+28,41-28+1),"%d",&NRHSIX ); //28..41 = Number of row indices (NRHSIX) poski_printMessage(3, "\tRHSType='%c' RHSGuess='%c' RHSExact='%c' NRHS='%d' NRHSIX='%d'\n",RHSType,RHSGuess,RHSExact,NRHS,NRHSIX); } poski_index_t PatternOnly = 0; if(VALLines==0)PatternOnly=1; if(MXTYPE[0]=='P')PatternOnly=1; // Decode Formats - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - poski_index_t PTRFMT_num,PTRFMT_chars,PTRFMT_mantissa;char PTRFMT_type;if(PTRLines)poski_decode_format(PTRFMT,&PTRFMT_num,&PTRFMT_type,&PTRFMT_chars,&PTRFMT_mantissa); poski_index_t INDFMT_num,INDFMT_chars,INDFMT_mantissa;char INDFMT_type;if(INDLines)poski_decode_format(INDFMT,&INDFMT_num,&INDFMT_type,&INDFMT_chars,&INDFMT_mantissa); poski_index_t VALFMT_num,VALFMT_chars,VALFMT_mantissa;char VALFMT_type;if(VALLines)poski_decode_format(VALFMT,&VALFMT_num,&VALFMT_type,&VALFMT_chars,&VALFMT_mantissa); if(PTRLines) poski_printMessage(3, "\t%s -> %d %c %d %d\n",PTRFMT,PTRFMT_num,PTRFMT_type,PTRFMT_chars,PTRFMT_mantissa); if(INDLines) poski_printMessage(3, "\t%s -> %d %c %d %d\n",INDFMT,INDFMT_num,INDFMT_type,INDFMT_chars,INDFMT_mantissa); if(VALLines) poski_printMessage(3, "\t%s -> %d %c %d %d\n",VALFMT,VALFMT_num,VALFMT_type,VALFMT_chars,VALFMT_mantissa); poski_printMessage(3, "\t%d(%d) x %d(%d), %d nonzeros\n",NRowsPadded,NROW,NColsPadded,NCOL,NNZERO); // Init Matrix / Choose strategies - - - - - - - - - - - - - - - - - - - - - - - - - - - - SpA->nrows=NRowsPadded; SpA->ncols=NColsPadded; // Read Matrix into array of nodes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - char WorkingLine[100]; poski_printMessage(3, "=> Reading Column Pointers..."); poski_index_t CPValue, Column=0; poski_index_t *ColumnPointers = poski_malloc(poski_index_t,(NCOL+1), 0); for(i=0;i<PTRLines;i++) { fgets(WorkingLine,100,fp); for(j=0;j<PTRFMT_num;j++)if(Column <= NCOL) { temp[PTRFMT_chars] = '\0';CPValue = atoi(strncpy(temp,WorkingLine + (PTRFMT_chars*j),PTRFMT_chars))-1; // -1 for conversion to arrays that start at 0 ColumnPointers[Column] = CPValue; Column++; } } poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); poski_printMessage(3, "=> Reading Row Indices..."); NonZeroNode *ArrayOfNodes = poski_malloc(NonZeroNode,(NNZERO+100), 0); poski_index_t Node=0; poski_index_t VNode=0; poski_index_t RowValue; Column=0; while(ColumnPointers[Column+1] == Node)Column++; for(i=0;i<INDLines;i++){ fgets(WorkingLine,100,fp); for(j=0;j<INDFMT_num;j++){if(Node<NNZERO){ temp[INDFMT_chars] = '\0';RowValue = atoi(strncpy(temp,WorkingLine + (INDFMT_chars*j),INDFMT_chars))-1; // -1 for conversion to arrays that start at 0 ArrayOfNodes[Node].Row = RowValue; ArrayOfNodes[Node].Col = Column; ArrayOfNodes[Node].next = NULL; #ifdef READ_VALUES ArrayOfNodes[Node].value = 1.0; // FIX #endif Node++; while(ColumnPointers[Column+1] == Node)Column++; } } } poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); VNode=Node; #ifdef READ_VALUES poski_printMessage(3, "=> Reading NonZero Values..."); if(PatternOnly){ poski_printMessage1(3, "%sIGNORED (Pattern Only)%s\n",CRT_ERROR,CRT_RESET); } else { for(i=0;i<=NCOL;i++)ColumnPointers[i]=0; oski_value_t NZValue; Node=0; VNode=0; for(i=0;i<VALLines;i++) { fgets(WorkingLine,100,fp); for(j=0;j<VALFMT_num;j++) { if(Node<NNZERO) { temp[VALFMT_chars] = '\0';NZValue = atof(strncpy(temp,WorkingLine + (VALFMT_chars*j),VALFMT_chars)); if(NZValue != 0.0) { ColumnPointers[ArrayOfNodes[Node].Col+1]++; ArrayOfNodes[VNode].Row = ArrayOfNodes[Node].Row; ArrayOfNodes[VNode].Col = ArrayOfNodes[Node].Col; ArrayOfNodes[VNode].next = NULL; ArrayOfNodes[VNode].value = NZValue; // FIX VNode++; } Node++; if(NZValue==0.0)ZerosInFile++; } } } poski_printMessage1(3, "%sdone%s :",CRT_DONE,CRT_RESET); poski_printMessage(3, "%d nonzeros, %d total\n",VNode,Node); for(i=0;i<NCOL;i++)ColumnPointers[i+1] += ColumnPointers[i]; } #endif // Link nodes in node array into row pointer array - - - - - - - - - - - - - - - - - - - - poski_printMessage(3, "=> Internal conversion from CSC to CSR..."); NonZeroNode ** ArrayOfLinkedListsOfNodes; ArrayOfLinkedListsOfNodes = poski_malloc(NonZeroNode *, (SpA->nrows), 0); for(i=0;i<(poski_index_t)SpA->nrows;i++)ArrayOfLinkedListsOfNodes[i] = NULL; for(i=(VNode-1);i>=0;i--) { ArrayOfNodes[i].next = ArrayOfLinkedListsOfNodes[ArrayOfNodes[i].Row]; ArrayOfLinkedListsOfNodes[ArrayOfNodes[i].Row] = &(ArrayOfNodes[i]); } poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); // Create SpA's structures & copy data into them - - - - - - - - - - - - - - // allocate RowPointers poski_printMessage(3, "=> Allocating Row Pointer Structures..."); SpA->Aptr = poski_malloc(poski_index_t, (SpA->nrows+1), 0); poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); // update RowPointers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - poski_printMessage(3, "=> Counting actual nonzeros..."); SpA->Aptr[0] = 0; for(i=0;i<(poski_index_t)SpA->nrows;i++) { SpA->Aptr[i+1] = SpA->Aptr[i]; NonZeroNode * tPtr = ArrayOfLinkedListsOfNodes[i]; while(tPtr) { if(tPtr->Col >= SpA->ncols){poski_error("poski_LoadMatrix_HBF_to_CSR", "NNZ.col too big - (%d,%d)\n",i,tPtr->Col); assert(0);} SpA->Aptr[i+1]++; tPtr = tPtr->next; } if((i<NROW)&&(MakeUnsymmetric)&&(MXTYPE[1] == 'S')) { for(j=ColumnPointers[i];j<ColumnPointers[i+1];j++) { if((ArrayOfNodes[j].Row != ArrayOfNodes[j].Col) #ifdef READ_VALUES &&(ArrayOfNodes[j].value != 0.0) #endif ) { if(ArrayOfNodes[j].Row >= SpA->ncols){poski_error("poski_LoadMatrix_HBF_to_CSR", "transposed NNZ.row too big - (%d,%d)\n",i,ArrayOfNodes[j].Row); assert(0);} if(ArrayOfNodes[j].Row < i){poski_error("poski_LoadMatrix_HBF_to_CSR", "transposed NNZ.row too small - (%d,%d)\n",ArrayOfNodes[j].Row,i); assert(0);} SpA->Aptr[i+1]++; } } } } poski_printMessage1(3, "%sdone%s(%d)\n",CRT_DONE,CRT_RESET,SpA->Aptr[SpA->nrows]); // allocate col's & values (function of size of blocked column) - - - - - - - - - - - - - - - - - - - - poski_printMessage(3, "=> Allocating Column and Data Arrays..."); SpA->Aval = poski_malloc(poski_value_t,SpA->Aptr[SpA->nrows], 0); SpA->Aind = poski_malloc(poski_index_t,SpA->Aptr[SpA->nrows], 0); poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); // for all NZ's in table, add to SpA's col/value pointers - - - - - - - - - - - - - - - - - - - - - - - poski_printMessage(3, "=> Copying NonZeros into Column and Data Arrays..."); poski_value_t *VPtr=SpA->Aval; poski_index_t *CPtr=SpA->Aind; SpA->nnz = 0; SpA->Aptr[0] = 0; for(i=0;i<(poski_index_t)SpA->nrows;i++) { SpA->Aptr[i+1] = SpA->Aptr[i]; NonZeroNode * tPtr = ArrayOfLinkedListsOfNodes[i]; while(tPtr) { if(tPtr->Col >= SpA->ncols){poski_error("poski_LoadMatrix_HBF_to_CSR", "NNZ.col too big - (%d,%d)\n",i,tPtr->Col); assert(0);} if((tPtr->Col > i)&&(MXTYPE[1] == 'S')){poski_error("poski_LoadMatrix_HBF_to_CSR", "NNZ.col too big for symmetric - (%d,%d)\n",i,tPtr->Col); assert(0);} SpA->Aptr[i+1]++; #ifdef READ_VALUES *VPtr = tPtr->value; #else #ifdef VERIFY *VPtr = 1.0*(1+rand()%1000); #else *VPtr = 1.0; #endif #endif if(*VPtr!=0.0)SpA->nnz++; VPtr++; *CPtr = tPtr->Col; CPtr++; tPtr = tPtr->next; } if((i<NROW)&&(MakeUnsymmetric)&&(MXTYPE[1] == 'S')) { for(j=ColumnPointers[i];j<ColumnPointers[i+1];j++) { if((ArrayOfNodes[j].Row != ArrayOfNodes[j].Col) #ifdef READ_VALUES &&(ArrayOfNodes[j].value != 0.0) #endif ) { if(ArrayOfNodes[j].Row >= SpA->ncols){poski_error("poski_LoadMatrix_HBF_to_CSR", "transposed NNZ.row too big - (%d,%d)\n",i,ArrayOfNodes[j].Row); assert(0);} if(ArrayOfNodes[j].Row < i){poski_error("poski_LoadMatrix_HBF_to_CSR", "transposed NNZ.row too small - (%d,%d)\n",ArrayOfNodes[j].Row,i); assert(0);} SpA->Aptr[i+1]++; #ifdef READ_VALUES *VPtr = ArrayOfNodes[j].value; #else #ifdef VERIFY *VPtr = 1.0*(1+rand()%1000); #else *VPtr = 1.0; #endif #endif if(*VPtr!=0.0)SpA->nnz++; VPtr++; *CPtr = ArrayOfNodes[j].Row; CPtr++; } } } } poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); // Cleanup - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - poski_printMessage(3, "=> Cleaning up temps..."); fclose(fp); free(ArrayOfLinkedListsOfNodes); free(ArrayOfNodes); free(ColumnPointers); poski_printMessage1(3, "%sdone%s\n",CRT_DONE,CRT_RESET); return(SpA); } // Internal functions //----------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------- // Test functions /** * @brief Test the poski_LoadMatrix_HB_to_CSR's routine. * * This routine is for testing the functionality of the poski_LoadMatrix_HB_to_CSR's routine. * * @return 0 if success, or an error message otherwise. */ int test_main_poski_LoadMatrix_HBF_to_CSR(char *fname) { TEST_LINECUT(1); poski_printMessage(0, "\tTEST: checking poski_LoadMatrix_HBF_to_CSR...\n"); char *matfile = NULL; if (matfile != NULL) { poski_printMessage(0, "\tTEST: error on initializing matrix file!\n"); exit(0); } matfile = fname; if (matfile == NULL) { poski_printMessage(0, "\tTEST: error on initializing sparse matrix!\n"); exit(0); } poski_sparse_matrix_t *SpA = NULL; if (SpA != NULL) { poski_printMessage(0, "\tTEST: error on initializing sparse matrix!\n"); exit(0); } SpA = poski_LoadMatrix_HBF_to_CSR(fname, 1); if (SpA == NULL) { poski_printMessage(0, "\tTEST: error on poski_LoadMatrix_HBF_to_CSR!\n"); exit(0); } free(SpA); poski_printMessage(0, "\tTEST: success on poski_LoadMatrix_HBF_to_CSR!\n"); return 0; } // Test functions //-----------------------------------------------------------------------------------------
2.5
2
2024-11-18T18:42:07.148875+00:00
2012-06-30T22:38:33
acffe2fb05063d0aa963ad26ffcb56da1d22e53b
{ "blob_id": "acffe2fb05063d0aa963ad26ffcb56da1d22e53b", "branch_name": "refs/heads/master", "committer_date": "2012-06-30T22:38:33", "content_id": "a453bfecb5e8c78b13a66ff7de9f891effff4517", "detected_licenses": [ "MIT" ], "directory_id": "1587be5bbcd099beaa6136e5459e392610460d8f", "extension": "c", "filename": "enigma.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 2715727, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1590, "license": "MIT", "license_type": "permissive", "path": "/crypto/enigma/trash/trash_1/src/enigma/enigma.c", "provenance": "stackv2-0030.json.gz:18654", "repo_name": "Fat-Zer/semestr-6", "revision_date": "2012-06-30T22:38:33", "revision_id": "a8747c358fc28b57335df3fc1f0ac000bc39a714", "snapshot_id": "f02af20a7fe81e0eb4329592946426435d301b98", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Fat-Zer/semestr-6/a8747c358fc28b57335df3fc1f0ac000bc39a714/crypto/enigma/trash/trash_1/src/enigma/enigma.c", "visit_date": "2021-01-20T10:13:56.015541" }
stackv2
#include <stdlib.h> #include <stdio.h> #include "enigma.h" int enigma_gen(struct enigma *eng) { int i; int retval; for(i=0;i<ROTOR_NUM;i++) if(retval=rotor_gen(eng->e_rotors)); return retval; return reflector_gen(eng->e_refl); } int rotor_gen(struct rotor *rtr) { char tmp[ROTOR_SZ]; int i; int retval; rtr->r_rotation = rand() % ROTOR_SZ; if(!(retval = transpos_gen(rtr->r_fwd,ROTOR_SZ))) for(i=0;i<ROTOR_SZ;i++) rtr->r_back[rtr->r_fwd] = i; return retval; } int reflector_gen(char e_refl *rfl) { char tmp[ROTOR_SZ]; int i,j; int retval; if(!(retval=transpos_gen(tmp,ROTOR_SZ))) for(i=0; i<sz; i++) { j=tmp[i]; rfl[j] = rfl[tmp[j]]; rfl[tmp[j]] = rfl[j]; } return retval; } int transpos_gen(char *arr, int sz) { int i,j; for(i=0; i<sz; i++) { j=rand()%i; arr[i]=arr[j]; arr[j]=i; } return 0; } int enigme_fwrite(FILE* fs, struct enigma *eng) { int i; int retval for(i=0;i<ROTOR_NUM;i++) if(retval=rotor_fwrite(fs, eng->e_rotors)); return retval; return reflector_fwrite(fs, eng->e_refl); } inline int rotor_fwrite(FILE* fs, struct rotor *rtr) { int retval; if(retval = transpos_fwrite(fs, rtr->f_fwd)) if(fwrite(rtr->r_rotation,sizeof(rtr->r_rotation),1,fs)!=1) retval=1; return retval; } int reflector_fwrite(FILE* fs, struct enigma *eng) { int i; for(i=0;i<ROTOR_NUM;i++) rotor_fwrite(fs, eng->e_rotors); reflector_fwrite(fs, eng->e_refl); } int transpos_fwrite(FILE* fs, struct enigma *eng) { int i; for(i=0;i<ROTOR_NUM;i++) rotor_fwrite(fs, eng->e_rotors); reflector_fwrite(fs, eng->e_refl); }
2.640625
3
2024-11-18T18:42:07.229848+00:00
2022-09-19T14:14:22
5e81f36ed733ef47348157769616621116bf138b
{ "blob_id": "5e81f36ed733ef47348157769616621116bf138b", "branch_name": "refs/heads/master", "committer_date": "2022-09-19T14:14:22", "content_id": "633de13f4f9dc200050391664e05d566dcd6b687", "detected_licenses": [ "CC0-1.0" ], "directory_id": "6610ed12b0d1e2a8b7efd4d2ad07fc1dab108950", "extension": "c", "filename": "tcdis.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 193400445, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5479, "license": "CC0-1.0", "license_type": "permissive", "path": "/t3x9r4/tcdis.c", "provenance": "stackv2-0030.json.gz:18782", "repo_name": "qeedquan/got3x9", "revision_date": "2022-09-19T14:14:22", "revision_id": "80e9d338d8b753b8a7b241afb63bb7a3733902a2", "snapshot_id": "b5ce742e71c7519f9442b4c28506ffc84f729efc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/qeedquan/got3x9/80e9d338d8b753b8a7b241afb63bb7a3733902a2/t3x9r4/tcdis.c", "visit_date": "2022-10-12T07:28:48.573001" }
stackv2
/* * Tcode9 disassembler * Nils M Holm, 2017, 0BSD license */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #define MEMSIZE 131072 #define byte unsigned char #define sbyte signed char #define cell int byte *M; sbyte *S; cell Red; cell Data; void writes(char *s) { write(1, s, strlen(s)); } void wlog(char *s) { write(1, s, strlen(s)); } void fail(char *s) { wlog("tcdis: "); wlog(s); wlog("\n"); _exit(1); } #define BSIZE 1024 char B[BSIZE]; int Fd, C, K; int rdch(void) { if (C >= K) { K = read(Fd, B, BSIZE); C = 0; if (K < 1) return -1; } C = C+1; return B[C-1] & 255; } cell rdwd(void) { cell v; v = rdch(); v = v | (rdch() << 8); v = v | (rdch() << 16); v = v | (rdch() << 24); return v; } void readblk(byte *v, int k) { int i, c; for (i=0; i<k; i++) { c = rdch(); if (-1 == c) fail("file too short"); v[i] = c & 255; } } void load(char *s) { int c; cell tp, dp; Fd = open(s, O_RDONLY); if (Fd < 0) fail("could not open program"); C = 0; K = 0; c = rdch(); while (c != '\n' && c != -1) c = rdch(); if (rdwd() != 0x39583354) fail("not a tcvm program"); tp = rdwd(); dp = rdwd(); Data = tp; Red = tp + dp; M = malloc(MEMSIZE); S = (sbyte *) M; if (NULL == M) fail("not enough memory"); readblk(M, tp+dp); if (rdch() != -1) fail("trailing garbage"); close(Fd); } cell A, F, I, P; cell w(cell a) { return M[a+0] | (M[a+1] << 8) | (M[a+2] << 16) | (M[a+3] << 24); } #define a() w(I+1) #define a2() w(I+5) #define s() S[I+1] #define s2() w(I+2) void decode(void) { cell j; for (I=0; I < Data; I++) { printf("%07x ", I); switch (M[I]) { case 0x80: case 0x00: printf("push"); break; case 0x81: case 0x01: printf("clear"); break; case 0x82: printf("ldval\t%x", s()); I++; break; case 0x02: printf("ldval\t%x", a()); I += 4; break; case 0x83: case 0x03: printf("ldaddr\t%x", a()); I += 4; break; case 0x84: printf("ldlref\t%x", s()); I++; break; case 0x04: printf("ldlref\t%x", a()); I += 4; break; case 0x85: case 0x05: printf("ldglob\t%x", a()); I += 4; break; case 0x86: printf("ldlocl\t%x", s()); I++; break; case 0x06: printf("ldlocl\t%x", a()); I += 4; break; case 0x87: case 0x07: printf("stglob\t%x", a()); I += 4; break; case 0x08: printf("stlocl\t%x", a()); I += 4; break; case 0x88: printf("stlocl\t%x", s()); I++; break; case 0x89: case 0x09: printf("stindr"); break; case 0x8a: case 0x0a: printf("stindb"); break; case 0x8b: case 0x0b: printf("incglob\t%x %x", a(), a2()); I += 8; break; case 0x8c: printf("inclocl\t%x %x", s(), s2()); I += 5; break; case 0x0c: printf("inclocl\t%x %x", a(), a2()); I += 8; break; case 0x8d: printf("alloc\t%x", s()); I++; break; case 0x0d: printf("alloc\t%x", a()); I += 4; break; case 0x8e: printf("dealloc\t%x", s()); I++; break; case 0x0e: printf("dealloc\t%x", a()); I += 4; break; case 0x8f: case 0x0f: printf("loclvec"); break; case 0x90: case 0x10: printf("globvec\t%x", a()); I += 4; break; case 0x91: case 0x11: printf("index"); break; case 0x92: case 0x12: printf("deref"); break; case 0x93: case 0x13: printf("indxb"); break; case 0x94: case 0x14: printf("drefb"); break; /* case 0x95: MARK */ /* case 0x15: MARK */ /* case 0x96: RESOLV */ /* case 0x16: RESOLV */ case 0x97: case 0x17: printf("call\t%x", a()+I+5); I += 4; break; case 0x98: case 0x18: printf("jumpfwd\t%x", a()+I+5); I += 4; break; case 0x99: case 0x19: printf("jumpback\t%x", a()+I+5); I += 4; break; case 0x9a: case 0x1a: printf("jmpfalse\t%x", a()+I+5); I += 4; break; case 0x9b: case 0x1b: printf("jmptrue\t%x", a()+I+5); I += 4; break; case 0x9c: case 0x1c: printf("for\t%x", a()+I+5); I += 4; break; case 0x9d: case 0x1d: printf("fordown\t%x", a()+I+5); I += 4; break; case 0x9e: case 0x1e: printf("enter"); break; case 0x9f: case 0x1f: printf("exit"); break; case 0xa0: printf("halt\t%x", s()); I++; break; case 0x20: printf("halt\t%x", a()); I += 4; break; case 0xa1: case 0x21: printf("neg"); break; case 0xa2: case 0x22: printf("inv"); break; case 0xa3: case 0x23: printf("lognot"); break; case 0xa4: case 0x24: printf("add"); break; case 0xa5: case 0x25: printf("sub"); break; case 0xa6: case 0x26: printf("mul"); break; case 0xa7: case 0x27: printf("div"); break; case 0xa8: case 0x28: printf("mod"); break; case 0xa9: case 0x29: printf("and"); break; case 0xaa: case 0x2a: printf("or"); break; case 0xab: case 0x2b: printf("xor"); break; case 0xac: case 0x2c: printf("shl"); break; case 0xad: case 0x2d: printf("shr"); break; case 0xae: case 0x2e: printf("eq"); break; case 0xaf: case 0x2f: printf("neq"); break; case 0xb0: case 0x30: printf("lt"); break; case 0xb1: case 0x31: printf("gt"); break; case 0xb2: case 0x32: printf("le"); break; case 0xb3: case 0x33: printf("ge"); break; /* case 0xb4: WORD */ /* case 0x34: WORD */ case 0xb5: case 0x35: printf("syscall\t%x", M[I+1]); I++; break; default: fail("invalId opcode"); break; } putchar('\n'); fflush(stdout); } putchar('\n'); for (; I < Red; I += 16) { printf("%07x ", I); for (j=0; j<16; j++) { if (j && j%4 == 0) putchar(' '); printf(" %02x", M[I+j]); } printf(" "); for (j=0; j<16; j++) printf("%c", ' ' <= M[I+j] && M[I+j] <= '~'? M[I+j]: '.'); putchar('\n'); } } cell main(cell argc, char **argv) { if (argc != 2) fail("usage: tcdis program"); load(argv[1]); decode(); return 0; }
2.53125
3
2024-11-18T18:42:08.905329+00:00
2021-06-15T15:39:11
1599b6d36840317b331bce255371e927383406d7
{ "blob_id": "1599b6d36840317b331bce255371e927383406d7", "branch_name": "refs/heads/main", "committer_date": "2021-06-15T15:39:11", "content_id": "2b0cc6b58cbed424db92c3c2e7c71e4f587a68bd", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "f0f6c89067f89aea40fe939ba7ab50adf9524be9", "extension": "c", "filename": "database_common.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 869, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/lib/wget-gui/src/model/database_common.c", "provenance": "stackv2-0030.json.gz:19807", "repo_name": "kyle-ip/learning-c", "revision_date": "2021-06-15T15:39:11", "revision_id": "b226826cde08da9dbbaae457c609b4d038843297", "snapshot_id": "20f79fba3c31f5f0cf8360dfa7bf063e85272841", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kyle-ip/learning-c/b226826cde08da9dbbaae457c609b4d038843297/lib/wget-gui/src/model/database_common.c", "visit_date": "2023-05-22T07:02:31.189920" }
stackv2
#include "model/database_common.h" #include "common/sqlite_manager.h" #include "utils/io_utils.h" #define TABLE_COUNT 1 static char *tables[TABLE_COUNT] = { "create table if not exists task_info(" " id integer primary key autoincrement," " url varchar(1024)," " filename varchar(1024)," " directory varchar(1024)," " size integer," " progress real default 0," " status integer default 0," " resume_support integer default 0," " create_time timestamp default current_timestamp" ");", }; /** * 数据表初始化。 * * @return */ int InitTables() { for (int i = 0; i < TABLE_COUNT; ++i) { char *create_table_sql = tables[i]; if (ExecuteSql(create_table_sql)) { PRINTLNF("Failed to create table with: %s\n", create_table_sql); return RESULT_FAILURE; } } return RESULT_OK; }
2.125
2
2024-11-18T18:42:09.169030+00:00
2018-02-01T15:31:54
1ee4e2a1bf7ba635c45660f1bffaa7575b4fdb35
{ "blob_id": "1ee4e2a1bf7ba635c45660f1bffaa7575b4fdb35", "branch_name": "refs/heads/master", "committer_date": "2018-02-01T15:31:54", "content_id": "41ed2712b6f26f743e9bd57d66135705a631c9ca", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7d447efaa28342cecf43fc5e432ac828443639fc", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2019-06-19T17:01:25", "gha_event_created_at": "2019-06-19T17:01:25", "gha_language": null, "gha_license_id": null, "github_id": 192772846, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2563, "license": "Apache-2.0", "license_type": "permissive", "path": "/rt-pwm/main.c", "provenance": "stackv2-0030.json.gz:20191", "repo_name": "l29ah/stm32-bluepill", "revision_date": "2018-02-01T15:31:54", "revision_id": "d42bc25b31bbec842c43d456d404291fefe6a4ce", "snapshot_id": "5e9ac5111f48af3444283d1586a6aee81942d1d3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/l29ah/stm32-bluepill/d42bc25b31bbec842c43d456d404291fefe6a4ce/rt-pwm/main.c", "visit_date": "2020-06-06T15:06:59.770335" }
stackv2
/* ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio 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. */ #include "hal.h" #include "ch.h" static PWMConfig pwmcfg = { 1000000, 20000, NULL, { {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL}, {PWM_OUTPUT_ACTIVE_HIGH, NULL} }, 0, 0, #if STM32_PWM_USE_ADVANCED 0 #endif }; int main(void) { halInit(); chSysInit(); // pull-up resisitor inplace, otherwise use pushpull mode palSetPadMode(GPIOA, 6, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOA, 7, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOB, 0, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOB, 1, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOB, 6, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOB, 7, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOB, 8, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOB, 9, PAL_MODE_STM32_ALTERNATE_OPENDRAIN); palSetPadMode(GPIOC, GPIOC_LED, PAL_MODE_OUTPUT_OPENDRAIN); pwmStart(&PWMD3, &pwmcfg); pwmStart(&PWMD4, &pwmcfg); pwmEnableChannel(&PWMD4, 0, 1500); pwmEnableChannel(&PWMD4, 1, 1500); pwmEnableChannel(&PWMD4, 2, 1500); pwmEnableChannel(&PWMD4, 3, 1500); pwmEnableChannel(&PWMD3, 0, 1500); pwmEnableChannel(&PWMD3, 1, 1500); pwmEnableChannel(&PWMD3, 2, 1500); pwmEnableChannel(&PWMD3, 3, 1500); int16_t w = 1500; int16_t step = 100; while(1) { pwmEnableChannel(&PWMD4, 0, w); pwmEnableChannel(&PWMD4, 1, w); pwmEnableChannel(&PWMD4, 2, w); pwmEnableChannel(&PWMD4, 3, w); pwmEnableChannel(&PWMD3, 0, w); pwmEnableChannel(&PWMD3, 1, w); pwmEnableChannel(&PWMD3, 2, w); pwmEnableChannel(&PWMD3, 3, w); w += step; if (w > 2400 || w < 600) { step = -step; } palTogglePad(GPIOC, GPIOC_LED); chThdSleepMilliseconds(50); } return 0; }
2.3125
2
2024-11-18T18:42:09.252669+00:00
2021-01-01T12:36:51
b7af217e66577c862cf813af727d91b523070c09
{ "blob_id": "b7af217e66577c862cf813af727d91b523070c09", "branch_name": "refs/heads/master", "committer_date": "2021-01-01T12:36:51", "content_id": "ed5c4ca6531432a14d9a75f52584815896582dd8", "detected_licenses": [ "MIT" ], "directory_id": "1c95245073d8f46d65108ea3eed0eeb410c4da4c", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 292187098, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 158, "license": "MIT", "license_type": "permissive", "path": "/codes/lecture_04/practice_ifndef/main.c", "provenance": "stackv2-0030.json.gz:20320", "repo_name": "h0han/SE271_OOP", "revision_date": "2021-01-01T12:36:51", "revision_id": "5b57b3a1664397d3c2d9cd9052626f8a17e7f6f8", "snapshot_id": "2ddc46d3f33f057e99ad44a7a45bc24c3640940c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/h0han/SE271_OOP/5b57b3a1664397d3c2d9cd9052626f8a17e7f6f8/codes/lecture_04/practice_ifndef/main.c", "visit_date": "2023-02-08T09:10:19.901273" }
stackv2
#include <stdio.h> #include "coordinate.h" int main(void) { struct coordinate coord; coord.x = 5; coord.y = 3; print_coordinate(&coord); return 0; }
2.125
2
2024-11-18T18:42:09.334948+00:00
2023-07-07T22:09:48
ae0044ebc2ac652ff20f24c400fbf76c41abc92d
{ "blob_id": "ae0044ebc2ac652ff20f24c400fbf76c41abc92d", "branch_name": "refs/heads/master", "committer_date": "2023-07-07T22:09:48", "content_id": "ce37b0ffb7d33e96d25acaa77ee5b400e600e56e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8200602192c30c01760407dbea45b106c42bf155", "extension": "c", "filename": "client_remote_node_info.c", "fork_events_count": 6, "gha_created_at": "2017-05-24T20:07:36", "gha_event_created_at": "2023-05-25T22:53:06", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 92332092, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3612, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/apps/dht/client_remote_node_info.c", "provenance": "stackv2-0030.json.gz:20448", "repo_name": "MAYHEM-Lab/cspot", "revision_date": "2023-07-07T22:09:48", "revision_id": "d310543a15d5ccba80732d3ddd84c01bcf70ce49", "snapshot_id": "861e292b5ab38813cb49d78e9f7a3b188e9e22aa", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/MAYHEM-Lab/cspot/d310543a15d5ccba80732d3ddd84c01bcf70ce49/apps/dht/client_remote_node_info.c", "visit_date": "2023-07-10T13:21:03.909211" }
stackv2
#include "dht.h" #include "dht_utils.h" #include "raft_client.h" #include "woofc-host.h" #include "woofc.h" #include <openssl/sha.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char** argv) { WooFInit(); DHT_NODE_INFO node = {0}; if (get_latest_node_info(&node) < 0) { log_error("couldn't get latest node info: %s", dht_error_msg); exit(1); } DHT_PREDECESSOR_INFO predecessor = {0}; if (get_latest_predecessor_info(&predecessor) < 0) { log_error("couldn't get latest predecessor info: %s", dht_error_msg); exit(1); } DHT_SUCCESSOR_INFO successor = {0}; if (get_latest_successor_info(&successor) < 0) { log_error("couldn't get latest successor info: %s", dht_error_msg); exit(1); } int i; char woof_name[DHT_NAME_LENGTH]; char hash[DHT_NAME_LENGTH]; // node int is_leader = raft_is_leader(); if (is_leader < 0) { printf("leader: ???\n"); } else if (is_leader) { printf("leader: yes\n"); } else { printf("leader: no\n"); } printf("node_name: %s\n", node.name); print_node_hash(hash, node.hash); printf("node_hash: %s\n", hash); printf("node_addr: %s\n", node.addr); for (i = 0; i < DHT_REPLICA_NUMBER; ++i) { if (node.replicas[i][0] == 0) { break; } printf("node_replica: %s\n", node.replicas[i]); } printf("node_replica_id: %d\n", node.replica_id); printf("node_leader_id: %d\n", node.leader_id); // predecessor print_node_hash(hash, predecessor.hash); printf("predecessor_hash: %s\n", hash); if (is_empty(predecessor.hash)) { printf("predecessor_addr: nil\n"); } else { print_node_hash(woof_name + strlen(woof_name), predecessor.hash); printf("predecessor_addr: %s\n", predecessor_addr(&predecessor)); for (i = 0; i < DHT_REPLICA_NUMBER; ++i) { if (predecessor.replicas[i][0] == 0) { break; } printf("predecessor_replica: %s\n", predecessor.replicas[i]); } } // successor int j; for (j = 0; j < DHT_SUCCESSOR_LIST_R; ++j) { print_node_hash(hash, successor.hash[j]); printf("successor_hash %d: %s\n", j, hash); if (is_empty(successor.hash[j])) { printf("successor_addr %d: nil\n", j); } else { print_node_hash(woof_name + strlen(woof_name), successor.hash[j]); printf("successor_addr %d: %s\n", j, successor_addr(&successor, j)); for (i = 0; i < DHT_REPLICA_NUMBER; ++i) { if (successor.replicas[i][0] == 0) { break; } printf("successor_replica: %s\n", successor.replicas[i]); } } } // finger int all_filled = 1; for (j = 1; j <= SHA_DIGEST_LENGTH * 8; ++j) { DHT_FINGER_INFO finger = {0}; if (get_latest_finger_info(j, &finger) < 0) { fprintf(stderr, "failed to get finger[%d]'s info: %s", j, dht_error_msg); exit(1); } print_node_hash(hash, finger.hash); printf("finger_hash %d: %s\n", j, hash); if (is_empty(finger.hash)) { all_filled = 0; printf("finger_addr %d: nil\n", j); } else { printf("finger_addr %d: %s\n", j, finger_addr(&finger)); } } if (all_filled) { printf("all fingers filled: yes\n"); } else { printf("all fingers filled: no\n"); } return 0; }
2.28125
2
2024-11-18T18:42:09.402067+00:00
2023-08-30T19:55:29
054254636665f1f760df5cb719eec4ec3cc31cf2
{ "blob_id": "054254636665f1f760df5cb719eec4ec3cc31cf2", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T19:55:29", "content_id": "0e4159b47d8ee97cd715a6838c023bf92563b510", "detected_licenses": [ "MIT" ], "directory_id": "83e7dc1281874779c46dfadcc15b2bb66d8e599c", "extension": "c", "filename": "lv_example_meter_2.c", "fork_events_count": 2218, "gha_created_at": "2016-06-08T04:14:34", "gha_event_created_at": "2023-09-14T17:59:34", "gha_language": "C", "gha_license_id": "MIT", "github_id": 60667730, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1767, "license": "MIT", "license_type": "permissive", "path": "/examples/widgets/meter/lv_example_meter_2.c", "provenance": "stackv2-0030.json.gz:20577", "repo_name": "lvgl/lvgl", "revision_date": "2023-08-30T19:55:29", "revision_id": "5c984b4a5364b6455966eb3a860153806c51626f", "snapshot_id": "7d51d6774d6ac71df7101fc7ded56fea4b70be01", "src_encoding": "UTF-8", "star_events_count": 9296, "url": "https://raw.githubusercontent.com/lvgl/lvgl/5c984b4a5364b6455966eb3a860153806c51626f/examples/widgets/meter/lv_example_meter_2.c", "visit_date": "2023-08-30T22:39:20.283922" }
stackv2
#include "../../lv_examples.h" #if LV_USE_METER && LV_BUILD_EXAMPLES static lv_obj_t * meter; static void set_value(void * indic, int32_t v) { lv_meter_set_indicator_end_value(meter, indic, v); } /** * A meter with multiple arcs */ void lv_example_meter_2(void) { meter = lv_meter_create(lv_scr_act()); lv_obj_center(meter); lv_obj_set_size(meter, 220, 220); /*Remove the circle from the middle*/ lv_obj_remove_style(meter, NULL, LV_PART_INDICATOR); /*Add a scale first*/ lv_meter_set_scale_ticks(meter, 11, 2, 10, lv_palette_main(LV_PALETTE_GREY)); lv_meter_set_scale_major_ticks(meter, 1, 2, 30, lv_color_hex3(0xeee), 15); lv_meter_set_scale_range(meter, 0, 100, 270, 90); /*Add a three arc indicator*/ lv_meter_indicator_t * indic1 = lv_meter_add_arc(meter, 10, lv_palette_main(LV_PALETTE_RED), 0); lv_meter_indicator_t * indic2 = lv_meter_add_arc(meter, 10, lv_palette_main(LV_PALETTE_GREEN), -10); lv_meter_indicator_t * indic3 = lv_meter_add_arc(meter, 10, lv_palette_main(LV_PALETTE_BLUE), -20); /*Create an animation to set the value*/ lv_anim_t a; lv_anim_init(&a); lv_anim_set_exec_cb(&a, set_value); lv_anim_set_values(&a, 0, 100); lv_anim_set_repeat_delay(&a, 100); lv_anim_set_playback_delay(&a, 100); lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE); lv_anim_set_time(&a, 2000); lv_anim_set_playback_time(&a, 500); lv_anim_set_var(&a, indic1); lv_anim_start(&a); lv_anim_set_time(&a, 1000); lv_anim_set_playback_time(&a, 1000); lv_anim_set_var(&a, indic2); lv_anim_start(&a); lv_anim_set_time(&a, 1000); lv_anim_set_playback_time(&a, 2000); lv_anim_set_var(&a, indic3); lv_anim_start(&a); } #endif
2.734375
3
2024-11-18T18:42:09.697323+00:00
2021-08-08T16:15:44
40cab50c4a3d536d7f0e420689a90e60bb585cb3
{ "blob_id": "40cab50c4a3d536d7f0e420689a90e60bb585cb3", "branch_name": "refs/heads/main", "committer_date": "2021-08-08T16:15:44", "content_id": "56b8760d5a252bf51ff12377e53402e328030260", "detected_licenses": [ "MIT" ], "directory_id": "0ef785344e4acd71d946f279c80a90ab029a6f7b", "extension": "h", "filename": "alloc.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 393976803, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1278, "license": "MIT", "license_type": "permissive", "path": "/alloc.h", "provenance": "stackv2-0030.json.gz:20705", "repo_name": "UoB-HPC/gpusched", "revision_date": "2021-08-08T16:15:44", "revision_id": "3a09f344a5c84a7e813508204025b97281cc7a82", "snapshot_id": "922f2290eb5af15cabd54b429fe81a877bb087a3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/UoB-HPC/gpusched/3a09f344a5c84a7e813508204025b97281cc7a82/alloc.h", "visit_date": "2023-07-02T15:52:38.701545" }
stackv2
#pragma once #include <stdlib.h> #include <atomics.h> #include <utils.h> #include <worker.h> struct alignas(CACHELINE_SIZE) malloc_info_t { volatile char* head; volatile char* tail; uint64_t max_alloc_size; }; // Should only be called on one worker // INLINE void init_malloc(team_t* team, void* malloc_storage, // uint64_t num_cachelines_per_sm) //{ // for (int i = 0; i < nsmid(); ++i) { // team->malloc_info[i].head = team->malloc_info[i].tail = // (char*)malloc_storage + CACHELINE_SIZE * num_cachelines_per_sm * i; // } // team->max_alloc_size = num_cachelines_per_sm * CACHELINE_SIZE; //} INLINE void* fast_malloc(worker_t* worker, uint64_t size) { volatile char** head = &worker->team->malloc_info[smid()].head; volatile char** tail = &worker->team->malloc_info[smid()].tail; //uint64_t mas = worker->team->max_alloc_size; uint64_t mas = worker->team->malloc_info[smid()].max_alloc_size; // TODO this may be a race condition here if (*tail - *head >= mas) { printf("(%d) error, out of memory: %p, %p, %llu\n", smid(), *tail, *head, mas); asm("trap;"); return nullptr; } else { return (void*)atomic_add((unsigned long long*)tail, (unsigned long long)size); } }
2.453125
2
2024-11-18T18:42:09.785017+00:00
2023-05-09T20:08:24
2d643108b0c2ff81cbea633ff2df50ac45128b6d
{ "blob_id": "2d643108b0c2ff81cbea633ff2df50ac45128b6d", "branch_name": "refs/heads/master", "committer_date": "2023-05-09T20:08:24", "content_id": "20cb8d8b398f59f25b62a20cab397ed016e4857d", "detected_licenses": [ "MIT" ], "directory_id": "b5d28de0f81d800758bc8234f265e5290bc303df", "extension": "c", "filename": "ioExpanderList.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 4457913, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1369, "license": "MIT", "license_type": "permissive", "path": "/drivers/ioExpander/ioExpanderList.c", "provenance": "stackv2-0030.json.gz:20834", "repo_name": "f4deb/cen-electronic", "revision_date": "2023-05-09T20:08:24", "revision_id": "eadf1a839445b57bba0319ba54c30ce333f912f0", "snapshot_id": "026c9b9d650487e70fde472cbbcf1a81ec9fe980", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/f4deb/cen-electronic/eadf1a839445b57bba0319ba54c30ce333f912f0/drivers/ioExpander/ioExpanderList.c", "visit_date": "2023-05-09T23:58:02.262631" }
stackv2
#include "ioExpanderList.h" #include <stdlib.h> #include <stdbool.h> #include "ioExpander.h" #include "../../common/error/error.h" #include "../../common/io/outputStream.h" #include "../../common/io/printWriter.h" #include "../../common/log/logHandler.h" #include "../../common/log/logger.h" #include "../../common/log/logLevel.h" void initIOExpanderList(IOExpanderList* ioExpanderList, IOExpander(*ioExpanderArray)[], unsigned int ioExpanderListSize) { if (ioExpanderArray == NULL) { writeError(IO_EXPANDER_LIST_NOT_INITIALIZED); } ioExpanderList->ioExpanderArray = ioExpanderArray; ioExpanderList->size = ioExpanderListSize; } IOExpander* getIOExpanderByIndex(IOExpanderList* ioExpanderList, unsigned int index) { if (ioExpanderList == NULL || ioExpanderList->ioExpanderArray == NULL) { writeError(IO_EXPANDER_LIST_NOT_INITIALIZED); return NULL; } if (index < 0 || index >= ioExpanderList->size) { writeError(IO_EXPANDER_LIST_ILLEGAL_INDEX); return NULL; } IOExpander* result = (IOExpander*) ioExpanderList->ioExpanderArray; // we don't need use sizeof because our pointer is a IOExpander pointer, so the shift // is already of the structure, we just have to shift of index. result += index; return result; }
2.296875
2
2024-11-18T18:42:10.080697+00:00
2019-04-18T08:39:33
60e054f15f2b273f12494cf95781be12564fd891
{ "blob_id": "60e054f15f2b273f12494cf95781be12564fd891", "branch_name": "refs/heads/master", "committer_date": "2019-04-18T08:39:33", "content_id": "1abe95f4037d0e5409131021d0e7404400757390", "detected_licenses": [ "MIT" ], "directory_id": "5f64a1ff4f8a76b5d9da44954737689f0d055041", "extension": "c", "filename": "BaseSeven.c", "fork_events_count": 1, "gha_created_at": "2018-08-10T14:30:45", "gha_event_created_at": "2019-02-25T15:10:12", "gha_language": "C", "gha_license_id": "MIT", "github_id": 144296507, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2168, "license": "MIT", "license_type": "permissive", "path": "/ports/esp32/zwlib/BaseSeven.c", "provenance": "stackv2-0030.json.gz:21220", "repo_name": "junhuanchen/micropython", "revision_date": "2019-04-18T08:39:33", "revision_id": "c02c157e4fc2a77b2f6e13171a8973a86f320c73", "snapshot_id": "25e689f604e5c629964f22ce717bbcbdaa30ecf9", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/junhuanchen/micropython/c02c157e4fc2a77b2f6e13171a8973a86f320c73/ports/esp32/zwlib/BaseSeven.c", "visit_date": "2020-04-28T09:02:49.531811" }
stackv2
#include "BaseSeven.h" #include <string.h> // 编码数据转换结构 union BSVar { uint16_t bit16; struct TwoChar { uint8_t right, left; }bit08; }; // 同步修改索引进行块编码。(由宏改) static void BsEncode(uint8_t *Buf[], uint8_t *Src[]) { union BSVar var = { 0 }; for (uint8_t shift = 1; 8 != shift; (*Buf)++, (*Src)++, shift++) { var.bit08.right = **Src, var.bit16 <<= 8 - shift; **Buf = var.bit08.left | 0x80, var.bit16 <<= shift; } **Buf = var.bit08.left | 0x80; } uint8_t BaseSevenEncode(uint8_t Buf[], uint32_t BufLen, uint8_t Src[], uint32_t SrcLen) { // 判断编码缓冲区是否可容纳数据源 if ((BufLen / 8) * 7 >= SrcLen) { while (SrcLen >= 7) { BsEncode(&Buf, &Src); // 准备下一个编码块 Buf++, SrcLen -= 7; } // 处理不足一个单位的部分 if (SrcLen) { uint8_t TmpBuf[7] = { '\0' }, *TmpSrc = TmpBuf; memcpy(TmpBuf, Src, SrcLen); BsEncode(&Buf, &TmpSrc); } return 1; } return 0; } uint8_t BaseSevenDecode(uint8_t Buf[], uint32_t BufLen, uint8_t Src[], uint32_t SrcLen) { if ((BufLen / 8) * 7 <= SrcLen) { // 数据位移长度值 for (union BSVar var; BufLen; BufLen -= 8) { // 以8字节为解码单位长度 var.bit08.left = (*Buf++); for (uint8_t shift = 1; 8 != shift; Buf++, Src++, shift++) { if (!(*Buf & 0x80)) return 0; // 异常编码值 var.bit08.right = *Buf << 1, var.bit16 <<= shift; *Src = var.bit08.left, var.bit16 <<= 7 - shift; } } return 1; } return 0; } // 单元测试 #ifdef UNIT_TEST #include <assert.h> #include <string.h> #define TestStr "0123456789ab" static RsaType main() { char Buf[16], Src[14]; assert(1 == BaseSevenEncode(Buf, sizeof(Buf), TestStr, sizeof(TestStr))); assert(1 == BaseSevenDecode(Buf, sizeof(Buf), Src, sizeof(Src))); assert(0 == memcmp(Src, TestStr, sizeof(TestStr))); memset(Buf, 0, sizeof(Buf)), memset(Src, 0, sizeof(Src)); assert(1 == BaseSevenEncode(Buf, sizeof(Buf), TestStr, sizeof(TestStr))); Buf[1] = 0x7F; assert(0 == BaseSevenDecode(Buf, sizeof(Buf), Src, sizeof(Src))); assert(0 != memcmp(Src, TestStr, sizeof(TestStr))); return 0; } #endif
2.71875
3
2024-11-18T18:42:11.289500+00:00
2020-09-05T23:29:36
64eca1c38b0d871c6b050fa44b7dd5892fe79ec6
{ "blob_id": "64eca1c38b0d871c6b050fa44b7dd5892fe79ec6", "branch_name": "refs/heads/master", "committer_date": "2020-09-05T23:29:36", "content_id": "03b70c663e6a3a78d6c91701a9f8851e1b82b6a2", "detected_licenses": [ "MIT" ], "directory_id": "b423a710f4d4717807dd831892090f420ece99a4", "extension": "c", "filename": "assume2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 339, "license": "MIT", "license_type": "permissive", "path": "/test/c/special/assume2.c", "provenance": "stackv2-0030.json.gz:21733", "repo_name": "dantecoupet/smack", "revision_date": "2020-09-05T23:29:36", "revision_id": "c1ccb518fa9ec98766d85bbdf6bb686bb0a514b6", "snapshot_id": "fc913aa860ee43a56538767d3a0dc667b9b825ea", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dantecoupet/smack/c1ccb518fa9ec98766d85bbdf6bb686bb0a514b6/test/c/special/assume2.c", "visit_date": "2023-01-23T03:12:58.241912" }
stackv2
#include "smack.h" // @expect verified // @flag --llvm-assumes=use int main(void) { unsigned int y = (2 * (unsigned int)__VERIFIER_nondet_unsigned_short()) + 1; // This assumption is used for verification, even though the assumption // is false, the assertion will pass. __builtin_assume((y & 1) == 0); assert((y & 1) == 0); }
2.015625
2
2024-11-18T18:42:12.165507+00:00
2021-03-05T20:21:39
e5465fb84dfd56354b976633be15a19a79531298
{ "blob_id": "e5465fb84dfd56354b976633be15a19a79531298", "branch_name": "refs/heads/master", "committer_date": "2021-03-05T20:21:39", "content_id": "77a6b8008afd61a7b2c7a1f24c1e7130101707c2", "detected_licenses": [ "MIT" ], "directory_id": "3a0f9f87d807e9aa33b87568b0829edd92da4ef3", "extension": "c", "filename": "e_mesh_bandwidth_near.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 343282601, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3486, "license": "MIT", "license_type": "permissive", "path": "/examples/epiphany-examples/emesh/emesh_bandwidth_neighbour/src/e_mesh_bandwidth_near.c", "provenance": "stackv2-0030.json.gz:22374", "repo_name": "Patuxent62/parallella-base-fs-gen", "revision_date": "2021-03-05T20:21:39", "revision_id": "67f85909185ad633433f95007b5a6a4c4aab096c", "snapshot_id": "eb3c13ba41e3f4f76ab32a159e40ae7ee529a52f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Patuxent62/parallella-base-fs-gen/67f85909185ad633433f95007b5a6a4c4aab096c/examples/epiphany-examples/emesh/emesh_bandwidth_neighbour/src/e_mesh_bandwidth_near.c", "visit_date": "2023-03-18T16:38:44.763305" }
stackv2
/* e_mesh_bandwidth_near.c Copyright (C) 2012 Adapteva, Inc. Contributed by Wenlin Song <[email protected]> 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 3 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, see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ // This is the DEVICE side of the e_mesh bandwidth example. // This core will write to and read from the four neighbour // cores. C_TIMER_0 register is used to record clock cycles. #include <stdio.h> #include <stdlib.h> #include <string.h> #include "e_lib.h" int main(void) { unsigned time_c, time_p; unsigned time; unsigned tran,k,i,j,q,h,m,n; unsigned *box; unsigned *n_row, *n_col, *p; unsigned *neighbour_n; unsigned *neighbour_s; unsigned *neighbour_w; unsigned *neighbour_e; unsigned *master; // Define the mailbox master = (unsigned *)0x2000; box = (unsigned *) 0x5000; n_row = (unsigned *)0x6000; n_col = (unsigned *)0x6004; tran = 2048; p =(unsigned *) 0x2000; // Get the neighbour global address e_neighbor_id(E_NEXT_CORE, E_ROW_WRAP, n_row, n_col); neighbour_e = (unsigned *) e_get_global_address(*n_row, *n_col, p) ; e_neighbor_id(E_PREV_CORE, E_ROW_WRAP, n_row, n_col); neighbour_w = (unsigned *) e_get_global_address(*n_row, *n_col, p) ; e_neighbor_id(E_NEXT_CORE, E_COL_WRAP, n_row, n_col); neighbour_s = (unsigned *) e_get_global_address(*n_row, *n_col, p) ; e_neighbor_id(E_PREV_CORE, E_COL_WRAP, n_row, n_col); neighbour_n = (unsigned *) e_get_global_address(*n_row, *n_col, p) ; // Test the writing bandwidth // Initialize master and slave for(i=0; i<tran; i++) { master[i] = 0xdeadbeef; neighbour_e[i] = 0x00000000; neighbour_w[i] = 0x00000000; neighbour_s[i] = 0x00000000; neighbour_n[i] = 0x00000000; } // Set the ctimer e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; // Start the ctimer and select the time type time_p = e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); // Write to all neighbour cores e_dma_copy(neighbour_e, master, 0x2000); e_dma_copy(neighbour_w, master, 0x2000); e_dma_copy(neighbour_s, master, 0x2000); e_dma_copy(neighbour_n, master, 0x2000); // Get the time now time_c = e_ctimer_get(E_CTIMER_0); time = time_p - time_c; // Output the result box[0] = time; // Test the reading bandwidth // Initialize master and slave for(i=0; i<tran; i++) { master[i] = 0x00000000; neighbour_e[i] = 0xdeadbee1; neighbour_w[i] = 0xdeadbee2; neighbour_s[i] = 0xdeadbee3; neighbour_n[i] = 0xdeadbee4; } // Set the ctimer e_ctimer_set(E_CTIMER_0, E_CTIMER_MAX) ; // Start the ctimer and select the time type time_p = e_ctimer_start(E_CTIMER_0, E_CTIMER_CLK); // Read from all neighbour cores e_dma_copy(master, neighbour_e, 0x2000); e_dma_copy(master, neighbour_w, 0x2000); e_dma_copy(master, neighbour_s, 0x2000); e_dma_copy(master, neighbour_n, 0x2000); // Get the time now time_c = e_ctimer_get(E_CTIMER_0); time = time_p - time_c; // Output the result box[1] = time; return 0; }
2.390625
2
2024-11-18T18:42:12.233265+00:00
2023-07-12T07:38:29
95deb3a6b65bf3fc4adcfd455e1c5ecf285a28d1
{ "blob_id": "95deb3a6b65bf3fc4adcfd455e1c5ecf285a28d1", "branch_name": "refs/heads/master", "committer_date": "2023-07-12T07:38:29", "content_id": "7c9abae084d33109908c096cd9b7bb658af5d882", "detected_licenses": [ "MIT" ], "directory_id": "52c8ed39b32ccc7c0673278c1adea3638797c9ff", "extension": "c", "filename": "blk-ramdisk.c", "fork_events_count": 296, "gha_created_at": "2010-01-14T08:25:12", "gha_event_created_at": "2023-05-25T09:39:01", "gha_language": "C", "gha_license_id": "MIT", "github_id": 471539, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3808, "license": "MIT", "license_type": "permissive", "path": "/src/driver/block/blk-ramdisk.c", "provenance": "stackv2-0030.json.gz:22502", "repo_name": "xboot/xboot", "revision_date": "2023-07-12T07:38:29", "revision_id": "6d6b93947b7fcb8c3924fedb0715c23877eedd5e", "snapshot_id": "0cab7b440b612aa0a4c366025598a53a7ec3adf1", "src_encoding": "UTF-8", "star_events_count": 765, "url": "https://raw.githubusercontent.com/xboot/xboot/6d6b93947b7fcb8c3924fedb0715c23877eedd5e/src/driver/block/blk-ramdisk.c", "visit_date": "2023-08-20T05:56:25.149388" }
stackv2
/* * driver/block/blk-ramdisk.c * * Copyright(c) 2007-2023 Jianjun Jiang <[email protected]> * Official site: http://xboot.org * Mobile phone: +86-18665388956 * QQ: 8192542 * * 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 <xboot.h> #include <block/block.h> struct blk_ramdisk_pdata_t { virtual_addr_t addr; virtual_size_t size; }; static u64_t blk_ramdisk_capacity(struct block_t * blk) { struct blk_ramdisk_pdata_t * pdat = (struct blk_ramdisk_pdata_t *)(blk->priv); return pdat->size; } static u64_t blk_ramdisk_read(struct block_t * blk, u8_t * buf, u64_t offset, u64_t count) { struct blk_ramdisk_pdata_t * pdat = (struct blk_ramdisk_pdata_t *)(blk->priv); memcpy((void *)buf, (const void *)((virtual_addr_t)(pdat->addr + offset)), count); return count; } static u64_t blk_ramdisk_write(struct block_t * blk, u8_t * buf, u64_t offset, u64_t count) { struct blk_ramdisk_pdata_t * pdat = (struct blk_ramdisk_pdata_t *)(blk->priv); memcpy((void *)((virtual_addr_t)(pdat->addr + offset)), (const void *)buf, count); return count; } static void blk_ramdisk_sync(struct block_t * blk) { } static struct device_t * blk_ramdisk_probe(struct driver_t * drv, struct dtnode_t * n) { struct blk_ramdisk_pdata_t * pdat; struct block_t * blk; struct device_t * dev; virtual_addr_t addr = dt_read_long(n, "address", 0); virtual_size_t size = dt_read_long(n, "size", 0); if(size <= 0) return NULL; pdat = malloc(sizeof(struct blk_ramdisk_pdata_t)); if(!pdat) return NULL; blk = malloc(sizeof(struct block_t)); if(!blk) { free(pdat); return NULL; } pdat->addr = addr; pdat->size = size; blk->name = alloc_device_name(dt_read_name(n), dt_read_id(n)); blk->capacity = blk_ramdisk_capacity; blk->read = blk_ramdisk_read; blk->write = blk_ramdisk_write; blk->sync = blk_ramdisk_sync; blk->priv = pdat; if(!(dev = register_block(blk, drv))) { free_device_name(blk->name); free(blk->priv); free(blk); return NULL; } return dev; } static void blk_ramdisk_remove(struct device_t * dev) { struct block_t * blk = (struct block_t *)dev->priv; if(blk) { unregister_block(blk); free_device_name(blk->name); free(blk->priv); free(blk); } } static void blk_ramdisk_suspend(struct device_t * dev) { } static void blk_ramdisk_resume(struct device_t * dev) { } static struct driver_t blk_ramdisk = { .name = "blk-ramdisk", .probe = blk_ramdisk_probe, .remove = blk_ramdisk_remove, .suspend = blk_ramdisk_suspend, .resume = blk_ramdisk_resume, }; static __init void blk_ramdisk_driver_init(void) { register_driver(&blk_ramdisk); } static __exit void blk_ramdisk_driver_exit(void) { unregister_driver(&blk_ramdisk); } driver_initcall(blk_ramdisk_driver_init); driver_exitcall(blk_ramdisk_driver_exit);
2.09375
2
2024-11-18T18:42:12.773785+00:00
2019-10-02T21:57:46
6f5790f263f04be66ecb2b7a9203b57d2f5607a2
{ "blob_id": "6f5790f263f04be66ecb2b7a9203b57d2f5607a2", "branch_name": "refs/heads/master", "committer_date": "2019-10-02T21:57:46", "content_id": "585ac68186cccc48bbed194799d4b4a085718084", "detected_licenses": [ "Unlicense" ], "directory_id": "cf66ae359417732c172597177769261b63cb17cc", "extension": "c", "filename": "maxnumber.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 135625201, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 654, "license": "Unlicense", "license_type": "permissive", "path": "/C/Introduction/maxnumber.c", "provenance": "stackv2-0030.json.gz:22758", "repo_name": "jerubball/HackerRank", "revision_date": "2019-10-02T21:57:46", "revision_id": "c484532d6e4cd57227d17f049df5dd754611f281", "snapshot_id": "fec45be53669d195c41d2edf0fbcb5eeb2f9de6f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jerubball/HackerRank/c484532d6e4cd57227d17f049df5dd754611f281/C/Introduction/maxnumber.c", "visit_date": "2021-06-12T11:05:07.408122" }
stackv2
#include <stdio.h> int sum_of_four (int a, int b, int c, int d); int max_of_four (int a, int b, int c, int d); /* * HackerRank C Introduction 4 * https://www.hackerrank.com/challenges/functions-in-c/problem * Author: Hasol */ int main() { int a, b, c, d; scanf ("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four (a, b, c, d); printf ("%d", ans); return 0; } int sum_of_four (int a, int b, int c, int d) { return a + b + c + d; } int max_of_four (int a, int b, int c, int d) { int max = a; if (max < b) max = b; if (max < c) max = c; if (max < d) max = d; return max; }
3.453125
3
2024-11-18T18:42:12.924379+00:00
2020-07-04T20:54:10
0323566e5c0de7b3332278271600b8f3aec29197
{ "blob_id": "0323566e5c0de7b3332278271600b8f3aec29197", "branch_name": "refs/heads/master", "committer_date": "2020-07-04T20:54:10", "content_id": "a2f932315ea707df91ff66f9c76c00ee97986f6c", "detected_licenses": [ "MIT" ], "directory_id": "fbd75a3173ef6b40a86ddf2cf2d8e0f079010315", "extension": "c", "filename": "threeAddressCode.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 109163247, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16944, "license": "MIT", "license_type": "permissive", "path": "/threeAddressCode.c", "provenance": "stackv2-0030.json.gz:23014", "repo_name": "andreluis034/compiladores", "revision_date": "2020-07-04T20:54:10", "revision_id": "9d9eb9017b8d917e147094518f07ce28701e5090", "snapshot_id": "324dff3389fa540811dcaafa183e96f4f7685bd1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andreluis034/compiladores/9d9eb9017b8d917e147094518f07ce28701e5090/threeAddressCode.c", "visit_date": "2021-03-16T11:02:08.066714" }
stackv2
#include <string.h> #include <stdlib.h> #include <stdio.h> #include "threeAddressCode.h" #define GET_T (tCount++) #define GET_LABEL (labelCount++) #define REGISTER_COUNT 32 #define ARG_REGISTER_START 4 #define STACK_POINTER 29 #define FRAME_POINTER 30 #define RETURN_ADDRESS 31 #define RETURN_REGISTER 2 #define GENERIC_REGISTER 8 unsigned int tCount = 0; unsigned int labelCount = 0; Register registers[REGISTER_COUNT] = {0}; Register registers_backup[REGISTER_COUNT] = {0}; char* registerNames[] = {"$zero","$at","$v0","$v1","$a0","$a1","$a2","$a3","$t0","$t1","$t2","$t3","$t4","$t5","$t6","$t7","$s0","$s1","$s2","$s3","$s4","$s5","$s6","$s7", "$t8", "$t9","$k0", "$k1", "$gp", "$sp", "$fp", "$ra"}; Scope* currentScope; makeTypeList(InstList*, makeInstList, Inst*) appendType(InstList*, appendInst, Inst*) prependType(InstList*, prependInst, Inst*) getType(Inst*, getInst, InstList*) concatType(InstList*, concatInst) void initializeRegisters() { int i; for(i = 0; i < REGISTER_COUNT; ++i) { registers[i].registerName = registerNames[i]; registers[i].registerNumber = i; registers[i].used = (i <= 7 || i >= 24) ? 1 : 0; registers[i].variableRepresented = NULL; } } InstSymbol* makeInstSymbolStr(char* str) { InstSymbol* i = (InstSymbol*) malloc(sizeof(InstSymbol)); i->type = S_STR; i->symbol.str = str; return i; } InstSymbol* makeInstSymbolInt(int integer) { InstSymbol* i = (InstSymbol*) malloc(sizeof(InstSymbol)); i->type = S_INT; i->symbol.number = integer; return i; } int getFreeRegister() { int i; int ret = -1; for(i = GENERIC_REGISTER; i < REGISTER_COUNT; ++i) { if(registers[i].used == 0) { if(registers[i].variableRepresented == NULL) { ret = i; break; } ret = i; } } registers[ret].variableRepresented = NULL; registers[i].used = 1; return ret; } int getFreeRegisterForVariable(char* varName, int* reused) { int i; int ret = -1; *reused = 0; for(i = GENERIC_REGISTER; i < REGISTER_COUNT; ++i) { if(registers[i].variableRepresented != NULL && strcmp(varName, registers[i].variableRepresented) == 0) { ret = i; *reused = 1; break; } if(registers[i].used == 0) { ret = i; if(registers[i].variableRepresented == NULL) { break; } } } registers[ret].variableRepresented = varName; registers[ret].used = 1; return ret; } //Declare that the register can be used for something else but we can still re use its value later void freeRegister(InstSymbol* symb) { int i; if(symb->symbol.str[1] == 'z' || symb->symbol.str[1] == 'a' || symb->symbol.str[1] == 'v') { return; } if(symb->type == S_INT) { printf("#TRYING TO FREE CONSTANT %d\n", symb->symbol.number); exit(-1); return; } for(i = 0; i < REGISTER_COUNT; ++i) { if(strcmp(symb->symbol.str, registers[i].registerName) == 0) { registers[i].used = 0; return; } } } InstSymbol* getNextSymbol(int reg) { //int reg = getRegisterForVariable(); //getUnusedRegister(); if(reg == -1) { printf("#COULD NOT GET ENOUGH REGISTERS\n"); exit(-1); } return makeInstSymbolStr(registers[reg].registerName); } InstSymbol* getLabel() { char* totallySafeBuffer = (char*) malloc(15); snprintf(totallySafeBuffer, 15, "LBL%d", GET_LABEL); return makeInstSymbolStr(totallySafeBuffer); } Pair* makePair(InstSymbol* symbol, InstList* list) { Pair* p = malloc(sizeof(Pair)); p->symbol = symbol; p->instructionList = list; return p; } Pair* makePairInt(int i, InstList* list) { return makePair(makeInstSymbolInt(i), list); } Pair* makePairStr(char* str, InstList* list) { return makePair(makeInstSymbolStr(str), list); } Inst* makeInstruction(InstType type, InstSymbol* s1, InstSymbol* s2, InstSymbol* s3) { Inst* inst = malloc(sizeof(Inst)); inst->type = type; inst->p1 = s1; inst->p2 = s2; inst->p3 = s3; return inst; } #define COMPILE_OPERATOR(ifORElseIF, op, enum) ifORElseIF(strcmp(operator, op) == 0) {\ Inst* inst = makeInstruction(enum, nextSymbol, left->symbol, right->symbol);\ requiredInstructions = appendInst(requiredInstructions, inst);\ } //NAKANAIDE IMA WA Pair* CompileExpression(char* operator, Pair* left, Pair* right) { if(left->symbol->type == S_STR) freeRegister(left->symbol); if(right->symbol->type == S_STR) freeRegister(right->symbol); InstSymbol* nextSymbol = getNextSymbol(getFreeRegister());//TODO: use one of the expressions InstList* requiredInstructions = concatInst(left->instructionList, right->instructionList); COMPILE_OPERATOR(if, "*", MUL) COMPILE_OPERATOR(else if, "/", DIV) COMPILE_OPERATOR(else if, "+", ADD) COMPILE_OPERATOR(else if, "-", SUB) COMPILE_OPERATOR(else if, "==", EQL) COMPILE_OPERATOR(else if, "||", OR) COMPILE_OPERATOR(else if, "&&", AND) COMPILE_OPERATOR(else if, "<",LESS) COMPILE_OPERATOR(else if, "<=",LESSEQ) COMPILE_OPERATOR(else if, ">",MORE) COMPILE_OPERATOR(else if, ">=",MOREEQ) return makePair(nextSymbol, requiredInstructions); } InstList* compileCmdList(CmdList* cmdlist) { InstList* instList = NULL; while(cmdlist != NULL) { instList = concatInst(instList, compileCommand(getCmd(cmdlist))); cmdlist = cmdlist->Next; } return instList; } Pair* loadVariable(char* varName) { int reuse = 0; Inst* inst = NULL; InstList* lw = EMPTY_LIST; Variable* variable = getVariableScope(currentScope, varName); if(variable == NULL) { printf("%s variable not found in the current scope\n", varName); exit(-1); } if(variable->location == registerr) { return makePair(getNextSymbol(variable->position.registerNumber + ARG_REGISTER_START), lw); } int reg = getFreeRegisterForVariable(varName, &reuse); InstSymbol* is = getNextSymbol(reg); if(reuse == 0) { inst = makeInstruction(LOAD_VARIABLE, is, makeInstSymbolStr("$fp"), makeInstSymbolInt( variable->position.stackOffset)); } lw = prependInst(lw, inst); return makePair(is, lw); } InstList* returnFunction() { InstList* instructionList = EMPTY_LIST; Inst* compiledInst; InstSymbol* symbol = getNextSymbol(STACK_POINTER); InstSymbol* symbol2 = getNextSymbol(FRAME_POINTER); //addi $sp $sp total_size compiledInst = makeInstruction(ADD, symbol, symbol, makeInstSymbolInt(currentScope->scope_size)); instructionList = appendInst(instructionList, compiledInst); //lw $ra -8($fp) compiledInst = makeInstruction(LOAD_VARIABLE, getNextSymbol(RETURN_ADDRESS), symbol2, makeInstSymbolInt(-8)); instructionList = appendInst(instructionList, compiledInst); //lw $fp -8($fp) compiledInst = makeInstruction(LOAD_VARIABLE, symbol2, symbol2, makeInstSymbolInt(-4)); instructionList = appendInst(instructionList, compiledInst); instructionList = appendInst(instructionList, makeInstruction(RETURN, NULL, NULL, NULL)); return instructionList; } InstList* activationFunctionRecord(Cmd* cmd) { InstList* instructionList = EMPTY_LIST; Inst* compiledInst; InstSymbol* symbol = getNextSymbol(STACK_POINTER); InstSymbol* symbol2 = getNextSymbol(FRAME_POINTER); currentScope = cmd->attr.func.scope; compiledInst = makeInstruction(LABEL, makeInstSymbolStr(cmd->attr.func.funcName), NULL, NULL); instructionList = appendInst(instructionList, compiledInst); //STACK ALLOCATION //addi $sp $sp -4 compiledInst = makeInstruction(ADD, symbol, symbol, makeInstSymbolInt(-4)); instructionList = appendInst(instructionList, compiledInst); //sw $fp 0($sp) compiledInst = makeInstruction(STORE_VARIABLE, symbol2, symbol, makeInstSymbolInt(0)); instructionList = appendInst(instructionList, compiledInst); //addi $fp $sp 4 compiledInst = makeInstruction(ADD, symbol2, symbol, makeInstSymbolInt(4)); instructionList = appendInst(instructionList, compiledInst); //addi $sp $sp -(scope_size - 4) compiledInst = makeInstruction(ADD, symbol, symbol, makeInstSymbolInt(-cmd->attr.func.scope->scope_size + 4)); instructionList = appendInst(instructionList, compiledInst); //sw $ra -8($fp) compiledInst = makeInstruction(STORE_VARIABLE, getNextSymbol(RETURN_ADDRESS), symbol2, makeInstSymbolInt(-8)); instructionList = appendInst(instructionList, compiledInst); return instructionList; } InstList* storeCompiledExpression(Pair* expr, char* varName) //TODO update register { Inst* compiledInst = NULL; InstList* instructionList = expr->instructionList; Variable* variable = getVariableScope(currentScope, varName); if(variable == NULL) { printf("%s variable not found in the current scope\n", varName); exit(-1); } if(variable->location == registerr) { compiledInst = makeInstruction(ADD, getNextSymbol(variable->position.registerNumber + ARG_REGISTER_START), getNextSymbol(0), expr->symbol); } else { compiledInst = makeInstruction(STORE_VARIABLE, expr->symbol, getNextSymbol(FRAME_POINTER), makeInstSymbolInt(variable->position.stackOffset)); } instructionList = appendInst(instructionList, compiledInst); return instructionList; } InstList* saveUsedRegisters() { InstList* instructionList = EMPTY_LIST; int i; memcpy(registers_backup, registers, sizeof(registers)); for(i = 1; i < REGISTER_COUNT; ++i) { if(registers[i].used == 1 && !(i <= 3 || i >= 24)) { if((i >= 4 && i <= 7 && currentScope->argument_registers + ARG_REGISTER_START - 1 >= i) || i > 7 ) { instructionList = appendInst(instructionList, makeInstruction(PUSH, getNextSymbol(registers[i].registerNumber), NULL, NULL)); } } registers[i].used = (i <= 3 || i >= 24) ? 1 : 0; registers[i].variableRepresented = NULL; } return instructionList; } InstList* restoreRegisters() { InstList* instructionList = EMPTY_LIST; int i; memcpy(registers, registers_backup, sizeof(registers)); for(i = (REGISTER_COUNT - 1); i >= 1; --i) { if(registers[i].used == 1 && !(i <= 3 || i >= 24)) { if((i >= 4 && i <= 7 && currentScope->argument_registers + ARG_REGISTER_START - 1 >= i) || i > 7 ) { instructionList = appendInst(instructionList, makeInstruction(POP, getNextSymbol(registers[i].registerNumber), NULL, NULL)); } } else if(!(i <= 3 || i >= 24)) { registers[i].variableRepresented = NULL; } } return instructionList; } InstList* compileCommand(Cmd* cmd) { if(cmd == NULL) return EMPTY_LIST; ExprList* exprlist; InstList* instructionList = EMPTY_LIST; Pair* compiledExpr; Pair* var; int regCount = 0; int argsPushedToStack = 0; InstSymbol* symbol; InstSymbol* symbol2; Inst* compiledInst; InstList* lastInsts = NULL; InstSymbol* exitif; Variable* variable; char op[2]; switch(cmd->kind) { case C_DECLARATION: compiledExpr = makePairExpr(cmd->attr.declaration.expr); instructionList = storeCompiledExpression(compiledExpr, cmd->attr.declaration.variable->attr.variable); if(compiledExpr->symbol->type == S_STR) freeRegister(compiledExpr->symbol); break; case C_INCREMENT: var = makePairExpr(cmd->attr.increment.variable); //compiledExpr = makePairExpr(cmd->attr.increment.) if(strcmp(cmd->attr.increment.operator, "++") == 0 || strcmp(cmd->attr.increment.operator, "--") == 0) { compiledExpr = makePairInt(1, NULL); } else { compiledExpr = makePairExpr(cmd->attr.increment.expr); } op[0] = cmd->attr.increment.operator[0]; op[1] = 0; compiledExpr = CompileExpression(op, var, compiledExpr); instructionList = storeCompiledExpression(compiledExpr, cmd->attr.increment.variable->attr.variable); if(compiledExpr->symbol->type == S_STR) freeRegister(compiledExpr->symbol); //appendInst(makeInstruction(ADD,)) break; case C_FOR: //inst inicial instructionList = compileCommand(cmd->attr.forCmd.initial); //instructionList = appendInst(instructionList,compiledInst); //LABEL symbol = getLabel(); instructionList = appendInst(instructionList,makeInstruction(LABEL,symbol,NULL,NULL)); //TEST compiledExpr = makePairExpr(cmd->attr.forCmd.condition); instructionList = concatList(instructionList,compiledExpr->instructionList); //BRANCH_EQ_ZERO exitif = getLabel(); instructionList = appendInst(instructionList, makeInstruction(BRANCH_EQ_ZERO, compiledExpr->symbol, exitif, NULL)); freeRegister(compiledExpr->symbol); //CMDLIST instructionList = concatInst(instructionList,compileCmdList(cmd->attr.forCmd.body)); //INST instructionList = concatInst(instructionList,compileCommand(cmd->attr.forCmd.afterIteration)); //GOTO LABEL instructionList = appendInst(instructionList,makeInstruction(GOTO,symbol,NULL,NULL)); //LABEL1 instructionList = appendInst(instructionList,makeInstruction(LABEL,exitif,NULL,NULL)); break; case C_IF_ELSE: //Compile expression compiledExpr = makePairExpr(cmd->attr.ifelse.condition); instructionList = compiledExpr->instructionList; symbol = getLabel(); exitif = getLabel(); //TEST instructionList = appendInst(instructionList, makeInstruction(BRANCH_EQ_ZERO, compiledExpr->symbol, symbol, NULL)); freeRegister(compiledExpr->symbol); //IFTRUE instructionList = concatInst(instructionList, compileCmdList(cmd->attr.ifelse.iftrue)); instructionList = appendInst(instructionList, makeInstruction(GOTO, exitif, NULL, NULL)); //EXIT //IFFALSE instructionList = appendInst(instructionList, makeInstruction(LABEL, symbol, NULL, NULL)); instructionList = concatInst(instructionList, compileCmdList(cmd->attr.ifelse.iffalse)); //FINISH instructionList = appendInst(instructionList, makeInstruction(LABEL, exitif, NULL, NULL)); break; case C_FUNC: instructionList = activationFunctionRecord(cmd); //Normal function operation instructionList = concatInst(instructionList, compileCmdList(cmd->attr.func.commandList)); instructionList = concatInst(instructionList, returnFunction()); currentScope = NULL; break; case C_FUNC_CALL: //TODO save used registers instructionList = saveUsedRegisters(); if(strcmp(cmd->attr.funcCall.funcName, "fmt.scan") == 0) { lastInsts = storeCompiledExpression(makePairStr(registers[RETURN_REGISTER].registerName, EMPTY_LIST), getExpr(cmd->attr.funcCall.variables)->attr.variable); } else { exprlist = cmd->attr.funcCall.variables; while(exprlist != NULL) { compiledExpr = makePairExpr(getExpr(exprlist)); if(regCount < ARG_REGISTER_COUNT) { compiledInst = makeInstruction(LOAD_ARGUMENT_REGISTER, getNextSymbol(regCount + ARG_REGISTER_START), compiledExpr->symbol, NULL); regCount++; } else { argsPushedToStack++; compiledInst = makeInstruction(LOAD_ARGUMENT_STACK, compiledExpr->symbol, NULL, NULL); } instructionList = concatList(instructionList, compiledExpr->instructionList); instructionList = appendInst(instructionList, compiledInst); if(compiledExpr->symbol->type == S_STR) freeRegister(compiledExpr->symbol); exprlist = exprlist->Next; } } compiledInst = makeInstruction(FUNC_CALL, makeInstSymbolStr(cmd->attr.funcCall.funcName), NULL, NULL ); instructionList = appendInst(instructionList, compiledInst); if(lastInsts != NULL) { instructionList = concatList(instructionList, lastInsts); } if(argsPushedToStack > 0 ){ compiledInst = makeInstruction(ADD, getNextSymbol(STACK_POINTER), getNextSymbol(STACK_POINTER), makeInstSymbolInt(argsPushedToStack * 4) ); instructionList = appendInst(instructionList, compiledInst); } instructionList = concatList(instructionList, restoreRegisters()); break; case C_RETURN: if(cmd->attr._return.value != NULL) { compiledExpr = makePairExpr(cmd->attr._return.value); instructionList = compiledExpr->instructionList; compiledInst = makeInstruction(ADD, getNextSymbol(RETURN_REGISTER), getNextSymbol(0), compiledExpr->symbol); instructionList = appendInst(instructionList, compiledInst); if(compiledExpr->symbol->type == S_STR) freeRegister(compiledExpr->symbol); } instructionList = concatInst(instructionList, returnFunction()); break; case C_FUNC_RETURN: instructionList = compileCommand(cmd->attr.funcReturn.funcCall); instructionList = concatInst(instructionList, storeCompiledExpression(makePairStr(registers[RETURN_REGISTER].registerName, EMPTY_LIST), cmd->attr.funcReturn.variable->attr.variable)); break; } return instructionList; } /* E_INTEGER, E_OPERATION, E_VARIABLE,*/ Pair* makePairExpr(Expr* expr) { Pair* p1; Pair* p2; switch(expr->kind) { case E_BOOL: case E_INTEGER: return makePairInt(expr->attr.value, NULL); case E_VARIABLE: return loadVariable(expr->attr.variable);// makePairStr(expr->attr.variable, NULL); case E_OPERATION: p1 = makePairExpr(expr->attr.op.left); p2 = makePairExpr(expr->attr.op.right); return CompileExpression(expr->attr.op.operator, p1, p2); default: printf("YOU FORGOT SOMETHING IDIOT type: %d\n", expr->kind); //TODO REMOVE return NULL; } return NULL; }
2.265625
2
2024-11-18T18:42:13.008738+00:00
2023-02-16T11:27:40
411355b9f198aee1628d4777d16cdd11971fd3c1
{ "blob_id": "411355b9f198aee1628d4777d16cdd11971fd3c1", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T14:59:16", "content_id": "fdb4d05bbe7032e65bfe79744c223e203677838a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493", "extension": "h", "filename": "intel_adsp_ipc.h", "fork_events_count": 32, "gha_created_at": "2016-08-05T22:14:50", "gha_event_created_at": "2022-04-05T17:14:07", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 65052293, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6008, "license": "Apache-2.0", "license_type": "permissive", "path": "/soc/xtensa/intel_adsp/common/include/intel_adsp_ipc.h", "provenance": "stackv2-0030.json.gz:23143", "repo_name": "intel/zephyr", "revision_date": "2023-02-16T11:27:40", "revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee", "snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7", "src_encoding": "UTF-8", "star_events_count": 32, "url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/soc/xtensa/intel_adsp/common/include/intel_adsp_ipc.h", "visit_date": "2023-09-04T00:20:35.217393" }
stackv2
/* Copyright (c) 2022 Intel Corporation * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_INTEL_ADSP_IPC_H #define ZEPHYR_INCLUDE_INTEL_ADSP_IPC_H #include <intel_adsp_ipc_devtree.h> #include <zephyr/kernel.h> #include <zephyr/device.h> struct intel_adsp_ipc_config { volatile struct intel_adsp_ipc *regs; }; /** * @brief Intel ADSP IPC Message Handler Callback. * * This function, once registered via intel_adsp_ipc_set_message_handler(), * is invoked in interrupt context to service messages sent from the * foreign/connected IPC context. The message contents of the TDR and * TDD registers are provided in the data/ext_data argument. * * The function should return true if processing of the message is * complete and return notification to the other side (via the TDA * register) is desired immediately. Returning false means that no * return "DONE" interrupt will occur until intel_adsp_ipc_complete() is * called on this device at some point in the future. * * @note Further messages on the link will not be transmitted or * received while an in-progress message remains incomplete! * * @param dev IPC device. * @param arg Registered argument from intel_adsp_ipc_set_message_handler(). * @param data Message data from other side (low bits of TDR register). * @param ext_dat Extended message data (TDD register). * @return true if the message is completely handled. */ typedef bool (*intel_adsp_ipc_handler_t)(const struct device *dev, void *arg, uint32_t data, uint32_t ext_data); /** * @brief Intel ADSP IPC Message Complete Callback. * * This function, once registered via intel_adsp_ipc_set_done_handler(), is * invoked in interrupt context when a "DONE" return interrupt is * received from the other side of the connection (indicating that a * previously sent message is finished processing). * * @note On Intel ADSP hardware the DONE interrupt is transmitted * synchronously with the interrupt being cleared on the remote * device. It is not possible to delay processing. This callback * will still occur, but protocols which rely on notification of * asynchronous command processing will need modification. * * @param dev IPC device. * @param arg Registered argument from intel_adsp_ipc_set_done_handler(). * @return True if IPC completion will be done externally, otherwise false. * @note Returning True will cause this API to skip writing IPC registers * signalling IPC message completion and those actions should be done by * external code manually. Returning false from the handler will perform * writing to IPC registers signalling message completion normally by this API. */ typedef bool (*intel_adsp_ipc_done_t)(const struct device *dev, void *arg); struct intel_adsp_ipc_data { struct k_sem sem; struct k_spinlock lock; intel_adsp_ipc_handler_t handle_message; void *handler_arg; intel_adsp_ipc_done_t done_notify; void *done_arg; bool tx_ack_pending; }; void z_intel_adsp_ipc_isr(const void *devarg); /** * @brief Register message callback handler. * * This function registers a handler function for received messages. * * @param dev IPC device. * @param fn Callback function. * @param arg Value to pass as the "arg" parameter to the function. */ void intel_adsp_ipc_set_message_handler(const struct device *dev, intel_adsp_ipc_handler_t fn, void *arg); /** * @brief Register done callback handler. * * This function registers a handler function for message completion * notifications. * * @param dev IPC device. * @param fn Callback function. * @param arg Value to pass as the "arg" parameter to the function. */ void intel_adsp_ipc_set_done_handler(const struct device *dev, intel_adsp_ipc_done_t fn, void *arg); /** @brief Initialize Intel ADSP IPC device. * * Initialize the device. Must be called before any API calls or * interrupts can be serviced. * * @param dev IPC device. * @return Zero on success, negative codes for error. */ int intel_adsp_ipc_init(const struct device *dev); /** @brief Complete an in-progress message. * * Notify the other side that the current in-progress message is * complete. This is a noop if no message is in progress. * * @note Further messages on the link will not be transmitted or * received while an in-progress message remains incomplete! * * @param dev IPC device. */ void intel_adsp_ipc_complete(const struct device *dev); /** @brief Message-in-progress predicate. * * Returns false if a message has been received but not yet completed * via intel_adsp_ipc_complete(), true otherwise. * * @param dev IPC device. * @return True if no message is in progress. */ bool intel_adsp_ipc_is_complete(const struct device *dev); /** @brief Send an IPC message. * * Sends a message to the other side of an IPC link. The data and * ext_data parameters are passed using the IDR/IDD registers. * Returns true if the message was sent, false if a current message is * in progress (in the sense of intel_adsp_ipc_is_complete()). * * @param dev IPC device. * @param data 30 bits value to transmit with the message (IDR register). * @param ext_data Extended value to transmit with the message (IDD register). * @return message successfully transmitted. */ bool intel_adsp_ipc_send_message(const struct device *dev, uint32_t data, uint32_t ext_data); /** @brief Send an IPC message, block until completion. * * As for intel_adsp_ipc_send_message(), but blocks the current thread until * the completion of the message or the expiration of the provided * timeout. * * @param dev IPC device * @param data 30 bits value to transmit with the message (IDR register) * @param ext_data Extended value to transmit with the message (IDD register) * @param timeout Maximum time to wait, or K_FOREVER, or K_NO_WAIT * @return message successfully transmitted */ bool intel_adsp_ipc_send_message_sync(const struct device *dev, uint32_t data, uint32_t ext_data, k_timeout_t timeout); #endif /* ZEPHYR_INCLUDE_INTEL_ADSP_IPC_H */
2.28125
2
2024-11-18T18:42:13.234079+00:00
2023-07-28T09:51:36
1d86a92c9e1cd2214e037ea7d027d5bc5364dd03
{ "blob_id": "1d86a92c9e1cd2214e037ea7d027d5bc5364dd03", "branch_name": "refs/heads/master", "committer_date": "2023-07-28T09:51:36", "content_id": "a3a6470897de1a5c7fc93dfa4a4d4e9acac6f6f5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "de6cbe04a0e00fbe83ea20a7cab8f85ad36831fe", "extension": "h", "filename": "gost_grasshopper_cipher.h", "fork_events_count": 220, "gha_created_at": "2015-08-13T17:30:16", "gha_event_created_at": "2023-06-14T14:55:01", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 40672482, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4060, "license": "Apache-2.0", "license_type": "permissive", "path": "/gost_grasshopper_cipher.h", "provenance": "stackv2-0030.json.gz:23399", "repo_name": "gost-engine/engine", "revision_date": "2023-07-28T09:51:36", "revision_id": "2a8a5e0ecaa3e3d6f4ec722a49aa72476755c2b7", "snapshot_id": "0d152b12ad8dfd63a3981cd2ccd3e84e354263f4", "src_encoding": "UTF-8", "star_events_count": 336, "url": "https://raw.githubusercontent.com/gost-engine/engine/2a8a5e0ecaa3e3d6f4ec722a49aa72476755c2b7/gost_grasshopper_cipher.h", "visit_date": "2023-09-05T17:46:34.716570" }
stackv2
/* * Maxim Tishkov 2016 * This file is distributed under the same license as OpenSSL */ #ifndef GOST_GRASSHOPPER_CIPHER_H #define GOST_GRASSHOPPER_CIPHER_H #define SN_kuznyechik_mgm "kuznyechik-mgm" #if defined(__cplusplus) extern "C" { #endif #include "gost_grasshopper_defines.h" #include "gost_lcl.h" #include <openssl/evp.h> // not thread safe // because of buffers typedef struct { uint8_t type; grasshopper_key_t master_key; grasshopper_key_t key; grasshopper_round_keys_t encrypt_round_keys; grasshopper_round_keys_t decrypt_round_keys; grasshopper_w128_t buffer; } gost_grasshopper_cipher_ctx; typedef struct { gost_grasshopper_cipher_ctx c; grasshopper_w128_t partial_buffer; unsigned int section_size; /* After how much bytes mesh the key, if 0 never mesh and work like plain ctr. */ unsigned char kdf_seed[8]; unsigned char tag[16]; EVP_MD_CTX *omac_ctx; } gost_grasshopper_cipher_ctx_ctr; static void gost_grasshopper_cipher_key(gost_grasshopper_cipher_ctx* c, const uint8_t* k); static void gost_grasshopper_cipher_destroy(gost_grasshopper_cipher_ctx* c); static int gost_grasshopper_cipher_init_ecb(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_cbc(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_ofb(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_cfb(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_ctr(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_ctracpkm(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_ctracpkm_omac(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init_mgm(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_init(EVP_CIPHER_CTX* ctx, const unsigned char* key, const unsigned char* iv, int enc); static int gost_grasshopper_cipher_do(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_ecb(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_cbc(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_ofb(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_cfb(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_ctr(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_ctracpkm(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_ctracpkm_omac(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_do_mgm(EVP_CIPHER_CTX* ctx, unsigned char* out, const unsigned char* in, size_t inl); static int gost_grasshopper_cipher_cleanup(EVP_CIPHER_CTX* ctx); static int gost_grasshopper_mgm_cleanup(EVP_CIPHER_CTX *c); static int gost_grasshopper_set_asn1_parameters(EVP_CIPHER_CTX* ctx, ASN1_TYPE* params); static int gost_grasshopper_get_asn1_parameters(EVP_CIPHER_CTX* ctx, ASN1_TYPE* params); static int gost_grasshopper_cipher_ctl(EVP_CIPHER_CTX* ctx, int type, int arg, void* ptr); static int gost_grasshopper_mgm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr); const EVP_CIPHER* cipher_gost_grasshopper_ctracpkm(); #if defined(__cplusplus) } #endif #endif
2
2
2024-11-18T18:42:14.168070+00:00
2018-05-07T12:46:49
7fa2eff973ce9380194a0005a1ce6046fd6f1ac3
{ "blob_id": "7fa2eff973ce9380194a0005a1ce6046fd6f1ac3", "branch_name": "refs/heads/master", "committer_date": "2018-05-07T12:46:49", "content_id": "1c14c4c892ca9a371bdcf7a1e48c256a98c60b0b", "detected_licenses": [ "MIT" ], "directory_id": "5282e06b246dcc6e9dbf67a777592bb16beb8bf4", "extension": "c", "filename": "2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 132457701, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 609, "license": "MIT", "license_type": "permissive", "path": "/5/2.c", "provenance": "stackv2-0030.json.gz:23527", "repo_name": "codelegant/c-primer-plus", "revision_date": "2018-05-07T12:46:49", "revision_id": "a23d2716d26c22d797e3eae1855be08b13a80c46", "snapshot_id": "40f352596cb0987e65e68496912b01a51dd1f75c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/codelegant/c-primer-plus/a23d2716d26c22d797e3eae1855be08b13a80c46/5/2.c", "visit_date": "2020-03-16T02:08:21.049139" }
stackv2
#include <stdio.h> int main(void) { const float CROP = 1E15; const unsigned short SQUARES = 64; double current; double total; short count = 1; printf("square grains total "); printf("fraction of "); printf(" added grain "); printf("US total\n"); total = current = 1.0; printf("%4d %13.2e %12e %12.2e\n",count, current, total, total/CROP); while(count < SQUARES) { count=count + 1; current = 2.0 * current; total=total + current; printf("%4d %13.2e %12e %12.2e\n",count, current, total, total/CROP); } printf("That's all.\n"); return 0; }
3
3
2024-11-18T18:42:14.357906+00:00
2022-06-21T17:03:13
7eae16609948bc78ea502acca1ef3401432d940f
{ "blob_id": "7eae16609948bc78ea502acca1ef3401432d940f", "branch_name": "refs/heads/master", "committer_date": "2022-06-28T19:49:43", "content_id": "eaa14d96fa9eb730865fa41ad56a270f67007a43", "detected_licenses": [], "directory_id": "00b3f5c7b5763c7b7dfec3d6beb35d534cb1f4f0", "extension": "c", "filename": "pomp_msg.c", "fork_events_count": 12, "gha_created_at": "2015-08-05T16:51:58", "gha_event_created_at": "2023-03-24T12:50:11", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 40257358, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9705, "license": "", "license_type": "permissive", "path": "/src/pomp_msg.c", "provenance": "stackv2-0030.json.gz:23783", "repo_name": "Parrot-Developers/libpomp", "revision_date": "2022-06-21T17:03:13", "revision_id": "702a5c37770ad5cebab097acddceb722782a7a5e", "snapshot_id": "f9b43e8de0e5793cbd496f5a718dcfd5e3b5c544", "src_encoding": "UTF-8", "star_events_count": 22, "url": "https://raw.githubusercontent.com/Parrot-Developers/libpomp/702a5c37770ad5cebab097acddceb722782a7a5e/src/pomp_msg.c", "visit_date": "2023-04-03T15:34:33.733743" }
stackv2
/** * @file pomp_msg.c * * @brief Handle formating/decoding of messages * * @author [email protected] * * Copyright (c) 2014 Parrot S.A. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Parrot Company 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 PARROT COMPANY 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. * */ #include "pomp_priv.h" /* * See documentation in public header. */ struct pomp_msg *pomp_msg_new(void) { struct pomp_msg *msg = NULL; /* Allocate message structure */ msg = calloc(1, sizeof(*msg)); if (msg == NULL) return NULL; return msg; } /* * See documentation in public header. */ struct pomp_msg *pomp_msg_new_copy(const struct pomp_msg *msg) { struct pomp_msg *newmsg = NULL; POMP_RETURN_VAL_IF_FAILED(msg != NULL, -EINVAL, NULL); /* Allocate message structure */ newmsg = calloc(1, sizeof(*newmsg)); if (newmsg == NULL) goto error; newmsg->msgid = msg->msgid; newmsg->finished = msg->finished; /* Copy buffer */ if (msg->buf != NULL) { newmsg->buf = pomp_buffer_new_copy(msg->buf); if (newmsg->buf == NULL) goto error; } return newmsg; /* Cleanup in case of error */ error: if (newmsg != NULL) { if (newmsg->buf != NULL) pomp_buffer_unref(newmsg->buf); free(newmsg); } return NULL; } /* * See documentation in public header. */ struct pomp_msg *pomp_msg_new_with_buffer(struct pomp_buffer *buf) { struct pomp_msg *msg = NULL; size_t pos = 0; uint32_t d = 0; POMP_RETURN_VAL_IF_FAILED(buf != NULL, -EINVAL, NULL); /* Allocate message structure */ msg = calloc(1, sizeof(*msg)); if (msg == NULL) goto error; /* Get a new ref on buffer */ msg->finished = 1; msg->buf = buf; pomp_buffer_ref(buf); /* Make sure header is valid */ if (msg->buf->len < POMP_PROT_HEADER_SIZE) { POMP_LOGW("Bad header size: %u", (uint32_t)msg->buf->len); goto error; } /* Check magic */ (void)pomp_buffer_read(msg->buf, &pos, &d, sizeof(d)); if (POMP_LE32TOH(d) != POMP_PROT_HEADER_MAGIC) { POMP_LOGW("Bad header magic: %08x(%08x)", POMP_LE32TOH(d), POMP_PROT_HEADER_MAGIC); goto error; } /* Message id */ (void)pomp_buffer_read(msg->buf, &pos, &d, sizeof(d)); msg->msgid = POMP_LE32TOH(d); /* Check message size */ (void)pomp_buffer_read(msg->buf, &pos, &d, sizeof(d)); if (POMP_LE32TOH(d) != buf->len) { POMP_LOGW("Bad message size: %08x(%08x)", (uint32_t)buf->len, POMP_LE32TOH(d)); goto error; } return msg; /* Cleanup in case of error */ error: if (msg != NULL) { if (msg->buf != NULL) pomp_buffer_unref(msg->buf); free(msg); } return NULL; } /* * See documentation in public header. */ int pomp_msg_destroy(struct pomp_msg *msg) { POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); (void)pomp_msg_clear(msg); free(msg); return 0; } /* * See documentation in public header. */ int pomp_msg_init(struct pomp_msg *msg, uint32_t msgid) { POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); POMP_RETURN_ERR_IF_FAILED(msg->buf == NULL, -EPERM); msg->msgid = msgid; msg->finished = 0; /* Allocate new buffer */ msg->buf = pomp_buffer_new(0); if (msg->buf == NULL) return -ENOMEM; return 0; } /* * See documentation in public header. */ int pomp_msg_finish(struct pomp_msg *msg) { int res = 0; size_t pos = 0; uint32_t d = 0; POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); POMP_RETURN_ERR_IF_FAILED(msg->buf != NULL, -EINVAL); POMP_RETURN_ERR_IF_FAILED(!msg->finished, -EINVAL); /* Make sure we will be able to write header */ res = pomp_buffer_ensure_capacity(msg->buf, POMP_PROT_HEADER_SIZE); if (res < 0) return res; /* Below writes should not fail because allocation is ok */ /* Magic */ (void)pomp_buffer_writeb(msg->buf, &pos, POMP_PROT_HEADER_MAGIC_0); (void)pomp_buffer_writeb(msg->buf, &pos, POMP_PROT_HEADER_MAGIC_1); (void)pomp_buffer_writeb(msg->buf, &pos, POMP_PROT_HEADER_MAGIC_2); (void)pomp_buffer_writeb(msg->buf, &pos, POMP_PROT_HEADER_MAGIC_3); /* Message id */ d = POMP_HTOLE32(msg->msgid); (void)pomp_buffer_write(msg->buf, &pos, &d, sizeof(d)); /* Message size (make sure we have at least the header size in * case no payload was written in buffer) */ if (msg->buf->len < POMP_PROT_HEADER_SIZE) d = POMP_HTOLE32(POMP_PROT_HEADER_SIZE); else d = POMP_HTOLE32((uint32_t)msg->buf->len); (void)pomp_buffer_write(msg->buf, &pos, &d, sizeof(d)); /* Message can not be modified anymore */ msg->finished = 1; return 0; } /* * See documentation in public header. */ int pomp_msg_clear(struct pomp_msg *msg) { POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); msg->msgid = 0; msg->finished = 0; /* Release buffer */ if (msg->buf != NULL) pomp_buffer_unref(msg->buf); msg->buf = NULL; return 0; } /* * See documentation in public header. */ uint32_t pomp_msg_get_id(const struct pomp_msg *msg) { POMP_RETURN_VAL_IF_FAILED(msg != NULL, -EINVAL, 0); return msg->msgid; } /* * See documentation in public header. */ struct pomp_buffer *pomp_msg_get_buffer(const struct pomp_msg *msg) { POMP_RETURN_VAL_IF_FAILED(msg != NULL, -EINVAL, NULL); return msg->buf; } /* * See documentation in public header. */ int pomp_msg_write(struct pomp_msg *msg, uint32_t msgid, const char *fmt, ...) { int res = 0; va_list args; va_start(args, fmt); res = pomp_msg_writev(msg, msgid, fmt, args); va_end(args); return res; } /* * See documentation in public header. */ int pomp_msg_writev(struct pomp_msg *msg, uint32_t msgid, const char *fmt, va_list args) { int res = 0; struct pomp_encoder enc = POMP_ENCODER_INITIALIZER; POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); /* Initialize message */ res = pomp_msg_init(msg, msgid); if (res < 0) goto out; /* Setup encoder */ res = pomp_encoder_init(&enc, msg); if (res < 0) goto out; /* Encode message */ res = pomp_encoder_writev(&enc, fmt, args); if (res < 0) goto out; /* Finish it */ res = pomp_msg_finish(msg); if (res < 0) goto out; out: /* Cleanup */ (void)pomp_encoder_clear(&enc); return res; } /* * See documentation in public header. */ int pomp_msg_write_argv(struct pomp_msg *msg, uint32_t msgid, const char *fmt, int argc, const char * const *argv) { int res = 0; struct pomp_encoder enc = POMP_ENCODER_INITIALIZER; POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); /* Initialize message */ res = pomp_msg_init(msg, msgid); if (res < 0) goto out; /* Setup encoder */ res = pomp_encoder_init(&enc, msg); if (res < 0) goto out; /* Encode message */ res = pomp_encoder_write_argv(&enc, fmt, argc, argv); if (res < 0) goto out; /* Finish it */ res = pomp_msg_finish(msg); if (res < 0) goto out; out: /* Cleanup */ (void)pomp_encoder_clear(&enc); return res; } /* * See documentation in public header. */ int pomp_msg_read(const struct pomp_msg *msg, const char *fmt, ...) { int res = 0; va_list args; va_start(args, fmt); res = pomp_msg_readv(msg, fmt, args); va_end(args); return res; } /* * See documentation in public header. */ int pomp_msg_readv(const struct pomp_msg *msg, const char *fmt, va_list args) { int res = 0; struct pomp_decoder dec = POMP_DECODER_INITIALIZER; POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); res = pomp_decoder_init(&dec, msg); if (res == 0) res = pomp_decoder_readv(&dec, fmt, args); /* Always clear decoder, even in case of error during decoding */ (void)pomp_decoder_clear(&dec); return res; } /* * See documentation in public header. */ int pomp_msg_dump(const struct pomp_msg *msg, char *dst, uint32_t maxdst) { int res = 0; struct pomp_decoder dec = POMP_DECODER_INITIALIZER; POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); res = pomp_decoder_init(&dec, msg); if (res == 0) res = pomp_decoder_dump(&dec, dst, maxdst); /* Always clear decoder, even in case of error during dump */ (void)pomp_decoder_clear(&dec); return res; } /* * See documentation in public header. */ int pomp_msg_adump(const struct pomp_msg *msg, char **dst) { int res = 0; struct pomp_decoder dec = POMP_DECODER_INITIALIZER; POMP_RETURN_ERR_IF_FAILED(msg != NULL, -EINVAL); POMP_RETURN_ERR_IF_FAILED(dst != NULL, -EINVAL); *dst = NULL; res = pomp_decoder_init(&dec, msg); if (res == 0) res = pomp_decoder_adump(&dec, dst); /* Always clear decoder, even in case of error during dump */ (void)pomp_decoder_clear(&dec); return res; }
2.21875
2
2024-11-18T18:42:14.440145+00:00
2018-05-11T02:59:46
df43a6ee623db44ac403ec16c6d7a9563542f1f4
{ "blob_id": "df43a6ee623db44ac403ec16c6d7a9563542f1f4", "branch_name": "refs/heads/master", "committer_date": "2018-05-11T02:59:46", "content_id": "e1e893e0348a1665446407ec294d87401a91a61d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e2312fcfbc2bdd1cb3895e0773d226e8c78aa585", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 132974831, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1923, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/test.c", "provenance": "stackv2-0030.json.gz:23911", "repo_name": "0x5446/demo-ip2location-c", "revision_date": "2018-05-11T02:59:46", "revision_id": "5cd1ccd8a35a1d9b278a3295bf9a167d11f14c5b", "snapshot_id": "863fe800ad64bc09ab2f7a0454fbfab38361f34b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/0x5446/demo-ip2location-c/5cd1ccd8a35a1d9b278a3295bf9a167d11f14c5b/src/test.c", "visit_date": "2020-03-16T20:50:35.320257" }
stackv2
// 全世界的ip库,都是分段的,比如有如下存储于文件的ip数据: // 10.111.1.3 10.111.5.8 北京市海淀区 表示从10.111.1.3开始到10.111.5.8结束的ip,其对应的地域信息都是北京市海淀区。 // 这样的数据大约有几百万条。 // 设计相应的数据结构,以及数据存储方式。 // 编写根据ip查找对应地域信息的函数。 // 即:String findIpLocation(String ip) #include <stdio.h> #include <assert.h> #include <math.h> #include <memory.h> #define DATA "ip.dat" //sorted file by iprange, entry: size_t(64bit iprange)+string(64bit location) #define ENTRY_SIZE 72 #define IP_SIZE 4 #define IPRANGE_SIZE 8 #define LOCATION_SIZE 64 #define ENTRY_COUNT 445065 unsigned int ip2int(char *ip) { unsigned char a, b, c, d; sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d); return (unsigned int)((a << 24) | (b << 16) | (c << 8) | d); } int int2ip(char *ipString, unsigned int ip) { unsigned char a, b, c, d; a = (unsigned char)(ip >> 24 & 0x000000FF); b = (unsigned char)(ip >> 16 & 0x000000FF); c = (unsigned char)(ip >> 8 & 0x000000FF); d = (unsigned char)(ip & 0x000000FF); snprintf(ipString, 16, "%hhu.%hhu.%hhu.%hhu", a, b, c, d); } int main(unsigned int argc, char *argv[]) { FILE *fp = fopen(DATA, "rb"); char buff[ENTRY_SIZE + 1], leftStr[16], rightStr[16]; unsigned int left, right; size_t n, pos; do { n = fread(buff, ENTRY_SIZE, 1, fp); if (n != 1) { break; } pos = ftell(fp); buff[ENTRY_SIZE] = '\0'; left = *((unsigned int *)buff); right = *((unsigned int *)&buff[IP_SIZE]); int2ip(leftStr, left); int2ip(rightStr, right); printf("%u: %s; %s(%u) ~ %s(%u)\n", pos, &buff[IPRANGE_SIZE], leftStr, left, rightStr, right); } while (n == 1); fclose(fp); return 0; }
2.6875
3
2024-11-18T18:42:14.581245+00:00
2021-06-10T14:06:32
d847ff80bc9143f6e128cf9b5da54fc79e155e98
{ "blob_id": "d847ff80bc9143f6e128cf9b5da54fc79e155e98", "branch_name": "refs/heads/main", "committer_date": "2021-06-10T14:06:32", "content_id": "2106e5ccaf2e7421e68b228604dbd49ef4299b6c", "detected_licenses": [ "MIT" ], "directory_id": "6fef84757834f436f13c81895e6a7ae8edadfca1", "extension": "c", "filename": "sleeping.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 375702426, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 162, "license": "MIT", "license_type": "permissive", "path": "/tech/plugins_components/plcomp00/examples/sleeping.c", "provenance": "stackv2-0030.json.gz:24040", "repo_name": "phantas/phantas.github.io", "revision_date": "2021-06-10T14:06:32", "revision_id": "916ca72d3da6e5b7d26e4f4dc1385669d36e05ab", "snapshot_id": "a852df532fd70a5c7b9eba9f135f45f6e88adb76", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/phantas/phantas.github.io/916ca72d3da6e5b7d26e4f4dc1385669d36e05ab/tech/plugins_components/plcomp00/examples/sleeping.c", "visit_date": "2023-05-25T07:17:52.100506" }
stackv2
/* sleeping.c */ #include "garfield.h" #include <stdio.h> mood sleep (int hours) { printf ("Garfield is sleeping for %d hours.\n", hours); return HUNGRY; }
2.109375
2
2024-11-18T18:42:14.969540+00:00
2015-10-16T15:58:44
5f8642038f65a7b5dcda129c7eea7e6547021dd6
{ "blob_id": "5f8642038f65a7b5dcda129c7eea7e6547021dd6", "branch_name": "refs/heads/master", "committer_date": "2015-10-16T15:58:44", "content_id": "d25b132892e7f62d63fcc3930be5115c8fc8d418", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f6525bae25696ec97f3653f1abbb6e35ee76ece2", "extension": "c", "filename": "test_scpi_utils.c", "fork_events_count": 1, "gha_created_at": "2015-10-15T19:38:59", "gha_event_created_at": "2015-10-15T19:38:59", "gha_language": null, "gha_license_id": null, "github_id": 44340865, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 36442, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/libscpi/test/test_scpi_utils.c", "provenance": "stackv2-0030.json.gz:24168", "repo_name": "mvladic/scpi-parser", "revision_date": "2015-10-16T15:58:44", "revision_id": "d6e013b6fabcc8e30b7a546eeb04f0790ee70ec1", "snapshot_id": "c278eeecfa0a8c0daaa5b40bc0121455d7f62631", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/mvladic/scpi-parser/d6e013b6fabcc8e30b7a546eeb04f0790ee70ec1/libscpi/test/test_scpi_utils.c", "visit_date": "2020-12-30T20:56:25.838108" }
stackv2
/*- * Copyright (c) 2013 Jan Breuer * Richard.hmm * Copyright (c) 2012 Jan Breuer * * All Rights Reserved * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. */ /* * File: test_scpi_utils.c * Author: Jan Breuer * * Created on 26.11.2012, 11:22:00 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include "CUnit/Basic.h" #include "scpi/scpi.h" #include "../src/utils_private.h" /* * CUnit Test Suite */ static int init_suite(void) { return 0; } static int clean_suite(void) { return 0; } static void test_strnpbrk() { char str[] = "ahoj"; CU_ASSERT(strnpbrk(str, 4, "a") == (str + 0)); CU_ASSERT(strnpbrk(str, 4, "h") == (str + 1)); CU_ASSERT(strnpbrk(str, 4, "b") == NULL); CU_ASSERT(strnpbrk(str, 1, "h") == NULL); CU_ASSERT(strnpbrk(str, 4, "xo") == (str + 2)); CU_ASSERT(strnpbrk(str, 4, "j") == (str + 3)); } static void test_Int32ToStr() { const size_t max = 32 + 1; int32_t val[] = {0, 1, -1, INT32_MIN, INT32_MAX, 0x01234567, 0x89abcdef}; int N = sizeof (val) / sizeof (int32_t); int i; char str[max]; char ref[max]; size_t len; // test signed conversion to decimal numbers for (i = 0; i < N; i++) { len = SCPI_Int32ToStr(val[i], str, max); snprintf(ref, max, "%"PRIi32, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } int16_t val16[] = {0, 1, -1, INT16_MIN, INT16_MAX, 0x0123, 0x4567, 0x89ab, 0xcdef}; int N16 = sizeof (val16) / sizeof (int16_t); // test signed conversion to decimal numbers for (i = 0; i < N16; i++) { len = SCPI_Int32ToStr((int32_t) val16[i], str, max); snprintf(ref, max, "%"PRIi16, val16[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } } static void test_UInt32ToStrBase() { const size_t max = 32 + 1; uint32_t val[] = {0, 1, -1, INT32_MIN, INT32_MAX, 0x01234567, 0x89abcdef}; int N = sizeof (val) / sizeof (uint32_t); int i; char str[max]; char ref[max]; size_t len; // test conversion to decimal numbers for (i = 0; i < N; i++) { len = SCPI_UInt32ToStrBase(val[i], str, max, 10); snprintf(ref, max, "%"PRIu32, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } // test conversion to hexadecimal numbers for (i = 0; i < N; i++) { len = SCPI_UInt32ToStrBase(val[i], str, max, 16); snprintf(ref, max, "%"PRIX32, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } // test conversion to octal numbers for (i = 0; i < N; i++) { len = SCPI_UInt32ToStrBase(val[i], str, max, 8); snprintf(ref, max, "%"PRIo32, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } // test conversion to binary numbers len = SCPI_UInt32ToStrBase(0, str, max, 2); CU_ASSERT(len == 1); CU_ASSERT_STRING_EQUAL(str, "0"); len = SCPI_UInt32ToStrBase(1, str, max, 2); CU_ASSERT(len == 1); CU_ASSERT_STRING_EQUAL(str, "1"); len = SCPI_UInt32ToStrBase(-1, str, max, 2); CU_ASSERT(len == 32); CU_ASSERT_STRING_EQUAL(str, "11111111111111111111111111111111"); len = SCPI_UInt32ToStrBase(0x01234567, str, max, 2); CU_ASSERT(len == 25); CU_ASSERT_STRING_EQUAL(str, "1001000110100010101100111"); len = SCPI_UInt32ToStrBase(0x89abcdef, str, max, 2); CU_ASSERT(len == 32); CU_ASSERT_STRING_EQUAL(str, "10001001101010111100110111101111"); } static void test_Int64ToStr() { const size_t max = 64 + 1; int64_t val[] = {0, 1, -1, INT64_MIN, INT64_MAX, 0x0123456789abcdef, 0xfedcba9876543210}; int N = sizeof (val) / sizeof (int64_t); int i; char str[max]; char ref[max]; size_t len; // test conversion to decimal numbers for (i = 0; i < N; i++) { len = SCPI_Int64ToStr(val[i], str, max); snprintf(ref, max, "%"PRIi64, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } } static void test_UInt64ToStrBase() { const size_t max = 64 + 1; uint64_t val[] = {0, 1, -1, INT64_MIN, INT64_MAX, 0x0123456789abcdef, 0xfedcba9876543210}; int N = sizeof (val) / sizeof (uint64_t); int i; char str[max]; char ref[max]; size_t len; // test conversion to decimal numbers for (i = 0; i < N; i++) { len = SCPI_UInt64ToStrBase(val[i], str, max, 10); snprintf(ref, max, "%"PRIu64, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } // test conversion to hexadecimal numbers for (i = 0; i < N; i++) { len = SCPI_UInt64ToStrBase(val[i], str, max, 16); snprintf(ref, max, "%"PRIX64, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } // test conversion to octal numbers for (i = 0; i < N; i++) { len = SCPI_UInt64ToStrBase(val[i], str, max, 8); snprintf(ref, max, "%"PRIo64, val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } // test conversion to binary numbers len = SCPI_UInt64ToStrBase(0, str, max, 2); CU_ASSERT(len == 1); CU_ASSERT_STRING_EQUAL(str, "0"); len = SCPI_UInt64ToStrBase(1, str, max, 2); CU_ASSERT(len == 1); CU_ASSERT_STRING_EQUAL(str, "1"); len = SCPI_UInt64ToStrBase(-1, str, max, 2); CU_ASSERT(len == 64); CU_ASSERT_STRING_EQUAL(str, "1111111111111111111111111111111111111111111111111111111111111111"); len = SCPI_UInt64ToStrBase(0x0123456789abcdef, str, max, 2); CU_ASSERT(len == 57); CU_ASSERT_STRING_EQUAL(str, "100100011010001010110011110001001101010111100110111101111"); len = SCPI_UInt64ToStrBase(0xfedcba9876543210, str, max, 2); CU_ASSERT(len == 64); CU_ASSERT_STRING_EQUAL(str, "1111111011011100101110101001100001110110010101000011001000010000"); } static void test_floatToStr() { const size_t max = 49 + 1; float val[] = {1, -1, 1.1, -1.1, 1e3, 1e30, -1.3e30, -1.3e-30}; int N = sizeof (val) / sizeof (float); int i; char str[max]; char ref[max]; size_t len; for (i = 0; i < N; i++) { len = SCPI_FloatToStr(val[i], str, max); snprintf(ref, max, "%g", val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } } static void test_doubleToStr() { const size_t max = 49 + 1; double val[] = {1, -1, 1.1, -1.1, 1e3, 1e30, -1.3e30, -1.3e-30}; int N = sizeof (val) / sizeof (double); int i; char str[max]; char ref[max]; size_t len; for (i = 0; i < N; i++) { len = SCPI_DoubleToStr(val[i], str, max); snprintf(ref, max, "%lg", val[i]); CU_ASSERT(len == strlen(ref)); CU_ASSERT_STRING_EQUAL(str, ref); } } static void test_strBaseToInt32() { size_t result; int32_t val; #define TEST_STR_TO_INT32(s, r, v, b) \ do { \ result = strBaseToInt32(s, &val, b); \ CU_ASSERT_EQUAL(val, v); \ CU_ASSERT_EQUAL(result, r); \ } while(0) \ // TODO: extend to corner cases, use scanf as reference TEST_STR_TO_INT32("", 0, 0, 10); TEST_STR_TO_INT32("1", 1, 1, 10); TEST_STR_TO_INT32("10", 2, 10, 10); TEST_STR_TO_INT32("-50", 3, -50, 10); TEST_STR_TO_INT32("100MHz", 3, 100, 10); TEST_STR_TO_INT32("MHz", 0, 0, 10); TEST_STR_TO_INT32("1.4", 1, 1, 10); TEST_STR_TO_INT32(" 1", 2, 1, 10); TEST_STR_TO_INT32(" +100", 5, 100, 10); // space and + TEST_STR_TO_INT32("FF", 2, 255, 16); // hexadecimal FF TEST_STR_TO_INT32("77", 2, 63, 8); // octal 77 TEST_STR_TO_INT32("18", 1, 1, 8); // octal 1, 8 is ignored } static void test_strBaseToUInt32() { size_t result; uint32_t val; #define TEST_STR_TO_UINT32(s, r, v, b) \ do { \ result = strBaseToUInt32(s, &val, b); \ CU_ASSERT_EQUAL(val, v); \ CU_ASSERT_EQUAL(result, r); \ } while(0) \ // TODO: extend to corner cases, use scanf as reference TEST_STR_TO_UINT32("", 0, 0, 10); TEST_STR_TO_UINT32("1", 1, 1, 10); TEST_STR_TO_UINT32("10", 2, 10, 10); TEST_STR_TO_UINT32("100MHz", 3, 100, 10); TEST_STR_TO_UINT32("MHz", 0, 0, 10); TEST_STR_TO_UINT32("1.4", 1, 1, 10); TEST_STR_TO_UINT32(" 1", 2, 1, 10); TEST_STR_TO_UINT32(" +100", 5, 100, 10); // space and + TEST_STR_TO_UINT32("FF", 2, 255, 16); // hexadecimal FF TEST_STR_TO_UINT32("77", 2, 63, 8); // octal 77 TEST_STR_TO_UINT32("18", 1, 1, 8); // octal 1, 8 is ignored TEST_STR_TO_UINT32("FFFFFFFF", 8, 0xffffffffu, 16); // octal 1, 8 is ignored } static void test_strBaseToInt64() { size_t result; int64_t val; #define TEST_STR_TO_INT64(s, r, v, b) \ do { \ result = strBaseToInt64(s, &val, b); \ CU_ASSERT_EQUAL(val, v); \ CU_ASSERT_EQUAL(result, r); \ } while(0) \ // TODO: extend to corner cases, use scanf as reference TEST_STR_TO_INT64("", 0, 0, 10); TEST_STR_TO_INT64("1", 1, 1, 10); TEST_STR_TO_INT64("10", 2, 10, 10); TEST_STR_TO_INT64("-50", 3, -50, 10); TEST_STR_TO_INT64("100MHz", 3, 100, 10); TEST_STR_TO_INT64("MHz", 0, 0, 10); TEST_STR_TO_INT64("1.4", 1, 1, 10); TEST_STR_TO_INT64(" 1", 2, 1, 10); TEST_STR_TO_INT64(" +100", 5, 100, 10); // space and + TEST_STR_TO_INT64("FF", 2, 255, 16); // hexadecimal FF TEST_STR_TO_INT64("77", 2, 63, 8); // octal 77 TEST_STR_TO_INT64("18", 1, 1, 8); // octal 1, 8 is ignored } static void test_strBaseToUInt64() { size_t result; uint64_t val; #define TEST_STR_TO_UINT64(s, r, v, b) \ do { \ result = strBaseToUInt64(s, &val, b); \ CU_ASSERT_EQUAL(val, v); \ CU_ASSERT_EQUAL(result, r); \ } while(0) \ // TODO: extend to corner cases, use scanf as reference TEST_STR_TO_UINT64("", 0, 0, 10); TEST_STR_TO_UINT64("1", 1, 1, 10); TEST_STR_TO_UINT64("10", 2, 10, 10); TEST_STR_TO_UINT64("100MHz", 3, 100, 10); TEST_STR_TO_UINT64("MHz", 0, 0, 10); TEST_STR_TO_UINT64("1.4", 1, 1, 10); TEST_STR_TO_UINT64(" 1", 2, 1, 10); TEST_STR_TO_UINT64(" +100", 5, 100, 10); // space and + TEST_STR_TO_UINT64("FF", 2, 255, 16); // hexadecimal FF TEST_STR_TO_UINT64("77", 2, 63, 8); // octal 77 TEST_STR_TO_UINT64("18", 1, 1, 8); // octal 1, 8 is ignored TEST_STR_TO_UINT64("FFFFFFFF", 8, 0xffffffffu, 16); // octal 1, 8 is ignored } static void test_strToDouble() { double val; size_t result; #define TEST_STR_TO_DOUBLE(s, r, v) \ do { \ result = strToDouble(s, &val); \ CU_ASSERT_EQUAL(result, r); \ CU_ASSERT_DOUBLE_EQUAL(v, val, 0.000001); \ } while(0); \ TEST_STR_TO_DOUBLE("", 0, 0.0); TEST_STR_TO_DOUBLE(" 1", 2, 1.0); TEST_STR_TO_DOUBLE("1", 1, 1.0); TEST_STR_TO_DOUBLE("10", 2, 10.0); TEST_STR_TO_DOUBLE("10MHz", 2, 10.0); TEST_STR_TO_DOUBLE("MHz", 0, 0.0); TEST_STR_TO_DOUBLE("1E", 1, 1.0); TEST_STR_TO_DOUBLE("1E3", 3, 1000.0); TEST_STR_TO_DOUBLE("1.2", 3, 1.2); TEST_STR_TO_DOUBLE("10.2", 4, 10.2); TEST_STR_TO_DOUBLE("10.2MHz", 4, 10.2); TEST_STR_TO_DOUBLE("MHz", 0, 0.0); TEST_STR_TO_DOUBLE("1.2E", 3, 1.2); TEST_STR_TO_DOUBLE("1.2E3", 5, 1200.0); TEST_STR_TO_DOUBLE("-1.2", 4, -1.2); } static void test_compareStr() { CU_ASSERT_TRUE(compareStr("abcd", 1, "afgh", 1)); CU_ASSERT_TRUE(compareStr("ABCD", 4, "abcd", 4)); CU_ASSERT_TRUE(compareStr("AbCd", 3, "AbCE", 3)); CU_ASSERT_TRUE(compareStr("ABCD", 1, "a", 1)); CU_ASSERT_FALSE(compareStr("abcd", 1, "efgh", 1)); CU_ASSERT_FALSE(compareStr("ABCD", 4, "abcd", 3)); } static void test_compareStrAndNum() { int32_t num; CU_ASSERT_TRUE(compareStrAndNum("abcd", 1, "afgh", 1, NULL)); CU_ASSERT_TRUE(compareStrAndNum("ABCD", 4, "abcd", 4, NULL)); CU_ASSERT_TRUE(compareStrAndNum("AbCd", 3, "AbCE", 3, NULL)); CU_ASSERT_TRUE(compareStrAndNum("ABCD", 1, "a", 1, NULL)); CU_ASSERT_FALSE(compareStrAndNum("abcd", 1, "efgh", 1, NULL)); CU_ASSERT_FALSE(compareStrAndNum("ABCD", 4, "abcd", 3, NULL)); CU_ASSERT_TRUE(compareStrAndNum("abcd", 4, "abcd1", 5, NULL)); CU_ASSERT_TRUE(compareStrAndNum("abcd", 4, "abcd123", 7, NULL)); CU_ASSERT_FALSE(compareStrAndNum("abcd", 4, "abcd12A", 7, NULL)); CU_ASSERT_FALSE(compareStrAndNum("abcd", 4, "abcdB12", 7, NULL)); CU_ASSERT_FALSE(compareStrAndNum("abdd", 4, "abcd132", 7, NULL)); #define TEST_COMPARE_STR_AND_NUM(s1, l1, s2, l2, v, r) \ do { \ num = -1; \ CU_ASSERT_EQUAL(compareStrAndNum(s1, l1, s2, l2, &num),r); \ CU_ASSERT_EQUAL(num, v); \ } while(0); \ TEST_COMPARE_STR_AND_NUM("abcd", 4, "abcd", 4, -1, TRUE); TEST_COMPARE_STR_AND_NUM("abcd", 4, "abcd1", 5, 1, TRUE); TEST_COMPARE_STR_AND_NUM("abcd", 4, "abcd123", 7, 123, TRUE); TEST_COMPARE_STR_AND_NUM("abcd", 4, "abcd12A", 7, -1, FALSE); TEST_COMPARE_STR_AND_NUM("abcd", 4, "abcdB12", 7, -1, FALSE); TEST_COMPARE_STR_AND_NUM("abdd", 4, "abcd132", 7, -1, FALSE); } static void test_matchPattern() { scpi_bool_t result; #define TEST_MATCH_PATTERN(p, s, r) \ do { \ result = matchPattern(p, strlen(p), s, strlen(s), NULL);\ CU_ASSERT_EQUAL(result, r); \ } while(0) \ TEST_MATCH_PATTERN("A", "a", TRUE); TEST_MATCH_PATTERN("Ab", "a", TRUE); TEST_MATCH_PATTERN("Ab", "ab", TRUE); TEST_MATCH_PATTERN("Ab", "aB", TRUE); TEST_MATCH_PATTERN("AB", "a", FALSE); TEST_MATCH_PATTERN("Ab#", "aB", TRUE); TEST_MATCH_PATTERN("Ab#", "aB10", TRUE); TEST_MATCH_PATTERN("Ab#", "a10", TRUE); } static void test_matchCommand() { scpi_bool_t result; int32_t values[20]; #define TEST_MATCH_COMMAND(p, s, r) \ do { \ result = matchCommand(p, s, strlen(s), NULL, 0, 0); \ CU_ASSERT_EQUAL(result, r); \ } while(0) \ #define NOPAREN(...) __VA_ARGS__ #define TEST_MATCH_COMMAND2(p, s, r, v) \ do { \ int32_t evalues[] = {NOPAREN v}; \ unsigned int cnt = (sizeof(evalues)/4); \ result = matchCommand(p, s, strlen(s), values, 20, -1); \ CU_ASSERT_EQUAL(result, r); \ {unsigned int i; for (i = 0; i<cnt; i++) { \ CU_ASSERT_EQUAL(evalues[i], values[i]); \ }} \ } while(0) \ TEST_MATCH_COMMAND("A", "a", TRUE); TEST_MATCH_COMMAND("Ab", "a", TRUE); TEST_MATCH_COMMAND("Ab", "ab", TRUE); TEST_MATCH_COMMAND("Ab", "aB", TRUE); TEST_MATCH_COMMAND("AB", "a", FALSE); TEST_MATCH_COMMAND("ABcc:AACddd", "ab:aac", TRUE); TEST_MATCH_COMMAND("ABcc:AACddd", "abcc:aac", TRUE); TEST_MATCH_COMMAND("ABcc:AACddd", "abcc:aacddd", TRUE); TEST_MATCH_COMMAND("ABcc:AACddd", "abcc:aacdd", FALSE); TEST_MATCH_COMMAND("ABcc:AACddd", "a:aac", FALSE); TEST_MATCH_COMMAND("ABcc:AACddd", ":ab:aac", TRUE); TEST_MATCH_COMMAND("ABcc:AACddd", ":abcc:aac", TRUE); TEST_MATCH_COMMAND("ABcc:AACddd", ":abcc:aacddd", TRUE); TEST_MATCH_COMMAND("ABcc:AACddd", ":abcc:aacdd", FALSE); TEST_MATCH_COMMAND("ABcc:AACddd", ":a:aac", FALSE); TEST_MATCH_COMMAND("?", "?", TRUE); TEST_MATCH_COMMAND("A?", "A?", TRUE); TEST_MATCH_COMMAND("A", "A?", FALSE); TEST_MATCH_COMMAND("A?", "A", FALSE); TEST_MATCH_COMMAND("[:ABcc]:AACddd", ":ab:aac", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:AACddd", "aac", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:AACddd", "aac?", FALSE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:AACddd?", ":ab:aac?", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:AACddd?", "aac?", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:AACddd?", "aac", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd]:CDEFGeeeee", "ab:bcc:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd]:CDEFGeeeee", "ab:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd]:CDEFGeeeee", "ab:cdefg?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd]:CDEFGeeeee?", "ab:bcc:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd]:CDEFGeeeee?", "ab:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd]:CDEFGeeeee?", "ab:cdefg", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc:BCCdddd[:CDEFGeeeee]", "ab:bcc:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc:BCCdddd[:CDEFGeeeee]", "ab:bcc", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc:BCCdddd[:CDEFGeeeee]", "ab:bcc?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc:BCCdddd[:CDEFGeeeee]?", "ab:bcc:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc:BCCdddd[:CDEFGeeeee]?", "ab:bcc?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc:BCCdddd[:CDEFGeeeee]?", "ab:bcc", FALSE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]", "ab:bcc:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]", "ab:bcc", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]", "bcc:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]", "ab:bcc?", FALSE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]", "bcc:cdefg?", FALSE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]?", "ab:bcc:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]?", "ab:bcc?", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]?", "bcc:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]?", "ab:bcc", FALSE); // test optional keyword TEST_MATCH_COMMAND("[:ABcc]:BCCdddd[:CDEFGeeeee]?", "bcc:cdefg", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]", "ab:bcc:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]", "ab:bcc", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]", "ab:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]", "ab:bcc?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]", "ab:cdefg?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]?", "ab:bcc:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]?", "ab:bcc?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]?", "ab:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]?", "ab:bcc", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee]?", "ab:cdefg", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:cdefg:defffffffff", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:cdefg:deffffffffffffffffffff", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:cdefg:de", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:defffffffff", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:cdefg:defffffffff", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:cdefg", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:defffffffff", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:cdefg?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc:defffffffff?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:cdefg:defffffffff?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:bcc?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:cdefg?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab:defffffffff?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]", "ab?", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc:cdefg:defffffffff?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc:defffffffff?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:cdefg:defffffffff?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:cdefg?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:defffffffff?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab?", TRUE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc:cdefg", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc:defffffffff", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:cdefg:defffffffff", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:bcc", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:cdefg", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab:defffffffff", FALSE); // test optional keyword TEST_MATCH_COMMAND("ABcc[:BCCdddd][:CDEFGeeeee][:DEFFFFFFFFFfffffffffff]?", "ab", FALSE); // test optional keyword TEST_MATCH_COMMAND("*IDN?", "idn", FALSE); // common command TEST_MATCH_COMMAND("*IDN?", "idn?", FALSE); // common command TEST_MATCH_COMMAND("*IDN?", "*idn", FALSE); // common command TEST_MATCH_COMMAND("*IDN?", "*idn?", TRUE); // common command TEST_MATCH_COMMAND("*IDN?", ":idn", FALSE); // common command TEST_MATCH_COMMAND("*IDN?", ":idn?", FALSE); // common command TEST_MATCH_COMMAND("*IDN?", ":*idn", FALSE); // common command TEST_MATCH_COMMAND("*IDN?", ":*idn?", FALSE); // common command TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", ":MEAS?", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", "MEAS?", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", ":MEAS:DC?", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", "MEAS:DC?", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", ":MEAS:CURR?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", "MEAS:CURR?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", ":MEAS:SCAL:CURR?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", "MEAS:SCAL:CURR?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", ":MEAS:SCAL:CURR:DC?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", "MEAS:SCAL:CURR:DC?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", ":MEAS:CURR:DC?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]?", "MEAS:CURR:DC?", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", ":MEAS", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", "MEAS", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", ":MEAS:DC", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", "MEAS:DC", FALSE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", ":MEAS:CURR", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", "MEAS:CURR", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", ":MEAS:SCAL:CURR", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", "MEAS:SCAL:CURR", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", ":MEAS:SCAL:CURR:DC", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", "MEAS:SCAL:CURR:DC", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", ":MEAS:CURR:DC", TRUE); TEST_MATCH_COMMAND("MEASure[:SCALar]:CURRent[:DC]", "MEAS:CURR:DC", TRUE); TEST_MATCH_COMMAND("ABCdef#", "abc", TRUE); // test numeric parameter TEST_MATCH_COMMAND("ABCdef#", "abc1324", TRUE); // test numeric parameter TEST_MATCH_COMMAND("ABCdef#", "abcDef1324", TRUE); // test numeric parameter TEST_MATCH_COMMAND("ABCdef#", "abcDef124b", FALSE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#:MODulation#:FM#", "abc", FALSE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#:MODulation#:FM#", "outp1:mod10:fm", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#:MODulation#:FM#", "output1:mod10:fm", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#:MODulation#:FM#", "outp1:modulation:fm5", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#:MODulation#:FM#", "output:mod:fm", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#:MODulation#:FM#", "outp1:mod10a:fm", FALSE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#[:MODulation#]:FM#", "outp1:fm", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#[:MODulation#]:FM#", "outp1:mod10:fm", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#[:MODulation#]:FM#", "outp1:fm2", TRUE); // test numeric parameter TEST_MATCH_COMMAND("OUTPut#[:MODulation#]:FM#", "output:fm", TRUE); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM#", "outp3:mod10:fm", TRUE, (3, 10, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM#", "output3:mod10:fm", TRUE, (3, 10, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM#", "outp30:modulation:fm5", TRUE, (30, -1, 5)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM#", "output:mod:fm", TRUE, (-1, -1, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM#", "outp3:fm", TRUE, (3, -1, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM#", "outp3:mod10:fm", TRUE, (3, 10, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM#", "outp3:fm2", TRUE, (3, -1, 2)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM#", "output:fm", TRUE, (-1, -1, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation:FM#", "outp3:mod:fm", TRUE, (3, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation:FM#", "output3:mod:fm", TRUE, (3, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation:FM#", "outp30:modulation:fm5", TRUE, (30, 5)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation:FM#", "output:mod:fm", TRUE, (-1, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation]:FM#", "outp3:fm", TRUE, (3, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation]:FM#", "outp3:mod:fm", TRUE, (3, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation]:FM#", "outp3:fm2", TRUE, (3, 2)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation]:FM#", "output:fm", TRUE, (-1, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM", "outp3:mod10:fm", TRUE, (3, 10)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM", "output3:mod10:fm", TRUE, (3, 10)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM", "outp30:modulation:fm", TRUE, (30, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#:MODulation#:FM", "output:mod:fm", TRUE, (-1, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM", "outp3:fm", TRUE, (3, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM", "outp3:mod10:fm", TRUE, (3, 10)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM", "outp3:fm", TRUE, (3, -1)); // test numeric parameter TEST_MATCH_COMMAND2("OUTPut#[:MODulation#]:FM", "output:fm", TRUE, (-1, -1)); // test numeric parameter } static void test_composeCompoundCommand(void) { #define TEST_COMPOSE_COMMAND(b, c1_len, c2_pos, c2_len, c2_final, r) \ { \ char buffer[100]; \ scpi_token_t cmd_prev, cmd_curr; \ cmd_prev.ptr = buffer; \ cmd_prev.len = c1_len; \ cmd_curr.ptr = buffer + c2_pos; \ cmd_curr.len = c2_len; \ scpi_bool_t res; \ \ strcpy(buffer, b); \ res = composeCompoundCommand(&cmd_prev, &cmd_curr); \ CU_ASSERT_EQUAL(res, r); \ CU_ASSERT_EQUAL(cmd_curr.len, strlen(c2_final)); \ CU_ASSERT_STRING_EQUAL(cmd_curr.ptr, c2_final); \ }\ TEST_COMPOSE_COMMAND("A:B;C", 3, 4, 1, "A:C", TRUE); TEST_COMPOSE_COMMAND("A:B;DD", 3, 4, 2, "A:DD", TRUE); TEST_COMPOSE_COMMAND("A:B", 0, 0, 3, "A:B", TRUE); TEST_COMPOSE_COMMAND("*IDN? ; ABC", 5, 8, 3, "ABC", TRUE); TEST_COMPOSE_COMMAND("A:B;*IDN?", 3, 4, 5, "*IDN?", TRUE); TEST_COMPOSE_COMMAND("A:B;:C", 3, 4, 2, ":C", TRUE); TEST_COMPOSE_COMMAND("B;C", 1, 2, 1, "C", TRUE); TEST_COMPOSE_COMMAND("A:B;C:D", 3, 4, 3, "A:C:D", TRUE); TEST_COMPOSE_COMMAND(":A:B;C", 4, 5, 1, ":A:C", TRUE); TEST_COMPOSE_COMMAND(":A:B;:C", 4, 5, 2, ":C", TRUE); TEST_COMPOSE_COMMAND(":A;C", 2, 3, 1, ":C", TRUE); } int main() { unsigned int result; CU_pSuite pSuite = NULL; /* Initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) return CU_get_error(); /* Add a suite to the registry */ pSuite = CU_add_suite("SCPI Utils", init_suite, clean_suite); if (NULL == pSuite) { CU_cleanup_registry(); return CU_get_error(); } /* Add the tests to the suite */ if (0 || (NULL == CU_add_test(pSuite, "strnpbrk", test_strnpbrk)) || (NULL == CU_add_test(pSuite, "Int32ToStr", test_Int32ToStr)) || (NULL == CU_add_test(pSuite, "UInt32ToStrBase", test_UInt32ToStrBase)) || (NULL == CU_add_test(pSuite, "Int64ToStr", test_Int64ToStr)) || (NULL == CU_add_test(pSuite, "UInt64ToStrBase", test_UInt64ToStrBase)) || (NULL == CU_add_test(pSuite, "floatToStr", test_floatToStr)) || (NULL == CU_add_test(pSuite, "doubleToStr", test_doubleToStr)) || (NULL == CU_add_test(pSuite, "strBaseToInt32", test_strBaseToInt32)) || (NULL == CU_add_test(pSuite, "strBaseToUInt32", test_strBaseToUInt32)) || (NULL == CU_add_test(pSuite, "strBaseToInt64", test_strBaseToInt64)) || (NULL == CU_add_test(pSuite, "strBaseToUInt64", test_strBaseToUInt64)) || (NULL == CU_add_test(pSuite, "strToDouble", test_strToDouble)) || (NULL == CU_add_test(pSuite, "compareStr", test_compareStr)) || (NULL == CU_add_test(pSuite, "compareStrAndNum", test_compareStrAndNum)) || (NULL == CU_add_test(pSuite, "matchPattern", test_matchPattern)) || (NULL == CU_add_test(pSuite, "matchCommand", test_matchCommand)) || (NULL == CU_add_test(pSuite, "composeCompoundCommand", test_composeCompoundCommand)) ) { CU_cleanup_registry(); return CU_get_error(); } /* Run all tests using the CUnit Basic interface */ CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); result = CU_get_number_of_tests_failed(); CU_cleanup_registry(); return result ? result : CU_get_error(); }
2.1875
2
2024-11-18T18:42:15.162101+00:00
2019-10-04T03:56:27
b28148767587ba9f031ef6a0721228d52e7e569f
{ "blob_id": "b28148767587ba9f031ef6a0721228d52e7e569f", "branch_name": "refs/heads/master", "committer_date": "2019-10-04T03:56:27", "content_id": "466835f745a4e2439bf42a6dea05201f5551a57b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7958ba70a603c0af7ae933f50416cb002c9de51b", "extension": "c", "filename": "panel.c", "fork_events_count": 0, "gha_created_at": "2020-03-07T19:56:33", "gha_event_created_at": "2020-03-07T19:56:34", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 245696552, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2319, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/rtgui/widgets/panel.c", "provenance": "stackv2-0030.json.gz:24424", "repo_name": "ghsecuritylab/Hackthon_weatherStation_RTT", "revision_date": "2019-10-04T03:56:27", "revision_id": "fdb8a5127b0e11e6c452985a0b8b2660feb4b686", "snapshot_id": "af7ff30d104cd07ac726a60915874640ce67a23a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ghsecuritylab/Hackthon_weatherStation_RTT/fdb8a5127b0e11e6c452985a0b8b2660feb4b686/components/rtgui/widgets/panel.c", "visit_date": "2021-02-28T12:21:19.428726" }
stackv2
/* * File : panel.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rt-thread.org/license/LICENSE * * Change Logs: * Date Author Notes * 2012-07-07 Bernard implement panel as a widget */ #include <rtgui/dc.h> #include <rtgui/widgets/panel.h> #include <rtgui/rtgui_system.h> #include <rtgui/rtgui_theme.h> static void _rtgui_panel_constructor(rtgui_panel_t *panel) { /* init widget and set event handler */ rtgui_object_set_event_handler(RTGUI_OBJECT(panel), rtgui_panel_event_handler); /* set field */ panel->border_style = RTGUI_BORDER_NONE; } DEFINE_CLASS_TYPE(panel, "panel", RTGUI_CONTAINER_TYPE, _rtgui_panel_constructor, RT_NULL, sizeof(struct rtgui_panel)); rt_bool_t rtgui_panel_event_handler(struct rtgui_object *object, struct rtgui_event *event) { struct rtgui_panel *panel; panel = RTGUI_PANEL(object); switch (event->type) { case RTGUI_EVENT_PAINT: { struct rtgui_dc *dc; struct rtgui_rect rect; rtgui_widget_get_rect(RTGUI_WIDGET(object), &rect); dc = rtgui_dc_begin_drawing(RTGUI_WIDGET(object)); if (dc == RT_NULL) return RT_FALSE; rtgui_dc_fill_rect(dc, &rect); // rtgui_rect_inflate(&rect, RTGUI_WIDGET(panel)->); rtgui_dc_draw_border(dc, &rect, panel->border_style); /* paint on each child */ rtgui_container_dispatch_event(RTGUI_CONTAINER(panel), event); rtgui_dc_end_drawing(dc); } break; default: return rtgui_container_event_handler(object, event); } return RT_FALSE; } rtgui_panel_t *rtgui_panel_create(int border_style) { struct rtgui_panel *panel; panel = (struct rtgui_panel *) rtgui_widget_create(RTGUI_PANEL_TYPE); if (panel != RT_NULL) { rtgui_rect_t rect = {0, 0, 100, 100}; rtgui_widget_set_rect(RTGUI_WIDGET(panel), &rect); panel->border_style = border_style; } return panel; } void rtgui_panel_destroy(rtgui_panel_t *panel) { rtgui_object_destroy(RTGUI_OBJECT(panel)); }
2.375
2
2024-11-18T18:42:15.561999+00:00
2011-05-29T06:31:29
3e088fa6f8bf9f6271199548ec7117ecc7955259
{ "blob_id": "3e088fa6f8bf9f6271199548ec7117ecc7955259", "branch_name": "refs/heads/master", "committer_date": "2011-05-29T06:31:29", "content_id": "36290ff402fa7525233cef91273b27e99b94ffb8", "detected_licenses": [ "ISC" ], "directory_id": "8e2f9d145432977dc351db9b4fd90f0ce5fb3609", "extension": "h", "filename": "Locking.h", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 781371, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1514, "license": "ISC", "license_type": "permissive", "path": "/include/Locking.h", "provenance": "stackv2-0030.json.gz:24552", "repo_name": "programble/proxos", "revision_date": "2011-05-29T06:31:29", "revision_id": "68eac65db803c74480a30ac5fe386acd84b6da79", "snapshot_id": "9cf1a496e5e08fd19f2e2d030b96150425e1c6f1", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/programble/proxos/68eac65db803c74480a30ac5fe386acd84b6da79/include/Locking.h", "visit_date": "2021-01-10T20:19:22.512077" }
stackv2
#ifndef __LOCKING_H__ #define __LOCKING_H__ #include <Kernel.h> #include <Init.h> #include <Threading.h> typedef enum { Locking_Lock_terminal, Locking_Lock_memory, Locking_Lock__size /* For getting the number of locks; not a real lock */ } Locking_Lock; static Bool Locking_locks[Locking_Lock__size] = {false}; /* Must be inline! */ always_inline Bool Locking_setLock(Locking_Lock lock) { /* <nixeagle> first argument = pointer to lock, second argument is the what should go in the EAX register... so 0x0 in your case, and the 3rd argument is what you want to set the lock to on success... so in your case 0x1. intel manual 2A page 264 __asm__ __volatile__("lock; cmpxchg"EFREG_OPL" %3, %0; setz %1" : "=m"(*p), "=q"(ret) : "m"(*p), "r" (val_new), "a"(val_old) : "memory");*/ u8 ret; __asm__ __volatile__("lock; cmpxchgl %3, %0; setz %1" : "=m" (Locking_locks[lock]), "=q" (ret) : "m" (Locking_locks[lock]), "r" (0x1), "a" (0x0) : "memory"); return ret == 1; } static inline void Locking_acquireLock(Locking_Lock lock) { Kernel_assert(lock < Locking_Lock__size, "Trying to acquire an invalid lock"); while (!Locking_setLock(lock)) { if (Init_initialized(Init_Component_threading)) Threading_yield(); } } static inline void Locking_releaseLock(Locking_Lock lock) { Kernel_assert(lock < Locking_Lock__size, "Trying to release an invalid lock"); Locking_locks[lock] = false; } #endif
2.578125
3
2024-11-18T18:42:16.055084+00:00
2016-03-02T22:22:09
6c4a9ed2091f659eca2e0bc009ce24e2b9029728
{ "blob_id": "6c4a9ed2091f659eca2e0bc009ce24e2b9029728", "branch_name": "refs/heads/master", "committer_date": "2016-03-02T22:22:09", "content_id": "fe13313d69ba63b8ea08b15e3639b73a29a234ea", "detected_licenses": [ "MIT" ], "directory_id": "d9d8f81fef62964dd45b909e40bee9c3e9d2bf79", "extension": "c", "filename": "serial.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50381611, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4966, "license": "MIT", "license_type": "permissive", "path": "/client/src/serial.c", "provenance": "stackv2-0030.json.gz:24809", "repo_name": "TaylorP/Raspboot", "revision_date": "2016-03-02T22:22:09", "revision_id": "75be279343de301c239a6425ca377157c3aa31e6", "snapshot_id": "ff5967d3f1cda0ce0777bbb69d082136ff305708", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/TaylorP/Raspboot/75be279343de301c239a6425ca377157c3aa31e6/client/src/serial.c", "visit_date": "2021-01-10T15:07:17.524610" }
stackv2
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "console.h" #include "serial.h" S32 _baudRate(const U32 baud); S32 _raspbootInitTerminal(Raspboot_Serial* serial, Raspboot_Args* args); S32 raspbootSerialInit(Raspboot_Serial* serial, Raspboot_Args* args) { // Return early if the arguments are null if (serial == 0 || args == 0) { return -1; } // Initialiaze the serial port output buffer serial->bufferIndex = 0; // Open a connection the device specified in the port argument serial->connection = open(args->port, O_RDWR | O_NOCTTY | O_SYNC); if (serial->connection < 0) { raspbootConsoleError(args, "Unable to open port `%s`: %s\n", args->port, strerror(errno)); return -1; } // Set TTY settings for the device return _raspbootInitTerminal(serial, args); } S32 raspbootSerialGet(Raspboot_Serial* serial, U8* byte) { if (read(serial->connection, byte, 1) == 1) { return 0; } return -1; } S32 raspbootSerialPut(Raspboot_Serial* serial, const U8 byte) { serial->buffer[serial->bufferIndex++] = byte; if (serial->bufferIndex == SERIAL_BUFFER_SIZE) { return raspbootSerialFlush(serial); } return 0; } S32 raspbootSerialPutW(Raspboot_Serial* serial, const U32 word) { U32 i; for (i = 0; i < 4; i++) { U8 b = (U8)((word >> ((3-i) << 3)) & 0xff); S32 result = raspbootSerialPut(serial, b); if (result != 0) { return result; } } return 0; } S32 raspbootSerialPutN(Raspboot_Serial* serial, U8* bytes, const U32 n) { U32 iter = 0; while (iter < n) { serial->buffer[serial->bufferIndex++] = bytes[iter]; if (serial->bufferIndex == SERIAL_BUFFER_SIZE) { S32 result = raspbootSerialFlush(serial); if (result != 0) { return result; } } iter++; } return 0; } S32 raspbootSerialFlush(Raspboot_Serial* serial) { S32 result = write(serial->connection, serial->buffer, serial->bufferIndex); usleep(serial->bufferIndex * 100); serial->bufferIndex = 0; return result; } S32 raspbootSerialClear(Raspboot_Serial* serial, const U32 queue) { return tcflush(serial->connection, queue); } S32 _raspbootBaudRate(const U32 baud) { switch (baud) { case 0: return B0; case 50: return B50; case 75: return B75; case 110: return B110; case 134: return B134; case 150: return B150; case 200: return B200; case 300: return B300; case 600: return B600; case 1200: return B1200; case 1800: return B1800; case 2400: return B2400; case 4800: return B4800; case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; case 230400: return B230400; default: return -1; } } S32 _raspbootInitTerminal(Raspboot_Serial* serial, Raspboot_Args* args) { // Initialize the tty structure struct termios* tty = &(serial->tty); memset(tty, 0, sizeof(*tty)); // Query initial TTY state if (tcgetattr(serial->connection, tty) != 0) { raspbootConsoleError(args, "Unable to query tty attributes. (%s)\n", strerror(errno)); return -1; } S32 baud = _raspbootBaudRate(args->speed); if (baud < 0) { raspbootConsoleWarn(args, "Invalid baud rate `%d`. Using default of 115,200.\n", args->speed); baud = B115200; } // Set the TTY speed cfsetospeed(tty, baud); cfsetispeed(tty, baud); // Set other terminal flags (char size, breaks, etc) tty->c_cflag = (tty->c_cflag & ~CSIZE) | CS8; tty->c_iflag &= ~IGNBRK; tty->c_lflag = 0; tty->c_oflag = 0; // Set blocking parameters tty->c_cc[VMIN] = 1; tty->c_cc[VTIME] = 5; // Disable xon/xoff control tty->c_iflag &= ~(IXON | IXOFF | IXANY); // Disable parity and CTS/RTs tty->c_cflag |= (CLOCAL | CREAD); tty->c_cflag &= ~(PARENB | PARODD); tty->c_cflag &= ~CSTOPB; tty->c_cflag &= ~CRTSCTS; // Apply the settings to the TTY if (tcsetattr(serial->connection, TCSANOW, tty) != 0) { raspbootConsoleError(args, "Unable to set tty attributes. (%s)\n", strerror(errno)); return -1; } // Clear all pending data from the TTY raspbootSerialClear(serial, TCIOFLUSH); return 0; }
2.578125
3
2024-11-18T18:42:16.317420+00:00
2021-04-17T03:00:35
aa5285292a90a30189fbcdf76c578291b83862b7
{ "blob_id": "aa5285292a90a30189fbcdf76c578291b83862b7", "branch_name": "refs/heads/master", "committer_date": "2021-04-17T03:00:35", "content_id": "95ccc35d5072ef1928950c6a8056bb3a3abee424", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "7e05636b884237d257b5cddcb8eeb4573ab044a3", "extension": "c", "filename": "test_libgps.c", "fork_events_count": 0, "gha_created_at": "2021-04-17T10:48:32", "gha_event_created_at": "2021-04-17T10:49:32", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 358853049, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3599, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/tests/test_libgps.c", "provenance": "stackv2-0030.json.gz:25067", "repo_name": "isabella232/gpsd", "revision_date": "2021-04-17T03:00:35", "revision_id": "b5dc433bf178db6efac784ac5615cdfe729bdf8f", "snapshot_id": "ac5b8958fbc8892590ca32fcaf5ede08cb9e4e03", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/isabella232/gpsd/b5dc433bf178db6efac784ac5615cdfe729bdf8f/tests/test_libgps.c", "visit_date": "2023-04-12T16:11:20.680979" }
stackv2
/* * A simple command-line exerciser for the library. * Not really useful for anything but debugging. * SPDX-License-Identifier: BSD-2-clause */ #include "../include/gpsd_config.h" /* must be before all includes */ #include <ctype.h> #include <errno.h> #include <getopt.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "../include/gps.h" #include "../include/libgps.h" #include "../include/gpsdclient.h" static void onsig(int sig) { (void)fprintf(stderr, "libgps: died with signal %d\n", sig); exit(EXIT_FAILURE); } #ifdef SOCKET_EXPORT_ENABLE /* must start zeroed, otherwise the unit test will try to chase garbage pointer fields. */ static struct gps_data_t gpsdata; #endif int main(int argc, char *argv[]) { struct gps_data_t collect; struct fixsource_t source; char buf[BUFSIZ]; int option; bool batchmode = false; bool forwardmode = false; char *fmsg = NULL; int debug = 0; (void)signal(SIGSEGV, onsig); #ifdef SIGBUS (void)signal(SIGBUS, onsig); #endif while ((option = getopt(argc, argv, "bf:hsD:?")) != -1) { switch (option) { case 'b': batchmode = true; break; case 'f': forwardmode = true; fmsg = optarg; break; case 's': (void) printf("Sizes: fix=%zu gpsdata=%zu rtcm2=%zu rtcm3=%zu " "ais=%zu compass=%zu raw=%zu devices=%zu policy=%zu " "version=%zu, noise=%zu\n", sizeof(struct gps_fix_t), sizeof(struct gps_data_t), sizeof(struct rtcm2_t), sizeof(struct rtcm3_t), sizeof(struct ais_t), sizeof(struct attitude_t), sizeof(struct rawdata_t), sizeof(collect.devices), sizeof(struct gps_policy_t), sizeof(struct version_t), sizeof(struct gst_t)); exit(EXIT_SUCCESS); case 'D': debug = atoi(optarg); break; case '?': case 'h': default: (void)fputs("usage: test_libgps [-b] [-f fwdmsg] [-D lvl] [-s] [server[:port:[device]]]\n", stderr); exit(EXIT_FAILURE); } } /* Grok the server, port, and device. */ if (optind < argc) { gpsd_source_spec(argv[optind], &source); } else gpsd_source_spec(NULL, &source); gps_enable_debug(debug, stdout); if (batchmode) { #ifdef SOCKET_EXPORT_ENABLE while (fgets(buf, sizeof(buf), stdin) != NULL) { if (buf[0] == '{' || isalpha( (int) buf[0])) { gps_unpack(buf, &gpsdata); libgps_dump_state(&gpsdata); } } #endif } else if (gps_open(source.server, source.port, &collect) != 0) { (void)fprintf(stderr, "test_libgps: no gpsd running or network error: %d, %s\n", errno, gps_errstr(errno)); exit(EXIT_FAILURE); } else if (forwardmode) { if (gps_send(&collect, fmsg) == -1) { (void)fprintf(stderr, "test_libgps: gps send error: %d, %s\n", errno, gps_errstr(errno)); } if (gps_read(&collect, NULL, 0) == -1) { (void)fprintf(stderr, "test_libgps: gps read error: %d, %s\n", errno, gps_errstr(errno)); } #ifdef SOCKET_EXPORT_ENABLE libgps_dump_state(&collect); #endif (void)gps_close(&collect); } else { int tty = isatty(0); if (tty) (void)fputs("This is the gpsd exerciser.\n", stdout); for (;;) { if (tty) (void)fputs("> ", stdout); if (fgets(buf, sizeof(buf), stdin) == NULL) { if (tty) putchar('\n'); break; } collect.set = 0; (void)gps_send(&collect, buf); (void)gps_read(&collect, NULL, 0); #ifdef SOCKET_EXPORT_ENABLE libgps_dump_state(&collect); #endif } (void)gps_close(&collect); } return 0; }
2.3125
2
2024-11-18T18:42:16.879202+00:00
2020-05-11T07:57:26
38df2298b8fdc725f233c98a8d1f22c4cd09d12b
{ "blob_id": "38df2298b8fdc725f233c98a8d1f22c4cd09d12b", "branch_name": "refs/heads/main", "committer_date": "2020-05-11T07:57:26", "content_id": "d174cb549b8ae7ac1b64c0a27afc6d466c01befb", "detected_licenses": [ "MIT" ], "directory_id": "5e843ab8adf9038aeadaed1b2bc127a1e4021173", "extension": "c", "filename": "queue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1119, "license": "MIT", "license_type": "permissive", "path": "/src/lib/libk/k/queue.c", "provenance": "stackv2-0030.json.gz:25323", "repo_name": "reymontero/Os2020", "revision_date": "2020-05-11T07:57:26", "revision_id": "c8a882e7e2de8e9bd31ad9e3fe11d9798880f15a", "snapshot_id": "8b35a29aa72b4f586092f8e4d1e5595f4725fddf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/reymontero/Os2020/c8a882e7e2de8e9bd31ad9e3fe11d9798880f15a/src/lib/libk/k/queue.c", "visit_date": "2022-12-31T11:48:16.970214" }
stackv2
#include "queue.h" #include <k/syscalls.h> #include <stdlib.h> // To avoid to free empty items static void tryFree(void *data) { if (data == NULL) return; free(data); } Queue *Queue_new(size_t capacity) { Queue *q = malloc(sizeof(Queue)); q->capacity = capacity; q->data = malloc(capacity * sizeof(void*)); q->start = q->end = 0; return q; } void Queue_del(Queue *q) { Queue_iter(q, tryFree); free(q); } void Queue_add(Queue *q, void *item) { q->data[q->end] = item; q->end = (q->end + 1) % q->capacity; if (Queue_full(q)) fatal("Queue : Can't enqueue with fully filled queue"); } void *Queue_pop(Queue *q) { if (Queue_empty(q)) fatal("Queue : Can't dequeue with empty queue"); void *ret = q->data[q->start]; q->start = (q->start + 1) % q->capacity; return ret; } void Queue_clear(Queue *q) { Queue_iter(q, free); q->start = q->end = 0; } void Queue_iter(Queue *q, void (*functor)(void *item)) { for (size_t i = q->start; i != q->end; i = (i + 1) % q->capacity) functor(q->data[i]); }
3.171875
3
2024-11-18T18:42:17.757703+00:00
2018-07-18T08:24:38
a22309d65b4a016dd2602ed57488a830d372e571
{ "blob_id": "a22309d65b4a016dd2602ed57488a830d372e571", "branch_name": "refs/heads/master", "committer_date": "2018-07-18T08:24:38", "content_id": "802aeb84c04ee92c9e999703d3e695ba86ac962f", "detected_licenses": [ "MIT" ], "directory_id": "7bc58acec9e1d92a8f207b9d81390345a967f2a0", "extension": "c", "filename": "peasant.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 138332084, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2772, "license": "MIT", "license_type": "permissive", "path": "/voxen/peasant.c", "provenance": "stackv2-0030.json.gz:25579", "repo_name": "mafiosso/voxen", "revision_date": "2018-07-18T08:24:38", "revision_id": "d0368bbfe3cf2134253480c362a313e258cf4fec", "snapshot_id": "cd41f5d583c9a2501be5a9266ff80799340d74db", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/mafiosso/voxen/d0368bbfe3cf2134253480c362a313e258cf4fec/voxen/peasant.c", "visit_date": "2020-03-21T08:16:25.374065" }
stackv2
/* support for threaded main loop my barrier vision - use threads only if needed and blocking like */ #include "VX_lib.h" static void field_destroy( VX_field * self ){ for( int i = 0 ; i < self->peasants_count ; i++ ){ self->workers[i].destroy_p = 1; if( i > 0 ){ self->workers[i].plant = NULL; sem_post( &(self->workers[i].sem_in) ); sem_wait( &(self->workers[i].sem_out) ); } } for( int i = 0 ; i < self->peasants_count-1 ; i++ ){ pthread_join( self->t[i] , NULL ); } free( self->t ); free( self->workers ); free( self ); } static void field_cultivate( VX_field * self , void ** params , void (*funcs[])(void*) ) { for( int i = 1 ; i < self->peasants_count ; i++ ){ self->workers[i].param = params[i]; self->workers[i].plant = funcs[i]; sem_post( &(self->workers[i].sem_in) ); } funcs[0]( params[0] ); for( int i = 1 ; i < self->peasants_count ; i++ ){ sem_wait( &(self->workers[i].sem_out) ); // this have undefined behavior see man pages of pthread //sem_init( &(self->workers[i].sem_out) , 0 , 0 ); } } static void work(VX_peasant * self ){ while( 1 ){ sem_wait( &(self->sem_in) ); if( !self->plant ){ break; } /* should be very power consumptive function */ self->plant( self->param ); /* do this twice because waiting in driving thread */ sem_post( &(self->sem_out) ); } sem_post( &(self->sem_out) ); } static int field_make( VX_field * self ){ /* start threads */ int p_cnt = self->peasants_count-1; pthread_t * threads = malloc(sizeof(pthread_t)*p_cnt); int ret = 0; for( int i = 0 ; i < p_cnt ; i++ ){ ret += pthread_create( &(threads[i]) , NULL , (void * (*)(void *))&work , &(self->workers[i+1]) ); } self->t = threads; return ret; } VX_field * VX_field_new( VX_uint32 peasants_count ) { if( !peasants_count ) return NULL; VX_field * out = calloc( 1 , sizeof(VX_field) ); out->peasants_count = peasants_count; out->workers = calloc(peasants_count , sizeof(VX_peasant)); for( int i = 0 ; i < peasants_count ; i++ ){ sem_init( &(out->workers[i].sem_in) , 0 , 0 ); sem_init( &(out->workers[i].sem_in) , 0 , 0 ); } if( field_make( out ) ){ printf("err: can not create threads!\n"); for( int i = 0 ; i < peasants_count ; i++ ){ free(out->workers); } free( out ); return NULL; } out->destroy = field_destroy; out->enter = field_cultivate; return out; }
2.890625
3
2024-11-18T18:42:17.839271+00:00
2017-11-14T11:44:03
4e87a4b9b033577191ffd9b360dea2e409db464a
{ "blob_id": "4e87a4b9b033577191ffd9b360dea2e409db464a", "branch_name": "refs/heads/master", "committer_date": "2017-11-14T11:44:03", "content_id": "9a020805f9ea0455501fbe1ebaae4ed8a9db5a1b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5459323235ad66754085b5c286b4d9614f706d1e", "extension": "c", "filename": "pi_omp_tasks.c", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 93849114, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2077, "license": "Apache-2.0", "license_type": "permissive", "path": "/boada/lab2/overheads/pi_omp_tasks.c", "provenance": "stackv2-0030.json.gz:25707", "repo_name": "felixarpa/PAR-Lab", "revision_date": "2017-11-14T11:44:03", "revision_id": "7b3bde3c3c95b61d0b53fc5992ea72dff182d0fe", "snapshot_id": "4d275f7c29c10d3b42283fa0972e40ea0ed8bd79", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/felixarpa/PAR-Lab/7b3bde3c3c95b61d0b53fc5992ea72dff182d0fe/boada/lab2/overheads/pi_omp_tasks.c", "visit_date": "2021-01-25T09:32:35.613365" }
stackv2
/* * Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * Parallel version using OpenMP */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <omp.h> /* OpenMP */ double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)(time.tv_sec * 1000000L + time.tv_usec)); } #define NUMITERS 10000 #define MINTASKS 2 #define MAXTASKS 64 #define STEPTASKS 2 double difference(int num_tasks, long int num_steps) { double x, sum; double step = 1.0/(double) num_steps; double stamp1 = getusec_(); for (int rep=0; rep<NUMITERS ; rep++) for (int iter=0; iter<num_tasks ; iter++) { sum = 0.0; for (long int i=0; i<num_steps; ++i) { x = (i+0.5)*step; sum += 4.0/(1.0+x*x); } } stamp1 = getusec_()-stamp1; double stamp2 = getusec_(); for (int rep=0; rep<NUMITERS ; rep++) { for (int iter=0; iter<num_tasks ; iter++) { sum = 0.0; #pragma omp task private(x) firstprivate(sum) for (long int i=0; i<num_steps; ++i) { x = (i+0.5)*step; sum += 4.0/(1.0+x*x); } } #pragma omp taskwait } stamp2 = getusec_()-stamp2; return((stamp2 - stamp1)/NUMITERS); } int main(int argc, char *argv[]) { const char Usage[] = "Usage: pi <num_steps> <num_threads> \n"; if (argc < 3) { fprintf(stderr, Usage); exit(1); } long int num_steps = atoi(argv[1]); int num_threads = atoi(argv[2]); printf("All overheads expressed in microseconds\n"); printf("Ntasks\tOverhead per task\n"); #pragma omp parallel num_threads(num_threads) #pragma omp single { difference(MINTASKS, num_steps); for (int n_tasks=MINTASKS; n_tasks<=MAXTASKS; n_tasks+=STEPTASKS) { double tmp = difference(n_tasks, num_steps); printf("%d\t%.4f\n", n_tasks, tmp/n_tasks); } } return EXIT_SUCCESS; }
3.375
3
2024-11-18T18:42:18.009541+00:00
2020-08-02T02:59:26
1cb40cbed7fcb0da547d4d82744e83c7036f14e4
{ "blob_id": "1cb40cbed7fcb0da547d4d82744e83c7036f14e4", "branch_name": "refs/heads/master", "committer_date": "2020-08-02T02:59:26", "content_id": "cd516d645ceaf1113ca39045f5dc816247a6830f", "detected_licenses": [ "Unlicense" ], "directory_id": "5160e2cbfa510d76113af771a541decc5807adf9", "extension": "c", "filename": "Measure.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 192198117, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 53760, "license": "Unlicense", "license_type": "permissive", "path": "/sourcecode/example/Measure.c", "provenance": "stackv2-0030.json.gz:26092", "repo_name": "byxlk/spms_vcmm", "revision_date": "2020-08-02T02:59:26", "revision_id": "574f8933a3d4e956abd7f13e0dbc5167d8a809c1", "snapshot_id": "8af62ab30cdf3dc97f284a361ccc0ceea000bfc5", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/byxlk/spms_vcmm/574f8933a3d4e956abd7f13e0dbc5167d8a809c1/sourcecode/example/Measure.c", "visit_date": "2021-07-10T12:00:22.324644" }
stackv2
#include "TypeMeter.h" #include "TypeE2p.h" #include "TypeRAM.h" #include "ht6xxx_lib.h" #include "TypeFRAM.h" #include "Data.h" #include "General.h" #include "Mem.h" #include "Port.h" #include "Display.h" #include "Initial.h" #include "Time.h" #include "Power.h" #include "ECProcess.h" #include "Measure.h" #include "COSEMComm.h" #include <math.h> #if( MEASCHIP == HT7017) unsigned char UART_Write( unsigned char Cmd, unsigned char* Data ) { // unsigned char Checksum; unsigned char Temp; int i,Delaysum; HT_FreeDog(); Com_HT7017.Comm_Enable = DISABLE; // NVIC_DisableIRQ(TIMER_2_IRQn); for(i=0;i<3;i++) {//每一个写操作数据帧都是 6 个字节固定长度 HT_UART3->UARTCON &=~ (UART_UARTCON_TXIE + UART_UARTCON_TXEN); Com_HT7017.MeasBuf_Tx[4] = 0x6A;//传输字节帧头,固定为 0x6A Com_HT7017.MeasBuf_Tx[0] = 0x6A; Com_HT7017.MeasBuf_Tx[1] = Cmd + 0x80; Com_HT7017.MeasBuf_Tx[4] += Cmd + 0x80; Com_HT7017.MeasBuf_Tx[2] = *Data;//写寄存器是固定 2 字节传输,高字节在前 Com_HT7017.MeasBuf_Tx[4] += *Data; Com_HT7017.MeasBuf_Tx[3] = *(Data + 1); Com_HT7017.MeasBuf_Tx[4] += *(Data + 1); Com_HT7017.MeasBuf_Tx[4] = ~Com_HT7017.MeasBuf_Tx[4];//将命令帧的各数据相加,抛弃进位,最后的结果按位取反 Com_HT7017.MeasState |= ATT7053Set; Com_HT7017.MeasState &=~ (ATT7053CommOK + ATT7053Read); Delaysum = 3000; //22M 26us 580 Com_HT7017.Tx_Ptr = 1; Com_HT7017.Rx_Ptr = 0; Com_HT7017.MeasBuf_Rx[0] = 0; // HT_UART3->UARTCON &=~ UART_UARTCON_RXEN; HT_UART3->UARTCON |= (UART_UARTCON_TXIE + UART_UARTCON_TXEN);//UCA2IE |= UCTXIE; HT_UART3->SBUF = Com_HT7017.MeasBuf_Tx[0]; HT_UART_ClearITPendingBit(HT_UART3, UART_UARTSTA_TXIF); // RAM_Fill(Com_HT7017.MeasBuf_Rx, 10 ); Delay(Measur_Delay); Delay(Measur_Delay); if(Com_HT7017.MeasBuf_Rx[0] == 0x54) { Com_HT7017.MeasState &=~ ATT7053Set; return 0; } /* while((Com_HT7017.MeasState & ATT7053CommOK) != ATT7053CommOK) { // Delay(10); Delay(1); Delaysum--; if(Delaysum == 0) { break; // return 1; } } if(Com_HT7017.MeasBuf_Rx[0] == 0x54) { // Delaysum = 30000; Temp = 0; // break; } else { // Delaysum = 30000; Temp = 1; } // NVIC_EnableIRQ(TIMER_2_IRQn); */ } // Com_HT7017.MeasState &=~ ATT7053Set; return Temp; } unsigned char UART_Read( unsigned char Cmd, unsigned char* Data ) { unsigned char Checksum; int i,Delaysum; HT_FreeDog(); for(i=0;i<2;i++) { //UCA2IE &=~ (UCRXIE + UCTXIE); HT_UART3->UARTCON &=~ (UART_UARTCON_TXIE + UART_UARTCON_TXEN); Checksum = 0x6A; Com_HT7017.MeasBuf_Tx[0] = 0x6A; Checksum = 0x6A; Com_HT7017.MeasBuf_Tx[1] = Cmd; Com_HT7017.Cmd = Cmd; Checksum += Cmd; Com_HT7017.MeasBuf_Tx[5] = Checksum; Com_HT7017.MeasBuf_Tx[5] = ~Com_HT7017.MeasBuf_Tx[5]; Com_HT7017.MeasState |= ATT7053Read; Com_HT7017.MeasState &=~ (ATT7053CommOK + ATT7053Set); // Delaysum = 2600; //4M 2012.8.11 Delaysum = 3000; //580 Com_HT7017.Tx_Ptr = 1; // Com_HT7017.Rx_Ptr = 0; // HT_UART3->UARTCON &=~ UART_UARTCON_RXEN; HT_UART3->UARTCON |= (UART_UARTCON_TXIE + UART_UARTCON_TXEN);//UCA2IE |= UCTXIE; HT_UART3->SBUF = Com_HT7017.MeasBuf_Tx[0]; /* RAM_Fill(Com_HT7017.MeasBuf_Rx, 10 ); while((Com_HT7017.MeasState & ATT7053CommOK) != ATT7053CommOK) { // Delay(30); Delay(1); Delaysum--; if(Delaysum == 0) { // Com_HT7017.Rx_Ptr=0; // RAM_Fill(Com_HT7017.MeasBuf_Rx, 10 ); // RAM_Fill(Data, 3 ); // return 1; break; } } Checksum += (Com_HT7017.MeasBuf_Rx[0] + Com_HT7017.MeasBuf_Rx[1] + Com_HT7017.MeasBuf_Rx[2]); Checksum = ~Checksum; if(Checksum == Com_HT7017.MeasBuf_Rx[3]) break; else { Com_HT7017.Rx_Ptr=0; RAM_Fill(Com_HT7017.MeasBuf_Rx, 5 ); } */ } /* //数据帧输出时,高字节在前,低字节在后。对于不足 3 个字节的寄存器, HT7017 的内部寄存器与数据帧的低位对齐。 *Data = Com_HT7017.MeasBuf_Rx[2]; *(Data + 1)= Com_HT7017.MeasBuf_Rx[1]; *(Data + 2)= Com_HT7017.MeasBuf_Rx[0]; Com_HT7017.MeasState &=~ ATT7053Read; */ return 0; } unsigned char UART_ReadInstan( unsigned char Cmd ) { unsigned char Checksum,i; HT_FreeDog(); // for(i=0;i<2;i++) // { //UCA2IE &=~ (UCRXIE + UCTXIE); HT_UART3->UARTCON &=~ (UART_UARTCON_TXIE + UART_UARTCON_TXEN); Checksum = 0x6A; Com_HT7017.MeasBuf_Tx[0] = 0x6A; Checksum = 0x6A; Com_HT7017.MeasBuf_Tx[1] = Cmd; Com_HT7017.Cmd = Cmd; Checksum += Cmd; Com_HT7017.MeasBuf_Tx[5] = Checksum; Com_HT7017.MeasBuf_Tx[5] = ~Com_HT7017.MeasBuf_Tx[5]; Com_HT7017.MeasState |= ATT7053Read; Com_HT7017.MeasState &=~ (ATT7053CommOK + ATT7053Set); // Delaysum = 2600; //4M 2012.8.11 // Delaysum = 3000; //580 Com_HT7017.Tx_Ptr = 1; Com_HT7017.Rx_Ptr = 0; HT_UART3->UARTCON |= (UART_UARTCON_TXIE + UART_UARTCON_TXEN);//UCA2IE |= UCTXIE; HT_UART3->SBUF = Com_HT7017.MeasBuf_Tx[0]; // } return 0; } unsigned char MasureData_Get(void) { unsigned char Checksum,i; unsigned char Error_Byte; unsigned char buff[4]; unsigned char* Data_ptr; Data_ptr = buff; RAM_Fill(Data_ptr,4); Checksum = 0x6A; Checksum += Com_HT7017.Cmd; Checksum += (Com_HT7017.MeasBuf_Rx[0] + Com_HT7017.MeasBuf_Rx[1] + Com_HT7017.MeasBuf_Rx[2]); Checksum = ~Checksum; if(Checksum == Com_HT7017.MeasBuf_Rx[3]) { *(Data_ptr + 3) = Com_HT7017.MeasBuf_Rx[2]; *(Data_ptr + 2)= Com_HT7017.MeasBuf_Rx[1]; *(Data_ptr + 1)= Com_HT7017.MeasBuf_Rx[0]; Error_Byte = 0; for(i=0; i<Measur_Num; i++) { if(HT7017_DATATab[i].ReadCmd == Com_HT7017.Cmd) break; } if(i==Measur_Num) Error_Byte = 1; else { RAM_Write(HT7017_DATATab[i].ReadData,Data_ptr,4); } Com_HT7017.MeasState |= ATT7053CommOK; Com_HT7017.MeasState &=~ ATT7053Read; Com_HT7017.Rx_Ptr=0; RAM_Fill(Com_HT7017.MeasBuf_Rx,10); } else { Error_Byte = 1; } return Error_Byte; } #if 0 void ChkMeasChipRST(unsigned int phase) { unsigned char *Point; Point = (unsigned char *)&MeasureHT7017.APowerPulP; //2012.12.19 if( ChkMeasChkSum(phase) == 1 ) { SoftResetMeas(phase); ATT7053Int(phase); RAM_Fill( Point+4*phase, 4); } } void CheckMeasChip(void) { if((Flag.HT7017PowerOn&F_PhaATT7053) == F_PhaATT7053) { ATT7053Int(0); MeasureHT7017.APowerPulP=0; } else { ChkMeasChipRST(0); } /* if((Flag.ATT7053PowerOn&F_PhaATT7053) == F_PhaATT7053) { ATT7053Int(0); Flag.APowerPulP=0; } else { ChkMeasChipRST(0); } if((Flag.ATT7053PowerOn&F_PhbATT7053) == F_PhbATT7053) { ATT7053Int(1); Flag.BPowerPulP=0; } else { ChkMeasChipRST(1); } if((Flag.ATT7053PowerOn&F_PhcATT7053) == F_PhcATT7053) { ATT7053Int(2); Flag.CPowerPulP=0; } else { ChkMeasChipRST(2); } */ } unsigned char ChkMeasChkSum(unsigned int phase) { unsigned char Buff[4]; unsigned char *Point; Point = Buff; /* switch(phase) { case 0: PDIR_CSA |= P_CSA; PDIR_CSC &= ~P_CSC; PDIR_CSB &= ~P_CSB; break; case 1: PDIR_CSA &= ~P_CSA; PDIR_CSB |= P_CSB; PDIR_CSC &= ~P_CSC; break; default: PDIR_CSA &= ~P_CSA; PDIR_CSB &= ~P_CSB; PDIR_CSC |= P_CSC; break; } */ ATT7053RdReg(SUMChecksum,Point); if(Data_Comp(Point, Para.MeasChkSum, 3)!=0) { E2P_RData( Para.MeasChkSum,MeasChkSum, 3 ); if(Data_Comp(Point, Para.MeasChkSum, 3)!=0) { ATT7053RdReg(SUMChecksum,Point); if(Data_Comp(Point, Para.MeasChkSum, 3)!=0) { /* PDIR_CSA &= ~P_CSA; PDIR_CSC &= ~P_CSC; PDIR_CSB &= ~P_CSB; */ return 1; } } } /* PDIR_CSA &= ~P_CSA; PDIR_CSC &= ~P_CSC; PDIR_CSB &= ~P_CSB; */ return 0; } #endif void SoftResetMeas(unsigned int phase) { unsigned char Buff[3]; /* switch(phase) { case 0: PDIR_CSA |= P_CSA; PDIR_CSC &= ~P_CSC; PDIR_CSB &= ~P_CSB; break; case 1: PDIR_CSA &= ~P_CSA; PDIR_CSB |= P_CSB; PDIR_CSC &= ~P_CSC; break; default: PDIR_CSA &= ~P_CSA; PDIR_CSB &= ~P_CSB; PDIR_CSC |= P_CSC; break; } */ Buff[0]=0x00; Buff[1]=0x55; UART_Write(SRSTREG_Address,Buff); //软件复位ATT7053 /* PDIR_CSA &= ~P_CSA; PDIR_CSC &= ~P_CSC; PDIR_CSB &= ~P_CSB; */ Delay(300); } short HT7017Init(void) { unsigned long Value; unsigned int Temp; unsigned char datbuff[5]; unsigned char* Point; Point = datbuff; HT_FreeDog(); /* UART_ReadInstan(IDCode); Delay(Measur_Delay); Delay(Measur_Delay); MasureData_Get(); RAM_Write(Point,(unsigned char *)&Measurement.HT7017_ID[1],3); if((datbuff[2]!= 0xB0)||(datbuff[1]!= 0x53)||(datbuff[0]!= 0x70)) { Flag.HT7017PowerOn |= F_PhaATT7053; return 1; } else { Flag.HT7017PowerOn &= ~F_PhaATT7053; } datbuff[0]=0x7E; datbuff[1]=0x7F; UART_Write(EMUIE_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); // // WPCFG = 0xBC:表示写保护打开,只能操作40H到45H的校表参数寄存器,不可操作50H到71H的校表参数寄存器// // // WPCFG = 0xA6:表示写保护打开,只能操作50H到71H的校表参数寄存器,不可操作40H到45H的校表参数寄存器。// datbuff[0]=0x00; datbuff[1]=0xBC; UART_Write(WPREG_Address,Point); //使能40-45写操作// Delay(Measur_Delay); Delay(Measur_Delay); Value = 0x0000BC; //EMUCFG // Value += 0x000088; //FreqCFG // Value += 0x00007E; //ModuleEn //datbuff[0]=0x40;//设置是否能量寄存器读后清 0(0:读后不清 0; 1:读后清 0) //datbuff[1]=0x12;//单相三线模式控制: 1=矢量和,单相三线累加模式选择(1:电流累加和模式) datbuff[0]=0xBE;//设置是否能量寄存器读后清 0(0:读后不清 0; 1:读后清 0) //datbuff[0]=0x9E; datbuff[1]=0x12; UART_Write(EMUCFG_Address,Point); //EMU 配置寄存器 Delay(Measur_Delay); Delay(Measur_Delay); Value += 0x004012; // datbuff[0]=0x00; // datbuff[1]=0xC8; datbuff[0]=0x01; datbuff[1]=0x48; UART_Write(FreqCFG_Address,Point); //时钟/更新频率配置寄存器 Delay(Measur_Delay); Delay(Measur_Delay); Value += 0x000148; datbuff[0]=0x00; datbuff[1]=0x7E; UART_Write(ModuleEn_Address,Point); //EMU 模块使能寄存器 Delay(Measur_Delay); Delay(Measur_Delay); Value += 0x00007E; datbuff[0]=0x00; datbuff[1]=0x0F; UART_Write(ANAEN,Point); //ADC开关寄存器// Delay(Measur_Delay); Delay(Measur_Delay); Value += 0x000007; //ADC开关寄存器 Value += 0x0000A6; //IOCFG datbuff[0]=0x00; datbuff[1]=0xA6; UART_Write(WPREG_Address,Point); //使能50-7C写操作// Delay(Measur_Delay); Delay(Measur_Delay); Value += 0x0000A6; // datbuff[0]=0xFE; // datbuff[1]=0x98; // UART_Write(QPhsCal_Address,Point); //当 femu=1MHz 时, 60Hz 信号频率下此寄存器写入 FE98H 即可,也不需要额外校准 // Delay(Measur_Delay); E2P_RAdj( datbuff, I2Gain, 2 );//电流通道 2 增益设置 SwapData(Point,2); UART_Write(I2Gain_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); E2P_RAdj( datbuff, HFCONST, 2 );//高频脉冲常数设置 SwapData(Point,2); UART_Write(HFConst_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); // ATT7053RdReg(WPREG,Point); //使能50-71写操作// //-----------电压电流有效值偏置校正---------- E2P_RAdj( datbuff, I1RMSOFFSET, 2 ); UART_Write(I1RMSOFFSET_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); E2P_RAdj( datbuff, I2RMSOFFSET, 2 ); UART_Write(I2RMSOFFSET_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); E2P_RAdj( datbuff, URMSOFFSET, 2 ); UART_Write(URMSOFFSET_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); E2P_RAdj( datbuff, AGPBase, 2 ); SwapData(Point,2); // datbuff[0]=0x13; // datbuff[1]=0x20; UART_Write(GP1,Point); //eeprom 3字节,实际使用2字节// Delay(Measur_Delay); Delay(Measur_Delay); // ATT7053RdReg(GP1,Point); //eeprom 3字节,实际使用2字节// UART_Write(GQ1,Point); //eeprom 3字节,实际使用2字节// Delay(Measur_Delay); Delay(Measur_Delay); UART_Write(GS1,Point); //eeprom 3字节,实际使用2字节// Delay(Measur_Delay); Delay(Measur_Delay); // ATT7053WtReg(GP2,Point); //eeprom 3字节,实际使用2字节// Temp = (*Point*256 + *(Point+1)); Value += Temp; //GP1 Value += Temp; //GQ1 Value += Temp; //GS1 E2P_RAdj( datbuff, AGPBase2, 2 ); SwapData(Point,2); UART_Write(GP2_Address,Point); //eeprom 3字节,实际使用2字节// Delay(Measur_Delay); Delay(Measur_Delay); UART_Write(GQ2_Address,Point); //eeprom 3字节,实际使用2字节// Delay(Measur_Delay); Delay(Measur_Delay); UART_Write(GS2_Address,Point); //eeprom 3字节,实际使用2字节// Delay(Measur_Delay); Delay(Measur_Delay); Temp = (*Point*256 + *(Point+1)); Value += Temp; //GP1 Value += Temp; //GQ1 Value += Temp; //GS1 Value += 0x00FF00; //QPhsCal //需要定死的寄存器// datbuff[0]=0x00; datbuff[1]=0x00; UART_Write(ADCCON,Point); //电流1放大16倍,电压放大1倍,电流2放大4倍// Delay(Measur_Delay); Delay(Measur_Delay); Value += 0x00003C; //ADCCON Value += 0x000040 + 0x000040; //PQStart,HFConst Value += 0x000010 + 0x000020 + 0x000004; //CHk,IPTAMP,ZCrossCurrent E2P_RAdj( Point, E2AP1OFFSET, 2 ); //2012.12.19 UART_Write(P1OFFSET,Point+1); //P1OFFSET Delay(Measur_Delay); Delay(Measur_Delay); UART_Write(P1OFFSETH_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); Temp = *(Point+1); Value += Temp; Value += *Point; E2P_RAdj( Point, E2AP2OFFSET, 2 ); //2012.12.19 UART_Write(P2OFFSET,Point+1); //P1OFFSET Delay(Measur_Delay); Delay(Measur_Delay); UART_Write(P2OFFSETH_Address,Point); Delay(Measur_Delay); Delay(Measur_Delay); Temp = *(Point+1); Value += Temp; Value += *Point; E2P_RAdj( datbuff, AGPhs, 2 ); SwapData(Point,2); UART_Write(GPhs1,Point); Delay(Measur_Delay); Delay(Measur_Delay); Temp = (*Point*256 + *(Point+1)); Value += Temp; E2P_RAdj( datbuff, AGPhs2, 2 ); SwapData(Point,2); UART_Write(GPhs2,Point); Delay(Measur_Delay); Delay(Measur_Delay); Temp = (*Point*256 + *(Point+1)); Value += Temp; // readep(&rambuf[1],EE_PHSA_7053,3,eplxjbcs); // rambuf[0]=0; // jchkprg(&rambuf[1]); // wr7053(rambuf,0x6d+0X80,3); //相位校准 datbuff[0]=0x00; datbuff[1]=0x00; datbuff[2]=0x00; UART_Write(WPREG_Address,Point); //关闭使能 Delay(Measur_Delay); Delay(Measur_Delay); RAM_Write( Para.MeasCheckSum, (unsigned char*)&Value, 3 ); //ATChk E2P_WData( MeasChkSum, (unsigned char *)&Value, 3 ); // } */ // ATT7053RdReg(ADCCON,Point); // ATT7053RdReg(GP1,Point); // ATT7053RdReg(Rms_U,Point); /* PDIR_CSA &= ~P_CSA; PDIR_CSC &= ~P_CSC; PDIR_CSB &= ~P_CSB; */ Flag.HT7017PowerOn &=~ F_Reset7053; return 0; } short Read_ATTValue( unsigned char cmd, unsigned char* Point , unsigned char length ) { unsigned char buff[4]; unsigned char* ptr; short return_value=0; ptr = buff; RAM_Fill(ptr,4); if(UART_Read(cmd,ptr)==0) { SwapData(ptr,4); RAM_Write(Point,ptr,4); return_value=0; } else return_value=-1; return return_value; } void ReadHT7017_V(void) { unsigned char Buff[4]; unsigned char *Point; unsigned long Temp; unsigned long long Temp2; Point = Buff; /* Temp = GetBuffToLong(Measurement.HT7017_U); if(MeasureHT7017.Urms_K!=0) Temp2 = MeasureHT7017.Urms_K; else Temp2 = 1; Temp2 *= Temp; Temp2 /= 100000; Temp2 /= 1000;//保留两位小数 Real.Uab = (unsigned short)Temp2; Word_BCD(Para.Ua,Real.Uab); */ } void ReadHT7017_HZ(void) { unsigned char Buff[4]; unsigned char *Point; unsigned long Temp2; Point = Buff; Temp2 = GetBuffToLong(Measurement.HT7017_Hz); Temp2 = 1000000/Temp2;//EMU 时钟(femu)选择为 1MHz Temp2/=2; Real.Freq = (unsigned short)Temp2;//hex Real.Freq*=100;//2位小数 Word_BCD(Point,Real.Freq); RAM_Write( Para.Fre, Point, 2 );//bcd } void ReadHT7017_I(void) { unsigned long Temp; unsigned long long Temp2; /* Temp = GetBuffToLong(Measurement.HT7017_Ia); if(MeasureHT7017.Irms1_K!=0) Temp2 = MeasureHT7017.Irms1_K; else Temp2 = 1; Temp2 *= Temp; Temp2 /= 100000; Temp2 /= 1000;//保留两位小数 Real.Ia = (unsigned short)Temp2; Word_BCD((unsigned char*)&Para.Ia,Real.Ia); Temp = GetBuffToLong(Measurement.HT7017_Ib); if(MeasureHT7017.Irms2_K!=0) Temp2 = MeasureHT7017.Irms2_K; else Temp2 = 1; Temp2 *= Temp; Temp2 /= 100000; Temp2 /= 1000;//保留两位小数 Real.Ib = (unsigned short)Temp2; */ } void ReadHT7017_P(void) { unsigned char Databuff[4]; unsigned char* Point; int State; // unsigned long int Power; long Power1,Power2,Power,angle,power_factor; long Temp; long long temp2,temp3; double anglezA; Power1 = 0; Power2 = 0; Point = Databuff; #if 0 if(MeasureHT7017.Power1_K==0) MeasureHT7017.Power1_K=1; if(MeasureHT7017.Power2_K==0) MeasureHT7017.Power2_K=1; Temp = GetBuffToLong(Measurement.HT7017_P1); if(Temp<0x800000) Power1 = Temp; else { Power1 = -(0x1000000-Temp); } MeasureHT7017.APowerPulP= Power1; temp2 = MeasureHT7017.Power1_K; temp2 *= Power1; Power = temp2; //-----第一通道角度-------- temp2 = GetBuffToLong(Measurement.HT7017_U); temp3 = MeasureHT7017.APowerPulP; anglezA = (double)((temp3*100)/(temp2*GetBuffToLong(Measurement.HT7017_Ia)/100000)); anglezA/=1000; if(anglezA > 100000) anglezA = 100000; Real.Angle_Ia = (unsigned short)(acos(anglezA)*1800/3.1416)*10; /* temp2 = Real.Uab; temp3 = Power; anglezA = (double)((temp3*100)/(temp2*Real.Ia)); anglezA/=1000; if(anglezA > 100000) anglezA = 100000; Real.Angle_Ia = (unsigned short)(acos(anglezA)*1800/3.1416)*10; */ Temp = GetBuffToLong(Measurement.HT7017_P2); if(Temp<0x800000) Power2 = Temp; else { Power2 = -(0x1000000-Temp); } MeasureHT7017.BPowerPulP= Power2; temp2 = MeasureHT7017.Power2_K; temp2 *= Power2; Power+=temp2; Power = Power/100000; Real.Pa = Power*100;//w位小数 if(Real.Pa<0) Real.Pa = -Real.Pa; //-----第二通道角度-------- temp2 = GetBuffToLong(Measurement.HT7017_U); temp3 = MeasureHT7017.BPowerPulP; anglezA = (double)((temp3*100)/(temp2*GetBuffToLong(Measurement.HT7017_Ib)/100000)); anglezA/=1000; if(anglezA > 100000) anglezA = 100000; Real.Angle_Ib= (unsigned short)(acos(anglezA)*1800/3.1416)*10; /* temp3 = temp2; temp2 = Real.Uab; anglezA = (double)((temp3*100)/(temp2*Real.Ib)); anglezA/=1000; if(anglezA > 100000) anglezA = 100000; Real.Angle_Ib= (unsigned short)(acos(anglezA)*1800/3.1416)*10; */ Temp = GetBuffToLong(Measurement.HT7017_S1); if(Temp<0x800000) Power1 = Temp; else { Power1 = -(0x1000000-Temp); } MeasureHT7017.SPowerPulP = Power1; if(MeasureHT7017.PowerS_K!=0) temp2 =MeasureHT7017.PowerS_K; else temp2 = 1; temp2 *= Power1; temp2/=100000; Power1 = temp2; Real.St = Power1*100;; Temp = GetBuffToLong(Measurement.HT7017_Q1); if(Temp<0x800000) Power1 = Temp; else { Power1 = -(0x1000000-Temp); } MeasureHT7017.APowerPulQ= Power1; temp2 = MeasureHT7017.Power2_K; temp2 *= Power1; Temp = GetBuffToLong(Measurement.HT7017_Q2); if(Temp<0x800000) Power2 = Temp; else { Power2 = -(0x1000000-Temp); } MeasureHT7017.BPowerPulQ= Power2; temp2 = MeasureHT7017.Power2_K; temp2 *= Power2; power_factor = ((MeasureHT7017.APowerPulP+MeasureHT7017.BPowerPulP)*100)/MeasureHT7017.SPowerPulP; //power_factor*=10; if(power_factor<0) power_factor = -power_factor; Real.Pfa = (unsigned char)power_factor; Word_BCD((unsigned char *)& Para.Pt,(unsigned short)power_factor); #endif } void Instan_Value(void) { ReadHT7017_V(); ReadHT7017_I(); ReadHT7017_HZ(); ReadHT7017_P(); } void Energy_Read(void) { unsigned long Temp; Temp = GetBuffToLong(Measurement.HT7017_P); ECInt.YPulse_Cum = (unsigned char)Temp; ECInt.YPulse_CumChk += ECInt.YPulse_Cum ; Temp = GetBuffToLong(Measurement.HT7017_Q); ECInt.WPulse_Cum = (unsigned char)Temp; ECInt.WPulse_CumChk += ECInt.WPulse_Cum ; RAM_Fill(Measurement.HT7017_P,4); RAM_Fill(Measurement.HT7017_Q,4); if(Measurement.HT7017_EMU_Status[3]&0x02) Real.PWFlag |= 0x10;//有功反向 else Real.PWFlag &=~ 0x10; if(Measurement.HT7017_EMU_Status[3]&0x01) Real.PWFlag |= 0x01;//无功反向 else Real.PWFlag &=~ 0x01; } #endif void Read_CMonEC( unsigned char* Dest, unsigned short ECRgAds ) { unsigned short i; unsigned short ECEAds; unsigned short ECFAds; unsigned char* ECRAds; // if( CombECJust( Dest, ECRgAds ) == 0 ) return; //组合电量判断 for( i=0;i<ECUnitNum;i++ ) { ECEAds = ECRgTab[i].ECEAds; ECRAds = ECRgTab[i].ECRAds; ECFAds = ECRgTab[i].ECFAds; if( ECEAds == ECRgAds ) break; //总电量 else if(( i < (ECUnitNum-1) )&&( ECEAds < ECRgAds )&&( ECRgTab[i+1].ECEAds > ECRgAds )) //费率电量 { if(((( ECRgAds - ECEAds ) % (ECDIGIT+1) ) == 0 )&&( ECRgTab[i].ECRgMode == 0 )) //有费率电量且费率电量地址正确 { ECRAds += ECRgAds - ECEAds; //费率电量RAM地址 ECFAds += ECRgAds - ECEAds; //费率电量铁电地址 break; } } } if( i == ECUnitNum ) { RAM_Fill( Dest, ECDIGIT ); //电量地址错误 return; } GetRamEC( Dest, ECRAds, ECFAds ); //读取RAM或FRAM中的电量 } void Read_CMonEC4( unsigned char* Dest, unsigned short ECRgAds ) { unsigned char Buff[6]; Read_CMonEC( Buff, ECRgAds ); RAM_Write( Dest, Buff+1, 4 ); } void Read_CMonEC4_HEX_U( unsigned char* Dest, unsigned short ECRgAds ) //16.08.29 { unsigned long Value; Read_CMonEC4( Dest, ECRgAds ); Value = BCD4_Long( Dest ); RAM_Write( Dest, (unsigned char*)&Value, 4 ); } void Read_CMonEC4_HEX_S( unsigned char* Dest, unsigned short ECRgAds ) //16.08.29 { long Value; short Temp=0; Read_CMonEC4( Dest, ECRgAds ); if(( *(Dest+3) & 0x80 ) != 0 ) { *(Dest+3) &= ~0x80; Temp = 1; } Value = BCD4_Long( Dest ); if( Temp == 1 ) Value = 0 - Value; RAM_Write( Dest, (unsigned char*)&Value, 4 ); } void Read_CMonEC8_HEX_U( unsigned char* Dest, unsigned short ECRgAds ) //16.08.29 { unsigned long long LValue; Disk.DigitsValidFlg = 0x55; //添加0.01kWh以下尾数 Read_CMonEC( Dest, ECRgAds ); Disk.DigitsValidFlg = 0x00; LValue = *(Dest+4); LValue <<= 32; LValue += BCD4_Long( Dest ); RAM_Write( Dest, (unsigned char*)&LValue, 8 ); } void Read_CMonEC8_HEX_S( unsigned char* Dest, unsigned short ECRgAds ) //16.08.29 { long long LValue; short Temp=0; Disk.DigitsValidFlg = 0x55; //添加0.01kWh以下尾数 Read_CMonEC( Dest, ECRgAds ); Disk.DigitsValidFlg = 0x00; if(( *(Dest+4) & 0x80 ) != 0 ) { *(Dest+4) &= ~0x80; Temp = 1; } LValue = *(Dest+4); LValue <<= 32; LValue += BCD4_Long( Dest ); if( Temp == 1 ) LValue = 0 - LValue; RAM_Write( Dest, (unsigned char*)&LValue, 8 ); } #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 void FeeECPulseAdd( unsigned short* PL_Cum, unsigned char* PL_Chk, unsigned char Pulse_Cum ) { unsigned short* PL_CumPtr; unsigned char* PL_ChkPtr; unsigned short Temp; if(( SM.FeeNo < 1 )||( SM.FeeNo > Total_Fee )) return; //当前费率号非法 Temp = SM.FeeNo; Temp -= 1; PL_CumPtr = PL_Cum; PL_CumPtr += Temp; PL_ChkPtr = PL_Chk; PL_ChkPtr += Temp; //新国网 //13.08.30 //#if (( METERTYPE == U220_I20A__80A320 )||( METERTYPE == U220_I20A__100A240 )||( METERTYPE == U220_I20A__120A240 )||( METERTYPE == U220_I30A__100A240 )||( METERTYPE == U220_I10A__100A240 )) // *PL_CumPtr += (unsigned short)Pulse_Cum * 10; //#else *PL_CumPtr += Pulse_Cum; //#endif *PL_ChkPtr = ChkNum( (unsigned char*)PL_CumPtr, 2 ); } #endif short GetMQuad( unsigned char PWFlag, short Reg ) { short Quad=1; // PWFlag = PWFlag >> Reg; PWFlag &= 0x11; switch( PWFlag ) { case 0: Quad = 1; break; case 0x10: Quad = 2; break; case 0x11: Quad = 3; break; case 0x01: Quad = 4; break; default: break; } return Quad; } #if 0 short RAMECIsOK( unsigned char* ECRAds ) { if(( ChkNum( ECRAds, ECDIGIT ) == *(ECRAds+ECDIGIT) )&&( AllIsBCD( ECRAds, ECDIGIT ) == 0 )) return 0; else return 1; } short E2PECIsOK( unsigned char* ECRAds ) { if((( Flag.BatState & F_E2PCheck ) == 0 )&&( AllIsBCD( ECRAds, ECDIGIT ) == 0 )) return 0; else return 1; } //取当前铁电电量地址在ECRgTab表内对应的行号 short GetECRgTabRowNo( unsigned short ECFAds ) { short i; unsigned short StartNo,EndNo; for( i=0;i<ECUnitNum;i++ ) { StartNo = ECRgTab[i].ECFAds; EndNo = StartNo + 5*(ECDIGIT+1); if( ECRgTab[i].ECRgMode == 0 ) //电量包含费率 { if(( ECFAds >= StartNo )&&( ECFAds < EndNo )&&((( ECFAds-StartNo)%(ECDIGIT+1)) == 0 )) break; } else { if( StartNo == ECFAds ) break; //不包含费率 } } if( i == ECUnitNum ) return -1; else return i; } void ECBCDAdd( unsigned char* Dest, unsigned char* Source ) { #if ( ECDIGIT == BYTE5 ) _BCD5ADD( Dest, Source ); #else _BCD4ADD( Dest, Source ); #endif } void ECBCDSub( unsigned char* Dest, unsigned char* Source ) { #if ( ECDIGIT == BYTE5 ) _BCD5SUB( Dest, Source ); #else _BCD4SUB( Dest, Source ); #endif } //检查RAM中的分时电量之和是否等于总 //Source: 存放电量的RAM区 //Type: 0:RAM区不包含每个电量的校验和; 1:每个电量后跟一个校验和。 short TotalFeeECCheck( unsigned char* Source, short Type ) { unsigned char Buff[8]; unsigned char* Ptr; unsigned short Len; short i; #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 unsigned long Value1; unsigned long Value2; #endif Ptr = Buff; if( Type == 0 ) Len = ECDIGIT; else Len = ECDIGIT + 1; RAM_Fill( Ptr, ECDIGIT ); for( i=0;i<4;i++ ) { ECBCDAdd( Ptr, Source+(i+1)*Len ); } #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 #if ( ECDIGIT == BYTE5 ) Value1 = BCD4_Long( Source+1 ); Value2 = BCD4_Long( Ptr+1 ); #else Value1 = BCD4_Long( Source ); Value2 = BCD4_Long( Ptr ); #endif if(( Value1 >= Value2 )&&(( Value1 - Value2 ) <= 4 )) return 0; //总等于分时电量之和 else return 1; #else if( Data_Comp( Ptr, Source, ECDIGIT ) != 0 ) return 1; //总不等于分时电量之和 else return 0; #endif } //根据EEPROM中保存的值进行数据恢复 void ResumeEC( unsigned char* Dest, unsigned char* ECRAds, unsigned short ECFAds ) { short i; short ECRgTabRowNo; unsigned char Buff[30]; unsigned char* Ptr; unsigned char Buff2[10]; unsigned char* Point; unsigned short Addr; unsigned char State=0; unsigned char* TempPtr; Ptr = Buff; Point = Buff2; ECRgTabRowNo = GetECRgTabRowNo( ECFAds ); if( ECRgTabRowNo == -1 ) return; //正常FRAM电量地址 Addr = ECRgTab[ECRgTabRowNo].ECEAds; //取对应的EEPROM中电量的地址 if( ECRgTab[ECRgTabRowNo].ECRgMode == 0 ) //电量包含费率 { TempPtr = Ptr; for( i=0;i<5;i++ ) //读取EEPROM中的总及各费率电量 { E2P_RData( TempPtr, Addr, ECDIGIT ); if( E2PECIsOK( TempPtr ) != 0 ) { State = 1; //EEPROM数据有错 break; } TempPtr += ECDIGIT; Addr += ECDIGIT+1; } if( State == 0 ) { if( TotalFeeECCheck( Ptr, 0 ) != 0 ) State = 1; //总不等于分时电量之和 } E2P_RFM( Point, ECFAds, ECDIGIT ); //再次读取FRAM数据。 if( E2PECIsOK( Point ) == 0 ) { RAM_Write( Dest, Point, ECDIGIT ); //铁电中电量读取正确,以铁电电量为准,放弃从RRPROM中取得的数据 RAM_Write( ECRAds, Dest, ECDIGIT ); //RAM中的值恢复为正确的铁电数据或备份EEPROM数据 *(ECRAds+ECDIGIT) = ChkNum( ECRAds, ECDIGIT ); } else { //铁电数据还是有误 if( State == 0 ) //EEPROM数据正确,包括校验和、BCD码、总等于分时费率之和 { TempPtr = ECRgTab[ECRgTabRowNo].ECRAds; Addr = ECRgTab[ECRgTabRowNo].ECFAds; //取铁电中电量首址 RAM_Write( Dest, Ptr+(((ECFAds-Addr)/(ECDIGIT+1))*ECDIGIT), ECDIGIT ); //恢复电量后需有当前项返回值 //10.12.08 for( i=0;i<5;i++ ) { E2P_WFM( Addr, Ptr+i*ECDIGIT, ECDIGIT ); //将EEPROM中的备份数据替换掉铁电中的错误电量,但可能导致电量减少。 RAM_Write( TempPtr, Ptr+i*ECDIGIT, ECDIGIT ); *(TempPtr+ECDIGIT) = ChkNum( TempPtr, ECDIGIT ); TempPtr += ECDIGIT+1; Addr += ECDIGIT+1; } } else { RAM_Write( Dest, Point, ECDIGIT ); //铁电、EEPROM数据均不对,以最近一次读取的铁电数据返回,但不刷新RAM数据 return; } } } else { //无费率电量 E2P_RData( Ptr, Addr, ECDIGIT ); if( E2PECIsOK( Ptr ) != 0 ) { State = 1; //EEPROM中数据自检错误 } E2P_RFM( Point, ECFAds, ECDIGIT ); //再次读取FRAM数据。 if( E2PECIsOK( Point ) == 0 ) { RAM_Write( Ptr, Point, ECDIGIT ); //铁电中电量读取正确,以铁电电量为准,放弃从RRPROM中取得的数据 } else { //铁电数据还是有误 if( State == 0 ) E2P_WFM( ECFAds, Ptr, ECDIGIT ); //将EEPROM中的备份数据替换掉铁电中的错误电量,可能导致电量减少。 else { RAM_Write( Dest, Point, ECDIGIT ); //铁电、EEPROM数据均不对,以最近一次读取的铁电数据返回,但不刷新RAM数据 return; } } RAM_Write( Dest, Ptr, ECDIGIT ); //返回正确的铁电数据或备份EEPROM数据 RAM_Write( ECRAds, Dest, ECDIGIT ); //RAM中的值恢复为正确的铁电数据或备份EEPROM数据 *(ECRAds+ECDIGIT) = ChkNum( ECRAds, ECDIGIT ); } return; } void GetRamEC( unsigned char* Dest, unsigned char* ECRAds, unsigned short ECFAds ) { if( RAMECIsOK( ECRAds ) == 0 ) { RAM_Write( Dest, ECRAds, ECDIGIT ); //RAM中电量校验和相等,提取RAM电量。 #if( ECDisDecDigitsValid == YesCheck ) //13.03.03 当前电量显示小数位真实有效 if( Disk.DigitsValidFlg == 0x55) AddECMantissa( Dest, ECRAds ); //显示时才添加0.01kWh以下尾数 #endif } else { E2P_RFM( Dest, ECFAds, ECDIGIT ); //RAM中校验和错误,读取FRAM数据。 if( E2PECIsOK( Dest ) == 0 ) { RAM_Write( ECRAds, Dest, ECDIGIT ); //RAM中的值恢复为FRAM中的值 *(ECRAds+ECDIGIT) = ChkNum( ECRAds, ECDIGIT ); } else { if((Flag.Power & F_PwrUp) != 0) //停电状态下不作数据恢复 { ResumeEC( Dest, ECRAds, ECFAds ); } } } } void Read_CMonEC( unsigned char* Dest, unsigned short ECRgAds ) { unsigned short i; unsigned short ECEAds; unsigned short ECFAds; unsigned char* ECRAds; /// if( CombECJust( Dest, ECRgAds ) == 0 ) return; //组合电量判断 for( i=0;i<ECUnitNum;i++ ) { ECEAds = ECRgTab[i].ECEAds; ECRAds = ECRgTab[i].ECRAds; ECFAds = ECRgTab[i].ECFAds; if( ECEAds == ECRgAds ) break; //总电量 else if(( i < (ECUnitNum-1) )&&( ECEAds < ECRgAds )&&( ECRgTab[i+1].ECEAds > ECRgAds )) //费率电量 { if(((( ECRgAds - ECEAds ) % (ECDIGIT+1) ) == 0 )&&( ECRgTab[i].ECRgMode == 0 )) //有费率电量且费率电量地址正确 { ECRAds += ECRgAds - ECEAds; //费率电量RAM地址 ECFAds += ECRgAds - ECEAds; //费率电量铁电地址 break; } } } if( i == ECUnitNum ) { RAM_Fill( Dest, ECDIGIT ); //电量地址错误 return; } GetRamEC( Dest, ECRAds, ECFAds ); //读取RAM或FRAM中的电量 } //总减RAM中的分时电量 //Source: 存放电量的RAM区 //Type: 0:RAM区不包含每个电量的校验和; 1:每个电量后跟一个校验和。 void FeeECSub( unsigned char* Source, short Type ) { unsigned char Buff[(ECDIGIT+1)*5]; unsigned char* Ptr; unsigned short Len; short i; unsigned short FeeNo; unsigned char Buff2[ECDIGIT+1]; //11.06.13 unsigned char* Point; //11.06.13 FeeNo = SM.FeeNo; if(( FeeNo < 1 )||( FeeNo > 4 )) return; //当前费率号非法 Ptr = Buff; Point = Buff2; //11.06.13 if( Type == 0 ) Len = ECDIGIT; else Len = ECDIGIT + 1; RAM_Write( Ptr, Source, (ECDIGIT+1)*5 ); RAM_Fill( Point, Len ); //11.06.13 for( i=1;i<5;i++ ) //11.06.13 { //11.06.13 if( i == FeeNo ) continue; //11.06.13 ECBCDAdd( Point, Ptr+i*Len ); //11.06.13 } //11.06.13 if( Data_Comp( Point, Ptr, Len ) > 0 ) return; //11.06.13 //分时电量之和大于总电量,费率电量不修正。 for( i=1;i<5;i++ ) { if( i == FeeNo ) continue; ECBCDSub( Ptr, Ptr+i*Len ); } RAM_Write( Source+FeeNo*Len, Ptr, ECDIGIT ); } //将当前脉冲电量加入铁电和RAM void AddCurrentEC( unsigned char* ECRAds, unsigned short ECFAds, unsigned char* Source ) { unsigned char* TempPtr; unsigned short FeeNo; FeeNo = SM.FeeNo; if(( FeeNo < 1 )||( FeeNo > 4 )) return; //当前费率号非法 ECBCDAdd( ECRAds, Source ); //取RAM内总电量为基准增加电量 *(ECRAds+ECDIGIT) = ChkNum( ECRAds, ECDIGIT ); TempPtr = ECRAds+FeeNo*(ECDIGIT+1); //取RAM内当前费率电量为基准增加电量 #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 ECBCDAdd( TempPtr, Source+6 ); #else ECBCDAdd( TempPtr, Source ); #endif *(TempPtr+ECDIGIT) = ChkNum( TempPtr, ECDIGIT ); E2P_WFM( ECFAds, ECRAds, ECDIGIT ); //做好校验后分别写入铁电 E2P_WFM( ECFAds+FeeNo*(ECDIGIT+1), TempPtr, ECDIGIT ); } //Source: 当前电量读出后在RAM区临时存放的首址 //AddData: 增加的电量 //Type: 0: 总出错 1:分时电量出错 short ModifyCurrentEC( unsigned char* ECRAds, unsigned short ECFAds, unsigned char* Source, unsigned char* AddData, short Type ) { unsigned short Addr; unsigned char* TempPtr1; unsigned short i; unsigned short FeeNo; FeeNo = SM.FeeNo; if(( FeeNo < 1 )||( FeeNo > 4 )) return 1; //当前费率号非法 TempPtr1 = Source+ECDIGIT; for( i=1;i<5;i++ ) { if( i == FeeNo ) { // TempPtr1 += ECDIGIT+1; //当前费率电量已正确,不再重读 TempPtr1 += ECDIGIT; //当前费率电量已正确,不再重读 //10.05.12 continue; } E2P_RFM( TempPtr1, ECFAds+i*(ECDIGIT+1), ECDIGIT ); //读出其余各费率电量 if( E2PECIsOK( TempPtr1 ) != 0 ) break; //判断从铁电中读出是否合法 // TempPtr1 += ECDIGIT+1; TempPtr1 += ECDIGIT; //10.05.12 } if( Type == 0 ) { TempPtr1 = Source; Addr = ECFAds; } else { TempPtr1 = Source + FeeNo*ECDIGIT; Addr = ECFAds+FeeNo*(ECDIGIT+1); } E2P_RFM( TempPtr1, Addr, ECDIGIT ); //再次读取铁电中的当前总电量或分时电量 // if( E2PECIsOK( TempPtr1 ) == 0 ) //电量正确 if(( E2PECIsOK( TempPtr1 ) == 0 )||( i != 5 )) //电量正确或无法修复以铁电为准 { RAM_Write( ECRAds, Source, ECDIGIT ); RAM_Write( ECRAds+FeeNo*(ECDIGIT+1), Source+FeeNo*ECDIGIT, ECDIGIT ); AddCurrentEC( ECRAds, ECFAds, AddData ); } else if( i == 5 ) { if( Type == 0 ) FeeECAdd( Source, 0 ); //总等于分时电量之和 else FeeECSub( Source, 0 ); //分时电量等于总减去其余分时电量 TempPtr1 = ECRAds; for( i=0;i<5;i++ ) { RAM_Write( TempPtr1, Source+i*ECDIGIT, ECDIGIT ); *(TempPtr1+ECDIGIT) = ChkNum( TempPtr1, ECDIGIT ); TempPtr1 += ECDIGIT+1; } AddCurrentEC( ECRAds, ECFAds, AddData ); } // else return 1; return 0; } #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 void FeeECPulseAdd( unsigned short* PL_Cum, unsigned char* PL_Chk, unsigned char Pulse_Cum ) { unsigned short* PL_CumPtr; unsigned char* PL_ChkPtr; unsigned short Temp; if(( SM.FeeNo < 1 )||( SM.FeeNo > 4 )) return; //当前费率号非法 Temp = SM.FeeNo; Temp -= 1; PL_CumPtr = PL_Cum; PL_CumPtr += Temp; PL_ChkPtr = PL_Chk; PL_ChkPtr += Temp; //新国网 //13.08.30 //#if (( METERTYPE == U220_I20A__80A320 )||( METERTYPE == U220_I20A__100A240 )||( METERTYPE == U220_I20A__120A240 )||( METERTYPE == U220_I30A__100A240 )||( METERTYPE == U220_I10A__100A240 )) // *PL_CumPtr += (unsigned short)Pulse_Cum * 10; //#else *PL_CumPtr += Pulse_Cum; //#endif *PL_ChkPtr = ChkNum( (unsigned char*)PL_CumPtr, 2 ); } #endif #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 short ECRgSum( short ECItem, unsigned short Data, unsigned short FData ) { unsigned short ECFAds; unsigned char* ECRAds; unsigned char Buff[30]; // unsigned char Buff2[6]; unsigned char Buff2[12]; unsigned char* Ptr; unsigned char* Source; unsigned char* TempPtr1; unsigned short i; unsigned char FStateZ=0; unsigned char FStateF=0; unsigned char RState=0; unsigned short FeeNo; Ptr = Buff; Source = Buff2; RAM_Fill( Ptr, 30 ); // RAM_Fill( Source, 6 ); RAM_Fill( Source, 12 ); Word_BCD( Source+1, Data ); //两位小数有效? Word_BCD( Source+7, FData ); //两位小数有效? ECRAds = ECRgTab[ECItem].ECRAds; ECFAds = ECRgTab[ECItem].ECFAds; FeeNo = SM.FeeNo; if(( FeeNo < 1 )||( FeeNo > 4 )) return 1; //当前费率号非法 if( ECRgTab[ECItem].ECRgMode == 0 ) //带费率电量 { E2P_RFM( Ptr, ECFAds, ECDIGIT ); if( E2PECIsOK( Ptr ) != 0 ) FStateZ = 1; //总电量是否合法 TempPtr1 = Ptr+FeeNo*ECDIGIT; E2P_RFM( TempPtr1, ECFAds+FeeNo*(ECDIGIT+1), ECDIGIT ); if( E2PECIsOK( TempPtr1 ) != 0 ) FStateF = 1; //分时电量是否合法 if(( FStateZ == 0 )&&( FStateF == 0 )) //总和当前费率电量读铁电均正确 { RAM_Write( ECRAds, Ptr, ECDIGIT ); RAM_Write( ECRAds+FeeNo*(ECDIGIT+1), Ptr+FeeNo*ECDIGIT, ECDIGIT ); AddCurrentEC( ECRAds, ECFAds, Source ); } else //读总电量和分时电量至少1个不成功 { if( TotalFeeECCheck( ECRAds, 1 ) == 0 ) //判断RAM区的电量总是否等于分时电量之和 { for( i=0;i<5;i++ ) { if( RAMECIsOK( ECRAds+i*(ECDIGIT+1) ) != 0 ) //RAM区的各电量自检是否正确 { RState = 1; //有电量非法,校验不对或为非BCD码 break; } } } else RState = 1; //RAM区电量有误,总与分时之和不等 if( RState == 0 ) //RAM内电量数据均合法。 { AddCurrentEC( ECRAds, ECFAds, Source ); } else //RAM内电量有误 { if(( FStateZ == 1 )&&( FStateF == 0 )) //总错误、当前费率电量读铁电正确 { return ModifyCurrentEC( ECRAds, ECFAds, Ptr, Source, 0 ); } else if(( FStateZ == 0 )&&( FStateF == 1 )) //总正确和当前费率电量读铁电错误 { return ModifyCurrentEC( ECRAds, ECFAds, Ptr, Source, 1 ); } // else return 1; else { ResumeEC( Ptr, ECRAds, ECFAds ); //若RAM和铁电均有错,则用EEPROM内电量恢复 //10.12.08 ResumeEC( Ptr+FeeNo*ECDIGIT, ECRAds+FeeNo*(ECDIGIT+1), ECFAds+FeeNo*(ECDIGIT+1) ); //若RAM和铁电均有错,则用EEPROM内电量恢复 //10.12.08 RAM_Write( ECRAds, Ptr, ECDIGIT ); //全错以铁电为准 RAM_Write( ECRAds+FeeNo*(ECDIGIT+1), Ptr+FeeNo*ECDIGIT, ECDIGIT ); AddCurrentEC( ECRAds, ECFAds, Source ); // return 1; } } } } else { E2P_RFM( Ptr, ECFAds, ECDIGIT ); if( E2PECIsOK( Ptr ) != 0 ) FStateZ = 1; if( RAMECIsOK( ECRAds ) != 0 ) RState = 1; if(( FStateZ == 1 )&&( RState == 1 )) ResumeEC( Ptr, ECRAds, ECFAds ); //若RAM和铁电均有错,则用EEPROM内电量恢复 //10.12.08 // if(( FStateZ == 0 )||( RState == 0 )) // { // if( FStateZ == 0 ) RAM_Write( ECRAds, Ptr, ECDIGIT ); //以铁电数据为准 if( RState != 0 ) RAM_Write( ECRAds, Ptr, ECDIGIT ); //只要RAM不对均以铁电数据为准 ECBCDAdd( ECRAds, Source ); *(ECRAds+ECDIGIT) = ChkNum( ECRAds, ECDIGIT ); E2P_WFM( ECFAds, ECRAds, ECDIGIT ); // } // else return 1; } return 0; } #else short ECRgSum( short ECItem, unsigned short Data ) { unsigned short ECFAds; unsigned char* ECRAds; unsigned char Buff[30]; unsigned char Buff2[6]; unsigned char* Ptr; unsigned char* Source; unsigned char* TempPtr1; unsigned short i; unsigned char FStateZ=0; unsigned char FStateF=0; unsigned char RState=0; unsigned short FeeNo; Ptr = Buff; Source = Buff2; RAM_Fill( Ptr, 30 ); RAM_Fill( Source, 6 ); Word_BCD( Source+1, Data ); //两位小数有效? ECRAds = ECRgTab[ECItem].ECRAds; ECFAds = ECRgTab[ECItem].ECFAds; FeeNo = SM.FeeNo; if(( FeeNo < 1 )||( FeeNo > 4 )) return 1; //当前费率号非法 if( ECRgTab[ECItem].ECRgMode == 0 ) //带费率电量 { E2P_RFM( Ptr, ECFAds, ECDIGIT ); if( E2PECIsOK( Ptr ) != 0 ) FStateZ = 1; //总电量是否合法 TempPtr1 = Ptr+FeeNo*ECDIGIT; E2P_RFM( TempPtr1, ECFAds+FeeNo*(ECDIGIT+1), ECDIGIT ); if( E2PECIsOK( TempPtr1 ) != 0 ) FStateF = 1; //分时电量是否合法 if(( FStateZ == 0 )&&( FStateF == 0 )) //总和当前费率电量读铁电均正确 { RAM_Write( ECRAds, Ptr, ECDIGIT ); RAM_Write( ECRAds+FeeNo*(ECDIGIT+1), Ptr+FeeNo*ECDIGIT, ECDIGIT ); AddCurrentEC( ECRAds, ECFAds, Source ); } else //读总电量和分时电量至少1个不成功 { if( TotalFeeECCheck( ECRAds, 1 ) == 0 ) //判断RAM区的电量总是否等于分时电量之和 { for( i=0;i<5;i++ ) { if( RAMECIsOK( ECRAds+i*(ECDIGIT+1) ) != 0 ) //RAM区的各电量自检是否正确 { RState = 1; //有电量非法,校验不对或为非BCD码 break; } } } else RState = 1; //RAM区电量有误,总与分时之和不等 if( RState == 0 ) //RAM内电量数据均合法。 { AddCurrentEC( ECRAds, ECFAds, Source ); } else //RAM内电量有误 { if(( FStateZ == 1 )&&( FStateF == 0 )) //总错误、当前费率电量读铁电正确 { return ModifyCurrentEC( ECRAds, ECFAds, Ptr, Source, 0 ); } else if(( FStateZ == 0 )&&( FStateF == 1 )) //总正确和当前费率电量读铁电错误 { return ModifyCurrentEC( ECRAds, ECFAds, Ptr, Source, 1 ); } // else return 1; else { ResumeEC( Ptr, ECRAds, ECFAds ); //若RAM和铁电均有错,则用EEPROM内电量恢复 //10.12.08 ResumeEC( Ptr+FeeNo*ECDIGIT, ECRAds+FeeNo*(ECDIGIT+1), ECFAds+FeeNo*(ECDIGIT+1) ); //若RAM和铁电均有错,则用EEPROM内电量恢复 //10.12.08 RAM_Write( ECRAds, Ptr, ECDIGIT ); //全错以铁电为准 RAM_Write( ECRAds+FeeNo*(ECDIGIT+1), Ptr+FeeNo*ECDIGIT, ECDIGIT ); AddCurrentEC( ECRAds, ECFAds, Source ); // return 1; } } } } else { E2P_RFM( Ptr, ECFAds, ECDIGIT ); if( E2PECIsOK( Ptr ) != 0 ) FStateZ = 1; if( RAMECIsOK( ECRAds ) != 0 ) RState = 1; if(( FStateZ == 1 )&&( RState == 1 )) ResumeEC( Ptr, ECRAds, ECFAds ); //若RAM和铁电均有错,则用EEPROM内电量恢复 //10.12.08 // if(( FStateZ == 0 )||( RState == 0 )) // { // if( FStateZ == 0 ) RAM_Write( ECRAds, Ptr, ECDIGIT ); //以铁电数据为准 if( RState != 0 ) RAM_Write( ECRAds, Ptr, ECDIGIT ); //只要RAM不对均以铁电数据为准 ECBCDAdd( ECRAds, Source ); *(ECRAds+ECDIGIT) = ChkNum( ECRAds, ECDIGIT ); E2P_WFM( ECFAds, ECRAds, ECDIGIT ); // } // else return 1; } return 0; } #endif void EC_Meas(void) { unsigned char YPulse_Cum=0; unsigned char WPulse_Cum=0; unsigned char YPulse_CumChk; unsigned char WPulse_CumChk; unsigned char Temp2; unsigned short Temp; short Meter_Quad,i; unsigned short PS32; //新国网 //13.08.30 #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 unsigned short* ECRamBufAdsPtr; unsigned char* ECRamBufChkAdsPtr; unsigned short* FeeECRamBufAdsPtr; unsigned char* FeeECRamBufChkAdsPtr; unsigned short Temp3; #endif #if ( MEASCHIP == IDT90E32 ) unsigned short TempInt; #endif // WDTCTL = WDT_ARST_1000; HT_FreeDog(); //先按1000脉冲常数算 PS32 = (Measur_Const/100);//MSpec.RMeterConst / 10; //新国网 //13.08.30 if(( ECInt.YPulse_Cum != 0 )||( ECInt.WPulse_Cum != 0 )) { __disable_irq();//_DINT(); YPulse_Cum = ECInt.YPulse_Cum; WPulse_Cum = ECInt.WPulse_Cum; YPulse_CumChk = ECInt.YPulse_CumChk; WPulse_CumChk = ECInt.WPulse_CumChk; ECInt.YPulse_Cum = 0; ECInt.WPulse_Cum = 0; ECInt.YPulse_CumChk = 0xA5; ECInt.WPulse_CumChk = 0xA5; __enable_irq();//_EINT(); Temp2 = YPulse_Cum + 0xA5; if( YPulse_CumChk != Temp2 ) YPulse_Cum = 0; Temp2 = WPulse_Cum + 0xA5; if( WPulse_CumChk != Temp2 ) WPulse_Cum = 0; #if ( FRAMPulseValidCheck == YesCheck ) //16.01.26 if(( YPulse_Cum != 0 )||( WPulse_Cum != 0 )) { if( SM.PulseFlag == 0 ) //已产生脉冲标记 //16.01.26 { E2P_WFM( FPulseValidFlag, (unsigned char*)&SM.PulseFlag, 1 ); //下电后保存RAM内的不到0.01Kwh的脉冲个数有效标志 } SM.PulseFlag = 1; } #endif } Meter_Quad = GetMQuad( Real.PWFlag,3 ); //取当前象限 if( YPulse_Cum !=0 ) { switch (Meter_Quad ) { case 2: case 3: ECP.PL_CumPn += YPulse_Cum; ECP.PL_ChkPn = ChkNum( (unsigned char*)&ECP.PL_CumPn, 2 ); MDBufPn.MD_Cum += YPulse_Cum; //有功反向需量 ECP.PL_CumPn_Dis += YPulse_Cum; #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 FeeECPulseAdd( &FeeECP.PL_CumPn1, &FeeECP.PL_ChkPn1, YPulse_Cum ); #endif break; //正反向合计? case 1: case 4: ECP.PL_CumPp += YPulse_Cum; ECP.PL_ChkPp = ChkNum( (unsigned char*)&ECP.PL_CumPp, 2 ); MDBufPp.MD_Cum += YPulse_Cum; //有功正向需量 ECP.PL_CumPp_Dis += YPulse_Cum; #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 FeeECPulseAdd( &FeeECP.PL_CumPp1, &FeeECP.PL_ChkPp1, YPulse_Cum ); #endif break; default: break; } } if( WPulse_Cum !=0 ) { switch (Meter_Quad ) { case 1: ECP.PL_CumQ1 += WPulse_Cum; ECP.PL_ChkQ1 = ChkNum( (unsigned char*)&ECP.PL_CumQ1, 2 ); ECP.PL_CumQp += WPulse_Cum; ECP.PL_ChkQp = ChkNum( (unsigned char*)&ECP.PL_CumQp, 2 ); break; case 2: ECP.PL_CumQ2 += WPulse_Cum; ECP.PL_ChkQ2 = ChkNum( (unsigned char*)&ECP.PL_CumQ2, 2 ); ECP.PL_CumQp += WPulse_Cum; ECP.PL_ChkQp = ChkNum( (unsigned char*)&ECP.PL_CumQp, 2 ); break; case 3: ECP.PL_CumQ3 += WPulse_Cum; ECP.PL_ChkQ3 = ChkNum( (unsigned char*)&ECP.PL_CumQ3, 2 ); ECP.PL_CumQn+= WPulse_Cum; ECP.PL_ChkQn= ChkNum( (unsigned char*)&ECP.PL_CumQn, 2 ); break; case 4: ECP.PL_CumQ4 += WPulse_Cum; ECP.PL_ChkQ4 = ChkNum( (unsigned char*)&ECP.PL_CumQ4, 2 ); ECP.PL_CumQn+= WPulse_Cum; ECP.PL_ChkQn= ChkNum( (unsigned char*)&ECP.PL_CumQn, 2 ); break; default: break; } #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 switch (Meter_Quad ) { case 1: FeeECPulseAdd( &FeeECP.PL_CumQ11, &FeeECP.PL_ChkQ11, WPulse_Cum ); break; case 2: FeeECPulseAdd( &FeeECP.PL_CumQ21, &FeeECP.PL_ChkQ21, WPulse_Cum ); break; case 3: FeeECPulseAdd( &FeeECP.PL_CumQ31, &FeeECP.PL_ChkQ31, WPulse_Cum ); break; case 4: FeeECPulseAdd( &FeeECP.PL_CumQ41, &FeeECP.PL_ChkQ41, WPulse_Cum ); break; default: break; } #endif } #if ( FeeECIndependence == YesCheck ) //11.01.15 费率电量独立计量 for( i=0;i<ECUnitNum;i++ ) //大于0.01度写铁电存储器 { ECRamBufAdsPtr = ECRgTab[i].ECRamBufAds; ECRamBufChkAdsPtr = ECRgTab[i].ECRamBufChkAds; if( *ECRamBufChkAdsPtr != ChkNum( (unsigned char*)ECRamBufAdsPtr, 2 ) ) { *ECRamBufAdsPtr = 0; *ECRamBufChkAdsPtr = 0; } Temp = 0; #if ( MEASCHIP == IDT90E32 ) if( i < 8 ) TempInt = PS32; else TempInt = PS32*10; //分相有无功电量和视在电量脉冲是从IDT90E32中读出,单位为0.1CF if( *ECRamBufAdsPtr >= TempInt ) { Temp = *ECRamBufAdsPtr / TempInt; *ECRamBufAdsPtr -= Temp * TempInt; *ECRamBufChkAdsPtr = ChkNum( (unsigned char*)ECRamBufAdsPtr, 2 ); } #else if( *ECRamBufAdsPtr >= PS32 ) { Temp = *ECRamBufAdsPtr / PS32; *ECRamBufAdsPtr -= Temp * PS32; *ECRamBufChkAdsPtr = ChkNum( (unsigned char*)ECRamBufAdsPtr, 2 ); } #endif if( i < 8 ) { Temp3 = 0; FeeECRamBufAdsPtr = FeeECRgTab[i].ECRamBufAds; FeeECRamBufAdsPtr += (SM.FeeNo-1); FeeECRamBufChkAdsPtr = FeeECRgTab[i].ECRamBufChkAds; FeeECRamBufChkAdsPtr += (SM.FeeNo-1); if( *FeeECRamBufChkAdsPtr != ChkNum( (unsigned char*)FeeECRamBufAdsPtr, 2 ) ) { *FeeECRamBufAdsPtr = 0; *FeeECRamBufChkAdsPtr = 0; } if( *FeeECRamBufAdsPtr >= PS32 ) { Temp3 = *FeeECRamBufAdsPtr / PS32; *FeeECRamBufAdsPtr -= Temp3 * PS32; *FeeECRamBufChkAdsPtr = ChkNum( (unsigned char*)FeeECRamBufAdsPtr, 2 ); } } else Temp3 = Temp; if(( Temp > 100 )||( Temp3 > 100 )) continue; //数据超差,不计入电量。 if(( Temp == 0 )&&( Temp3 == 0 )) continue; //无脉冲,返回。 //11.03.01 ECRgSum( i, Temp, Temp3 ); /* #if( LocalSmartMeter == YesCheck ) //17.04.22 if((( i == 0 )||(( i == 1 )&&(( Para.RActiveMode & 0x0C ) == 0x04 )))&&( Temp != 0 )) IncConsumECSum( Temp, 0 ); //增加正向有功阶梯用电金额 //15.07.31 if((( i == 0 )||(( i == 1 )&&(( Para.RActiveMode & 0x0C ) == 0x04 )))&&( Temp3 != 0 )) IncConsumECSum( Temp3, 1 ); //增加正向有功费率用电金额 //新国网 //13.11.30 //15.07.31 #endif #if ( GeneralSmartMeter == YesCheck ) //普通智能表 //新国网 //13.11.06 #else //新国网 //13.11.06 #if ( MagnKeepRelay == NoCheck ) //10.08.07 if((( i == 0 )||(( i == 1 )&&(( Para.RActiveMode & 0x0C ) == 0x04 )))&&( Temp != 0 )) //继电器外置表在跳闸后总电量每走0.01kWh就再拉闸一次。 { if(( Para.RMeterRelayState == 0x1A )&&( ICComm.RelayDrivePulseWidth == 0 )) //已拉闸且不是正在拉闸 //10.08.07 { RelayDrive( RELAY_OFF ); } } #endif #endif //新国网 //13.11.06 */ } #else for( i=0;i<ECUnitNum;i++ ) //大于0.01度写铁电存储器 { if( *ECRgTab[i].ECRamBufChkAds != ChkNum( (unsigned char*)ECRgTab[i].ECRamBufAds, 2 ) ) { *ECRgTab[i].ECRamBufAds = 0; *ECRgTab[i].ECRamBufChkAds = 0; } #if ( MEASCHIP == IDT90E32 ) if( i < 6 ) TempInt = PS32; else TempInt = PS32*10; //分相有无功电量和视在电量脉冲是从IDT90E32中读出,单位为0.1CF if( *ECRgTab[i].ECRamBufAds >= TempInt ) { Temp = *ECRgTab[i].ECRamBufAds / TempInt; *ECRgTab[i].ECRamBufAds -= Temp * TempInt; #else if( *ECRgTab[i].ECRamBufAds >= PS32 ) { Temp = *ECRgTab[i].ECRamBufAds / PS32; *ECRgTab[i].ECRamBufAds -= Temp * PS32; #endif *ECRgTab[i].ECRamBufChkAds = ChkNum( (unsigned char*)ECRgTab[i].ECRamBufAds, 2 ); if( Temp > 100 ) continue; //数据超差,不计入电量。 ECRgSum( i, Temp); // if( Temp > 100 ) // { // *ECRgTab[i].ECRamBufAds -= Temp * PS32; // *ECRgTab[i].ECRamBufChkAds = ChkNum( (unsigned char*)ECRgTab[i].ECRamBufAds, 2 ); // continue; //数据超差,不计入电量。 // } // if( ECRgSum( i, Temp) == 0 ) // { // *ECRgTab[i].ECRamBufAds -= Temp * PS32; // *ECRgTab[i].ECRamBufChkAds = ChkNum( (unsigned char*)ECRgTab[i].ECRamBufAds, 2 ); // } // else continue; /* #if( LocalSmartMeter == YesCheck ) //17.04.22 if(( i == 0 )||(( i == 1 )&&(( Para.RActiveMode & 0x0C ) == 0x04 ))) IncConsumECSum( Temp ); //增加正向有功用电金额 #endif #if ( GeneralSmartMeter == YesCheck ) //普通智能表 //新国网 //13.11.06 #else //新国网 //13.11.06 //#if (( JiangSuRequire == YesCheck )&&( MagnKeepRelay == NoCheck)) //10.08.07 #if ( MagnKeepRelay == NoCheck ) //10.08.07 if( i == 0 ) //继电器外置表在跳闸后每走0.01kWh就再拉闸一次。 { // if( Para.RMeterRelayState == 0x1A ) //已拉闸 if(( Para.RMeterRelayState == 0x1A )&&( ICComm.RelayDrivePulseWidth == 0 )) //已拉闸且不是正在拉闸 //10.08.07 { RelayDrive( RELAY_OFF ); // if( Un55VoltJudge() == 0 ) RelayDrive( RELAY_OFF ); //10.01.18 } } #endif #endif */ } } #endif } #endif
2.0625
2
2024-11-18T18:42:18.345791+00:00
2023-08-30T21:39:44
b889d22c6e08dc6b3180d489cf53f372d9aa0b96
{ "blob_id": "b889d22c6e08dc6b3180d489cf53f372d9aa0b96", "branch_name": "refs/heads/main", "committer_date": "2023-08-30T21:39:44", "content_id": "80d366f917af9ed6f2ad24999cd586042ca5efef", "detected_licenses": [ "MIT" ], "directory_id": "78dc9f153549b281be709227bc9897931b06260d", "extension": "h", "filename": "MSChapp.h", "fork_events_count": 107, "gha_created_at": "2020-06-08T21:52:10", "gha_event_created_at": "2023-09-14T18:49:44", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 270838404, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2407, "license": "MIT", "license_type": "permissive", "path": "/generation/WinSDK/RecompiledIdlHeaders/um/MSChapp.h", "provenance": "stackv2-0030.json.gz:26607", "repo_name": "microsoft/win32metadata", "revision_date": "2023-08-30T21:39:44", "revision_id": "5bf233f04d45f7a697e112e9639722551103eb07", "snapshot_id": "dff35b4fe904d556162cee5133294c4498f1a79a", "src_encoding": "UTF-8", "star_events_count": 1240, "url": "https://raw.githubusercontent.com/microsoft/win32metadata/5bf233f04d45f7a697e112e9639722551103eb07/generation/WinSDK/RecompiledIdlHeaders/um/MSChapp.h", "visit_date": "2023-09-01T19:51:22.972899" }
stackv2
/*++ Copyright (C) Microsoft Corporation, 1999 Module Name: mschapp - MS-CHAP Password Change API Abstract: These APIs correspond to the MS-CHAP RFC -2433 sections 9 and 10. In order to develop an MS-CHAP RAS server that works with an NT domain, these APIs are required. Only wide (Unicode) versions of these apis will be available. These are the 2 callable APIs: * MSChapSrvChangePassword * MsChapSrvChangePassword2 --*/ #ifndef _MSCHAPP_H_ #define _MSCHAPP_H_ #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #ifndef _NTCRYPT_ #define CYPHER_BLOCK_LENGTH 8 typedef struct _CYPHER_BLOCK { CHAR data[CYPHER_BLOCK_LENGTH]; }CYPHER_BLOCK; typedef struct _LM_OWF_PASSWORD { CYPHER_BLOCK data[2]; } LM_OWF_PASSWORD; typedef LM_OWF_PASSWORD * PLM_OWF_PASSWORD; typedef LM_OWF_PASSWORD NT_OWF_PASSWORD; typedef NT_OWF_PASSWORD * PNT_OWF_PASSWORD; typedef struct _SAMPR_ENCRYPTED_USER_PASSWORD { UCHAR Buffer[ (256 * 2) + 4 ]; } SAMPR_ENCRYPTED_USER_PASSWORD, *PSAMPR_ENCRYPTED_USER_PASSWORD; typedef struct _ENCRYPTED_LM_OWF_PASSWORD { CYPHER_BLOCK data[2]; } ENCRYPTED_LM_OWF_PASSWORD, *PENCRYPTED_LM_OWF_PASSWORD; typedef ENCRYPTED_LM_OWF_PASSWORD ENCRYPTED_NT_OWF_PASSWORD; typedef ENCRYPTED_NT_OWF_PASSWORD * PENCRYPTED_NT_OWF_PASSWORD; #endif // _NTCRYPT // // Change a password. // extern WINADVAPI DWORD WINAPI MSChapSrvChangePassword( _In_ PWSTR ServerName, _In_ PWSTR UserName, _In_ BOOLEAN LmOldPresent, _In_ PLM_OWF_PASSWORD LmOldOwfPassword, _In_ PLM_OWF_PASSWORD LmNewOwfPassword, _In_ PNT_OWF_PASSWORD NtOldOwfPassword, _In_ PNT_OWF_PASSWORD NtNewOwfPassword ); // // Change a password using mutual encryption. // extern WINADVAPI DWORD WINAPI MSChapSrvChangePassword2( _In_ PWSTR ServerName, _In_ PWSTR UserName, _In_ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldNt, _In_ PENCRYPTED_NT_OWF_PASSWORD OldNtOwfPasswordEncryptedWithNewNt, _In_ BOOLEAN LmPresent, _In_ PSAMPR_ENCRYPTED_USER_PASSWORD NewPasswordEncryptedWithOldLm, _In_ PENCRYPTED_LM_OWF_PASSWORD OldLmOwfPasswordEncryptedWithNewLmOrNt ); #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion #endif // _MSCHAPP_H_
2.09375
2
2024-11-18T18:42:18.454168+00:00
2016-01-31T08:57:11
99a8bf2a3d24401765b5e11e647623e67ff08d85
{ "blob_id": "99a8bf2a3d24401765b5e11e647623e67ff08d85", "branch_name": "refs/heads/master", "committer_date": "2016-01-31T08:57:11", "content_id": "956e8cfab01d3f4996b58416601bc2f9b2c715cd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d97466662adf6d658d01b0e362ed3b8640acca53", "extension": "c", "filename": "SPCString.c", "fork_events_count": 2, "gha_created_at": "2015-11-13T15:12:48", "gha_event_created_at": "2015-11-17T11:32:34", "gha_language": null, "gha_license_id": null, "github_id": 46129015, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1373, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/SPCString.c", "provenance": "stackv2-0030.json.gz:26736", "repo_name": "dannylsl/SPCleaner", "revision_date": "2016-01-31T08:57:11", "revision_id": "8bb69d3224eb93579a4b12b2d35373647a4a93d9", "snapshot_id": "a113eedfce5dd6d0689fb4f774f78262f2eaf108", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dannylsl/SPCleaner/8bb69d3224eb93579a4b12b2d35373647a4a93d9/lib/SPCString.c", "visit_date": "2016-08-11T13:37:04.427570" }
stackv2
#include "SPCString.h" char *SPC_LTrim(char *line) { char *ptr = line; while(*ptr == ' ' || *ptr == '\t') { ptr++; } strcpy(line, ptr); return line; } char *SPC_RTrim(char *line) { char CRLF[CRLF_LEN] = {0}; int len = strlen(line); char *end; if(len <= 1) { return line; } end = line + len - 1; if(*end == '\r') { /* MAC CRLF */ strcpy(CRLF,"\r\0\0"); }else if(*end == '\n') { end--; if(*end == '\r') { /* DOS CRLF */ if( len == 2) { return line; } strcpy(CRLF,"\r\n\0"); }else { /* UNIX CRLF */ strcpy(CRLF,"\n\0\0"); } }else{ /* NO NEW LINE */ memset(CRLF, 0x00, CRLF_LEN); } end--; while(end != line) { if(*end == ' ' || *end == '\t') { *end = '\0'; end--; }else{ break; } } strcat(line, CRLF); return line; } char *SPC_Trim(char *line) { return SPC_RTrim(SPC_LTrim(line)); } char *SPC_Strip(char *line) { int len; char *end = NULL; if(line == NULL) return line; len = strlen(line); end = line + len - 1; while(*end == '\n' || *end == '\r') { *end = '\0'; end = end - 1; } return line; }
2.953125
3
2024-11-18T18:42:18.859484+00:00
2021-03-19T16:05:28
3da2016ee964ddae2e631670d800be85432fd970
{ "blob_id": "3da2016ee964ddae2e631670d800be85432fd970", "branch_name": "refs/heads/master", "committer_date": "2021-03-19T16:05:28", "content_id": "30b77fae2cd339ed47faedc7627960a3385932a0", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "b16cb9345a7c9450c38b0d4fdf22237c26932202", "extension": "c", "filename": "test_TASession.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3679341, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4107, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/test/TA/test_TASession.c", "provenance": "stackv2-0030.json.gz:27121", "repo_name": "th0x4c/octa", "revision_date": "2021-03-19T16:05:28", "revision_id": "0512443cf96d531802a1f2a234ed041f28502502", "snapshot_id": "2efc871b837d80f22f0fcd11fae84a9d2bb5bf53", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/th0x4c/octa/0512443cf96d531802a1f2a234ed041f28502502/test/TA/test_TASession.c", "visit_date": "2021-06-06T21:27:08.562024" }
stackv2
/* * test_TASession.c * TA * * Created by Takashi Hashizume on 03/04/12. * Copyright 2012 Takashi Hashizume. All rights reserved. */ #include <TA/TASession.h> #include "../munit.h" #include <stdio.h> /* snprintf */ #include <stdlib.h> /* malloc exit free */ #include <string.h> /* strcpy */ #include <time.h> /* nanosleep */ int mu_nfail=0; int mu_ntest=0; int mu_nassert=0; #define TX_COUNT 5 #define MSGSIZE 64 static int myTX(TASession self, void **inout) { int ret = 0; char *msg = (char *)*inout; TALog log = TASession_log(self); char logmsg[MSGSIZE] = ""; TATXStat stat = TASession_currentStatByName(self, "my TX"); struct timespec sleeptp; snprintf(logmsg, MSGSIZE, "myTX input: %s", msg); TALog_info(log, logmsg); strcpy(msg, "from myTX"); sleeptp.tv_sec = 0; sleeptp.tv_nsec = 10000000; /* 10ms */ nanosleep(&sleeptp, NULL); if (TATXStat_count(stat) == 2) ret = 999; return ret; } static void myafterTX(TASession self, void **inout) { char *msg = (char *)*inout; TALog log = TASession_log(self); char logmsg[MSGSIZE] = ""; TATXStat stat = TASession_currentStatByName(self, "my TX"); snprintf(logmsg, MSGSIZE, "myafterTX input: %s", msg); TALog_info(log, logmsg); strcpy(msg, "from myafterTX"); if (TATXStat_count(stat) == TX_COUNT) TASession_setStatus(self, TASession_STOP); } static void mywhen_errorTX(TASession self, void **inout, int error_code, char *error_message, size_t error_message_size) { char *msg = (char *)*inout; TALog log = TASession_log(self); char logmsg[MSGSIZE] = ""; snprintf(logmsg, MSGSIZE, "mywhen_errorTX input: %s", msg); TALog_info(log, logmsg); strcpy(msg, "from mywhen_errorTX"); snprintf(error_message, error_message_size, "ERROR-%d Occurred", error_code); } static void mysetup(TASession self, void **inout) { char *msg = (char *)*inout; TALog log = TASession_log(self); char logmsg[MSGSIZE] = ""; snprintf(logmsg, MSGSIZE, "mysetup input: %s", msg); TALog_info(log, logmsg); strcpy(msg, "from mysetup"); TASession_setTX(self, myTX, "my TX"); TASession_setAfterTX(self, myafterTX, "my TX"); TASession_setWhenErrorTX(self, mywhen_errorTX, "my TX"); TASession_setStatus(self, TASession_RUNNING); } static char *myselectTX(TASession self) { #define MAX_NAME_SIZE 64 static char mytx_name[MAX_NAME_SIZE] = "my TX"; return mytx_name; } static void myteardown(TASession self, void **inout) { char *msg = (char *)*inout; TALog log = TASession_log(self); char logmsg[MSGSIZE] = ""; TATXStat stat = TASession_statByNameInPeriodInPhase(self, "my TX", TASession_MEASUREMENT, TASession_TX); #define DESC_SIZE 512 char desc[DESC_SIZE] = ""; snprintf(logmsg, MSGSIZE, "myteardown input: %s", msg); TALog_info(log, logmsg); strcpy(msg, "from myteardown"); TALog_info(log, TATXStat_description(stat, desc, DESC_SIZE)); } static void test_TASession_deepCopy() { TASession tasession = TASession_init(); TASession destses = NULL; destses = malloc(TASession_sizeof()); if (destses == NULL) exit(1); TASession_setID(tasession, 1); TASession_setSetup(tasession, mysetup); TASession_setSelectTX(tasession, myselectTX); TASession_setTeardown(tasession, myteardown); TASession_deepCopy(tasession, destses); mu_assert(TASession_ID(destses) == 1); } static void test_TASession_main() { TASession tasession = TASession_init(); char *msg = ""; msg = malloc(sizeof(char) * MSGSIZE); if (msg == NULL) exit(1); strcpy(msg, "from main"); TASession_setID(tasession, 1); TASession_setSetup(tasession, mysetup); TASession_setSelectTX(tasession, myselectTX); TASession_setTeardown(tasession, myteardown); mu_assert(TASession_main(tasession, (void **)&msg) == 0); TASession_release(tasession); free(msg); } int main(int argc, char *argv[]) { mu_run_test(test_TASession_deepCopy); mu_run_test(test_TASession_main); mu_show_failures(); return mu_nfail != 0; }
2.21875
2
2024-11-18T18:42:19.293531+00:00
2018-05-25T14:46:20
551f5aff92259e31ce6845af20dc5bcaff631dba
{ "blob_id": "551f5aff92259e31ce6845af20dc5bcaff631dba", "branch_name": "refs/heads/master", "committer_date": "2018-05-25T14:46:20", "content_id": "6cc0b672793d4d0a30b10fbafe206c36acb852f7", "detected_licenses": [ "MIT" ], "directory_id": "35e328eecc78aad18baa17611fa08d61cc66633d", "extension": "h", "filename": "coroutine.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1388, "license": "MIT", "license_type": "permissive", "path": "/include/agents/coroutine.h", "provenance": "stackv2-0030.json.gz:27505", "repo_name": "daodaoliang/libpull", "revision_date": "2018-05-25T14:46:20", "revision_id": "79324914b491d7317cd12e036ad9fcd4b69e97d5", "snapshot_id": "06229ae0eece0fcfa06f1310c3540177871a58dc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daodaoliang/libpull/79324914b491d7317cd12e036ad9fcd4b69e97d5/include/agents/coroutine.h", "visit_date": "2020-03-18T18:28:20.154325" }
stackv2
#ifndef AGENTS_COROUTINE_H_ #define AGENTS_COROUTINE_H_ #define PULL_BEGIN(state) \ static agent_t agent = { \ .current_state = state, \ .current_error = PULL_SUCCESS, \ .required_action = CONTINUE, \ }; \ switch(agent.current_state) { case 0: \ #define PULL_CONTINUE(state) \ do { \ agent.current_state=state; \ agent.current_error=PULL_SUCCESS; \ agent.required_action=CONTINUE; \ return agent; \ case state:; \ } while(0) \ #define PULL_SEND(state) \ do { \ agent.current_state=state; \ agent.current_error=PULL_SUCCESS; \ agent.required_action=SEND; \ return agent; \ case state:; \ } while(0); \ #define PULL_RECOVER(state, error) \ do { \ agent.current_state=state; \ agent.current_error=error; \ agent.required_action=RECOVER; \ return agent; \ case state:; \ } while (0); \ #define PULL_FAILURE(error) \ do { \ agent.current_error=error; \ agent.required_action=FAILURE; \ return agent; \ } while (0); \ #define PULL_FINISH(state) } \ agent.current_state=state; \ agent.required_action=APPLY; \ return agent; \ #endif /* AGENTS_COROUTINE_H_ */
2.078125
2
2024-11-18T18:42:19.462401+00:00
2023-08-27T19:14:02
ead80de3a262217355a584a555730bdf7869b1c7
{ "blob_id": "ead80de3a262217355a584a555730bdf7869b1c7", "branch_name": "refs/heads/master", "committer_date": "2023-08-27T19:14:02", "content_id": "10f62f6ec31ab840b3d3a66f0dd6a6fa2eff7755", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4", "extension": "h", "filename": "HttpBootSupport.h", "fork_events_count": 770, "gha_created_at": "2019-09-02T08:22:14", "gha_event_created_at": "2023-09-03T12:41:33", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 205810121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14518, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/NetworkPkg/HttpBootDxe/HttpBootSupport.h", "provenance": "stackv2-0030.json.gz:27633", "repo_name": "CloverHackyColor/CloverBootloader", "revision_date": "2023-08-27T19:14:02", "revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5", "snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee", "src_encoding": "UTF-8", "star_events_count": 4734, "url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/NetworkPkg/HttpBootDxe/HttpBootSupport.h", "visit_date": "2023-08-30T22:14:34.590134" }
stackv2
/** @file Support functions declaration for UEFI HTTP boot driver. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __EFI_HTTP_BOOT_SUPPORT_H__ #define __EFI_HTTP_BOOT_SUPPORT_H__ /** Get the Nic handle using any child handle in the IPv4 stack. @param[in] ControllerHandle Pointer to child handle over IPv4. @return NicHandle The pointer to the Nic handle. @return NULL Can't find the Nic handle. **/ EFI_HANDLE HttpBootGetNicByIp4Children ( IN EFI_HANDLE ControllerHandle ); /** Get the Nic handle using any child handle in the IPv6 stack. @param[in] ControllerHandle Pointer to child handle over IPv6. @return NicHandle The pointer to the Nic handle. @return NULL Can't find the Nic handle. **/ EFI_HANDLE HttpBootGetNicByIp6Children ( IN EFI_HANDLE ControllerHandle ); /** This function is to convert UINTN to ASCII string with the required formatting. @param[in] Number Numeric value to be converted. @param[in] Buffer The pointer to the buffer for ASCII string. @param[in] Length The length of the required format. **/ VOID HttpBootUintnToAscDecWithFormat ( IN UINTN Number, IN UINT8 *Buffer, IN INTN Length ); /** This function is to display the IPv4 address. @param[in] Ip The pointer to the IPv4 address. **/ VOID HttpBootShowIp4Addr ( IN EFI_IPv4_ADDRESS *Ip ); /** This function is to display the IPv6 address. @param[in] Ip The pointer to the IPv6 address. **/ VOID HttpBootShowIp6Addr ( IN EFI_IPv6_ADDRESS *Ip ); /** This function is to display the HTTP error status. @param[in] StatusCode The status code value in HTTP message. **/ VOID HttpBootPrintErrorMessage ( EFI_HTTP_STATUS_CODE StatusCode ); // // A wrapper structure to hold the HTTP headers. // typedef struct { UINTN MaxHeaderCount; UINTN HeaderCount; EFI_HTTP_HEADER *Headers; } HTTP_IO_HEADER; /** Create a HTTP_IO_HEADER to hold the HTTP header items. @param[in] MaxHeaderCount The maximun number of HTTP header in this holder. @return A pointer of the HTTP header holder or NULL if failed. **/ HTTP_IO_HEADER * HttpBootCreateHeader ( IN UINTN MaxHeaderCount ); /** Destroy the HTTP_IO_HEADER and release the resouces. @param[in] HttpIoHeader Point to the HTTP header holder to be destroyed. **/ VOID HttpBootFreeHeader ( IN HTTP_IO_HEADER *HttpIoHeader ); /** Set or update a HTTP header with the field name and corresponding value. @param[in] HttpIoHeader Point to the HTTP header holder. @param[in] FieldName Null terminated string which describes a field name. @param[in] FieldValue Null terminated string which describes the corresponding field value. @retval EFI_SUCCESS The HTTP header has been set or updated. @retval EFI_INVALID_PARAMETER Any input parameter is invalid. @retval EFI_OUT_OF_RESOURCES Insufficient resource to complete the operation. @retval Other Unexpected error happened. **/ EFI_STATUS HttpBootSetHeader ( IN HTTP_IO_HEADER *HttpIoHeader, IN CHAR8 *FieldName, IN CHAR8 *FieldValue ); /// /// HTTP_IO_CALLBACK_EVENT /// typedef enum { HttpIoRequest, HttpIoResponse } HTTP_IO_CALLBACK_EVENT; /** HttpIo Callback function which will be invoked when specified HTTP_IO_CALLBACK_EVENT happened. @param[in] EventType Indicate the Event type that occurs in the current callback. @param[in] Message HTTP message which will be send to, or just received from HTTP server. @param[in] Context The Callback Context pointer. @retval EFI_SUCCESS Tells the HttpIo to continue the HTTP process. @retval Others Tells the HttpIo to abort the current HTTP process. **/ typedef EFI_STATUS (EFIAPI * HTTP_IO_CALLBACK) ( IN HTTP_IO_CALLBACK_EVENT EventType, IN EFI_HTTP_MESSAGE *Message, IN VOID *Context ); // // HTTP_IO configuration data for IPv4 // typedef struct { EFI_HTTP_VERSION HttpVersion; UINT32 RequestTimeOut; // In milliseconds. UINT32 ResponseTimeOut; // In milliseconds. BOOLEAN UseDefaultAddress; EFI_IPv4_ADDRESS LocalIp; EFI_IPv4_ADDRESS SubnetMask; UINT16 LocalPort; } HTTP4_IO_CONFIG_DATA; // // HTTP_IO configuration data for IPv6 // typedef struct { EFI_HTTP_VERSION HttpVersion; UINT32 RequestTimeOut; // In milliseconds. BOOLEAN UseDefaultAddress; EFI_IPv6_ADDRESS LocalIp; UINT16 LocalPort; } HTTP6_IO_CONFIG_DATA; // // HTTP_IO configuration // typedef union { HTTP4_IO_CONFIG_DATA Config4; HTTP6_IO_CONFIG_DATA Config6; } HTTP_IO_CONFIG_DATA; // // HTTP_IO wrapper of the EFI HTTP service. // typedef struct { UINT8 IpVersion; EFI_HANDLE Image; EFI_HANDLE Controller; EFI_HANDLE Handle; EFI_HTTP_PROTOCOL *Http; HTTP_IO_CALLBACK Callback; VOID *Context; EFI_HTTP_TOKEN ReqToken; EFI_HTTP_MESSAGE ReqMessage; EFI_HTTP_TOKEN RspToken; EFI_HTTP_MESSAGE RspMessage; BOOLEAN IsTxDone; BOOLEAN IsRxDone; EFI_EVENT TimeoutEvent; } HTTP_IO; // // A wrapper structure to hold the received HTTP response data. // typedef struct { EFI_HTTP_RESPONSE_DATA Response; UINTN HeaderCount; EFI_HTTP_HEADER *Headers; UINTN BodyLength; CHAR8 *Body; EFI_STATUS Status; } HTTP_IO_RESPONSE_DATA; /** Retrieve the host address using the EFI_DNS6_PROTOCOL. @param[in] Private The pointer to the driver's private data. @param[in] HostName Pointer to buffer containing hostname. @param[out] IpAddress On output, pointer to buffer containing IPv6 address. @retval EFI_SUCCESS Operation succeeded. @retval EFI_DEVICE_ERROR An unexpected network error occurred. @retval Others Other errors as indicated. **/ EFI_STATUS HttpBootDns ( IN HTTP_BOOT_PRIVATE_DATA *Private, IN CHAR16 *HostName, OUT EFI_IPv6_ADDRESS *IpAddress ); /** Notify the callback function when an event is triggered. @param[in] Event The triggered event. @param[in] Context The opaque parameter to the function. **/ VOID EFIAPI HttpBootCommonNotify ( IN EFI_EVENT Event, IN VOID *Context ); /** Create a HTTP_IO to access the HTTP service. It will create and configure a HTTP child handle. @param[in] Image The handle of the driver image. @param[in] Controller The handle of the controller. @param[in] IpVersion IP_VERSION_4 or IP_VERSION_6. @param[in] ConfigData The HTTP_IO configuration data. @param[in] Callback Callback function which will be invoked when specified HTTP_IO_CALLBACK_EVENT happened. @param[in] Context The Context data which will be passed to the Callback function. @param[out] HttpIo The HTTP_IO. @retval EFI_SUCCESS The HTTP_IO is created and configured. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_UNSUPPORTED One or more of the control options are not supported in the implementation. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval Others Failed to create the HTTP_IO or configure it. **/ EFI_STATUS HttpIoCreateIo ( IN EFI_HANDLE Image, IN EFI_HANDLE Controller, IN UINT8 IpVersion, IN HTTP_IO_CONFIG_DATA *ConfigData, IN HTTP_IO_CALLBACK Callback, IN VOID *Context, OUT HTTP_IO *HttpIo ); /** Destroy the HTTP_IO and release the resouces. @param[in] HttpIo The HTTP_IO which wraps the HTTP service to be destroyed. **/ VOID HttpIoDestroyIo ( IN HTTP_IO *HttpIo ); /** Synchronously send a HTTP REQUEST message to the server. @param[in] HttpIo The HttpIo wrapping the HTTP service. @param[in] Request A pointer to storage such data as URL and HTTP method. @param[in] HeaderCount Number of HTTP header structures in Headers list. @param[in] Headers Array containing list of HTTP headers. @param[in] BodyLength Length in bytes of the HTTP body. @param[in] Body Body associated with the HTTP request. @retval EFI_SUCCESS The HTTP request is trasmitted. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_DEVICE_ERROR An unexpected network or system error occurred. @retval Others Other errors as indicated. **/ EFI_STATUS HttpIoSendRequest ( IN HTTP_IO *HttpIo, IN EFI_HTTP_REQUEST_DATA *Request, OPTIONAL IN UINTN HeaderCount, IN EFI_HTTP_HEADER *Headers, OPTIONAL IN UINTN BodyLength, IN VOID *Body OPTIONAL ); /** Synchronously receive a HTTP RESPONSE message from the server. @param[in] HttpIo The HttpIo wrapping the HTTP service. @param[in] RecvMsgHeader TRUE to receive a new HTTP response (from message header). FALSE to continue receive the previous response message. @param[out] ResponseData Point to a wrapper of the received response data. @retval EFI_SUCCESS The HTTP response is received. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_DEVICE_ERROR An unexpected network or system error occurred. @retval Others Other errors as indicated. **/ EFI_STATUS HttpIoRecvResponse ( IN HTTP_IO *HttpIo, IN BOOLEAN RecvMsgHeader, OUT HTTP_IO_RESPONSE_DATA *ResponseData ); /** This function checks the HTTP(S) URI scheme. @param[in] Uri The pointer to the URI string. @retval EFI_SUCCESS The URI scheme is valid. @retval EFI_INVALID_PARAMETER The URI scheme is not HTTP or HTTPS. @retval EFI_ACCESS_DENIED HTTP is disabled and the URI is HTTP. **/ EFI_STATUS HttpBootCheckUriScheme ( IN CHAR8 *Uri ); /** Get the URI address string from the input device path. Caller need to free the buffer in the UriAddress pointer. @param[in] FilePath Pointer to the device path which contains a URI device path node. @param[out] UriAddress The URI address string extract from the device path. @retval EFI_SUCCESS The URI string is returned. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. **/ EFI_STATUS HttpBootParseFilePath ( IN EFI_DEVICE_PATH_PROTOCOL *FilePath, OUT CHAR8 **UriAddress ); /** This function returns the image type according to server replied HTTP message and also the image's URI info. @param[in] Uri The pointer to the image's URI string. @param[in] UriParser URI Parse result returned by NetHttpParseUrl(). @param[in] HeaderCount Number of HTTP header structures in Headers list. @param[in] Headers Array containing list of HTTP headers. @param[out] ImageType The image type of the downloaded file. @retval EFI_SUCCESS The image type is returned in ImageType. @retval EFI_INVALID_PARAMETER ImageType, Uri or UriParser is NULL. @retval EFI_INVALID_PARAMETER HeaderCount is not zero, and Headers is NULL. @retval EFI_NOT_FOUND Failed to identify the image type. @retval Others Unexpect error happened. **/ EFI_STATUS HttpBootCheckImageType ( IN CHAR8 *Uri, IN VOID *UriParser, IN UINTN HeaderCount, IN EFI_HTTP_HEADER *Headers, OUT HTTP_BOOT_IMAGE_TYPE *ImageType ); /** This function register the RAM disk info to the system. @param[in] Private The pointer to the driver's private data. @param[in] BufferSize The size of Buffer in bytes. @param[in] Buffer The base address of the RAM disk. @param[in] ImageType The image type of the file in Buffer. @retval EFI_SUCCESS The RAM disk has been registered. @retval EFI_NOT_FOUND No RAM disk protocol instances were found. @retval EFI_UNSUPPORTED The ImageType is not supported. @retval Others Unexpected error happened. **/ EFI_STATUS HttpBootRegisterRamDisk ( IN HTTP_BOOT_PRIVATE_DATA *Private, IN UINTN BufferSize, IN VOID *Buffer, IN HTTP_BOOT_IMAGE_TYPE ImageType ); /** Indicate if the HTTP status code indicates a redirection. @param[in] StatusCode HTTP status code from server. @return TRUE if it's redirection. **/ BOOLEAN HttpBootIsHttpRedirectStatusCode ( IN EFI_HTTP_STATUS_CODE StatusCode ); #endif
2.265625
2
2024-11-18T18:42:19.710777+00:00
2016-04-13T21:28:35
184ce7c5e1f0af07035b1eadabe0ea13c750349c
{ "blob_id": "184ce7c5e1f0af07035b1eadabe0ea13c750349c", "branch_name": "refs/heads/master", "committer_date": "2016-04-13T21:28:35", "content_id": "9bf4abc7659071101cd42b1bfba9869a40da1b67", "detected_licenses": [ "MIT" ], "directory_id": "2914886ad2b07120587842ca5fd0d1c0acee0192", "extension": "c", "filename": "gui.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13365259, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 23991, "license": "MIT", "license_type": "permissive", "path": "/src/gui.c", "provenance": "stackv2-0030.json.gz:28019", "repo_name": "burnison/clip", "revision_date": "2016-04-13T21:28:35", "revision_id": "eb3ff2a4c7421e9c68f8f0f3a63f03b5f6204cb5", "snapshot_id": "e88f6f365840fe3396da89e6e6901636b51a8c70", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/burnison/clip/eb3ff2a4c7421e9c68f8f0f3a63f03b5f6204cb5/src/gui.c", "visit_date": "2021-01-18T23:26:00.692846" }
stackv2
/* * Copyright (c) 2016 Richard Burnison * * 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 "gui.h" #include "gui_editor.h" #include "gui_search.h" #include "keybinder.h" #include "config.h" #include "clipboard_events.h" #include "utils.h" #include <gtk/gtk.h> #include <math.h> #include <string.h> // Not owned. static Clipboard *clipboard = NULL; // Owned. static GtkWidget *menu = NULL; static GtkWidget *menu_item_search = NULL; static GtkWidget *menu_item_clear = NULL; static GtkWidget *menu_item_history = NULL; static GtkWidget *menu_item_empty = NULL; static GtkWidget *menu_item_trim = NULL; #ifdef DEBUG static GtkWidget *menu_item_exit = NULL; #endif static gboolean marking = FALSE; static gboolean finding = FALSE; static int rows = 0; typedef struct { ClipboardEntry *entry; int row; } Data; static gboolean clip_gui_menu_item_is_selectable(GtkWidget *widget) { GtkWidget *contents = gtk_bin_get_child(GTK_BIN(widget)); return GTK_IS_LABEL(contents) && gtk_widget_is_sensitive(contents) && contents != gtk_bin_get_child(GTK_BIN(menu_item_clear)) && contents != gtk_bin_get_child(GTK_BIN(menu_item_history)) && contents != gtk_bin_get_child(GTK_BIN(menu_item_empty)) && contents != gtk_bin_get_child(GTK_BIN(menu_item_trim)) ; } static GtkWidget* clip_gui_get_selected_item(void) { return gtk_menu_shell_get_selected_item(GTK_MENU_SHELL(menu)); } static Data* clip_gui_get_data(GtkWidget *menu_item) { if(menu_item == NULL || !clip_gui_menu_item_is_selectable(menu_item)){ return NULL; } return g_object_get_data(G_OBJECT(menu_item), "data"); } static GtkWidget* clip_gui_menu_item_find(GCompareFunc compare) { GList *children = gtk_container_get_children(GTK_CONTAINER(menu)); GList *found_child = g_list_find_custom(children, NULL, compare); GtkWidget *found = found_child == NULL ? NULL : found_child->data; g_list_free(children); return found; } static GtkWidget* clip_gui_menu_item_find_for_entry(ClipboardEntry *entry) { gint compare(GtkWidget *widget) { Data *data = clip_gui_get_data(widget); if(data == NULL){ return -1; } return !clip_clipboard_entry_equals(entry, data->entry); } return clip_gui_menu_item_find((GCompareFunc)compare); } static void clip_gui_activate_menu_item(GtkWidget *widget) { if(widget == NULL){ debug("No widget to select.\n"); return; } gtk_menu_shell_select_item(GTK_MENU_SHELL(menu), widget); gtk_menu_item_activate(GTK_MENU_ITEM(widget)); gtk_menu_shell_deactivate(GTK_MENU_SHELL(menu)); } static ClipboardEntry* clip_gui_get_entry(GtkWidget *menu_item) { Data *data = clip_gui_get_data(menu_item); if(data == NULL){ return NULL; } return data->entry; } static ClipboardEntry* clip_gui_get_entry_copy(GtkWidget *menu_item) { ClipboardEntry *entry = clip_gui_get_entry(menu_item); if(entry == NULL){ return NULL; } return clip_clipboard_entry_clone(entry); } static void clip_gui_set_normal_label(GtkBin *item, char *text) { gtk_label_set_label(GTK_LABEL(gtk_bin_get_child(item)), text); } static void clip_gui_set_markedup_label(GtkBin *item, char *format, char *text) { GtkLabel *label = GTK_LABEL(gtk_bin_get_child(item)); char *markedup = g_markup_printf_escaped(format, text); gtk_label_set_markup(label, markedup); g_free(markedup); } static void clip_gui_menu_item_update(GtkWidget *menu_item) { Data *data = clip_gui_get_data(menu_item); if(data == NULL){ warn("Got an update action for a missing entry.\n"); return; } char *text = clip_clipboard_entry_get_text(data->entry); char *shortened = clip_clipboard_entry_is_masked(data->entry) ? g_strnfill(MIN(GUI_DISPLAY_CHARACTERS, strlen(text)), GUI_MASK_CHAR) : g_strndup(text, GUI_DISPLAY_CHARACTERS); GString *mask = g_string_new("%s"); if(clip_clipboard_entry_get_locked(data->entry)){ g_string_prepend(mask, "<b>"); g_string_append(mask, "</b>"); } if(clip_clipboard_is_head(clipboard, data->entry)){ g_string_prepend(mask, "<i>"); g_string_append(mask, "</i>"); } char tag = clip_clipboard_entry_get_tag(data->entry); if(tag != 0){ GString *tagged = g_string_new(""); g_string_printf(tagged, "<span foreground='gray'>%c</span> %s", tag, mask->str); g_string_free(mask, TRUE); mask = tagged; } if(data->row < 10){ GString *numbered = g_string_new(""); g_string_printf(numbered, "<span foreground='gray'>%d</span> %s", data->row, mask->str); g_string_free(mask, TRUE); mask = numbered; } clip_gui_set_markedup_label(GTK_BIN(menu_item), mask->str, shortened); g_string_free(mask, TRUE); g_free(shortened); } static void clip_gui_menu_item_change_entry(GtkWidget *menu_item, ClipboardEntry *entry) { Data *data = clip_gui_get_data(menu_item); if(data == NULL){ warn("Got an update action for a missing entry.\n"); } ClipboardEntry *old_entry = data->entry; data->entry = clip_clipboard_entry_clone(entry); clip_clipboard_entry_free(old_entry); clip_gui_menu_item_update(menu_item); } static void clip_gui_menu_update(void) { char *search_text = clip_gui_search_in_progress() ? clip_gui_search_get_term() : GUI_SEARCH_MESSAGE; clip_gui_set_markedup_label(GTK_BIN(menu_item_search), "<i><b>%s</b></i>", search_text); char *history_text = clip_clipboard_is_enabled(clipboard) ? GUI_HISTORY_DISABLE_MESSAGE : GUI_HISTORY_ENABLE_MESSAGE; clip_gui_set_normal_label(GTK_BIN(menu_item_history), history_text); char *mode_name = GUI_AUTO_TRIM_MESSAGE; switch(clip_clipboard_get_trim_mode(clipboard)){ case TRIM_OFF: case TRIM_STOP: mode_name = GUI_AUTO_TRIM_MESSAGE " (Off)"; break; case TRIM_CHOMP: mode_name = GUI_AUTO_TRIM_MESSAGE " (Trim Right)"; break; case TRIM_CHUG: mode_name = GUI_AUTO_TRIM_MESSAGE " (Trim Left)"; break; case TRIM_STRIP: mode_name = GUI_AUTO_TRIM_MESSAGE " (Trim Both)"; break; } clip_gui_set_normal_label(GTK_BIN(menu_item_trim), mode_name); } /** * Remove the specified menu item. */ static void clip_gui_menu_item_remove(GtkWidget *menu_item) { Data *data = clip_gui_get_data(menu_item); if(data != NULL){ g_object_set_data(G_OBJECT(menu_item),"data", NULL); clip_clipboard_entry_free(data->entry); data->entry = NULL; data->row = 0; g_free(data); } gtk_container_remove(GTK_CONTAINER(menu), menu_item); } static void clip_gui_do_delete(GtkWidget *menu_item) { GtkWidget *selected_item = clip_gui_get_selected_item(); if(selected_item == NULL){ warn("Trying to remove a selected item, but no item is selected.\n"); return; } //FIXME: I don't belong here. ClipboardEntry *entry = clip_gui_get_entry_copy(selected_item); if(!clip_clipboard_entry_get_locked(entry)){ clip_clipboard_remove(clipboard, entry); } else { debug("Refusing to delete locked item.\n"); } clip_clipboard_entry_free(entry); } static void clip_gui_do_lock(GtkWidget *selected_menu_item) { if(selected_menu_item == NULL){ trace("Tried to lock with no item selected.\n"); return; } ClipboardEntry *entry = clip_gui_get_entry_copy(selected_menu_item); clip_clipboard_toggle_lock(clipboard, entry); clip_clipboard_entry_free(entry); } static void clip_gui_do_edit(GtkWidget *selected_menu_item, gboolean promote) { if(!clip_clipboard_is_enabled(clipboard) || selected_menu_item == NULL){ trace("Clipboard is disabled or no item is selected.\n"); return; } trace("Editing current value.\n"); gtk_menu_shell_deactivate(GTK_MENU_SHELL(menu)); ClipboardEntry *selected_entry = clip_gui_get_entry_copy(selected_menu_item); clip_clipboard_disable_history(clipboard); char *current = clip_clipboard_entry_get_text(selected_entry); char *edited = clip_gui_editor_edit_text(current); clip_clipboard_enable_history(clipboard); if(edited != NULL){ clip_clipboard_entry_set_text(selected_entry, edited); if(promote){ clip_clipboard_set(clipboard, selected_entry, TRUE); } else { clip_clipboard_replace(clipboard, selected_entry); } clip_gui_menu_update(); } else { debug("Edited text is unchanged. Ignoring edit request.\n"); } clip_gui_editor_free_text(edited); clip_clipboard_entry_free(selected_entry); } static void clip_gui_do_mask(GtkWidget *selected_menu_item) { if(selected_menu_item == NULL){ trace("Tried to join with no item selected.\n"); return; } ClipboardEntry *entry = clip_gui_get_entry_copy(selected_menu_item); clip_clipboard_toggle_mask(clipboard, entry); clip_clipboard_entry_free(entry); } static void clip_gui_do_join(GtkWidget *selected_menu_item) { if(selected_menu_item == NULL){ trace("Tried to join with no item selected.\n"); return; } ClipboardEntry *entry = clip_gui_get_entry_copy(selected_menu_item); clip_clipboard_join(clipboard, entry); clip_clipboard_entry_free(entry); } static void clip_gui_do_change_case(GtkWidget *selected_menu_item, gboolean to_upper) { if(selected_menu_item == NULL){ trace("Tried to change case with no item selected.\n"); return; } gboolean (*func)() = to_upper ? clip_clipboard_to_upper : clip_clipboard_to_lower; ClipboardEntry *entry = clip_gui_get_entry_copy(selected_menu_item); func(clipboard, entry); clip_clipboard_entry_free(entry); } static void clip_gui_trim(GtkWidget *selected_menu_item) { if(selected_menu_item == NULL){ trace("Tried to trim with no item selected."); return; } ClipboardEntry *entry = clip_gui_get_entry_copy(selected_menu_item); clip_clipboard_trim(clipboard, entry); clip_clipboard_entry_free(entry); } static gboolean clip_gui_do_mark(GtkWidget *selected_menu_item, guint keyval) { if(selected_menu_item == NULL) { return FALSE; } if(keyval == GDK_KEY_space || g_unichar_iscntrl(gdk_keyval_to_unicode(keyval))) { return TRUE; } debug("Entering mark mode. Next letter marks.\n"); ClipboardEntry *selected_entry = clip_gui_get_entry_copy(selected_menu_item); clip_clipboard_tag(clipboard, selected_entry, keyval); clip_clipboard_entry_free(selected_entry); return FALSE; } static gboolean clip_gui_activate_mark(guint keyval) { // Control character may modify the next val. Let it pass through. if(keyval == GDK_KEY_space || g_unichar_iscntrl(gdk_keyval_to_unicode(keyval))) { return TRUE; } gint compare(GtkWidget *widget) { Data *data = clip_gui_get_data(widget); if(data == NULL) { return -1; } return !clip_clipboard_entry_has_tag(data->entry, keyval); } debug("Looking for mark, %c.\n", keyval); GtkWidget *marked = clip_gui_menu_item_find((GCompareFunc)compare); clip_gui_activate_menu_item(marked); return FALSE; } static void clip_gui_activate_index(unsigned int index) { gint compare(GtkWidget *widget) { Data *data = clip_gui_get_data(widget); if(data == NULL) { return -1; } return data->row != index; } debug("Looking for index, %d.\n", index); GtkWidget *nth = clip_gui_menu_item_find((GCompareFunc)compare); clip_gui_activate_menu_item(nth); } static void clip_gui_select_search_match(gboolean reset_on_end) { if(!clip_gui_search_in_progress() || clip_gui_search_get_length() < 1){ return; } gint compare(GtkWidget *widget) { Data *data = clip_gui_get_data(widget); if(data == NULL || data->row < clip_gui_search_get_position()) { return -1; } const char *text = clip_clipboard_entry_get_text(data->entry); return !g_regex_match_simple(clip_gui_search_get_term(), text, G_REGEX_CASELESS, FALSE); } GtkWidget *matching = clip_gui_menu_item_find((GCompareFunc)compare); if(matching != NULL) { Data *data = clip_gui_get_data(matching); gtk_menu_shell_select_item(GTK_MENU_SHELL(menu), matching); clip_gui_search_set_position(data->row); } else { gtk_menu_shell_deselect(GTK_MENU_SHELL(menu)); clip_gui_search_set_position(0); if(reset_on_end) { clip_gui_select_search_match(FALSE); } } } static gboolean clip_gui_cb_keypress(GtkWidget *widget, GdkEvent *event, gpointer data) { guint keyval = ((GdkEventKey*)event)->keyval; gboolean update_required = TRUE; gboolean handled = TRUE; GtkWidget *selected_menu_item = clip_gui_get_selected_item(); if (marking) { marking = clip_gui_do_mark(selected_menu_item, keyval); } else if (finding) { finding = clip_gui_activate_mark(keyval); update_required = FALSE; } else if (clip_gui_search_in_progress()){ switch(keyval){ case GDK_KEY_Escape: case GDK_KEY_Down: case GDK_KEY_Up: case GDK_KEY_Page_Up: case GDK_KEY_Page_Down: case GDK_KEY_Home: case GDK_KEY_End: case GDK_KEY_Return: clip_gui_search_end(); update_required = FALSE; handled = FALSE; break; case GDK_KEY_BackSpace: clip_gui_search_remove_char(); break; case GDK_KEY_Tab: clip_gui_search_increment_position(); break; default: clip_gui_search_append(keyval); break; } clip_gui_select_search_match(TRUE); } else { switch(keyval){ case GUI_SEARCH_LEADER: clip_gui_search_start(); break; case GDK_KEY_a: clip_clipboard_next_trim_mode(clipboard); break; case GDK_KEY_c: clip_clipboard_clear(clipboard); update_required = FALSE; break; case GDK_KEY_d: case GDK_KEY_Delete: clip_gui_do_delete(selected_menu_item); break; case GDK_KEY_0: case GDK_KEY_1: case GDK_KEY_2: case GDK_KEY_3: case GDK_KEY_4: case GDK_KEY_5: case GDK_KEY_6: case GDK_KEY_7: case GDK_KEY_8: case GDK_KEY_9: clip_gui_activate_index(keyval - GDK_KEY_0); update_required = FALSE; break; case GDK_KEY_e: case GDK_KEY_E: clip_gui_do_edit(selected_menu_item, keyval == GDK_KEY_E); update_required = FALSE; break; case GDK_KEY_h: clip_clipboard_toggle_history(clipboard); break; case GDK_KEY_J: clip_gui_do_join(selected_menu_item); update_required = FALSE; break; case GDK_KEY_L: clip_gui_do_lock(selected_menu_item); break; case GDK_KEY_u: case GDK_KEY_U: clip_gui_do_change_case(selected_menu_item, keyval == GDK_KEY_U); break; case GDK_KEY_t: clip_gui_trim(selected_menu_item); break; case GDK_KEY_m: marking = TRUE; break; case GDK_KEY_grave: finding = TRUE; update_required = FALSE; break; case GDK_KEY_asterisk: clip_gui_do_mask(selected_menu_item); break; default: handled = FALSE; break; } } if(update_required) { clip_gui_menu_update(); } // If search mode is turned on, drop all subsequent callbacks (like mnemonics). return handled || clip_gui_search_in_progress(); } static gboolean clip_gui_cb_toggle_lock(GtkWidget *widget, GdkEvent *event, Data *data) { // Only handle right button press. if(((GdkEventButton*)event)->button == 3) { clip_gui_do_lock(widget); return TRUE; } return FALSE; } /** * Invoked when a historical menu item has been selected. */ static gboolean clip_gui_cb_history_activated(GtkMenuItem *widget, Data *data) { trace("History item activated.\n"); clip_clipboard_set(clipboard, data->entry, TRUE); return FALSE; } static gboolean clip_gui_cb_clear_clipboard(GtkMenuItem *item, Data *data) { trace("Clearing clipboard history.\n"); clip_clipboard_clear(clipboard); return FALSE; } static gboolean clip_gui_cb_toggle_clipboard(GtkMenuItem *item, Data *data) { trace("Toggle clipboard history.\n"); clip_clipboard_toggle_history(clipboard); return FALSE; } /** * Triggered by keybinder library. */ static void clip_gui_cb_hotkey_handler(const char *keystring, gpointer user_data) { trace("Global hotkey pressed. Showing dialog.\n"); clip_gui_show(); } /** * Removes a menu item from the menu. */ static void clip_gui_cb_remove_menu_item(GtkWidget *item, gpointer user_data) { clip_gui_menu_item_remove(item); } static void clip_gui_cb_trim(GtkWidget *item, gpointer user_data) { clip_clipboard_next_trim_mode(clipboard); clip_gui_menu_update(); } static void clip_gui_do_add_entry(ClipboardEntry *entry, int *row) { Data *data = g_malloc(sizeof(Data)); data->entry = clip_clipboard_entry_clone(entry); data->row = (*row)++; GtkWidget *item = gtk_menu_item_new_with_label(NULL); g_object_set_data(G_OBJECT(item),"data", data); clip_gui_menu_item_update(item); g_signal_connect(G_OBJECT(item), "button-release-event", G_CALLBACK(clip_gui_cb_toggle_lock), data); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(clip_gui_cb_history_activated), data); GtkLabel *label = GTK_LABEL(gtk_bin_get_child(GTK_BIN(item))); gtk_label_set_single_line_mode(label, TRUE); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); } /** * Updates the menu to contain up-to-date history entries. */ static void clip_gui_prepare_menu(void) { trace("Preparing menu.\n"); clip_gui_search_end(); gtk_container_foreach(GTK_CONTAINER(menu), (GtkCallback)clip_gui_cb_remove_menu_item, NULL); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item_search); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); GList* history = clip_clipboard_get_history(clipboard); rows = 0; if(history == NULL){ gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item_empty); } else { g_list_foreach(history, (GFunc)clip_gui_do_add_entry, &rows); } clip_clipboard_free_history(history); debug("Showing %d entries.\n", rows); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item_trim); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item_history); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item_clear); #ifdef DEBUG gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item_exit); #endif clip_gui_menu_update(); gtk_widget_show_all(menu); } void clip_gui_show(void) { trace("Showing history menu.\n"); if(menu == NULL){ warn("GUI has not yet been initialized!\n"); return; } clip_gui_prepare_menu(); gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time()); } static void clip_gui_on_event(ClipboardEvent event, ClipboardEntry* entry) { switch(event){ case CLIPBOARD_REMOVE_EVENT: debug("Entry removed.\n"); clip_gui_menu_item_remove(clip_gui_menu_item_find_for_entry(entry)); break; case CLIPBOARD_UPDATE_EVENT: debug("Entry updated.\n"); clip_gui_menu_item_change_entry(clip_gui_menu_item_find_for_entry(entry), entry); break; case CLIPBOARD_ADD_EVENT: case CLIPBOARD_CLEAR_EVENT: debug("Clipboard cleared.\n"); clip_gui_prepare_menu(); break; } } void clip_gui_init(Clipboard *_clipboard) { trace("Creating new GUI menu.\n"); clip_events_add_observer(clip_gui_on_event); clipboard = _clipboard; menu = gtk_menu_new(); g_signal_connect(G_OBJECT(menu), "key-press-event", G_CALLBACK(clip_gui_cb_keypress), NULL); menu_item_search = g_object_ref(gtk_menu_item_new_with_label(GUI_SEARCH_MESSAGE)); gtk_widget_set_sensitive(menu_item_search, FALSE); menu_item_clear = g_object_ref(gtk_menu_item_new_with_mnemonic(GUI_CLEAR_MESSAGE)); g_signal_connect(G_OBJECT(menu_item_clear), "activate", G_CALLBACK(clip_gui_cb_clear_clipboard), NULL); menu_item_history = g_object_ref(gtk_menu_item_new_with_mnemonic(GUI_HISTORY_DISABLE_MESSAGE)); g_signal_connect(G_OBJECT(menu_item_history), "activate", G_CALLBACK(clip_gui_cb_toggle_clipboard), NULL); menu_item_empty = g_object_ref(gtk_menu_item_new_with_label(GUI_EMPTY_MESSAGE)); clip_gui_set_markedup_label(GTK_BIN(menu_item_empty), "<i>%s</i>", GUI_EMPTY_MESSAGE); gtk_widget_set_sensitive(menu_item_empty, FALSE); menu_item_trim = g_object_ref(gtk_menu_item_new_with_mnemonic(GUI_AUTO_TRIM_MESSAGE)); g_signal_connect(G_OBJECT(menu_item_trim), "activate", G_CALLBACK(clip_gui_cb_trim), NULL); #ifdef DEBUG menu_item_exit = g_object_ref(gtk_menu_item_new_with_mnemonic(GUI_DEBUG_EXIT_MESSAGE)); g_signal_connect(G_OBJECT(menu_item_exit), "activate", G_CALLBACK(gtk_main_quit), NULL); #endif keybinder_init(); keybinder_bind(GUI_GLOBAL_KEY, clip_gui_cb_hotkey_handler, NULL); clip_gui_menu_update(); } void clip_gui_destroy(void) { keybinder_unbind(GUI_GLOBAL_KEY, clip_gui_cb_hotkey_handler); clip_gui_search_end(); clipboard = NULL; g_object_unref(menu_item_search); gtk_widget_destroy(menu_item_search); menu_item_search = NULL; g_object_unref(menu_item_history); gtk_widget_destroy(menu_item_history); menu_item_history = NULL; g_object_unref(menu_item_empty); gtk_widget_destroy(menu_item_empty); menu_item_empty = NULL; g_object_unref(menu_item_clear); gtk_widget_destroy(menu_item_clear); menu_item_clear = NULL; g_object_unref(menu_item_trim); gtk_widget_destroy(menu_item_trim); menu_item_trim = NULL; #ifdef DEBUG g_object_unref(menu_item_exit); gtk_widget_destroy(menu_item_exit); menu_item_exit = NULL; #endif gtk_widget_destroy(menu); menu = NULL; }
2.125
2
2024-11-18T18:42:19.862897+00:00
2021-01-14T12:19:25
a9e7c8c06f664ed4b7f9cf959029b16c233bcd57
{ "blob_id": "a9e7c8c06f664ed4b7f9cf959029b16c233bcd57", "branch_name": "refs/heads/master", "committer_date": "2021-01-14T12:19:25", "content_id": "5c68a92a505109c456e1ab592ddbb74a103c5527", "detected_licenses": [ "MIT" ], "directory_id": "f631ee899d2f1ec6efceee62bd4218807ab6da16", "extension": "c", "filename": "data.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 323398747, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1127, "license": "MIT", "license_type": "permissive", "path": "/libs/util/data.c", "provenance": "stackv2-0030.json.gz:28148", "repo_name": "m3sserschmitt/shell", "revision_date": "2021-01-14T12:19:25", "revision_id": "836cdfe3db0733130a8152ca45cf4343a4a46470", "snapshot_id": "2124ba0965d21887b4e04d8d86ef83446a094cd5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/m3sserschmitt/shell/836cdfe3db0733130a8152ca45cf4343a4a46470/libs/util/data.c", "visit_date": "2023-02-20T23:18:47.959618" }
stackv2
#include <unistd.h> #include <stdlib.h> #include <string.h> ssize_t read_data(int fd, char **recv_data, int stdoutw) { const size_t block_size = 1024; size_t current_size = block_size; *recv_data = (char *)malloc((current_size + 1) * sizeof(char)); memset(*recv_data, 0, current_size + 1); char *recv_buffer = (char *)malloc(block_size * sizeof(char)); memset(recv_buffer, 0, block_size); ssize_t total_received = 0; size_t received = 0; while ((received = read(fd, recv_buffer, block_size)) > 0) { if (stdoutw) { write(1, recv_buffer, strlen(recv_buffer)); } if (total_received + received > current_size) { current_size += block_size; *recv_data = realloc(*recv_data, (current_size + 1) * sizeof(char)); memset(*recv_data + total_received, 0, current_size - total_received + 1); } total_received += received; strcat(*recv_data, recv_buffer); memset(recv_buffer, 0, block_size); } free(recv_buffer); return received < 0 ? -1 : total_received; }
2.609375
3
2024-11-18T18:42:19.972387+00:00
2017-01-01T22:39:28
bea1d9958092b1d7846661d608d6f961d605177a
{ "blob_id": "bea1d9958092b1d7846661d608d6f961d605177a", "branch_name": "refs/heads/master", "committer_date": "2017-01-01T22:39:28", "content_id": "75a297a63c6aaa887049e3975d649ba3c3ed235c", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "1b2e24713b63620709e5a181eb93edeed526291e", "extension": "c", "filename": "t_lrint.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 146086916, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3527, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/math/t_lrint.c", "provenance": "stackv2-0030.json.gz:28276", "repo_name": "ekamperi/mathlib", "revision_date": "2017-01-01T22:39:28", "revision_id": "fff08a6944170fd8e4c396e24b73e511ad06236b", "snapshot_id": "aed0473d65f8f6653d1dbe0b93feeeb5e953d5b2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ekamperi/mathlib/fff08a6944170fd8e4c396e24b73e511ad06236b/math/t_lrint.c", "visit_date": "2020-03-27T06:11:41.140829" }
stackv2
#define _XOPEN_SOURCE 600 #include <atf-c.h> #include <errno.h> #include <limits.h> #include <math.h> #include <stdlib.h> #include <time.h> #include "config.h" #include "subr_atf.h" #include "subr_errhandling.h" #include "subr_fpcmp.h" #include "subr_random.h" static const struct tentry { double x; /* Input */ double y; /* lrint output */ } ttable[] = { }; /* * Test case 1 -- Basic functionality */ ATF_TC(test_lrint1); ATF_TC_HEAD(test_lrint1, tc) { atf_tc_set_md_var(tc, "descr", "Basic functionality based on a set of good (x, lrint(x)) pairs"); } ATF_TC_BODY(test_lrint1, tc) { } /* * Test case 2 -- Domain error */ const long double t2table[] = { /* NAN */ #ifdef NAN NAN, #endif /* x is +-Inf */ #ifdef INFINITY INFINITY, -INFINITY, #endif #ifdef HUGE_VAL HUGE_VAL, -HUGE_VAL, #endif #ifdef HUGE_VALF HUGE_VALF, -HUGE_VALF, #endif #ifdef HUGE_VALL HUGE_VALL, -HUGE_VALL #endif }; ATF_TC(test_lrint2); ATF_TC_HEAD(test_lrint2, tc) { atf_tc_set_md_var(tc, "descr", "Check that domain errors are properly generated"); } ATF_TC_BODY(test_lrint2, tc) { size_t i, N; N = sizeof(t2table) / sizeof(t2table[0]); ATF_REQUIRE(N > 0); for (i = 0; i < N; i++) { /* float */ errno = 0; clear_exceptions(); (void)lrintf((float)t2table[i]); ATF_CHECK(errno_equalto(ERANGE)); ATF_CHECK(raised_exceptions(MY_FE_INVALID)); /* double */ errno = 0; clear_exceptions(); lrint((double)t2table[i]); ATF_CHECK(errno_equalto(ERANGE)); ATF_CHECK(raised_exceptions(MY_FE_INVALID)); /* long double */ #ifdef HAVE_LRINTL errno = 0; clear_exceptions(); lrintl(t2table[i]); ATF_CHECK(errno_equalto(ERANGE)); ATF_CHECK(raised_exceptions(MY_FE_INVALID)); #endif } } /* * Test case 3 * * If the correct value is positive and too large to represent as a long, * a domain error shall occur and an unspecified value is returned. * * If the correct value is negative and too large to represent as a long, * a domain error shall occur and an unspecified value is returned. */ ATF_TC(test_lrint3); ATF_TC_HEAD(test_lrint3, tc) { atf_tc_set_md_var(tc, "descr", "Check that domain errors are properly generated"); } ATF_TC_BODY(test_lrint3, tc) { double dx; long double ldx; long i, N; N = atf_tc_get_config_var_as_long(tc, "iterations"); ATF_REQUIRE(N > 0); /* Initialize random number generator */ init_randgen(); ATF_FOR_LOOP(i, N, i++) { /* double */ do { dx = random_double(FP_NORMAL); } while (dx <= LONG_MAX); /* positive */ errno = 0; clear_exceptions(); (void)rint(dx); ATF_PASS_OR_BREAK(errno_equalto(ERANGE)); ATF_PASS_OR_BREAK(raised_exceptions(MY_FE_INVALID)); /* negative */ errno = 0; clear_exceptions(); (void)rint(-dx); ATF_PASS_OR_BREAK(errno_equalto(ERANGE)); ATF_PASS_OR_BREAK(raised_exceptions(MY_FE_INVALID)); /* long double */ #ifdef HAVE_LRINTL do { ldx = random_long_double(FP_NORMAL); } while (ldx <= LONG_MAX); /* positive */ errno = 0; clear_exceptions(); (void)lrintl(ldx); ATF_PASS_OR_BREAK(errno_equalto(ERANGE)); ATF_PASS_OR_BREAK(raised_exceptions(MY_FE_INVALID)); /* negative */ errno = 0; clear_exceptions(); (void)lrintl(-ldx); ATF_PASS_OR_BREAK(errno_equalto(ERANGE)); ATF_PASS_OR_BREAK(raised_exceptions(MY_FE_INVALID)); #endif } } /* Add test cases to test program */ ATF_TP_ADD_TCS(tp) { ATF_TP_ADD_TC(tp, test_lrint1); ATF_TP_ADD_TC(tp, test_lrint2); ATF_TP_ADD_TC(tp, test_lrint3); return atf_no_error(); }
2.4375
2
2024-11-18T18:42:20.136978+00:00
2021-04-30T17:16:50
ead282686b14849584f1b5aa5a63074dff3a44d1
{ "blob_id": "ead282686b14849584f1b5aa5a63074dff3a44d1", "branch_name": "refs/heads/master", "committer_date": "2021-04-30T17:16:50", "content_id": "e2989a20a0a6afc422ce8678c3c67dff63196381", "detected_licenses": [ "MIT" ], "directory_id": "2a22ac1d2354e9e33020470c21d82b9f0705cdf9", "extension": "c", "filename": "example2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 578, "license": "MIT", "license_type": "permissive", "path": "/sem09-x86-asm-nostdlib/example2.c", "provenance": "stackv2-0030.json.gz:28533", "repo_name": "RickMortey/caos", "revision_date": "2021-04-30T17:16:50", "revision_id": "616fe20bfc101f5653c6ef162c988503b1842a75", "snapshot_id": "0687c027a03f1163111814546a7201e00a4b2a54", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RickMortey/caos/616fe20bfc101f5653c6ef162c988503b1842a75/sem09-x86-asm-nostdlib/example2.c", "visit_date": "2023-04-12T00:59:30.656865" }
stackv2
// %%cpp example2.c // %run gcc -m64 -masm=intel -nostdlib -O3 example2.c -o example2.exe // %run strace ./example2.exe ; echo "Exited with code=$?" int my_exit(int code); __asm__(R"( my_exit: mov rax, 231 /* номер системного вызова exit_group */ syscall /* не нужно возвращаться из функции, на этом программа завершится */ )"); // Именно с этой функции всегда начинается выполнение программы void _start() { my_exit(0); }
2.03125
2
2024-11-18T18:42:20.195765+00:00
2023-05-31T23:22:47
cbb8f39a37c09070f17dac61d389e71d2de2f920
{ "blob_id": "cbb8f39a37c09070f17dac61d389e71d2de2f920", "branch_name": "refs/heads/main", "committer_date": "2023-05-31T23:22:47", "content_id": "3dd2d2b61279b7bc6b62d26db3e1fd99adb3eb6c", "detected_licenses": [ "MIT" ], "directory_id": "4a727ce379e9d21826895699d09164cdac4836d5", "extension": "c", "filename": "fork_tests.c", "fork_events_count": 95, "gha_created_at": "2018-11-09T22:21:21", "gha_event_created_at": "2022-11-26T19:09:25", "gha_language": "C", "gha_license_id": "MIT", "github_id": 156924419, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9371, "license": "MIT", "license_type": "permissive", "path": "/homeworks/15_advancedmem/fork_tests.c", "provenance": "stackv2-0030.json.gz:28661", "repo_name": "RHIT-CSSE/csse332", "revision_date": "2023-05-31T23:22:47", "revision_id": "7b9e292381062d25934c18210e6bbe7241392cdc", "snapshot_id": "83e58d6c377e67d4cfcc37e2f20f18991c5063bf", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/RHIT-CSSE/csse332/7b9e292381062d25934c18210e6bbe7241392cdc/homeworks/15_advancedmem/fork_tests.c", "visit_date": "2023-06-08T11:16:43.095931" }
stackv2
#include <stdio.h> #include "CuTest.h" #include "forking_forth.h" #include "forth/forth_embed.h" void test0_oneforth(CuTest *tc) { initialize_forths(); int pid = create_forth(".\" hello\" "); struct run_output result = run_forth_until_event(pid); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertStrEquals(tc, "hello", result.output); } void test1_twoforths(CuTest *tc) { initialize_forths(); // this forth is being set to use binary numbers int pid = create_forth(" 2 BASE ! 1 1 + . "); // this (different forth) is using decimal numbers int pid2 = create_forth("1 1 + . "); struct run_output result = run_forth_until_event(pid); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertStrEquals(tc, "10 ", result.output); result = run_forth_until_event(pid2); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertStrEquals(tc, "2 ", result.output); } void test2_yields(CuTest *tc) { initialize_forths(); int pid = create_forth("2 1 . YIELD ."); int pid2 = create_forth("4 3 . YIELD ."); struct run_output result = run_forth_until_event(pid); CuAssertIntEquals(tc, FCONTINUE_YIELD, result.result_code); CuAssertStrEquals(tc, "1 ", result.output); result = run_forth_until_event(pid2); CuAssertIntEquals(tc, FCONTINUE_YIELD, result.result_code); CuAssertStrEquals(tc, "3 ", result.output); result = run_forth_until_event(pid); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertStrEquals(tc, "2 ", result.output); result = run_forth_until_event(pid2); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertStrEquals(tc, "4 ", result.output); } void test3_page_count(CuTest *tc) { initialize_forths(); CuAssertIntEquals(tc, 0, get_used_pages_count()); int pid = create_forth("3 4 +"); // the part after the yield is forth's equiavlent of malloc(5000) int pid2 = create_forth("5 6 + YIELD 5000 ALLOT 4999 + @"); struct run_output result = run_forth_until_event(pid); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); result = run_forth_until_event(pid2); CuAssertIntEquals(tc, FCONTINUE_YIELD, result.result_code); // each forth uses 2 pages of heap, 1 stack, and 1 return stack CuAssertIntEquals(tc, 8, get_used_pages_count()); // after the yield in pid2 we allocate 5000 bytes on the heap // which should force us to use another page of heap result = run_forth_until_event(pid2); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertIntEquals(tc, 9, get_used_pages_count()); } // this test is designed to pass whether or not fork actually pushes a // parent/child return value onto the forth stacks. But of course // without that value to differentiate, the parent and the children // must act identically void test4_identical_fork(CuTest *tc) { initialize_forths(); int parent_id = create_forth("20 20 FORK DROP . "); struct run_output result = run_forth_until_event(parent_id); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); CuAssertTrue(tc, result.forked_child_id != -1); result = run_forth_until_event(result.forked_child_id); CuAssertStrEquals(tc, "20 ", result.output); result = run_forth_until_event(parent_id); CuAssertStrEquals(tc, "20 ", result.output); } void test5_fork_return(CuTest *tc) { initialize_forths(); int parent_id = create_forth(": TESTFUNC 20 20 FORK " " IF .\" parent\"" " ELSE .\" child\" THEN ; " " TESTFUNC "); struct run_output result = run_forth_until_event(parent_id); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); CuAssertTrue(tc, result.forked_child_id != -1); result = run_forth_until_event(result.forked_child_id); CuAssertStrEquals(tc, "child", result.output); result = run_forth_until_event(parent_id); CuAssertStrEquals(tc, "parent", result.output); } // a double fork should produce 4 processes as usual void test6_double_fork(CuTest *tc) { initialize_forths(); int parent = create_forth("20 20 FORK FORK . . "); struct run_output result = run_forth_until_event(parent); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int child = result.forked_child_id; CuAssertTrue(tc, child != -1); result = run_forth_until_event(parent); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int child2 = result.forked_child_id; CuAssertTrue(tc, child2 != -1); result = run_forth_until_event(child); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int grandchild = result.forked_child_id; CuAssertTrue(tc, grandchild != -1); result = run_forth_until_event(parent); CuAssertStrEquals(tc, "1 1 ", result.output); result = run_forth_until_event(grandchild); CuAssertStrEquals(tc, "0 0 ", result.output); result = run_forth_until_event(child); CuAssertStrEquals(tc, "1 0 ", result.output); result = run_forth_until_event(child2); CuAssertStrEquals(tc, "0 1 ", result.output); } void test7_copy_on_write(CuTest *tc) { initialize_forths(); int parent_id = create_forth(" 10 FORK + . YIELD VARIABLE VAR"); struct run_output result = run_forth_until_event(parent_id); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int child_id = result.forked_child_id; CuAssertTrue(tc, child_id != -1); // we've forked, and we've edited the stack of both pages so we // should see 5 pages (4 for parent, 1 for stack copy) CuAssertIntEquals(tc, 5, get_used_pages_count()); // we get an additional page when we run the child and the child // edits the return stack result = run_forth_until_event(child_id); CuAssertStrEquals(tc, "10 ", result.output); CuAssertIntEquals(tc, 6, get_used_pages_count()); // we finally get a 3rd additional page when "VARIABLE VAR" // allocates some heap result = run_forth_until_event(child_id); CuAssertIntEquals(tc, FCONTINUE_INPUT_DONE, result.result_code); CuAssertIntEquals(tc, 7, get_used_pages_count()); } void test8_copy_on_write_parent_edit(CuTest *tc) { initialize_forths(); int parent_id = create_forth(" 10 FORK + . "); struct run_output result = run_forth_until_event(parent_id); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int child_id = result.forked_child_id; CuAssertTrue(tc, child_id != -1); // we've forked, and we've edited the stack of both pages so we // should see 5 pages CuAssertIntEquals(tc, 5, get_used_pages_count()); // running the parent should cause return stack to be copied too result = run_forth_until_event(parent_id); CuAssertStrEquals(tc, "11 ", result.output); CuAssertIntEquals(tc, 6, get_used_pages_count()); } void test9_double_fork_copy_on_write(CuTest *tc) { initialize_forths(); int parent = create_forth("20 20 FORK FORK . . YIELD VARIABLE VAR"); struct run_output result = run_forth_until_event(parent); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int child = result.forked_child_id; CuAssertTrue(tc, child != -1); result = run_forth_until_event(parent); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int child2 = result.forked_child_id; CuAssertTrue(tc, child2 != -1); result = run_forth_until_event(child); CuAssertIntEquals(tc, FCONTINUE_FORK, result.result_code); int grandchild = result.forked_child_id; CuAssertTrue(tc, grandchild != -1); result = run_forth_until_event(parent); CuAssertStrEquals(tc, "1 1 ", result.output); result = run_forth_until_event(grandchild); CuAssertStrEquals(tc, "0 0 ", result.output); result = run_forth_until_event(child); CuAssertStrEquals(tc, "1 0 ", result.output); result = run_forth_until_event(child2); CuAssertStrEquals(tc, "0 1 ", result.output); // at this point we should have copied the stack and return stack // 3 times CuAssertIntEquals(tc, 10, get_used_pages_count()); // now run the parent which edits the shared heap page run_forth_until_event(parent); CuAssertIntEquals(tc, 11, get_used_pages_count()); } int main(int argc, char *argv[]) { CuString *output = CuStringNew(); CuSuite* suite = CuSuiteNew(); // these are all the tests but you'll probably want to comment // them out and add them back one step at a time SUITE_ADD_TEST(suite, test0_oneforth); // SUITE_ADD_TEST(suite, test1_twoforths); // SUITE_ADD_TEST(suite, test2_yields); // SUITE_ADD_TEST(suite, test3_page_count); // SUITE_ADD_TEST(suite, test4_identical_fork); // SUITE_ADD_TEST(suite, test5_fork_return); // SUITE_ADD_TEST(suite, test6_double_fork); // SUITE_ADD_TEST(suite, test7_copy_on_write); // SUITE_ADD_TEST(suite, test8_copy_on_write_parent_edit); // SUITE_ADD_TEST(suite, test9_double_fork_copy_on_write); CuSuiteRun(suite); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("%s\n", output->buffer); CuStringDelete(output); CuSuiteDelete(suite); }
2.578125
3
2024-11-18T18:42:20.249517+00:00
2017-08-29T04:26:17
03555415b56f0731390214e2270d3599fc7e2dd0
{ "blob_id": "03555415b56f0731390214e2270d3599fc7e2dd0", "branch_name": "refs/heads/master", "committer_date": "2017-08-29T04:26:17", "content_id": "107a5c3a1cf1e87c76d92a85be9d0468265091b3", "detected_licenses": [ "MIT" ], "directory_id": "ce6bb170a4b503ed6dc0d2a5121210c39fe31245", "extension": "idc", "filename": "all.idc", "fork_events_count": 0, "gha_created_at": "2017-08-29T04:24:56", "gha_event_created_at": "2017-08-29T04:24:56", "gha_language": null, "gha_license_id": null, "github_id": 101718734, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 522, "license": "MIT", "license_type": "permissive", "path": "/toolchain/IDAScript/all.idc", "provenance": "stackv2-0030.json.gz:28790", "repo_name": "JohnCoatesOSS/DSYMCreator", "revision_date": "2017-08-29T04:26:17", "revision_id": "03dd2ed32079b19fb9ef0b77f6d6a918db227a59", "snapshot_id": "acac733facaa9436e7afb6b1d65208509b54e540", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JohnCoatesOSS/DSYMCreator/03dd2ed32079b19fb9ef0b77f6d6a918db227a59/toolchain/IDAScript/all.idc", "visit_date": "2021-01-20T12:33:48.084132" }
stackv2
#include <idc.idc> static print_all_method(filename) { auto file = fopen(filename, "w"); if (file != 0) { auto addr = 0; for (addr = NextFunction(addr); addr != BADADDR; addr = NextFunction(addr)) { auto name = GetFunctionName(addr); auto end = GetFunctionAttr(addr, FUNCATTR_END); Message("0x%x\t0x%x\t%s\n", addr, end, name); fprintf(file, "0x%x\t0x%x\t%s\n", addr, end, name); } } fclose(file); } static main() { Wait(); print_all_method(ARGV[1]); Exit(0); }
2.09375
2
2024-11-18T18:42:20.442760+00:00
2016-09-30T14:47:50
71f11db077e82999f78cb6777e0b48d8e39b1074
{ "blob_id": "71f11db077e82999f78cb6777e0b48d8e39b1074", "branch_name": "refs/heads/master", "committer_date": "2016-09-30T14:47:50", "content_id": "3bfdf0750c8a4a0eb7b440768ae03405e333aabd", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "9dede2e742404cf39eb1a51e4a268b18b3c9c795", "extension": "c", "filename": "disk.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 68952591, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3953, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/disk.c", "provenance": "stackv2-0030.json.gz:29046", "repo_name": "haxworx/os2disk", "revision_date": "2016-09-30T14:47:50", "revision_id": "284965c057e19f2dee7ed842a9eca4a274cb65c9", "snapshot_id": "e6266bdb1ad5b9090600e8509972d5b0e05e1034", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/haxworx/os2disk/284965c057e19f2dee7ed842a9eca4a274cb65c9/src/disk.c", "visit_date": "2020-05-25T15:45:39.760921" }
stackv2
/* Copyright (c) 2016, Al Poole <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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. */ #include "disk.h" #include "ui.h" extern Ui_Main_Contents *ui; void _clear_storage(void) { int i; for (i = 0; i < MAX_DISKS; i++) { if (storage[i]) { free(storage[i]); storage[i] = NULL; } } } int system_get_disks(void) { int disk_count = 0; _clear_storage(); #if defined(__OpenBSD__) static const mib[] = { CTL_HW, HW_DISKNAMES }; static const unsigned int miblen = 2; char buf[128]; char *drives; size_t len; sysctl(mib, miblen, NULL, &len, NULL, 0); if (!len) return; drives = calloc(1, len + 1); if (!drives) { return 0; } sysctl(mib, miblen, drives, &len, NULL, 0); char *s = drives; while (s) { char *end = strchr(s, ':'); if (!end) { break; } *end = '\0'; /* Do not expose common drives */ if (!strcmp(s, "sd0") || !strcmp(s, "hd0") || !strncmp(s, "cd", 2)) { goto skip; } if (s[0] == ',') { s++; } snprintf(buf, sizeof(buf), "/dev/%sc", s); printf("buffer: %s\n\n", buf); storage[disk_count++] = strdup(buf); skip: end++; s = strchr(end, ','); if (!s) { break; } } free(drives); #else /* This is problematic...eeze is broken atm. */ eeze_init(); Eina_List *devices = eeze_udev_find_by_type(EEZE_UDEV_TYPE_DRIVE_REMOVABLE, NULL); Eina_List *l; char *data; EINA_LIST_FOREACH(devices, l, data) { char buf[PATH_MAX]; snprintf(buf, sizeof(buf), "%s/block", data); DIR *dir = opendir(buf); struct dirent *dh; while (dh = readdir(dir)) { if (dh->d_name[0] == '.') continue; char p[PATH_MAX]; snprintf(p, sizeof(p), "%s/%s", buf, dh->d_name); struct stat fstats; stat(p, &fstats); if (S_ISDIR(fstats.st_mode)) { char devpath[PATH_MAX]; snprintf(devpath, sizeof(devpath), "/dev/%s", dh->d_name); storage[disk_count++] = strdup(devpath); break; } } closedir(dir); } eina_list_free(devices); eeze_shutdown(); #endif storage[disk_count] = NULL; if (disk_count) { if (ui) { update_combobox_storage(); } } return disk_count; }
2.03125
2
2024-11-18T18:42:20.558524+00:00
2019-04-14T07:17:15
36beb6ed88ae589da3b257ca521bb66960d15be2
{ "blob_id": "36beb6ed88ae589da3b257ca521bb66960d15be2", "branch_name": "refs/heads/master", "committer_date": "2019-04-14T07:17:15", "content_id": "4615fe4e75920b9a7244433c02a61d53a6e2a09a", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "ff0396e1b93d2d32d036398dddce6120006532d9", "extension": "c", "filename": "wintext.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 989, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/usr/wintext.c", "provenance": "stackv2-0030.json.gz:29174", "repo_name": "moneytech/ucbmaze1984", "revision_date": "2019-04-14T07:17:15", "revision_id": "3ff4168c5e6c97637c6dc2934f9fbfe8b8832f47", "snapshot_id": "14167e12e8294cea7d4cff3f46ff60316069844a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/moneytech/ucbmaze1984/3ff4168c5e6c97637c6dc2934f9fbfe8b8832f47/usr/wintext.c", "visit_date": "2021-10-26T20:18:42.927402" }
stackv2
#ifndef lint static char rcsid[] = "$Header: wintext.c,v 1.1 84/08/25 17:11:36 jcoker Exp $"; #endif #include <stdio.h> #include "../h/sunscreen.h" /* * Print the character at the given position on the pixrect. */ mvaddch(pr, x, y, c) struct pixrect *pr; { char buf[2]; buf[0] = c; buf[1] = '\0'; return mvaddstr(pr, x, y, buf); } /* * Put the string on the pixrect at the given coordianates. */ mvaddstr(pr, x, y, string) struct pixrect *pr; char *string; { struct pr_prpos where; where.pr = pr; where.pos.x = x; where.pos.y = y; pf_ttext(where, OP_CLEAR, pf_font, string); } /* * Do a printf at the specified position on the standard * screen pixrect. */ /*VARARGS4*/ mvprintf(pr, x, y, format, args) struct pixrect *pr; char *format; { char buf[BUFSIZ]; FILE str; str._flag = _IOWRT | _IOSTRG; str._cnt = sizeof buf; str._ptr = buf; str._file = -1; _doprnt(format, &args, &str); putc('\0', &str); return mvaddstr(pr, x, y, buf); }
2.375
2
2024-11-18T18:42:21.039516+00:00
2017-12-29T02:38:48
d0de576f257307ff2edcccda0d166aa0b532e3cd
{ "blob_id": "d0de576f257307ff2edcccda0d166aa0b532e3cd", "branch_name": "refs/heads/master", "committer_date": "2017-12-29T02:38:48", "content_id": "e3a710f4cb4b2a728244a71cf9b76b4977546002", "detected_licenses": [ "MIT" ], "directory_id": "b019a1dc9d93bbd551279e2d07c1aecf1e5cc7c8", "extension": "h", "filename": "xsocket.h", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 109394744, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 749, "license": "MIT", "license_type": "permissive", "path": "/xsocket.h", "provenance": "stackv2-0030.json.gz:29558", "repo_name": "Neol-d2022/OpenSync-se106a", "revision_date": "2017-12-29T02:38:48", "revision_id": "a5a67d2462884de16cc7b001bc054ceabe70f37e", "snapshot_id": "298aa74d2f5c69284803e8f809e721d7e09c9204", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Neol-d2022/OpenSync-se106a/a5a67d2462884de16cc7b001bc054ceabe70f37e/xsocket.h", "visit_date": "2021-09-03T02:54:18.553597" }
stackv2
#ifndef _XSOCKET_H_LOADED #define _XSOCKET_H_LOADED #ifdef _WIN32 /* See http://stackoverflow.com/questions/12765743/getaddrinfo-on-win32 */ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 /* Windows XP. */ #endif #include <Ws2tcpip.h> #include <winsock2.h> #else /* Assume that any non-Windows platform uses POSIX-style sockets instead. */ #include <arpa/inet.h> #include <netdb.h> /* Needed for getaddrinfo() and freeaddrinfo() */ #include <sys/socket.h> #include <unistd.h> /* Needed for close() */ typedef int SOCKET; #define INVALID_SOCKET (-1) #endif int socketLibInit(void); int socketLibDeInit(void); int socketClose(SOCKET sock); #endif /* Based on the answer at https://stackoverflow.com/questions/28027937/cross-platform-sockets */
2.015625
2
2024-11-18T18:42:21.205776+00:00
2017-12-23T14:30:50
1515039da04cef6c91a1bf6e63d423cdd7fc4de1
{ "blob_id": "1515039da04cef6c91a1bf6e63d423cdd7fc4de1", "branch_name": "refs/heads/master", "committer_date": "2017-12-23T14:30:50", "content_id": "232793c0fd38d738d980b5afd06e10ee9dbab9ee", "detected_licenses": [ "MIT" ], "directory_id": "32c1cb02fef24306e486f26327ab0c48c71477cd", "extension": "c", "filename": "lab1.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55706066, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2380, "license": "MIT", "license_type": "permissive", "path": "/OSlab/lab/lab1/lab1.c", "provenance": "stackv2-0030.json.gz:29815", "repo_name": "chaohu/Daily-Learning", "revision_date": "2017-12-23T14:30:50", "revision_id": "0e8d14a3497ad319eda20bc4682cec08d5d6fb08", "snapshot_id": "f015cdc8bfa3046780acf5c54ad0604bb82fb8a5", "src_encoding": "UTF-8", "star_events_count": 12, "url": "https://raw.githubusercontent.com/chaohu/Daily-Learning/0e8d14a3497ad319eda20bc4682cec08d5d6fb08/OSlab/lab/lab1/lab1.c", "visit_date": "2021-01-19T03:00:29.302645" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> void waiting(); void stop(); int wait_mark; void waiting() { while(wait_mark != 0); } void stop(int sig_no) { if(sig_no == SIGINT) wait_mark = 0; if(sig_no == SIGUSR1) wait_mark = 0; if(sig_no == SIGUSR2) wait_mark = 0; } int main(void) { int fd[2]; int child1pid,child2pid; char readbuffer[80]; pipe(fd); if((child1pid = fork()) == -1) { //创建子进程1 perror("fork"); exit(1); } if(child1pid == 0) { //子进程1运行代码 signal(SIGUSR1,stop); signal(SIGINT,SIG_IGN); wait_mark = 1; int num = 1; char cnum[5]; char string1[20] = "I send you "; char string2[10] = " times.\n"; char *string = (char *)malloc(sizeof(char)*40); close(fd[0]); while(wait_mark) { sprintf(cnum,"%d",num); strcat(string,string1); strcat(string,cnum); strcat(string,string2); write(fd[1],string,(strlen(string)+1)); free(string); string = (char *)malloc(sizeof(char)*40); num++; sleep(1); } printf("Child Process 1 is Killed by Parent!\n"); exit(0); } else { if((child2pid = fork()) == -1) { //再创建子进程2 perror("fork"); exit(1); } if(child2pid == 0) { //子进程2运行代码 signal(SIGUSR2,stop); signal(SIGINT,SIG_IGN); wait_mark = 1; close(fd[1]); while(wait_mark) { read(fd[0],readbuffer,sizeof(readbuffer)); printf("Received string:%s",readbuffer); sleep(1); } printf("Child Process 2 is Killed by Parent!\n"); exit(0); } else { //父进程代码 signal(SIGINT,stop); wait_mark = 1; waiting(); kill(child1pid,SIGUSR1); kill(child2pid,SIGUSR2); waitpid(child1pid,NULL,0); waitpid(child2pid,NULL,0); close(fd[0]); close(fd[1]); printf("Parent Process is Killed!\n"); exit(0); } } return 0; }
3.109375
3
2024-11-18T18:42:21.469721+00:00
2015-09-28T17:23:16
69688183392e6d53bcae9b5c559db6f7493acae4
{ "blob_id": "69688183392e6d53bcae9b5c559db6f7493acae4", "branch_name": "refs/heads/master", "committer_date": "2015-09-28T17:23:16", "content_id": "1c3223c20fccfad3ee2a15ec7d7976a06cc00820", "detected_licenses": [ "Apache-2.0" ], "directory_id": "99ec5c4436d6c20129807c416bbc9e234c2be937", "extension": "c", "filename": "timer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43112206, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7210, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/timer.c", "provenance": "stackv2-0030.json.gz:30072", "repo_name": "zhangfeibao/RD-JYJSJ-B", "revision_date": "2015-09-28T17:23:16", "revision_id": "f88621775dfa7defec88e87465f5d31696e7fed5", "snapshot_id": "6f2314685af78ff71888feeac80759cb0389b746", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zhangfeibao/RD-JYJSJ-B/f88621775dfa7defec88e87465f5d31696e7fed5/src/timer.c", "visit_date": "2021-01-10T01:44:45.117884" }
stackv2
#include "def.h" #include "STM8S103F3P.h" #include "timer.h" void delayus(uint8 dus) { uint8 i; uint8 m; for(i=0;i<dus;i++) { ; } } void TIM4_Init(void) { CLK_PCKENR1 |= 0x10;//timer4 clock enable TIM4_CR1=0x84; // 1 000 0 1 00 TIM4_IER=0x41; //触发中断使能 TIM4_SR=0x00; TIM4_EGR=0x01; TIM4_CNTR=0x00; // 1ms TIM4_PSCR=0x04; // 1/16---1us 分频后的频率1M,1US TIM4_ARR=124;//250; // 0--250 == 250us TIM4_CR1|=0x01; // enable counter } /* * 函数介绍:时间中心,每2MS执行一次。 * 输入参数:无 * 输出参数:无 * 返回值:无 */ void TimeCenter(void) { Time10Ms ++; if(Time10Ms >= 5) { Time10Ms = 0; f_10ms = 1; } if(++Time20Ms >= 10) { Time20Ms = 0; f_20ms = 1; } if(++Time500Ms >= 250) { //5ms时间点到: Time500Ms = 0; TimeUpData(); } /* if(WriteFlashDelay) { WriteFlashDelay --; if(f_need_write) { } } */ } /* * 函数介绍:时间更新 500MS执行一次。 * 输入参数:无 * 输出参数:无 * 返回值:无 */ void TimeUpData(void) { uint8 i; if(!f_first_10s) { TimePower ++; if(TimePower >= 20) { f_first_10s = 1; } } //滤芯计时: lifehour ++; if(ZjMode) { PP1filterTime += 180; if(PP1filterTime >= C_PP1filter_life) { PP1filterTime = C_PP1filter_life; f_PP1_life_over = 1; } C1filterTime += 180; if(C1filterTime >= C_C1filter_life) { C1filterTime = C_C1filter_life; f_C1_life_over = 1; } PP2filterTime += 180; if(PP2filterTime >= C_PP2filter_life) { PP2filterTime = C_PP2filter_life; f_PP2_life_over = 1; } ROfilterTime += 180; if(ROfilterTime >= C_ROfilter_life) { ROfilterTime = C_ROfilter_life; f_RO_life_over = 1; } CUFfilterTime += 180; if(CUFfilterTime >= C_CUFfilter_life) { CUFfilterTime = C_CUFfilter_life; f_CUF_life_over = 1; } //将滤芯时间存储起来: //WriteFilterData(); //SetWriteData(); } else { #if C_DEBUG if(lifehour >= 1) { i = 1; lifehour = 0; PP1filterTime ++; if(PP1filterTime == C_PP1_life_1_3) { SetWriteData(); } else if(PP1filterTime == C_PP1_life_2_3) { SetWriteData(); } else if(PP1filterTime == C_PP1_life_2_3_2) { SetWriteData(); } else if(PP1filterTime == C_PP1filter_life) { SetWriteData(); } if(PP1filterTime >= C_PP1filter_life) { PP1filterTime = C_PP1filter_life +1; f_PP1_life_over = 1; } C1filterTime ++; if(C1filterTime == C_C1_life_1_3) { SetWriteData(); } else if(C1filterTime == C_C1_life_2_3) { SetWriteData(); } else if(C1filterTime == C_C1_life_2_3_2) { SetWriteData(); } else if(C1filterTime == C_C1filter_life) { SetWriteData(); } if(C1filterTime >= C_C1filter_life) { C1filterTime = C_C1filter_life +1; f_C1_life_over = 1; } PP2filterTime ++; if(PP2filterTime == C_PP2_life_1_3) { SetWriteData(); } else if(PP2filterTime == C_PP2_life_2_3) { SetWriteData(); } else if(PP2filterTime == C_PP2_life_2_3_2) { SetWriteData(); } else if(PP2filterTime == C_PP2filter_life) { SetWriteData(); } if(PP2filterTime >= C_PP2filter_life) { PP2filterTime = C_PP2filter_life +1; f_PP2_life_over = 1; } ROfilterTime ++; if(ROfilterTime == C_RO_life_1_3) { SetWriteData(); } else if(ROfilterTime == C_RO_life_2_3) { SetWriteData(); } else if(ROfilterTime == C_RO_life_2_3_2) { SetWriteData(); } else if(ROfilterTime == C_ROfilter_life) { SetWriteData(); } if(ROfilterTime >= C_ROfilter_life) { ROfilterTime = C_ROfilter_life +1; f_RO_life_over = 1; } CUFfilterTime ++; if(CUFfilterTime == C_CUF_life_1_3) { SetWriteData(); } else if(CUFfilterTime == C_CUF_life_2_3) { SetWriteData(); } else if(CUFfilterTime == C_CUF_life_2_3_2) { SetWriteData(); } else if(CUFfilterTime == C_CUFfilter_life) { SetWriteData(); } if(CUFfilterTime >= C_CUFfilter_life) { CUFfilterTime = C_CUFfilter_life +1; f_CUF_life_over = 1; } } #else if(lifehour >= 7200) { lifehour = 0; PP1filterTime ++; if(PP1filterTime >= C_PP1filter_life) { PP1filterTime = C_PP1filter_life; f_PP1_life_over = 1; } C1filterTime ++; if(C1filterTime >= C_C1filter_life) { C1filterTime = C_C1filter_life; f_C1_life_over = 1; } PP2filterTime ++; if(PP2filterTime >= C_PP2filter_life) { PP2filterTime = C_PP2filter_life; f_PP2_life_over = 1; } ROfilterTime ++; if(ROfilterTime >= C_ROfilter_life) { ROfilterTime = C_ROfilter_life; f_RO_life_over = 1; } CUFfilterTime ++; if(CUFfilterTime >= C_CUFfilter_life) { CUFfilterTime = C_CUFfilter_life; f_CUF_life_over = 1; } //将滤芯时间存储起来: //WriteFilterData(); SetWriteData(); } #endif } //连续制水计时: if(f_zs_on) { ZsContiTimer ++; if(ZsContiTimer >= C_ZsContiTimer) { ZsContiTimer = 0; f_zs_err = 1; BeepSet(30,25,25); //报警30下, } } else { ZsContiTimer = 0; } }
2.28125
2
2024-11-18T18:42:21.708670+00:00
2022-04-17T18:47:46
29a6561d3d85081d27ce6fc56d49120186cc6541
{ "blob_id": "29a6561d3d85081d27ce6fc56d49120186cc6541", "branch_name": "refs/heads/master", "committer_date": "2022-04-17T18:47:46", "content_id": "120f8844bda2908d9693bdf6a0e4b768000147e3", "detected_licenses": [ "MIT" ], "directory_id": "130a666c9e3e3a75a133a875d2e4a61c9ac51117", "extension": "c", "filename": "test_peerd.c", "fork_events_count": 93, "gha_created_at": "2014-03-11T09:44:14", "gha_event_created_at": "2022-04-17T18:47:47", "gha_language": "C", "gha_license_id": "MIT", "github_id": 17625362, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 988, "license": "MIT", "license_type": "permissive", "path": "/src/zyre_peer_example/src/test_peerd.c", "provenance": "stackv2-0030.json.gz:30328", "repo_name": "zeromq/zproto", "revision_date": "2022-04-17T18:47:46", "revision_id": "a6172637216275dfd9b91c035ce143ab6e559b64", "snapshot_id": "af73edd065f4133c5f042fb6572c5463180ab707", "src_encoding": "UTF-8", "star_events_count": 203, "url": "https://raw.githubusercontent.com/zeromq/zproto/a6172637216275dfd9b91c035ce143ab6e559b64/src/zyre_peer_example/src/test_peerd.c", "visit_date": "2023-08-24T23:25:24.177614" }
stackv2
#include <stdio.h> #include "../include/test_peer.h" int main(void) { example_peer_t * peer = example_peer_new (); if (!peer) return -1; // Interrupted zpoller_t *poller = zpoller_new (stdin, example_peer_actor(peer), NULL); while (!zsys_interrupted) { void *which = zpoller_wait (poller, -1); // no timeout if(!which) break; //Inerruppted if (which == stdin){ char command [1024]; if (!fgets( command, 1024, stdin)) break; command[strlen(command)-1] = 0; // drop the trailing linefeed example_peer_send_chat(peer,command); } else { zmsg_t * msg = zmsg_recv(example_peer_actor(peer)); zmsg_print(msg); } } zpoller_destroy(&poller); example_peer_destroy (&peer); zsys_shutdown(); return 0; }
2.25
2
2024-11-18T18:42:21.994848+00:00
2013-05-16T19:49:17
0d34abedbe505fff513ff2278612d25f4c804b27
{ "blob_id": "0d34abedbe505fff513ff2278612d25f4c804b27", "branch_name": "refs/heads/master", "committer_date": "2013-05-16T19:49:17", "content_id": "e66f0dc761ca671cf8338d39c74395444eac8d1d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8f1b94dabca3b45ddf3b214db24dd4aa3481239a", "extension": "h", "filename": "tbuffer.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3519382, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1224, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/tbuffer.h", "provenance": "stackv2-0030.json.gz:30586", "repo_name": "tmbx/libktools", "revision_date": "2013-05-16T19:49:17", "revision_id": "08a95694e342dfb0225299c3ed5fcf64d7ff180b", "snapshot_id": "fc4d47951db2e609e9c2a21f8b4142a1ddbdb831", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tmbx/libktools/08a95694e342dfb0225299c3ed5fcf64d7ff180b/src/tbuffer.h", "visit_date": "2021-01-22T09:09:11.489829" }
stackv2
/** * klib/priv/tbuffer.h * Copyright (C) 2006-2012 Opersys inc., All rights reserved. * * Dynamic typed buffer. * * @author François-Denis Gonthier * Reviewed by Laurent Birtz on 22 january 2007. */ #ifndef _KLIB_TBUFFER_H #define _KLIB_TBUFFER_H typedef struct __tbuffer tbuffer; struct __tbuffer { int del_dbuf; kbuffer *dbuf; }; /** Typed buffer types * * That enum matches the #define of equivalent types in the KNP * protocol definition. */ enum tbuffer_type { TBUF_UINT32 = 1, TBUF_UINT64 = 2, TBUF_STR = 3 }; tbuffer *tbuffer_new(size_t s); tbuffer *tbuffer_new_dbuf(kbuffer *dbuf); void tbuffer_destroy(tbuffer *self); kbuffer *tbuffer_get_dbuf(tbuffer *self); int tbuffer_read_uint32(tbuffer *self, uint32_t *n); int tbuffer_read_uint64(tbuffer *self, uint64_t *n); int tbuffer_read_string(tbuffer *self, const char **str, size_t *str_s); int tbuffer_peek_type(tbuffer *self, enum tbuffer_type *type); void tbuffer_write_uint64(tbuffer *self, uint64_t n); void tbuffer_write_uint32(tbuffer *self, uint32_t n); void tbuffer_write_str(tbuffer *self, const char *str, size_t str_s); void tbuffer_write_cstr(tbuffer *self, const char *str); #endif // _KLIB_TBUFFER_H
2.359375
2
2024-11-18T18:42:22.522511+00:00
2023-07-10T16:06:35
12c75789d8597b76514a14a4ad24ea1ddfec73e2
{ "blob_id": "12c75789d8597b76514a14a4ad24ea1ddfec73e2", "branch_name": "refs/heads/master", "committer_date": "2023-07-10T16:06:35", "content_id": "6b7d531d2a8cbc26337442a55a4ebb01131e6856", "detected_licenses": [ "ISC", "MIT" ], "directory_id": "d2e0fb3fdad7fc2cb70894591d358f40d8db13d2", "extension": "c", "filename": "connection.c", "fork_events_count": 15, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55073371, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12993, "license": "ISC,MIT", "license_type": "permissive", "path": "/gui/connection.c", "provenance": "stackv2-0030.json.gz:31100", "repo_name": "dennis95/dennix", "revision_date": "2023-07-10T16:06:35", "revision_id": "f898bb2d27346f6257df1650a002ee929e66e7fa", "snapshot_id": "54c568485862a0799664033eb0717abb028d3924", "src_encoding": "UTF-8", "star_events_count": 168, "url": "https://raw.githubusercontent.com/dennis95/dennix/f898bb2d27346f6257df1650a002ee929e66e7fa/gui/connection.c", "visit_date": "2023-08-17T06:54:17.274650" }
stackv2
/* Copyright (c) 2020, 2021 Dennis Wölfing * * 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. */ /* gui/connection.c * Connection. */ #include <errno.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "connection.h" #include "window.h" static struct Window* getWindow(struct Connection* conn, unsigned int windowId); static void handleMessage(struct Connection* conn, unsigned int type, size_t length, void* msg); static bool sendOutput(struct Connection* conn, const void* buffer, size_t size); static void handleCloseWindow(struct Connection* conn, size_t length, struct gui_msg_close_window* msg); static void handleCreateWindow(struct Connection* conn, size_t length, struct gui_msg_create_window* msg); static void handleHideWindow(struct Connection* conn, size_t length, struct gui_msg_hide_window* msg); static void handleRedrawWindow(struct Connection* conn, size_t length, struct gui_msg_redraw_window* msg); static void handleRedrawWindowPart(struct Connection* conn, size_t length, struct gui_msg_redraw_window_part* msg); static void handleResizeWindow(struct Connection* conn, size_t length, struct gui_msg_resize_window* msg); static void handleSetRelativeMouse(struct Connection* conn, size_t length, struct gui_msg_set_relative_mouse* msg); static void handleSetWindowBackground(struct Connection* conn, size_t length, struct gui_msg_set_window_background* msg); static void handleSetWindowCursor(struct Connection* conn, size_t length, struct gui_msg_set_window_cursor* msg); static void handleSetWindowTitle(struct Connection* conn, size_t length, struct gui_msg_set_window_title* msg); static void handleShowWindow(struct Connection* conn, size_t length, struct gui_msg_show_window* msg); bool flushConnectionBuffer(struct Connection* conn) { while (conn->outputBuffered) { size_t copySize = conn->outputBufferSize - conn->outputBufferOffset; if (conn->outputBuffered < copySize) copySize = conn->outputBuffered; ssize_t written = write(conn->fd, conn->outputBuffer + conn->outputBufferOffset, copySize); if (written < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) return true; return false; } conn->outputBufferOffset = (conn->outputBufferOffset + written) % conn->outputBufferSize; conn->outputBuffered -= written; } conn->outputBufferOffset = 0; return true; } static struct Window* getWindow(struct Connection* conn, unsigned int windowId) { if (windowId >= conn->windowsAllocated) return NULL; return conn->windows[windowId]; } static void handleMessage(struct Connection* conn, unsigned int type, size_t length, void* msg) { switch (type) { case GUI_MSG_CLOSE_WINDOW: handleCloseWindow(conn, length, msg); break; case GUI_MSG_CREATE_WINDOW: handleCreateWindow(conn, length, msg); break; case GUI_MSG_HIDE_WINDOW: handleHideWindow(conn, length, msg); break; case GUI_MSG_REDRAW_WINDOW: handleRedrawWindow(conn, length, msg); break; case GUI_MSG_REDRAW_WINDOW_PART: handleRedrawWindowPart(conn, length, msg); break; case GUI_MSG_RESIZE_WINDOW: handleResizeWindow(conn, length, msg); break; case GUI_MSG_SET_RELATIVE_MOUSE: handleSetRelativeMouse(conn, length, msg); break; case GUI_MSG_SET_WINDOW_BACKGROUND: handleSetWindowBackground(conn, length, msg); break; case GUI_MSG_SET_WINDOW_CURSOR: handleSetWindowCursor(conn, length, msg); break; case GUI_MSG_SET_WINDOW_TITLE: handleSetWindowTitle(conn, length, msg); break; case GUI_MSG_SHOW_WINDOW: handleShowWindow(conn, length, msg); break; } } bool receiveMessage(struct Connection* conn) { while (conn->headerReceived < sizeof(struct gui_msg_header)) { ssize_t bytesRead = read(conn->fd, (char*) &conn->headerBuffer + conn->headerReceived, sizeof(struct gui_msg_header) - conn->headerReceived); if (bytesRead < 0) { return errno == EAGAIN || errno == EWOULDBLOCK; } conn->headerReceived += bytesRead; } size_t length = conn->headerBuffer.length; if (!conn->messageBuffer) { conn->messageBuffer = malloc(length); if (!conn->messageBuffer) dxui_panic(context, "malloc"); } while (conn->messageReceived < length) { ssize_t bytesRead = read(conn->fd, conn->messageBuffer + conn->messageReceived, length - conn->messageReceived); if (bytesRead < 0) { return errno == EAGAIN || errno == EWOULDBLOCK; } conn->messageReceived += bytesRead; } handleMessage(conn, conn->headerBuffer.type, length, conn->messageBuffer); free(conn->messageBuffer); conn->messageBuffer = NULL; conn->messageReceived = 0; conn->headerReceived = 0; return true; } void sendEvent(struct Connection* conn, unsigned int type, size_t length, void* msg) { struct gui_msg_header header; header.type = type; header.length = length; sendOutput(conn, &header, sizeof(header)); sendOutput(conn, msg, length); } static bool sendOutput(struct Connection* conn, const void* buffer, size_t size) { const char* buf = buffer; if (!conn->outputBuffered) { while (size) { ssize_t written = write(conn->fd, buf, size); if (written < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; return false; } buf += written; size -= written; } } if (size) { if (size < conn->outputBufferSize - conn->outputBuffered) { size_t offset = (conn->outputBufferOffset + conn->outputBuffered) % conn->outputBufferSize; size_t copySize = conn->outputBufferSize - offset; if (size < copySize) copySize = size; memcpy(conn->outputBuffer + offset, buf, copySize); buf += copySize; if (size - copySize) { memcpy(conn->outputBuffer, buf, size - copySize); } conn->outputBuffered += size; } else { char* newBuffer = malloc(conn->outputBuffered + size); if (!newBuffer) dxui_panic(context, "malloc"); size_t copySize = conn->outputBufferSize - conn->outputBufferOffset; if (conn->outputBuffered < copySize) { copySize = conn->outputBuffered; } memcpy(newBuffer, conn->outputBuffer + conn->outputBufferOffset, copySize); if (conn->outputBuffered > copySize) { memcpy(newBuffer + copySize, conn->outputBuffer, conn->outputBuffered - copySize); } memcpy(newBuffer + conn->outputBuffered, buf, size); free(conn->outputBuffer); conn->outputBuffer = newBuffer; conn->outputBuffered += size; conn->outputBufferOffset = 0; conn->outputBufferSize = conn->outputBuffered; } } return true; } static void handleCloseWindow(struct Connection* conn, size_t length, struct gui_msg_close_window* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; closeWindow(window); } static void handleCreateWindow(struct Connection* conn, size_t length, struct gui_msg_create_window* msg) { if (length < sizeof(*msg)) return; char* title = strndup(msg->title, length - sizeof(*msg)); if (!title) dxui_panic(context, "malloc"); struct Window* window = addWindow(msg->x, msg->y, msg->width, msg->height, title, msg->flags, conn); free(title); struct gui_event_window_created response; for (size_t i = 0; i < conn->windowsAllocated; i++) { if (!conn->windows[i]) { conn->windows[i] = window; window->id = i; response.window_id = i; sendEvent(conn, GUI_EVENT_WINDOW_CREATED, sizeof(response), &response); return; } } size_t newSize = conn->windowsAllocated ? conn->windowsAllocated * 2 : 8; conn->windows = reallocarray(conn->windows, newSize, sizeof(struct Window*)); if (!conn->windows) dxui_panic(context, "realloc"); memset(conn->windows + conn->windowsAllocated, 0, (newSize - conn->windowsAllocated) * sizeof(struct Window*)); conn->windows[conn->windowsAllocated] = window; window->id = conn->windowsAllocated; response.window_id = conn->windowsAllocated; sendEvent(conn, GUI_EVENT_WINDOW_CREATED, sizeof(response), &response); conn->windowsAllocated = newSize; } static void handleHideWindow(struct Connection* conn, size_t length, struct gui_msg_hide_window* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; hideWindow(window); } static void handleRedrawWindow(struct Connection* conn, size_t length, struct gui_msg_redraw_window* msg) { if (length < sizeof(*msg)) return; size_t lfbSize = msg->height * msg->width * sizeof(dxui_color); if (length < sizeof(*msg) + lfbSize) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; redrawWindow(window, msg->width, msg->height, msg->lfb); } static void handleRedrawWindowPart(struct Connection* conn, size_t length, struct gui_msg_redraw_window_part* msg) { if (length < sizeof(*msg)) return; size_t lfbSize = ((msg->height - 1) * msg->pitch + msg->width) * sizeof(dxui_color); if (length < sizeof(*msg) + lfbSize) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; redrawWindowPart(window, msg->x, msg->y, msg->width, msg->height, msg->pitch, msg->lfb); } static void handleResizeWindow(struct Connection* conn, size_t length, struct gui_msg_resize_window* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; dxui_dim dim = { msg->width, msg->height }; resizeClientRect(window, dim); } static void handleSetRelativeMouse(struct Connection* conn, size_t length, struct gui_msg_set_relative_mouse* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; window->relativeMouse = msg->relative; if (window == topWindow) { dxui_set_relative_mouse(compositorWindow, msg->relative); } } static void handleSetWindowBackground(struct Connection* conn, size_t length, struct gui_msg_set_window_background* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; setWindowBackground(window, msg->color); } static void handleSetWindowCursor(struct Connection* conn, size_t length, struct gui_msg_set_window_cursor* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; if (msg->cursor >= GUI_NUM_CURSORS) return; setWindowCursor(window, msg->cursor); } static void handleSetWindowTitle(struct Connection* conn, size_t length, struct gui_msg_set_window_title* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; char* title = strndup(msg->title, length - sizeof(*msg)); if (!title) dxui_panic(context, "malloc"); setWindowTitle(window, title); free(title); } static void handleShowWindow(struct Connection* conn, size_t length, struct gui_msg_show_window* msg) { if (length < sizeof(*msg)) return; struct Window* window = getWindow(conn, msg->window_id); if (!window) return; showWindow(window); }
2.34375
2
2024-11-18T18:42:22.770538+00:00
2023-03-29T20:16:12
008f5b9b169520a58be231ba51b8952da5e77d5f
{ "blob_id": "008f5b9b169520a58be231ba51b8952da5e77d5f", "branch_name": "refs/heads/master", "committer_date": "2023-03-29T20:16:12", "content_id": "0586ff91be33e76a3b208f53993e27202e8b1562", "detected_licenses": [ "Unlicense" ], "directory_id": "4927960c9f30ef7681b301518e51f47209c48714", "extension": "c", "filename": "basic.c", "fork_events_count": 25, "gha_created_at": "2017-06-04T20:42:34", "gha_event_created_at": "2021-07-29T17:31:03", "gha_language": "C", "gha_license_id": "Unlicense", "github_id": 93340272, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 732, "license": "Unlicense", "license_type": "permissive", "path": "/pset5/2021/sandbox/basic.c", "provenance": "stackv2-0030.json.gz:31228", "repo_name": "glennlopez/CS50.HarvardX", "revision_date": "2023-03-29T20:16:12", "revision_id": "1a916709dad88902c7fb6a3e125833e724dcbd53", "snapshot_id": "bc8208e44ef7205de3240e00e0747c91870c2b97", "src_encoding": "UTF-8", "star_events_count": 34, "url": "https://raw.githubusercontent.com/glennlopez/CS50.HarvardX/1a916709dad88902c7fb6a3e125833e724dcbd53/pset5/2021/sandbox/basic.c", "visit_date": "2023-04-08T15:26:43.589132" }
stackv2
#include <stdio.h> #include <stdlib.h> // node struct typedef struct node_ptr { int number; struct node_ptr *next; } node; // prototypes void PrintLinkedList(node *head); /* Manual linking lists using pointers (no HEAP) */ int main() { node n1, n2, n3; node *head; n1.number = 99; n2.number = 98; n3.number = 97; // linking head = &n1; n1.next = &n2; n2.next = &n3; n3.next = NULL; PrintLinkedList(head); return 0; } void PrintLinkedList(node *head) { node *temp = head; while(temp != NULL) { // print the number value in the node printf("%i\n", (*temp).number); // update the list temp = (*temp).next; } }
3.484375
3
2024-11-18T19:39:16.230997+00:00
2020-04-15T20:58:21
74db6a679f507760bae5c491fef7a3f4c8637093
{ "blob_id": "74db6a679f507760bae5c491fef7a3f4c8637093", "branch_name": "refs/heads/master", "committer_date": "2020-04-15T20:58:21", "content_id": "6411f0d0f1684c11fc72120727e453f74d7a372f", "detected_licenses": [ "MIT" ], "directory_id": "ebc700cb11b49d5319544d3f7bbc8882250a8e5a", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 264354106, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3019, "license": "MIT", "license_type": "permissive", "path": "/tests/altium_crap/Soft Designs/Legacy/NB1/EX18/Embedded/main.c", "provenance": "stackv2-0032.json.gz:114617", "repo_name": "hanun2999/Altium-Schematic-Parser", "revision_date": "2020-04-15T20:58:21", "revision_id": "a9bd5b1a865f92f2e3f749433fb29107af528498", "snapshot_id": "1c6dde56f673f7cb2a517f7dba8596e55282b246", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/hanun2999/Altium-Schematic-Parser/a9bd5b1a865f92f2e3f749433fb29107af528498/tests/altium_crap/Soft Designs/Legacy/NB1/EX18/Embedded/main.c", "visit_date": "2022-04-16T21:43:18.502597" }
stackv2
/************************************************************************** ** * ** FILE : main.c * ** * ** DESCRIPTION : IO Redirection example. * ** This example shows how to redirect standard IO to in- * ** and output devices. All standard IO functions like * ** printf, fscanf, putchar, fgets map on the low level * ** functions _write() for output and _read() for input * ** So to redirect IO to a specific device all that is * ** required is to customize these functions for the * ** specific input/output device. This example uses the * ** following mappings: * ** 0 - STDIN - RS232 Serial in * ** 1 - STDOUT - RS232 Serial out * ** 2 - STDERR - LCD * ** See also the _read.c and _write.c modules in this * ** example. * ** * ** COPYRIGHT : 2004 Altium BV * ** * **************************************************************************/ #include <stdio.h> #include <string.h> #include "lcd.h" void cmd_version( void ) { printf( "IO Redirection example v1.0\r\n" ); } void cmd_help( void ) { printf( "Valid commands:\r\n" ); printf( " help\r\n" ); printf( " version\r\n" ); } void handle_command( char *cmd ) { char validcmd = 0; size_t len = strlen( cmd ); // check for and remove ending newline if ( cmd[len-1] == '\n' ) { cmd[len-1] = '\0'; --len; } switch ( len ) { case 4: if ( !strcmp(cmd,"help") ) { validcmd = 1; cmd_help(); } break; case 7: if ( !strcmp(cmd,"version") ) { validcmd = 1; cmd_version(); } break; } if ( !validcmd ) { printf( "Invalid command: \"%s\"\r\n", cmd ); } } void main( void ) { char line[100]; lcd_init(); while ( 1 ) { do { /* message printed to stdout = serial out */ printf( "Enter command: " ); /* Read a line from stdin = serial in */ fgets( line, sizeof(line), stdin ); } while ( strlen(line) <= 1 ); /* and write it to stdout = LCD */ fprintf( stderr, "Command entered:%s\n", line ); handle_command( line ); } }
2.9375
3
2024-11-18T20:02:55.405436+00:00
2021-05-25T08:29:01
1c1a87df44a622ded5052723c38d7d2d11fabc9f
{ "blob_id": "1c1a87df44a622ded5052723c38d7d2d11fabc9f", "branch_name": "refs/heads/master", "committer_date": "2021-05-25T08:29:01", "content_id": "b619665cc16b5229da55ddcb368c924a6049bbb7", "detected_licenses": [ "MIT" ], "directory_id": "82873b85f33c88a9a717394296a4a658f6903493", "extension": "c", "filename": "rwtowin.c", "fork_events_count": 0, "gha_created_at": "2020-09-01T12:45:02", "gha_event_created_at": "2020-09-01T12:45:03", "gha_language": null, "gha_license_id": "MIT", "github_id": 291995472, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4315, "license": "MIT", "license_type": "permissive", "path": "/nlp/sources/ogm_xpt/lib/rwtowin.c", "provenance": "stackv2-0033.json.gz:513", "repo_name": "odespesse/viky-ai", "revision_date": "2021-05-25T08:29:01", "revision_id": "de617b2798e49698e756eec0e0d6add89b57d0e0", "snapshot_id": "c191a88cb44f2e99288c7472b23ffc5b609482f3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/odespesse/viky-ai/de617b2798e49698e756eec0e0d6add89b57d0e0/nlp/sources/ogm_xpt/lib/rwtowin.c", "visit_date": "2023-08-17T23:09:42.982666" }
stackv2
/* * Running a function with timeout, from wget code, Windows version * Copyright (c) 2004 Pertimm bu Patrick Constant * Dev : June 2004 * Version 1.0 */ #define DPcInDll #include <logxpt.h> #include <assert.h> /* mswindows.c -- Windows-specific support Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. This file is part of GNU Wget. GNU Wget 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. GNU Wget 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 Wget; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. In addition, as a special exception, the Free Software Foundation gives permission to link the code of its release of Wget with the OpenSSL project's "OpenSSL" library (or with modified versions of it that use the same license as the "OpenSSL" library), and distribute the linked executables. You must obey the GNU General Public License in all respects for all of the code used other than "OpenSSL". If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ /* run_with_timeout Windows implementation. */ /* Stack size 0 uses default thread stack-size (reserve+commit). * Determined by what's in the PE header. */ #define THREAD_STACK_SIZE 0 struct thread_data { int (*fun) (void *); void *arg; DWORD ws_error; }; /* The callback that runs FUN(ARG) in a separate thread. This function exists for two reasons: a) to not require FUN to be declared WINAPI/__stdcall[1], and b) to retrieve Winsock errors, which are per-thread. The latter is useful when FUN calls Winsock functions, which is how run_with_timeout is used in Wget. [1] MSVC can use __fastcall globally (cl /Gr) and on Watcom this is the default (wcc386 -3r). */ static DWORD WINAPI thread_helper (void *arg) { struct thread_data *td = (struct thread_data *) arg; /* Initialize Winsock error to what it was in the parent. That way the subsequent call to WSAGetLastError will return the same value if td->fun doesn't change Winsock error state. */ WSASetLastError (td->ws_error); td->fun (td->arg); /* Return Winsock error to the caller, in case FUN ran Winsock code. */ td->ws_error = WSAGetLastError (); return 0; } /* Call FUN(ARG), but don't allow it to run for more than TIMEOUT seconds. Returns non-zero if the function was interrupted with a timeout, zero otherwise. This works by running FUN in a separate thread and terminating the thread if it doesn't finish in the specified time. */ PUBLIC(int) OgRunWithTimeout(double seconds, int (*fun) (void *), void *arg, char *where) { static HANDLE thread_hnd = NULL; struct thread_data thread_arg; DWORD thread_id; int rc = 0; if (seconds == 0) { blocking_fallback: IFE(fun(arg)); return 0; } /* Should never happen, but test for recursivety anyway */ assert (thread_hnd == NULL); thread_arg.fun = fun; thread_arg.arg = arg; thread_arg.ws_error = WSAGetLastError (); thread_hnd = CreateThread (NULL, THREAD_STACK_SIZE, thread_helper, &thread_arg, 0, &thread_id); if (!thread_hnd) { OgMessageLog(DOgMlogInLog,where,0,"CreateThread() failed; %s\n", strerror (GetLastError ())); goto blocking_fallback; } if (WaitForSingleObject (thread_hnd, (DWORD)(1000 * seconds)) == WAIT_OBJECT_0) { /* Propagate error state (which is per-thread) to this thread, so the caller can inspect it. */ WSASetLastError (thread_arg.ws_error); rc = 0; } else { TerminateThread (thread_hnd, 1); rc = 1; } CloseHandle (thread_hnd); /* clear-up after TerminateThread() */ thread_hnd = NULL; return rc; }
2.125
2
2024-11-18T20:15:11.424247+00:00
2020-10-31T08:48:14
a08eac0af4e1c72cfa185777619857da2567443f
{ "blob_id": "a08eac0af4e1c72cfa185777619857da2567443f", "branch_name": "refs/heads/master", "committer_date": "2020-10-31T08:48:14", "content_id": "a5e06c6a9543739a4b8bb530c21ac6baf94957bb", "detected_licenses": [ "MIT" ], "directory_id": "e30b1da5d500d6126928757ab71102ef1d1822d7", "extension": "c", "filename": "options.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 292681832, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9905, "license": "MIT", "license_type": "permissive", "path": "/src/common/options.c", "provenance": "stackv2-0033.json.gz:157589", "repo_name": "alpha-catharsis/psp", "revision_date": "2020-10-31T08:48:14", "revision_id": "f3ecbd1087b3927939d2e06748a8b095e1f4dcda", "snapshot_id": "8d22bc251ba7154ac236b17bc1b7ccddc1b72aa9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alpha-catharsis/psp/f3ecbd1087b3927939d2e06748a8b095e1f4dcda/src/common/options.c", "visit_date": "2023-01-03T01:43:46.282163" }
stackv2
/* Configuration header */ #include "../config.h" /* C standard library headers */ #include <limits.h> #include <stdio.h> #include <stdlib.h> /* POSIX library headers */ #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> /* PSP Common headers */ #include "options.h" #include "output.h" /* globals */ const struct num_ubounds verb_bounds = {erro_lvl, debg_lvl}; /* functions prototypes */ char *gen_opt_string(struct option_descriptor *); int apply_option(struct option_descriptor *, char, char *); /* option register management */ int parse_opts(struct option_descriptor* ods_ptr, int argc, char **argv) { int c; char *optstring = gen_opt_string(ods_ptr); if(!optstring) return 0; int res = 1; while((c = getopt(argc, argv, optstring)) != -1){ if((c == ':') || (c == '?')){ printf("invalid options\n"); res = 0; }else{ if(!apply_option(ods_ptr, (char) c, optarg)){ res = 0; } } } free(optstring); return res; } int check_opts(struct option_descriptor* ods_ptr) { struct option_descriptor *it = ods_ptr; struct option_descriptor *od_ptr; const char *opt_letter; while(it->letter != '\0'){ if(it->set){ if(it->required_opts[0] != '*'){ opt_letter = it->required_opts; while(*opt_letter != '\0'){ od_ptr = find_opt_desc(ods_ptr, *opt_letter); if(!od_ptr){ printf("program bug\n"); return 0; }else{ if(!od_ptr->set){ printf("option '-%c' requires option '-%c'\n", it->letter, *opt_letter); return 0; } } opt_letter++; } } opt_letter = it->forbidden_opts; while(*opt_letter != '\0'){ od_ptr = find_opt_desc(ods_ptr, *opt_letter); if(!od_ptr){ printf("program bug\n"); return 0; }else{ if(od_ptr->set){ printf("option '-%c' is incompatible with option '-%c'\n", it->letter, *opt_letter); return 0; } } opt_letter++; } }else{ if(it->required_opts[0] == '*'){ printf("option '-%c' must be specified\n", it->letter); return 0; } } it++; } return 1; } int print_help_msg(const char *prolg1, const char *prolg2, struct option_descriptor *ods_ptr, struct opt_group *ogs) { struct opt_group *group_it; const char *opt_letter_it; struct option_descriptor *od_ptr; printf(prolg1); printf("\n"); printf(prolg2); printf("\n"); group_it = ogs; while(group_it->group_name){ printf(" %s:\n", group_it->group_name); opt_letter_it = group_it->opts; while(*opt_letter_it != '\0'){ od_ptr = find_opt_desc(ods_ptr, *opt_letter_it); if(!od_ptr){ printf("program bug\n"); return 0; }else{ printf(" -%c %s\n", *opt_letter_it, od_ptr->desc); } opt_letter_it++; } puts(""); group_it++; } return 1; } int is_opt_set(struct option_descriptor *ods_ptr, char letter) { struct option_descriptor *od_ptr = find_opt_desc(ods_ptr, letter); if(!od_ptr){ printf("program bug\n"); return 0; }else{ return od_ptr->set; } } struct option_descriptor *find_opt_desc(struct option_descriptor *ods_ptr, char letter) { struct option_descriptor *it = ods_ptr; while(it->letter != '\0'){ if(it->letter == letter){ return it; } it++; } return NULL; } /* general options management */ void init_general_options(struct general_options *gen_opts_ptr) { gen_opts_ptr->verb_lvl = info_lvl; gen_opts_ptr->log_fname = NULL; } void apply_general_options(const struct general_options *gen_opts_ptr) { set_verbosity(gen_opts_ptr->verb_lvl); if(gen_opts_ptr->log_fname){ set_logfile(gen_opts_ptr->log_fname); } } /* helper functions */ char *gen_opt_string(struct option_descriptor *ods_ptr) { size_t chr_cnt = 3; struct option_descriptor *it = ods_ptr; char *res, *res_it; while(it->letter != '\0'){ chr_cnt += it->has_param ? 2 : 1; it++; } res = malloc(chr_cnt); if(!res){ return NULL; }else{ it = ods_ptr; res_it = res; *res_it = ':'; res_it++; while(it->letter != '\0'){ *res_it = it->letter; res_it++; if(it->has_param){ *res_it = ':'; res_it++; } it++; } } return res; } int apply_option(struct option_descriptor *ods_ptr, char letter, char *arg) { struct option_descriptor *od_ptr = find_opt_desc(ods_ptr, letter); if(!od_ptr){ printf("unrecognized option '-%c'\n", letter); return 0; }else{ if(od_ptr->has_param){ if(!arg){ printf("no parameter provided for option '-%c'\n", letter); return 0; }else{ if(!od_ptr->apply_option(od_ptr, arg, od_ptr->apply_data)){ return 0; } } }else{ if((od_ptr->apply_option) && (!od_ptr->apply_option(od_ptr, NULL, od_ptr->apply_data))){ return 0; } } od_ptr->set = 1; } return 1; } /* options apply callbacks */ int opt_flag_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { int *trgt_int = (int *) opt_desc_ptr->trgt; (void) arg; (void) data_ptr; *trgt_int = 1; return 1; } int opt_int_set_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { int *trgt_int = (int *) opt_desc_ptr->trgt; (void) arg; *trgt_int = *((const int *) data_ptr); return 1; } int opt_int_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { char *endptr; int *trgt_int = (int *) opt_desc_ptr->trgt; const struct num_bounds *bounds_ptr = (const struct num_bounds *) data_ptr; long aux = strtol(arg, &endptr, 10); if(*endptr == '\0'){ if((aux >= INT_MIN) && (aux <= INT_MAX) && (!bounds_ptr || ((aux >= bounds_ptr->low_bound) && (aux <= bounds_ptr->hi_bound)))){ *trgt_int = (int) aux; }else{ printf("option '-%c': integer %ld is out of bounds\n", opt_desc_ptr->letter, aux); return 0; } }else{ printf("option '-%c': invalid integer \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_uint_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { char *endptr; unsigned int *trgt_int = (unsigned int *) opt_desc_ptr->trgt; const struct num_ubounds *bounds_ptr = (const struct num_ubounds *) data_ptr; unsigned long aux = strtoul(arg, &endptr, 10); if(*endptr == '\0'){ if((aux <= UINT_MAX) && (!bounds_ptr || ((aux >= bounds_ptr->low_bound) && (aux <= bounds_ptr->hi_bound)))){ *trgt_int = (unsigned int) aux; }else{ printf("option '-%c': unsigned integer %ld is out of bounds\n", opt_desc_ptr->letter, aux); return 0; } }else{ printf("option '-%c': invalid unsigned integer \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_long_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { char *endptr; long *trgt_int = (long *) opt_desc_ptr->trgt; const struct num_bounds *bounds_ptr = (const struct num_bounds *) data_ptr; long aux = strtol(arg, &endptr, 10); if(*endptr == '\0'){ if((!bounds_ptr || ((aux >= bounds_ptr->low_bound) && (aux <= bounds_ptr->hi_bound)))){ *trgt_int = (long) aux; }else{ printf("option '-%c': long integer %ld is out of bounds\n", opt_desc_ptr->letter, aux); return 0; } }else{ printf("option '-%c': invalid long integer \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_ulong_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { char *endptr; unsigned long *trgt_int = (unsigned long *) opt_desc_ptr->trgt; const struct num_ubounds *bounds_ptr = (const struct num_ubounds *) data_ptr; unsigned long aux = strtoul(arg, &endptr, 10); if(*endptr == '\0'){ if((!bounds_ptr || ((aux >= bounds_ptr->low_bound) && (aux <= bounds_ptr->hi_bound)))){ *trgt_int = (unsigned long) aux; }else{ printf("option '-%c': unsigned long integer %ld is out of bounds\n", opt_desc_ptr->letter, aux); return 0; } }else{ printf("option '-%c': invalid unsigned long integer \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_double_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { char *endptr; double *trgt_int = (double *) opt_desc_ptr->trgt; const struct num_dbounds *bounds_ptr = (const struct num_dbounds *) data_ptr; double aux = strtod(arg, &endptr); if(*endptr == '\0'){ if((!bounds_ptr || ((aux >= bounds_ptr->low_bound) && (aux <= bounds_ptr->hi_bound)))){ *trgt_int = (double) aux; }else{ printf("option '-%c': real %f is out of bounds\n", opt_desc_ptr->letter, aux); return 0; } }else{ printf("option '-%c': invalid real \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_in_addr_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { in_addr_t *trgt_addr = (in_addr_t *) opt_desc_ptr->trgt; in_addr_t addr_aux = inet_addr(arg); (void) data_ptr; if(addr_aux != ((in_addr_t) (-1))){ *trgt_addr = addr_aux; }else{ printf("option '-%c': invalid IP adderss \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_in_port_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { in_port_t *trgt_port = (in_port_t *) opt_desc_ptr->trgt; long aux = atol(optarg); (void) data_ptr; if((aux > 0) && (aux <= USHRT_MAX)){ *trgt_port = htons((in_port_t) aux); }else{ printf("option '-%c': invalid internet port \"%s\"\n", opt_desc_ptr->letter, arg); return 0; } return 1; } int opt_str_apply(struct option_descriptor *opt_desc_ptr, const char *arg, const void *data_ptr) { const char **trgt_str = (const char **) opt_desc_ptr->trgt; *trgt_str = arg; (void) data_ptr; return 1; }
2.53125
3
2024-11-18T20:15:11.487711+00:00
2019-09-22T12:27:32
672102bda53632e0546f6e23db5db8d5d4191861
{ "blob_id": "672102bda53632e0546f6e23db5db8d5d4191861", "branch_name": "refs/heads/master", "committer_date": "2019-09-22T12:27:32", "content_id": "9e1e0c9a789c1415d78c85000ba825d2a98b6cab", "detected_licenses": [ "MIT" ], "directory_id": "c53069a9b35f1bb7459d9e23eacc4dd646206c62", "extension": "c", "filename": "jamjtag.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 129426904, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 35006, "license": "MIT", "license_type": "permissive", "path": "/libs/libz80board/src/jam_player/jamjtag.c", "provenance": "stackv2-0033.json.gz:157717", "repo_name": "lightemittingresistor/z80-board-utilities", "revision_date": "2019-09-22T12:27:32", "revision_id": "214a10390e276b178ab4763091e4a4380f3153a4", "snapshot_id": "66b01b985703065b8e9b0a293a8ba4a7e7ab9d8d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lightemittingresistor/z80-board-utilities/214a10390e276b178ab4763091e4a4380f3153a4/libs/libz80board/src/jam_player/jamjtag.c", "visit_date": "2020-03-10T14:27:37.521285" }
stackv2
/****************************************************************************/ /* */ /* Module: jamjtag.c */ /* */ /* Copyright (C) Altera Corporation 1997 */ /* */ /* Description: Contains array management functions, including */ /* functions for reading array initialization data in */ /* compressed formats. */ /* */ /* Revisions: 2.2 updated state transition paths */ /* 2.0 added multi-page scan code for 16-bit PORT */ /* 1.1 allow WAIT USECS without using JTAG hardware if */ /* JTAG hardware has not yet been initialized -- this is */ /* needed to create delays in VECTOR (non-JTAG) programs */ /* */ /****************************************************************************/ #include "jamexprt.h" #include "jamdefs.h" #include "jamsym.h" #include "jamstack.h" #include "jamutil.h" #include "jamjtag.h" /* * Global variable to store the current JTAG state */ JAME_JTAG_STATE jam_jtag_state = JAM_ILLEGAL_JTAG_STATE; /* * Store current stop-state for DR and IR scan commands */ JAME_JTAG_STATE jam_drstop_state = IDLE; JAME_JTAG_STATE jam_irstop_state = IDLE; /* * Store current padding values */ int jam_dr_preamble = 0; int jam_dr_postamble = 0; int jam_ir_preamble = 0; int jam_ir_postamble = 0; int jam_dr_length = 0; int jam_ir_length = 0; int *jam_dr_preamble_data = NULL; int *jam_dr_postamble_data = NULL; int *jam_ir_preamble_data = NULL; int *jam_ir_postamble_data = NULL; char *jam_dr_buffer = NULL; char *jam_ir_buffer = NULL; /* * Table of JTAG state names */ struct JAMS_JTAG_MAP { JAME_JTAG_STATE state; char string[JAMC_MAX_JTAG_STATE_LENGTH + 1]; } jam_jtag_state_table[] = { { RESET, "RESET" }, { IDLE, "IDLE" }, { DRSELECT, "DRSELECT" }, { DRCAPTURE, "DRCAPTURE" }, { DRSHIFT, "DRSHIFT" }, { DREXIT1, "DREXIT1" }, { DRPAUSE, "DRPAUSE" }, { DREXIT2, "DREXIT2" }, { DRUPDATE, "DRUPDATE" }, { IRSELECT, "IRSELECT" }, { IRCAPTURE, "IRCAPTURE" }, { IRSHIFT, "IRSHIFT" }, { IREXIT1, "IREXIT1" }, { IRPAUSE, "IRPAUSE" }, { IREXIT2, "IREXIT2" }, { IRUPDATE, "IRUPDATE" } }; #define JAMC_JTAG_STATE_COUNT \ (sizeof(jam_jtag_state_table) / sizeof(jam_jtag_state_table[0])) /* * This structure shows, for each JTAG state, which state is reached after * a single TCK clock cycle with TMS high or TMS low, respectively. This * describes all possible state transitions in the JTAG state machine. */ struct JAMS_JTAG_MACHINE { JAME_JTAG_STATE tms_high; JAME_JTAG_STATE tms_low; } jam_jtag_state_transitions[] = { /* RESET */ { RESET, IDLE }, /* IDLE */ { DRSELECT, IDLE }, /* DRSELECT */ { IRSELECT, DRCAPTURE }, /* DRCAPTURE */ { DREXIT1, DRSHIFT }, /* DRSHIFT */ { DREXIT1, DRSHIFT }, /* DREXIT1 */ { DRUPDATE, DRPAUSE }, /* DRPAUSE */ { DREXIT2, DRPAUSE }, /* DREXIT2 */ { DRUPDATE, DRSHIFT }, /* DRUPDATE */ { DRSELECT, IDLE }, /* IRSELECT */ { RESET, IRCAPTURE }, /* IRCAPTURE */ { IREXIT1, IRSHIFT }, /* IRSHIFT */ { IREXIT1, IRSHIFT }, /* IREXIT1 */ { IRUPDATE, IRPAUSE }, /* IRPAUSE */ { IREXIT2, IRPAUSE }, /* IREXIT2 */ { IRUPDATE, IRSHIFT }, /* IRUPDATE */ { DRSELECT, IDLE } }; /* * This table contains the TMS value to be used to take the NEXT STEP on * the path to the desired state. The array index is the current state, * and the bit position is the desired endstate. To find out which state * is used as the intermediate state, look up the TMS value in the * jam_jtag_state_transitions[] table. */ unsigned short jam_jtag_path_map[16] = { /* RST RTI SDRS CDR SDR E1DR PDR E2DR */ 0x0001, 0xFFFD, 0xFE01, 0xFFE7, 0xFFEF, 0xFF0F, 0xFFBF, 0xFFFF, /* UDR SIRS CIR SIR E1IR PIR E2IR UIR */ 0xFEFD, 0x0001, 0xF3FF, 0xF7FF, 0x87FF, 0xDFFF, 0xFFFF, 0x7FFD }; /* * Flag bits for jam_jtag_io() function */ #define TMS_HIGH 1 #define TMS_LOW 0 #define TDI_HIGH 1 #define TDI_LOW 0 #define READ_TDO 1 #define IGNORE_TDO 0 /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_init_jtag(void) /* */ /****************************************************************************/ { void **symbol_table = NULL; JAMS_STACK_RECORD *stack = NULL; /* initial JTAG state is unknown */ jam_jtag_state = JAM_ILLEGAL_JTAG_STATE; /* initialize global variables to default state */ jam_drstop_state = IDLE; jam_irstop_state = IDLE; jam_dr_preamble = 0; jam_dr_postamble = 0; jam_ir_preamble = 0; jam_ir_postamble = 0; jam_dr_length = 0; jam_ir_length = 0; if (jam_workspace != NULL) { symbol_table = (void **) jam_workspace; stack = (JAMS_STACK_RECORD *) &symbol_table[JAMC_MAX_SYMBOL_COUNT]; jam_dr_preamble_data = (int *) &stack[JAMC_MAX_NESTING_DEPTH]; jam_dr_postamble_data = &jam_dr_preamble_data[JAMC_MAX_JTAG_DR_PREAMBLE / 32]; jam_ir_preamble_data = &jam_dr_postamble_data[JAMC_MAX_JTAG_DR_POSTAMBLE / 32]; jam_ir_postamble_data = &jam_ir_preamble_data[JAMC_MAX_JTAG_IR_PREAMBLE / 32]; jam_dr_buffer = (char * )&jam_ir_postamble_data[JAMC_MAX_JTAG_IR_POSTAMBLE / 32]; jam_ir_buffer = &jam_dr_buffer[JAMC_MAX_JTAG_DR_LENGTH / 8]; } else { jam_dr_preamble_data = NULL; jam_dr_postamble_data = NULL; jam_ir_preamble_data = NULL; jam_ir_postamble_data = NULL; jam_dr_buffer = NULL; jam_ir_buffer = NULL; } return (JAMC_SUCCESS); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_set_drstop_state ( JAME_JTAG_STATE state ) /* */ /****************************************************************************/ { jam_drstop_state = state; return (JAMC_SUCCESS); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_set_irstop_state ( JAME_JTAG_STATE state ) /* */ /****************************************************************************/ { jam_irstop_state = state; return (JAMC_SUCCESS); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_set_dr_preamble ( int count, int start_index, int *data ) /* */ /****************************************************************************/ { JAM_RETURN_TYPE status = JAMC_SUCCESS; int alloc_longs = 0; int i = 0; int bit = 0; if (count >= 0) { if (jam_workspace != NULL) { if (count > JAMC_MAX_JTAG_DR_PREAMBLE) { status = JAMC_OUT_OF_MEMORY; } else { jam_dr_preamble = count; } } else { if (count > jam_dr_preamble) { alloc_longs = (count + 31) >> 5; jam_free(jam_dr_preamble_data); jam_dr_preamble_data = (int *) jam_malloc( alloc_longs * sizeof(int)); if (jam_dr_preamble_data == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_dr_preamble = count; } } else { jam_dr_preamble = count; } } if (status == JAMC_SUCCESS) { for (i = 0; i < count; ++i) { bit = i + start_index; if (data == NULL) { jam_dr_preamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { if (data[bit >> 5] & (1L << (bit & 0x1f))) { jam_dr_preamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { jam_dr_preamble_data[i >> 5] &= ~(unsigned long) (1L << (bit & 0x1f)); } } } } } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_set_ir_preamble ( int count, int start_index, int *data ) /* */ /****************************************************************************/ { JAM_RETURN_TYPE status = JAMC_SUCCESS; int alloc_longs = 0; int i = 0; int bit = 0; if (count >= 0) { if (jam_workspace != NULL) { if (count > JAMC_MAX_JTAG_IR_PREAMBLE) { status = JAMC_OUT_OF_MEMORY; } else { jam_ir_preamble = count; } } else { if (count > jam_ir_preamble) { alloc_longs = (count + 31) >> 5; jam_free(jam_ir_preamble_data); jam_ir_preamble_data = (int *) jam_malloc( alloc_longs * sizeof(int)); if (jam_ir_preamble_data == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_ir_preamble = count; } } else { jam_ir_preamble = count; } } if (status == JAMC_SUCCESS) { for (i = 0; i < count; ++i) { bit = i + start_index; if (data == NULL) { jam_ir_preamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { if (data[bit >> 5] & (1L << (bit & 0x1f))) { jam_ir_preamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { jam_ir_preamble_data[i >> 5] &= ~(unsigned long) (1L << (bit & 0x1f)); } } } } } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_set_dr_postamble ( int count, int start_index, int *data ) /* */ /****************************************************************************/ { JAM_RETURN_TYPE status = JAMC_SUCCESS; int alloc_longs = 0; int i = 0; int bit = 0; if (count >= 0) { if (jam_workspace != NULL) { if (count > JAMC_MAX_JTAG_DR_POSTAMBLE) { status = JAMC_OUT_OF_MEMORY; } else { jam_dr_postamble = count; } } else { if (count > jam_dr_postamble) { alloc_longs = (count + 31) >> 5; jam_free(jam_dr_postamble_data); jam_dr_postamble_data = (int *) jam_malloc( alloc_longs * sizeof(int)); if (jam_dr_postamble_data == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_dr_postamble = count; } } else { jam_dr_postamble = count; } } if (status == JAMC_SUCCESS) { for (i = 0; i < count; ++i) { bit = i + start_index; if (data == NULL) { jam_dr_postamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { if (data[bit >> 5] & (1L << (bit & 0x1f))) { jam_dr_postamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { jam_dr_postamble_data[i >> 5] &= ~(unsigned long) (1L << (bit & 0x1f)); } } } } } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_set_ir_postamble ( int count, int start_index, int *data ) /* */ /****************************************************************************/ { JAM_RETURN_TYPE status = JAMC_SUCCESS; int alloc_longs = 0; int i = 0; int bit = 0; if (count >= 0) { if (jam_workspace != NULL) { if (count > JAMC_MAX_JTAG_IR_POSTAMBLE) { status = JAMC_OUT_OF_MEMORY; } else { jam_ir_postamble = count; } } else { if (count > jam_ir_postamble) { alloc_longs = (count + 31) >> 5; jam_free(jam_ir_postamble_data); jam_ir_postamble_data = (int *) jam_malloc( alloc_longs * sizeof(int)); if (jam_ir_postamble_data == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_ir_postamble = count; } } else { jam_ir_postamble = count; } } if (status == JAMC_SUCCESS) { for (i = 0; i < count; ++i) { bit = i + start_index; if (data == NULL) { jam_ir_postamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { if (data[bit >> 5] & (1L << (bit & 0x1f))) { jam_ir_postamble_data[i >> 5] |= (1L << (bit & 0x1f)); } else { jam_ir_postamble_data[i >> 5] &= ~(unsigned long) (1L << (bit & 0x1f)); } } } } } return (status); } /****************************************************************************/ /* */ void jam_jtag_reset_idle(void) /* */ /****************************************************************************/ { int i = 0; /* * Go to Test Logic Reset (no matter what the starting state may be) */ for (i = 0; i < 5; ++i) { jam_jtag_io(TMS_HIGH, TDI_LOW, IGNORE_TDO); } /* * Now step to Run Test / Idle */ jam_jtag_io(TMS_LOW, TDI_LOW, IGNORE_TDO); jam_jtag_state = IDLE; } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_goto_jtag_state ( JAME_JTAG_STATE state ) /* */ /****************************************************************************/ { int tms = 0; int count = 0; JAM_RETURN_TYPE status = JAMC_SUCCESS; if (jam_jtag_state == JAM_ILLEGAL_JTAG_STATE) { /* initialize JTAG chain to known state */ jam_jtag_reset_idle(); } if (jam_jtag_state == state) { /* * We are already in the desired state. If it is a stable state, * loop here. Otherwise do nothing (no clock cycles). */ if ((state == IDLE) || (state == DRSHIFT) || (state == DRPAUSE) || (state == IRSHIFT) || (state == IRPAUSE)) { jam_jtag_io(TMS_LOW, TDI_LOW, IGNORE_TDO); } else if (state == RESET) { jam_jtag_io(TMS_HIGH, TDI_LOW, IGNORE_TDO); } } else { while ((jam_jtag_state != state) && (count < 9)) { /* * Get TMS value to take a step toward desired state */ tms = (jam_jtag_path_map[jam_jtag_state] & (1 << state)) ? TMS_HIGH : TMS_LOW; /* * Take a step */ jam_jtag_io(tms, TDI_LOW, IGNORE_TDO); if (tms) { jam_jtag_state = jam_jtag_state_transitions[jam_jtag_state].tms_high; } else { jam_jtag_state = jam_jtag_state_transitions[jam_jtag_state].tms_low; } ++count; } } if (jam_jtag_state != state) { status = JAMC_INTERNAL_ERROR; } return (status); } /****************************************************************************/ /* */ JAME_JTAG_STATE jam_get_jtag_state_from_name ( char *name ) /* */ /* Description: Finds JTAG state code corresponding to name of state */ /* supplied as a string */ /* */ /* Returns: JTAG state code, or JAM_ILLEGAL_JTAG_STATE if string */ /* does not match any valid state name */ /* */ /****************************************************************************/ { int i = 0; JAME_JTAG_STATE jtag_state = JAM_ILLEGAL_JTAG_STATE; for (i = 0; (jtag_state == JAM_ILLEGAL_JTAG_STATE) && (i < (int) JAMC_JTAG_STATE_COUNT); ++i) { if (jam_strcmp(name, jam_jtag_state_table[i].string) == 0) { jtag_state = jam_jtag_state_table[i].state; } } return (jtag_state); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_do_wait_cycles ( long cycles, JAME_JTAG_STATE wait_state ) /* */ /* Description: Causes JTAG hardware to loop in the specified stable */ /* state for the specified number of TCK clock cycles. */ /* */ /* Returns: JAMC_SUCCESS for success, else appropriate error code */ /* */ /****************************************************************************/ { int tms = 0; long count = 0L; JAM_RETURN_TYPE status = JAMC_SUCCESS; if (jam_jtag_state != wait_state) { status = jam_goto_jtag_state(wait_state); } if (status == JAMC_SUCCESS) { /* * Set TMS high to loop in RESET state * Set TMS low to loop in any other stable state */ tms = (wait_state == RESET) ? TMS_HIGH : TMS_LOW; for (count = 0L; count < cycles; count++) { jam_jtag_io(tms, TDI_LOW, IGNORE_TDO); } } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_do_wait_microseconds ( long microseconds, JAME_JTAG_STATE wait_state ) /* */ /* Description: Causes JTAG hardware to sit in the specified stable */ /* state for the specified duration of real time. If */ /* no JTAG operations have been performed yet, then only */ /* a delay is performed. This permits the WAIT USECS */ /* statement to be used in VECTOR programs without causing */ /* any JTAG operations. */ /* */ /* Returns: JAMC_SUCCESS for success, else appropriate error code */ /* */ /****************************************************************************/ { JAM_RETURN_TYPE status = JAMC_SUCCESS; if ((jam_jtag_state != JAM_ILLEGAL_JTAG_STATE) && (jam_jtag_state != wait_state)) { status = jam_goto_jtag_state(wait_state); } if (status == JAMC_SUCCESS) { /* * Wait for specified time interval */ jam_delay(microseconds); } return (status); } /****************************************************************************/ /* */ void jam_jtag_concatenate_data ( char *buffer, int *preamble_data, long preamble_count, int *target_data, long start_index, long target_count, int *postamble_data, long postamble_count ) /* */ /* Description: Copies preamble data, target data, and postamble data */ /* into one buffer for IR or DR scans. Note that buffer */ /* is an array of char, while other arrays are of long */ /* */ /* Returns: nothing */ /* */ /****************************************************************************/ { long i = 0L; long j = 0L; long k = 0L; for (i = 0L; i < preamble_count; ++i) { if (preamble_data[i >> 5] & (1L << (i & 0x1f))) { buffer[i >> 3] |= (1 << (i & 7)); } else { buffer[i >> 3] &= ~(unsigned int) (1 << (i & 7)); } } j = start_index; k = preamble_count + target_count; for (; i < k; ++i, ++j) { if (target_data[j >> 5] & (1L << (j & 0x1f))) { buffer[i >> 3] |= (1 << (i & 7)); } else { buffer[i >> 3] &= ~(unsigned int) (1 << (i & 7)); } } j = 0L; k = preamble_count + target_count + postamble_count; for (; i < k; ++i, ++j) { if (postamble_data[j >> 5] & (1L << (j & 0x1f))) { buffer[i >> 3] |= (1 << (i & 7)); } else { buffer[i >> 3] &= ~(unsigned int) (1 << (i & 7)); } } } /****************************************************************************/ /* */ void jam_jtag_extract_target_data ( char *buffer, int *target_data, long start_index, long preamble_count, long target_count ) /* */ /* Description: Copies target data from scan buffer, filtering out */ /* preamble and postamble data. Note that buffer is an */ /* array of char, while target_data is an array of long */ /* */ /* Returns: nothing */ /* */ /****************************************************************************/ { int i = 0L; int j = 0L; int k = 0L; j = preamble_count; k = start_index + target_count; for (i = start_index; i < k; ++i, ++j) { if (buffer[j >> 3] & (1 << (j & 7))) { target_data[i >> 5] |= (1L << (i & 0x1f)); } else { target_data[i >> 5] &= ~(unsigned int) (1L << (i & 0x1f)); } } } int jam_jtag_drscan ( int start_state, int count, char *tdi, char *tdo ) { int i = 0; int tdo_bit = 0; int status = 1; /* * First go to DRSHIFT state */ switch (start_state) { case 0: /* IDLE */ jam_jtag_io(1, 0, 0); /* DRSELECT */ jam_jtag_io(0, 0, 0); /* DRCAPTURE */ jam_jtag_io(0, 0, 0); /* DRSHIFT */ break; case 1: /* DRPAUSE */ jam_jtag_io(1, 0, 0); /* DREXIT2 */ jam_jtag_io(1, 0, 0); /* DRUPDATE */ jam_jtag_io(1, 0, 0); /* DRSELECT */ jam_jtag_io(0, 0, 0); /* DRCAPTURE */ jam_jtag_io(0, 0, 0); /* DRSHIFT */ break; case 2: /* IRPAUSE */ jam_jtag_io(1, 0, 0); /* IREXIT2 */ jam_jtag_io(1, 0, 0); /* IRUPDATE */ jam_jtag_io(1, 0, 0); /* DRSELECT */ jam_jtag_io(0, 0, 0); /* DRCAPTURE */ jam_jtag_io(0, 0, 0); /* DRSHIFT */ break; default: status = 0; } if (status) { /* loop in the SHIFT-DR state */ for (i = 0; i < count; i++) { tdo_bit = jam_jtag_io( (i == count - 1), tdi[i >> 3] & (1 << (i & 7)), (tdo != NULL)); if (tdo != NULL) { if (tdo_bit) { tdo[i >> 3] |= (1 << (i & 7)); } else { tdo[i >> 3] &= ~(unsigned int) (1 << (i & 7)); } } } jam_jtag_io(0, 0, 0); /* DRPAUSE */ } return (status); } int jam_jtag_irscan ( int start_state, int count, char *tdi, char *tdo ) { int i = 0; int tdo_bit = 0; int status = 1; /* * First go to IRSHIFT state */ switch (start_state) { case 0: /* IDLE */ jam_jtag_io(1, 0, 0); /* DRSELECT */ jam_jtag_io(1, 0, 0); /* IRSELECT */ jam_jtag_io(0, 0, 0); /* IRCAPTURE */ jam_jtag_io(0, 0, 0); /* IRSHIFT */ break; case 1: /* DRPAUSE */ jam_jtag_io(1, 0, 0); /* DREXIT2 */ jam_jtag_io(1, 0, 0); /* DRUPDATE */ jam_jtag_io(1, 0, 0); /* DRSELECT */ jam_jtag_io(1, 0, 0); /* IRSELECT */ jam_jtag_io(0, 0, 0); /* IRCAPTURE */ jam_jtag_io(0, 0, 0); /* IRSHIFT */ break; case 2: /* IRPAUSE */ jam_jtag_io(1, 0, 0); /* IREXIT2 */ jam_jtag_io(0, 0, 0); /* IRSHIFT */ break; default: status = 0; } if (status) { /* loop in the SHIFT-IR state */ for (i = 0; i < count; i++) { tdo_bit = jam_jtag_io( (i == count - 1), tdi[i >> 3] & (1 << (i & 7)), (tdo != NULL)); if (tdo != NULL) { if (tdo_bit) { tdo[i >> 3] |= (1 << (i & 7)); } else { tdo[i >> 3] &= ~(unsigned int) (1 << (i & 7)); } } } jam_jtag_io(0, 0, 0); /* IRPAUSE */ } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_do_irscan ( long count, int *data, long start_index ) /* */ /* Description: Shifts data into instruction register */ /* */ /* Returns: JAMC_SUCCESS for success, else appropriate error code */ /* */ /****************************************************************************/ { int start_code = 0; int alloc_chars = 0; int shift_count = (int) (jam_ir_preamble + count + jam_ir_postamble); JAM_RETURN_TYPE status = JAMC_SUCCESS; JAME_JTAG_STATE start_state = JAM_ILLEGAL_JTAG_STATE; switch (jam_jtag_state) { case JAM_ILLEGAL_JTAG_STATE: case RESET: case IDLE: start_code = 0; start_state = IDLE; break; case DRSELECT: case DRCAPTURE: case DRSHIFT: case DREXIT1: case DRPAUSE: case DREXIT2: case DRUPDATE: start_code = 1; start_state = DRPAUSE; break; case IRSELECT: case IRCAPTURE: case IRSHIFT: case IREXIT1: case IRPAUSE: case IREXIT2: case IRUPDATE: start_code = 2; start_state = IRPAUSE; break; default: status = JAMC_INTERNAL_ERROR; break; } if (status == JAMC_SUCCESS) { if (jam_jtag_state != start_state) { status = jam_goto_jtag_state(start_state); } } if (status == JAMC_SUCCESS) { if (jam_workspace != NULL) { if (shift_count > JAMC_MAX_JTAG_IR_LENGTH) { status = JAMC_OUT_OF_MEMORY; } } else if (shift_count > jam_ir_length) { alloc_chars = (shift_count + 7) >> 3; jam_free(jam_ir_buffer); jam_ir_buffer = (char *) jam_malloc(alloc_chars); if (jam_ir_buffer == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_ir_length = alloc_chars * 8; } } } if (status == JAMC_SUCCESS) { /* * Copy preamble data, IR data, and postamble data into a buffer */ jam_jtag_concatenate_data ( jam_ir_buffer, jam_ir_preamble_data, jam_ir_preamble, data, start_index, count, jam_ir_postamble_data, jam_ir_postamble ); /* * Do the IRSCAN */ jam_jtag_irscan ( start_code, shift_count, jam_ir_buffer, NULL ); /* jam_jtag_irscan() always ends in IRPAUSE state */ jam_jtag_state = IRPAUSE; } if (status == JAMC_SUCCESS) { if (jam_irstop_state != IRPAUSE) { status = jam_goto_jtag_state(jam_irstop_state); } } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_swap_ir ( long count, int *in_data, long in_index, int *out_data, long out_index ) /* */ /* Description: Shifts data into instruction register, capturing output */ /* data */ /* */ /* Returns: JAMC_SUCCESS for success, else appropriate error code */ /* */ /****************************************************************************/ { int start_code = 0; int alloc_chars = 0; int shift_count = (int) (jam_ir_preamble + count + jam_ir_postamble); JAM_RETURN_TYPE status = JAMC_SUCCESS; JAME_JTAG_STATE start_state = JAM_ILLEGAL_JTAG_STATE; switch (jam_jtag_state) { case JAM_ILLEGAL_JTAG_STATE: case RESET: case IDLE: start_code = 0; start_state = IDLE; break; case DRSELECT: case DRCAPTURE: case DRSHIFT: case DREXIT1: case DRPAUSE: case DREXIT2: case DRUPDATE: start_code = 1; start_state = DRPAUSE; break; case IRSELECT: case IRCAPTURE: case IRSHIFT: case IREXIT1: case IRPAUSE: case IREXIT2: case IRUPDATE: start_code = 2; start_state = IRPAUSE; break; default: status = JAMC_INTERNAL_ERROR; break; } if (status == JAMC_SUCCESS) { if (jam_jtag_state != start_state) { status = jam_goto_jtag_state(start_state); } } if (status == JAMC_SUCCESS) { if (jam_workspace != NULL) { if (shift_count > JAMC_MAX_JTAG_IR_LENGTH) { status = JAMC_OUT_OF_MEMORY; } } else if (shift_count > jam_ir_length) { alloc_chars = (shift_count + 7) >> 3; jam_free(jam_ir_buffer); jam_ir_buffer = (char *) jam_malloc(alloc_chars); if (jam_ir_buffer == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_ir_length = alloc_chars * 8; } } } if (status == JAMC_SUCCESS) { /* * Copy preamble data, IR data, and postamble data into a buffer */ jam_jtag_concatenate_data ( jam_ir_buffer, jam_ir_preamble_data, jam_ir_preamble, in_data, in_index, count, jam_ir_postamble_data, jam_ir_postamble ); /* * Do the IRSCAN */ jam_jtag_irscan ( start_code, shift_count, jam_ir_buffer, jam_ir_buffer ); /* jam_jtag_irscan() always ends in IRPAUSE state */ jam_jtag_state = IRPAUSE; } if (status == JAMC_SUCCESS) { if (jam_irstop_state != IRPAUSE) { status = jam_goto_jtag_state(jam_irstop_state); } } if (status == JAMC_SUCCESS) { /* * Now extract the returned data from the buffer */ jam_jtag_extract_target_data ( jam_ir_buffer, out_data, out_index, jam_ir_preamble, count ); } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_do_drscan ( long count, int *data, long start_index ) /* */ /* Description: Shifts data into data register (ignoring output data) */ /* */ /* Returns: JAMC_SUCCESS for success, else appropriate error code */ /* */ /****************************************************************************/ { int start_code = 0; int alloc_chars = 0; int shift_count = (int) (jam_dr_preamble + count + jam_dr_postamble); JAM_RETURN_TYPE status = JAMC_SUCCESS; JAME_JTAG_STATE start_state = JAM_ILLEGAL_JTAG_STATE; switch (jam_jtag_state) { case JAM_ILLEGAL_JTAG_STATE: case RESET: case IDLE: start_code = 0; start_state = IDLE; break; case DRSELECT: case DRCAPTURE: case DRSHIFT: case DREXIT1: case DRPAUSE: case DREXIT2: case DRUPDATE: start_code = 1; start_state = DRPAUSE; break; case IRSELECT: case IRCAPTURE: case IRSHIFT: case IREXIT1: case IRPAUSE: case IREXIT2: case IRUPDATE: start_code = 2; start_state = IRPAUSE; break; default: status = JAMC_INTERNAL_ERROR; break; } if (status == JAMC_SUCCESS) { if (jam_jtag_state != start_state) { status = jam_goto_jtag_state(start_state); } } if (status == JAMC_SUCCESS) { if (jam_workspace != NULL) { if (shift_count > JAMC_MAX_JTAG_DR_LENGTH) { status = JAMC_OUT_OF_MEMORY; } } else if (shift_count > jam_dr_length) { alloc_chars = (shift_count + 7) >> 3; jam_free(jam_dr_buffer); jam_dr_buffer = (char *) jam_malloc(alloc_chars); if (jam_dr_buffer == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_dr_length = alloc_chars * 8; } } } if (status == JAMC_SUCCESS) { /* * Copy preamble data, DR data, and postamble data into a buffer */ jam_jtag_concatenate_data ( jam_dr_buffer, jam_dr_preamble_data, jam_dr_preamble, data, start_index, count, jam_dr_postamble_data, jam_dr_postamble ); /* * Do the DRSCAN */ jam_jtag_drscan ( start_code, shift_count, jam_dr_buffer, NULL ); /* jam_jtag_drscan() always ends in DRPAUSE state */ jam_jtag_state = DRPAUSE; } if (status == JAMC_SUCCESS) { if (jam_drstop_state != DRPAUSE) { status = jam_goto_jtag_state(jam_drstop_state); } } return (status); } /****************************************************************************/ /* */ JAM_RETURN_TYPE jam_swap_dr ( long count, int *in_data, long in_index, int *out_data, long out_index ) /* */ /* Description: Shifts data into data register, capturing output data */ /* */ /* Returns: JAMC_SUCCESS for success, else appropriate error code */ /* */ /****************************************************************************/ { int start_code = 0; int alloc_chars = 0; int shift_count = (int) (jam_dr_preamble + count + jam_dr_postamble); JAM_RETURN_TYPE status = JAMC_SUCCESS; JAME_JTAG_STATE start_state = JAM_ILLEGAL_JTAG_STATE; switch (jam_jtag_state) { case JAM_ILLEGAL_JTAG_STATE: case RESET: case IDLE: start_code = 0; start_state = IDLE; break; case DRSELECT: case DRCAPTURE: case DRSHIFT: case DREXIT1: case DRPAUSE: case DREXIT2: case DRUPDATE: start_code = 1; start_state = DRPAUSE; break; case IRSELECT: case IRCAPTURE: case IRSHIFT: case IREXIT1: case IRPAUSE: case IREXIT2: case IRUPDATE: start_code = 2; start_state = IRPAUSE; break; default: status = JAMC_INTERNAL_ERROR; break; } if (status == JAMC_SUCCESS) { if (jam_jtag_state != start_state) { status = jam_goto_jtag_state(start_state); } } if (status == JAMC_SUCCESS) { if (jam_workspace != NULL) { if (shift_count > JAMC_MAX_JTAG_DR_LENGTH) { status = JAMC_OUT_OF_MEMORY; } } else if (shift_count > jam_dr_length) { alloc_chars = (shift_count + 7) >> 3; jam_free(jam_dr_buffer); jam_dr_buffer = (char *) jam_malloc(alloc_chars); if (jam_dr_buffer == NULL) { status = JAMC_OUT_OF_MEMORY; } else { jam_dr_length = alloc_chars * 8; } } } if (status == JAMC_SUCCESS) { /* * Copy preamble data, DR data, and postamble data into a buffer */ jam_jtag_concatenate_data ( jam_dr_buffer, jam_dr_preamble_data, jam_dr_preamble, in_data, in_index, count, jam_dr_postamble_data, jam_dr_postamble ); /* * Do the DRSCAN */ jam_jtag_drscan ( start_code, shift_count, jam_dr_buffer, jam_dr_buffer ); /* jam_jtag_drscan() always ends in DRPAUSE state */ jam_jtag_state = DRPAUSE; } if (status == JAMC_SUCCESS) { if (jam_drstop_state != DRPAUSE) { status = jam_goto_jtag_state(jam_drstop_state); } } if (status == JAMC_SUCCESS) { /* * Now extract the returned data from the buffer */ jam_jtag_extract_target_data ( jam_dr_buffer, out_data, out_index, jam_dr_preamble, count ); } return (status); } /****************************************************************************/ /* */ void jam_free_jtag_padding_buffers(int reset_jtag) /* */ /* Description: Frees memory allocated for JTAG IR and DR buffers */ /* */ /* Returns: nothing */ /* */ /****************************************************************************/ { /* * If the JTAG interface was used, reset it to TLR */ if (reset_jtag && (jam_jtag_state != JAM_ILLEGAL_JTAG_STATE)) { jam_jtag_reset_idle(); } if (jam_workspace == NULL) { if (jam_dr_preamble_data != NULL) { jam_free(jam_dr_preamble_data); jam_dr_preamble_data = NULL; } if (jam_dr_postamble_data != NULL) { jam_free(jam_dr_postamble_data); jam_dr_postamble_data = NULL; } if (jam_dr_buffer != NULL) { jam_free(jam_dr_buffer); jam_dr_buffer = NULL; } if (jam_ir_preamble_data != NULL) { jam_free(jam_ir_preamble_data); jam_ir_preamble_data = NULL; } if (jam_ir_postamble_data != NULL) { jam_free(jam_ir_postamble_data); jam_ir_postamble_data = NULL; } if (jam_ir_buffer != NULL) { jam_free(jam_ir_buffer); jam_ir_buffer = NULL; } } }
2.109375
2
2024-11-18T20:15:11.900539+00:00
2018-06-13T16:20:23
c0106f2367264ae493495b5e705d892a856ee417
{ "blob_id": "c0106f2367264ae493495b5e705d892a856ee417", "branch_name": "refs/heads/master", "committer_date": "2018-06-13T16:20:23", "content_id": "4106b60e842731ac39c0b28a10ea70e3c410ddf1", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "6b84d7ef75086a7106e2a9e61ed9b5c26987fcea", "extension": "c", "filename": "decodeDX9.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 137236339, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 36525, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/Code/!external/HBAOPlus/build/tools/HLSLcc/May_2014/src/decodeDX9.c", "provenance": "stackv2-0033.json.gz:158103", "repo_name": "astralis3d/DX11Framework", "revision_date": "2018-06-13T16:20:23", "revision_id": "002c7fb2fd9e50a4ced416fbed169c09b0659650", "snapshot_id": "e53cacaebe09266f6321dd62d1015a9c60accdf3", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/astralis3d/DX11Framework/002c7fb2fd9e50a4ced416fbed169c09b0659650/Code/!external/HBAOPlus/build/tools/HLSLcc/May_2014/src/decodeDX9.c", "visit_date": "2020-03-20T06:02:59.863704" }
stackv2
#include "internal_includes/tokens.h" #include "internal_includes/structs.h" #include "internal_includes/decode.h" #include "stdlib.h" #include "stdio.h" #include "internal_includes/reflect.h" #include "internal_includes/debug.h" #include "internal_includes/hlslcc_malloc.h" #define FOURCC(a, b, c, d) ((uint32_t)(uint8_t)(a) | ((uint32_t)(uint8_t)(b) << 8) | ((uint32_t)(uint8_t)(c) << 16) | ((uint32_t)(uint8_t)(d) << 24 )) static enum {FOURCC_CTAB = FOURCC('C', 'T', 'A', 'B')}; //Constant table #ifdef _DEBUG static uint64_t operandID = 0; static uint64_t instructionID = 0; #endif static uint32_t aui32ImmediateConst[256]; static uint32_t ui32MaxTemp = 0; uint32_t DX9_DECODE_OPERAND_IS_SRC = 0x1; uint32_t DX9_DECODE_OPERAND_IS_DEST = 0x2; uint32_t DX9_DECODE_OPERAND_IS_DECL = 0x4; uint32_t DX9_DECODE_OPERAND_IS_CONST = 0x8; uint32_t DX9_DECODE_OPERAND_IS_ICONST = 0x10; uint32_t DX9_DECODE_OPERAND_IS_BCONST = 0x20; #define MAX_INPUTS 64 static DECLUSAGE_DX9 aeInputUsage[MAX_INPUTS]; static uint32_t aui32InputUsageIndex[MAX_INPUTS]; static void DecodeOperandDX9(const Shader* psShader, const uint32_t ui32Token, const uint32_t ui32Token1, uint32_t ui32Flags, Operand *psOperand) { const uint32_t ui32RegNum = DecodeOperandRegisterNumberDX9(ui32Token); const uint32_t ui32RegType = DecodeOperandTypeDX9(ui32Token); const uint32_t bRelativeAddr = DecodeOperandIsRelativeAddressModeDX9(ui32Token); const uint32_t ui32WriteMask = DecodeDestWriteMaskDX9(ui32Token); const uint32_t ui32Swizzle = DecodeOperandSwizzleDX9(ui32Token); SHADER_VARIABLE_TYPE ConstType; psOperand->ui32RegisterNumber = ui32RegNum; psOperand->iNumComponents = 4; #ifdef _DEBUG psOperand->id = operandID++; #endif psOperand->iWriteMaskEnabled = 0; psOperand->iGSInput = 0; psOperand->iExtended = 0; psOperand->psSubOperand[0] = 0; psOperand->psSubOperand[1] = 0; psOperand->psSubOperand[2] = 0; psOperand->iIndexDims = INDEX_0D; psOperand->iIntegerImmediate = 0; psOperand->pszSpecialName[0] ='\0'; psOperand->eModifier = OPERAND_MODIFIER_NONE; if(ui32Flags & DX9_DECODE_OPERAND_IS_SRC) { uint32_t ui32Modifier = DecodeSrcModifierDX9(ui32Token); switch(ui32Modifier) { case SRCMOD_DX9_NONE: { break; } case SRCMOD_DX9_NEG: { psOperand->eModifier = OPERAND_MODIFIER_NEG; break; } case SRCMOD_DX9_ABS: { psOperand->eModifier = OPERAND_MODIFIER_ABS; break; } case SRCMOD_DX9_ABSNEG: { psOperand->eModifier = OPERAND_MODIFIER_ABSNEG; break; } default: { ASSERT(0); break; } } } if((ui32Flags & DX9_DECODE_OPERAND_IS_DECL)==0) { if(ui32Flags & DX9_DECODE_OPERAND_IS_DEST) { if(ui32WriteMask != DX9_WRITEMASK_ALL) { psOperand->iWriteMaskEnabled = 1; psOperand->eSelMode = OPERAND_4_COMPONENT_MASK_MODE; if(ui32WriteMask & DX9_WRITEMASK_0) { psOperand->ui32CompMask |= OPERAND_4_COMPONENT_MASK_X; } if(ui32WriteMask & DX9_WRITEMASK_1) { psOperand->ui32CompMask |= OPERAND_4_COMPONENT_MASK_Y; } if(ui32WriteMask & DX9_WRITEMASK_2) { psOperand->ui32CompMask |= OPERAND_4_COMPONENT_MASK_Z; } if(ui32WriteMask & DX9_WRITEMASK_3) { psOperand->ui32CompMask |= OPERAND_4_COMPONENT_MASK_W; } } } else if(ui32Swizzle != NO_SWIZZLE_DX9) { uint32_t component; psOperand->iWriteMaskEnabled = 1; psOperand->eSelMode = OPERAND_4_COMPONENT_SWIZZLE_MODE; psOperand->ui32Swizzle = 1; /* Add the swizzle */ if(ui32Swizzle == REPLICATE_SWIZZLE_DX9(0)) { psOperand->eSelMode = OPERAND_4_COMPONENT_SELECT_1_MODE; psOperand->aui32Swizzle[0] = OPERAND_4_COMPONENT_X; } else if(ui32Swizzle == REPLICATE_SWIZZLE_DX9(1)) { psOperand->eSelMode = OPERAND_4_COMPONENT_SELECT_1_MODE; psOperand->aui32Swizzle[0] = OPERAND_4_COMPONENT_Y; } else if(ui32Swizzle == REPLICATE_SWIZZLE_DX9(2)) { psOperand->eSelMode = OPERAND_4_COMPONENT_SELECT_1_MODE; psOperand->aui32Swizzle[0] = OPERAND_4_COMPONENT_Z; } else if(ui32Swizzle == REPLICATE_SWIZZLE_DX9(3)) { psOperand->eSelMode = OPERAND_4_COMPONENT_SELECT_1_MODE; psOperand->aui32Swizzle[0] = OPERAND_4_COMPONENT_W; } else { for (component = 0; component < 4; component++) { uint32_t ui32CompSwiz = ui32Swizzle & (3 << (DX9_SWIZZLE_SHIFT+(component*2))); ui32CompSwiz >>= (DX9_SWIZZLE_SHIFT+(component*2)); if (ui32CompSwiz == 0) { psOperand->aui32Swizzle[component] = OPERAND_4_COMPONENT_X; } else if (ui32CompSwiz == 1) { psOperand->aui32Swizzle[component] = OPERAND_4_COMPONENT_Y; } else if (ui32CompSwiz == 2) { psOperand->aui32Swizzle[component] = OPERAND_4_COMPONENT_Z; } else { psOperand->aui32Swizzle[component] = OPERAND_4_COMPONENT_W; } } } } if(bRelativeAddr) { psOperand->psSubOperand[0] = hlslcc_malloc(sizeof(Operand)); DecodeOperandDX9(psShader, ui32Token1, 0, ui32Flags, psOperand->psSubOperand[0]); psOperand->iIndexDims = INDEX_1D; psOperand->eIndexRep[0] = OPERAND_INDEX_RELATIVE; psOperand->aui32ArraySizes[0] = 0; } } if(ui32RegType == OPERAND_TYPE_DX9_CONSTBOOL) { ui32Flags |= DX9_DECODE_OPERAND_IS_BCONST; ConstType = SVT_BOOL; } else if(ui32RegType == OPERAND_TYPE_DX9_CONSTINT) { ui32Flags |= DX9_DECODE_OPERAND_IS_ICONST; ConstType = SVT_INT; } else if(ui32RegType == OPERAND_TYPE_DX9_CONST) { ui32Flags |= DX9_DECODE_OPERAND_IS_CONST; ConstType = SVT_FLOAT; } switch(ui32RegType) { case OPERAND_TYPE_DX9_TEMP: { psOperand->eType = OPERAND_TYPE_TEMP; if(ui32MaxTemp < ui32RegNum+1) { ui32MaxTemp = ui32RegNum+1; } break; } case OPERAND_TYPE_DX9_INPUT: { psOperand->eType = OPERAND_TYPE_INPUT; ASSERT(ui32RegNum < MAX_INPUTS); if(psShader->eShaderType == PIXEL_SHADER) { if(aeInputUsage[ui32RegNum] == DECLUSAGE_TEXCOORD) { psOperand->eType = OPERAND_TYPE_SPECIAL_TEXCOORD; psOperand->ui32RegisterNumber = aui32InputUsageIndex[ui32RegNum]; } else //0 = base colour, 1 = offset colour. if(ui32RegNum == 0) { psOperand->eType = OPERAND_TYPE_SPECIAL_OUTBASECOLOUR; } else { ASSERT(ui32RegNum == 1); psOperand->eType = OPERAND_TYPE_SPECIAL_OUTOFFSETCOLOUR; } } break; } //Same value as OPERAND_TYPE_DX9_TEXCRDOUT //OPERAND_TYPE_DX9_TEXCRDOUT is the pre-SM3 equivalent case OPERAND_TYPE_DX9_OUTPUT: { psOperand->eType = OPERAND_TYPE_OUTPUT; if(psShader->eShaderType == VERTEX_SHADER) { psOperand->eType = OPERAND_TYPE_SPECIAL_TEXCOORD; } break; } case OPERAND_TYPE_DX9_RASTOUT: { //RegNum: //0=POSIION //1=FOG //2=POINTSIZE psOperand->eType = OPERAND_TYPE_OUTPUT; switch(ui32RegNum) { case 0: { psOperand->eType = OPERAND_TYPE_SPECIAL_POSITION; break; } case 1: { psOperand->eType = OPERAND_TYPE_SPECIAL_FOG; break; } case 2: { psOperand->eType = OPERAND_TYPE_SPECIAL_POINTSIZE; psOperand->iNumComponents = 1; break; } } break; } case OPERAND_TYPE_DX9_ATTROUT: { ASSERT(psShader->eShaderType == VERTEX_SHADER); psOperand->eType = OPERAND_TYPE_OUTPUT; //0 = base colour, 1 = offset colour. if(ui32RegNum == 0) { psOperand->eType = OPERAND_TYPE_SPECIAL_OUTBASECOLOUR; } else { ASSERT(ui32RegNum == 1); psOperand->eType = OPERAND_TYPE_SPECIAL_OUTOFFSETCOLOUR; } break; } case OPERAND_TYPE_DX9_COLOROUT: { ASSERT(psShader->eShaderType == PIXEL_SHADER); psOperand->eType = OPERAND_TYPE_OUTPUT; break; } case OPERAND_TYPE_DX9_CONSTBOOL: case OPERAND_TYPE_DX9_CONSTINT: case OPERAND_TYPE_DX9_CONST: { //c# = constant float //i# = constant int //b# = constant bool //c0 might be an immediate while i0 is in the constant buffer if(aui32ImmediateConst[ui32RegNum] & ui32Flags) { if(ConstType != SVT_FLOAT) { psOperand->eType = OPERAND_TYPE_SPECIAL_IMMCONSTINT; } else { psOperand->eType = OPERAND_TYPE_SPECIAL_IMMCONST; } } else { psOperand->eType = OPERAND_TYPE_CONSTANT_BUFFER; psOperand->aui32ArraySizes[1] = psOperand->ui32RegisterNumber; } break; } case OPERAND_TYPE_DX9_ADDR: { //Vertex shader: address register (only have one of these) //Pixel shader: texture coordinate register (a few of these) if(psShader->eShaderType == PIXEL_SHADER) { psOperand->eType = OPERAND_TYPE_SPECIAL_TEXCOORD; } else { psOperand->eType = OPERAND_TYPE_SPECIAL_ADDRESS; } break; } case OPERAND_TYPE_DX9_SAMPLER: { psOperand->eType = OPERAND_TYPE_RESOURCE; break; } case OPERAND_TYPE_DX9_LOOP: { psOperand->eType = OPERAND_TYPE_SPECIAL_LOOPCOUNTER; break; } default: { ASSERT(0); break; } } } static void DeclareNumTemps(Shader* psShader, const uint32_t ui32NumTemps, Declaration* psDecl) { psDecl->eOpcode = OPCODE_DCL_TEMPS; psDecl->value.ui32NumTemps = ui32NumTemps; } static void SetupRegisterUsage(const Shader* psShader, const uint32_t ui32Token0, const uint32_t ui32Token1) { DECLUSAGE_DX9 eUsage = DecodeUsageDX9(ui32Token0); uint32_t ui32UsageIndex = DecodeUsageIndexDX9(ui32Token0); uint32_t ui32RegNum = DecodeOperandRegisterNumberDX9(ui32Token1); uint32_t ui32RegType = DecodeOperandTypeDX9(ui32Token1); if(ui32RegType == OPERAND_TYPE_DX9_INPUT) { ASSERT(ui32RegNum < MAX_INPUTS); aeInputUsage[ui32RegNum] = eUsage; aui32InputUsageIndex[ui32RegNum] = ui32UsageIndex; } } //Declaring one constant from a constant buffer will cause all constants in the buffer decalared. //In dx9 there is only one constant buffer per shader. static void DeclareConstantBuffer(const Shader* psShader, Declaration* psDecl) { DECLUSAGE_DX9 eUsage = (DECLUSAGE_DX9)0; uint32_t ui32UsageIndex = 0; //Pick any constant register in the table. Might not start at c0 (e.g. when register(cX) is used). uint32_t ui32RegNum = psShader->sInfo.psConstantBuffers->asVars[0].ui32StartOffset / 16; OPERAND_TYPE_DX9 ui32RegType = OPERAND_TYPE_DX9_CONST; if(psShader->sInfo.psConstantBuffers->asVars[0].sType.Type == SVT_INT) { ui32RegType = OPERAND_TYPE_DX9_CONSTINT; } else if(psShader->sInfo.psConstantBuffers->asVars[0].sType.Type == SVT_BOOL) { ui32RegType = OPERAND_TYPE_DX9_CONSTBOOL; } if(psShader->eShaderType == VERTEX_SHADER) { psDecl->eOpcode = OPCODE_DCL_INPUT; } else { psDecl->eOpcode = OPCODE_DCL_INPUT_PS; } psDecl->ui32NumOperands = 1; DecodeOperandDX9(psShader, CreateOperandTokenDX9(ui32RegNum, ui32RegType), 0, DX9_DECODE_OPERAND_IS_DECL, &psDecl->asOperands[0]); ASSERT(psDecl->asOperands[0].eType == OPERAND_TYPE_CONSTANT_BUFFER); psDecl->eOpcode = OPCODE_DCL_CONSTANT_BUFFER; ASSERT(psShader->sInfo.ui32NumConstantBuffers); psDecl->asOperands[0].aui32ArraySizes[0] = 0;//Const buffer index psDecl->asOperands[0].aui32ArraySizes[1] = psShader->sInfo.psConstantBuffers[0].ui32TotalSizeInBytes / 16;//Number of vec4 constants. } static void DecodeDeclarationDX9(const Shader* psShader, const uint32_t ui32Token0, const uint32_t ui32Token1, Declaration* psDecl) { DECLUSAGE_DX9 eUsage = DecodeUsageDX9(ui32Token0); uint32_t ui32UsageIndex = DecodeUsageIndexDX9(ui32Token0); uint32_t ui32RegNum = DecodeOperandRegisterNumberDX9(ui32Token1); uint32_t ui32RegType = DecodeOperandTypeDX9(ui32Token1); if(psShader->eShaderType == VERTEX_SHADER) { psDecl->eOpcode = OPCODE_DCL_INPUT; } else { psDecl->eOpcode = OPCODE_DCL_INPUT_PS; } psDecl->ui32NumOperands = 1; DecodeOperandDX9(psShader, ui32Token1, 0, DX9_DECODE_OPERAND_IS_DECL, &psDecl->asOperands[0]); if(ui32RegType == OPERAND_TYPE_DX9_SAMPLER) { const RESOURCE_DIMENSION eResDim = DecodeTextureTypeMaskDX9(ui32Token0); psDecl->value.eResourceDimension = eResDim; psDecl->ui32IsShadowTex = 0; psDecl->eOpcode = OPCODE_DCL_RESOURCE; } if(psDecl->asOperands[0].eType == OPERAND_TYPE_OUTPUT) { psDecl->eOpcode = OPCODE_DCL_OUTPUT; if(psDecl->asOperands[0].ui32RegisterNumber==0 && psShader->eShaderType == VERTEX_SHADER) { psDecl->eOpcode = OPCODE_DCL_OUTPUT_SIV; //gl_Position psDecl->asOperands[0].eSpecialName = NAME_POSITION; } } else if(psDecl->asOperands[0].eType == OPERAND_TYPE_CONSTANT_BUFFER) { psDecl->eOpcode = OPCODE_DCL_CONSTANT_BUFFER; ASSERT(psShader->sInfo.ui32NumConstantBuffers); psDecl->asOperands[0].aui32ArraySizes[0] = 0;//Const buffer index psDecl->asOperands[0].aui32ArraySizes[1] = psShader->sInfo.psConstantBuffers[0].ui32TotalSizeInBytes / 16;//Number of vec4 constants. } } static void DefineDX9(Shader* psShader, const uint32_t ui32RegNum, const uint32_t ui32Flags, const uint32_t c0, const uint32_t c1, const uint32_t c2, const uint32_t c3, Declaration* psDecl) { psDecl->eOpcode = OPCODE_SPECIAL_DCL_IMMCONST; psDecl->ui32NumOperands = 2; memset(&psDecl->asOperands[0], 0, sizeof(Operand)); psDecl->asOperands[0].eType = OPERAND_TYPE_SPECIAL_IMMCONST; psDecl->asOperands[0].ui32RegisterNumber = ui32RegNum; if(ui32Flags & (DX9_DECODE_OPERAND_IS_ICONST|DX9_DECODE_OPERAND_IS_BCONST)) { psDecl->asOperands[0].eType = OPERAND_TYPE_SPECIAL_IMMCONSTINT; } aui32ImmediateConst[ui32RegNum] |= ui32Flags; memset(&psDecl->asOperands[1], 0, sizeof(Operand)); psDecl->asOperands[1].eType = OPERAND_TYPE_IMMEDIATE32; psDecl->asOperands[1].iNumComponents = 4; psDecl->asOperands[1].iIntegerImmediate = (ui32Flags & (DX9_DECODE_OPERAND_IS_ICONST|DX9_DECODE_OPERAND_IS_BCONST)) ? 1 : 0; psDecl->asOperands[1].afImmediates[0] = *((float*)&c0); psDecl->asOperands[1].afImmediates[1] = *((float*)&c1); psDecl->asOperands[1].afImmediates[2] = *((float*)&c2); psDecl->asOperands[1].afImmediates[3] = *((float*)&c3); } static void CreateD3D10Instruction( Shader* psShader, Instruction* psInst, const OPCODE_TYPE eType, const uint32_t bHasDest, const uint32_t ui32SrcCount, const uint32_t* pui32Tokens) { uint32_t ui32Src; uint32_t ui32Offset = 1; memset(psInst, 0, sizeof(Instruction)); #ifdef _DEBUG psInst->id = instructionID++; #endif psInst->eOpcode = eType; psInst->ui32NumOperands = ui32SrcCount; if(bHasDest) { ++psInst->ui32NumOperands; DecodeOperandDX9(psShader, pui32Tokens[ui32Offset], pui32Tokens[ui32Offset+1], DX9_DECODE_OPERAND_IS_DEST, &psInst->asOperands[0]); if(DecodeDestModifierDX9(pui32Tokens[ui32Offset]) & DESTMOD_DX9_SATURATE) { psInst->bSaturate = 1; } ui32Offset++; psInst->ui32FirstSrc = 1; } for(ui32Src=0; ui32Src < ui32SrcCount; ++ui32Src) { DecodeOperandDX9(psShader, pui32Tokens[ui32Offset], pui32Tokens[ui32Offset+1], DX9_DECODE_OPERAND_IS_SRC, &psInst->asOperands[bHasDest+ui32Src]); ui32Offset++; } } Shader* DecodeDX9BC(const uint32_t* pui32Tokens) { const uint32_t* pui32CurrentToken = pui32Tokens; uint32_t ui32NumInstructions = 0; uint32_t ui32NumDeclarations = 0; Instruction* psInst; Declaration* psDecl; uint32_t decl, inst; uint32_t bDeclareConstantTable = 0; Shader* psShader = hlslcc_calloc(1, sizeof(Shader)); memset(aui32ImmediateConst, 0, 256); psShader->ui32MajorVersion = DecodeProgramMajorVersionDX9(*pui32CurrentToken); psShader->ui32MinorVersion = DecodeProgramMinorVersionDX9(*pui32CurrentToken); psShader->eShaderType = DecodeShaderTypeDX9(*pui32CurrentToken); pui32CurrentToken++; //Work out how many instructions and declarations we need to allocate memory for. while (1) { OPCODE_TYPE_DX9 eOpcode = DecodeOpcodeTypeDX9(pui32CurrentToken[0]); uint32_t ui32InstLen = DecodeInstructionLengthDX9(pui32CurrentToken[0]); if(eOpcode == OPCODE_DX9_END) { //SM4+ always end with RET. //Insert a RET instruction on END to //replicate this behaviour. ++ui32NumInstructions; break; } else if(eOpcode == OPCODE_DX9_COMMENT) { ui32InstLen = DecodeCommentLengthDX9(pui32CurrentToken[0]); if(pui32CurrentToken[1] == FOURCC_CTAB) { LoadD3D9ConstantTable((char*)(&pui32CurrentToken[2]), &psShader->sInfo); ASSERT(psShader->sInfo.ui32NumConstantBuffers); if(psShader->sInfo.psConstantBuffers[0].ui32NumVars) { ++ui32NumDeclarations; bDeclareConstantTable = 1; } } } else if((eOpcode == OPCODE_DX9_DEF)||(eOpcode == OPCODE_DX9_DEFI)||(eOpcode == OPCODE_DX9_DEFB)) { ++ui32NumDeclarations; } else if(eOpcode == OPCODE_DX9_DCL) { const OPERAND_TYPE_DX9 eType = DecodeOperandTypeDX9(pui32CurrentToken[2]); uint32_t ignoreDCL = 0; //Inputs and outputs are declared in AddVersionDependentCode if(psShader->eShaderType == PIXEL_SHADER && (OPERAND_TYPE_DX9_CONST != eType && OPERAND_TYPE_DX9_SAMPLER != eType)) { ignoreDCL = 1; } if(!ignoreDCL) { ++ui32NumDeclarations; } } else { switch(eOpcode) { case OPCODE_DX9_NRM: { //Emulate with dp4 and rsq ui32NumInstructions += 2; break; } default: { ++ui32NumInstructions; break; } } } pui32CurrentToken += ui32InstLen + 1; } psInst = hlslcc_malloc(sizeof(Instruction) * ui32NumInstructions); psShader->psInst = psInst; psShader->ui32InstCount = ui32NumInstructions; if(psShader->eShaderType == VERTEX_SHADER) { //Declare gl_Position. vs_3_0 does declare it, SM1/2 do not ui32NumDeclarations++; } //For declaring temps. ui32NumDeclarations++; psDecl = hlslcc_malloc(sizeof(Declaration) * ui32NumDeclarations); psShader->psDecl = psDecl; psShader->ui32DeclCount = ui32NumDeclarations; pui32CurrentToken = pui32Tokens + 1; inst=0; decl=0; while (1) { OPCODE_TYPE_DX9 eOpcode = DecodeOpcodeTypeDX9(pui32CurrentToken[0]); uint32_t ui32InstLen = DecodeInstructionLengthDX9(pui32CurrentToken[0]); if(eOpcode == OPCODE_DX9_END) { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_RET, 0, 0, pui32CurrentToken); inst++; break; } else if(eOpcode == OPCODE_DX9_COMMENT) { ui32InstLen = DecodeCommentLengthDX9(pui32CurrentToken[0]); } else if(eOpcode == OPCODE_DX9_DCL) { const OPERAND_TYPE_DX9 eType = DecodeOperandTypeDX9(pui32CurrentToken[2]); uint32_t ignoreDCL = 0; //Inputs and outputs are declared in AddVersionDependentCode if(psShader->eShaderType == PIXEL_SHADER && (OPERAND_TYPE_DX9_CONST != eType && OPERAND_TYPE_DX9_SAMPLER != eType)) { ignoreDCL = 1; } SetupRegisterUsage(psShader, pui32CurrentToken[1], pui32CurrentToken[2]); if(!ignoreDCL) { DecodeDeclarationDX9(psShader, pui32CurrentToken[1], pui32CurrentToken[2], &psDecl[decl]); decl++; } } else if((eOpcode == OPCODE_DX9_DEF)||(eOpcode == OPCODE_DX9_DEFI)||(eOpcode == OPCODE_DX9_DEFB)) { const uint32_t ui32Const0 = *(pui32CurrentToken+2); const uint32_t ui32Const1 = *(pui32CurrentToken+3); const uint32_t ui32Const2 = *(pui32CurrentToken+4); const uint32_t ui32Const3 = *(pui32CurrentToken+5); uint32_t ui32Flags = 0; if(eOpcode == OPCODE_DX9_DEF) { ui32Flags |= DX9_DECODE_OPERAND_IS_CONST; } else if(eOpcode == OPCODE_DX9_DEFI) { ui32Flags |= DX9_DECODE_OPERAND_IS_ICONST; } else { ui32Flags |= DX9_DECODE_OPERAND_IS_BCONST; } DefineDX9(psShader, DecodeOperandRegisterNumberDX9(pui32CurrentToken[1]), ui32Flags, ui32Const0, ui32Const1, ui32Const2, ui32Const3, &psDecl[decl]); decl++; } else { switch(eOpcode) { case OPCODE_DX9_MOV: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_MOV, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_LIT: { /*Dest.x = 1 Dest.y = (Src0.x > 0) ? Src0.x : 0 Dest.z = (Src0.x > 0 && Src0.y > 0) ? pow(Src0.y, Src0.w) : 0 Dest.w = 1 */ ASSERT(0); break; } case OPCODE_DX9_ADD: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ADD, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_SUB: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ADD, 1, 2, pui32CurrentToken); ASSERT(psInst[inst].asOperands[2].eModifier == OPERAND_MODIFIER_NONE); psInst[inst].asOperands[2].eModifier = OPERAND_MODIFIER_NEG; break; } case OPCODE_DX9_MAD: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_MAD, 1, 3, pui32CurrentToken); break; } case OPCODE_DX9_MUL: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_MUL, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_RCP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_RCP, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_RSQ: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_RSQ, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_DP3: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DP3, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_DP4: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DP4, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_MIN: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_MIN, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_MAX: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_MAX, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_SLT: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_LT, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_SGE: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_GE, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_EXP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_EXP, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_LOG: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_LOG, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_NRM: { //Convert NRM RESULT, SRCA into: //dp4 RESULT, SRCA, SRCA //rsq RESULT, RESULT CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DP4, 1, 1, pui32CurrentToken); memcpy(&psInst[inst].asOperands[2],&psInst[inst].asOperands[1], sizeof(Operand)); ++inst; CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_RSQ, 0, 0, pui32CurrentToken); memcpy(&psInst[inst].asOperands[0],&psInst[inst-1].asOperands[0], sizeof(Operand)); break; } case OPCODE_DX9_SINCOS: { //Before SM3, SINCOS has 2 extra constant sources -D3DSINCOSCONST1 and D3DSINCOSCONST2. //Ignore them. CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_SINCOS, 1, 1, pui32CurrentToken); //Pre-SM4: //If the write mask is .x: dest.x = cos( V ) //If the write mask is .y: dest.y = sin( V ) //If the write mask is .xy: //dest.x = cos( V ) //dest.y = sin( V ) //SM4+ //destSin destCos Angle psInst[inst].ui32NumOperands = 3; //Set the angle memcpy(&psInst[inst].asOperands[2],&psInst[inst].asOperands[1], sizeof(Operand)); //Set the cosine dest memcpy(&psInst[inst].asOperands[1],&psInst[inst].asOperands[0], sizeof(Operand)); //Set write masks psInst[inst].asOperands[0].ui32CompMask &= ~OPERAND_4_COMPONENT_MASK_Y; if(psInst[inst].asOperands[0].ui32CompMask & OPERAND_4_COMPONENT_MASK_X) { //Need cosine } else { psInst[inst].asOperands[0].eType = OPERAND_TYPE_NULL; } psInst[inst].asOperands[1].ui32CompMask &= ~OPERAND_4_COMPONENT_MASK_X; if(psInst[inst].asOperands[1].ui32CompMask & OPERAND_4_COMPONENT_MASK_Y) { //Need sine } else { psInst[inst].asOperands[1].eType = OPERAND_TYPE_NULL; } break; } case OPCODE_DX9_FRC: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_FRC, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_MOVA: { //MOVA preforms RoundToNearest on the src data. //The only rounding functions available in all GLSL version are ceil and floor. CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ROUND_NI, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_TEX: { //texld r0, t0, s0 // srcAddress[.swizzle], srcResource[.swizzle], srcSampler CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_SAMPLE, 1, 2, pui32CurrentToken); psInst[inst].asOperands[2].ui32RegisterNumber = 0; break; } case OPCODE_DX9_TEXLDL: { //texld r0, t0, s0 // srcAddress[.swizzle], srcResource[.swizzle], srcSampler CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_SAMPLE_L, 1, 2, pui32CurrentToken); psInst[inst].asOperands[2].ui32RegisterNumber = 0; //Lod comes from fourth coordinate of address. memcpy(&psInst[inst].asOperands[4], &psInst[inst].asOperands[1], sizeof(Operand)); psInst[inst].ui32NumOperands = 5; break; } case OPCODE_DX9_IF: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_IF, 0, 1, pui32CurrentToken); psInst[inst].eDX9TestType = D3DSPC_BOOLEAN; break; } case OPCODE_DX9_IFC: { const COMPARISON_DX9 eCmpOp = DecodeComparisonDX9(pui32CurrentToken[0]); CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_IF, 0, 2, pui32CurrentToken); psInst[inst].eDX9TestType = eCmpOp; break; } case OPCODE_DX9_ELSE: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ELSE, 0, 0, pui32CurrentToken); break; } case OPCODE_DX9_CMP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_MOVC, 1, 3, pui32CurrentToken); break; } case OPCODE_DX9_REP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_REP, 0, 1, pui32CurrentToken); break; } case OPCODE_DX9_ENDREP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ENDREP, 0, 0, pui32CurrentToken); break; } case OPCODE_DX9_BREAKC: { const COMPARISON_DX9 eCmpOp = DecodeComparisonDX9(pui32CurrentToken[0]); CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_BREAKC, 0, 2, pui32CurrentToken); psInst[inst].eDX9TestType = eCmpOp; break; } case OPCODE_DX9_DSX: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DERIV_RTX, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_DSY: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DERIV_RTY, 1, 1, pui32CurrentToken); break; } case OPCODE_DX9_TEXKILL: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DISCARD, 1, 0, pui32CurrentToken); break; } case OPCODE_DX9_TEXLDD: { // texldd, dst, src0, src1, src2, src3 // srcAddress[.swizzle], srcResource[.swizzle], srcSampler, XGradient, YGradient CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_SAMPLE_D, 1, 4, pui32CurrentToken); psInst[inst].asOperands[2].ui32RegisterNumber = 0; break; } case OPCODE_DX9_LRP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_LRP, 1, 3, pui32CurrentToken); break; } case OPCODE_DX9_DP2ADD: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_DP2ADD, 1, 3, pui32CurrentToken); break; } case OPCODE_DX9_POW: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_POW, 1, 2, pui32CurrentToken); break; } case OPCODE_DX9_DST: case OPCODE_DX9_M4x4: case OPCODE_DX9_M4x3: case OPCODE_DX9_M3x4: case OPCODE_DX9_M3x3: case OPCODE_DX9_M3x2: case OPCODE_DX9_CALL: case OPCODE_DX9_CALLNZ: case OPCODE_DX9_LABEL: case OPCODE_DX9_CRS: case OPCODE_DX9_SGN: case OPCODE_DX9_ABS: case OPCODE_DX9_TEXCOORD: case OPCODE_DX9_TEXBEM: case OPCODE_DX9_TEXBEML: case OPCODE_DX9_TEXREG2AR: case OPCODE_DX9_TEXREG2GB: case OPCODE_DX9_TEXM3x2PAD: case OPCODE_DX9_TEXM3x2TEX: case OPCODE_DX9_TEXM3x3PAD: case OPCODE_DX9_TEXM3x3TEX: case OPCODE_DX9_TEXM3x3SPEC: case OPCODE_DX9_TEXM3x3VSPEC: case OPCODE_DX9_EXPP: case OPCODE_DX9_LOGP: case OPCODE_DX9_CND: case OPCODE_DX9_TEXREG2RGB: case OPCODE_DX9_TEXDP3TEX: case OPCODE_DX9_TEXM3x2DEPTH: case OPCODE_DX9_TEXDP3: case OPCODE_DX9_TEXM3x3: case OPCODE_DX9_TEXDEPTH: case OPCODE_DX9_BEM: case OPCODE_DX9_SETP: case OPCODE_DX9_BREAKP: { ASSERT(0); break; } case OPCODE_DX9_NOP: case OPCODE_DX9_PHASE: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_NOP, 0, 0, pui32CurrentToken); break; } case OPCODE_DX9_LOOP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_LOOP, 0, 2, pui32CurrentToken); break; } case OPCODE_DX9_RET: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_RET, 0, 0, pui32CurrentToken); break; } case OPCODE_DX9_ENDLOOP: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ENDLOOP, 0, 0, pui32CurrentToken); break; } case OPCODE_DX9_ENDIF: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_ENDIF, 0, 0, pui32CurrentToken); break; } case OPCODE_DX9_BREAK: { CreateD3D10Instruction(psShader, &psInst[inst], OPCODE_BREAK, 0, 0, pui32CurrentToken); break; } default: { ASSERT(0); break; } } UpdateOperandReferences(psShader, &psInst[inst]); inst++; } pui32CurrentToken += ui32InstLen + 1; } DeclareNumTemps(psShader, ui32MaxTemp, &psDecl[decl]); ++decl; if(psShader->eShaderType == VERTEX_SHADER) { //Declare gl_Position. vs_3_0 does declare it, SM1/2 do not if(bDeclareConstantTable) { DecodeDeclarationDX9(psShader, 0, CreateOperandTokenDX9(0, OPERAND_TYPE_DX9_RASTOUT), &psDecl[decl+1]); } else { DecodeDeclarationDX9(psShader, 0, CreateOperandTokenDX9(0, OPERAND_TYPE_DX9_RASTOUT), &psDecl[decl]); } } if(bDeclareConstantTable) { DeclareConstantBuffer(psShader, &psDecl[decl]); } return psShader; }
2.015625
2
2024-11-18T20:15:12.241723+00:00
2019-01-24T13:54:07
f3d771f5027a33c64bdff2d9e6223c0bf5aadde3
{ "blob_id": "f3d771f5027a33c64bdff2d9e6223c0bf5aadde3", "branch_name": "refs/heads/master", "committer_date": "2019-01-24T13:54:07", "content_id": "aed44076f7caecd5eba6185681ba4403813409d3", "detected_licenses": [ "MIT" ], "directory_id": "8d41c4ebef2c10c420715f4fbfc9712f9729397b", "extension": "c", "filename": "9-Test.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 162122255, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1575, "license": "MIT", "license_type": "permissive", "path": "/Chapter 9/9-Test.c", "provenance": "stackv2-0033.json.gz:158231", "repo_name": "Ruesigoren/Solution", "revision_date": "2019-01-24T13:54:07", "revision_id": "882471de39cb4bf471e958769f9f1c1a967da9c2", "snapshot_id": "8eee0107461ab41c5711e8eaac33d2701e5395f0", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Ruesigoren/Solution/882471de39cb4bf471e958769f9f1c1a967da9c2/Chapter 9/9-Test.c", "visit_date": "2020-04-11T21:59:45.702841" }
stackv2
/* * file: 9-Test.c * -------------- * this program define a enum type named outcomT. */ #include <stdio.h> #include <ctype.h> #include "strlib.h" #include "random.h" /* main program */ main() { Randomize(); typedef enum { Lose = -1, Draw = 0, Win = 1 } outcomeT; char t1 = 37; int t2 = 37; char t3 = 'A'; int t4 = 'A'; printf("%d %d %d %d\n", '$', '@', '\a', 'x'); printf("%c\n", t4); printf("%d\n", isdigit(53)); printf("%d\n", toupper('5')); printf("%d\n", StringsLength("ABCDE")); printf("%d\n", StringsLength("")); printf("%d\n", StringsLength("\a")); printf("%c\n", IthChar("ABC", 2)); printf("%s\n", Concat("12", ".00")); printf("%s\n", Concat(CharToStrings('2'), ".00")); printf("%s\n", SubStrings("ABCDE", 0, 3)); printf("%s\n", SubStrings("ABCDE", 4, 1)); printf("%s\n", SubStrings("ABCDE", 3, 9)); printf("%s\n", SubStrings("ABCDE", 3, 3)); printf("%d\n", StringsEqual("ABCDE", "abcde")); printf("%d\n", StringsCompare("ABCDE", "ABCDE")); printf("%d\n", StringsCompare("ABCDE", "ABC")); printf("%d\n", StringsCompare("ABCDE", "abcde")); printf("%d\n", FindChar('a', "ABracadabra", 0)); printf("%d\n", FindStrings("ra", "ABracadabra", 3)); printf("%d\n", FindStrings("is", "This is a test.", 0)); printf("%d\n", FindStrings("This is a test.", "test", 0)); printf("%s\n", ConvertToLowerCase("Catch-22")); printf("%d\n", StringsToInteger(SubStrings("Catch-22", 5, 7))); printf("%s\n", RealToStrings(3.140)); printf("%s\n", Concat(IntegerToStrings(4 / 3), "pi")); int b = RandomInteger(1, 90); printf("%d\n", b); }
3.1875
3