repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
Kristopher38/LuaCPU | hardware/hps_0.h | #ifndef _ALTERA_HPS_0_H_
#define _ALTERA_HPS_0_H_
/*
* This file was automatically generated by the swinfo2header utility.
*
* Created from SOPC Builder system 'soc_system' in
* file 'C:/altera/13.1/embedded/HPS_LED_HEX/LED_HEX_hardware/soc_system.sopcinfo'.
*/
/*
* This file contains macros for module 'hps_0' and devices
* connected to the following masters:
* h2f_axi_master
* h2f_lw_axi_master
*
* Do not include this header file and another header file created for a
* different module or master group at the same time.
* Doing so may result in duplicate macro names.
* Instead, use the system header file which has macros with unique names.
*/
/*
* Macros for device 'onchip_memory2_0', class 'altera_avalon_onchip_memory2'
* The macros are prefixed with 'ONCHIP_MEMORY2_0_'.
* The prefix is the slave descriptor.
*/
#define ONCHIP_MEMORY2_0_COMPONENT_TYPE altera_avalon_onchip_memory2
#define ONCHIP_MEMORY2_0_COMPONENT_NAME onchip_memory2_0
#define ONCHIP_MEMORY2_0_BASE 0x0
#define ONCHIP_MEMORY2_0_SPAN 65536
#define ONCHIP_MEMORY2_0_END 0xffff
#define ONCHIP_MEMORY2_0_ALLOW_IN_SYSTEM_MEMORY_CONTENT_EDITOR 0
#define ONCHIP_MEMORY2_0_ALLOW_MRAM_SIM_CONTENTS_ONLY_FILE 0
#define ONCHIP_MEMORY2_0_CONTENTS_INFO ""
#define ONCHIP_MEMORY2_0_DUAL_PORT 0
#define ONCHIP_MEMORY2_0_GUI_RAM_BLOCK_TYPE AUTO
#define ONCHIP_MEMORY2_0_INIT_CONTENTS_FILE soc_system_onchip_memory2_0
#define ONCHIP_MEMORY2_0_INIT_MEM_CONTENT 1
#define ONCHIP_MEMORY2_0_INSTANCE_ID NONE
#define ONCHIP_MEMORY2_0_NON_DEFAULT_INIT_FILE_ENABLED 0
#define ONCHIP_MEMORY2_0_RAM_BLOCK_TYPE AUTO
#define ONCHIP_MEMORY2_0_READ_DURING_WRITE_MODE DONT_CARE
#define ONCHIP_MEMORY2_0_SINGLE_CLOCK_OP 0
#define ONCHIP_MEMORY2_0_SIZE_MULTIPLE 1
#define ONCHIP_MEMORY2_0_SIZE_VALUE 65536
#define ONCHIP_MEMORY2_0_WRITABLE 1
#define ONCHIP_MEMORY2_0_MEMORY_INFO_DAT_SYM_INSTALL_DIR SIM_DIR
#define ONCHIP_MEMORY2_0_MEMORY_INFO_GENERATE_DAT_SYM 1
#define ONCHIP_MEMORY2_0_MEMORY_INFO_GENERATE_HEX 1
#define ONCHIP_MEMORY2_0_MEMORY_INFO_HAS_BYTE_LANE 0
#define ONCHIP_MEMORY2_0_MEMORY_INFO_HEX_INSTALL_DIR QPF_DIR
#define ONCHIP_MEMORY2_0_MEMORY_INFO_MEM_INIT_DATA_WIDTH 64
#define ONCHIP_MEMORY2_0_MEMORY_INFO_MEM_INIT_FILENAME soc_system_onchip_memory2_0
/*
* Macros for device 'sysid_qsys', class 'altera_avalon_sysid_qsys'
* The macros are prefixed with 'SYSID_QSYS_'.
* The prefix is the slave descriptor.
*/
#define SYSID_QSYS_COMPONENT_TYPE altera_avalon_sysid_qsys
#define SYSID_QSYS_COMPONENT_NAME sysid_qsys
#define SYSID_QSYS_BASE 0x10000
#define SYSID_QSYS_SPAN 8
#define SYSID_QSYS_END 0x10007
#define SYSID_QSYS_ID 2899645186
#define SYSID_QSYS_TIMESTAMP 1383720737
/*
* Macros for device 'SEG7_IF', class 'SEG7_IF'
* The macros are prefixed with 'SEG7_IF_'.
* The prefix is the slave descriptor.
*/
#define SEG7_IF_COMPONENT_TYPE SEG7_IF
#define SEG7_IF_COMPONENT_NAME SEG7_IF
#define SEG7_IF_BASE 0x10020
#define SEG7_IF_SPAN 128
#define SEG7_IF_END 0x1009f
/*
* Macros for device 'led_pio', class 'altera_avalon_pio'
* The macros are prefixed with 'LED_PIO_'.
* The prefix is the slave descriptor.
*/
#define LED_PIO_COMPONENT_TYPE altera_avalon_pio
#define LED_PIO_COMPONENT_NAME led_pio
#define LED_PIO_BASE 0x10040
#define LED_PIO_SPAN 64
#define LED_PIO_END 0x1007f
#define LED_PIO_BIT_CLEARING_EDGE_REGISTER 0
#define LED_PIO_BIT_MODIFYING_OUTPUT_REGISTER 0
#define LED_PIO_CAPTURE 0
#define LED_PIO_DATA_WIDTH 10
#define LED_PIO_DO_TEST_BENCH_WIRING 0
#define LED_PIO_DRIVEN_SIM_VALUE 0
#define LED_PIO_EDGE_TYPE NONE
#define LED_PIO_FREQ 50000000
#define LED_PIO_HAS_IN 0
#define LED_PIO_HAS_OUT 1
#define LED_PIO_HAS_TRI 0
#define LED_PIO_IRQ_TYPE NONE
#define LED_PIO_RESET_VALUE 1023
/*
* Macros for device 'jtag_uart', class 'altera_avalon_jtag_uart'
* The macros are prefixed with 'JTAG_UART_'.
* The prefix is the slave descriptor.
*/
#define JTAG_UART_COMPONENT_TYPE altera_avalon_jtag_uart
#define JTAG_UART_COMPONENT_NAME jtag_uart
#define JTAG_UART_BASE 0x20000
#define JTAG_UART_SPAN 32
#define JTAG_UART_END 0x2001f
#define JTAG_UART_IRQ 2
#define JTAG_UART_READ_DEPTH 64
#define JTAG_UART_READ_THRESHOLD 8
#define JTAG_UART_WRITE_DEPTH 64
#define JTAG_UART_WRITE_THRESHOLD 8
#endif /* _ALTERA_HPS_0_H_ */
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_fs_reg.c | <gh_stars>100-1000
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
#include <errno.h>
#include "sys/alt_dev.h"
#include "priv/alt_file.h"
/*
* The alt_fs_reg() function is used to register a file system. Once registered
* a device can be accessed using the standard posix calls: open(), read(),
* write() etc.
*
* System behaviour is undefined in the event that a file system is registered
* with a name that conflicts with an existing device or file system.
*
* alt_fs_reg() is not thread safe in the sense that there should be no other
* thread using the file system list at the time that alt_dev_reg() is called. In
* practice this means that alt_fs_reg() should only be called while operating
* in a single threaded mode. The expectation is that it will only be called
* by the file system initilisation functions invoked by alt_sys_init(), which in
* turn should only be called by the single threaded C startup code.
*
* A return value of zero indicates success. A negative return value indicates
* failure.
*/
int alt_fs_reg (alt_dev* dev)
{
/*
* check that the device has a name.
*/
if (!dev->name)
{
return -ENODEV;
}
/*
* register the file system.
*/
alt_llist_insert(&alt_fs_list, &dev->llist);
return 0;
}
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/inc/priv/alt_file.h | #ifndef __ALT_FILE_H__
#define __ALT_FILE_H__
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
/******************************************************************************
* *
* THIS IS A LIBRARY READ-ONLY SOURCE FILE. DO NOT EDIT. *
* *
******************************************************************************/
#include "sys/alt_dev.h"
#include "sys/alt_llist.h"
#include "os/alt_sem.h"
#include "alt_types.h"
/*
* This header provides the internal defenitions required to control file
* access. These variables and functions are not guaranteed to exist in
* future implementations of the HAL.
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* The function alt_find_dev() is used to search the device list "list" to
* locate a device named "name". If a match is found, then a pointer to the
* device is returned, otherwise NULL is returned.
*/
extern alt_dev* alt_find_dev (const char* name, alt_llist* list);
/*
* alt_find_file() is used to search the list of registered file systems to
* find the filesystem that the file named "name" belongs to. If a match is
* found, then a pointer to the filesystems alt_dev structure is returned,
* otherwise NULL is returned.
*
* Note that a match does not indicate that the file exists, only that a
* filesystem exists that is registered for a partition that could contain
* the file. The filesystems open() function would need to be called in order
* to determine if the file exists.
*/
extern alt_dev* alt_find_file (const char* name);
/*
* alt_get_fd() is used to allocate a file descriptor for the device or
* filesystem "dev". A negative return value indicates an error, otherwise the
* return value is the index of the file descriptor within the file descriptor
* pool.
*/
extern int alt_get_fd (alt_dev* dev);
/*
* alt_release_fd() is called to free the file descriptor with index "fd".
*/
extern void alt_release_fd (int fd);
/*
* alt_fd_lock() is called by ioctl() to mark the file descriptor "fd" as
* being open for exclusive access. Subsequent calls to open() for the device
* associated with "fd" will fail. A device is unlocked by either calling
* close() for "fd", or by an alternate call to ioctl() (see ioctl.c for
* details).
*/
extern int alt_fd_lock (alt_fd* fd);
/*
* alt_fd_unlock() is called by ioctl() to unlock a descriptor previously
* locked by a call to alt_fd_lock().
*/
extern int alt_fd_unlock (alt_fd* fd);
/*
* "alt_fd_list" is the pool of file descriptors.
*/
extern alt_fd alt_fd_list[];
/*
* flags used by alt_fd.
*
* ALT_FD_EXCL is used to mark a file descriptor as locked for exclusive
* access, i.e. further calls to open() for the associated device should
* fail.
*
* ALT_FD_DEV marks a dile descriptor as belonging to a device as oposed to a
* filesystem.
*/
#define ALT_FD_EXCL 0x80000000
#define ALT_FD_DEV 0x40000000
#define ALT_FD_FLAGS_MASK (ALT_FD_EXCL | ALT_FD_DEV)
/*
* "alt_dev_list" is the head of the linked list of registered devices.
*/
extern alt_llist alt_dev_list;
/*
* "alt_fs_list" is the head of the linked list of registered filesystems.
*/
extern alt_llist alt_fs_list;
/*
* "alt_fd_list_lock" is a semaphore used to ensure that access to the pool
* of file descriptors is thread safe.
*/
ALT_EXTERN_SEM(alt_fd_list_lock)
/*
* "alt_max_fd" is a 'high water mark'. It indicates the highest file
* descriptor allocated. Use of this can save searching the entire pool
* for active file descriptors, which helps avoid contention on access
* to the file descriptor pool.
*/
extern alt_32 alt_max_fd;
/*
* alt_io_redirect() is called at startup to redirect stdout, stdin, and
* stderr to the devices named in the input arguments. By default these streams
* are directed at /dev/null, and are then redirected using this function once
* all of the devices have been registered within the system.
*/
extern void alt_io_redirect(const char* stdout_dev,
const char* stdin_dev,
const char* stderr_dev);
#ifdef __cplusplus
}
#endif
#endif /* __ALT_FILE_H__ */
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_main.c | /******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include "sys/alt_dev.h"
#include "sys/alt_sys_init.h"
#include "sys/alt_irq.h"
#include "sys/alt_dev.h"
#include "os/alt_hooks.h"
#include "priv/alt_file.h"
#include "alt_types.h"
#include "system.h"
#include "sys/alt_log_printf.h"
extern void _do_ctors(void);
extern void _do_dtors(void);
/*
* Standard arguments for main. By default, no arguments are passed to main.
* However a device driver may choose to configure these arguments by calling
* alt_set_args(). The expectation is that this facility will only be used by
* the iclient/ihost utility.
*/
int alt_argc = 0;
char** alt_argv = {NULL};
char** alt_envp = {NULL};
/*
* Prototype for the entry point to the users application.
*/
extern int main (int, char **, char **);
/*
* alt_main is the C entry point for the HAL. It is called by the assembler
* startup code in the processor specific crt0.S. It is responsible for:
* completing the C runtime configuration; configuring all the
* devices/filesystems/components in the system; and call the entry point for
* the users application, i.e. main().
*/
void alt_main (void)
{
#ifndef ALT_NO_EXIT
int result;
#endif
/* ALT LOG - please see HAL/sys/alt_log_printf.h for details */
ALT_LOG_PRINT_BOOT("[alt_main.c] Entering alt_main, calling alt_irq_init.\r\n");
/* Initialize the interrupt controller. */
alt_irq_init (NULL);
/* Initialize the operating system */
ALT_LOG_PRINT_BOOT("[alt_main.c] Done alt_irq_init, calling alt_os_init.\r\n");
ALT_OS_INIT();
/*
* Initialize the semaphore used to control access to the file descriptor
* list.
*/
ALT_LOG_PRINT_BOOT("[alt_main.c] Done OS Init, calling alt_sem_create.\r\n");
ALT_SEM_CREATE (&alt_fd_list_lock, 1);
/* Initialize the device drivers/software components. */
ALT_LOG_PRINT_BOOT("[alt_main.c] Calling alt_sys_init.\r\n");
alt_sys_init();
ALT_LOG_PRINT_BOOT("[alt_main.c] Done alt_sys_init.\r\n");
#if !defined(ALT_USE_DIRECT_DRIVERS) && (defined(ALT_STDIN_PRESENT) || defined(ALT_STDOUT_PRESENT) || defined(ALT_STDERR_PRESENT))
/*
* Redirect stdio to the apropriate devices now that the devices have
* been initialized. This is only done if the user has requested these
* devices be present (not equal to /dev/null) and if direct drivers
* aren't being used.
*/
ALT_LOG_PRINT_BOOT("[alt_main.c] Redirecting IO.\r\n");
alt_io_redirect(ALT_STDOUT, ALT_STDIN, ALT_STDERR);
#endif
#ifndef ALT_NO_C_PLUS_PLUS
/*
* Call the C++ constructors
*/
ALT_LOG_PRINT_BOOT("[alt_main.c] Calling C++ constructors.\r\n");
_do_ctors ();
#endif /* ALT_NO_C_PLUS_PLUS */
#if !defined(ALT_NO_C_PLUS_PLUS) && !defined(ALT_NO_CLEAN_EXIT) && !defined(ALT_NO_EXIT)
/*
* Set the C++ destructors to be called at system shutdown. This is only done
* if a clean exit has been requested (i.e. the exit() function has not been
* redefined as _exit()). This is in the interest of reducing code footprint,
* in that the atexit() overhead is removed when it's not needed.
*/
ALT_LOG_PRINT_BOOT("[alt_main.c] Calling atexit.\r\n");
atexit (_do_dtors);
#endif
/*
* Finally, call main(). The return code is then passed to a subsequent
* call to exit() unless the application is never supposed to exit.
*/
ALT_LOG_PRINT_BOOT("[alt_main.c] Calling main.\r\n");
#ifdef ALT_NO_EXIT
main (alt_argc, alt_argv, alt_envp);
#else
result = main (alt_argc, alt_argv, alt_envp);
close(STDOUT_FILENO);
exit (result);
#endif
ALT_LOG_PRINT_BOOT("[alt_main.c] After main - we should not be here?.\r\n");
}
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_irq_handler.c | /******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2009 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
#include <errno.h>
#include "system.h"
/*
* This interrupt handler only works with an internal interrupt controller
* (IIC). Processors with an external interrupt controller (EIC) use an
* implementation provided by an EIC driver.
*/
#ifndef ALT_CPU_EIC_PRESENT
#include "sys/alt_irq.h"
#include "os/alt_hooks.h"
#include "alt_types.h"
/*
* A table describing each interrupt handler. The index into the array is the
* interrupt id associated with the handler.
*
* When an interrupt occurs, the associated handler is called with
* the argument stored in the context member.
*/
struct ALT_IRQ_HANDLER
{
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
void (*handler)(void*);
#else
void (*handler)(void*, alt_u32);
#endif
void *context;
} alt_irq[ALT_NIRQ];
/*
* alt_irq_handler() is called by the interrupt exception handler in order to
* process any outstanding interrupts.
*
* It is defined here since it is linked in using weak linkage.
* This means that if there is never a call to alt_irq_register() (above) then
* this function will not get linked in to the executable. This is acceptable
* since if no handler is ever registered, then an interrupt can never occur.
*
* If Nios II interrupt vector custom instruction exists, use it to accelerate
* the dispatch of interrupt handlers. The Nios II interrupt vector custom
* instruction is present if the macro ALT_CI_INTERRUPT_VECTOR defined.
*/
void alt_irq_handler (void) __attribute__ ((section (".exceptions")));
void alt_irq_handler (void)
{
#ifdef ALT_CI_INTERRUPT_VECTOR
alt_32 offset;
char* alt_irq_base = (char*)alt_irq;
#else
alt_u32 active;
alt_u32 mask;
alt_u32 i;
#endif /* ALT_CI_INTERRUPT_VECTOR */
/*
* Notify the operating system that we are at interrupt level.
*/
ALT_OS_INT_ENTER();
#ifdef ALT_CI_INTERRUPT_VECTOR
/*
* Call the interrupt vector custom instruction using the
* ALT_CI_INTERRUPT_VECTOR macro.
* It returns the offset into the vector table of the lowest-valued pending
* interrupt (corresponds to highest priority) or a negative value if none.
* The custom instruction assumes that each table entry is eight bytes.
*/
while ((offset = ALT_CI_INTERRUPT_VECTOR) >= 0) {
struct ALT_IRQ_HANDLER* handler_entry =
(struct ALT_IRQ_HANDLER*)(alt_irq_base + offset);
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
handler_entry->handler(handler_entry->context);
#else
handler_entry->handler(handler_entry->context, offset >> 3);
#endif
}
#else /* ALT_CI_INTERRUPT_VECTOR */
/*
* Obtain from the interrupt controller a bit list of pending interrupts,
* and then process the highest priority interrupt. This process loops,
* loading the active interrupt list on each pass until alt_irq_pending()
* return zero.
*
* The maximum interrupt latency for the highest priority interrupt is
* reduced by finding out which interrupts are pending as late as possible.
* Consider the case where the high priority interupt is asserted during
* the interrupt entry sequence for a lower priority interrupt to see why
* this is the case.
*/
active = alt_irq_pending ();
do
{
i = 0;
mask = 1;
/*
* Test each bit in turn looking for an active interrupt. Once one is
* found, the interrupt handler asigned by a call to alt_irq_register() is
* called to clear the interrupt condition.
*/
do
{
if (active & mask)
{
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
alt_irq[i].handler(alt_irq[i].context);
#else
alt_irq[i].handler(alt_irq[i].context, i);
#endif
break;
}
mask <<= 1;
i++;
} while (1);
active = alt_irq_pending ();
} while (active);
#endif /* ALT_CI_INTERRUPT_VECTOR */
/*
* Notify the operating system that interrupt processing is complete.
*/
ALT_OS_INT_EXIT();
}
#endif /* ALT_CPU_EIC_PRESENT */
|
Kristopher38/LuaCPU | software/lua_on_nios2/lua/lstring.h | <filename>software/lua_on_nios2/lua/lstring.h
/*
** $Id: lstring.h,v 1.61.1.1 2017/04/19 17:20:42 roberto Exp $
** String table (keep all strings handled by Lua)
** See Copyright Notice in lua.h
*/
#ifndef lstring_h
#define lstring_h
#include "lgc.h"
#include "lobject.h"
#include "lstate.h"
#define sizelstring(l) (sizeof(union UTString) + ((l) + 1) * sizeof(char))
#define sizeludata(l) (sizeof(union UUdata) + (l))
#define sizeudata(u) sizeludata((u)->len)
#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
(sizeof(s)/sizeof(char))-1))
/*
** test whether a string is a reserved word
*/
#define isreserved(s) ((s)->tt == LUA_TSHRSTR && (s)->extra > 0)
/*
** equality for short strings, which are always internalized
*/
#define eqshrstr(a,b) check_exp((a)->tt == LUA_TSHRSTR, (a) == (b))
LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);
LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts);
LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b);
LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
LUAI_FUNC void luaS_clearcache (global_State *g);
LUAI_FUNC void luaS_init (lua_State *L);
LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s);
LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l);
#endif
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/inc/sys/alt_warning.h | <filename>software/lua_on_nios2_bsp/HAL/inc/sys/alt_warning.h
#ifndef __WARNING_H__
#define __WARNING_H__
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2003 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
/*
* alt_warning.h provides macro definitions that can be used to generate link
* time warnings.
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* The symbol "__alt_invalid" is used to force a link error. There should be
* no corresponding implementation of this function.
*/
extern void __alt_invalid (void);
#define ALT_LINK_WARNING(symbol, msg) \
__asm__(".ifndef __evoke_link_warning_" #symbol \
"\n\t .section .gnu.warning." #symbol \
"\n__evoke_link_warning_" #symbol ":\n\t .string \x22" msg "\x22 \n\t .previous" \
"\n .endif");
/* A canned warning for sysdeps/stub functions. */
#define ALT_STUB_WARNING(name) \
ALT_LINK_WARNING (name, \
"warning: " #name " is not implemented and will always fail")
#define ALT_OBSOLETE_FUNCTION_WARNING(name) \
ALT_LINK_WARNING (name, \
"warning: " #name " is a deprecated function")
#define ALT_LINK_ERROR(msg) \
ALT_LINK_WARNING (__alt_invalid, msg); \
__alt_invalid()
#ifdef __cplusplus
}
#endif
#endif /* __WARNING_H__ */
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/drivers/src/altera_avalon_jtag_uart_write.c | <reponame>Kristopher38/LuaCPU
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2006 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#include "sys/alt_irq.h"
#include "sys/alt_alarm.h"
#include "sys/ioctl.h"
#include "alt_types.h"
#include "altera_avalon_jtag_uart_regs.h"
#include "altera_avalon_jtag_uart.h"
#include "sys/alt_log_printf.h"
#ifdef __ucosii__
#include "includes.h"
#endif /* __ucosii__ */
#ifdef ALTERA_AVALON_JTAG_UART_SMALL
/* ----------------------------------------------------------- */
/* ------------------------ SMALL DRIVER --------------------- */
/* ----------------------------------------------------------- */
/* Write routine. The small version blocks when there is no space to write
* into, so it's performance will be very bad if you are writing more than
* one FIFOs worth of data. But you said you didn't want to use interrupts :-)
*/
int altera_avalon_jtag_uart_write(altera_avalon_jtag_uart_state* sp,
const char * ptr, int count, int flags)
{
unsigned int base = sp->base;
const char * end = ptr + count;
while (ptr < end)
if ((IORD_ALTERA_AVALON_JTAG_UART_CONTROL(base) & ALTERA_AVALON_JTAG_UART_CONTROL_WSPACE_MSK) != 0)
IOWR_ALTERA_AVALON_JTAG_UART_DATA(base, *ptr++);
return count;
}
#else /* !ALTERA_AVALON_JTAG_UART_SMALL */
/* ----------------------------------------------------------- */
/* ------------------------- FAST DRIVER --------------------- */
/* ----------------------------------------------------------- */
int
altera_avalon_jtag_uart_write(altera_avalon_jtag_uart_state* sp,
const char * ptr, int count, int flags)
{
/* Remove warning at optimisation level 03 by seting out to 0 */
unsigned int in, out=0;
unsigned int n;
alt_irq_context context;
const char * start = ptr;
/*
* When running in a multi threaded environment, obtain the "write_lock"
* semaphore. This ensures that writing to the device is thread-safe.
*/
ALT_SEM_PEND (sp->write_lock, 0);
do
{
/* Copy as much as we can into the transmit buffer */
while (count > 0)
{
/* We need a stable value of the out pointer to calculate the space available */
in = sp->tx_in;
out = sp->tx_out;
if (in < out)
n = out - 1 - in;
else if (out > 0)
n = ALTERA_AVALON_JTAG_UART_BUF_LEN - in;
else
n = ALTERA_AVALON_JTAG_UART_BUF_LEN - 1 - in;
if (n == 0)
break;
if (n > count)
n = count;
memcpy(sp->tx_buf + in, ptr, n);
ptr += n;
count -= n;
sp->tx_in = (in + n) % ALTERA_AVALON_JTAG_UART_BUF_LEN;
}
/*
* If interrupts are disabled then we could transmit here, we only need
* to enable interrupts if there is no space left in the FIFO
*
* For now kick the interrupt routine every time to make it transmit
* the data
*/
context = alt_irq_disable_all();
sp->irq_enable |= ALTERA_AVALON_JTAG_UART_CONTROL_WE_MSK;
IOWR_ALTERA_AVALON_JTAG_UART_CONTROL(sp->base, sp->irq_enable);
alt_irq_enable_all(context);
/*
* If there is any data left then either return now or block until
* some has been sent
*/
/* consider: test whether there is anything there while doing this and delay for at most 2s. */
if (count > 0)
{
if (flags & O_NONBLOCK)
break;
#ifdef __ucosii__
/* OS Present: Pend on a flag if the OS is running, otherwise spin */
if(OSRunning == OS_TRUE) {
/*
* When running in a multi-threaded mode, we pend on the write event
* flag set or the timeout flag in the isr. This avoids wasting CPU
* cycles waiting in this thread, when we could be doing something
* more profitable elsewhere.
*/
#ifdef ALTERA_AVALON_JTAG_UART_IGNORE_FIFO_FULL_ERROR
if(!sp->host_inactive)
#endif
ALT_FLAG_PEND (sp->events,
ALT_JTAG_UART_WRITE_RDY | ALT_JTAG_UART_TIMEOUT,
OS_FLAG_WAIT_SET_ANY + OS_FLAG_CONSUME,
0);
}
else {
/*
* OS not running: Wait for data to be removed from buffer.
* Once the interrupt routine has removed some data then we
* will be able to insert some more.
*/
while (out == sp->tx_out && sp->host_inactive < sp->timeout)
;
}
#else
/*
* No OS present: Always wait for data to be removed from buffer. Once
* the interrupt routine has removed some data then we will be able to
* insert some more.
*/
while (out == sp->tx_out && sp->host_inactive < sp->timeout)
;
#endif /* __ucosii__ */
if (sp->host_inactive)
break;
}
}
while (count > 0);
/*
* Now that access to the circular buffer is complete, release the write
* semaphore so that other threads can access the buffer.
*/
ALT_SEM_POST (sp->write_lock);
if (ptr != start)
return ptr - start;
else if (flags & O_NONBLOCK)
return -EWOULDBLOCK;
#ifdef ALTERA_AVALON_JTAG_UART_IGNORE_FIFO_FULL_ERROR
else if (sp->host_inactive >= sp->timeout) {
/*
* Reset the software FIFO, hardware FIFO could not be reset.
* Just throw away characters without reporting error.
*/
sp->tx_out = sp->tx_in = 0;
return ptr - start + count;
}
#endif
else
return -EIO; /* Host not connected */
}
#endif /* ALTERA_AVALON_JTAG_UART_SMALL */
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/system.h | <gh_stars>0
/*
* system.h - SOPC Builder system and BSP software package information
*
* Machine generated for CPU 'nios2_gen2_0' in SOPC Builder design 'soc_system'
* SOPC Builder design path: /home/kris/luacpu/hardware/soc_system.sopcinfo
*
* Generated: Wed Feb 16 22:25:28 CET 2022
*/
/*
* DO NOT MODIFY THIS FILE
*
* Changing this file will have subtle consequences
* which will almost certainly lead to a nonfunctioning
* system. If you do modify this file, be aware that your
* changes will be overwritten and lost when this file
* is generated again.
*
* DO NOT MODIFY THIS FILE
*/
/*
* License Agreement
*
* Copyright (c) 2008
* Altera Corporation, San Jose, California, USA.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* This agreement shall be governed in all respects by the laws of the State
* of California and by the laws of the United States of America.
*/
#ifndef __SYSTEM_H_
#define __SYSTEM_H_
/* Include definitions from linker script generator */
#include "linker.h"
/*
* CPU configuration
*
*/
#define ALT_CPU_ARCHITECTURE "altera_nios2_gen2"
#define ALT_CPU_BIG_ENDIAN 0
#define ALT_CPU_BREAK_ADDR 0x70000820
#define ALT_CPU_CPU_ARCH_NIOS2_R1
#define ALT_CPU_CPU_FREQ 50000000u
#define ALT_CPU_CPU_ID_SIZE 1
#define ALT_CPU_CPU_ID_VALUE 0x00000000
#define ALT_CPU_CPU_IMPLEMENTATION "fast"
#define ALT_CPU_DATA_ADDR_WIDTH 0x1f
#define ALT_CPU_DCACHE_LINE_SIZE 0
#define ALT_CPU_DCACHE_LINE_SIZE_LOG2 0
#define ALT_CPU_DCACHE_SIZE 0
#define ALT_CPU_EXCEPTION_ADDR 0x00000020
#define ALT_CPU_FLASH_ACCELERATOR_LINES 0
#define ALT_CPU_FLASH_ACCELERATOR_LINE_SIZE 0
#define ALT_CPU_FLUSHDA_SUPPORTED
#define ALT_CPU_FREQ 50000000
#define ALT_CPU_HARDWARE_DIVIDE_PRESENT 0
#define ALT_CPU_HARDWARE_MULTIPLY_PRESENT 1
#define ALT_CPU_HARDWARE_MULX_PRESENT 0
#define ALT_CPU_HAS_DEBUG_CORE 1
#define ALT_CPU_HAS_DEBUG_STUB
#define ALT_CPU_HAS_EXTRA_EXCEPTION_INFO
#define ALT_CPU_HAS_ILLEGAL_INSTRUCTION_EXCEPTION
#define ALT_CPU_HAS_JMPI_INSTRUCTION
#define ALT_CPU_ICACHE_LINE_SIZE 32
#define ALT_CPU_ICACHE_LINE_SIZE_LOG2 5
#define ALT_CPU_ICACHE_SIZE 2048
#define ALT_CPU_INST_ADDR_WIDTH 0x1f
#define ALT_CPU_NAME "nios2_gen2_0"
#define ALT_CPU_NUM_OF_SHADOW_REG_SETS 0
#define ALT_CPU_OCI_VERSION 1
#define ALT_CPU_RESET_ADDR 0x00000000
/*
* CPU configuration (with legacy prefix - don't use these anymore)
*
*/
#define NIOS2_BIG_ENDIAN 0
#define NIOS2_BREAK_ADDR 0x70000820
#define NIOS2_CPU_ARCH_NIOS2_R1
#define NIOS2_CPU_FREQ 50000000u
#define NIOS2_CPU_ID_SIZE 1
#define NIOS2_CPU_ID_VALUE 0x00000000
#define NIOS2_CPU_IMPLEMENTATION "fast"
#define NIOS2_DATA_ADDR_WIDTH 0x1f
#define NIOS2_DCACHE_LINE_SIZE 0
#define NIOS2_DCACHE_LINE_SIZE_LOG2 0
#define NIOS2_DCACHE_SIZE 0
#define NIOS2_EXCEPTION_ADDR 0x00000020
#define NIOS2_FLASH_ACCELERATOR_LINES 0
#define NIOS2_FLASH_ACCELERATOR_LINE_SIZE 0
#define NIOS2_FLUSHDA_SUPPORTED
#define NIOS2_HARDWARE_DIVIDE_PRESENT 0
#define NIOS2_HARDWARE_MULTIPLY_PRESENT 1
#define NIOS2_HARDWARE_MULX_PRESENT 0
#define NIOS2_HAS_DEBUG_CORE 1
#define NIOS2_HAS_DEBUG_STUB
#define NIOS2_HAS_EXTRA_EXCEPTION_INFO
#define NIOS2_HAS_ILLEGAL_INSTRUCTION_EXCEPTION
#define NIOS2_HAS_JMPI_INSTRUCTION
#define NIOS2_ICACHE_LINE_SIZE 32
#define NIOS2_ICACHE_LINE_SIZE_LOG2 5
#define NIOS2_ICACHE_SIZE 2048
#define NIOS2_INST_ADDR_WIDTH 0x1f
#define NIOS2_NUM_OF_SHADOW_REG_SETS 0
#define NIOS2_OCI_VERSION 1
#define NIOS2_RESET_ADDR 0x00000000
/*
* Custom instruction macros
*
*/
#define ALT_CI_LUA_CPU_0(n,A,B) __builtin_custom_inii(ALT_CI_LUA_CPU_0_N+(n&ALT_CI_LUA_CPU_0_N_MASK),(A),(B))
#define ALT_CI_LUA_CPU_0_N 0x0
#define ALT_CI_LUA_CPU_0_N_MASK ((1<<2)-1)
/*
* Define for each module class mastered by the CPU
*
*/
#define __ALTERA_AVALON_JTAG_UART
#define __ALTERA_AVALON_NEW_SDRAM_CONTROLLER
#define __ALTERA_AVALON_PIO
#define __ALTERA_AVALON_SYSID_QSYS
#define __ALTERA_NIOS2_GEN2
#define __LUA_CPU
/*
* System configuration
*
*/
#define ALT_DEVICE_FAMILY "Cyclone V"
#define ALT_ENHANCED_INTERRUPT_API_PRESENT
#define ALT_IRQ_BASE NULL
#define ALT_LOG_PORT "/dev/null"
#define ALT_LOG_PORT_BASE 0x0
#define ALT_LOG_PORT_DEV null
#define ALT_LOG_PORT_TYPE ""
#define ALT_NUM_EXTERNAL_INTERRUPT_CONTROLLERS 0
#define ALT_NUM_INTERNAL_INTERRUPT_CONTROLLERS 1
#define ALT_NUM_INTERRUPT_CONTROLLERS 1
#define ALT_STDERR "/dev/jtag_uart"
#define ALT_STDERR_BASE 0x30000000
#define ALT_STDERR_DEV jtag_uart
#define ALT_STDERR_IS_JTAG_UART
#define ALT_STDERR_PRESENT
#define ALT_STDERR_TYPE "altera_avalon_jtag_uart"
#define ALT_STDIN "/dev/jtag_uart"
#define ALT_STDIN_BASE 0x30000000
#define ALT_STDIN_DEV jtag_uart
#define ALT_STDIN_IS_JTAG_UART
#define ALT_STDIN_PRESENT
#define ALT_STDIN_TYPE "altera_avalon_jtag_uart"
#define ALT_STDOUT "/dev/jtag_uart"
#define ALT_STDOUT_BASE 0x30000000
#define ALT_STDOUT_DEV jtag_uart
#define ALT_STDOUT_IS_JTAG_UART
#define ALT_STDOUT_PRESENT
#define ALT_STDOUT_TYPE "altera_avalon_jtag_uart"
#define ALT_SYSTEM_NAME "soc_system"
/*
* hal configuration
*
*/
#define ALT_INCLUDE_INSTRUCTION_RELATED_EXCEPTION_API
#define ALT_MAX_FD 32
#define ALT_SYS_CLK none
#define ALT_TIMESTAMP_CLK none
/*
* jtag_uart configuration
*
*/
#define ALT_MODULE_CLASS_jtag_uart altera_avalon_jtag_uart
#define JTAG_UART_BASE 0x30000000
#define JTAG_UART_IRQ 0
#define JTAG_UART_IRQ_INTERRUPT_CONTROLLER_ID 0
#define JTAG_UART_NAME "/dev/jtag_uart"
#define JTAG_UART_READ_DEPTH 64
#define JTAG_UART_READ_THRESHOLD 8
#define JTAG_UART_SPAN 8
#define JTAG_UART_TYPE "altera_avalon_jtag_uart"
#define JTAG_UART_WRITE_DEPTH 64
#define JTAG_UART_WRITE_THRESHOLD 8
/*
* leds_0 configuration
*
*/
#define ALT_MODULE_CLASS_leds_0 altera_avalon_pio
#define LEDS_0_BASE 0x70000000
#define LEDS_0_BIT_CLEARING_EDGE_REGISTER 0
#define LEDS_0_BIT_MODIFYING_OUTPUT_REGISTER 0
#define LEDS_0_CAPTURE 0
#define LEDS_0_DATA_WIDTH 10
#define LEDS_0_DO_TEST_BENCH_WIRING 0
#define LEDS_0_DRIVEN_SIM_VALUE 0
#define LEDS_0_EDGE_TYPE "NONE"
#define LEDS_0_FREQ 50000000
#define LEDS_0_HAS_IN 0
#define LEDS_0_HAS_OUT 1
#define LEDS_0_HAS_TRI 0
#define LEDS_0_IRQ -1
#define LEDS_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define LEDS_0_IRQ_TYPE "NONE"
#define LEDS_0_NAME "/dev/leds_0"
#define LEDS_0_RESET_VALUE 0
#define LEDS_0_SPAN 16
#define LEDS_0_TYPE "altera_avalon_pio"
/*
* sdram_controller_0 configuration
*
*/
#define ALT_MODULE_CLASS_sdram_controller_0 altera_avalon_new_sdram_controller
#define SDRAM_CONTROLLER_0_BASE 0x0
#define SDRAM_CONTROLLER_0_CAS_LATENCY 3
#define SDRAM_CONTROLLER_0_CONTENTS_INFO
#define SDRAM_CONTROLLER_0_INIT_NOP_DELAY 0.0
#define SDRAM_CONTROLLER_0_INIT_REFRESH_COMMANDS 2
#define SDRAM_CONTROLLER_0_IRQ -1
#define SDRAM_CONTROLLER_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SDRAM_CONTROLLER_0_IS_INITIALIZED 1
#define SDRAM_CONTROLLER_0_NAME "/dev/sdram_controller_0"
#define SDRAM_CONTROLLER_0_POWERUP_DELAY 100.0
#define SDRAM_CONTROLLER_0_REFRESH_PERIOD 7.8125
#define SDRAM_CONTROLLER_0_REGISTER_DATA_IN 1
#define SDRAM_CONTROLLER_0_SDRAM_ADDR_WIDTH 0x19
#define SDRAM_CONTROLLER_0_SDRAM_BANK_WIDTH 2
#define SDRAM_CONTROLLER_0_SDRAM_COL_WIDTH 10
#define SDRAM_CONTROLLER_0_SDRAM_DATA_WIDTH 16
#define SDRAM_CONTROLLER_0_SDRAM_NUM_BANKS 4
#define SDRAM_CONTROLLER_0_SDRAM_NUM_CHIPSELECTS 1
#define SDRAM_CONTROLLER_0_SDRAM_ROW_WIDTH 13
#define SDRAM_CONTROLLER_0_SHARED_DATA 0
#define SDRAM_CONTROLLER_0_SIM_MODEL_BASE 0
#define SDRAM_CONTROLLER_0_SPAN 67108864
#define SDRAM_CONTROLLER_0_STARVATION_INDICATOR 0
#define SDRAM_CONTROLLER_0_TRISTATE_BRIDGE_SLAVE ""
#define SDRAM_CONTROLLER_0_TYPE "altera_avalon_new_sdram_controller"
#define SDRAM_CONTROLLER_0_T_AC 5.4
#define SDRAM_CONTROLLER_0_T_MRD 3
#define SDRAM_CONTROLLER_0_T_RCD 15.0
#define SDRAM_CONTROLLER_0_T_RFC 70.0
#define SDRAM_CONTROLLER_0_T_RP 15.0
#define SDRAM_CONTROLLER_0_T_WR 14.0
/*
* sysid_qsys_0 configuration
*
*/
#define ALT_MODULE_CLASS_sysid_qsys_0 altera_avalon_sysid_qsys
#define SYSID_QSYS_0_BASE 0x70000010
#define SYSID_QSYS_0_ID -559038737
#define SYSID_QSYS_0_IRQ -1
#define SYSID_QSYS_0_IRQ_INTERRUPT_CONTROLLER_ID -1
#define SYSID_QSYS_0_NAME "/dev/sysid_qsys_0"
#define SYSID_QSYS_0_SPAN 8
#define SYSID_QSYS_0_TIMESTAMP 1645045668
#define SYSID_QSYS_0_TYPE "altera_avalon_sysid_qsys"
#endif /* __SYSTEM_H_ */
|
Kristopher38/LuaCPU | software/lua_on_nios2/lua/lprefix.h | <filename>software/lua_on_nios2/lua/lprefix.h
/*
** $Id: lprefix.h,v 1.2.1.1 2017/04/19 17:20:42 roberto Exp $
** Definitions for Lua code that must come before any other header file
** See Copyright Notice in lua.h
*/
#ifndef lprefix_h
#define lprefix_h
/*
** Allows POSIX/XSI stuff
*/
#if !defined(LUA_USE_C89) /* { */
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#elif _XOPEN_SOURCE == 0
#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */
#endif
/*
** Allows manipulation of large files in gcc and some other compilers
*/
#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)
#define _LARGEFILE_SOURCE 1
#define _FILE_OFFSET_BITS 64
#endif
#endif /* } */
/*
** Windows stuff
*/
#if defined(_WIN32) /* { */
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */
#endif
#endif /* } */
#endif
|
Kristopher38/LuaCPU | software/lua_on_nios2/lua/testes/libs/lib11.c | #include "lua.h"
/* function from lib1.c */
int lib1_export (lua_State *L);
LUAMOD_API int luaopen_lib11 (lua_State *L) {
return lib1_export(L);
}
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_iic_isr_register.c | <reponame>Kristopher38/LuaCPU
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2009 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
#include <errno.h>
#include "system.h"
/*
* Provides an interrupt registry mechanism for the any CPUs internal interrupt
* controller (IIC) when the enhanced interrupt API is active.
*/
#ifndef ALT_CPU_EIC_PRESENT
#ifdef ALT_ENHANCED_INTERRUPT_API_PRESENT
#include "alt_types.h"
#include "sys/alt_irq.h"
#include "priv/alt_iic_isr_register.h"
/*
* The header, alt_irq_entry.h, contains the exception entry point, and is
* provided by the processor component. It is included here, so that the code
* will be added to the executable only if alt_irq_register() is present, i.e.
* if no interrupts are registered - there's no need to provide any
* interrupt handling.
*/
#include "sys/alt_irq_entry.h"
/*
* The header, alt_irq_table.h contains a table describing which function
* handles each interrupt.
*/
#include "priv/alt_irq_table.h"
/** @Function Description: This function registers an interrupt handler.
* If the function is succesful, then the requested interrupt will be enabled
* upon return. Registering a NULL handler will disable the interrupt.
*
* @API Type: External
* @param ic_id Interrupt controller ID
* @param irq IRQ ID number
* @param isr Pointer to interrupt service routine
* @param isr_context Opaque pointer passed to ISR
* @param flags
* @return 0 if successful, else error (-1)
*/
int alt_iic_isr_register(alt_u32 ic_id, alt_u32 irq, alt_isr_func isr,
void *isr_context, void *flags)
{
int rc = -EINVAL;
int id = irq; /* IRQ interpreted as the interrupt ID. */
alt_irq_context status;
if (id < ALT_NIRQ)
{
/*
* interrupts are disabled while the handler tables are updated to ensure
* that an interrupt doesn't occur while the tables are in an inconsistant
* state.
*/
status = alt_irq_disable_all();
alt_irq[id].handler = isr;
alt_irq[id].context = isr_context;
rc = (isr) ? alt_ic_irq_enable(ic_id, id) : alt_ic_irq_disable(ic_id, id);
alt_irq_enable_all(status);
}
return rc;
}
#endif /* ALT_ENHANCED_INTERRUPT_API_PRESENT */
#endif /* ALT_CPU_EIC_PRESENT */
|
Kristopher38/LuaCPU | software/lua_on_nios2/lua/cpusim.h | <reponame>Kristopher38/LuaCPU
#ifndef h_cpusim
#define h_cpusim
#include <iostream>
#include <queue>
#include <verilated.h>
#include "obj_dir/Vlua_cpu.h"
#include "verilated_vcd_c.h"
class SDRAMController;
extern Vlua_cpu* cpu;
extern SDRAMController* sdram;
extern VerilatedVcdC* tfp;
extern uint32_t luacpu_simulate(void* L, void* ci);
extern void luacpu_reset();
extern void luacpu_init(int argc, char** argv);
extern void luacpu_deinit();
void clk_half(int dir);
void clk_up();
void clk_down();
void clk();
void instr_begin(int n);
void luacpu_storett(void* regbase, int tt);
void luacpu_storebase(void* base);
template <typename T>
void luacpu_storeval(void* regbase, T val)
{
instr_begin(1);
cpu->nios_lua_exec_slave_dataa = reinterpret_cast<uint32_t>(regbase);
// gcc won't let me use reinterpret cast on all types:
// cpu->nios_lua_exec_slave_datab = reinterpret_cast<uint32_t>(val);
__asm__("" : "=r" (cpu->nios_lua_exec_slave_datab) : "0" (val));
clk();
cpu->nios_lua_exec_slave_start = 0;
while (!cpu->nios_lua_exec_slave_done)
clk();
}
#endif |
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_usleep.c | <gh_stars>100-1000
/*
* Copyright (c) 2003 Altera Corporation, San Jose, California, USA.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* ------------
*
* Altera does not recommend, suggest or require that this reference design
* file be used in conjunction or combination with any other product.
*
* usleep.c - Microsecond delay routine
*/
#include <unistd.h>
#include "priv/alt_busy_sleep.h"
#include "os/alt_syscall.h"
/*
* This function simply calls alt_busy_sleep() to perform the delay. This
* function implements the delay as a calibrated "busy loop".
*
* ALT_USLEEP is mapped onto the usleep() system call in alt_syscall.h
*/
#if defined (__GNUC__) && __GNUC__ >= 4
int ALT_USLEEP (useconds_t us)
#else
unsigned int ALT_USLEEP (unsigned int us)
#endif
{
return alt_busy_sleep(us);
}
|
Kristopher38/LuaCPU | software/lua_on_nios2/lua/obj_dir/Vlua_cpu.h | <reponame>Kristopher38/LuaCPU
// Verilated -*- C++ -*-
// DESCRIPTION: Verilator output: Primary model header
//
// This header should be included by all source files instantiating the design.
// The class here is then constructed to instantiate the design.
// See the Verilator manual for examples.
#ifndef VERILATED_VLUA_CPU_H_
#define VERILATED_VLUA_CPU_H_ // guard
#include "verilated.h"
class Vlua_cpu__Syms;
class Vlua_cpu___024root;
class VerilatedVcdC;
// This class is the main interface to the Verilated model
class Vlua_cpu VL_NOT_FINAL {
private:
// Symbol table holding complete model state (owned by this class)
Vlua_cpu__Syms* const vlSymsp;
public:
// PORTS
// The application code writes and reads these signals to
// propagate new values into/out from the Verilated model.
VL_IN8(&nios_lua_exec_slave_clk,0,0);
VL_IN8(&nios_lua_exec_slave_clk_en,0,0);
VL_IN8(&nios_lua_exec_slave_start,0,0);
VL_OUT8(&nios_lua_exec_slave_done,0,0);
VL_IN8(&nios_lua_exec_slave_a,4,0);
VL_IN8(&nios_lua_exec_slave_b,4,0);
VL_IN8(&nios_lua_exec_slave_c,4,0);
VL_IN8(&nios_lua_exec_slave_n,1,0);
VL_IN8(&nios_lua_exec_slave_readra,0,0);
VL_IN8(&nios_lua_exec_slave_readrb,0,0);
VL_IN8(&nios_lua_exec_slave_reset,0,0);
VL_IN8(&nios_lua_exec_slave_writerc,0,0);
VL_OUT8(&avalon_master_read,0,0);
VL_OUT8(&avalon_master_write,0,0);
VL_IN8(&avalon_master_waitrequest,0,0);
VL_IN8(&clock_sink_clk,0,0);
VL_IN8(&reset_sink_reset,0,0);
VL_IN(&nios_lua_exec_slave_dataa,31,0);
VL_IN(&nios_lua_exec_slave_datab,31,0);
VL_OUT(&nios_lua_exec_slave_result,31,0);
VL_OUT(&avalon_master_address,31,0);
VL_IN(&avalon_master_readdata,31,0);
VL_OUT(&avalon_master_writedata,31,0);
// CELLS
// Public to allow access to /* verilator public */ items.
// Otherwise the application code can consider these internals.
// Root instance pointer to allow access to model internals,
// including inlined /* verilator public_flat_* */ items.
Vlua_cpu___024root* const rootp;
// CONSTRUCTORS
/// Construct the model; called by application code
/// If contextp is null, then the model will use the default global context
/// If name is "", then makes a wrapper with a
/// single model invisible with respect to DPI scope names.
explicit Vlua_cpu(VerilatedContext* contextp, const char* name = "TOP");
explicit Vlua_cpu(const char* name = "TOP");
/// Destroy the model; called (often implicitly) by application code
virtual ~Vlua_cpu();
private:
VL_UNCOPYABLE(Vlua_cpu); ///< Copying not allowed
public:
// API METHODS
/// Evaluate the model. Application must call when inputs change.
void eval() { eval_step(); }
/// Evaluate when calling multiple units/models per time step.
void eval_step();
/// Evaluate at end of a timestep for tracing, when using eval_step().
/// Application must call after all eval() and before time changes.
void eval_end_step() {}
/// Simulation complete, run final blocks. Application must call on completion.
void final();
/// Trace signals in the model; called by application code
void trace(VerilatedVcdC* tfp, int levels, int options = 0);
/// Return current simulation context for this model.
/// Used to get to e.g. simulation time via contextp()->time()
VerilatedContext* contextp() const;
/// Retrieve name of this model instance (as passed to constructor).
const char* name() const;
} VL_ATTR_ALIGNED(VL_CACHE_LINE_BYTES);
#endif // guard
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/inc/priv/alt_alarm.h | #ifndef __ALT_PRIV_ALARM_H__
#define __ALT_PRIV_ALARM_H__
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
/******************************************************************************
* *
* THIS IS A LIBRARY READ-ONLY SOURCE FILE. DO NOT EDIT. *
* *
******************************************************************************/
#include "alt_types.h"
/*
* This header provides the internal defenitions required by the public
* interface alt_alarm.h. These variables and structures are not guaranteed to
* exist in future implementations of the HAL.
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* "alt_alarm_s" is a structure type used to maintain lists of alarm callback
* functions.
*/
struct alt_alarm_s
{
alt_llist llist; /* linked list */
alt_u32 time; /* time in system ticks of the callback */
alt_u32 (*callback) (void* context); /* callback function. The return
* value is the period for the next callback; where
* zero indicates that the alarm should be removed
* from the list.
*/
alt_u8 rollover; /* set when desired alarm time + current time causes
overflow, to prevent premature alarm */
void* context; /* Argument for the callback */
};
/*
* "_alt_tick_rate" is a global variable used to store the system clock rate
* in ticks per second. This is initialised to zero, which coresponds to there
* being no system clock available.
*
* It is then set to it's final value by the system clock driver through a call
* to alt_sysclk_init().
*/
extern alt_u32 _alt_tick_rate;
/*
* "_alt_nticks" is a global variable which records the elapsed number of
* system clock ticks since the last call to settimeofday() or since reset if
* settimeofday() has not been called.
*/
extern volatile alt_u32 _alt_nticks;
/* The list of registered alarms. */
extern alt_llist alt_alarm_list;
#ifdef __cplusplus
}
#endif
#endif /* __ALT_PRIV_ALARM_H__ */
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_remap_uncached.c | /******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2003,2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
#include "sys/alt_warning.h"
#include "sys/alt_cache.h"
#include "system.h"
/*
* Convert a pointer to a block of cached memory into a block of uncached memory.
* Return a pointer that should be used to access the uncached memory.
*
* This routine was created for Nios II Gen1 cores which allow mixing cacheable and
* uncachable data in the same data cache line. So, they could take any memory region
* and make it uncached. However, Nios II Gen2 cores don't support mixing cacheable
* and uncachable data in the same data cache line so require the memory region to
* be aligned to a cache line boundary and must be an integer number of cache line
* bytes in size. So, software on a Nios II Gen2 core shouldn't really be using this
* function so it fails with a link error.
*/
volatile void*
alt_remap_uncached(void* ptr, alt_u32 len)
{
/* Generate a link time error, should this function ever be called. */
ALT_LINK_ERROR("alt_remap_uncached() is not available because Nios II Gen2 cores with data caches don't support mixing cacheable and uncacheable data on the same line.");
return NULL;
}
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/drivers/src/altera_avalon_sysid_qsys.c | <reponame>Kristopher38/LuaCPU
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2003 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
#include "altera_avalon_sysid_qsys.h"
#include "altera_avalon_sysid_qsys_regs.h"
#include "alt_types.h"
#include <io.h>
/*
* This component is special: there's only one of it.
* Therefore we can dispense with a bunch of complexity
* normally associated with components, such as specialized
* structs containing parameter info, and instead use that
* info by name directly out of system.h. A downside of this
* approach is that each time the system is regenerated, and
* system.h changes, this file must be recompiled. Fortunately
* this file is, and is likely to remain, quite small.
*/
#include "system.h"
#ifdef SYSID_BASE
/*
* return values:
* 0 if the hardware and software appear to be in sync
* 1 if software appears to be older than hardware
* -1 if hardware appears to be older than software
*/
alt_32 alt_avalon_sysid_qsys_test(void)
{
/* Read the hardware-tag, aka value0, from the hardware. */
alt_u32 hardware_id = IORD_ALTERA_AVALON_SYSID_QSYS_ID(SYSID_BASE);
/* Read the time-of-generation, aka value1, from the hardware register. */
alt_u32 hardware_timestamp = IORD_ALTERA_AVALON_SYSID_QSYS_TIMESTAMP(SYSID_BASE);
/* Return 0 if the hardware and software appear to be in sync. */
if ((SYSID_TIMESTAMP == hardware_timestamp) && (SYSID_ID == hardware_id))
{
return 0;
}
/*
* Return 1 if software appears to be older than hardware (that is,
* the value returned by the hardware is larger than that recorded by
* the generator function).
* If the hardware time happens to match the generator program's value
* (but the hardware tag, value0, doesn't match or 0 would have been
* returned above), return an arbitrary value, let's say -1.
*/
return ((alt_32)(hardware_timestamp - SYSID_TIMESTAMP)) > 0 ? 1 : -1;
}
#endif
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/drivers/inc/altera_avalon_jtag_uart_regs.h | <reponame>Kristopher38/LuaCPU
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2003 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
#ifndef __ALTERA_AVALON_JTAG_UART_REGS_H__
#define __ALTERA_AVALON_JTAG_UART_REGS_H__
#include <io.h>
#define ALTERA_AVALON_JTAG_UART_DATA_REG 0
#define IOADDR_ALTERA_AVALON_JTAG_UART_DATA(base) \
__IO_CALC_ADDRESS_NATIVE(base, ALTERA_AVALON_JTAG_UART_DATA_REG)
#define IORD_ALTERA_AVALON_JTAG_UART_DATA(base) \
IORD(base, ALTERA_AVALON_JTAG_UART_DATA_REG)
#define IOWR_ALTERA_AVALON_JTAG_UART_DATA(base, data) \
IOWR(base, ALTERA_AVALON_JTAG_UART_DATA_REG, data)
#define ALTERA_AVALON_JTAG_UART_DATA_DATA_MSK (0x000000FF)
#define ALTERA_AVALON_JTAG_UART_DATA_DATA_OFST (0)
#define ALTERA_AVALON_JTAG_UART_DATA_RVALID_MSK (0x00008000)
#define ALTERA_AVALON_JTAG_UART_DATA_RVALID_OFST (15)
#define ALTERA_AVALON_JTAG_UART_DATA_RAVAIL_MSK (0xFFFF0000)
#define ALTERA_AVALON_JTAG_UART_DATA_RAVAIL_OFST (16)
#define ALTERA_AVALON_JTAG_UART_CONTROL_REG 1
#define IOADDR_ALTERA_AVALON_JTAG_UART_CONTROL(base) \
__IO_CALC_ADDRESS_NATIVE(base, ALTERA_AVALON_JTAG_UART_CONTROL_REG)
#define IORD_ALTERA_AVALON_JTAG_UART_CONTROL(base) \
IORD(base, ALTERA_AVALON_JTAG_UART_CONTROL_REG)
#define IOWR_ALTERA_AVALON_JTAG_UART_CONTROL(base, data) \
IOWR(base, ALTERA_AVALON_JTAG_UART_CONTROL_REG, data)
#define ALTERA_AVALON_JTAG_UART_CONTROL_RE_MSK (0x00000001)
#define ALTERA_AVALON_JTAG_UART_CONTROL_RE_OFST (0)
#define ALTERA_AVALON_JTAG_UART_CONTROL_WE_MSK (0x00000002)
#define ALTERA_AVALON_JTAG_UART_CONTROL_WE_OFST (1)
#define ALTERA_AVALON_JTAG_UART_CONTROL_RI_MSK (0x00000100)
#define ALTERA_AVALON_JTAG_UART_CONTROL_RI_OFST (8)
#define ALTERA_AVALON_JTAG_UART_CONTROL_WI_MSK (0x00000200)
#define ALTERA_AVALON_JTAG_UART_CONTROL_WI_OFST (9)
#define ALTERA_AVALON_JTAG_UART_CONTROL_AC_MSK (0x00000400)
#define ALTERA_AVALON_JTAG_UART_CONTROL_AC_OFST (10)
#define ALTERA_AVALON_JTAG_UART_CONTROL_WSPACE_MSK (0xFFFF0000)
#define ALTERA_AVALON_JTAG_UART_CONTROL_WSPACE_OFST (16)
#endif /* __ALTERA_AVALON_JTAG_UART_REGS_H__ */
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_sbrk.c | <gh_stars>100-1000
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
#include <sys/types.h>
#include "os/alt_syscall.h"
#include "sys/alt_irq.h"
#include "sys/alt_stack.h"
#include "system.h"
/*
* sbrk() is called to dynamically extend the data segment for the application.
* Thie input argument "incr" is the size of the block to allocate.
*
* This simple implementation does not perform any bounds checking. Memory will
* be allocated, even if the request region colides with the stack or overflows
* the available physical memory.
*
* ALT_SBRK is mapped onto the sbrk() system call in alt_syscall.h
*
* This function is called by the profiling code to allocate memory so must be
* safe if called from an interrupt context. It must also not be instrumented
* because that would lead to an infinate loop.
*/
extern char __alt_heap_start[]; /* set by linker */
extern char __alt_heap_limit[]; /* set by linker */
static char *heap_end = __alt_heap_start;
#if defined(ALT_EXCEPTION_STACK) && defined(ALT_STACK_CHECK)
char * alt_exception_old_stack_limit = NULL;
#endif
caddr_t ALT_SBRK (int incr) __attribute__ ((no_instrument_function ));
caddr_t ALT_SBRK (int incr)
{
alt_irq_context context;
char *prev_heap_end;
context = alt_irq_disable_all();
/* Always return data aligned on a word boundary */
heap_end = (char *)(((unsigned int)heap_end + 3) & ~3);
#ifdef ALT_MAX_HEAP_BYTES
/*
* User specified a maximum heap size. Return -1 if it would
* be exceeded by this sbrk call.
*/
if (((heap_end + incr) - __alt_heap_start) > ALT_MAX_HEAP_BYTES) {
alt_irq_enable_all(context);
return (caddr_t)-1;
}
#else
if ((heap_end + incr) > __alt_heap_limit) {
alt_irq_enable_all(context);
return (caddr_t)-1;
}
#endif
prev_heap_end = heap_end;
heap_end += incr;
#ifdef ALT_STACK_CHECK
/*
* If the stack and heap are contiguous then extending the heap reduces the
* space available for the stack. If we are still using the default stack
* then adjust the stack limit to note this, while checking for stack
* pointer overflow.
* If the stack limit isn't pointing at the top of the heap then the code
* is using a different stack so none of this needs to be done.
*/
if (alt_stack_limit() == prev_heap_end)
{
if (alt_stack_pointer() <= heap_end)
alt_report_stack_overflow();
alt_set_stack_limit(heap_end);
}
#ifdef ALT_EXCEPTION_STACK
/*
* If we are executing from the exception stack then compare against the
* stack we switched away from as well. The exception stack is a fixed
* size so doesn't need to be checked.
*/
if (alt_exception_old_stack_limit == prev_heap_end)
{
if (alt_exception_old_stack_limit <= heap_end)
alt_report_stack_overflow();
alt_exception_old_stack_limit = heap_end;
}
#endif
#endif
alt_irq_enable_all(context);
return (caddr_t) prev_heap_end;
}
|
Kristopher38/LuaCPU | software/lua_on_nios2_bsp/HAL/src/alt_uncached_malloc.c | <filename>software/lua_on_nios2_bsp/HAL/src/alt_uncached_malloc.c
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2003,2007 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
******************************************************************************/
#include <malloc.h>
#include "sys/alt_warning.h"
#include "sys/alt_cache.h"
#include "system.h"
/*
* Allocate a block of uncached memory.
* Return pointer to the block of memory or NULL if can't allocate it.
*/
volatile void*
alt_uncached_malloc(size_t size)
{
#if ALT_CPU_DCACHE_SIZE > 0
#ifdef ALT_CPU_DCACHE_BYPASS_MASK
void* ptr;
/* Round up size to an integer number of data cache lines. Required to guarantee that
* cacheable and non-cacheable data won't be mixed on the same cache line. */
const size_t num_lines = (size + ALT_CPU_DCACHE_LINE_SIZE - 1) / ALT_CPU_DCACHE_LINE_SIZE;
const size_t aligned_size = num_lines * ALT_CPU_DCACHE_LINE_SIZE;
/* Use memalign() Newlib routine to allocate starting on a data cache aligned address.
* Required to guarantee that cacheable and non-cacheable data won't be mixed on the
* same cache line. */
ptr = memalign(ALT_CPU_DCACHE_LINE_SIZE, aligned_size);
if (ptr == NULL) {
return NULL; /* Out of memory */
}
/* Ensure that the memory region isn't in the data cache. */
alt_dcache_flush(ptr, aligned_size);
return (volatile void*) (((alt_u32)ptr) | ALT_CPU_DCACHE_BYPASS_MASK);
#else /* No address mask option enabled. */
/* Generate a link time error, should this function ever be called. */
ALT_LINK_ERROR("alt_uncached_malloc() is not available because CPU is not configured to use bit 31 of address to bypass data cache");
return NULL;
#endif /* No address mask option enabled. */
#else /* No data cache */
/* Just use regular malloc. */
return malloc(size);
#endif /* No data cache */
}
|
dltech/laminator-nemo | lib/tm1637.h | <reponame>dltech/laminator-nemo<gh_stars>0
#ifndef H_TM1637
#define H_TM1637
/*
* printf for TM1637 display-driver based 7-segment displays
* connected to STM32.
*
* Copyright 2021 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "inttypes.h"
// ports
#define TM_SCL 10
#define TM_SDA 9
// how much digits on your display
#define DISPLAY_SIZE 3
// TM1637 registers
// data command
#define WRITE_DATA_CMD_AVT 0x70
#define WRITE_DATA_CMD_FIX 0x74
#define READ_KEY_DATA_CMD 0x72
// address command
#define SET_0H 0xf0
#define SET_1H 0xf1
#define SET_2H 0xf2
#define SET_3H 0xf3
#define SET_4H 0xf4
#define SET_5H 0xf5
#define MAXDIGITS 6
// display control
#define DISP_OFF 0xb0
#define BRIGHT6P 0xb8
#define BRIGHT13P 0xb9
#define BRIGHT25P 0xba
#define BRIGHT63P 0xbb
#define BRIGHT69P 0xbc
#define BRIGHT75P 0xbd
#define BRIGHT81P 0xbe
#define BRIGHT88P 0xbf
// Init the MCU and driver before transmit digits.
void tmInit(void);
// You can set brightness of the display in percent.
void setBrightness(uint8_t percent);
// Send new data (blocking api).
void tmUpd(uint8_t *data);
#endif
|
dltech/laminator-nemo | fw/main.c | #include "mystmbackend.h"
#include "printf7.h"
#include "freq_dr.h"
#include "ds18b20.h"
volatile int32_t temp = 0;
volatile uint32_t cnts = 0;
int main(void) {
delay_ms(10);
clkInit();
tmInit();
dsInit();
initPwm();
while(1){
temp = tempBlocking();
if(temp == -1) {
myprintf("err");
} else {
myprintf("%03d",temp/1000);
}
delay_s(1);
++cnts;
}
}
|
dltech/laminator-nemo | lib/cmsis_sin.c | <gh_stars>0
#include "cmsis_sin.h"
const uint32_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1] = {
0x00000000, 0x01921D20, 0x03242ABF, 0x04B6195D, 0x0647D97C, 0x07D95B9E,
0x096A9049, 0x0AFB6805, 0x0C8BD35E, 0x0E1BC2E4, 0x0FAB272B, 0x1139F0CF,
0x12C8106F, 0x145576B1, 0x15E21445, 0x176DD9DE, 0x18F8B83C, 0x1A82A026,
0x1C0B826A, 0x1D934FE5, 0x1F19F97B, 0x209F701C, 0x2223A4C5, 0x23A6887F,
0x25280C5E, 0x26A82186, 0x2826B928, 0x29A3C485, 0x2B1F34EB, 0x2C98FBBA,
0x2E110A62, 0x2F875262, 0x30FBC54D, 0x326E54C7, 0x33DEF287, 0x354D9057,
0x36BA2014, 0x382493B0, 0x398CDD32, 0x3AF2EEB7, 0x3C56BA70, 0x3DB832A6,
0x3F1749B8, 0x4073F21D, 0x41CE1E65, 0x4325C135, 0x447ACD50, 0x45CD358F,
0x471CECE7, 0x4869E665, 0x49B41533, 0x4AFB6C98, 0x4C3FDFF4, 0x4D8162C4,
0x4EBFE8A5, 0x4FFB654D, 0x5133CC94, 0x5269126E, 0x539B2AF0, 0x54CA0A4B,
0x55F5A4D2, 0x571DEEFA, 0x5842DD54, 0x59646498, 0x5A82799A, 0x5B9D1154,
0x5CB420E0, 0x5DC79D7C, 0x5ED77C8A, 0x5FE3B38D, 0x60EC3830, 0x61F1003F,
0x62F201AC, 0x63EF3290, 0x64E88926, 0x65DDFBD3, 0x66CF8120, 0x67BD0FBD,
0x68A69E81, 0x698C246C, 0x6A6D98A4, 0x6B4AF279, 0x6C242960, 0x6CF934FC,
0x6DCA0D14, 0x6E96A99D, 0x6F5F02B2, 0x7023109A, 0x70E2CBC6, 0x719E2CD2,
0x72552C85, 0x7307C3D0, 0x73B5EBD1, 0x745F9DD1, 0x7504D345, 0x75A585CF,
0x7641AF3D, 0x76D94989, 0x776C4EDB, 0x77FAB989, 0x78848414, 0x7909A92D,
0x798A23B1, 0x7A05EEAD, 0x7A7D055B, 0x7AEF6323, 0x7B5D039E, 0x7BC5E290,
0x7C29FBEE, 0x7C894BDE, 0x7CE3CEB2, 0x7D3980EC, 0x7D8A5F40, 0x7DD6668F,
0x7E1D93EA, 0x7E5FE493, 0x7E9D55FC, 0x7ED5E5C6, 0x7F0991C4, 0x7F3857F6,
0x7F62368F, 0x7F872BF3, 0x7FA736B4, 0x7FC25596, 0x7FD8878E, 0x7FE9CBC0,
0x7FF62182, 0x7FFD885A, 0x7FFFFFFF, 0x7FFD885A, 0x7FF62182, 0x7FE9CBC0,
0x7FD8878E, 0x7FC25596, 0x7FA736B4, 0x7F872BF3, 0x7F62368F, 0x7F3857F6,
0x7F0991C4, 0x7ED5E5C6, 0x7E9D55FC, 0x7E5FE493, 0x7E1D93EA, 0x7DD6668F,
0x7D8A5F40, 0x7D3980EC, 0x7CE3CEB2, 0x7C894BDE, 0x7C29FBEE, 0x7BC5E290,
0x7B5D039E, 0x7AEF6323, 0x7A7D055B, 0x7A05EEAD, 0x798A23B1, 0x7909A92D,
0x78848414, 0x77FAB989, 0x776C4EDB, 0x76D94989, 0x7641AF3D, 0x75A585CF,
0x7504D345, 0x745F9DD1, 0x73B5EBD1, 0x7307C3D0, 0x72552C85, 0x719E2CD2,
0x70E2CBC6, 0x7023109A, 0x6F5F02B2, 0x6E96A99D, 0x6DCA0D14, 0x6CF934FC,
0x6C242960, 0x6B4AF279, 0x6A6D98A4, 0x698C246C, 0x68A69E81, 0x67BD0FBD,
0x66CF8120, 0x65DDFBD3, 0x64E88926, 0x63EF3290, 0x62F201AC, 0x61F1003F,
0x60EC3830, 0x5FE3B38D, 0x5ED77C8A, 0x5DC79D7C, 0x5CB420E0, 0x5B9D1154,
0x5A82799A, 0x59646498, 0x5842DD54, 0x571DEEFA, 0x55F5A4D2, 0x54CA0A4B,
0x539B2AF0, 0x5269126E, 0x5133CC94, 0x4FFB654D, 0x4EBFE8A5, 0x4D8162C4,
0x4C3FDFF4, 0x4AFB6C98, 0x49B41533, 0x4869E665, 0x471CECE7, 0x45CD358F,
0x447ACD50, 0x4325C135, 0x41CE1E65, 0x4073F21D, 0x3F1749B8, 0x3DB832A6,
0x3C56BA70, 0x3AF2EEB7, 0x398CDD32, 0x382493B0, 0x36BA2014, 0x354D9057,
0x33DEF287, 0x326E54C7, 0x30FBC54D, 0x2F875262, 0x2E110A62, 0x2C98FBBA,
0x2B1F34EB, 0x29A3C485, 0x2826B928, 0x26A82186, 0x25280C5E, 0x23A6887F,
0x2223A4C5, 0x209F701C, 0x1F19F97B, 0x1D934FE5, 0x1C0B826A, 0x1A82A026,
0x18F8B83C, 0x176DD9DE, 0x15E21445, 0x145576B1, 0x12C8106F, 0x1139F0CF,
0x0FAB272B, 0x0E1BC2E4, 0x0C8BD35E, 0x0AFB6805, 0x096A9049, 0x07D95B9E,
0x0647D97C, 0x04B6195D, 0x03242ABF, 0x01921D20, 0x00000000, 0xFE6DE2E0,
0xFCDBD541, 0xFB49E6A3, 0xF9B82684, 0xF826A462, 0xF6956FB7, 0xF50497FB,
0xF3742CA2, 0xF1E43D1C, 0xF054D8D5, 0xEEC60F31, 0xED37EF91, 0xEBAA894F,
0xEA1DEBBB, 0xE8922622, 0xE70747C4, 0xE57D5FDA, 0xE3F47D96, 0xE26CB01B,
0xE0E60685, 0xDF608FE4, 0xDDDC5B3B, 0xDC597781, 0xDAD7F3A2, 0xD957DE7A,
0xD7D946D8, 0xD65C3B7B, 0xD4E0CB15, 0xD3670446, 0xD1EEF59E, 0xD078AD9E,
0xCF043AB3, 0xCD91AB39, 0xCC210D79, 0xCAB26FA9, 0xC945DFEC, 0xC7DB6C50,
0xC67322CE, 0xC50D1149, 0xC3A94590, 0xC247CD5A, 0xC0E8B648, 0xBF8C0DE3,
0xBE31E19B, 0xBCDA3ECB, 0xBB8532B0, 0xBA32CA71, 0xB8E31319, 0xB796199B,
0xB64BEACD, 0xB5049368, 0xB3C0200C, 0xB27E9D3C, 0xB140175B, 0xB0049AB3,
0xAECC336C, 0xAD96ED92, 0xAC64D510, 0xAB35F5B5, 0xAA0A5B2E, 0xA8E21106,
0xA7BD22AC, 0xA69B9B68, 0xA57D8666, 0xA462EEAC, 0xA34BDF20, 0xA2386284,
0xA1288376, 0xA01C4C73, 0x9F13C7D0, 0x9E0EFFC1, 0x9D0DFE54, 0x9C10CD70,
0x9B1776DA, 0x9A22042D, 0x99307EE0, 0x9842F043, 0x9759617F, 0x9673DB94,
0x9592675C, 0x94B50D87, 0x93DBD6A0, 0x9306CB04, 0x9235F2EC, 0x91695663,
0x90A0FD4E, 0x8FDCEF66, 0x8F1D343A, 0x8E61D32E, 0x8DAAD37B, 0x8CF83C30,
0x8C4A142F, 0x8BA0622F, 0x8AFB2CBB, 0x8A5A7A31, 0x89BE50C3, 0x8926B677,
0x8893B125, 0x88054677, 0x877B7BEC, 0x86F656D3, 0x8675DC4F, 0x85FA1153,
0x8582FAA5, 0x85109CDD, 0x84A2FC62, 0x843A1D70, 0x83D60412, 0x8376B422,
0x831C314E, 0x82C67F14, 0x8275A0C0, 0x82299971, 0x81E26C16, 0x81A01B6D,
0x8162AA04, 0x812A1A3A, 0x80F66E3C, 0x80C7A80A, 0x809DC971, 0x8078D40D,
0x8058C94C, 0x803DAA6A, 0x80277872, 0x80163440, 0x8009DE7E, 0x800277A6,
0x80000000, 0x800277A6, 0x8009DE7E, 0x80163440, 0x80277872, 0x803DAA6A,
0x8058C94C, 0x8078D40D, 0x809DC971, 0x80C7A80A, 0x80F66E3C, 0x812A1A3A,
0x8162AA04, 0x81A01B6D, 0x81E26C16, 0x82299971, 0x8275A0C0, 0x82C67F14,
0x831C314E, 0x8376B422, 0x83D60412, 0x843A1D70, 0x84A2FC62, 0x85109CDD,
0x8582FAA5, 0x85FA1153, 0x8675DC4F, 0x86F656D3, 0x877B7BEC, 0x88054677,
0x8893B125, 0x8926B677, 0x89BE50C3, 0x8A5A7A31, 0x8AFB2CBB, 0x8BA0622F,
0x8C4A142F, 0x8CF83C30, 0x8DAAD37B, 0x8E61D32E, 0x8F1D343A, 0x8FDCEF66,
0x90A0FD4E, 0x91695663, 0x9235F2EC, 0x9306CB04, 0x93DBD6A0, 0x94B50D87,
0x9592675C, 0x9673DB94, 0x9759617F, 0x9842F043, 0x99307EE0, 0x9A22042D,
0x9B1776DA, 0x9C10CD70, 0x9D0DFE54, 0x9E0EFFC1, 0x9F13C7D0, 0xA01C4C73,
0xA1288376, 0xA2386284, 0xA34BDF20, 0xA462EEAC, 0xA57D8666, 0xA69B9B68,
0xA7BD22AC, 0xA8E21106, 0xAA0A5B2E, 0xAB35F5B5, 0xAC64D510, 0xAD96ED92,
0xAECC336C, 0xB0049AB3, 0xB140175B, 0xB27E9D3C, 0xB3C0200C, 0xB5049368,
0xB64BEACD, 0xB796199B, 0xB8E31319, 0xBA32CA71, 0xBB8532B0, 0xBCDA3ECB,
0xBE31E19B, 0xBF8C0DE3, 0xC0E8B648, 0xC247CD5A, 0xC3A94590, 0xC50D1149,
0xC67322CE, 0xC7DB6C50, 0xC945DFEC, 0xCAB26FA9, 0xCC210D79, 0xCD91AB39,
0xCF043AB3, 0xD078AD9E, 0xD1EEF59E, 0xD3670446, 0xD4E0CB15, 0xD65C3B7B,
0xD7D946D8, 0xD957DE7A, 0xDAD7F3A2, 0xDC597781, 0xDDDC5B3B, 0xDF608FE4,
0xE0E60685, 0xE26CB01B, 0xE3F47D96, 0xE57D5FDA, 0xE70747C4, 0xE8922622,
0xEA1DEBBB, 0xEBAA894F, 0xED37EF91, 0xEEC60F31, 0xF054D8D5, 0xF1E43D1C,
0xF3742CA2, 0xF50497FB, 0xF6956FB7, 0xF826A462, 0xF9B82684, 0xFB49E6A3,
0xFCDBD541, 0xFE6DE2E0, 0x00000000
};
/**
* @brief Fast approximation to the trigonometric sine function for Q31 data.
* @param[in] x Scaled input value in radians.
* @return sin(x).
*
* The Q31 input value is in the range [0 +0.9999] and is mapped to a radian value in the range [0 2*pi). */
uint32_t arm_sin_q31(uint32_t x)
{
uint32_t sinVal; /* Temporary variables for input, output */
int32_t index; /* Index variables */
uint32_t a, b; /* Four nearest output values */
uint32_t fract; /* Temporary values for fractional values */
/* Calculate the nearest index */
index = (uint32_t)x >> FAST_MATH_Q31_SHIFT;
/* Calculation of fractional value */
fract = (x - (index << FAST_MATH_Q31_SHIFT)) << 9;
/* Read two nearest values of input value from the sin table */
a = sinTable_q31[index];
b = sinTable_q31[index+1];
/* Linear interpolation process */
sinVal = (uint64_t)(0x80000000-fract)*a >> 32;
sinVal = (uint32_t)((((uint64_t)sinVal << 32) + ((uint64_t)fract*b)) >> 32);
return sinVal << 1;
}
|
dltech/laminator-nemo | lib/ds18b20.h | #ifndef H_DS18B20
#define H_DS18B20
/*
* stm32 usart based ds18b20 lib
*
* Copyright 2021 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "inttypes.h"
/* Configuration macro */
// Rom commands
#define SEARCH_ROM 0xf0
#define READ_ROM 0x33
#define MATCH_ROM 0x55
#define SKIP_ROM 0xcc
#define ALARM_SEARCH 0xec
// Function commands
#define CONVERT_T 0x44
#define READ_SCRATCHPAD 0xbe
#define WRITE_SCRATCHPAD 0x4e
#define COPY_SCRATCHPAD 0x48
#define RECALL_E2 0xb8
#define READ_POWER_SUPPLY 0xb4
// ds18b20 family code
#define FAMILY_CODE 0x28
// configuration
#define RESOL_9BIT 0x1f
#define RESOL_10BIT 0x3f
#define RESOL_11BIT 0x5f
#define RESOL_12BIT 0x7f
// timings
// for bit read/write
#define WRITE0T 70
#define WRITE1T1 10
#define WRITE1T2 70
#define READT 10
#define TIMESLOT 100
// for init pulse
#define RESET_PULSE 500
#define RESET_WAIT 50
#define INIT_PULSE_MIN 50
#define INIT_PULSE_MAX 300
// ds port latency
#define PULSE_DELAY 4
/* settings */
// mcu related
#define DS_PORT GPIOA
#define DS_PIN 2
// set the resolution
#define DEFAULT_RESOL RESOL_9BIT
void dsInit(void);
int dsStart(void);
int32_t tempBlocking(void);
int32_t dsReadScratchpad(void);
#endif
|
dltech/laminator-nemo | lib/tm1637.c | <gh_stars>0
/*
* printf for TM1637 display-driver based 7-segment displays
* connected to STM32.
*
* Copyright 2021 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tm1637.h"
#include "../libopencm3/include/libopencm3/stm32/rcc.h"
#include "../libopencm3/include/libopencm3/stm32/gpio.h"
#include "../libopencm3/include/libopencm3/stm32/timer.h"
// little init functions as parts of main init function
void tmPortInit(void);
void tmDelayInit(void);
void tmDelayUpdate(void);
// timer based accurate delays
void quaterTact(void);
void halfTact(void);
// data transmission
int pushByte(uint8_t byte);
int tipoI2cBlockingTx1(uint8_t data);
int tipoI2cBlockingTx(uint8_t *data, uint8_t size);
/* display only, no keys reads */
void tmInit()
{
tmPortInit();
tmDelayInit();
uint8_t data[DISPLAY_SIZE] = {};
tmUpd(data);
setBrightness(100);
}
void tmPortInit()
{
RCC_AHBENR |= RCC_AHBENR_GPIOAEN;
GPIOA_MODER |= GPIO_MODE_OUTPUT << (TM_SCL*2) \
| GPIO_MODE_OUTPUT << (TM_SDA*2);
GPIOA_OTYPER |= GPIO_OTYPE_OD << (TM_SCL) \
| GPIO_OTYPE_OD << (TM_SDA);
GPIOA_OSPEEDR |= GPIO_OSPEED_100MHZ << (TM_SCL*2) \
| GPIO_OSPEED_100MHZ << (TM_SDA*2);
GPIOA_PUPDR |= GPIO_PUPD_PULLUP << (TM_SCL*2) \
| GPIO_PUPD_PULLUP << (TM_SDA*2);
GPIOA_BSRR |= (1 << TM_SDA) | (1 << TM_SCL);
}
void tmDelayInit()
{
// timer for tacts
RCC_APB2ENR |= RCC_APB2ENR_TIM16EN;
TIM16_CR1 = (uint32_t) TIM_CR1_CKD_CK_INT;
TIM16_CR1 |= (uint32_t) TIM_CR1_CEN;
tmDelayUpdate();
}
void tmDelayUpdate()
{
TIM16_PSC = (uint32_t) 63;
TIM16_ARR = (uint32_t) 1;
TIM16_EGR |= TIM_EGR_UG;
}
void quaterTact()
{
uint32_t timeout = 1e7;
TIM16_EGR |= TIM_EGR_UG;
TIM16_SR = 0;
while( (TIM16_SR == 0) && (--timeout > 0) );
}
void halfTact()
{
quaterTact();
quaterTact();
}
int pushByte(uint8_t byte)
{
int ret;
for(int i=0 ; i<8 ; ++i)
{
GPIOA_BRR |= 1 << TM_SCL;
quaterTact();
if((byte & (1<<i)) > 0) {
GPIOA_BSRR |= 1 << TM_SDA;
} else {
GPIOA_BRR |= 1 << TM_SDA;
}
quaterTact();
GPIOA_BSRR |= 1 << TM_SCL;
halfTact();
}
// ack tact
GPIOA_BRR |= 1 << TM_SCL;
quaterTact();
GPIOA_BSRR |= 1 << TM_SDA;
quaterTact();
GPIOA_BSRR |= 1 << TM_SCL;
quaterTact();
if((GPIOA_IDR & (1 << TM_SDA)) > 0) {
ret = -1;
} else {
ret = 0;
}
quaterTact();
return ret;
}
// transmit to tm only one byte
int tipoI2cBlockingTx1(uint8_t data)
{
int err = 0;
GPIOA_BSRR |= (1 << TM_SDA) | (1 << TM_SCL);
halfTact();
halfTact();
// start condition
GPIOA_BRR |= 1 << TM_SDA;
halfTact();
// clock data
err = pushByte(data);
// stop bit
GPIOA_BRR |= 1 << TM_SDA;
GPIOA_BRR |= 1 << TM_SCL;
halfTact();
GPIOA_BSRR |= 1 << TM_SCL;
halfTact();
GPIOA_BSRR |= (1 << TM_SDA) | (1 << TM_SCL);
return err;
}
// transmit to tm array of bytes
int tipoI2cBlockingTx(uint8_t *data, uint8_t size)
{
int err = 0;
GPIOA_BSRR |= (1 << TM_SDA) | (1 << TM_SCL);
halfTact();
halfTact();
// start condition
GPIOA_BRR |= 1 << TM_SDA;
halfTact();
// clock data
for(int i=0 ; i<size ; ++i) {
err += pushByte(data[i]);
}
// stop bit
GPIOA_BRR |= 1 << TM_SDA;
GPIOA_BRR |= 1 << TM_SCL;
halfTact();
GPIOA_BSRR |= 1 << TM_SCL;
halfTact();
GPIOA_BSRR |= (1 << TM_SDA) | (1 << TM_SCL);
return err;
}
void tmUpd(uint8_t *data)
{
tmDelayUpdate();
tipoI2cBlockingTx1(WRITE_DATA_CMD_AVT);
uint8_t cnt = 0;
uint8_t tx[DISPLAY_SIZE+1];
tx[cnt++] = SET_0H;
for(int i=0 ; i<DISPLAY_SIZE ; ++i) {
tx[cnt++] = data[i];
}
tipoI2cBlockingTx(tx, cnt);
}
void setBrightness(uint8_t percent)
{
tmDelayUpdate();
uint8_t reg = BRIGHT6P;
if(percent == 0) {
reg = DISP_OFF;
} else if(percent <= 6) {
reg = BRIGHT6P;
} else if(percent <= 13) {
reg = BRIGHT13P;
} else if(percent <= 25) {
reg = BRIGHT25P;
} else if(percent <= 63) {
reg = BRIGHT63P;
} else if(percent <= 69) {
reg = BRIGHT69P;
} else if(percent <= 75) {
reg = BRIGHT75P;
} else if(percent <= 81) {
reg = BRIGHT81P;
} else if(percent <= 100) {
reg = BRIGHT88P;
}
tipoI2cBlockingTx1(reg);
}
|
dltech/laminator-nemo | lib/printf7.h | <filename>lib/printf7.h
#ifndef H_DISPLAY
#define H_DISPLAY
#include <stdint.h>
#include "tm1637.h"
// schematic depended (not necessarily segment A fits byte 0)
#define SEGA (1 << 0)
#define SEGB (1 << 2)
#define SEGC (1 << 4)
#define SEGD (1 << 6)
#define SEGE (1 << 7)
#define SEGF (1 << 1)
#define SEGG (1 << 3)
#define SEGDP (1 << 5)
#define DIGITS DISPLAY_SIZE
void myprintf(char *format, ... );
#endif
|
dltech/laminator-nemo | lib/freq_dr.h | #ifndef H_FREQDR
#define H_FREQDR
#define SIN_RESOL_HP 16
#define DIR_OFFS 5
#define PINL 6
#define PINR 7
#define SYSCLK 48000000
#define PSC 16
#define ARR(out_clk) SYSCLK / PSC / SIN_RESOL_HP / out_clk
#define forward_dir 0
#define reverse_dir 1
void setSpd(uint32_t hz, uint8_t reverse);
void initPwm(void);
#endif
|
dltech/laminator-nemo | lib/ds18b20.c | /*
* stm32 timer based ds18b20 lib
* Copyright 2021 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ds18b20.h"
#include "mystmbackend.h"
#include "../libopencm3/include/libopencm3/stm32/rcc.h"
#include "../libopencm3/include/libopencm3/stm32/gpio.h"
#include "../libopencm3/include/libopencm3/stm32/timer.h"
volatile uint32_t timeoutGl;
volatile uint32_t dl[200];
volatile uint32_t cnt = 0;
volatile uint8_t cst = 0;
volatile uint8_t ccrc = 0;
// init subfunctions
void dsPortConfig(void);
void dsTimerConfig(void);
// timer related functions
void dsTimerUpdate(void);
void dsTimerStart(void);
uint8_t dsTimeout(void);
int dsElapsedTime(void);
void dsDelayUs(uint16_t us);
// GPIO related functions
uint8_t dsReadPin(void);
void dsSetPin(void);
void dsResetPin(void);
// DS18B20 relateg functions
int dsInitSequence(void);
uint8_t dsTxBit(uint8_t bit);
uint8_t dsTxByte(uint8_t byte);
uint8_t dsCrc(uint8_t *data, uint8_t size);
int32_t dsTransTemp(uint8_t templ, uint8_t temph, uint8_t conf);
// commands
int dsReadRomCmd(void);
int dsWriteScratchpad(uint16_t Tpar, uint8_t configByte);
// Hardware related functions (backend).
void dsPortConfig()
{
RCC_AHBENR |= RCC_AHBENR_GPIOAEN;
GPIOA_MODER |= GPIO_MODE_OUTPUT << (DS_PIN*2);
GPIOA_OTYPER |= GPIO_OTYPE_OD << (DS_PIN);
GPIOA_OSPEEDR |= GPIO_OSPEED_100MHZ << (DS_PIN*2);
GPIOA_PUPDR |= GPIO_PUPD_PULLUP << (DS_PIN*2);
GPIOA_BSRR |= 1 << DS_PIN;
}
void dsTimerConfig()
{
// timer for tacts
RCC_APB2ENR |= RCC_APB2ENR_TIM16EN;
TIM16_CR1 = (uint32_t) TIM_CR1_CKD_CK_INT;
TIM16_CR1 |= (uint32_t) TIM_CR1_CEN;
dsTimerUpdate();
}
void dsTimerUpdate()
{
TIM16_PSC = (uint32_t) 47;
TIM16_ARR = (uint32_t) 65535;
TIM16_EGR |= TIM_EGR_UG;
}
void dsTimerStart()
{
timeoutGl = 1e6;
TIM16_EGR |= TIM_EGR_UG;
}
int dsElapsedTime()
{
if(--timeoutGl < 5) {
return 65000;
}
return TIM16_CNT;
}
void dsDelayUs(uint16_t us)
{
TIM16_EGR |= TIM_EGR_UG;
timeoutGl = 1e6;
while((TIM16_CNT < us) && (--timeoutGl > 1));
}
uint8_t dsReadPin()
{
if((GPIOA_IDR & (1 << DS_PIN)) > 0) {
return 1;
}
return 0;
}
void dsSetPin()
{
GPIOA_BSRR |= 1 << DS_PIN;
}
void dsResetPin()
{
GPIOA_BRR |= 1 << DS_PIN;
}
uint8_t dsTxBit(uint8_t bit)
{
uint8_t ret = 0;
dsResetPin();
if(bit == 0) {
dsDelayUs(WRITE0T);
dsSetPin();
dsDelayUs(PULSE_DELAY);
return 0;
}
dsDelayUs(WRITE1T1);
dsSetPin();
dsTimerStart();
dsDelayUs(PULSE_DELAY);
while( (dsElapsedTime() < TIMESLOT) && (dsReadPin() == 0) );
uint16_t time = dsElapsedTime();
dl[cnt++] = time;
if(time > READT) {
ret = 0;
} else {
ret = 1;
}
while(dsElapsedTime() < WRITE1T2);
dl[cnt++] = dsElapsedTime();
if(cnt>200) cnt = 0;
return ret;
}
uint8_t dsTxByte(uint8_t byte)
{
uint8_t ret = 0;
for(int i=0 ; i<8 ; ++i) {
if( dsTxBit(byte & (1<<i)) == 1 ) {
ret |= 1<<i;
}
// I don't know why
dsDelayUs(20);
}
return ret;
}
// DS18B20 related functions based of low-level presented above
void dsInit()
{
dsPortConfig();
dsTimerConfig();
rough_delay_us(100);
dsWriteScratchpad(0x7ff, DEFAULT_RESOL);
dsStart();
}
// returns 0 if device is found
int dsInitSequence()
{
dsResetPin();
dsDelayUs(RESET_PULSE);
dsSetPin();
dsDelayUs(RESET_WAIT);
dsTimerStart();
while((dsReadPin() == 0) && (dsElapsedTime() < INIT_PULSE_MAX));
uint16_t time = dsElapsedTime();
dl[cnt++] = time;
dl[cnt++] = 0;
if(cnt>200) cnt = 0;
if( (time > INIT_PULSE_MAX) || (time < INIT_PULSE_MIN) ) {
++cst;
return -1;
}
while( dsElapsedTime() < RESET_PULSE );
return 0;
}
// This function calculates the cumulative Maxim 1-Wire CRC of the message.
// The result will be 0 if ok. The table was obtained from maximintegrated.com.
uint8_t dsCrc(uint8_t *data, uint8_t size)
{
const uint8_t table[256] =
{0, 94, 188, 226, 97, 63, 221, 131, 194, 156, 126, 32, 163, 253, 31, 65,
157, 195, 33, 127, 252, 162, 64, 30, 95, 1, 227, 189, 62, 96, 130, 220,
35, 125, 159, 193, 66, 28, 254, 160, 225, 191, 93, 3, 128, 222, 60, 98,
190, 224, 2, 92, 223, 129, 99, 61, 124, 34, 192, 158, 29, 67, 161, 255,
70, 24, 250, 164, 39, 121, 155, 197, 132, 218, 56, 102, 229, 187, 89, 7,
219, 133, 103, 57, 186, 228, 6, 88, 25, 71, 165, 251, 120, 38, 196, 154,
101, 59, 217, 135, 4, 90, 184, 230, 167, 249, 27, 69, 198, 152, 122, 36,
248, 166, 68, 26, 153, 199, 37, 123, 58, 100, 134, 216, 91, 5, 231, 185,
140, 210, 48, 110, 237, 179, 81, 15, 78, 16, 242, 172, 47, 113, 147, 205,
17, 79, 173, 243, 112, 46, 204, 146, 211, 141, 111, 49, 178, 236, 14, 80,
175, 241, 19, 77, 206, 144, 114, 44, 109, 51, 209, 143, 12, 82, 176, 238,
50, 108, 142, 208, 83, 13, 239, 177, 240, 174, 76, 18, 145, 207, 45, 115,
202, 148, 118, 40, 171, 245, 23, 73, 8, 86, 180, 234, 105, 55, 213, 139,
87, 9, 235, 181, 54, 104, 138, 212, 149, 203, 41, 119, 244, 170, 72, 22,
233, 183, 85, 11, 136, 214, 52, 106, 43, 117, 151, 201, 74, 20, 246, 168,
116, 42, 200, 150, 21, 75, 169, 247, 182, 232, 10, 84, 215, 137, 107, 53};
uint8_t crc = 0;
for(int i=0 ; i<size ; ++i) {
crc = table[crc ^ data[i]];
}
return crc;
}
int32_t dsTransTemp(uint8_t templ, uint8_t temph, uint8_t conf)
{
uint32_t tempRaw = ((uint32_t)templ + ((uint32_t)temph << 8)) & 0x07ff;
int32_t sign = 1;
if( (temph & 0x80) > 0 ) {
sign = -1;
}
switch(conf)
{
case RESOL_9BIT :
return (int32_t)((tempRaw >> 3) * 500) * sign;
break;
case RESOL_10BIT :
return (int32_t)((tempRaw >> 2) * 250) * sign;
break;
case RESOL_11BIT :
return (int32_t)((tempRaw >> 1) * 125) * sign;
break;
case RESOL_12BIT :
return (int32_t)((tempRaw * 625)/10) * sign;
break;
}
return -1;
}
// commands
int dsReadRomCmd()
{
uint8_t buffer[7];
int ret;
if( dsInitSequence() < 0 ) {
return -1;
}
dsTxByte(READ_ROM);
buffer[0] = dsTxByte(0xff);
if( buffer[0] != FAMILY_CODE ) {
return -1;
}
// ds ROM CODE not needed
for(int i=0 ; i<6 ; ++i) {
buffer[i+1] = dsTxByte(0xff);
}
uint8_t crc = dsTxByte(0xff);
if( crc != dsCrc(buffer,7) ) {
++ccrc;
return -1;
}
return 0;
}
// reads scratchpad, returns temperature only, multiplied by 1000
int32_t dsReadScratchpad()
{
dsTimerUpdate();
if( dsReadRomCmd() < 0 ) {
return -1;
}
dsTxByte(READ_SCRATCHPAD);
uint8_t scratchpad[9];
uint8_t crc;
for(int i=0 ; i<9 ; ++i) {
scratchpad[i] = dsTxByte(0xff);
}
if( scratchpad[8] != dsCrc(scratchpad, 8) ) {
++ccrc;
return -1;
}
return dsTransTemp(scratchpad[0], scratchpad[1], scratchpad[4]);
}
int dsWriteScratchpad(uint16_t Tpar, uint8_t configByte)
{
if( dsReadRomCmd() < 0 ) {
return -1;
}
dsTxByte(WRITE_SCRATCHPAD);
dsTxByte((uint8_t)((Tpar >> 8) & 0x00ff));
dsTxByte((uint8_t)(Tpar & 0x00ff));
dsTxByte(configByte);
if( dsReadRomCmd() < 0 ) {
return -1;
}
dsTxByte(COPY_SCRATCHPAD);
uint32_t timeout = 1e6;
while( (dsTxBit(1) == 0) && (--timeout > 0) );
if(timeout < 2) {
return -1;
}
return 0;
}
int dsStart()
{
dsTimerUpdate();
if( dsReadRomCmd() < 0 ) {
return -1;
}
dsTxByte(CONVERT_T);
return 0;
}
int32_t tempBlocking()
{
dsTimerUpdate();
uint32_t timeout = 1e6;
if( dsStart() < 0 ) {
return -1;
}
while( (dsTxBit(1) == 0) && (--timeout > 0) );
if(timeout > 0) {
return dsReadScratchpad();
}
return -1;
}
|
dltech/laminator-nemo | lib/printf7.c | #include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "printf7.h"
#include "tm1637.h"
//volatile uint8_t dispBuffer[DIGITS] = {0, 0, 0};
uint32_t alphabet(char s);
void myprintf(char *format, ... )
{
char buffer[DIGITS*4];
uint8_t dispBuffer[DIGITS];
va_list args;
va_start (args, format);
vsprintf (buffer, format, args);
va_end (args);
// проверонька
if(strlen(buffer) > DIGITS*2)
return;
// Перевод в кодировку семисегментника, учитывается то условие, что точка
// и символ на одном и том же знакоместе, а не отдельно.
uint8_t outCnt = 0;
for( uint8_t i = 0 ; (i < strlen(buffer)) && (outCnt < DIGITS) ; ++i )
{
if( (buffer[i] != '.') && (buffer[i] != ',') && \
((buffer[i+1] == '.') || (buffer[i+1] == ',')) ) {
dispBuffer[outCnt++] = (alphabet(buffer[i++]) | SEGDP);
} else {
dispBuffer[outCnt++] = (alphabet(buffer[i]));
}
}
tmUpd(dispBuffer);
}
// латинский алфавит и цифры
uint32_t alphabet(char s)
{
switch (s)
{
case '.':
case ',':
return SEGDP;
break;
case '=':
return SEGD + SEGD;
break;
case '-':
return SEGG;
break;
case '_':
return SEGD;
break;
case '"':
return SEGB + SEGF;
break;
case '\'':
return SEGF;
break;
case ']':
return SEGA + SEGB + SEGC + SEGD;
break;
case '2':
return SEGA + SEGB + SEGD + SEGE + SEGG;
break;
case '3':
return SEGA + SEGB + SEGC + SEGD + SEGG;
break;
case '4':
return SEGB + SEGC + SEGG + SEGF;
break;
case '5':
return SEGA + SEGC + SEGD + SEGF + SEGG;
break;
case '6':
return SEGA + SEGC + SEGD + SEGE + SEGF + SEGG;
break;
case '7':
return SEGA + SEGB + SEGC;
break;
case '8':
return SEGA + SEGB + SEGC + SEGD + SEGE + SEGF + SEGG;
break;
case '9':
return SEGA + SEGB + SEGC + SEGD + SEGF + SEGG;
break;
case 'A':
case 'a':
return SEGA + SEGB + SEGC + SEGE + SEGF + SEGG;
break;
case 'B':
case 'b':
return SEGC + SEGD + SEGE + SEGF + SEGG;
break;
case '[' :
case 'C' :
case 'c' :
return SEGA + SEGD + SEGE + SEGF;
break;
case 'D' :
case 'd' :
return SEGB + SEGC + SEGD + SEGE + SEGG;
break;
case 'E' :
case 'e' :
return SEGA + SEGD + SEGE + SEGF + SEGG;
break;
case 'F' :
case 'f' :
return SEGA + SEGE + SEGF + SEGG;
break;
case 'G' :
case 'g' :
return SEGA + SEGC + SEGD + SEGE + SEGF;
break;
case 'H' :
case 'h' :
case 'x' :
case 'X' :
return SEGB + SEGC + SEGE + SEGF + SEGG;
break;
case 'I' :
case 'i' :
case '1' :
return SEGB + SEGC;
break;
case 'J' :
case 'j' :
return SEGB + SEGC + SEGD;
break;
case 'K' :
case 'k' :
return SEGA + SEGC + SEGE + SEGF + SEGG;
break;
case 'L':
case 'l':
return SEGD + SEGE + SEGF;
break;
case 'M':
case 'm':
return SEGA + SEGC + SEGE;
break;
case 'N':
case 'n':
return SEGC + SEGE + SEGG;
break;
case 'O':
case 'o':
case '0':
return SEGA + SEGB + SEGC + SEGD + SEGE + SEGF;
break;
case 'P':
case 'p':
return SEGA + SEGB + SEGE + SEGF + SEGG;
break;
case 'Q':
case 'q':
return SEGA + SEGB + SEGC + SEGF + SEGG;
break;
case 'R':
case 'r':
return SEGE + SEGG;
break;
case 'S':
case 's':
return SEGA + SEGC + SEGD + SEGF;
break;
case 'T':
case 't':
return SEGD + SEGE + SEGF + SEGG;
break;
case 'U':
case 'u':
return SEGB + SEGC + SEGD + SEGE + SEGF;
break;
case 'V':
case 'v':
return SEGC + SEGD + SEGE;
break;
case 'W':
case 'w':
return SEGB + SEGD + SEGF;
break;
case 'Y':
case 'y':
return SEGB + SEGC + SEGD + SEGF + SEGG;
break;
case 'Z':
case 'z':
return SEGA + SEGB + SEGD + SEGE;
break;
default :
return 0;
}
}
|
dltech/laminator-nemo | lib/cmsis_sin.h | <filename>lib/cmsis_sin.h
#ifndef H_SIN
#define H_SIN
#include <inttypes.h>
#define FAST_MATH_TABLE_SIZE 512
#define FAST_MATH_Q31_SHIFT (32 - 10)
#define BASEQ31 2147483648
/* This is ripped out sin function from CMSIS library input and output
are in q31 format */
uint32_t arm_sin_q31(uint32_t x);
#endif
|
dltech/laminator-nemo | lib/mystmbackend.c | <filename>lib/mystmbackend.c<gh_stars>0
#include "mystmbackend.h"
#include "../libopencm3/include/libopencm3/stm32/i2c.h"
#include "../libopencm3/include/libopencm3/stm32/rcc.h"
#include "../libopencm3/include/libopencm3/stm32/gpio.h"
void clkInit()
{
// не знаю зачем, на всякий случай
RCC_CR |= RCC_CR_HSION;
RCC_CFGR2 = RCC_CFGR2_PREDIV_NODIV;
// такирование от встроенных RC генераторов, SYS 48 МГц, AHB 48МГц, APB 48 МГц
uint32_t timeout = TIMEOUT_CLKS;
if ( (RCC_CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL )
{
RCC_CFGR &= ~RCC_CFGR_SW;
while ( ((RCC_CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI) || \
(--timeout > 1) );
}
RCC_CFGR |= RCC_CFGR_PLLSRC_HSI_CLK_DIV2;
RCC_CR &= (uint32_t)(~RCC_CR_PLLON);
timeout = TIMEOUT_CLKS;
while( ((RCC_CR & RCC_CR_PLLRDY) != 0) && (--timeout > 1) );
RCC_CFGR &= ~RCC_CFGR_PLLMUL;
RCC_CFGR |= RCC_CFGR_PLLMUL_MUL12;
RCC_CR |= RCC_CR_PLLON;
timeout = TIMEOUT_CLKS;
while( ((RCC_CR & RCC_CR_PLLRDY) == 0) && (--timeout > 1) );
RCC_CFGR |= (uint32_t) (RCC_CFGR_SW_PLL);
timeout = TIMEOUT_CLKS;
while ( ((RCC_CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL) && (--timeout > 1) );
RCC_CFGR |= (uint32_t) RCC_CFGR_HPRE_NODIV | RCC_CFGR_PPRE_NODIV;
RCC_CSR |= (uint32_t) RCC_CSR_LSION;
timeout = TIMEOUT_CLKS;
while ( ((RCC_CSR & RCC_CSR_LSIRDY) == 0 ) && (--timeout > 0) );
}
void delay_s(uint16_t s)
{
uint16_t cnt = s*20;
while(cnt-- > 0) rough_delay_us(50000);
}
void rough_delay_us(uint16_t us)
{
// podbiral na glazok
volatile uint32_t cnt = (uint32_t)us*(uint32_t)5;
while(cnt-- > 0);
}
void delay_ms(uint16_t ms)
{
while(ms-- > 0) rough_delay_us(1000);
}
void f0I2cInit()
{
// rcc and ports
RCC_CFGR3 &= ~RCC_CFGR3_I2C1SW;
RCC_APB1ENR |= RCC_APB1ENR_I2C1EN;
RCC_AHBENR |= RCC_AHBENR_GPIOAEN;
GPIOA_MODER |= GPIO_MODE_AF << (SCL*2) \
| GPIO_MODE_AF << (SDA*2);
GPIOA_OTYPER |= GPIO_OTYPE_OD << (SCL) \
| GPIO_OTYPE_OD << (SDA);
GPIOA_OSPEEDR |= GPIO_OSPEED_100MHZ << (SCL*2) \
| GPIO_OSPEED_100MHZ << (SDA*2);
GPIOA_PUPDR |= GPIO_PUPD_PULLUP << (SCL*2) \
| GPIO_PUPD_PULLUP << (SDA*2);
GPIOA_AFRH |= GPIO_AF4 << ((SCL-8)*4) \
| GPIO_AF4 << ((SDA-8)*4);
// reset
I2C1_CR1 &= ~I2C_CR1_PE;
// digital filter disabled, analogue enabled
// I2C1_CR1 &= ~(0 << I2C_CR1_DNF_SHIFT);
I2C1_CR1 &= ~I2C_CR1_ANFOFF;
// clocks for 200k transfer
I2C1_TIMINGR = (0x01) << I2C_TIMINGR_PRESC_SHIFT | \
(0x04) << I2C_TIMINGR_SCLDEL_SHIFT | \
(0x02) << I2C_TIMINGR_SDADEL_SHIFT | \
(0xc3) << I2C_TIMINGR_SCLH_SHIFT | \
(0xc7) << I2C_TIMINGR_SCLL_SHIFT;
// I2C1_TIMINGR = (0x01) << I2C_TIMINGR_PRESC_SHIFT | \
// (0x02) << I2C_TIMINGR_SCLDEL_SHIFT | \
// (0x01) << I2C_TIMINGR_SDADEL_SHIFT | \
// (0x08) << I2C_TIMINGR_SCLH_SHIFT | \
// (0x0a) << I2C_TIMINGR_SCLL_SHIFT;
I2C1_CR1 &= ~I2C_CR1_NOSTRETCH;
I2C1_CR1 |= I2C_CR1_PE;
}
volatile uint32_t isr[16] = {0xee, 0xee, 0xee, 0xee, \
0xee, 0xee, 0xee, 0xee, \
0xee, 0xee, 0xee, 0xee, \
0xee, 0xee, 0xee, 0xee};
volatile uint32_t tout[16] = {0xee, 0xee, 0xee, 0xee, \
0xee, 0xee, 0xee, 0xee, \
0xee, 0xee, 0xee, 0xee, \
0xee, 0xee, 0xee, 0xee};
volatile uint32_t cr2;
void f0I2cSend(uint8_t addr, uint8_t *data, uint8_t nBytes)
{
I2C1_CR1 &= ~I2C_CR1_PE; // reset na vsyakiy sluchay
rough_delay_us(10);
I2C1_CR1 |= I2C_CR1_PE;
// empty 7-bit address
I2C1_CR2 &= ~I2C_CR2_ADD10;
I2C1_CR2 |= (addr << I2C_CR2_SADD_7BIT_SHIFT) & I2C_CR2_SADD_7BIT_MASK;
// tak nado
I2C1_CR2 |= I2C_CR2_AUTOEND;
// I2C1_CR2 |= I2C_CR2_STOP;
I2C1_CR2 &= ~I2C_CR2_RD_WRN; // write
I2C1_CR2 |= (0x06 << I2C_CR2_NBYTES_SHIFT) & I2C_CR2_NBYTES_MASK;
isr[nBytes+1] = I2C1_ISR;
isr[15] = nBytes;
I2C1_CR2 |= I2C_CR2_START;
cr2 = I2C1_CR2;
uint32_t timeout = 1e6;
for(int i=0 ; i<nBytes ; ++i) {
timeout = 1e6;
while( ((I2C1_ISR & (I2C_ISR_NACKF + I2C_ISR_TXIS)) == 0) && (--timeout > 0) );
isr[i] = I2C1_ISR;
tout[i] = timeout;
if((I2C1_ISR & I2C_ISR_NACKF) > 0) {
return;
}
I2C1_TXDR = data[i];
}
timeout = 1e6;
while( ((I2C1_ISR & (I2C_ISR_NACKF + I2C_ISR_TXIS)) == 0) && (--timeout > 0) );
isr[15] = I2C1_ISR;
tout[15] = timeout;
}
/*
uint8_t f0I2cTransferGet()
{
}
void f0I2cDmaInit()
{
}
*/
|
dltech/laminator-nemo | lib/mystmbackend.h | <filename>lib/mystmbackend.h
#ifndef H_MYSTM
#define H_MYSTM
#include "inttypes.h"
#define SCL 9
#define SDA 10
#define I2C_ADD_NE_ADD 0x00
#define TIMEOUT_CLKS 10000
void clkInit(void);
void rough_delay_us(uint16_t us);
void delay_ms(uint16_t ms);
void delay_s(uint16_t s);
void f0I2cInit(void);
void f0I2cSend(uint8_t addr, uint8_t *data, uint8_t nBytes);
#endif
|
dltech/laminator-nemo | lib/buttons.c | #include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "../libopencm3/include/libopencm3/stm32/rcc.h"
#include "../libopencm3/include/libopencm3/stm32/exti.h"
#include "../libopencm3/include/libopencm3/stm32/gpio.h"
#include "../libopencm3/include/libopencm3/stm32/timer.h"
#include "../libopencm3/include/libopencm3/cm3/nvic.h"
#include "buttons.h"
#include "menu.h"
extern volatile menuSettings menuSet;
volatile uint32_t buttons = 0xffffffff;
void buttonsInit()
{
// прерывания на кнопках
// инициализация портов (подтяжка к +3.3, вход)
RCC_AHBENR |= RCC_AHBENR_GPIOAEN;
gpio_mode_setup(BUTTON_PORT, GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, SET_PIN | CHOOSE_PIN);
gpio_set_output_options(BUTTON_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_100MHZ, SET_PIN | CHOOSE_PIN);
// конфиг прерываний по нажатию на кнопки
exti_select_source(EXTI9, GPIOA);
exti_select_source(EXTI10, GPIOA);
exti_set_trigger(EXTI9 | EXTI10, EXTI_TRIGGER_FALLING);
exti_enable_request(EXTI9 | EXTI10);
EXTI_PR = 0xffffffff;
nvic_enable_irq(NVIC_EXTI4_15_IRQ);
nvic_set_priority(NVIC_EXTI4_15_IRQ, 0x40);
EXTI_PR = 0xffffffff;
// таймер антидребезга
RCC_APB2ENR |= RCC_APB2ENR_TIM17EN;
TIM17_CR1 = (uint32_t) TIM_CR1_CKD_CK_INT | TIM_CR1_ARPE | TIM_CR1_OPM;
TIM17_PSC = (uint32_t) 65535;
TIM17_ARR = (uint32_t) 5;
TIM17_DIER = (uint32_t) TIM_DIER_UIE;
TIM17_EGR |= (uint32_t) TIM_EGR_UG;
TIM17_SR = 0;
nvic_enable_irq(NVIC_TIM17_IRQ);
nvic_set_priority(NVIC_TIM17_IRQ, 0x40);
}
void startButtonsCheck()
{
// when the button is pressed, off the interrupt of button
exti_disable_request(EXTI9 | EXTI10);
EXTI_PR = 0xffffffff;
menuSet.setButFlag = 0;
menuSet.cvButFlag = 0;
// check buttons
buttons = BUTTON_READ;
// and start three another checks throw the delays
TIM17_SR = 0;
TIM17_CR1 |= (uint32_t) TIM_CR1_CEN;
}
void checkButtonResetTimer()
{
static uint8_t counter = 0;
if( counter > 254 ) counter = 0;
const uint8_t minimal = 3;
TIM17_SR = 0;
uint32_t prevButtons = buttons;
buttons |= (uint32_t)BUTTON_READ;
if( ((~buttons) & (CHOOSE_PIN | SET_PIN)) > 0 ) {
++counter;
TIM17_CR1 |= (uint32_t) TIM_CR1_CEN;
return;
}
if( (counter > minimal) && ((prevButtons & SET_PIN) == 0) ) {
menuSet.setButFlag = 1;
} else if( (counter > minimal) && ((prevButtons & CHOOSE_PIN) == 0) ) {
menuSet.cvButFlag = 1;
}
counter = 0;
EXTI_PR = 0xffffffff;
exti_enable_request(EXTI9 | EXTI10);
}
|
dltech/laminator-nemo | lib/freq_dr.c | #include "../libopencm3/include/libopencm3/stm32/rcc.h"
#include "../libopencm3/include/libopencm3/stm32/gpio.h"
#include "../libopencm3/include/libopencm3/stm32/timer.h"
#include "../libopencm3/include/libopencm3/stm32/dma.h"
#include "freq_dr.h"
#include "cmsis_sin.h"
volatile uint32_t positive[SIN_RESOL_HP*2];
volatile uint32_t negative[SIN_RESOL_HP*2];
void sinGenerator(uint32_t arr, uint8_t isOffs, uint8_t isFirst, volatile uint32_t *sinus);
volatile uint32_t otl1;
volatile uint32_t otl2;
volatile uint32_t otl3;
volatile uint32_t otl4;
// just suppose pin6 for forward direction, PINL, and rely on 3 timer
// pin7 is for reverse direction, PINR, timer 1 ch 1N
void initPwm(void)
{
RCC_AHBENR |= RCC_AHBENR_GPIOAEN;
GPIOA_MODER |= GPIO_MODE_AF << (PINL*2) \
| GPIO_MODE_AF << (PINR*2);
GPIOA_OTYPER |= GPIO_OTYPE_PP << (PINL) \
| GPIO_OTYPE_PP << (PINR);
GPIOA_OSPEEDR|= GPIO_OSPEED_100MHZ << (PINL*2) \
| GPIO_OSPEED_100MHZ << (PINR*2);
GPIOA_PUPDR |= GPIO_PUPD_NONE << (PINL*2) \
| GPIO_PUPD_NONE << (PINR*2);
GPIOA_AFRL |= GPIO_AF1 << (PINL*4) \
| GPIO_AF2 << (PINR*4);
// timer configure for outputs
RCC_APB1ENR |= RCC_APB1ENR_TIM3EN;
RCC_APB2ENR |= RCC_APB2ENR_TIM1EN;
TIM1_CR1 = (uint32_t) TIM_CR1_CKD_CK_INT;
TIM1_PSC = (uint32_t) PSC;
TIM3_CR1 = (uint32_t) TIM_CR1_CKD_CK_INT;
TIM3_PSC = (uint32_t) PSC;
setSpd(30, forward_dir);
TIM1_CCMR1 = (uint32_t) TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_CC1S_OUT;
TIM1_CCER = (uint32_t) TIM_CCER_CC1E;
TIM1_CCR1 = (uint32_t) 0;
TIM3_CCMR1 = (uint32_t) TIM_CCMR1_OC1M_PWM2 | TIM_CCMR1_CC1S_OUT;
TIM3_CCER = (uint32_t) TIM_CCER_CC1E;
TIM3_CCR1 = (uint32_t) 0;
// timer master slave configure
TIM1_CR2 = (uint32_t) TIM_CR2_MMS_UPDATE;
TIM3_SMCR = (uint32_t) TIM_SMCR_TS_ITR0 | TIM_SMCR_SMS_RM;
// dma configure for sinus output
// on dma timer clock
TIM1_DIER = (uint32_t) TIM_DIER_UDE | TIM_DIER_CC1DE;
TIM3_DIER = (uint32_t) TIM_DIER_UDE | TIM_DIER_CC1DE;
// forward dma
RCC_AHBENR |= RCC_AHBENR_DMA1EN;
DMA1_CPAR2 = (uint32_t) &TIM1_CCR1;
DMA1_CMAR2 = (uint32_t) positive;
DMA1_CNDTR2 = (uint32_t) SIN_RESOL_HP*2;
uint32_t ccr= DMA_CCR_MINC | DMA_CCR_MSIZE_32BIT | DMA_CCR_PSIZE_32BIT;
ccr |= DMA_CCR_PL_LOW | DMA_CCR_DIR | DMA_CCR_CIRC;
ccr |= DMA_CCR_TEIE;
DMA1_CCR2 = ccr;
// reverse dma
DMA1_CPAR4 = (uint32_t) &TIM3_CCR1;
DMA1_CMAR4 = (uint32_t) negative;
DMA1_CNDTR4 = (uint32_t) SIN_RESOL_HP*2;
ccr = DMA_CCR_MINC | DMA_CCR_MSIZE_32BIT | DMA_CCR_PSIZE_32BIT;
ccr |= DMA_CCR_PL_LOW | DMA_CCR_DIR | DMA_CCR_CIRC;
ccr |= DMA_CCR_TEIE;
DMA1_CCR4 = ccr;
// start
TIM1_CR1 |= (uint32_t) TIM_CR1_CEN;
TIM3_CR1 |= (uint32_t) TIM_CR1_CEN;
DMA1_CCR2 |= DMA_CCR_EN;
DMA1_CCR4 |= DMA_CCR_EN;
// two timers are connected as master slave
TIM1_EGR |= TIM_EGR_UG;
}
void setSpd(uint32_t hz, uint8_t dir)
{
const uint32_t arrr = ARR(hz);
if(dir == forward_dir) {
sinGenerator(arrr/2, 1, 1, positive);
sinGenerator(arrr/2, 0, 0, negative);
} else {
sinGenerator(arrr/2, 0, 1, positive);
sinGenerator(arrr/2, 1, 0, negative);
}
TIM1_ARR = arrr;
TIM3_ARR = arrr;
otl1 = arrr;
}
void sinGenerator(uint32_t arr, uint8_t isOffs, uint8_t isFirst, volatile uint32_t *sinus)
{
uint64_t iterQ31;
uint64_t sinQ31;
for(int i=0 ; i<SIN_RESOL_HP*2 ; ++i) {
sinus[i] = 0;
}
if(isFirst) {
for(int i=2 ; i<SIN_RESOL_HP-2 ; ++i) {
iterQ31 = ((uint64_t)i*BASEQ31)/(SIN_RESOL_HP-1)/2;
sinQ31 = (uint64_t)arm_sin_q31((uint32_t)iterQ31);
sinus[i] = (uint32_t)(sinQ31 * (uint64_t)arr / BASEQ31);
sinus[i] += DIR_OFFS * isOffs;
}
} else {
for(int i=SIN_RESOL_HP+2 ; i<SIN_RESOL_HP*2-2 ; ++i) {
iterQ31 = ((uint64_t)(i-SIN_RESOL_HP)*BASEQ31)/(SIN_RESOL_HP-1)/2;
sinQ31 = (uint64_t)arm_sin_q31((uint32_t)iterQ31);
sinus[i] = (uint32_t)(sinQ31 * arr / BASEQ31);
sinus[i] += DIR_OFFS * isOffs;
}
}
}
|
dltech/laminator-nemo | lib/buttons.h | <reponame>dltech/laminator-nemo<gh_stars>0
#ifndef H_BUTTONS
#define H_BUTTONS
#define BUTTON_PORT GPIOA
#define BUTTON_READ GPIOA_IDR
#define SET_PIN GPIO9
#define CHOOSE_PIN GPIO10
void buttonsInit(void);
void checkButtonResetTimer(void);
void startButtonsCheck(void);
#endif
|
gigimushroom/DatabaseBackendEngine | src/include/logging/log_recovery.h | <reponame>gigimushroom/DatabaseBackendEngine<filename>src/include/logging/log_recovery.h
/**
* recovery_manager.h
* Read log file from disk, redo and undo
*/
#pragma once
#include <algorithm>
#include <mutex>
#include <unordered_map>
#include "buffer/buffer_pool_manager.h"
#include "concurrency/lock_manager.h"
#include "logging/log_record.h"
namespace cmudb {
class LogRecovery {
public:
LogRecovery(DiskManager *disk_manager,
BufferPoolManager *buffer_pool_manager)
: disk_manager_(disk_manager), buffer_pool_manager_(buffer_pool_manager),
offset_(0) {
// global transaction through recovery phase
log_buffer_ = new char[LOG_BUFFER_SIZE];
}
~LogRecovery() {
delete[] log_buffer_;
log_buffer_ = nullptr;
}
void Redo();
void Undo();
bool DeserializeLogRecord(const char *data, LogRecord &log_record);
private:
// TODO: you can add whatever member variable here
// Don't forget to initialize newly added variable in constructor
DiskManager *disk_manager_;
BufferPoolManager *buffer_pool_manager_;
// maintain active transactions and its corresponds latest lsn
std::unordered_map<txn_id_t, lsn_t> active_txn_;
// mapping log sequence number to log file offset, for undo purpose
std::unordered_map<lsn_t, int> lsn_mapping_;
// log buffer related
int offset_;
char *log_buffer_;
void UndoInternal(LogRecord &log_record);
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/table/table_heap.h | /**
* table_heap.h
*
* doubly-linked list of heap pages
*/
#pragma once
#include "buffer/buffer_pool_manager.h"
#include "logging/log_manager.h"
#include "page/table_page.h"
#include "table/table_iterator.h"
#include "table/tuple.h"
namespace cmudb {
class TableHeap {
friend class TableIterator;
public:
~TableHeap() {}
// open a table heap
TableHeap(BufferPoolManager *buffer_pool_manager, LockManager *lock_manager,
LogManager *log_manager, page_id_t first_page_id);
// create table heap
TableHeap(BufferPoolManager *buffer_pool_manager, LockManager *lock_manager,
LogManager *log_manager, Transaction *txn);
// for insert, if tuple is too large (>~page_size), return false
bool InsertTuple(const Tuple &tuple, RID &rid, Transaction *txn);
bool MarkDelete(const RID &rid, Transaction *txn); // for delete
// if the new tuple is too large to fit in the old page, return false (will
// delete and insert)
bool UpdateTuple(const Tuple &tuple, const RID &rid, Transaction *txn);
// commit/abort time
void ApplyDelete(const RID &rid,
Transaction *txn); // when commit delete or rollback insert
void RollbackDelete(const RID &rid, Transaction *txn); // when rollback delete
bool GetTuple(const RID &rid, Tuple &tuple, Transaction *txn);
bool DeleteTableHeap();
TableIterator begin(Transaction *txn);
TableIterator end();
inline page_id_t GetFirstPageId() const { return first_page_id_; }
private:
/**
* Members
*/
BufferPoolManager *buffer_pool_manager_;
LockManager *lock_manager_;
LogManager *log_manager_;
page_id_t first_page_id_;
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/page/table_page.h | <gh_stars>10-100
/**
* table_page.h
*
* Slotted page format:
* ---------------------------------------
* | HEADER | ... FREE SPACES ... | TUPLES |
* ---------------------------------------
* ^
* free space pointer
*
* Header format (size in byte):
* --------------------------------------------------------------------------
* | PageId (4)| LSN (4)| PrevPageId (4)| NextPageId (4)| FreeSpacePointer(4) |
* --------------------------------------------------------------------------
* --------------------------------------------------------------
* | TupleCount (4) | Tuple_1 offset (4) | Tuple_1 size (4) | ... |
* --------------------------------------------------------------
*
*/
#pragma once
#include <cstring>
#include "common/rid.h"
#include "concurrency/lock_manager.h"
#include "logging/log_manager.h"
#include "page/page.h"
#include "table/tuple.h"
namespace cmudb {
class TablePage : public Page {
public:
/**
* Header related
*/
void Init(page_id_t page_id, size_t page_size, page_id_t prev_page_id,
LogManager *log_manager, Transaction *txn);
page_id_t GetPageId();
page_id_t GetPrevPageId();
page_id_t GetNextPageId();
void SetPrevPageId(page_id_t prev_page_id);
void SetNextPageId(page_id_t next_page_id);
/**
* Tuple related
*/
bool InsertTuple(const Tuple &tuple, RID &rid, Transaction *txn,
LockManager *lock_manager,
LogManager *log_manager); // return rid if success
bool MarkDelete(const RID &rid, Transaction *txn, LockManager *lock_manager,
LogManager *log_manager); // delete
bool UpdateTuple(const Tuple &new_tuple, Tuple &old_tuple, const RID &rid,
Transaction *txn, LockManager *lock_manager,
LogManager *log_manager);
// commit/abort time
void ApplyDelete(const RID &rid, Transaction *txn,
LogManager *log_manager); // when commit success
void RollbackDelete(const RID &rid, Transaction *txn,
LogManager *log_manager); // when commit abort
// return tuple (with data pointing to heap) if success
bool GetTuple(const RID &rid, Tuple &tuple, Transaction *txn,
LockManager *lock_manager);
/**
* Tuple iterator
*/
bool GetFirstTupleRid(RID &first_rid);
bool GetNextTupleRid(const RID &cur_rid, RID &next_rid);
private:
/**
* helper functions
*/
int32_t GetTupleOffset(int slot_num);
int32_t GetTupleSize(int slot_num);
void SetTupleOffset(int slot_num, int32_t offset);
void SetTupleSize(int slot_num, int32_t offset);
int32_t GetFreeSpacePointer(); // offset of the beginning of free space
void SetFreeSpacePointer(int32_t free_space_pointer);
int32_t GetTupleCount(); // Note that this tuple count may be larger than # of
// actual tuples because some slots may be empty
void SetTupleCount(int32_t tuple_count);
int32_t GetFreeSpaceSize();
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/page/b_plus_tree_page.h | <filename>src/include/page/b_plus_tree_page.h<gh_stars>10-100
/**
* b_plus_tree_page.h
*
* Both internal and leaf page are inherited from this page.
*
* It actually serves as a header part for each B+ tree page and
* contains information shared by both leaf page and internal page.
*
* Header format (size in byte, 20 bytes in total):
* ----------------------------------------------------------------------------
* | PageType (4) | LSN (4) | CurrentSize (4) | MaxSize (4) |
* ----------------------------------------------------------------------------
* | ParentPageId (4) | PageId(4) |
* ----------------------------------------------------------------------------
*/
#pragma once
#include <cassert>
#include <climits>
#include <cstdlib>
#include <string>
#include "buffer/buffer_pool_manager.h"
#include "index/generic_key.h"
namespace cmudb {
#define MappingType std::pair<KeyType, ValueType>
#define INDEX_TEMPLATE_ARGUMENTS \
template <typename KeyType, typename ValueType, typename KeyComparator>
// define page type enum
enum class IndexPageType { INVALID_INDEX_PAGE = 0, LEAF_PAGE, INTERNAL_PAGE };
// Abstract class.
class BPlusTreePage {
public:
bool IsLeafPage() const;
bool IsRootPage() const;
void SetPageType(IndexPageType page_type);
int GetSize() const;
void SetSize(int size);
void IncreaseSize(int amount);
int GetMaxSize() const;
void SetMaxSize(int max_size);
int GetMinSize() const;
page_id_t GetParentPageId() const;
void SetParentPageId(page_id_t parent_page_id);
page_id_t GetPageId() const;
void SetPageId(page_id_t page_id);
void SetLSN(lsn_t lsn = INVALID_LSN);
std::string ToString(bool verbose = false) const { return "empty"; }
bool IsSafe(int type) {
if (type == 1) { // insert
return (GetSize() < GetMaxSize());
} else if (type == 2) { // delete
return (GetSize() >= GetMinSize());
}
return false;
}
private:
// member variable, attributes that both internal and leaf page share
IndexPageType page_type_;
lsn_t lsn_;
int size_;
int max_size_;
page_id_t parent_page_id_;
page_id_t page_id_;
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/disk/disk_manager.h | <reponame>gigimushroom/DatabaseBackendEngine<gh_stars>10-100
/**
* disk_manager.h
*
* Disk manager takes care of the allocation and deallocation of pages within a
* database. It also performs read and write of pages to and from disk, and
* provides a logical file layer within the context of a database management
* system.
*/
#pragma once
#include <atomic>
#include <fstream>
#include <future>
#include <string>
#include "common/config.h"
namespace cmudb {
class DiskManager {
public:
DiskManager(const std::string &db_file);
~DiskManager();
void WritePage(page_id_t page_id, const char *page_data);
void ReadPage(page_id_t page_id, char *page_data);
void WriteLog(char *log_data, int size);
bool ReadLog(char *log_data, int size, int offset);
page_id_t AllocatePage();
void DeallocatePage(page_id_t page_id);
int GetNumFlushes() const;
bool GetFlushState() const;
inline void SetFlushLogFuture(std::future<void> *f) { flush_log_f_ = f; }
inline bool HasFlushLogFuture() { return flush_log_f_ != nullptr; }
private:
int GetFileSize(const std::string &name);
// stream to write log file
std::fstream log_io_;
std::string log_name_;
// stream to write db file
std::fstream db_io_;
std::string file_name_;
std::atomic<page_id_t> next_page_id_;
int num_flushes_;
bool flush_log_;
std::future<void> *flush_log_f_;
};
} // namespace cmudb |
gigimushroom/DatabaseBackendEngine | src/include/common/rwmutex.h | <filename>src/include/common/rwmutex.h
/**
* rwmutex.h
*
* Reader-Writer lock
*/
#pragma once
#include <climits>
#include <condition_variable>
#include <mutex>
namespace cmudb {
class RWMutex {
typedef std::mutex mutex_t;
typedef std::condition_variable cond_t;
static const uint32_t max_readers_ = UINT_MAX;
public:
RWMutex() : reader_count_(0), writer_entered_(false) {}
~RWMutex() { std::lock_guard<mutex_t> guard(mutex_); }
RWMutex(const RWMutex &) = delete;
RWMutex &operator=(const RWMutex &) = delete;
void WLock() {
std::unique_lock<mutex_t> lock(mutex_);
while (writer_entered_)
reader_.wait(lock);
writer_entered_ = true;
while (reader_count_ > 0)
writer_.wait(lock);
}
void WUnlock() {
std::lock_guard<mutex_t> guard(mutex_);
writer_entered_ = false;
reader_.notify_all();
}
void RLock() {
std::unique_lock<mutex_t> lock(mutex_);
while (writer_entered_ || reader_count_ == max_readers_)
reader_.wait(lock);
reader_count_++;
}
void RUnlock() {
std::lock_guard<mutex_t> guard(mutex_);
reader_count_--;
if (writer_entered_) {
if (reader_count_ == 0)
writer_.notify_one();
} else {
if (reader_count_ == max_readers_ - 1) // I don't understand
reader_.notify_one();
}
}
private:
mutex_t mutex_;
cond_t writer_;
cond_t reader_;
uint32_t reader_count_;
bool writer_entered_;
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/hash/extendible_hash.h | <reponame>gigimushroom/DatabaseBackendEngine<filename>src/include/hash/extendible_hash.h
/*
* extendible_hash.h : implementation of in-memory hash table using extendible
* hashing
*
* Functionality: The buffer pool manager must maintain a page table to be able
* to quickly map a PageId to its corresponding memory location; or alternately
* report that the PageId does not match any currently-buffered page.
*/
#pragma once
#include <cstdlib>
#include <vector>
#include <string>
#include <map>
// Below fix the error: ‘shared_ptr’ is not a member of ‘std’
#include <memory>
#include <mutex>
#include "hash/hash_table.h"
#include <math.h> /* pow */
namespace cmudb {
template <typename K, typename V>
class ExtendibleHash : public HashTable<K, V> {
public:
// constructor
ExtendibleHash(size_t size);
// helper function to generate hash addressing
size_t HashKey(const K &key);
// helper function to get global & local depth
int GetGlobalDepth() const;
int GetLocalDepth(int bucket_id) const;
int GetNumBuckets() const;
// lookup and modifier
bool Find(const K &key, V &value) override;
bool Remove(const K &key) override;
void Insert(const K &key, const V &value) override;
struct Bucket {
Bucket() = default;
Bucket(int depth, int id)
: mLocalDepth(depth), mId(id)
{}
int mLocalDepth = 0;
int mId = 0;
// std::array must be a compile-time constant. We use vector instead
std::map<K,V> dataMap;
};
private:
// add your own member variables here
size_t GetBucketIndexFromHash(size_t hash);
void Split(size_t index, const K &key, const V &value);
size_t GetDirCapacity() const { return pow(2, mDepth); }
// total num of bits needed to express the total num of buckets
int mDepth; // gloabl depth
int mBucketCount;
size_t mBucketDataSize;
std::vector<std::shared_ptr<Bucket>> mDirectory;
mutable std::mutex mutex_;
void dump(const K &key);
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/type/numeric_type.h | <gh_stars>10-100
/**
* numeric_type.h
*/
#pragma once
#include <cmath>
#include "type/value.h"
namespace cmudb {
// A numeric value is an abstract type representing a number. Numerics can be
// either integral or non-integral (decimal), but must provide arithmetic
// operations on its value.
class NumericType : public Type {
public:
NumericType(TypeId type) : Type(type) {}
~NumericType() {}
// Other mathematical functions
virtual Value Add(const Value &left, const Value &right) const = 0;
virtual Value Subtract(const Value &left, const Value &right) const = 0;
virtual Value Multiply(const Value &left, const Value &right) const = 0;
virtual Value Divide(const Value &left, const Value &right) const = 0;
virtual Value Modulo(const Value &left, const Value &right) const = 0;
virtual Value Min(const Value &left, const Value &right) const = 0;
virtual Value Max(const Value &left, const Value &right) const = 0;
virtual Value Sqrt(const Value &val) const = 0;
virtual Value OperateNull(const Value &left, const Value &right) const = 0;
virtual bool IsZero(const Value &val) const = 0;
protected:
static inline double ValMod(double x, double y) {
return x - std::trunc((double)x / (double)y) * y;
}
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/index/index_iterator.h | <filename>src/include/index/index_iterator.h<gh_stars>10-100
/**
* index_iterator.h
* For range scan of b+ tree
*/
#pragma once
#include "page/b_plus_tree_leaf_page.h"
#include "buffer/buffer_pool_manager.h"
//#include "common/logger.h"
namespace cmudb {
#define INDEXITERATOR_TYPE \
IndexIterator<KeyType, ValueType, KeyComparator>
INDEX_TEMPLATE_ARGUMENTS
class IndexIterator {
public:
// you may define your own constructor based on your member variables
IndexIterator(BPlusTreeLeafPage<KeyType, ValueType, KeyComparator> *,
int, BufferPoolManager *);
IndexIterator() {}
~IndexIterator();
bool isEnd() {
// if we go BEYOND our leaf node, and our leaf node does not have next,
// we are at the end
if (leaf_->GetNextPageId() == INVALID_PAGE_ID && index_ >= leaf_->GetSize()) {
return true;
}
return false;
}
const MappingType &operator*() {
return leaf_->GetItem(index_);
}
IndexIterator &operator++() {
index_++;
// check if we need to switch to right sibling leaf node
if (index_ >= leaf_->GetSize()) {
page_id_t next = leaf_->GetNextPageId();
if (next == INVALID_PAGE_ID) {
//LOG_INFO("No more sibling in indexItr");
} else {
index_ = 0;
buff_pool_manager_->UnpinPage(leaf_->GetPageId(), false);
leaf_ =
reinterpret_cast<B_PLUS_TREE_LEAF_PAGE_TYPE *> (buff_pool_manager_->FetchPage(next)->GetData());
}
}
return *this;
}
private:
// add your own private member variables here
BPlusTreeLeafPage<KeyType, ValueType, KeyComparator> *leaf_;
int index_;
BufferPoolManager *buff_pool_manager_;
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/concurrency/lock_manager.h | /**
* lock_manager.h
*
* Tuple level lock manager, use wait-die to prevent deadlocks
*/
#pragma once
#include <condition_variable>
#include <list>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include "common/rid.h"
#include "concurrency/transaction.h"
namespace cmudb {
class LockManager {
public:
enum LockState {SHARED, EXCLUSIVE};
struct LockRequest {
LockRequest() {}
LockRequest(LockState state, txn_id_t id) {
lock_state_ = state;
granted_ids.insert(id);
oldest_id_ = id;
}
LockState lock_state_ = SHARED;
std::unordered_set<txn_id_t> granted_ids;
int oldest_id_ = -1;
struct WaitingItem {
LockState lock_state_;
int txid = -1;
};
std::list<WaitingItem> waiting_list_;
};
LockManager(bool strict_2PL) : strict_2PL_(strict_2PL){};
/*** below are APIs need to implement ***/
// lock:
// return false if transaction is aborted
// it should be blocked on waiting and should return true when granted
// note the behavior of trying to lock locked rids by same txn is undefined
// it is transaction's job to keep track of its current locks
bool LockShared(Transaction *txn, const RID &rid);
bool LockExclusive(Transaction *txn, const RID &rid);
bool LockUpgrade(Transaction *txn, const RID &rid);
// unlock:
// release the lock hold by the txn
bool Unlock(Transaction *txn, const RID &rid);
/*** END OF APIs ***/
private:
bool strict_2PL_;
std::mutex mutex_;
std::condition_variable cv;
std::unordered_map<RID, LockRequest> reqByRIDsMap_;
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | src/include/concurrency/transaction_manager.h | <filename>src/include/concurrency/transaction_manager.h
/**
* transaction_manager.h
*
*/
#pragma once
#include <atomic>
#include <unordered_set>
#include "common/config.h"
#include "concurrency/lock_manager.h"
#include "logging/log_manager.h"
namespace cmudb {
class TransactionManager {
public:
TransactionManager(LockManager *lock_manager,
LogManager *log_manager = nullptr)
: next_txn_id_(0), lock_manager_(lock_manager),
log_manager_(log_manager) {}
Transaction *Begin();
void Commit(Transaction *txn);
void Abort(Transaction *txn);
private:
std::atomic<txn_id_t> next_txn_id_;
LockManager *lock_manager_;
LogManager *log_manager_;
};
} // namespace cmudb
|
gigimushroom/DatabaseBackendEngine | test/include/logging/common.h | /**
* common.h
*/
#pragma once
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include "table/tuple.h"
namespace cmudb {
// use a fixed schema to construct a random tuple
Tuple ConstructTuple(Schema *schema) {
std::vector<Value> values;
Value v(TypeId::INVALID);
struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);
for (int i = 0; i < schema->GetColumnCount(); i++) {
// get type
TypeId type = schema->GetType(i);
switch (type) {
case TypeId::BOOLEAN:
v = Value(type, rand() % 2);
break;
case TypeId::TINYINT:
v = Value(type, (int8_t)rand() % 1000);
break;
case TypeId::SMALLINT:
case TypeId::INTEGER:
v = Value(type, (int32_t)rand() % 1000);
break;
case TypeId::BIGINT:
v = Value(type, (int64_t)rand() % 100000);
break;
case TypeId::VARCHAR: {
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int len = 1 + rand() % 9;
char s[10];
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
v = Value(type, s, len + 1, true);
break;
}
default:
break;
}
values.emplace_back(v);
}
return Tuple(values, schema);
}
} // namespace cmudb
|
sksdlin/GroupChatClientDesktop | src/global.h | <gh_stars>0
#include <QString>
#include <QTcpSocket>
#include <QByteArray>
#include <QWebSocket>
#ifndef GLOBAL_H
#define GLOBAL_H
extern QString USERNAME;
extern QWebSocket *SOCKET;
extern QString DATA;
#endif // GLOBAL_H
|
sksdlin/GroupChatClientDesktop | src/adminchat.h | #ifndef ADMINCHAT_H
#define ADMINCHAT_H
#include <QMainWindow>
#include "global.h"
namespace Ui {
class AdminChat;
}
class AdminChat : public QMainWindow
{
Q_OBJECT
public:
explicit AdminChat(QWidget *parent = 0);
void loadAllBlocked();
void loadAllUnBlocked();
QVector<QString> comaEndedStr(QString baStr);
~AdminChat();
private slots:
void on_pbBlock_clicked();
void on_pbUnblock_clicked();
void loadMessage(QString mFromServ);
void on_pbLoadUnblockedUsers_clicked();
void on_pbLoadBlockUsers_clicked();
private:
Ui::AdminChat *ui;
};
#endif // ADMINCHAT_H
|
sksdlin/GroupChatClientDesktop | src/regex.h | #ifndef REGEX_H
#define REGEX_H
#include<QRegExp>
class RegEx
{
//QRegExp regX;
public:
RegEx();
bool regEmail (QString );
bool regUserName (QString );
bool regDob (QString );
bool regName (QString );
};
#endif // REGEX_H
|
sksdlin/GroupChatClientDesktop | src/forgotpassword.h | #ifndef FORGOTPASSWORD_H
#define FORGOTPASSWORD_H
#include <QDialog>
namespace Ui {
class ForgotPassword;
}
class ForgotPassword : public QDialog
{
Q_OBJECT
public:
explicit ForgotPassword(QWidget *parent = 0);
QVector<QString> commaEndedStr(QString Str);
QString hashSha1(QString hashIt);
~ForgotPassword();
private slots:
void on_pbGetQuestion_clicked();
void ReplyFromServer(QString messageFromServer);
void on_pbChangePass_clicked();
private:
Ui::ForgotPassword *ui;
};
#endif // FORGOTPASSWORD_H
|
sksdlin/GroupChatClientDesktop | src/regwindow.h | #ifndef REGWINDOW_H
#define REGWINDOW_H
#include <QWidget>
#include <QMainWindow>
#include "regex.h"
#include "global.h"
#include <QCryptographicHash>
namespace Ui {
class RegWindow;
}
class RegWindow : public QMainWindow
{
Q_OBJECT
public:
explicit RegWindow(QWidget *parent = 0);
QString hashSha1(QString hashIt);
~RegWindow();
private slots:
void ReplyFromServer(QString);
void on_pbRegister_clicked();
void on_pbCheckUsername_clicked();
private:
QString userName;
QString firstName;
QString lastName;
QString password;
QString dob;
QString email;
QString prq;
QString pra;
RegEx regX;
Ui::RegWindow *ui;
};
#endif // REGWINDOW_H
|
sksdlin/GroupChatClientDesktop | src/loginwindow.h | <gh_stars>0
#ifndef LOGINWINDOW_H
#define LOGINWINDOW_H
#include <QMainWindow>
#include <QWidget>
#include <QTcpSocket>
#include <regex>
#include <QCryptographicHash>
#include <QSslError>
namespace Ui {
class LoginWindow;
}
class LoginWindow : public QMainWindow
{
Q_OBJECT
public:
explicit LoginWindow(QWidget *parent = 0);
QString hashSha1(QString hashIt);
QString getStrRandomNumber();
static QString getStrRequestNumber();
~LoginWindow();
private slots:
void on_pbRegister_clicked();
void on_pbLogin_clicked();
void onConnected();
void onSslErrors(const QList<QSslError> &errors);
void ReplyFromServer(QString serverMessage);
void on_pbForgotPassword_clicked();
private:
Ui::LoginWindow *ui;
QString SERVERMESSAGE = "Uninited string............";
static QString strRandomNumber;
};
#endif // LOGINWINDOW_H
|
sksdlin/GroupChatClientDesktop | src/chat.h | <filename>src/chat.h<gh_stars>0
#ifndef CHAT_H
#define CHAT_H
#include <QMainWindow>
#include <QTcpSocket>
#include <QHostAddress>
#include <string>
#include <QDataStream>
namespace Ui {
class Chat;
}
class Chat : public QMainWindow
{
Q_OBJECT
public:
explicit Chat(QWidget *parent = 0);
void closeEvent (QCloseEvent *event);
~Chat();
private slots:
void on_pbSend_clicked();
void loadMessage(QString response);
void on_leUserChat_returnPressed();
private:
Ui::Chat *ui;
//QTcpSocket *socket;
};
#endif // CHAT_H
|
tealminivan/FinalProject | kernel/generated_pybind.h | //#include <pybind11/pybind11.h>
//#include "dlpack.h"
//#include "kernel.h"
//#include "csr.h"
//namespace py = pybind11;
inline void export_kernel(py::module &m) {
m.def("spmm",
[](graph_t& graph, py::capsule& input, py::capsule& output) {
array2d_t<float> input_array = capsule_to_array2d(input);
array2d_t<float> output_array = capsule_to_array2d(output);
return invoke_spmm(graph, input_array, output_array);
}
);
}
|
tealminivan/FinalProject | kernel/kernel.h | #pragma once
#include "csr.h"
#include "op.h"
extern int THD_COUNT;
void invoke_spmm(graph_t& graph, array2d_t<float> & input, array2d_t<float> & output);
|
tealminivan/FinalProject | kernel/op.h | <reponame>tealminivan/FinalProject
//
// Created by yidong on 8/31/20.
//
#pragma once
#include <string>
#include <cstring>
enum op_t {
eSUM = 0,
eMAX,
eMIN,
eSUB,
eMUL,
eDIV,
};
//1D tensor
template <class T>
struct array1d_t {
T* data_ptr;
int64_t col_count;
bool alloc;
T& operator[] (int64_t index) {//returns the element
return data_ptr[index];
}
void assign (int64_t index, const T& value) {//returns the element
data_ptr[index] = value ;
}
array1d_t(int64_t a_col_count) {
data_ptr = (T*)calloc(sizeof(T), a_col_count);
col_count = a_col_count;
alloc = true;
}
array1d_t(T* ptr, int64_t a_col_count) {
data_ptr = ptr;
col_count = a_col_count;
alloc = false;
}
~array1d_t() {
if (alloc) {
free(data_ptr);
}
}
void reset() {
memset(data_ptr, 0, col_count*sizeof(T));
}
void add(T* ptr) {
T* row_ptr = data_ptr;
for (int64_t i = 0; i < col_count; ++i) {
row_ptr[i] += ptr[i];
}
}
void addw(T* ptr, T weight) {
T* row_ptr = data_ptr;
for (int64_t i = 0; i < col_count; ++i) {
row_ptr[i] += ptr[i]*weight;
}
}
};
//2D tensor
template <class T>
struct array2d_t {
T* data_ptr;
int64_t row_count;
int64_t col_count;
T* operator[] (int64_t index) {//returns a row
return data_ptr + col_count*index;
}
array2d_t(T* a_ptr, int64_t a_row_count, int64_t a_col_count) {
data_ptr = a_ptr;
row_count = a_row_count;
col_count = a_col_count;
}
void row_copy(T* ptr, int64_t index) {
T* row_ptr = data_ptr + col_count*index;
memcpy(row_ptr, ptr, col_count*sizeof(T));
}
void row_copy_norm(T* ptr, int64_t index, int degree) {
T* row_ptr = data_ptr + col_count*index;
for (int64_t i = 0; i < col_count; ++i) {
row_ptr[i] = ptr[i]/degree;
}
}
void row_add(T* ptr, int64_t index) {
T* row_ptr = data_ptr + col_count*index;
for (int64_t i = 0; i < col_count; ++i) {
row_ptr[i] += ptr[i];
}
}
void row_normalize(int64_t index, T degree) {
T* row_ptr = data_ptr + col_count*index;
if (degree == 0){
return;
}
for (int64_t i = 0; i < col_count; ++i) {
row_ptr[i] /= degree;
}
}
T get_item(int64_t row_id, int64_t col_id) {
return data_ptr[row_id*col_count + col_id];
}
array1d_t<T> get_row(int64_t row_id) {
return array1d_t<T>(data_ptr + row_id*col_count, col_count);
}
void reset() {
memset(data_ptr, 0, row_count*col_count*sizeof(T));
}
};
//3D tensor
template <class T>
struct array3d_t {
T* data_ptr;
int64_t matrix_count;
int64_t row_count;
int64_t col_count;
T* operator[] (int64_t index) {//returns a matrix
return data_ptr + col_count * row_count * index;
}
array3d_t(T* a_ptr, int64_t a_matrix_count, int64_t a_row_count, int64_t a_col_count) {
data_ptr = a_ptr;
matrix_count = a_matrix_count;
row_count = a_row_count;
col_count = a_col_count;
}
void matrix_copy(T* ptr, int64_t index) {
T* row_ptr = data_ptr + row_count * col_count * index;
memcpy(row_ptr, ptr, row_count * col_count * sizeof(T));
}
array1d_t<T> get_row(int64_t index, int64_t row_id) {
T* row_ptr = data_ptr + row_count * col_count * index + row_id*col_count;
array1d_t<T> array(row_ptr, col_count);
return array;
}
T* get_row_ptr(int64_t index, int64_t row_id) {
T* row_ptr = data_ptr + row_count * col_count * index + row_id*col_count;
return row_ptr;
}
void row_copy(T* ptr, int64_t index, int64_t row_id) {
T* row_ptr = data_ptr + row_count * col_count * index + row_id*col_count;
memcpy(row_ptr, ptr, row_count * col_count * sizeof(T));
}
};
|
tealminivan/FinalProject | kernel/csr.h | <reponame>tealminivan/FinalProject
#pragma once
#include "stdint.h"
using namespace std;
#ifdef B64
typedef uint64_t vid_t;
#elif B32
typedef uint32_t vid_t;
#endif
typedef float val_t;
struct neighbor_t {
vid_t dst;
val_t weight;
};
class csr_t {
public:
vid_t v_count; //This is actual vcount in a graph
vid_t e_count;
vid_t dst_size;
vid_t* offset;
neighbor_t* nebrs;
int* degrees;
int64_t flag;
public:
csr_t() {
};
void init(vid_t a_vcount, vid_t a_dstsize, void* a_offset, void* a_nebrs, int64_t a_flag, vid_t edge_count) {
}
vid_t get_vcount() {
return v_count;
}
vid_t get_ecount() {
return e_count;
}
vid_t get_degree(vid_t index) {
return offset[index + 1] - offset[index];
}
};
class edge_t {
public:
vid_t src;
vid_t dst;
//edge properties here if any.
};
class coo_t {
public:
edge_t* edges;
vid_t dst_size;
vid_t v_count;
vid_t e_count;
coo_t() {
edges = 0;
dst_size = 0;
v_count = 0;
e_count = 0;
}
void init(vid_t a_vcount, vid_t a_dstsize, vid_t a_ecount, edge_t* a_edges) {
}
};
class graph_t {
public:
csr_t csr;
csr_t csc;
coo_t coo;
public:
void init(vid_t a_vcount, vid_t a_dstsize, void* a_offset, void* a_nebrs, void* a_offset1, void* a_nebrs1, int64_t flag, int64_t num_vcount) {
csr.offset = (vid_t*)a_offset;
csr.nebrs = (neighbor_t*)a_nebrs;
csc.offset = (vid_t*)a_offset1;
csc.nebrs = (neighbor_t*)a_nebrs1;
csr.v_count = a_vcount;
csr.dst_size = a_dstsize;
csr.flag = flag;
csc.v_count = a_vcount;
csc.dst_size = a_dstsize;
csc.flag = flag;
}
vid_t get_vcount() {
return csr.v_count;
}
vid_t get_edge_count() {
return csr.e_count;
}
};
|
khoih-prog/RTL8720_TimerInterrupt | src_h/RTL8720_TimerInterrupt.h | <filename>src_h/RTL8720_TimerInterrupt.h
/****************************************************************************************************************************
RTL8720_TimerInterrupt.h
For RTL8720DN, RTL8722DM and RTL8722CSM boards
Written by <NAME>
Built by Khoi Hoang https://github.com/khoih-prog/RTL8720_TimerInterrupt
Licensed under MIT license
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RTL8720DN, RTL8722DM and RTL8722CSM timer and avoid conflicting
with other cores' tasks. The accuracy is nearly perfect compared to software timers. The most important feature is they're
ISR-based timers. Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: <EMAIL>
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: <NAME>
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 <NAME> 09/08/2021 Initial coding for RTL8720DN, RTL8722DM and RTL8722CSM
*****************************************************************************************************************************/
#pragma once
#ifndef RTL8720_TIMERINTERRUPT_H
#define RTL8720_TIMERINTERRUPT_H
#if !defined(CONFIG_PLATFORM_8721D)
#error Only for Ameba Realtek RTL8720DN, RTL8722DM and RTM8722CSM platform.
#endif
#ifndef RTL8720_TIMER_INTERRUPT_VERSION
#define RTL8720_TIMER_INTERRUPT_VERSION "RTL8720_TimerInterrupt v1.0.0"
#endif
#include "TimerInterrupt_Generic_Debug.h"
#ifdef __cplusplus
extern "C"
{
#include "timer_api.h"
}
#endif
typedef enum
{
Timer0 = GTIMER_MAX,
Timer1 = GTIMER_MAX,
Timer2 = 2,
Timer3 = 3,
MAX_TIMER = GTIMER_MAX,
} RTL8720_TimerNumber;
// TIMER0, reserved and used in us_tick(), wait_ms() functions. Users are not recommended to use
// TIMER1, used in APP_TIM_ID. Users are not recommended to use
uint32_t timer_mapping[GTIMER_MAX] =
{
TIMER0,
TIMER1,
TIMER2,
TIMER3
};
class RTL8720TimerInterrupt;
typedef RTL8720TimerInterrupt RTL8720Timer;
typedef void (*timerCallback) (uint32_t data);
class RTL8720TimerInterrupt
{
private:
uint32_t _timer = GTIMER_MAX;
gtimer_t _timerObj;
timerCallback _callback; // pointer to the callback function
float _frequency; // Timer frequency
uint32_t _timerCount; // count to activate timer
public:
RTL8720TimerInterrupt(uint8_t timer)
{
if (timer >= GTIMER_MAX)
{
return;
}
_timer = timer;
gtimer_init(&_timerObj, timer_mapping[_timer]);
_callback = NULL;
};
~RTL8720TimerInterrupt()
{
}
// frequency (in hertz)
bool setFrequency(float frequency, timerCallback callback)
{
if ( (_timer >= GTIMER_MAX) )
{
TISR_LOGERROR(F("RTL8720TimerInterrupt init error"));
return false;
}
// select timer frequency is 1MHz for better accuracy. We don't use 16-bit prescaler for now.
// Will use later if very low frequency is needed.
_frequency = frequency;
_timerCount = (uint32_t) (1000000.0f / _frequency);
_callback = callback;
TISR_LOGWARN(F("RTL8720TimerInterrupt"));
TISR_LOGWARN3(F("Request Interval (mS) ="), _timerCount / 1000, F(", _count ="), (uint32_t) (_timerCount));
gtimer_start_periodical(&_timerObj, _timerCount, (void *) callback, _timer);
return true;
}
// interval (in microseconds)
bool setInterval(unsigned long interval, timerCallback callback)
{
return setFrequency((float) (1000000.0f / interval), callback);
}
bool attachInterrupt(float frequency, timerCallback callback)
{
return setFrequency(frequency, callback);
}
// interval (in microseconds)
bool attachInterruptInterval(unsigned long interval, timerCallback callback)
{
return setFrequency( (float) ( 1000000.0f / interval), callback);
}
void detachInterrupt()
{
gtimer_stop(&_timerObj);
}
void disableTimer()
{
gtimer_stop(&_timerObj);
}
void reattachInterrupt()
{
setFrequency(_frequency, _callback);
}
void enableTimer()
{
setFrequency(_frequency, _callback);
}
// Just stop clock source, clear the count
void stopTimer()
{
gtimer_stop(&_timerObj);
}
// Just reconnect clock source, start current count from 0
void restartTimer()
{
setFrequency(_frequency, _callback);
}
}; // class RTL8720TimerInterrupt
#endif // RTL8720_TIMERINTERRUPT_H
|
lusm554/operating-system-concepts | src/chapter-3/what_the_output.c | <reponame>lusm554/operating-system-concepts
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int value = 5;
int main(void) {
pid_t pid;
pid = fork();
printf("pid - %u\n", pid);
if (pid == 0) { // child
value += 15;
return 0;
}
if (pid > 0) { // parent
wait(NULL);
printf("num: %u\n", value);
return 0;
}
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/pid_manager.c | #include <stdio.h>
#include <stdlib.h>
#define MIN_PID 300
#define MAX_PID 5000
#define SIZE MAX_PID - MIN_PID
int alloc_map(void);
int alloc_pid(void);
void release_pid(int pid);
int bitmap[SIZE] = {0};
int main(void) {
alloc_map();
printf("%zu\n", sizeof bitmap);
for (int i = 0; i < 5; i++) {
int t = alloc_pid();
}
for (int i = 0; i < 6; i++) {
printf("bitmap[%d] = %d\n", i, bitmap[i]);
}
for (int i = 0; i < 5; i++) {
release_pid(MIN_PID + i);
}
printf("\n");
for (int i = 0; i < 6; i++) {
printf("bitmap[%d] = %d\n", i, bitmap[i]);
}
return 0;
}
// TODO: fix allocation of map
int alloc_map(void) {
return 1;
}
int alloc_pid(void) {
for (int i = 0; i < SIZE; i++) {
if (bitmap[i] == 0) {
bitmap[i] = MIN_PID + i;
return MIN_PID + i;
}
}
return -1;
}
void release_pid(int pid) {
if (!(pid >= MIN_PID & pid <= MAX_PID)) return;
bitmap[pid - MIN_PID] = 0;
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/time_ver_2.c | <filename>src/chapter-3/Programming-Problems/time_ver_2.c<gh_stars>0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#define SIZE 128
#define READ_END 0
#define WRITE_END 1
int elapsed(struct timeval *start, struct timeval *end);
char *to_str_view(int all_msecs);
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: ./time [command_to_execute]\n");
return 1;
}
int write_msg[SIZE];
int read_msg[SIZE];
int fd[2];
pid_t pid;
if (pipe(fd) == -1) {
perror("pipe()");
return EXIT_FAILURE;
}
pid = fork();
if (pid < 0) { // error
perror("fork()");
return EXIT_FAILURE;
}
if (pid == 0) { // child
struct timeval start;
gettimeofday(&start, NULL);
write_msg[0] = start.tv_sec;
write_msg[1] = start.tv_usec;
system(argv[1]);
close(fd[READ_END]);
write(fd[WRITE_END], write_msg, SIZE);
close(fd[WRITE_END]);
}
if (pid > 0) { // parent
close(fd[WRITE_END]);
// read pointer
read(fd[READ_END], read_msg, SIZE);
struct timeval start, end;
gettimeofday(&end, NULL);
start.tv_sec = read_msg[0];
start.tv_usec = read_msg[1];
close(fd[READ_END]);
printf("%s", to_str_view(elapsed(&start, &end)));
wait(NULL);
}
return 0;
}
// creates view of microseconds to seconds
char *to_str_view(int all_msecs) {
int sec = all_msecs/1e+6;
int msec = all_msecs%(int)1e+6;
char *str;
sprintf(str, "\nElapsed time: %u.%u\n", sec, msec);
return str;
}
// count diff between two timeval
int elapsed(struct timeval *start, struct timeval *end) {
return ((end->tv_sec - start->tv_sec) * 1000000) + (end->tv_usec - start->tv_usec);
}
|
lusm554/operating-system-concepts | src/chapter-4/Programming-Problems/fibonacci.c | <filename>src/chapter-4/Programming-Problems/fibonacci.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *runner(void *param);
int *arr;
int main(int argc, char **argv) {
if (argc != 2) return 1;
char *count = argv[1];
arr = malloc(sizeof(*arr) * atoi(count));
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, count);
pthread_join(tid, NULL);
printf("Fibonacci sequence:\n");
for (int i = 0; i < atoi(count); i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
void *runner(void *param) {
int count = atoi(param);
int a = 0, b = 1;
// 0 1 1 2 3
for (int i = 0; i < count; i++) {
arr[i] = a;
int temp = a;
a = b;
b = temp + b;
}
pthread_exit(0);
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/cp.c | #include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define READ_END 0
#define WRITE_END 1
int main(int argc, void **argv) {
if (argc != 3) return 1;
char *src = argv[1];
char *dest = argv[2];
FILE *fp_read;
FILE *fp_write;
int fd[2];
pid_t pid;
/* Create the pipe */
if (pipe(fd)) {
perror("pipe");
return EXIT_FAILURE;
}
pid = fork();
/* parent */
if (pid > 0 ) {
if (!(fp_read = fopen(src, "r"))) {
perror("fopen");
return EXIT_FAILURE;
}
int c;
FILE *stream;
stream = fdopen(fd[WRITE_END], "w");
close(fd[READ_END]);
while ((c = getc(fp_read)) != EOF)
fprintf(stream, "%c", c);
fclose(stream);
fclose(fp_read);
close(fd[WRITE_END]);
wait(NULL);
}
/* child */
if (pid == 0) {
FILE *stream;
int c;
if (!(fp_write = fopen(dest, "w"))) {
perror("fopen");
return EXIT_FAILURE;
}
close(fd[WRITE_END]);
stream = fdopen(fd[READ_END], "r");
while ((c = fgetc(stream)) != EOF)
fputc(c, fp_write);
fclose(fp_write);
fclose(stream);
close(fd[READ_END]);
}
/* error */
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
return 0;
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/SHM-Collatz-conjecture.c | <reponame>lusm554/operating-system-concepts<filename>src/chapter-3/Programming-Problems/SHM-Collatz-conjecture.c<gh_stars>0
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define NAME "/Collatz_conjecture"
#define MAX_SEQ_SIZE 500
#define SIZE sizeof(int) * MAX_SEQ_SIZE
long to_num(char *str);
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: ./a.out [num]\n");
return 1;
}
long num;
if ((num = to_num(argv[1])) == -1) {
perror("incorrect integer");
return 1;
}
/* SHM */
int fd = shm_open(NAME, O_CREAT | O_EXCL | O_RDWR, 0666);
if (fd < 0) {
perror("sh_open()");
return EXIT_FAILURE;
}
if (ftruncate(fd, SIZE) < 0) {
perror("ftruncate()");
return EXIT_FAILURE;
}
int *ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
/* CHILD PROCESS */
pid_t pid;
pid = fork();
if (pid < 0) { //error
perror("fork()");
return EXIT_FAILURE;
}
if (pid == 0) { // child
int i = 0;
while (num != 1) {
ptr[i] = num;
if (num % 2 == 0)
num /= 2;
else
num = 3 * num + 1;
if (i == MAX_SEQ_SIZE)
return 1;
i++;
}
ptr[i] = 1;
ptr[++i] = -1;
}
if (pid > 0) { // parent
wait(NULL);
int i = 0;
while (ptr[i] != -1) {
printf("%d ", ptr[i++]);
}
printf("\n");
// remove shm
munmap(ptr, SIZE);
close(fd);
shm_unlink(NAME);
}
return 0;
}
long to_num(char *str) {
char *p;
errno = 0;
long num = strtol(str, &p, 10);
if (errno != 0 || *p != '\0' || num > INT_MAX || num < 0) {
return -1;
}
return num;
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/Collatz-conjecture.c | <filename>src/chapter-3/Programming-Problems/Collatz-conjecture.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <wait.h>
long to_num(char *str);
int main(int argc, char **argv) {
if (argc != 2) return 1;
long num;
if ((num = to_num(argv[1])) == -1) return 1;
printf("Input: %s\n", argv[1]);
pid_t pid;
pid = fork();
if (pid < 0) // error
return 1;
if (pid == 0) { // child
while (num != 1) {
printf("%ld ", num);
if (num % 2 == 0) {
num /= 2;
} else {
num = 3 * num + 1;
}
}
printf("1\n");
}
if (pid > 0) { // parent
wait(NULL);
}
return 0;
}
long to_num(char *str) {
char *p;
errno = 0;
long num = strtol(str, &p, 10);
if (errno != 0 || *p != '\0' || num > INT_MAX || num < 0) {
return -1;
}
return num;
}
|
lusm554/operating-system-concepts | src/chapter-4/Programming-Problems/calculate-statistical-values.c | <filename>src/chapter-4/Programming-Problems/calculate-statistical-values.c<gh_stars>0
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *get_avg(void *raw_args);
void *get_max(void *raw_args);
void *get_min(void *raw_args);
int MAX;
int MIN;
int AVG;
struct arg_struct {
int *arr;
int len;
} *args;
int main(int argc, char **argv) {
int arr[argc-1];
args = malloc((int)sizeof(struct arg_struct));
for (int i = 1; i < argc; i++) {
arr[i-1] = atoi(argv[i]);
}
args->arr = arr;
args->len = (int)(sizeof(arr)/sizeof(int));
for (int i = 0; i < 3; i++) {
pthread_t tid; // the thread identifier
pthread_attr_t attr; // set of thread attributes
pthread_attr_init(&attr); // set the default attributes of the thread
switch (i) {
case 0:
pthread_create(&tid, &attr, get_avg, args); // create the thread
break;
case 1:
pthread_create(&tid, &attr, get_max, args); // create the thread
break;
case 2:
pthread_create(&tid, &attr, get_min, args); // create the thread
break;
}
pthread_join(tid, NULL); // wait for the thread to exit
}
printf("avg: %d, max: %d, min: %d\n", AVG, MIN, MAX);
free(args);
return 0;
}
void *get_avg(void *raw_args) {
struct arg_struct *args = raw_args;
AVG = 0;
int sum = 0;
for (int i = 0; i < args->len; i++) {
sum += args->arr[i];
}
AVG = sum / args->len;
pthread_exit(0);
}
void *get_max(void *raw_args) {
struct arg_struct *args = raw_args;
int m = args->arr[0];
for (int i = 0; i < args->len; i++) {
if (args->arr[i] > m) {
m = args->arr[i];
}
}
MIN = m;
pthread_exit(0);
}
void *get_min(void *raw_args) {
struct arg_struct *args = raw_args;
int m = args->arr[0];
for (int i = 0; i < args->len; i++) {
if (args->arr[i] < m) {
m = args->arr[i];
}
}
MAX = m;
pthread_exit(0);
}
|
lusm554/operating-system-concepts | src/chapter-3/producer.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h> // for avoid warning for truncate
#include <sys/mman.h>
int main(void) {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* strings written to shared memory */
const char *msg_0 = "Hello";
const char *msg_1 = "World!";
/* shared memory file descriptor */
int fd;
/* pointer to shared memory object */
char *ptr;
/* create the shared memory object */
fd = shm_open(name, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory object */
ftruncate(fd, SIZE);
/* memory map the shared memory object */
ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
/* write to the shared memory object */
sprintf(ptr, "%s", msg_0);
ptr += strlen(msg_0);
sprintf(ptr, "%s", msg_1);
ptr += strlen(msg_1);
return 0;
}
|
lusm554/operating-system-concepts | src/chapter-3/consumer-producer-problem.c | <filename>src/chapter-3/consumer-producer-problem.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
void write_shm(void);
void read_shm(void);
int main(void) {
write_shm();
read_shm();
return 0;
}
void write_shm(void) {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* strings written to shared memory */
const char *msg_0 = "Hello";
const char *msg_1 = "World!";
/* shared memory file descriptor */
int fd;
/* pointer to shared memory object */
char *ptr;
/* create the shared memory object */
fd = shm_open(name, O_CREAT | O_RDWR, 0666);
printf("fd write - %u\n", fd);
/* configure the size of the shared memory object */
ftruncate(fd, SIZE);
/* memory map the shared memory object */
ptr = (char *)
mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
/* write to the shared memory object */
sprintf(ptr, "%s", msg_0);
ptr += strlen(msg_0);
sprintf(ptr, "%s", msg_1);
ptr += strlen(msg_1);
}
void read_shm(void) {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* shared memory file descriptor */
int fd;
/* pointer to shared memory object */
char *ptr;
/* open the shared memory object */
fd = shm_open(name, O_RDONLY, 0666);
printf("fd read - %u\n", fd);
/* memory map the shared memory object */
ptr = (char *)
(mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
/* read from the shared memory object */
printf("%s", (char*)ptr);
/* remove the shared memory object */
shm_unlink(name);
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/zombie-process.c | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(void) {
pid_t pid;
pid = fork();
if (pid < 0) { // error
return 1;
}
if (pid == 0) { // child process
exit(0);
}
if (pid > 0) { // parent process
// sleep 20 seconds
time_t end_time = time(NULL) + 20;
while(time(NULL) < end_time);
// or just sleep(20);
}
return 0;
}
|
lusm554/operating-system-concepts | src/chapter-2/Linux-Kernel-Modules/simple.c | #include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/hash.h> // GOLDEN_RATIO_PRIME
#include <linux/gcd.h> // gcd
#include <asm/param.h> // HZ
#include <linux/jiffies.h> // jiffies
unsigned long int JIFFIES_AT_INIT;
/* This function is called when the module is loaded. */
int simple_init(void) {
printk(KERN_INFO "Loading Kernel Module\n");
unsigned long int a = 3300;
unsigned int b = 24;
JIFFIES_AT_INIT = jiffies;
/* Print GOLDEN_RATIO_PRIME and GCD of a and b. */
printk(KERN_INFO "GOLDEN_RATIO_PRIME: %u\n", GOLDEN_RATIO_PRIME);
printk(KERN_INFO "Greatest common divisor of %u and %u: %llu\n", a, b, gcd(a, b));
/* Print jiffies and HZ. */
printk(KERN_INFO "Jiffies in init: %u\n", jiffies);
printk(KERN_INFO "HZ: %u\n", HZ);
return 0;
}
/* This function is called when the module is removed. */
void simple_exit(void) {
int time = (jiffies - JIFFIES_AT_INIT) / HZ;
/* Print jiffies and number of seconds that have elapsed since module loaded. */
printk(KERN_INFO "Jiffies in exit: %u\n", jiffies);
printk(KERN_INFO "Number of seconds since module loaded: %u\n", time);
printk(KERN_INFO "Removing Kernel Module\n");
}
/* Macros for registering module entry and exit points. */
module_init(simple_init);
module_exit(simple_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Projects/unix-shell.c | <gh_stars>0
#include <stdio.h>
#include <unistd.h>
#include <errno.h> // errno
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#define MAX_LINE 256 /* The max length of command */
#define MAX_TOKEN 64
#define TOK_DELIM " \t\r\n\a"
/*
* errno
*
* Value: Description:
* 0 No error
* EDOM Domain error (from math)
* EILSEQ Encoding error (from character conversion)
* ERANGE Range error (from math)
*/
char *read_line(void);
char **split_line(char *line);
int execute(char **args, char**hist);
int launch(char **args, int isBackground, char **hist);
int IsHistExist = 0;
int main(void) {
char *line;
char **args;
int should_run = 1;
char **hist = malloc(MAX_TOKEN * sizeof(char *));
// Check history object.
if (!hist) {
perror("malloc");
exit(EXIT_FAILURE);
}
while (should_run) {
printf("osh>");
// Calls force the output to standard output.
fflush(stdout);
line = read_line();
args = split_line(line);
// Check first four chars on 'exit'.
if (strncmp(line, "exit", 4) == 0) {
free(line);
free(args);
break;
}
should_run = execute(args, hist);
free(line);
free(args);
}
return 0;
}
char *read_line(void) {
char *line = malloc(sizeof(char) * MAX_LINE);
int i = 0;
int c;
if (!line) {
perror("malloc");
exit(EXIT_FAILURE);
}
while (1) {
// Read char from stdin.
c = getchar();
// If get EOF, replace it will null char and return.
if (c == EOF || c == '\n') {
line[i] = '\0';
return line;
} else {
line[i] = c;
}
i++;
// If input exceeded the line buffer, error.
if (i >= MAX_LINE) {
perror("too big line");
exit(EXIT_FAILURE);
}
}
}
char **split_line(char *line) {
char **tokens = malloc(MAX_TOKEN * sizeof(char *));
char *token;
int i = 0;
if (!tokens) {
perror("malloc");
exit(EXIT_FAILURE);
}
token = strtok(line, TOK_DELIM);
while (token != NULL) {
tokens[i] = token;
i++;
if (i >= MAX_TOKEN * sizeof(char *)) {
perror("too big token");
exit(EXIT_FAILURE);
}
token = strtok(NULL, TOK_DELIM);
}
tokens[i] = NULL;
return tokens;
}
int execute(char **args, char**hist) {
// An empty command was entered.
if (args[0] == NULL) {
return 1;
}
// Check for '!!', run previous command
if (strncmp(args[0], "!!", 2) == 0 ) {
if (!IsHistExist) {
printf("No commands in history.\n");
return 1;
}
int i = 0;
while (hist[i] != NULL) {
printf("%s\n", hist[i++]);
}
return launch(hist, 0, hist);
}
// Check for &.
int isBackground = 0, i = 0;
while (args[i] != NULL) {
printf("ebat %s\n", args[i]);
char *temp = args[i] + strlen(args[i]) - 1;
if (strncmp(temp, "&", 1) == 0 && args[i+1] == NULL) {
isBackground = 1;
if (strlen(args[i]) == 1) {
args[i] = NULL;
} else {
args[i][strlen(args[i]) - 1] = '\0';
}
break;
}
i++;
}
return launch(args, isBackground, hist);
}
int launch(char **args, int isBackground, char **hist) {
pid_t pid, wpid;
int status;
hist = strdup(args);
pid = fork();
// Child process.
if (pid == 0) {
if (isBackground) {
printf("\n");
}
if (execvp(args[0], args) == -1) {
perror("execvp");
}
exit(EXIT_FAILURE);
}
// Parent process.
if (pid > 0) {
if (!isBackground) {
// Waiting for child (command) process.
do {
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
// Save current command to history.
//strncpy(hist, args, sizeof(hist));
IsHistExist = 1;
}
// Error forking.
if (pid < 0) {
perror("fork");
}
return 1;
}
|
lusm554/operating-system-concepts | src/chapter-2/Linux-Kernel-Modules/seconds.c | <filename>src/chapter-2/Linux-Kernel-Modules/seconds.c
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/jiffies.h> // seconds
#include <asm/param.h> // HZ
#define BUFFER_SIZE 128
#define PROC_NAME "seconds"
unsigned long int JIFFIES_AT_INIT;
ssize_t proc_read(struct file *file, char __user *usr_buf, size_t count, loff_t *pos);
/* .read – name of the function that will be called whenever /proc/seconds is read. */
static struct file_operations proc_ops = {
.owner = THIS_MODULE,
.read = proc_read,
};
/* This function is called when the module is loaded. */
int proc_init(void) {
/* create the "/proc/seconds" entry */
proc_create(PROC_NAME, 0666, NULL, &proc_ops);
printk(KERN_INFO "Loading Kernel Module \"seconds\"\n");
JIFFIES_AT_INIT = jiffies;
return 0;
}
/* This function is called when the module is removed. */
void proc_exit(void) {
/* removes the "/proc/seconds" entry. */
remove_proc_entry(PROC_NAME, NULL);
printk(KERN_INFO "Removing Kernel Module \"seconds\"\n");
}
/*
* Each time "/proc/seconds" file is read, this function is called repeatedly until it returns 0.
* So there must be logic to ensure that this function returns 0 once it has called.
*/
ssize_t proc_read(struct file *file, char __user *usr_buf, size_t count, loff_t *pos) {
int rv = 0;
char buffer[BUFFER_SIZE];
static int completed = 0;
// save from infinity loop
if (completed) {
completed = 0;
return 0;
}
completed = 1;
int elapsed_time = (jiffies - JIFFIES_AT_INIT) / HZ;
rv = sprintf(buffer, "%u\n", elapsed_time);
/* copies kernel space buffer to user space usr_buf */
copy_to_user(usr_buf, buffer, rv);
printk(KERN_INFO "Reading \"seconds\"\n");
return rv;
}
module_init(proc_init);
module_exit(proc_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Seconds Module");
MODULE_AUTHOR("SGG");
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/time_ver_1.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define SIZE sizeof(long long int) * 2 // two nums
#define NAME "/time_counter"
int elapsed(struct timeval *start, struct timeval *end);
char *to_str_view(int all_msecs);
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: ./time [command_to_execute]\n");
return 1;
}
/* SHARED MEMORY */
int fd = shm_open(NAME, O_CREAT | O_EXCL | O_RDWR, 0666);
if (fd < 0) {
perror("shm_open()");
return EXIT_FAILURE;
}
if (ftruncate(fd, SIZE) < 0) {
perror("ftruncate()");
return EXIT_FAILURE;
}
int *ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
//printf("shm address: %p\n", ptr);
/* CREATE CHILD PROCESS */
pid_t pid;
pid = fork();
if (pid < 0) { // error
perror("fork()");
return EXIT_FAILURE;
}
if (pid == 0) { // child
/* TIMEVAL */
struct timeval start;
gettimeofday(&start, NULL);
ptr[0] = start.tv_sec;
ptr[1] = start.tv_usec;
//execlp("/bin/ls", "ls", NULL);
system(argv[1]);
}
if (pid > 0) { // parent
wait(NULL);
/* TIMEVAL */
struct timeval start, end;
gettimeofday(&end, NULL);
start.tv_sec = ptr[0];
start.tv_usec = ptr[1];
printf("%s", to_str_view(elapsed(&start, &end)));
munmap(ptr, SIZE);
close(fd);
shm_unlink(NAME);
}
return 0;
}
// creates view of microseconds to seconds
char *to_str_view(int all_msecs) {
int sec = all_msecs/1e+6;
int msec = all_msecs%(int)1e+6;
char *str;
sprintf(str, "\nElapsed time: %u.%u\n", sec, msec);
return str;
}
// count diff between two timeval
int elapsed(struct timeval *start, struct timeval *end) {
return ((end->tv_sec - start->tv_sec) * 1000000) + (end->tv_usec - start->tv_usec);
}
|
lusm554/operating-system-concepts | src/chapter-4/multithreaded-sum.c | <gh_stars>0
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
// This data is shared by the thread(s)
int sum;
// Threads call this function
void *runner(void *param);
int main(int argc, char **argv) {
char *number_to_sum = argv[1];
pthread_t tid; // the thread identifier
pthread_attr_t attr; // set of thread attributes
// Set the default attributes of the thread
pthread_attr_init(&attr);
// Create the thread
pthread_create(&tid, &attr, runner, number_to_sum);
// Wait for the thread to exit
pthread_join(tid, NULL);
printf("sum = %d\n", sum);
return 0;
}
// The thread will execute in this function
void *runner(void *param) {
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++) {
sum += i;
}
pthread_exit(0);
}
|
lusm554/operating-system-concepts | src/chapter-4/Programming-Projects/sudoku-solution-validator.c | #include <stdio.h>
int main(void) {
int solution_to_9x9_puzzle[9][9] = {
{6, 2, 4, 5, 3, 9, 1, 8, 7},
{5, 1, 9, 7, 2, 8, 6, 3, 4},
{8, 3, 7, 6, 1, 4, 2, 9, 5},
{1, 4, 3, 8, 6, 5, 7, 2, 9},
{9, 5, 8, 2, 4, 7, 3, 6, 1},
{7, 6, 2, 3, 9, 1, 4 ,5, 8},
{3, 7, 1, 9, 5, 6, 8, 4, 2},
{4, 9, 6, 1, 8, 2, 5, 7, 3},
{2, 8, 5, 4, 7, 3, 9, 1, 6}
};
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
printf("%d ", solution_to_9x9_puzzle[i][j]);
}
printf("\n");
}
return 0;
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/quote-of-the-day.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#define PORT "6017"
#define BACKLOG 5 // how many pending connections queue will hold
char *get_quote();
void sigchld_handler(int s);
void *get_in_addr(struct sockaddr *sa);
int main(void) {
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address info
socklen_t sin_size;
struct sigaction sa;
int yes = 1;
char s[INET6_ADDRSTRLEN];
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigation");
exit(1);
}
printf("server: waiting for connections...\n");
while (1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
char *q = get_quote();
if (send(new_fd, q, strlen(q), 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
return 0;
}
void sigchld_handler(int s) {
// waitpid() might overwrite errno, so we save and restore it:
int saved_errno = errno;
while (waitpid(-1, NULL, WNOHANG) > 0);
errno = saved_errno;
}
void *get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa) -> sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
char *get_quote() {
int len = 11;
char *quotes[] = {
"It is not a lack of love, but a lack of friendship that makes unhappy marriages.",
"That which does not kill us makes us stronger.",
"I'm not upset that you lied to me, I'm upset that from now on I can't believe you.",
"You must have chaos within you to give birth to a dancing star.",
"In heaven, all the interesting people are missing.",
"Man is the cruelest animal.",
"We cannot solve our problems with the same thinking we used when we created them.",
"The true sign of intelligence is not knowledge but imagination.",
"I have no special talent. I am only passionately curious.",
"It should be possible to explain the laws of physics to a barmaid.",
"The only real valuable thing is intuition.",
};
srand(time(0));
return quotes[rand() % len + 0];
}
|
lusm554/operating-system-concepts | src/chapter-4/Programming-Problems/prime_nums.c | <filename>src/chapter-4/Programming-Problems/prime_nums.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *runner(void *param);
int main(int argc, char **argv) {
if (argc != 2) return 1;
char *limit = argv[1];
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, limit);
pthread_join(tid, NULL);
return 0;
}
void *runner(void *param) {
int limit = atoi(param);
for (int i = 1; i < limit; i++) {
int isPrime = 1;
for (int j = 2; j <= i/2; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
printf("Prime - %d\n", i);
}
}
pthread_exit(0);
}
|
lusm554/operating-system-concepts | src/chapter-3/Programming-Problems/reverse-case-pipe.c | #include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define SIZE 25
#define READ_END 0
#define WRITE_END 1
void read_pipe(int *fd, char *read_msg);
void write_pipe(int *fd, char *write_msg);
int main(int argc, char **argv) {
// parent buf
char write_msg_p[SIZE];
memcpy(write_msg_p, argv[1], strlen(argv[1]));
char read_msg_p[SIZE];
// child buf
char write_msg_c[SIZE];
char read_msg_c[SIZE];
int fd_p[2]; // parent pipe
int fd_c[2]; // child pipe
pid_t pid;
/* create the pipe */
if ((pipe(fd_p) == -1) || (pipe(fd_c) == -1)) {
perror("pipe");
return 1;
}
pid = fork(); // fork child process
if (pid < 0) { // error
perror("fork");
return 1;
}
if (pid > 0) { // parent 1
write_pipe(fd_p, write_msg_p);
wait(NULL);
read_pipe(fd_c, read_msg_c);
printf("parent: read '%s'\n", read_msg_c);
}
if (pid == 0 ) { // child 2
read_pipe(fd_p, read_msg_p);
printf("child: read '%s'\n", read_msg_p);
int c = 0;
char ch;
while (read_msg_p[c] != '\0') {
ch = read_msg_p[c];
if (ch >= 'A' && ch <= 'Z')
write_msg_p[c] += 32;
else if (ch >= 'a' && ch <= 'z')
write_msg_p[c] -= 32;
c++;
}
write_pipe(fd_c, write_msg_p);
}
return 0;
}
void write_pipe(int *fd, char *write_msg) {
close(fd[READ_END]);
write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
close(fd[WRITE_END]);
}
void read_pipe(int *fd, char *read_msg) {
close(fd[WRITE_END]);
read(fd[READ_END], read_msg, SIZE);
close(fd[READ_END]);
}
|
lusm554/operating-system-concepts | src/chapter-2/Programming-Problems/FileCopy.c | #include <stdio.h>
#include <unistd.h>
/*
Write cp program using either the POSIX or Windows API.
Be sure to include all necessary error checking, including ensuring that the source file exists.
Input:
1. source file
2. destination file
*/
#define ENOENT 64 // machine is not on the network (args < 2)
#define EPERM 1 // operation not permitted (source not exist)
int main(int argc, char *argv[]) {
// check amount of args
if (argc != 3) return ENOENT;
char *src = argv[1];
char *dest = argv[2];
// check file existence
if (access(src, F_OK) != 0) return EPERM;
// Read
FILE *inputp;
int inputcc;
inputp = fopen(src, "r");
// Write
FILE *outputp;
outputp = fopen(dest, "w");
// Copy data
while ((inputcc = fgetc(inputp)) != EOF)
fputc(inputcc, outputp);
fclose(inputp);
fclose(outputp);
return 0;
}
|
barikang/npk | libnpk/external/tea/tea.h | /* TEA code from http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html */
void tea_encode(unsigned char* v, int* k);
void tea_decode(unsigned char* v, int* k);
void tea_encode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains);
void tea_decode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains);
|
barikang/npk | libnpk/tests/testutil.h | /* testutil.h from haje01's GX library */
#ifndef __TESTUTIL_H__
#define __TESTUTIL_H__
#include <iostream>
#include <fcntl.h>
#if defined( WIN32 )
#include <io.h>
#pragma warning ( disable : 4819 )
#pragma warning ( disable : 4996 )
#else
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#if defined( WIN32 )
#define CHECK(x) \
{if(!(x)) { printf("Assertion Failed : %s, %d\n",__FILE__,__LINE__); \
__debugbreak(); }}
#else
#define CHECK(x) \
{if(!(x)) { printf("Assertion Failed : %s, %d\n",__FILE__,__LINE__); \
__asm__("int $0x03");}}
#endif
#define CHECK_CLOSE( M_A, M_B, M_EPSILON ) \
CHECK( fabs( M_A - M_B ) < M_EPSILON );
#define CHECK_EQUAL( M_A, M_B ) \
CHECK( M_A == M_B )
#define CHECK_EQUAL_STR( M_A, M_B ) \
CHECK( strcmp((M_A), (M_B)) == 0 )
#define CHECK_EQUAL_STR_SIZE( M_A, M_B, S ) \
CHECK( strncmp((M_A), (M_B), (S)) == 0 )
static void CHECK_EQUAL_STR_WITH_FILE( const char* src, const char* filename )
{
int h;
char* buf;
size_t size;
h = open( filename, O_RDONLY | O_BINARY );
CHECK( h >= 0 );
size = lseek( h, 0, SEEK_END );
CHECK( size != 0 );
lseek( h, 0, SEEK_SET );
buf = (char*)malloc( size+1 );
CHECK( buf != NULL );
// put '\0' at last
((char*)buf)[size] = '\0';
CHECK_EQUAL( size, read( h, buf, size ) );
CHECK_EQUAL_STR_SIZE( buf, src, size );
free( buf );
close( h );
}
static void CHECK_EQUAL_STR_WITH_FILE_PARTIAL( const char* src, const char* filename, size_t offset, size_t size )
{
int h;
char* buf;
h = open( filename, O_RDONLY | O_BINARY );
CHECK( h >= 0 );
lseek( h, offset, SEEK_SET );
buf = (char*)malloc( size+1 );
CHECK( buf != NULL );
CHECK_EQUAL( size, read( h, buf, size ) );
CHECK_EQUAL_STR_SIZE( src, buf, size );
free( buf );
close( h );
}
#endif // __TESTUTIL_H__
|
barikang/npk | npk/cli/helper_bstrcmp.h | <reponame>barikang/npk<filename>npk/cli/helper_bstrcmp.h
/* created by <EMAIL> */
// msdos-like wildcard comparator
bool b_strcmp( const char* s, const char* d, bool casesensitive = true )
{
bool asterisk = false;
int sPos = 0, dPos = 0;
if( !s || !d ) return false;
while(1)
{
if( s[sPos] == '*' )
{
++sPos;
asterisk = true;
}
if( ( s[sPos] != d[dPos] ) && ( s[sPos] != '?' ) && !asterisk )
{
// big and small letter check
if( !casesensitive )
{
if( s[sPos] >= 'a' && s[sPos] <= 'z' && d[dPos] >= 'A' && d[dPos] <= 'Z' )
{
if( (s[sPos] - 32) != d[dPos] )
return false;
}
else if( s[sPos] >= 'A' && s[sPos] <= 'Z' && d[dPos] >= 'a' && d[dPos] <= 'z' )
{
if( (s[sPos] + 32) != d[dPos] )
return false;
}
else
return false;
}
else
return false;
}
else if( s[sPos] =='\0' )
{
if( d[dPos] != '\0' && !asterisk )
return false;
else
break;
}
else
{
if( d[dPos] == '\0' )
return false;
}
if( asterisk )
{
if( d[dPos] == s[sPos] )
{
asterisk = false;
++sPos;
}
}
else
++sPos;
++dPos;
}
return true;
}
bool b_strncmp( const char* s, const char* d, size_t dlength, bool casesensitive = true )
{
bool asterisk = false;
int sPos = 0, dPos = 0;
if( !s || !d ) return false;
for(;;)
{
if( s[sPos] == '*' )
{
++sPos;
asterisk = true;
}
char dChar = '\0';
if ( (unsigned int)( dPos ) < dlength )
{
dChar = d[dPos];
}
if( ( s[sPos] != dChar ) && ( s[sPos] != '?' ) && !asterisk )
{
// big and small letter check
if( !casesensitive )
{
if( s[sPos] >= 'a' && s[sPos] <= 'z' && dChar >= 'A' && dChar <= 'Z' )
{
if( (s[sPos] - 32) != dChar )
return false;
}
else if( s[sPos] >= 'A' && s[sPos] <= 'Z' && dChar >= 'a' && dChar <= 'z' )
{
if( (s[sPos] + 32) != dChar )
return false;
}
else
return false;
}
else
return false;
}
else if( s[sPos] =='\0' )
{
if( dChar != '\0' && !asterisk )
return false;
else
break;
}
else
{
if( dChar == '\0' )
return false;
}
if( asterisk )
{
if( d[dPos] == s[sPos] )
{
asterisk = false;
++sPos;
}
}
else
++sPos;
++dPos;
}
return true;
}
bool b_strcmp_path_delimited( const char* s, const char* d, char delimiter, bool casesensitive = true )
{
if( !s || !d ) return false;
const char* begin = d;
const char* end = d;
for ( ; ; )
{
for( ; *end != '\0' && *end != delimiter ; ++end ) {}
if ( b_strncmp( s, begin, end - begin, casesensitive ) )
{
return true;
}
if ( *end == '\0' )
{
break;
}
++end;
begin = end;
}
return false;
}
|
barikang/npk | libnpk/external/tea/tea.c | <gh_stars>10-100
#include <sys/types.h>
#include <stddef.h>
#ifdef NPK_DEV
void tea_encode(unsigned char* c, int* k)
{
unsigned int y, z, sum=0, delta=0x9e3779b9, n=32;
y = c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24;
z = c[4] | c[5] << 8 | c[6] << 16 | c[7] << 24;
while (n-->0) {
sum += delta;
y += (z<<4)+k[0] ^ z+sum ^ (z>>5)+k[1];
z += (y<<4)+k[2] ^ y+sum ^ (y>>5)+k[3];
}
c[0] = y & 0xFF;
c[1] = y >> 8 & 0xFF;
c[2] = y >> 16 & 0xFF;
c[3] = y >> 24 & 0xFF;
c[4] = z & 0xFF;
c[5] = z >> 8 & 0xFF;
c[6] = z >> 16 & 0xFF;
c[7] = z >> 24 & 0xFF;
}
void tea_encode_byte(unsigned char* v, int* k, off_t p)
{
unsigned char y[] = "NpK!TeA";
*v = *v^y[p]^(unsigned char)(k[p%4]%0xFF);
}
void tea_encode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains)
{
unsigned char *p;
off_t remain = in_size % 8;
off_t align_size = in_size - remain;
for (p = in_buffer; p < in_buffer + align_size; p += 8)
tea_encode(p, key);
if( remain > 0 && cipherRemains )
for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1)
tea_encode_byte( p, key, --remain );
}
#endif
void tea_decode(unsigned char* c,int* k)
{
unsigned int n=32, sum, y, z, delta=0x9e3779b9;
y = c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24;
z = c[4] | c[5] << 8 | c[6] << 16 | c[7] << 24;
sum=delta<<5 ;
/* start cycle */
while (n-->0) {
z-= (y<<4)+k[2] ^ y+sum ^ (y>>5)+k[3];
y-= (z<<4)+k[0] ^ z+sum ^ (z>>5)+k[1];
sum-=delta ; }
/* end cycle */
c[0] = y & 0xFF;
c[1] = y >> 8 & 0xFF;
c[2] = y >> 16 & 0xFF;
c[3] = y >> 24 & 0xFF;
c[4] = z & 0xFF;
c[5] = z >> 8 & 0xFF;
c[6] = z >> 16 & 0xFF;
c[7] = z >> 24 & 0xFF;
}
void tea_decode_byte(unsigned char* v, int* k, off_t p)
{
unsigned char y[] = "NpK!TeA";
*v = *v^(unsigned char)(k[p%4]%0xFF)^y[p];
}
void tea_decode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains)
{
unsigned char *p;
off_t remain = in_size % 8;
off_t align_size = in_size - remain;
for (p = in_buffer; p < in_buffer + align_size; p += 8)
tea_decode(p, key);
if( remain > 0 && cipherRemains )
for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1)
tea_decode_byte( p, key, --remain );
}
|
barikang/npk | libnpk/external/xxtea/xxtea.c | #include <sys/types.h>
#include <stddef.h>
#define DELTA 0x9e3779b9
#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)))
#ifdef NPK_DEV
void xxtea_encode(unsigned char* c, int* k)
{
unsigned int n = 2;
unsigned int v[2];
unsigned int y, z, sum;
unsigned int p, rounds, e;
v[0] = c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24;
v[1] = c[4] | c[5] << 8 | c[6] << 16 | c[7] << 24;
rounds = 6 + 52/n;
sum = 0;
z = v[n-1];
do {
sum += DELTA;
e = (sum >> 2) & 3;
for (p=0; p<n-1; p++) {
y = v[p+1];
z = v[p] += MX;
}
y = v[0];
z = v[n-1] += MX;
} while (--rounds);
c[0] = v[0] & 0xFF;
c[1] = v[0] >> 8 & 0xFF;
c[2] = v[0] >> 16 & 0xFF;
c[3] = v[0] >> 24 & 0xFF;
c[4] = v[1] & 0xFF;
c[5] = v[1] >> 8 & 0xFF;
c[6] = v[1] >> 16 & 0xFF;
c[7] = v[1] >> 24 & 0xFF;
}
void xxtea_encode_byte(unsigned char* v, int* k, off_t p)
{
unsigned char y[] = "XtEaNpK";
*v = *v^y[p]^(unsigned char)(k[p%4]%0xFF);
}
void xxtea_encode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains)
{
unsigned char *p;
off_t remain = in_size % 8;
off_t align_size = in_size - remain;
for (p = in_buffer; p < in_buffer + align_size; p += 8)
xxtea_encode(p, key);
if( remain > 0 && cipherRemains )
for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1)
xxtea_encode_byte( p, key, --remain );
}
#endif
void xxtea_decode(unsigned char* c,int* k)
{
unsigned int n = 2;
unsigned int v[2];
unsigned int y, z, sum;
unsigned int p, rounds, e;
v[0] = c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24;
v[1] = c[4] | c[5] << 8 | c[6] << 16 | c[7] << 24;
rounds = 6 + 52/n;
sum = rounds*DELTA;
y = v[0];
while (sum != 0) {
e = (sum >> 2) & 3;
for (p=n-1; p>0; p--) {
z = v[p-1];
y = v[p] -= MX;
}
z = v[n-1];
y = v[0] -= MX;
sum -= DELTA;
}
c[0] = v[0] & 0xFF;
c[1] = v[0] >> 8 & 0xFF;
c[2] = v[0] >> 16 & 0xFF;
c[3] = v[0] >> 24 & 0xFF;
c[4] = v[1] & 0xFF;
c[5] = v[1] >> 8 & 0xFF;
c[6] = v[1] >> 16 & 0xFF;
c[7] = v[1] >> 24 & 0xFF;
}
void xxtea_decode_byte(unsigned char* v, int* k, off_t p)
{
unsigned char y[] = "XtEaNpK";
*v = *v^(unsigned char)(k[p%4]%0xFF)^y[p];
}
void xxtea_decode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains)
{
unsigned char *p;
off_t remain = in_size % 8;
off_t align_size = in_size - remain;
for (p = in_buffer; p < in_buffer + align_size; p += 8)
xxtea_decode(p, key);
if( remain > 0 && cipherRemains )
for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1)
xxtea_decode_byte( p, key, --remain );
}
|
barikang/npk | libnpk/include/npk_base.h | /*
npk - neat package system
See README for copyright and license information.
base type and definitions of npk
*/
#include <stddef.h>
#include "npk_conf.h"
#ifndef _NPK_BASE_H_
#define _NPK_BASE_H_
// Type
typedef int NPK_RESULT;
typedef void* NPK_PACKAGE;
typedef void* NPK_ENTITY;
typedef int NPK_HANDLE;
typedef unsigned int NPK_FLAG;
typedef unsigned int NPK_HASHKEY;
typedef int NPK_TEAKEY;
typedef char NPK_CHAR;
typedef const NPK_CHAR* NPK_CSTR;
typedef NPK_CHAR* NPK_STR;
typedef unsigned int NPK_SIZE;
typedef off_t NPK_OFFSET;
typedef unsigned short NPK_NAMESIZE;
typedef char NPK_BYTE;
typedef unsigned long long NPK_64BIT;
typedef int NPK_TIME;
// NPK
#define NPK_SIGNATURE "NPK!"
#define NPK_OLD_SIGNATURE "NPAK"
#define NPK_SIGNATURE_LENGTH 4
#define NPK_MAXFOLDERNFILENAME 512
#define NPK_MIN_SIZE_ZIPABLE 256
#define NPK_HASH_BUCKETS 257
// Version Information
#define NPK_VERSION_SINGLEPACKHEADER 24
#define NPK_VERSION_ENCRYPTREMAINS 25
#define NPK_VERSION_USEXXTEAONHEADER 26
#define NPK_VERSION_STREAMABLE 27
#define NPK_VERSION_MINIMUM NPK_VERSION_SINGLEPACKHEADER
#define NPK_VERSION_CURRENT NPK_VERSION_STREAMABLE
// Entity Flag
#define NPK_ENTITY_NULL 0
#define NPK_ENTITY_TEXTFILE 0x00000001 // NOT USED
#define NPK_ENTITY_ENCRYPT_XXTEA 0x00000010 // Encrypted by XXTEA
#define NPK_ENTITY_ENCRYPT_TEA 0x00000100 // Encrypted by TEA
#define NPK_ENTITY_COMPRESS_ZLIB 0x00001000 // Compressed by zlib
#define NPK_ENTITY_REVERSE 0x00100000 // Encryption & Compression order.(0=E->C,1=C->E)
#define NPK_ENTITY_INHERIT 0xF0000000
// Callback
#define NPK_ACCESSTYPE_READ 0
#define NPK_ACCESSTYPE_WRITE 1
#define NPK_PROCESSTYPE_FILE 0
#define NPK_PROCESSTYPE_ENTITYHEADER 1
#define NPK_PROCESSTYPE_ENTITY 2
#define NPK_PROCESSTYPE_PACKAGEHEADER 3
#define NPK_PROCESSTYPE_PACKAGE 4
typedef int( *NPK_CALLBACK )( int accessType,
int processType,
NPK_CSTR identifier,
NPK_OFFSET current,
NPK_OFFSET total
);
#endif /* _NPK_BASE_H_ */
|
barikang/npk | libnpk/include/npk.h | <reponame>barikang/npk
/*
npk - neat package system
See README for copyright and license information.
*/
#ifndef _NPK_H_
#define _NPK_H_
#include "npk_conf.h"
#include "npk_base.h"
#include "npk_error.h"
#ifdef __cplusplus
extern "C" {
#endif
extern NPK_API int g_npkError;
extern NPK_API int g_useCriticalSection;
NPK_API NPK_PACKAGE npk_package_open ( NPK_CSTR filename, NPK_TEAKEY teakey[4] );
NPK_API NPK_PACKAGE npk_package_open_with_fd ( NPK_CSTR name, int fd, long offset, long size, NPK_TEAKEY teakey[4] );
NPK_API bool npk_package_close ( NPK_PACKAGE package );
NPK_API NPK_ENTITY npk_package_get_entity ( NPK_PACKAGE package, NPK_CSTR entityname );
NPK_API NPK_ENTITY npk_package_get_first_entity( NPK_PACKAGE package );
NPK_API NPK_CSTR npk_entity_get_name ( NPK_ENTITY entity );
NPK_API NPK_SIZE npk_entity_get_size ( NPK_ENTITY entity );
NPK_API NPK_SIZE npk_entity_get_packed_size ( NPK_ENTITY entity );
NPK_API NPK_SIZE npk_entity_get_offset ( NPK_ENTITY entity );
NPK_API bool npk_entity_is_ready ( NPK_ENTITY entity );
NPK_API NPK_ENTITY npk_entity_next ( NPK_ENTITY entity );
NPK_API bool npk_entity_read ( NPK_ENTITY entity, void* buf );
NPK_API bool npk_entity_read_partial ( NPK_ENTITY entity, void* buf, NPK_SIZE offset, NPK_SIZE size );
NPK_API void npk_enable_callback ( NPK_CALLBACK cb, NPK_SIZE cb_size );
NPK_API void npk_disable_callback ();
NPK_API NPK_STR npk_error_to_str ( NPK_RESULT res );
NPK_API void npk_enable_criticalsection ();
NPK_API void npk_disable_criticalsection ();
// custom file I/O
typedef void* (*npk_open_func) (const char*, const char*); // filename, mode as per fopen (ie "r" "wb+" etc)
typedef int (*npk_close_func) (void*);
typedef size_t (*npk_read_func) (void*, size_t, size_t, void*);
typedef size_t (*npk_write_func) (const void*, size_t, size_t, void*);
typedef off_t (*npk_seek_func) (void*, off_t, int);
typedef long (*npk_tell_func) (void*);
typedef void (*npk_rewind_func)(void*);
typedef void (*npk_commit_func)(void*);
NPK_API void npk_io_open_func (npk_open_func func);
NPK_API void npk_io_close_func (npk_close_func func);
NPK_API void npk_io_read_func (npk_read_func func);
NPK_API void npk_io_write_func (npk_write_func func);
NPK_API void npk_io_seek_func (npk_seek_func func);
NPK_API void npk_io_tell_func (npk_tell_func func);
NPK_API void npk_io_rewind_func(npk_rewind_func func);
NPK_API void npk_io_commit_func(npk_commit_func func);
#ifdef __cplusplus
}
#endif
#endif /* _NPK_H_ */
|
barikang/npk | libnpk/include/npk_dev.h | <reponame>barikang/npk
/*
npk - neat package system
See README for copyright and license information.
header for npk development mode
*/
#ifndef _NPK_DEV_H_
#define _NPK_DEV_H_
#include "npk_conf.h"
#include "npk_base.h"
#include "npk_error.h"
#ifdef NPK_PLATFORM_WINDOWS
#include <windows.h>
#endif
#define NPK_SAFE_FREE(x) if(x) { free(x); x = NULL; }
#pragma pack(push, 4)
/* Structures */
typedef struct NPK_DEV_API NPK_tagENTITYINFO
{
NPK_SIZE offset_; /* Data position. */
NPK_SIZE size_; /* Data size. */
NPK_SIZE originalSize_; /* Original size. */
NPK_FLAG flag_; /* Composite of EntityFlag. ( see npk_base.h ) */
NPK_TIME modified_; /* Last modified date of entity - 32bit time_t */
NPK_BYTE reserved_[4]; /* Reserved for 64bit-time_t */
NPK_NAMESIZE nameLength_; /* Length of Foldername + FileName. */
} NPK_ENTITYINFO, *NPK_LPENTITYINFO;
typedef struct NPK_DEV_API NPK_tagENTITYBODY
{
NPK_ENTITYINFO info_;
NPK_FLAG newflag_; /* New entity flags */
NPK_STR name_; /* Foldername + FileName. */
NPK_STR localname_; /* Local Foldername + FileName. */
NPK_PACKAGE owner_;
struct NPK_tagENTITYBODY* prev_;
struct NPK_tagENTITYBODY* next_;
struct NPK_tagENTITYBODY* prevInBucket_;
struct NPK_tagENTITYBODY* nextInBucket_;
} NPK_ENTITYBODY, *NPK_LPENTITYBODY;
typedef struct NPK_DEV_API NPK_tagPACKAGEINFO
{
NPK_CHAR signature_[4]; /* NPAK */
int version_; /* Package version. */
NPK_SIZE entityCount_; /* Quantity of entities. */
NPK_SIZE entityInfoOffset_; /* Entities' information offset. */
NPK_SIZE entityDataOffset_; /* Entities' data offset. */
NPK_TIME modified_; /* Last modified date of package - 32bit time_t */
} NPK_PACKAGEINFO, *NPK_LPPACKAGEINFO;
typedef struct NPK_DEV_API NPK_tagBUCKET
{
NPK_LPENTITYBODY pEntityHead_;
NPK_LPENTITYBODY pEntityTail_;
} NPK_BUCKET, *NPK_LPBUCKET;
typedef struct NPK_DEV_API NPK_tagPACKAGEBODY
{
NPK_PACKAGEINFO info_;
NPK_TIME modified_;
NPK_HANDLE handle_; /* File handle. */
NPK_TEAKEY teakey_[4];
NPK_LPENTITYBODY pEntityHead_;
NPK_LPENTITYBODY pEntityTail_;
NPK_LPENTITYBODY pEntityLatest_;
#ifdef _WIN32
CRITICAL_SECTION cs_;
#endif
NPK_LPBUCKET bucket_[NPK_HASH_BUCKETS];
bool usingHashmap_;
bool usingFdopen_;
long offsetJump_;
} NPK_PACKAGEBODY, *NPK_LPPACKAGEBODY;
#pragma pack(pop)
#ifdef __cplusplus
extern "C" {
#endif
extern NPK_DEV_API NPK_CALLBACK g_callbackfp;
extern NPK_DEV_API NPK_OFFSET g_callbackSize;
/* Helper Functions */
NPK_DEV_API void npk_log( NPK_CSTR format, ... );
NPK_DEV_API NPK_RESULT npk_error( NPK_RESULT res );
NPK_DEV_API NPK_RESULT npk_alloc_copy_string( NPK_STR* dst, NPK_CSTR src );
NPK_DEV_API NPK_RESULT npk_get_filetime( NPK_CSTR filename, NPK_TIME* pft );
NPK_DEV_API NPK_RESULT npk_set_filetime( NPK_CSTR filename, const NPK_TIME pft );
NPK_DEV_API void npk_filetime_to_unixtime( NPK_64BIT* pft, NPK_TIME* pt );
NPK_DEV_API void npk_enable_gluetime( NPK_TIME time );
NPK_DEV_API void npk_disable_gluetime();
NPK_DEV_API NPK_HASHKEY npk_get_bucket( NPK_CSTR name );
NPK_DEV_API NPK_RESULT npk_prepare_entityname( NPK_CSTR src, NPK_STR dst, size_t dstLen );
/* File I/O Functions */
NPK_DEV_API NPK_RESULT npk_open( NPK_HANDLE* handle, NPK_CSTR fileName, bool createfile, bool bcheckexist );
NPK_DEV_API NPK_RESULT npk_flush( NPK_HANDLE handle );
NPK_DEV_API NPK_RESULT npk_close( NPK_HANDLE handle );
NPK_DEV_API NPK_OFFSET npk_seek( NPK_HANDLE handle, off_t offset, int origin );
NPK_DEV_API NPK_OFFSET npk_tell( NPK_HANDLE handle );
NPK_DEV_API NPK_RESULT npk_read( NPK_HANDLE handle, void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier );
NPK_DEV_API NPK_RESULT npk_write( NPK_HANDLE handle, const void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier );
NPK_DEV_API NPK_RESULT npk_read_encrypt( NPK_TEAKEY* key, NPK_HANDLE handle, void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier,
bool cipherRemains, bool useXXTEA );
NPK_DEV_API NPK_RESULT npk_write_encrypt( NPK_TEAKEY* key, NPK_HANDLE handle, const void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier,
bool cipherRemains, bool useXXTEA );
/* Entity Functions */
NPK_DEV_API NPK_RESULT npk_entity_alloc( NPK_ENTITY* lpEntity );
NPK_DEV_API NPK_RESULT npk_entity_init( NPK_ENTITY entity );
NPK_DEV_API NPK_RESULT npk_entity_get_current_flag( NPK_ENTITY entity, NPK_FLAG* flag );
NPK_DEV_API NPK_RESULT npk_entity_get_new_flag( NPK_ENTITY entity, NPK_FLAG* flag );
NPK_DEV_API NPK_RESULT npk_entity_set_flag( NPK_ENTITY entity, NPK_FLAG flag );
NPK_DEV_API NPK_RESULT npk_entity_add_flag( NPK_ENTITY entity, NPK_FLAG flag );
NPK_DEV_API NPK_RESULT npk_entity_sub_flag( NPK_ENTITY entity, NPK_FLAG flag );
NPK_DEV_API NPK_RESULT npk_entity_write( NPK_ENTITY entity, NPK_HANDLE handle, bool forceProcessing );
NPK_DEV_API NPK_RESULT npk_entity_export( NPK_ENTITY entity, NPK_CSTR filename, bool forceOverwrite );
/* Package Functions */
NPK_DEV_API NPK_RESULT npk_package_alloc( NPK_PACKAGE* lpPackage, NPK_TEAKEY teakey[4] );
NPK_DEV_API NPK_RESULT npk_package_init( NPK_PACKAGE package );
NPK_DEV_API NPK_RESULT npk_package_save( NPK_PACKAGE package, NPK_CSTR filename, bool forceOverwrite );
NPK_DEV_API NPK_RESULT npk_package_clear( NPK_PACKAGE package );
NPK_DEV_API NPK_RESULT npk_package_add_file( NPK_PACKAGE package, NPK_CSTR filename, NPK_CSTR entityname, NPK_ENTITY* lpEntity );
NPK_DEV_API NPK_RESULT npk_package_add_entity( NPK_PACKAGE package, NPK_ENTITY entity );
NPK_DEV_API NPK_RESULT npk_package_remove_entity( NPK_PACKAGE package, NPK_ENTITY entity );
NPK_DEV_API NPK_RESULT npk_package_detach_entity( NPK_PACKAGE package, NPK_ENTITY entity );
NPK_DEV_API NPK_RESULT npk_package_remove_all_entity( NPK_PACKAGE package );
NPK_DEV_API NPK_RESULT npk_package_detach_all_entity( NPK_PACKAGE package );
NPK_DEV_API void npk_package_lock( NPK_PACKAGE package );
NPK_DEV_API void npk_package_free( NPK_PACKAGE package );
/* For FFI */
NPK_DEV_API NPK_ENTITY _npk_entity_alloc();
NPK_DEV_API NPK_ENTITY _npk_package_add_file( NPK_PACKAGE package, NPK_CSTR filename, NPK_CSTR entityname );
NPK_DEV_API NPK_PACKAGE _npk_package_alloc( NPK_TEAKEY teakey[4] );
/* Custom file handler */
extern npk_open_func __open;
extern npk_close_func __close;
extern npk_read_func __read;
extern npk_write_func __write;
extern npk_seek_func __seek;
extern npk_tell_func __tell;
extern npk_rewind_func __rewind;
extern npk_commit_func __commit;
extern bool __use_open;
extern bool __use_close;
extern bool __use_read;
extern bool __use_write;
extern bool __use_seek;
extern bool __use_tell;
extern bool __use_rewind;
extern bool __use_commit;
#ifdef __cplusplus
}
#endif
#endif /* _NPK_DEV_H_ */
|
barikang/npk | libnpk/include/npk_error.h | /*
npk - neat package system
See README for copyright and license information.
npk error code
*/
#ifndef _NPK_ERROR_H_
#define _NPK_ERROR_H_
// Success
#define NPK_SUCCESS 1
// Error
#define NPK_ERROR 0
#define NPK_ERROR_FileNotFound -1
#define NPK_ERROR_FileOpenError -2
#define NPK_ERROR_FileSaveError -3
#define NPK_ERROR_FileReadError -4
#define NPK_ERROR_PermissionDenied -5
#define NPK_ERROR_ReadOnlyFile -6
#define NPK_ERROR_FailToGetFiletime -7
#define NPK_ERROR_NotValidFileName -8
#define NPK_ERROR_NotValidPackage -9
#define NPK_ERROR_CannotFindEntity -10
#define NPK_ERROR_CannotCreateFile -11
#define NPK_ERROR_PackageHasNoName -12
#define NPK_ERROR_PackageHasNoVersion -13
#define NPK_ERROR_ZeroFileSize -14
#define NPK_ERROR_SameEntityExist -15
#define NPK_ERROR_FailToSetFiletime -17
#define NPK_ERROR_NotValidEntity -18
#define NPK_ERROR_NotValidEntityName -20
#define NPK_ERROR_OpenedPackage -25
#define NPK_ERROR_NotOpenedPackage -26
#define NPK_ERROR_SamePackageExist -27
#define NPK_ERROR_NonAllocatedBuffer -28
#define NPK_ERROR_NullPointerBuffer -29
#define NPK_ERROR_FailToDecompress -30
#define NPK_ERROR_AlreadyAllocated -31
#define NPK_ERROR_NonStaticPackage -32
#define NPK_ERROR_NeedSpecifiedTeaKey -33
#define NPK_ERROR_EntityIsNull -40
#define NPK_ERROR_PackageIsNull -41
#define NPK_ERROR_EntityIsNotInThePackage -42
#define NPK_ERROR_CantReadCompressedEntityByPartial -43
#define NPK_ERROR_SourceStringisNull -44
#define NPK_ERROR_CannotCopyToItself -45
#define NPK_ERROR_FileAlreadyExists -46
#define NPK_ERROR_NoEntityInPackage -47
#define NPK_ERROR_ReadingEncryptedEntityByPartialShouldBeAligned -48
#define NPK_ERROR_InvalidTeaKey -50
#define NPK_ERROR_EntityIsNotReady -51
#define NPK_ERROR_PackageIsNotReady -52
#define NPK_ERROR_NotEnoughMemory -100
#define NPK_ERROR_NotEnoughDiscSpace -101
#define NPK_ERROR_CannotFindPackage -103
#define NPK_ERROR_CancelByCallback -200
#define NPK_ERROR_NotSupportedVersion -255
#endif /*_NPK_ERROR_H_*/
|
barikang/npk | npk/cli/helper_dirent.c | /*
Implementation of POSIX directory browsing functions and types for Win32.
Author: <NAME> (<EMAIL>, <EMAIL>)
History: Created March 1997. Updated June 2003.
Rights: See end of file.
*/
#include "helper_dirent.h"
#include <errno.h>
#include <io.h> /* _findfirst and _findnext set errno iff they return -1 */
#include <stdlib.h>
#include <string.h>
#pragma warning( disable : 4996 )
#ifdef __cplusplus
extern "C"
{
#endif
struct DIR
{
long handle; /* -1 for failed rewind */
struct _finddata_t info;
struct dirent result; /* d_name null iff first time */
char *name; /* null-terminated char string */
};
DIR *opendir(const char *name)
{
DIR *dir = 0;
if(name && name[0])
{
size_t base_length = strlen(name);
const char *all = /* search pattern must end with suitable wildcard */
strchr("/\\", name[base_length - 1]) ? "*" : "/*";
if((dir = (DIR *) malloc(sizeof *dir)) != 0 &&
(dir->name = (char *) malloc(base_length + strlen(all) + 1)) != 0)
{
strcat(strcpy(dir->name, name), all);
if((dir->handle = (long) _findfirst(dir->name, &dir->info)) != -1)
{
dir->result.d_name = 0;
}
else /* rollback */
{
free(dir->name);
free(dir);
dir = 0;
}
}
else /* rollback */
{
free(dir);
dir = 0;
errno = ENOMEM;
}
}
else
{
errno = EINVAL;
}
return dir;
}
int closedir(DIR *dir)
{
int result = -1;
if(dir)
{
if(dir->handle != -1)
{
result = _findclose(dir->handle);
}
free(dir->name);
free(dir);
}
if(result == -1) /* map all errors to EBADF */
{
errno = EBADF;
}
return result;
}
struct dirent *readdir(DIR *dir)
{
struct dirent *result = 0;
if(dir && dir->handle != -1)
{
if(!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1)
{
result = &dir->result;
result->d_name = dir->info.name;
}
}
else
{
errno = EBADF;
}
return result;
}
void rewinddir(DIR *dir)
{
if(dir && dir->handle != -1)
{
_findclose(dir->handle);
dir->handle = (long) _findfirst(dir->name, &dir->info);
dir->result.d_name = 0;
}
else
{
errno = EBADF;
}
}
#ifdef __cplusplus
}
#endif
/*
Copyright <NAME>, 1997, 2003. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose is hereby granted without fee, provided
that this copyright and permissions notice appear in all copies and
derivatives.
This software is supplied "as is" without express or implied warranty.
But that said, if there are any problems please get in touch.
*/
|
barikang/npk | libnpk/external/xxtea/xxtea.h | <reponame>barikang/npk
/* Corrected Block TEA code from http://en.wikipedia.org/wiki/XXTEA */
void xxtea_encode(unsigned char* v, int* k);
void xxtea_decode(unsigned char* v, int* k);
void xxtea_encode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains);
void xxtea_decode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains);
|
barikang/npk | libnpk/src/npk.c | /*
npk - neat package system
See README for copyright and license information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include "npk.h"
#include "npk_dev.h"
#ifdef NPK_PLATFORM_MACOS
#include <strings.h>
#else
#include <string.h>
#endif
#include "../external/tea/tea.h"
#include "../external/xxtea/xxtea.h"
#include "../external/zlib/zlib.h"
NPK_API int g_npkError = 0; /* this variable has no multi-thread safety */
NPK_API int g_useCriticalSection = 0;
#ifdef NPK_PLATFORM_WINDOWS
#pragma warning( disable : 4996 )
#else
#define strnicmp strncasecmp
#define stricmp strcasecmp
#endif
NPK_CALLBACK g_callbackfp;
NPK_OFFSET g_callbackSize;
NPK_RESULT __npk_package_add_entity( NPK_PACKAGE package, NPK_ENTITY entity, bool check );
NPK_RESULT __npk_package_open( NPK_PACKAGEBODY* pb, const NPK_CHAR* filename, NPK_OFFSET filesize, NPK_TEAKEY teakey[4] )
{
NPK_CHAR buf[512];
NPK_ENTITYBODY* eb = NULL;
NPK_SIZE entityCount = 0;
NPK_CHAR* entityheaderbuf;
NPK_CHAR* pos;
NPK_OFFSET entityheadersize = 0;
NPK_RESULT res;
if( filesize == 0 )
{
filesize = npk_seek( pb->handle_, 0, SEEK_END );
npk_seek( pb->handle_, 0, SEEK_SET );
}
if( filesize < sizeof(NPK_PACKAGEINFO) )
return( npk_error( NPK_ERROR_PackageIsNotReady ) );
// Read common header
res = npk_read( pb->handle_,
(void*)&pb->info_,
sizeof(NPK_PACKAGEINFO),
g_callbackfp,
NPK_PROCESSTYPE_PACKAGEHEADER,
g_callbackSize,
filename );
if( res != NPK_SUCCESS ) return res;
if( strncmp( pb->info_.signature_, NPK_SIGNATURE, 4 ) != 0 )
if( strncmp( pb->info_.signature_, NPK_OLD_SIGNATURE, 4 ) != 0 )
return( npk_error( NPK_ERROR_NotValidPackage ) );
if( pb->info_.version_ < NPK_VERSION_MINIMUM )
return ( npk_error( NPK_ERROR_NotSupportedVersion ) );
// Read own tea key
if( teakey == NULL )
return ( npk_error( NPK_ERROR_NeedSpecifiedTeaKey ) );
memcpy( pb->teakey_, teakey, sizeof(NPK_TEAKEY) * 4 );
entityCount = pb->info_.entityCount_;
pb->info_.entityCount_ = 0;
if( pb->info_.version_ >= NPK_VERSION_SINGLEPACKHEADER )
{
if( pb->info_.version_ >= NPK_VERSION_STREAMABLE )
{
if( filesize < (long)pb->info_.entityDataOffset_ )
return( npk_error( NPK_ERROR_PackageIsNotReady ) );
entityheadersize = (long)pb->info_.entityDataOffset_ - (long)pb->info_.entityInfoOffset_;
}
else
{
entityheadersize = filesize - (long)pb->info_.entityInfoOffset_;
npk_seek( pb->handle_, (long)pb->info_.entityInfoOffset_+pb->offsetJump_, SEEK_SET );
}
entityheaderbuf = malloc( (size_t)entityheadersize );
if( !entityheaderbuf )
return( npk_error( NPK_ERROR_NotEnoughMemory ) );
res = npk_read_encrypt( teakey,
pb->handle_,
(void*)entityheaderbuf,
entityheadersize,
g_callbackfp,
NPK_PROCESSTYPE_ENTITYHEADER,
g_callbackSize,
filename,
pb->info_.version_ >= NPK_VERSION_ENCRYPTREMAINS,
pb->info_.version_ >= NPK_VERSION_USEXXTEAONHEADER
);
if( res != NPK_SUCCESS ) return res;
pos = entityheaderbuf;
while( entityCount > 0 )
{
--entityCount;
res = npk_entity_alloc( (NPK_ENTITY*)&eb );
if( res != NPK_SUCCESS )
goto __npk_package_open_return_res_with_free;
eb->owner_ = pb;
memcpy( &eb->info_, pos, sizeof(NPK_ENTITYINFO) );
pos += sizeof(NPK_ENTITYINFO);
if( pb->info_.version_ < NPK_VERSION_STREAMABLE )
if( eb->info_.offset_ >= pb->info_.entityInfoOffset_ )
{
res = npk_error( NPK_ERROR_InvalidTeaKey );
goto __npk_package_open_return_res_with_free;
}
eb->newflag_ = eb->info_.flag_;
eb->name_ = malloc( sizeof(NPK_CHAR)*(eb->info_.nameLength_+1) );
if( !eb->name_ )
{
res = npk_error( NPK_ERROR_NotEnoughMemory );
goto __npk_package_open_return_res_with_free;
}
eb->name_[eb->info_.nameLength_] = '\0';
memcpy( eb->name_, pos, eb->info_.nameLength_ );
pos += eb->info_.nameLength_;
__npk_package_add_entity( pb, eb, false );
}
NPK_SAFE_FREE( entityheaderbuf );
}
else // old style entity header
{
npk_seek( pb->handle_, (long)pb->info_.entityInfoOffset_+pb->offsetJump_, SEEK_SET );
while( entityCount > 0 )
{
--entityCount;
res = npk_entity_alloc( (NPK_ENTITY*)&eb );
if( res != NPK_SUCCESS )
goto __npk_package_open_return_res_with_free;
eb->owner_ = pb;
res = npk_read_encrypt( teakey,
pb->handle_,
(void*)&eb->info_,
sizeof(NPK_ENTITYINFO),
g_callbackfp,
NPK_PROCESSTYPE_ENTITYHEADER,
g_callbackSize,
filename,
false,
false );
if( res != NPK_SUCCESS )
goto __npk_package_open_return_res_with_free;
if( eb->info_.offset_ >= pb->info_.entityInfoOffset_ )
{
res = npk_error( NPK_ERROR_InvalidTeaKey );
goto __npk_package_open_return_res_with_free;
}
res = npk_read_encrypt( teakey,
pb->handle_,
(void*)buf,
sizeof(char) * eb->info_.nameLength_,
g_callbackfp,
NPK_PROCESSTYPE_ENTITYHEADER,
g_callbackSize,
filename,
false,
false );
if( res != NPK_SUCCESS )
goto __npk_package_open_return_res_with_free;
eb->newflag_ = eb->info_.flag_;
// copy name into entity body
buf[eb->info_.nameLength_] = '\0';
res = npk_alloc_copy_string( &eb->name_, buf );
if( res != NPK_SUCCESS )
goto __npk_package_open_return_res_with_free;
__npk_package_add_entity( pb, eb, false );
}
}
return NPK_SUCCESS;
__npk_package_open_return_res_with_free:
NPK_SAFE_FREE( eb );
return res;
}
NPK_PACKAGE npk_package_open_with_fd( NPK_CSTR name, int fd, long offset, long size, NPK_TEAKEY teakey[4] )
{
NPK_PACKAGEBODY* pb = NULL;
if( NPK_SUCCESS != npk_package_alloc( (NPK_PACKAGE*)&pb, teakey ))
return NULL;
pb->handle_ = fd;
pb->usingFdopen_ = true;
pb->offsetJump_ = offset;
npk_seek( fd, offset, SEEK_CUR );
if( NPK_SUCCESS != __npk_package_open( pb, name, size, teakey ))
goto npk_package_open_return_null_with_free;
return (NPK_PACKAGE*)pb;
npk_package_open_return_null_with_free:
if( pb )
npk_package_close( pb );
return NULL;
}
NPK_PACKAGE npk_package_open( NPK_CSTR filename, NPK_TEAKEY teakey[4] )
{
NPK_PACKAGEBODY* pb = NULL;
if( NPK_SUCCESS != npk_package_alloc( (NPK_PACKAGE*)&pb, teakey ) )
return NULL;
if( NPK_SUCCESS != npk_open( &pb->handle_, filename, false, false ) )
goto npk_package_open_return_null_with_free;
if( NPK_SUCCESS != __npk_package_open( pb, filename, 0, teakey ))
goto npk_package_open_return_null_with_free;
return (NPK_PACKAGE*)pb;
npk_package_open_return_null_with_free:
if( pb )
npk_package_close( pb );
return NULL;
}
bool npk_package_close( NPK_PACKAGE package )
{
NPK_PACKAGEBODY* pb = (NPK_PACKAGEBODY*)package;
NPK_RESULT res;
int i;
if( !package )
{
npk_error( NPK_ERROR_PackageIsNull );
return false;
}
res = npk_package_remove_all_entity( pb );
if( NPK_SUCCESS != res )
return res;
#ifdef NPK_PLATFORM_WINDOWS
DeleteCriticalSection( &pb->cs_ );
#endif
if( false == pb->usingFdopen_ )
npk_close( pb->handle_ );
for( i = 0; i < NPK_HASH_BUCKETS; ++i )
NPK_SAFE_FREE( pb->bucket_[i] );
NPK_SAFE_FREE( pb );
return true;
}
NPK_ENTITY npk_package_get_entity( NPK_PACKAGE package, NPK_CSTR entityname )
{
NPK_ENTITYBODY* eb = NULL;
NPK_PACKAGEBODY* pb = package;
NPK_BUCKET* bucket = NULL;
NPK_CHAR buf[512];
if( !package )
{
npk_error( NPK_ERROR_PackageIsNull );
return NULL;
}
if( NPK_SUCCESS != npk_prepare_entityname( entityname, buf, 512 ) )
return NULL;
if( pb->usingHashmap_ )
{
bucket = pb->bucket_[npk_get_bucket(buf)];
if( bucket != NULL )
{
eb = bucket->pEntityHead_;
while( eb != NULL )
{
#ifdef NPK_CASESENSITIVE
if( strcmp( eb->name_, buf ) == 0 )
#else
if( stricmp( eb->name_, buf ) == 0 )
#endif
{
pb->pEntityLatest_ = eb;
return eb;
}
eb = eb->nextInBucket_;
}
}
}
else /* not usingHashmap_ */
{
eb = pb->pEntityHead_;
while( eb != NULL )
{
#ifdef NPK_CASESENSITIVE
if( strcmp( eb->name_, buf ) == 0 )
#else
if( stricmp( eb->name_, buf ) == 0 )
#endif
{
pb->pEntityLatest_ = eb;
return eb;
}
eb = eb->next_;
}
}
npk_error( NPK_ERROR_CannotFindEntity );
return NULL;
}
NPK_SIZE npk_entity_get_size( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return 0;
}
return eb->info_.originalSize_;
}
NPK_SIZE npk_entity_get_packed_size( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return 0;
}
return eb->info_.size_;
}
NPK_SIZE npk_entity_get_offset( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return 0;
}
return eb->info_.offset_;
}
NPK_CSTR npk_entity_get_name( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return 0;
}
return eb->name_;
}
bool npk_entity_is_ready( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
NPK_PACKAGEBODY* pb = NULL;
int res;
struct stat buf;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return false;
}
pb = eb->owner_;
res = fstat( pb->handle_, &buf );
if( (long)( pb->offsetJump_ + eb->info_.offset_ + eb->info_.size_ ) <= buf.st_size )
return true;
return false;
}
bool npk_entity_read( NPK_ENTITY entity, void* buf )
{
NPK_ENTITYBODY* eb = entity;
NPK_PACKAGEBODY* pb = NULL;
void** lplpTarget = &buf;
void* lpDecompressBuffer = NULL;
//NPK_SIZE uncompLen = 0;
unsigned long uncompLen = 0;
NPK_RESULT res;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return false;
}
if( eb->info_.flag_ & NPK_ENTITY_COMPRESS_ZLIB )
{
lpDecompressBuffer = malloc( sizeof(char) * eb->info_.size_ );
lplpTarget = &lpDecompressBuffer;
}
pb = eb->owner_;
npk_package_lock( pb );
npk_seek( pb->handle_, (long)eb->info_.offset_+pb->offsetJump_, SEEK_SET );
res = npk_read( pb->handle_,
(*lplpTarget),
eb->info_.size_,
g_callbackfp,
NPK_PROCESSTYPE_ENTITY,
g_callbackSize,
eb->name_ );
npk_package_free( pb );
if( res != NPK_SUCCESS )
goto npk_entity_read_return_with_free;
// Decode before uncompress, after v21
if( ( eb->info_.flag_ & NPK_ENTITY_ENCRYPT_TEA ) && ( eb->info_.flag_ & NPK_ENTITY_REVERSE ) )
tea_decode_buffer((unsigned char*)(*lplpTarget), eb->info_.size_, pb->teakey_, (pb->info_.version_ >= NPK_VERSION_ENCRYPTREMAINS));
if( eb->info_.flag_ & NPK_ENTITY_ENCRYPT_XXTEA )
xxtea_decode_buffer((unsigned char*)(*lplpTarget), eb->info_.size_, pb->teakey_, (pb->info_.version_ >= NPK_VERSION_ENCRYPTREMAINS));
if( eb->info_.flag_ & NPK_ENTITY_COMPRESS_ZLIB )
{
uncompLen = eb->info_.originalSize_;
if( uncompLen >= NPK_MIN_SIZE_ZIPABLE )
{
#ifdef Z_PREFIX
if( Z_OK != z_uncompress((Bytef*)(buf), (z_uLong*)&uncompLen, (const Bytef*)lpDecompressBuffer, (z_uLong)eb->info_.size_ ) )
#else
if( Z_OK != uncompress((Bytef*)(buf), (uLong*)&uncompLen, (const Bytef*)lpDecompressBuffer, (uLong)eb->info_.size_ ) )
#endif
{
npk_error( NPK_ERROR_FailToDecompress );
goto npk_entity_read_return_with_free;
}
if( eb->info_.originalSize_ != uncompLen )
{
npk_error( NPK_ERROR_FailToDecompress );
goto npk_entity_read_return_with_free;
}
}
else
memcpy( buf, lpDecompressBuffer, eb->info_.size_ );
NPK_SAFE_FREE( lpDecompressBuffer );
lplpTarget = &buf;
}
// Decode after uncompress, before v21
if( ( eb->info_.flag_ & NPK_ENTITY_ENCRYPT_TEA ) && !( eb->info_.flag_ & NPK_ENTITY_REVERSE ) )
tea_decode_buffer((unsigned char*)(*lplpTarget), eb->info_.originalSize_, pb->teakey_, false);
return true;
npk_entity_read_return_with_free:
NPK_SAFE_FREE( lpDecompressBuffer );
return false;
}
bool npk_entity_read_partial( NPK_ENTITY entity, void* buf, NPK_SIZE offset, NPK_SIZE size )
{
NPK_ENTITYBODY* eb = entity;
NPK_PACKAGEBODY* pb = NULL;
NPK_SIZE head_size = 0;
NPK_SIZE tail_size = 0;
NPK_SIZE body_size = 0;
NPK_SIZE remains = 0;
unsigned char temp_buf[8];
NPK_RESULT res;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return false;
}
// Compressed entities cannot be read partially.
if( eb->info_.flag_ & NPK_ENTITY_COMPRESS_ZLIB )
{
npk_error( NPK_ERROR_CantReadCompressedEntityByPartial );
return false;
}
pb = eb->owner_;
npk_package_lock( pb );
if( eb->info_.flag_ & ( NPK_ENTITY_ENCRYPT_TEA | NPK_ENTITY_ENCRYPT_XXTEA ) ) {
if( size < 8 ) {
tail_size = size;
} else {
head_size = 8 - (offset % 8);
if( head_size == 8 ) // Offset is aligned, do not need to read head separately.
head_size = 0;
tail_size = (size - head_size) % 8;
body_size = size - head_size - tail_size;
}
// If offset is not aligned, then read it separately.
if( head_size != 0 ) {
npk_seek( pb->handle_, (long)(eb->info_.offset_ + offset - 8 + head_size) + pb->offsetJump_, SEEK_SET );
// do not use callback
res = npk_read( pb->handle_, temp_buf, 8, NULL, NPK_PROCESSTYPE_ENTITY, 0, eb->name_ );
if( res != NPK_SUCCESS )
goto npk_entity_read_partial_return_with_free;
if( eb->info_.flag_ & NPK_ENTITY_ENCRYPT_TEA )
tea_decode_buffer(temp_buf, 8, pb->teakey_, false);
else
xxtea_decode_buffer(temp_buf, 8, pb->teakey_, false);
memcpy( buf, &temp_buf[8 - head_size], head_size );
} else {
npk_seek( pb->handle_, (long)(eb->info_.offset_ + offset) + pb->offsetJump_, SEEK_SET );
}
// The, read 'aligned' middle part.
if( body_size != 0 ) {
res = npk_read( pb->handle_,
buf + head_size,
body_size,
g_callbackfp,
NPK_PROCESSTYPE_ENTITY,
g_callbackSize,
eb->name_ );
if( res != NPK_SUCCESS )
goto npk_entity_read_partial_return_with_free;
if( eb->info_.flag_ & NPK_ENTITY_ENCRYPT_TEA )
tea_decode_buffer(buf + head_size, body_size, pb->teakey_, false);
else
xxtea_decode_buffer(buf + head_size, body_size, pb->teakey_, false);
}
// If the size of middle part is not aligned, then read remainer.
if( tail_size != 0 ) {
if( offset + head_size + body_size + 8 > eb->info_.size_ ) {
// tail exceeds entity size. do not over-read.
remains = tail_size;
} else {
remains = 8;
}
// do not use callback
res = npk_read( pb->handle_, temp_buf, remains, NULL, NPK_PROCESSTYPE_ENTITY, 0, eb->name_ );
if( res != NPK_SUCCESS )
goto npk_entity_read_partial_return_with_free;
if( eb->info_.flag_ & NPK_ENTITY_ENCRYPT_TEA )
tea_decode_buffer(temp_buf, remains, pb->teakey_, (pb->info_.version_ >= NPK_VERSION_ENCRYPTREMAINS));
else
xxtea_decode_buffer(temp_buf, remains, pb->teakey_, (pb->info_.version_ >= NPK_VERSION_ENCRYPTREMAINS));
memcpy( buf + head_size + body_size, temp_buf, tail_size );
}
} else {
// If this entity is not encrypted, then just read it at once.
npk_seek( pb->handle_, (long)(eb->info_.offset_ + offset) + pb->offsetJump_, SEEK_SET );
res = npk_read( pb->handle_, buf, size, g_callbackfp, NPK_PROCESSTYPE_ENTITY, g_callbackSize, eb->name_ );
if( res != NPK_SUCCESS )
goto npk_entity_read_partial_return_with_free;
}
npk_package_free( pb );
return true;
npk_entity_read_partial_return_with_free:
npk_package_free( pb );
return false;
}
void npk_enable_callback( NPK_CALLBACK cb, NPK_SIZE cb_size )
{
g_callbackfp = cb;
g_callbackSize = cb_size;
}
void npk_disable_callback()
{
g_callbackfp = NULL;
}
void npk_enable_criticalsection()
{
g_useCriticalSection = 1;
}
void npk_disable_criticalsection()
{
g_useCriticalSection = 0;
}
NPK_ENTITY npk_package_get_first_entity( NPK_PACKAGE package )
{
NPK_PACKAGEBODY* pb = package;
if( !package )
{
npk_error( NPK_ERROR_PackageIsNull );
return NULL;
}
return pb->pEntityHead_;
}
NPK_ENTITY npk_entity_next( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
if( !entity )
{
npk_error( NPK_ERROR_EntityIsNull );
return NULL;
}
return eb->next_;
}
|
barikang/npk | libnpk/src/npk_common.c | <filename>libnpk/src/npk_common.c
/*
npk - neat package system
See README for copyright and license information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "npk.h"
#include "npk_dev.h"
#ifdef NPK_PLATFORM_WINDOWS
#include <io.h>
#include <sys/utime.h>
#pragma warning( disable : 4996 )
#else
#include <utime.h>
#include <unistd.h>
#endif
#include "../external/tea/tea.h"
#include "../external/xxtea/xxtea.h"
#include "../external/zlib/zlib.h"
npk_open_func __open = NULL;
npk_close_func __close = NULL;
npk_read_func __read = NULL;
npk_write_func __write = NULL;
npk_seek_func __seek = NULL;
npk_tell_func __tell = NULL;
npk_rewind_func __rewind = NULL;
npk_commit_func __commit = NULL;
bool __use_open = false;
bool __use_close = false;
bool __use_read = false;
bool __use_write = false;
bool __use_seek = false;
bool __use_tell = false;
bool __use_rewind = false;
bool __use_commit = false;
NPK_API void npk_io_open_func (npk_open_func func) { __use_open = true; __open = func; }
NPK_API void npk_io_close_func (npk_close_func func) { __use_close = true; __close = func; }
NPK_API void npk_io_read_func (npk_read_func func) { __use_read = true; __read = func; }
NPK_API void npk_io_write_func (npk_write_func func) { __use_write = true; __write = func; }
NPK_API void npk_io_seek_func (npk_seek_func func) { __use_seek = true; __seek = func; }
NPK_API void npk_io_tell_func (npk_tell_func func) { __use_tell = true; __tell = func; }
NPK_API void npk_io_rewind_func(npk_rewind_func func){ __use_rewind = true; __rewind = func; }
NPK_API void npk_io_commit_func(npk_commit_func func){ __use_commit = true; __commit = func; }
NPK_RESULT npk_error( NPK_RESULT res )
{
g_npkError = res;
return res;
}
NPK_STR npk_error_to_str( NPK_RESULT res )
{
switch( res )
{
case NPK_SUCCESS:
return "SUCCESS";
case NPK_ERROR_FileNotFound:
return "ERROR: File not found.";
case NPK_ERROR_FileOpenError:
return "ERROR: File open error.";
case NPK_ERROR_FileSaveError:
return "ERROR: File save error.";
case NPK_ERROR_FileReadError:
return "ERROR: File read error.";
case NPK_ERROR_PermissionDenied:
return "ERROR: Permission denied.";
case NPK_ERROR_ReadOnlyFile:
return "ERROR: Read only file.";
case NPK_ERROR_FailToGetFiletime:
return "ERROR: Fail to get filetime.";
case NPK_ERROR_NotValidFileName:
return "ERROR: Not valid filename.";
case NPK_ERROR_NotValidPackage:
return "ERROR: Not valid package.";
case NPK_ERROR_CannotFindEntity:
return "ERROR: Cannot find an entity.";
case NPK_ERROR_CannotCreateFile:
return "ERROR: Cannot create a file.";
case NPK_ERROR_PackageHasNoName:
return "ERROR: Package has no name.";
case NPK_ERROR_PackageHasNoVersion:
return "ERROR: Package has no version.";
case NPK_ERROR_ZeroFileSize:
return "ERROR: File size is zero.";
case NPK_ERROR_SameEntityExist:
return "ERROR: Same entity name.";
case NPK_ERROR_FailToSetFiletime:
return "ERROR: Fail to set filetime.";
case NPK_ERROR_NotValidEntity:
return "ERROR: Not valid entity.";
case NPK_ERROR_NotValidEntityName:
return "ERROR: Not valid entity name.";
case NPK_ERROR_OpenedPackage:
return "ERROR: Package is already opened.";
case NPK_ERROR_NotOpenedPackage:
return "ERROR: Package is not opened.";
case NPK_ERROR_SamePackageExist:
return "ERROR: Same package exists.";
case NPK_ERROR_NonAllocatedBuffer:
return "ERROR: Buffer is not allocated.";
case NPK_ERROR_NullPointerBuffer:
return "ERROR: Buffer is null pointer.";
case NPK_ERROR_FailToDecompress:
return "ERROR: Fail to decompress.";
case NPK_ERROR_AlreadyAllocated:
return "ERROR: Buffer is already allocated.";
case NPK_ERROR_NonStaticPackage:
return "ERROR: This is non-static package.";
case NPK_ERROR_NeedSpecifiedTeaKey:
return "ERROR: Need teakey.";
case NPK_ERROR_EntityIsNull:
return "ERROR: Entity pointer is null.";
case NPK_ERROR_PackageIsNull:
return "ERROR: Package pointer is null.";
case NPK_ERROR_EntityIsNotInThePackage:
return "ERROR: Entity is not in the package.";
case NPK_ERROR_CantReadCompressedEntityByPartial:
return "ERROR: Cannot read compressed entity partially.";
case NPK_ERROR_ReadingEncryptedEntityByPartialShouldBeAligned :
return "ERROR: Offset and size must be aligned by 8 bytes.";
case NPK_ERROR_FileAlreadyExists:
return "ERROR: File already exists.";
case NPK_ERROR_NoEntityInPackage:
return "ERROR: No entity in the package.";
case NPK_ERROR_InvalidTeaKey:
return "ERROR: Invalid tea key.";
case NPK_ERROR_EntityIsNotReady:
return "ERROR: Entity is not ready.";
case NPK_ERROR_PackageIsNotReady:
return "ERROR: Package is not ready.";
case NPK_ERROR_SourceStringisNull:
return "ERROR: Cannot copy string. Source pointer is null.";
case NPK_ERROR_CannotCopyToItself:
return "ERROR: Cannot copy string to itself.";
case NPK_ERROR_NotEnoughMemory:
return "ERROR: Not enough memory.";
case NPK_ERROR_NotEnoughDiscSpace:
return "ERROR: Not enough disk space.";
case NPK_ERROR_CannotFindPackage:
return "ERROR: Cannot find the package.";
case NPK_ERROR_CancelByCallback:
return "ERROR: Canceled by user input.";
}
return "ERROR: Unrecognized error number.";
}
NPK_RESULT npk_alloc_copy_string( NPK_STR* dst, NPK_CSTR src )
{
NPK_SIZE len = (NPK_SIZE)strlen(src);
if( src == NULL )
return( npk_error( NPK_ERROR_SourceStringisNull ) );
if( *dst == src )
return( npk_error( NPK_ERROR_CannotCopyToItself ) );
if( *dst )
free( *dst );
*dst = malloc( sizeof(NPK_CHAR)*(len+1) );
if( *dst == NULL )
return( npk_error( NPK_ERROR_NotEnoughMemory ) );
strncpy( *dst, src, len );
(*dst)[len] = '\0';
return NPK_SUCCESS;
}
void npk_filetime_to_unixtime( NPK_64BIT* pft, NPK_TIME* pt )
{
*pt = (NPK_TIME)((*pft - 116444736000000000LL)/10000000LL);
}
NPK_RESULT npk_open( NPK_HANDLE* handle, NPK_CSTR fileName, bool createfile, bool bcheckexist )
{
if(!__use_open)
{
if( createfile )
{
#ifdef NPK_PLATFORM_WINDOWS
if( bcheckexist )
{
*handle = open( fileName, O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR );
}
else
{
*handle = creat( fileName, S_IRUSR | S_IWUSR );
if( errno == EACCES )
return( npk_error( NPK_ERROR_ReadOnlyFile ) );
close( *handle );
*handle = open( fileName, O_CREAT | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR );
}
#else
mode_t mask = umask(0);
if( bcheckexist )
{
*handle = open( fileName, O_CREAT | O_EXCL | O_RDWR | O_BINARY, 0666 );
if( *handle != -1 ) fchmod( *handle, 0666&~mask );
}
else
{
*handle = creat( fileName, S_IRUSR | S_IWUSR );
if( errno == EACCES )
return( npk_error( NPK_ERROR_ReadOnlyFile ) );
close( *handle );
*handle = open( fileName, O_CREAT | O_RDWR | O_BINARY, 0666 );
if( *handle != -1 ) fchmod( *handle, 0666&~mask );
}
umask( mask );
#endif
}
else
*handle = open( fileName, O_BINARY | O_RDONLY );
if( *handle == -1 )
{
if( errno == ENOENT )
return( npk_error( NPK_ERROR_FileNotFound ) );
else if( errno == EEXIST )
return( npk_error( NPK_ERROR_FileAlreadyExists ) );
else
return( npk_error( NPK_ERROR_FileOpenError ) );
}
}
else
{
if( createfile )
*handle = (NPK_HANDLE)(intptr_t)__open( fileName, "wb+" );
else
*handle = (NPK_HANDLE)(intptr_t)__open( fileName, "rb+" );
if( *handle == -1 )
{
if( errno == ENOENT )
return( npk_error( NPK_ERROR_FileNotFound ) );
else if( errno == EEXIST )
return( npk_error( NPK_ERROR_FileAlreadyExists ) );
else
return( npk_error( NPK_ERROR_FileOpenError ) );
}
}
return NPK_SUCCESS;
}
NPK_RESULT npk_close( NPK_HANDLE handle )
{
if( handle > 0 )
{
if(!__use_close)
close( handle );
else
__close((void*)(intptr_t)handle);
}
return NPK_SUCCESS;
}
NPK_OFFSET npk_seek( NPK_HANDLE handle, NPK_OFFSET offset, int origin )
{
if(!__use_seek)
#ifdef NPK_PLATFORM_WINDOWS
return _lseek( handle, offset, origin );
#else
return lseek( handle, offset, origin );
#endif
else
return __seek((void*)(intptr_t)handle, offset, origin);
}
NPK_RESULT npk_read( NPK_HANDLE handle, void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier )
{
NPK_OFFSET currentread;
NPK_OFFSET totalread = 0;
NPK_OFFSET unit = cbsize;
if( cb )
{
if( unit <= 0 )
unit = size;
do
{
if( (cb)( NPK_ACCESSTYPE_READ, cbprocesstype, cbidentifier, totalread, size ) == false )
return( npk_error( NPK_ERROR_CancelByCallback ) );
if( ( size - totalread ) < unit )
unit = size - totalread;
if(!__use_read)
currentread = read( handle, (NPK_STR)buf + totalread, (unsigned int)unit );
else
currentread = __read( (NPK_STR)buf + totalread, sizeof(char), (size_t)unit, (void*)(intptr_t)handle );
if( currentread < unit )
{
if( errno == EACCES )
return( npk_error( NPK_ERROR_PermissionDenied ) );
else
return( npk_error( NPK_ERROR_FileReadError ) );
}
totalread += currentread;
} while( totalread < size );
if( (cb)( NPK_ACCESSTYPE_READ, cbprocesstype, cbidentifier, totalread, size ) == false )
return( npk_error( NPK_ERROR_CancelByCallback ) );
}
else
{
if(!__use_read)
currentread = read( handle, (NPK_STR)buf, (size_t)size );
else
currentread = __read( (NPK_STR)buf, sizeof(char), (size_t)size, (void*)(intptr_t)handle );
if( currentread < size )
{
if( errno == EACCES )
return( npk_error( NPK_ERROR_PermissionDenied ) );
else
return( npk_error( NPK_ERROR_FileReadError ) );
}
}
return NPK_SUCCESS;
}
NPK_RESULT npk_read_encrypt( NPK_TEAKEY* key, NPK_HANDLE handle, void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier,
bool cipherRemains, bool useXXTEA )
{
NPK_RESULT res = npk_read( handle, buf, size, cb, cbprocesstype, cbsize, cbidentifier );
if( res == NPK_SUCCESS )
{
if( useXXTEA )
xxtea_decode_buffer( (unsigned char*)buf, size, key, cipherRemains );
else
tea_decode_buffer( (unsigned char*)buf, size, key, cipherRemains );
}
return res;
}
NPK_RESULT npk_package_alloc( NPK_PACKAGE* lpPackage, NPK_TEAKEY teakey[4] )
{
NPK_PACKAGEBODY* pb;
NPK_RESULT res;
int i;
if( teakey == NULL )
return npk_error( NPK_ERROR_NeedSpecifiedTeaKey );
pb = malloc( sizeof(NPK_PACKAGEBODY) );
if( !pb )
return npk_error( NPK_ERROR_NotEnoughMemory );
for( i = 0; i < NPK_HASH_BUCKETS; ++i )
{
pb->bucket_[i] = malloc( sizeof(NPK_BUCKET) );
if( !pb->bucket_[i] )
return npk_error( NPK_ERROR_NotEnoughMemory );
}
if( ( res = npk_package_init( pb ) ) != NPK_SUCCESS )
{
NPK_SAFE_FREE( pb );
return res;
}
memcpy( pb->teakey_, teakey, sizeof(NPK_TEAKEY) * 4 );
*lpPackage = pb;
return NPK_SUCCESS;
}
NPK_PACKAGE _npk_package_alloc( NPK_TEAKEY teakey[4] )
{
NPK_PACKAGE p = NULL;
if( NPK_SUCCESS == npk_package_alloc( &p, teakey ) )
return p;
return NULL;
}
NPK_RESULT npk_entity_alloc( NPK_ENTITY* lpEntity )
{
NPK_ENTITYBODY* eb;
NPK_RESULT res;
eb = malloc( sizeof(NPK_ENTITYBODY) );
if( !eb )
return npk_error( NPK_ERROR_NotEnoughMemory );
if( ( res = npk_entity_init( eb ) ) != NPK_SUCCESS )
{
NPK_SAFE_FREE( eb );
return res;
}
*lpEntity = eb;
return NPK_SUCCESS;
}
NPK_ENTITY _npk_entity_alloc()
{
NPK_ENTITY e = NULL;
if( NPK_SUCCESS == npk_entity_alloc( &e ) )
return e;
return NULL;
}
NPK_RESULT npk_entity_init( NPK_ENTITY entity )
{
NPK_ENTITYBODY* eb = entity;
if( !entity )
return npk_error( NPK_ERROR_EntityIsNull );
memset( eb, 0, sizeof(NPK_ENTITYBODY) );
eb->newflag_ = NPK_ENTITY_NULL;
eb->name_ = NULL;
eb->localname_ = NULL;
eb->owner_ = NULL;
eb->prev_ = NULL;
eb->next_ = NULL;
eb->info_.flag_ = NPK_ENTITY_REVERSE;
eb->newflag_ = NPK_ENTITY_REVERSE;
return NPK_SUCCESS;
}
NPK_RESULT npk_package_init( NPK_PACKAGE package )
{
NPK_PACKAGEBODY* pb = package;
int i = 0;
if( !package )
return npk_error( NPK_ERROR_PackageIsNull );
pb->info_.entityCount_ = 0;
pb->info_.entityDataOffset_ = 0;
pb->info_.entityInfoOffset_ = 0;
pb->info_.version_ = 0;
pb->handle_ = 0;
pb->pEntityHead_ = NULL;
pb->pEntityTail_ = NULL;
#ifdef NPK_PLATFORM_WINDOWS
InitializeCriticalSection( &pb->cs_ );
#endif
for( i = 0; i < NPK_HASH_BUCKETS; ++i )
{
pb->bucket_[i]->pEntityHead_ = NULL;
pb->bucket_[i]->pEntityTail_ = NULL;
}
pb->usingHashmap_ = false;
pb->usingFdopen_ = false;
pb->offsetJump_ = 0;
return NPK_SUCCESS;
}
NPK_RESULT __npk_package_add_entity( NPK_PACKAGE package, NPK_ENTITY entity, bool check )
{
NPK_ENTITYBODY* eb = entity;
NPK_PACKAGEBODY* pb = package;
NPK_BUCKET* bucket = NULL;
if( check )
{
if( !entity )
return npk_error( NPK_ERROR_EntityIsNull );
if( !package )
return npk_error( NPK_ERROR_PackageIsNull );
if( npk_package_get_entity( package, eb->name_ ) != NULL )
return npk_error( NPK_ERROR_SameEntityExist );
}
pb->pEntityLatest_ = entity;
eb->owner_ = pb;
bucket = pb->bucket_[npk_get_bucket(eb->name_)];
if( pb->pEntityHead_ == NULL )
{
pb->pEntityHead_ = eb;
pb->pEntityTail_ = eb;
}
else
{
pb->pEntityTail_->next_ = eb;
eb->prev_ = pb->pEntityTail_;
pb->pEntityTail_ = eb;
}
if( bucket->pEntityHead_ == NULL )
{
bucket->pEntityHead_ = eb;
bucket->pEntityTail_ = eb;
}
else
{
bucket->pEntityTail_->nextInBucket_ = eb;
eb->prevInBucket_ = bucket->pEntityTail_;
bucket->pEntityTail_ = eb;
}
++pb->info_.entityCount_;
if( pb->info_.entityCount_ >= NPK_HASH_BUCKETS )
pb->usingHashmap_ = true;
return NPK_SUCCESS;
}
NPK_RESULT npk_package_add_entity( NPK_PACKAGE package, NPK_ENTITY entity )
{
return __npk_package_add_entity( package, entity, true );
}
/* adler32 algorithm from http://en.wikipedia.org/wiki/Adler-32 */
NPK_HASHKEY npk_get_bucket( NPK_CSTR name )
{
const int MOD_ADLER = 65521;
NPK_HASHKEY a = 1, b = 0;
while( *name )
{
#ifndef NPK_CASESENSITIVE
if( *name >= 'A' && *name <= 'Z' )
a = (a + (*name+32)) % MOD_ADLER;
else
#endif
a = (a + *name) % MOD_ADLER;
b = (b + a) % MOD_ADLER;
++name;
}
return ( (b << 16) | a ) % NPK_HASH_BUCKETS;
}
NPK_RESULT npk_prepare_entityname( NPK_CSTR src, NPK_STR dst, size_t dstLen )
{
size_t i;
size_t l = strlen(src);
if( l >= dstLen )
return npk_error( NPK_ERROR_NotValidEntityName );
for( i = 0 ; i < l; ++i )
if( src[i] == '\\' ) dst[i] = '/'; else dst[i] = src[i];
dst[i] = '\0';
return NPK_SUCCESS;
}
NPK_RESULT __npk_package_remove_all_entity( NPK_PACKAGE package, bool deepRemove )
{
NPK_ENTITYBODY* eb = NULL;
NPK_PACKAGEBODY* pb = package;
int i = 0;
if( !package )
return npk_error( NPK_ERROR_PackageIsNull );
if( deepRemove )
{
while( pb->pEntityHead_ != NULL )
{
eb = pb->pEntityHead_;
pb->pEntityHead_ = pb->pEntityHead_->next_;
NPK_SAFE_FREE( eb->name_ );
NPK_SAFE_FREE( eb->localname_ );
NPK_SAFE_FREE( eb );
}
}
else
{
while( pb->pEntityHead_ != NULL )
{
eb = pb->pEntityHead_;
pb->pEntityHead_ = pb->pEntityHead_->next_;
eb->next_ = NULL;
eb->prev_ = NULL;
eb->nextInBucket_ = NULL;
eb->prevInBucket_ = NULL;
}
}
for( i = 0; i < NPK_HASH_BUCKETS; ++i )
{
pb->bucket_[i]->pEntityHead_ = NULL;
pb->bucket_[i]->pEntityTail_ = NULL;
}
pb->usingHashmap_ = false;
pb->pEntityHead_ = NULL;
pb->pEntityTail_ = NULL;
pb->pEntityLatest_ = NULL;
pb->info_.entityCount_ = 0;
return NPK_SUCCESS;
}
NPK_RESULT npk_package_remove_all_entity( NPK_PACKAGE package )
{
return __npk_package_remove_all_entity( package, true );
}
NPK_RESULT npk_entity_get_current_flag( NPK_ENTITY entity, NPK_FLAG* flag )
{
NPK_ENTITYBODY* eb = entity;
if( !eb )
return npk_error( NPK_ERROR_EntityIsNull );
*flag = eb->info_.flag_;
return NPK_SUCCESS;
}
void npk_package_lock( NPK_PACKAGE package )
{
if( !g_useCriticalSection ) return;
#ifdef NPK_PLATFORM_WINDOWS
EnterCriticalSection( &((NPK_PACKAGEBODY*)package)->cs_ );
#endif
}
void npk_package_free( NPK_PACKAGE package )
{
if( !g_useCriticalSection ) return;
#ifdef NPK_PLATFORM_WINDOWS
LeaveCriticalSection( &((NPK_PACKAGEBODY*)package)->cs_ );
#endif
}
|
barikang/npk | libnpk/src/npk_dev.c | /*
npk - neat package system
See README for copyright and license information.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "npk.h"
#include "npk_dev.h"
#ifdef NPK_PLATFORM_WINDOWS
#include <io.h>
#include <sys/utime.h>
#pragma warning( disable : 4996 )
#else
#include <utime.h>
#include <unistd.h>
#endif
#include "../external/tea/tea.h"
#include "../external/xxtea/xxtea.h"
#include "../external/zlib/zlib.h"
#ifdef NPK_DEV
bool g_use_gluetime;
NPK_TIME g_gluetime;
void npk_log( NPK_CSTR format, ... )
{
NPK_CHAR buf[512];
va_list args;
va_start( args, format );
vsnprintf( buf, sizeof(buf) / sizeof(buf[0]), format, args);
va_end( args );
printf( "%s\n", buf );
}
NPK_RESULT npk_get_filetime( NPK_CSTR filename, NPK_TIME* pft )
{
struct stat __sbuf;
int result;
if( g_use_gluetime )
*pft = g_gluetime;
else
{
result = stat( filename, &__sbuf );
if( result != 0 )
{
switch( errno )
{
case ENOENT:
return( npk_error( NPK_ERROR_FileNotFound ) );
}
return( npk_error( NPK_ERROR_FailToGetFiletime ) );
}
*pft = (NPK_TIME)__sbuf.st_mtime;
}
return NPK_SUCCESS;
}
NPK_RESULT npk_set_filetime( NPK_CSTR filename, const NPK_TIME pft )
{
struct stat __sbuf;
struct utimbuf __ubuf;
int result;
result = stat( filename, &__sbuf );
if( result != 0 )
{
switch( errno )
{
case ENOENT:
return( npk_error( NPK_ERROR_FileNotFound ) );
}
return( npk_error( NPK_ERROR_FailToGetFiletime ) );
}
__ubuf.actime = __sbuf.st_atime;
__ubuf.modtime = pft;
utime( filename, &__ubuf );
return NPK_SUCCESS;
}
void npk_enable_gluetime( NPK_TIME time )
{
g_use_gluetime = true;
g_gluetime = time;
}
void npk_disable_gluetime()
{
g_use_gluetime = false;
}
NPK_RESULT npk_flush( NPK_HANDLE handle )
{
if( handle != 0 )
{
if(!__use_commit)
#ifdef NPK_PLATFORM_WINDOWS
_commit( handle );
#else
fsync( handle );
#endif
else
__commit( (void*)(intptr_t)handle );
}
return NPK_SUCCESS;
}
NPK_OFFSET npk_tell( NPK_HANDLE handle )
{
if(!__use_seek)
#ifdef NPK_PLATFORM_WINDOWS
return _lseek( handle, 0, SEEK_CUR );
#else
return lseek( handle, 0, SEEK_CUR );
#endif
else
return __seek( (void*)(intptr_t)handle, 0, SEEK_CUR );
}
NPK_RESULT npk_write( NPK_HANDLE handle, const void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier )
{
NPK_SIZE currentwritten;
NPK_SIZE unit = cbsize;
NPK_OFFSET totalwritten = 0;
if( cb )
{
if( unit <= 0 )
unit = size;
do
{
if( (cb)( NPK_ACCESSTYPE_WRITE, cbprocesstype, cbidentifier, totalwritten, size ) == false )
return( npk_error( NPK_ERROR_CancelByCallback ) );
if( (NPK_SIZE)( size - totalwritten ) < unit )
unit = size - totalwritten;
if(!__use_write)
currentwritten = write( handle, (NPK_STR)buf + totalwritten, (size_t)unit );
else
currentwritten = __write( (NPK_STR)buf + totalwritten, sizeof(char*), (size_t)unit, (void*)(intptr_t)handle );
if( currentwritten < unit )
{
if( errno == EACCES )
return( npk_error( NPK_ERROR_PermissionDenied ) );
else if( errno == ENOSPC )
return( npk_error( NPK_ERROR_NotEnoughDiscSpace ) );
else
return( npk_error( NPK_ERROR_FileSaveError ) );
}
totalwritten += currentwritten;
} while( totalwritten < size );
if( (cb)( NPK_ACCESSTYPE_WRITE, cbprocesstype, cbidentifier, totalwritten, size ) == false )
return( npk_error( NPK_ERROR_CancelByCallback ) );
}
else
{
currentwritten = write( handle, (NPK_STR)buf, size );
if( (NPK_OFFSET)currentwritten < size )
{
if( errno == EACCES )
return( npk_error( NPK_ERROR_PermissionDenied ) );
else if( errno == ENOSPC )
return( npk_error( NPK_ERROR_NotEnoughDiscSpace ) );
else
return( npk_error( NPK_ERROR_FileSaveError ) );
}
}
return NPK_SUCCESS;
}
NPK_RESULT npk_write_encrypt( NPK_TEAKEY* key, NPK_HANDLE handle, const void* buf, NPK_OFFSET size,
NPK_CALLBACK cb, int cbprocesstype, NPK_OFFSET cbsize, NPK_CSTR cbidentifier,
bool cipherRemains, bool useXXTEA )
{
NPK_RESULT res;
void* bufferforencode = malloc( sizeof(char) * size );
if( !bufferforencode )
return npk_error( NPK_ERROR_NotEnoughMemory );
memcpy( bufferforencode, buf, sizeof(char) * size );
if( useXXTEA )
xxtea_encode_buffer( (unsigned char*)bufferforencode, size, key, cipherRemains );
else
tea_encode_buffer( (unsigned char*)bufferforencode, size, key, cipherRemains );
res = npk_write( handle, bufferforencode, size, cb, cbprocesstype, cbsize, cbidentifier );
free( bufferforencode );
return res;
}
NPK_RESULT npk_entity_get_new_flag( NPK_ENTITY entity, NPK_FLAG* flag )
{
NPK_ENTITYBODY* eb = entity;
if( !eb )
return npk_error( NPK_ERROR_EntityIsNull );
*flag = eb->newflag_;
return NPK_SUCCESS;
}
NPK_RESULT npk_entity_set_flag( NPK_ENTITY entity, NPK_FLAG flag )
{
NPK_ENTITYBODY* eb = entity;
if( !eb )
return npk_error( NPK_ERROR_EntityIsNull );
eb->newflag_ = flag;
return NPK_SUCCESS;
}
NPK_RESULT npk_entity_add_flag( NPK_ENTITY entity, NPK_FLAG flag )
{
NPK_ENTITYBODY* eb = entity;
if( !eb )
return npk_error( NPK_ERROR_EntityIsNull );
eb->newflag_ |= flag;
return NPK_SUCCESS;
}
NPK_RESULT npk_entity_sub_flag( NPK_ENTITY entity, NPK_FLAG flag )
{
NPK_ENTITYBODY* eb = entity;
if( !eb )
return npk_error( NPK_ERROR_EntityIsNull );
eb->newflag_ &= ~flag;
return NPK_SUCCESS;
}
NPK_RESULT npk_entity_write( NPK_ENTITY entity, NPK_HANDLE handle, bool forceProcessing )
{
NPK_PACKAGEBODY* pb;
NPK_ENTITYBODY* eb = entity;
NPK_RESULT res;
bool skipProcessing;
void* buf = NULL;
void* buf_for_zlib = NULL;
NPK_SIZE size, endpos, startpos;
NPK_HANDLE filehandle;
int z_res;
if( !eb )
return npk_error( NPK_ERROR_EntityIsNull );
pb = eb->owner_;
skipProcessing = false;
if( eb->localname_ != NULL )
{ // read native file and write
if( ( res = npk_open( &filehandle, eb->localname_, false, false ) ) != NPK_SUCCESS )
return res;
endpos = npk_seek( filehandle, 0, SEEK_END );
startpos = npk_seek( filehandle, 0, SEEK_SET );
size = endpos - startpos;
if( size == 0 )
return npk_error( NPK_ERROR_ZeroFileSize );
eb->info_.originalSize_ = size;
buf = malloc( size );
if( ( res = npk_read( filehandle,
buf,
size,
g_callbackfp,
NPK_PROCESSTYPE_ENTITY,
g_callbackSize,
eb->name_ ) ) != NPK_SUCCESS )
goto npk_entity_write_return_with_free;
npk_close( filehandle );
npk_get_filetime( eb->localname_, &eb->info_.modified_ );
NPK_SAFE_FREE( eb->localname_ );
}
else
{
if( eb->newflag_ != eb->info_.flag_ || forceProcessing )
{ // read entity and write
size = eb->info_.originalSize_;
buf = malloc( size );
npk_entity_read( eb, buf );
}
else
{ // just copy
size = eb->info_.size_;
buf = malloc( size );
npk_seek( pb->handle_, (long)eb->info_.offset_+pb->offsetJump_, SEEK_SET );
if( ( res = npk_read( pb->handle_,
buf,
size,
g_callbackfp,
NPK_PROCESSTYPE_ENTITY,
g_callbackSize,
eb->name_ ) ) != NPK_SUCCESS )
goto npk_entity_write_return_with_free;
skipProcessing = true;
}
}
if( !skipProcessing )
{
// Encode before compress, before v21
if( ( eb->newflag_ & NPK_ENTITY_ENCRYPT_TEA ) && !( eb->newflag_ & NPK_ENTITY_REVERSE ) )
tea_encode_buffer((unsigned char*)buf, (int)size, pb->teakey_, false );
if( eb->newflag_ & NPK_ENTITY_COMPRESS_ZLIB )
{
if( size >= NPK_MIN_SIZE_ZIPABLE )
{
unsigned long compressedSize = (unsigned long)(sizeof(char) * size * 1.1 + 12); // margin rules from zlib/compress.c
buf_for_zlib = malloc( compressedSize );
#ifdef Z_PREFIX
z_res = z_compress( (Bytef*)buf_for_zlib, (z_uLong*)&compressedSize, (const Bytef*)buf, (z_uLong)size );
#else
z_res = compress( (Bytef*)buf_for_zlib, (uLong*)&compressedSize, (const Bytef*)buf, (uLong)size );
#endif
if( ( z_res == Z_OK ) && ( compressedSize < size ) )
{
free( buf );
buf = buf_for_zlib;
buf_for_zlib = NULL;
size = compressedSize;
}
else // not suitable to compress
{
free( buf_for_zlib );
eb->newflag_ &= !NPK_ENTITY_COMPRESS_ZLIB;
}
}
}
// Encode after compress, after v21
if( ( eb->newflag_ & NPK_ENTITY_ENCRYPT_TEA ) && ( eb->newflag_ & NPK_ENTITY_REVERSE ) )
tea_encode_buffer((unsigned char*)buf, (int)size, pb->teakey_, (NPK_VERSION_CURRENT >= NPK_VERSION_ENCRYPTREMAINS) );
if( eb->newflag_ & NPK_ENTITY_ENCRYPT_XXTEA )
xxtea_encode_buffer((unsigned char*)buf, (int)size, pb->teakey_, (NPK_VERSION_CURRENT >= NPK_VERSION_ENCRYPTREMAINS) );
}
eb->info_.size_ = size;
eb->info_.offset_ = npk_tell( handle );
if( ( res = npk_write( handle,
buf,
size,
g_callbackfp,
NPK_PROCESSTYPE_ENTITY,
g_callbackSize,
eb->name_ ) ) != NPK_SUCCESS )
goto npk_entity_write_return_with_free;
free( buf );
eb->info_.flag_ = eb->newflag_;
return NPK_SUCCESS;
npk_entity_write_return_with_free:
NPK_SAFE_FREE( buf );
NPK_SAFE_FREE( buf_for_zlib );
return res;
}
NPK_RESULT npk_entity_export( NPK_ENTITY entity, NPK_CSTR filename, bool forceOverwrite )
{
void* buf;
NPK_HANDLE handle;
NPK_ENTITYBODY* eb = entity;
NPK_RESULT res;
if( !entity )
return npk_error( NPK_ERROR_EntityIsNull );
buf = malloc( eb->info_.originalSize_ );
if( !buf )
return npk_error( NPK_ERROR_NotEnoughMemory );
if( !( res = npk_entity_read( eb, buf ) ) )
return res;
if( ( res = npk_open( &handle, filename, true, true ) ) != NPK_SUCCESS )
{
if( !forceOverwrite )
return res;
if( ( res = npk_open( &handle, filename, true, false ) ) != NPK_SUCCESS )
return res;
}
if( ( res = npk_write( handle,
buf,
eb->info_.originalSize_,
g_callbackfp,
NPK_PROCESSTYPE_ENTITY,
g_callbackSize,
eb->name_ ) ) != NPK_SUCCESS )
return res;
if( ( res = npk_close( handle ) ) != NPK_SUCCESS )
return res;
npk_set_filetime( filename, eb->info_.modified_ );
free( buf );
return NPK_SUCCESS;
}
NPK_RESULT npk_package_clear( NPK_PACKAGE package )
{
NPK_RESULT res;
if( !package )
return npk_error( NPK_ERROR_PackageIsNull );
if( ( res = npk_package_remove_all_entity( package ) ) != NPK_SUCCESS )
return res;
if( ( res = npk_package_init( package ) ) != NPK_SUCCESS )
return res;
return NPK_SUCCESS;
}
NPK_RESULT npk_package_save( NPK_PACKAGE package, NPK_CSTR filename, bool forceOverwrite )
{
NPK_PACKAGEBODY* pb = package;
NPK_ENTITYBODY* eb = NULL;
NPK_RESULT res;
bool bVersionUp = false;
bool bUseTemporaryFile = false;
NPK_SIZE len;
int savecount = 0;
NPK_STR savefilename = NULL;
NPK_HANDLE savefilehandle;
NPK_CHAR* buf;
NPK_CHAR* buf_pos;
if( !package )
return npk_error( NPK_ERROR_PackageIsNull );
if( !filename )
return npk_error( NPK_ERROR_PackageHasNoName );
if( ( res = npk_open( &savefilehandle, filename, true, true ) ) == NPK_SUCCESS )
{
npk_alloc_copy_string( &savefilename, filename );
}
else
{
if( res != NPK_ERROR_FileAlreadyExists )
return res;
if( !forceOverwrite )
return res;
len = (NPK_SIZE)strlen( filename );
savefilename = malloc( sizeof(NPK_CHAR)*(len+2) );
if( savefilename == NULL )
return( npk_error( NPK_ERROR_NotEnoughMemory ) );
strncpy( savefilename, filename, len );
savefilename[len+0] = '_';
savefilename[len+1] = '\0';
bUseTemporaryFile = true;
if( ( res = npk_open( &savefilehandle, savefilename, true, false ) ) != NPK_SUCCESS )
return res;
}
strncpy( pb->info_.signature_, NPK_SIGNATURE, sizeof(NPK_CHAR)*4 );
if( pb->info_.version_ != NPK_VERSION_CURRENT )
bVersionUp = true;
pb->info_.entityInfoOffset_ = sizeof(NPK_PACKAGEINFO);
// version 27, precalculate entity information header length
eb = pb->pEntityHead_;
len = 0;
while( eb != NULL )
{
len += sizeof(NPK_ENTITYINFO);
len += sizeof(NPK_CHAR)*eb->info_.nameLength_;
eb = eb->next_;
}
pb->info_.entityDataOffset_ = pb->info_.entityInfoOffset_ + len;
npk_seek( savefilehandle, (long)pb->info_.entityDataOffset_, SEEK_SET );
eb = pb->pEntityHead_;
while( eb != NULL )
{
if( g_callbackfp )
if( (g_callbackfp)( NPK_ACCESSTYPE_WRITE, NPK_PROCESSTYPE_PACKAGE, filename, savecount, pb->info_.entityCount_ ) == false )
return( npk_error( NPK_ERROR_CancelByCallback ) );
npk_entity_write( eb, savefilehandle, bVersionUp );
++savecount;
eb = eb->next_;
}
pb->info_.entityCount_ = savecount;
// version 24, Take single encryption to whole entity headers
buf = malloc( (sizeof(NPK_ENTITYINFO)+260)*savecount ); // 260 = MAX_PATH on windows, isn't it enough?
if( !buf )
return( npk_error( NPK_ERROR_NotEnoughMemory ) );
buf_pos = buf;
eb = pb->pEntityHead_;
while( eb != NULL )
{
memcpy( buf_pos, &eb->info_, sizeof(NPK_ENTITYINFO) );
buf_pos += sizeof(NPK_ENTITYINFO);
memcpy( buf_pos, eb->name_, sizeof(NPK_CHAR)*eb->info_.nameLength_ );
buf_pos += sizeof(NPK_CHAR)*eb->info_.nameLength_;
eb = eb->next_;
}
npk_seek( savefilehandle, (long)pb->info_.entityInfoOffset_, SEEK_SET );
if( ( res = npk_write_encrypt( pb->teakey_,
savefilehandle,
buf,
buf_pos - buf,
g_callbackfp,
NPK_PROCESSTYPE_ENTITYHEADER,
g_callbackSize,
savefilename,
(NPK_VERSION_CURRENT >= NPK_VERSION_ENCRYPTREMAINS),
(NPK_VERSION_CURRENT >= NPK_VERSION_USEXXTEAONHEADER)
) ) != NPK_SUCCESS )
return res;
NPK_SAFE_FREE( buf );
pb->info_.version_ = NPK_VERSION_CURRENT;
pb->info_.modified_ = (NPK_TIME)time(NULL);
npk_seek( savefilehandle, 0, SEEK_SET );
if( ( res = npk_write( savefilehandle,
&pb->info_,
sizeof(NPK_PACKAGEINFO),
g_callbackfp,
NPK_PROCESSTYPE_PACKAGEHEADER,
g_callbackSize,
savefilename ) ) != NPK_SUCCESS )
return res;
npk_flush( savefilehandle );
npk_close( pb->handle_ );
if( bUseTemporaryFile )
{
npk_close( savefilehandle );
remove( filename );
rename( savefilename, filename );
if( (res = npk_open( &pb->handle_, filename, false, false ) ) != NPK_SUCCESS )
return res;
}
else
{
pb->handle_ = savefilehandle;
}
NPK_SAFE_FREE( savefilename );
return NPK_SUCCESS;
}
NPK_RESULT npk_package_add_file( NPK_PACKAGE package, NPK_CSTR filename, NPK_CSTR entityname, NPK_ENTITY* lpEntity )
{
NPK_ENTITYBODY* eb;
NPK_CSTR __entityname;
NPK_RESULT res;
NPK_CHAR namebuf[512];
if( ( res = npk_entity_alloc( (NPK_ENTITY*)&eb ) ) != NPK_SUCCESS )
return res;
if( entityname == NULL )
{
__entityname = NULL;
if( ( entityname = strrchr( filename, '\\' ) ) == NULL )
if( ( entityname = strrchr( filename, '/' ) ) == NULL )
__entityname = filename;
if( __entityname == NULL )
__entityname = entityname + sizeof(NPK_CHAR);
}
else
__entityname = entityname;
if( ( res = npk_prepare_entityname( __entityname, namebuf, 512 ) ) != NPK_SUCCESS )
goto npk_package_add_file_return_with_error;
if( ( res = npk_get_filetime( filename, &eb->info_.modified_ ) ) != NPK_SUCCESS )
goto npk_package_add_file_return_with_error;
if( ( res = npk_alloc_copy_string( &eb->localname_, filename ) ) != NPK_SUCCESS )
goto npk_package_add_file_return_with_error;
if( ( res = npk_alloc_copy_string( &eb->name_, namebuf ) ) != NPK_SUCCESS )
goto npk_package_add_file_return_with_error;
eb->info_.nameLength_ = (NPK_SIZE)strlen( eb->name_ );
if( ( res = npk_package_add_entity( package, eb ) ) != NPK_SUCCESS )
goto npk_package_add_file_return_with_error;
if( lpEntity )
*lpEntity = eb;
return NPK_SUCCESS;
npk_package_add_file_return_with_error:
NPK_SAFE_FREE( eb );
return res;
}
NPK_ENTITY _npk_package_add_file( NPK_PACKAGE package, NPK_CSTR filename, NPK_CSTR entityname )
{
NPK_ENTITY e = NULL;
if( NPK_SUCCESS == npk_package_add_file( package, filename, entityname, &e ) )
return e;
return NULL;
}
NPK_RESULT __npk_package_remove_entity( NPK_PACKAGE package, NPK_ENTITY entity, bool deepRemove )
{
NPK_ENTITYBODY* eb = entity;
NPK_PACKAGEBODY* pb = package;
NPK_BUCKET* bucket = NULL;
if( !entity )
return npk_error( NPK_ERROR_EntityIsNull );
if( !package )
return npk_error( NPK_ERROR_PackageIsNull );
if( eb->owner_ != package )
return npk_error( NPK_ERROR_EntityIsNotInThePackage );
bucket = pb->bucket_[npk_get_bucket(eb->name_)];
if( eb->prev_ )
eb->prev_->next_ = eb->next_;
if( eb->next_ )
eb->next_->prev_ = eb->prev_;
if( eb->prevInBucket_ )
eb->prevInBucket_->nextInBucket_ = eb->nextInBucket_;
if( eb->nextInBucket_ )
eb->nextInBucket_->prevInBucket_ = eb->prevInBucket_;
if( eb == pb->pEntityHead_ )
pb->pEntityHead_ = eb->next_;
if( eb == pb->pEntityTail_ )
pb->pEntityTail_ = eb->prev_;
if( eb == bucket->pEntityHead_ )
bucket->pEntityHead_ = eb->nextInBucket_;
if( eb == bucket->pEntityTail_ )
bucket->pEntityTail_ = eb->prevInBucket_;
pb->pEntityLatest_ = eb->next_;
--pb->info_.entityCount_;
if( deepRemove )
{
NPK_SAFE_FREE( eb->name_ );
NPK_SAFE_FREE( eb->localname_ );
NPK_SAFE_FREE( eb );
}
else
{
eb->next_ = NULL;
eb->prev_ = NULL;
eb->nextInBucket_ = NULL;
eb->prevInBucket_ = NULL;
}
return NPK_SUCCESS;
}
NPK_RESULT npk_package_remove_entity( NPK_PACKAGE package, NPK_ENTITY entity )
{
return __npk_package_remove_entity( package, entity, true );
}
NPK_RESULT npk_package_detach_entity( NPK_PACKAGE package, NPK_ENTITY entity )
{
return __npk_package_remove_entity( package, entity, false );
}
NPK_RESULT __npk_package_remove_all_entity( NPK_PACKAGE package, bool deepRemove );
NPK_RESULT npk_package_detach_all_entity( NPK_PACKAGE package )
{
return __npk_package_remove_all_entity( package, false );
}
#endif /* NPK_DEV */
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab4/src/example/app/main.c | #include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
pid_t pid;
printf("Порождение процесса 1 PID = %d PPID = %d\n", getppid(), getppid());
// Порождение второго процесса
if ( (pid = fork()) == -1 )
printf("Ошибка!\n");
else if (pid == 0) {
printf("Порождение процесса 2 PID = %d PPID = %d\n", getpid(), getppid());
// Порождение четвертого процесса
if ( (pid = fork()) == -1 )
printf("Ошибка!\n");
else if (pid == 0) {
printf("Порождение процесса 4 PID = %d PPID = %d\n", getpid(), getppid());
printf("Завершился процесс 4 PID = %d PPID = %d\n", getpid(), getppid());
execl("/bin/ls", "ls", NULL);
}
printf("Завершился процесс 2 PID = %d PPID = %d\n", getpid(), getppid());
exit(0);
} else sleep(1); //задержка родительского процесса
// Порождение третьего процесса
if ( (pid = fork()) == -1 )
printf("Ошибка!\n");
else if (pid == 0) {
printf("Порождение 3 PID = %d PPID = %d\n", getpid(), getppid());
printf("Завершился процесс 3: PID = %d, PPID = %d\n", getpid(), getppid());
exit(0);
} else sleep(1);
printf("Завершился процесс 1: PID = %d, PPID = %d\n", getpid(), getppid());
exit(0);
return 1;
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab5/src/example2/src/main.c | #include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
size_t sizeRead, sizeWrite;
char string[255];
/* Считываем данные из стандартного потока ввода */
sizeRead = read(0, string, 255);
if (sizeRead <= 0) {
printf("Can\'t read.\n");
return(-1);
}
(void) umask(0);
if ((fd = open("myfile", O_WRONLY | O_CREAT, 0666)) < 0)
{
printf("Can\'t open file\n");
return(-1);
}
/* Запись в файл */
sizeWrite = write(fd, string, sizeRead);
/* Вывод на экран */
//sizeWrite = write(1, string, sizeRead);
if (sizeWrite != sizeRead)
{
printf("Can\'t write all string\n");
return(-1);
}
if (close(fd) < 0)
{
printf("Can\'t close file\n");
}
return 0;
} |
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab5/src/option5-part3/src/main.c | //библиотеки
#include <unistd.h> //read()
#include <stdio.h> //printf()
#include <stdlib.h> //calloc(), realloc(), free()
#include <string.h> //strcpy(), strlen(), strcat()
//прототипы
struct WordNode
{
char* word;
struct WordNode* left;
struct WordNode* right;
};
struct WordNode* WordNode__Constructor(struct WordNode* object, char* word);
struct WordNode* WordNode__Destructor(struct WordNode* object);
struct WordNode* WordNode__add_top(struct WordNode* object, char* word);
struct WordNode* WordNode__get_bottom(struct WordNode* object);
struct WordNode* WordNode__get_by_index(struct WordNode* object, int index);
void WordNode__set_word(struct WordNode* object, char* word);
struct WordNode* get_words_file_list(const char path[]);
char* copy_strg1_to_strg2(char* string1, char* string2);
//главная функция
int main()
{
struct WordNode* list_file_words = get_words_file_list("../lorem100.html");
struct WordNode* string_list = NULL;
struct WordNode* result = NULL;
const int buffer_size = 1;
char buffer[buffer_size];
int str_size = 0;
char* str = (char*) calloc(str_size, sizeof(char*));
while(read(0, buffer, buffer_size))
{
char character = buffer[0];
if (character == '\n')
{
string_list = WordNode__add_top(string_list, str);
str_size = 0;
str = (char*) realloc(str, str_size * sizeof(char));
continue;
}
str_size += 1;
str = (char*) realloc(str, str_size * sizeof(char));
str[str_size - 1] = character;
}
free(str);
printf(" ~ ~ ~ ~ ~ file descriptor = 0 ~ ~ ~ ~ ~\n");
for (struct WordNode* temp = WordNode__get_bottom(string_list); temp != NULL; temp = temp->right)
{
printf("%s\n", temp->word);
}
int index_file_word = 0;
for (struct WordNode* temp = WordNode__get_bottom(string_list); temp != NULL; temp = temp->right)
{
char* string1 = temp->word;
char* string2 = WordNode__get_by_index(list_file_words, index_file_word)->word;
char* strng = copy_strg1_to_strg2(string1, string2);
WordNode__set_word(temp, strng);
free(strng);
index_file_word += 1;
}
for (struct WordNode* temp = WordNode__get_bottom(string_list); temp != NULL; temp = temp->right)
{
str_size = 0;
str = (char*) calloc(str_size, sizeof(char));
if (str == NULL) printf("Память не выделилась\n");
struct WordNode* words_list = NULL;
for (int i = 0; ; i++)
{
char ch = temp->word[i];
if (ch == '\0') break;
if (ch == ' ')
{
words_list = WordNode__add_top(words_list, str);
str_size = 0;
str = (char*) realloc(str, str_size * sizeof(char));
continue;
}
str_size += 1;
str = (char*) realloc(str, str_size * sizeof(char));
if (str == NULL) printf("Память не выделилась\n");
str[str_size - 1] = ch;
}
int number = atoi( WordNode__get_bottom(words_list)->word );
if( number != 0 && number % 2 == 0 )
{
result = WordNode__add_top(result, temp->word);
}
words_list = WordNode__Destructor(words_list);
free(str);
}
string_list = WordNode__Destructor(string_list);
printf(" ~ ~ ~ ~ ~ file descriptor = 1 ~ ~ ~ ~ ~\n");
for(struct WordNode* temp = WordNode__get_bottom(result); temp != NULL ; temp = temp->right)
{
int file_descriptor = 1;
char* buf = temp->word;
int buf_size = strlen(buf);
write(file_descriptor, buf, buf_size);
write(file_descriptor, "\n", 1);
}
result = WordNode__Destructor(result);
list_file_words = WordNode__Destructor(list_file_words);
return 0;
}
//реализация прототипов
struct WordNode* WordNode__Constructor(struct WordNode* object, char* word)
{
object = (struct WordNode*) malloc(sizeof(struct WordNode));
if (object == NULL) printf("Память не выделилась\n");
//printf("%p Constructor\n", object);
object->left = NULL;
object->right = NULL;
object->word = (char*) calloc(strlen(word), sizeof(char));
if (object->word == NULL) printf("Память не выделилась\n");
strcpy(object->word, word);
return object;
}
struct WordNode* WordNode__Destructor(struct WordNode* object)
{
for (struct WordNode* temp = object; temp != NULL; )
{
free(temp->word);
object = temp;
//printf("%p Destructor\n", object);
temp = temp->left;
free(object);
}
return NULL;
}
struct WordNode* WordNode__add_top(struct WordNode* object, char* word)
{
if (word == NULL)
{
return object;
}
if (word[0] == '\0')
{
return object;
}
struct WordNode* new_node = WordNode__Constructor(new_node, word);
new_node->left = object;
if (object == NULL)
{
return new_node;
}
object->right = new_node;
return new_node;
}
struct WordNode* WordNode__get_bottom(struct WordNode* object)
{
if (object == NULL)
{
return NULL;
}
struct WordNode* temp = object;
while(temp->left != NULL)
{
temp = temp->left;
}
return temp;
}
struct WordNode* WordNode__get_by_index(struct WordNode* object, int index)
{
struct WordNode* temp = WordNode__get_bottom(object);
for(int i = 0; temp != NULL && i != index; temp = temp->right, i += 1)
{
}
return temp;
}
void WordNode__set_word(struct WordNode* object, char* word)
{
free(object->word);
object->word = (char*) calloc(strlen(word), sizeof(char));
if ( object->word == NULL )
{
printf("Память не выделилась\n");
return;
}
strcpy(object->word, word);
}
struct WordNode* get_words_file_list(const char path[])
{
FILE* file_pointer = fopen(path, "r");
if (file_pointer == NULL)
{
printf("File %s not opened\n", path);
return 0;
}
int word_size = 0;
char* word = (char*) calloc(word_size, sizeof(char));
if (word == NULL) printf("Память не выделилась\n");
struct WordNode* list_file_words = NULL;
while(!feof(file_pointer))
{
char character = fgetc(file_pointer);
if(
character == ' '
|| character == ','
|| character == '.'
|| character == '!'
)
{
if (word_size == 0)
{
continue;
}
list_file_words = WordNode__add_top(list_file_words, word);
word_size = 0;
word = (char*) realloc(word, word_size * sizeof(char));
continue;
}
word_size += 1;
word = (char*) realloc(word, word_size * sizeof(char));
word[word_size - 1] = character;
}
if (word != NULL)
{
free(word);
}
fclose(file_pointer);
return list_file_words;
}
char* copy_strg1_to_strg2(char* string1, char* string2)
{
int string1_size = strlen(string1);
int string2_size = strlen(string2);
int result_string_size = string1_size + string2_size;
char* result_string = (char*) calloc(result_string_size, sizeof(char));
if (result_string == NULL) printf("Память не выделилась\n");
strcpy(result_string, string1);
strcat(result_string, string2);
return result_string;
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab4/src/option5/app/main.c | <gh_stars>0
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
// 0112233
// 1234567
// if0
// if1
// if2
// if4
// if5
// if3
// if6
// if7
int main()
{
pid_t pid;
// print 0
printf("start pr 0 PID = %d PPID = %d\n", getpid(), getppid());
//1
if ((pid = fork()) == -1) printf("Err\n");
else if(pid == 0)
{
//print 1
printf("\tstart pr 1 PID = %d PPID = %d\n", getpid(), getppid());
//2
if ((pid = fork()) == -1) printf("Err\n");
else if (pid == 0)
{
//print 2
printf("\t\tstart pr 2 PID = %d PPID = %d\n", getpid(), getppid());
//4
if ((pid = fork()) == -1) printf("Err\n");
else if (pid == 0)
{
//print 4
printf("\t\t\tstart pr 4 PID = %d PPID = %d\n", getpid(), getppid());
printf("\t\t\tend pr 4\n");
exit(0);
} else sleep(1);
//5
if ((pid = fork()) == -1) printf("Err\n");
else if (pid == 0)
{
//print 5
printf("\t\t\tstart pr 5 PID = %d PPID = %d\n", getpid(), getppid());
printf("\t\tend and exec(df) pr 5\n");
printf("\n");
printf("\t\t\t\t= = = = = run $df\n");
execl("/bin/df","df",NULL);
} else sleep(1);
exit(0);
}
else sleep(3);
//3
if ((pid = fork()) == -1) printf("Err\n");
else if (pid == 0)
{
//print 3
printf("\t\tstart pr 3 PID = %d PPID = %d\n", getpid(), getppid());
//6
if ((pid = fork()) == -1) printf("Err\n");
else if (pid == 0)
{
//print 6
printf("\t\t\tstart pr 6 PID = %d PPID = %d\n", getpid(), getppid());
printf("\t\t\tend pr 6\n");
exit(0);
} else sleep(1);
//7
if ((pid = fork()) == -1) printf("Err\n");
else if (pid == 0)
{
//print 7
printf("\t\t\tstart pr 7 PID = %d PPID = %d\n", getpid(), getppid());
printf("\t\t\tend pr 7\n");
exit(0);
} else sleep(1);
printf("\t\tend pr 3\n");
exit(0);
}
else sleep(3);
printf("\tend pr 1\n");
exit(0);
}
else sleep(10);
printf("End program...\n");
return 0;
}
|
Pavel-Innokentevich-Galanin/BrSTU-4-sem_Operating-Systems-and-System-Programming | lab7/src/option5/two.c | #include <unistd.h>
#include <stdio.h> //printf()
#include <stdlib.h> //rand()
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>
#include <time.h> //time(), localetime()
int get_random(int x1, int x2);
void print_real_time();
int main() {
char symbols[] = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtVvUuWwXxYyZz"; //символы
sem_t* get = sem_open(
"sem_one", //const char* name
O_CREAT, //int oflag
0777, //mode_t mode
0 //unsigned int value
);
sem_t* put = sem_open(
"sem_two", //const char* name
O_CREAT, //int oflag
0777, //mode_t mode
0 //unsigned int value
);
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
(void)umask(0);
while (1) //бесконечный цикл
{
sem_wait(get);
pthread_mutex_lock(&mutex);
int fd = open( //открываем файл
"file.bin", //*.bin - бинарный файл
O_RDWR,
0777 //- rwx rwx rwx (0 111 111 111)
);
char str[1024]; //строку, которую возьмем из файла
read(fd, &str, sizeof(str)); //записали данные в строку
print_real_time();
printf(
"Process %d get message: %s\n", //форматная строка
getpid(), //PID - номер процесса
str //строка
);
print_real_time();
int length = atoi(str); //длина строки (длины цифры)
for(int i = 0; i < length; i++) //выводим (length - 1) рандомную букву
{
int random_number = get_random(0, sizeof(symbols)); //рандом число из массива букв
char random_character = symbols[random_number]; //получаем символ
printf("%c", random_character); //печатаем символ
}
printf("\n\n");
close(fd); //закрываем файл
pthread_mutex_unlock(&mutex);
sem_post(put);
}
pthread_mutex_destroy(&mutex);
sem_close(put);
sem_close(get);
return 0;
}
int get_random(int x1, int x2)
{
int a = x1 < x2 ? x1 : x2; //a = min(a, b)
int b = x1 > x2 ? x1 : x2; //b = max(a, b)
return rand() % (b - a + 1) + a; //random [a; b]
}
void print_real_time()
{
time_t now = time(0);
struct tm *ltm = localtime(&now);
printf(
"%02d:%02d:%02d : ",
1 + ltm->tm_hour, // часы
1 + ltm->tm_min, // минуты
1 + ltm->tm_sec // секунды
);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.