repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
RonxBulld/anvm
src/Gpu.h
#pragma once #include <map> using namespace std; class Gpu { private: SDL_Surface *SurfacePool[9]; SDL_Renderer *DrawRenderer[10]; Point StartDrawPoint[10]; map<int, SDL_Surface*> ResPool; SDL_Surface *CreateSurface(int width, int height); int RequestResourceHandle(); SDL_Surface *GetSurface(int handle); Uint32 __get_pixel(SDL_Surface *Surface, int x, int y); void __put_pixel(SDL_Surface *Surface, int x, int y, Uint32 pixel); void __plot_circle_points(SDL_Surface *Surface, int xc, int yc, int x, int y, Uint32 c); void __bresenham_circle(SDL_Surface *Surface, int xc, int yc, int radius, Uint32 c); public: Gpu(); ~Gpu(); int AllocSurface(); void FreeSurface(int index); int LoadPicture(const char *FileName, unsigned int index); void FreePicture(int Handle); void DrawPicture(int page, int pic, int dx, int dy, int w, int h, int x, int y, int mode); void CloneSurface(int SrcSurfaceHandle, int DestSurfaceHandle, int x = 0, int y = 0); void FillSurface(int SurfaceHandle, int x, int y, int w, int h, int color); void WritePixel(int SurfaceHandle, int x, int y, int color); unsigned int ReadPixel(int SurfaceHandle, int x, int y); int GetPictureWidth(int Handle); int GetPictureHeigth(int Handle); void SetPenColor(int Handle, int Color); void MovePen(int Handle, int x, int y); void DrawLine(int Handle, int x, int y); void DrawRectangle(int Handle, int x1, int y1, int x2, int y2); void DrawCircle(int Handle, int x, int y, int r); };
RonxBulld/anvm
src/Storage.h
#pragma once #include <map> using namespace std; class Storage { private: map<int, FILE*> FilePool; public: void OpenFile(const char *FileName, const int Handle); void CloseFile(const int Handle); int ReadFile_Int(const int Handle, const int Offset); float ReadFile_Float(const int Handle, const int Offset); unsigned char *ReadFile_String(const int Handle, const int Offset); void WriteFile_Int32(const int Handle, const int Offset, const int Data); void WriteFile_String(const int Handle, const int Offset, const char *Data); bool Eof(const int Handle); unsigned int GetFileSize(const int Handle); unsigned int GetPosition(const int Handle); void MovePosition(const int Handle, const int Position); };
RonxBulld/anvm
src/CoreConst.h
#pragma once #define Z 1 #define B 2 #define BE 3 #define A 4 #define AE 5 #define NZ 6 #define RP 0 #define RF 1 #define RS 2 #define RB 3 #define R0 4 #define R1 5 #define R2 6 #define R3 7 #define REG 0 #define REG_EX 1 #define IMM 2 #define IMM_EX 3 #define DWORD 0 #define WORD 1 #define BYTE 2 #define FLOAT 3 #define INT 4 #define ADD 0 #define SUB 1 #define MUL 2 #define DIV 3 #define MOD 4 #define ENV_SIM 0
RonxBulld/anvm
src/ErrorLog.h
#pragma once void Log(const char *fmt, ...); void Error(const char *fmt, ...); void vError(const char *fmt, va_list ap);
GEEKiDoS/KsDumper
KsDumperDriver/NTUndocumented.h
#pragma once #include <ntddk.h> typedef struct _KAPC_STATE { LIST_ENTRY ApcListHead[MaximumMode]; struct _KPROCESS *Process; BOOLEAN KernelApcInProgress; BOOLEAN KernelApcPending; BOOLEAN UserApcPending; } KAPC_STATE, *PKAPC_STATE, *PRKAPC_STATE; typedef enum _SYSTEM_INFORMATION_CLASS { SystemProcessInformation = 5 } SYSTEM_INFORMATION_CLASS; typedef enum _MEMORY_INFORMATION_CLASS { MemoryBasicInformation, MemoryWorkingSetInformation, MemoryMappedFilenameInformation, MemoryRegionInformation, MemoryWorkingSetExInformation } MEMORY_INFORMATION_CLASS; typedef struct _MEMORY_BASIC_INFORMATION { PVOID BaseAddress; PVOID AllocationBase; INT32 AllocationProtect; SIZE_T RegionSize; INT32 State; INT32 Protect; INT32 Type; } MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION; NTKERNELAPI NTSTATUS IoCreateDriver(IN PUNICODE_STRING DriverName, OPTIONAL IN PDRIVER_INITIALIZE InitializationFunction); NTKERNELAPI VOID KeStackAttachProcess(__inout struct _KPROCESS * PROCESS, __out PRKAPC_STATE ApcState); NTKERNELAPI VOID KeUnstackDetachProcess(__in PRKAPC_STATE ApcState); NTKERNELAPI NTSTATUS NTAPI MmCopyVirtualMemory(IN PEPROCESS FromProcess, IN PVOID FromAddress, IN PEPROCESS ToProcess, OUT PVOID ToAddress, IN SIZE_T BufferSize, IN KPROCESSOR_MODE PreviousMode, OUT PSIZE_T NumberOfBytesCopied); NTSYSAPI NTSTATUS NTAPI ZwQuerySystemInformation(IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL); NTSYSAPI NTSTATUS NTAPI ZwQueryVirtualMemory(IN HANDLE ProcessHandle, IN PVOID BaseAddress, IN MEMORY_INFORMATION_CLASS MemoryInformationClass, OUT PVOID MemoryInformation, IN SIZE_T MemoryInformationLength, OUT PSIZE_T ReturnLength OPTIONAL); NTKERNELAPI NTSTATUS PsLookupProcessByProcessId(IN HANDLE ProcessId, OUT PEPROCESS *Process); NTKERNELAPI PVOID PsGetProcessSectionBaseAddress(__in PEPROCESS Process); NTKERNELAPI PPEB NTAPI PsGetProcessPeb(IN PEPROCESS Process);
GEEKiDoS/KsDumper
KsDumperDriver/ProcessLister.h
#pragma once #include <ntddk.h> #pragma pack(push, 1) typedef struct _PROCESS_SUMMARY { INT32 ProcessId; PVOID MainModuleBase; WCHAR MainModuleFileName[256]; UINT32 MainModuleImageSize; PVOID MainModuleEntryPoint; BOOLEAN WOW64; } PROCESS_SUMMARY, *PPROCESS_SUMMARY; typedef struct _MODULE_SUMMARY { PVOID ModuleBase; WCHAR ModuleFileName[256]; UINT32 ModuleImageSize; PVOID ModuleEntryPoint; BOOLEAN WOW64; } MODULE_SUMMARY, *PMODULE_SUMMARY; #pragma pack(pop) typedef struct _SYSTEM_PROCESS_INFORMATION { ULONG NextEntryOffset; ULONG NumberOfThreads; LARGE_INTEGER SpareLi1; LARGE_INTEGER SpareLi2; LARGE_INTEGER SpareLi3; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ImageName; KPRIORITY BasePriority; HANDLE UniqueProcessId; HANDLE InheritedFromUniqueProcessId; ULONG HandleCount; ULONG SessionId; ULONG_PTR PageDirectoryBase; SIZE_T PeakVirtualSize; SIZE_T VirtualSize; ULONG PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; SIZE_T PrivatePageCount; LARGE_INTEGER ReadOperationCount; LARGE_INTEGER WriteOperationCount; LARGE_INTEGER OtherOperationCount; LARGE_INTEGER ReadTransferCount; LARGE_INTEGER WriteTransferCount; LARGE_INTEGER OtherTransferCount; } SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION; typedef struct _LDR_DATA_TABLE_ENTRY { LIST_ENTRY InLoadOrderLinks; LIST_ENTRY InMemoryOrderLinks; CHAR Reserved0[0x10]; PVOID DllBase; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; typedef struct _PEB_LDR_DATA { ULONG Length; BOOLEAN Initialized; PVOID SsHandler; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID EntryInProgress; } PEB_LDR_DATA, *PPEB_LDR_DATA; typedef struct _PEB64 { CHAR Reserved[0x10]; PVOID ImageBaseAddress; PPEB_LDR_DATA Ldr; } PEB64, *PPEB64; typedef struct _IMAGE_DOS_HEADER { USHORT e_magic; USHORT e_cblp; USHORT e_cp; USHORT e_crlc; USHORT e_cparhdr; USHORT e_minalloc; USHORT e_maxalloc; USHORT e_ss; USHORT e_sp; USHORT e_csum; USHORT e_ip; USHORT e_cs; USHORT e_lfarlc; USHORT e_ovno; USHORT e_res[4]; USHORT e_oemid; USHORT e_oeminfo; USHORT e_res2[10]; LONG e_lfanew; } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; typedef struct _PE_HEADER { CHAR Signature[4]; USHORT Machine; USHORT NumberOfSections; UINT32 TimeDateStamp; UINT32 PointerToSymbolTable; UINT32 NumberOfSymbols; USHORT SizeOfOptionalHeader; USHORT Characteristics; USHORT Magic; } PE_HEADER, *PPE_HEADER; #define PE_HEADER_MAGIC_OFFSET 0x18 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IS_WOW64_PE( baseAddress ) (*((USHORT*)((CHAR *)baseAddress + \ ((PIMAGE_DOS_HEADER)baseAddress)->e_lfanew + PE_HEADER_MAGIC_OFFSET)) \ == IMAGE_NT_OPTIONAL_HDR32_MAGIC) NTSTATUS GetProcessList(PVOID listedProcessBuffer, INT32 bufferSize, PINT32 requiredBufferSize, PINT32 processCount); NTSTATUS QueryProcessInfo(INT32 pid, PVOID buffer, INT32 bufferSize, PINT32 moduleCount);
GEEKiDoS/KsDumper
KsDumperDriver/ProcessLister.c
<reponame>GEEKiDoS/KsDumper #include "NTUndocumented.h" #include "ProcessLister.h" #include "Utility.h" static PSYSTEM_PROCESS_INFORMATION GetRawProcessList() { ULONG bufferSize = 0; PVOID bufferPtr = NULL; if (ZwQuerySystemInformation(SystemProcessInformation, 0, bufferSize, &bufferSize) == STATUS_INFO_LENGTH_MISMATCH) { bufferPtr = ExAllocatePool(NonPagedPool, bufferSize); if (bufferPtr != NULL) { ZwQuerySystemInformation(SystemProcessInformation, bufferPtr, bufferSize, &bufferSize); } } return (PSYSTEM_PROCESS_INFORMATION)bufferPtr; } static ULONG CalculateProcessListOutputSize(PSYSTEM_PROCESS_INFORMATION rawProcessList) { int size = 0; while (rawProcessList->NextEntryOffset) { size += sizeof(PROCESS_SUMMARY); rawProcessList = (PSYSTEM_PROCESS_INFORMATION)(((CHAR*)rawProcessList) + rawProcessList->NextEntryOffset); } return size; } static PLDR_DATA_TABLE_ENTRY GetMainModuleDataTableEntry(PPEB64 peb) { if (SanitizeUserPointer(peb, sizeof(PEB64))) { if (peb->Ldr) { if (SanitizeUserPointer(peb->Ldr, sizeof(PEB_LDR_DATA))) { if (!peb->Ldr->Initialized) { int initLoadCount = 0; while (!peb->Ldr->Initialized && initLoadCount++ < 4) { DriverSleep(250); } } if (peb->Ldr->Initialized) { return CONTAINING_RECORD(peb->Ldr->InLoadOrderModuleList.Flink, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); } } } } return NULL; } NTSTATUS GetProcessList(PVOID listedProcessBuffer, INT32 bufferSize, PINT32 requiredBufferSize, PINT32 processCount) { PPROCESS_SUMMARY processSummary = (PPROCESS_SUMMARY)listedProcessBuffer; PSYSTEM_PROCESS_INFORMATION rawProcessList = GetRawProcessList(); PVOID listHeadPointer = rawProcessList; *processCount = 0; if (rawProcessList) { int expectedBufferSize = CalculateProcessListOutputSize(rawProcessList); if (!listedProcessBuffer || bufferSize < expectedBufferSize) { *requiredBufferSize = expectedBufferSize; return STATUS_INFO_LENGTH_MISMATCH; } while (rawProcessList->NextEntryOffset) { PEPROCESS targetProcess; KAPC_STATE state; if (NT_SUCCESS(PsLookupProcessByProcessId(rawProcessList->UniqueProcessId, &targetProcess))) { PVOID mainModuleBase = NULL; PVOID mainModuleEntryPoint = NULL; UINT32 mainModuleImageSize = 0; PWCHAR mainModuleFileName = NULL; BOOLEAN isWow64 = 0; __try { KeStackAttachProcess(targetProcess, &state); __try { mainModuleBase = PsGetProcessSectionBaseAddress(targetProcess); if (mainModuleBase) { PPEB64 peb = (PPEB64)PsGetProcessPeb(targetProcess); if (peb) { PLDR_DATA_TABLE_ENTRY mainModuleEntry = GetMainModuleDataTableEntry(peb); mainModuleEntry = SanitizeUserPointer(mainModuleEntry, sizeof(LDR_DATA_TABLE_ENTRY)); if (mainModuleEntry) { mainModuleEntryPoint = mainModuleEntry->EntryPoint; mainModuleImageSize = mainModuleEntry->SizeOfImage; isWow64 = IS_WOW64_PE(mainModuleBase); mainModuleFileName = ExAllocatePool(NonPagedPool, 256 * sizeof(WCHAR)); RtlZeroMemory(mainModuleFileName, 256 * sizeof(WCHAR)); RtlCopyMemory(mainModuleFileName, mainModuleEntry->FullDllName.Buffer, 256 * sizeof(WCHAR)); } } } } __except (GetExceptionCode()) { DbgPrintEx(0, 0, "Peb Interaction Failed.\n"); } } __finally { KeUnstackDetachProcess(&state); } if (mainModuleFileName) { RtlCopyMemory(processSummary->MainModuleFileName, mainModuleFileName, 256 * sizeof(WCHAR)); ExFreePool(mainModuleFileName); processSummary->ProcessId = rawProcessList->UniqueProcessId; processSummary->MainModuleBase = mainModuleBase; processSummary->MainModuleEntryPoint = mainModuleEntryPoint; processSummary->MainModuleImageSize = mainModuleImageSize; processSummary->WOW64 = isWow64; processSummary++; (*processCount)++; } ObDereferenceObject(targetProcess); } rawProcessList = (PSYSTEM_PROCESS_INFORMATION)(((CHAR*)rawProcessList) + rawProcessList->NextEntryOffset); } ExFreePool(listHeadPointer); return STATUS_SUCCESS; } } NTSTATUS QueryProcessInfo(INT32 pid, PVOID buffer, INT32 bufferSize, PINT32 moduleCount) { PEPROCESS targetProcess; KAPC_STATE state; PMODULE_SUMMARY summary = (PMODULE_SUMMARY)buffer; if (NT_SUCCESS(PsLookupProcessByProcessId(pid, &targetProcess))) { PPEB64 peb = (PPEB64)PsGetProcessPeb(targetProcess); int count = 0; PVOID ModuleBase = NULL; PVOID ModuleEntryPoint = NULL; INT32 ModuleImageSize = 0; PWCHAR ModuleFileName = ExAllocatePool(NonPagedPool, 256 * sizeof(WCHAR)); BOOLEAN isWow64 = 0; KeStackAttachProcess(targetProcess, &state); if (peb->Ldr->Initialized) { PLIST_ENTRY pEntry = NULL; PLIST_ENTRY pHeadEntry = &peb->Ldr->InLoadOrderModuleList; for (pEntry = pHeadEntry->Flink; pEntry != pHeadEntry; pEntry = pEntry->Flink) { if (++count * sizeof(MODULE_SUMMARY) > bufferSize) { return STATUS_INFO_LENGTH_MISMATCH; } PLDR_DATA_TABLE_ENTRY moduleEntry = SanitizeUserPointer(CONTAINING_RECORD(pEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks), sizeof(LDR_DATA_TABLE_ENTRY)); if (moduleEntry) { RtlZeroMemory(ModuleFileName, 256 * sizeof(WCHAR)); RtlCopyMemory(ModuleFileName, moduleEntry->FullDllName.Buffer, moduleEntry->FullDllName.Length * sizeof(WCHAR)); ModuleBase = moduleEntry->DllBase; ModuleImageSize = moduleEntry->SizeOfImage; ModuleEntryPoint = moduleEntry->EntryPoint; isWow64 = IS_WOW64_PE(ModuleBase); KeUnstackDetachProcess(&state); RtlCopyMemory(summary->ModuleFileName, ModuleFileName, 256 * sizeof(WCHAR)); summary->ModuleBase = ModuleBase; summary->ModuleEntryPoint = ModuleEntryPoint; summary->ModuleImageSize = ModuleImageSize; summary->WOW64 = isWow64; summary++; KeStackAttachProcess(targetProcess, &state); } } } KeUnstackDetachProcess(&state); ExFreePool(ModuleFileName); *moduleCount = count; } return STATUS_SUCCESS; }
sansuba/SSRecPlayer
SSRP/SSRP.h
// // SSRP.h // SSRP // // Created by <NAME> on 11/12/15. // Copyright © 2015 Persystance Networks. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for SSRP. FOUNDATION_EXPORT double SSRPVersionNumber; //! Project version string for SSRP. FOUNDATION_EXPORT const unsigned char SSRPVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <SSRP/PublicHeader.h> #import "VMRecorder.h"
sansuba/SSRecPlayer
SSRP/VMRecorder.h
<gh_stars>0 // // VMRecorder.h // AVRecorder // // Created by <NAME> on 9/8/15. // Copyright (c) 2015 Persystance Networks. All rights reserved. // #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> typedef NS_ENUM(NSUInteger, RecordFormat) { CAF, M4A }; typedef void(^BlockPlayingProgress)(float progress, float currentTime); typedef void(^BlockPlayingDone)(BOOL done); typedef void(^BlockRecordingDone)(BOOL done); @interface VMRecorder : UIView <AVAudioRecorderDelegate, AVAudioPlayerDelegate> @property (strong, nonatomic) AVAudioRecorder *audioRecorder; @property (strong, nonatomic) AVAudioPlayer *audioPlayer; -(NSURL*)recorderUrl; -(BOOL)record; -(BOOL)recordingWithBlock:(BlockRecordingDone)block; -(BOOL)isRecording; -(BOOL)isPlaying; -(void)play; -(void)playWithURL:(NSURL*)url; -(void)playWithData:(NSData*)data; -(void)stop; -(void)initializeRecorderM4A; -(void)playerProgress:(BlockPlayingProgress)progress withDoneBlock:(BlockPlayingDone)done; @end
frugalos/openstack_liberasurecode
src/erasurecode_helpers.c
<filename>src/erasurecode_helpers.c /* * Copyright 2014 <NAME>, <NAME>, <NAME> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY * THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * liberasurecode API helpers implementation * * vi: set noai tw=79 ts=4 sw=4: */ #include <assert.h> #include <stdio.h> #include <stdarg.h> #include <zlib.h> #include "erasurecode_backend.h" #include "erasurecode_helpers.h" #include "erasurecode_helpers_ext.h" #include "erasurecode_stdinc.h" #include "erasurecode_version.h" #include "alg_sig.h" #include "erasurecode_log.h" /* ==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~== */ static bool is_fragment(char *buf) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic == LIBERASURECODE_FRAG_HEADER_MAGIC) { return true; } return false; } /** * Memory Management Methods * * The following methods provide wrappers for allocating and deallocating * memory. */ void *get_aligned_buffer16(int size) { void *buf; /** * Ensure all memory is aligned to 16-byte boundaries * to support 128-bit operations */ if (posix_memalign(&buf, 16, size) != 0) { return NULL; } memset(buf, 0, size); return buf; } /** * Allocate a zero-ed buffer of a specific size. * * @param size integer size in bytes of buffer to allocate * @return pointer to start of allocated buffer or NULL on error */ void * alloc_zeroed_buffer(int size) { return alloc_and_set_buffer(size, 0); } /** * Allocate a buffer of a specific size and set its' contents * to the specified value. * * @param size integer size in bytes of buffer to allocate * @param value * @return pointer to start of allocated buffer or NULL on error */ void * alloc_and_set_buffer(int size, int value) { void * buf = NULL; /* buffer to allocate and return */ /* Allocate and zero the buffer, or set the appropriate error */ buf = malloc((size_t) size); if (buf) { buf = memset(buf, value, (size_t) size); } return buf; } /** * Deallocate memory buffer if it's not NULL. This methods returns NULL so * that you can free and reset a buffer using a single line as follows: * * my_ptr = check_and_free_buffer(my_ptr); * * @return NULL */ void * check_and_free_buffer(void * buf) { if (buf) free(buf); return NULL; } char *alloc_fragment_buffer(int size) { char *buf; fragment_header_t *header = NULL; size += sizeof(fragment_header_t); buf = get_aligned_buffer16(size); if (buf) { header = (fragment_header_t *) buf; header->magic = LIBERASURECODE_FRAG_HEADER_MAGIC; } return buf; } int free_fragment_buffer(char *buf) { fragment_header_t *header; if (NULL == buf) { return -1; } buf -= sizeof(fragment_header_t); header = (fragment_header_t *) buf; if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (free fragment)!"); return -1; } free(buf); return 0; } /* ==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~== */ /** * Return total fragment length (on-disk, on-wire) * * @param buf - pointer to fragment buffer * * @return fragment size on disk */ uint64_t get_fragment_size(char *buf) { if (NULL == buf) return -1; return get_fragment_buffer_size(buf) + sizeof(fragment_header_t); } /** * Compute a size aligned to the number of data and the underlying wordsize * of the EC algorithm. * * @param instance, ec_backend_t instance (to extract args) * @param data_len, integer length of data in bytes * @return integer data length aligned with wordsize of EC algorithm */ int get_aligned_data_size(ec_backend_t instance, int data_len) { int k = instance->args.uargs.k; int w = instance->args.uargs.w; int word_size = w / 8; int alignment_multiple; int aligned_size = 0; /* * For Cauchy reed-solomon align to k*word_size*packet_size * For Vandermonde reed-solomon and flat-XOR, align to k*word_size */ if (EC_BACKEND_JERASURE_RS_CAUCHY == instance->common.id) { alignment_multiple = k * w * (sizeof(long) * 128); } else { alignment_multiple = k * word_size; } aligned_size = ((data_len + alignment_multiple - 1) / alignment_multiple) * alignment_multiple; return aligned_size; } /* ==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~== */ char *get_data_ptr_from_fragment(char *buf) { buf += sizeof(fragment_header_t); return buf; } int get_data_ptr_array_from_fragments(char **data_array, char **fragments, int num_fragments) { int i = 0, num = 0; for (i = 0; i < num_fragments; i++) { char *frag = fragments[i]; if (frag == NULL) { data_array[i] = NULL; continue; } data_array[i] = get_data_ptr_from_fragment(frag); num++; } return num; } int get_fragment_ptr_array_from_data(char **frag_array, char **data, int num_data) { int i = 0, num = 0; for (i = 0; i < num_data; i++) { char *data_ptr = frag_array[i]; if (data_ptr == NULL) { data[i] = NULL; continue; } data[i] = get_fragment_ptr_from_data(data_ptr); num++; } return num; } char *get_fragment_ptr_from_data_novalidate(char *buf) { buf -= sizeof(fragment_header_t); return buf; } char *get_fragment_ptr_from_data(char *buf) { fragment_header_t *header; buf -= sizeof(fragment_header_t); header = (fragment_header_t *) buf; if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get header ptr)!\n"); return NULL; } return buf; } /* ==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~== */ int set_fragment_idx(char *buf, int idx) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (idx check)!\n"); return -1; } header->meta.idx = idx; return 0; } int get_fragment_idx(char *buf) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get idx)!"); return -1; } return header->meta.idx; } int set_fragment_payload_size(char *buf, int size) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (size check)!"); return -1; } header->meta.size = size; return 0; } int get_fragment_payload_size(char *buf) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get size)!"); return -1; } return header->meta.size; } int set_fragment_backend_metadata_size(char *buf, int size) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (set fragment backend metadata size)!"); return -1; } header->meta.frag_backend_metadata_size = size; return 0; } int get_fragment_backend_metadata_size(char *buf) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get fragment backend metadata size)!"); return -1; } return header->meta.frag_backend_metadata_size; } int get_fragment_buffer_size(char *buf) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get size)!"); return -1; } return header->meta.size + header->meta.frag_backend_metadata_size; } int set_orig_data_size(char *buf, int orig_data_size) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (set orig data check)!"); return -1; } header->meta.orig_data_size = orig_data_size; return 0; } int get_orig_data_size(char *buf) { fragment_header_t *header = (fragment_header_t *) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get orig data check)!"); return -1; } return header->meta.orig_data_size; } int set_libec_version(char *buf) { if (!is_fragment(buf)) { return -1; } fragment_header_t *header = (fragment_header_t *) buf; header->libec_version = (uint32_t)LIBERASURECODE_VERSION; return 0; } int get_libec_version(char *buf, uint32_t *ver) { if (!is_fragment(buf)) { return -1; } fragment_header_t *header = (fragment_header_t *) buf; *ver = header->libec_version; return 0; } int set_backend_id(char *buf, ec_backend_id_t id) { if (!is_fragment(buf)) { return -1; } fragment_header_t *header = (fragment_header_t *) buf; header->meta.backend_id = (uint8_t)id; return 0; } int get_backend_id(char *buf, ec_backend_id_t *id) { if (!is_fragment(buf)) { return -1; } fragment_header_t *header = (fragment_header_t *) buf; *id = header->meta.backend_id; return 0; } int set_backend_version(char *buf, uint32_t version) { if (!is_fragment(buf)) { return -1; } fragment_header_t *header = (fragment_header_t *) buf; header->meta.backend_version = version; return 0; } int get_backend_version(char *buf, uint32_t *version) { if (!is_fragment(buf)) { return -1; } fragment_header_t *header = (fragment_header_t *) buf; *version = header->meta.backend_version; return 0; } /* ==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~== */ inline int set_checksum(ec_checksum_type_t ct, char *buf, int blocksize) { fragment_header_t* header = (fragment_header_t*) buf; char *data = get_data_ptr_from_fragment(buf); assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (set chksum)!\n"); return -1; } header->meta.chksum_type = ct; header->meta.chksum_mismatch = 0; switch(header->meta.chksum_type) { case CHKSUM_CRC32: header->meta.chksum[0] = crc32(0, (unsigned char *) data, blocksize); break; case CHKSUM_MD5: break; case CHKSUM_NONE: default: break; } return 0; } inline uint32_t* get_chksum(char *buf) { fragment_header_t* header = (fragment_header_t*) buf; assert(NULL != header); if (header->magic != LIBERASURECODE_FRAG_HEADER_MAGIC) { log_error("Invalid fragment header (get chksum)!"); return NULL; } return (uint32_t *) header->meta.chksum; } /* ==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~==~=*=~== */
Eiyeron/squint
src/AsepriteConnection.h
<filename>src/AsepriteConnection.h #ifndef _SQUINT_ASEPRITECONNECTION_H_ #define _SQUINT_ASEPRITECONNECTION_H_ #include "ixwebsocket/IXConnectionState.h" #include "ixwebsocket/IXWebSocket.h" #include "ixwebsocket/IXWebSocketMessageType.h" #include "raylib.h" #include <cstdint> #include <memory> #include <vector> #include <mutex> struct AsepriteImage { uint32_t width = 0; uint32_t height = 0; std::vector<Color> pixels{}; AsepriteImage() = default; AsepriteImage(AsepriteImage &&other) noexcept; AsepriteImage &operator=(AsepriteImage &&other) noexcept; AsepriteImage(const AsepriteImage &other) = delete; AsepriteImage &operator=(const AsepriteImage &other) = delete; }; struct AsepriteConnection { mutable std::mutex lastReadyImageMutex; AsepriteImage lastReadyImage; bool connected = false; void onMessage(std::shared_ptr<ix::ConnectionState> connectionState, ix::WebSocket &webSocket, const ix::WebSocketMessagePtr &msg); }; #endif // _SQUINT_ASEPRITECONNECTION_H_
Eiyeron/squint
src/Upscaler.h
<filename>src/Upscaler.h #ifndef _SQUINT_UPSCALER_H_ #define _SQUINT_UPSCALER_H_ #include "raylib.h" #include <string> #include <vector> class Upscaler { public: struct Uniform { enum class Type { Float, Int, }; Type type; std::string name; std::string uniformName; float value; float min; float max; }; Upscaler(const char *path); ~Upscaler(); void unloadShader(); void reload(); void addUniform(Uniform uniform); int getTextWidth() const; bool drawSettings(float x, float y); void draw(Texture2D texture, RenderTexture2D output); size_t getNumUniforms() const; private: std::vector<Uniform> uniforms; std::string shaderPath; Shader shader{}; }; #endif // __SQUINT_UPSCALER_H_
Eiyeron/squint
src/platformSetup.h
<gh_stars>1-10 #ifndef _SQUINT_PLATFORMSETUP_H_ #define _SQUINT_PLATFORMSETUP_H_ void setupLoggingOutput(); void unsetupLoggingOutput(); #endif // _SQUINT_PLATFORMSETUP_H_
Dts0/code
MOOC/6.c
<filename>MOOC/6.c #include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Term; ElementType Expon; PtrToNode Next; }; typedef PtrToNode List; List Read(); void Print(List L); List Add(List L1, List L2); List Multi(List L1, List L2); List MultiByNode(List L1, struct Node L2); int main() { List L1, L2, LAdd, LMulti; L1 = Read(); L2 = Read(); LMulti = Multi(L1, L2); LAdd = Add(L1, L2); Print(LMulti); Print(LAdd); return 0; } List Read(){ List L, head; L = (List)malloc(sizeof(List)); L->Next = NULL; head = L; int n; scanf("%d", &n); if (n > 0){ for (int i = 0; i < n; i++){ List temp = (List)malloc(sizeof(List)); scanf("%d%d", &(temp->Term), &(temp->Expon)); temp->Next = NULL; L->Next = temp; L = temp; } } return head; } void Print(List L){ List p = L->Next; if (!p){ printf("0 0\n"); } else{ while (p){ if (p->Next != NULL){ printf("%d %d ", p->Term, p->Expon); } else { printf("%d %d\n", p->Term, p->Expon); } p = p->Next; } } } List Add(List L1, List L2){ List L, head, t1, t2; L = (List)malloc(sizeof(List)); L->Next = NULL; head = L; t1 = L1->Next; t2 = L2->Next; while (t1 != NULL&&t2 != NULL){ List temp = (List)malloc(sizeof(List)); temp->Next = NULL; if (t1->Expon > t2->Expon){ temp->Term = t1->Term; temp->Expon = t1->Expon; L->Next = temp; L = temp; t1 = t1->Next; } else if (t1->Expon < t2->Expon) { temp->Term = t2->Term; temp->Expon = t2->Expon; L->Next = temp; L = temp; t2 = t2->Next; } else if (t1->Expon == t2->Expon){ //抵消 if ((t1->Term + t2->Term) == 0){ t1 = t1->Next; t2 = t2->Next; } else{ temp->Term = t1->Term + t2->Term; temp->Expon = t1->Expon; L->Next = temp; L = temp; t1 = t1->Next; t2 = t2->Next; } } } //剩下的项直接挂上去 if (t1 == NULL){ L->Next = t2; } else if (t2 == NULL){ L->Next = t1; } return head; } List Multi(List L1, List L2){ List L, head, t1, t2, temp; L = (List)malloc(sizeof(List)); L->Next = NULL; head = L; t1 = L1->Next; t2 = L2->Next; if (t1 != NULL&&t2 != NULL){ temp = MultiByNode(L1, *t2); t2 = t2->Next; while (t2){ List temp2 = MultiByNode(L1, *t2); temp = Add(temp, temp2); t2 = t2->Next; } L->Next = temp->Next; } return head; } List MultiByNode(List L1, struct Node L2){ List L, head, t1; L = (List)malloc(sizeof(List)); L->Next = NULL; head = L; t1 = L1->Next; while (t1){ List temp = (List)malloc(sizeof(List)); temp->Next = NULL; temp->Term = t1->Term*L2.Term; temp->Expon = t1->Expon + L2.Expon; L->Next = temp; L = temp; t1 = t1->Next; } return head; }
Dts0/code
linux/hello_mod/hello_mod.c
#include<linux/init.h> #include<linux/module.h> MODULE_LICENSE("DualBSD/GPL"); static int hello_init(void) { printk(KERN_ALERT "Hello,world\n"); return 0; } static void hello_exit(void) { printk(KERN_ALERT "Goodbye,world\n"); } module_init(hello_init); module_exit(hello_exit);
Dts0/code
MOOC/18.c
#include<stdio.h> #include<stdlib.h> #define MAXN 15 int visited[MAXN] = {0}; //建立邻接矩阵 //Create Graph int G[MAXN][MAXN]={0},NV,NE; void BuildGraph() { //freopen("test1.txt","r",stdin); int i,j,v1,v2; scanf("%d%d",&NV,&NE); for( i=0; i<NE; i++) { scanf("%d%d",&v1,&v2); //InsertEdge G[v1][v2] = 1; G[v2][v1] = 1; } } //DFS void DFS(int v) { visited[v] = 1; printf("%d ",v);//输出这个点 for(int i=0; i<NV; i++) { if(G[v][i] && !visited[i])//如果联通这个点且没有访问过 { DFS(i); } } } void ListComponentsDFS() { int i; for(i=0; i<NV; i++) { if(!visited[i]) { printf("{ "); DFS(i); printf("}\n"); } } } //初始化visited void isvisited() { for(int i=0; i<MAXN; i++) { visited[i] = 0; } } //BFS void BFS(int v) { //队列 const int MAXSIZE=100; int quene[MAXSIZE]; int first = -1, rear = -1; quene[++rear] = v;//入队 visited[v] = 1; while(first < rear)//队列不为空 { int de = quene[++first];//出队 printf("%d ",de); for(int i=0; i<NV; i++) { if(!visited[i]&&G[de][i]) { visited[i] = 1; quene[++rear] = i; } } } } void ListComponentsBFS() { int i; for(i=0; i<NV; i++) { if(!visited[i]) { printf("{ "); BFS(i); printf("}\n"); } } } int main() { //建图 BuildGraph(); //DFS遍历连通集 ListComponentsDFS(); isvisited(); //BFS遍历连通集 ListComponentsBFS(); return 0; }
Dts0/code
else/fileops.c
#include<stdio.h> int main(){ FILE* tty; tty = fopen("./test","w"); fputs("hi",tty); fclose(tty); }
Dts0/code
student/read.c
#include<stdio.h> #include<stdlib.h> struct stu{ int id; char name[10]; int Mathematics; int Chinese; int English; }; int main(){ FILE *fp; fp=fopen("student.dat","ab+"); const int size=5; struct stu student[size]; for(int i=0;i<size;++i){ fgets(&student[i],sizeof(struct stu)+1,fp); } fclose(fp); for(int i=0;i<size;++i){ printf("%d,%s,%d,%d,%d\n",student[i].id,student[i].name, student[i].Mathematics,student[i].Chinese,student[i].English); } return 0; }
Dts0/code
else/1001.c
<filename>else/1001.c<gh_stars>0 #include <stdio.h> int getCallatzResult(int num); int main() { int input=0; scanf("%d",&input); int result=getCallatzResult(input); printf("%d",result); return 0; } int getCallatzResult(int num) { int count=0; if(num>1000||num<0) { return -1;//不符合要求的输入 } while(num!=1) { if(num%2==0)//偶数 { num/=2; count++; } else if(num%2==1)//奇数 { num=(3*num+1)/2; count++; } } return count; }
Dts0/code
test/test_asm.c
#include<stdio.h> #include<stdlib.h> #define clear_block(addr) \ __asm__ __volatile__("cld\n\t" \ "rep\n\t" \ "stosl" \ ::"a" (0),"c" (BLOCK_SIZE/4),"D" ((long) (addr))) #define clear_block(addr) \ __asm__ __volatile__("cld\n\t" \ //清方向位 "rep\n\t" \ // 重复执行存储数据(0). "stosl" ::"a" (0),"c" (BLOCK_SIZE/4),"D" ((long) (addr))) #define do_it() \ __asm__ __volatile__("movl %1,%0\n\t" \ "add $50,%0" \ :"=r" (dst) \ :"r" (src)); int main(){ unsigned int src=100,dst; do_it() printf("%u\n",dst); return 0; }
Dts0/code
test/test_stack_overflow.c
#include <stdio.h> #include <stdlib.h> void pass(){ /* printf("456"); exit(0); */ int y=0; printf("%lx ",(unsigned long)&y); *(&y+8)=456; } void pass_ex(int range_min,int range_max){ int tmp=0; for(int* i=&tmp-range_min;i<&tmp+range_max;++i){ if(*i==123){ *i=456; printf("change 123 at 0x%lx to 456\n",(unsigned long)i); } } } int main(void){ //printf("%d %d %d\n",sizeof(int*),sizeof(unsigned int),sizeof(unsigned long)); int x=123; printf("%d\n",x); pass_ex(100,100); printf("%d\n",x); printf("%lx ",(unsigned long)&x); return 0; }
Dts0/code
MOOC/2.c
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Data; PtrToNode Next; }; typedef PtrToNode List; List Read(); /* 细节在此不表 */ void Print( List L ); /* 细节在此不表;空链表将输出NULL */ List Merge( List L1, List L2 ); int main() { List L1, L2, L; L1 = Read(); L2 = Read(); L = Merge(L1, L2); Print(L); Print(L1); Print(L2); return 0; } /* 你的代码将被嵌在这里 */ List Read() { int n; scanf("%d",&n); List L=(List)malloc(sizeof(PtrToNode)); ///申请一个头结点 L->Next = NULL; ///头指针为空 if(n) ///当n不是0时 { List r=L; ///r是一个中间变量的节点 for(int i=0;i<n;i++) { List p=(List)malloc(sizeof(struct Node)); scanf("%d",&(p->Data)); ///尾插法 r->Next = p; r = p; } r->Next = NULL; } return L; } void Print( List L ) { List p=L->Next; if(p) { List r; r = L; while(r->Next) { r = r->Next; printf("%d ",r->Data); } } else { printf("NULL"); } printf("\n"); } List Merge( List L1, List L2 ) ///合并函数 重点要写的函数! { List list1,list2,p,L; L = (List)malloc(sizeof(struct Node)); list1=L1->Next; list2=L2->Next; p = L; while(list1 && list2) { if(list1->Data <= list2->Data) { p->Next = list1; p = list1; list1 = list1->Next; } else { p->Next = list2; p = list2; list2 = list2->Next; } } p->Next = list1 ? list1 : list2; L1->Next = NULL; L2->Next = NULL; return L; }
Dts0/code
else/time.c
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ //setenv("TZ","Asia/Shanghai",1); while(1){ time_t now_1970=time(NULL);//从1970到现在的秒数 struct tm tm_now=*localtime(&now_1970);//现在的年月日等 /*//测试用 tm_now.tm_year=78; tm_now.tm_mon=1; tm_now.tm_mday=1; tm_now.tm_hour=0; tm_now.tm_min=0; tm_now.tm_sec=2; */ int year=tm_now.tm_year-78; int month=tm_now.tm_mon-0;//注意mon为从0到11 int day=tm_now.tm_mday-1; int hour=tm_now.tm_hour; int minute=tm_now.tm_min; int second=tm_now.tm_sec; printf("无协成立%d年%d月%d日%d时%d分%d秒\n",year,month,day,hour,minute,second); while(time(NULL)==now_1970); } }
Dts0/code
else/test.c
<gh_stars>0 #include<stdio.h> #include<stdlib.h> typedef void (*fun)(void); void print(){ printf("passed\n"); } int main(){ fun f=print; f(); return 0; }
Dts0/code
else/pointer.c
<reponame>Dts0/code #include<stdio.h> #include<stdlib.h> void swap(int* x,int* y){ int tmp; tmp=*y; *y=*x; *x=tmp; } int main(){ int x=100,y=999; printf("%d %d\n",x,y); swap(&x,&y); printf("%d %d",x,y); return 0; } /* int tmp; tmp=y; y=x; x=tmp; */ /* int* tmp_ptr=(int *)malloc(sizeof(int)); *tmp_ptr=y; y=x; x=*tmp_ptr; free(tmp_ptr); */
Dts0/code
else/sam.c
#include<stdio.h> #include<stdlib.h> int main(){ int a; int* p; p=&a; scanf("%d",p); printf("%d\n",*p); return 0; }
Dts0/code
MOOC/3.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; void PreorderTraversal( BinTree BT ); /* 先序遍历,由裁判实现,细节不表 */ void InorderTraversal( BinTree BT ); /* 中序遍历,由裁判实现,细节不表 */ BinTree Insert( BinTree BST, ElementType X ); BinTree Delete( BinTree BST, ElementType X ); Position Find( BinTree BST, ElementType X ); Position FindMin( BinTree BST ); Position FindMax( BinTree BST ); int main() { BinTree BST, MinP, MaxP, Tmp; ElementType X; int N, i; BST = NULL; scanf("%d", &N); for ( i=0; i<N; i++ ) { scanf("%d", &X); BST = Insert(BST, X); } printf("Preorder:"); PreorderTraversal(BST); printf("\n"); MinP = FindMin(BST); MaxP = FindMax(BST); scanf("%d", &N); for( i=0; i<N; i++ ) { scanf("%d", &X); Tmp = Find(BST, X); if (Tmp == NULL) printf("%d is not found\n", X); else { printf("%d is found\n", Tmp->Data); if (Tmp==MinP) printf("%d is the smallest key\n", Tmp->Data); if (Tmp==MaxP) printf("%d is the largest key\n", Tmp->Data); } } scanf("%d", &N); for( i=0; i<N; i++ ) { scanf("%d", &X); BST = Delete(BST, X); } printf("Inorder:"); InorderTraversal(BST); printf("\n"); return 0; } /* 你的代码将被嵌在这里 */ void PreorderTraversal( BinTree BT ) { if(BT==NULL) return; else{ printf(" %d",BT->Data); PreorderTraversal(BT->Left); PreorderTraversal(BT->Right); } } void InorderTraversal( BinTree BT ) { if(BT==NULL) return; else{ InorderTraversal(BT->Left); printf(" %d",BT->Data); InorderTraversal(BT->Right); } } BinTree Insert( BinTree BST, ElementType X ) { if(!BST)//如果BST为空的话,返回只有一个节点的树 { BST=(BinTree)malloc(sizeof(struct TNode)); BST->Data=X; BST->Left=NULL; BST->Right=NULL; } else//如果BST不是为空的话 {//开始寻找要插入的位置 if(X<BST->Data) BST->Left=Insert(BST->Left,X); else if(X>BST ->Data) BST->Right=Insert(BST->Right,X); } return BST; } BinTree Delete( BinTree BST, ElementType X ) { BinTree Tmp; if(!BST) printf("Not Found\n"); else{ if(X<BST->Data) BST->Left=Delete(BST->Left,X); else if(X>BST->Data) { BST->Right=Delete(BST->Right,X); } else//考虑如果找到这个位置,并且有左节点或者右节点或者没有节点三种情况 { if(BST->Left && BST->Right) { Tmp=FindMin(BST->Right); /* 在右子树中找到最小结点填充删除结点 */ BST->Data = Tmp ->Data; BST->Right=Delete(BST->Right,BST->Data);/* 递归删除要删除结点的右子树中最小元素 */ } else { /* 被删除结点有一个或没有子结点*/ Tmp = BST; if(!BST->Left) BST = BST->Right; /*有右孩子或者没孩子*/ else if(!BST->Right) BST = BST->Left;/*有左孩子,一定要加else,不然BST可能是NULL,会段错误*/ free(Tmp); /*如无左右孩子直接删除*/ } } } return BST; } Position Find( BinTree BST, ElementType X ) { if(!BST) return NULL; if(BST->Data==X) return BST; else if(X<BST->Data) { return Find(BST->Left,X); } else if(X>BST->Data) { return Find(BST->Right,X); } return BST; } Position FindMin( BinTree BST ) { if(BST!=NULL) { while(BST->Left) BST=BST->Left; } return BST; } Position FindMax( BinTree BST ) { if(BST!=NULL) { while(BST->Right) BST=BST->Right; } return BST; }
Dts0/code
else/test2.c
<reponame>Dts0/code<gh_stars>0 #include<stdio.h> #include<stdlib.h> int main(){ int s0=999; int s; s= 3>2?({ s=10; s0+1; }):100000; printf("%d %d\n",s0,s); return 0; }
Dts0/code
student/write.c
<reponame>Dts0/code #include<stdio.h> #include<stdlib.h> #include<errno.h> struct stu{ int id; char name[10]; int Mathematics; int Chinese; int English; }; int main(){ struct stu student; FILE *fp; printf("学号\n"); scanf("%d",&student.id); getchar(); printf("姓名\n"); gets(student.name); fflush(stdin); printf("数学\n"); scanf("%d",&student.Mathematics); getchar(); printf("语文\n"); scanf("%d",&student.Chinese); getchar(); printf("英语\n"); scanf("%d",&student.English); getchar(); fp=fopen("student.dat","ab+"); if(fp==NULL){ printf("打开文件失败"); exit(0); } fwrite(&student,sizeof(struct stu),1,fp); fclose(fp); return 0; }
Dts0/code
test/test_inline_addr.c
#include<stdio.h> #include<stdlib.h> int add(int x,int y);//inline 函数必须要有前置声明 int inline add(int x,int y){ return x+y; } int add2(int x,int y){ return x+y; } int main(){ int r=add(2,55); printf("%d\n%x\n%x\n",r,(unsigned int)&add,(unsigned int)&add2); return 0; }
Dts0/code
student/test.c
<reponame>Dts0/code #include <stdlib.h> #include<stdio.h> //#include<malloc.h> //#include<errno.h> //static int line = 0; int size = 0; void head(); void increase(); void _select(); void condition(); int main() { //head(); //_select(); head(); return 0; } /* 学生类 */ struct stu { int id; //学生学号 char name[10]; //学生名字 int Mathematics; //数学成绩 int Chinese; //语文成绩 int English; //英语成绩 }; void head() { int num; printf("----------------欢迎使用学生管理系统----------------------\n"); printf("1:查询所有学生信息\n"); printf("2:按条件查询学生信息\n"); printf("3:添加学生信息\n"); printf("4:删除学生信息\n"); printf("5:退出学生管理系统\n"); do{ printf("\n"); printf("请输入:"); scanf("%d",&num); getchar(); switch (num) { case 1: _select(); break; case 2: printf("测试语句2\n"); break; case 3: increase(); break; case 4: printf("测试语句4\n"); break; case 5: printf("退出程序!"); break; default: printf("输入错误!请重新输入\n"); break; } } while (num != 5); } /* 添加 */ void increase() { struct stu student; FILE *fp; int err; printf("请输入学生学号\n"); scanf("%d", &student.id); getchar(); printf("请输入学生姓名\n"); gets(student.name); fflush(stdin); //防止回车作为输入 printf("请输入学生数学成绩\n"); scanf("%d", &student.Mathematics); getchar(); printf("请输入学生语文成绩\n"); scanf("%d", &student.Chinese); getchar(); printf("请输入学生英语成绩\n"); scanf("%d", &student.English); getchar(); //student = {student.id,student.name[10],student.Mathematics,student.Chinese,student.English}; //struct stu student = { 1,"zxxx",78,69,32 }; fp = fopen("student.dat", "ab+"); if (fp==0) { printf("打开文件失败"); exit(0); } //fwrite(&student, sizeof(struct stu), 1, fp); //向文件中写入数据 if (fwrite(&student, sizeof(struct stu), 1, fp)<1) { printf("文件写入失败!\n"); } else { printf("文件写入成功!\n"); ++size; } fclose(fp); } void _select() { FILE *fp; int err; fp = fopen("student.dat", "rb"); int i = 1; long count; if (fp== 0) { printf("文件打开失败!\n"); exit(0); } struct stu student[size]; for (int i = 0; i< size; ++i) { fgets((char *)&student[i], sizeof(struct stu) + 1, fp); } fclose(fp); for (int i = 0; i < size; ++i) { printf("%d,%s,%d,%d,%d\n", student[i].id, student[i].name, student[i].Mathematics, student[i].Chinese, student[i].English); } } void condition() { FILE *fp; int err; struct stu student; fp = fopen("student.dat", "rb"); if (fp==0) { printf("文件打开失败!\n"); exit(0); } fread(&student,sizeof(struct stu),1,fp); }
Dts0/code
else/1002_1.c
<gh_stars>0 #include<stdio.h> void getNums(long long num,int nums[]); void printNum(int num); void exchange(int input[],int length); //1234567890987654321123456789 //1844674407370955161 //超界了,换方法,这个只能处理在longlong即1844674407370955161以内的 int main() { long long input=0; scanf("%lld",&input); int nums[100];//小于2^100的数字最多有99位十进制数,所以设置一个100的数组不会越界 getNums(input,nums); int sum=0; for(int i=0;nums[i]!=-1;i++) { sum+=nums[i]; printf("%d ",sum); } printf("\n"); int results[100]; getNums(sum,results); for(int i=0;results[i]!=-1;i++) { printNum(results[i]); if(results[i+1]!=-1) printf(" "); } } void getNums(long long num,int nums[]) { int i=0; while(num>=10) { nums[i]=num%10;//取最后一位 printf("nums[%d]=%d ",i,nums[i]); num=num/10;//整体右移一位 printf("num=%lld\n",num); ++i; } nums[i]=num%10; printf("nums[%d]=%d ",i,nums[i]); nums[i+1]=-1;//-1填充 printf("%d位\n",i+1); //接下来的部分用于调整顺序 exchange(nums,i+1); } void printNum(int num)//打印一个数字0~9的拼音 { switch(num) { case 0:printf("ling");break; case 1:printf("yi");break; case 2:printf("er");break; case 3:printf("san");break; case 4:printf("si");break; case 5:printf("wu");break; case 6:printf("liu");break; case 7:printf("qi");break; case 8:printf("ba");break; case 9:printf("jiu");break; default: break; } } void exchange(int input[],int length) { int buf[length/2]; for(int i=0;i<length/2;++i) { buf[i]=input[i]; input[i]=input[length-i-1]; input[length-i-1]=buf[i]; } }
Dts0/code
tools/socketTools/socketServer.c
#include <stdio.h> //perror,printf #include <stdlib.h> //exit #include <sys/socket.h> //socket,bind,listen,accept,send,recv #include <netinet/in.h> //struct sockaddr_in,htons #include <arpa/inet.h> //inet_addr #include <unistd.h> //close #include <string.h> //memset,strcmp #define SOCKET_ADDR "127.0.0.1" #define SOCKET_PORT 18888 #define MAXSIZE 1024 int main(){ int sockfd; uint16_t port=18888; struct sockaddr_in sockaddr; sockfd=socket(AF_INET,SOCK_STREAM,0);//默认为TCP if(sockfd<0){ perror("socket"); exit(EXIT_FAILURE); } printf("sockfd:%d\n",sockfd); sockaddr.sin_family=AF_INET; sockaddr.sin_port=htons(port); sockaddr.sin_addr.s_addr=inet_addr(SOCKET_ADDR); if(bind(sockfd,(struct sockaddr*)&sockaddr,sizeof(sockaddr))<0){ perror("bind"); exit(EXIT_FAILURE); } if(listen(sockfd,MAXSIZE)<0){//最多接受MAXSIZE个连接 perror("listen"); exit(EXIT_FAILURE); } printf("waiting for client...\n"); int connfd; int n; char buf[MAXSIZE]; while(1){ connfd=accept(sockfd,(struct sockaddr*)NULL,NULL); printf("connected,sockfd:%d\n",connfd); if(connfd<0){ perror("accpet"); continue; } memset(buf, 0, sizeof(buf)); n=recv(connfd,buf,MAXSIZE,0);//接收最大MAXSIZE个字符 if(strcmp(buf,"exit\n")==0 || strcmp(buf,"exit")==0) break; send(connfd,"ok!",3,0);//发送"ok!" printf("%d bytes from client:\n%s\n",n,buf); close(connfd);//关闭本连接 } printf("closed\n"); close(sockfd);//关闭监听端口 //shutdown(connfd,SHUT_RDWR); //使用shutdown可以达到仅可读或仅可写 return 0; }
Dts0/code
MOOC/1.c
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 #define NotFound 0 typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ }; List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */ Position BinarySearch( List L, ElementType X ); int main() { List L; ElementType X; Position P; L = ReadInput(); scanf("%d", &X); P = BinarySearch( L, X ); printf("%d\n", P); return 0; } /* 你的代码将被嵌在这里 */ Position BinarySearch( List L, ElementType X ){ Position left; Position right; if (L->Last) { left = 1; right = L->Last; while(left <= right) { if (X == L->Data[(left + right) / 2]) return (left + right) / 2; else { if (X < L->Data[(left + right) / 2]) right = (left + right) / 2 - 1; else left = (left + right) / 2 + 1; } } } return NotFound; } List ReadInput(){ List L; Position num; L=(List)malloc(sizeof(struct LNode)); scanf("%d",&num); L->Last=num; for(Position i=1;i<=num;i++) scanf("%d",&L->Data[i]); return L; }
Dts0/code
else/1005.c
<filename>else/1005.c #include<stdio.h> #include<stdlib.h> int main(){ int reply=0; reply=0; printf("%s",reply); return 0; }
Dts0/code
MOOC/22.c
<gh_stars>0 #include<stdio.h> #include<math.h> #define inf 9999999 int n,d,flag=0,exist=0,newp; int mark[101]; int path[101]; int distance[101]; struct node{ int x; int y; }stu[101]; double dis(int x,int y){ return sqrt(x*x+y*y); } int canjump(int x1,int y1,int x2,int y2){ if(sqrt(pow((x1-x2),2)+pow(y1-y2,2))<=d){ return 1; } else{ return 0; } } void init(){ int i; flag=0; for(i=0;i<n;i++){ mark[i]=0; path[i]=-1; distance[i]=inf; } } void dijkstra(int s){ mark[s]=1; distance[s]=1;//从第一跳开始 ! path[s]=-2; int i; newp=s; while(1){ if(50-abs(stu[newp].x)<=d||50-abs(stu[newp].y)<=d){ distance[newp]++;//还要跳到岸上! flag=1;exist=1;break; } for(i=0;i<n;i++){ if(mark[i]==0&&canjump(stu[newp].x,stu[newp].y,stu[i].x,stu[i].y)){ if(distance[newp]+1<distance[i]){ distance[i]=distance[newp]+1; path[i]=newp; } } } int min=inf; for(i=0;i<n;i++){ if(mark[i]==0&&distance[i]<inf){ if(distance[i]<min){ min=distance[i]; newp=i; } } } mark[newp]=1; if(min==inf){ break; } } } int main(){ int i; scanf("%d %d",&n,&d); for(i=0;i<n;i++){ scanf("%d %d",&stu[i].x,&stu[i].y); } if(d>=50-7.5){ printf("1\n");return 0;//最小N,一步跳到岸 错了这个点 } int firstjump[n];//第一跳下标 int numfirst=0; for(i=0;i<n;i++){ if(d+7.5>=dis(stu[i].x,stu[i].y)){ firstjump[numfirst++]=i; } } int min=inf,index; int store[n],cou=0; for(i=0;i<numfirst;i++){ init(); dijkstra(firstjump[i]); if(flag){//找到路径 if(distance[newp]<min){ min=distance[newp]; cou=0; store[cou++]=firstjump[i]; } else if(distance[newp]==min){ store[cou++]=firstjump[i]; } } } if(exist==0){ printf("0");return 0; } min=inf; int indexmin;//如果最短路径相同,则距离源点最近的点唯一(题目保证) for(i=0;i<cou;i++){ int index=store[i]; if(min>dis(stu[index].x,stu[index].y)-7.5){ min=dis(stu[index].x,stu[index].y)-7.5; indexmin=store[i]; } } init();//别忘了初始化 !!!! dijkstra(indexmin); printf("%d\n",distance[newp]); cou=0; while(1){ store[cou++]=newp; newp=path[newp]; if(newp==-2){ break; } } for(i=cou-1;i>=0;i--){ printf("%d %d\n",stu[store[i]].x,stu[store[i]].y); } }
Dts0/code
else/1002_2.c
<reponame>Dts0/code<gh_stars>0 #include<stdio.h> void getNums(char num[],int nums[]); void getNums_2(int num,int nums[]); void printNum(int num); void exchange(int input[],int length); int atoi(char c); int main() { char input[100]; scanf("%s",input); int nums[100]; getNums(input,nums); int sum=0; for(int i=0;nums[i]!=-1;i++) { sum+=nums[i]; } int results[100]; getNums_2(sum,results); for(int i=0;results[i]!=-1;i++) { printNum(results[i]); if(results[i+1]!=-1) printf(" "); } return 0; } void getNums(char num[],int nums[])//因为10^100超出C语言表达范围,只能用数组来代替 { int i; for(i=0;num[i]!='\0';++i) { nums[i]=atoi(num[i]); if(nums[i]==-1) printf("an err occured while getting nums."); } nums[i]=-1; } void getNums_2(int num,int nums[]) { int i=0; while(num>=10) { nums[i]=num%10;//取最后一位 num=num/10;//整体右移一位 ++i; } nums[i]=num%10; nums[i+1]=-1;//-1填充 //接下来的部分用于调整顺序 exchange(nums,i+1); } void printNum(int num)//打印一个数字0~9的拼音 { switch(num) { case 0:printf("ling");break; case 1:printf("yi");break; case 2:printf("er");break; case 3:printf("san");break; case 4:printf("si");break; case 5:printf("wu");break; case 6:printf("liu");break; case 7:printf("qi");break; case 8:printf("ba");break; case 9:printf("jiu");break; default: break; } } void exchange(int input[],int length) { int buf[length/2]; for(int i=0;i<length/2;++i) { buf[i]=input[i]; input[i]=input[length-i-1]; input[length-i-1]=buf[i]; } } int atoi(char c) { switch(c) { case '0':return 0; case '1':return 1; case '2':return 2; case '3':return 3; case '4':return 4; case '5':return 5; case '6':return 6; case '7':return 7; case '8':return 8; case '9':return 9; default: return -1; } }
Dts0/code
bin/theCat/src/include/reply.h
#ifndef REPLY_H #define REPLY_H #include<string> string reply(string inputStr); #endif
Dts0/code
MOOC/23.c
<filename>MOOC/23.c #include <stdio.h> #include <string.h> #define N 500 #define INF 501 int g[N][N][2], dis[N + 1], known[N], pay[N]; int main() { int n, m, s, d, i, j, t1, t2, v; scanf("%d%d%d%d", &n, &m, &s, &d); for (i = 0;i < n;i++) { for (j = 0;j < n;j++) { g[i][j][0] = INF; g[i][j][1] = INF; } } while (m--) { scanf("%d%d%d%d", &i, &j, &t1, &t2); g[i][j][0] = g[j][i][0] = t1; g[i][j][1] = g[j][i][1] = t2; } memset(known, 0, n*sizeof(int)); for (j = 0;j < n;j++) { dis[j] = g[s][j][0]; pay[j] = g[s][j][1]; } dis[s] = 0; pay[s] = 0; dis[n] = INF; while (1) { v = n; for (i = 0;i < n;i++) { if (!known[i] && dis[i] < dis[v]) v = i; } if (v == n) break; known[v] = 1; for (i = 0;i < n;i++) { if (!known[i] && g[v][i][0] < INF) { if (dis[v] + g[v][i][0] < dis[i]) { dis[i] = dis[v] + g[v][i][0]; pay[i] = pay[v] + g[v][i][1]; } else if (!known[i] && dis[v] + g[v][i][0] == dis[i] && pay[v] + g[v][i][1] < pay[i]) { pay[i] = pay[v] + g[v][i][1]; } } } } if(dis[d] < INF) printf("%d %d", dis[d], pay[d]); return 0; }
Dts0/code
MOOC/21.c
#include <stdio.h> #define Max 10000 int g[100][100]; int main() { int n, m, w, i, j, k, maxl, minl = Max; scanf("%d %d\n", &n, &m); for (i = 0;i < n;i++) { for (j = 0;j < n;j++) g[i][j] = Max; } while (m--) { scanf("%d %d %d\n", &i, &j, &w); g[i-1][j-1] = w; g[j-1][i-1] = w; } for (k = 0;k < n;k++) { for (i = 0;i < n;i++) { for (j = 0;j < n;j++) { if (g[i][k] + g[k][j] < g[i][j]) g[i][j] = g[i][k] + g[k][j]; } } } for (i = 0;i < n;i++) { maxl = 0; for (j = 0;j < n;j++) { if (i != j && g[i][j]>maxl) maxl = g[i][j]; if (maxl >= Max) break; } if (maxl < minl) { k = i + 1; minl = maxl; } } if (minl < Max) printf("%d %d", k, minl); else printf("0"); return 0; }
Dts0/code
tools/socketTools/socketClient.c
<filename>tools/socketTools/socketClient.c #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #define SOCKET_ADDR "127.0.0.1" #define SOCKET_PORT 18888 #define MAXSIZE 1024 int main(){ int sockfd; struct sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons(SOCKET_PORT); sockaddr.sin_addr.s_addr = inet_addr(SOCKET_ADDR); char sendbuf[MAXSIZE]; char recvbuf[MAXSIZE]; while(1){ memset(sendbuf, 0, sizeof(sendbuf)); memset(recvbuf, 0, sizeof(recvbuf)); sockfd = socket(AF_INET,SOCK_STREAM, 0); if(sockfd<0){ perror("socket"); exit(EXIT_FAILURE); } printf("sockfd:%d\n",sockfd); if (connect(sockfd, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0){ perror("connect"); exit(EXIT_FAILURE); } //scanf("%s",sendbuf); fgets(sendbuf,MAXSIZE,stdin);//使用fgets可以连控制字符一起读 //当前逻辑,每次发送后等待接收 send(sockfd, sendbuf, strlen(sendbuf),0); ///发送 if(strcmp(sendbuf,"exit\n")==0 || strcmp(sendbuf,"exit")==0) break; if(strcmp(sendbuf,"stop\n")==0 || strcmp(sendbuf,"stop")==0) break; recv(sockfd, recvbuf, sizeof(recvbuf),0); ///接收 //fputs(recvbuf, stdout); printf("Client:%s\n",sendbuf); printf("Server:%s\n",recvbuf); close(sockfd); } return 0; }
csauer42/rover
rpi/include/conversion.h
#ifndef CONVERSION_H #define CONVERSION_H #include <cmath> #include "constants.h" #include "crc.h" /** Convert 4 integer motor values to 11-byte serial message */ void convertValues(int*, uint8_t c[]); /** Remove any 0xFF byte from command before applying CRC */ void filterCommand(uint8_t c[]); #endif
csauer42/rover
rpi/include/serial_comms.h
#ifndef SERIAL_COMMS_H #define SERIAL_COMMS_H #include <iostream> #include <cstdio> #include <cstring> #include <termios.h> #include <unistd.h> #include <ctime> #include <cstdint> #include "constants.h" /** writes command to serial device and reads reply */ float writeCommand(uint8_t[], int); #endif
csauer42/rover
rpi/include/Rover.h
#ifndef ROVER_H #define ROVER_H #include <iostream> #include <cstdint> #include <cstdlib> #include <zmq.hpp> #include "serial_setup.h" #include "conversion.h" #include "serial_comms.h" /** Rover Class, handles tranfer and conversion of control values and voltage reads */ class Rover { public: /** Constructor takes serial port name */ Rover(const char *ttydevice); ~Rover(); void run(); void stop(); private: bool runflag; int serialfd; zmq::context_t *ctx; zmq::socket_t *socket; uint8_t command[CLENGTH]; // from constants.h }; #endif
csauer42/rover
rpi/include/crc.h
<gh_stars>0 #ifndef CRC_H #define CRC_H #define CRC16INIT 0xFFFF #define CRC8INIT 0x00 #include <cstdint> // crc implementations borrowed from <util/crc16.h> uint16_t crc16_update(uint16_t, uint8_t); uint16_t calculate_crc16(unsigned char[], int size); uint8_t crc_ibutton_update(uint8_t crc, uint8_t data); uint8_t calculate_crc8(uint8_t[], int); #endif
csauer42/rover
rpi/include/serial_setup.h
#ifndef SERIAL_SETUP_H #define SERIAL_SETUP_H #include <cstring> #include <cstdlib> #include <termios.h> #include <sys/ioctl.h> #include <sys/file.h> #include <fcntl.h> #include <cstdio> #include <time.h> #include <unistd.h> #include <errno.h> /** error codes */ #define ERRLOPEN -1 #define ERRLLOCK -2 #define ERRPOPEN -3 #define ERRPFCNTL -4 #define ERRPIOCTL -5 #define ERRPFLUSH -6 #define ERRPSETATTR -7 #define ERRPCLOSE -8 #define ERRLUNLOCK -16 #define ERRLREMOVE -32 /** Serial port lock file name */ #define LOCKNAME "/tmp/serial_lock" /** Baudrate for serial connection */ #define TTYBAUDRATE B38400 /** Open serial port and create lockfile */ int open_port(const char*); /** Initialize port (linux handling) */ int setup_port(int); /** Closes serial port and removes lock file */ int close_port(int); #endif
csauer42/rover
avr/MotorControlV1/MotorControlV1/main.c
<gh_stars>0 /** MotorControl for Rover project, handles 6x pwm * channels for dc/servo motor control and battery * voltage read through adc, controlled via UART */ #define F_CPU 8000000UL #define BAUDRATE 38400 #define BAUD_PRESCALLER (((F_CPU / (BAUDRATE * 16UL))) - 1) #define CLENGTH 11 #define START 0xFF #define CHANNEL 5 #include <avr/io.h> #include <util/delay.h> #include <util/crc16.h> void USART_init(); void USART_send(uint8_t); uint8_t USART_receive(); void PWMInit(); void setPWM(uint8_t[]); void clearCommand(uint8_t[]); void zeroAll(); int CRCcheck(uint8_t[]); void initADC(); uint16_t readADC(uint8_t); int main(void) { uint8_t command[CLENGTH]; int i; uint16_t voltRef = 0; clearCommand(command); PWMInit(); zeroAll(); USART_init(); initADC(); while (1) { for (i=0; i < CLENGTH; i++) { // fragile, switch to UART interrupts command[i] = USART_receive(); // to enable smoother acceleration/motion if (i > 0 && command[i] == 0xFF) { // track current vs target motor values, command[0] = 0xFF; // change gradually in main loop i = 0; } } if (CRCcheck(command) == 0) { setPWM(command); voltRef = readADC(CHANNEL); } else { voltRef = 0; } USART_send(voltRef >> 8); USART_send(voltRef & 0xFF); clearCommand(command); } } void USART_init() { UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8); UBRR0L = (uint8_t)(BAUD_PRESCALLER); UCSR0B = (1<<RXEN0)|(1<<TXEN0); UCSR0C = ((1<<UCSZ00)|(1<<UCSZ01)); } void USART_send(uint8_t data) { while(!(UCSR0A & (1<<UDRE0))); UDR0 = data; } uint8_t USART_receive() { while(!(UCSR0A & (1<<RXC0))); return UDR0; } void PWMInit() { PORTB = 0; PORTD = 0; //PORTC ?? // set all 3 timer counters to clear OC* when up-counting, phase-correct pwm, // no prescaling TCCR0A |= ((1<<COM0A1) | (1<<COM0B1) | (1<<WGM00)); TCCR0B |= ((1<<WGM00) | (1<<CS00)); // 16-bit, 50 hz, use 10-bit values for input ICR1 = 19999; TCCR1A |= ((1<<COM1A1) | (1<<COM1B1) | (1<<WGM11)); TCCR1B |= ((1<<WGM13) | (1<<WGM12) | (1<<CS11)); TCCR2A |= ((1 << COM2A1) | (1<<COM2B1) | (1<<WGM20)); TCCR2B |= ((1<<WGM20) | (1<<CS20)); // set all pwm pins to output DDRB |= ((1<<DDB1) | (1<<DDB2) | (1<<DDB3)); DDRD |= ((1<<DDD3) | (1<<DDD5) | (1<<DDD6)); // set ADC pin defaults to input } void clearCommand(uint8_t c[]) { int i; for (i=0; i<CLENGTH; i++) { c[i] = 0; } } void setPWM(uint8_t c[]) { // motor forward l/r OCR0A = c[1]; OCR2A = c[2]; // servo vert/horiz uint16_t look_vertical = (c[5] << 8) | c[6]; uint16_t look_horizontal = (c[7] << 8) | c[8]; OCR1A = ICR1 * (1.0 + (look_vertical/1023.0)) / 20; OCR1B = ICR1 * (1.0 + (look_horizontal/1023.0)) / 20; // motor backward l/r OCR0B = c[3]; OCR2B = c[4]; } void zeroAll() { OCR0A = 0; OCR2A = 0; OCR1A = ICR1 * 1.5 / 20; OCR1B = ICR1 * 1.5 / 20; OCR0B = 0; OCR2A = 0; } int CRCcheck(uint8_t c[]) { uint16_t crc = 0xFFFF; for (int i = 0; i < CLENGTH; i++) { crc = _crc16_update(crc, c[i]); } return crc; } void initADC() { ADMUX |= (1<<REFS0); // use AVcc ADCSRA |= (1<<ADEN); // enable, no prescaler } uint16_t readADC(uint8_t channel) { ADMUX = (ADMUX & 0xF0) | (channel & 0x0F); ADCSRA |= (1<<ADSC); while ((ADCSRA & (1<<ADSC))); return ADC; }
csauer42/rover
rpi/include/constants.h
<filename>rpi/include/constants.h #ifndef CONSTANTS_H #define CONSTANTS_H #define CLENGTH 11 // length of serial command #define MAXMOTOR 255.0 // maximum value for dc motor (8-bit) #define LOOK_OFFSET 511 // offset value for servo motor (10-bit) #define FILTER_BYTE 0xFF // start byte for serial read, do not send in command #endif
dannys42/DTSAnalytics
Example/Pods/Target Support Files/Pods-DTSAnalytics_Example/Pods-DTSAnalytics_Example-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_DTSAnalytics_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_DTSAnalytics_ExampleVersionString[];
dannys42/DTSAnalytics
Example/Pods/Target Support Files/Pods-DTSAnalytics_Tests/Pods-DTSAnalytics_Tests-umbrella.h
<reponame>dannys42/DTSAnalytics<gh_stars>0 #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_DTSAnalytics_TestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_DTSAnalytics_TestsVersionString[];
dannys42/DTSAnalytics
Example/Pods/Target Support Files/DTSAnalytics/DTSAnalytics-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double DTSAnalyticsVersionNumber; FOUNDATION_EXPORT const unsigned char DTSAnalyticsVersionString[];
zouboan/incubator-nuttx
libs/libc/stdlib/lib_atexit.c
/**************************************************************************** * libs/libc/stdlib/lib_atexit.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdlib.h> #include <nuttx/atexit.h> #include <nuttx/semaphore.h> #include <nuttx/tls.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: get_exitfuncs * * Description: * Obtain the list of exit functions. * * Input Parameters: * None * * Returned Value: * Pointer to the list of exit functions. * ****************************************************************************/ static FAR struct atexit_list_s * get_exitfuncs(void) { FAR struct task_info_s *info; info = task_get_info(); return &info->ta_exit; } /**************************************************************************** * Name: exitfunc_lock * * Description: * Obtain the exit function lock. * * Returned Value: * OK on success, or negated errno on failure * ****************************************************************************/ static int exitfunc_lock(void) { FAR struct task_info_s *info = task_get_info(); int ret = _SEM_WAIT(&info->ta_sem); if (ret < 0) { ret = _SEM_ERRVAL(ret); } return ret; } /**************************************************************************** * Name: exitfunc_unlock * * Description: * Release exit function lock . * ****************************************************************************/ static void exitfunc_unlock(void) { FAR struct task_info_s *info = task_get_info(); _SEM_POST(&info->ta_sem); } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: atexit * * Description: * Registers a function to be called at program exit. * The atexit() function registers the given function to be called * at normal process termination, whether via exit or via return from * the program's main(). * * Limitations in the current implementation: * * 1. Only a single atexit function can be registered unless * CONFIG_LIBC_MAX_EXITFUNS defines a larger number. * 2. atexit functions are not inherited when a new task is * created. * * Input Parameters: * func - A pointer to the function to be called when the task exits. * * Returned Value: * Zero on success. Non-zero on failure. * ****************************************************************************/ int atexit(CODE void (*func)(void)) { return atexit_register(ATTYPE_ATEXIT, func, NULL, NULL); } int atexit_register(int type, CODE void (*func)(void), FAR void *arg, FAR void *dso) { FAR struct atexit_list_s *aehead; int idx; int ret = ERROR; /* REVISIT: Missing logic */ UNUSED(dso); /* The following must be atomic */ aehead = get_exitfuncs(); if (func) { ret = exitfunc_lock(); if (ret < 0) { return ret; } if ((idx = aehead->nfuncs) < ATEXIT_MAX) { aehead->funcs[idx].type = type; aehead->funcs[idx].func = func; aehead->funcs[idx].arg = arg; aehead->nfuncs++; ret = OK; } else { ret = ERROR; } exitfunc_unlock(); } return ret; } void atexit_call_exitfuncs(int status) { FAR struct atexit_list_s *aehead; CODE void (*func)(void); FAR void *arg; int idx; int type; /* Call exit functions in reverse order */ aehead = get_exitfuncs(); for (idx = aehead->nfuncs - 1; idx >= 0; idx--) { /* Remove the function to prevent recursive call to it */ type = aehead->funcs[idx].type; func = aehead->funcs[idx].func; arg = aehead->funcs[idx].arg; aehead->funcs[idx].func = NULL; aehead->funcs[idx].arg = NULL; if (!func) { continue; } /* Call the atexit/on_exit/cxa_atexit() function */ if (type == ATTYPE_ATEXIT) { (*func)(); } else if (type == ATTYPE_ONEXIT) { (*((CODE void (*)(int, FAR void *))func))(status, arg); } else if (type == ATTYPE_CXA) { (*((CODE void (*)(FAR void *))func))(arg); } } }
zouboan/incubator-nuttx
sched/tls/task_initinfo.c
/**************************************************************************** * sched/tls/task_initinfo.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <errno.h> #include <nuttx/kmalloc.h> #include <nuttx/semaphore.h> #include <nuttx/tls.h> #include "tls.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: task_init_info * * Description: * Allocate and initilize task_info_s structure. * * Input Parameters: * - group: The group of new task * * Returned Value: * Zero (OK) on success; a negated errno value on failure. * ****************************************************************************/ int task_init_info(FAR struct task_group_s *group) { FAR struct task_info_s *info; /* Allocate task info for group */ info = group_zalloc(group, sizeof(struct task_info_s)); if (info == NULL) { return -ENOMEM; } /* Initialize user space semaphore */ nxsem_init(&info->ta_sem, 0, 1); group->tg_info = info; return OK; }
zouboan/incubator-nuttx
sched/pthread/pthread_cancel.c
/**************************************************************************** * sched/pthread/pthread_cancel.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <unistd.h> #include <pthread.h> #include <assert.h> #include <errno.h> #include <nuttx/tls.h> #include <nuttx/pthread.h> #include "sched/sched.h" #include "task/task.h" #include "pthread/pthread.h" /**************************************************************************** * Public Functions ****************************************************************************/ int pthread_cancel(pthread_t thread) { FAR struct tcb_s *tcb; /* First, make sure that the handle references a valid thread */ if ((pid_t)thread == IDLE_PROCESS_ID) { /* pid == 0 is the IDLE task (in a single CPU configuration). Callers * cannot cancel the IDLE task. */ return ESRCH; } tcb = nxsched_get_tcb((pid_t)thread); if (tcb == NULL) { /* The pid does not correspond to any known thread. The thread * has probably already exited. */ return ESRCH; } /* Only pthreads should use this interface */ DEBUGASSERT((tcb->flags & TCB_FLAG_TTYPE_MASK) == TCB_FLAG_TTYPE_PTHREAD); /* Notify the target if the non-cancelable or deferred cancellation set */ if (nxnotify_cancellation(tcb)) { return OK; } /* Otherwise, perform the asyncrhonous cancellation */ /* Check to see if the ID refers to ourselves.. this would be the * same as pthread_exit(PTHREAD_CANCELED). */ if (tcb == this_task()) { pthread_exit(PTHREAD_CANCELED); } /* Refer to tls_get_info() */ #ifdef CONFIG_PTHREAD_CLEANUP pthread_cleanup_popall(tcb->stack_alloc_ptr); #endif /* Complete pending join operations */ pthread_completejoin((pid_t)thread, PTHREAD_CANCELED); /* Then let nxtask_terminate do the real work */ return nxtask_terminate((pid_t)thread, false); }
zouboan/incubator-nuttx
sched/tls/tls.h
/**************************************************************************** * sched/tls/tls.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ #ifndef __SCHED_TLS_TLS_H #define __SCHED_TLS_TLS_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/sched.h> /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: task_init_info * * Description: * Allocate and initilize task_info_s structure. * * Input Parameters: * - group: The group of new task * * Returned Value: * Zero (OK) on success; a negated errno value on failure. * ****************************************************************************/ int task_init_info(FAR struct task_group_s *group); /**************************************************************************** * Name: task_uninit_info * * Description: * Uninitilize and free task_info_s structure. * * Input Parameters: * - group: The group of new task * * Returned Value: * None. * ****************************************************************************/ void task_uninit_info(FAR struct task_group_s *group); /**************************************************************************** * Name: tls_init_info * * Description: * Allocate and initilize tls_info_s structure. * * Input Parameters: * - tcb: The TCB of new task * * Returned Value: * Zero (OK) on success; a negated errno value on failure. * ****************************************************************************/ int tls_init_info(FAR struct tcb_s *tcb); /**************************************************************************** * Name: tls_dup_info * * Description: * Allocate and duplicate tls_info_s structure. * * Input Parameters: * - dst: The TCB of new task * - src: The TCB of source task * * Returned Value: * Zero (OK) on success; a negated errno value on failure. * ****************************************************************************/ int tls_dup_info(FAR struct tcb_s *dst, FAR struct tcb_s *src); #endif /* __SCHED_TLS_TLS_H */
Patrik-Berglund/esp8266-mqtt-nexa-bridge
user/user_main.c
<filename>user/user_main.c /* * Copyright (c) 2014-2015, <NAME> <tuanpm at live dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ets_sys.h" #include "driver/uart.h" #include "osapi.h" #include "mqtt.h" #include "wifi.h" #include "config.h" #include "debug.h" #include "gpio.h" #include "user_interface.h" #include "mem.h" MQTT_Client mqttClient; uint32_t symbolTime = 250; bool nexaTxBusy = false; bool nexaTxStart = false; uint8_t nexaRawFrame[43] = {0}; uint32_t nexaRawFrameLength = 0; uint32_t nexaRawFrameCounter = 0; uint8_t nexaRawFrameRepeatCounter = 0; typedef enum { FRC1_SOURCE = 0, NMI_SOURCE = 1, } FRC1_TIMER_SOURCE_TYPE; void ICACHE_FLASH_ATTR wifiConnectCb(uint8_t status){ if(status == STATION_GOT_IP){ MQTT_Connect(&mqttClient); } else { MQTT_Disconnect(&mqttClient); } } void ICACHE_FLASH_ATTR mqttConnectedCb(uint32_t *args){ MQTT_Client* client = (MQTT_Client*)args; INFO("MQTT: Connected\n"); MQTT_Subscribe(client, MQTT_TOPIC_NEXA_BRIDGE_SEND, 0); } void ICACHE_FLASH_ATTR mqttDisconnectedCb(uint32_t *args){ MQTT_Client* client = (MQTT_Client*)args; INFO("MQTT: Disconnected\n"); } void ICACHE_FLASH_ATTR mqttPublishedCb(uint32_t *args){ MQTT_Client* client = (MQTT_Client*)args; INFO("MQTT: Published\n"); } void ICACHE_FLASH_ATTR mqttParseMessage(const char* topic, uint32_t topic_len, const char *data, uint32_t data_len){ if(strcmpi(topic, MQTT_TOPIC_NEXA_BRIDGE_SEND) == 0){ parseNexaSendMessage(data, data_len); } else{ INFO("MQTT: Unknown topic\n"); } } void ICACHE_FLASH_ATTR mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len){ char *topicBuf = (char*)os_zalloc(topic_len+1); char *dataBuf = (char*)os_zalloc(data_len+1); MQTT_Client* client = (MQTT_Client*)args; os_memcpy(topicBuf, topic, topic_len); topicBuf[topic_len] = 0; os_memcpy(dataBuf, data, data_len); dataBuf[data_len] = 0; INFO("MQTT: Receive topic: %s, data: %s\n", topicBuf, dataBuf); mqttParseMessage(topicBuf, topic_len, dataBuf, data_len); os_free(topicBuf); os_free(dataBuf); } void ICACHE_FLASH_ATTR parseNexaSendMessage(const char *data, uint32_t data_len){ uint32_t i; int32_t r; jsmn_parser p; jsmntok_t t[15]; bool versionAssigned = false; bool idAssigned = false; bool groupAssigned = false; bool onffAssigned = false; bool channelAssigned = false; bool dimAssigned = false; bool repeatAssigned = false; int32_t version = 1, id, group, onoff, channel, dim = 0, repeat = 4; jsmn_init(&p); r = jsmn_parse(&p, data, data_len, t, sizeof(t)/sizeof(t[0])); if (r < 0) { INFO("NEXA: JSON, Parser error: %d\n", r); return; } if (r < 1 || t[0].type != JSMN_OBJECT) { INFO("NEXA: JSON, Object expected\n"); return; } if((r != 9) && (r != 11) && (r != 13) && (r != 15)){ INFO("NEXA: JSON, Missing token(s): %d\n", r); return; } INFO("NEXA: JSON payload \n"); for (i = 1; i < r; i++) { if (jsonEq(data, &t[i], "version")) { version = strtol(data + t[i+1].start, NULL, 10); versionAssigned = true; INFO("\tVersion: %d\n", version); i++; } else if (jsonEq(data, &t[i], "id")) { id = strtol(data + t[i+1].start, NULL, 10); idAssigned = true; INFO("\tId: %d\n", id); i++; } else if (jsonEq(data, &t[i], "group")) { group = strtol(data + t[i+1].start, NULL, 10); groupAssigned = true; INFO("\tGroup: %d\n", group); i++; } else if (jsonEq(data, &t[i], "onoff")) { onoff = strtol(data + t[i+1].start, NULL, 10); onffAssigned = true; INFO("\tOnOff: %d\n", onoff); i++; } else if (jsonEq(data, &t[i], "channel")) { channel = strtol(data + t[i+1].start, NULL, 10); channelAssigned = true; INFO("\tChannel: %d\n", channel); i++; } else if (jsonEq(data, &t[i], "dim")) { dim = strtol(data + t[i+1].start, NULL, 10); dimAssigned = true; INFO("\tDim: %d\n", dim); i++; } else if (jsonEq(data, &t[i], "repeat")) { repeat = strtol(data + t[i+1].start, NULL, 10); repeatAssigned = true; INFO("\tRepeat: %d\n", repeat); i++; } else { INFO("\tUnexpected key\n"); } } if(idAssigned && groupAssigned && onffAssigned && channelAssigned){ INFO("NEXA: JSON, All parameters assigned for on/off breaker\n"); createNexaFrame(version, id, group, onoff, channel, -1, repeat); }else if(idAssigned && groupAssigned && channelAssigned && dimAssigned){ INFO("NEXA: JSON, All parameters assigned for dimmer \n"); createNexaFrame(version, id, group, 0, channel, dim, repeat); } } void ICACHE_FLASH_ATTR createNexaFrame(int32_t version, int32_t id, int32_t group, int32_t onOff, int32_t channel, int32_t dim, int32_t repeat){ uint8_t header[2] = {0x00, 0x04}; uint8_t zeroBit = 0xA0; uint8_t oneBit = 0x82; uint8_t trailer[5] = {0x00, 0x00, 0x00, 0x00, 0x80}; uint32_t i; uint64_t f = 0; uint8_t fLength = 0; if(!nexaTxBusy){ if(version == 1){ os_memcpy(nexaRawFrame, trailer, 5); fLength+=5; f = (id & 0x3FFFFFF) << 6; f |= ((group & 1) << 5); f |= ((onOff & 1) << 4); f |= ((~channel) & 15); fLength+=32; if(dim >= 0){ f <<=4; f |= (dim & 15); fLength+=4; } INFO("NEXA WORD: %08x %08x\n", *(((uint32_t*)(&f))+1), f); for(i=5;i<fLength;i++){ nexaRawFrame[i] = (testBit64(&f, i-5)) ? oneBit : zeroBit; } os_memcpy(nexaRawFrame+fLength, header, 2); fLength+=2; nexaRawFrameLength = fLength * 8; nexaRawFrameCounter = 0; nexaRawFrameRepeatCounter = (uint8_t) repeat; INFO("NEXA: RAW Frame length: %u \n", nexaRawFrameLength); INFO("NEXA: RAW Frame [HEX]: \n"); for(i=0; i < fLength;i++){ INFO("%02X ", nexaRawFrame[fLength-1-i]); } INFO("\n"); if(dim >= 0){ nexaRawFrame[13] = 0xA0; for(i=13;i > 0;i--){ nexaRawFrame[i] &= 0xF0; nexaRawFrame[i] |= ((nexaRawFrame[i-1] & 0xF0) >> 4); nexaRawFrame[i-1] <<= 4; } INFO("NEXA: After dim, RAW Frame [HEX]: \n"); for(i=0; i < fLength;i++){ INFO("%02X ", nexaRawFrame[fLength-1-i]); } INFO("\n"); } INFO("NEXA: RAW Frame [BIN]: \n"); for(i=0; i < nexaRawFrameLength;i++){ INFO("%d", (testBit8(nexaRawFrame, nexaRawFrameLength-1-i)) ? 1 : 0); } INFO("\n"); nexaTxBusy = true; nexaTxStart = true; } } else{ INFO("NEXA: Error, Transmitter busy!"); } } void symbolTimerCb(void){ if((nexaRawFrameCounter < nexaRawFrameLength) && nexaTxStart){ if(testBit8(nexaRawFrame, nexaRawFrameLength-nexaRawFrameCounter-1)) { gpio_output_set(BIT2, 0, BIT2, 0); } else{ gpio_output_set(0, BIT2, BIT2, 0); } nexaRawFrameCounter++; } else if((nexaRawFrameRepeatCounter > 0) && nexaTxStart){ nexaRawFrameCounter = 0; nexaRawFrameRepeatCounter--; } else{ gpio_output_set(0, BIT2, BIT2, 0); nexaTxStart = false; nexaTxBusy = false; } } bool testBit8(uint8_t A[], int32_t k ){ return (bool)( (A[k/8] & ((uint8_t)1 << (k%8) )) != 0 ); } bool ICACHE_FLASH_ATTR testBit32( uint32_t A[], int32_t k ){ return (bool)( (A[k/32] & ((uint32_t)1 << (k%32) )) != 0 ); } bool ICACHE_FLASH_ATTR testBit64( uint64_t A[], int32_t k ){ return (bool)( (A[k/64] & ((uint64_t)1 << (k%64) )) != 0 ); } bool ICACHE_FLASH_ATTR jsonEq(const char *json, jsmntok_t *tok, const char *s) { return (bool)(tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && strncmpi(json + tok->start, s, tok->end - tok->start) == 0); } void ICACHE_FLASH_ATTR gpioSetup(void){ gpio_init(); PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); gpio_output_set(0, BIT2, BIT2, 0); } void ICACHE_FLASH_ATTR timerSetup(void){ hw_timer_init(FRC1_SOURCE, 1); hw_timer_set_func(symbolTimerCb); hw_timer_arm(symbolTime); } void ICACHE_FLASH_ATTR user_init(void){ system_timer_reinit(); uart_init(BIT_RATE_115200, BIT_RATE_115200); os_delay_us(1000000); INFO("SDK version: %s\n", system_get_sdk_version()); INFO("System init ...\n"); CFG_Load(); gpioSetup(); MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.security); MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive, 1); MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0); MQTT_OnConnected(&mqttClient, mqttConnectedCb); MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); MQTT_OnPublished(&mqttClient, mqttPublishedCb); MQTT_OnData(&mqttClient, mqttDataCb); WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb); timerSetup(); INFO("\nSystem started ...\n"); }
esotericist/frf
src/main/vm.h
<filename>src/main/vm.h #ifndef VM_H_ #define VM_H_ struct node_state* newnode(); proc* newprocess( struct node_state *N ); proc* process_from_pid(struct node_state *N, size_t pid ); void process_setactive( proc *P ); void process_setinactive( proc *P ); void process_reset( proc *P, size_t reasonatom ); void process_kill( proc *P, size_t reasonatom, sfs text ); void process_addmessage( proc *P, struct array_span *arr ); size_t process_messagecount( proc *P ); struct array_span * process_fetchmessage( proc *P ); #define runtimefault(x) \ if( P->errorstate ) { \ process_kill( P, P->errorstate, sfsnew((x)) ); \ } else { \ process_kill( P, a_unspecified_error , sfsnew((x)) ); \ } \ return; void * atomtoprim( struct node_state *N, size_t atom ); size_t primtoatom( struct node_state *N, void * ptr ); size_t wordtoatom( struct node_state *N, struct code_set* ptr ); struct code_set* atomtoword( struct node_state *N, size_t atom ); void registerword(struct node_state *N, size_t atom, struct code_set *ptr ); void unregisterword(struct node_state *N, size_t atom); void pushcallstackframe( proc *P ); void popcallstackframe( proc *P ); void copyframe( struct callstackframe *source, struct callstackframe *dest ); size_t executetimeslice( proc *P ); void scheduler( struct node_state *N ); #endif
esotericist/frf
src/main/vm.c
<gh_stars>1-10 #include <stdio.h> #include <string.h> #include "datatypes.h" #include "atoms.h" #include "stack.h" #include "vm.h" atom(active) atom(inactive) atom(killed) atom(callstack_overflow) atom(exit) void definelist_add( struct node_state *N, sfs key, sfs value ) { sfs k = sfsnew(key); if ( !(sfscmp( k, sfsempty() ))) { return; } sListType *elem = alloc_slist(); elem->s = k; elem->ptr = (uintptr_t) (void *)sfsnew(value); sglib_hashed_sListType_add( N->definetable, elem ); } struct node_state* newnode() { struct node_state *new_N = GC_malloc( sizeof( struct node_state) ); sglib_hashed_iListType_init( new_N->atomtoprimtable ); sglib_hashed_iListType_init( new_N->atomtowordtable ); sglib_hashed_iListType_init( new_N->primtoatomtable ); sglib_hashed_iListType_init( new_N->atomtowordtable ); sglib_hashed_sListType_init( new_N->definetable ); sglib_hashed_iListType_init( new_N->process_table ); new_N->next_pid = 1; definelist_add( new_N, "case", "begin dup " ); definelist_add( new_N, "when", "if pop " ); definelist_add( new_N, "end", "break then dup " ); definelist_add( new_N, "default", "pop 1 if " ); definelist_add( new_N, "endcase", "pop pop 1 until " ); definelist_add( new_N, "}tuple", "} tuple_make" ); definelist_add( new_N, "}array", "} array_make" ); definelist_add( new_N, "0@", "0 getitem" ); definelist_add( new_N, "1@", "1 getitem" ); definelist_add( new_N, "2@", "2 getitem" ); definelist_add( new_N, "3@", "3 getitem" ); definelist_add( new_N, "4@", "4 getitem" ); definelist_add( new_N, "5@", "5 getitem" ); definelist_add( new_N, "0!", "0 setitem" ); definelist_add( new_N, "1!", "1 setitem" ); definelist_add( new_N, "2!", "2 setitem" ); definelist_add( new_N, "3!", "3 setitem" ); definelist_add( new_N, "4!", "4 setitem" ); definelist_add( new_N, "5!", "5 setitem" ); definelist_add( new_N, "", "" ); return new_N; } void process_setactive( proc *P ) { if(P->activitylist_ptr == NULL ) { P->activitylist_ptr = alloc_ilist(); P->activitylist_ptr->first.a_val = P->pid; P->activitylist_ptr->second.p_val = (uintptr_t)(proc *) P; } if(P->executestate == a_inactive) { sglib_iListType_delete(&P->node->processlist_inactive, P->activitylist_ptr ); } if(P->executestate != a_active) { P->executestate = a_active; sglib_iListType_add(&P->node->processlist_active, P->activitylist_ptr ); } } void process_setinactive( proc *P ) { if(P->executestate == a_active) { sglib_iListType_delete(&P->node->processlist_active, P->activitylist_ptr ); } if(P->executestate != a_inactive) { P->executestate = a_inactive; sglib_iListType_add(&P->node->processlist_inactive, P->activitylist_ptr ); } } void process_setdead( proc *P ) { iListType *ptr = P->activitylist_ptr; if(P->executestate == a_active) { sglib_iListType_delete(&P->node->processlist_active, P->activitylist_ptr ); } if(P->executestate == a_inactive) { sglib_iListType_delete(&P->node->processlist_inactive, P->activitylist_ptr ); } if( ! sglib_iListType_is_member( P->node->processlist_dead, P->activitylist_ptr ) ) { P->executestate = a_killed; sglib_iListType_add(&P->node->processlist_dead, ptr ); } } void process_reset( proc *P, size_t reasonatom ) { if( P->current_codestream->nameatom && P->compilestate && P->compilestate->parsemode.compile ) { printf( "undefining word %s\n", atomtostring( P->current_codestream->nameatom) ); iListType *entry = alloc_ilist(); entry->first.a_val = P->current_codestream->nameatom; entry->second.p_val = (uintptr_t)(void *) P->current_codestream; iListType *result; sglib_hashed_iListType_delete_if_member( P->node->atomtowordtable, entry, &result ); swap_ilist(entry); sglib_hashed_iListType_delete_if_member(P->node->wordtoatomtable, entry, &result ); P->current_codestream->nameatom = 0; } process_setdead( P ); P->debugmode = 0; P->currentop = 0; P->current_codestream = 0; P->errorstate = reasonatom; } proc* process_from_pid(struct node_state *N, size_t pid ) { iListType *P_search = alloc_ilist(); P_search->first.a_val = pid; iListType *P_result = sglib_hashed_iListType_find_member( N->process_table, P_search ); if( P_result == NULL) { return NULL; } else { return (proc *)(uintptr_t)P_result->second.p_val; } } void process_kill( proc *P, size_t reasonatom, sfs text ) { if( sfsmatchcount( text, sfsnew( "%zu" ) ) ) { printf(text, P->pid, atomtostring(reasonatom) ); } else { printf(text, atomtostring(reasonatom) ); } process_reset( P, reasonatom ); } void process_addmessage( proc *P, struct array_span *arr ) { qListType *message = alloc_qlist(); message->p_val = (uintptr_t)(struct array_span *) arr; sglib_qListType_concat( &P->messagequeue, message ); if( P->executestate == a_inactive ) { process_setactive(P); } } size_t process_messagecount( proc *P ) { return sglib_qListType_len( P->messagequeue ); } struct array_span * process_fetchmessage( proc *P ) { qListType *first = P->messagequeue; struct array_span *arr = (struct array_span *)(uintptr_t) first->p_val; sglib_qListType_delete(&P->messagequeue, first ); return arr; } proc* newprocess( struct node_state *N ) { proc *new_P = GC_malloc( sizeof( proc ) ); // more init stuff goes here size_t max = 1024; new_P->d = GC_malloc( sizeof( struct datastack ) + sizeof ( struct datapoint ) * (max) ); new_P->d->max = max; new_P->c = GC_malloc( sizeof( struct callstack ) + sizeof ( struct callstackframe ) * (max) ); new_P->c->max = max; new_P->node = N; new_P->max_slice_ops = 20; // arbitrarily chosen value to keep things cycling between processes new_P->pid = N->next_pid++; new_P->processtable_ptr = alloc_ilist(); new_P->processtable_ptr->first.a_val = new_P->pid; new_P->processtable_ptr->second.p_val = (uintptr_t)(proc *) new_P; sglib_hashed_iListType_add( N->process_table, new_P->processtable_ptr ); process_setactive(new_P); return new_P; } void procreport( proc *P ) { sfs resultstring = sfscatprintf( sfsempty(), "[%zu] stack: %s. total operations: %zu", P->pid, dump_stack(P), P->total_operations ); if( P->errorstate == a_exit ) { resultstring = sfscatc( resultstring, " OK" ); } else { resultstring = sfscatsfs( sfscatc( resultstring, " " ), sfstoupper( atomtostring( P->errorstate ) ) ); } printf( "%s\n\n", resultstring ); } void freeprocess( proc *P ) { if(P->executestate == a_active) { sglib_iListType_delete( &P->node->processlist_active, P->activitylist_ptr ); } if(P->executestate == a_inactive) { sglib_iListType_delete( &P->node->processlist_inactive, P->activitylist_ptr ); } if(P->executestate == a_killed) { sglib_iListType_delete( &P->node->processlist_dead, P->activitylist_ptr ); } sglib_hashed_iListType_delete(P->node->process_table, P->processtable_ptr ); } #define callstack P->c->stack #define calltop P->c->top typedef void (*call_prim)(proc *p); void * atomtoprim( struct node_state *N, size_t atom ) { iListType *it = alloc_ilist(); it->first.a_val = atom; struct ilist *tmp = sglib_hashed_iListType_find_member( N->atomtoprimtable, it ); if(tmp) { return (void*)(uintptr_t)tmp->second.p_val; } return 0; } size_t primtoatom( struct node_state *N, void * ptr ) { iListType *tmp = alloc_ilist(); tmp->first.p_val = (uintptr_t)ptr; return sglib_hashed_iListType_find_member( N->primtoatomtable, tmp )->second.a_val; } size_t wordtoatom( struct node_state *N, struct code_set* ptr ) { iListType *it = alloc_ilist(); it->first.p_val = (uintptr_t)(void *)ptr; return sglib_hashed_iListType_find_member( N->wordtoatomtable, it )->second.a_val; } struct code_set* atomtoword( struct node_state *N, size_t atom ) { iListType *it = alloc_ilist(); it->first.a_val = atom; struct ilist *tmp = sglib_hashed_iListType_find_member( N->atomtowordtable, it ); if( tmp ) { return (void*)(uintptr_t)tmp->second.p_val; } else { return 0; } } void registerword(struct node_state *N, size_t atom, struct code_set *ptr ) { iListType *newword = alloc_ilist(); newword->first.a_val = atom; newword->second.p_val = (uintptr_t)(void*)ptr; sglib_hashed_iListType_add( N->atomtowordtable, newword ); iListType *newword2 = swap_ilist(newword); sglib_hashed_iListType_add( N->wordtoatomtable, newword2 ); } void unregisterword(struct node_state *N, size_t atom) { iListType *newword = alloc_ilist(); newword->first.a_val = atom; newword->second.p_val = (uintptr_t)(void*)atomtoword(N, atom); sglib_hashed_iListType_delete( N->atomtowordtable, newword ); iListType *newword2 = swap_ilist( newword ); sglib_hashed_iListType_delete( N->wordtoatomtable, newword2 ); } void pushcallstackframe( proc *P ){ if( calltop < P->c->max ) { callstack[calltop].cword = P->current_codestream; callstack[calltop].varset = P->current_varset; callstack[calltop].currentop = P->currentop; calltop++; } else { runtimefault( "error in %zu: callstack overflow\n" ) } } void popcallstackframe( proc *P ) { if( calltop > 0 ) { calltop--; P->current_codestream = callstack[calltop].cword; P->current_varset = callstack[calltop].varset; P->currentop = callstack[calltop].currentop; callstack[calltop].cword = 0; callstack[calltop].currentop = 0; callstack[calltop].varset = 0; } else { process_kill( P, a_exit, sfsempty() ); } } void copyframe( struct callstackframe *source, struct callstackframe *dest ) { dest->currentop = source->currentop; dest->cword = source->cword; if(source->varset ) { dest->varset = grow_variable_set(source->varset); dest->varset->count--; } } void * funcfrommungedptr( uintptr_t p ) { return (void *)(uintptr_t) ( p & ~(3) ); } size_t executetimeslice( proc *P ) { size_t count = 0; while( P->current_codestream && P->current_codestream->instructioncount > 0 && P->executestate == a_active && count++ < P->max_slice_ops ) { size_t pos = P->currentop++; uintptr_t check_op = P->current_codestream->codestream[pos].u_val; if( check_op == 0 || P->errorstate ) { P->current_codestream = 0; break; } if( check_op & 3 ) { sfs stackstate = sfsempty(); if( P->debugmode ) { stackstate = dump_stack (P ); } call_prim ptr = funcfrommungedptr( check_op ); if( P->debugmode ) { sfs primname = atomtostring( primtoatom( P->node, ptr ) ); printf("[%zu] %s > %s\n", P->pid, stackstate, primname ); } ptr( P ); } } P->total_operations += count; return count; } void scheduler( struct node_state *N ) { iListType *p_ref; struct sglib_iListType_iterator it; proc *P; if (N->processlist_active) { for( p_ref =sglib_iListType_it_init(&it, N->processlist_active); p_ref != NULL ; p_ref=sglib_iListType_it_next(&it) ) { P = ( proc * )(uintptr_t) p_ref->second.p_val; if( P->current_codestream && ( P->compilestate == NULL || P->compilestate->parsemode.flags == 0)) { executetimeslice(P); } else { if(P->errorstate) { procreport(P); freeprocess(P); } else { process_setinactive(P); } } } } for( p_ref =sglib_iListType_it_init(&it, N->processlist_dead); p_ref != NULL ; p_ref=sglib_iListType_it_next(&it) ) { P = ( proc * )(uintptr_t) p_ref->second.p_val; procreport(P); freeprocess(P); } }
esotericist/frf
src/main/events.h
#ifndef files_H_ #define files_H_ #include "datatypes.h" #include "atoms.h" #include <uv.h> extern uv_loop_t *uvloop; void events_initialization(); void events_teardown(); #endif
esotericist/frf
src/main/structures.c
<gh_stars>1-10 #include "prims.h" #include "stdlib.h" #include "stack.h" #include "vm.h" atom(range_error) #pragma GCC push_options #pragma GCC optimize("align-functions=16") void copy_span( struct array_span *source, struct array_span *dest ) { for(size_t i = 0; i < source->size; i++ ) { dest->elems[i] = source->elems[i]; } } struct array_span* grow_span( struct array_span *arr ) { struct array_span *newarr = newarrayspan(arr->size + 1 ); copy_span(arr, newarr); return newarr; } void copy_span_skip_source_idx( struct array_span *source, struct array_span *dest, size_t source_idx, size_t dest_idx ) { for(size_t i = 0; i < source->size; i++ ) { dest->elems[i] = source->elems[i]; } } void copy_span_skip_dest_idx( struct array_span *source, struct array_span *dest, size_t dest_idx ) { size_t offset = 0; for(size_t i = 0; i < source->size + 1; i++ ) { if( i == dest_idx ) { offset = 1; } dest->elems[i+offset] = source->elems[i]; } } void structure_explode( proc *P ) { require_structure *arr = pop_array; for(size_t i = 0; i < arr->size; i++ ) { push_dp(P, arr->elems[i]); } push_int(arr->size); } #define get_item(arr, idx, dp) \ if( idx >= 0 && idx < arr->size) { \ dp.u_val = arr->elems[idx].u_val; \ } else { \ P->errorstate = a_range_error; \ runtimefault( "error in %zu: index exceeds bounds\n" ); \ } #define set_item( arr, idx, dp, newarr)\ if( idx >= 0 && idx < arr->size) {\ newarr = newarrayspan( arr->size );\ copy_span( arr, newarr );\ newarr->elems[idx] = dp;\ } else {\ P->errorstate = a_range_error;\ runtimefault( "error in %zu: index exceeds bounds\n" );\ } prim(getitem) { require_int idx = pop_int; require_structure *arr = pop_array; struct datapoint dp; get_item(arr, idx, dp) push_dp( P, dp); } prim( setitem ) { require_int idx = pop_int; needstack(1) struct datapoint arrdp= pop_dp(P); struct array_span *arr; if( dp_is_structure(arrdp)) { arr = dp_get_array(arrdp); } else { stackfault( a_expected_structure ) runtimefault( "error in %zu: expected array or tuple\n") } needstack(1) struct datapoint dp = pop_dp(P); struct array_span *newarr; set_item(arr, idx, dp, newarr) if(dp_is_array(arrdp)) { push_arr(newarr); } else { push_tup(newarr); } } // #region tuples prim( tuple_make ) { require_int count = pop_int; if( count > 0 ) { needstack( count ) struct array_span *arr = newarrayspan( count ); for(size_t i = 0; i < count; i++ ) { arr->elems[count - (i + 1) ] = pop_dp(P); } push_tup(arr); } else { runtimefault( "error in %zu: tuple_make expects a positive integer\n" ); } } prim( tuple_getitem ) { require_int idx = pop_int; require_tuple *arr = pop_tuple; struct datapoint dp; get_item(arr, idx, dp) push_dp( P, dp); } prim( tuple_setitem ) { require_int idx = pop_int; require_tuple *arr = pop_tuple; needstack(1) struct datapoint dp = pop_dp(P); struct array_span *newarr; set_item(arr, idx, dp, newarr) push_tup(newarr); } prim( tuple_explode ) { structure_explode(P); } // #endregion // #region arrays prim(array_make) { require_int count = pop_int; if( count > 0 ) { needstack( count ) struct array_span *arr = newarrayspan( count ); for(size_t i = 0; i < count; i++ ) { arr->elems[count - (i + 1) ] = pop_dp(P); } push_arr(arr); } else { struct array_span *arr = newarrayspan(0); push_arr(arr); } } prim(array_vals) { require_arr *arr = pop_array; size_t count = arr->size; for(size_t i = 0; i < count; i++ ) { push_dp(P, arr->elems[i]); } } prim(array_count) { require_arr *arr = pop_array; push_int( arr->size ); } prim(array_getitem) { require_int idx = pop_int; require_arr *arr = pop_array; struct datapoint dp; get_item(arr, idx, dp) push_dp( P, dp); } prim(array_setitem) { require_int idx = pop_int; require_arr *arr = pop_array; needstack(1) struct datapoint dp = pop_dp(P); struct array_span *newarr; set_item(arr, idx, dp, newarr) push_arr(newarr); } prim(array_appenditem) { require_arr *arr = pop_array; needstack(1) struct datapoint dp = pop_dp(P); struct array_span *newarr = grow_span( arr ); newarr->elems[arr->size] = dp; push_arr(newarr); } prim(array_insertitem) { require_int idx = pop_int; require_arr *arr = pop_array; needstack(1) struct datapoint dp = pop_dp(P); if( idx >= 0 && idx <= arr->size) { struct array_span *newarr = newarrayspan( arr->size + 1 ); copy_span_skip_dest_idx(arr, newarr, idx ); newarr->elems[idx] = dp; push_arr(newarr); } else { P->errorstate = a_range_error; runtimefault( "error in %zu: range exceeds bounds\n" ); } } prim(array_delitem) { require_int idx = pop_int; require_arr *arr = pop_array; size_t offset = 0; if( idx >= 0 && idx < arr->size) { struct array_span *newarr = newarrayspan( arr->size - 1); for(size_t i = 0; i < arr->size; i++ ) { if( i == idx ) { offset = 1; } else { newarr->elems[i - offset] = arr->elems[i]; } } push_arr(newarr); } else { P->errorstate = a_range_error; runtimefault( "error in %zu: range exceeds bounds\n" ); } } prim(array_reverse) { require_arr *arr = pop_array; size_t count = arr->size; struct array_span *newarr = newarrayspan( count ); for(size_t i = 0; i < count; i++ ) { newarr->elems[count - (i + 1) ] = arr->elems[i]; } push_arr(newarr); } prim(array_join) { require_string s = pop_string; require_arr *arr = pop_array; sfs workingstring = sfsempty(); for(size_t i = 0; i < arr->size; i++ ) { if( i > 0 ) { workingstring = sfscatsfs (workingstring, s ); } workingstring = sfscatsfs( workingstring, objecttostring( arr->elems[i] )); } push_string(workingstring); } prim(array_interpret) { require_arr *arr = pop_array; sfs workingstring = sfsempty(); for(size_t i = 0; i < arr->size; i++ ) { workingstring = sfscatsfs( workingstring, objecttostring( arr->elems[i] )); } push_string(workingstring); } prim(array_explode) { structure_explode(P); } // #endregion
esotericist/frf
src/main/compile.h
#ifndef COMPILE_H_ #define COMPILE_H_ void initcommonstring(); void parse_line( proc *P, sfs input ); #endif
esotericist/frf
src/main/events.c
<gh_stars>1-10 #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <dirent.h> #include "stack.h" #include "vm.h" #include "events.h" #include "structures.h" #include "prims.h" uv_loop_t *uvloop; // definitions for various event things typedef struct timer { sfs timer_handle; proc *P; } event_timer; sListType *timer_table[slist_hash_size]; // swiped from https://stackoverflow.com/a/47229318 on 2021/11/18 // /* The original code is public domain -- <NAME> 4/9/09 */ /* Modifications, public domain as well, by <NAME>, 11/10/17 - Switched to getc on 5/23/19 */ ssize_t getline(char **lineptr, size_t *n, FILE *stream) { size_t pos; int c; if (lineptr == NULL || stream == NULL || n == NULL) { errno = EINVAL; return -1; } c = getc(stream); if (c == EOF) { return -1; } if (*lineptr == NULL) { *lineptr = GC_malloc(128); if (*lineptr == NULL) { return -1; } *n = 128; } pos = 0; while(c != EOF) { if (pos + 1 >= *n) { size_t new_size = *n + (*n >> 2); if (new_size < 128) { new_size = 128; } char *new_ptr = GC_realloc(*lineptr, new_size); if (new_ptr == NULL) { return -1; } *n = new_size; *lineptr = new_ptr; } ((unsigned char *)(*lineptr))[pos ++] = c; if (c == '\n') { break; } c = getc(stream); } (*lineptr)[pos] = '\0'; return pos; } void events_initialization() { uvloop = GC_malloc( sizeof(uv_loop_t)); uv_loop_init(uvloop); sglib_hashed_sListType_init(timer_table); } void events_teardown() { uv_loop_close(uvloop); GC_free(uvloop); } #pragma GCC push_options #pragma GCC optimize("align-functions=16") // #region libuv helper prims // stub: eventually we want a monotonic thing like erlang, but that's work prim(now) { push_int(uv_hrtime()); } // #endregion // #region event prims atom(event_timer) atom(complete) void event_timer_callback( uv_timer_t *req ) { sListType *elem = (sListType *)(void *)req->data; proc *target_P = (proc *)(uintptr_t) elem->ptr; struct array_span *arr = newarrayspan(3); dp_put_atom(&arr->elems[0], a_event_timer); dp_put_string(&arr->elems[1], elem->s); dp_put_atom(&arr->elems[2], a_complete); process_addmessage( target_P, arr); /* sglib_hashed_sListType_delete(timer_table, elem); sglib_hashed_sListType_add(timer_table, elem); */ } prim(event_timer) { require_string handle = pop_string; require_int delay_in_ms = pop_int; uv_timer_t *timer_handle = GC_malloc(sizeof(uv_timer_t)); uv_timer_init(uvloop, timer_handle); uv_timer_start(timer_handle,event_timer_callback, delay_in_ms, 0); sListType *timer = alloc_slist(); timer->s = handle; timer->ptr = (uintptr_t)(proc *) P; timer_handle->data = timer; } // #endregion // #region ipc prims atom(message) prim(message_send) { needstack(2) struct datapoint val = pop_dp(P); require_int target_pid = pop_int; proc * target_P = process_from_pid(P->node, target_pid); if( target_P == NULL ) { runtimefault( "error in %zu: process doesn't exist" ) } struct array_span *arr = newarrayspan(3); dp_put_atom(&arr->elems[0], a_message); dp_put_int(&arr->elems[1], P->pid); arr->elems[2].u_val = val.u_val; process_addmessage( target_P, arr); } atom(empty) prim(message_receive) { if(process_messagecount(P) > 0) { push_tup(process_fetchmessage(P)); } else { push_atom(a_empty); } } prim(message_waitfor) { if(process_messagecount(P) == 0) { process_setinactive(P); P->currentop--; } else { push_int(process_messagecount(P)); } } prim(message_count) { push_int(process_messagecount(P)); } // #endregion // #region file manipulation prims // ( s:filename -- i:size ) prim(fsize) { require_string filename = pop_string; struct stat statbuf; if( stat( filename, &statbuf) == -1 ) { runtimefault("error in %zu: unable to open file"); } push_int(statbuf.st_size); } // ( -- s:cwd ) prim(fcwd) { char buffer[BUFSIZ]; if( getcwd(buffer, BUFSIZ) ) { push_string( sfsnew( buffer ) ); } } // (s:filename -- ) prim(frm) { require_string filename = pop_string; int result = remove( filename ); push_int(result); } // (s:original s:newname -- ) prim(fmv) { require_string newname = pop_string; require_string original = pop_string; int result = rename( original, newname ); push_int(result); } // (s:pathname -- arr/int ) prim(fgetdir) { require_string pathname = pop_string; DIR *thedir = opendir( pathname ); struct dirent * entry; struct array_span *arr = newarrayspan(0); if(thedir != NULL) { while(( entry = readdir(thedir)) != NULL ) { sfs fname = sfsnew(entry->d_name); sfs fullname = sfscatprintf( pathname, "/%s", fname ); struct stat statbuf; stat( fullname, &statbuf); if( statbuf.st_mode & S_IFDIR) { fname = sfscatc(fname, "/" ); } arr = grow_span(arr); struct datapoint dp; dp_put_string( &dp, fname ); arr->elems[arr->size - 1] = dp; } push_arr(arr); } else { push_int(0); } } // (s:inputstring s:filename -- i:finaloffset ) prim(fappend) { require_string filename = pop_string; require_string inputstring = pop_string; FILE *thefile = fopen( filename, "ab" ); if( thefile == NULL ) { sfs error = sfscatprintf(sfsempty(), "error in %%zu: unable to open file: %s\n", filename ); runtimefault( error ); } else { fseek( thefile, 0, SEEK_END ); fprintf( thefile, "%s", inputstring ); } fclose(thefile); struct stat statbuf; stat( filename, &statbuf); push_int( statbuf.st_size ); } // (s:inputstring s:filename i:initialoffset -- i:finaloffset ) prim(fwrite) { require_int initialoffset = pop_int; require_string filename = pop_string; require_string inputstring = pop_string; FILE *thefile = fopen( filename, "wb" ); if( thefile == NULL ) { sfs error = sfscatprintf(sfsempty(), "error in %%zu: unable to open file: %s\n", filename ); runtimefault( error ); } else { fseek( thefile, initialoffset, SEEK_SET ); fprintf( thefile, "%s", inputstring ); } fclose(thefile); struct stat statbuf; stat( filename, &statbuf); push_int( statbuf.st_size ); } // ( s:filename i:initialoffset s:delimiter -- i:finaloffset s:outputstring ) prim(freadto) { require_string delimiter = pop_string; require_int initialoffset = pop_int; require_string filename = pop_string; if (!sfscmp( delimiter, sfsnew("$EOF$") )) { delimiter = sfsempty(); } else { } struct stat statbuf; if( stat( filename, &statbuf) == -1 ) { runtimefault("error in %zu: unable to open file"); } if( initialoffset > statbuf.st_size ) { push_string(sfsempty()); push_int(statbuf.st_size); } sfs finalstring = sfsempty(); size_t finaloffset = 0; FILE *thefile = fopen( filename, "r" ); if( thefile == NULL ) { sfs error = sfscatprintf(sfsempty(), "error in %%zu: unable to open file: %s\n", filename ); runtimefault( error ); } else { char buffer[BUFSIZ]; fseek( thefile, initialoffset, SEEK_SET ); size_t i = 0; do{ int c = fgetc(thefile); if( feof(thefile) || c == delimiter[0] ) { if( i < BUFSIZ ) { buffer[i] = 0; } finalstring = sfscatsfs(finalstring, sfsnew(buffer)); finaloffset = initialoffset + i + 1; break; } buffer[i] = c; i++; if(i == BUFSIZ ) { finalstring = sfscatsfs(finalstring, sfsnewlen(buffer, i - 1)); initialoffset = initialoffset + i; i = 0; } } while ( true ); fclose(thefile); } push_string(finalstring); push_int(finaloffset); } prim(readline) { char *instring = NULL; size_t buffer_size = 0; ssize_t read_size; read_size = getline( &instring, &buffer_size, stdin ); if( read_size > 0 ) { push_string(sfsnewlen( instring, read_size )); } else { push_string(sfsempty()); } } prim2(print, .) { needstack(1) struct datapoint dp = pop_dp(P); size_t type = checktype(dp); if (type == a_type_string) { printf("%s", dp_get_string(dp)); } else { printf("%s", formatobject(P, dp)); } } // #endregion
esotericist/frf
src/main/prims.h
<reponame>esotericist/frf #ifndef PRIMS_H_ #define PRIMS_H_ #include "datatypes.h" #include "atoms.h" struct preprim { void *thefunc; char *prim; }; struct preprim *preprims; size_t numpreprims; void preregisterprim( void *thefunc, char *str ); void finalizeprims( struct node_state *N ); #define prim(x) \ void p_##x ( proc *P );\ static inline void __attribute__ ((constructor)) p_##x##_() { \ preregisterprim( &p_##x, (#x)); \ }\ void p_##x ( proc *P ) #define prim2(x, y) \ void p_##x ( proc *P );\ static inline void __attribute__ ((constructor)) p_##x##_() { \ preregisterprim( &p_##x, (#y)); \ }\ void p_##x ( proc *P ) #endif
esotericist/frf
src/main/compile.c
#include "datatypes.h" #include "compile.h" #include "prims.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "vm.h" int errorstate = 0; #define pmode P->compilestate->parsemode #define vset P->current_codestream->vars uintptr_t tag_prim (void *v) { return ( (uintptr_t)(void *) v ) | 3; } void append_prim( proc *P, size_t v ) { void * ptr = atomtoprim( P->node, v ); append_cp( P, tag_prim( ptr ) ); } void append_word( proc *P, void * v ) { append_cp(P, (uintptr_t)(void *) v ); } int64_t parse_atomtovar( proc *P, size_t atom ) { iListType *it = alloc_ilist(); it->first.a_val = atom; struct ilist *tmp = sglib_hashed_iListType_find_member( P->compilestate->vartable, it ); if(tmp) { return tmp->second.a_val; } return -1; } void record_var(proc *P, sfs varname, size_t varnum ) { size_t varatom = stringtoatom( sfstolower( sfstrim( varname, " ") ) ); iListType *newword = alloc_ilist(); newword->first.a_val = varatom; newword->second.a_val = varnum; sglib_hashed_iListType_add( P->compilestate->vartable, newword ); vset->vars[vset->count].name = varatom; vset->vars[vset->count].dp.u_val = 1; vset = grow_variable_set( vset ); } atom(if) atom(else) atom(then) atom(begin) atom(until) atom(repeat) atom(continue) atom(break) atom(while) atom(jmp) atom(cjmp) #define flowstack P->compilestate->flowcontrolstack #define flowtop P->compilestate->flowcontroltop #define flowtopatom flowstack[flowtop].flowatom #define flowtopcell flowstack[flowtop].celltarget bool searchflowstack( proc *P, size_t searchatom ) { for(size_t i = flowtop ; i > 0 ; i-- ) { if ( flowstack[i].flowatom == searchatom ) { return true; } } return false; } void addflowframe(proc *P, size_t thisatom ) { flowtop++; flowstack[flowtop].flowatom = thisatom; flowstack[flowtop].celltarget = P->current_codestream->instructioncount; } void popflowtop(proc *P ) { flowstack[flowtop].flowatom = 0; flowstack[flowtop].celltarget = 0; flowtop--; } void dropflowframe(proc *P, size_t stackitem ) { for ( size_t i = stackitem ; i < flowtop ; i++ ) { flowstack[flowtop].flowatom = flowstack[flowtop + 1].flowatom; flowstack[flowtop].celltarget = flowstack[flowtop + 1].celltarget; } flowtop--; } /* P, firstcell.i, lastcell.i, keyop.i, targetcell.i */ void updatecells(proc *P, size_t firstcell, size_t lastcell, uintptr_t keyop, size_t targetcell ) { for ( size_t i = firstcell ; i < lastcell ; i++ ) { if( P->current_codestream->codestream[i].u_val == keyop && P->current_codestream->codestream[i+1].u_val == keyop ) { P->current_codestream->codestream[i+1].u_val = targetcell; } } } void unexpectedprim( proc *P, size_t foundatom, size_t previousatom ) { printf( "error: unexpected %s after %s\n", atomtostring( foundatom ), atomtostring( previousatom ) ); } bool checkflowcontrol(proc *P, size_t maybeop ) { size_t pos_if, pos_then, pos_else, loopstart, loopend; if( maybeop == a_if ) { addflowframe(P, a_if ); append_cp(P, 0); append_cp(P, 0); } else if ( maybeop == a_else ) { if( flowtopatom == a_if ) { addflowframe(P, a_else ); append_cp(P, 0); append_cp(P, 0); } else { unexpectedprim( P, maybeop, flowtopatom ); } } else if ( maybeop == a_then ) { if( flowtopatom == a_if ) { pos_if = flowtopcell; pos_then = P->current_codestream->instructioncount; popflowtop( P ); void * ptr = atomtoprim( P->node, a_cjmp ); P->current_codestream->codestream[pos_if].u_val = tag_prim( ptr ) ; P->current_codestream->codestream[pos_if+1].u_val = pos_then; } else if( flowtopatom == a_else ) { pos_else = flowtopcell; popflowtop ( P ); pos_if = flowtopcell; popflowtop ( P ); pos_then = P->current_codestream->instructioncount; P->current_codestream->codestream[pos_if].u_val = tag_prim( atomtoprim( P->node, a_cjmp ) ); P->current_codestream->codestream[pos_if+1].u_val = pos_else+2; P->current_codestream->codestream[pos_else].u_val = tag_prim( atomtoprim( P->node, a_jmp ) ); P->current_codestream->codestream[pos_else+1].u_val = pos_then; } else { unexpectedprim( P, maybeop, flowtopatom ); } } else if ( maybeop == a_begin ) { addflowframe( P, a_begin ); } else if ( maybeop == a_until ) { if( flowtopatom == a_begin ) { loopstart = flowtopcell; loopend = P->current_codestream->instructioncount; popflowtop( P ); append_prim( P, a_cjmp ); append_cp( P, loopstart ); updatecells(P, loopstart, loopend, tag_prim( atomtoprim ( P->node, a_continue ) ), loopstart); updatecells(P, loopstart, loopend, tag_prim( atomtoprim ( P->node, a_break ) ), loopend+2); updatecells(P, loopstart, loopend, tag_prim( atomtoprim ( P->node, a_while ) ), loopend+2); } else { unexpectedprim( P, maybeop, flowtopatom ); } } else if ( maybeop == a_repeat ) { if( flowtopatom == a_begin ) { loopstart = flowtopcell; loopend = P->current_codestream->instructioncount; popflowtop( P ); append_prim( P, a_jmp ); append_cp( P, loopstart ); updatecells(P, loopstart, loopend, tag_prim( atomtoprim ( P->node, a_continue ) ), loopstart); updatecells(P, loopstart, loopend, tag_prim( atomtoprim ( P->node, a_break ) ), loopend+2); updatecells(P, loopstart, loopend, tag_prim( atomtoprim ( P->node, a_while ) ), loopend+2); } else { unexpectedprim( P, a_repeat, flowtopatom ); } } else if ( maybeop == a_while ) { if( searchflowstack(P, a_begin )) { append_prim( P, a_while ); append_prim( P, a_while ); } else { unexpectedprim( P, maybeop, flowtopatom ); } } else if ( maybeop == a_continue ) { if( searchflowstack(P, a_begin )) { append_prim( P, a_continue ); append_prim( P, a_continue ); } else { unexpectedprim( P, maybeop, flowtopatom ); } } else if ( maybeop == a_break ) { if( searchflowstack(P, a_begin )) { append_prim( P, a_break ); append_prim( P, a_break ); } else { unexpectedprim( P, maybeop, flowtopatom ); } } else { return false; } return true; } atom(push_int) atom(push_string) atom(push_atom) atom(push_var) atom(call) atom(exit) atom(var) atom2(var_store, var!) atom2(exclaim, !) atom(unexpected_variable) atom(unrecognized_token) // set in frf.c // used for comparisons in tokenize sfs numstring; sfs opstring; void tokenize( proc *P, sfs input ) { sfs c = sfsnewlen( input, 1 ); if( sfsmatchcount ( numstring, c ) || ( sfslen(input) >=2 && sfsmatchcount( opstring, c ) ) ) { append_cp( P, ( (uintptr_t)(void *) atomtoprim( P->node, a_push_int ) ) | 3 ); append_cp( P, atoi( input ) ); return; } input = sfstolower( input ); size_t maybe_op = verifyatom( input ); if( pmode.directive) { if( P->compilestate->keyword == a_var || P->compilestate->keyword == a_var_store) { if( maybe_op && parse_atomtovar(P, maybe_op) >= 0 ) { printf( "error: unexpected existing variable %s in variable declaration.\n", atomtostring( maybe_op ) ); } else { record_var( P, input, vset->count ); } pmode.directive = false; if(P->compilestate->keyword == a_var_store ) { append_prim( P, a_push_var ); append_cp( P, vset->count -1 ); append_prim( P, a_exclaim ); } P->compilestate->keyword = 0; return; } } else if( maybe_op == a_var ) { pmode.directive = true; P->compilestate->keyword = a_var; return; } else if( maybe_op == a_var_store ) { pmode.directive = true; P->compilestate->keyword = a_var_store; return; } if( checkflowcontrol(P, maybe_op) ) { return; } else { if( maybe_op ) { int64_t maybe_var = parse_atomtovar( P, maybe_op ); if( maybe_var >= 0 ) { append_prim( P, a_push_var); append_cp( P, maybe_var ); return; } void * maybe_prim = atomtoprim( P->node, maybe_op ); if( maybe_prim ) { append_prim( P, maybe_op ); return; } else { void * maybe_word = atomtoword(P->node, maybe_op ); if( maybe_word ) { append_prim( P, a_call ); append_word( P, maybe_word ); return; } } } } printf( "unexpected token: %s\n", sfstrim( input, sfsnew( " " ) ) ); process_reset(P, a_unrecognized_token); } typedef void (*call_prim)(proc *p); #define checktoken(s) do { sListType *elem = slist_find( P->node->definetable, (s)); \ if( elem) { \ inputstr = sfscatsfs( sfsnew((char *) (uintptr_t) elem->ptr), inputstr ); \ workingstring =sfsempty(); \ } else { \ tokenize(P, s);\ }\ } while(0) #define continue_str workingstring = sfscatc( workingstring, nextchar ) sfs parse_atom( proc *P, sfs inputstr ) { sfs workingstring = sfsempty(); sfs nextchar = sfsempty(); while ( sfslen( inputstr ) ) { nextchar = sfsnewlen( inputstr, 1 ); inputstr = sfsright( inputstr, sfslen( inputstr) - 1 ); size_t nextchar_a = verifyatom( nextchar ); if( nextchar_a == a__squote ) { size_t stringatom = stringtoatom( workingstring ); append_prim( P, a_push_atom ); append_cp(P, stringatom ); workingstring = sfsempty(); pmode.atom = false; return inputstr; } else { continue_str; } } return inputstr; } sfs parse_string(proc *P, sfs inputstr ) { size_t a__little_r = stringtoatom( sfsnew( "r" )); size_t a__big_r = stringtoatom( sfsnew( "R" )); size_t a__little_n = stringtoatom( sfsnew( "n" )); sfs workingstring = sfsempty(); sfs nextchar = sfsempty(); while ( sfslen( inputstr ) ) { nextchar = sfsnewlen( inputstr, 1 ); inputstr = sfsright( inputstr, sfslen( inputstr) - 1 ); size_t nextchar_a = verifyatom( nextchar ); if( (nextchar_a == a__little_r ) || (nextchar_a == a__big_r ) || ( nextchar_a == a__little_n ) ) { if( pmode.escape ) { pmode.escape = false; nextchar = "\n"; } continue_str; } else if ( nextchar_a == a__backslash ) { if( pmode.escape ) { pmode.escape = false; continue_str; } else { nextchar = sfsempty(); pmode.escape = true; } } else if ( nextchar_a == a__dquote ) { if( pmode.escape ) { pmode.escape = false; continue_str; nextchar = sfsempty(); } else { size_t stringatom = stringtoatom( workingstring ); append_prim( P, a_push_string ); append_cp(P, stringatom ); workingstring = sfsempty(); pmode.string = false; return inputstr; } } else { continue_str; } } return inputstr; } sfs parse_immed(proc *P, sfs inputstr ) { sfs workingstring = sfsempty(); sfs nextchar = sfsempty(); while ( sfslen( inputstr ) ) { if(P->errorstate) { return workingstring; } nextchar = sfsnewlen( inputstr, 1 ); inputstr = sfsright( inputstr, sfslen( inputstr) - 1 ); size_t nextchar_a = verifyatom( nextchar ); if( nextchar_a == a__space || nextchar_a == a__newline ) { if( sfslen( workingstring) > 0 ) { checktoken( workingstring); } workingstring = sfsempty(); } else if( nextchar_a == a__dsign ) { if( sfslen( workingstring) == 0 ) { pmode.directive = true; return sfscatc( nextchar, inputstr ); } else { continue_str; } } else if( nextchar_a == a__dquote ) { pmode.string = true; return inputstr; } else if( nextchar_a == a__squote ) { pmode.atom = true; return inputstr; } else if( nextchar_a == a__parenl ) { if( sfslen(workingstring) > 0 ) { checktoken( workingstring); } workingstring = sfsempty(); pmode.comment = true; return inputstr; } else if( nextchar_a == a__colon ) { pmode.compile = true; return inputstr; } else { continue_str; } } return inputstr; } sfs parse_compile(proc *P, sfs inputstr ) { sfs workingstring = sfsempty(); sfs nextchar = sfsempty(); while ( sfslen( inputstr ) ) { if(P->errorstate) { return workingstring; } nextchar = sfsnewlen( inputstr, 1 ); inputstr = sfsright( inputstr, sfslen( inputstr) - 1 ); size_t nextchar_a = verifyatom( nextchar ); if( nextchar_a == a__space || nextchar_a == a__newline ) { if( sfslen( workingstring) > 0 ) { checktoken( workingstring); } workingstring = sfsempty(); } else if( nextchar_a == a__dquote ) { pmode.string = true; return inputstr; } else if( nextchar_a == a__squote ) { pmode.atom = true; return inputstr; } else if( nextchar_a == a__parenl ) { if( sfslen(workingstring) > 0 ) { checktoken( workingstring); } workingstring = sfsempty(); pmode.comment = true; return inputstr; } else if( nextchar_a == a__semicolon ) { if( sfslen( workingstring ) ) { printf( "unknown token: %s.\n", workingstring ); // big error here return inputstr; } else { append_prim( P, a_exit ); if( flowtop ) { printf( "unexpected end of word\n" ); // more big error here } else { sfs wordname = atomtostring( P->current_codestream->nameatom ); size_t icount = P->current_codestream->instructioncount; size_t vcount = P->current_codestream->vars->count; printf( "word added: %s, codestream size: %zu, variables: %zu.\n", wordname , icount, vcount ); if( vcount ) { sfs vlist = sfsnew( "variable list: " ); for( size_t i = 0; i < vcount; i++ ) { if( i> 0 ) { vlist = sfscatc(vlist, ", " ); } vlist = sfscatsfs(vlist, atomtostring(P->current_codestream->vars->vars[i].name)); } printf( "%s\n", vlist); } pmode.compile = false; popcallstackframe(P); } sglib_hashed_iListType_init( P->compilestate->vartable ); } } else { workingstring = sfscatc( workingstring, nextchar ); } } return inputstr; } sfs parse_comment(proc *P, sfs inputstr ) { sfs workingstring = sfsempty(); sfs nextchar = sfsempty(); while ( sfslen( inputstr ) ) { nextchar = sfsnewlen( inputstr, 1 ); inputstr = sfsright( inputstr, sfslen( inputstr) - 1 ); size_t nextchar_a = verifyatom( nextchar ); if( nextchar_a == a__parenr ) { pmode.comment = false; return inputstr; } else { continue_str; } } return inputstr; } void define_newword( proc *P, sfs inputstr ) { if( sfscmp( inputstr, sfsnew( ":" ) ) || sfscmp( inputstr, sfsnew( ";" ) ) || sfscmp( inputstr, sfsnew( "@" ) ) || sfscmp( inputstr, sfsnew( "!" ) ) || sfscmp( inputstr, sfsnew( "var" ) ) ) { // big error here invocation. } size_t wordname = newatom( inputstr ); if( wordname ) { pushcallstackframe(P); P->current_codestream=newcodeset( P->node, 1024, wordname ); printf( "compiling new word: %s.\n", atomtostring(wordname) ); } } sfs parse_newword(proc *P, sfs inputstr ) { sfs workingstring = sfsempty(); sfs nextchar = sfsempty(); while ( sfslen( inputstr ) ) { nextchar = sfsnewlen( inputstr, 1 ); inputstr = sfsright( inputstr, sfslen( inputstr) - 1 ); size_t nextchar_a = verifyatom( nextchar ); if( nextchar_a == a__parenl || nextchar_a == a__space ) { if( sfslen( workingstring ) > 0 && sfscmp( workingstring, sfsnew( " " ) ) ) { define_newword( P, workingstring ); } if(nextchar_a == a__parenl ) { pmode.comment = true; } return inputstr; } else { continue_str; } } return inputstr; } void parse_line( proc *P, sfs input ) { sfs s_space = sfsnew( " " ); input = sfstrim( sfstrim( input, s_space ), "\n" ); sfs workingstring = sfscatc( input, s_space ); while( sfslen( workingstring) > 0 && errorstate == 0 ) { if( pmode.comment ) { workingstring = parse_comment( P, workingstring ); } else if ( pmode.atom ) { workingstring = parse_atom( P, workingstring ); } else if ( pmode.directive ) { // workingstring = parse_directive( workingstring ); } else if ( pmode.string ) { workingstring = parse_string( P, workingstring ); } else if ( pmode.compile ) { if ( P->current_codestream->nameatom == 0 ) { workingstring = parse_newword( P, workingstring ); } else { workingstring = parse_compile( P, workingstring ); } } else { workingstring = parse_immed( P, workingstring ); } } }
esotericist/frf
src/main/frf.c
<filename>src/main/frf.c #include <gc.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <uv.h> #include "frf.h" #include "datatypes.h" #include "atoms.h" #include "compile.h" #include "prims.h" #include "stack.h" #include "events.h" #include "vm.h" atom(exit) sfs readfile( proc *P ) { sfs to_return = sfsempty(); char buffer[BUFSIZ]; getcwd(buffer, BUFSIZ); sfs filepath = sfscatsfs( sfsnew(buffer), sfsnew( "/tests/ipctest.frf" ) ); FILE *thefile; thefile = fopen( filepath, "r" ); while( fgets( buffer, BUFSIZ, thefile ) != NULL && P->errorstate == 0 ) { to_return = sfsnew( buffer ); parse_line( P, to_return); } fclose(thefile); return to_return; } extern sfs numstring; extern sfs opstring; struct node_state *N; void frf_initialization() { GC_INIT(); atoms_init(); numstring = sfsnew( "0123456789" ); opstring = sfsnew( "-$%" ); events_initialization(); } void frf_teardown() { events_teardown(); } void node_bootstrap() { N = newnode(); finalizeprims( N ); proc *P = newprocess( N ); newcompilestate( P ); P->current_codestream = newcodeset(N, 1024, 0 ); sfs input = readfile( P ); sfstolower ( input ); } void node_run() { while( N->processlist_active || N->processlist_inactive ) { uv_run(uvloop, UV_RUN_DEFAULT); scheduler(N); } } int main(int argc, char **argv) { frf_initialization(); node_bootstrap(); node_run(); frf_teardown(); return 0; }
esotericist/frf
src/main/datatypes.c
<gh_stars>1-10 #include "datatypes.h" #include "vm.h" #include "atoms.h" SGLIB_DEFINE_LIST_FUNCTIONS(qListType, QLIST_COMPARATOR, next_ptr) SGLIB_DEFINE_SORTED_LIST_FUNCTIONS(iListType, ILIST_COMPARATOR, next_ptr) SGLIB_DEFINE_HASHED_CONTAINER_FUNCTIONS(iListType, ilist_hash_size, ilist_hash_function ) SGLIB_DEFINE_SORTED_LIST_FUNCTIONS(sListType, SLIST_COMPARATOR, next_ptr) SGLIB_DEFINE_HASHED_CONTAINER_FUNCTIONS(sListType, slist_hash_size, slist_hash_function ) struct qlist* alloc_qlist() { return GC_malloc( sizeof( struct qlist )); } struct ilist* alloc_ilist() { return GC_malloc( sizeof( struct ilist )); } struct ilist* swap_ilist( struct ilist* old ) { struct ilist *new = alloc_ilist(); new->first.a_val = old->second.a_val; new->second.a_val = old->first.a_val; return new; } struct slist* alloc_slist() { return GC_malloc( sizeof( struct slist )); } // pulled from https://stackoverflow.com/a/12996028 // in turn apparently derived from https://xorshift.di.unimi.it/splitmix64.c uint64_t hash64(uint64_t x) { x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9); x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb); x = x ^ (x >> 31); return x; } unsigned int ilist_comp_function(iListType *e1, iListType *e2 ) { return ( e1->first.a_val - e2->first.a_val ); } unsigned int ilist_hash_function(iListType *e) { return hash64 ( e->first.a_val ); } unsigned int slist_hash_function(sListType *e) { // cribbed from http://www.cse.yorku.ca/~oz/hash.html int c; unsigned long hash = 5381; size_t len = sfslen( e->s ); sfs str = e->s; for( int i = 0; i < len; i++ ) { c = str[i]; hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } return hash; } sListType* slist_find( sListType **tbl, sfs key ) { sListType *elem = alloc_slist(); elem->s = key; sListType *found = sglib_hashed_sListType_find_member( tbl, elem ); return found; } struct code_set* newcodeset ( struct node_state *N, size_t size, size_t wordatom ) { struct code_set *new_cs = GC_malloc( sizeof( struct code_set ) + sizeof ( struct code_point ) * (size) ); new_cs->length = size; if( wordatom ) { new_cs->nameatom = wordatom; registerword( N, wordatom, new_cs ); new_cs->vars = new_varset(); } return new_cs; } struct variable_set* new_varset() { return GC_malloc( sizeof (size_t) + sizeof ( struct variable_entry ) ); } struct variable_set* grow_variable_set(struct variable_set *vs) { struct variable_set *new_vs = GC_malloc( sizeof (size_t) + sizeof ( struct variable_entry ) * (vs->count + 2) ); for(size_t i = 0; i <= vs->count ; i++ ) { new_vs->vars[i].name = vs->vars[i].name; new_vs->vars[i].dp.u_val = vs->vars[i].dp.u_val; } new_vs->count = vs->count +1; return new_vs; } void append_cp( proc *P, size_t v ) { if( P->current_codestream->instructioncount > P->current_codestream->length - 10) { size_t size = P->current_codestream->length + 1024; P->current_codestream = GC_realloc( P->current_codestream , sizeof( struct code_set ) + sizeof ( struct code_point ) * (size) ); P->current_codestream->length = size; } P->current_codestream->codestream[P->current_codestream->instructioncount++].u_val = v; } void newcompilestate( proc *P ) { P->compilestate = GC_malloc( sizeof( struct compile_state ) ); P->compilestate->parsemode.flags = 0; sglib_hashed_iListType_init( P->compilestate->vartable ); }
esotericist/frf
src/main/prims.c
<gh_stars>1-10 #include <stdlib.h> #include "prims.h" #include "stack.h" #include "vm.h" // #region prim registration void preregisterprim(void *thefunc, char *s) { preprims = realloc(preprims, sizeof(struct preprim) * (numpreprims + 1)); preprims[numpreprims].thefunc = thefunc; preprims[numpreprims].prim = s; numpreprims++; } extern sListType *atom_table[slist_hash_size]; void finalizeprims(struct node_state *N) { for (int i = 0; i < numpreprims; i++) { uintptr_t new_prim_ptr = (uintptr_t)(void *)preprims[i].thefunc; sfs primname = sfstrim(sfsnew(preprims[i].prim), " "); size_t new_atom_val = stringtoatom(primname); iListType *new_prim_entry = alloc_ilist(); iListType *new_atom_entry = alloc_ilist(); new_prim_entry->first.p_val = new_prim_ptr; new_prim_entry->second.a_val = new_atom_val; sglib_hashed_iListType_add(N->primtoatomtable, new_prim_entry); new_atom_entry->first.a_val = new_atom_val; new_atom_entry->second.p_val = new_prim_ptr; sglib_hashed_iListType_add(N->atomtoprimtable, new_atom_entry); } } // #endregion #pragma GCC push_options #pragma GCC optimize("align-functions=16") // #region raw value prims prim(push_int) { size_t pos = P->currentop++; struct code_point *cp = &P->current_codestream->codestream[pos]; push_int( cp_get_int(cp)); } prim(push_atom) { size_t pos = P->currentop++; push_atom( cp_get_atom(&P->current_codestream->codestream[pos])); } prim(push_string) { size_t pos = P->currentop++; push_string( cp_get_string(&P->current_codestream->codestream[pos])); } prim(push_var) { size_t pos = P->currentop++; push_var( cp_get_int(&P->current_codestream->codestream[pos]) ); } prim2(push_stackmark, { ) { push_mark } prim2(stackrange, } ) { size_t range, pos; for(size_t i = dcount -1; i >= 0; i-- ) { if(dp_is_mark( dstack[i])) { pos = i; break; } } for(size_t i = pos; i < dcount -1; i++ ) { dstack[i] = dstack[i+1]; } dcount--; range = dcount - pos; push_int(range); } prim2( store_var, ! ) { require_var v = pop_var; if( v >= 0 ) { needstack(1) struct datapoint d = pop_dp(P); P->current_varset->vars[v].dp.u_val = d.u_val; } else { runtimefault( "error in %zu: invalid variable" ) } } prim2( fetch_var, @ ) { require_var v = pop_var; if( v >= 0 ) { push_dp(P, P->current_varset->vars[v].dp ); } else { runtimefault( "error in %zu: invalid variable" ) } } prim2(checkisint, int? ) { bool t = dp_is_int( topdp ); push_bool( t ); } // todo: add floats prim2(checkisnum, number? ) { bool t = dp_is_int( topdp ); push_bool( t ); } prim2(checkisstr, string? ) { bool t = dp_is_string( topdp ); push_bool( t ); } prim2(checkisatom, atom? ) { bool t = dp_is_atom( topdp ); push_bool( t ); } prim2(checkisarray, array?) { bool t = dp_is_array( topdp ); push_bool( t ); } prim2(checkistuple, tuple?) { bool t = dp_is_tuple( topdp ); push_bool( t ); } // #endregion // #region stackprims prim(dup) { needstack(1) push_dp(P, topdp); } prim(over) { needstack(2) push_dp(P, dstack[dcount - 2]); } prim(pick) { require_int count = pop_int; if (count < 1) { stackfault(a_expected_positive_integer) } needstack(count) push_dp(P, dstack[dcount - count]); } prim(depth) { int64_t v = P->d->top; push_int( v ); } prim(swap) { needstack(2) struct datapoint second = (pop_dp(P)); struct datapoint first = (pop_dp(P)); push_dp(P, second); push_dp(P, first); } void rotate(proc *P, int64_t count) { if (count < 0) { count = -count; needstack(count) struct datapoint top = dstack[dcount - 1]; for (size_t i = 0; i < count; i++) { dstack[dcount - i] = dstack[dcount - i - 1]; } dstack[dcount - count] = top; } else { needstack(count) struct datapoint bottom = dstack[dcount - count]; for (size_t i = count - 1; i > 0; i--) { dstack[dcount - i - 1] = dstack[dcount - i]; } dstack[dcount - 1] = bottom; } } prim(rotate) { require_int count = pop_int; rotate(P, count); } prim(rot) { rotate(P, 3); } prim(pop) { needstack(1) pop_dp(P); } prim(popn) { require_int count = pop_int; needstack(count) if (count >= 0) { for (size_t i = 0; i < count; i++) { pop_dp(P); } } } prim(dupn) { require_int count = pop_int; size_t offset = dcount - count; needstack(count) if( count >= 0) { for (size_t i = 0; i < count; i++) { push_dp(P, dstack[offset + i]); } } } prim(nip) { p_swap(P); pop_dp(P); } prim(tuck) { p_dup(P); rotate(P, -3); } prim(put) { require_int count = pop_int; needstack(count) rotate(P, - (count + 1)); rotate(P, count); pop_dp(P); } // #endregion // #region flow control prims // unconditional jump primarily used by the compiler // pulls its address from the next cell prim(jmp) { size_t pos = P->currentop++; struct code_point *cp = &P->current_codestream->codestream[pos]; P->currentop = cp_get_int(cp); } // conditional jump, primarly used by the compiler // uses the top entry of the stack for truth, pulls its address from the next cell prim(cjmp) { size_t pos = P->currentop++; require_bool val = pop_bool; if (!val) { struct code_point *cp = &P->current_codestream->codestream[pos]; P->currentop = cp_get_int(cp); } } prim(continue) { P->currentop = cp_get_int(&P->current_codestream->codestream[P->currentop]); } prim(break) { P->currentop = cp_get_int(&P->current_codestream->codestream[P->currentop]); } prim(while) { if (pop_bool) { P->currentop++; } else { P->currentop = P->current_codestream->codestream[P->currentop].u_val; } } prim(call) { struct code_set *targetword = (void *)(uintptr_t)P->current_codestream->codestream[P->currentop].p_val; P->currentop++; pushcallstackframe(P); if (!P->errorstate) { P->current_codestream = targetword; P->current_varset = grow_variable_set( targetword->vars ); P->current_varset->count--; P->currentop = 0; } } prim(exit) { popcallstackframe(P); } prim(pid) { push_int(P->pid) } atom(killed) prim(kill) { require_int i1 = pop_int; iListType *tmp= alloc_ilist(); tmp->first.a_val = i1; if( i1 > 0 ) { tmp = sglib_hashed_iListType_find_member( P->node->process_table, tmp ); if( tmp ) { push_int(1); process_kill( (proc *)(uintptr_t) tmp->second.p_val, a_killed, sfsempty() ); } else { push_int(0); } } } prim(fork) { proc *new_P = newprocess( P->node ); new_P->current_codestream = P->current_codestream; new_P->currentop = P->currentop; if( P->current_varset ) { new_P->current_varset = grow_variable_set(P->current_varset); new_P->current_varset->count--; } new_P->debugmode = P->debugmode; new_P->max_slice_ops = P->max_slice_ops; for( size_t i = 0; i < P->d->top ; i++ ) { push_dp(new_P, P->d->stack[i] ); } for( size_t i = 0; i < P->c->top ; i++ ) { copyframe( &P->c->stack[i] , &new_P->c->stack[i] ); } push_int(new_P->pid); P = new_P; push_int(0); } // #endregion // #region math prims prim2(add, +) { require_int second = pop_int; require_int first = pop_int; push_int( first + second ); } prim2(minus, -) { require_int second = pop_int; require_int first = pop_int; push_int( first - second ); } prim2(mult, *) { require_int second = pop_int; require_int first = pop_int; push_int( first * second ); } prim2(div, /) { require_int second = pop_int; require_int first = pop_int; push_int( first / second ); } prim2(modulo, %) { require_int second = pop_int; require_int first = pop_int; push_int( first % second ); } // #endregion // #region logic prims prim2(isequalto, =) { require_int second = pop_int; require_int first = pop_int; push_bool( first == second ); } prim2(isnotsequalto, !=) { require_int second = pop_int; require_int first = pop_int; push_bool( first != second ); } prim2(isgreaterthan, >) { require_int second = pop_int; require_int first = pop_int; push_bool( first > second ); } prim2(islessthan, <) { require_int second = pop_int; require_int first = pop_int; push_bool( first < second ); } prim2(isgreaterorequal, >=) { require_int second = pop_int; require_int first = pop_int; push_bool( first >= second ); } prim2(islesserorequal, <=) { require_int second = pop_int; require_int first = pop_int; push_bool( first <= second ); } prim(not ) { needstack(1) push_bool( !pop_bool ); } prim(or) { require_bool second = pop_bool; require_bool first = pop_bool; push_bool( first || second ); } prim(and) { require_bool second = pop_bool; require_bool first = pop_bool; push_bool( first && second ); } // #endregion // #region string prims prim(strlen) { require_string s = pop_string; push_int( sfslen(s) ); } prim(strcat) { require_string s2 = pop_string; require_string s1 = pop_string; push_string( sfscatsfs(s1, s2) ); } prim(strcmp) { require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfscmp(s1, s2) ); } // MUF called this 'strncmp', but renaming it to match 'popn' prim(strcmpn) { require_int len = pop_int; require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfscmp(sfsnewlen(s1, len), sfsnewlen(s2, len)) ); } // MUF used 'stringcmp', but that's terrible notation, and i think it should be like 'strcmpn' prim(strcmpi) { require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfscmp(sfstolower(s1), sfstolower(s2)) ); } prim(stringpfx) { require_string s2 = pop_string; require_string s1 = pop_string; push_bool( sfscmp(sfsnewlen(s1, sfslen(s2)), s2) == 0 ); } prim(strcut) { require_int index = pop_int; require_string str = pop_string; size_t len = sfslen(str); if (index < 0) { index = 0; } if (index > len) { index = len; } push_string( sfsnewlen(str, index)); push_string( sfsright(str, len - index)); } prim(midstr) { require_int i2 = pop_int; require_int i1 = pop_int - 1; require_string s = pop_string; size_t len = sfslen(s); if(i1 < 0 ) { i1 = 0; } if(i2 > len) { i2 = len; } push_string( sfsrange( s, i1, i1 + i2 - 1 )); } prim(instr) { require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfsinstr( s1, s2, false ) ); } // case insensitive instr (was 'instring' in muf) prim(instri) { require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfsinstr( sfstolower(s1), sfstolower(s2), false ) ); } // reverse instr prim(rinstr) { require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfsinstr( s1, s2, true ) ); } // case insensitive rinstr (was 'rinstring' in muf) prim(rinstri) { require_string s2 = pop_string; require_string s1 = pop_string; push_int( sfsinstr( sfstolower(s1), sfstolower(s2), true ) ); } prim(explode) { require_string s2 = pop_string; require_string s1 = pop_string; size_t count; sfs *strings = sfssplit( s1, s2, &count ); for( size_t i = count; i > 0; --i ) { push_string( strings[i-1]); } push_int( count); } prim(split) { require_string s2 = pop_string; require_string s1 = pop_string; size_t index = sfsinstr( s1, s2, false ); if( index ) { push_string( sfsnewlen( s1, index -1 )); push_string( sfsright( s1, sfslen(s1) - index )); } else { push_string( s1); push_string( sfsempty()); } } prim(rsplit) { require_string s2 = pop_string; require_string s1 = pop_string; size_t index = sfsinstr( s1, s2, true ); if( index ) { push_string( sfsnewlen( s1, index -1 )); push_string( sfsright( s1, sfslen(s1) - index )); } else { push_string( s1); push_string( sfsempty()); } } prim(tolower) { require_string s = pop_string; push_string( sfstolower(s)); } prim(toupper) { require_string s = pop_string; push_string( sfstoupper(s)); } prim(subst) { require_string s3 = pop_string; require_string s2 = pop_string; require_string s1 = pop_string; push_string( sfssubst( s1, s3, s2 )); } // #endregion // #region conversion prims prim(intostr) { require_int num = pop_int; push_string( sfsfromlonglong(num)); } prim(ctoi) { require_string str = pop_string; push_int( str[0]); } // #endregion // #region debugging prim(debug_on) { P->debugmode = true; } prim(debug_off) { P->debugmode = false; } prim(debug_line) { printf("%s\n", dump_stack(P)); } // #endregion
plaes/envytools
nva/nvaevo.c
/* * Copyright 2011 Red Hat Inc. * 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 (including the next * paragraph) 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. * * Authors: <NAME> */ #include "nva.h" #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { if (nva_init()) { fprintf (stderr, "PCI init failure!\n"); return 1; } int c; int cnum =0; while ((c = getopt (argc, argv, "c:")) != -1) switch (c) { case 'c': sscanf(optarg, "%d", &cnum); break; } if (cnum >= nva_cardsnum) { if (nva_cardsnum) fprintf (stderr, "No such card.\n"); else fprintf (stderr, "No cards found.\n"); return 1; } uint32_t m, d, ctrl; if (optind + 3 > argc) { fprintf (stderr, "%s: <channel> <method> <data>\n", argv[0]); return 1; } sscanf (argv[optind + 0], "%d", &c); sscanf (argv[optind + 1], "%x", &m); sscanf (argv[optind + 2], "%x", &d); if (nva_cards[cnum].chipset.chipset >= 0xd0) { ctrl = nva_rd32(cnum, 0x610700 + (c * 8)); nva_wr32(cnum, 0x610700 + (c * 8), ctrl | 1); nva_wr32(cnum, 0x610704 + (c * 8), d); nva_wr32(cnum, 0x610700 + (c * 8), 0x80000001 | m); while (nva_rd32(cnum, 0x610700 + (c * 8)) & 0x80000000); nva_wr32(cnum, 0x610700 + (c * 8), ctrl); } else if (nva_cards[cnum].chipset.chipset == 0x50 || nva_cards[cnum].chipset.chipset >= 0x84) { ctrl = nva_rd32(cnum, 0x610300 + (c * 8)); nva_wr32(cnum, 0x610300 + (c * 8), ctrl | 1); nva_wr32(cnum, 0x610304 + (c * 8), d); nva_wr32(cnum, 0x610300 + (c * 8), 0x80000001 | m); while (nva_rd32(cnum, 0x610300 + (c * 8)) & 0x80000000); nva_wr32(cnum, 0x610300 + (c * 8), ctrl); } else { fprintf (stderr, "unsupported chipset\n"); return 1; } return 0; }
plaes/envytools
include/rnn.h
/* * Copyright (C) 2010 <NAME> <<EMAIL>> * Copyright (C) 2010 <NAME> <<EMAIL>> * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef RNN_H #define RNN_H #include <stdint.h> #include <stdlib.h> struct rnnauthor { char* name; char* email; char* contributions; char* license; char** nicknames; int nicknamesnum; int nicknamesmax; }; struct rnncopyright { unsigned firstyear; char* license; struct rnnauthor **authors; int authorsnum; int authorsmax; }; struct rnndb { struct rnncopyright copyright; struct rnnenum **enums; int enumsnum; int enumsmax; struct rnnbitset **bitsets; int bitsetsnum; int bitsetsmax; struct rnndomain **domains; int domainsnum; int domainsmax; struct rnngroup **groups; int groupsnum; int groupsmax; struct rnnspectype **spectypes; int spectypesnum; int spectypesmax; char **files; int filesnum; int filesmax; int estatus; }; struct rnnvarset { struct rnnenum *venum; int *variants; }; struct rnnvarinfo { char *prefixstr; char *varsetstr; char *variantsstr; int dead; struct rnnenum *prefenum; char *prefix; struct rnnvarset **varsets; int varsetsnum; int varsetsmax; }; struct rnnenum { char *name; int bare; int isinline; struct rnnvarinfo varinfo; struct rnnvalue **vals; int valsnum; int valsmax; char *fullname; int prepared; char *file; }; struct rnnvalue { char *name; int valvalid; uint64_t value; struct rnnvarinfo varinfo; char *fullname; char *file; }; struct rnntypeinfo { char *name; enum rnnttype { RNN_TTYPE_INLINE_ENUM, RNN_TTYPE_INLINE_BITSET, RNN_TTYPE_ENUM, RNN_TTYPE_BITSET, RNN_TTYPE_SPECTYPE, RNN_TTYPE_HEX, RNN_TTYPE_INT, RNN_TTYPE_UINT, RNN_TTYPE_FLOAT, RNN_TTYPE_BOOLEAN, RNN_TTYPE_FIXED, RNN_TTYPE_UFIXED, RNN_TTYPE_A3XX_REGID, } type; struct rnnenum *eenum; struct rnnbitset *ebitset; struct rnnspectype *spectype; struct rnnbitfield **bitfields; int bitfieldsnum; int bitfieldsmax; struct rnnvalue **vals; int valsnum; int valsmax; int shr; uint64_t min, max, align, radix; int minvalid, maxvalid, alignvalid, radixvalid; }; struct rnnbitset { char *name; int bare; int isinline; struct rnnvarinfo varinfo; struct rnnbitfield **bitfields; int bitfieldsnum; int bitfieldsmax; char *fullname; char *file; }; struct rnnbitfield { char *name; int low, high; uint64_t mask; struct rnnvarinfo varinfo; struct rnntypeinfo typeinfo; char *fullname; char *file; }; struct rnndomain { char *name; int bare; int width; uint64_t size; int sizevalid; struct rnnvarinfo varinfo; struct rnndelem **subelems; int subelemsnum; int subelemsmax; char *fullname; char *file; }; struct rnngroup { char *name; struct rnndelem **subelems; int subelemsnum; int subelemsmax; }; struct rnndelem { enum rnnetype { RNN_ETYPE_REG, RNN_ETYPE_ARRAY, RNN_ETYPE_STRIPE, RNN_ETYPE_USE_GROUP, } type; char *name; int width; enum rnnaccess { RNN_ACCESS_R, RNN_ACCESS_W, RNN_ACCESS_RW, } access; uint64_t offset; uint64_t *offsets; /* for "array" with irregular offsets */ int offsetsnum; int offsetsmax; uint64_t length; uint64_t stride; struct rnndelem **subelems; int subelemsnum; int subelemsmax; struct rnnvarinfo varinfo; struct rnntypeinfo typeinfo; struct rnnenum *index; /* for arrays, for symbolic idx values */ char *fullname; char *file; }; struct rnnspectype { char *name; struct rnntypeinfo typeinfo; char *file; }; void rnn_init(); struct rnndb *rnn_newdb(); void rnn_parsefile (struct rnndb *db, char *file); void rnn_prepdb (struct rnndb *db); struct rnnenum *rnn_findenum (struct rnndb *db, const char *name); struct rnnbitset *rnn_findbitset (struct rnndb *db, const char *name); struct rnndomain *rnn_finddomain (struct rnndb *db, const char *name); struct rnnspectype *rnn_findspectype (struct rnndb *db, const char *name); #endif
plaes/envytools
nva/nvapoke.c
/* * Copyright (C) 2010-2011 <NAME> <<EMAIL>> * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "nva.h" #include <stdio.h> #include <unistd.h> #include <inttypes.h> int main(int argc, char **argv) { if (nva_init()) { fprintf (stderr, "PCI init failure!\n"); return 1; } int c; struct nva_regspace rs = { 0 }; while ((c = getopt (argc, argv, "c:i:b:t:")) != -1) switch (c) { case 'c': sscanf(optarg, "%d", &rs.cnum); break; case 'i': sscanf(optarg, "%d", &rs.idx); break; case 'b': sscanf(optarg, "%d", &rs.regsz); if (rs.regsz != 1 && rs.regsz != 2 && rs.regsz != 4 && rs.regsz != 8) { fprintf (stderr, "Invalid size.\n"); return 1; } break; case 't': rs.type = nva_rstype(optarg); if (rs.type == NVA_REGSPACE_UNKNOWN) { fprintf (stderr, "Unknown register space.\n"); return 1; } break; } if (rs.cnum >= nva_cardsnum) { if (nva_cardsnum) fprintf (stderr, "No such card.\n"); else fprintf (stderr, "No cards found.\n"); return 1; } rs.card = &nva_cards[rs.cnum]; if (rs.regsz == 0) rs.regsz = nva_rsdefsz(&rs); uint32_t a, b = rs.regsz; uint64_t val, step = 0; if (optind >= argc) { fprintf (stderr, "No address specified.\n"); return 1; } sscanf (argv[optind], "%x", &a); if (optind + 1 >= argc) { fprintf (stderr, "No value specified.\n"); return 1; } if (optind + 2 >= argc) { sscanf (argv[optind + 1], "%"SCNx64, &val); } else { sscanf (argv[optind + 1], "%x", &b); sscanf (argv[optind + 2], "%"SCNx64, &val); } if (optind + 3 < argc) sscanf (argv[optind + 3], "%"SCNx64, &step); while (b > 0) { int e = nva_wr(&rs, a, val); if (e) printf("%08x: ERR %c\n", a, nva_rserrc(e)); a += rs.regsz; b -= rs.regsz; val += step; } return 0; }
plaes/envytools
rnn/dedma_back.c
/* * Copyright (C) 2010 <NAME>. * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "dedma.h" void parse_renouveau_chipset(struct state *s, char *path) { char *buf = NULL; uint32_t val; FILE *f; asprintf(&buf, "%s/card_stdout.txt", path); f = fopen(buf, "r"); if (!f) { fprintf(stderr, "Couldn't open %s: %s\n", buf, strerror(errno)); goto out; } while (getline(&s->parse.buf, &s->parse.n, f) >= 0) { if (sscanf(s->parse.buf, "BOOT0\t%x", &val) == 1) { s->chipset = (val & 0x0f000000 ? (val >> 20) & 0xff : val & 0x0000f000 ? ((val >> 20) & 0xf) + 4 : (val >> 16) & 0xf); } else if (sscanf(s->parse.buf, "pci_id\t%x", &val) == 1) { s->pci_id = val; } } fclose(f); out: free(buf); } void parse_renouveau_objects(struct state *s, char *path) { char *buf = NULL; uint32_t handle, ent; FILE *f; asprintf(&buf, "%s/card_objects.txt", path); f = fopen(buf, "r"); if (!f) { fprintf(stderr, "Couldn't open %s: %s\n", buf, strerror(errno)); goto out; } while (getline(&s->parse.buf, &s->parse.n, f) >= 0) { if (sscanf(s->parse.buf, "%x %*x %x", &handle, &ent) == 2) add_object(s, handle, (s->chipset >= 0x40 ? ent & 0xffff : ent & 0xfff)); } fclose(f); out: free(buf); } void parse_renouveau_startup(struct state *s, char *path) { char *buf = NULL; FILE *f; asprintf(&buf, "%s/card_%04x-%04x_test_startup.txt", path, s->pci_id >> 16, s->pci_id & 0xffff); f = fopen(buf, "r"); if (!f) { fprintf(stderr, "Couldn't open %s: %s\n", buf, strerror(errno)); goto out; } dedma(s, f, true); fclose(f); out: free(buf); } bool parse_renouveau(struct state *s) { struct ent e = { .addr = s->parse.addr }; int ret; for (;;) { if (getline(&s->parse.buf, &s->parse.n, s->f) < 0) return false; ret = sscanf(s->parse.buf, "%x", &e.val); if (ret == 1) break; } add_ent(s, &e); s->parse.addr += 4; return true; } bool parse_valgrind(struct state *s) { struct ent e = {}; unsigned m, addr, val[4]; char c[3] = {}; int i; for (;;) { if (getline(&s->parse.buf, &s->parse.n, s->f) < 0) return false; i = sscanf(s->parse.buf, "--%*d-- w %d:%x, %x%c%x%c%x%c%x", &m, &addr, &val[0], &c[0], &val[1], &c[1], &val[2], &c[2], &val[3]); if(i==6){ //reorder words (2,1) => (1,2) unsigned x = val[0]; val[0] = val[1]; val[1] = x; } else if(i==9){ //reorder words (4,3,2,1) => (1,2,3,4) unsigned x = val[0]; val[0] = val[3]; val[3] = x; x = val[1]; val[1] = val[2]; val[2] = x; } if (i >= 4 && m == s->filter.map) break; i = sscanf(s->parse.buf, "--%*d-- create gpu object" " 0x%*x:0x%x type 0x%x", &val[0], &val[1]); if (i == 2) add_object(s, val[0], val[1]); } for (i = 0; i <= 3 && (i == 0 || c[i - 1] == ','); i++) { e.addr = addr; e.val = val[i]; add_ent(s, &e); addr += 4; } return true; }
plaes/envytools
include/nva.h
/* * Copyright (C) 2010-2011 <NAME> <<EMAIL>> * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NVA_H #define NVA_H #include <stdint.h> #include <stddef.h> #include "nvhw.h" struct nva_card { struct pci_device *pci; struct chipset_info chipset; void *bar0; size_t bar0len; int hasbar1; void *bar1; size_t bar1len; int hasbar2; void *bar2; size_t bar2len; }; int nva_init(); extern struct nva_card *nva_cards; extern int nva_cardsnum; static inline uint32_t nva_grd32(void *base, uint32_t addr) { return *((volatile uint32_t*)(((volatile uint8_t *)base) + addr)); } static inline void nva_gwr32(void *base, uint32_t addr, uint32_t val) { *((volatile uint32_t*)(((volatile uint8_t *)base) + addr)) = val; } static inline uint32_t nva_grd8(void *base, uint32_t addr) { return *(((volatile uint8_t *)base) + addr); } static inline void nva_gwr8(void *base, uint32_t addr, uint32_t val) { *(((volatile uint8_t *)base) + addr) = val; } static inline uint32_t nva_rd32(int card, uint32_t addr) { return nva_grd32(nva_cards[card].bar0, addr); } static inline void nva_wr32(int card, uint32_t addr, uint32_t val) { nva_gwr32(nva_cards[card].bar0, addr, val); } static inline uint32_t nva_rd8(int card, uint32_t addr) { return nva_grd8(nva_cards[card].bar0, addr); } static inline void nva_wr8(int card, uint32_t addr, uint32_t val) { nva_gwr8(nva_cards[card].bar0, addr, val); } static inline uint32_t nva_mask(int cnum, uint32_t reg, uint32_t mask, uint32_t val) { uint32_t tmp = nva_rd32(cnum, reg); nva_wr32(cnum, reg, (tmp & ~mask) | val); return tmp; } struct nva_regspace { struct nva_card *card; int cnum; enum { NVA_REGSPACE_BAR0, NVA_REGSPACE_BAR1, NVA_REGSPACE_BAR2, NVA_REGSPACE_PDAC, NVA_REGSPACE_EEPROM, NVA_REGSPACE_VGA_CR, NVA_REGSPACE_VGA_SR, NVA_REGSPACE_VGA_AR, NVA_REGSPACE_VGA_GR, NVA_REGSPACE_VGA_ST, NVA_REGSPACE_PIPE, NVA_REGSPACE_RDI, NVA_REGSPACE_VCOMP_CODE, NVA_REGSPACE_VCOMP_REG, NVA_REGSPACE_MACRO_CODE, NVA_REGSPACE_XT, NVA_REGSPACE_UNKNOWN, } type; int regsz; int idx; }; int nva_wr(struct nva_regspace *regspace, uint32_t addr, uint64_t val); int nva_rd(struct nva_regspace *regspace, uint32_t addr, uint64_t *val); enum nva_err { NVA_ERR_SUCCESS, NVA_ERR_RANGE, NVA_ERR_REGSZ, NVA_ERR_NOSPC, NVA_ERR_MAP, }; int nva_rstype(const char *name); int nva_rsdefsz(struct nva_regspace *regspace); char nva_rserrc(enum nva_err err); void nva_rsprint(struct nva_regspace *regspace, enum nva_err err, uint64_t val); #endif
plaes/envytools
nva/nvapms.c
<filename>nva/nvapms.c /* * Copyright (C) 2011 <NAME> <<EMAIL>> * Copyright (C) 2012 <NAME> <<EMAIL>> * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "nva.h" #include <stdio.h> #include <unistd.h> #include <sys/time.h> typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; #if defined(_MSC_VER) || defined(__BORLANDC__) typedef unsigned __int64 u64; #else typedef unsigned long long u64; #endif typedef u64 ptime_t; #include "nouveau_pms.h" #define NV04_PTIMER_TIME_0 0x00009400 #define NV04_PTIMER_TIME_1 0x00009410 #define NV04_PTIMER_CLOCK_DIV 0x00009200 ptime_t time_diff_us(struct timeval start, struct timeval end) { return ((end.tv_sec) - (start.tv_sec))*1000000 + ((end.tv_usec) - (start.tv_usec)); } ptime_t get_time(unsigned int card) { ptime_t low; /* From kmmio dumps on nv28 this looks like how the blob does this. * It reads the high dword twice, before and after. * The only explanation seems to be that the 64-bit timer counter * advances between high and low dword reads and may corrupt the * result. Not confirmed. */ ptime_t high2 = nva_rd32(card, NV04_PTIMER_TIME_1); ptime_t high1; do { high1 = high2; low = nva_rd32(card, NV04_PTIMER_TIME_0); high2 = nva_rd32(card, NV04_PTIMER_TIME_1); } while (high1 != high2); return ((((ptime_t)high2) << 32) | (ptime_t)low); } static ptime_t pms_launch(int cnum, struct pms_ucode* pms, ptime_t *wall_time) { u32 pbus1098; u32 pms_data, pms_kick; ptime_t ptimer_start, ptimer_end; struct timeval wall_start, wall_end; int i; if (nva_cards[cnum].chipset.chipset < 0x90) { pms_data = 0x001400; pms_kick = 0x00000003; } else { pms_data = 0x080000; pms_kick = 0x00000001; } /* upload ucode */ pbus1098 = nva_mask(cnum, 0x001098, 0x00000008, 0x00000000); nva_wr32(cnum, 0x001304, 0x00000000); for (i = 0; i < pms->len / 4; i++) nva_wr32(cnum, pms_data + (i * 4), pms->ptr.u32[i]); nva_wr32(cnum, 0x001098, pbus1098 | 0x18); /* and run it! */ gettimeofday(&wall_start, NULL); ptimer_start = get_time(cnum); nva_wr32(cnum, 0x00130c, pms_kick); /* Wait for completion */ while (nva_rd32(cnum, 0x001308) & 0x100); ptimer_end = get_time(cnum); gettimeofday(&wall_end, NULL); if (wall_time) *wall_time = time_diff_us(wall_start, wall_end); return ptimer_end - ptimer_start - (get_time(cnum) - get_time(cnum)); } void timing_pms_waits(int cnum) { struct pms_ucode _pms, *pms=&_pms; ptime_t exec_time; int instr, i; printf("Timing PMS wait instructions:\n"); /* Slow PTIMER down */ /*ptimer_div = nva_rd32(cnum, NV04_PTIMER_CLOCK_DIV); nva_wr32(cnum, NV04_PTIMER_CLOCK_DIV, ptimer_div * 2);*/ for (instr=0; instr <= 0xf; instr++) { pms_init(pms); for (i = 0; i < 250; i++) pms_unkn(pms, instr); pms_fini(pms); exec_time = pms_launch(cnum, pms, NULL); printf(" Instr. 0x0%x: 0x%Lx PTIMER cycles\n", instr, exec_time/250); } /* Restore PTIMER */ /*nva_wr32(cnum, NV04_PTIMER_CLOCK_DIV, ptimer_div);*/ } int main(int argc, char **argv) { if (nva_init()) { fprintf (stderr, "PCI init failure!\n"); return 1; } int c; int cnum =0; while ((c = getopt (argc, argv, "c:")) != -1) switch (c) { case 'c': sscanf(optarg, "%d", &cnum); break; } if (cnum >= nva_cardsnum) { if (nva_cardsnum) fprintf (stderr, "No such card.\n"); else fprintf (stderr, "No cards found.\n"); return 1; } timing_pms_waits(cnum); return 0; }
plaes/envytools
nva/set_timings.c
/* * Copyright 2011 <NAME> (inspired from <NAME>'s work) * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <X11/Xlib.h> #include "libXNVCtrl/NVCtrl.h" #include "libXNVCtrl/NVCtrlLib.h" #include <sys/types.h> #include <signal.h> #include <stdint.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <sys/mount.h> #include <sys/wait.h> #include <errno.h> #include "nva.h" #include "nvamemtiming.h" #define NOUVEAU_TIME_WAIT 60 int vbios_upload_pramin(int cnum, uint8_t *vbios, int length); enum color { NO_COLOR = 0, COLOR = 1 }; enum value_type { EMPTY, VALUE, BITFIELD }; enum value_type nv40_timing_value_types[] = { VALUE, VALUE, VALUE, VALUE, EMPTY, VALUE, EMPTY, VALUE, EMPTY, VALUE, VALUE, VALUE, VALUE, VALUE, BITFIELD, VALUE, BITFIELD, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE }; enum value_type nvc0_timing_value_types[] = { VALUE, VALUE, VALUE, VALUE, EMPTY, VALUE, EMPTY, VALUE, EMPTY, VALUE, VALUE, VALUE, VALUE, VALUE, BITFIELD, EMPTY, EMPTY, EMPTY, VALUE, VALUE, VALUE, VALUE, EMPTY, EMPTY, VALUE }; enum value_type *timing_value_types = NULL; static int write_to_file(const char *path, const char *data) { FILE *file = fopen(path, "wb"); if (!file) return 1; fputs(data, file); fclose(file); return 0; } static void mmiotrace_start(int entry) { int ret; #ifdef __linux__ ret = mount("debugfs", "/sys/kernel/debug", "debugfs", 0, 0); if (ret) fprintf(stderr, "mounting debugfs returned error %i: %s\n", ret, strerror(ret)); if (write_to_file("/sys/kernel/debug/tracing/buffer_size_kb", "128000")) fprintf(stderr, "Increasing the buffer size returned error %i: %s\n", ret, strerror(ret)); if (write_to_file("/sys/kernel/debug/tracing/current_tracer", "mmiotrace")) fprintf(stderr, "Changing the tracer returned error %i: %s\n", ret, strerror(ret)); if (write_to_file("/sys/kernel/debug/tracing/current_tracer", "mmiotrace")) fprintf(stderr, "Changing the tracer returned error %i: %s\n", ret, strerror(ret)); pid_t pid = fork(); if (pid == 0) { char cmd[101]; snprintf(cmd, 100, "cat /sys/kernel/debug/tracing/trace_pipe > mmt_entry_%i", entry); exit(system(cmd)); } else if (pid < 0) { perror("fork"); } printf("mmiotrace started\n"); #else ret = ENOSYS; fprintf(stderr, "debugfs is not available on this platform %i: %s\n", ret, strerror(ret)); #endif } static void mmiotrace_stop() { #ifdef __linux__ if (write_to_file("/sys/kernel/debug/tracing/current_tracer", "nop")) fprintf(stderr, "Copying the trace to a file failed\n"); printf("mmiotrace stopped\n"); #endif } static int upclock_card(Display *dpy) { unsigned long start_time, get_time; struct timeval tv; int cur_perflvl = -1, tmp; gettimeofday(&tv, NULL); start_time = tv.tv_sec; XNVCTRLQueryTargetAttribute (dpy, NV_CTRL_TARGET_TYPE_X_SCREEN, 0, 0, NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL, &cur_perflvl); pid_t pid = fork(); if (pid == 0) { exit (system("timeout 3 glxgears")); } else if (pid == -1) { fprintf(stderr, "Fork failed! Abort\n"); exit (4); } sleep(1); do { usleep(10000); /* 10 ms */ gettimeofday(&tv, NULL); get_time = tv.tv_sec; XNVCTRLQueryTargetAttribute (dpy, NV_CTRL_TARGET_TYPE_X_SCREEN, 0, 0, NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE, &tmp); } while ( tmp != NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE_MAXPERF && (start_time + 2) < get_time); kill(pid, SIGTERM); waitpid(pid, NULL, 0); return 0; } static int wait_for_perflvl(Display *dpy, uint8_t wanted_perflvl) { unsigned long start_time, get_time; struct timeval tv; int cur_perflvl = -1, tmp; gettimeofday(&tv, NULL); start_time = tv.tv_sec; fprintf(stderr, "XNVCTRLQueryTargetAttribute\n"); XNVCTRLQueryTargetAttribute (dpy, NV_CTRL_TARGET_TYPE_GPU, 0, 0, NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE , &tmp); if (tmp != NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE_ENABLED) { fprintf(stderr, "ERROR - Driver not in Adaptive state\n"); return 1; } do { gettimeofday(&tv, NULL); get_time = tv.tv_sec; if ((start_time + NOUVEAU_TIME_WAIT) < get_time ) { fprintf(stderr, "ERROR - Timeout\n"); return 2; } XNVCTRLQueryTargetAttribute (dpy, NV_CTRL_TARGET_TYPE_X_SCREEN, 0, 0, NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL, &tmp); if (cur_perflvl < 0) { cur_perflvl = tmp; fprintf(stderr, "NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL = %d\n", cur_perflvl); } else if (tmp != cur_perflvl) { cur_perflvl = tmp; fprintf(stderr, "Changed NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL = %d\n", cur_perflvl); } } while ( cur_perflvl != wanted_perflvl ); return 0; } static int force_timing_changes(uint8_t wanted_perflvl, int mmiotrace) { Display *dpy = NULL; int ret = 0, i = 0; /* wait for X to come up */ do { usleep(10000); /* 10 ms */ dpy = XOpenDisplay(NULL); i++; } while(!dpy && i < 200 ); /* wait 2 seconds */ fprintf(stderr, "-- Display opened\n"); if (!dpy) { fprintf(stderr, "ERROR - XOpenDisplay failed\n"); return 1; } if (!upclock_card(dpy)) { if (mmiotrace) { ret = write_to_file("/sys/kernel/debug/tracing/trace_marker", "Start downclocking\n"); if (ret) fprintf(stderr, "Addind a marker to the mmiotrace returned error %i: %s\n", ret, strerror(ret)); } if (!wait_for_perflvl(dpy, wanted_perflvl)) { fprintf(stderr, "Downclock monitoring finished\n"); ret = 0; } } /* wait for PDAEMON to actually change the memory clock */ sleep(1); XCloseDisplay(dpy); fprintf(stderr, "-- Display closed (pid = %i)\n", getpid()); return ret; } static void print_reg_diff(FILE* outf, uint32_t orig, uint32_t dest, enum color diff) { uint8_t *o = (uint8_t*)&orig; uint8_t *d = (uint8_t*)&dest; int i; for (i = 3; i >= 0; i--) { const char* colour = "\e[0;31m"; if (diff == NO_COLOR || o[i] == d[i]) colour = NULL; fprintf(outf, "%s%02x%s", colour?colour:"", d[i], colour?"\e[0m":""); } fprintf(outf, " "); } static void dump_regs(int cnum, FILE* outf, uint32_t ref_val[], int ref_exist, uint32_t reg, uint32_t regs_len, enum color color) { uint32_t val; int r; for (r = 0; r < regs_len; r+=4) { if (r % 0x10 == 0) fprintf(outf, "%08x: ", reg + r); val = nva_rd32(cnum, reg + r); print_reg_diff(outf, ref_val[r], val, color); /* if the value wasn't initialized before, store it as a reference */ if (ref_exist == 0) ref_val[r] = val; if (r % 0x10 == 0xc) fprintf(outf, "\n"); } } static void dump_timings(struct nvamemtiming_conf *conf, FILE* outf, int8_t progression, enum color color) { static uint32_t ref_val1[0xa0] = { 0 }; static uint32_t ref_val2[0x30] = { 0 }; static uint32_t ref_val3[0x20] = { 0 }; static uint32_t ref_val4[0x10] = { 0 }; static int ref_exist = 0; uint8_t *vbios_entry = conf->vbios.data + conf->vbios.timing_entry_offset; int i; fprintf(outf, "timing entry [%u/%u]: ", progression, conf->vbios.timing_entry_length); for (i = 0; i < conf->vbios.timing_entry_length; i++) { if (i != progression - 1) fprintf(outf, "%02x ", vbios_entry[i]); else fprintf(outf, "\e[0;31m%02x\e[0m ", vbios_entry[i]); } fprintf(outf, "\n"); if (nva_cards[conf->cnum].chipset.card_type >= 0xc0) { dump_regs(conf->cnum, outf, ref_val3, ref_exist, 0x10f240, 0x20, color && progression > 0); dump_regs(conf->cnum, outf, ref_val1, ref_exist, 0x10f290, 0xa0, color && progression > 0); dump_regs(conf->cnum, outf, ref_val4, ref_exist, 0x10f610, 0x10, color && progression > 0); dump_regs(conf->cnum, outf, ref_val2, ref_exist, 0x10f720, 0x20, color && progression > 0); } else { dump_regs(conf->cnum, outf, ref_val1, ref_exist, 0x100220, 0x30, color && progression > 0); dump_regs(conf->cnum, outf, ref_val2, ref_exist, 0x1002c0, 0x30, color && progression > 0); dump_regs(conf->cnum, outf, ref_val3, ref_exist, 0x100510, 0x10, color && progression > 0); dump_regs(conf->cnum, outf, ref_val4, ref_exist, 0x100710, 0x10, color && progression > 0); } fprintf(outf, "\n"); fflush(outf); ref_exist = 1; } static int launch(struct nvamemtiming_conf *conf, FILE *outf, uint8_t progression, enum color color) { printf("--- Start sequence number %u\n", progression); if (system("rmmod nvidia") == 127) { fprintf(stderr, "rmmod not found. Abort\n"); exit (2); } if (vbios_upload_pramin(conf->cnum, conf->vbios.data, conf->vbios.length) != 1) { fprintf(stderr, "upload failed. Abort\n"); exit(3); } /* modify our env so as we can launch apps on X */ setenv("DISPLAY", ":0", 1); /* monitor downclocking */ if (conf->mmiotrace) mmiotrace_start(progression); pid_t pid = fork(); if (pid == 0) { system("killall X 2> /dev/null > /dev/null"); system("X > /dev/null 2> /dev/null"); fprintf(stderr, "X exited, let's quit!\n"); exit(0); } else if (pid == -1) { fprintf(stderr, "Fork failed! Abort\n"); exit (4); } /* X runs, wait for the right perflvl to be selected */ if (force_timing_changes(conf->timing.perflvl, conf->mmiotrace)) return 1; if (conf->mmiotrace) mmiotrace_stop(); dump_timings(conf, outf, progression, color); system("killall X"); /* wait for all zombie processes */ while(wait(NULL) > 0); /* increase the launch counter */ conf->counter++; /* wait for the nvidia driver to modeset back to the crappy resolution */ sleep(5); return 0; } static void iterate_bitfield(struct nvamemtiming_conf *conf, FILE *outf, uint8_t index, enum color color) { int b; for (b = 0; b < 8; b++) { conf->vbios.data[conf->vbios.timing_entry_offset + index] = (1 << b); launch(conf, outf, index + 1 , COLOR); } } static void iterate_values(struct nvamemtiming_conf *conf, FILE *outf, uint8_t index, enum color color) { uint8_t initial, target; int v; if (conf->mode != MODE_DEEP) return; initial = conf->vbios.data[conf->vbios.timing_entry_offset + index]; target = conf->vbios.data[conf->deep.timing_entry_offset + index]; for (v = initial+1; v <= target; v++) { conf->vbios.data[conf->vbios.timing_entry_offset + index] = v; launch(conf, outf, index + 1 , COLOR); } } int deep_dump(struct nvamemtiming_conf *conf) { char filename[21]; int i; if (conf->range.start == (unsigned char) -1 || conf->range.end == (unsigned char) -1) sprintf(filename, "regs_timing_deep_%i_%i", conf->range.start, conf->range.end); else sprintf(filename, "regs_timing_deep"); /* TODO: get this filename from the command line */ FILE *outf = fopen(filename, "wb"); if (!outf) { perror("Open regs_timing_deep"); return 1; } if (nva_cards[conf->cnum].chipset.card_type >= 0xc0) timing_value_types = nvc0_timing_value_types; else timing_value_types = nv40_timing_value_types; if (conf->range.start == (unsigned char) -1) conf->range.start = 0; if (conf->range.end == (unsigned char) -1) conf->range.end = conf->vbios.timing_entry_length; fprintf(stderr, "Deep mode: Will iterate between %i and %i\n", conf->range.start, conf->range.end); launch(conf, outf, 0, NO_COLOR); /* iterate through the vbios timing values */ for (i = 0; i < conf->vbios.timing_entry_length; i++) { uint8_t orig = conf->vbios.data[conf->vbios.timing_entry_offset + i]; if (timing_value_types[i] == VALUE || (timing_value_types[i] == EMPTY && orig > 0)) { if (timing_value_types[i] == EMPTY && orig > 0) fprintf(outf, "WARNING: The following entry was supposed to be unused!\n"); iterate_values(conf, outf, i, COLOR); } else if (timing_value_types[i] == BITFIELD) { iterate_bitfield(conf, outf, i, COLOR); } else if (timing_value_types[i] == EMPTY) { fprintf(outf, "timing entry [%u/%u] is supposed empty\n\n", i + 1, conf->vbios.timing_entry_length); } conf->vbios.data[conf->vbios.timing_entry_offset + i] = orig; } fclose(outf); return 0; } int shallow_dump(struct nvamemtiming_conf *conf) { char filename[21]; int i; if (conf->range.start == (unsigned char) -1 || conf->range.end == (unsigned char) -1) sprintf(filename, "regs_timing_%i_%i", conf->range.start, conf->range.end); else sprintf(filename, "regs_timing"); /* TODO: get this filename from the command line */ FILE *outf = fopen(filename, "wb"); if (!outf) { perror("Open regs_timing"); return 1; } if (nva_cards[conf->cnum].chipset.card_type >= 0xc0) timing_value_types = nvc0_timing_value_types; else timing_value_types = nv40_timing_value_types; if (conf->range.start == (unsigned char) -1) conf->range.start = 0; if (conf->range.end == (unsigned char) -1) conf->range.end = conf->vbios.timing_entry_length; fprintf(stderr, "Shallow mode: Will iterate between %i and %i\n", conf->range.start, conf->range.end); launch(conf, outf, 0, NO_COLOR); /* iterate through the vbios timing values */ for (i = conf->range.start; i < conf->range.end; i++) { uint8_t orig = conf->vbios.data[conf->vbios.timing_entry_offset + i]; if (timing_value_types[i] == VALUE || (timing_value_types[i] == EMPTY && orig > 0)) { if (timing_value_types[i] == EMPTY && orig > 0) fprintf(outf, "WARNING: The following entry was supposed to be unused!\n"); conf->vbios.data[conf->vbios.timing_entry_offset + i]++; launch(conf, outf, i + 1, COLOR); } else if (timing_value_types[i] == BITFIELD) { iterate_bitfield(conf, outf, i, COLOR); } else if (timing_value_types[i] == EMPTY) { fprintf(outf, "timing entry [%u/%u] is supposed empty\n\n", i + 1, conf->vbios.timing_entry_length); } conf->vbios.data[conf->vbios.timing_entry_offset + i] = orig; } fclose(outf); return 0; } int bitfield_check(struct nvamemtiming_conf *conf) { char outfile[21]; snprintf(outfile, 20, "entry_b_%i", conf->bitfield.index); /* TODO: get this filename from the command line */ FILE *outf = fopen(outfile, "wb"); if (!outf) { perror("Open the output file"); return 1; } printf("Bitfield mode: test index %i\n", conf->bitfield.index); launch(conf, outf, 0, NO_COLOR); iterate_bitfield(conf, outf, conf->bitfield.index, COLOR); fclose(outf); return 0; } int manual_check(struct nvamemtiming_conf *conf) { char outfile[21]; snprintf(outfile, 20, "entry_%i_%i", conf->manual.index, conf->manual.value); /* TODO: get this filename from the command line */ FILE *outf = fopen(outfile, "wb"); if (!outf) { perror("Open the output file"); return 1; } printf("Manual mode: set index %i to value 0x%x\n", conf->manual.index, conf->manual.value); conf->vbios.data[conf->vbios.timing_entry_offset + conf->manual.index] = conf->manual.value; launch(conf, outf, 0, NO_COLOR); fclose(outf); return 0; }
plaes/envytools
nva/nva.c
/* * Copyright (C) 2010-2011 <NAME> <<EMAIL>> * Copyright (C) 2011 <NAME> <<EMAIL>> * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <pciaccess.h> #include <stdio.h> #include <stdlib.h> #include "nva.h" #include "util.h" struct nva_card *nva_cards = 0; int nva_cardsnum = 0; int nva_cardsmax = 0; struct pci_id_match nv_match[4] = { {0x104a, 0x0009, PCI_MATCH_ANY, PCI_MATCH_ANY, 0, 0}, {0x12d2, PCI_MATCH_ANY, PCI_MATCH_ANY, PCI_MATCH_ANY, 0x30000, 0xffff0000}, {0x10de, PCI_MATCH_ANY, PCI_MATCH_ANY, PCI_MATCH_ANY, 0x30000, 0xffff0000}, {0x10de, PCI_MATCH_ANY, PCI_MATCH_ANY, PCI_MATCH_ANY, 0x48000, 0xffffff00}, }; int nva_init() { int ret; ret = pci_system_init(); if (ret) return -1; int i; for (i = 0; i < ARRAY_SIZE(nv_match); i++) { struct pci_device_iterator* it = pci_id_match_iterator_create(&nv_match[i]); if (!it) { pci_system_cleanup(); return -1; } struct pci_device *dev; while ((dev = pci_device_next(it))) { struct nva_card c = { 0 }; ret = pci_device_probe(dev); if (ret) { fprintf (stderr, "WARN: Can't probe %04x:%02x:%02x.%x\n", dev->domain, dev->bus, dev->dev, dev->func); continue; } c.pci = dev; ADDARRAY(nva_cards, c); } pci_iterator_destroy(it); } for (i = 0; i < nva_cardsnum; i++) { struct pci_device *dev; dev = nva_cards[i].pci; ret = pci_device_map_range(dev, dev->regions[0].base_addr, dev->regions[0].size, PCI_DEV_MAP_FLAG_WRITABLE, &nva_cards[i].bar0); if (ret) { fprintf (stderr, "WARN: Can't probe %04x:%02x:%02x.%x\n", dev->domain, dev->bus, dev->dev, dev->func); int j; for (j = i + 1; j < nva_cardsnum; j++) { nva_cards[j-1] = nva_cards[j]; } nva_cardsnum--; i--; continue; } nva_cards[i].bar0len = dev->regions[0].size; if (dev->regions[1].size) { nva_cards[i].hasbar1 = 1; nva_cards[i].bar1len = dev->regions[1].size; ret = pci_device_map_range(dev, dev->regions[1].base_addr, dev->regions[1].size, PCI_DEV_MAP_FLAG_WRITABLE, &nva_cards[i].bar1); if (ret) { nva_cards[i].bar1 = 0; } } if (dev->regions[2].size) { nva_cards[i].hasbar2 = 1; nva_cards[i].bar2len = dev->regions[2].size; ret = pci_device_map_range(dev, dev->regions[2].base_addr, dev->regions[2].size, PCI_DEV_MAP_FLAG_WRITABLE, &nva_cards[i].bar2); if (ret) { nva_cards[i].bar2 = 0; } } else if (dev->regions[3].size) { nva_cards[i].hasbar2 = 1; nva_cards[i].bar2len = dev->regions[3].size; ret = pci_device_map_range(dev, dev->regions[3].base_addr, dev->regions[3].size, PCI_DEV_MAP_FLAG_WRITABLE, &nva_cards[i].bar2); if (ret) { nva_cards[i].bar2 = 0; } } uint32_t pmc_id = nva_rd32(i, 0); parse_pmc_id(pmc_id, &nva_cards[i].chipset); } return (nva_cardsnum == 0); }
plaes/envytools
nva/nvalist.c
<filename>nva/nvalist.c /* * Copyright (C) 2010-2011 <NAME> <<EMAIL>> * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "nva.h" #include <stdio.h> #include <pciaccess.h> int main() { if (nva_init()) { fprintf (stderr, "PCI init failure!\n"); return 1; } int i; for (i = 0; i < nva_cardsnum; i++) printf ("%d: %04x:%02x:%02x.%x %s %08x\n", i, nva_cards[i].pci->domain, nva_cards[i].pci->bus, nva_cards[i].pci->dev, nva_cards[i].pci->func, nva_cards[i].chipset.name, nva_cards[i].chipset.pmc_id); return 0; }
greg-minshall/flstats
flstats.c
/* * Copyright (c) 1996 * Ipsilon Networks, Inc. * * please see terms and conditions of copyright at the end of this file */ /* * output flow statistics from a tcpdump file. * */ static char *flstats_c_rcsid = "$Id: af0d9d167513dbbf27d9045dad2e66733f2523b6 $"; #include "config.h" #define _GNU_SOURCE /* needed for asprintf(3) */ #if defined(HAVE_ERRNO_H) /* http://blog.nirkabel.org/2009/01/18/errnoh-problem/comment-page-1/ */ #include <errno.h> #endif /* defined(HAVE_ERRNO_H) */ #include <signal.h> #if !defined(HAVE_ASPRINTF) #include <stdarg.h> #endif /* !defined(HAVE_ASPRINTF) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <pcap.h> #include <tcl.h> #include "flstats.h" /* global variables */ u_char protohasports[256]; u_short Ipv4type = 0x800; u_short IPv6type = 0x86dd; int fileeof = 0; int filetype = 0; flowentry_p buckets[31979]; flowentry_p onebehinds[NUM(buckets)]; flowentry_p table; /* list of everything */ flowentry_p table_last; /* last of everything */ flowentry_p flow_enum_state; struct timeval curtime, starttime; struct timeval ZERO = { 0, 0 }; ri_t ri; /* reporting interval structure */ /* * delta time reporting: * * (BOT == beginning of trace run; RI == reporting interval) * * absolute: absolute time (secs.usecs since epoch) * within_tr: BOT relative time (secs.usecs since BOT) * within_ri: RI relative time (secs.usecs within RI) * * (note that "within_ri" does *not* make sense for reporting the * start time of the RI itself; delta_ri.delta can *only* be * 'absolute' or 'within_tr') * * then, secs.usecs? or, just secs? */ typedef enum { absolute, within_tr, within_ri, invalid } delta_t; delta_t delta_wi, delta_ri; int binsecs = 0; /* number of seconds in a bin */ /* XXX any bounds checking from upper level (Tcl) calls? */ ftinfo_t ftinfo[10]; /* number of distinct flow types in use */ llcl_t llclasses[NUM(ftinfo)]; /* * application defined "classes". Class[0] is special, in that * it gets any counts not tied to any other flow type or flow. */ /* XXX any bounds checking from upper level (Tcl) calls? */ class_t classes[NUM(ftinfo)]; class_p class_enum_state; int flow_types = 0; pcap_t *pcap_descriptor; int pcap_dlt, /* data link type of input file */ pcap_snap; /* snap length of input file */ pcap_handler pcap_receiver; char pcap_errbuf[PCAP_ERRBUF_SIZE]; /* FDDI stuff */ /* * This is a place where pcap is a bit messed up (should be two DLTs). */ #if defined(ultrix) || defined(__alpha) #define FDDIPAD 3 #else #define FDDIPAD 0 #endif int fddipad = FDDIPAD; int packet_error = 0; int pending, pendingcaplen, pendingpktlen, pending_maxpktlen; u_char *pending_packet, *pktbuffer;; flowentry_t timers[150]; u_long pktcount, signalled, lastsignalled; char *args, /* arguments... */ argcount[200]; /* number of them */ char fl_tclprogram[] = #include "flstats.char" ; /* * signal handling */ static void gotsignal(int which) { signalled++; } /* * forward declarations */ static void delete_flow(flowentry_p fe); /* * return the microseconds from a struct timeval */ static long tvusecs(suseconds_t su_usecs) { long usecs = su_usecs; return usecs; } /* * return the correct secs (based on delta_wi) for a timeval */ static long dtsecs(struct timeval *tv, delta_t delta) { switch (delta) { case absolute: return tv->tv_sec; case within_tr: return TIMEDIFFSECS(tv, &starttime); case within_ri: return TIMEDIFFSECS(tv, &ri.ri_starttime); default: fprintf(stderr, "%s:%d: delta parameter, invalid value\n", __FILE__, __LINE__); exit(1); /*NOTREACHED*/ } } /* * return the correct usecs (based on delta_wi) for a timeval */ static long dtusecs(struct timeval *tv, delta_t delta) { switch (delta) { case absolute: return tvusecs(tv->tv_usec); case within_tr: return tvusecs(TIMEDIFFUSECS(tv, &starttime)); case within_ri: return tvusecs(TIMEDIFFUSECS(tv, &ri.ri_starttime)); default: fprintf(stderr, "%s:%d: delta parameter, invalid value\n", __FILE__, __LINE__); exit(1); /*NOTREACHED*/ } } static long dtsecs_wi(struct timeval *tv) { return dtsecs(tv, delta_wi); } static long dtsecs_ri(struct timeval *tv) { return dtsecs(tv, delta_ri); } static long dtusecs_wi(struct timeval *tv) { return dtusecs(tv, delta_wi); } static long dtusecs_ri(struct timeval *tv) { return dtusecs(tv, delta_ri); } /* * save a string */ char * strsave(const char *s) { int n = strlen(s); char *new; new = (char *) malloc(n+1); if (new) { strncpy(new, s, n+1); } return new; } /* * save some bytes */ u_char * u_char_save(const u_char *u, int len) { u_char *new; new = (u_char *) malloc(len); if (new) { memcpy(new, u, len); } return new; } #if !defined(HAVE_ASPRINTF) /* * slow, but simple (hopefully, almost *never* needed) */ static int asprintf(char **where, const char *format, ...) { va_list ap; char foo[1]; /* used in determining the correct size */ char *place; int len; /* */ va_start(ap, format); /* this first call does no real printing, just determines size */ len = vsnprintf(foo, 0, format, ap); place = malloc(len); if (place == 0) { *where = 0; return -1; /* see man page for asprintf(3) */ } vsnprintf(place, len, format, ap); *where = place; return len; } #endif /* !defined(HAVE_ASPRINTF) */ /* * delete a string returned from asprintf(3) * (in a way that makes Tcl_SetResult(3) happy, sigh) */ static void tclasfree(char *tofree) { free(tofree); } /* * identify a packet for an error message */ char * pktloc() { static char loc[100]; sprintf(loc, "%ld", pktcount); return loc; } /* * a new file is being opened, so clean up from the last one. */ static int newfile(Tcl_Interp *interp, int maxpktlen) { flowentry_p fe, nfe; class_p cl; extern int errno; char *asret; fileeof = 0; flow_enum_state = 0; class_enum_state = 0; switch (filetype) { case TYPE_PCAP: if (pcap_descriptor != 0) { pcap_close(pcap_descriptor); pcap_descriptor = 0; } break; case TYPE_UNKNOWN: /* nothing to do */ break; default: asprintf(&asret, "%s.%d: filetype %d unknown!\n", __FILE__, __LINE__, filetype); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } filetype = TYPE_UNKNOWN; /* go into neutral... */ memset(&classes[0], 0, sizeof classes); for (cl = &classes[0]; cl < &classes[NUM(classes)]; cl++) { cl->cls_last_bin_active = 0xffffffff; } curtime = ZERO; starttime = ZERO; pending = 0; for (fe = table; fe; fe = nfe) { nfe = fe->fe_next_in_table; free(fe); } table = table_last = 0; memset(buckets, 0, sizeof buckets); memset(onebehinds, 0, sizeof onebehinds); /* if pending buffer is already set, free it */ if (pending_packet) { free(pending_packet); pending_packet = 0; /* empty the water bucket */ pending_maxpktlen = 0; } /* allocate packet for pending buffer */ pending_packet = malloc(maxpktlen); /* room for packet */ if (pending_packet == 0) { asprintf(&asret, "no room for %d-byte packet buffer", maxpktlen); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } pending_maxpktlen = maxpktlen; /* remember size of buffer */ /* if we've already allocated a packet buffer, free it */ if (pktbuffer) { free(pktbuffer); pktbuffer = 0; } pktbuffer = malloc(maxpktlen); /* room for alignment */ if (pktbuffer == 0) { asprintf(&asret, "no room for %d-byte packet buffer", maxpktlen); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } return TCL_OK; } /* * Compute a checksum on a contiguous area of storage * * This is tailored to doing quite short data structures, * in particular, flow ids. */ static u_short cksum(u_char *p, int len) { int shorts = len/2; u_long sum = 0; while (shorts > 4) { /* 0*/ sum += PICKUP_NETSHORT(p); p += 2; sum += PICKUP_NETSHORT(p); p += 2; /* 2*/ sum += PICKUP_NETSHORT(p); p += 2; sum += PICKUP_NETSHORT(p); p += 2; /* 4*/ shorts -= 4; } while (shorts > 0) { sum += PICKUP_NETSHORT(p); p += 2; shorts--; } if (len&1) { sum += p[0]<<8; } /* * Reduce * * 0xffff + 0xffff = 0x1fffe. So, */ sum = (sum&0xffff)+((sum>>16)&0xffff); sum = (sum&0xffff)+((sum>>16)&0xffff); /* That's enough */ return (u_short) (~htons(sum))&0xffff; } static char * flow_type_to_string(u_char *type_indices, int len) { static char result[MAX_FLOW_ID_BYTES*10]; char *sep = ""; atoft_p xp; int i; result[0] = 0; for (i = 0; i < len; i++) { xp = &atoft[type_indices[i]]; sprintf(result+strlen(result), "%s%s", sep, xp->name); sep = "/"; } return result; } static char * flow_id_to_string(ftinfo_p ft, u_char *id) { static char result[MAX_FLOW_ID_BYTES*10]; char fidstring[30], *fidp; char *sep = "", *dot, *fmt0xff, *fmt0xf; atoft_p xp; u_long decimal; int i, firstbit, numbits, lastbit; u_long byte; result[0] = 0; for (i = 0; i < ft->fti_type_indices_len; i++) { xp = &atoft[ft->fti_type_indices[i]]; fidp = fidstring; dot = ""; /* for dotted decimal */ decimal = 0; /* for decimal */ switch (xp->fmt) { case FMT_DECIMAL: break; /* done in for loop (sigh) */ case FMT_DOTTED: fmt0xff = "%s%d"; fmt0xf = "%s%d"; break; case FMT_HEX: fmt0xff = "%s%02x"; fmt0xf = "%s%x"; break; default: fprintf(stderr, "%s:%d: %d is bad fmt\n", __FILE__, __LINE__, xp->fmt); break; } firstbit = xp->firstbit; numbits = xp->numbits; while (numbits > 0) { byte = *id++; lastbit = (firstbit+numbits) > 8 ? 7 : firstbit+numbits-1; if (firstbit > 0) { byte = (byte<<(firstbit+24))>>(firstbit+24); } if (lastbit < 7) { byte = (byte>>(7-lastbit))<<(7-lastbit); } if (xp->fmt == FMT_DECIMAL) { decimal = (decimal<<(lastbit-firstbit+1))+(byte>>(7-lastbit)); } else { if (firstbit < 4) { sprintf(fidp, fmt0xff, dot, byte); } else { sprintf(fidp, fmt0xf, dot, byte); } fidp += strlen(fidp); } numbits -= (8-firstbit); firstbit = 0; if (xp->fmt == FMT_DOTTED) { dot = "."; } } if (xp->fmt == FMT_DECIMAL) { sprintf(fidstring, "%ld", decimal); } else { *fidp = 0; } sprintf(result+strlen(result), "%s%s", sep, fidstring); sep = "/"; } return result; } /* * formats for reporting flow, class statistics. these can be read, * and modified, by the scripting language */ static char *flow_stats_template = "class %d type %s id %s pkts %lu bytes " "%lu sipg %lu.%06lu created %ld.%06ld last %ld.%06ld", *flow_stats_format; static char * flow_statistics(flowentry_p fe) { static char summary[2000]; ftinfo_p ft = &ftinfo[fe->fe_flow_type]; sprintf(summary, flow_stats_format, fe->fe_class, flow_type_to_string(ft->fti_type_indices, ft->fti_type_indices_len), flow_id_to_string(ft, fe->fe_id), fe->fe_pkts-fe->fe_pkts_last_enum, fe->fe_bytes-fe->fe_bytes_last_enum, SIPG_TO_SECS(fe->fe_sipg), SIPG_TO_USECS(fe->fe_sipg), dtsecs_ri(&fe->fe_created), dtusecs_ri(&fe->fe_created), dtsecs_ri(&fe->fe_last_pkt_rcvd), dtusecs_ri(&fe->fe_last_pkt_rcvd)); return summary; } static char *class_stats_template = "class %d type %s created %lu deleted %lu added %lu removed %lu " "active %lu pkts %lu bytes %lu sipg %lu.%06lu " "lastrecv %ld.%06ld", *class_stats_format; static char * class_statistics(class_p clsp) { static char summary[10000]; sprintf(summary, class_stats_format, clsp-classes, flow_type_to_string(clsp->cls_type_indices, clsp->cls_type_indices_len), clsp->cls_ri.cls_ri_created, clsp->cls_ri.cls_ri_deleted, clsp->cls_ri.cls_ri_added, clsp->cls_ri.cls_ri_removed, clsp->cls_ri.cls_ri_active, clsp->cls_ri.cls_ri_pkts, clsp->cls_ri.cls_ri_bytes, SIPG_TO_SECS(clsp->cls_sipg), SIPG_TO_USECS(clsp->cls_sipg), dtsecs_ri(&clsp->cls_last_pkt_rcvd), dtusecs_ri(&clsp->cls_last_pkt_rcvd)); return summary; } static char *ri_stats_template = "binno %lu ri_start %ld.%06ld ri_end %ld.%06ld " "ri_firstpkt %ld.%06ld ri_lastpkt %ld.%06ld " "ri_pkts %lu ri_bytes %lu " "ri_tsipg %lu.%06lu ri_isipg %lu.%06lu " "ipv6pkts %lu ipv6bytes %lu " "nonippkts %lu nonipbytes %lu " "unclpkts %lu unclbytes %lu " "fragpkts %lu fragbytes %lu toosmallpkts %lu toosmallbytes %lu " "runtpkts %lu runtbytes %lu noportpkts %lu noportbytes %lu", *ri_stats_format; static char * ri_statistics() { char *asret; /* * note: only ri_stime uses delta_ri; everything can be * relative to it */ asprintf(&asret, ri_stats_format, ri.ri_binno, dtsecs_ri(&ri.ri_starttime), dtusecs_ri(&ri.ri_starttime), dtsecs_wi(&ri.ri_endtime), dtusecs_wi(&ri.ri_endtime), dtsecs_wi(&ri.ri_first_pkt_rcvd), dtusecs_wi(&ri.ri_first_pkt_rcvd), dtsecs_wi(&ri.ri_last_pkt_rcvd), dtusecs_wi(&ri.ri_last_pkt_rcvd), ri.ri_pkts, ri.ri_bytes, SIPG_TO_SECS(ri.ri_isipg), SIPG_TO_USECS(ri.ri_isipg), SIPG_TO_SECS(ri.ri_tsipg), SIPG_TO_USECS(ri.ri_tsipg), ri.ri_ipv6pkts, ri.ri_ipv6bytes, ri.ri_nonippkts, ri.ri_nonipbytes, ri.ri_unclpkts, ri.ri_unclbytes, ri.ri_fragpkts, ri.ri_fragbytes, ri.ri_toosmallpkts, ri.ri_toosmallbytes, ri.ri_runtpkts, ri.ri_runtbytes, ri.ri_noportpkts, ri.ri_noportbytes); return asret; } /* * arrange for something to run shortly after "timertime" */ static void timer_insert(flowentry_p fe, struct timeval *timertime) { flowentry_p timer = &timers[timertime->tv_sec%NUM(timers)]; timer->fe_prev_in_timer->fe_next_in_timer = fe; fe->fe_prev_in_timer = timer->fe_prev_in_timer; timer->fe_prev_in_timer = fe; fe->fe_next_in_timer = timer; } static void timer_remove(flowentry_p fe) { if (fe->fe_prev_in_timer) { fe->fe_prev_in_timer->fe_next_in_timer = fe->fe_next_in_timer; fe->fe_next_in_timer->fe_prev_in_timer = fe->fe_prev_in_timer; } } static flowentry_p timer_get_slot() { flowentry_p timer = &timers[curtime.tv_sec%NUM(timers)]; flowentry_p slot = timer->fe_next_in_timer; if (slot == timer->fe_prev_in_timer) { return 0; /* nothing */ } /* keep ends from dangling */ slot->fe_prev_in_timer = 0; timer->fe_prev_in_timer->fe_next_in_timer = 0; /* point to self */ timer->fe_next_in_timer = timer; timer->fe_prev_in_timer = timer; return slot; } static void do_timers(Tcl_Interp *interp) { flowentry_p nfe, fe; ftinfo_p fti; char buf[100]; int n; long usecs; nfe = timer_get_slot(); while ((fe = nfe) != 0) { nfe = fe->fe_next_in_timer; fe->fe_next_in_timer = fe->fe_prev_in_timer = 0; if (TIME_LT(&fe->fe_timer_time, &curtime)) { fti = &ftinfo[fe->fe_flow_type]; if ((fti->fti_timer_upcall == 0) || TIME_EQ(&fe->fe_timer_time, &ZERO)) { continue; /* maybe flow type changed? */ } /* * call: "timer_upcall timesecs.usecs FLOW flowstats" * result: "command secs.usecs" * * XXX should this follow -D flag? */ sprintf(buf, " %ld.%06ld ", curtime.tv_sec, tvusecs(curtime.tv_usec)); if (Tcl_VarEval(interp, ftinfo[fe->fe_flow_type].fti_timer_upcall, buf, " FLOW ", flow_statistics(fe), 0) != TCL_OK) { packet_error = TCL_ERROR; return; } fe->fe_timer_time.tv_usec = 0; n = sscanf(Tcl_GetStringResult(interp), "%s %ld.%ld", buf, &fe->fe_timer_time.tv_sec, &usecs); fe->fe_timer_time.tv_usec = usecs; if ((n >= 1) && !strcmp(buf, "DELETE")) { delete_flow(fe); } else if (n >= 2) { if (!TIME_EQ(&fe->fe_timer_time, &ZERO)) { TIME_ADD(&fe->fe_timer_time, &fe->fe_timer_time, &curtime); timer_insert(fe, &fe->fe_timer_time); } } } else { timer_insert(fe, &fe->fe_timer_time); } } } static void set_time(Tcl_Interp *interp, long sec, long usec) { struct timeval now; char *asret; now.tv_sec = sec; now.tv_usec = usec; if (TIME_LT(&now, &ZERO)) { asprintf(&asret, "[%s] bad trace file format -- negative time in packet", pktloc()); Tcl_SetResult(interp, asret, tclasfree); packet_error = TCL_ERROR; return; } if (TIME_EQ(&ri.ri_starttime, &ZERO)) { ri.ri_starttime = now; } ri.ri_endtime = now; if (TIME_EQ(&starttime, &ZERO)) { starttime = now; curtime = now; } else { if (TIME_LT(&now, &curtime)) { #if 0 /* * OK. Vern's tcpslice(1) doesn't worry about this (but, like this * #if 0, just doesn't update time for a while). hmm ' */ sprintf(interp->result, "[%s] bad trace file format -- time goes backwards", pktloc()); packet_error = TCL_ERROR; #endif /* 0 */ return; } /* call timers once per second */ while (curtime.tv_sec != now.tv_sec) { do_timers(interp); curtime.tv_sec++; /* advance the time */ } curtime.tv_usec = now.tv_usec; if (TIME_EQ(&ri.ri_starttime, &ZERO)) { ri.ri_starttime = curtime; } } if (ri.ri_binno == -1) { ri.ri_binno = NOW_AS_BINNO(); } } /* table lookup */ static flowentry_p tbl_lookup(u_char *id, ftinfo_p ft) { int id_len = ft->fti_id_len; int type_index = ft-ftinfo; u_short sum = cksum(id, id_len); flowentry_p fe = buckets[sum%NUM(buckets)]; flowentry_p onebehind = onebehinds[sum%NUM(onebehinds)]; #define MATCH(id,len,sum,type_index,p) \ ((sum == (p)->fe_sum) && (type_index == (p)->fe_flow_type) && \ (len == (p)->fe_id_len) && !memcmp(id, (p)->fe_id, len)) if (onebehind && MATCH(id, id_len, sum, type_index, onebehind)) { return onebehind; } while (fe) { if (MATCH(id, id_len, sum, type_index, fe)) { onebehinds[sum%NUM(onebehinds)] = fe; break; } fe = fe->fe_next_in_bucket; } return fe; } static flowentry_p tbl_add(u_char *id, int id_len) { u_short sum = cksum(id, id_len); flowentry_p *hbucket = &buckets[sum%NUM(buckets)]; flowentry_p fe; fe = (flowentry_p) malloc(sizeof *fe+id_len-1); if (fe == 0) { return 0; } memset(fe, 0, sizeof *fe); fe->fe_sum = sum; fe->fe_id_len = id_len; fe->fe_id = u_char_save(id, id_len); fe->fe_next_in_bucket = *hbucket; if (fe->fe_next_in_bucket) { fe->fe_next_in_bucket->fe_prev_in_bucket = fe; } fe->fe_prev_in_bucket = 0; *hbucket = fe; fe->fe_next_in_table = 0; fe->fe_prev_in_table = table_last; if (table_last) { table_last->fe_next_in_table = fe; } else { table = fe; } table_last = fe; fe->fe_next_in_timer = fe->fe_prev_in_timer = 0; return fe; } static void tbl_delete(flowentry_p fe) { u_short sum = cksum(fe->fe_id, fe->fe_id_len); flowentry_p *hbucket = &buckets[sum%NUM(buckets)]; flowentry_p *honebehind = &onebehinds[sum%NUM(onebehinds)]; /* dequeue the silly thing... */ /* out of timer */ if (fe->fe_prev_in_timer) { timer_remove(fe); } /* out of bucket */ if (fe->fe_prev_in_bucket) { fe->fe_prev_in_bucket->fe_next_in_bucket = fe->fe_next_in_bucket; } else { *hbucket = fe->fe_next_in_bucket; } if (fe->fe_next_in_bucket) { fe->fe_next_in_bucket->fe_prev_in_bucket = fe->fe_prev_in_bucket; } if (*honebehind == fe) { *honebehind = *hbucket; } /* out of table */ if (fe->fe_prev_in_table) { fe->fe_prev_in_table->fe_next_in_table = fe->fe_next_in_table; } else { table = fe->fe_next_in_table; } if (fe->fe_next_in_table) { fe->fe_next_in_table->fe_prev_in_table = fe->fe_prev_in_table; } else { table_last = fe->fe_prev_in_table; } free(fe->fe_id); /* free up id */ free(fe); } static void delete_flow(flowentry_p fe) { classes[fe->fe_class].cls_ri.cls_ri_deleted++; classes[fe->fe_class].cls_last_bin_active = ri.ri_binno; tbl_delete(fe); } /* main thing: name this class */ static void new_flow_in_class(u_short class, flowentry_p fe, ftinfo_p ft) { class_p cls; if (fe->fe_class >= NUM(classes)) { fprintf(stderr, "%s:%d: assertion failure\n", __FILE__, __LINE__); exit(2); } cls = &classes[fe->fe_class]; if (ft->fti_type_indices_len > sizeof(cls->cls_type_indices)) { fprintf(stderr, "%s:%d: assertion failure\n", __FILE__, __LINE__); exit(2); } if (cls->cls_type_indices_len == 0) { /* never initialized */ memcpy(cls->cls_type_indices, ft->fti_type_indices, ft->fti_type_indices_len); cls->cls_type_indices_len = ft->fti_type_indices_len; } else if ((ft->fti_type_indices_len != cls->cls_type_indices_len) || (memcmp(ft->fti_type_indices, cls->cls_type_indices, cls->cls_type_indices_len))) { /* our previous value doesn't match */ /* now what? */ fprintf(stderr, "%s:%d: new_flow_in_class got a *different* value\n", __FILE__, __LINE__); } } static flowentry_p new_flow(Tcl_Interp *interp, ftinfo_p ft, u_char *flowid, int class) { flowentry_p fe; fe = tbl_add(flowid, ft->fti_id_len); if (fe == 0) { return 0; } fe->fe_flow_type = ft-ftinfo; fe->fe_parent_ftype = ft->fti_parent_ftype; /* default */ fe->fe_parent_class = ftinfo[ft->fti_parent_ftype].fti_class;/* default */ fe->fe_class = class; new_flow_in_class(class, fe, ft); fe->fe_last_bin_active = 0xffffffff; fe->fe_created = curtime; fe->fe_last_pkt_rcvd = ZERO; /* * now, if there is a "new flow" callout registered in this * flow type, call it. * * the callout is allowed to change certain parameters of * this flow entry: the class, the parent flow type, * the recv_upcall and parameters, and the timer_upcall * and parameters. */ if (ft->fti_new_flow_upcall) { int n; u_long sipgsecs, sipgusecs; long usecs1, usecs2; char buf[1000]; sprintf(buf, " %d %ld ", fe->fe_class, ft-ftinfo); if (Tcl_VarEval(interp, ft->fti_new_flow_upcall, buf, flow_type_to_string(ft->fti_type_indices, ft->fti_type_indices_len), " ", flow_id_to_string(ft, fe->fe_id), 0) != TCL_OK) { packet_error = TCL_ERROR; return 0; } fe->fe_upcall_when_secs_ge.tv_usec = 0; fe->fe_timer_time.tv_usec = 0; sipgusecs = 0; n = sscanf(Tcl_GetStringResult(interp), "%hd %hd %hd %ld.%ld %ld %lu.%lu %ld.%ld", &fe->fe_class, &fe->fe_parent_class, &fe->fe_parent_ftype, &fe->fe_upcall_when_secs_ge.tv_sec, &usecs1, &fe->fe_upcall_when_pkts_ge, &sipgsecs, &sipgusecs, &fe->fe_timer_time.tv_sec, &usecs2); fe->fe_upcall_when_secs_ge.tv_usec = usecs1; fe->fe_timer_time.tv_usec = usecs2; /* * (yes, these "if" stmts could be nested, and thus * be more efficient; but, they would be less legible, * so...) */ if (n >= 4) { if (!TIME_EQ(&fe->fe_upcall_when_secs_ge, &ZERO)) { /* returned value is relative to now, so make absolute */ TIME_ADD(&fe->fe_upcall_when_secs_ge, &fe->fe_upcall_when_secs_ge, &curtime); } } if (n >= 7) { fe->fe_upcall_when_sipg_lt = SECS_USECS_TO_SIPG(sipgsecs,sipgusecs); } if (n >= 9) { if (!TIME_EQ(&fe->fe_timer_time, &ZERO)) { /* returned value is relative to now, so make absolute */ TIME_ADD(&fe->fe_timer_time, &fe->fe_timer_time, &curtime); timer_insert(fe, &fe->fe_timer_time); } } } classes[fe->fe_class].cls_ri.cls_ri_created++; classes[fe->fe_class].cls_last_bin_active = ri.ri_binno; return fe; } /* * smoothed IPG (exponentially weighted moving average) * * sipg is expressed in units of 8 microseconds (usecs) */ static u_long sipg_update(u_long cur_sipg, struct timeval *last_pkt) { u_long sipg; if (TIME_EQ(last_pkt, &ZERO)) { return cur_sipg; } sipg = (curtime.tv_sec - last_pkt->tv_sec)*1000000UL; sipg += (curtime.tv_usec - last_pkt->tv_usec); /* two lines from VJ '88 SIGCOMM */ sipg -= (cur_sipg>>3); return cur_sipg + sipg; } /* * do per flow processing of a packet that has been received. * * this involves updating counters as well as calling out * to the "packet_received" callback routine if appropriate. */ static void packetinflow(Tcl_Interp *interp, flowentry_p fe, int len) { class_p cl; cl = &classes[fe->fe_class]; cl->cls_last_bin_active = ri.ri_binno; /* update statistics */ cl->cls_ri.cls_ri_pkts++; cl->cls_ri.cls_ri_bytes += len; if (cl->cls_last_pkt_rcvd.tv_sec) { /* sipg */ cl->cls_sipg = sipg_update(cl->cls_sipg, &cl->cls_last_pkt_rcvd); } cl->cls_last_pkt_rcvd = curtime; fe->fe_pkts++; fe->fe_bytes += len; if (fe->fe_last_pkt_rcvd.tv_sec) { /* sipg */ fe->fe_sipg = sipg_update(fe->fe_sipg, &fe->fe_last_pkt_rcvd); } fe->fe_last_pkt_rcvd = curtime; /* count activity in this bin */ if (fe->fe_last_bin_active != ri.ri_binno) { fe->fe_last_bin_active = ri.ri_binno; cl->cls_ri.cls_ri_active++; } /* do we need to callout? */ /* * i can think of a few things this might be good for: * * 1. if this should be switched, then after .N seconds, * switch to a "switched" statistics group. * 2. if we were running on a real system, with this * as the split between the "fast" code and the * "slow" (or, just a slow call between the two * halves), then if this was associated witha * flow coming in on a default label, and if * we had sent a redirect upstream, then we * could use this to detect that we were still * receiving on the default label after * N seconds. */ if (ftinfo[fe->fe_flow_type].fti_recv_upcall && (fe->fe_pkts >= fe->fe_upcall_when_pkts_ge) && (fe->fe_sipg < fe->fe_upcall_when_sipg_lt) && TIME_GE(&curtime, &fe->fe_upcall_when_secs_ge)) { int n, outcls; u_long sipgsecs, sipgusecs; long usecs; struct timeval outtime; if (Tcl_VarEval(interp, ftinfo[fe->fe_flow_type].fti_recv_upcall, " FLOW ", flow_statistics(fe), 0) != TCL_OK) { packet_error = TCL_ERROR; return; } fe->fe_upcall_when_secs_ge.tv_usec = 0; sipgusecs = 0; outcls = fe->fe_class; n = sscanf(Tcl_GetStringResult(interp), "%d %ld.%ld %ld %lu.%lu", &outcls, &fe->fe_upcall_when_secs_ge.tv_sec, &usecs, &fe->fe_upcall_when_pkts_ge, &sipgsecs, &sipgusecs); fe->fe_upcall_when_secs_ge.tv_usec = usecs; if (outcls != fe->fe_class) { /* class is changing --- update statistics */ classes[fe->fe_class].cls_ri.cls_ri_removed++; fe->fe_class = outcls; classes[fe->fe_class].cls_ri.cls_ri_added++; classes[fe->fe_class].cls_last_bin_active = ri.ri_binno; } if (n >= 2) { if (!TIME_EQ(&fe->fe_upcall_when_secs_ge, &ZERO)) { TIME_ADD(&fe->fe_upcall_when_secs_ge, &curtime, &outtime); } } if (n >= 5) { fe->fe_upcall_when_sipg_lt = SECS_USECS_TO_SIPG(sipgsecs,sipgusecs); } } } /* * This is the main packet input routine, called when a packet * has been received. * * We first map the incoming packet into a lower level * flow type (llft). We use that to find the lower level * flow entry (llfe). We also use the llft (possibly via * a callout routine) to find an upper level flow type (ulft). * We then use this ulft to find the upper level flow entry (ulfe). */ static void packetin(Tcl_Interp *interp, const u_char *packet, int caplen, int pktlen) { u_char llfid[MAX_FLOW_ID_BYTES], ulfid[MAX_FLOW_ID_BYTES]; int llclindex; int pktprotohasports, pktbigenough, capbigenough, fragmented; flowentry_p llfe, ulfe; /* lower and upper level flow entries */ ftinfo_p llft, ulft; /* lower and upper level flow types */ /* check for a pending packet */ if (pending) { if (caplen) { /* shouldn't happen! */ Tcl_SetResult(interp, "invalid condition in packetin", TCL_STATIC); packet_error = TCL_ERROR; return; } pending = 0; ri.ri_binno = NOW_AS_BINNO(); /* use the pending packet */ packet = (const u_char *)pending_packet; caplen = pendingcaplen; pktlen = pendingpktlen; } else if (ri.ri_binno != NOW_AS_BINNO()) { /* if we've gone over to another bin number... */ pending = 1; memcpy(pending_packet, packet, MIN(caplen, pending_maxpktlen)); pendingcaplen = caplen; pendingpktlen = pktlen; /* wait till next time */ return; } pktcount++; ri.ri_pkts++; ri.ri_bytes += pktlen; if (TIME_EQ(&ri.ri_first_pkt_rcvd, &ZERO)) { ri.ri_first_pkt_rcvd = curtime; } ri.ri_isipg = sipg_update(ri.ri_isipg, &ri.ri_last_pkt_rcvd); ri.ri_tsipg = sipg_update(ri.ri_tsipg, &ri.ri_last_pkt_rcvd); ri.ri_last_pkt_rcvd = curtime; /* now, do the low level classification into a llft */ pktprotohasports = protohasports[packet[9]]; pktbigenough = 0; capbigenough = 0; fragmented = 0; for (llclindex = 0; llclindex < NUM(llclasses) && !LLCL_UNUSED(&llclasses[llclindex]); llclindex++) { llft = &ftinfo[llclasses[llclindex].llcl_fti]; if (pktlen >= llft->fti_id_covers) { pktbigenough = 1; /* packet was big enough */ if (caplen >= llft->fti_id_covers) { capbigenough = 1; /* and, we captured enough */ /* * if ft doesn't use ports, or this protocol has ports and we * aren't fragmented, this is fine. */ if (FTI_USES_PORTS(llft)) { if (pktprotohasports && ((PICKUP_NETSHORT(&packet[6])&0x1fff) == 0)) { /* * needed ports and the protocol in packet * has ports and this isn't a fragment */ break; /* accept this packet in this class */ } else { /* * needed ports, but got a packet with a protocol * which doesn't have ports or got a fragment */ fragmented = 1; } } else { /* don't need to worry about ports... */ break; /* accept this packet in this class */ } } } } if (llclindex >= NUM(llclasses)) { ri.ri_unclpkts++; ri.ri_unclbytes += pktlen; if (pktbigenough) { /* packet was big enough, but... */ /* never found a flow type into which it fit */ if (capbigenough) { if (packet[6]&0x1fff) { ri.ri_fragpkts++; ri.ri_fragbytes += pktlen; } else { /* * this means there is no flow type for protocols * which don't have a port number field (i.e., this * is probably a bug... */ ri.ri_noportpkts++; ri.ri_noportbytes += pktlen; } } else { ri.ri_runtpkts++; ri.ri_runtbytes += pktlen; } } else { /* packet was too small for *any* defined flow */ ri.ri_toosmallpkts++; ri.ri_toosmallbytes += pktlen; } return; } /* create lower level flow id for this packet */ FLOW_ID_FROM_HDR(llfid, packet, llft); /* find the lower level flow entry */ llfe = tbl_lookup(llfid, llft); if (llfe == 0) { /* the lower level flow doesn't exist, so will need to be created */ llfe = new_flow(interp, llft, llfid, llft->fti_class); if (llfe == 0) { if (packet_error == 0) { Tcl_SetResult(interp, "unable to create a new lower level flow", TCL_STATIC); packet_error = TCL_ERROR; } return; } } /* track packet stats */ packetinflow(interp, llfe, pktlen); /* now, need to find ulfe from llfe */ while ((llfe->fe_parent_ftype != 0) && (llfe->fe_parent_ftype != llfe->fe_flow_type)) { ulft = &ftinfo[llfe->fe_parent_ftype]; /* get ll's parent flow type */ /* create the ulfid */ FLOW_ID_FROM_HDR(ulfid, packet, ulft); /* lookup the upper level flow entry */ ulfe = tbl_lookup(ulfid, ulft); if (ulfe == 0) { /* the upper level flow doesn't exist -- create it */ ulfe = new_flow(interp, ulft, ulfid, llfe->fe_parent_class); if (ulfe == 0) { if (packet_error == 0) { Tcl_SetResult(interp, "unable to create a new upper level flow", TCL_STATIC); packet_error = TCL_ERROR; } return; } } /* * there is a situation in which a UL flow is shared by * various LL flow types. in this case, it may be that * the class of the UL flow depends on which LL flows are * using it. this *could* cause us to call out every time * a new packet arrives (or, a packet arrives with a new * UL class, or ...). * * we use the following hack XXX : we infer a priority based * on the class number. if a packet comes in and the class * number in its parent_class field is greater than the class * numberin its parent, then the parent is "reclassed". * * i really don't know how to do this "right", sigh. */ if (llfe->fe_parent_class > ulfe->fe_class) { /* class is changing --- update statistics */ classes[ulfe->fe_class].cls_ri.cls_ri_removed++; classes[ulfe->fe_class].cls_last_bin_active = ri.ri_binno; ulfe->fe_class = llfe->fe_parent_class; classes[ulfe->fe_class].cls_ri.cls_ri_added++; classes[ulfe->fe_class].cls_last_bin_active = ri.ri_binno; } /* track packet stats */ packetinflow(interp, ulfe, pktlen); /* OK, old ulfe is new llfe, and loop... */ llfe = ulfe; } } /* * receive an ethernet frame. */ static void receive_tcpd_en10mb(u_char *user, const struct pcap_pkthdr *h, const u_char *buffer) { u_short type; Tcl_Interp *interp = (Tcl_Interp *)user; set_time(interp, h->ts.tv_sec, h->ts.tv_usec); if (h->caplen < 14) { /* need to call packetin to set counters, etc. */ packetin(interp, buffer, 0, 0); return; } type = buffer[12]<<8|buffer[13]; if (type != Ipv4type) { if (type == IPv6type) { ri.ri_ipv6pkts++; ri.ri_ipv6bytes += h->caplen-14; /* not that 14 is a magic number... */ } else { ri.ri_nonippkts++; ri.ri_nonipbytes += h->caplen-14; /* not that 14 is a magic number... */ } return; /* only IPv4 packets */ } packetin(interp, buffer+14, h->caplen-14, h->len-14); } /* * receive a slip frame */ static void receive_tcpd_slip(u_char *user, const struct pcap_pkthdr *h, const u_char *buffer) { #if !defined(SLIP_HDRLEN) #define SLIP_HDRLEN 16 #endif /* !defined(SLIP_HDRLEN) */ Tcl_Interp *interp = (Tcl_Interp *)user; set_time(interp, h->ts.tv_sec, h->ts.tv_usec); if (h->caplen < SLIP_HDRLEN) { packetin(interp, buffer, 0, 0); return; } packetin(interp, buffer+SLIP_HDRLEN, h->caplen-SLIP_HDRLEN, h->len-SLIP_HDRLEN); } /* * receive a PPP frame */ static void receive_tcpd_ppp(u_char *user, const struct pcap_pkthdr *h, const u_char *buffer) { #define PPP_HDRLEN 4 Tcl_Interp *interp = (Tcl_Interp *)user; set_time(interp, h->ts.tv_sec, h->ts.tv_usec); if (h->caplen < PPP_HDRLEN) { packetin(interp, buffer, 0, 0); return; } packetin(interp, buffer+PPP_HDRLEN, h->caplen-PPP_HDRLEN, h->len-PPP_HDRLEN); } /* * receive a FDDI frame */ static void receive_tcpd_fddi(u_char *user, const struct pcap_pkthdr *h, const u_char *buffer) { #define FDDI_HDRLEN 13 int caplen = h->caplen, length = h->len; u_short type; Tcl_Interp *interp = (Tcl_Interp *)user; struct fddi_header *fddip; static u_char SNAPHDR[] = { LLC_SNAP_LSAP, LLC_SNAP_LSAP, LLC_UI, 0, 0, 0 }; set_time(interp, h->ts.tv_sec, h->ts.tv_usec); if (caplen < FDDI_HDRLEN) { packetin(interp, buffer, 0, 0); return; } fddip = (struct fddi_header *)buffer; length -= FDDI_HDRLEN; buffer += FDDI_HDRLEN; caplen -= FDDI_HDRLEN; if ((fddip->fddi_fc&FDDIFC_CLFF) == FDDIFC_LLC_ASYNC) { if (caplen < sizeof SNAPHDR+2) { packetin(interp, buffer, 0, 0); return; } if (memcmp(buffer, SNAPHDR, sizeof SNAPHDR) == 0) { type = buffer[sizeof SNAPHDR]<<8|buffer[sizeof SNAPHDR+1]; if (type == 0x0800) { caplen -= (sizeof SNAPHDR+2); length -= (sizeof SNAPHDR+2); buffer += (sizeof SNAPHDR+2); packetin(interp, buffer, caplen, length); } else { return; } } else { return; } } else { return; } } /* * receive a null packet */ static void receive_tcpd_null(u_char *user, const struct pcap_pkthdr *h, const u_char *buffer) { #define NULL_HDRLEN 4 Tcl_Interp *interp = (Tcl_Interp *)user; set_time(interp, h->ts.tv_sec, h->ts.tv_usec); if (h->caplen < NULL_HDRLEN) { packetin(interp, buffer, 0, 0); return; } packetin(interp, buffer+NULL_HDRLEN, h->caplen-NULL_HDRLEN, h->len-NULL_HDRLEN); } static int process_one_packet(Tcl_Interp *interp) { packet_error = TCL_OK; if (pending) { packetin(interp, 0, 0, 0); } else { switch (filetype) { case TYPE_PCAP: if (pcap_dispatch(pcap_descriptor, 1, pcap_receiver, (u_char *)interp) == 0) { fileeof = 1; filetype = TYPE_UNKNOWN; } break; } } return packet_error; } /* * Read packets for one bin interval. * * Returns the current bin number. * * Returns -1 if EOF reached on the input file. */ static int fl_read_one_bin(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { int error; if (argc > 2) { Tcl_SetResult(interp, "Usage: fl_read_one_bin ?binsecs?", TCL_STATIC); return TCL_ERROR; } else if (argc == 2) { error = Tcl_GetInt(interp, argv[1], &binsecs); if (error != TCL_OK) { return error; } } else if (argc == 1) { ; /* use old binsecs */ } lastsignalled = signalled; /* reset ri statistics */ { u_long savesipg = ri.ri_tsipg; struct timeval savestart = ri.ri_endtime; memset(&ri, 0, sizeof ri); ri.ri_starttime = ZERO; ri.ri_tsipg = savesipg; ri.ri_starttime = savestart; /* one ends, next starts */ ri.ri_binno = -1; } if (!fileeof) { if (filetype == TYPE_UNKNOWN) { Tcl_SetResult(interp, "need to call fl_set_tcpd_file first", TCL_STATIC); return TCL_ERROR; } if (flow_types == 0) { Tcl_SetResult(interp, "need to call fl_set_flow_type first", TCL_STATIC); return TCL_ERROR; } while (((ri.ri_binno == -1) || (ri.ri_binno == NOW_AS_BINNO())) && (!fileeof) && (signalled == lastsignalled)) { error = process_one_packet(interp); if (error != TCL_OK) { return error; } } } if (TIME_EQ(&ri.ri_first_pkt_rcvd, &ZERO)) { Tcl_SetResult(interp, "", TCL_STATIC); } else { Tcl_SetResult(interp, ri_statistics(), tclasfree); } return TCL_OK; } static int set_flow_type(Tcl_Interp *interp, int ftype, int Ftype, int class, const char *name, char *new_flow_upcall, char *recv_upcall, char *timer_upcall) { char initial[MAX_FLOW_ID_BYTES*5], after[MAX_FLOW_ID_BYTES*5]; /* 5 rndm */ const char *curdesc; int bandm = 0; /* number of bytes in fti_bytes_and_mask used */ int indices = 0; /* index (in atoft) of each field in flow id */ atoft_p xp; ftinfo_p fti = &ftinfo[ftype]; /* forget current file type */ fti->fti_bytes_and_mask_len = 0; fti->fti_id_covers = 0; fti->fti_id_len = 0; curdesc = name; if (strlen(name) >= NUM(initial)) { Tcl_SetResult(interp, "flow name too long", TCL_STATIC); return TCL_ERROR; } while (*curdesc) { int j, n; n = sscanf(curdesc, "%[a-zA-Z0-9]%s", initial, after); if (n == 0) { break; } if (n == 1) { curdesc = ""; } else { curdesc = after+1; /* +1 to strip off delimiter */ } for (j = 0, xp = atoft; j < NUM(atoft); j++, xp++) { if (strcasecmp(xp->name, initial) == 0) { int off, firstbit, numbits, lastbit; u_long mask; off = xp->offset; firstbit = xp->firstbit; numbits = xp->numbits; while (numbits > 0) { if (bandm >= (2*MAX_FLOW_ID_BYTES)) { Tcl_SetResult(interp, "flow type specifier too long", TCL_STATIC); return TCL_ERROR; } if (off > fti->fti_id_covers) { fti->fti_id_covers = off; } mask = 0xff; lastbit = (firstbit+numbits) > 8 ? 7 : (firstbit+numbits-1); if (firstbit > 0) { mask = (mask<<(firstbit+24))>>(firstbit+24); } if (lastbit < 7) { mask = (mask>>(7-lastbit))<<(7-lastbit); } numbits -= (8-firstbit); firstbit = 0; fti->fti_bytes_and_mask[bandm++] = off++; fti->fti_bytes_and_mask[bandm++] = mask; } if (indices >= NUM(fti->fti_type_indices)) { Tcl_SetResult(interp, "too many fields in flow type specifier", TCL_STATIC); return TCL_ERROR; } fti->fti_type_indices[indices++] = j; break; } } if (j >= NUM(atoft)) { char *asret; asprintf(&asret, "Bad flow field name %s in \"%s\"\n", initial, name); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } } fti->fti_bytes_and_mask_len = bandm; fti->fti_id_len = bandm/2; fti->fti_type_indices_len = indices; fti->fti_class = class; fti->fti_parent_ftype = Ftype; if (fti->fti_new_flow_upcall) { free(fti->fti_new_flow_upcall); } fti->fti_new_flow_upcall = new_flow_upcall; if (fti->fti_recv_upcall) { free(fti->fti_recv_upcall); } fti->fti_recv_upcall = recv_upcall; if (fti->fti_timer_upcall) { free(fti->fti_timer_upcall); } fti->fti_timer_upcall = timer_upcall; return TCL_OK; } /* * set a flow type. * * the caller manages the index since the way the system * works, an incoming packet will be mapped to a specific * flow type in a way which is dependent on the flow type * index. */ static int fl_set_flow_type(ClientData clientData, Tcl_Interp *interp, int argc, char const *argv[]) { int error; int ftype, Ftype, class; char *new_flow_upcall, *recv_upcall, *timer_upcall; char *asret; static char *usage = "Usage: fl_set_flow_type " "?-n new_flow_command? ?-r recv_command? " "?-t timer_command? ?-c default_class? ?-f flow_type? " "?-F default_parent_flow_type? specifier"; int op; extern char *optarg; extern int optind, opterr; ftype = 0; Ftype = 0; class = 0; new_flow_upcall = 0; recv_upcall = 0; timer_upcall = 0; opterr = 0; optind = 1; while ((op = getopt(argc, (char *const *)argv, "c:f:F:n:r:t:")) != EOF) { /* XXX ugly cast */ switch (op) { case 'c': class = atoi(optarg); break; case 'f': ftype = atoi(optarg); break; case 'F': Ftype = atoi(optarg); break; case 'n': new_flow_upcall = strsave(optarg); if (new_flow_upcall == 0) { Tcl_SetResult(interp, "malloc failed", TCL_STATIC); return TCL_ERROR; } break; case 'r': recv_upcall = strsave(optarg); if (recv_upcall == 0) { Tcl_SetResult(interp, "malloc failed", TCL_STATIC); return TCL_ERROR; } break; case 't': timer_upcall = strsave(optarg); if (timer_upcall == 0) { Tcl_SetResult(interp, "malloc failed", TCL_STATIC); return TCL_ERROR; } break; default: Tcl_SetResult(interp, usage, TCL_STATIC); return TCL_ERROR; /*NOTREACHED*/ } } argc -= optind; argv += optind; if (argc != 1) { Tcl_SetResult(interp, usage, TCL_STATIC); return TCL_ERROR; } if (ftype >= NUM(ftinfo)) { Tcl_SetResult(interp, "flow_type higher than maximum", TCL_STATIC); return TCL_ERROR; } error = set_flow_type(interp, ftype, Ftype, class, argv[0], new_flow_upcall, recv_upcall, timer_upcall); if (error != TCL_OK) { return error; } flow_types = 1; /* got a flow type */ asprintf(&asret, "%d", ftype); Tcl_SetResult(interp, asret, tclasfree); return TCL_OK; } static int fl_class_stats(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { class_p clsp; if (argc != 2) { Tcl_SetResult(interp, "Usage: fl_class_stats class", TCL_STATIC); return TCL_ERROR; } if (atoi(argv[1]) >= NUM(classes)) { Tcl_SetResult(interp, "class too high", TCL_STATIC); return TCL_ERROR; } clsp = &classes[atoi(argv[1])]; Tcl_SetResult(interp, class_statistics(clsp), TCL_VOLATILE); return TCL_OK; } /* * set up to enumerate the classes. */ static int fl_start_class_enumeration(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { class_enum_state = NULL; return TCL_OK; } /* * in order for flow-within-class enumeration to work, it's important * that class_enum_state, at *exit* from * fl_continue_class_enumeration, point at the most recently accessed * class structure. */ static int fl_continue_class_enumeration(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { class_p cl; while (class_enum_state != LAST(classes)) { if (class_enum_state == NULL) { class_enum_state = &classes[0]; } else { class_enum_state++; } cl = class_enum_state; if (class_enum_state >= &classes[NUM(classes)]) { class_enum_state = 0; } if (cl->cls_last_bin_active == ri.ri_binno) { Tcl_SetResult(interp, class_statistics(cl), TCL_VOLATILE); /* now, clear stats for next go round... */ /* but, preserve sipg and last rcvd... */ memset(&cl->cls_ri, 0, sizeof cl->cls_ri); cl->cls_last_bin_active = ri.ri_binno; return TCL_OK; } } Tcl_SetResult(interp, "", TCL_STATIC); return TCL_OK; } /* * set up to enumerate the flows. */ static int fl_start_flow_enumeration(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { flow_enum_state = table; return TCL_OK; } static int fl_continue_flow_enumeration(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { int class; if (argc == 2) { /* for a specific class */ /* XXX do some argument testing */ class = class_enum_state-classes; /* find id of currently * enumerated class */ } else { class = -1; } while (flow_enum_state) { if ((flow_enum_state->fe_last_bin_active == ri.ri_binno) && ((class == -1) || (class == flow_enum_state->fe_class))) { Tcl_SetResult(interp, flow_statistics(flow_enum_state), TCL_VOLATILE); flow_enum_state->fe_pkts_last_enum = flow_enum_state->fe_pkts; flow_enum_state->fe_bytes_last_enum = flow_enum_state->fe_bytes; flow_enum_state = flow_enum_state->fe_next_in_table; return TCL_OK; } flow_enum_state = flow_enum_state->fe_next_in_table; } Tcl_SetResult(interp, "", TCL_STATIC); return TCL_OK; } static int set_tcpd_file(ClientData clientData, Tcl_Interp *interp, const char *filename) { char *asret; /* * need to do this here (rather than in newfile()), because * we are about to overwrite pcap_descriptor. */ if (filetype == TYPE_PCAP) { pcap_close(pcap_descriptor); pcap_descriptor = 0; } pcap_descriptor = pcap_open_offline(filename, pcap_errbuf); if (pcap_descriptor == 0) { asprintf(&asret, "%s", pcap_errbuf); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } pcap_dlt = pcap_datalink(pcap_descriptor); pcap_snap = pcap_snapshot(pcap_descriptor); switch (pcap_dlt) { case DLT_EN10MB: pcap_receiver = receive_tcpd_en10mb; break; case DLT_SLIP: pcap_receiver = receive_tcpd_slip; break; case DLT_PPP: pcap_receiver = receive_tcpd_ppp; break; case DLT_FDDI: pcap_receiver = receive_tcpd_fddi; break; case DLT_NULL: pcap_receiver = receive_tcpd_null; break; default: asprintf(&asret, "unknown data link type %d", pcap_dlt); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } if (newfile(interp, pcap_snap) != TCL_OK) { return TCL_ERROR; } filetype = TYPE_PCAP; return TCL_OK; } static int fl_set_file(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { static char *usage = "Usage: fl_set_file filename"; if (argc < 2) { Tcl_SetResult(interp, usage, TCL_STATIC); return TCL_ERROR; } return set_tcpd_file(clientData, interp, argv[1]); } static int fl_set_ll_classifier(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { llcl_p llcl; if ((argc < 2) || (argc > 3)) { Tcl_SetResult(interp, "Usage: fl_set_ll_classifier ll_classifier_index " "[associated_flow_type_index]", TCL_STATIC); return TCL_ERROR; } llcl = &llclasses[atoi(argv[1])]; if (llcl >= &llclasses[NUM(llclasses)]) { Tcl_SetResult(interp, "fl_set_ll_classifier ll_classifier_index too high", TCL_STATIC); return TCL_ERROR; } if (argc == 3) { llcl->llcl_inuse = 1; llcl->llcl_fti = atoi(argv[2]); if (llcl->llcl_fti >= NUM(ftinfo)) { llcl->llcl_inuse = 0; Tcl_SetResult(interp, "fl_set_ll_classifier associated_flow_type_index too high", TCL_STATIC); return TCL_ERROR; } } else { llcl->llcl_inuse = 0; } return TCL_OK; } static int fl_tcl_code(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { if (argc != 1) { Tcl_SetResult(interp, "Usage: fl_tcl_code", TCL_STATIC); return TCL_ERROR; } Tcl_SetResult(interp, fl_tclprogram, TCL_STATIC); return TCL_OK; } static int fl_stats_format(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { char *new, **current, *template, *asret; int templatep = 0; static char *usage = \ "Usage: fl_stats_format {class|flow|ri} {current|template} [newformat]"; if ((argc != 3) && (argc != 4)) { asprintf(&asret, "not the right number of arguments (%d given)\n%s", argc, usage); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } if (!strcasecmp(argv[1], "class")) { current = &class_stats_format; template = class_stats_template; } else if (!strcasecmp(argv[1], "flow")) { current = &flow_stats_format; template = flow_stats_template; } else if (!strcasecmp(argv[1], "ri")) { current = &ri_stats_format; template = ri_stats_template; } else { asprintf(&asret, "unknown kind \"%s\", looking for {class|flow|ri}.\n%s", argv[1], usage); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } if (!strcasecmp(argv[2], "current")) { templatep = 0; } else if (!strcasecmp(argv[2], "template")) { templatep = 1; } else { asprintf(&asret, "unknown instance \"%s\", looking for {current|template}\n%s", argv[2], usage); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } if (argc == 3) { if (templatep) { Tcl_SetResult(interp, template, TCL_VOLATILE); } else { Tcl_SetResult(interp, *current, TCL_VOLATILE); } } else { /* argc == 4 */ if (templatep) { Tcl_SetResult(interp, "[fl_stats_format]: can\'t change \"template\"", TCL_STATIC); return TCL_ERROR; } new = strsave(argv[3]); if (new == 0) { Tcl_SetResult(interp, "fl_stats_format: unable to allocate space for new format", TCL_STATIC); return TCL_ERROR; } free(*current); *current = new; } return TCL_OK; } static int fl_catch_signal(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { struct sigaction act, oact; char *asret; act.sa_handler = gotsignal; if (sigemptyset(&act.sa_mask) == -1) { asprintf(&asret, "sigemptyset: %s", strerror(errno)); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } act.sa_flags = SA_RESTART; /* w/out this, we take only one * signal, die on next */ if (sigaction(SIGUSR1, &act, &oact) == -1) { asprintf(&asret, "sigaction: %s", strerror(errno)); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } return TCL_OK; } static delta_t delta_decode(const char *string) { if (!strcasecmp(string, "absolute")) { return absolute; } else if (!strcasecmp(string, "within_tr")) { return within_tr; } else if (!strcasecmp(string, "within_ri")) { return within_ri; } else { return invalid; } } static int fl_time_base(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { static char usage[] = "Usage: fl_time_base {absolute|within_tr} {absolute|within_tr|within_ri}"; char *asret; delta_t l_delta_wi, l_delta_ri; if (argc != 3) { /* XXX return current settings... */ Tcl_SetResult(interp, usage, TCL_STATIC); return TCL_ERROR; } l_delta_ri = delta_decode(argv[1]); l_delta_wi = delta_decode(argv[2]); if ((l_delta_ri == invalid) || (l_delta_ri == within_ri)) { asprintf(&asret, "invalid \"reporting interval\" delta parameter: %s.\n%s\n", argv[1], usage); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } if (l_delta_wi == invalid) { asprintf(&asret, "invalid \"within\" delta parameter: %s.\n%s\n", argv[2], usage); Tcl_SetResult(interp, asret, tclasfree); return TCL_ERROR; } delta_wi = l_delta_wi; delta_ri = l_delta_ri; return TCL_OK; } static int fl_version(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { if (argc != 1) { Tcl_SetResult(interp, "Usage: fl_set_version", TCL_STATIC); return TCL_ERROR; } Tcl_SetResult(interp, flstats_c_rcsid, TCL_STATIC); return TCL_OK; } int Tcl_AppInit(Tcl_Interp *interp) { #if 0 /* We *don't* call Tcl_Init(), since that requires Tcl to be * installed on the execution machine (and, we want to run * on lots of execution machines, requiring as little as * possible on each machine). */ if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* 0 */ Tcl_CreateCommand(interp, "fl_catch_signal", fl_catch_signal, NULL, NULL); Tcl_CreateCommand(interp, "fl_class_stats", fl_class_stats, NULL, NULL); Tcl_CreateCommand(interp, "fl_continue_class_enumeration", fl_continue_class_enumeration, NULL, NULL); Tcl_CreateCommand(interp, "fl_continue_flow_enumeration", fl_continue_flow_enumeration, NULL, NULL); Tcl_CreateCommand(interp, "fl_time_base", fl_time_base, NULL, NULL); Tcl_CreateCommand(interp, "fl_read_one_bin", fl_read_one_bin, NULL, NULL); Tcl_CreateCommand(interp, "fl_set_file", fl_set_file, NULL, NULL); Tcl_CreateCommand(interp, "fl_set_flow_type", fl_set_flow_type, NULL, NULL); Tcl_CreateCommand(interp, "fl_set_ll_classifier", fl_set_ll_classifier, NULL, NULL); Tcl_CreateCommand(interp, "fl_start_class_enumeration", fl_start_class_enumeration, NULL, NULL); Tcl_CreateCommand(interp, "fl_start_flow_enumeration", fl_start_flow_enumeration, NULL, NULL); Tcl_CreateCommand(interp, "fl_stats_format", fl_stats_format, NULL, NULL); Tcl_CreateCommand(interp, "fl_tcl_code", fl_tcl_code, NULL, NULL); Tcl_CreateCommand(interp, "fl_version", fl_version, NULL, NULL); /* call out to Tcl to set up whatever... */ if (Tcl_GlobalEval(interp, fl_tclprogram) != TCL_OK) { return TCL_ERROR; } return Tcl_VarEval(interp, "fl_startup ", argcount, " { ", args, " }", (char *) NULL); } int main(int argc, char *const argv[]) { int i; for (i = 0; i < NUM(timers); i++) { timers[i].fe_next_in_timer = timers[i].fe_prev_in_timer = &timers[i]; } protohasports[6] = protohasports[17] = 1; flow_stats_format = strsave(flow_stats_template); class_stats_format = strsave(class_stats_template); ri_stats_format = strsave(ri_stats_template); delta_wi = delta_ri = absolute; if ((flow_stats_format == 0) || (class_stats_format == 0)) { fprintf(stderr, "%s:%d: no room for allocating formats\n", __FILE__, __LINE__); exit(1); } args = Tcl_Merge(argc-1, (const char *const *)(argv+1)); /* XXX ugly cast */ sprintf(argcount, "%d", argc-1); /* we lie to Tcl_Main(), because, by gum, *WE* control argument parsing */ Tcl_Main(1, (char **)argv, Tcl_AppInit); /* XXX ugly cast */ exit(0); } /* * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Ipsilon Networks, Inc. * 4. The name of Ipsilon Networks, Inc., may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY IPSILON NETWORKS, INC., ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IPSILON NETWORKS, INC., BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
greg-minshall/flstats
flstats.h
/* * Copyright (c) 1996 * Ipsilon Networks, Inc. * * please see terms and conditions of copyright at the end of this file * */ /* * output flow statistics from a tcpdump file. * */ static char *flstats_h_rcsid = "$Id: 004d9c199d7b5d469bd612f292de926b6df18ef6 $"; /* global preprocessor defines */ #define MAX_PACKET_SIZE 1518 #define MAX_FLOW_ID_BYTES 30 /* maximum number of bytes in flow id */ /* number of elements in an array */ #define NUM(a) (sizeof (a)/sizeof ((a)[0])) /* maximum index for an array */ #define MAXINDEX(a) (NUM((a))-1) /* last element of an array */ #define LAST(a) (&(a)[MAXINDEX(a)]) #define MIN(a,b) ((a) < (b) ? (a):(b)) #define PICKUP_NETSHORT(p) ((((u_char *)p)[0]<<8)|((u_char *)p)[1]) #define TIME_ADD(r,a,b) { \ (r)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (r)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((r)->tv_usec >= 1000000) { /* deal with carry */ \ (r)->tv_sec++; \ (r)->tv_usec -= 1000000; \ } \ } #define TIME_LE(a,b) \ (((a)->tv_sec < (b)->tv_sec) \ || (((a)->tv_sec == (b)->tv_sec) && \ ((a)->tv_usec <= (b)->tv_usec))) #define TIME_LT(a,b) \ (((a)->tv_sec < (b)->tv_sec) \ || (((a)->tv_sec == (b)->tv_sec) && \ ((a)->tv_usec < (b)->tv_usec))) #define TIME_GE(a,b) (!TIME_LT((a),(b))) #define TIME_EQ(a,b) \ (((a)->tv_sec == (b)->tv_sec) && \ ((a)->tv_usec == (b)->tv_usec)) #define TIMEDIFFSECS(now,then) \ (((now)->tv_sec-(then)->tv_sec) -\ ((now)->tv_usec < (then)->tv_usec ? 1 : 0)) #define TIMEDIFFUSECS(now,then) \ (((now)->tv_usec-(then)->tv_usec) +\ ((now)->tv_usec < (then)->tv_usec ? 1000000 : 0)) #define NOW_AS_BINNO() (binsecs == 0 ? signalled : \ (TIMEDIFFSECS(&curtime, &starttime)/binsecs)) #define FLOW_ID_FROM_HDR(fid,hdr,ftip) { \ int i, j; \ for (i = 0, j = 0; j < ftip->fti_bytes_and_mask_len; i++, j += 2) { \ (fid)[i] = (hdr)[ftip->fti_bytes_and_mask[j]] \ &ftip->fti_bytes_and_mask[j+1]; \ } \ } #define SIPG_TO_SECS(x) (((x)>>3)/1000000) #define SIPG_TO_USECS(x) (((x)>>3)%1000000) #define SECS_USECS_TO_SIPG(s,u) ((((s)*1000000)+(u))<<3) /* Types of input files to be processed */ #define TYPE_UNKNOWN 0 #define TYPE_PCAP 2 /* type defines */ /* * This is the basic hash table entry. */ typedef struct flowentry flowentry_t, *flowentry_p; struct flowentry { /* fields for application use */ u_short fe_flow_type, /* which flow type is this? */ fe_class, /* class of this flow */ fe_parent_ftype, /* parent's flow type */ fe_parent_class; /* parent's class */ u_long fe_pkts, /* number of packets received */ fe_pkts_last_enum, /* number of packets *last* time enum done */ fe_bytes, /* number of bytes received */ fe_bytes_last_enum, /* number of bytes *last* time enum done */ fe_sipg, /* smoothed interpacket gap (units of 8 usec) */ fe_last_bin_active, /* last bin this saw activity */ fe_upcall_when_pkts_ge, /* num pkts needs to be >= m */ fe_upcall_when_sipg_lt; /* sipg needs to be < p */ /* (0xffffffff ==> ignore sipg) */ /* (0 ==> never call out) */ struct timeval fe_created, /* time created */ fe_last_pkt_rcvd, /* time most recent packet seen */ fe_upcall_when_secs_ge, /* recv_upcall won't run till this time */ fe_timer_time; /* time to run timer routine */ /* fields for hashing */ u_short fe_sum, /* hash of id, speeds up searching */ fe_id_len; /* length of id */ u_char *fe_id; /* id of this flow entry */ flowentry_p fe_next_in_bucket, fe_prev_in_bucket, fe_next_in_table, fe_prev_in_table, fe_next_in_timer, fe_prev_in_timer; }; /* * At the lower level, application-defined "classes" are merely * known as a place to record some statistics. Flow types and * flows map into classes. * * At this lower level, there is *no* representation of policy. * Instead, various policy parameters are set into the flow * type and/or flow entry structures. * * (If the *classifier* were moved into the lower level, then we * would represent policies specifically here.) */ typedef struct cls_ri_stats { u_long cls_ri_created, /* num flows created in this class */ cls_ri_deleted, /* num flows created in this class */ cls_ri_added, /* num flows added to this class */ cls_ri_removed, /* num flows removed from this class */ cls_ri_active, /* flows active this interval */ cls_ri_pkts, /* packets read */ cls_ri_bytes; /* bytes read */ } cls_ri_stats_t, *cls_ri_stats_p; typedef struct class { u_char cls_type_indices[MAX_FLOW_ID_BYTES]; int cls_type_indices_len; u_long cls_sipg, cls_last_bin_active; /* last bin this class saw activity */ struct timeval cls_last_pkt_rcvd; /* time last packet received in class */ cls_ri_stats_t cls_ri; } class_t, *class_p; /* * reporting interval structure * * only one, but defining for ease of use */ typedef struct ri { u_long ri_binno, /* current ri bin number */ ri_pkts, /* number of packets received this ri */ ri_bytes, /* number of bytes seen this ri */ ri_isipg, /* smoothed ipg (w/in this ri) */ ri_tsipg, /* smoothed ipg (w/in trace) */ ri_ipv6pkts, /* IPv6 packets */ ri_ipv6bytes, /* IPv6 bytes */ ri_nonippkts, /* not an IP packet (so, didn't even classify) */ ri_nonipbytes, /* bytes of same */ ri_unclpkts, /* packets that didn't match any class */ ri_unclbytes, /* bytes that didn't match any class */ /* the following are all included in above "uncl" */ ri_fragpkts, /* fragments seen (using ports) */ ri_fragbytes, /* bytes seen in those frags */ ri_toosmallpkts, /* packet length too small */ ri_toosmallbytes, /* bytes seen in those frags */ ri_runtpkts, /* captured portion too small */ ri_runtbytes, /* bytes seen in those frags */ ri_noportpkts, /* packet had no ports (but needed) */ ri_noportbytes; /* bytes seen in those frags */ struct timeval ri_starttime, /* time this ri started */ ri_first_pkt_rcvd, /* time first packet received this ri */ ri_last_pkt_rcvd, /* time last packet received this ri */ ri_endtime; /* time this ri ended */ } ri_t, *ri_p; /* * The following represents a flow type. A flow type defines * the bits in the header used to separate packets into different * flows (within the same flow type). * * The way things work here is that the lower level turns incoming * packets into flows within a given flow type (based on a very * simple classifier which tries to match the packet with the most * specific flow type; this classifier knows about port numbers, * for example). Then, if this is * a new flow, it will call into the upper level. The upper level * can then specify a *different* flow type for packets of this * flow (in addition to some other parameters for this flow). * In essence, the more specific lower level flow is used to map * incoming packets into a higher level flow type. One constraint * in doing this is that two packets which are in the same * *lower level* flow * cannot be in two *different* higher * level flows. * * The lower level *keeps* its specific flow entry, and points * it at the flow entry specified by the upper level. Future * packets received at the specific flow are thus correlated * with the higher level flow without any interaction with the * higher level. * * When the upper level enumerates flows, it doesn't see any of * these more-specific lower level flows. * * (Note, however, that the upper level can indicate that the * flow type used by the lower level is the same flow type which * the upper level would like to use for a flow. In this case, * enumerating the flows will cause that flow entry to be revealed.) * * To aid in this separation between lower-level and higher-level * flow types, the low-level classifier tries to fit the packet * into flow types starting at index 0, and stops when it runs * into a flow type that hasn't been initialized. Thus, the * application can initialize the lower-level flow types, leave * a gap, and then initialize upper-level flow types, knowing * that the packet receive routine won't ever use "its" flow * types. (In practice, this may not be needed at all.) * Fragmentation is painful here, since packets that *should* be * in a more-specific (i.e., including ports) flow type will be * classified in a less-specific flow type. */ typedef struct ftinfo ftinfo_t, *ftinfo_p; struct ftinfo { u_char fti_type_indices[MAX_FLOW_ID_BYTES], fti_bytes_and_mask[2*MAX_FLOW_ID_BYTES]; int fti_bytes_and_mask_len, fti_type_indices_len, fti_id_len, /* length of a flow id for this type */ fti_id_covers, /* how far into pkt hdr the flow id reaches */ fti_class, /* default class (overridable by upcall) */ fti_parent_ftype; /* default PARENT flow type (ditto) */ char *fti_new_flow_upcall; /* * routine: fti_new_flow_upcall * call: "fti_new_flow_upcall class flowindex flowtype flowid" * result: "class upper_class upper_ftype recvsecs.usecs" * revcpkts recvsipg.usecs timersecs.usecs" * * 'class' is the class of the new flow. 'upper_class' * is the class for any parent flow that might be created. * 'upper_ftype' is the flow type for a created parent flow. * recvsecs.usecs after the current time in the output flow, * a received packet will cause the flow types receive routine * to be called if recvpkts have been received and the smoothed * inter-packet gap is less that recvsipg.usecs. timersecs.usecs * from now, the flow type's timer routine will be called for * this flow. */ char *fti_recv_upcall; /* command to call when a pkt received */ /* * routine: recv_upcall * call: "recv_upcall FLOW flowstats" * result: "class recvsecs.usecs recvpkts sipgsecs.usecs" * * if, on output, recvsecs is null (i.e., not returned), * then the recv_upcall will be made when the next packet * in this flow is received. */ char *fti_timer_upcall; /* timer command (if registered) */ /* * routine: timer_upcall * call: "timer_upcall timesecs.usecs FLOW flowstats" * result: "command secs.usecs" * * if "command" is "DELETE", the associated flow will be * deleted. if "command" starts with '-', it will be ignored. * other values for "command" are TBD. * * if the flow is not deleted, the next timer upcall will * be made "secs.usecs" from the current time. (A returned * value of "0" inhibits future timer upcalls for this flow.) */ }; #define FTI_USES_PORTS(p) ((p)->fti_id_covers > 20) #define FTI_UNUSED(p) ((p)->fti_id_len == 0) typedef struct llcl { int llcl_inuse; int llcl_fti; /* flow type index */ } llcl_t, *llcl_p; #define LLCL_UNUSED(p) ((p)->llcl_inuse == 0) /* * This describes the IP header and relevant fields of TCP/UDP header. * * This is used for translating flow_types to an internal form (and * going backwards). * * This is also used for turning flowids into ascii, as well as * packet headers into ascii. For the latter application, it is important * that the elements in the array 'atoft' be specified in the order in * which they occur in the packet header. */ typedef struct { char *name; /* external name */ u_char offset, /* where in header */ firstbit, /* where the first bit is (0 == MSB) */ numbits, /* number of bits */ fmt; /* format for output (see below) */ } atoft_t, *atoft_p; #define FMT_DECIMAL 0 /* 123 */ #define FMT_DOTTED 1 /* 1.2.3.4 (i.e., IP addresses) */ #define FMT_HEX 2 /* 0x2a */ atoft_t atoft[] = { { "ihv", 0, 0, 4 }, { "ihl", 0, 4, 4 }, { "tos", 1, 0, 8 }, { "len", 2, 0, 16 }, { "id", 4, 0, 16 }, { "df", 6, 1, 1}, { "mf", 6, 2, 1}, { "foff", 6, 3, 13}, { "ttl", 8, 0, 8}, { "prot", 9, 0, 8}, { "sum", 10, 0, 16}, { "src", 12, 0, 32, FMT_DOTTED}, { "dst", 16, 0, 32, FMT_DOTTED}, { "src8", 12, 0, 8, FMT_DOTTED}, { "dst8", 16, 0, 8, FMT_DOTTED}, { "src16", 12, 0, 16, FMT_DOTTED}, { "dst16", 16, 0, 16, FMT_DOTTED}, { "src24", 12, 0, 24, FMT_DOTTED}, { "dst24", 16, 0, 24, FMT_DOTTED}, { "src32", 12, 0, 32, FMT_DOTTED}, { "dst32", 16, 0, 32, FMT_DOTTED}, { "sport", 20, 0, 16}, { "dport", 22, 0, 16} }; #if !defined(FDDIFC_LLC_ASYNC) /* * if we can't find any FDDI header files... */ struct fddi_header { u_char fddi_fc; u_char fddi_dhost[6]; /* destination */ u_char fddi_shost[6]; /* source */ }; #define FDDIFC_LLC_ASYNC 0x50 #endif /* !defined(FDDIFC_LLC_ASYNC) */ #if !defined(FDDIFC_CLFF) #define FDDIFC_CLFF 0xf0 /* length/class/format bits */ #endif /* !defined(FDDIFC_CLFF) */ #if !defined(LLC_UI) /* * if we can't find LLC header files... * * (this is a very minimal LLC header, sufficient only for our * limited needs.) */ struct llc { u_char llc_dsap; /* source SAP (service access point) */ u_char llc_ssap; /* destination SAP */ u_char llc_control; /* control byte (in some frames) */ }; #define LLC_UI 0x03 /* this is an unnumbered info frame */ #define LLC_SNAP_LSAP 0xaa /* SNAP SAP */ #endif /* !defined(LLC_UI) */ /* * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Ipsilon Networks, Inc. * 4. The name of Ipsilon Networks, Inc., may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY IPSILON NETWORKS, INC., ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IPSILON NETWORKS, INC., BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
MyDevNote/Estrutura-de-dados
alocacaode_memoria.c
# include <stdio.h> int main(){ int x = 25; // A variável x é iniciada com valor 25 int* y = &x; // A variável y recebe o endereço onde a variável x esta alocada *y = 30; int a = sizeof(int); printf("%i %i %i", *y, &x, a); return 0; }
MyDevNote/Estrutura-de-dados
aula_07.c
void void main(){ insere(10, lista); } void insere(int nr, struct no *) void exibir(struct no *plista){ struct no *aux; aux = plista; if(aux!=NULL){ while(aux != NULL){ printf("[%x] %d -> %x\n", aux, aux->info, aux->prox); aux = aux->prox; } } else{ printf("A lista esta vazia\n"); } }
MyDevNote/Estrutura-de-dados
Funcao_maloc.c
<reponame>MyDevNote/Estrutura-de-dados // Função Malloc # include <stdio.h> # include <malloc.h> int main() { int* y = (int*) malloc(sizeof(int)); *y = 20; int z = sizeof(int); printf("*y= %i z= %i\n ymalloc= %i", *y, z,y); return 0; }
MyDevNote/Estrutura-de-dados
teste.c
#define TAM 10000 main() { int inicio, final, tempo_decorrido; int vetor[TAM],x,y,aux; x = 0; y = 0; aux = 0; printf("\nGerando um vetor com %d inteiros aleatorios:\n",TAM); for(x = 0; x < TAM; x++ ) { vetor[x] = rand() % 100; printf("%d\t", vetor[x]); } getchar(); inicio = GetTickCount(); for( x = 0; x < TAM; x++ ) { for( y = x + 1; y < TAM; y++ ) { if ( vetor[x] > vetor[y] ) { aux = vetor[x]; vetor[x] = vetor[y]; vetor[y] = aux; } } } final = GetTickCount(); tempo_decorrido = final - inicio; printf("\nTempo de Ordenacao = : %d milisegundos ",tempo_decorrido); getchar(); printf("\nVetor Ordenado\n "); for( x = 0; x < TAM; x++ ) printf("%d\t",vetor[x]); system("pause"); }
Millionaryearl/CW2DTable
Pod/Classes/CW2DTableVC.h
<gh_stars>1-10 // // TwoDStatisticVController.h // SmartOrder-V2 // // Created by millionaryearl on 14-5-9. // Copyright (c) 2014年 Shanghai AgileMobi Co., Ltd. All rights reserved. // #import <UIKit/UIKit.h> #import "CW2DTableLayout.h" @interface CW2DTableVC : UICollectionViewController <UIPopoverControllerDelegate> @property (assign, nonatomic) IBOutlet UISegmentedControl *rltTypeSwitchBtn; @property (strong, nonatomic) NSDictionary *dicRecd; @end
Millionaryearl/CW2DTable
CW2DTableLayoutStyle4.h
// // CW2DTableLayoutStyle4.h // Pods // // Created by millionaryearl on 14/12/4. // // #import <UIKit/UIKit.h> @interface CW2DTableLayoutStyle4 : UICollectionViewLayout @property (nonatomic)UIOffset itemOffSet; @end
Millionaryearl/CW2DTable
CW2DTableVC4.h
<gh_stars>1-10 // // CW2DTableVC4.h // Pods // // Created by millionaryearl on 14/12/4. // // #import <UIKit/UIKit.h> @interface CW2DTableVC4 : UICollectionViewController @end
Millionaryearl/CW2DTable
Pod/Classes/CW2DTableCell.h
// // TwoDContentCell.h // SmartOrder-V2 // // Created by millionaryearl on 14-5-9. // Copyright (c) 2014年 Shanghai AgileMobi Co., Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface CW2DTableCell : UICollectionViewCell @property(nonatomic,strong)IBOutlet UILabel *nameLabel; @end
Millionaryearl/CW2DTable
CW2DTableVC3.h
<filename>CW2DTableVC3.h // // CW2DTableVC3.h // Pods // // Created by millionaryearl on 14/12/2. // // #import <UIKit/UIKit.h> @interface CW2DTableVC3 : UICollectionViewController @end
Millionaryearl/CW2DTable
Example/CW2DTable/CWAppDelegate.h
<reponame>Millionaryearl/CW2DTable<filename>Example/CW2DTable/CWAppDelegate.h // // CWAppDelegate.h // CW2DTable // // Created by CocoaPods on 07/29/2014. // Copyright (c) 2014 Millionaryearl. All rights reserved. // #import <UIKit/UIKit.h> @interface CWAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
Millionaryearl/CW2DTable
CW2DTabeLayoutStyle3.h
<filename>CW2DTabeLayoutStyle3.h // // CW2DTabeLayoutStyle3.h // Pods // // Created by millionaryearl on 14/12/2. // // #import <UIKit/UIKit.h> @interface CW2DTabeLayoutStyle3 : UICollectionViewLayout @property (nonatomic)UIOffset itemOffSet; @end
Millionaryearl/CW2DTable
CW2DTableVC2.h
<gh_stars>1-10 // // CW2DTableVC2.h // Pods // // Created by millionaryearl on 14/11/26. // // #import <Foundation/Foundation.h> #import "CW2DTableLayoutStyle2.h" @interface CW2DTableVC2 : UICollectionViewController @end
Millionaryearl/CW2DTable
Pod/Classes/CW2DTableLayout.h
// // TwoDStatisticLayout.h // SmartOrder-V2 // // Created by millionaryearl on 14-5-9. // Copyright (c) 2014年 Shanghai AgileMobi Co., Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface CW2DTableLayout : UICollectionViewLayout @property (nonatomic)UIOffset itemOffSet; @end
tvl83/fio
libraries/wasm-jit/Include/Emscripten/Emscripten.h
<filename>libraries/wasm-jit/Include/Emscripten/Emscripten.h #pragma once #ifndef EMSCRIPTEN_API #define EMSCRIPTEN_API DLL_IMPORT #endif #include <vector> namespace IR { struct Module; } namespace Runtime { struct ModuleInstance; } namespace Emscripten { EMSCRIPTEN_API void initInstance(const IR::Module &module, Runtime::ModuleInstance *moduleInstance); EMSCRIPTEN_API void injectCommandArgs(const std::vector<const char *> &argStrings, std::vector <Runtime::Value> &outInvokeArgs); }
tvl83/fio
libraries/wasm-jit/Include/Logging/Logging.h
#pragma once #ifndef LOGGING_API #define LOGGING_API DLL_IMPORT #endif #include "Inline/BasicTypes.h" #include "Platform/Platform.h" // Debug logging. namespace Log { // Allow filtering the logging by category. enum class Category { error, debug, metrics, num }; LOGGING_API void setCategoryEnabled(Category category, bool enable); LOGGING_API bool isCategoryEnabled(Category category); // Print some categorized, formatted string, and flush the output. Newline is not included. LOGGING_API void printf(Category category, const char *format, ...); };
tvl83/fio
libraries/wasm-jit/Source/Runtime/LLVMJIT.h
<reponame>tvl83/fio #pragma once #include "Inline/BasicTypes.h" #include "Platform/Platform.h" #include "RuntimePrivate.h" #include "Intrinsics.h" #ifdef _WIN32 #pragma warning(push) #pragma warning (disable:4267) #pragma warning (disable:4800) #pragma warning (disable:4291) #pragma warning (disable:4244) #pragma warning (disable:4351) #pragma warning (disable:4065) #pragma warning (disable:4624) #pragma warning (disable:4245) // conversion from 'int' to 'unsigned int', signed/unsigned mismatch #pragma warning(disable:4146) // unary minus operator applied to unsigned type, result is still unsigned #pragma warning(disable:4458) // declaration of 'x' hides class member #pragma warning(disable:4510) // default constructor could not be generated #pragma warning(disable:4610) // struct can never be instantiated - user defined constructor required #pragma warning(disable:4324) // structure was padded due to alignment specifier #pragma warning(disable:4702) // unreachable code #endif #include "llvm/Analysis/Passes.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/RTDyldMemoryManager.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Verifier.h" #include "llvm/IR/ValueHandle.h" #include "llvm/IR/DebugLoc.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Object/SymbolSize.h" #include "llvm/Support/Debug.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Host.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Transforms/Scalar.h" #include "llvm/IR/DIBuilder.h" #include <cctype> #include <string> #include <vector> #ifdef _WIN32 #undef and #undef or #undef xor #pragma warning(pop) #endif namespace LLVMJIT { // The global LLVM context. extern llvm::LLVMContext context; // Maps a type ID to the corresponding LLVM type. extern llvm::Type *llvmResultTypes[(Uptr) ResultType::num]; extern llvm::Type *llvmI8Type; extern llvm::Type *llvmI16Type; extern llvm::Type *llvmI32Type; extern llvm::Type *llvmI64Type; extern llvm::Type *llvmF32Type; extern llvm::Type *llvmF64Type; extern llvm::Type *llvmVoidType; extern llvm::Type *llvmBoolType; extern llvm::Type *llvmI8PtrType; #if ENABLE_SIMD_PROTOTYPE extern llvm::Type* llvmI8x16Type; extern llvm::Type* llvmI16x8Type; extern llvm::Type* llvmI32x4Type; extern llvm::Type* llvmI64x2Type; extern llvm::Type* llvmF32x4Type; extern llvm::Type* llvmF64x2Type; #endif // Zero constants of each type. extern llvm::Constant *typedZeroConstants[(Uptr) ValueType::num]; // Converts a WebAssembly type to a LLVM type. inline llvm::Type *asLLVMType(ValueType type) { return llvmResultTypes[(Uptr) asResultType(type)]; } inline llvm::Type *asLLVMType(ResultType type) { return llvmResultTypes[(Uptr) type]; } // Converts a WebAssembly function type to a LLVM type. inline llvm::FunctionType *asLLVMType(const FunctionType *functionType) { auto llvmArgTypes = (llvm::Type **) alloca(sizeof(llvm::Type *) * functionType->parameters.size()); for (Uptr argIndex = 0; argIndex < functionType->parameters.size(); ++argIndex) { llvmArgTypes[argIndex] = asLLVMType(functionType->parameters[argIndex]); } auto llvmResultType = asLLVMType(functionType->ret); return llvm::FunctionType::get(llvmResultType, llvm::ArrayRef<llvm::Type *>(llvmArgTypes, functionType->parameters.size()), false); } // Overloaded functions that compile a literal value to a LLVM constant of the right type. inline llvm::ConstantInt *emitLiteral(U32 value) { return (llvm::ConstantInt *) llvm::ConstantInt::get(llvmI32Type, llvm::APInt( 32, (U64) value, false)); } inline llvm::ConstantInt *emitLiteral(I32 value) { return (llvm::ConstantInt *) llvm::ConstantInt::get(llvmI32Type, llvm::APInt( 32, (I64) value, false)); } inline llvm::ConstantInt *emitLiteral(U64 value) { return (llvm::ConstantInt *) llvm::ConstantInt::get(llvmI64Type, llvm::APInt( 64, value, false)); } inline llvm::ConstantInt *emitLiteral(I64 value) { return (llvm::ConstantInt *) llvm::ConstantInt::get(llvmI64Type, llvm::APInt( 64, value, false)); } inline llvm::Constant *emitLiteral(F32 value) { return llvm::ConstantFP::get(context, llvm::APFloat(value)); } inline llvm::Constant *emitLiteral(F64 value) { return llvm::ConstantFP::get(context, llvm::APFloat(value)); } inline llvm::Constant *emitLiteral(bool value) { return llvm::ConstantInt::get(llvmBoolType, llvm::APInt(1, value ? 1 : 0, false)); } inline llvm::Constant *emitLiteralPointer(const void *pointer, llvm::Type *type) { auto pointerInt = llvm::APInt(sizeof(Uptr) == 8 ? 64 : 32, reinterpret_cast<Uptr>(pointer)); return llvm::Constant::getIntegerValue(type, pointerInt); } // Functions that map between the symbols used for externally visible functions and the function std::string getExternalFunctionName(ModuleInstance *moduleInstance, Uptr functionDefIndex); bool getFunctionIndexFromExternalName(const char *externalName, Uptr &outFunctionDefIndex); // Emits LLVM IR for a module. llvm::Module *emitModule(const IR::Module &module, ModuleInstance *moduleInstance); }
tvl83/fio
libraries/builtins/fixunstfti.c
<reponame>tvl83/fio /* ===-- fixunstfsi.c - Implement __fixunstfsi -----------------------------=== * * The LLVM Compiler Infrastructure * * This file is dual licensed under the MIT and the University of Illinois Open * Source Licenses. See LICENSE.TXT for details. * * ===----------------------------------------------------------------------=== */ #include "fp128.h" typedef float128_t fp_t; typedef unsigned __int128 fixuint_t; typedef unsigned __int128 tu_int; typedef __int128 rep_t; tu_int ___fixunstfti(fp_t a) { // Break a into sign, exponent, significand const rep_t aRep = toRep(a); const rep_t aAbs = aRep & absMask; const int sign = aRep & signBit ? -1 : 1; const int exponent = (aAbs >> significandBits) - exponentBias; const rep_t significand = (aAbs & significandMask) | implicitBit; // If either the value or the exponent is negative, the result is zero. if (sign == -1 || exponent < 0) return 0; // If the value is too large for the integer type, saturate. if ((unsigned) exponent >= sizeof(fixuint_t) * CHAR_BIT) return ~(fixuint_t) 0; // If 0 <= exponent < significandBits, right shift to get the result. // Otherwise, shift left. if (exponent < significandBits) return significand >> (significandBits - exponent); else return (fixuint_t) significand << (exponent - significandBits); }
tvl83/fio
libraries/chain/include/eosio/chain/fioio/fioserialize.h
<filename>libraries/chain/include/eosio/chain/fioio/fioserialize.h<gh_stars>10-100 /** fio serialize definitions file * Description: This account will help the chain plugin and contracts to serialize fioaddresses into hashed values. * @author <NAME> / <NAME> * @file fioserialize.hpp * @license FIO Foundation ( https://github.com/fioprotocol/fio/blob/master/LICENSE ) * */ #include <string> #include <eosio/chain/name.hpp> #include <fc/crypto/sha1.hpp> #pragma once namespace fioio { using uint128_t = unsigned __int128; // Converts a string to a uint64_t using the same hashing mechanism as string_to_name without using the base32 symbols static uint128_t string_to_uint128_t(const char *str) { uint128_t retval = 0; uint32_t len = 0; if( str != nullptr ){ while (str[len]) ++len; fc::sha1 res = fc::sha1::hash(str, len); memcpy(&retval, &res, sizeof(retval)); } return retval; } //use this to see the value of your uint128_t, this will match what shows in get table. static std::string to_hex_little_endian(const char *d, uint32_t s) { std::string r; if( d != nullptr ){ const char *to_hexi = "0123456789abcdef"; uint8_t *c = (uint8_t *) d; for (int i = (s - 1); i >= 0; --i) { (r += to_hexi[(c[i] >> 4)]) += to_hexi[(c[i] & 0x0f)]; } } return r; } }
tvl83/fio
libraries/wasm-jit/Include/IR/IR.h
#pragma once #include "Platform/Platform.h" #ifndef IR_API #define IR_API DLL_IMPORT #endif namespace IR { enum { maxMemoryPages = (Uptr) 65536 }; enum { numBytesPerPage = (Uptr) 65536 }; enum { numBytesPerPageLog2 = (Uptr) 16 }; enum { requireSharedFlagForAtomicOperators = false }; }
tvl83/fio
libraries/wasm-jit/Include/Runtime/TaggedValue.h
#pragma once #include "IR/Types.h" #include "Inline/Floats.h" #include <string.h> #undef ENABLE_SIMD_PROTOTYPE namespace Runtime { // A runtime value of any type. struct UntaggedValue { union { I32 i32; U32 u32; I64 i64; U64 u64; F32 f32; F64 f64; #if ENABLE_SIMD_PROTOTYPE IR::V128 v128; #endif }; UntaggedValue(I32 inI32) { i32 = inI32; } UntaggedValue(I64 inI64) { i64 = inI64; } UntaggedValue(U32 inU32) { u32 = inU32; } UntaggedValue(U64 inU64) { u64 = inU64; } UntaggedValue(F32 inF32) { f32 = inF32; } UntaggedValue(F64 inF64) { f64 = inF64; } #if ENABLE_SIMD_PROTOTYPE UntaggedValue(IR::V128 inV128) { v128 = inV128; } #endif UntaggedValue() { memset(this, 0, sizeof(*this)); } }; // A boxed value: may hold any value that can be passed to a function invoked through the runtime. struct Value : UntaggedValue { IR::ValueType type; Value(I32 inI32) : UntaggedValue(inI32), type(IR::ValueType::i32) {} Value(I64 inI64) : UntaggedValue(inI64), type(IR::ValueType::i64) {} Value(U32 inU32) : UntaggedValue(inU32), type(IR::ValueType::i32) {} Value(U64 inU64) : UntaggedValue(inU64), type(IR::ValueType::i64) {} Value(F32 inF32) : UntaggedValue(inF32), type(IR::ValueType::f32) {} Value(F64 inF64) : UntaggedValue(inF64), type(IR::ValueType::f64) {} #if ENABLE_SIMD_PROTOTYPE Value(const IR::V128& inV128): UntaggedValue(inV128), type(IR::ValueType::v128) {} #endif Value(IR::ValueType inType, UntaggedValue inValue) : UntaggedValue(inValue), type(inType) {} Value() : type(IR::ValueType::any) {} friend std::string asString(const Value &value) { switch (value.type) { case IR::ValueType::i32: return "i32(" + std::to_string(value.i32) + ")"; case IR::ValueType::i64: return "i64(" + std::to_string(value.i64) + ")"; case IR::ValueType::f32: return "f32(" + Floats::asString(value.f32) + ")"; case IR::ValueType::f64: return "f64(" + Floats::asString(value.f64) + ")"; #if ENABLE_SIMD_PROTOTYPE case IR::ValueType::v128: return "v128(" + std::to_string(value.v128.u64[0]) + "," + std::to_string(value.v128.u64[1]) + ")"; #endif default: Errors::unreachable(); } } }; // A boxed value: may hold any value that can be returned from a function invoked through the runtime. struct Result : UntaggedValue { IR::ResultType type; Result(I32 inI32) : UntaggedValue(inI32), type(IR::ResultType::i32) {} Result(I64 inI64) : UntaggedValue(inI64), type(IR::ResultType::i64) {} Result(U32 inU32) : UntaggedValue(inU32), type(IR::ResultType::i32) {} Result(U64 inU64) : UntaggedValue(inU64), type(IR::ResultType::i64) {} Result(F32 inF32) : UntaggedValue(inF32), type(IR::ResultType::f32) {} Result(F64 inF64) : UntaggedValue(inF64), type(IR::ResultType::f64) {} #if ENABLE_SIMD_PROTOTYPE Result(const IR::V128& inV128): UntaggedValue(inV128), type(IR::ResultType::v128) {} #endif Result(IR::ResultType inType, UntaggedValue inValue) : UntaggedValue(inValue), type(inType) {} Result(const Value &inValue) : UntaggedValue(inValue), type(asResultType(inValue.type)) {} Result() : type(IR::ResultType::none) {} friend std::string asString(const Result &result) { switch (result.type) { case IR::ResultType::none: return "()"; case IR::ResultType::i32: return "i32(" + std::to_string(result.i32) + ")"; case IR::ResultType::i64: return "i64(" + std::to_string(result.i64) + ")"; case IR::ResultType::f32: return "f32(" + Floats::asString(result.f32) + ")"; case IR::ResultType::f64: return "f64(" + Floats::asString(result.f64) + ")"; #if ENABLE_SIMD_PROTOTYPE case IR::ResultType::v128: return "v128(" + std::to_string(result.v128.u64[0]) + "," + std::to_string(result.v128.u64[1]) + ")"; #endif default: Errors::unreachable(); } } }; // Compares whether two UntaggedValue of the same type have identical bits. inline bool areBitsEqual(IR::ResultType type, UntaggedValue a, UntaggedValue b) { switch (type) { case IR::ResultType::i32: case IR::ResultType::f32: return a.i32 == b.i32; case IR::ResultType::i64: case IR::ResultType::f64: return a.i64 == b.i64; #if ENABLE_SIMD_PROTOTYPE case IR::ResultType::v128: return a.v128.u64[0] == b.v128.u64[0] && a.v128.u64[1] == b.v128.u64[1]; #endif case IR::ResultType::none: return true; default: Errors::unreachable(); }; } // Compares whether two Value/Result have the same type and bits. inline bool areBitsEqual(const Value &a, const Value &b) { return a.type == b.type && areBitsEqual(asResultType(a.type), a, b); } inline bool areBitsEqual(const Result &a, const Result &b) { return a.type == b.type && areBitsEqual(a.type, a, b); } inline bool areBitsEqual(const Result &a, const Value &b) { return a.type == asResultType(b.type) && areBitsEqual(a.type, a, b); } inline bool areBitsEqual(const Value &a, const Result &b) { return asResultType(a.type) == b.type && areBitsEqual(b.type, a, b); } }
tvl83/fio
libraries/wasm-jit/Source/WAST/Parse.h
#pragma once #include "Inline/BasicTypes.h" #include "WAST.h" #include "Lexer.h" #include "IR/Types.h" #include "IR/Module.h" #include <functional> #include <map> #include <unordered_map> namespace WAST { struct FatalParseException { }; struct RecoverParseException { }; // Like WAST::Error, but only has an offset in the input string instead of a full TextFileLocus. struct UnresolvedError { Uptr charOffset; std::string message; UnresolvedError(Uptr inCharOffset, std::string &&inMessage) : charOffset(inCharOffset), message(inMessage) {} }; // The state that's threaded through the various parsers. struct ParseState { const char *string; const LineInfo *lineInfo; std::vector<UnresolvedError> &errors; const Token *nextToken; ParseState(const char *inString, const LineInfo *inLineInfo, std::vector<UnresolvedError> &inErrors, const Token *inNextToken) : string(inString), lineInfo(inLineInfo), errors(inErrors), nextToken(inNextToken) {} }; // Encapsulates a name ($whatever) parsed from the WAST file. // References the characters in the input string the name was parsed from, // so it can handle arbitrary length names in a fixed size struct, but only // as long as the input string isn't freed. // Includes a hash of the name's characters. struct Name { Name() : begin(nullptr), numChars(0), hash(0) {} Name(const char *inBegin, U32 inNumChars) : begin(inBegin), numChars(inNumChars), hash(calcHash(inBegin, inNumChars)) {} operator bool() const { return begin != nullptr; } std::string getString() const { return begin ? std::string(begin + 1, numChars - 1) : std::string(); } Uptr getCharOffset(const char *string) const { return begin - string; } friend bool operator==(const Name &a, const Name &b) { return a.hash == b.hash && a.numChars == b.numChars && memcmp(a.begin, b.begin, a.numChars) == 0; } friend bool operator!=(const Name &a, const Name &b) { return !(a == b); } struct Hasher { Uptr operator()(const Name &name) const { return name.hash; } }; private: const char *begin; U32 numChars; U32 hash; static U32 calcHash(const char *begin, U32 numChars); }; // A map from Name to index using a hash table. typedef std::unordered_map<Name, U32, Name::Hasher> NameToIndexMap; // Represents a yet-to-be-resolved reference, parsed as either a name or an index. struct Reference { enum class Type { invalid, name, index }; Type type; union { Name name; U32 index; }; const Token *token; Reference(const Name &inName) : type(Type::name), name(inName) {} Reference(U32 inIndex) : type(Type::index), index(inIndex) {} Reference() : type(Type::invalid), token(nullptr) {} operator bool() const { return type != Type::invalid; } }; // Represents a function type, either as an unresolved name/index, or as an explicit type, or both. struct UnresolvedFunctionType { Reference reference; const IR::FunctionType *explicitType; }; // State associated with parsing a module. struct ModuleParseState : ParseState { IR::Module &module; std::map<const IR::FunctionType *, U32> functionTypeToIndexMap; NameToIndexMap typeNameToIndexMap; NameToIndexMap functionNameToIndexMap; NameToIndexMap tableNameToIndexMap; NameToIndexMap memoryNameToIndexMap; NameToIndexMap globalNameToIndexMap; IR::DisassemblyNames disassemblyNames; // Thunks that are called after parsing all types. std::vector<std::function<void(ModuleParseState &)>> postTypeCallbacks; // Thunks that are called after parsing all declarations. std::vector<std::function<void(ModuleParseState &)>> postDeclarationCallbacks; ModuleParseState(const char *inString, const LineInfo *inLineInfo, std::vector<UnresolvedError> &inErrors, const Token *inNextToken, IR::Module &inModule) : ParseState(inString, inLineInfo, inErrors, inNextToken), module(inModule) {} }; // Error handling. void parseErrorf(ParseState &state, Uptr charOffset, const char *messageFormat, ...); void parseErrorf(ParseState &state, const char *nextChar, const char *messageFormat, ...); void parseErrorf(ParseState &state, const Token *nextToken, const char *messageFormat, ...); void require(ParseState &state, TokenType type); // Type parsing and uniqueing bool tryParseValueType(ParseState &state, IR::ValueType &outValueType); bool tryParseResultType(ParseState &state, IR::ResultType &outResultType); IR::ValueType parseValueType(ParseState &state); const IR::FunctionType *parseFunctionType(ModuleParseState &state, NameToIndexMap &outLocalNameToIndexMap, std::vector<std::string> &outLocalDisassemblyNames); UnresolvedFunctionType parseFunctionTypeRefAndOrDecl(ModuleParseState &state, NameToIndexMap &outLocalNameToIndexMap, std::vector<std::string> &outLocalDisassemblyNames); IR::IndexedFunctionType resolveFunctionType(ModuleParseState &state, const UnresolvedFunctionType &unresolvedType); IR::IndexedFunctionType getUniqueFunctionTypeIndex(ModuleParseState &state, const IR::FunctionType *functionType); // Literal parsing. bool tryParseHexit(const char *&nextChar, U8 &outValue); bool tryParseI32(ParseState &state, U32 &outI32); bool tryParseI64(ParseState &state, U64 &outI64); U8 parseI8(ParseState &state); U32 parseI32(ParseState &state); U64 parseI64(ParseState &state); F32 parseF32(ParseState &state); F64 parseF64(ParseState &state); bool tryParseString(ParseState &state, std::string &outString); std::string parseUTF8String(ParseState &state); // Name parsing and resolution. bool tryParseName(ParseState &state, Name &outName); bool tryParseNameOrIndexRef(ParseState &state, Reference &outRef); U32 parseAndResolveNameOrIndexRef(ParseState &state, const NameToIndexMap &nameToIndexMap, Uptr maxIndex, const char *context); void bindName(ParseState &state, NameToIndexMap &nameToIndexMap, const Name &name, Uptr index); U32 resolveRef(ParseState &state, const NameToIndexMap &nameToIndexMap, Uptr maxIndex, const Reference &ref); // Finds the parenthesis closing the current s-expression. void findClosingParenthesis(ParseState &state, const Token *openingParenthesisToken); // Parses the surrounding parentheses for an inner parser, and handles recovery at the closing parenthesis. template<typename ParseInner> static void parseParenthesized(ParseState &state, ParseInner parseInner) { const Token *openingParenthesisToken = state.nextToken; require(state, t_leftParenthesis); try { parseInner(); require(state, t_rightParenthesis); } catch (RecoverParseException) { findClosingParenthesis(state, openingParenthesisToken); } } // Tries to parse '(' tagType parseInner ')', handling recovery at the closing parenthesis. // Returns true if any tokens were consumed. template<typename ParseInner> static bool tryParseParenthesizedTagged(ParseState &state, TokenType tagType, ParseInner parseInner) { const Token *openingParenthesisToken = state.nextToken; if (state.nextToken[0].type != t_leftParenthesis || state.nextToken[1].type != tagType) { return false; } try { state.nextToken += 2; parseInner(); require(state, t_rightParenthesis); } catch (RecoverParseException) { findClosingParenthesis(state, openingParenthesisToken); } return true; } // Function parsing. IR::FunctionDef parseFunctionDef(ModuleParseState &state, const Token *funcToken); // Module parsing. void parseModuleBody(ModuleParseState &state); };
tvl83/fio
libraries/wasm-jit/Source/Programs/CLI.h
#pragma once #include "Inline/BasicTypes.h" #include "Inline/Floats.h" #include "Inline/Timing.h" #include "WAST/WAST.h" #include "WASM/WASM.h" #include "IR/Module.h" #include "IR/Validate.h" #include "Runtime/Runtime.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <cstring> inline std::string loadFile(const char *filename) { Timing::Timer timer; std::ifstream stream(filename, std::ios::binary | std::ios::ate); if (!stream.is_open()) { std::cerr << "Failed to open " << filename << ": " << std::strerror(errno) << std::endl; return std::string(); } std::string data; data.resize((unsigned int) stream.tellg()); stream.seekg(0); stream.read(const_cast<char *>(data.data()), data.size()); stream.close(); Timing::logRatePerSecond("loaded file", timer, data.size() / 1024.0 / 1024.0, "MB"); return data; } inline bool loadTextModule(const char *filename, const std::string &wastString, IR::Module &outModule) { std::vector <WAST::Error> parseErrors; WAST::parseModule(wastString.c_str(), wastString.size(), outModule, parseErrors); if (!parseErrors.size()) { return true; } else { // Print any parse errors; std::cerr << "Error parsing WebAssembly text file:" << std::endl; for (auto &error : parseErrors) { std::cerr << filename << ":" << error.locus.describe() << ": " << error.message.c_str() << std::endl; std::cerr << error.locus.sourceLine << std::endl; std::cerr << std::setw(error.locus.column(8)) << "^" << std::endl; } return false; } } inline bool loadTextModule(const char *filename, IR::Module &outModule) { // Read the file into a string. auto wastBytes = loadFile(filename); if (!wastBytes.size()) { return false; } const std::string wastString = std::move(wastBytes); return loadTextModule(filename, wastString, outModule); } inline bool loadBinaryModule(const std::string &wasmBytes, IR::Module &outModule) { Timing::Timer loadTimer; // Load the module from a binary WebAssembly file. try { Serialization::MemoryInputStream stream((const U8 *) wasmBytes.data(), wasmBytes.size()); WASM::serialize(stream, outModule); } catch (Serialization::FatalSerializationException exception) { std::cerr << "Error deserializing WebAssembly binary file:" << std::endl; std::cerr << exception.message << std::endl; return false; } catch (IR::ValidationException exception) { std::cerr << "Error validating WebAssembly binary file:" << std::endl; std::cerr << exception.message << std::endl; return false; } catch (std::bad_alloc) { std::cerr << "Memory allocation failed: input is likely malformed" << std::endl; return false; } Timing::logRatePerSecond("Loaded WASM", loadTimer, wasmBytes.size() / 1024.0 / 1024.0, "MB"); return true; } inline bool loadBinaryModule(const char *wasmFilename, IR::Module &outModule) { // Read in packed .wasm file bytes. auto wasmBytes = loadFile(wasmFilename); if (!wasmBytes.size()) { return false; } return loadBinaryModule(wasmBytes, outModule); } inline bool loadModule(const char *filename, IR::Module &outModule) { // Read the specified file into an array. auto fileBytes = loadFile(filename); if (!fileBytes.size()) { return false; } // If the file starts with the WASM binary magic number, load it as a binary module. if (*(U32 *) fileBytes.data() == 0x6d736100) { return loadBinaryModule(fileBytes, outModule); } else { // Otherwise, load it as a text module. auto wastString = std::move(fileBytes); return loadTextModule(filename, wastString, outModule); } } inline bool saveBinaryModule(const char *wasmFilename, const IR::Module &module) { Timing::Timer saveTimer; std::vector <U8> wasmBytes; try { // Serialize the WebAssembly module. Serialization::ArrayOutputStream stream; WASM::serialize(stream, module); wasmBytes = stream.getBytes(); } catch (Serialization::FatalSerializationException exception) { std::cerr << "Error serializing WebAssembly binary file:" << std::endl; std::cerr << exception.message << std::endl; return false; } Timing::logRatePerSecond("Saved WASM", saveTimer, wasmBytes.size() / 1024.0 / 1024.0, "MB"); // Write the serialized data to the output file. std::ofstream outputStream(wasmFilename, std::ios::binary); outputStream.write((char *) wasmBytes.data(), wasmBytes.size()); outputStream.close(); return true; } inline bool endsWith(const char *str, const char *suffix) { if (!str || !suffix) { return false; } Uptr lenstr = strlen(str); Uptr lensuffix = strlen(suffix); if (lenstr < lensuffix) { return false; } return (strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0); } int commandMain(int argc, char **argv); int main(int argc, char **argv) { try { return commandMain(argc, argv); } catch (IR::ValidationException exception) { std::cerr << "Failed to validate module: " << exception.message << std::endl; return EXIT_FAILURE; } catch (Runtime::Exception exception) { std::cerr << "Runtime exception: " << describeExceptionCause(exception.cause) << std::endl; for (auto calledFunction : exception.callStack) { std::cerr << " " << calledFunction << std::endl; } return EXIT_FAILURE; } catch (Serialization::FatalSerializationException exception) { std::cerr << "Fatal serialization exception: " << exception.message << std::endl; return EXIT_FAILURE; } }