repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/src/atol.c | /*
* atol.c --
*
* Source code for the "atol" library procedure.
*
* Copyright 1988 Regents of the University of California
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies. The University of California
* makes no representations about the suitability of this
* software for any purpose. It is provided "as is" without
* express or implied warranty.
*/
#include <ctype.h>
/*
*----------------------------------------------------------------------
*
* atol --
*
* Convert an ASCII string into a long integer.
*
* Results:
* The return value is the integer equivalent of string. If there
* are no decimal digits in string, then 0 is returned.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
atol(char * string)
{
register int result = 0;
register unsigned int digit;
int sign;
/*
* Skip any leading blanks.
*/
while (isspace(*string)) {
string += 1;
}
/*
* Check for a sign.
*/
if (*string == '-') {
sign = 1;
string += 1;
} else {
sign = 0;
if (*string == '+') {
string += 1;
}
}
for ( ; ; string += 1) {
digit = *string - '0';
if (digit > 9) {
break;
}
result = (10*result) + digit;
}
if (sign) {
return -result;
}
return result;
} |
keystone-enclave/FreeRTOS-Kernel | main/src/commands.c | #include <stdint.h>
#include <string.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "FreeRTOS_IO.h"
#include "FreeRTOS_CLI.h"
/*-----------------------------------------------------------*/
/* Create the cli function */
/* This function implements the behaviour of a command, so must have the correct
prototype. */
static BaseType_t prvTaskStatsCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
const char *const pcHeader = "Task State Priority Stack #\n************************************************\n";
/* Remove compile time warnings about unused parameters, and check the
write buffer is not NULL. NOTE - for simplicity, this example assumes the
write buffer length is adequate, so does not check for buffer overflows. */
( void ) pcCommandString;
( void ) xWriteBufferLen;
configASSERT( pcWriteBuffer );
/* Generate a table of task stats. */
strcpy( pcWriteBuffer, pcHeader );
// vTaskList( pcWriteBuffer + strlen( pcHeader ) );
/* There is no more data to return after this single string, so return
pdFALSE. */
return pdFALSE;
}
/* Structure that defines the "task-stats" command line command. */
static const CLI_Command_Definition_t xTaskStats =
{
"task-stats", /* The command string to type. */
"\ntask-stats:\n Displays a table showing the state of each FreeRTOS task\n\n",
prvTaskStatsCommand, /* The function to run. */
0 /* No parameters are expected. */
};
/*-----------------------------------------------------------*/
static portBASE_TYPE prvThreeParameterEchoCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
char *pcParameterString;
portBASE_TYPE xParameterStringLength, xReturn;
static portBASE_TYPE xParameterNumber = 0;
/* Remove compile time warnings about unused parameters, and check the
write buffer is not NULL. NOTE - for simplicity, this example assumes the
write buffer length is adequate, so does not check for buffer overflows. */
( void ) pcCommandString;
( void ) xWriteBufferLen;
configASSERT( pcWriteBuffer );
if( xParameterNumber == 0 )
{
/* The first time the function is called after the command has been
entered just a header string is returned. */
sprintf( ( char * ) pcWriteBuffer, "The three parameters were:\r\n" );
/* Next time the function is called the first parameter will be echoed
back. */
xParameterNumber = 1L;
/* There is more data to be returned as no parameters have been echoed
back yet. */
xReturn = pdPASS;
}
else
{
/* Obtain the parameter string. */
pcParameterString = ( char * ) FreeRTOS_CLIGetParameter
(
pcCommandString, /* The command string itself. */
xParameterNumber, /* Return the next parameter. */
&xParameterStringLength /* Store the parameter string length. */
);
/* Sanity check something was returned. */
configASSERT( pcParameterString );
/* Return the parameter string. */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
sprintf( ( char * ) pcWriteBuffer, "%d: ", xParameterNumber );
strncat( ( char * ) pcWriteBuffer, ( const char * ) pcParameterString, xParameterStringLength );
strncat( ( char * ) pcWriteBuffer, "\r\n", strlen( "\r\n" ) );
/* If this is the last of the three parameters then there are no more
strings to return after this one. */
if( xParameterNumber == 3L )
{
/* If this is the last of the three parameters then there are no more
strings to return after this one. */
xReturn = pdFALSE;
xParameterNumber = 0L;
}
else
{
/* There are more parameters to return after this one. */
xReturn = pdTRUE;
xParameterNumber++;
}
}
return xReturn;
}
/* Structure that defines the "echo_3_parameters" command line command. This
takes exactly three parameters that the command simply echos back one at a
time. */
static const CLI_Command_Definition_t prvThreeParameterEchoCommandDefinition =
{
( const char * const ) "echo-3-parameters",
( const char * const ) "echo-3-parameters <param1> <param2> <param3>:\r\n Expects three parameters, echos each in turn\r\n\r\n",
prvThreeParameterEchoCommand, /* The function to run. */
3 /* Three parameters are expected, which can take any value. */
};
/*-----------------------------------------------------------*/
static portBASE_TYPE prvMultiParameterEchoCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
char *pcParameterString;
portBASE_TYPE xParameterStringLength, xReturn;
static portBASE_TYPE xParameterNumber = 0;
/* Remove compile time warnings about unused parameters, and check the
write buffer is not NULL. NOTE - for simplicity, this example assumes the
write buffer length is adequate, so does not check for buffer overflows. */
( void ) pcCommandString;
( void ) xWriteBufferLen;
configASSERT( pcWriteBuffer );
if( xParameterNumber == 0 )
{
/* The first time the function is called after the command has been
entered just a header string is returned. */
sprintf( ( char * ) pcWriteBuffer, "The parameters were:\r\n" );
/* Next time the function is called the first parameter will be echoed
back. */
xParameterNumber = 1L;
/* There is more data to be returned as no parameters have been echoed
back yet. */
xReturn = pdPASS;
}
else
{
/* Obtain the parameter string. */
pcParameterString = ( char * ) FreeRTOS_CLIGetParameter
(
pcCommandString, /* The command string itself. */
xParameterNumber, /* Return the next parameter. */
&xParameterStringLength /* Store the parameter string length. */
);
if( pcParameterString != NULL )
{
/* Return the parameter string. */
memset( pcWriteBuffer, 0x00, xWriteBufferLen );
sprintf( ( char * ) pcWriteBuffer, "%d: ", xParameterNumber );
strncat( ( char * ) pcWriteBuffer, ( const char * ) pcParameterString, xParameterStringLength );
strncat( ( char * ) pcWriteBuffer, "\r\n", strlen( "\r\n" ) );
/* There might be more parameters to return after this one. */
xReturn = pdTRUE;
xParameterNumber++;
}
else
{
/* No more parameters were found. Make sure the write buffer does
not contain a valid string. */
pcWriteBuffer[ 0 ] = 0x00;
/* No more data to return. */
xReturn = pdFALSE;
/* Start over the next time this command is executed. */
xParameterNumber = 0;
}
}
return xReturn;
}
/* Structure that defines the "echo_parameters" command line command. This
takes a variable number of parameters that the command simply echos back one at
a time. */
static const CLI_Command_Definition_t prvMultiParameterEchoCommandDefinition =
{
( const char * const ) "echo-parameters",
( const char * const ) "echo-parameters <...>:\r\n Take variable number of parameters, echos each in turn\r\n\r\n",
prvMultiParameterEchoCommand, /* The function to run. */
-1 /* The user can enter any number of commands. */
};
/*-----------------------------------------------------------*/
/*
* Holds the handle of the task created by the create-task command.
*/
static TaskHandle_t xCreatedTaskHandle = NULL;
void vOutputString( const uint8_t * const pucMessage )
{
/* Obtaining the write mutex prevents strings output using this function
from corrupting strings output by the command interpreter task (and visa
versa). It does not, however, prevent complete strings output using this
function intermingling with complete strings output from the command
interpreter as the command interpreter only holds the mutex on an output
string by output string basis. */
Peripheral_Descriptor_t xUART = FreeRTOS_open("/dev/uart", 0);
if( xUART != NULL )
{
// if( FreeRTOS_ioctl( xUART, ioctlOBTAIN_WRITE_MUTEX, cmd500ms ) == pdPASS )
{
FreeRTOS_write( xUART, pucMessage, strlen( ( char * ) pucMessage ) );
}
}
}
// static void prvCreatedTask( void *pvParameters )
// {
// portPOINTER_SIZE_TYPE lParameterValue;
// static uint8_t pucLocalBuffer[ 60 ];
// void vOutputString( const uint8_t * const pucMessage );
// /* Cast the parameter to an appropriate type. */
// lParameterValue = ( portPOINTER_SIZE_TYPE ) pvParameters;
// memset( ( void * ) pucLocalBuffer, 0x00, sizeof( pucLocalBuffer ) );
// sprintf( ( char * ) pucLocalBuffer, "Created task running. Received parameter %d\r\n\r\n", ( long ) lParameterValue );
// vOutputString( pucLocalBuffer );
// for( ;; )
// {
// vTaskDelay( portMAX_DELAY );
// }
// }
static void taskTestFn(void *pvParameters){
printf("Your number is: %p\n", pvParameters);
printf("Untrusted Task 1 DONE\n");
syscall_task_return();
}
TaskHandle_t taskTest;
/*-----------------------------------------------------------*/
static portBASE_TYPE prvCreateTaskCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
char *pcParameterString;
portBASE_TYPE xParameterStringLength;
static const char *pcSuccessMessage = ( char * ) "Task created\r\n";
static const char *pcFailureMessage = ( char * ) "Task not created\r\n";
static const char *pcTaskAlreadyCreatedMessage = ( char * ) "The task has already been created. Execute the delete-task command first.\r\n";
portPOINTER_SIZE_TYPE lParameterValue;
/* Remove compile time warnings about unused parameters, and check the
write buffer is not NULL. NOTE - for simplicity, this example assumes the
write buffer length is adequate, so does not check for buffer overflows. */
( void ) xWriteBufferLen;
configASSERT( pcWriteBuffer );
/* Obtain the parameter string. */
pcParameterString = ( char * ) FreeRTOS_CLIGetParameter
(
pcCommandString, /* The command string itself. */
1, /* Return the first parameter. */
&xParameterStringLength /* Store the parameter string length. */
);
/* Turn the parameter into a number. */
lParameterValue = ( portPOINTER_SIZE_TYPE ) atol( ( const char * ) pcParameterString );
/* Attempt to create the task. */
if( xCreatedTaskHandle != NULL )
{
strcpy( ( char * ) pcWriteBuffer, ( const char * ) pcTaskAlreadyCreatedMessage );
}
else
{
// else if( xTaskCreate( prvCreatedTask, ( const char * ) "Created", configMINIMAL_STACK_SIZE, ( void * ) lParameterValue, tskIDLE_PRIORITY, &xCreatedTaskHandle ) == pdPASS )
if( xTaskCreate(taskTestFn, "taskTest1", configMINIMAL_STACK_SIZE, (void*) lParameterValue, 25, &taskTest) == pdPASS )
{
strcpy( ( char * ) pcWriteBuffer, ( const char * ) pcSuccessMessage );
}
else
{
strcpy( ( char * ) pcWriteBuffer, ( const char * ) pcFailureMessage );
}
}
/* There is no more data to return after this single string, so return
pdFALSE. */
return pdFALSE;
}
/* Structure that defines the "create-task" command line command. This takes a
single parameter that is passed into a newly created task. The task then
periodically writes to the console. The parameter must be a numerical value. */
static const CLI_Command_Definition_t prvCreateTaskCommandDefinition =
{
( const char * const ) "create-task",
( const char * const ) "create-task <param>:\r\n Creates a new task that periodically writes the parameter to the CLI output\r\n\r\n",
prvCreateTaskCommand, /* The function to run. */
1 /* A single parameter should be entered. */
};
/*-----------------------------------------------------------*/
static portBASE_TYPE prvDeleteTaskCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
static const char *pcSuccessMessage = ( char * ) "Task deleted\r\n";
static const char *pcFailureMessage = ( char * ) "The task was not running. Execute the create-task command first.\r\n";
/* Remove compile time warnings about unused parameters, and check the
write buffer is not NULL. NOTE - for simplicity, this example assumes the
write buffer length is adequate, so does not check for buffer overflows. */
( void ) pcCommandString;
( void ) xWriteBufferLen;
configASSERT( pcWriteBuffer );
/* See if the task is running. */
if( xCreatedTaskHandle != NULL )
{
vTaskDelete( xCreatedTaskHandle );
xCreatedTaskHandle = NULL;
strcpy( ( char * ) pcWriteBuffer, ( const char * ) pcSuccessMessage );
}
else
{
strcpy( ( char * ) pcWriteBuffer, ( const char * ) pcFailureMessage );
}
/* There is no more data to return after this single string, so return
pdFALSE. */
return pdFALSE;
}
/* Structure that defines the "delete-task" command line command. This deletes
the task that was previously created using the "create-command" command. */
static const CLI_Command_Definition_t prvDeleteTaskCommandDefinition =
{
( const char * const ) "delete-task",
( const char * const ) "delete-task:\r\n Deletes the task created by the create-task command\r\n\r\n",
prvDeleteTaskCommand, /* The function to run. */
0 /* A single parameter should be entered. */
};
/*-----------------------------------------------------------*/
void vRegisterCLICommands( void )
{
/* Register all the command line commands defined immediately above. */
FreeRTOS_CLIRegisterCommand( &xTaskStats );
FreeRTOS_CLIRegisterCommand( &prvThreeParameterEchoCommandDefinition );
FreeRTOS_CLIRegisterCommand( &prvMultiParameterEchoCommandDefinition );
FreeRTOS_CLIRegisterCommand( &prvCreateTaskCommandDefinition );
FreeRTOS_CLIRegisterCommand( &prvDeleteTaskCommandDefinition );
} |
keystone-enclave/FreeRTOS-Kernel | sdk/lib/src/string.c | <gh_stars>1-10
#include "string.h"
/* TODO This is a temporary place to put libc functionality until we
* decide on a lib to provide such functionality to the runtime */
#include <stdint.h>
#include <ctype.h>
void* memcpy(void* dest, const void* src, size_t len)
{
const char* s = src;
char *d = dest;
if ((((uintptr_t)dest | (uintptr_t)src) & (sizeof(uintptr_t)-1)) == 0) {
while ((void*)d < (dest + len - (sizeof(uintptr_t)-1))) {
*(uintptr_t*)d = *(const uintptr_t*)s;
d += sizeof(uintptr_t);
s += sizeof(uintptr_t);
}
}
while (d < (char*)(dest + len))
*d++ = *s++;
return dest;
}
void* memset(void* dest, int byte, size_t len)
{
if ((((uintptr_t)dest | len) & (sizeof(uintptr_t)-1)) == 0) {
uintptr_t word = byte & 0xFF;
word |= word << 8;
word |= word << 16;
word |= word << 16 << 16;
uintptr_t *d = dest;
while (d < (uintptr_t*)(dest + len))
*d++ = word;
} else {
char *d = dest;
while (d < (char*)(dest + len))
*d++ = byte;
}
return dest;
}
int memcmp(const void* s1, const void* s2, size_t n)
{
unsigned char u1, u2;
for ( ; n-- ; s1++, s2++) {
u1 = * (unsigned char *) s1;
u2 = * (unsigned char *) s2;
if ( u1 != u2) {
return (u1-u2);
}
}
return 0;
}
/* Received from https://code.woboq.org/userspace/glibc/string/strcmp.c.html*/
/* Compare S1 and S2, returning less than, equal to or
greater than zero if S1 is lexicographically less than,
equal to or greater than S2. */
int
strcmp (const char *p1, const char *p2)
{
const unsigned char *s1 = (const unsigned char *) p1;
const unsigned char *s2 = (const unsigned char *) p2;
unsigned char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
/* https://code.woboq.org/userspace/glibc/string/strcpy.c.html */
char *
strcpy (char *dest, const char *src)
{
return memcpy (dest, src, strlen (src) + 1);
}
/* https://code.woboq.org/userspace/glibc/string/strlen.c.html */
size_t
strlen (const char *str)
{
const char *char_ptr;
const unsigned long int *longword_ptr;
unsigned long int longword, himagic, lomagic;
/* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = str; ((unsigned long int) char_ptr
& (sizeof (longword) - 1)) != 0;
++char_ptr)
if (*char_ptr == '\0')
return char_ptr - str;
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to 8-byte longwords. */
longword_ptr = (unsigned long int *) char_ptr;
/* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
the "holes." Note that there is a hole just to the left of
each byte, with an extra at the end:
bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
himagic = 0x80808080L;
lomagic = 0x01010101L;
if (sizeof (longword) > 4)
{
/* 64-bit version of the magic. */
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
himagic = ((himagic << 16) << 16) | himagic;
lomagic = ((lomagic << 16) << 16) | lomagic;
}
if (sizeof (longword) > 8)
return 0;
/* Instead of the traditional loop which tests each character,
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
for (;;)
{
longword = *longword_ptr++;
if (((longword - lomagic) & ~longword & himagic) != 0)
{
/* Which of the bytes was the zero? If none of them were, it was
a misfire; continue the search. */
const char *cp = (const char *) (longword_ptr - 1);
if (cp[0] == 0)
return cp - str;
if (cp[1] == 0)
return cp - str + 1;
if (cp[2] == 0)
return cp - str + 2;
if (cp[3] == 0)
return cp - str + 3;
if (sizeof (longword) > 4)
{
if (cp[4] == 0)
return cp - str + 4;
if (cp[5] == 0)
return cp - str + 5;
if (cp[6] == 0)
return cp - str + 6;
if (cp[7] == 0)
return cp - str + 7;
}
}
}
}
/* Set N bytes of S to 0. */
void
bzero (void *s, size_t len)
{
memset (s, '\0', len);
} |
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-IO/src/FreeRTOS_IO.c |
/* Standard includes. */
#include <string.h>
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Utils includes. */
#include "FreeRTOS_IO.h"
typedef struct xIO_INPUT_LIST
{
const IO_Device_Definition_t *pxDeviceDefinition;
struct xIO_INPUT_LIST *pxNext;
} IO_Definition_List_Item_t;
/* The definition of the list of devices. Devices that are registered are
added to this list. */
static IO_Definition_List_Item_t xRegisteredDevices =
{
NULL, /* The first command in the list is always the help command, defined in this file. */
NULL /* The next pointer is initialised to NULL, as there are no other registered commands yet. */
};
/*-----------------------------------------------------------*/
Peripheral_Descriptor_t
FreeRTOS_open( const char *pcPath, const uint32_t ulFlags )
{
const char *pcRegisteredDeviceString;
size_t xDeviceStringLength;
/* Search for the device string in the list of registered devices. */
for( IO_Definition_List_Item_t * pxDevice = &xRegisteredDevices; pxDevice != NULL; pxDevice = pxDevice->pxNext )
{
if (!pxDevice->pxDeviceDefinition)
continue;
pcRegisteredDeviceString = pxDevice->pxDeviceDefinition->pcDevice;
xDeviceStringLength = strlen( pcRegisteredDeviceString );
/* To ensure the string lengths match exactly, so as not to pick up
a sub-string of a longer device name, check the byte after the expected
end of the string is either the end of the string or a space before
a parameter. */
if( strncmp( pcPath, pcRegisteredDeviceString, xDeviceStringLength ) == 0 )
{
if( ( pcPath[ xDeviceStringLength ] == ' ' ) || ( pcPath[ xDeviceStringLength ] == 0x00 ) )
{
return pxDevice->pxDeviceDefinition;
}
}
}
return NULL;
}
size_t
FreeRTOS_read( Peripheral_Descriptor_t const pxPeripheral, void * const pvBuffer, const size_t xBytes )
{
if (pxPeripheral)
return pxPeripheral->pxReadCallback(pvBuffer, xBytes);
return 0;
}
size_t
FreeRTOS_write( Peripheral_Descriptor_t const pxPeripheral, const void *pvBuffer, const size_t xBytes )
{
if (pxPeripheral)
return pxPeripheral->pxWriteCallback(pvBuffer, xBytes);
return 0;
}
BaseType_t
FreeRTOS_ioctl( Peripheral_Descriptor_t const xPeripheral, uint32_t ulRequest, void *pvValue )
{
if (xPeripheral)
return xPeripheral->pxIoctlCallback(ulRequest, pvValue);
return pdFAIL;
}
/*-----------------------------------------------------------*/
BaseType_t FreeRTOS_IORegisterDevice( const IO_Device_Definition_t * const pxDeviceToRegister )
{
static IO_Definition_List_Item_t *pxLastDeviceInList = &xRegisteredDevices;
IO_Definition_List_Item_t *pxNewListItem;
BaseType_t xReturn = pdFAIL;
/* Check the parameter is not NULL. */
configASSERT( pxDeviceToRegister );
/* Create a new list item that will reference the command being registered. */
pxNewListItem = ( IO_Definition_List_Item_t * ) pvPortMalloc( sizeof( IO_Definition_List_Item_t ) );
configASSERT( pxNewListItem );
if( pxNewListItem != NULL )
{
taskENTER_CRITICAL();
{
/* Reference the device being registered from the newly created
list item. */
pxNewListItem->pxDeviceDefinition = pxDeviceToRegister;
/* The new list item will get added to the end of the list, so
pxNext has nowhere to point. */
pxNewListItem->pxNext = NULL;
/* Add the newly created list item to the end of the already existing
list. */
pxLastDeviceInList->pxNext = pxNewListItem;
/* Set the end of list marker to the new list item. */
pxLastDeviceInList = pxNewListItem;
}
taskEXIT_CRITICAL();
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/ |
keystone-enclave/FreeRTOS-Kernel | sdk/lib/src/tiny-malloc.c | // https://github.com/32bitmicro/newlib-nano-1.0/blob/master/newlib/libc/machine/xstormy16/tiny-malloc.c
/* A replacement malloc with:
- Much reduced code size;
- Smaller RAM footprint;
- The ability to handle downward-growing heaps;
but
- Slower;
- Probably higher memory fragmentation;
- Doesn't support threads (but, if it did support threads,
it wouldn't need a global lock, only a compare-and-swap instruction);
- Assumes the maximum alignment required is the alignment of a pointer;
- Assumes that memory is already there and doesn't need to be allocated.
* Synopsis of public routines
malloc(size_t n);
Return a pointer to a newly allocated chunk of at least n bytes, or null
if no space is available.
free(void* p);
Release the chunk of memory pointed to by p, or no effect if p is null.
realloc(void* p, size_t n);
Return a pointer to a chunk of size n that contains the same data
as does chunk p up to the minimum of (n, p's size) bytes, or null
if no space is available. The returned pointer may or may not be
the same as p. If p is null, equivalent to malloc. Unless the
#define REALLOC_ZERO_BYTES_FREES below is set, realloc with a
size argument of zero (re)allocates a minimum-sized chunk.
memalign(size_t alignment, size_t n);
Return a pointer to a newly allocated chunk of n bytes, aligned
in accord with the alignment argument, which must be a power of
two. Will fail if 'alignment' is too large.
calloc(size_t unit, size_t quantity);
Returns a pointer to quantity * unit bytes, with all locations
set to zero.
cfree(void* p);
Equivalent to free(p).
malloc_trim(size_t pad);
Release all but pad bytes of freed top-most memory back
to the system. Return 1 if successful, else 0.
malloc_usable_size(void* p);
Report the number usable allocated bytes associated with allocated
chunk p. This may or may not report more bytes than were requested,
due to alignment and minimum size constraints.
malloc_stats();
Prints brief summary statistics on stderr.
mallinfo()
Returns (by copy) a struct containing various summary statistics.
mallopt(int parameter_number, int parameter_value)
Changes one of the tunable parameters described below. Returns
1 if successful in changing the parameter, else 0. Actually, returns 0
always, as no parameter can be changed.
*/
#ifndef MALLOC_DIRECTION
#define MALLOC_DIRECTION 1
#endif
#include <stddef.h>
#include "string.h"
void* malloc(size_t);
void
free(void*);
void*
realloc(void*, size_t);
void* memalign(size_t, size_t);
void* valloc(size_t);
void* pvalloc(size_t);
void* calloc(size_t, size_t);
void
cfree(void*);
int malloc_trim(size_t);
size_t
malloc_usable_size(void*);
void
malloc_stats(void);
int
mallopt(int, int);
struct mallinfo
mallinfo(void);
typedef struct freelist_entry {
size_t size;
struct freelist_entry* next;
} * fle;
static fle __malloc_freelist = 0;
static void* __malloc_end = 0;
// fle __malloc_freelist;
/* Return the number of bytes that need to be added to X to make it
aligned to an ALIGN boundary. ALIGN must be a power of 2. */
#define M_ALIGN(x, align) (-(size_t)(x) & ((align)-1))
/* Return the number of bytes that need to be subtracted from X to make it
aligned to an ALIGN boundary. ALIGN must be a power of 2. */
#define M_ALIGN_SUB(x, align) ((size_t)(x) & ((align)-1))
extern char* __malloc_start;
// extern char *__malloc_zone_stop; /* dkohlbre: added since our malloc region
// is static */
/* This is the minimum gap allowed between __malloc_end and the top of
the stack. This is only checked for when __malloc_end is
decreased; if instead the stack grows into the heap, silent data
corruption will result. */
#define MALLOC_MINIMUM_GAP 32
#ifdef __xstormy16__
register void* stack_pointer asm("r15");
#define MALLOC_LIMIT stack_pointer
#else
#define MALLOC_LIMIT \
__builtin_frame_address(0) /* dkohlbre: modification for our malloc region \
*/
#endif
#if MALLOC_DIRECTION < 0
#define CAN_ALLOC_P(required) \
(((size_t)__malloc_end - (size_t)MALLOC_LIMIT - MALLOC_MINIMUM_GAP) >= \
(required))
#else
#define CAN_ALLOC_P(required) \
(((size_t)MALLOC_LIMIT - (size_t)__malloc_end - MALLOC_MINIMUM_GAP) >= \
(required))
#endif
/* real_size is the size we actually have to allocate, allowing for
overhead and alignment. */
#define REAL_SIZE(sz) \
((sz) < sizeof(struct freelist_entry) - sizeof(size_t) \
? sizeof(struct freelist_entry) \
: sz + sizeof(size_t) + M_ALIGN(sz, sizeof(size_t)))
void*
malloc(size_t sz) {
fle* nextfree;
fle block;
/* dkohlbre: Force init of malloc_end, it wasn't always gettng set */
if (__malloc_end == NULL) {
__malloc_end = &__malloc_start;
}
/* real_size is the size we actually have to allocate, allowing for
overhead and alignment. */
size_t real_size = REAL_SIZE(sz);
/* Look for the first block on the freelist that is large enough. */
for (nextfree = &__malloc_freelist; *nextfree;
nextfree = &(*nextfree)->next) {
block = *nextfree;
if (block->size >= real_size) {
/* If the block found is just the right size, remove it from
the free list. Otherwise, split it. */
if (block->size < real_size + sizeof(struct freelist_entry)) {
*nextfree = block->next;
return (void*)&block->next;
} else {
size_t newsize = block->size - real_size;
fle newnext = block->next;
*nextfree = (fle)((size_t)block + real_size);
(*nextfree)->size = newsize;
(*nextfree)->next = newnext;
goto done;
}
}
/* If this is the last block on the freelist, and it was too small,
enlarge it. */
if (!block->next && __malloc_end == (void*)((size_t)block + block->size)) {
size_t moresize = real_size - block->size;
if (!CAN_ALLOC_P(moresize)) return NULL;
*nextfree = NULL;
if (MALLOC_DIRECTION < 0) {
block = __malloc_end = (void*)((size_t)block - moresize);
} else {
__malloc_end = (void*)((size_t)block + real_size);
}
goto done;
}
}
/* No free space at the end of the free list. Allocate new space
and use that. */
if (!CAN_ALLOC_P(real_size)) return NULL;
if (MALLOC_DIRECTION > 0) {
block = __malloc_end;
__malloc_end = (void*)((size_t)__malloc_end + real_size);
} else {
block = __malloc_end = (void*)((size_t)__malloc_end - real_size);
}
done:
block->size = real_size;
return (void*)&block->next;
}
void
free(void* block_p) {
fle* nextfree;
fle block = (fle)((size_t)block_p - offsetof(struct freelist_entry, next));
if (block_p == NULL) return;
/* Look on the freelist to see if there's a free block just before
or just after this block. */
for (nextfree = &__malloc_freelist; *nextfree;
nextfree = &(*nextfree)->next) {
fle thisblock = *nextfree;
if ((size_t)thisblock + thisblock->size == (size_t)block) {
thisblock->size += block->size;
if (MALLOC_DIRECTION > 0 && thisblock->next &&
(size_t)block + block->size == (size_t)thisblock->next) {
thisblock->size += thisblock->next->size;
thisblock->next = thisblock->next->next;
}
return;
} else if ((size_t)thisblock == (size_t)block + block->size) {
if (MALLOC_DIRECTION < 0 && thisblock->next &&
(size_t)block == ((size_t)thisblock->next + thisblock->next->size)) {
*nextfree = thisblock->next;
thisblock->next->size += block->size + thisblock->size;
} else {
block->size += thisblock->size;
block->next = thisblock->next;
*nextfree = block;
}
return;
} else if (
(MALLOC_DIRECTION > 0 && (size_t)thisblock > (size_t)block) ||
(MALLOC_DIRECTION < 0 && (size_t)thisblock < (size_t)block))
break;
}
block->next = *nextfree;
*nextfree = block;
return;
}
void*
realloc(void* block_p, size_t sz) {
fle block = (fle)((size_t)block_p - offsetof(struct freelist_entry, next));
size_t real_size = REAL_SIZE(sz);
size_t old_real_size;
if (block_p == NULL) return malloc(sz);
old_real_size = block->size;
/* Perhaps we need to allocate more space. */
if (old_real_size < real_size) {
void* result;
size_t old_size = old_real_size - sizeof(size_t);
/* Need to allocate, copy, and free. */
result = malloc(sz);
if (result == NULL) return NULL;
memcpy(result, block_p, old_size < sz ? old_size : sz);
free(block_p);
return result;
}
/* Perhaps we can free some space. */
if (old_real_size - real_size >= sizeof(struct freelist_entry)) {
fle newblock = (fle)((size_t)block + real_size);
block->size = real_size;
newblock->size = old_real_size - real_size;
free(&newblock->next);
}
return block_p;
}
void*
calloc(size_t n, size_t elem_size) {
void* result;
size_t sz = n * elem_size;
result = malloc(sz);
if (result != NULL) memset(result, 0, sz);
return result;
}
void
cfree(void* p) {
free(p);
}
void*
memalign(size_t align, size_t sz) {
fle* nextfree;
fle block;
/* real_size is the size we actually have to allocate, allowing for
overhead and alignment. */
size_t real_size = REAL_SIZE(sz);
/* Some sanity checking on 'align'. */
if ((align & (align - 1)) != 0 || align <= 0) return NULL;
/* Look for the first block on the freelist that is large enough. */
/* One tricky part is this: We want the result to be a valid pointer
to free. That means that there has to be room for a size_t
before the block. If there's additional space before the block,
it should go on the freelist, or it'll be lost---we could add it
to the size of the block before it in memory, but finding the
previous block is expensive. */
for (nextfree = &__malloc_freelist;; nextfree = &(*nextfree)->next) {
size_t before_size;
size_t old_size;
/* If we've run out of free blocks, allocate more space. */
if (!*nextfree) {
old_size = real_size;
if (MALLOC_DIRECTION < 0) {
old_size += M_ALIGN_SUB(
((size_t)__malloc_end - old_size + sizeof(size_t)), align);
if (!CAN_ALLOC_P(old_size)) return NULL;
block = __malloc_end = (void*)((size_t)__malloc_end - old_size);
} else {
block = __malloc_end;
old_size += M_ALIGN((size_t)__malloc_end + sizeof(size_t), align);
if (!CAN_ALLOC_P(old_size)) return NULL;
__malloc_end = (void*)((size_t)__malloc_end + old_size);
}
*nextfree = block;
block->size = old_size;
block->next = NULL;
} else {
block = *nextfree;
old_size = block->size;
}
before_size = M_ALIGN(&block->next, align);
if (before_size != 0)
before_size = sizeof(*block) + M_ALIGN(&(block + 1)->next, align);
/* If this is the last block on the freelist, and it is too small,
enlarge it. */
if (!block->next && old_size < real_size + before_size &&
__malloc_end == (void*)((size_t)block + block->size)) {
if (MALLOC_DIRECTION < 0) {
size_t moresize = real_size - block->size;
moresize += M_ALIGN_SUB((size_t)&block->next - moresize, align);
if (!CAN_ALLOC_P(moresize)) return NULL;
block = __malloc_end = (void*)((size_t)block - moresize);
block->next = NULL;
block->size = old_size = old_size + moresize;
before_size = 0;
} else {
if (!CAN_ALLOC_P(before_size + real_size - block->size)) return NULL;
__malloc_end = (void*)((size_t)block + before_size + real_size);
block->size = old_size = before_size + real_size;
}
/* Two out of the four cases below will now be possible; which
two depends on MALLOC_DIRECTION. */
}
if (old_size >= real_size + before_size) {
/* This block will do. If there needs to be space before it,
split the block. */
if (before_size != 0) {
fle old_block = block;
old_block->size = before_size;
block = (fle)((size_t)block + before_size);
/* If there's no space after the block, we're now nearly
done; just make a note of the size required.
Otherwise, we need to create a new free space block. */
if (old_size - before_size <=
real_size + sizeof(struct freelist_entry)) {
block->size = old_size - before_size;
return (void*)&block->next;
} else {
fle new_block;
new_block = (fle)((size_t)block + real_size);
new_block->size = old_size - before_size - real_size;
if (MALLOC_DIRECTION > 0) {
new_block->next = old_block->next;
old_block->next = new_block;
} else {
new_block->next = old_block;
*nextfree = new_block;
}
goto done;
}
} else {
/* If the block found is just the right size, remove it from
the free list. Otherwise, split it. */
if (old_size <= real_size + sizeof(struct freelist_entry)) {
*nextfree = block->next;
return (void*)&block->next;
} else {
size_t newsize = old_size - real_size;
fle newnext = block->next;
*nextfree = (fle)((size_t)block + real_size);
(*nextfree)->size = newsize;
(*nextfree)->next = newnext;
goto done;
}
}
}
}
done:
block->size = real_size;
return (void*)&block->next;
}
void*
valloc(size_t sz) {
return memalign(128, sz);
}
void*
pvalloc(size_t sz) {
return memalign(128, sz + M_ALIGN(sz, 128));
}
#ifdef DEFINE_MALLINFO
#include "malloc.h"
struct mallinfo
mallinfo(void) {
struct mallinfo r;
fle fr;
size_t free_size;
size_t total_size;
size_t free_blocks;
memset(&r, 0, sizeof(r));
free_size = 0;
free_blocks = 0;
for (fr = __malloc_freelist; fr; fr = fr->next) {
free_size += fr->size;
free_blocks++;
if (!fr->next) {
int atend;
if (MALLOC_DIRECTION > 0)
atend = (void*)((size_t)fr + fr->size) == __malloc_end;
else
atend = (void*)fr == __malloc_end;
if (atend) r.keepcost = fr->size;
}
}
if (MALLOC_DIRECTION > 0)
total_size = (char*)__malloc_end - (char*)&__malloc_start;
else
total_size = (char*)&__malloc_start - (char*)__malloc_end;
#ifdef DEBUG
/* Fixme: should walk through all the in-use blocks and see if
they're valid. */
#endif
r.arena = total_size;
r.fordblks = free_size;
r.uordblks = total_size - free_size;
r.ordblks = free_blocks;
return r;
}
#endif
#ifdef DEFINE_MALLOC_STATS
#include <stdio.h>
#include "malloc.h"
void
malloc_stats(void) {
struct mallinfo i;
FILE* fp;
fp = stderr;
i = mallinfo();
fprintf(
fp, "malloc has reserved %u bytes between %p and %p\n", i.arena,
&__malloc_start, __malloc_end);
fprintf(fp, "there are %u bytes free in %u chunks\n", i.fordblks, i.ordblks);
fprintf(
fp, "of which %u bytes are at the end of the reserved space\n",
i.keepcost);
fprintf(fp, "and %u bytes are in use.\n", i.uordblks);
}
#endif
#ifdef DEFINE_MALLOC_USABLE_SIZE
size_t
malloc_usable_size(void* block_p) {
fle block = (fle)((size_t)block_p - offsetof(struct freelist_entry, next));
return block->size - sizeof(size_t);
}
#endif
#ifdef DEFINE_MALLOPT
int
mallopt(int n, int v) {
(void)n;
(void)v;
return 0;
}
#endif
|
keystone-enclave/FreeRTOS-Kernel | main/src/devices.c | <reponame>keystone-enclave/FreeRTOS-Kernel<filename>main/src/devices.c
#include "syscall.h"
#include "stdio.h"
#include "FreeRTOS_IO.h"
/*-----------------------------------------------------------*/
size_t
uart_read( void * const pvBuffer, const size_t xBytes )
{
// Lazy impl just to grab stdin.
char * buf = pvBuffer;
size_t i = 0;
size_t ctr = 0;
for (; i < xBytes; i++) {
ctr = 0;
do
{
if (ctr > 100) {
syscall_task_yield();
ctr = 0;
} else {
ctr++;
}
int c = getchar();
if (c != -1) {
*buf = (char) c;
break;
}
} while (1);
}
return i;
}
size_t
uart_write( const void *pvBuffer, const size_t xBytes )
{
// Lazy impl just to set stdout.
const char * buf = pvBuffer;
size_t i = 0;
for (; i < xBytes; i++) {
putchar(*(buf + i));
}
return i;
}
/* Structure that defines the "Uart" device. */
static const IO_Device_Definition_t xUart =
{
"/dev/uart", /* The device string to type into open. */
uart_read, /* The function to run if the IO read command is called. */
uart_write, /* The function to run if the IO write command is called. */
NULL /* The function to run if the IO ioctl command is called. Note uart does not support ioctl. */
};
/*-----------------------------------------------------------*/
void vRegisterIODevices( void )
{
FreeRTOS_IORegisterDevice(&xUart);
}
/*-----------------------------------------------------------*/ |
keystone-enclave/FreeRTOS-Kernel | sdk/rv8/primes/primes.c | // #include <stdio.h>
#include <stdint.h>
// #include <stdlib.h>
// #include <math.h>
#include "printf.h"
#include "malloc.h"
#include "eapp_utils.h"
#define test(p) (primes[p >> 6] & 1 << (p & 0x3f))
#define set(p) (primes[p >> 6] |= 1 << (p & 0x3f))
#define is_prime(p) !test(p)
void EAPP_ENTRY eapp_entry()
{
uintptr_t cycles1,cycles2;
printf("[primes]\n");
asm volatile ("rdcycle %0" : "=r" (cycles1));
int limit = 333333;
int64_t sqrt_limit = 577.34577; //Should be sqrt(limit)
size_t primes_size = ((limit >> 6) + 1) * sizeof(uint64_t);
uint64_t *primes = (uint64_t*)malloc(primes_size);
int64_t p = 2;
while (p <= limit >> 1) {
for (int64_t n = 2 * p; n <= limit; n += p) if (!test(n)) set(n);
while (++p <= sqrt_limit && test(p));
}
for (int i = limit; i > 0; i--) {
if (is_prime(i)) {
printf("%d\n", i);
asm volatile ("rdcycle %0" : "=r" (cycles2));
printf("iruntime %lu\r\n",cycles2-cycles1);
syscall_task_return();
}
}
};
|
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-CLI/src/register_CLI.c | // /* FreeRTOS includes. */
// #include "FreeRTOS.h"
// #include "FreeRTOS_CLI.h"
// BaseType_t FreeRTOS_CLIRegisterFunction( const char * taskName, const char * helpString, const void * prvFunction, size_t elfSize )
// {
// CLI_Command_Definition_t * pxNewCommandItem = ( CLI_Command_Definition_t * ) pvPortMalloc( sizeof( CLI_Command_Definition_t ) );
// pxNewCommandItem->pcCommand = taskName;
// pxNewCommandItem->pcHelpString = helpString;
// pxNewCommandItem->pxCommandInterpreter = prvFunction;
// pxNewCommandItem->cExpectedNumberOfParameters = 0;
// pxNewCommandItem->elfsize = elfSize;
// return FreeRTOS_CLIRegisterCommand(pxNewCommandItem);
// } |
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-CLI/src/CLI_functions.c |
/* Standard includes. */
#include <string.h>
#include <stdint.h>
#include <stdio.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "enclave.h"
/* Utils includes. */
#include "CLI_functions.h"
#include "FreeRTOS_CLI.h"
typedef struct xFunction_INPUT_LIST
{
const Function_Definition_t *pxFunctionDefinition;
struct xFunction_INPUT_LIST *pxNext;
} Function_Definition_List_Item_t;
/* The definition of the list of Functions. Functions that are registered are
added to this list. */
static Function_Definition_List_Item_t xRegisteredFunctions =
{
NULL, /* The first command in the list is always the help command, defined in this file. */
NULL /* The next pointer is initialised to NULL, as there are no other registered commands yet. */
};
static const CLI_Command_Definition_t prvRunTaskCommandDefinition =
{
( const char * const ) "run",
( const char * const ) "run:\r\n run's the specified task\r\n\r\n",
FreeRTOS_run, /* The function to run. */
1 /* A single parameter should be entered. */
};
/*-----------------------------------------------------------*/
BaseType_t
FreeRTOS_run( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
const char *pcRegisteredFunctionString;
size_t xFunctionStringLength;
/* Search for the Function string in the list of registered Functions. */
for( Function_Definition_List_Item_t * pxFunction = &xRegisteredFunctions; pxFunction != NULL; pxFunction = pxFunction->pxNext )
{
if (!pxFunction->pxFunctionDefinition)
continue;
pcRegisteredFunctionString = pxFunction->pxFunctionDefinition->pcFunction;
xFunctionStringLength = strlen( pcRegisteredFunctionString );
/* To ensure the string lengths match exactly, so as not to pick up
a sub-string of a longer Function name, check the byte after the expected
end of the string is either the end of the string or a space before
a parameter. */
if( strncmp( pcWriteBuffer, pcRegisteredFunctionString, xFunctionStringLength ) == 0 )
{
if( ( pcWriteBuffer[ xFunctionStringLength ] == ' ' ) || ( pcWriteBuffer[ xFunctionStringLength ] == 0x00 ) )
{
if (pxFunction->pxFunctionDefinition->enclaveSize) {
xTaskCreateEnclave((uintptr_t) pxFunction->pxFunctionDefinition->pxFunctionCallback, pxFunction->pxFunctionDefinition->enclaveSize, pxFunction->pxFunctionDefinition->pcFunction, 2, NULL, NULL);
} else {
xTaskCreate(pxFunction->pxFunctionDefinition->pxFunctionCallback, pxFunction->pxFunctionDefinition->pcFunction, configMINIMAL_STACK_SIZE, NULL, 2, NULL);
}
return pdPASS;
}
}
}
return pdFAIL;
}
/*-----------------------------------------------------------*/
BaseType_t FreeRTOS_RegisterFunction( char * pcFunction, void * pxFunction, size_t enclaveSize )
{
static Function_Definition_List_Item_t *pxLastFunctionInList = &xRegisteredFunctions;
Function_Definition_List_Item_t *pxNewListItem;
BaseType_t xReturn = pdFAIL;
static int hasBeenInitialized = 0;
if (!hasBeenInitialized) {
FreeRTOS_CLIRegisterCommand( &prvRunTaskCommandDefinition );
hasBeenInitialized = 1;
printf("RUN INIT\n");
}
Function_Definition_t * pxFunctionToRegister = (Function_Definition_t *) pvPortMalloc( sizeof( Function_Definition_t ) );
pxFunctionToRegister->pcFunction = pcFunction;
pxFunctionToRegister->pxFunctionCallback = pxFunction;
pxFunctionToRegister->enclaveSize = enclaveSize;
/* Check the parameter is not NULL. */
configASSERT( pxFunctionToRegister );
/* Create a new list item that will reference the command being registered. */
pxNewListItem = ( Function_Definition_List_Item_t * ) pvPortMalloc( sizeof( Function_Definition_List_Item_t ) );
configASSERT( pxNewListItem );
if( pxNewListItem != NULL )
{
taskENTER_CRITICAL();
{
/* Reference the Function being registered from the newly created
list item. */
pxNewListItem->pxFunctionDefinition = pxFunctionToRegister;
/* The new list item will get added to the end of the list, so
pxNext has nowhere to point. */
pxNewListItem->pxNext = NULL;
/* Add the newly created list item to the end of the already existing
list. */
pxLastFunctionInList->pxNext = pxNewListItem;
/* Set the end of list marker to the new list item. */
pxLastFunctionInList = pxNewListItem;
}
taskEXIT_CRITICAL();
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/ |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/src/sbi.c | <reponame>keystone-enclave/FreeRTOS-Kernel
#include "sbi.h"
#include "csr.h"
int
sbi_putchar(int character) {
return SBI_CALL_1(SBI_CONSOLE_PUTCHAR, character);
}
int
sbi_getchar() {
return SBI_CALL_0(SBI_CONSOLE_GETCHAR);
}
void
sbi_set_timer(uint64_t stime_value) {
#if __riscv_xlen == 32
SBI_CALL_2(SBI_SET_TIMER, stime_value, stime_value >> 32);
#else
SBI_CALL_1(SBI_SET_TIMER, stime_value);
#endif
}
void
sbi_enable_interrupts(){
// SBI_CALL_1(SBI_ENABLE_INTERRUPT, 1);
}
void
sbi_disable_interrupts(){
// SBI_CALL_1(SBI_ENABLE_INTERRUPT, 0);
}
int sbi_send(int task_id, void *msg, int size, uintptr_t yield){
return SBI_CALL_4(SBI_SEND_TASK, task_id, msg, size, yield);
}
int sbi_recv(int task_id, void *msg, int size, uintptr_t yield){
return SBI_CALL_4(SBI_RECV_TASK, task_id, msg, size, yield);
} |
keystone-enclave/FreeRTOS-Kernel | sdk/attest/attest.c | <filename>sdk/attest/attest.c
#include "eapp_utils.h"
#include "printf.h"
#define MDSIZE 64
#define SIGNATURE_SIZE 64
#define PRIVATE_KEY_SIZE 64 // includes public key
#define PUBLIC_KEY_SIZE 32
typedef unsigned char byte;
#define ATTEST_DATA_MAXLEN 1024
/* attestation reports */
struct enclave_report
{
byte hash[MDSIZE];
uint64_t data_len;
byte data[ATTEST_DATA_MAXLEN];
byte signature[SIGNATURE_SIZE];
};
struct sm_report
{
byte hash[MDSIZE];
byte public_key[PUBLIC_KEY_SIZE];
byte signature[SIGNATURE_SIZE];
};
struct report
{
struct enclave_report enclave;
struct sm_report sm;
byte dev_public_key[PUBLIC_KEY_SIZE];
};
uintptr_t
sbi_attest_task(void* report, void* buf, uintptr_t len) {
return SBI_CALL_3(SBI_ATTEST_TASK, report, buf, len);
}
void EAPP_ENTRY eapp_entry(){
char* data = "nonce";
char buffer[2048];
struct report *report;
sbi_attest_task((void*) buffer, data, 5);
report = (struct report *) buffer;
printf("[Enclave 2] Enclave hash is...\n");
for(int i = 0; i < MDSIZE; i++){
printf("%x", report->enclave.hash[i]);
}
printf("\n");
printf("[Enclave 2] SM hash is...\n");
for(int i = 0; i < MDSIZE; i++){
printf("%x", report->sm.hash[i]);
}
printf("\n");
printf("[Enclave 2] Signature is...\n");
for(int i = 0; i < SIGNATURE_SIZE; i++){
printf("%x", report->enclave.signature[i]);
}
printf("\n");
printf("[Enclave 2] DONE\n");
syscall_task_return();
} |
keystone-enclave/FreeRTOS-Kernel | lib/utils/elf/src/elf64.c | /*
* Copyright (c) 1999-2004 University of New South Wales
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <elf.h>
#include <elf64.h>
#include <inttypes.h>
#include <string.h>
/* ELF header functions */
int
elf64_checkFile(elf_t* elf) {
if (sizeof(uintptr_t) != sizeof(uint64_t)) {
return -1; /* not supported on 32-bit architecture */
}
if (elf->elfSize < sizeof(Elf64_Ehdr)) {
return -1; /* file smaller than ELF header */
}
if (elf_check_magic((char*)elf->elfFile) < 0) {
return -1; /* not an ELF file */
}
Elf64_Ehdr* header = (Elf64_Ehdr*)elf->elfFile;
if (header->e_ident[EI_CLASS] != ELFCLASS64) {
return -1; /* not a 64-bit ELF */
}
if (header->e_phentsize != sizeof(Elf64_Phdr)) {
return -1; /* unexpected program header size */
}
if (header->e_shentsize != sizeof(Elf64_Shdr)) {
return -1; /* unexpected section header size */
}
if (header->e_shstrndx >= header->e_shnum) {
return -1; /* invalid section header string table section */
}
elf->elfClass = header->e_ident[EI_CLASS];
return 0; /* elf header looks OK */
}
int
elf64_checkProgramHeaderTable(elf_t* elf) {
Elf64_Ehdr* header = (Elf64_Ehdr*)elf->elfFile;
size_t ph_end = header->e_phoff + header->e_phentsize * header->e_phnum;
if (elf->elfSize < ph_end || ph_end < header->e_phoff) {
return -1; /* invalid program header table */
}
return 0;
}
int
elf64_checkSectionTable(elf_t* elf) {
Elf64_Ehdr* header = (Elf64_Ehdr*)elf->elfFile;
size_t sh_end = header->e_shoff + header->e_shentsize * header->e_shnum;
if (elf->elfSize < sh_end || sh_end < header->e_shoff) {
return -1; /* invalid section header table */
}
return 0;
} |
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/include/ctype.h | int isspace(int c); |
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/include/stdio.h | <gh_stars>1-10
int getchar();
int putchar(int); |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/include/sbi.h | <reponame>keystone-enclave/FreeRTOS-Kernel
#ifndef __SBI_H_
#define __SBI_H_
#include <stdint.h>
#define SBI_SET_TIMER 0
#define SBI_CONSOLE_PUTCHAR 1
#define SBI_CONSOLE_GETCHAR 2
#define SBI_SM_CREATE_ENCLAVE 101
#define SBI_SM_DESTROY_ENCLAVE 102
#define SBI_SM_ATTEST_ENCLAVE 103
#define SBI_SM_GET_SEALING_KEY 104
#define SBI_SM_RUN_ENCLAVE 105
#define SBI_SM_STOP_ENCLAVE 106
#define SBI_SM_RESUME_ENCLAVE 107
#define SBI_SM_RANDOM 108
#define SBI_SEND_TASK 204
#define SBI_RECV_TASK 205
#define SBI_SM_EXIT_ENCLAVE 1101
#define SBI_SM_CALL_PLUGIN 1000
#define SBI_SM_NOT_IMPLEMENTED 1111
#define SBI_CALL(___which, ___arg0, ___arg1, ___arg2, ___arg3) \
({ \
register uintptr_t a0 __asm__("a0") = (uintptr_t)(___arg0); \
register uintptr_t a1 __asm__("a1") = (uintptr_t)(___arg1); \
register uintptr_t a2 __asm__("a2") = (uintptr_t)(___arg2); \
register uintptr_t a3 __asm__("a3") = (uintptr_t)(___arg3); \
register uintptr_t a7 __asm__("a7") = (uintptr_t)(___which); \
__asm__ volatile("ecall" \
: "+r"(a0) \
: "r"(a1), "r"(a2), "r"(a3), "r"(a7) \
: "memory"); \
a0; \
})
/* Lazy implementations until SBI is finalized */
#define SBI_CALL_0(___which) SBI_CALL(___which, 0, 0, 0, 0)
#define SBI_CALL_1(___which, ___arg0) SBI_CALL(___which, ___arg0, 0, 0, 0)
#define SBI_CALL_2(___which, ___arg0, ___arg1) \
SBI_CALL(___which, ___arg0, ___arg1, 0, 0)
#define SBI_CALL_3(___which, ___arg0, ___arg1, ___arg2) \
SBI_CALL(___which, ___arg0, ___arg1, ___arg2, 0)
#define SBI_CALL_4(___which, ___arg0, ___arg1, ___arg2, ___arg3) \
SBI_CALL(___which, ___arg0, ___arg1, ___arg2, ___arg3)
int
sbi_putchar(int c);
int
sbi_getchar();
void
sbi_set_timer(uint64_t stime_value);
void
sbi_switch_task();
void
sbi_enable_interrupts();
void
sbi_disable_interrupts();
void handle_timer_interrupt();
void ENABLE_INTERRUPTS(void);
void DISABLE_INTERRUPTS(void);
int sbi_recv(int task_id, void *msg, int size, uintptr_t yield);
int sbi_send(int task_id, void *msg, int size, uintptr_t yield);
#endif
|
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/src/stdio.c | <filename>lib/utils/lib/src/stdio.c
#include "sbi.h"
int
getchar()
{
return sbi_getchar();
}
int
putchar(int character)
{
return sbi_putchar(character);
} |
keystone-enclave/FreeRTOS-Kernel | lib/utils/elf/include/elf64.h | <filename>lib/utils/elf/include/elf64.h
/*
* Copyright (c) 1999-2004 University of New South Wales
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <elf.h>
#include <stdint.h>
/* ELF header functions */
int
elf64_checkFile(elf_t* elf);
int
elf64_checkProgramHeaderTable(elf_t* elf);
int
elf64_checkSectionTable(elf_t* elf);
static inline bool
elf_isElf64(elf_t* elf) {
return elf->elfClass == ELFCLASS64;
}
static inline Elf64_Ehdr
elf64_getHeader(elf_t* elf) {
return *(Elf64_Ehdr*)elf->elfFile;
}
static inline uintptr_t
elf64_getEntryPoint(elf_t* file) {
return elf64_getHeader(file).e_entry;
}
static inline Elf64_Phdr*
elf64_getProgramHeaderTable(elf_t* file) {
return (Elf64_Phdr*)((uint8_t*)file->elfFile + elf64_getHeader(file).e_phoff);
}
static inline Elf64_Shdr*
elf64_getSectionTable(elf_t* file) {
return (Elf64_Shdr*)((uint8_t*)file->elfFile + elf64_getHeader(file).e_shoff);
}
static inline size_t
elf64_getNumProgramHeaders(elf_t* file) {
return elf64_getHeader(file).e_phnum;
}
static inline size_t
elf64_getNumSections(elf_t* elf) {
return elf64_getHeader(elf).e_shnum;
}
static inline size_t
elf64_getSectionStringTableIndex(elf_t* elf) {
return elf64_getHeader(elf).e_shstrndx;
}
/* Section header functions */
static inline size_t
elf64_getSectionNameOffset(elf_t* elf, size_t s) {
return elf64_getSectionTable(elf)[s].sh_name;
}
static inline uint32_t
elf64_getSectionType(elf_t* file, size_t s) {
return elf64_getSectionTable(file)[s].sh_type;
}
static inline size_t
elf64_getSectionFlags(elf_t* file, size_t s) {
return elf64_getSectionTable(file)[s].sh_flags;
}
static inline uintptr_t
elf64_getSectionAddr(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_addr;
}
static inline size_t
elf64_getSectionOffset(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_offset;
}
static inline size_t
elf64_getSectionSize(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_size;
}
static inline uint32_t
elf64_getSectionLink(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_link;
}
static inline uint32_t
elf64_getSectionInfo(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_info;
}
static inline size_t
elf64_getSectionAddrAlign(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_addralign;
}
static inline size_t
elf64_getSectionEntrySize(elf_t* elf, size_t i) {
return elf64_getSectionTable(elf)[i].sh_entsize;
}
/* Program header functions */
static inline uint32_t
elf64_getProgramHeaderType(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_type;
}
static inline size_t
elf64_getProgramHeaderOffset(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_offset;
}
static inline uintptr_t
elf64_getProgramHeaderVaddr(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_vaddr;
}
static inline uintptr_t
elf64_getProgramHeaderPaddr(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_paddr;
}
static inline size_t
elf64_getProgramHeaderFileSize(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_filesz;
}
static inline size_t
elf64_getProgramHeaderMemorySize(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_memsz;
}
static inline uint32_t
elf64_getProgramHeaderFlags(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_flags;
}
static inline size_t
elf64_getProgramHeaderAlign(elf_t* file, size_t ph) {
return elf64_getProgramHeaderTable(file)[ph].p_align;
} |
keystone-enclave/FreeRTOS-Kernel | lib/utils/elf/src/elf.c | /*
* Copyright (c) 1999-2004 University of New South Wales
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <elf.h>
#include <elf32.h>
#include <elf64.h>
#include <stdio.h>
#include <string.h>
/* ELF header functions */
int
elf_newFile(void* file, size_t size, elf_t* res) {
return elf_newFile_maybe_unsafe(file, size, true, true, res);
}
int
elf_newFile_maybe_unsafe(
void* file, size_t size, bool check_pht, bool check_st, elf_t* res) {
elf_t new_file = {.elfFile = file, .elfSize = size};
int status = elf_checkFile(&new_file);
if (status < 0) {
return status;
}
if (check_pht) {
status = elf_checkProgramHeaderTable(&new_file);
if (status < 0) {
return status;
}
}
if (check_st) {
status = elf_checkSectionTable(&new_file);
if (status < 0) {
return status;
}
}
if (res) {
*res = new_file;
}
return status;
}
int
elf_check_magic(char* file) {
if (memcmp(file, ELFMAG, SELFMAG) != 0) {
return -1;
}
return 0;
}
/*
* Checks that elfFile points to a valid elf file. Returns 0 if the elf
* file is valid, < 0 if invalid.
*/
int
elf_checkFile(elf_t* elfFile) {
int res = elf32_checkFile(elfFile);
if (res == 0) {
return 0;
}
res = elf64_checkFile(elfFile);
if (res == 0) {
return 0;
}
return -1;
}
int
elf_checkProgramHeaderTable(elf_t* elfFile) {
if (elf_isElf32(elfFile)) {
return elf32_checkProgramHeaderTable(elfFile);
} else {
return elf64_checkProgramHeaderTable(elfFile);
}
}
int
elf_checkSectionTable(elf_t* elfFile) {
if (elf_isElf32(elfFile)) {
return elf32_checkSectionTable(elfFile);
} else {
return elf64_checkSectionTable(elfFile);
}
}
uintptr_t
elf_getEntryPoint(elf_t* elfFile) {
if (elf_isElf32(elfFile)) {
return elf32_getEntryPoint(elfFile);
} else {
return elf64_getEntryPoint(elfFile);
}
}
size_t
elf_getNumProgramHeaders(elf_t* elfFile) {
if (elf_isElf32(elfFile)) {
return elf32_getNumProgramHeaders(elfFile);
} else {
return elf64_getNumProgramHeaders(elfFile);
}
}
size_t
elf_getNumSections(elf_t* elfFile) {
if (elf_isElf32(elfFile)) {
return elf32_getNumSections(elfFile);
} else {
return elf64_getNumSections(elfFile);
}
}
size_t
elf_getSectionStringTableIndex(elf_t* elf) {
if (elf_isElf32(elf)) {
return elf32_getSectionStringTableIndex(elf);
} else {
return elf64_getSectionStringTableIndex(elf);
}
}
const char*
elf_getStringTable(elf_t* elf, size_t string_segment) {
const char* string_table = (const char*)elf_getSection(elf, string_segment);
if (string_table == NULL) {
return NULL; /* no such section */
}
if (elf_getSectionType(elf, string_segment) != SHT_STRTAB) {
return NULL; /* not a string table */
}
size_t size = elf_getSectionSize(elf, string_segment);
if (string_table[size - 1] != 0) {
return NULL; /* string table is not null-terminated */
}
return string_table;
}
const char*
elf_getSectionStringTable(elf_t* elf) {
size_t index = elf_getSectionStringTableIndex(elf);
return elf_getStringTable(elf, index);
}
/* Section header functions */
void*
elf_getSection(elf_t* elf, size_t i) {
if (i == 0 || i >= elf_getNumSections(elf)) {
return NULL; /* no such section */
}
size_t section_offset = elf_getSectionOffset(elf, i);
size_t section_size = elf_getSectionSize(elf, i);
if (section_size == 0) {
return NULL; /* section is empty */
}
size_t section_end = section_offset + section_size;
/* possible wraparound - check that section end is not before section start */
if (section_end > elf->elfSize || section_end < section_offset) {
return NULL;
}
return (uint8_t*)elf->elfFile + section_offset;
}
void*
elf_getSectionNamed(elf_t* elfFile, const char* str, size_t* id) {
size_t numSections = elf_getNumSections(elfFile);
for (size_t i = 0; i < numSections; i++) {
if (strcmp(str, elf_getSectionName(elfFile, i)) == 0) {
if (id != NULL) {
*id = i;
}
return elf_getSection(elfFile, i);
}
}
return NULL;
}
const char*
elf_getSectionName(elf_t* elf, size_t i) {
size_t str_table_idx = elf_getSectionStringTableIndex(elf);
const char* str_table = elf_getStringTable(elf, str_table_idx);
size_t offset = elf_getSectionNameOffset(elf, i);
size_t size = elf_getSectionSize(elf, str_table_idx);
if (str_table == NULL || offset > size) {
return "<corrupted>";
}
return str_table + offset;
}
size_t
elf_getSectionNameOffset(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionNameOffset(elfFile, i);
} else {
return elf64_getSectionNameOffset(elfFile, i);
}
}
uint32_t
elf_getSectionType(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionType(elfFile, i);
} else {
return elf64_getSectionType(elfFile, i);
}
}
size_t
elf_getSectionFlags(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionFlags(elfFile, i);
} else {
return elf64_getSectionFlags(elfFile, i);
}
}
uintptr_t
elf_getSectionAddr(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionAddr(elfFile, i);
} else {
return elf64_getSectionAddr(elfFile, i);
}
}
size_t
elf_getSectionOffset(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionOffset(elfFile, i);
} else {
return elf64_getSectionOffset(elfFile, i);
}
}
size_t
elf_getSectionSize(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionSize(elfFile, i);
} else {
return elf64_getSectionSize(elfFile, i);
}
}
uint32_t
elf_getSectionLink(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionLink(elfFile, i);
} else {
return elf64_getSectionLink(elfFile, i);
}
}
uint32_t
elf_getSectionInfo(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionInfo(elfFile, i);
} else {
return elf64_getSectionInfo(elfFile, i);
}
}
size_t
elf_getSectionAddrAlign(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionAddrAlign(elfFile, i);
} else {
return elf64_getSectionAddrAlign(elfFile, i);
}
}
size_t
elf_getSectionEntrySize(elf_t* elfFile, size_t i) {
if (elf_isElf32(elfFile)) {
return elf32_getSectionEntrySize(elfFile, i);
} else {
return elf64_getSectionEntrySize(elfFile, i);
}
}
/* Program headers function */
void*
elf_getProgramSegment(elf_t* elf, size_t ph) {
size_t offset = elf_getProgramHeaderOffset(elf, ph);
size_t file_size = elf_getProgramHeaderFileSize(elf, ph);
size_t segment_end = offset + file_size;
/* possible wraparound - check that segment end is not before segment start */
if (elf->elfSize < segment_end || segment_end < offset) {
return NULL;
}
return (uint8_t*)elf->elfFile + offset;
}
uint32_t
elf_getProgramHeaderType(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderType(elfFile, ph);
} else {
return elf64_getProgramHeaderType(elfFile, ph);
}
}
size_t
elf_getProgramHeaderOffset(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderOffset(elfFile, ph);
} else {
return elf64_getProgramHeaderOffset(elfFile, ph);
}
}
uintptr_t
elf_getProgramHeaderVaddr(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderVaddr(elfFile, ph);
} else {
return elf64_getProgramHeaderVaddr(elfFile, ph);
}
}
uintptr_t
elf_getProgramHeaderPaddr(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderPaddr(elfFile, ph);
} else {
return elf64_getProgramHeaderPaddr(elfFile, ph);
}
}
size_t
elf_getProgramHeaderFileSize(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderFileSize(elfFile, ph);
} else {
return elf64_getProgramHeaderFileSize(elfFile, ph);
}
}
size_t
elf_getProgramHeaderMemorySize(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderMemorySize(elfFile, ph);
} else {
return elf64_getProgramHeaderMemorySize(elfFile, ph);
}
}
uint32_t
elf_getProgramHeaderFlags(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderFlags(elfFile, ph);
} else {
return elf64_getProgramHeaderFlags(elfFile, ph);
}
}
size_t
elf_getProgramHeaderAlign(elf_t* elfFile, size_t ph) {
if (elf_isElf32(elfFile)) {
return elf32_getProgramHeaderAlign(elfFile, ph);
} else {
return elf64_getProgramHeaderAlign(elfFile, ph);
}
}
/* Utility functions */
int
elf_getMemoryBounds(
elf_t* elfFile, elf_addr_type_t addr_type, uintptr_t* min, uintptr_t* max) {
uintptr_t mem_min = UINTPTR_MAX;
uintptr_t mem_max = 0;
size_t i;
for (i = 0; i < elf_getNumProgramHeaders(elfFile); i++) {
uintptr_t sect_min, sect_max;
if (elf_getProgramHeaderMemorySize(elfFile, i) == 0) {
continue;
}
if (addr_type == PHYSICAL) {
sect_min = elf_getProgramHeaderPaddr(elfFile, i);
} else {
sect_min = elf_getProgramHeaderVaddr(elfFile, i);
}
sect_max = sect_min + elf_getProgramHeaderMemorySize(elfFile, i);
if (sect_max > mem_max) {
mem_max = sect_max;
}
if (sect_min < mem_min) {
mem_min = sect_min;
}
}
*min = mem_min;
*max = mem_max;
return 1;
}
int
elf_vaddrInProgramHeader(elf_t* elfFile, size_t ph, uintptr_t vaddr) {
uintptr_t min = elf_getProgramHeaderVaddr(elfFile, ph);
uintptr_t max = min + elf_getProgramHeaderMemorySize(elfFile, ph);
if (vaddr >= min && vaddr < max) {
return 1;
} else {
return 0;
}
}
uintptr_t
elf_vtopProgramHeader(elf_t* elfFile, size_t ph, uintptr_t vaddr) {
uintptr_t ph_phys = elf_getProgramHeaderPaddr(elfFile, ph);
uintptr_t ph_virt = elf_getProgramHeaderVaddr(elfFile, ph);
uintptr_t paddr;
paddr = vaddr - ph_virt + ph_phys;
return paddr;
}
int
elf_loadFile(elf_t* elf, elf_addr_type_t addr_type) {
size_t i;
for (i = 0; i < elf_getNumProgramHeaders(elf); i++) {
/* Load that section */
uintptr_t dest, src;
size_t len;
if (addr_type == PHYSICAL) {
dest = elf_getProgramHeaderPaddr(elf, i);
} else {
dest = elf_getProgramHeaderVaddr(elf, i);
}
len = elf_getProgramHeaderFileSize(elf, i);
src = (uintptr_t)elf->elfFile + elf_getProgramHeaderOffset(elf, i);
memcpy((void*)dest, (void*)src, len);
dest += len;
memset((void*)dest, 0, elf_getProgramHeaderMemorySize(elf, i) - len);
}
return 1;
} |
keystone-enclave/FreeRTOS-Kernel | sdk/receiver/receiver.c | #include <stdint.h>
#include <timex.h>
#include "enclave_rl.h"
#include "printf.h"
#include "eapp_utils.h"
#include "msg_test.h"
char send_buf[DATA_SIZE] = "alex";
char recv_buf[DATA_SIZE] = {0};
void EAPP_ENTRY eapp_entry(int SENDER_TID){
// sbi_recv(SENDER_TID, recv_buf, DATA_SIZE, YIELD);
while(sbi_recv(SENDER_TID, recv_buf, DATA_SIZE, YIELD));
sbi_send(SENDER_TID, send_buf, DATA_SIZE, YIELD);
syscall_task_yield();
syscall_task_return();
} |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/include/enclave.h | <gh_stars>1-10
#ifndef _ENCLAVE_H
#define _ENCLAVE_H
uintptr_t xTaskCreateEnclave(uintptr_t start, uintptr_t size,
const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
UBaseType_t uxPriority,
void * const pvParameters,
TaskHandle_t * const pxCreatedTask);
#endif |
keystone-enclave/FreeRTOS-Kernel | lib/rtos/include/regs.h | //******************************************************************************
// Copyright (c) 2018, The Regents of the University of California (Regents).
// All Rights Reserved. See LICENSE for license details.
//------------------------------------------------------------------------------
#ifndef _REGS_H_
#define _REGS_H_
#include <stdint.h>
struct regs {
uintptr_t pc; // use this slot as pc
uintptr_t ra;
uintptr_t sp;
uintptr_t t0;
uintptr_t t1;
uintptr_t t2;
uintptr_t s0;
uintptr_t s1;
uintptr_t a0;
uintptr_t a1;
uintptr_t a2;
uintptr_t a3;
uintptr_t a4;
uintptr_t a5;
uintptr_t a6;
uintptr_t a7;
uintptr_t s2;
uintptr_t s3;
uintptr_t s4;
uintptr_t s5;
uintptr_t s6;
uintptr_t s7;
uintptr_t s8;
uintptr_t s9;
uintptr_t s10;
uintptr_t s11;
uintptr_t t3;
uintptr_t t4;
uintptr_t t5;
uintptr_t t6;
};
#endif /* _REGS_H_ */ |
keystone-enclave/FreeRTOS-Kernel | main/src/msg_tasks.c | <filename>main/src/msg_tasks.c
#include <FreeRTOS.h>
#include <task.h>
#include <printf.h>
#include <csr.h>
#include <sbi.h>
#include <syscall.h>
#include <enclave.h>
#include <elf.h>
#include <stdio.h>
#include <string.h>
#include <queue.h>
#include <rl.h>
#include <rl_config.h>
#include <timex.h> |
keystone-enclave/FreeRTOS-Kernel | lib/utils/lib/include/string.h | <reponame>keystone-enclave/FreeRTOS-Kernel
#ifndef __STRING_H__
#define __STRING_H__
#include <stddef.h>
#include <stdint.h>
void* memcpy(void* dest, const void* src, size_t len);
void* memset(void* dest, int byte, size_t len);
int memcmp(const void* ptr1, const void* ptr2, size_t len);
/* Received from https://code.woboq.org/userspace/glibc/string/strcmp.c.html*/
int strcmp (const char *p1, const char *p2);
int strncmp (const char *s1, const char *s2, size_t n);
size_t strlen (const char *str);
size_t strnlen(const char *str, size_t maxlen);
char * strcpy (char *dest, const char *src);
char * strncpy (char *s1, const char *s2, size_t n);
char * strncat (char *s1, const char *s2, size_t n);
#endif
|
keystone-enclave/FreeRTOS-Kernel | lib/utils/FreeRTOS-Plus-IO/include/FreeRTOS_IO.h | #include <stdlib.h>
#include <stdint.h>
#include "FreeRTOS.h"
#include "portmacro.h"
#ifndef FREERTOS_IO_H
#define FREERTOS_IO_H
/* The prototype to which callback functions used to process command line
commands must comply. pcWriteBuffer is a buffer into which the output from
executing the command can be written, xWriteBufferLen is the length, in bytes of
the pcWriteBuffer buffer, and pcCommandString is the entire string as input by
the user (from which parameters can be extracted).*/
typedef size_t (*pdREAD_CALLBACK)( void * const pvBuffer, const size_t xBytes );
typedef size_t (*pdWRITE_CALLBACK)( const void *pvBuffer, const size_t xBytes );
typedef BaseType_t (*pdIOCTL_CALLBACK)( uint32_t ulRequest, void *pvValue );
/* The structure that defines command line commands. A command line command
should be defined by declaring a const structure of this type. */
typedef struct xIO_DEVICE
{
const char * const pcDevice; /* The device name which open will use. */
const pdREAD_CALLBACK pxReadCallback; /* A pointer to the callback function that will perform a device read. */
const pdWRITE_CALLBACK pxWriteCallback; /* A pointer to the callback function that will perform a device read. */
const pdIOCTL_CALLBACK pxIoctlCallback; /* A pointer to the callback function that will perform a device read. */
} IO_Device_Definition_t;
/* Peripheral handles are void * for data hiding purposes. */
// typedef const void * Peripheral_Descriptor_t;
typedef const IO_Device_Definition_t * Peripheral_Descriptor_t;
Peripheral_Descriptor_t FreeRTOS_open( const char *pcPath, const uint32_t ulFlags );
size_t FreeRTOS_read( Peripheral_Descriptor_t const pxPeripheral, void * const pvBuffer, const size_t xBytes );
size_t FreeRTOS_write( Peripheral_Descriptor_t const pxPeripheral, const void *pvBuffer, const size_t xBytes );
BaseType_t FreeRTOS_ioctl( Peripheral_Descriptor_t const xPeripheral, uint32_t ulRequest, void *pvValue );
BaseType_t FreeRTOS_IORegisterDevice( const IO_Device_Definition_t * const pxDeviceToRegister );
#endif /* FREERTOS_IO_H */ |
keystone-enclave/FreeRTOS-Kernel | sdk/lib/include/eapp_utils.h | <reponame>keystone-enclave/FreeRTOS-Kernel
#ifndef __EAPP_H__
#define __EAPP_H__
#include <stdint.h>
#define SBI_CONSOLE_PUTCHAR 1
#define RET_EXIT 0
#define RET_YIELD 1
#define SBI_SWITCH_TASK 201
#define SBI_ATTEST_TASK 203
#define SBI_SEND_TASK 204
#define SBI_RECV_TASK 205
#define SBI_SM_UID 109
#define SBI_SM_MAILBOX_SEND 110
#define SBI_SM_MAILBOX_RECV 111
#define SBI_CALL(___which, ___arg0, ___arg1, ___arg2, ___arg3) \
({ \
register uintptr_t a0 __asm__("a0") = (uintptr_t)(___arg0); \
register uintptr_t a1 __asm__("a1") = (uintptr_t)(___arg1); \
register uintptr_t a2 __asm__("a2") = (uintptr_t)(___arg2); \
register uintptr_t a3 __asm__("a3") = (uintptr_t)(___arg3); \
register uintptr_t a7 __asm__("a7") = (uintptr_t)(___which); \
__asm__ volatile("ecall" \
: "+r"(a0) \
: "r"(a1), "r"(a2), "r"(a3), "r"(a7) \
: "memory"); \
a0; \
})
/* Lazy implementations until SBI is finalized */
#define SBI_CALL_0(___which) SBI_CALL(___which, 0, 0, 0, 0)
#define SBI_CALL_1(___which, ___arg0) SBI_CALL(___which, ___arg0, 0, 0, 0)
#define SBI_CALL_2(___which, ___arg0, ___arg1) \
SBI_CALL(___which, ___arg0, ___arg1, 0, 0)
#define SBI_CALL_3(___which, ___arg0, ___arg1, ___arg2) \
SBI_CALL(___which, ___arg0, ___arg1, ___arg2, 0)
#define SBI_CALL_4(___which, ___arg0, ___arg1, ___arg2, ___arg3) \
SBI_CALL(___which, ___arg0, ___arg1, ___arg2, ___arg3)
#define EAPP_ENTRY __attribute__((__section__(".text._start")))
void
sbi_putchar(char character);
void syscall_task_yield();
void syscall_task_return();
int sbi_recv(int task_id, void *msg, int size, uintptr_t yield);
int sbi_send(int task_id, void *msg, int size, uintptr_t yield);
#endif |
keystone-enclave/FreeRTOS-Kernel | main/src/agent_task.c | #include <FreeRTOS.h>
#include <task.h>
#include <printf.h>
#include <csr.h>
#include <sbi.h>
#include <syscall.h>
#include <enclave.h>
#include <elf.h>
#include <stdio.h>
#include <string.h>
#include <queue.h>
#include <rl.h>
#include <rl_config.h>
#include <timex.h>
static unsigned long my_rand_state = 1;
long rand()
{
my_rand_state = (my_rand_state * 1103515245 + 12345) % 2147483648;
return my_rand_state;
}
int finish = 0;
struct context
{
int reward;
int done;
struct pos next_pos;
};
int max_action(double *actions)
{
double max = 0.0;
int max_idx = 0;
for (int i = 0; i < N_ACTION; i++)
{
if (actions[i] > max)
{
max = actions[i];
max_idx = i;
}
}
return max_idx;
}
double max(double *actions)
{
double ret = 0.0;
for (int i = 0; i < N_ACTION; i++)
{
if (actions[i] > ret)
{
ret = actions[i];
}
}
return ret;
}
void print_q_table(double **q_table)
{
for (int i = 0; i < Q_STATE_N; i++)
{
for (int j = 0; j < Q_STATE_N; j++)
{
printf("| ");
for (int k = 0; k < N_ACTION; k++)
{
printf("%.2f ", q_table[i * Q_STATE_N + j][k]);
}
printf("| ");
}
printf("\n");
}
printf("\n");
}
void send_finish(QueueHandle_t send_queue){
struct send_action_args send_action;
send_action.msg_type = FINISH;
struct send_action_args *args = &send_action;
xQueueSend(send_queue, &args, QUEUE_MAX_DELAY);
}
void send_env_reset(QueueHandle_t send_queue, QueueHandle_t recv_queue){
struct send_action_args send_action;
send_action.msg_type = RESET;
struct send_action_args *args = &send_action;
xQueueSend(send_queue, &args, QUEUE_MAX_DELAY );
xQueueReceive(recv_queue, &args, QUEUE_MAX_DELAY);
}
void send_env_step(QueueHandle_t send_queue, QueueHandle_t recv_queue, struct probability_matrix_item *next, int action){
struct send_action_args send_action;
struct ctx ctx_recv;
send_action.action = action;
send_action.msg_type = STEP;
struct send_action_args *args = &send_action;
struct ctx *ctx_buf = &ctx_recv;
xQueueSend(send_queue, &args, QUEUE_MAX_DELAY);
xQueueReceive(recv_queue, &ctx_buf, QUEUE_MAX_DELAY);
next->ctx.done = ctx_buf->done;
next->ctx.new_state = ctx_buf->new_state;
next->ctx.reward = ctx_buf->reward;
}
#ifdef TA_TD_RL
static void agent_task(void *pvParameters)
{
cycles_t st = get_cycles();
printf("Agent Start Time: %u\n", st);
printf("Enter Agent\n");
int action;
int state;
int new_state;
int reward;
int done;
int rewards_current_episode = 0;
struct probability_matrix_item next;
double q_table[Q_STATE][N_ACTION] = {0};
double e_greedy = E_GREEDY;
int i, j;
for (i = 0; i < NUM_EPISODES; i++)
{
done = FALSE;
rewards_current_episode = 0;
state = 0;
send_env_reset(xDriverQueue, xAgentQueue);
for (j = 0; j < STEPS_PER_EP; j++)
{
float random_f = (float)rand() / (float)(RAND_MAX / 1.0);
if (random_f > e_greedy)
{
action = max_action(q_table[state]);
}
else
{
action = rand() % 4;
}
send_env_step(xDriverQueue, xAgentQueue, &next, action);
new_state = next.ctx.new_state;
reward = next.ctx.reward;
done = next.ctx.done;
q_table[state][action] = q_table[state][action] * (1.0 - LEARN_RATE) + LEARN_RATE * (reward + DISCOUNT * max(q_table[new_state]));
state = new_state;
rewards_current_episode += reward;
if (done == TRUE)
{
if (reward == 1)
{
if (e_greedy > E_GREEDY_F)
e_greedy *= E_GREEDY_DECAY;
#ifdef DEBUG
printf("You reached the goal!\n");
#endif
}
else
{
#ifdef DEBUG
printf("You fell in a hole!\n");
#endif
}
break;
}
}
if (i % 10 == 0)
{
printf("Episode: %d, Steps taken: %d, Reward: %d\n", i, j, rewards_current_episode);
}
}
send_finish(xDriverQueue);
cycles_t et = get_cycles();
printf("Agent End Time: %u\nAgent Duration: %u\n", et, et - st);
return_general();
}
#endif |
keystone-enclave/FreeRTOS-Kernel | sdk/fibonacci/fibonacci.c | //******************************************************************************
// Copyright (c) 2018, The Regents of the University of California (Regents).
// All Rights Reserved. See LICENSE for license details.
//------------------------------------------------------------------------------
#include "eapp_utils.h"
#include "printf.h"
char arr[1024] = {0};
unsigned long fibonacci_rec(unsigned long in){
if( in <= 1)
return 1;
else
return fibonacci_rec(in-1)+fibonacci_rec(in-2);
}
void EAPP_ENTRY eapp_entry(){
int arg = 35;
int ret = fibonacci_rec(arg);
printf("Enclave 1: %d\n", ret);
syscall_task_return();
} |
ctrl-shift-make/pypy | rpython/translator/c/src/support.c | <gh_stars>100-1000
#include "common_header.h"
#include <src/support.h>
#include <src/exception.h>
/************************************************************/
/*** C header subsection: support functions ***/
#include <stdio.h>
#include <stdlib.h>
/*** misc ***/
#define Sign_bit 0x80000000
#define NAN_WORD0 0x7ff80000
#define NAN_WORD1 0
#define PY_UINT32_T unsigned int
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define IEEE_8087
#endif
#ifdef IEEE_8087
#define word0(x) (x)->L[1]
#define word1(x) (x)->L[0]
#else
#define word0(x) (x)->L[0]
#define word1(x) (x)->L[1]
#endif
#define dval(x) (x)->d
typedef PY_UINT32_T ULong;
typedef union { double d; ULong L[2]; } U;
RPY_EXTERN
void RPyAssertFailed(const char* filename, long lineno,
const char* function, const char *msg) {
fprintf(stderr,
"PyPy assertion failed at %s:%ld:\n"
"in %s: %s\n",
filename, lineno, function, msg);
abort();
}
RPY_EXTERN
void RPyAbort(void) {
fprintf(stderr, "Invalid RPython operation (NULL ptr or bad array index)\n");
abort();
}
/* Return a 'standard' NaN value.
There are exactly two quiet NaNs that don't arise by 'quieting' signaling
NaNs (see IEEE 754-2008, section 6.2.1). If sign == 0, return the one whose
sign bit is cleared. Otherwise, return the one whose sign bit is set.
*/
double
_PyPy_dg_stdnan(int sign)
{
U rv;
word0(&rv) = NAN_WORD0;
word1(&rv) = NAN_WORD1;
if (sign)
word0(&rv) |= Sign_bit;
return dval(&rv);
}
|
ctrl-shift-make/pypy | rpython/translator/c/src/thread_gil.c | <filename>rpython/translator/c/src/thread_gil.c
/* Idea:
0. "The GIL" is a composite concept. There are two locks, and "the
GIL is locked" when both are locked.
1. The first lock is a simple global variable 'rpy_fastgil'. 0 means
unlocked, != 0 means unlocked (see point (3).
2. The second lock is a regular mutex called 'mutex_gil'. In the fast path,
it is never unlocked. Remember that "the GIL is unlocked" means that
either the first or the second lock is unlocked. It should never be the
case that both are unlocked at the same time.
3. Whenever the GIL is locked, rpy_fastgil contains the thread ID of the
thread holding the GIL. Note that there is a period of time in which
rpy_fastgil contains a thread ID, but the GIL itself is not locked
because the mutex in point (2) is unlocked: however, this happens only
inside the functions RPyGilAcquireSlowPath and RPyGilYieldThread. So, for
"general" code, you can easily check whether you are holding the GIL by
doing: rpy_fastgil == rthread.get_ident()
With this setup, we have a very fast way to release/acquire the GIL:
4. To release, you set rpy_fastgil=0; the invariant is that mutex_gil is
still locked at this point.
5. To acquire, you do a compare_and_swap on rpy_fastgil: if it was 0, then
it means the mutex_gil was already locked, so you have the GIL and you
are done. If rpy_fastgil was NOT 0, the compare_and_swap fails, so you
must go through the slow path in RPyGilAcquireSlowPath
This fast path is implemented in two places:
* RPyGilAcquire, to be called by general RPython code
* By native code emitted by the JIT around external calls; look e.g. to
rpython.jit.backend.x86.callbuilder:move_real_result_and_call_reacqgil_addr
The slow path works as follows:
6. Suppose there are many threads which want the GIL: at any point in time,
only one will actively try to acquire the GIL. This is called "the
stealer".
7. To become the stealer, you need to acquire 'mutex_gil_stealer'.
8. Once you are the stealer, you try to acquire the GIL by running the
following loop:
A. We try again to lock the GIL using the fast-path.
B. Try to acquire 'mutex_gil' with a timeout. If you succeed, you set
rpy_fastgil and you are done. If not, go to A.
To sum up, there are various possible patterns of interaction:
- I release the GIL using the fast-path: the GIL will be acquired by a
thread in the fast path in point (2) OR the fast path in point (8.A). Note
that this could be myself a bit later
- I want to explicitly yield the control to ANOTHER thread: I do this by
releasing mutex_gil: the stealer will acquire the GIL in point (8.B).
- I want the GIL and there are exactly 2 threads in total: I will
immediately become the stealer and go to point 8
- I want the GIL but there are more than 2 threads in total: I will spend
most of my time waiting for mutex_gil_stealer, and then go to point 8
*/
/* The GIL is initially released; see pypy_main_function(), which calls
RPyGilAcquire/RPyGilRelease. The point is that when building
RPython libraries, they can be a collection of regular functions that
also call RPyGilAcquire/RPyGilRelease; see test_standalone.TestShared.
*/
#include "src/threadlocal.h"
Signed rpy_fastgil = 0;
static Signed rpy_waiting_threads = -42; /* GIL not initialized */
static volatile int rpy_early_poll_n = 0;
static mutex1_t mutex_gil_stealer;
static mutex2_t mutex_gil;
static void rpy_init_mutexes(void)
{
mutex1_init(&mutex_gil_stealer);
mutex2_init_locked(&mutex_gil);
rpy_waiting_threads = 0;
}
void RPyGilAllocate(void)
{
if (rpy_waiting_threads < 0) {
assert(rpy_waiting_threads == -42);
rpy_init_mutexes();
#ifdef HAVE_PTHREAD_ATFORK
pthread_atfork(NULL, NULL, rpy_init_mutexes);
#endif
}
}
#define RPY_GIL_POKE_MIN 40
#define RPY_GIL_POKE_MAX 400
void RPyGilAcquireSlowPath(void)
{
/* Acquires the GIL. This is the slow path after which we failed
the compare-and-swap (after point (5)). Another thread is busy
with the GIL.
*/
if (1) { /* preserve commit history */
int n;
Signed old_waiting_threads;
if (rpy_waiting_threads < 0) {
/* <arigo> I tried to have RPyGilAllocate() called from
* here, but it fails occasionally on an example
* (2.7/test/test_threading.py). I think what occurs is
* that if one thread runs RPyGilAllocate(), it still
* doesn't have the GIL; then the other thread might fork()
* at precisely this moment, killing the first thread.
*/
fprintf(stderr, "Fatal RPython error: a thread is trying to wait "
"for the GIL, but the GIL was not initialized\n"
"(For PyPy, see "
"https://bitbucket.org/pypy/pypy/issues/2274)\n");
abort();
}
/* Register me as one of the threads that is actively waiting
for the GIL. The number of such threads is found in
rpy_waiting_threads. */
old_waiting_threads = atomic_increment(&rpy_waiting_threads);
/* Early polling: before entering the waiting queue, we check
a certain number of times if the GIL becomes free. The
motivation for this is issue #2341. Note that we do this
polling even if there are already other threads in the
queue, and one of thesee threads is the stealer. This is
because the stealer is likely sleeping right now. There
are use cases where the GIL will really be released very
soon after RPyGilAcquireSlowPath() is called, so it's worth
always doing this check.
To avoid falling into bad cases, we "randomize" the number
of iterations: we loop N times, where N is choosen between
RPY_GIL_POKE_MIN and RPY_GIL_POKE_MAX.
*/
n = rpy_early_poll_n * 2 + 1;
while (n >= RPY_GIL_POKE_MAX)
n -= (RPY_GIL_POKE_MAX - RPY_GIL_POKE_MIN);
rpy_early_poll_n = n;
while (n >= 0) {
n--;
if (old_waiting_threads != rpy_waiting_threads) {
/* If the number changed, it is because another thread
entered or left this function. In that case, stop
this loop: if another thread left it means the GIL
has been acquired by that thread; if another thread
entered there is no point in running the present
loop twice. */
break;
}
RPy_YieldProcessor();
RPy_CompilerMemoryBarrier();
if (!RPY_FASTGIL_LOCKED(rpy_fastgil)) {
if (_rpygil_acquire_fast_path()) {
/* We got the gil before entering the waiting
queue. In case there are other threads waiting
for the GIL, wake up the stealer thread now and
go to the waiting queue anyway, for fairness.
This will fall through if there are no other
threads waiting.
*/
assert(RPY_FASTGIL_LOCKED(rpy_fastgil));
mutex2_unlock(&mutex_gil);
break;
}
}
}
/* Now we are in point (3): mutex_gil might be released, but
rpy_fastgil might still contain an arbitrary tid */
/* Enter the waiting queue from the end. Assuming a roughly
first-in-first-out order, this will nicely give the threads
a round-robin chance.
*/
mutex1_lock(&mutex_gil_stealer);
mutex2_loop_start(&mutex_gil);
/* We are now the stealer thread. Steals! */
while (1) {
/* Busy-looping here. Try to look again if 'rpy_fastgil' is
released.
*/
if (!RPY_FASTGIL_LOCKED(rpy_fastgil)) {
/* point (8.A) */
if (_rpygil_acquire_fast_path()) {
/* we just acquired the GIL */
break;
}
}
/* Sleep for one interval of time. We may be woken up earlier
if 'mutex_gil' is released. Point (8.B)
*/
if (mutex2_lock_timeout(&mutex_gil, 0.0001)) { /* 0.1 ms... */
/* We arrive here if 'mutex_gil' was recently released
and we just relocked it.
*/
assert(RPY_FASTGIL_LOCKED(rpy_fastgil));
/* restore the invariant point (3) */
rpy_fastgil = _rpygil_get_my_ident();
break;
}
/* Loop back. */
}
atomic_decrement(&rpy_waiting_threads);
mutex2_loop_stop(&mutex_gil);
mutex1_unlock(&mutex_gil_stealer);
}
assert(RPY_FASTGIL_LOCKED(rpy_fastgil));
}
Signed RPyGilYieldThread(void)
{
/* can be called even before RPyGilAllocate(), but in this case,
'rpy_waiting_threads' will be -42. */
assert(RPY_FASTGIL_LOCKED(rpy_fastgil));
if (rpy_waiting_threads <= 0)
return 0;
/* Explicitly release the 'mutex_gil'.
*/
mutex2_unlock(&mutex_gil);
/* Now nobody has got the GIL, because 'mutex_gil' is released (but
rpy_fastgil is still locked). Call RPyGilAcquire(). It will
enqueue ourselves at the end of the 'mutex_gil_stealer' queue.
If there is no other waiting thread, it will fall through both
its mutex_lock() and mutex_lock_timeout() now. But that's
unlikely, because we tested above that 'rpy_waiting_threads > 0'.
*/
RPyGilAcquire();
return 1;
}
/********** for tests only **********/
/* These functions are usually defined as a macros RPyXyz() in thread.h
which get translated into calls to _RpyXyz(). But for tests we need
the real functions to exists in the library as well.
*/
#undef RPyGilRelease
RPY_EXTERN
void RPyGilRelease(void)
{
/* Releases the GIL in order to do an external function call.
We assume that the common case is that the function call is
actually very short, and optimize accordingly.
*/
_RPyGilRelease();
}
#undef RPyGilAcquire
RPY_EXTERN
void RPyGilAcquire(void)
{
_RPyGilAcquire();
}
#undef RPyFetchFastGil
RPY_EXTERN
Signed *RPyFetchFastGil(void)
{
return _RPyFetchFastGil();
}
#undef RPyGilGetHolder
RPY_EXTERN
Signed RPyGilGetHolder(void)
{
return _RPyGilGetHolder();
}
|
Ozypher/VULKANHANDIN | src/vectors.c | <gh_stars>0
#include "vectors.h"
#include <cmath>
#include <cfloat>
vec2 operator+(const vec2& l, const vec2& r){
return{ l.x + r.x + l.y + r.y };
} |
Ozypher/VULKANHANDIN | src/game.c | <filename>src/game.c
#include <SDL.h>
#include "simple_logger.h"
#include "gfc_vector.h"
#include "gfc_matrix.h"
#include "gf3d_entity.h"
#include "gf3d_vgraphics.h"
#include "gf3d_pipeline.h"
#include "gf3d_swapchain.h"
#include "gf3d_model.h"
#include "gf3d_camera.h"
#include "gf3d_texture.h"
#include "gf3d_cube.h"
void game_think(struct Entity_S* self){
//nothing yet
}
void game_update(struct Entity_S* self,Matrix4 modelMat2){
gfc_matrix_make_translation(modelMat2, self->position);
gfc_matrix_rotate(modelMat2, modelMat2, (self->rotation.x + 90)* GFC_DEGTORAD, vector3d(0, 0, 1));
}
void game_touch(struct Entity_S* self){
//nothing yet
}
int main(int argc, char *argv[])
{
int done = 0;
int a;
int i = 0;
Uint8 validate = 0;
const Uint8 * keys;
Uint32 bufferFrame = 0;
VkCommandBuffer commandBuffer;
Model *model;
Matrix4 modelMat;
Model *model2;
Matrix4 modelMat2;
float accelForward = 0.0;
struct Entity_S *ent;
Entity *building;
Entity *car;
float damage = 0;
Entity *powerup;
for (a = 1; a < argc; a++)
{
if (strcmp(argv[a], "-disable_validate") == 0)
{
validate = 0;
}
}
init_logger("gf3d.log");
slog("gf3d begin");
gf3d_vgraphics_init(
"gf3d", //program name
1920, //screen width
1080, //screen height
vector4d(0.51, 0.75, 1, 1),//background color
0, //fullscreen
validate //validation
);
// main game loop
slog("gf3d main loop begin");
model = gf3d_model_load("building");
model2 = gf3d_model_load("APC");
gfc_matrix_identity(modelMat);
gfc_matrix_make_translation(
modelMat,
vector3d(10, -15, -1));
gfc_matrix_rotate(
modelMat,
modelMat,
0.4,
vector3d(0, 0, 1));
gfc_matrix_identity(modelMat2);
gfc_matrix_make_translation(
modelMat2,
vector3d(10, 0, 0));
gf3d_entity_manager_init(10);
powerup = gf3d_entity_new();
car = gf3d_entity_new();
car->rotation = vector3d(0, 0, 0);
car->carNum = 1;
building = gf3d_entity_new();
building->health = 2000;
building->position = vector3d(10, -15, -1);
car->box.boxext = vector3d(5, 5, 5);
building->box.boxext = vector3d(40, 40, 40);
powerup->position = vector3d(15, 15, 15);
powerup->box.boxext = vector3d(5, 5, 5);
//gf3d_set_entity_bounding_box(car);
//gf3d_set_entity_bounding_box(building);
while (!done)
{
SDL_PumpEvents(); // update SDL's internal event structures
keys = SDL_GetKeyboardState(NULL); // get the keyboard state for this frame
//update game things here
SDL_Event event;
Vector3D forward;
car->box.boxpos = car->position;
building->box.boxpos = building->position;
if (gf3d_colliding(car->box, building->box)&& damage != 1){
slog("it worked.");
model2 = gf3d_model_load("APCDAM");
damage = 1;
}
if (gf3d_colliding(car->box, powerup->box)){
float decider = gfc_random();
if (decider >= 0.6){
powerup->poweruppickup = 3;
}
if (decider < 0.6 && decider >= 0.3){
powerup->poweruppickup = 2;
powerup->poweruptime = 3500;
}
if (decider < 0.3){
powerup->poweruppickup = 1;
powerup->poweruptime = 6000;
}
}
if (keys[SDL_SCANCODE_1]){
car->carNum = 1;
model2 = gf3d_model_load("APC");
if (car->carNum == 1){
car->health = 100;
car->accel = 0.00005;
car->maxspeed = 0.05;
car->grip = 0.000025;
car->armor = 10;
car->handling = 0.2;
car->guntype = 1;
}
}
if (keys[SDL_SCANCODE_2]){
car->carNum = 2;
model2 = gf3d_model_load("thump");
if (car->carNum == 2){
car->health = 50;
car->accel = 0.0001;
car->maxspeed = 0.09;
car->grip = 0.00005;
car->armor = 5;
car->handling = 0.4;
car->guntype = 2;
}
}
if (keys[SDL_SCANCODE_3]){
car->carNum = 3;
model2 = gf3d_model_load("tank");
if (car->carNum == 3){
car->health = 150;
car->accel = 0.00003;
car->maxspeed = 0.03;
car->grip = 0.00001;
car->armor = 15;
car->handling = 0.1;
car->guntype = 3;
}
}
if (car->accelForward > 0.000001){//'friction code goes here, have to change the float to a modifiable value in ent system
car->accelForward -= car->grip;
}
if (keys[SDL_SCANCODE_UP]){
if (car->accelForward <= car->maxspeed){
car->accelForward += car->accel;
}
if (car->accelForward > car->maxspeed){
car->accelForward -= 0.003;
}
// jiwa was here uwu
while (!(car->accelForward <= 0.000001)){
i = 1;
break;
}
//game_think(e);
i = 0;
}
if (keys[SDL_SCANCODE_DOWN]){
car->accelForward -= car->accel;
if (car->accelForward < -0.015){
car->accelForward += 0.006;
}
}
if (keys[SDL_SCANCODE_P]){
car->maxspeed = 100;
car->accel = 0.001;
}
if (keys[SDL_SCANCODE_I]){
car->scale = vector3d(2, 2, 2);
}
if (keys[SDL_SCANCODE_O]){
model2 = gf3d_model_load("APC");
}
if (keys[SDL_SCANCODE_SPACE]){
if (car->guntype == 0){
slog("click");
}
if (car->guntype == 1){
//machineguncode
}
if (car->guntype == 2){
//shotguncode
}
if (car->guntype == 3){
//rocketcode
}
}
//game_think(e);
game_update(car, modelMat2);
float handlingslow = car->handling / 2.5;
if (i = 1){
if (keys[SDL_SCANCODE_RIGHT] && (car->accelForward > 0.05 || car->carNum ==3)){
car->rotation.x -= car->handling;
}
if (keys[SDL_SCANCODE_LEFT] && (car->accelForward > 0.05 || car->carNum == 3)){
car->rotation.x += car->handling;
}
if (keys[SDL_SCANCODE_RIGHT] && car->accelForward < 0.05 && car->accelForward >0.00075){
car->rotation.x -= (handlingslow);
}
if (keys[SDL_SCANCODE_LEFT] && car->accelForward < 0.05 && car->accelForward >0.00075){
car->rotation.x += (handlingslow);
}
vector3d_angle_vectors(car->rotation, &forward, NULL, NULL);
vector3d_set_magnitude(&forward, car->accelForward);
vector3d_add(car->position, car->position, forward);
gfc_matrix_make_translation(modelMat2, car->position);
game_update(car, modelMat2);
}
// configure render command for graphics command pool
// for each mesh, get a command and configure it from the pool
bufferFrame = gf3d_vgraphics_render_begin();
gf3d_pipeline_reset_frame(gf3d_vgraphics_get_graphics_pipeline(), bufferFrame);
commandBuffer = gf3d_command_rendering_begin(bufferFrame);
gf3d_model_draw(model2, bufferFrame, commandBuffer, modelMat2,0);
gf3d_model_draw(model, bufferFrame, commandBuffer, modelMat,0);
gf3d_command_rendering_end(commandBuffer);
gf3d_vgraphics_render_end(bufferFrame);
if (keys[SDL_SCANCODE_ESCAPE])done = 1; // exit condition
}
vkDeviceWaitIdle(gf3d_vgraphics_get_default_logical_device());
//cleanup
slog("gf3d program end");
slog_sync();
return 0;
}
/*eol@eof*/
|
Ozypher/VULKANHANDIN | src/gf3d_entity.c | <reponame>Ozypher/VULKANHANDIN
#include <stdlib.h>
#include <string.h>
#include "gfc_list.h"
#include "simple_logger.h"
#include "gf3d_physics.h"
#include "gf3d_entity.h"
#include "gf3d_model.h"
#include "gf3d_collision.h"
typedef struct
{
Entity *entity_list;
Uint32 entity_max;
}EntityManager;
static EntityManager gf3d_entity_manager = { 0 };
void gf3d_entity_manager_close()
{
if (gf3d_entity_manager.entity_list != NULL)
{
free(gf3d_entity_manager.entity_list);
}
memset(&gf3d_entity_manager, 0, sizeof(EntityManager));
}
void gf3d_entity_manager_init(Uint32 entity_max)
{
gf3d_entity_manager.entity_list = (Entity*)gfc_allocate_array(sizeof(Entity), entity_max);
if (!gf3d_entity_manager.entity_list)
{
slog("failed to allocate entity list");
return;
}
gf3d_entity_manager.entity_max = entity_max;
slog("allocated entity list of size %u", sizeof(gf3d_entity_manager.entity_list));
atexit(gf3d_entity_manager_close);
}
Entity *gf3d_entity_new()
{
int i;
for (i = 0; i < gf3d_entity_manager.entity_max; i++)
{
slog("the _inuse flage for this entity is %u", gf3d_entity_manager.entity_list[i]._inuse);
if (gf3d_entity_manager.entity_list[i]._inuse)continue;
//. found a free entity
memset(&gf3d_entity_manager.entity_list[i], 0, sizeof(Entity));
gf3d_entity_manager.entity_list[i]._inuse = 1;
return &gf3d_entity_manager.entity_list[i];
}
slog("request for entity failed: all full up");
return NULL;
}
void gf3d_entity_free(Entity *self)
{
if (!self)
{
slog("self pointer is not valid");
return;
}
self->_inuse = 0;
free(self->entityMat);
gf3d_model_free(self->model);
if (self->data != NULL)
{
slog("warning: data not freed at entity free!");
}
}
Entity * gf3d_entity_init(char * model, Bool isEnvironment, int startFrame, int endFrame)
{
Entity * temp = gf3d_entity_new();
Model * m;
int numAnimations = endFrame - startFrame;
if (numAnimations <= 0)
{
//gf3d_model_free(model);
free(temp);
slog("frameRange is zero or negative: %i", numAnimations);
return NULL;
}
else if (numAnimations == 1)
{
m = gf3d_model_load(model);
}
else
{
//m = gf3d_model_load_animated(model, startFrame, endFrame);
}
slog("loaded model successfully");
Matrix4 * mat;
mat = (Matrix4 *)malloc(sizeof(Matrix4));
gfc_matrix_identity(*mat);
temp->model = m;
temp->entityMat = mat;
temp->isEnvironment2 = isEnvironment;
temp->name = model;
temp->lastUpdate = 0;
temp->velocity = vector3d(0, 0, 0);
temp->acceleration = vector3d(0, 0, 0);
temp->lastUpdate = 0;
slog("before");
gf3d_set_entity_bounding_box(temp);
slog("created bounding box successfully");
temp->numAnimations = numAnimations;
return temp;
}
void gf3d_entity_move(Entity * e, float x, float y, float z)
{
gfc_matrix_translate(e->entityMat, vector3d(x, 0, 0));
gfc_matrix_translate(e->entityMat, vector3d(0, y, 0));
gfc_matrix_translate(e->entityMat, vector3d(0, 0, z));
}
void gf3d_entity_draw(Entity * e, int frame, Uint32 bufferFrame, VkCommandBuffer commandBuffer)
{
gf3d_model_draw(e->model, bufferFrame, commandBuffer, (*e->entityMat), frame);
}
void gf3d_update_all_entities()
{
int i, j;
//List * collisions;
if (!gf3d_entity_manager.entity_list)
{
slog("failed to update entites list is empty");
return;
}
for (i = 0; i<gf3d_entity_manager.entity_max; i++)
{
Entity *temp = &gf3d_entity_manager.entity_list[i];
if (temp->_inuse == 0) continue;
update_entity(temp);
if (temp->isEnvironment2) continue;
//collisions = gfc_list_new();
//gf3d_collision_update_entity(temp);
}
}
void update_entity(Entity *e)
{
slog("update");
gf3d_physics_update(e);
//gf3d_update_entity_bounding_box(e);
}
void gf3d_set_entity_bounding_box(Entity *e)
{
// int i,numBB;
Mesh * m = e->model->mesh[0];
//slog("befiore2");
//e->entityBoundingBoxes = (BoundingBox*)gfc_allocate_array(sizeof(BoundingBox),1);
//BoundingBox b = e->entityBoundingBoxes;
gf3d_entity_sync_position(e);
//slog("positions synced");
e->width = m->max_vertices.x - m->min_vertices.x;
e->height = m->max_vertices.z - m->min_vertices.z;
e->depth = m->max_vertices.y - m->min_vertices.y;
slog("width =%f height =%f depth =%f", e->width, e->height, e->depth);
e->entityBoundingBoxes.boundingX1 = e->position.x - e->width / 2;
e->entityBoundingBoxes.boundingX2 = e->position.x + e->width / 2;
e->entityBoundingBoxes.boundingY1 = e->position.y - e->depth / 2;
e->entityBoundingBoxes.boundingY2 = e->position.y + e->depth / 2;
e->entityBoundingBoxes.boundingZ1 = e->position.z - e->height / 2;
e->entityBoundingBoxes.boundingZ2 = e->position.z + e->height / 2;
//gf3d_entity_setup_cube_plane(e);
//BoundingBox b = e->entityBoundingBoxes;
//gf3d_collision_print_collision_box(b);
}
/*void gf3d_update_entity_bounding_box(Entity *e)
{
int i, numBB;
Mesh * m = e->model->mesh[0];
gf3d_entity_sync_position(e);
e->width = m->max_vertices.x - m->min_vertices.x;
e->height = m->max_vertices.z - m->min_vertices.z;
e->depth = m->max_vertices.y - m->min_vertices.y;
//slog("width =%f height =%f depth =%f",e->width,e->height,e->depth);
e->entityBoundingBoxes.boundingX1 = e->position.x - e->width / 2;
e->entityBoundingBoxes.boundingX2 = e->position.x + e->width / 2;
e->entityBoundingBoxes.boundingY1 = e->position.y - e->depth / 2;
e->entityBoundingBoxes.boundingY2 = e->position.y + e->depth / 2;
e->entityBoundingBoxes.boundingZ1 = e->position.z - e->height / 2;
e->entityBoundingBoxes.boundingZ2 = e->position.z + e->height / 2;
//BoundingBox b = e->entityBoundingBoxes;
//gf3d_entity_setup_cube_plane(e);
//gf3d_collision_print_collision_box(b);
}
*/
Entity * gf3d_entity_manager_get_entity(int n)
{
return &gf3d_entity_manager.entity_list[n];
}
void gf3d_entity_sync_position(Entity *e)
{
e->position.x = (*e->entityMat)[3][0];
e->position.y = (*e->entityMat)[3][1];
e->position.z = (*e->entityMat)[3][2];
}
int gf3d_entity_manager_get_size()
{
return gf3d_entity_manager.entity_max;
}
void gf3d_entity_setup_cube_plane(Entity * e)
{
Mesh * m = e->model->mesh[0];
float x1, x2, y1, y2, z1, z2;
x1 = e->entityBoundingBoxes.boundingX1;
y1 = e->entityBoundingBoxes.boundingY1;
z1 = e->entityBoundingBoxes.boundingZ1;
x2 = e->entityBoundingBoxes.boundingX2;
y2 = e->entityBoundingBoxes.boundingY2;
z2 = e->entityBoundingBoxes.boundingZ2;
e->cp.xy1.planeVert[0] = vector3d(x1, y1, z1);
e->cp.xy1.planeVert[1] = vector3d(x2, y1, z1);
e->cp.xy1.planeVert[2] = vector3d(x2, y2, z1);
e->cp.xy1.planeVert[3] = vector3d(x1, y2, z1);
e->cp.xy2.planeVert[0] = vector3d(x1, y1, z2);
e->cp.xy2.planeVert[1] = vector3d(x2, y1, z2);
e->cp.xy2.planeVert[2] = vector3d(x2, y2, z2);
e->cp.xy2.planeVert[3] = vector3d(x1, y2, z2);
e->cp.xz1.planeVert[0] = vector3d(x1, y1, z1);
e->cp.xz1.planeVert[1] = vector3d(x2, y1, z1);
e->cp.xz1.planeVert[2] = vector3d(x2, y1, z2);
e->cp.xz1.planeVert[3] = vector3d(x1, y1, z2);
e->cp.xz2.planeVert[0] = vector3d(x1, y2, z1);
e->cp.xz2.planeVert[1] = vector3d(x2, y2, z1);
e->cp.xz2.planeVert[2] = vector3d(x2, y2, z2);
e->cp.xz2.planeVert[3] = vector3d(x1, y2, z2);
e->cp.yz1.planeVert[0] = vector3d(x1, y1, z1);
e->cp.yz1.planeVert[1] = vector3d(x1, y1, z2);
e->cp.yz1.planeVert[2] = vector3d(x1, y2, z2);
e->cp.yz1.planeVert[3] = vector3d(x1, y2, z1);
e->cp.yz2.planeVert[0] = vector3d(x2, y1, z1);
e->cp.yz2.planeVert[1] = vector3d(x2, y1, z2);
e->cp.yz2.planeVert[2] = vector3d(x2, y2, z2);
e->cp.yz2.planeVert[3] = vector3d(x2, y2, z1);
}
/*eol@eof*/ |
smlckz/pl0c | pl0c.c | #include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char __stdin[24];
static const char *__errstr;
static long __writestridx;
#ifndef HAVE_STRTONUM
#include "strtonum.c"
#endif
static const long CHECK_LHS = 0;
static const long CHECK_RHS = 1;
static const long CHECK_CALL = 2;
static const long TOK_IDENT = 'I';
static const long TOK_NUMBER = 'N';
static const long TOK_CONST = 'C';
static const long TOK_VAR = 'V';
static const long TOK_PROCEDURE = 'P';
static const long TOK_CALL = 'c';
static const long TOK_BEGIN = 'B';
static const long TOK_END = 'E';
static const long TOK_IF = 'i';
static const long TOK_THEN = 'T';
static const long TOK_ELSE = 'e';
static const long TOK_WHILE = 'W';
static const long TOK_DO = 'D';
static const long TOK_ODD = 'O';
static const long TOK_WRITEINT = 'w';
static const long TOK_WRITECHAR = 'H';
static const long TOK_WRITESTR = 'S';
static const long TOK_READINT = 'R';
static const long TOK_READCHAR = 'h';
static const long TOK_INTO = 'n';
static const long TOK_SIZE = 's';
static const long TOK_EXIT = 'X';
static const long TOK_AND = '&';
static const long TOK_OR = '|';
static const long TOK_NOT = '~';
static const long TOK_FORWARD = 'F';
static const long TOK_DOT = '.';
static const long TOK_EQUAL = '=';
static const long TOK_COMMA = ',';
static const long TOK_SEMICOLON = ';';
static const long TOK_ASSIGN = ':';
static const long TOK_HASH = '#';
static const long TOK_LTHAN = '<';
static const long TOK_GTHAN = '>';
static const long TOK_LTHANE = '{';
static const long TOK_GTHANE = '}';
static const long TOK_PLUS = '+';
static const long TOK_MINUS = '-';
static const long TOK_MULTIPLY = '*';
static const long TOK_DIVIDE = '/';
static const long TOK_MODULO = '%';
static const long TOK_LPAREN = '(';
static const long TOK_RPAREN = ')';
static const long TOK_LBRACK = '[';
static const long TOK_RBRACK = ']';
static const long TOK_STRING = '"';
static long raw[1048576];
static long loc;
static long symtab[1048576];
static long symtype;
static long token[256];
static long type;
static long expectedtype;
static long typetoprint;
static long str[256];
static long symtabcnt;
static long ret;
static long keywords[256];
static long keywordidx[64];
static long depth;
static long proc;
static long value;
static long line;
static void expression(void);
static void error(void) {
{
(void)fprintf(stdout, "\npl0c: error: ");
;
(void)fprintf(stdout, "%ld", (long)(line));
;
(void)fprintf(stdout, ": ");
;
;
};
}
static void setupkeywords(void) {
long i;
{
i = 0;
keywordidx[0] = TOK_CONST;
keywordidx[1] = i;
keywords[i + 0] = 'c';
keywords[i + 1] = 'o';
keywords[i + 2] = 'n';
keywords[i + 3] = 's';
keywords[i + 4] = 't';
keywords[i + 5] = '\0';
i = i + 6;
keywordidx[2] = TOK_VAR;
keywordidx[3] = i;
keywords[i + 0] = 'v';
keywords[i + 1] = 'a';
keywords[i + 2] = 'r';
keywords[i + 3] = '\0';
i = i + 4;
keywordidx[4] = TOK_PROCEDURE;
keywordidx[5] = i;
keywords[i + 0] = 'p';
keywords[i + 1] = 'r';
keywords[i + 2] = 'o';
keywords[i + 3] = 'c';
keywords[i + 4] = 'e';
keywords[i + 5] = 'd';
keywords[i + 6] = 'u';
keywords[i + 7] = 'r';
keywords[i + 8] = 'e';
keywords[i + 9] = '\0';
i = i + 10;
keywordidx[6] = TOK_CALL;
keywordidx[7] = i;
keywords[i + 0] = 'c';
keywords[i + 1] = 'a';
keywords[i + 2] = 'l';
keywords[i + 3] = 'l';
keywords[i + 4] = '\0';
i = i + 5;
keywordidx[8] = TOK_BEGIN;
keywordidx[9] = i;
keywords[i + 0] = 'b';
keywords[i + 1] = 'e';
keywords[i + 2] = 'g';
keywords[i + 3] = 'i';
keywords[i + 4] = 'n';
keywords[i + 5] = '\0';
i = i + 6;
keywordidx[10] = TOK_END;
keywordidx[11] = i;
keywords[i + 0] = 'e';
keywords[i + 1] = 'n';
keywords[i + 2] = 'd';
keywords[i + 3] = '\0';
i = i + 4;
keywordidx[12] = TOK_IF;
keywordidx[13] = i;
keywords[i + 0] = 'i';
keywords[i + 1] = 'f';
keywords[i + 2] = '\0';
i = i + 3;
keywordidx[14] = TOK_THEN;
keywordidx[15] = i;
keywords[i + 0] = 't';
keywords[i + 1] = 'h';
keywords[i + 2] = 'e';
keywords[i + 3] = 'n';
keywords[i + 4] = '\0';
i = i + 5;
keywordidx[16] = TOK_ELSE;
keywordidx[17] = i;
keywords[i + 0] = 'e';
keywords[i + 1] = 'l';
keywords[i + 2] = 's';
keywords[i + 3] = 'e';
keywords[i + 4] = '\0';
i = i + 5;
keywordidx[18] = TOK_WHILE;
keywordidx[19] = i;
keywords[i + 0] = 'w';
keywords[i + 1] = 'h';
keywords[i + 2] = 'i';
keywords[i + 3] = 'l';
keywords[i + 4] = 'e';
keywords[i + 5] = '\0';
i = i + 6;
keywordidx[20] = TOK_DO;
keywordidx[21] = i;
keywords[i + 0] = 'd';
keywords[i + 1] = 'o';
keywords[i + 2] = '\0';
i = i + 3;
keywordidx[22] = TOK_ODD;
keywordidx[23] = i;
keywords[i + 0] = 'o';
keywords[i + 1] = 'd';
keywords[i + 2] = 'd';
keywords[i + 3] = '\0';
i = i + 4;
keywordidx[24] = TOK_WRITEINT;
keywordidx[25] = i;
keywords[i + 0] = 'w';
keywords[i + 1] = 'r';
keywords[i + 2] = 'i';
keywords[i + 3] = 't';
keywords[i + 4] = 'e';
keywords[i + 5] = 'I';
keywords[i + 6] = 'n';
keywords[i + 7] = 't';
keywords[i + 8] = '\0';
i = i + 9;
keywordidx[26] = TOK_WRITECHAR;
keywordidx[27] = i;
keywords[i + 0] = 'w';
keywords[i + 1] = 'r';
keywords[i + 2] = 'i';
keywords[i + 3] = 't';
keywords[i + 4] = 'e';
keywords[i + 5] = 'C';
keywords[i + 6] = 'h';
keywords[i + 7] = 'a';
keywords[i + 8] = 'r';
keywords[i + 9] = '\0';
i = i + 10;
keywordidx[28] = TOK_WRITESTR;
keywordidx[29] = i;
keywords[i + 0] = 'w';
keywords[i + 1] = 'r';
keywords[i + 2] = 'i';
keywords[i + 3] = 't';
keywords[i + 4] = 'e';
keywords[i + 5] = 'S';
keywords[i + 6] = 't';
keywords[i + 7] = 'r';
keywords[i + 8] = '\0';
i = i + 9;
keywordidx[30] = TOK_READINT;
keywordidx[31] = i;
keywords[i + 0] = 'r';
keywords[i + 1] = 'e';
keywords[i + 2] = 'a';
keywords[i + 3] = 'd';
keywords[i + 4] = 'I';
keywords[i + 5] = 'n';
keywords[i + 6] = 't';
keywords[i + 7] = '\0';
i = i + 8;
keywordidx[32] = TOK_READCHAR;
keywordidx[33] = i;
keywords[i + 0] = 'r';
keywords[i + 1] = 'e';
keywords[i + 2] = 'a';
keywords[i + 3] = 'd';
keywords[i + 4] = 'C';
keywords[i + 5] = 'h';
keywords[i + 6] = 'a';
keywords[i + 7] = 'r';
keywords[i + 8] = '\0';
i = i + 9;
keywordidx[34] = TOK_INTO;
keywordidx[35] = i;
keywords[i + 0] = 'i';
keywords[i + 1] = 'n';
keywords[i + 2] = 't';
keywords[i + 3] = 'o';
keywords[i + 4] = '\0';
i = i + 5;
keywordidx[36] = TOK_SIZE;
keywordidx[37] = i;
keywords[i + 0] = 's';
keywords[i + 1] = 'i';
keywords[i + 2] = 'z';
keywords[i + 3] = 'e';
keywords[i + 4] = '\0';
i = i + 5;
keywordidx[38] = TOK_EXIT;
keywordidx[39] = i;
keywords[i + 0] = 'e';
keywords[i + 1] = 'x';
keywords[i + 2] = 'i';
keywords[i + 3] = 't';
keywords[i + 4] = '\0';
i = i + 5;
keywordidx[40] = TOK_AND;
keywordidx[41] = i;
keywords[i + 0] = 'a';
keywords[i + 1] = 'n';
keywords[i + 2] = 'd';
keywords[i + 3] = '\0';
i = i + 4;
keywordidx[42] = TOK_OR;
keywordidx[43] = i;
keywords[i + 0] = 'o';
keywords[i + 1] = 'r';
keywords[i + 2] = '\0';
i = i + 3;
keywordidx[44] = TOK_NOT;
keywordidx[45] = i;
keywords[i + 0] = 'n';
keywords[i + 1] = 'o';
keywords[i + 2] = 't';
keywords[i + 3] = '\0';
i = i + 4;
keywordidx[46] = TOK_MODULO;
keywordidx[47] = i;
keywords[i + 0] = 'm';
keywords[i + 1] = 'o';
keywords[i + 2] = 'd';
keywords[i + 3] = '\0';
i = i + 4;
keywordidx[48] = TOK_FORWARD;
keywordidx[49] = i;
keywords[i + 0] = 'f';
keywords[i + 1] = 'o';
keywords[i + 2] = 'r';
keywords[i + 3] = 'w';
keywords[i + 4] = 'a';
keywords[i + 5] = 'r';
keywords[i + 6] = 'd';
keywords[i + 7] = '\0';
i = i + 8;
keywordidx[50] = -1;
;
};
}
static void findkeyword(void) {
long keyword;
long k;
long i;
long eq;
{
keyword = 0;
ret = 1;
while ((ret * (keywordidx[keyword * 2] + 1)) != 0) {
type = keywordidx[keyword * 2];
k = keywordidx[keyword * 2 + 1];
eq = 1;
i = 0;
while ((eq * keywords[k]) != 0) {
if (keywords[k] != token[i]) {
eq = 0;
};
k = k + 1;
i = i + 1;
};
if (token[i] != '\0') {
eq = 0;
};
if (eq == 1) {
ret = 0;
};
keyword = keyword + 1;
;
};
;
};
}
static void cmpstr(void) {
long i;
{
i = 0;
ret = 0;
while (i < 256) {
if (token[i] != str[i]) {
ret = 1;
};
i = i + 1;
};
;
};
}
static void clrstr(void) {
long i;
{
i = 0;
while (i < 256) {
str[i] = '\0';
i = i + 1;
};
;
};
}
static void readin(void) {
long ch;
long i;
{
i = 0;
ch = (int)fgetc(stdin);
;
while (ch != -1) {
raw[i] = ch;
i = i + 1;
if (i == 1048577) {
{
error();
;
(void)fprintf(stdout, "file too big\n");
;
exit(1);
;
;
};
};
ch = (int)fgetc(stdin);
;
;
};
loc = 0;
};
}
static void comment(void) {
{
while (raw[loc] != '}') {
if (raw[loc] == '\0') {
{
error();
;
(void)fprintf(stdout, "unterminated comment\n");
;
exit(1);
;
;
};
} else {
if (raw[loc] == '\n') {
line = line + 1;
};
};
loc = loc + 1;
};
;
};
}
static void ident(void) {
long i;
long loop;
{
i = 0;
loop = 1;
while (i < 256) {
token[i] = '\0';
i = i + 1;
};
i = 0;
while (loop != 0) {
loop = 0;
if (raw[loc] >= 'A') {
{
if (raw[loc] <= 'Z') {
{
loop = 1;
token[i] = raw[loc];
i = i + 1;
if (i == 32) {
{
error();
;
(void)fprintf(stdout, "identifier too long\n");
;
exit(1);
;
};
};
;
};
};
;
};
};
if (loop == 0) {
{
if (raw[loc] >= 'a') {
{
if (raw[loc] <= 'z') {
{
loop = 1;
token[i] = raw[loc];
i = i + 1;
if (i == 32) {
{
error();
;
(void)fprintf(stdout, "identifier too long\n");
;
exit(1);
;
};
};
;
};
};
;
};
};
;
};
};
if (loop == 0) {
{
if (raw[loc] >= '0') {
{
if (raw[loc] <= '9') {
{
loop = 1;
token[i] = raw[loc];
i = i + 1;
if (i == 32) {
{
error();
;
(void)fprintf(stdout, "identifier too long\n");
;
exit(1);
;
};
};
;
};
};
;
};
};
;
};
};
if (loop == 0) {
{
if (raw[loc] == '_') {
{
loop = 1;
token[i] = raw[loc];
i = i + 1;
if (i == 32) {
{
error();
;
(void)fprintf(stdout, "identifier too long\n");
;
exit(1);
;
};
};
;
};
};
;
};
};
if (loop != 0) {
loc = loc + 1;
};
;
};
loc = loc - 1;
findkeyword();
;
if (ret != 0) {
type = TOK_IDENT;
};
;
};
}
static void number(void) {
long i;
long loop;
{
i = 0;
loop = 1;
value = 0;
while (i < 256) {
token[i] = '\0';
i = i + 1;
};
i = 0;
while (loop != 0) {
loop = 0;
if (raw[loc] >= '0') {
{
if (raw[loc] <= '9') {
{
loop = 1;
token[i] = raw[loc];
i = i + 1;
if (i == 21) {
{
error();
;
(void)fprintf(stdout, "number too long\n");
;
exit(1);
;
;
};
};
value = value * 10;
value = value + (raw[loc] - '0');
};
};
;
};
};
if (loop == 0) {
{
if (raw[loc] == '_') {
loop = 1;
};
;
};
};
if (loop != 0) {
loc = loc + 1;
};
;
};
loc = loc - 1;
type = TOK_NUMBER;
;
};
}
static void string(void) {
long i;
long loop;
{
i = 0;
loop = 1;
while (i < 256) {
token[i] = '\0';
i = i + 1;
};
i = 1;
type = TOK_STRING;
loc = loc + 1;
token[0] = '"';
while (loop != 0) {
if (raw[loc] == '\'') {
{
loc = loc + 1;
if (raw[loc] != '\'') {
loop = 0;
} else {
{
token[i] = '\\';
i = i + 1;
if (i == 255) {
{
error();
;
(void)fprintf(stdout, "string too long\n");
;
exit(1);
;
;
};
};
token[i] = raw[loc];
i = i + 1;
if (i == 255) {
{
error();
;
(void)fprintf(stdout, "number too long\n");
;
exit(1);
;
;
};
};
;
};
};
;
};
} else {
if (raw[loc] == '\n') {
{
error();
;
(void)fprintf(stdout, "unterminated string\n");
;
exit(1);
;
;
};
} else {
if (raw[loc] == '\0') {
{
error();
;
(void)fprintf(stdout, "unterminated string\n");
;
exit(1);
;
;
};
} else {
{
token[i] = raw[loc];
i = i + 1;
if (i == 255) {
{
error();
;
(void)fprintf(stdout, "string too long\n");
;
exit(1);
;
;
};
};
;
};
};
};
};
if (loop != 0) {
loc = loc + 1;
};
;
};
loc = loc - 1;
token[i] = '"';
if (i == 2) {
{
token[0] = '\'';
token[2] = '\'';
type = TOK_NUMBER;
};
} else {
if (i == 3) {
{
if (token[1] == '\\') {
{
token[0] = '\'';
token[3] = '\'';
type = TOK_NUMBER;
};
};
;
};
};
};
;
};
}
static void lex(void) {
long i;
long whitespace;
long isident;
long isnumber;
{
isident = 0;
isnumber = 0;
i = 0;
whitespace = 1;
while (whitespace == 1) {
if (raw[loc] == ' ') {
{
whitespace = 1;
loc = loc + 1;
;
};
} else {
if (raw[loc] == '\t') {
{
whitespace = 1;
loc = loc + 1;
;
};
} else {
if (raw[loc] == '\n') {
{
whitespace = 1;
loc = loc + 1;
line = line + 1;
;
};
} else {
whitespace = 0;
};
};
};
};
if (raw[loc] >= 'A') {
{
if (raw[loc] <= 'Z') {
{
isident = 1;
ident();
;
;
};
};
;
};
};
if (isident == 0) {
{
if (raw[loc] >= 'a') {
{
if (raw[loc] <= 'z') {
{
isident = 1;
ident();
;
;
};
};
;
};
};
;
};
};
if (isident == 0) {
{
if (raw[loc] == '_') {
{
isident = 1;
ident();
;
;
};
};
;
};
};
if (isident == 0) {
{
if (raw[loc] >= '0') {
{
if (raw[loc] <= '9') {
{
isnumber = 1;
number();
;
;
};
};
;
};
};
;
};
};
if (isident == 0) {
{
if (isnumber == 0) {
{
if (raw[loc] == '{') {
{
comment();
;
type = -1;
};
} else {
if (raw[loc] == '.') {
type = TOK_DOT;
} else {
if (raw[loc] == '=') {
type = TOK_EQUAL;
} else {
if (raw[loc] == ',') {
type = TOK_COMMA;
} else {
if (raw[loc] == ';') {
type = TOK_SEMICOLON;
} else {
if (raw[loc] == '#') {
type = TOK_HASH;
} else {
if (raw[loc] == '+') {
type = TOK_PLUS;
} else {
if (raw[loc] == '-') {
type = TOK_MINUS;
} else {
if (raw[loc] == '*') {
type = TOK_MULTIPLY;
} else {
if (raw[loc] == '/') {
type = TOK_DIVIDE;
} else {
if (raw[loc] == '%') {
type = TOK_MODULO;
} else {
if (raw[loc] == '(') {
type = TOK_LPAREN;
} else {
if (raw[loc] == ')') {
type = TOK_RPAREN;
} else {
if (raw[loc] == '[') {
type = TOK_LBRACK;
} else {
if (raw[loc] == ']') {
type = TOK_RBRACK;
} else {
if (raw[loc] == '<') {
{
loc = loc + 1;
if (raw[loc] == '=') {
type = TOK_LTHANE;
} else {
if (raw[loc] == '>') {
type = TOK_HASH;
} else {
{
loc = loc - 1;
type = TOK_LTHAN;
};
};
};
;
};
} else {
if (raw[loc] == '>') {
{
loc = loc + 1;
if (raw[loc] == '=') {
type = TOK_GTHANE;
} else {
{
loc = loc - 1;
type = TOK_GTHAN;
};
};
;
};
} else {
if (raw[loc] == ':') {
{
loc = loc + 1;
if (raw[loc] != '=') {
{
error();
;
(void)fprintf(
stdout,
"unknown token: \'");
;
(void)fprintf(
stdout, "%c",
(unsigned char)(raw[loc]));
;
(void)fprintf(stdout,
"\'\n");
;
exit(1);
;
;
};
};
type = TOK_ASSIGN;
;
};
} else {
if (raw[loc] == '\'') {
{
string();
;
;
};
} else {
if (raw[loc] == '\0') {
type = 0;
} else {
{
error();
;
(void)fprintf(
stdout,
"unknown token: \'");
;
(void)fprintf(
stdout, "%c",
(unsigned char)(raw[loc]));
;
(void)fprintf(stdout,
"\'\n");
;
exit(1);
;
;
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
;
};
};
;
};
};
loc = loc + 1;
};
}
static void cg_array(void) {
{
(void)fprintf(stdout, "%c", (unsigned char)('['));
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "%c", (unsigned char)(']'));
;
};
}
static void cg_call(void) {
{
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "();\n");
;
};
}
static void cg_closeblock(void) {
{
(void)fprintf(stdout, ";}\n");
;
};
}
static void cg_const(void) {
{
if (proc == 0) {
(void)fprintf(stdout, "static ");
;
};
(void)fprintf(stdout, "const long ");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "%c", (unsigned char)('='));
;
};
}
static void cg_crlf(void) {
{
(void)fprintf(stdout, "%c", (unsigned char)('\n'));
;
};
}
static void cg_end(void) {
{
(void)fprintf(stdout, "/* PL/0 compiler 1.0.2 */\n");
;
};
}
static void cg_epilogue(void) {
{
(void)fprintf(stdout, "%c", (unsigned char)(';'));
;
if (proc == 0) {
(void)fprintf(stdout, "\nreturn 0;");
;
};
(void)fprintf(stdout, "\n}\n\n");
;
};
}
static void cg_exit(void) {
{
(void)fprintf(stdout, "exit(");
;
};
}
static void cg_forward(void) {
{
(void)fprintf(stdout, "static void ");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "(void);\n");
;
};
}
static void cg_init(void) {
{
(void)fprintf(stdout, "#include <limits.h>\n");
;
(void)fprintf(stdout, "#include <stdio.h>\n");
;
(void)fprintf(stdout, "#include <stdlib.h>\n");
;
(void)fprintf(stdout, "#include <string.h>\n\n");
;
(void)fprintf(stdout, "static char __stdin[24];\n");
;
(void)fprintf(stdout, "static const char *__errstr;\n\n");
;
(void)fprintf(stdout, "static long __writestridx;\n\n");
;
(void)fprintf(stdout, "#ifndef HAVE_STRTONUM\n");
;
(void)fprintf(stdout, "#include ");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, "strtonum.c");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, "%c", (unsigned char)('\n'));
;
(void)fprintf(stdout, "#endif\n\n");
;
};
}
static void cg_odd(void) {
{
(void)fprintf(stdout, ")&1");
;
};
}
static void cg_procedure(void) {
{
if (proc == 0) {
{
(void)fprintf(stdout, "int\n");
;
(void)fprintf(stdout, "main(int argc, char *argv[])\n");
;
};
} else {
{
(void)fprintf(stdout, "static void\n");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "(void)\n");
;
};
};
(void)fprintf(stdout, "{\n");
;
};
}
static void cg_readchar(void) {
{
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "=(int) fgetc(stdin);");
;
};
}
static void cg_readint(void) {
{
(void)fprintf(stdout, "(void) fgets(__stdin, sizeof(__stdin), stdin);\n");
;
(void)fprintf(stdout, "if(__stdin[strlen(__stdin) - 1] == \'\\n\')");
;
(void)fprintf(stdout, "__stdin[strlen(__stdin) - 1] = \'\\0\';");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(
stdout, "=(long) strtonum(__stdin, LONG_MIN, LONG_MAX, &__errstr);\n");
;
(void)fprintf(stdout, "if(__errstr!=NULL){");
;
(void)fprintf(stdout, "(void) fprintf(stderr, ");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, "invalid number: %%s");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, ", __stdin);\n");
;
(void)fprintf(stdout, "exit(1);");
;
(void)fprintf(stdout, "%c", (unsigned char)('}'));
;
};
}
static void cg_rparen(void) {
{
(void)fprintf(stdout, "%c", (unsigned char)(')'));
;
};
}
static void cg_semicolon(void) {
{
(void)fprintf(stdout, ";\n");
;
};
}
static void cg_symbol(void) {
{
if (type == TOK_IDENT) {
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
} else {
if (type == TOK_NUMBER) {
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
} else {
if (type == TOK_BEGIN) {
(void)fprintf(stdout, "{\n");
;
} else {
if (type == TOK_END) {
(void)fprintf(stdout, ";\n}\n");
;
} else {
if (type == TOK_IF) {
(void)fprintf(stdout, "if(");
;
} else {
if (type == TOK_THEN) {
(void)fprintf(stdout, "){");
;
} else {
if (type == TOK_DO) {
(void)fprintf(stdout, "%c", (unsigned char)(')'));
;
} else {
if (type == TOK_ELSE) {
(void)fprintf(stdout, ";}else{");
;
} else {
if (type == TOK_ODD) {
(void)fprintf(stdout, "%c", (unsigned char)('('));
;
} else {
if (type == TOK_WHILE) {
(void)fprintf(stdout, "while(");
;
} else {
if (type == TOK_EQUAL) {
(void)fprintf(stdout, "==");
;
} else {
if (type == TOK_ASSIGN) {
(void)fprintf(stdout, "%c", (unsigned char)('='));
;
} else {
if (type == TOK_HASH) {
(void)fprintf(stdout, "!=");
;
} else {
if (type == TOK_LTHANE) {
(void)fprintf(stdout, "<=");
;
} else {
if (type == TOK_GTHANE) {
(void)fprintf(stdout, ">=");
;
} else {
(void)fprintf(stdout, "%c",
(unsigned char)(type));
;
};
};
};
};
};
};
};
};
};
};
};
};
};
};
};
;
};
}
static void cg_var(void) {
{
if (proc == 0) {
(void)fprintf(stdout, "static ");
;
};
(void)fprintf(stdout, "long ");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
};
}
static void cg_writechar(void) {
{
(void)fprintf(stdout, "(void) fprintf(stdout, ");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, "%%c");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, ", (unsigned char) (");
;
};
}
static void cg_writeint(void) {
{
(void)fprintf(stdout, "(void) fprintf(stdout, ");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, "%%ld");
;
(void)fprintf(stdout, "%c", (unsigned char)('"'));
;
(void)fprintf(stdout, ", (long) (");
;
};
}
static void cg_writestr(void) {
long i;
long n;
long p;
long save;
{
i = 0;
save = 0;
if (type == TOK_IDENT) {
{
while (i < symtabcnt) {
clrstr();
;
n = 0;
p = 35 * i;
while (n < 32) {
str[n] = symtab[p];
p = p + 1;
n = n + 1;
};
cmpstr();
;
if (ret == 0) {
save = 35 * i;
};
i = i + 1;
};
if (save == 0) {
{
error();
;
(void)fprintf(stdout, "undefined symbol: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
if (symtab[save + 34] == 0) {
{
error();
;
(void)fprintf(stdout, "writeStr requires an array\n");
;
exit(1);
;
;
};
};
(void)fprintf(stdout, "__writestridx = 0;\n");
;
(void)fprintf(stdout, "while(");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "[__writestridx]!=\'\\0\'&&__writestridx<");
;
(void)fprintf(stdout, "%ld", (long)(symtab[save + 34]));
;
(void)fprintf(stdout, ")\n");
;
(void)fprintf(stdout, "(void)fputc((unsigned char)");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "[__writestridx++],stdout);\n");
;
};
} else {
{
(void)fprintf(stdout, "(void)fprintf(stdout, ");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, ");\n");
;
};
};
;
};
}
static void next(void) {
{
lex();
;
while (type == -1)
lex();
;
;
};
}
static void printtype(void) {
long kw;
long i;
long c;
long loop;
{
if (typetoprint == TOK_IDENT) {
(void)fprintf(stdout, "an identifier");
;
} else {
if (typetoprint == TOK_NUMBER) {
(void)fprintf(stdout, "a number");
;
} else {
if (typetoprint == TOK_STRING) {
(void)fprintf(stdout, "a string");
;
} else {
if (typetoprint == TOK_ASSIGN) {
(void)fprintf(stdout, " \':=\' ");
;
} else {
if (typetoprint == TOK_HASH) {
(void)fprintf(stdout, " \'#\' or \'<>\' ");
;
} else {
if (typetoprint == TOK_LTHANE) {
(void)fprintf(stdout, " \'<=\' ");
;
} else {
if (typetoprint == TOK_GTHANE) {
(void)fprintf(stdout, " \'>=\' ");
;
} else {
if (typetoprint == TOK_MODULO) {
{
(void)fprintf(stdout, " \'");
;
(void)fprintf(stdout, "%c", (unsigned char)('%'));
;
(void)fprintf(stdout, "\' or \'mod\' ");
;
;
};
} else {
{
kw = 0;
loop = 1;
while ((loop * (keywordidx[kw * 2] + 1)) != 0) {
if (typetoprint == keywordidx[kw * 2]) {
{
loop = 0;
;
};
};
kw = kw + 1;
;
};
if (loop == 0) {
{
i = keywordidx[kw * 2 + 1];
c = keywords[i];
while (c != '\0') {
(void)fprintf(stdout, "%c", (unsigned char)(c));
;
i = i + 1;
c = keywords[i];
;
};
;
};
} else {
{
(void)fprintf(stdout, " \'");
;
(void)fprintf(stdout, "%c",
(unsigned char)(typetoprint));
;
(void)fprintf(stdout, "\' ");
;
;
};
};
;
};
};
};
};
};
};
};
};
};
;
};
}
static void expect(void) {
{
if (type != expectedtype) {
{
error();
;
(void)fprintf(stdout, "syntax error: expected ");
;
typetoprint = expectedtype;
printtype();
;
(void)fprintf(stdout, " but got ");
;
typetoprint = type;
printtype();
;
(void)fprintf(stdout, "%c", (unsigned char)('\n'));
;
exit(1);
;
;
};
};
next();
;
;
};
}
static void expect_begin(void) {
{
expectedtype = TOK_BEGIN;
expect();
;
;
};
}
static void expect_call(void) {
{
expectedtype = TOK_CALL;
expect();
;
;
};
}
static void expect_const(void) {
{
expectedtype = TOK_CONST;
expect();
;
;
};
}
static void expect_do(void) {
{
expectedtype = TOK_DO;
expect();
;
;
};
}
static void expect_else(void) {
{
expectedtype = TOK_ELSE;
expect();
;
;
};
}
static void expect_end(void) {
{
expectedtype = TOK_END;
expect();
;
;
};
}
static void expect_exit(void) {
{
expectedtype = TOK_EXIT;
expect();
;
;
};
}
static void expect_forward(void) {
{
expectedtype = TOK_FORWARD;
expect();
;
;
};
}
static void expect_ident(void) {
{
expectedtype = TOK_IDENT;
expect();
;
;
};
}
static void expect_if(void) {
{
expectedtype = TOK_IF;
expect();
;
;
};
}
static void expect_into(void) {
{
expectedtype = TOK_INTO;
expect();
;
;
};
}
static void expect_number(void) {
{
expectedtype = TOK_NUMBER;
expect();
;
;
};
}
static void expect_odd(void) {
{
expectedtype = TOK_ODD;
expect();
;
;
};
}
static void expect_procedure(void) {
{
expectedtype = TOK_PROCEDURE;
expect();
;
;
};
}
static void expect_readchar(void) {
{
expectedtype = TOK_READCHAR;
expect();
;
;
};
}
static void expect_readint(void) {
{
expectedtype = TOK_READINT;
expect();
;
;
};
}
static void expect_size(void) {
{
expectedtype = TOK_SIZE;
expect();
;
;
};
}
static void expect_string(void) {
{
expectedtype = TOK_STRING;
expect();
;
;
};
}
static void expect_then(void) {
{
expectedtype = TOK_THEN;
expect();
;
;
};
}
static void expect_var(void) {
{
expectedtype = TOK_VAR;
expect();
;
;
};
}
static void expect_while(void) {
{
expectedtype = TOK_WHILE;
expect();
;
;
};
}
static void expect_writechar(void) {
{
expectedtype = TOK_WRITECHAR;
expect();
;
;
};
}
static void expect_writeint(void) {
{
expectedtype = TOK_WRITEINT;
expect();
;
;
};
}
static void expect_writestr(void) {
{
expectedtype = TOK_WRITESTR;
expect();
;
;
};
}
static void assign(void) {
{
expectedtype = TOK_ASSIGN;
expect();
;
;
};
}
static void comma(void) {
{
expectedtype = TOK_COMMA;
expect();
;
;
};
}
static void dot(void) {
{
expectedtype = TOK_DOT;
expect();
;
;
};
}
static void equal(void) {
{
expectedtype = TOK_EQUAL;
expect();
;
;
};
}
static void lbrack(void) {
{
expectedtype = TOK_LBRACK;
expect();
;
;
};
}
static void lparen(void) {
{
expectedtype = TOK_LPAREN;
expect();
;
;
};
}
static void rbrack(void) {
{
expectedtype = TOK_RBRACK;
expect();
;
;
};
}
static void rparen(void) {
{
expectedtype = TOK_RPAREN;
expect();
;
;
};
}
static void semicolon(void) {
{
expectedtype = TOK_SEMICOLON;
expect();
;
;
};
}
static void addsymbol(void) {
long i;
long n;
{
i = symtabcnt * 35;
n = 0;
while (n < 32) {
symtab[i] = token[n];
i = i + 1;
n = n + 1;
};
symtab[i] = symtype;
i = i + 1;
symtab[i] = depth - 1;
i = i + 1;
symtab[i] = 0;
symtabcnt = symtabcnt + 1;
if (symtabcnt == 29961) {
{
error();
;
(void)fprintf(stdout, "symbol table exhausted\n");
;
exit(1);
;
;
};
};
;
};
}
static void arraycheck(void) {
long i;
long n;
long p;
long save;
{
i = 0;
save = 0;
while (i < symtabcnt) {
clrstr();
;
n = 0;
p = 35 * i;
while (n < 32) {
str[n] = symtab[p];
p = p + 1;
n = n + 1;
};
cmpstr();
;
if (ret == 0) {
save = 35 * i;
};
i = i + 1;
};
if (save == 0) {
{
error();
;
(void)fprintf(stdout, "undefined symbol: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
if (symtab[save + 34] == 0) {
{
error();
;
(void)fprintf(stdout, "not an array: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
;
};
}
static void arraysize(void) {
long i;
{
i = 0;
i = 35 * (symtabcnt - 1);
if (symtab[i + 32] != TOK_VAR) {
{
error();
;
(void)fprintf(stdout, "arrays must be declared with \"var\": \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
symtab[i + 34] = value;
if (value < 1) {
{
error();
;
(void)fprintf(stdout, "invalid array size: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
;
};
}
static void initsymtab(void) {
long i;
{
symtab[0] = 'm';
symtab[1] = 'a';
symtab[2] = 'i';
symtab[3] = 'n';
i = 4;
while (i < 32) {
symtab[i] = '\0';
i = i + 1;
};
symtab[i] = TOK_PROCEDURE;
i = i + 1;
symtab[i] = 0;
i = i + 1;
symtab[i] = 0;
symtabcnt = 1;
};
}
static void symcheck(void) {
long i;
long n;
long p;
long save;
{
i = 0;
save = 0;
while (i < symtabcnt) {
clrstr();
;
n = 0;
p = 35 * i;
while (n < 32) {
str[n] = symtab[p];
p = p + 1;
n = n + 1;
};
cmpstr();
;
if (ret == 0) {
save = 35 * i;
};
i = i + 1;
};
if (save == 0) {
{
error();
;
(void)fprintf(stdout, "undefined symbol: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
if (symtype == CHECK_LHS) {
{
if (symtab[save + 32] != TOK_VAR) {
{
error();
;
(void)fprintf(stdout, "must be a variable: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
;
};
} else {
if (symtype == CHECK_RHS) {
{
if (symtab[save + 32] == TOK_PROCEDURE) {
{
error();
;
(void)fprintf(stdout, "must not be a procedure: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
} else {
if (symtab[save + 32] == TOK_FORWARD) {
{
error();
;
(void)fprintf(stdout, "must not be a procedure: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
};
;
};
} else {
if (symtype == CHECK_CALL) {
{
if (symtab[save + 32] != TOK_PROCEDURE) {
{
if (symtab[save + 32] != TOK_FORWARD) {
{
error();
;
(void)fprintf(stdout, "must be a procedure: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++],
stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
;
};
};
;
};
};
};
};
;
};
}
static void destroysymbols(void) {
long i;
long n;
{
i = 35 * (symtabcnt - 1);
while (symtab[i + 32] != TOK_PROCEDURE) {
n = 0;
while (n < 35) {
symtab[i] = '\0';
i = i + 1;
n = n + 1;
};
symtabcnt = symtabcnt - 1;
i = 35 * (symtabcnt - 1);
};
;
};
}
static void factor(void) {
{
if (type == TOK_IDENT) {
{
symtype = CHECK_RHS;
symcheck();
;
cg_symbol();
;
expect_ident();
;
if (type == TOK_LBRACK) {
{
arraycheck();
;
cg_symbol();
;
lbrack();
;
expression();
;
if (type == TOK_RBRACK) {
{
cg_symbol();
;
;
};
};
rbrack();
;
;
};
};
;
};
} else {
if (type == TOK_NUMBER) {
{
cg_symbol();
;
expect_number();
;
};
} else {
if (type == TOK_LPAREN) {
{
cg_symbol();
;
lparen();
;
expression();
;
if (type == TOK_RPAREN) {
{
cg_symbol();
;
;
};
};
rparen();
;
;
};
};
};
};
;
};
}
static void term(void) {
long loop;
{
loop = 1;
factor();
;
while (loop != 0) {
loop = 0;
if (type == TOK_MULTIPLY) {
{
loop = 1;
cg_symbol();
;
next();
;
factor();
;
;
};
} else {
if (type == TOK_DIVIDE) {
{
loop = 1;
cg_symbol();
;
next();
;
factor();
;
;
};
} else {
if (type == TOK_MODULO) {
{
loop = 1;
cg_symbol();
;
next();
;
factor();
;
;
};
} else {
if (type == TOK_AND) {
{
loop = 1;
cg_symbol();
;
next();
;
factor();
;
;
};
};
};
};
};
;
};
;
};
}
static void expression(void) {
long loop;
{
loop = 1;
if (type == TOK_PLUS) {
{
cg_symbol();
;
next();
;
};
} else {
if (type == TOK_MINUS) {
{
cg_symbol();
;
next();
;
};
};
};
term();
;
while (loop != 0) {
loop = 0;
if (type == TOK_PLUS) {
{
loop = 1;
cg_symbol();
;
next();
;
term();
;
;
};
} else {
if (type == TOK_MINUS) {
{
loop = 1;
cg_symbol();
;
next();
;
term();
;
;
};
} else {
if (type == TOK_OR) {
{
loop = 1;
cg_symbol();
;
next();
;
term();
;
;
};
};
};
};
;
};
;
};
}
static void condition(void) {
{
if (type == TOK_ODD) {
{
cg_symbol();
;
expect_odd();
;
expression();
;
cg_odd();
;
};
} else {
{
expression();
;
if (type == TOK_EQUAL) {
{
cg_symbol();
;
next();
;
};
} else {
if (type == TOK_HASH) {
{
cg_symbol();
;
next();
;
};
} else {
if (type == TOK_LTHAN) {
{
cg_symbol();
;
next();
;
};
} else {
if (type == TOK_GTHAN) {
{
cg_symbol();
;
next();
;
};
} else {
if (type == TOK_LTHANE) {
{
cg_symbol();
;
next();
;
};
} else {
if (type == TOK_GTHANE) {
{
cg_symbol();
;
next();
;
};
} else {
{
error();
;
(void)fprintf(stdout, "invalid conditional: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' &&
__writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++],
stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
};
};
};
};
};
expression();
;
;
};
};
;
};
}
static void statement(void) {
{
if (type == TOK_IDENT) {
{
symtype = CHECK_LHS;
symcheck();
;
cg_symbol();
;
expect_ident();
;
if (type == TOK_LBRACK) {
{
arraycheck();
;
cg_symbol();
;
lbrack();
;
expression();
;
if (type == TOK_RBRACK) {
{
cg_symbol();
;
;
};
};
rbrack();
;
;
};
};
if (type == TOK_ASSIGN) {
{
cg_symbol();
;
;
};
};
assign();
;
expression();
;
;
};
} else {
if (type == TOK_CALL) {
{
expect_call();
;
if (type == TOK_IDENT) {
{
symtype = TOK_CALL;
symcheck();
;
cg_call();
;
};
};
expect_ident();
;
;
};
} else {
if (type == TOK_BEGIN) {
{
cg_symbol();
;
expect_begin();
;
statement();
;
while (type == TOK_SEMICOLON) {
cg_semicolon();
;
semicolon();
;
statement();
;
};
if (type == TOK_END) {
{
cg_symbol();
;
;
};
};
expect_end();
;
;
};
} else {
if (type == TOK_IF) {
{
cg_symbol();
;
expect_if();
;
condition();
;
if (type == TOK_THEN) {
{
cg_symbol();
;
;
};
};
expect_then();
;
statement();
;
if (type == TOK_ELSE) {
{
cg_symbol();
;
expect_else();
;
statement();
;
};
};
cg_closeblock();
;
};
} else {
if (type == TOK_WHILE) {
{
cg_symbol();
;
expect_while();
;
condition();
;
if (type == TOK_DO) {
{
cg_symbol();
;
;
};
};
expect_do();
;
statement();
;
;
};
} else {
if (type == TOK_WRITEINT) {
{
expect_writeint();
;
cg_writeint();
;
expression();
;
cg_rparen();
;
cg_rparen();
;
cg_semicolon();
;
;
};
} else {
if (type == TOK_WRITECHAR) {
{
expect_writechar();
;
cg_writechar();
;
expression();
;
cg_rparen();
;
cg_rparen();
;
cg_semicolon();
;
;
};
} else {
if (type == TOK_WRITESTR) {
{
expect_writestr();
;
if (type == TOK_IDENT) {
{
symtype = CHECK_LHS;
symcheck();
;
cg_writestr();
;
expect_ident();
;
};
} else {
if (type == TOK_STRING) {
{
cg_writestr();
;
expect_string();
;
};
} else {
{
error();
;
(void)fprintf(
stdout,
"writeStr takes an array or a string: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' &&
__writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++],
stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
};
;
};
} else {
if (type == TOK_READINT) {
{
expect_readint();
;
if (type == TOK_INTO) {
expect_into();
;
};
if (type == TOK_IDENT) {
{
symtype = CHECK_LHS;
symcheck();
;
cg_readint();
;
};
};
expect_ident();
;
;
};
} else {
if (type == TOK_READCHAR) {
{
expect_readchar();
;
if (type == TOK_INTO) {
expect_into();
;
};
if (type == TOK_IDENT) {
{
symtype = CHECK_LHS;
symcheck();
;
cg_readchar();
;
};
};
expect_ident();
;
;
};
} else {
if (type == TOK_EXIT) {
{
expect_exit();
;
cg_exit();
;
expression();
;
cg_rparen();
;
cg_semicolon();
;
};
};
};
};
};
};
};
};
};
};
};
};
;
};
}
static void block(void) {
{
if (depth > 1) {
{
error();
;
(void)fprintf(stdout, "nesting depth exceeded\n");
;
exit(1);
;
;
};
};
depth = depth + 1;
if (type == TOK_CONST) {
{
expect_const();
;
if (type == TOK_IDENT) {
{
symtype = TOK_CONST;
addsymbol();
;
cg_const();
;
};
};
expect_ident();
;
equal();
;
if (type == TOK_NUMBER) {
{
cg_symbol();
;
cg_semicolon();
;
};
};
expect_number();
;
while (type == TOK_COMMA) {
comma();
;
if (type == TOK_IDENT) {
{
symtype = TOK_CONST;
addsymbol();
;
cg_const();
;
};
};
expect_ident();
;
equal();
;
if (type == TOK_NUMBER) {
{
cg_symbol();
;
cg_semicolon();
;
};
};
expect_number();
;
;
};
semicolon();
;
;
};
};
if (type == TOK_VAR) {
{
expect_var();
;
if (type == TOK_IDENT) {
{
symtype = TOK_VAR;
addsymbol();
;
cg_var();
;
};
};
expect_ident();
;
if (type == TOK_SIZE) {
{
expect_size();
;
if (type == TOK_NUMBER) {
{
arraysize();
;
cg_array();
;
;
};
};
expect_number();
;
;
};
};
cg_semicolon();
;
while (type == TOK_COMMA) {
comma();
;
if (type == TOK_IDENT) {
{
symtype = TOK_VAR;
addsymbol();
;
cg_var();
;
};
};
expect_ident();
;
if (type == TOK_SIZE) {
{
expect_size();
;
if (type == TOK_NUMBER) {
{
arraysize();
;
cg_array();
;
expect_number();
;
};
};
;
};
};
cg_semicolon();
;
};
semicolon();
;
cg_crlf();
;
};
};
while (type == TOK_FORWARD) {
expect_forward();
;
if (type == TOK_IDENT) {
{
symtype = TOK_FORWARD;
addsymbol();
;
cg_forward();
;
};
};
expect_ident();
;
semicolon();
;
;
};
while (type == TOK_PROCEDURE) {
proc = 1;
expect_procedure();
;
if (type == TOK_IDENT) {
{
symtype = TOK_PROCEDURE;
addsymbol();
;
cg_procedure();
;
};
};
expect_ident();
;
semicolon();
;
block();
;
semicolon();
;
proc = 0;
destroysymbols();
;
;
};
if (proc == 0) {
{
cg_procedure();
;
;
};
};
statement();
;
cg_epilogue();
;
depth = depth - 1;
if (depth < 0) {
{
error();
;
(void)fprintf(stdout, "nesting depth fell below 0\n");
;
exit(1);
;
;
};
};
;
};
}
static void parse(void) {
{
cg_init();
;
next();
;
block();
;
dot();
;
if (type != 0) {
{
error();
;
(void)fprintf(stdout, "extra tokens at end of file: \'");
;
__writestridx = 0;
while (token[__writestridx] != '\0' && __writestridx < 256)
(void)fputc((unsigned char)token[__writestridx++], stdout);
;
(void)fprintf(stdout, "\'\n");
;
exit(1);
;
;
};
};
cg_end();
;
;
};
}
int main(int argc, char *argv[]) {
{
line = 1;
type = -1;
setupkeywords();
;
readin();
;
initsymtab();
;
parse();
;
};
return 0;
}
/* PL/0 compiler 1.0.2 */
|
smlckz/pl0c | original.c | /*
* Copyright (c) 2021 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR 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.
*/
/*
* NOTE: This is the original C implementation used to bootstrap the
* self-hosting compiler. It is no longer used but is the subject
* of the blog series found here:
* https://briancallahan.net/blog/20210814.html
*/
#include <sys/stat.h>
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifndef HAVE_STRTONUM
#include "strtonum.c"
#endif
#define PL0C_VERSION "1.2.0"
#define CHECK_LHS 0
#define CHECK_RHS 1
#define CHECK_CALL 2
#define TOK_IDENT 'I'
#define TOK_NUMBER 'N'
#define TOK_CONST 'C'
#define TOK_VAR 'V'
#define TOK_PROCEDURE 'P'
#define TOK_CALL 'c'
#define TOK_BEGIN 'B'
#define TOK_END 'E'
#define TOK_IF 'i'
#define TOK_THEN 'T'
#define TOK_ELSE 'e'
#define TOK_WHILE 'W'
#define TOK_DO 'D'
#define TOK_ODD 'O'
#define TOK_WRITEINT 'w'
#define TOK_WRITECHAR 'H'
#define TOK_WRITESTR 'S'
#define TOK_READINT 'R'
#define TOK_READCHAR 'h'
#define TOK_INTO 'n'
#define TOK_SIZE 's'
#define TOK_EXIT 'X'
#define TOK_AND '&'
#define TOK_OR '|'
#define TOK_NOT '~'
#define TOK_FORWARD 'F'
#define TOK_DOT '.'
#define TOK_EQUAL '='
#define TOK_COMMA ','
#define TOK_SEMICOLON ';'
#define TOK_ASSIGN ':'
#define TOK_HASH '#'
#define TOK_LESSTHAN '<'
#define TOK_GREATERTHAN '>'
#define TOK_LTEQUALS '{'
#define TOK_GTEQUALS '}'
#define TOK_PLUS '+'
#define TOK_MINUS '-'
#define TOK_MULTIPLY '*'
#define TOK_DIVIDE '/'
#define TOK_MODULO '%'
#define TOK_LPAREN '('
#define TOK_RPAREN ')'
#define TOK_LBRACK '['
#define TOK_RBRACK ']'
#define TOK_STRING '"'
/*
* pl0c -- PL/0 compiler.
*
* program = block "." .
* block = [ "const" ident "=" number { "," ident "=" number } ";" ]
* [ "var" ident [ array ] { "," ident [ array ] } ";" ]
{ "forward" ident ";" }
* { "procedure" ident ";" block ";" } statement .
* statement = [ ident ":=" expression
* | "call" ident
* | "begin" statement { ";" statement } "end"
* | "if" condition "then" statement [ "else" statement ]
* | "while" condition "do" statement
* | "readInt" [ "into" ] ident
* | "readChar" [ "into" ] ident
* | "writeInt" expression
* | "writeChar" expression
* | "writeStr" ( ident | string )
* | "exit" expression ] .
* condition = "odd" expression
* | expression ( comparator ) expression .
* expression = [ "+" | "-" | "not" ] term { ( "+" | "-" | "or" ) term } .
* term = factor { ( "*" | "/" | "mod" | "and" ) factor } .
* factor = ident
* | number
* | "(" expression ")" .
* comparator = "=" | "#" | "<" | ">" | "<=" | ">=" | "<>" .
* array = "size" number .
*/
static char *raw, *token;
static int depth, proc, type;
static size_t line = 1;
struct symtab {
int depth;
int type;
long size;
char *name;
struct symtab *next;
};
static struct symtab *head;
static void expression(void);
/*
* Misc. functions.
*/
static void
error(const char *fmt, ...)
{
va_list ap;
(void) fprintf(stderr, "pl0c: error: %lu: ", line);
va_start(ap, fmt);
(void) vfprintf(stderr, fmt, ap);
va_end(ap);
(void) fputc('\n', stderr);
exit(1);
}
static void
readin(char *file)
{
int fd;
struct stat st;
if (strrchr(file, '.') == NULL)
error("file must end in '.pl0'");
if (!!strcmp(strrchr(file, '.'), ".pl0"))
error("file must end in '.pl0'");
if ((fd = open(file, O_RDONLY)) == -1)
error("couldn't open %s", file);
if (fstat(fd, &st) == -1)
error("couldn't get size");
if ((raw = malloc(st.st_size + 1)) == NULL)
error("malloc failed");
if (read(fd, raw, st.st_size) != st.st_size)
error("couldn't read %s", file);
raw[st.st_size] = '\0';
(void) close(fd);
}
/*
* Lexer.
*/
static void
comment(void)
{
int ch;
while ((ch = *raw++) != '}') {
if (ch == '\0')
error("unterminated comment");
if (ch == '\n')
++line;
}
}
static int
ident(void)
{
char *p;
size_t i, len;
p = raw;
while (isalnum(*raw) || *raw == '_')
++raw;
len = raw - p;
--raw;
free(token);
if ((token = malloc(len + 1)) == NULL)
error("malloc failed");
for (i = 0; i < len; i++)
token[i] = *p++;
token[i] = '\0';
if (!strcmp(token, "const"))
return TOK_CONST;
else if (!strcmp(token, "var"))
return TOK_VAR;
else if (!strcmp(token, "procedure"))
return TOK_PROCEDURE;
else if (!strcmp(token, "call"))
return TOK_CALL;
else if (!strcmp(token, "begin"))
return TOK_BEGIN;
else if (!strcmp(token, "end"))
return TOK_END;
else if (!strcmp(token, "if"))
return TOK_IF;
else if (!strcmp(token, "then"))
return TOK_THEN;
else if (!strcmp(token, "else"))
return TOK_ELSE;
else if (!strcmp(token, "while"))
return TOK_WHILE;
else if (!strcmp(token, "do"))
return TOK_DO;
else if (!strcmp(token, "odd"))
return TOK_ODD;
else if (!strcmp(token, "writeInt"))
return TOK_WRITEINT;
else if (!strcmp(token, "writeChar"))
return TOK_WRITECHAR;
else if (!strcmp(token, "writeStr"))
return TOK_WRITESTR;
else if (!strcmp(token, "readInt"))
return TOK_READINT;
else if (!strcmp(token, "readChar"))
return TOK_READCHAR;
else if (!strcmp(token, "into"))
return TOK_INTO;
else if (!strcmp(token, "size"))
return TOK_SIZE;
else if (!strcmp(token, "exit"))
return TOK_EXIT;
else if (!strcmp(token, "and"))
return TOK_AND;
else if (!strcmp(token, "or"))
return TOK_OR;
else if (!strcmp(token, "not"))
return TOK_NOT;
else if (!strcmp(token, "mod"))
return TOK_MODULO;
else if (!strcmp(token, "forward"))
return TOK_FORWARD;
return TOK_IDENT;
}
static int
number(void)
{
const char *errstr;
char *p;
size_t i, j = 0, len;
p = raw;
while (isdigit(*raw) || *raw == '_')
++raw;
len = raw - p;
--raw;
free(token);
if ((token = malloc(len + 1)) == NULL)
error("malloc failed");
for (i = 0; i < len; i++) {
if (isdigit(*p))
token[j++] = *p;
++p;
}
token[j] = '\0';
(void) strtonum(token, 0, LONG_MAX, &errstr);
if (errstr != NULL)
error("invalid number: %s", token);
return TOK_NUMBER;
}
static int
string(void)
{
char *p;
size_t i, len, mod = 0;
p = ++raw;
restart:
while (*raw != '\'') {
if (*raw == '\n' || *raw == '\0')
error("unterminated string");
if (*raw++ == '"')
++mod;
}
if (*++raw == '\'') {
++raw;
goto restart;
}
--raw;
len = raw - p + mod;
if (len < 1)
error("impossible string");
free(token);
if ((token = malloc(len + 3)) == NULL)
error("malloc failed");
token[0] = '"';
for (i = 1; i <= len; i++) {
if (*p == '\'') {
token[i++] = '\\';
++p;
} else if (*p == '"') {
token[i++] = '\\';
}
token[i] = *p++;
}
token[i++] = '"';
token[i] = '\0';
if (len == 1 || (len == 2 && token[1] == '\\')) {
token[0] = '\'';
if (len == 1)
token[2] = '\'';
else
token[3] = '\'';
return TOK_NUMBER;
}
return TOK_STRING;
}
static int
lex(void)
{
again:
/* Skip whitespace. */
while (*raw == ' ' || *raw == '\t' || *raw == '\n') {
if (*raw++ == '\n')
++line;
}
if (isalpha(*raw) || *raw == '_')
return ident();
if (isdigit(*raw))
return number();
switch (*raw) {
case '{':
comment();
goto again;
case '.':
case '=':
case ',':
case ';':
case '#':
case '+':
case '-':
case '*':
case '/':
case '%':
case '(':
case ')':
case '[':
case ']':
return (*raw);
case '<':
if (*++raw == '=')
return TOK_LTEQUALS;
if (*raw == '>')
return TOK_HASH;
--raw;
return TOK_LESSTHAN;
case '>':
if (*++raw == '=')
return TOK_GTEQUALS;
--raw;
return TOK_GREATERTHAN;
case ':':
if (*++raw != '=')
error("unknown token: ':%c'", *raw);
return TOK_ASSIGN;
case '\'':
return string();
case '\0':
return 0;
default:
error("unknown token: '%c'", *raw);
}
return 0;
}
/*
* Code generator.
*/
static void
aout(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
(void) vfprintf(stdout, fmt, ap);
va_end(ap);
}
static void
cg_array(void)
{
aout("[%s]", token);
}
static void
cg_call(void)
{
aout("%s();\n", token);
}
static void
cg_closeblock(void)
{
aout(";}\n");
}
static void
cg_const(void)
{
if (proc == 0)
aout("static ");
aout("const long %s=", token);
}
static void
cg_crlf(void)
{
aout("\n");
}
static void
cg_end(void)
{
aout("/* PL/0 historical compiler %s */\n", PL0C_VERSION);
}
static void
cg_epilogue(void)
{
aout(";");
if (proc == 0)
aout("\nreturn 0;");
aout("\n}\n\n");
}
static void
cg_exit(void)
{
aout("exit(");
}
static void
cg_forward(void)
{
aout("static void %s(void);", token);
}
static void
cg_init(void)
{
aout("#include <limits.h>\n");
aout("#include <stdio.h>\n");
aout("#include <stdlib.h>\n");
aout("#include <string.h>\n\n");
aout("static char __stdin[24];\n");
aout("static const char *__errstr;\n\n");
aout("static long __writestridx;\n\n");
}
static void
cg_odd(void)
{
aout(")&1");
}
static void
cg_procedure(void)
{
if (proc == 0) {
aout("int\n");
aout("main(int argc, char *argv[])\n");
} else {
aout("static void\n");
aout("%s(void)\n", token);
}
aout("{\n");
}
static void
cg_readchar(void)
{
aout("%s=(int) fgetc(stdin);", token);
}
static void
cg_readint(void)
{
aout("(void) fgets(__stdin, sizeof(__stdin), stdin);\n");
aout("if(__stdin[strlen(__stdin) - 1] == '\\n')");
aout("__stdin[strlen(__stdin) - 1] = '\\0';");
aout("%s=(long) strtonum(__stdin, LONG_MIN, LONG_MAX, &__errstr);\n",
token);
aout("if(__errstr!=NULL){");
aout("(void) fprintf(stderr, \"invalid number: %%s\\n\", __stdin);");
aout("exit(1);");
aout("}");
}
static void
cg_rparen(void)
{
aout(")");
}
static void
cg_semicolon(void)
{
aout(";\n");
}
static void
cg_symbol(void)
{
switch (type) {
case TOK_IDENT:
case TOK_NUMBER:
aout("%s", token);
break;
case TOK_BEGIN:
aout("{\n");
break;
case TOK_END:
aout(";\n}\n");
break;
case TOK_IF:
aout("if(");
break;
case TOK_THEN:
aout("){");
break;
case TOK_DO:
aout(")");
break;
case TOK_ELSE:
aout(";}else{");
break;
case TOK_ODD:
aout("(");
break;
case TOK_WHILE:
aout("while(");
break;
case TOK_EQUAL:
aout("==");
break;
case TOK_ASSIGN:
aout("=");
break;
case TOK_HASH:
aout("!=");
break;
case TOK_LTEQUALS:
aout("<=");
break;
case TOK_GTEQUALS:
aout(">=");
break;
default:
aout("%c", type);
}
}
static void
cg_var(void)
{
if (proc == 0)
aout("static ");
aout("long %s", token);
}
static void
cg_writechar(void)
{
aout("(void) fprintf(stdout, \"%%c\", (unsigned char) (");
}
static void
cg_writeint(void)
{
aout("(void) fprintf(stdout, \"%%ld\", (long) (");
}
static void
cg_writestr(void)
{
struct symtab *curr, *ret;
if (type == TOK_IDENT) {
curr = head;
while (curr != NULL) {
if (!strcmp(curr->name, token))
ret = curr;
curr = curr->next;
}
if (ret == NULL)
error("undefined symbol: %s", token);
if (ret->size == 0)
error("writeStr requires an array");
aout("__writestridx = 0;\n");
aout("while(%s[__writestridx]!='\\0'&&__writestridx<%ld)\n",
token, ret->size);
aout("(void)fputc((unsigned char)%s[__writestridx++],stdout);\n",
token);
} else {
aout("(void)fprintf(stdout, %s);\n", token);
}
}
/*
* Semantics.
*/
static void
arraycheck(void)
{
struct symtab *curr, *ret = NULL;
curr = head;
while (curr != NULL) {
if (!strcmp(token, curr->name))
ret = curr;
curr = curr->next;
}
if (ret == NULL)
error("undefined symbol: %s", token);
if (ret->size == 0)
error("symbol %s is not an array", token);
}
static void
symcheck(int check)
{
struct symtab *curr, *ret = NULL;
curr = head;
while (curr != NULL) {
if (!strcmp(token, curr->name))
ret = curr;
curr = curr->next;
}
if (ret == NULL)
error("undefined symbol: %s", token);
switch (check) {
case CHECK_LHS:
if (ret->type != TOK_VAR)
error("must be a variable: %s", token);
break;
case CHECK_RHS:
if (ret->type == TOK_PROCEDURE || ret->type == TOK_FORWARD)
error("must not be a procedure: %s", token);
break;
case CHECK_CALL:
if (ret->type != TOK_PROCEDURE && ret->type != TOK_FORWARD)
error("must be a procedure: %s", token);
}
}
/*
* Parser.
*/
static void
next(void)
{
type = lex();
++raw;
}
static void
expect(int match)
{
if (match != type)
error("syntax error");
next();
}
static void
addsymbol(int type)
{
struct symtab *curr, *new;
curr = head;
while (1) {
if (!strcmp(curr->name, token)) {
if (curr->depth == (depth - 1)) {
if (curr->type == TOK_FORWARD &&
type == TOK_PROCEDURE) {
/* Don't error out! */
} else {
error("duplicate symbol: %s", token);
}
}
}
if (curr->next == NULL)
break;
curr = curr->next;
}
if ((new = malloc(sizeof(struct symtab))) == NULL)
error("malloc failed");
new->depth = depth - 1;
new->type = type;
new->size = 0;
if ((new->name = strdup(token)) == NULL)
error("malloc failed");
new->next = NULL;
curr->next = new;
}
static void
arraysize(void)
{
struct symtab *curr;
const char *errstr;
curr = head;
while (curr->next != NULL)
curr = curr->next;
if (curr->type != TOK_VAR)
error("arrays must be declared with \"var\"");
curr->size = strtonum(token, 1, LONG_MAX, &errstr);
if (errstr != NULL)
error("invalid array size");
}
static void
destroysymbols(void)
{
struct symtab *curr, *prev;
again:
curr = head;
while (curr->next != NULL) {
prev = curr;
curr = curr->next;
}
if (curr->type != TOK_PROCEDURE) {
free(curr->name);
free(curr);
prev->next = NULL;
goto again;
}
}
static void
initsymtab(void)
{
struct symtab *new;
if ((new = malloc(sizeof(struct symtab))) == NULL)
error("malloc failed");
new->depth = 0;
new->type = TOK_PROCEDURE;
new->size = 0;
new->name = "main";
new->next = NULL;
head = new;
}
static void
factor(void)
{
switch (type) {
case TOK_IDENT:
symcheck(CHECK_RHS);
cg_symbol();
expect(TOK_IDENT);
if (type == TOK_LBRACK) {
arraycheck();
cg_symbol();
expect(TOK_LBRACK);
expression();
if (type == TOK_RBRACK)
cg_symbol();
expect(TOK_RBRACK);
}
break;
case TOK_NUMBER:
cg_symbol();
expect(TOK_NUMBER);
break;
case TOK_LPAREN:
cg_symbol();
expect(TOK_LPAREN);
expression();
if (type == TOK_RPAREN)
cg_symbol();
expect(TOK_RPAREN);
}
}
static void
term(void)
{
factor();
while (type == TOK_MULTIPLY || type == TOK_DIVIDE ||
type == TOK_MODULO || type == TOK_AND) {
cg_symbol();
next();
factor();
}
}
static void
expression(void)
{
if (type == TOK_PLUS || type == TOK_MINUS || type == TOK_NOT) {
cg_symbol();
next();
}
term();
while (type == TOK_PLUS || type == TOK_MINUS || type == TOK_OR) {
cg_symbol();
next();
term();
}
}
static void
condition(void)
{
if (type == TOK_ODD) {
cg_symbol();
expect(TOK_ODD);
expression();
cg_odd();
} else {
expression();
switch (type) {
case TOK_EQUAL:
case TOK_HASH:
case TOK_LESSTHAN:
case TOK_GREATERTHAN:
case TOK_LTEQUALS:
case TOK_GTEQUALS:
cg_symbol();
next();
break;
default:
error("invalid conditional");
}
expression();
}
}
static void
statement(void)
{
switch (type) {
case TOK_IDENT:
symcheck(CHECK_LHS);
cg_symbol();
expect(TOK_IDENT);
if (type == TOK_LBRACK) {
arraycheck();
cg_symbol();
expect(TOK_LBRACK);
expression();
if (type == TOK_RBRACK)
cg_symbol();
expect(TOK_RBRACK);
}
if (type == TOK_ASSIGN)
cg_symbol();
expect(TOK_ASSIGN);
expression();
break;
case TOK_CALL:
expect(TOK_CALL);
if (type == TOK_IDENT) {
symcheck(CHECK_CALL);
cg_call();
}
expect(TOK_IDENT);
break;
case TOK_BEGIN:
cg_symbol();
expect(TOK_BEGIN);
statement();
while (type == TOK_SEMICOLON) {
cg_semicolon();
expect(TOK_SEMICOLON);
statement();
}
if (type == TOK_END)
cg_symbol();
expect(TOK_END);
break;
case TOK_IF:
cg_symbol();
expect(TOK_IF);
condition();
if (type == TOK_THEN)
cg_symbol();
expect(TOK_THEN);
statement();
if (type == TOK_ELSE) {
cg_symbol();
expect(TOK_ELSE);
statement();
}
cg_closeblock();
break;
case TOK_WHILE:
cg_symbol();
expect(TOK_WHILE);
condition();
if (type == TOK_DO)
cg_symbol();
expect(TOK_DO);
statement();
break;
case TOK_WRITEINT:
expect(TOK_WRITEINT);
cg_writeint();
expression();
cg_rparen();
cg_rparen();
cg_semicolon();
break;
case TOK_WRITECHAR:
expect(TOK_WRITECHAR);
cg_writechar();
expression();
cg_rparen();
cg_rparen();
cg_semicolon();
break;
case TOK_WRITESTR:
expect(TOK_WRITESTR);
if (type == TOK_IDENT || type == TOK_STRING) {
if (type == TOK_IDENT)
symcheck(CHECK_LHS);
cg_writestr();
if (type == TOK_IDENT)
expect(TOK_IDENT);
else
expect(TOK_STRING);
} else {
error("writeStr takes an array or a string");
}
break;
case TOK_READINT:
expect(TOK_READINT);
if (type == TOK_INTO)
expect(TOK_INTO);
if (type == TOK_IDENT) {
symcheck(CHECK_LHS);
cg_readint();
}
expect(TOK_IDENT);
break;
case TOK_READCHAR:
expect(TOK_READCHAR);
if (type == TOK_INTO)
expect(TOK_INTO);
if (type == TOK_IDENT) {
symcheck(CHECK_LHS);
cg_readchar();
}
expect(TOK_IDENT);
break;
case TOK_EXIT:
expect(TOK_EXIT);
cg_exit();
expression();
cg_rparen();
cg_semicolon();
}
}
static void
block(void)
{
if (depth++ > 1)
error("nesting depth exceeded");
if (type == TOK_CONST) {
expect(TOK_CONST);
if (type == TOK_IDENT) {
addsymbol(TOK_CONST);
cg_const();
}
expect(TOK_IDENT);
expect(TOK_EQUAL);
if (type == TOK_NUMBER) {
cg_symbol();
cg_semicolon();
}
expect(TOK_NUMBER);
while (type == TOK_COMMA) {
expect(TOK_COMMA);
if (type == TOK_IDENT) {
addsymbol(TOK_CONST);
cg_const();
}
expect(TOK_IDENT);
expect(TOK_EQUAL);
if (type == TOK_NUMBER) {
cg_symbol();
cg_semicolon();
}
expect(TOK_NUMBER);
}
expect(TOK_SEMICOLON);
}
if (type == TOK_VAR) {
expect(TOK_VAR);
if (type == TOK_IDENT) {
addsymbol(TOK_VAR);
cg_var();
}
expect(TOK_IDENT);
if (type == TOK_SIZE) {
expect(TOK_SIZE);
if (type == TOK_NUMBER) {
arraysize();
cg_array();
}
expect(TOK_NUMBER);
}
cg_semicolon();
while (type == TOK_COMMA) {
expect(TOK_COMMA);
if (type == TOK_IDENT) {
addsymbol(TOK_VAR);
cg_var();
}
expect(TOK_IDENT);
if (type == TOK_SIZE) {
expect(TOK_SIZE);
if (type == TOK_NUMBER) {
arraysize();
cg_array();
expect(TOK_NUMBER);
}
}
cg_semicolon();
}
expect(TOK_SEMICOLON);
cg_crlf();
}
while (type == TOK_FORWARD) {
expect(TOK_FORWARD);
if (type == TOK_IDENT) {
addsymbol(TOK_FORWARD);
cg_forward();
}
expect(TOK_IDENT);
expect(TOK_SEMICOLON);
}
while (type == TOK_PROCEDURE) {
proc = 1;
expect(TOK_PROCEDURE);
if (type == TOK_IDENT) {
addsymbol(TOK_PROCEDURE);
cg_procedure();
}
expect(TOK_IDENT);
expect(TOK_SEMICOLON);
block();
expect(TOK_SEMICOLON);
proc = 0;
destroysymbols();
}
if (proc == 0)
cg_procedure();
statement();
cg_epilogue();
if (--depth < 0)
error("nesting depth fell below 0");
}
static void
parse(void)
{
cg_init();
next();
block();
expect(TOK_DOT);
if (type != 0)
error("extra tokens at end of file");
cg_end();
}
/*
* Main.
*/
int
main(int argc, char *argv[])
{
if (argc != 2) {
(void) fputs("usage: pl0c file.pl0\n", stderr);
exit(1);
}
readin(argv[1]);
initsymtab();
parse();
return 0;
}
|
marceloburegio/mq135 | src/mgos_mq135.c | <gh_stars>0
#include "mgos.h"
#include "mgos_adc.h"
#include <math.h>
struct mgos_mq135 {
int pin;
float rload; // The load resistance on the board
float rzero; // Calibration resistance at atmospheric CO2 level
};
/// Parameters for calculating ppm of CO2 from sensor resistance
#define MGOS_MQ135_PARA 116.6020682
#define MGOS_MQ135_PARB 2.769034857
/// Parameters to model temperature and humidity dependence
#define MGOS_MQ135_CORA 0.00035
#define MGOS_MQ135_CORB 0.02718
#define MGOS_MQ135_CORC 1.39538
#define MGOS_MQ135_CORD 0.0018
#define MGOS_MQ135_CORE -0.003333333
#define MGOS_MQ135_CORF -0.001923077
#define MGOS_MQ135_CORG 1.130128205
/// Atmospheric CO2 level for calibration purposes
#define MGOS_MQ135_ATMOCO2 403 // 403 = C02 in the forests / 410-425 = CO2 in a city with high car pollution
// Private functions follow
// Private functions end
// Public functions follow
struct mgos_mq135 *mgos_mq135_create(int pin) {
struct mgos_mq135 *mq;
if (!mgos_adc_enable(pin)) {
return NULL;
}
mq = calloc(1, sizeof(struct mgos_mq135));
if (!mq) {
return NULL;
}
memset(mq, 0, sizeof(struct mgos_mq135));
mq->pin = pin;
mq->rload = 22.0;
mq->rzero = 76.63;
LOG(LL_DEBUG, ("Sensor MQ135 was successfully created using pin %d", pin));
return mq;
}
/* Get the correction factor to correct for temperature and humidity */
float mgos_mq135_get_correction_factor(float t, float h) {
// Linearization of the temperature dependency curve under and above 20 degree C
// below 20degC: fact = a * t * t - b * t - (h - 33) * d
// above 20degC: fact = a * t + b * h + c
// this assumes a linear dependency on humidity
if (t < 20) {
return MGOS_MQ135_CORA * t * t - MGOS_MQ135_CORB * t + MGOS_MQ135_CORC - (h - 33.) * MGOS_MQ135_CORD;
}
else {
return MGOS_MQ135_CORE * t + MGOS_MQ135_CORF * h + MGOS_MQ135_CORG;
}
}
/* Get the resistance of the sensor, ie. the measurement value */
float mgos_mq135_get_resistance(struct mgos_mq135 *mq) {
int val = mgos_adc_read(mq->pin);
return ((1023. / (float)val) - 1.) * mq->rload; // Before was: ((1023. / (float)val) * 5. - 1.) * mq->rload;
}
/* Get the resistance of the sensor, ie. the measurement value corrected for temperature/humidity */
float mgos_mq135_get_corrected_resistance(struct mgos_mq135 *mq, float t, float h) {
return mgos_mq135_get_resistance(mq) / mgos_mq135_get_correction_factor(t, h);
}
/* Get the ppm of CO2 sensed (assuming only CO2 in the air) */
float mgos_mq135_get_ppm(struct mgos_mq135 *mq) {
return MGOS_MQ135_PARA * pow((mgos_mq135_get_resistance(mq) / mq->rzero), -MGOS_MQ135_PARB);
}
/* Get the ppm of CO2 sensed (assuming only CO2 in the air), corrected for temperature/humidity */
float mgos_mq135_get_corrected_ppm(struct mgos_mq135 *mq, float t, float h) {
return MGOS_MQ135_PARA * pow((mgos_mq135_get_corrected_resistance(mq, t, h) / mq->rzero), -MGOS_MQ135_PARB);
}
/* Get the resistance RZero of the sensor for calibration purposes */
float mgos_mq135_get_rzero(struct mgos_mq135 *mq) {
return mgos_mq135_get_resistance(mq) * pow((MGOS_MQ135_ATMOCO2 / MGOS_MQ135_PARA), (1. / MGOS_MQ135_PARB));
}
/* Get the corrected resistance RZero of the sensor for calibration purposes */
float mgos_mq135_get_corrected_rzero(struct mgos_mq135 *mq, float t, float h) {
return mgos_mq135_get_corrected_resistance(mq, t, h) * pow((MGOS_MQ135_ATMOCO2 / MGOS_MQ135_PARA), (1. / MGOS_MQ135_PARB));
}
/* Initialization function for MGOS -- currently a noop */
bool mgos_mq135_init(void) {
return true;
}
// Public functions end |
marceloburegio/mq135 | include/mgos_mq135.h | <gh_stars>0
#ifndef CS_MOS_LIBS_MQ135_INCLUDE_MGOS_MQ135_H_
#define CS_MOS_LIBS_MQ135_INCLUDE_MGOS_MQ135_H_
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
struct mgos_mq135;
/* Initialise MQ135 sensor. Return an opaque MQ135 handle, or `NULL` on error */
struct mgos_mq135 *mgos_mq135_create(int pin);
/* Close MQ135 handle */
void mgos_mq135_close(struct mgos_mq135 *mq);
/* Get the correction factor to correct for temperature and humidity */
float mgos_mq135_get_correction_factor(float t, float h);
/* Get the resistance of the sensor, ie. the measurement value */
float mgos_mq135_get_resistance(struct mgos_mq135 *mq);
/* Get the resistance of the sensor, ie. the measurement value corrected for temperature/humidity */
float mgos_mq135_get_corrected_resistance(struct mgos_mq135 *mq, float t, float h);
/* Get the ppm of CO2 sensed (assuming only CO2 in the air) */
float mgos_mq135_get_ppm(struct mgos_mq135 *mq);
/* Get the ppm of CO2 sensed (assuming only CO2 in the air), corrected for temperature/humidity */
float mgos_mq135_get_corrected_ppm(struct mgos_mq135 *mq, float t, float h);
/* Get the resistance RZero of the sensor for calibration purposes */
float mgos_mq135_get_rzero(struct mgos_mq135 *mq);
/* Get the corrected resistance RZero of the sensor for calibration purposes */
float mgos_mq135_get_corrected_rzero(struct mgos_mq135 *mq, float t, float h);
/* Initialization function for MGOS -- currently a noop */
bool mgos_mq135_init(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_MOS_LIBS_MQ135_INCLUDE_MGOS_MQ135_H_ */
|
RUB-crypto/RUBIK | src/llmq/quorums_blockprocessor.h | // Copyright (c) 2018 The Rubik Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef RUBIK_QUORUMS_BLOCKPROCESSOR_H
#define RUBIK_QUORUMS_BLOCKPROCESSOR_H
#include "llmq/quorums_commitment.h"
#include "llmq/quorums_utils.h"
#include "consensus/params.h"
#include "primitives/transaction.h"
#include "saltedhasher.h"
#include "sync.h"
#include <map>
#include <unordered_map>
class CNode;
class CConnman;
namespace llmq
{
class CQuorumBlockProcessor
{
private:
CEvoDB& evoDb;
// TODO cleanup
CCriticalSection minableCommitmentsCs;
std::map<std::pair<Consensus::LLMQType, uint256>, uint256> minableCommitmentsByQuorum;
std::map<uint256, CFinalCommitment> minableCommitments;
std::unordered_map<std::pair<Consensus::LLMQType, uint256>, bool, StaticSaltedHasher> hasMinedCommitmentCache;
public:
CQuorumBlockProcessor(CEvoDB& _evoDb) : evoDb(_evoDb) {}
void UpgradeDB();
void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman);
bool ProcessBlock(const CBlock& block, const CBlockIndex* pindex, CValidationState& state);
bool UndoBlock(const CBlock& block, const CBlockIndex* pindex);
void AddMinableCommitment(const CFinalCommitment& fqc);
bool HasMinableCommitment(const uint256& hash);
bool GetMinableCommitmentByHash(const uint256& commitmentHash, CFinalCommitment& ret);
bool GetMinableCommitment(Consensus::LLMQType llmqType, int nHeight, CFinalCommitment& ret);
bool GetMinableCommitmentTx(Consensus::LLMQType llmqType, int nHeight, CTransactionRef& ret);
bool HasMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash);
bool GetMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash, CFinalCommitment& ret, uint256& retMinedBlockHash);
std::vector<const CBlockIndex*> GetMinedCommitmentsUntilBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex, size_t maxCount);
std::map<Consensus::LLMQType, std::vector<const CBlockIndex*>> GetMinedAndActiveCommitmentsUntilBlock(const CBlockIndex* pindex);
private:
bool GetCommitmentsFromBlock(const CBlock& block, const CBlockIndex* pindex, std::map<Consensus::LLMQType, CFinalCommitment>& ret, CValidationState& state);
bool ProcessCommitment(int nHeight, const uint256& blockHash, const CFinalCommitment& qc, CValidationState& state);
bool IsMiningPhase(Consensus::LLMQType llmqType, int nHeight);
bool IsCommitmentRequired(Consensus::LLMQType llmqType, int nHeight);
uint256 GetQuorumBlockHash(Consensus::LLMQType llmqType, int nHeight);
};
extern CQuorumBlockProcessor* quorumBlockProcessor;
}
#endif//RUBIK_QUORUMS_BLOCKPROCESSOR_H
|
RUB-crypto/RUBIK | src/chainparamsseeds.h | #ifndef RUBIK_CHAINPARAMSSEEDS_H
#define RUBIK_CHAINPARAMSSEEDS_H
/**
* List of fixed seed nodes for the rubik network
* AUTOGENERATED by contrib/seeds/generate-seeds.py
*
* Each line contains a 16-byte IPv6 address and a port.
* IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.
*/
static SeedSpec6 pnSeed6_main[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xa5,0x16,0x34,0x83}, 9921}
};
static SeedSpec6 pnSeed6_test[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x12,0xca,0x34,0xaa}, 20008},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x12,0xca,0x34,0xaa}, 20004},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x12,0xca,0x34,0xaa}, 20000},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x12,0xca,0x34,0xaa}, 20012},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x12,0xca,0x34,0xaa}, 20016},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x12,0xca,0x34,0xaa}, 20020},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0xff,0x0f,0x14}, 20007},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0xff,0x0f,0x14}, 20003},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0xff,0x0f,0x14}, 20015},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0xff,0x0f,0x14}, 20011},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0xff,0x0f,0x14}, 20019},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0xff,0x0f,0x14}, 20023},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x34,0x32,0xd0,0x35}, 20009},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x34,0x32,0xd0,0x35}, 20005},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x34,0x32,0xd0,0x35}, 20001},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x34,0x32,0xd0,0x35}, 20013},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x34,0x32,0xd0,0x35}, 20017},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x34,0x32,0xd0,0x35}, 20021},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x21,0xee,0x55}, 20010},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x21,0xee,0x55}, 20006},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x21,0xee,0x55}, 20002},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x21,0xee,0x55}, 20014},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x21,0xee,0x55}, 20018},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x3f,0x21,0xee,0x55}, 20022},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x10}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x11}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x12}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x13}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x14}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x15}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x16}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x17}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x18}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x91,0xef,0xeb,0x19}, 19999},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb2,0x3e,0xcb,0xf9}, 19999}
};
#endif // RUBIK_CHAINPARAMSSEEDS_H |
PeterSommerlad/PSBitField | psbitfield.h | #ifndef PSBITFIELD_H_
#define PSBITFIELD_H_
#include <cstdint>
#include <climits>
#include <type_traits>
#include <limits>
#include <cassert>
#include <ostream>
// this is a bitfield implementation to be used within unions for device registers
// where the bits are positioned absolutely with the least-significant-bit has from-index 0
// using the aliases with the _v makes the data members volatile to prevent optimiazations
// but note, that setting inidividual fields mean both reading and writing the word
// accessing individual union members is sanctioned, because they have the same struct-ure.
//
// Usage:
//
// union MyReg16 {
// template<uint8_t from, uint8_t width>
// using bf = psbf::bits16<from,width>; // shorthand below
// psbf::allbits16 word; // should be the first to ensure init: MyReg16 reg{};
// bf<0,4> firstnibble;
// bf<4,1> fourthbit;
// bf<5,3> threebits;
// bf<8,8> secondbyte;
// };
// MyReg16 volatile var{}; // at mmio address
// var.firstnibble = 42;
// std::cout << std::hex << var.word;
// var.fourthbit = 1;
// var.threebits = 5;
// std::cout << var.word;
// unsigned const x = var.secondbyte; // would not deduce integer type
// std::cout << x;
// // x.threebits = 8; // asserts!
//
// volatile from the outer variable is propagated!
// all bitfield accesses are unsigned
namespace psbf {
template<uint8_t from, uint8_t width, typename UINT=uint32_t>
struct bitfield{
using result_type = std::remove_volatile_t<UINT>;
using as_volatile = std::conditional_t<std::is_volatile_v<UINT>,UINT,UINT volatile>;
using expr_type = std::conditional_t<sizeof(result_type)<=sizeof(unsigned),unsigned,result_type >;
static_assert(std::numeric_limits<UINT>::is_integer && ! std::numeric_limits<UINT>::is_signed, "must use unsigned bitfield base type");
static_assert(std::numeric_limits<UINT>::digits == sizeof(UINT)*CHAR_BIT);
static constexpr inline uint8_t wordsize = sizeof(UINT)*CHAR_BIT;
static constexpr inline expr_type widthmask = (width == wordsize)?result_type(-1):(result_type(1)<<width)-1;
static constexpr inline expr_type mask = (result_type(-1) >> (wordsize-width)) << from; // we have two's complement!
static_assert(widthmask == (mask>>from) );
static_assert((width==wordsize?result_type(-1):(result_type(1u)<<width)-result_type(1u))==(from > 0? mask>>from: mask));
static_assert(from < wordsize, "starting position too big");
static_assert(from+width <= wordsize, "bitfield too wide");
static_assert(width>0, "zero-size bitfields not supported");
as_volatile& allbitsvolatileforwrite() volatile & {
return const_cast<as_volatile&>(allbits);
}
as_volatile const & allbitsvolatileforread() const volatile {
return const_cast<as_volatile const&>(allbits);
}
operator result_type() const volatile { return (expr_type(allbitsvolatileforread()) & mask) >> from;}
constexpr
operator result_type() const { return (expr_type(allbits) & mask) >> from;}
void operator=(result_type newval) volatile & { // don't support chaining!
assert(0==(newval& ~widthmask));
allbitsvolatileforwrite() = UINT((expr_type(allbitsvolatileforread()) & ~mask ) | ((expr_type(newval)&widthmask)<<from));
}
constexpr void operator=(result_type newval) & { // don't support chaining!
assert(0==(newval& ~widthmask));
allbits = UINT((expr_type(allbits) & ~mask) | ((expr_type(newval)&widthmask)<<from));
}
// prevent copying as bitfield struct and thus surrounding union:
bitfield& operator=(bitfield&&) & noexcept = delete;
UINT allbits;
};
namespace detail{
template<typename UINT=uint32_t>
using allbits=bitfield<0,std::numeric_limits<UINT>::digits,UINT>;
}
// for use as first union member
using allbits64 = detail::allbits<uint64_t >;
using allbits32 = detail::allbits<uint32_t >;
using allbits16 = detail::allbits<uint16_t >;
using allbits8 = detail::allbits<uint8_t >;
template<uint8_t from, uint8_t width>
using bits8 = bitfield<from,width,uint8_t>;
template<uint8_t from, uint8_t width>
using bits16 = bitfield<from,width,uint16_t>;
template<uint8_t from, uint8_t width>
using bits32 = bitfield<from,width,uint32_t>;
template<uint8_t from, uint8_t width>
using bits64 = bitfield<from,width,uint64_t>;
}
#endif /* PSBITFIELD_H_ */
|
NFAcz/RAWcooked | Source/Lib/ThirdParty/endianness.h | /**
* @file endianness.h
* @brief Convert Endianness of shorts, longs, long longs, regardless of architecture/OS
*
* Defines (without pulling in platform-specific network include headers):
* bswap16, bswap32, bswap64, ntoh16, hton16, ntoh32 hton32, ntoh64, hton64
*
* Should support linux / macos / solaris / windows.
* Supports GCC (on any platform, including embedded), MSVC2015, and clang,
* and should support intel, solaris, and ibm compilers as well.
*
* Copyright 2020 github user jtbr, Released under MIT license
* Updated by MediaArea.net with l and b swap variants + C++ overloads
*/
#ifndef ENDIANNESS_H_
#define ENDIANNESS_H_
#include <stdlib.h>
#include <stdint.h>
#ifdef __cplusplus
#include <cstring> // for memcpy
#endif
/* Detect platform endianness at compile time */
// If boost were available on all platforms, could use this instead to detect endianness
// #include <boost/predef/endian.h>
// When available, these headers can improve platform endianness detection
#ifdef __has_include // C++17, supported as extension to C++11 in clang, GCC 5+, vs2015
# if __has_include(<endian.h>)
# include <endian.h> // gnu libc normally provides, linux
# elif __has_include(<machine/endian.h>)
# include <machine/endian.h> //open bsd, macos
# elif __has_include(<sys/param.h>)
# include <sys/param.h> // mingw, some bsd (not open/macos)
# elif __has_include(<sys/isadefs.h>)
# include <sys/isadefs.h> // solaris
# endif
#endif
#if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
# if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || \
(defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN) || \
(defined(_BYTE_ORDER) && _BYTE_ORDER == _BIG_ENDIAN) || \
(defined(BYTE_ORDER) && BYTE_ORDER == BIG_ENDIAN) || \
(defined(__sun) && defined(__SVR4) && defined(_BIG_ENDIAN)) || \
defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__) || \
defined(_M_PPC)
# define __BIG_ENDIAN__
# elif (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || /* gcc */\
(defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN) /* linux header */ || \
(defined(_BYTE_ORDER) && _BYTE_ORDER == _LITTLE_ENDIAN) || \
(defined(BYTE_ORDER) && BYTE_ORDER == LITTLE_ENDIAN) /* mingw header */ || \
(defined(__sun) && defined(__SVR4) && defined(_LITTLE_ENDIAN)) || /* solaris */ \
defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \
defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) || \
defined(_M_IX86) || defined(_M_X64) || defined(_M_IA64) || /* msvc for intel processors */ \
defined(_M_ARM) /* msvc code on arm executes in little endian mode */
# define __LITTLE_ENDIAN__
# endif
#endif
#if !defined(__LITTLE_ENDIAN__) & !defined(__BIG_ENDIAN__)
# error "UNKNOWN Platform / endianness. Configure endianness checks for this platform or set explicitly."
#endif
#if defined(bswap16) || defined(bswap32) || defined(bswap64) || defined(bswapf) || defined(bswapd)
# error "unexpected define!" // freebsd may define these; probably just need to undefine them
#endif
/* Define byte-swap functions, using fast processor-native built-ins where possible */
#if defined(_MSC_VER) // needs to be first because msvc doesn't short-circuit after failing defined(__has_builtin)
# define bswap16(x) _byteswap_ushort((x))
# define bswap32(x) _byteswap_ulong((x))
# define bswap64(x) _byteswap_uint64((x))
#elif (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
# define bswap16(x) __builtin_bswap16((x))
# define bswap32(x) __builtin_bswap32((x))
# define bswap64(x) __builtin_bswap64((x))
#elif defined(__has_builtin) && __has_builtin(__builtin_bswap64) /* for clang; gcc 5 fails on this and && shortcircuit fails; must be after GCC check */
# define bswap16(x) __builtin_bswap16((x))
# define bswap32(x) __builtin_bswap32((x))
# define bswap64(x) __builtin_bswap64((x))
#else
/* even in this case, compilers often optimize by using native instructions */
static inline uint16_t bswap16(uint16_t x) {
return ((( x >> 8 ) & 0xffu ) | (( x & 0xffu ) << 8 ));
}
static inline uint32_t bswap32(uint32_t x) {
return ((( x & 0xff000000u ) >> 24 ) |
(( x & 0x00ff0000u ) >> 8 ) |
(( x & 0x0000ff00u ) << 8 ) |
(( x & 0x000000ffu ) << 24 ));
}
static inline uint64_t bswap64(uint64_t x) {
return ((( x & 0xff00000000000000ull ) >> 56 ) |
(( x & 0x00ff000000000000ull ) >> 40 ) |
(( x & 0x0000ff0000000000ull ) >> 24 ) |
(( x & 0x000000ff00000000ull ) >> 8 ) |
(( x & 0x00000000ff000000ull ) << 8 ) |
(( x & 0x0000000000ff0000ull ) << 24 ) |
(( x & 0x000000000000ff00ull ) << 40 ) |
(( x & 0x00000000000000ffull ) << 56 ));
}
#endif
//! Byte-swap 32-bit float
static inline float bswapf(float f) {
#ifdef __cplusplus
static_assert(sizeof(float) == sizeof(uint32_t), "Unexpected float format");
/* Problem: de-referencing float pointer as uint32_t breaks strict-aliasing rules for C++ and C, even if it normally works
* uint32_t val = bswap32(*(reinterpret_cast<const uint32_t *>(&f)));
* return *(reinterpret_cast<float *>(&val));
*/
// memcpy approach is guaranteed to work in C & C++ and fn calls should be optimized out:
uint32_t asInt;
std::memcpy(&asInt, reinterpret_cast<const void *>(&f), sizeof(uint32_t));
asInt = bswap32(asInt);
std::memcpy(&f, reinterpret_cast<void *>(&asInt), sizeof(float));
return f;
#else
_Static_assert(sizeof(float) == sizeof(uint32_t), "Unexpected float format");
// union approach is guaranteed to work in C99 and later (but not in C++, though in practice it normally will):
union { uint32_t asInt; float asFloat; } conversion_union;
conversion_union.asFloat = f;
conversion_union.asInt = bswap32(conversion_union.asInt);
return conversion_union.asFloat;
#endif
}
//! Byte-swap 64-bit double
static inline double bswapd(double d) {
#ifdef __cplusplus
static_assert(sizeof(double) == sizeof(uint64_t), "Unexpected double format");
uint64_t asInt;
std::memcpy(&asInt, reinterpret_cast<const void *>(&d), sizeof(uint64_t));
asInt = bswap64(asInt);
std::memcpy(&d, reinterpret_cast<void *>(&asInt), sizeof(double));
return d;
#else
_Static_assert(sizeof(double) == sizeof(uint64_t), "Unexpected double format");
union { uint64_t asInt; double asDouble; } conversion_union;
conversion_union.asDouble = d;
conversion_union.asInt = bswap64(conversion_union.asInt);
return conversion_union.asDouble;
#endif
}
/* Define network - host byte swaps as needed depending upon platform endianness */
// (note that network order is big endian)
#if defined(__LITTLE_ENDIAN__)
# define ntoh16(x) bswap16((x))
# define hton16(x) bswap16((x))
# define ntoh32(x) bswap32((x))
# define hton32(x) bswap32((x))
# define ntoh64(x) bswap64((x))
# define hton64(x) bswap64((x))
# define ntohf(x) bswapf((x))
# define htonf(x) bswapf((x))
# define ntohd(x) bswapd((x))
# define htond(x) bswapd((x))
# define btoh16(x) bswap16((x))
# define htob16(x) bswap16((x))
# define btoh32(x) bswap32((x))
# define htob32(x) bswap32((x))
# define btoh64(x) bswap64((x))
# define htob64(x) bswap64((x))
# define btohf(x) bswapf((x))
# define htobf(x) bswapf((x))
# define btohd(x) bswapd((x))
# define htobd(x) bswapd((x))
# define ltoh16(x) (x)
# define htol16(x) (x)
# define ltoh32(x) (x)
# define htol32(x) (x)
# define ltoh64(x) (x)
# define htol64(x) (x)
# define ltohf(x) (x)
# define htolf(x) (x)
# define ltohd(x) (x)
# define htold(x) (x)
#elif defined(__BIG_ENDIAN__)
# define ntoh16(x) (x)
# define hton16(x) (x)
# define ntoh32(x) (x)
# define hton32(x) (x)
# define ntoh64(x) (x)
# define hton64(x) (x)
# define ntohf(x) (x)
# define htonf(x) (x)
# define ntohd(x) (x)
# define htond(x) (x)
# define btoh16(x) (x)
# define htob16(x) (x)
# define btoh32(x) (x)
# define htob32(x) (x)
# define btoh64(x) (x)
# define htob64(x) (x)
# define btohf(x) (x)
# define htobf(x) (x)
# define btohd(x) (x)
# define htobd(x) (x)
# define ltoh16(x) bswap16((x))
# define htol16(x) bswap16((x))
# define ltoh32(x) bswap32((x))
# define htol32(x) bswap32((x))
# define ltoh64(x) bswap64((x))
# define htol64(x) bswap64((x))
# define ltohf(x) bswapf((x))
# define htolf(x) bswapf((x))
# define ltohd(x) bswapd((x))
# define htold(x) bswapd((x))
# else
# warning "UNKNOWN Platform / endianness; network / host byte swaps not defined."
#endif
#if defined(__cplusplus) && (defined(__LITTLE_ENDIAN__) || defined(__BIG_ENDIAN__))
static inline uint16_t ntoh(uint16_t x) { return ntoh16(x); }
static inline uint16_t hton(uint16_t x) { return hton16(x); }
static inline uint32_t ntoh(uint32_t x) { return ntoh32(x); }
static inline uint32_t hton(uint32_t x) { return hton32(x); }
static inline uint64_t ntoh(uint64_t x) { return ntoh64(x); }
static inline uint64_t hton(uint64_t x) { return hton64(x); }
static inline float ntoh(float x) { return ntohf (x); }
static inline float hton(float x) { return htonf (x); }
static inline double ntoh(double x) { return ntohd (x); }
static inline double hton(double x) { return htond (x); }
static inline uint16_t btoh(uint16_t x) { return btoh16(x); }
static inline uint16_t htob(uint16_t x) { return htob16(x); }
static inline uint32_t btoh(uint32_t x) { return btoh32(x); }
static inline uint32_t htob(uint32_t x) { return htob32(x); }
static inline uint64_t btoh(uint64_t x) { return btoh64(x); }
static inline uint64_t htob(uint64_t x) { return htob64(x); }
static inline float btoh(float x) { return btohf (x); }
static inline float htob(float x) { return htobf (x); }
static inline double btoh(double x) { return btohd (x); }
static inline double htob(double x) { return htobd (x); }
static inline uint16_t ltoh(uint16_t x) { return ltoh16(x); }
static inline uint16_t htol(uint16_t x) { return htol16(x); }
static inline uint32_t ltoh(uint32_t x) { return ltoh32(x); }
static inline uint32_t htol(uint32_t x) { return htol32(x); }
static inline uint64_t ltoh(uint64_t x) { return ltoh64(x); }
static inline uint64_t htol(uint64_t x) { return htol64(x); }
static inline float ltoh(float x) { return ltohf (x); }
static inline float htol(float x) { return htolf (x); }
static inline double ltoh(double x) { return ltohd (x); }
static inline double htol(double x) { return htold (x); }
#endif
#endif //ENDIANNESS_H_ |
NFAcz/RAWcooked | Source/Lib/Transform/Transform.h | /* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#ifndef TransformH
#define TransformH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "Lib/Config.h"
using namespace std;
class raw_frame;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class transform_base
{
public:
virtual void From(pixel_t* P1, pixel_t* P2 = nullptr, pixel_t* P3 = nullptr, pixel_t* P4 = nullptr) = 0;
};
//---------------------------------------------------------------------------
enum class pix_style
{
RGBA,
YUVA,
};
//---------------------------------------------------------------------------
transform_base* Transform_Init(raw_frame* RawFrame, pix_style PixStyle, size_t Bits, size_t x_offset, size_t y_offset, size_t w, size_t h);
//---------------------------------------------------------------------------
#endif
|
NFAcz/RAWcooked | Source/CLI/Global.h | /* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#ifndef GlobalH
#define GlobalH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "CLI/Config.h"
#include "Lib/Config.h"
#include "Lib/Uncompressed/HashSum/HashSum.h"
#include "Lib/License/License.h"
#include <map>
#include <vector>
#include <string>
#include <thread>
#include <bitset>
using namespace std;
//---------------------------------------------------------------------------
//--------------------------------------------------------------------------
class global
{
public:
// Options
map<string, string> VideoInputOptions;
map<string, string> OutputOptions;
size_t AttachmentMaxSize;
string rawcooked_reversibility_FileName;
string OutputFileName;
string FrameMd5FileName;
string BinName;
string LicenseKey;
uint64_t SubLicenseId;
uint64_t SubLicenseDur;
bool IgnoreLicenseKey;
bool ShowLicenseKey;
bool StoreLicenseKey;
bool DisplayCommand;
bool AcceptFiles;
bool HasAtLeastOneDir;
bool HasAtLeastOneFile;
bool OutputFileName_IsProvided;
bool Quiet;
bitset<Action_Max> Actions;
// Intermediate info
size_t Path_Pos_Global;
vector<string> Inputs;
license License;
user_mode Mode = Ask;
hashes Hashes;
errors Errors;
ask_callback Ask_Callback = nullptr;
// Conformance check intermediary info
vector<double> Durations;
vector<string> Durations_FileName;
// Options
int ManageCommandLine(const char* argv[], int argc);
int SetDefaults();
// Progress indicator
void ProgressIndicator_Start(size_t Total);
void ProgressIndicator_Increment() { ProgressIndicator_Current++; }
void ProgressIndicator_Stop();
condition_variable ProgressIndicator_IsEnd;
bool ProgressIndicator_IsPaused = false;
// Theading relating functions
void ProgressIndicator_Show();
int SetCheck(bool Value);
int SetVersion(const char* Value);
private:
int SetOption(const char* argv[], int& i, int argc);
int SetOutputFileName(const char* FileName);
int SetBinName(const char* FileName);
int SetLicenseKey(const char* Key, bool Add);
int SetSubLicenseId(uint64_t Id);
int SetSubLicenseDur(uint64_t Dur);
int SetDisplayCommand();
int SetAcceptFiles();
int SetCheck(const char* Value, int& i);
int SetQuickCheck();
int SetCheckPadding(bool Value);
int SetQuickCheckPadding();
int SetAcceptGaps(bool Value);
int SetCoherency(bool Value);
int SetConch(bool Value);
int SetDecode(bool Value);
int SetEncode(bool Value);
int SetInfo(bool Value);
int SetFrameMd5(bool Value);
int SetFrameMd5FileName(const char* FileName);
int SetHash(bool Value);
int SetAll(bool Value);
// Progress indicator
thread* ProgressIndicator_Thread;
size_t ProgressIndicator_Current;
size_t ProgressIndicator_Total;
};
#endif
|
NFAcz/RAWcooked | Source/Lib/Compressed/RAWcooked/RAWcooked.h | <filename>Source/Lib/Compressed/RAWcooked/RAWcooked.h
/* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#ifndef RawCookedH
#define RawCookedH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "Lib/Compressed/RAWcooked/IntermediateWrite.h"
#include <condition_variable>
#include <cstdint>
#include <cstddef>
#include <string>
using namespace std;
//---------------------------------------------------------------------------
class rawcooked : public intermediate_write
{
public:
rawcooked();
~rawcooked();
bool Unique = false; // If set, data is for the whole stream (unique file)
const uint8_t* BeforeData = nullptr;
uint64_t BeforeData_Size = 0;
const uint8_t* AfterData = nullptr;
uint64_t AfterData_Size = 0;
const uint8_t* InData = nullptr;
uint64_t InData_Size = 0;
md5* HashValue = nullptr;
bool IsAttachment = false;
void Parse();
void ResetTrack();
string OutputFileName;
string OutputFileName_Full;
uint64_t FileSize = 0;
filemap* ReversibilityFile = nullptr;
enum class version
{
v1,
mini,
v2,
};
version Version = version::v1;
private:
// Private
class private_data;
private_data* const Data_;
};
//---------------------------------------------------------------------------
#endif
|
NFAcz/RAWcooked | Source/CLI/Output.h | /* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#ifndef OutputH
#define OutputH
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "CLI/Config.h"
#include "CLI/Global.h"
#include <string>
#include <vector>
using namespace std;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
struct stream
{
string FileName;
string FileName_Template;
string FileName_StartNumber;
string FileName_EndNumber;
string FileList;
string Flavor;
string Slices;
string FrameRate;
bool Problem;
stream()
: Problem(false)
{}
};
struct attachment
{
string FileName_In; // Complete path
string FileName_Out; // Relative path
};
class output
{
public:
// To be filled by external means
vector<stream> Streams;
vector<attachment> Attachments;
// Commands
int Process(global& Global, bool IgnoreReversibilityFile = false);
private:
int FFmpeg_Command(const char* FileName, global& Global, bool IgnoreReversibilityFile = false);
};
#endif
|
chronoxor/CppTemplate | include/template/version.h | <filename>include/template/version.h<gh_stars>10-100
/*!
\file version.h
\brief Version definition
\author <NAME>
\date 26.05.2016
\copyright MIT License
*/
#ifndef CPPTEMPLATE_VERSION_H
#define CPPTEMPLATE_VERSION_H
/*! \mainpage C++ Template Library
C++ Template Library contains initial templates for a new C++ library project.
This document contains CppTemplate API references.
Library description, features, requirements and usage examples can be find on
GitHub: https://github.com/chronoxor/CppTemplate
*/
/*!
\namespace CppTemplate
\brief C++ Template project definitions
*/
namespace CppTemplate {
//! Project version
const char version[] = "1.0.2.0";
} // namespace CppTemplate
#endif // CPPTEMPLATE_VERSION_H
|
chronoxor/CppTemplate | include/template/function.h | /*!
\file function.h
\brief Template function definition
\author <NAME>
\date 26.05.2016
\copyright MIT License
*/
#ifndef CPPTEMPLATE_TEMPLATE_FUNCTION_H
#define CPPTEMPLATE_TEMPLATE_FUNCTION_H
namespace CppTemplate {
//! Template function
/*!
Template function details.
Thread-safe.
\param parameter - Template function parameter
\return Template function result
*/
int function(int parameter);
/*! \example template_function.cpp Template function example */
} // namespace CppTemplate
#endif // CPPTEMPLATE_TEMPLATE_FUNCTION_H
|
chronoxor/CppTemplate | include/template/class.h | /*!
\file class.h
\brief Template class definition
\author <NAME>
\date 26.05.2016
\copyright MIT License
*/
#ifndef CPPTEMPLATE_TEMPLATE_CLASS_H
#define CPPTEMPLATE_TEMPLATE_CLASS_H
namespace CppTemplate {
//! Template class
/*!
Template class details.
Thread-safe.
*/
class Template
{
public:
//! Default class constructor
/*!
\param filed - Filed value
*/
explicit Template(int filed) noexcept : _field(filed) {}
Template(const Template&) noexcept = default;
Template(Template&&) noexcept = default;
~Template() noexcept = default;
Template& operator=(const Template&) noexcept = default;
Template& operator=(Template&&) noexcept = default;
//! Get field value
int field() const noexcept { return _field; }
//! Some method
/*!
\param parameter - Method parameter
\return Method result
*/
int Method(int parameter) const noexcept;
//! Some static method
/*!
\param parameter - Static method parameter
\return Static method result
*/
static int StaticMethod(int parameter) noexcept;
private:
int _field;
};
/*! \example template_class.cpp Template class example */
} // namespace CppTemplate
#include "class.inl"
#endif // CPPTEMPLATE_TEMPLATE_CLASS_H
|
TheJamsh/UE4VoxelTerrain | UE4VoxelTerrain/Source/UE4VoxelTerrain/UE4VoxelTerrain.h | <reponame>TheJamsh/UE4VoxelTerrain
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#ifndef __UE4VOXELTERRAIN_H__
#define __UE4VOXELTERRAIN_H__
#include "EngineMinimal.h"
DECLARE_LOG_CATEGORY_EXTERN(LogUE4VoxelTerrain, Log, All);
#endif
|
TheJamsh/UE4VoxelTerrain | UE4VoxelTerrain/Source/UE4VoxelTerrain/UI/SystemInfoWidget.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Runtime/UMG/Public/UMG.h"
#include "Runtime/UMG/Public/UMGStyle.h"
#include "Runtime/UMG/Public/Slate/SObjectWidget.h"
#include "Runtime/UMG/Public/IUMGModule.h"
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"
#include "TerrainController.h"
#include "Blueprint/UserWidget.h"
#include "SystemInfoWidget.generated.h"
/**
*
*/
UCLASS()
class UE4VOXELTERRAIN_API USystemInfoWidget : public UUserWidget
{
GENERATED_BODY()
protected:
UFUNCTION(BlueprintCallable, Category = "SandboxHUD")
FString sandboxSystemInfoText();
UFUNCTION(BlueprintCallable, Category = "SandboxHUD")
float sandboxSystemInfoPercent();
UFUNCTION(BlueprintCallable, Category = "SandboxHUD")
ESlateVisibility sandboxSystemInfoVisiblity();
private:
ATerrainController* controller;
ATerrainController* getController();
};
|
TheJamsh/UE4VoxelTerrain | UE4VoxelTerrain/Source/UE4VoxelTerrain/UE4VoxelTerrainPlayerController.h | <reponame>TheJamsh/UE4VoxelTerrain
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/PlayerController.h"
#include "SandboxPlayerController.h"
#include "UE4VoxelTerrainPlayerController.generated.h"
UCLASS()
class AUE4VoxelTerrainPlayerController : public ASandboxPlayerController
{
GENERATED_BODY()
public:
AUE4VoxelTerrainPlayerController();
protected:
virtual void PlayerTick(float DeltaTime) override;
virtual void SetupInputComponent() override;
virtual void OnMainActionPressed();
virtual void OnMainActionReleased();
virtual void OnAltActionPressed();
virtual void OnAltActionReleased();
void PerformAction();
public:
int tool_mode = 0;
FHitResult TracePlayerActionPoint();
private:
FTimerHandle timer;
void setTool0();
void setTool1();
void setTool2();
void setTool3();
void setTool4();
void setTool5();
void setTool6();
void setTool7();
};
|
TheJamsh/UE4VoxelTerrain | UE4VoxelTerrain/Source/UE4VoxelTerrain/TerrainController.h | <filename>UE4VoxelTerrain/Source/UE4VoxelTerrain/TerrainController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "SandboxTerrainController.h"
#include "TerrainController.generated.h"
/**
*
*/
UCLASS()
class UE4VOXELTERRAIN_API ATerrainController : public ASandboxTerrainController
{
GENERATED_BODY()
public:
virtual SandboxVoxelGenerator newTerrainGenerator(TVoxelData &voxel_data) override;
int32 ZoneLoaderConter = 0;
int32 ZoneLoaderTotal = 0;
protected:
virtual void OnLoadZoneProgress(int progress, int total) override;
virtual void OnLoadZoneListFinished() override;
};
|
particle-iot/CellularHelper | src/CellularHelper.h | <gh_stars>1-10
#ifndef __CELLULARHELPER_H
#define __CELLULARHELPER_H
#include "Particle.h"
#if Wiring_Cellular
// Class to hold results from getting network information
class CellularHelperNetworkInfo {
public:
String accessTechnology;
uint16_t mcc;
uint16_t mnc;
String band;
};
// Class for quering information directly from the u-blox SARA modem
/**
* @brief Common base class for response objects
*
* All response objects inherit from this, so the parse() method can be called
* in the subclass, and also the resp and enableDebug members are always available.
*/
class CellularHelperCommonResponse {
public:
/**
* @brief Response code from Cellular.command
*
* The typical return values are:
* - RESP_OK = -2
* - RESP_ERROR = -3
* - RESP_ABORTED = -5
*/
int resp = RESP_ERROR;
/**
* @brief Enables debug mode (default: false)
*
* If you set this to true in your response object class, additional debugging logs
* (Log.info, etc.) will be generated to help troubleshoot problems.
*/
bool enableDebug = false;
/**
* @brief Method to parse the output from the modem
*
* @param type one of 13 different enumerated AT command response types.
*
* @param buf a pointer to the character array containing the AT command response.
*
* @param len length of the AT command response buf.
* This is called from responseCallback, which is the callback to Cellular.command.
*
* In the base class CellularHelperCommonResponse this is pure virtual and must be
* subclassed in your concrete subclass of CellularHelperCommonResponse.
*/
virtual int parse(int type, const char *buf, int len) = 0;
/**
* @brief Used when enableDebug is true to log the Cellular.command callback data using Log.info
*
* @param type one of 13 different enumerated AT command response types.
*
* @param buf a pointer to the character array containing the AT command response.
*
* @param len length of the AT command response buf.
*/
void logCellularDebug(int type, const char *buf, int len) const;
};
/**
* @brief Things that return a simple string, like the manufacturer string, use this
*
* Since it inherits from CellularHelperCommonResponse you
* can check resp == RESP_OK to make sure the call succeeded.
*/
class CellularHelperStringResponse : public CellularHelperCommonResponse {
public:
/**
* @brief Returned string is stored here
*/
String string;
/**
* @brief Method to parse the output from the modem
*
* @param type one of 13 different enumerated AT command response types.
*
* @param buf a pointer to the character array containing the AT command response.
*
* @param len length of the AT command response buf.
*
* This is called from responseCallback, which is the callback to Cellular.command.
*
* This class just appends all TYPE_UNKNOWN data into string.
*/
virtual int parse(int type, const char *buf, int len);
};
/**
* @brief Things that return a + response and a string use this.
*
* Since it inherits from CellularHelperCommonResponse you
* can check resp == RESP_OK to make sure the call succeeded.
*/
class CellularHelperPlusStringResponse : public CellularHelperCommonResponse {
public:
/**
* @brief Your subclass must set this to the command requesting (not including the AT+ part)
*
* Say you're implementing an AT+CSQ response handler. You would set command to "CSQ". This
* is because the modem will return +CSQ as the response so the parser needs to know what
* to look for.
*/
String command;
/**
* @brief Returned string is stored here
*/
String string;
/**
* @brief Method to parse the output from the modem
*
* @param type one of 13 different enumerated AT command response types.
*
* @param buf a pointer to the character array containing the AT command response.
*
* @param len length of the AT command response buf.
*
* This is called from responseCallback, which is the callback to Cellular.command.
*
* This class just appends all + responses (TYPE_PLUS) that match command into string.
*/
virtual int parse(int type, const char *buf, int len);
/**
* @brief Gets the double quoted part of a string response
*
* @param onlyFirst (boolean, default true) Only the first double quoted string
* is returned if true. If false, all double quoted strings are concatenated,
* ignoring all of the parts outside of the double quotes.
*
* Some commands, like AT+UDOPN return a + response that contains a double quoted
* string. If you only want to extract this string, you can use this method to
* extract it.
*
*/
String getDoubleQuotedPart(bool onlyFirst = true) const;
};
/**
* @brief This class is used to return the rssi and qual values (AT+CSQ)
*
* Note that for 2G, qual is not available and 99 is always returned.
*
* Since it inherits from CellularHelperPlusStringResponse and CellularHelperCommonResponse you
* can check resp == RESP_OK to make sure the call succeeded.
*
* This class is the result of CellularHelper.getRSSIQual(); you normally wouldn't
* instantiate one of these directly.
*/
class CellularHelperRSSIQualResponse : public CellularHelperPlusStringResponse {
public:
/**
* @brief RSSI Received Signal Strength Indication value
*
* Values:
* - 0: -113 dBm or less
* - 1: -111 dBm
* - 2..30: from -109 to -53 dBm with 2 dBm steps
* - 31: -51 dBm or greater
* - 99: not known or not detectable or currently not available
*/
int rssi = 99;
/**
* @brief Signal quality value
*
* Values:
* - 0..7: Signal quality, 0 = good, 7 = bad
* - 99: not known or not detectable or currently not available
*/
int qual = 99;
/**
* @brief Parses string and stores the results in rssi and qual
*/
void postProcess();
/**
* @brief Converts this object into a string
*
* The string will be of the format `rssi=-50 qual=3`. If either value is unknown, it will
* show as 99.
*/
String toString() const;
};
/**
* @brief Response class for the AT+CESQ command
*
* This class is the result of CellularHelper.getExtendedQual(); you normally wouldn't
* instantiate one of these directly.
*/
class CellularHelperExtendedQualResponse : public CellularHelperPlusStringResponse {
public:
/**
* @brief Received Signal Strength Indication (RSSI)
*
* Values:
* - 0: less than -110 dBm
* - 1..62: from -110 to -49 dBm with 1 dBm steps
* - 63: -48 dBm or greater
* - 99: not known or not detectable
*/
uint8_t rxlev = 99;
/**
* @brief Bit Error Rate (BER)
*
* Values:
* - 0..7: as the RXQUAL values described in GSM TS 05.08 [28]
* - 99: not known or not detectable
*/
uint8_t ber = 99;
/**
* @brief Received Signal Code Power (RSCP)
*
* Values:
* - 0: -121 dBm or less
* - 1..95: from -120 dBm to -24 dBm with 1 dBm steps
* - 96: -25 dBm or greater
* - 255: not known or not detectable
*/
uint8_t rscp = 99;
/**
* @brief Ratio of received energy per PN chip to the total received power spectral density
*
* Values:
* - 0: -24.5 dB or less
* - 1..48: from -24 dB to -0.5 dBm with 0.5 dB steps
* - 49: 0 dB or greater
* - 255: not known or not detectable
*/
uint8_t ecn0 = 255;
/**
* @brief Reference Signal Received Quality (RSRQ)
*
* Values:
* - 0: -19 dB or less
* - 1..33: from -19.5 dB to -3.5 dB with 0.5 dB steps
* - 34: -3 dB or greater
* - 255: not known or not detectable Number
*/
uint8_t rsrq = 255;
/**
* @brief Reference Signal Received Power (RSRP)
*
* Values:
* - 0: -141 dBm or less
* - 1..96: from -140 dBm to -45 dBm with 1 dBm steps
* - 97: -44 dBm or greater
* - 255: not known or not detectable
*/
uint8_t rsrp = 255;
/**
* @brief Converts the data in string into the broken out fields like rxlev, ber, rsrq, etc.
*/
void postProcess();
/**
* @brief Converts this object into a string
*
* The string will be of the format `rxlev=99 ber=99 rscp=255 ecn0=255 rsrq=0 rsrp=37`.
* Unknown values for rxlev, ber, and rscp are 99.
* Unknown values for ecn0, rsrq, rsrp are 255.
*/
String toString() const;
};
/**
* @brief Used to hold the results for one cell (service or neighbor) from the AT+CGED command
*
* You will normally use CellularHelperEnvironmentResponseStatic<> or CellularHelperEnvironmentResponse
* which includes this as a member.
*/
class CellularHelperEnvironmentCellData { // 44 bytes
public:
/**
* @brief Mobile Country Code
*
* - Range 0 - 999 (3 digits). Other values are to be considered invalid / not available.
*/
int mcc = 65535;
/**
* @brief Mobile Network Code
*
* - Range 0 - 999 (1 to 3 digits). Other values are to be considered invalid / not available.
*/
int mnc = 255;
/**
* @brief Location Area Code
*
* - Range 0h-FFFFh (2 octets).
*/
int lac;
/**
* @brief Cell Identity
*
* - 2G cell: range 0h-FFFFh (2 octets)
* - 3G cell: range 0h-FFFFFFFh (28 bits)
*/
int ci;
/**
* @brief Base Station Identify Code
*
* - Range 0h-3Fh (6 bits) [2G]
*/
int bsic;
/**
* @brief Absolute Radio Frequency Channel Number
*
* - Range 0 - 1023 [2G only]
* - The parameter value also decodes the band indicator bit (DCS or PCS) by means of the
* most significant byte (8 means 1900 band) (i.e. if the parameter reports the value 33485,
* it corresponds to 0x82CD, in the most significant byte there is the band indicator bit,
* so the `arfcn` is 0x2CD (717) and belongs to 1900 band).
*/
int arfcn;
/**
* @brief Received signal level on the cell
*
* - Range 0 - 63; see the 3GPP TS 05.08 [2G]
*/
int rxlev;
/**
* @brief RAT is GSM (false) or UMTS (true)
*/
bool isUMTS = false;
/**
* @brief Downlink frequency.
*
* - Range 0 - 16383 [3G only]
*/
int dlf;
/**
* @brief Uplink frequency. Range 0 - 16383 [3G only]
*/
int ulf;
/**
* @brief Received signal level [3G]
*
* Received Signal Code Power expressed in dBm levels. Range 0 - 91.
*
* | Value | RSCP | Note |
* | :---: | :---: | :--- |
* | 0 | RSCP < -115 dBm | Weak |
* | 1 | -115 <= RSCP < -114 dBm | |
* | 90 | -26 <= RSCP < -25 dBm | |
* | 91 | RSCP == -25 dBm | Strong |
*/
int rscpLev = 255;
/**
* @brief Returns true if this object looks valid
*
* @param ignoreCI (bool, default false) Sometimes the cell identifier (CI) valid is not
* returned by the towers but other fields are set. Passing true in this parameter causes
* the CI to be ignored.
*
* @return true if the object looks valid or false if not.
*/
bool isValid(bool ignoreCI = false) const;
/**
* @brief Parses the output from the modem (used internally)
*
* Some classes use postprocess() to process the + response, but the AT+CGED response
* is sufficiently complicated that we parse each response as it comes in using the parse()
* method rather than waiting until all responses have come in.
*
* @param str The comma separated response from the modem to parse
*/
void parse(const char *str);
/**
* @brief Add a key-value pair (used internally)
*
* The AT+CGED response contains key-value pairs. This parses out the ones we care about and
* stores them in the specific fields of this structure.
*/
void addKeyValue(const char *key, const char *value);
/**
* @brief Returns a readable representation of this object as a String
*
*/
String toString() const;
// Calculated
/**
* @brief Calculated field to determine the cellular frequency band
*
* Values are frequency in MHz, such as: 700, 800, 850, 900, 1700, 1800, 1900, 2100
*
* Not all bands are used by existing hardware.
*
* Note that for 2G, 1800 is returned for the 1900 MHz band. This is because they
* use the same arfcn values. So 1800 really means 1800 or 1900 MHz for 2G.
*
*/
int getBand() const;
/**
* @brief Returns a readable string that identifies the cellular frequency band
*
* Example 3G: `rat=UMTS mcc=310, mnc=410, lac=1af7 ci=817b57f band=UMTS 850 rssi=0 dlf=4384 ulf=4159`
*
* Example 2G: `rat=GSM mcc=310, mnc=260, lac=ab22 ci=a78a band=DCS 1800 or 1900 rssi=-97 bsic=23 arfcn=596 rxlev=24`
*
*/
String getBandString() const;
/**
* @brief Get the RSSI (received signal strength indication)
*
* This only available on 3G devices, and even then is not always returned. It may be 0 or 255 if not known.
*/
int getRSSI() const;
/**
* @brief Get the RSSI as "bars" of signal strength (0-5)
*
* | RSSI | Bars |
* | :-----: | :---: |
* | >= -57 | 5 |
* | > -68 | 4 |
* | > -80 | 3 |
* | > -92 | 2 |
* | > -104 | 1 |
* | <= -104 | 0 |
*
* This is simlar to the bar graph display on phones.
*/
int getBars() const;
};
/**
* @brief Used to hold the results from the AT+CGED command
*
* You may want to use CellularHelperEnvironmentResponseStatic<> instead of separately allocating this
* object and the array of CellularHelperEnvironmentCellData.
*
* Using this class with the default contructor is handy if you are using ENVIRONMENT_SERVING_CELL mode
* with CellularHelper.getLocation()
*/
class CellularHelperEnvironmentResponse : public CellularHelperPlusStringResponse {
public:
/**
* @brief Constructor for AT+CGED without neighbor data
*
* Since only the Electron 2G (SARA-G350) supports getting neighbor data, this constructor can be
* used with ENVIRONMENT_SERVING_CELL to get only the serving cell.
*/
CellularHelperEnvironmentResponse();
/**
* @brief Constructor that takes an external array of CellularHelperEnvironmentCellData
*
* @param neighbors Pointer to array of CellularHelperEnvironmentCellData. Can be NULL.
*
* @param numNeighbors Number of items in neighbors. Can be 0.
*
* The templated CellularHelperEnvironmentResponseStatic<> uses this constructor but eliminates the
* need to separately allocate the neighbor CellularHelperEnvironmentCellData and may be easier
* to use.
*/
CellularHelperEnvironmentResponse(CellularHelperEnvironmentCellData *neighbors, size_t numNeighbors);
/**
* @brief Information about the service cell (the one you're connected to)
*
* Filled in in both ENVIRONMENT_SERVING_CELL and ENVIRONMENT_SERVING_CELL_AND_NEIGHBORS modes.
*/
CellularHelperEnvironmentCellData service;
/**
* @brief Information about the neighboring cells
*
* Only filled in when using ENVIRONMENT_SERVING_CELL_AND_NEIGHBORS mode, which only works on the
* 2G Electron (SARA-G350). Maximum number of neighboring cells is 30, however it will be further
* limited by the numNeighbors (the size of your array).
*
* The value of this member is passed into the constructor.
*/
CellularHelperEnvironmentCellData *neighbors;
/**
* @brief Number of entries in the neighbors array
*
* The value of this member is passed into the constructor.
*/
size_t numNeighbors;
/**
* @brief Current index we're writing to
*
* - -1 = service
* - 0 = first element of neighbors
* - 1 = second element of neighbors
* - ...
*/
int curDataIndex = -1;
/**
* @brief Method to parse the output from the modem
*
* @param type one of 13 different enumerated AT command response types.
*
* @param buf a pointer to the character array containing the AT command response.
*
* @param len length of the AT command response buf.
*
* This is called from responseCallback, which is the callback to Cellular.command.
*
*/
virtual int parse(int type, const char *buf, int len);
/**
* @brief Clear the data so the object can be reused
*/
void clear();
/**
* @brief Log the decoded environment data to the debug log using Log.info
*/
void logResponse() const;
/**
* @brief Gets the number of neighboring cells that were returned
*
* - 0 = no neighboring cells
* - 1 = one neighboring cell
* - ...
*/
size_t getNumNeighbors() const;
};
/**
* @brief Response class for getting cell tower information with statically defined array of neighbor cells
*
* @param MAX_NEIGHBOR_CELLS templated parameter for number of neighbors to allocate. Each one is 44 bytes. Can be 0.
*
* The maximum the modem supports is 30, however you can set it smaller. Beware of using values over 10 or so
* when storing this object on the stack as you could get a stack overflow.
*/
template <size_t MAX_NEIGHBOR_CELLS>
class CellularHelperEnvironmentResponseStatic : public CellularHelperEnvironmentResponse {
public:
explicit CellularHelperEnvironmentResponseStatic() : CellularHelperEnvironmentResponse(staticNeighbors, MAX_NEIGHBOR_CELLS) {
}
protected:
/**
* @brief Array of neighbor cell data
*/
CellularHelperEnvironmentCellData staticNeighbors[MAX_NEIGHBOR_CELLS];
};
/**
* @brief Reponse class for the AT+ULOC command
*
* This class is returned from CellularHelper.getLocation(). You normally won't instantiate one
* of these directly.
*/
class CellularHelperLocationResponse : public CellularHelperPlusStringResponse {
public:
/**
* @brief Set to true if the values have been set
*/
bool valid = false;
/**
* @brief Estimated latitude, in degrees (-90 to +90)
*/
float lat = 0.0;
/**
* @brief Estimated longitude, in degrees (-180 to +180)
*/
float lon = 0.0;
/**
* @brief Estimated altitude, in meters. Not always returned.
*/
int alt = 0;
/**
* @brief Maximum possible error, in meters (0 - 20000000)
*/
int uncertainty = 0;
/**
* @brief Returns true if a valid location was found
*/
bool isValid() const { return valid; };
/**
* @brief Converts the data in string into the broken out fields like lat, lon, alt, uncertainty.
*/
void postProcess();
/**
* @brief Converts this object into a readable string
*
* The string will be of the format `lat=12.345 lon=567.89 alt=0 uncertainty=2000`.
*/
String toString() const;
};
/**
* @brief Reponse class for the AT+CREG? command. This is deprecated and will be removed in the future.
*
* This class is returned from CelluarHelper.getCREG(). You normally won't instantiate one of these
* directly.
*/
class CellularHelperCREGResponse : public CellularHelperPlusStringResponse {
public:
/**
* @brief Set to true if the values have been set
*/
bool valid = false;
/**
* @brief Network connection status
*
* - 0: not registered, the MT is not currently searching a new operator to register to
* - 1: registered, home network
* - 2: not registered, but the MT is currently searching a new operator to register to
* - 3: registration denied
* - 4: unknown (e.g. out of GERAN/UTRAN/E-UTRAN coverage)
* - 5: registered, roaming
* - 6: registered for "SMSonly", home network(applicable only when AcTStatus indicates E-UTRAN)
* - 7: registered for "SMSonly",roaming (applicable only when AcTStatus indicates E-UTRAN)
* - 9: registered for "CSFBnotpreferred",home network(applicable only when AcTStatus indicates E-UTRAN)
* - 10 :registered for" CSFBnotpreferred",roaming (applicable only when AcTStatus indicates E-UTRAN)
*/
int stat = 0;
/**
* @brief Two bytes location area code or tracking area code
*/
int lac = 0xFFFF;
/**
* @brief Cell Identifier (CI)
*/
int ci = 0xFFFFFFFF;
/**
* @brief Radio access technology (RAT), the AcTStatus value in the response
*
* - 0: GSM
* - 1: GSM COMPACT
* - 2: UTRAN
* - 3: GSM with EDGE availability
* - 4: UTRAN with HSDPA availability
* - 5: UTRAN with HSUPA availability
* - 6: UTRAN with HSDPA and HSUPA availability
* - 7: E-UTRAN
* - 255: the current AcTStatus value is invalid
*/
int rat = 0;
/**
* @brief Returns true if the results were returned from the modem
*/
bool isValid() const { return valid; };
/**
* @brief Converts the data in string into the broken out fields like stat, lac, ci, rat.
*/
void postProcess();
/**
* @brief Converts this object into a readable string
*/
String toString() const;
};
/**
* @brief Reponse class for the AT+UCGED? command.
*
* This is used on the u-blox SARA-R410M to get the earfcn, to get the frequency band
*/
class CellularHelperUCGEDResponse : public CellularHelperCommonResponse {
public:
CellularHelperUCGEDResponse();
virtual ~CellularHelperUCGEDResponse();
virtual int parse(int type, const char *buf, int len);
int run();
public:
int earfcn = 0;
String rsrp;
String rsrq;
bool valid = false;
};
/**
* @brief Reponse class for the AT+QNWINFO command.
*
* This is used on Quectel modems to get the mcc, mnc, and channel (earfcn) information.
*/
class CellularHelperQNWINFOResponse : public CellularHelperPlusStringResponse {
public:
CellularHelperQNWINFOResponse();
virtual ~CellularHelperQNWINFOResponse();
/**
* @brief Converts the data in string into the broken out fields
*/
void postProcess();
/**
* @brief Returns true if the results were returned from the modem
*/
bool isValid() const { return valid; };
public:
bool valid = false;
String act;
int mcc;
int mnc;
String band;
int channel;
};
/**
* @brief Class for calling the u-blox SARA modem directly.
*
* Most of the methods you will need are in this class, and can be referenced using the
* global `CellularHelper` object. For example:
*
* ```
* String mfg = CellularHelper.getManufacturer();
* ```
*/
class CellularHelperClass {
public:
/**
* @brief Returns a string, typically "u-blox"
*/
String getManufacturer() const;
/**
* @brief Returns a string like "SARA-G350", "SARA-U260" or "SARA-U270"
*/
String getModel() const;
/**
* @brief Returns a string like "SARA-U260-00S-00".
*/
String getOrderingCode() const;
/**
* @brief Returns a string like "23.20"
*/
String getFirmwareVersion() const;
/**
* @brief Returns the IMEI for the modem
*
* Both IMEI and ICCID are commonly used identifiers. The IMEI is assigned to the modem itself.
* The ICCID is assigned to the SIM card.
*
* For countries that require the cellular devices to be registered, the IMEI is typically
* the number that is required.
*/
String getIMEI() const;
/**
* @brief Returns the IMSI for the modem
*/
String getIMSI() const;
/**
* @brief Returns the ICCID for the SIM card
*
* Both IMEI and ICCID are commonly used identifiers. The IMEI is assigned to the modem itself.
* The ICCID is assigned to the SIM card.
*/
String getICCID() const;
/**
* @brief Returns true if the device is LTE Cat-M1 (deprecated method)
*
* This method is deprecated. You should use isSARA_R4() instead. Included for backward
* compatibility for now.
*/
bool isLTE() const { return isSARA_R4(); };
/**
* @brief Returns true if the device is a u-blox SARA-R4 model (LTE-Cat M1)
*/
bool isSARA_R4() const;
/**
* @brief Returns the operator name string, something like "AT&T" or "T-Mobile" in the United States (2G/3G only)
*
* | Modem | Device | Compatible |
* | :------------: | :---: | :---: |
* | SARA-G350 | Gen 2 | Yes |
* | SARA-U260 | Gen 2 | Yes |
* | SARA-U270 | Gen 2 | Yes |
* | SARA-U201 | All | Yes |
* | SARA-R410M-02B | All | No |
*/
String getOperatorName(int operatorNameType = OPERATOR_NAME_LONG_EONS) const;
/**
* @brief Get the RSSI and qual values for the receiving cell site.
*
* The response structure contains the following public members:
*
* - resp - is RESP_OK if the call succeeded or RESP_ERROR on failure
*
* - rssi - RSSI Received Signal Strength Indication value
* - 0: -113 dBm or less
* - 1: -111 dBm
* - 2..30: from -109 to -53 dBm with 2 dBm steps
* - 31: -51 dBm or greater
* - 99: not known or not detectable or currently not available
*
* - qual - Signal quality
* - 0..7: Signal quality, 0 = good, 7 = bad
* - 99: not known or not detectable or currently not available
*
* The qual value is not always available.
*
* | Modem | Device | Qual Available |
* | :------------: | :---: | :---: |
* | SARA-G350 | Gen 2 | No |
* | SARA-U260 | Gen 2 | Usually |
* | SARA-U270 | Gen 2 | Usually |
* | SARA-U201 | All | Usually |
* | SARA-R410M-02B | All | No |
*/
CellularHelperRSSIQualResponse getRSSIQual() const;
/**
* @brief Gets extended quality information on LTE Cat M1 devices (SARA-R410M-02B) (AT+CESQ)
*
* The response structure contains the following public members:
*
* - resp - is RESP_OK if the call succeeded or RESP_ERROR on failure
*
* - rxlev - Received Signal Strength Indication (RSSI)
* - 0: less than -110 dBm
* - 1..62: from -110 to -49 dBm with 1 dBm steps
* - 63: -48 dBm or greater
* - 99: not known or not detectable
*
* - ber - Bit Error Rate (BER)
* - 0..7: as the RXQUAL values described in GSM TS 05.08 [28]
* - 99: not known or not detectable
*
* - rscp - Received Signal Code Power (RSCP)
* - 0: -121 dBm or less
* - 1..95: from -120 dBm to -24 dBm with 1 dBm steps
* - 96: -25 dBm or greater
* - 255: not known or not detectable
*
* - ecn0 - Ratio of received energy per PN chip to the total received power spectral density
* - 0: -24.5 dB or less
* - 1..48: from -24 dB to -0.5 dBm with 0.5 dB steps
* - 49: 0 dB or greater
* - 255: not known or not detectable
*
* - rsrq - Reference Signal Received Quality (RSRQ)
* - 0: -19 dB or less
* - 1..33: from -19.5 dB to -3.5 dB with 0.5 dB steps
* - 34: -3 dB or greater
* - 255: not known or not detectable Number
*
* - rsrp - Reference Signal Received Power (RSRP)
* - 0: -141 dBm or less
* - 1..96: from -140 dBm to -45 dBm with 1 dBm steps
* - 97: -44 dBm or greater
* - 255: not known or not detectable
*
*
* Compatibility:
*
* | Modem | Device | Available |
* | :------------: | :---: | :---: |
* | SARA-G350 | Gen 2 | No |
* | SARA-U260 | Gen 2 | No |
* | SARA-U270 | Gen 2 | No |
* | SARA-U201 | All | No |
* | SARA-R410M-02B | All | Yes |
*/
CellularHelperExtendedQualResponse getExtendedQual() const;
/**
* @brief Select the mobile operator (in areas where more than 1 carrier is supported by the SIM) (AT+COPS)
*
* @param mccMnc The MCC/MNC numeric string to identify the carrier. For examples, see the table below.
*
* @return true on success or false on error
*
* | MCC-MNC | Carrier |
* | :-----: | :--- |
* | 310410 | AT&T |
* | 310260 | T-Mobile |
*
* You must turn cellular on before making this call, but it's most efficient if you don't Cellular.connect()
* or Particle.connect(). You should use SYSTEM_MODE(SEMI_AUTOMATIC) or SYSTEM_MODE(MANUAL).
*
* If the selected carrier matches, this function return true quickly.
*
* If the carrier needs to be changed it may take 15 seconds or longer for the operation to complete.
*
* Omitting the mccMnc parameter or passing NULL will reset the default automatic mode.
*
* This setting is stored in the modem but reset on power down, so you should set it from setup().
*/
bool selectOperator(const char *mccMnc = NULL) const;
/**
* @brief Gets cell tower information (AT+CGED). Only on 2G/3G, does not work on LTE Cat M1.
*
* @param mode is whether to get the serving cell, or serving cell and neighboring cells:
*
* - ENVIRONMENT_SERVING_CELL - only the cell you're connected to
* - ENVIRONMENT_SERVING_CELL_AND_NEIGHBORS - note: only works on Electron 2G G350, not 3G models
*
* @param resp Filled in with the response data.
*
* Note: With Device OS 1.2.1 and later you should use the CellularGlobalIdentity built into
* Device OS instead of using this method (AT+CGED). CellularGlobalIdentity is much more efficient
* and works on LTE Cat M1 devices. The 5-cellular-global-identity example shows how to get the
* CI (cell identifier), LAC (location area code), MCC (mobile country code), and MNC (mobile
* network code) efficiently using CellularGlobalIdentity.
*
* | Modem | Device | Available | Neighbors Available |
* | :------------: | :---: | :-------: | :---: |
* | SARA-G350 | Gen 2 | Yes | Yes |
* | SARA-U260 | Gen 2 | Yes | No |
* | SARA-U270 | Gen 2 | Yes | No |
* | SARA-U201 | All | Yes | No |
* | SARA-R410M-02B | All | No | No |
*
*/
void getEnvironment(int mode, CellularHelperEnvironmentResponse &resp) const;
/**
* @brief Gets the location coordinates using the CellLocate feature of the u-blox modem (AT+ULOC)
*
* @param timeoutMs timeout in milliseconds. Should be at least 10 seconds.
*
* This may take several seconds to execute and only works on Gen 2 2G/3G devices. It does not
* work on Gen 3 and does not work on LTE M1 (SARA-R410M-02B). In general, we recommend
* using a cloud-based approach (google-maps-device-locator) instead of using CellLocate.
*
* Compatibility:
*
* | Modem | Device | Compatible |
* | :------------: | :---: | :---: |
* | SARA-G350 | Gen 2 | Yes |
* | SARA-U260 | Gen 2 | Yes |
* | SARA-U270 | Gen 2 | Yes |
* | SARA-U201 | Gen 2 | Yes |
* | SARA-U201 | Gen 3 | No |
* | SARA-R410M-02B | All | No |
*
*/
CellularHelperLocationResponse getLocation(unsigned long timeoutMs = DEFAULT_TIMEOUT) const;
/**
* @brief Gets the AT+CREG (registration info including CI and LAC) as an alternative to AT+CGED
*
* @param resp Filled in with the response data
*
* Note: This has limited support and using the CellularGlobalIdentity in Device OS 1.2.1 and later
* is the preferred method to get the CI and LAC. This function will be deprecated in the future.
*
* | Modem | Device | Device OS | Compatible |
* | :------------: | :---: | :-------: | :---: |
* | SARA-G350 | Gen 2 | < 1.2.1 | Yes |
* | SARA-U260 | Gen 2 | < 1.2.1 | Yes |
* | SARA-U270 | Gen 2 | < 1.2.1 | Yes |
* | SARA-U201 | Gen 2 | < 1.2.1 | Yes |
* | SARA-R410M-02B | Gen 2 | < 1.2.1 | Yes |
* | Any | Gen 3 | Any | No |
* | Any | Any | >= 1.2.1 | No |
*
*/
void getCREG(CellularHelperCREGResponse &resp) const;
/**
*/
void getQNWINFO(CellularHelperQNWINFOResponse &resp) const;
/**
* @brief Get information about the network connected to (accessTechology, mcc, mnc, band)
*/
bool getNetworkInfo(CellularHelperNetworkInfo &resp);
/**
* @brief Convert an access technology from CellularSignal into a readable string
*/
String getAccessTechnologyString(hal_net_access_tech_t rat);
/**
* @brief Get LTE band information from an earfcn (available from AT+UCGED on the SARA-R410M)
*/
bool getLTEBandInfo(int earfcn, int &bandNum, int &freq, String &bandStr);
/**
* @brief Append a buffer (pointer and length) to a String object
*
* Used internally to add data to a String object with buffer and length,
* which is not one of the built-in overloads for String. This format is
* what comes from the Cellular.command callbacks.
*
* @param str The String object to append to
*
* @param buf The buffer to copy from. Does not need to be null terminated.
*
* @param len The number of bytes to copy.
*
* @param noEOL (default: true) If true, don't copy CR and LF characters to the output.
*/
static void appendBufferToString(String &str, const char *buf, int len, bool noEOL = true);
/**
* @brief Default timeout in milliseconds. Passed to Cellular.command().
*
* Several commands take an optional timeout value and the default value is this.
*/
static const system_tick_t DEFAULT_TIMEOUT = 10000;
/**
* @brief Constant for getEnvironment() to get information about the connected cell
*
* This only works on the 2G and 3G Electron, E Series, and Boron. It does not work on LTE Cat M1
* (SARA-R410M-02B) models. See getEnvironment() for alternatives.
*/
static const int ENVIRONMENT_SERVING_CELL = 3;
/**
* @brief Constant for getEnvironment() to get information about the connected cell and neighbors
*
* This only works on the 2G Electron (G350)!
*/
static const int ENVIRONMENT_SERVING_CELL_AND_NEIGHBORS = 5;
/**
* @brief Constants for getOperatorName(). Default and recommended value is OPERATOR_NAME_LONG_EONS.
*
* In most cases, `OPERATOR_NAME_NUMERIC` is 6 BCD digits in cccnnn format where (ccc = MCC and nnn = MNC).
* However, in some countries MNC is only two BCD digits, so in that case it will be cccnn (5 BCD digits).
*/
static const int OPERATOR_NAME_NUMERIC = 0; //!< Numeric format of MCC/MNC network (three BCD digit country code and two/three BCD digit network code)
static const int OPERATOR_NAME_SHORT_ROM = 1; //!< Short name in ROM
static const int OPERATOR_NAME_LONG_ROM = 2; //!< Long name in ROM
static const int OPERATOR_NAME_SHORT_CPHS = 3; //!< Short network operator name (CPHS)
static const int OPERATOR_NAME_LONG_CPHS = 4; //!< Long network operator name (CPHS)
static const int OPERATOR_NAME_SHORT_NITZ = 5; //!< Short NITZ name
static const int OPERATOR_NAME_LONG_NITZ = 6; //!< Full NITZ name
static const int OPERATOR_NAME_SERVICE_PROVIDER = 7; //!< Service provider name
static const int OPERATOR_NAME_SHORT_EONS = 8; //!< EONS short operator name
static const int OPERATOR_NAME_LONG_EONS = 9; //!< EONS long operator name
static const int OPERATOR_NAME_SHORT_NETWORK_OPERATOR = 11; //!< Short network operator name
static const int OPERATOR_NAME_LONG_NETWORK_OPERATOR = 12; //!< Long network operator name
/**
* @brief Used internally as the Cellular.command callback
*
* @param type one of 13 different enumerated AT command response types.
*
* @param buf a pointer to the character array containing the AT command response.
*
* @param len length of the AT command response buf.
*
* @param param a pointer to the variable or structure being updated by the callback function.
*
* @return user specified callback return value
*/
static int responseCallback(int type, const char* buf, int len, void *param);
/**
* @brief Function to convert an RSSI value into "bars" of signal strength (0-5)
*
* | RSSI | Bars |
* | :-----: | :---: |
* | >= -57 | 5 |
* | > -68 | 4 |
* | > -80 | 3 |
* | > -92 | 2 |
* | > -104 | 1 |
* | <= -104 | 0 |
*
* 5 is strong and 0 is weak.
*/
static int rssiToBars(int rssi);
protected:
bool getNetworkInfoUCGED(CellularHelperNetworkInfo &resp);
bool getNetworkInfoQNWINFO(CellularHelperNetworkInfo &resp);
bool getNetworkInfoCGED(CellularHelperNetworkInfo &resp);
};
extern CellularHelperClass CellularHelper;
#endif /* Wiring_Cellular */
#endif /* __CELLULARHELPER_H */
|
byte-mug/tcphelper | tcpsrv.c | <gh_stars>0
/*
* Copyright (c) 2016 <NAME>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgement in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
static int isinv(char c){
switch(c){
case 0:
case '.':
case '-':
return 1;
}
return 0;
}
static int findit(const char* chr){
if(!chr) return 0;
while(*chr) switch(*chr++){
case '4':return 4;
case '6':return 6;
}
return 0;
}
static char NAME[4090];
int main(int argc,const char* const * argv){
union {
struct sockaddr_in i4;
struct sockaddr_in6 i6;
} au;
socklen_t al;
int server;
int fam;
int worked;
uid_t uid;
if(argc<=4){printf("argc<=4 %d \n",argc);return 1;}
sscanf(argv[3],"%d",&server);
switch(findit(argv[1])){
case 4:
inet_pton(AF_INET,argv[2],&(au.i4.sin_addr.s_addr));
au.i4.sin_family = AF_INET;
fam = PF_INET;
au.i4.sin_port = htons(server);
al = sizeof(struct sockaddr_in);
break;
case 6:
if(!isinv(*argv[2]))
inet_pton(AF_INET6,argv[2],&(au.i6.sin6_addr.s6_addr));
else
au.i6.sin6_addr = in6addr_any;
au.i6.sin6_family = AF_INET6;
fam = PF_INET6;
au.i6.sin6_port = htons(server);
al = sizeof(struct sockaddr_in6);
break;
default: printf("invalid protocol type\n"); return 1;
}
server = socket(fam, SOCK_STREAM, 0);
if(server<0){ perror("socket"); return 1; }
uid = getuid();
/*
* We try to gain Root privileges. Useful for bind(). If `tcpsrv' is a
* setuid-executable, it shall be able to bind onto any TCP port.
*/
worked = setuid(0)>=0;
if(bind(server,(struct sockaddr*)&au,al)<0){ perror("bind"); return 1; }
/*
* Revert the setuid(0)-Step.
*/
if(worked){
if(setuid(uid)<0){
perror("setuid");
printf("unable to drop root privileges\n");
printf("to fix that: chmod -s %s\n",argv[0]);
return 1;
}
}
if(listen(server,10)<0){ perror("listen"); return 1; }
snprintf(NAME,sizeof(NAME)-1,"%d",server);
setenv("SOCKET",NAME,1);
execvp(argv[4],(char*const*)argv+4);
perror("execvp");
return 1;
}
|
byte-mug/tcphelper | unixsrv.c | <reponame>byte-mug/tcphelper<filename>unixsrv.c
/*
* Copyright (c) 2016 <NAME>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgement in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/un.h>
static char NAME[4090];
struct sockaddr* build_address(const char* name,socklen_t *al){
static struct sockaddr_un stun;
size_t siz = strlen(name)+1;
size_t asiz = sizeof(stun)-sizeof(stun.sun_path)+siz;
struct sockaddr_un *un;
if(asiz>sizeof(stun)) {
*al = asiz;
un = malloc(asiz);
if(!un)return NULL;
} else {
*al = sizeof(stun);
un = &stun;
}
un->sun_family = AF_UNIX;
memcpy(un->sun_path,name,siz);
return (struct sockaddr*)un;
}
int main(int argc,const char* const * argv){
socklen_t al;
int server;
int fam;
int worked;
uid_t uid;
if(argc<=2){printf("argc<=2 %d \n",argc);return 1;}
struct sockaddr* addr = build_address(argv[1],&al);
if(!addr) { perror("build_address"); return 1; }
server = socket(AF_UNIX, SOCK_STREAM, 0);
if(server<0){ perror("socket"); return 1; }
unlink(argv[1]);
if(bind(server,addr,al)<0){ perror("bind"); return 1; }
if(listen(server,10)<0){ perror("listen"); return 1; }
snprintf(NAME,sizeof(NAME)-1,"%d",server);
setenv("SOCKET",NAME,1);
execvp(argv[2],(char*const*)argv+2);
perror("execvp");
return 1;
}
|
byte-mug/tcphelper | tcploop.c | <filename>tcploop.c<gh_stars>0
/*
* Copyright (c) 2016 <NAME>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgement in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/un.h>
void sig_exit()
{
int status;
while(wait(&status)<=0);
}
void fail(const char* str){
if(!errno)return;
perror(str);
_exit(1);
}
char NAME[4090];
int main(int argc,const char* const * argv){
union {
struct sockaddr_in i4;
struct sockaddr_in6 i6;
struct sockaddr_un un;
} au;
int sock;
int client;
pid_t pid;
socklen_t al;
const char* chr = getenv("SOCKET");
unsetenv("SOCKET");
signal (SIGCHLD, sig_exit);
if(!chr)return 1;
sscanf(chr,"%d",&sock);
for(;;){
al = sizeof(au);
client = accept(sock, (struct sockaddr*)&au, &al);
if(client<0) { usleep(100); continue; }
pid = fork();
if(pid==0){
errno = 0;
dup2(1,2); fail("dup2 1,2");
dup2(client,0); fail("dup2 client,0");
dup2(client,1); fail("dup2 client,1");
close(client); fail("close");
close(sock); fail("close");
switch(au.i4.sin_family){
case AF_INET:
inet_ntop(AF_INET, &(au.i4.sin_addr), NAME, sizeof(NAME)-1);
break;
case AF_INET6:
inet_ntop(AF_INET6, &(au.i6.sin6_addr), NAME, sizeof(NAME)-1);
break;
default:
goto skip;
}
setenv("REMOTE_IP",NAME,1);
sprintf(NAME,"%d",(int)ntohs(au.i4.sin_port) );
setenv("REMOTE_PORT",NAME,1);
skip:
execvp(argv[1],(char*const*)argv+1);
perror("execvp");
return 1;
}
if(pid<0)perror("fork");
close(client);
}
}
|
MinhoTeam/MinhoUDPCOM | udpcom.h | <reponame>MinhoTeam/MinhoUDPCOM
#ifndef UDPCOM_H
#define UDPCOM_H
#include "mainwindow.h"
#include "QHostAddress"
#include <QUdpSocket>
#include <QNetworkInterface>
class UDPCOM
{
public:
UDPCOM(MainWindow *mainw, QString MyAddress1, QString DestineAddress1, int MyPort1, int DestinePort1);
~UDPCOM();
QString UDPread(void);
void UDPwrite(QString txt);
private:
MainWindow *myMain;
QUdpSocket *udpSocketOut;
QUdpSocket *udpSocketIn;
QString MyAddress;
QString DestineAddress;
int MyPort,DestinePort;
};
#endif // UDPCOM_H
|
MinhoTeam/MinhoUDPCOM | serialport.h | <gh_stars>0
#ifndef SERIALPORT_H
#define SERIALPORT_H
#include "mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QDebug>
class SerialPort
{
private slots:
bool ConnectSerial();
MainWindow *myMain;
public:
QSerialPort serial;
QString readAll();
void write(QString txt);
SerialPort(MainWindow *mainw,QString name, int baudRate);
bool close();
bool isOpen();
~SerialPort();
private:
QByteArray frameToSend;
};
#endif // SERIALPORT_H
|
MinhoTeam/MinhoUDPCOM | mainwindow.h | <filename>mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
private slots:
void readPendingDatagrams();
//void on_btSendUDP_clicked();
void readResponse();
//void on_btSendSerial_clicked();
void on_btOpenSerial_clicked();
void on_btRefresh_clicked();
void on_btCloseSerial_clicked();
void on_btOpenUDP_clicked();
void on_btSendUDP_clicked();
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
|
atar-axis/fmi_adapter | fmi_adapter/include/fmi_adapter/FMUVariable.h | <filename>fmi_adapter/include/fmi_adapter/FMUVariable.h
/*
* Copyright (c) 2021 <NAME> - <EMAIL>
* All rights reserved.
*/
#pragma once
#include <memory>
#include <string>
#include <variant>
#include <ros/ros.h>
#include <fmilib.h>
#include <FMI2/fmi2_enums.h>
#include <FMI2/fmi2_functions.h>
#include <FMI2/fmi2_import_variable.h>
namespace fmi_adapter {
typedef std::variant<double, int, bool> valueVariantTypes;
class FMUVariable {
private:
fmi2_import_variable_t* variable; // TODO: use an UUID instead
fmi2_value_reference_t valueReference;
std::string rawName;
fmi2_base_type_enu_t rawType;
fmi2_causality_enu_t rawCausality;
fmi2_import_t* parent_fmu;
public:
FMUVariable(fmi2_import_t* parent_fmu, fmi2_import_variable_t* element);
~FMUVariable() = default;
// no copies or assignments allowed, we are holding an pointer!
FMUVariable(const FMUVariable&) = delete;
FMUVariable& operator=(const fmi_adapter::FMUVariable&) = delete;
std::string rosifyName(const std::string& rawName) const;
// getters for non-changing variable attributes
fmi2_import_variable_t* getVariablePointerRaw() const;
std::string getNameRaw() const;
fmi2_base_type_enu_t getTypeRaw() const;
fmi2_causality_enu_t getCausalityRaw() const;
std::string getNameRos() const;
fmi2_value_reference_t getValueReference() const;
// filters for use in boost::adaptors::filtered
static bool varInput_filter(std::pair<std::string, std::shared_ptr<FMUVariable>> variable);
static bool varOutput_filter(std::pair<std::string, std::shared_ptr<FMUVariable>> variable);
static bool varParam_filter(std::pair<std::string, std::shared_ptr<FMUVariable>> variable);
valueVariantTypes getValue();
void setValue(valueVariantTypes value);
};
} // namespace fmi_adapter |
atar-axis/fmi_adapter | fmi_adapter/include/fmi_adapter/FMIMaster.h | <filename>fmi_adapter/include/fmi_adapter/FMIMaster.h
/*
* Copyright (c) 2021 <NAME> - <EMAIL>
* All rights reserved.
*/
#pragma once
#include <fstream>
#include <map>
#include <string>
#include <variant>
#include "FMU.h"
#include <ros/ros.h>
#include <nlohmann/json.hpp>
#include <boost/filesystem.hpp> // for path
namespace fmi_adapter {
class FMIMaster {
private:
std::map<std::string, std::unique_ptr<FMU>> slave_fmus{};
std::map<std::pair<std::string, std::string>, std::shared_ptr<FMUVariable>> master_inputs{};
std::map<std::pair<std::string, std::string>, std::shared_ptr<FMUVariable>> master_outputs{};
double stepSize;
nlohmann::json jsonConfig{};
void propagateResults();
void createSlave(std::string unique_name, std::string fmuPath);
public:
FMIMaster(double stepSize) : stepSize(stepSize) {}
~FMIMaster() = default;
// Copy and assignments not allowed
FMIMaster(const FMIMaster& other) = delete;
FMIMaster& operator=(const FMIMaster&) = delete;
void config(const std::string json_path);
void initSlavesFromROS(const ros::NodeHandle& wrappingNode);
void exitInitModeSlaves(ros::Time simulationTime);
void doStepsUntil(const ros::Time simulationTime);
const std::map<std::pair<std::string, std::string>, std::shared_ptr<FMUVariable>> &getOutputs();
const std::map<std::pair<std::string, std::string>, std::shared_ptr<FMUVariable>>& getInputs();
void setInputValue(std::string fmuName, std::string portName, ros::Time when, valueVariantTypes value);
ros::Time getSimulationTime() const;
};
} // namespace fmi_adapter |
atar-axis/fmi_adapter | fmi_adapter/include/fmi_adapter/FMU.h | <gh_stars>0
/*
* Copyright (c) 2021 <NAME> - <EMAIL>
* All rights reserved.
*/
// Copyright (c) 2018 - for information on the respective copyright owner
// see the NOTICE file and/or the repository https://github.com/boschresearch/fmi_adapter.
//
// 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.
#pragma once
#include <cassert>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include "FMUVariable.h"
#include <ros/ros.h>
#include <FMI2/fmi2_enums.h>
#include <FMI2/fmi2_functions.h>
#include <boost/range/adaptor/filtered.hpp>
struct fmi_xml_context_t;
typedef struct fmi_xml_context_t fmi_import_context_t;
struct fmi2_import_t;
struct fmi2_xml_variable_t;
typedef struct fmi2_xml_variable_t fmi2_import_variable_t;
struct jm_callbacks;
namespace fmi_adapter {
// An instance of this class wraps a FMU and allows to simulate it using the ROS time notion and standard C++ types.
// In the background, the FMI Library (a BSD-licensed C library) is used for interacting with the FMU.
// This class also provides concenvience functions to read parameters and initial values from ROS parameters.
class FMU {
public:
// This ctor creates an instance using the FMU from the given path. If the step-size argument
// is zero, the default experiment step-size given in the FMU is used.
explicit FMU(const std::string& fmuName, const std::string& fmuPath, ros::Duration stepSize = ros::Duration(0.0),
bool interpolateInput = true, const std::string& tmpPath = "");
FMU(const FMU& other) = delete;
FMU& operator=(const FMU&) = delete;
virtual ~FMU();
// Returns a ROSified version of the given variable name, replaces all not supported characters with '_'.
static std::string rosifyName(const std::string& name);
// Returns true if the FMU of this instances supports a variable communication step-size.
bool canHandleVariableCommunicationStepSize() const;
// Returns the default experiment step-size of the FMU of this instance.
ros::Duration getDefaultExperimentStep() const;
// Stores a value for the given variable to be considered by doStep*(..) at the given time of the FMU simulation.
void _setInputValueRaw(fmi2_import_variable_t* variable, ros::Time time, valueVariantTypes value);
// Stores a value for the variable with the given name to be considered by doStep*(..) at the given
// time of the FMU simulation.
void setInputValue(std::string variableName, ros::Time time, valueVariantTypes value);
// Returns the step-size used in the FMU simulation.
ros::Duration getStepSize() const { return stepSize_; }
// Returns true if the wrapped FMU is still in initialization mode, which allows to set parameters
// and initial values.
bool isInInitializationMode() const { return inInitializationMode_; }
// Exits the initialization mode and starts the simulation of the wrapped FMU. Uses the given timestamp
// as start time for the simulation whereas the FMU internally starts at time 0.
// All times passed to setValue(..) and doStep*(..) are translated correspondingly.
void exitInitializationMode(ros::Time simulationTime);
// Performs one simulation step using the configured step size and returns the current simulation time.
ros::Time doStep();
// Performs one simulation step using the given step size and returns the current simulation time.
ros::Time doStep(const ros::Duration& stepSize);
// Advances the simulation of the wrapped FMU until the given point in time (modulo step-size).
// In detail, the simulation is performed iteratively using the configured step-size. Before each simulation step
// the relevant input values passed previously by setInputValue(..) are set depending on the given timestamps.
ros::Time doStepsUntil(const ros::Time simulationTime);
// Returns the current simulation time.
ros::Time getSimulationTime() const;
// Tries to read inital values for each variable (including parameters and aliases) from the ROS parameter set.
// The function only considers private ROS parameters, i.e. parameters that have the node name as prefix.
// Note that ROS parameter names may use the characters [A-Za-z0-9_] only. Therefore, all other characters in an
// FMU variable name are mapped to '_'. For example, to pass a value for the FMU variable 'dx[2]', use the ROS
// parameter '/my_node_name/dx_2_'.
void initializeFromROSParameters(const ros::NodeHandle& handle);
std::map<std::string, std::shared_ptr<FMUVariable>> getCachedVariables() const;
std::shared_ptr<FMUVariable> getCachedVariable(std::string name);
// variable type conversion helpers
template <typename Tin, typename Tout>
static Tout convert(Tin value);
fmi2_import_t* getRawFMU();
private:
// Name of the FMU being wrapped by this instance.
const std::string fmuName_;
// Path of the FMU being wrapped by this instance.
const std::string fmuPath_;
// Step size for the FMU simulation
ros::Duration stepSize_;
// Interpolate the input signals (as continuous), or not (piecewise constant)
bool interpolateInput_{false};
// Path to folder for temporary extraction of the FMU archive
std::string tmpPath_;
// If given tmp path is "", then an arbitrary one in /tmp is used. Remove this folder
bool removeTmpPathInDtor_{false};
// Is the FMU is still in init mode
bool inInitializationMode_{true};
// The internal FMU simulation time
double fmuTime_{0.0};
// Offset between the FMU's time and the ROS simulation time, used for doStep*(..) and setValue(..)
ros::Time rosStartTime_{0.0};
// Stores the FMU Variables
std::map<std::string, std::shared_ptr<FMUVariable>> cachedVariables_{};
// Stores the mapping from timestamps to variable values for the FMU simulation
std::map<fmi2_import_variable_t*, std::map<ros::Time, valueVariantTypes>> inputValuesByVariable_{};
// Pointer from the FMU Library types to the FMU instance
fmi2_import_t* fmu_{nullptr};
// Pointer from the FMU Library types to the FMU context
fmi_import_context_t* context_{nullptr};
// Callback functions for FMI Library. Cannot use type fmi2_callback_functions_t here as it is a typedef of an
// anonymous struct, cf. https://stackoverflow.com/questions/7256436/forward-declarations-of-unnamed-struct
void* fmiCallbacks_{nullptr};
// Further callback functions for FMI Library
jm_callbacks* jmCallbacks_{nullptr};
// Performs one simulation step using the given step size. Argument and initialization mode not checked.
void doStep_(const ros::Duration& stepSize);
// Returns the current simulation time w.r.t. the time where the FMU simulation started in ROS.
ros::Time getSimTimeForROS_() const { return rosStartTime_ + ros::Duration(fmuTime_); }
// Fill the FMU Variables Map
void cacheVariables_();
};
} // namespace fmi_adapter
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBFMDBEncrypt/VBFMEncryptDatabase.h | //
// VBFMEncryptDatabase.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <FMDB/FMDB.h>
@interface VBFMEncryptDatabase : FMDatabase
/** 如果需要自定义encryptkey,可以调用这个方法修改(在使用之前)*/
+ (void)setEncryptKey:(NSString *)encryptKey;
@end
|
VisionBao/VBMusic | VBMusic/Managers/HTTPManager/VBHTTPManager/VBHTTPHelper.h | //
// VBHTTPHelper.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#ifndef VBHTTPHelper_h
#define VBHTTPHelper_h
#import "VBHTTPManager.h"
#import "VBHTTPErrorManager.h"
#import "VBFileConfig.h"
#endif /* VBHTTPHelper_h */
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBUI/Base/VBView.h | //
// VBView.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface VBView : UIView
@end
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBFMDBEncrypt/VBFMEncryptDatabaseQueue.h | //
// VBFMEncryptDatabaseQueue.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <FMDB/FMDB.h>
@interface VBFMEncryptDatabaseQueue : FMDatabaseQueue
@end
|
VisionBao/VBMusic | VBMusic/Managers/HTTPManager/VBHTTPManager/VBHTTPErrorManager.h | //
// VBHTTPErrorManager.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBHTTPErrorManager : NSObject
@end
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBFoundation/VBFoundation.h | <gh_stars>0
//
// VBFoundation.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#ifndef VBFoundation_h
#define VBFoundation_h
#import "VBObject.h"
#import "VBLog.h"
#endif /* VBFoundation_h */
|
VisionBao/VBMusic | VBMusic/UI/Root/VBRootViewController.h | <gh_stars>0
//
// VBRootViewController.h
// VBMusic
//
// Created by Vision on 16/9/5.
// Copyright © 2016年 VisionBao. All rights reserved.
//
#import "VBViewController.h"
@interface VBRootViewController : VBViewController
@end
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBFoundation/VBObject.h | //
// VBObject.h
// VBMusic
//
// Created by Vision on 15/11/20.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBObject : NSObject
@end
@interface NSObject (VBObject)
/**
*
* performSelector 附带多参数
*
* @param aSelector Selector
* @param object 参数
*
* @return 执行结果
*/
- (id)performSelector:(SEL)aSelector withMultiObjects:(id)object, ...;
/**
*
* performSelector 附带多参数
*
* @param aSelector Selector
* @param delay 延迟执行时间
* @param object 参数
*/
- (void)performSelector:(SEL)aSelector afterDelay:(NSTimeInterval)delay withMultiObjects:(id)object, ...;
@end
|
VisionBao/VBMusic | VBMusic/Managers/HTTPManager/VBHTTPManager/VBFileConfig.h | <reponame>VisionBao/VBMusic
//
// VBFileConfig.h
// VBMusic
//
// Created by Vision on 15/12/22.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBFileConfig : NSObject
/**
* 文件数据
*/
@property (nonatomic, strong) NSData *fileData;
/**
* 服务器接收参数名
*/
@property (nonatomic, copy) NSString *name;
/**
* 文件名
*/
@property (nonatomic, copy) NSString *fileName;
/**
* 文件类型
*/
@property (nonatomic, copy) NSString *mimeType;
+ (instancetype)fileConfigWithfileData:(NSData *)fileData name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType;
- (instancetype)initWithfileData:(NSData *)fileData name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType;
@end
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBUI/Base/VBTabBarController.h | //
// VBTabBarController.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface VBTabBarController : UITabBarController
@end
|
VisionBao/VBMusic | VBMusic/3rd/Categories/UIKit/UIViewController/UIViewController+RecursiveDescription.h | //
// UIViewController+RecursiveDescription.h
// HLiPad
//
// Created by <NAME> on 07/01/2013.
//
//
#import <UIKit/UIKit.h>
@interface UIViewController (RecursiveDescription)
/**
* @brief 视图层级
*
* @return 视图层级字符串
*/
-(NSString*)recursiveDescription;
@end
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBUI/Base/VBUI.h | <reponame>VisionBao/VBMusic<filename>VBMusic/VBFrameworks/VBUI/Base/VBUI.h
//
// VBUI.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#ifndef VBUI_h
#define VBUI_h
#import "VBView.h"
#import "VBViewController.h"
#import "VBNavigationController.h"
#import "VBNavigationBar.h"
#import "VBTableView.h"
#import "VBTableViewCell.h"
#import "VBTabBarController.h"
#endif /* VBUI_h */
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBUI/Base/VBNavigationController.h | //
// VBNavigationController.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface VBNavigationController : UINavigationController
@end
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBFMDBEncrypt/VBFMDBEncryptConfig.h | //
// VBFMDBEncryptConfig.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#ifndef VBFMDBEncryptConfig_h
#define VBFMDBEncryptConfig_h
#define VBFMDBEncryptKey @"visionbao"
#endif /* VBFMDBEncryptConfig_h */
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBConfigDBManager.h | //
// VBConfigDBManager.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "VBDBManager.h"
@interface VBConfigDBManager : NSObject{
VBDBManager *_dbMgr;
}
+ (id)sharedManager;
@end
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBFMDBEncrypt/VBFMEncryptHelper.h | <reponame>VisionBao/VBMusic<gh_stars>0
//
// VBFMEncryptHelper.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBFMEncryptHelper : NSObject
/** 对数据库加密 */
+ (BOOL)encryptDatabase:(NSString *)path;
/** 对数据库解密 */
+ (BOOL)unEncryptDatabase:(NSString *)path;
/** 对数据库加密 */
+ (BOOL)encryptDatabase:(NSString *)sourcePath targetPath:(NSString *)targetPath;
/** 对数据库解密 */
+ (BOOL)unEncryptDatabase:(NSString *)sourcePath targetPath:(NSString *)targetPath;
/** 修改数据库秘钥 */
+ (BOOL)changeKey:(NSString *)dbPath originKey:(NSString *)originKey newKey:(NSString *)newKey;
@end
|
VisionBao/VBMusic | VBMusic/UI/Player/VBPlayerViewController.h | <reponame>VisionBao/VBMusic
//
// VBPlayerViewController.h
// VBMusic
//
// Created by Vision on 16/9/5.
// Copyright © 2016年 VisionBao. All rights reserved.
//
#import "VBViewController.h"
@interface VBPlayerViewController : VBViewController
@end
|
VisionBao/VBMusic | VBMusic/Managers/HTTPManager/VBHttpUrlManager.h | //
// VBHttpUrlManager.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBHttpUrlManager : NSObject
+ (id)defaultManager;
//判断是否为测试环境
- (BOOL)isInTestMode;
@end
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManagerFactory.h | //
// VBDBManagerFactory.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBDBManagerFactory : NSObject
+(id)sharedInstance;
@end
|
VisionBao/VBMusic | VBMusic/Managers/HTTPManager/VBHTTPModels.h | //
// VBHTTPModels.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface VBHTTPModels : NSObject
+ (void)fuck;
@end
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBUI/Base/VBTableViewCell.h | <reponame>VisionBao/VBMusic
//
// VBTableViewCell.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface VBTableViewCell : UITableViewCell
@end
|
VisionBao/VBMusic | VBMusic/VBFrameworks/VBUI/Base/VBNavigationBar.h | <reponame>VisionBao/VBMusic
//
// VBNavigationBar.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface VBNavigationBar : UINavigationBar
@end
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBFMDBEncrypt/VBFMDBEncrypt.h | //
// VBFMDBEncrypt.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#ifndef VBFMDBEncrypt_h
#define VBFMDBEncrypt_h
#import "VBFMEncryptDatabase.h"
#import "VBFMEncryptDatabaseQueue.h"
#import "VBFMEncryptHelper.h"
#endif /* VBFMDBEncrypt_h */
|
VisionBao/VBMusic | VBMusic/Managers/HTTPManager/VBHTTPManager/VBHTTPManager.h | //
// VBHTTPManager.h
// VBMusic
//
// Created by Vision on 15/12/5.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AFNetworking.h>
@class VBFileConfig;
/**
请求成功block
*/
typedef void (^requestSuccessBlock)(id responseObj);
/**
请求失败block
*/
typedef void (^requestFailureBlock) (NSError *error);
/**
请求响应block
*/
typedef void (^responseBlock)(id dataObj,NSURL *filePath, NSError *error);
/**
监听进度响应block
*/
typedef void (^progressBlock)(int64_t bytesWritten, int64_t totalBytesWritten);
@interface VBHTTPManager : NSObject
+ (id)defaultManager;
/**
* 检测网络是否可用
*/
- (BOOL)checkNetworkStatus;
/**
GET请求
*/
- (void)getRequest:(NSString *)url params:(NSDictionary *)params success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler;
/**
POST请求
*/
- (void)postRequest:(NSString *)url params:(NSDictionary *)params success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler;
/**
PUT请求
*/
- (void)putRequest:(NSString *)url params:(NSDictionary *)params success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler;
/**
DELETE请求
*/
- (void)deleteRequest:(NSString *)url params:(NSDictionary *)params success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler;
/**
下载文件,监听下载进度
*/
- (void)downloadRequest:(NSString *)url filePath:(NSString *)filePath successAndProgress:(progressBlock)progressHandler complete:(responseBlock)completionHandler;
/**
文件上传
*/
- (void)updateRequest:(NSString *)url params:(NSDictionary *)params fileConfig:(VBFileConfig *)fileConfig success:(requestSuccessBlock)successHandler failure:(requestFailureBlock)failureHandler;
/**
文件上传,监听上传进度
*/
- (void)updateRequest:(NSString *)url params:(NSDictionary *)params fileConfig:(VBFileConfig *)fileConfig successAndProgress:(progressBlock)progressHandler complete:(responseBlock)completionHandler;
@end
|
VisionBao/VBMusic | VBMusic/Models/VBMusicModel.h | <filename>VBMusic/Models/VBMusicModel.h<gh_stars>0
//
// VBMusicModel.h
// VBMusic
//
// Created by Vision on 15/11/20.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import "VBObject.h"
@class Data,Url_List,Audition_List;
@interface VBMusicModel : VBObject
@property (nonatomic, assign) NSInteger code;
@property (nonatomic, assign) NSInteger pages;
@property (nonatomic, assign) NSInteger rows;
@property (nonatomic, strong) NSArray<Data *> *data;
@end
@interface Data : NSObject
@property (nonatomic, assign) NSInteger album_id;
@property (nonatomic, assign) NSInteger song_id;
@property (nonatomic, copy) NSString *singer_name;
@property (nonatomic, copy) NSString *song_name;
@property (nonatomic, strong) NSArray<Audition_List *> *audition_list;
@property (nonatomic, strong) NSArray<Url_List *> *url_list;
@property (nonatomic, copy) NSString *album_name;
@property (nonatomic, assign) NSInteger pick_count;
@property (nonatomic, assign) NSInteger vip;
@property (nonatomic, assign) NSInteger singer_id;
@property (nonatomic, assign) NSInteger artist_flag;
@end
@interface Url_List : NSObject
@property (nonatomic, copy) NSString *format;
@property (nonatomic, copy) NSString *size;
@property (nonatomic, copy) NSString *duration;
@property (nonatomic, copy) NSString *type_description;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger bitrate;
@property (nonatomic, copy) NSString *url;
@end
@interface Audition_List : NSObject
@property (nonatomic, copy) NSString *format;
@property (nonatomic, copy) NSString *size;
@property (nonatomic, copy) NSString *duration;
@property (nonatomic, copy) NSString *type_description;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger bitrate;
@property (nonatomic, copy) NSString *url;
@end
|
VisionBao/VBMusic | VBMusic/Managers/DBManager/VBDBManager/VBDBManager.h | <gh_stars>0
//
// VBDBManager.h
// VBMusic
//
// Created by Vision on 15/12/23.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "fmdb.h"
#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))
/**
* 数据库管理基类
*/
@interface VBDBManager : NSObject{
FMDatabaseQueue *_dbQueue;
}
+ (id)defaultMgr;
- (FMDatabaseQueue *)fmDabaseQueue;
@end
|
VisionBao/VBMusic | VBMusic/Models/VBModelHeaders.h | //
// VBModelHeaders.h
// VBMusic
//
// Created by Vision on 15/12/24.
// Copyright © 2015年 VisionBao. All rights reserved.
//
#ifndef VBModelHeaders_h
#define VBModelHeaders_h
#import "VBMusicModel.h"
#endif /* VBModelHeaders_h */
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/Model/SegmentBase.h | <filename>DASH Player/DASH Player/Model/SegmentBase.h
//
// SegmentBase.h
// DASH Player
//
// Created by DataArt Apps on 04.11.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Initialization.h"
@interface SegmentBase : NSObject
@property (nonatomic, strong) NSString *indexRange;
@property (nonatomic, strong) Initialization *initialization;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANAppDelegate.h | <filename>DASH Player/DASH Player/ANAppDelegate.h
//
// ANAppDelegate.h
// DASH Player
//
// Created by DataArt Apps on 24.07.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ANAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANPlayerViewController.h | //
// ANPlayer.h
// DASH Player
//
// Created by DataArt Apps on 05.08.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ANDashMultimediaManager.h"
#import "ANControlPanelView.h"
@class ANDrawingPlayerView;
@class ANVideoDecoder;
@class MPD;
@interface ANPlayerViewController : UIViewController <ANDashMultimediaMangerDelegate>
@property (nonatomic, strong) ANDrawingPlayerView *playerView;
@property (strong, nonatomic) ANControlPanelView *controlPanelView;
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UIView *controlPanelContainer;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *controlPanelBottomSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *controlPanelContainerHeigthConstraint;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;
- (void)pause;
- (void)stop;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/Model/AudioChannelConfiguration.h | //
// AudioChannelConfiguration.h
// DASH Player
//
// Created by DataArt Apps on 28.07.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface AudioChannelConfiguration : NSObject
@property (nonatomic, strong) NSString *schemeIdUri;
@property (nonatomic, assign) NSUInteger value;
- (void)setValueFromString:(NSString *)valueString;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANPlayerView.h | <reponame>mlvhub/MPEGDASH-iOS-Player<filename>DASH Player/DASH Player/ANPlayerView.h
//
// ANPlayerView.h
// DASH Player
//
// Created by DataArt Apps on 24.07.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <UIKit/UIKit.h>
@class VideoFrameExtractor;
@class MPD;
@interface ANPlayerView : UIView {
UIImageView *playerImageView;
UIButton *playButton;
UILabel *fpsLabel;
}
@property (nonatomic) IBOutlet UIImageView *playerImageView;
@property (nonatomic) IBOutlet UIButton *playButton;
@property (nonatomic) IBOutlet UILabel *fpsLabel;
@property (nonatomic) IBOutlet UILabel *downloadSpeedLabel;
@property (nonatomic) UIImage *image;
@property (nonatomic, assign) BOOL enablePlayButton;
@property (nonatomic, strong) NSString *fpsValueString;
@property (nonatomic, strong) CALayer *imageLayer;
- (void)displayCurrentFrame:(UIImage *)image;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANDashMultimediaManager.h | <filename>DASH Player/DASH Player/ANDashMultimediaManager.h<gh_stars>10-100
//
// ANDashMultimediaManager.h
// DASH Player
//
// Created by DataArt Apps on 07.08.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
//#import "ANOperation.h"
typedef NS_ENUM(NSUInteger, ANStreamType) {
ANStreamTypeStatic,
ANStreamTypeDynamic,
ANStreamTypeNone
};
@class ANAudioData;
@class ANVideoData;
@protocol ANDashMultimediaMangerDelegate;
@interface ANDashMultimediaManager : NSObject
@property (nonatomic, weak) id <ANDashMultimediaMangerDelegate> delegate;
@property (nonatomic, assign) ANStreamType streamType;
@property (nonatomic, assign) BOOL stopped;
- (id)initWithMpdUrl:(NSURL *)mpdUrl;
- (void)launchManager;
- (void)dynamic_downloadNextVideoSegment;
- (void)dynamic_downloadNextAudioSegment;
- (void)static_downloadNextVideoSegment;
- (void)static_downloadNextAudioSegment;
- (NSTimeInterval)totalMediaDuration;
- (void)shiftVideoToPosition:(NSTimeInterval)pos;
+ (NSThread *)dashMultimediaThread;
@end
@protocol ANDashMultimediaMangerDelegate <NSObject>
@optional
- (void)dashMultimediaManger:(ANDashMultimediaManager *)manager didDownloadFirstVideoSegment:(ANVideoData *)videData firstAudioSegment:(ANAudioData *)audioData;
- (void)dashMultimediaManger:(ANDashMultimediaManager *)manager didDownloadVideoData:(ANVideoData *)videoData;
- (void)dashMultimediaManger:(ANDashMultimediaManager *)manager didDownloadAudioData:(ANAudioData *)audioData;
- (void)dashMultimediaManger:(ANDashMultimediaManager *)manager didFailWithMessage:(NSString *)failMessage;
@end |
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANRingBuffer.h | //
// ANRingBuffer.h
// DASH Player
//
// Created by DataArt Apps on 18.08.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ANRingBuffer : NSObject {
uint8_t* data;
int size;
int max_size;
int readIndex; // Read position
int writeIndex; // Write position
BOOL eof; // EOF flag
int lastOp; // last operation flag: 0 - read, 1 - write
NSLock *mutex;
NSCondition *readCond;
NSCondition *writeCond;
}
- (id)initWitSize:(int)initialSize maxSize:(int)maxSize;
- (int)write:(void *) buffer withLength:(int)len block:(BOOL) block;
- (int)read:(void*)buffer withLength:(int)len block:(BOOL) block;
- (int)size;
- (void)eof;
- (BOOL)isEof;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANAudioDecoder.h | //
// AudioFrameExtractor.h
// DASH Player
//
// Created by DataArt Apps on 22.08.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/time.h"
#include "libswresample/swresample.h"
#include "libavutil/opt.h"
@class ANRingBuffer;
@class ANAudioData;
@protocol ANAudioDecoderDelegate;
@interface ANAudioDecoder : NSObject {
AVFormatContext *formatContext;
AVCodecContext *codecContext;
AVFrame *frame;
AVPacket packet;
AVPicture picture;
AVStream *audioStream;
int audioStreamIndex;
int bytesRead;
int bytesLeft;
}
- (id)initWithAudioData:(ANAudioData *)audioData;
@property (nonatomic, strong) ANRingBuffer *ringBuffer;
@property (nonatomic, assign, readonly, getter = isAudioFinished) BOOL audioIsFinished;
@property (nonatomic, weak) id <ANAudioDecoderDelegate> delegate;
@property (nonatomic, readonly) double duration;
- (void)startWork;
- (int)sampleRate;
- (int)channels;
- (void)quit;
- (BOOL)isQuit;
@end
@protocol ANAudioDecoderDelegate <NSObject>
- (void)audioDidEnd:(ANAudioDecoder *)audio;
@end |
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANHttpClient.h | <reponame>mlvhub/MPEGDASH-iOS-Player<filename>DASH Player/DASH Player/ANHttpClient.h
//
// ANHttpClient.h
// DASH Player
//
// Created by DataArt Apps on 06.08.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ANHttpClient : NSObject
@property (nonatomic, assign) NSUInteger bytesDownloaded;
@property (nonatomic, assign) double timeForDownload;
@property (nonatomic, assign) NSUInteger lastBytesDownloaded;
@property (nonatomic, assign) double lastTimeForDownload;
@property (nonatomic, assign) double averageNetworkSpeed;
@property (nonatomic, assign) double lastNetworkSpeed;
+ (instancetype)sharedHttpClient;
- (void)downloadFile:(NSURL *)fileUrl
withSuccess:(ANSuccessWithResponseCompletionBlock)success
failure:(ANFailureCompletionBlock)failure;
- (void)downloadFile:(NSURL *)fileUrl
atRange:(NSString *)rangeString
withSuccess:(ANSuccessWithResponseCompletionBlock)success
failure:(ANFailureCompletionBlock)failure;
- (NSUInteger)lastDownloadSpeed;
- (void)cancelDownloading;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/Model/Initialization.h | //
// Initialization.h
// DASH Player
//
// Created by DataArt Apps on 04.11.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Initialization : NSObject
@property (nonatomic, strong) NSString *range;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/Model/ANSegmentsManager.h | <reponame>mlvhub/MPEGDASH-iOS-Player<filename>DASH Player/DASH Player/Model/ANSegmentsManager.h
//
// ANSegmentsManager.h
// DASH Player
//
// Created by DataArt Apps on 28.07.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import <Foundation/Foundation.h>
@class ANHttpClient;
@interface ANSegmentsManager :NSObject
@property (nonatomic, strong) NSString *lastVideoSegmentPath;
@property (nonatomic, strong) NSString *lastAudioSegmentPath;
@property (nonatomic, strong) NSData *lastVideoSegmentData;
@property (nonatomic, strong) NSData *lastAudioSegmentData;
- (void)downloadInitialVideoSegment:(NSURL *)segmentUrl withCompletionBlock:(ANCompletionBlockWithData)completion;
- (void)downloadVideoSegment:(NSURL *)segmentUrl withCompletionBlock:(ANCompletionBlock)completion;
- (void)downloadInitialAudioSegment:(NSURL *)segmentUrl withCompletionBlock:(ANCompletionBlock)completion;
- (void)downloadAudioSegment:(NSURL *)segmentUrl withCompletionBlock:(ANCompletionBlock)completion;
- (void)downloadInitialVideoSegment:(NSURL *)segmentUrl
witRange:(NSString *)range
andCompletionBlock:(ANCompletionBlockWithData)completion;
- (void)downloadData:(NSURL *)segmentUrl
atRange:(NSString *)range
withCompletionBlock:(ANCompletionBlockWithData)completion;
@end
|
mlvhub/MPEGDASH-iOS-Player | DASH Player/DASH Player/ANDashMultimediaManagerForRange.h | <filename>DASH Player/DASH Player/ANDashMultimediaManagerForRange.h
//
// ANDashMultimediaManagerForRange.h
// DASH Player
//
// Created by DataArt Apps on 04.11.14.
// Copyright (c) 2014 DataArt Apps. All rights reserved.
//
#import "ANDashMultimediaManager.h"
@interface ANDashMultimediaManagerForRange : ANDashMultimediaManager
@property (nonatomic, weak) id <ANDashMultimediaMangerDelegate> delegate;
@property (nonatomic, strong) NSURL *mpdUrl;
@property (nonatomic, assign) NSTimeInterval totalMediaDuration;
- (id)initWithMpdUrl:(NSURL *)mpdUrl;
- (void)launchManager;
- (void)static_downloadNextVideoSegment;
- (void)static_downloadNextAudioSegment;
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.