max_stars_repo_path
stringlengths
9
64
max_stars_repo_name
stringlengths
11
48
max_stars_count
float64
0
1.34k
id
stringlengths
6
7
content
stringlengths
60
400k
score
float64
0.5
1
label
stringclasses
2 values
linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h
isabella232/wireless-media-drive
10
7113385
<filename>linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h /* * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ /* * @file sah_kernel.h * * @brief Provides definitions for items that user-space and kernel-space share. */ /****************************************************************************** * * This file needs to be PORTED to a non-Linux platform */ #ifndef SAH_KERNEL_H #define SAH_KERNEL_H #if defined(__KERNEL__) #if defined(CONFIG_ARCH_MXC91321) || defined(CONFIG_ARCH_MXC91231) \ || defined(CONFIG_ARCH_MX27) || defined(CONFIG_ARCH_MXC92323) #include <mach/hardware.h> #define SAHA_BASE_ADDR SAHARA_BASE_ADDR #define SAHARA_IRQ MXC_INT_SAHARA #elif defined(CONFIG_ARCH_MX5) #include <mach/hardware.h> #define SAHA_BASE_ADDR SAHARA_BASE_ADDR #define SAHARA_IRQ MXC_INT_SAHARA_H0 #else #include <mach/mx2.h> #endif #endif /* KERNEL */ /* IO Controls */ /* The magic number 'k' is reserved for the SPARC architecture. (See <kernel * source root>/Documentation/ioctl-number.txt. * * Note: Numbers 8-13 were used in a previous version of the API and should * be avoided. */ #define SAH_IOC_MAGIC 'k' #define SAHARA_HWRESET _IO(SAH_IOC_MAGIC, 0) #define SAHARA_SET_HA _IO(SAH_IOC_MAGIC, 1) #define SAHARA_CHK_TEST_MODE _IOR(SAH_IOC_MAGIC,2, int) #define SAHARA_DAR _IO(SAH_IOC_MAGIC, 3) #define SAHARA_GET_RESULTS _IO(SAH_IOC_MAGIC, 4) #define SAHARA_REGISTER _IO(SAH_IOC_MAGIC, 5) #define SAHARA_DEREGISTER _IO(SAH_IOC_MAGIC, 6) /* 7 */ /* 8 */ /* 9 */ /* 10 */ /* 11 */ /* 12 */ /* 13 */ #define SAHARA_SCC_DROP_PERMS _IOWR(SAH_IOC_MAGIC, 14, scc_partition_info_t) #define SAHARA_SCC_SFREE _IOWR(SAH_IOC_MAGIC, 15, scc_partition_info_t) #define SAHARA_SK_ALLOC _IOWR(SAH_IOC_MAGIC, 16, scc_slot_t) #define SAHARA_SK_DEALLOC _IOWR(SAH_IOC_MAGIC, 17, scc_slot_t) #define SAHARA_SK_LOAD _IOWR(SAH_IOC_MAGIC, 18, scc_slot_t) #define SAHARA_SK_UNLOAD _IOWR(SAH_IOC_MAGIC, 19, scc_slot_t) #define SAHARA_SK_SLOT_ENC _IOWR(SAH_IOC_MAGIC, 20, scc_slot_t) #define SAHARA_SK_SLOT_DEC _IOWR(SAH_IOC_MAGIC, 21, scc_slot_t) #define SAHARA_SCC_ENCRYPT _IOWR(SAH_IOC_MAGIC, 22, scc_region_t) #define SAHARA_SCC_DECRYPT _IOWR(SAH_IOC_MAGIC, 23, scc_region_t) #define SAHARA_GET_CAPS _IOWR(SAH_IOC_MAGIC, 24, fsl_shw_pco_t) #define SAHARA_SCC_SSTATUS _IOWR(SAH_IOC_MAGIC, 25, scc_partition_info_t) #define SAHARA_SK_READ _IOWR(SAH_IOC_MAGIC, 29, scc_slot_t) /*! This is the name that will appear in /proc/interrupts */ #define SAHARA_NAME "SAHARA" /*! * SAHARA IRQ number. See page 9-239 of TLICS - Motorola Semiconductors H.K. * TAHITI-Lite IC Specification, Rev 1.1, Feb 2003. * * TAHITI has two blocks of 32 interrupts. The SAHARA IRQ is number 27 * in the second block. This means that the SAHARA IRQ is 27 + 32 = 59. */ #ifndef SAHARA_IRQ #define SAHARA_IRQ (27+32) #endif /*! * Device file definition. The #ifndef is here to support the unit test code * by allowing it to specify a different test device. */ #ifndef SAHARA_DEVICE_SHORT #define SAHARA_DEVICE_SHORT "sahara" #endif #ifndef SAHARA_DEVICE #define SAHARA_DEVICE "/dev/"SAHARA_DEVICE_SHORT #endif #endif /* SAH_KERNEL_H */ /* End of sah_kernel.h */
0.992188
high
Pod/Classes/SVGPathSegmentClosePath.h
cotkjaer/SilverbackScalableVectorGraphics
1
2508913
// // SVGPathElementSegmentClosePath.h // Pods // // Created by <NAME> on 16/12/14. // // #import "SVGPathSegment.h" @interface SVGPathSegmentClosePath : SVGPathSegment @end
0.664063
low
soundgen.c
bharadwaj-raju/SoundGen
2
4171057
#include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <math.h> #include "wavfile.h" #define TRUE 1 #define FALSE 0 struct Tone { float duration; float frequency; float amplitude_perc; }; short * calculate_tone(double duration, double frequency, double amplitude) { int n_samples = (int) WAVFILE_SAMPLES_PER_SECOND * duration; int volume = (int) 32768 * (amplitude / 100); short * waveform = malloc(sizeof(short) * n_samples); for (int i=0; i<n_samples;i++) { double t = (double) i / WAVFILE_SAMPLES_PER_SECOND; waveform[i] = (int) volume * sin(frequency * t * 2 * M_PI); } return waveform; } int main(int argc, char * argv[]) { int opt_play = FALSE; if (argc < 3) { printf("Not enough arguments.\n"); printf("Usage: %s tones_file wav_output_file [--play]\n", argv[0]); return 1; } if (argc == 3) { if (access(argv[1], F_OK) == -1) { printf("File %s does not exist.\n", argv[1]); return 1; } } if (argc > 3) { if (strcmp(argv[3], "--play") == 0) { opt_play = TRUE; } } FILE * tones_fp = fopen(argv[1], "r"); if (tones_fp == NULL) { printf("Could not open file %s for reading.\n", argv[1]); return 1; } char line[512]; char **lines = NULL; int n_tones = 0; while (fgets(line, sizeof(line), tones_fp)) { lines = (char **) realloc(lines, (n_tones+1) * sizeof(char *)); lines[n_tones++] = strdup(line); } struct Tone tones[n_tones]; float d, f, a = 0.0; char sd[256], sf[256], sa[256]; float total_duration = 0.0; for (int i=0; i<n_tones; i++) { sscanf(lines[i], "%s %s %s\n", sd, sf, sa); d = atof(sd); f = atof(sf); a = atof(sa); tones[i].duration = d; tones[i].frequency = f; tones[i].amplitude_perc = a; total_duration += d; free(lines[i]); } int total_samples = (int) (total_duration * WAVFILE_SAMPLES_PER_SECOND); short * final_waveform = malloc(total_samples * sizeof(short)); printf("%d\n", total_samples); int samples_done = 0; for (int i=0; i<n_tones; i++) { int n_samples = (int) WAVFILE_SAMPLES_PER_SECOND * tones[i].duration; short * wavepart = calculate_tone(tones[i].duration, tones[i].frequency, tones[i].amplitude_perc); memcpy(final_waveform + samples_done, wavepart, n_samples * sizeof(short)); samples_done += n_samples; printf("Tone %d: d=%f f=%f a=%f n_samp=%d samp_done=%d\n", i, tones[i].duration, tones[i].frequency, tones[i].amplitude_perc, n_samples, samples_done); free(wavepart); } FILE * out_fp = wavfile_open(argv[2]); if (out_fp == NULL) { printf("Could not open file %s for writing.\n", argv[2]); return 1; } wavfile_write(out_fp, final_waveform, total_samples); wavfile_close(out_fp); fclose(tones_fp); free(final_waveform); free(lines); char commandbuffer[512]; sprintf(commandbuffer, "aplay '%500s'", argv[2]); if (opt_play == TRUE) { system(commandbuffer); } }
0.984375
high
include/Audio/AudioPlayer.h
Sytten/ARMUS
1
7366577
/* ============================================================================ Name : AudioPlayer Author : <NAME> Modified on: 2015-11-29 Description : Wrapper on the libarmus API calls ============================================================================ */ #ifndef AUDIOPLAYER_H_ #define AUDIOPLAYER_H_ #include <libarmus.h> #include "Audio/Notes.h" /** * Using the sent parameter, plays the good audio file * @param notes Value that will select the good audio file, recommended to be used with Audio/Notes.h defines * @return The audio playfile system stream ID */ unsigned int PlayNote(int notes); /** * Stops the stream at the parameters ID * @param ID Stream ID to stop */ void StopNote(unsigned int ID); #endif /*CHOOSINGNTOES_H_*/
0.722656
high
SQMagnet/SQMagnet/Main/SQNavigationController.h
13701777868/iOS-Extension-Objective-C
264
1095345
// // SQNavigationController.h // SQMagnet // // Created by 朱双泉 on 2019/7/12. // Copyright © 2019 Castie!. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface SQNavigationController : UINavigationController @end NS_ASSUME_NONNULL_END
0.613281
high
groups/bsl/bslalg/bslalg_hashtableanchor.h
emeryberger/bde
1
3759480
// bslalg_hashtableanchor.h -*-C++-*- #ifndef INCLUDED_BSLALG_HASHTABLEANCHOR #define INCLUDED_BSLALG_HASHTABLEANCHOR #include <bsls_ident.h> BSLS_IDENT("$Id: $") //@PURPOSE: Provide a type holding the constituent parts of a hash table. // //@CLASSES: // bslalg::HashTableAnchor: (in-core) bucket-array and node list // //@SEE_ALSO: bslstl_hashtable, bslalg_hashtableimputil // //@DESCRIPTION: This component provides a single, complex-constrained // *in*-*core* (value-semantic) attribute class, 'bslalg::HashTableAnchor', // that is used to hold (not own) the array of buckets and the list of nodes // that form the key data elements of a hash-table. This class is typically // used with the utilities provided in 'bslstl_hashtableimputil'. Note that // the decision to store nodes in a linked list (i.e., resolving collisions // through chaining) is intended to facilitate a hash-table implementation // meeting the requirements of a C++11 standard unordered container. // ///Attributes ///---------- //.. // Name Type Simple Constraints // ------------------ ------------------- ------------------ // bucketArrayAddress HashTableBucket * none // // bucketArraySize size_t none // // listRootAddress BidirectionalLink * none // // // Complex Constraint // ------------------------------------------------------------------------- // 'bucketArrayAddress' must refer to a contiguous sequence of valid // 'bslalg::HashTableBucket' objects of at least the specified // 'bucketArraySize' or both 'bucketArrayAddress' and 'bucketArraySize' must // be 0. //.. // //: o 'listRootAddress': address of the head of the linked list of nodes //: holding the elements contained in a hash table //: //: o 'bucketArrayAddress': address of the first element of the sequence of //: 'HashTableBucket' objects, each of which refers to the first and last //: node (from 'listRootAddress') in that bucket //: //: o 'bucketArraySize': the number of (contiguous) buckets in the array of //: buckets at 'bucketArrayAddress' // ///Usage ///----- // This section illustrates intended use of this component. // // Suppose we want to create a hash table that keeps track of pointers. // Pointers can be added ('insert'ed) or removed ('erase'd) from the table, and // the table will keep track, at any time, of whether a pointer is currently // stored in the table using the 'count' method. It will also be able to // return the total number of objects stored in the table (the 'size' method). // Redundant 'insert's have no effect -- a given pointer may only be stored in // the table once. // // First, we create our class: //.. // class PtrHashSet : public bslalg::HashTableAnchor { // // PRIVATE TYPES // typedef bsls::Types::UintPtr UintPtr; // typedef bslalg::BidirectionalNode<void *> Node; // typedef bslalg::HashTableBucket Bucket; // typedef bslalg::BidirectionalLinkListUtil Util; // // // DATA // double d_maxLoadFactor; // unsigned d_numNodes; // bslma::Allocator *d_allocator_p; // // // PRIVATE MANIPULATORS // void grow(); // // Roughly double the number of buckets, such that the number of // // buckets shall always be '2^N - 1'. // // // PRIVATE ACCESSORS // bool checkInvariants() const; // // Perform sanity checks on this table, returning 'true' if all the // // tests pass and 'false' otherwise. Note that many of the checks // // are done with the 'ASSERTV' macro and will cause messages to be // // written to the console. // // bool find(Node **node, Bucket **bucket, const void *ptr) const; // // If the specified value 'ptr' is stored in this table, return // // pointers to its node and bucket in the specified 'node' and // // 'bucket'. If it is not in this table, return the bucket it // // should be in, and a pointer to the first node, if any, in that // // bucket. If the bucket is empty, return with // // '*node == listRootAddress()'. Return 'true' if 'ptr' was found // // in the table and 'false' otherwise. Note that it is permissible // // to pass 0 to 'node' and / or 'bucket', in which case these // // arguments are ignored. // // private: // // NOT IMPLEMENTED // PtrHashSet(const PtrHashSet&, bslma::Allocator *); // PtrHashSet& operator=(const PtrHashSet&); // // public: // // CREATORS // explicit // PtrHashSet(bslma::Allocator *allocator = 0); // // Create a 'PtrHashSet', using the specified 'allocator'. If no // // allocator is specified, use the default allocator. // // ~PtrHashSet(); // // Destroy this 'PtrHashSet', freeing all its memory. // // // MANIPULATORS // bool insert(void *ptr); // // If the specfied 'ptr' is not in this hash table, add it, // // returning 'true'. If it is already in the table, return 'false' // // with no action taken. // // bool erase(void *ptr); // // If the specfied 'ptr' is in this hash table, remove it, // // returning 'true'. If it is not found in the table, return // // 'false' with no action taken. // // // ACCESSORS // native_std::size_t count(void *ptr) const; // // Return 1 if the specified value 'ptr' is in this table and 0 // // otherwise. // // native_std::size_t size() const; // // Return the number of discrete values that are stored in this // // table. // }; // // // PRIVATE MANIPULATORS // void PtrHashSet::grow() // { // // 'bucketArraySize' will always be '2^N - 1', so that when pointers // // are aligned by some 2^N they're likely to be relatively prime. // // native_std::size_t newBucketArraySize = bucketArraySize() * 2 + 1; // native_std::size_t newBucketArraySizeInBytes = // newBucketArraySize * sizeof(Bucket); // memset(bucketArrayAddress(), 0x5a, size() * sizeof(Bucket)); // d_allocator_p->deallocate(bucketArrayAddress()); // setBucketArrayAddressAndSize( // (Bucket *) d_allocator_p->allocate(newBucketArraySizeInBytes), // newBucketArraySize); // memset(bucketArrayAddress(), 0, newBucketArraySizeInBytes); // Node *newListRootAddress = 0; // // unsigned numNodes = 0; // for (Node *node = (Node *) listRootAddress(); node; ++numNodes) { // Node *rippedOut = node; // node = (Node *) node->nextLink(); // // native_std::size_t index = // (UintPtr) rippedOut->value() % bucketArraySize(); // Bucket& bucket = bucketArrayAddress()[index]; // if (bucket.first()) { // if (0 == bucket.first()->previousLink()) { // newListRootAddress = rippedOut; // } // Util::insertLinkBeforeTarget(rippedOut, bucket.first()); // bucket.setFirst(rippedOut); // } // else { // Util::insertLinkBeforeTarget(rippedOut, // newListRootAddress); // newListRootAddress = rippedOut; // bucket.setFirstAndLast(rippedOut, rippedOut); // } // } // assert(size() == numNodes); // // setListRootAddress(newListRootAddress); // // checkInvariants(); // } // // // PRIVATE ACCESSORS // bool PtrHashSet::checkInvariants() const // { // bool ok; // // unsigned numNodes = 0; // Node *prev = 0; // for (Node *node = (Node *) listRootAddress(); node; // prev = node, node = (Node *) node->nextLink()) { // ok = node->previousLink() == prev; // assert(ok && "node->previousLink() == prev"); // if (!ok) return false; // RETURN // ++numNodes; // } // ok = size() == numNodes; // assert(ok && "size() == numNodes"); // if (!ok) return false; // RETURN // // numNodes = 0; // for (unsigned i = 0; i < bucketArraySize(); ++i) { // Bucket& bucket = bucketArrayAddress()[i]; // if (bucket.first()) { // ++numNodes; // for (Node *node = (Node *) bucket.first(); // bucket.last() != node; // node = (Node *) node->nextLink()) { // ++numNodes; // } // } // else { // ok = !bucket.last(); // assert(ok && "!bucket.last()"); // if (!ok) return false; // RETURN // } // } // ok = size() == numNodes; // assert(ok && "size() == numNodes"); // // return ok; // } // // bool PtrHashSet::find(Node **node, Bucket **bucket, const void *ptr) const // { // Node *dummyNodePtr; // Bucket *dummyBucketPtr; // if (!node ) node = &dummyNodePtr; // if (!bucket) bucket = &dummyBucketPtr; // // Node *& nodePtrRef = *node; // unsigned index = (UintPtr) ptr % bucketArraySize(); // Bucket& bucketRef = bucketArrayAddress()[index]; // *bucket = &bucketRef; // if (bucketRef.first()) { // Node *begin = (Node *) bucketRef.first(); // Node * const end = (Node *) bucketRef.last()->nextLink(); // for (Node *n = begin; end != n; n = (Node *) n->nextLink()) { // if (n->value() == ptr) { // // found // // nodePtrRef = n; // return true; // RETURN // } // } // // not found // // nodePtrRef = begin; // return false; // RETURN // } // // empty bucket // // nodePtrRef = (Node *) listRootAddress(); // return false; // } // // // CREATORS // PtrHashSet::PtrHashSet(bslma::Allocator *allocator) // : HashTableAnchor(0, 0, 0) // , d_maxLoadFactor(0.4) // , d_numNodes(0) // { // enum { NUM_BUCKETS = 3 }; // // d_allocator_p = bslma::Default::allocator(allocator); // native_std::size_t bucketArraySizeInBytes = // NUM_BUCKETS * sizeof(Bucket); // setBucketArrayAddressAndSize( // (Bucket *) d_allocator_p->allocate(bucketArraySizeInBytes), // NUM_BUCKETS); // memset(bucketArrayAddress(), 0, bucketArraySizeInBytes); // } // // PtrHashSet::~PtrHashSet() // { // BSLS_ASSERT_SAFE(checkInvariants()); // // for (Node *node = (Node *) listRootAddress(); node; ) { // Node *toDelete = node; // node = (Node *) node->nextLink(); // // memset(toDelete, 0x5a, sizeof(*toDelete)); // d_allocator_p->deallocate(toDelete); // } // // d_allocator_p->deallocate(bucketArrayAddress()); // } // // // MANIPULATORS // bool PtrHashSet::erase(void *ptr) // { // Bucket *bucket; // Node *node; // // if (!find(&node, &bucket, ptr)) { // return false; // RETURN // } // // if (bucket->first() == node) { // if (bucket->last() == node) { // bucket->reset(); // } // else { // bucket->setFirst(node->nextLink()); // } // } // else if (bucket->last() == node) { // bucket->setLast(node->previousLink()); // } // // --d_numNodes; // Util::unlink(node); // // d_allocator_p->deallocate(node); // // checkInvariants(); // // return true; // } // // bool PtrHashSet::insert(void *ptr) // { // Bucket *bucket; // Node *insertionPoint; // // if (find(&insertionPoint, &bucket, ptr)) { // // Already in set, do nothing. // // return false; // RETURN // } // // if (bucketArraySize() * d_maxLoadFactor < d_numNodes + 1) { // grow(); // bool found = find(&insertionPoint, &bucket, ptr); // BSLS_ASSERT_SAFE(!found); // } // // ++d_numNodes; // Node *node = (Node *) d_allocator_p->allocate(sizeof(Node)); // // Util::insertLinkBeforeTarget(node, insertionPoint); // node->value() = ptr; // if (listRootAddress() == insertionPoint) { // BSLS_ASSERT_SAFE(0 == node->previousLink()); // setListRootAddress(node); // } // // if (bucket->first()) { // BSLS_ASSERT_SAFE(bucket->first() == insertionPoint); // // bucket->setFirst(node); // } // else { // BSLS_ASSERT_SAFE(!bucket->last()); // // bucket->setFirstAndLast(node, node); // } // // assert(count(ptr)); // // checkInvariants(); // // return true; // } // // // ACCESSORS // native_std::size_t PtrHashSet::count(void *ptr) const // { // return find(0, 0, ptr); // } // // native_std::size_t PtrHashSet::size() const // { // return d_numNodes; // } //.. // Then, in 'main', we create a test allocator for use in this example to // ensure that no memory is leaked: //.. // bslma::TestAllocator ta("test", veryVeryVeryVerbose); //.. // Next, we declare our table using that allocator: //.. // PtrHashSet phs(&ta); //.. // Then, we create an area of memory from which our pointers will come: //.. // enum { SEGMENT_LENGTH = 1000 }; // char *pc = (char *) ta.allocate(SEGMENT_LENGTH); //.. // Next, we iterate through the length of the segment, insert those pointers // for which 'ptr - pc == N * 7' is true. We keep a count of the number of // items we insert into the table in the variable 'sevens': //.. // unsigned sevens = 0; // for (int i = 0; i < SEGMENT_LENGTH; i += 7) { // ++sevens; // bool status = phs.insert(&pc[i]); // assert(status); // } //.. // Then, we verify the number of objects we've placed in the table: //.. // assert(phs.size() == sevens); //.. // Next, we iterate through ALL pointers in the 'pc' array, using the 'count' // method to verify that the ones we expect are in the table: //.. // for (int i = 0; i < SEGMENT_LENGTH; ++i) { // assert(phs.count(&pc[i]) == (0 == i % 7)); // } //.. // Then, we iterate, deleting all elements from the table for which // 'ptr - pc == 3 * N' is true. We keep a count of the number of elements that // were deleted from the table in the variable 'killed': //.. // unsigned killed = 0; // for (int i = 0; i < SEGMENT_LENGTH; i += 3) { // const bool deleted = phs.erase(&pc[i]); // assert(deleted == (0 == i % 7)); // killed += deleted; // } //.. // Next, we verify the number of remaining elements in the table: //.. // assert(killed < sevens); // assert(phs.size() == sevens - killed); //.. // Then, in verbose mode we print our tallies: //.. // if (verbose) { // printf("sevens = %u, killed = %u, phs.size() = %u\n", sevens, // killed, (unsigned) phs.size()); // } //.. // Now, we iterate through every element of the 'pc' array, verifying that the // surviving elements are exactly those for which 'ptr - pc' was divisible by 7 // and not by 3: //.. // for (int i = 0; i < SEGMENT_LENGTH; ++i) { // const bool present = phs.count(&pc[i]); // assert(present == ((0 == i % 7) && (0 != i % 3))); // } //.. // Finally, we clean up our 'pc' array: //.. // ta.deallocate(pc); //.. #include <bslscm_version.h> #include <bslalg_bidirectionallink.h> #include <bslalg_scalarprimitives.h> #include <bslmf_istriviallycopyable.h> #include <bslmf_nestedtraitdeclaration.h> #include <bsls_assert.h> #include <bsls_nativestd.h> #include <cstddef> namespace BloombergLP { namespace bslalg { struct HashTableBucket; // This is known to be a POD struct. // ============================= // class bslalg::HashTableAnchor // ============================= class HashTableAnchor { // This complex constrained *in*-*core* (value-semantic) attribute class // characterizes the key data elements of a hash table. See the // "Attributes" section under @DESCRIPTION in the component-level // documentation for/ information on the class attributes. Note that the // class invariant is the identically the complex constraint of this // component. // // This class: //: o supports a complete set of *value-semantic* operations //: o except for 'bdex' serialization and default construction //: o is *in-core* //: o is *exception-neutral* (agnostic) //: o is *alias-safe* //: o is 'const' *thread-safe* // For terminology see 'bsldoc_glossary'. // DATA HashTableBucket *d_bucketArrayAddress_p; // address of the array of // buckets (held, not owned) native_std::size_t d_bucketArraySize; // size of 'd_bucketArray' BidirectionalLink *d_listRootAddress_p; // head of the list of // elements in the hash-table // (held, not owned) public: // TRAITS BSLMF_NESTED_TRAIT_DECLARATION(HashTableAnchor, bsl::is_trivially_copyable); // CREATORS HashTableAnchor(HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize, BidirectionalLink *listRootAddress); // Create a 'bslalg::HashTableAnchor' object having the specified // 'bucketArrayAddress', 'bucketArraySize', and 'listRootAddress' // attributes. The behavior is undefined unless 'bucketArrayAddress' // refers to a contiguous sequence of valid 'bslalg::HashTableBucket' // objects of at least 'bucketArraySize' or unless both // 'bucketArrayAddress' and 'bucketArraySize' are 0. HashTableAnchor(const HashTableAnchor& original); // Create a 'bslalg::HashTableAnchor' object having the same value // as the specified 'original' object. // ~bslalg::HashTableAnchor(); = default // Destroy this object. // MANIPULATORS bslalg::HashTableAnchor& operator=(const bslalg::HashTableAnchor& rhs); // Assign to this object the value of the specified 'rhs' object, and // return a reference providing modifiable access to this object. void setBucketArrayAddressAndSize(HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize); // Set the bucket array address and bucket array size attributes of // this object to the specified 'bucketArrayAddress' and // 'bucketArraySize' values. The behavior is undefined unless // 'bucketArrayAddress' refers to a contiguous sequence of valid // 'bslalg::HashTableBucket' objects of at least 'bucketArraySize', or // unless both 'bucketArrayAddress' and 'bucketArraySize' are 0. void setListRootAddress(BidirectionalLink *value); // Set the 'listRootAddress' attribute of this object to the // specified 'value'. // Aspects void swap(HashTableAnchor& other); // Efficiently exchange the value of this object with the value of the // specified 'other' object. This method provides the no-throw // exception-safety guarantee. // ACCESSORS HashTableBucket *bucketArrayAddress() const; // Return the value of the 'bucketArrayAddress' attribute of this // object. native_std::size_t bucketArraySize() const; // Return the value of the 'bucketArraySize' attribute of this object. BidirectionalLink *listRootAddress() const; // Return the value 'listRootAddress' attribute of this object. }; // FREE OPERATORS bool operator==(const HashTableAnchor& lhs, const HashTableAnchor& rhs); // Return 'true' if the specified 'lhs' and 'rhs' objects have the same // value, and 'false' otherwise. Two 'bslalg::HashTableAnchor' objects // have the same value if all of the corresponding values of their // 'bucketArrayAddress', 'bucketArraySize', and 'listRootAddress' // attributes are the same. bool operator!=(const HashTableAnchor& lhs, const HashTableAnchor& rhs); // Return 'true' if the specified 'lhs' and 'rhs' objects do not have the // same value, and 'false' otherwise. Two 'bslalg::HashTableAnchor' // objects do not have the same value if any of the corresponding values of // their 'bucketArrayAddress', 'bucketArraySize', or 'listRootAddress' // attributes are not the same. // FREE FUNCTIONS void swap(HashTableAnchor& a, HashTableAnchor& b); // Efficiently exchange the values of the specified 'a' and 'b' objects. // This function provides the no-throw exception-safety guarantee. The // behavior is undefined unless the two objects were created with the same // allocator. // ============================================================================ // INLINE FUNCTION DEFINITIONS // ============================================================================ // ----------------------------- // class bslalg::HashTableAnchor // ----------------------------- // CREATORS inline HashTableAnchor::HashTableAnchor(bslalg::HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize, bslalg::BidirectionalLink *listRootAddress) : d_bucketArrayAddress_p(bucketArrayAddress) , d_bucketArraySize(bucketArraySize) , d_listRootAddress_p(listRootAddress) { BSLS_ASSERT_SAFE( (!bucketArrayAddress && !bucketArraySize) || (bucketArrayAddress && 0 < bucketArraySize)); BSLS_ASSERT_SAFE(!listRootAddress || !(listRootAddress->previousLink())); } inline HashTableAnchor::HashTableAnchor(const HashTableAnchor& original) : d_bucketArrayAddress_p(original.d_bucketArrayAddress_p) , d_bucketArraySize(original.d_bucketArraySize) , d_listRootAddress_p(original.d_listRootAddress_p) { } // MANIPULATORS inline HashTableAnchor& HashTableAnchor::operator=(const HashTableAnchor& rhs) { d_bucketArrayAddress_p = rhs.d_bucketArrayAddress_p; d_bucketArraySize = rhs.d_bucketArraySize; d_listRootAddress_p = rhs.d_listRootAddress_p; return *this; } inline void HashTableAnchor::setBucketArrayAddressAndSize( HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize) { BSLS_ASSERT_SAFE(( bucketArrayAddress && 0 < bucketArraySize) || (!bucketArrayAddress && !bucketArraySize)); d_bucketArrayAddress_p = bucketArrayAddress; d_bucketArraySize = bucketArraySize; } inline void HashTableAnchor::setListRootAddress(BidirectionalLink *value) { BSLS_ASSERT_SAFE(!value || !value->previousLink()); d_listRootAddress_p = value; } // Aspects inline void HashTableAnchor::swap(HashTableAnchor& other) { bslalg::ScalarPrimitives::swap(*this, other); } // ACCESSORS inline BidirectionalLink *HashTableAnchor::listRootAddress() const { return d_listRootAddress_p; } inline std::size_t HashTableAnchor::bucketArraySize() const { return d_bucketArraySize; } inline HashTableBucket *HashTableAnchor::bucketArrayAddress() const { return d_bucketArrayAddress_p; } } // close package namespace // FREE OPERATORS inline void bslalg::swap(bslalg::HashTableAnchor& a, bslalg::HashTableAnchor& b) { a.swap(b); } inline bool bslalg::operator==(const bslalg::HashTableAnchor& lhs, const bslalg::HashTableAnchor& rhs) { return lhs.bucketArrayAddress() == rhs.bucketArrayAddress() && lhs.bucketArraySize() == rhs.bucketArraySize() && lhs.listRootAddress() == rhs.listRootAddress(); } inline bool bslalg::operator!=(const bslalg::HashTableAnchor& lhs, const bslalg::HashTableAnchor& rhs) { return lhs.bucketArrayAddress() != rhs.bucketArrayAddress() || lhs.bucketArraySize() != rhs.bucketArraySize() || lhs.listRootAddress() != rhs.listRootAddress(); } } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
1
high
bin/varnishd/storage/storage_persistent_silo.c
konstantin-f/varnish-cache
0
685001
<filename>bin/varnishd/storage/storage_persistent_silo.c<gh_stars>0 /*- * Copyright (c) 2008-2011 Varnish Software AS * All rights reserved. * * Author: <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * Persistent storage method * * XXX: Before we start the client or maybe after it stops, we should give the * XXX: stevedores a chance to examine their storage for consistency. * */ #include "config.h" #include "cache/cache.h" #include <stdio.h> #include <stdlib.h> #include "storage/storage.h" #include "storage/storage_simple.h" #include "hash/hash_slinger.h" #include "vsha256.h" #include "vend.h" #include "vtim.h" #include "storage/storage_persistent.h" /* * We use the top bit to mark objects still needing fixup * In theory this may need to be platform dependent */ #define NEED_FIXUP (1U << 31) /*-------------------------------------------------------------------- * Write the segmentlist back to the silo. * * We write the first copy, sync it synchronously, then write the * second copy and sync it synchronously. * * Provided the kernel doesn't lie, that means we will always have * at least one valid copy on in the silo. */ static void smp_save_seg(const struct smp_sc *sc, struct smp_signspace *spc) { struct smp_segptr *ss; struct smp_seg *sg; uint64_t length; Lck_AssertHeld(&sc->mtx); smp_reset_signspace(spc); ss = SIGNSPACE_DATA(spc); length = 0; VTAILQ_FOREACH(sg, &sc->segments, list) { assert(sg->p.offset < sc->mediasize); assert(sg->p.offset + sg->p.length <= sc->mediasize); *ss = sg->p; ss++; length += sizeof *ss; } smp_append_signspace(spc, length); smp_sync_sign(&spc->ctx); } void smp_save_segs(struct smp_sc *sc) { struct smp_seg *sg, *sg2; Lck_AssertHeld(&sc->mtx); /* * Remove empty segments from the front of the list * before we write the segments to disk. */ VTAILQ_FOREACH_SAFE(sg, &sc->segments, list, sg2) { if (sg->nobj > 0) break; if (sg == sc->cur_seg) continue; VTAILQ_REMOVE(&sc->segments, sg, list); AN(VTAILQ_EMPTY(&sg->objcores)); FREE_OBJ(sg); } smp_save_seg(sc, &sc->seg1); smp_save_seg(sc, &sc->seg2); } /*-------------------------------------------------------------------- * Load segments * * The overall objective is to register the existence of an object, based * only on the minimally sized struct smp_object, without causing the * main object to be faulted in. * * XXX: We can test this by mprotecting the main body of the segment * XXX: until the first fixup happens, or even just over this loop, * XXX: However: the requires that the smp_objects starter further * XXX: into the segment than a page so that they do not get hit * XXX: by the protection. */ void smp_load_seg(struct worker *wrk, const struct smp_sc *sc, struct smp_seg *sg) { struct smp_object *so; struct objcore *oc; struct ban *ban; uint32_t no; double t_now = VTIM_real(); struct smp_signctx ctx[1]; ASSERT_SILO_THREAD(sc); CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(sg, SMP_SEG_MAGIC); assert(sg->flags & SMP_SEG_MUSTLOAD); sg->flags &= ~SMP_SEG_MUSTLOAD; AN(sg->p.offset); if (sg->p.objlist == 0) return; smp_def_sign(sc, ctx, sg->p.offset, "SEGHEAD"); if (smp_chk_sign(ctx)) return; /* test SEGTAIL */ /* test OBJIDX */ so = (void*)(sc->base + sg->p.objlist); sg->objs = so; no = sg->p.lobjlist; /* Clear the bogus "hold" count */ sg->nobj = 0; for (;no > 0; so++,no--) { if (EXP_WHEN(so) < t_now) continue; ban = BAN_FindBan(so->ban); AN(ban); oc = ObjNew(wrk); oc->stobj->stevedore = sc->parent; smp_init_oc(oc, sg, no); VTAILQ_INSERT_TAIL(&sg->objcores, oc, lru_list); oc->stobj->priv2 |= NEED_FIXUP; EXP_COPY(oc, so); sg->nobj++; oc->refcnt++; HSH_Insert(wrk, so->hash, oc, ban); AN(oc->ban); HSH_DerefBoc(wrk, oc); // XXX Keep it an stream resurrection? (void)HSH_DerefObjCore(wrk, &oc, HSH_RUSH_POLICY); wrk->stats->n_vampireobject++; } Pool_Sumstat(wrk); sg->flags |= SMP_SEG_LOADED; } /*-------------------------------------------------------------------- * Create a new segment */ void smp_new_seg(struct smp_sc *sc) { struct smp_seg tmpsg; struct smp_seg *sg; AZ(sc->cur_seg); Lck_AssertHeld(&sc->mtx); /* XXX: find where it goes in silo */ INIT_OBJ(&tmpsg, SMP_SEG_MAGIC); tmpsg.sc = sc; tmpsg.p.offset = sc->free_offset; /* XXX: align */ assert(tmpsg.p.offset >= sc->ident->stuff[SMP_SPC_STUFF]); assert(tmpsg.p.offset < sc->mediasize); tmpsg.p.length = sc->aim_segl; tmpsg.p.length = RDN2(tmpsg.p.length, 8); if (smp_segend(&tmpsg) > sc->mediasize) /* XXX: Consider truncation in this case */ tmpsg.p.offset = sc->ident->stuff[SMP_SPC_STUFF]; assert(smp_segend(&tmpsg) <= sc->mediasize); sg = VTAILQ_FIRST(&sc->segments); if (sg != NULL && tmpsg.p.offset <= sg->p.offset) { if (smp_segend(&tmpsg) > sg->p.offset) /* No more space, return (cur_seg will be NULL) */ /* XXX: Consider truncation instead of failing */ return; assert(smp_segend(&tmpsg) <= sg->p.offset); } if (tmpsg.p.offset == sc->ident->stuff[SMP_SPC_STUFF]) printf("Wrapped silo\n"); ALLOC_OBJ(sg, SMP_SEG_MAGIC); if (sg == NULL) return; *sg = tmpsg; VTAILQ_INIT(&sg->objcores); sg->p.offset = IRNUP(sc, sg->p.offset); sg->p.length -= sg->p.offset - tmpsg.p.offset; sg->p.length = IRNDN(sc, sg->p.length); assert(sg->p.offset + sg->p.length <= tmpsg.p.offset + tmpsg.p.length); sc->free_offset = sg->p.offset + sg->p.length; VTAILQ_INSERT_TAIL(&sc->segments, sg, list); /* Neuter the new segment in case there is an old one there */ AN(sg->p.offset); smp_def_sign(sc, sg->ctx, sg->p.offset, "SEGHEAD"); smp_reset_sign(sg->ctx); smp_sync_sign(sg->ctx); /* Set up our allocation points */ sc->cur_seg = sg; sc->next_bot = sg->p.offset + IRNUP(sc, SMP_SIGN_SPACE); sc->next_top = smp_segend(sg); sc->next_top -= IRNUP(sc, SMP_SIGN_SPACE); IASSERTALIGN(sc, sc->next_bot); IASSERTALIGN(sc, sc->next_top); sg->objs = (void*)(sc->base + sc->next_top); } /*-------------------------------------------------------------------- * Close a segment */ void smp_close_seg(struct smp_sc *sc, struct smp_seg *sg) { uint64_t left, dst, len; void *dp; Lck_AssertHeld(&sc->mtx); CHECK_OBJ_NOTNULL(sg, SMP_SEG_MAGIC); assert(sg == sc->cur_seg); AN(sg->p.offset); sc->cur_seg = NULL; if (sg->nalloc == 0) { /* If segment is empty, delete instead */ VTAILQ_REMOVE(&sc->segments, sg, list); assert(sg->p.offset >= sc->ident->stuff[SMP_SPC_STUFF]); assert(sg->p.offset < sc->mediasize); sc->free_offset = sg->p.offset; AN(VTAILQ_EMPTY(&sg->objcores)); FREE_OBJ(sg); return; } /* * If there is enough space left, that we can move the smp_objects * down without overwriting the present copy, we will do so to * compact the segment. */ left = smp_spaceleft(sc, sg); len = sizeof(struct smp_object) * sg->p.lobjlist; if (len < left) { dst = sc->next_bot + IRNUP(sc, SMP_SIGN_SPACE); dp = sc->base + dst; assert((uintptr_t)dp + len < (uintptr_t)sg->objs); memcpy(dp, sg->objs, len); sc->next_top = dst; sg->objs = dp; sg->p.length = (sc->next_top - sg->p.offset) + len + IRNUP(sc, SMP_SIGN_SPACE); (void)smp_spaceleft(sc, sg); /* for the asserts */ } /* Update the segment header */ sg->p.objlist = sc->next_top; /* Write the (empty) OBJIDX signature */ sc->next_top -= IRNUP(sc, SMP_SIGN_SPACE); assert(sc->next_top >= sc->next_bot); smp_def_sign(sc, sg->ctx, sc->next_top, "OBJIDX"); smp_reset_sign(sg->ctx); smp_sync_sign(sg->ctx); /* Write the (empty) SEGTAIL signature */ smp_def_sign(sc, sg->ctx, sg->p.offset + sg->p.length - IRNUP(sc, SMP_SIGN_SPACE), "SEGTAIL"); smp_reset_sign(sg->ctx); smp_sync_sign(sg->ctx); /* Save segment list */ smp_save_segs(sc); sc->free_offset = smp_segend(sg); } /*--------------------------------------------------------------------- */ static struct smp_object * smp_find_so(const struct smp_seg *sg, unsigned priv2) { struct smp_object *so; priv2 &= ~NEED_FIXUP; assert(priv2 > 0); assert(priv2 <= sg->p.lobjlist); so = &sg->objs[sg->p.lobjlist - priv2]; return (so); } /*--------------------------------------------------------------------- * Check if a given storage structure is valid to use */ static int smp_loaded_st(const struct smp_sc *sc, const struct smp_seg *sg, const struct storage *st) { struct smp_seg *sg2; const uint8_t *pst; uint64_t o; (void)sg; /* XXX: faster: Start search from here */ pst = (const void *)st; if (pst < (sc->base + sc->ident->stuff[SMP_SPC_STUFF])) return (0x01); /* Before silo payload start */ if (pst > (sc->base + sc->ident->stuff[SMP_END_STUFF])) return (0x02); /* After silo end */ o = pst - sc->base; /* Find which segment contains the storage structure */ VTAILQ_FOREACH(sg2, &sc->segments, list) if (o > sg2->p.offset && (o + sizeof(*st)) < sg2->p.objlist) break; if (sg2 == NULL) return (0x04); /* No claiming segment */ if (!(sg2->flags & SMP_SEG_LOADED)) return (0x08); /* Claiming segment not loaded */ /* It is now safe to access the storage structure */ if (st->magic != STORAGE_MAGIC) return (0x10); /* Not enough magic */ if (o + st->space >= sg2->p.objlist) return (0x20); /* Allocation not inside segment */ if (st->len > st->space) return (0x40); /* Plain bad... */ /* * XXX: We could patch up st->stevedore and st->priv here * XXX: but if things go right, we will never need them. */ return (0); } /*--------------------------------------------------------------------- * objcore methods for persistent objects */ struct object * __match_proto__(sml_getobj_f) smp_sml_getobj(struct worker *wrk, struct objcore *oc) { struct object *o; struct smp_seg *sg; struct smp_object *so; struct storage *st; uint64_t l; int bad; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); AN(oc->stobj->stevedore); CAST_OBJ_NOTNULL(sg, oc->stobj->priv, SMP_SEG_MAGIC); so = smp_find_so(sg, oc->stobj->priv2); o = (void*)(sg->sc->base + so->ptr); /* * The object may not be in this segment since we allocate it * In a separate operation than the smp_object. We could check * that it is in a later segment, but that would be complicated. * XXX: For now, be happy if it is inside the silo */ ASSERT_PTR_IN_SILO(sg->sc, o); CHECK_OBJ_NOTNULL(o, OBJECT_MAGIC); /* * If this flag is not set, it will not be, and the lock is not * needed to test it. */ if (!(oc->stobj->priv2 & NEED_FIXUP)) return (o); Lck_Lock(&sg->sc->mtx); /* Check again, we might have raced. */ if (oc->stobj->priv2 & NEED_FIXUP) { /* We trust caller to have a refcnt for us */ bad = 0; l = 0; VTAILQ_FOREACH(st, &o->list, list) { bad |= smp_loaded_st(sg->sc, sg, st); if (bad) break; l += st->len; } if (l != vbe64dec(o->fa_len)) bad |= 0x100; if (bad) { EXP_ZERO(oc); EXP_ZERO(so); } sg->nfixed++; wrk->stats->n_object++; wrk->stats->n_vampireobject--; oc->stobj->priv2 &= ~NEED_FIXUP; } Lck_Unlock(&sg->sc->mtx); return (o); } void __match_proto__(objfree_f) smp_oc_objfree(struct worker *wrk, struct objcore *oc) { struct smp_seg *sg; struct smp_object *so; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); CAST_OBJ_NOTNULL(sg, oc->stobj->priv, SMP_SEG_MAGIC); so = smp_find_so(sg, oc->stobj->priv2); Lck_Lock(&sg->sc->mtx); EXP_ZERO(so); so->ptr = 0; assert(sg->nobj > 0); sg->nobj--; if (oc->stobj->priv2 & NEED_FIXUP) { wrk->stats->n_vampireobject--; } else { assert(sg->nfixed > 0); sg->nfixed--; wrk->stats->n_object--; } VTAILQ_REMOVE(&sg->objcores, oc, lru_list); Lck_Unlock(&sg->sc->mtx); memset(oc->stobj, 0, sizeof oc->stobj); } /*--------------------------------------------------------------------*/ void smp_init_oc(struct objcore *oc, struct smp_seg *sg, unsigned objidx) { AZ(objidx & NEED_FIXUP); oc->stobj->priv = sg; oc->stobj->priv2 = objidx; } /*--------------------------------------------------------------------*/ void __match_proto__(obj_event_f) smp_oc_event(struct worker *wrk, void *priv, struct objcore *oc, unsigned ev) { struct stevedore *st; struct smp_seg *sg; struct smp_object *so; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CAST_OBJ_NOTNULL(st, priv, STEVEDORE_MAGIC); CHECK_OBJ_NOTNULL(oc, OBJCORE_MAGIC); if (oc->stobj->stevedore != st) return; CAST_OBJ_NOTNULL(sg, oc->stobj->priv, SMP_SEG_MAGIC); CHECK_OBJ_NOTNULL(sg->sc, SMP_SC_MAGIC); so = smp_find_so(sg, oc->stobj->priv2); if (sg == sg->sc->cur_seg) { /* Lock necessary, we might race close_seg */ Lck_Lock(&sg->sc->mtx); if (ev & (OEV_BANCHG|OEV_INSERT)) so->ban = BAN_Time(oc->ban); if (ev & (OEV_TTLCHG|OEV_INSERT)) EXP_COPY(so, oc); Lck_Unlock(&sg->sc->mtx); } else { if (ev & (OEV_BANCHG|OEV_INSERT)) so->ban = BAN_Time(oc->ban); if (ev & (OEV_TTLCHG|OEV_INSERT)) EXP_COPY(so, oc); } }
0.996094
high
Algorithms/linked list/singly linked list.c
TeacherManoj0131/HacktoberFest2020-Contributions
256
8483840
<gh_stars>100-1000 #include <stdio.h> #include <stdlib.h> struct node { int key; struct node* link; }; typedef struct node NODE; struct list { NODE *head; }; typedef struct list LIST; void init(LIST*); void read_priority(LIST*); void insert_at_pos(LIST*); void insert_at_head(LIST*); void insert_at_tail(LIST*); void delete_priority(LIST*); void delete_at_pos(LIST*); void delete_head(LIST*); void delete_tail(LIST*); void delete_first_occurence(LIST*); void delete_last_occurence(LIST*); void delete_all_occurence(LIST*); void display(LIST*); void display_recursive(NODE*); void find(LIST*); int count(LIST*); void merge(LIST*, LIST*); void merge_sorted(LIST*, LIST*); void union_lists(LIST*,LIST*,LIST*); void intersection(LIST*,LIST*,LIST*); void reverse(LIST*); void destroy(LIST*); int main() { LIST *l = (LIST*)malloc(sizeof(LIST)); init(l); int n; printf("Enter number of nodes for list 1 : "); scanf("%d",&n); for (int i = 0;i<n;i++) read_priority(l); display(l); reverse(l); display(l); //insert_at_tail(l); //insert_at_pos(l); //insert_at_head(l); //insert_at_tail(l); //delete_priority(l); //delete_head(l); //delete_tail(l); //delete_at_pos(l); //delete_first_occurence(l); //delete_last_occurence(l); //delete_all_occurence(l); //printf("Number of nodes = %d\n", count(l)); //find(l); //display_recursive(l->head); #if 0 LIST *l2 = (LIST*)malloc(sizeof(LIST)); init(l2); printf("Enter number of nodes for list 2 : "); scanf("%d",&n); for (int i = 0;i<n;i++) read_priority(l2); display(l2); #endif #if 0 LIST *l3 = (LIST*)malloc(sizeof(LIST)); LIST *l4 = (LIST*)malloc(sizeof(LIST)); init(l3); init(l4); union_lists(l,l2,l3); intersection(l,l2,l4); display(l3); display(l4); #endif destroy(l); } void init(LIST* l) { l->head = NULL; } void read_priority(LIST* l) { NODE* node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); if (l->head == NULL) { l->head = node; } else { NODE *prev = NULL; NODE *pres = l->head; while (pres!=NULL && pres->key<node->key) { prev = pres; pres = pres->link; } if (prev==NULL) { node->link = l->head; l->head = node; } else { prev->link = node; node->link = pres; } } } void display(LIST* l) { NODE* node = l->head; while(node!=NULL) { printf("%d ",node->key); node = node->link; } printf("\n"); } void display_recursive(NODE *node) { if(node!=NULL) { printf("%d ",node->key); display_recursive(node->link); } } void insert_at_pos(LIST* l) { //printf("Inserting at position\n"); NODE* node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); printf("Enter a position : "); int pos; scanf("%d", &pos); if(l->head==NULL) { l->head = node; } else { NODE *prev = NULL; NODE *pres = l->head; int ctr = 0; while(pres!=NULL && ctr<pos) { prev = pres; pres = pres->link; ctr++; } if (prev == NULL) { node->link = l->head; l->head = node; } else { prev->link = node; node->link = pres; } } } void insert_at_head(LIST* l) { //printf("Inserting at head\n"); NODE *node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); if(l->head == NULL) l->head = node; else { node->link = l->head; l->head = node; } } void insert_at_tail(LIST *l) { //printf("Inserting at tail\n"); NODE *node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; printf("Enter value : "); scanf("%d", &(node->key)); if(l->head == NULL) l->head = node; else { NODE *prev = NULL; NODE *pres = l->head; while (pres!=NULL) { prev = pres; pres = pres->link; } prev->link = node; node->link = pres; //pres is null } } void delete_priority(LIST *l) { if(l->head != NULL) { NODE* prev = NULL; NODE* pres = l->head; NODE* max = NULL; int mval = l->head->key; while(pres!=NULL) { if(pres->key>mval) { max = prev; mval = pres->key; } prev = pres; pres = pres->link; } if (max == NULL) { NODE *temp = l->head; l->head = l->head->link; free(temp); } else { NODE* temp = max->link; max->link = max->link->link; free(temp); } } } void delete_at_pos(LIST* l) { int pos; printf("Enter position to delete at : "); scanf("%d", &pos); if(l->head!=NULL) { NODE* prev = NULL; NODE* pres = l->head; int ctr = 0; while(pres!=NULL && ctr<pos) { prev = pres; pres = pres->link; ctr++; } if (prev==NULL) { l->head = pres->link; free(pres); } else { prev->link = pres->link; free(pres); } } } void delete_tail(LIST *l) { NODE *prev = NULL; NODE *pres = l->head; if (pres == NULL) printf("EMPTY\n"); else { while (pres->link!=NULL) { prev = pres; pres = pres->link; } if(prev==NULL) l->head = NULL; else prev->link = NULL; free(pres); } } void delete_head(LIST *l) { if(l->head != NULL) { NODE *temp = l->head; l->head = l->head->link; free(temp); } } void delete_first_occurence(LIST *l) { if (l->head != NULL) { printf("Enter element to delete : "); int val; scanf("%d", &val); NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if (pres->key == val) { if (prev == NULL) { NODE *temp = l->head; l->head = l->head->link; free(temp); } else { prev->link = pres->link; free(pres); } break; } prev = pres; pres = pres->link; } } } void delete_last_occurence(LIST *l) { if(l->head!=NULL) { int pos = 0, ctr = 0; printf("Enter element to delete : "); int val; scanf("%d", &val); NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if(pres->key == val) pos = ctr; prev = pres; pres = pres->link; ctr+=1; } prev = NULL; pres = l->head; ctr = 0; while(pres!=NULL && ctr<pos) { prev = pres; pres = pres->link; ctr++; } if (prev==NULL) { l->head = pres->link; free(pres); } else { prev->link = pres->link; free(pres); } } } void delete_all_occurence(LIST *l) { if(l->head != NULL) { printf("Enter element to delete : "); int val; scanf("%d", &val); NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if(pres->key == val) { if(prev==NULL) { pres=pres->link; l->head = pres; } else { pres = pres->link; prev->link = pres; } } else { prev = pres; pres = pres->link; } } } } int count(LIST *l) { int ctr = 0; if (l->head == NULL) return 0; else { NODE *node = l->head; while (node!=NULL) { ctr++; node = node->link; } return ctr; } } void destroy(LIST *l) { NODE *prev = NULL; NODE *pres = l->head; while(pres!=NULL) { prev = pres; pres = pres->link; free(prev); } } void find(LIST *l) { printf("Enter element to find : "); int s; scanf("%d", &s); int pos = -1; if(l->head == NULL) printf("Index = %d\n", pos); else { int ctr = 0; NODE* prev = NULL; NODE* pres = l->head; while(pres!=NULL) { if(s==pres->key) pos = ctr; prev = pres; pres = pres->link; ctr++; } printf("Index = %d\n", pos); } } void merge(LIST *l1, LIST *l2) { if(l1->head==NULL) { if(l2->head!=NULL) { l1->head=l2->head; l2->head=NULL; } } else { NODE *prev = NULL; NODE *pres = l1->head; while(pres!=NULL) { prev = pres; pres=pres->link; } prev->link = l2->head; l2->head=NULL; } } void merge_sorted(LIST *l1, LIST *l2) { if (l1->head!=NULL && l2->head!=NULL) { NODE *prev = NULL; NODE *pres = l2->head; NODE *temp1 = NULL; NODE *temp2 = l1->head; while(pres!=NULL) { NODE *node = (NODE*)malloc(sizeof(NODE)); node->key = pres->key; node->link = NULL; temp1 = NULL; temp2 = l1->head; while(temp2!=NULL && temp2->key<=node->key) { temp1 = temp2; temp2=temp2->link; } if (temp1==NULL) { node->link = l1->head; l1->head = node; } else { temp1->link = node; node->link = temp2; } pres = pres->link; } } } void insert(LIST *l, int val) { NODE* node = (NODE*)malloc(sizeof(NODE)); node->link = NULL; node->key = val; if (l->head == NULL) { l->head = node; } else { NODE *prev = NULL; NODE *pres = l->head; while (pres!=NULL && pres->key<node->key) { prev = pres; pres = pres->link; } if (prev==NULL) { node->link = l->head; l->head = node; } else { prev->link = node; node->link = pres; } } } void check(LIST *l1,LIST *l3) { NODE *pres1 = l1->head; while(pres1!=NULL) { NODE *pres2 = l3->head; int ctr = 0; while(pres2!=NULL) { if (pres1->key==pres2->key) ctr++; pres2 = pres2->link; } if (ctr==0) { insert(l3,pres1->key); } pres1 = pres1->link; } } void union_lists(LIST* l1, LIST *l2, LIST *l3) { check(l1,l3); check(l2,l3); } void intersection(LIST *l1, LIST *l2, LIST *l3) { NODE *node1 = l1->head; int flag; while(node1!=NULL) { flag = 0; NODE *node2 = l2->head; while(node2!=NULL) { if (node2->key==node1->key) { flag = 1; break; } node2 = node2->link; } if (flag==1) { insert(l3,node1->key); } node1=node1->link; } } void reverse(LIST *l) { NODE *pres = l->head; NODE *prev = NULL; NODE *temp = NULL; while(pres!=NULL) { temp = pres->link; pres->link = prev; prev = pres; pres = temp; } l->head = prev; }
0.976563
high
08_Structs/src/main.c
rjbernaldo/c-programming-for-beginners
1
3875897
<filename>08_Structs/src/main.c #include <stdio.h> #include <string.h> #define NUMBER_OF_CDS 1 typedef struct cd CD; typedef char Str50[50]; struct cd { Str50 name[50]; Str50 artist[50]; int trackcount; int rating; }; CD cd_collection[NUMBER_OF_CDS]; void create_cd_collection() { strcpy(cd_collection[0].name, "Name"); strcpy(cd_collection[0].artist, "Artist"); cd_collection[0].trackcount = 1; cd_collection[0].rating = 10; } void display_cd_collection() { int i; CD thiscd; for (i = 0; i < NUMBER_OF_CDS; i++) { thiscd = cd_collection[i]; printf("CD #%d: %s - %s - %d - %d", i, thiscd.name, thiscd.artist, thiscd.trackcount, thiscd.rating); } } int main() { create_cd_collection(); display_cd_collection(); }
0.972656
high
examples/STM32_LAN8720/FullyFeatured_STM32_LAN8720/defines.h
khoih-prog/AsyncMQTT_Generic
4
2337889
/**************************************************************************************************************************** defines.h defines.h AsyncMqttClient_Generic is a library for ESP32, ESP8266, Protenta_H7, STM32F7, etc. with current AsyncTCP support Based on and modified from : 1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client) Built by <NAME> https://github.com/khoih-prog/AsyncMqttClient_Generic *****************************************************************************************************************************/ #ifndef defines_h #define defines_h #if !( defined(ARDUINO_BLACK_F407VE) || defined(ARDUINO_BLACK_F407VG) || defined(ARDUINO_BLACK_F407ZE) || defined(ARDUINO_BLACK_F407ZG) || \ defined(ARDUINO_BLUE_F407VE_Mini) || defined(ARDUINO_DIYMORE_F407VGT) || defined(ARDUINO_FK407M1) || defined(ARDUINO_NUCLEO_F429ZI) || \ defined(ARDUINO_DISCO_F746NG) || defined(ARDUINO_NUCLEO_F746ZG) || defined(ARDUINO_NUCLEO_F756ZG) || defined(ARDUINO_NUCLEO_H743ZI) ) //#error This code is designed to run on some STM32F407XX NUCLEO-F429ZI, STM32F746 and STM32F756 platform! Please check your Tools->Board setting. #endif // Use from 0 to 4. Higher number, more debugging messages and memory usage. #define _ASYNC_MQTT_LOGLEVEL_ 1 #define USING_LAN8720 true #if defined(STM32F0) #warning STM32F0 board selected #define BOARD_TYPE "STM32F0" #elif defined(STM32F1) #warning STM32F1 board selected #define BOARD_TYPE "STM32F1" #elif defined(STM32F2) #warning STM32F2 board selected #define BOARD_TYPE "STM32F2" #elif defined(STM32F3) #warning STM32F3 board selected #define BOARD_TYPE "STM32F3" #elif defined(STM32F4) #warning STM32F4 board selected #define BOARD_TYPE "STM32F4" #elif defined(STM32F7) #warning STM32F7 board selected #define BOARD_TYPE "STM32F7" #elif defined(STM32L0) #warning STM32L0 board selected #define BOARD_TYPE "STM32L0" #elif defined(STM32L1) #warning STM32L1 board selected #define BOARD_TYPE "STM32L1" #elif defined(STM32L4) #warning STM32L4 board selected #define BOARD_TYPE "STM32L4" #elif defined(STM32H7) #warning STM32H7 board selected #define BOARD_TYPE "STM32H7" #elif defined(STM32G0) #warning STM32G0 board selected #define BOARD_TYPE "STM32G0" #elif defined(STM32G4) #warning STM32G4 board selected #define BOARD_TYPE "STM32G4" #elif defined(STM32WB) #warning STM32WB board selected #define BOARD_TYPE "STM32WB" #elif defined(STM32MP1) #warning STM32MP1 board selected #define BOARD_TYPE "STM32MP1" #else #warning STM32 unknown board selected #define BOARD_TYPE "STM32 Unknown" #endif #ifndef BOARD_NAME #define BOARD_NAME BOARD_TYPE #endif #define SHIELD_TYPE "LAN8720 Ethernet" #include <LwIP.h> #include <STM32Ethernet.h> //#include <AsyncWebServer_STM32.h> // Enter a MAC address and IP address for your controller below. #define NUMBER_OF_MAC 20 byte mac[][NUMBER_OF_MAC] = { { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x01 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x02 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x03 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x04 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x05 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x06 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x07 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x08 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x09 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0A }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0B }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0C }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0D }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0E }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x0F }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x10 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x11 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x12 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x13 }, { 0xDE, 0xAD, 0xBE, 0xEF, 0x32, 0x14 }, }; // Select the IP address according to your local network IPAddress ip(192, 168, 2, 232); #endif //defines_h
0.972656
high
tests/demo/Demo.h
kan-xyz/Arc
4
5533425
#pragma once namespace Demo { void Demo(); }
0.929688
low
Libraries/LibJS/Interpreter.h
jcs/serenity
9
3330856
<reponame>jcs/serenity /* * Copyright (c) 2020, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #pragma once #include <AK/FlyString.h> #include <AK/HashMap.h> #include <AK/String.h> #include <AK/Vector.h> #include <LibJS/Forward.h> #include <LibJS/Heap/Heap.h> #include <LibJS/Runtime/Exception.h> #include <LibJS/Runtime/Value.h> namespace JS { enum class ScopeType { None, Function, Block, Try, Breakable, Continuable, }; struct Variable { Value value; DeclarationKind declaration_kind; }; struct ScopeFrame { ScopeType type; NonnullRefPtr<ScopeNode> scope_node; HashMap<FlyString, Variable> variables; }; struct CallFrame { Value this_value; Vector<Value> arguments; }; struct Argument { FlyString name; Value value; }; typedef Vector<Argument, 8> ArgumentVector; class Interpreter { public: template<typename GlobalObjectType, typename... Args> static NonnullOwnPtr<Interpreter> create(Args&&... args) { auto interpreter = adopt_own(*new Interpreter); interpreter->m_global_object = interpreter->heap().allocate<GlobalObjectType>(forward<Args>(args)...); return interpreter; } ~Interpreter(); Value run(const Statement&, ArgumentVector = {}, ScopeType = ScopeType::Block); GlobalObject& global_object(); const GlobalObject& global_object() const; Heap& heap() { return m_heap; } void unwind(ScopeType type) { m_unwind_until = type; } void stop_unwind() { m_unwind_until = ScopeType::None; } bool should_unwind_until(ScopeType type) const { return m_unwind_until == type; } bool should_unwind() const { return m_unwind_until != ScopeType::None; } Optional<Value> get_variable(const FlyString& name); void set_variable(const FlyString& name, Value, bool first_assignment = false); void declare_variable(const FlyString& name, DeclarationKind); void gather_roots(Badge<Heap>, HashTable<Cell*>&); void enter_scope(const ScopeNode&, ArgumentVector, ScopeType); void exit_scope(const ScopeNode&); Value call(Function*, Value this_value = {}, const Vector<Value>& arguments = {}); CallFrame& push_call_frame() { m_call_stack.append({ js_undefined(), {} }); return m_call_stack.last(); } void pop_call_frame() { m_call_stack.take_last(); } const CallFrame& call_frame() { return m_call_stack.last(); } size_t argument_count() const { if (m_call_stack.is_empty()) return 0; return m_call_stack.last().arguments.size(); } Value argument(size_t index) const { if (m_call_stack.is_empty()) return {}; auto& arguments = m_call_stack.last().arguments; return index < arguments.size() ? arguments[index] : js_undefined(); } Value this_value() const { if (m_call_stack.is_empty()) return m_global_object; return m_call_stack.last().this_value; } Shape* empty_object_shape() { return m_empty_object_shape; } Object* string_prototype() { return m_string_prototype; } Object* object_prototype() { return m_object_prototype; } Object* array_prototype() { return m_array_prototype; } Object* error_prototype() { return m_error_prototype; } Object* date_prototype() { return m_date_prototype; } Object* function_prototype() { return m_function_prototype; } Object* number_prototype() { return m_number_prototype; } Object* boolean_prototype() { return m_boolean_prototype; } Exception* exception() { return m_exception; } void clear_exception() { m_exception = nullptr; } template<typename T, typename... Args> Value throw_exception(Args&&... args) { return throw_exception(heap().allocate<T>(forward<Args>(args)...)); } Value throw_exception(Exception*); Value throw_exception(Value value) { return throw_exception(heap().allocate<Exception>(value)); } Value last_value() const { return m_last_value; } private: Interpreter(); Heap m_heap; Value m_last_value; Vector<ScopeFrame> m_scope_stack; Vector<CallFrame> m_call_stack; Shape* m_empty_object_shape { nullptr }; Object* m_global_object { nullptr }; Object* m_string_prototype { nullptr }; Object* m_object_prototype { nullptr }; Object* m_array_prototype { nullptr }; Object* m_error_prototype { nullptr }; Object* m_date_prototype { nullptr }; Object* m_function_prototype { nullptr }; Object* m_number_prototype { nullptr }; Object* m_boolean_prototype { nullptr }; Exception* m_exception { nullptr }; ScopeType m_unwind_until { ScopeType::None }; }; }
1
high
JFilewraper/JCompressfile.h
WhiteGroup/JAV-AV-Engine
15
1659440
<reponame>WhiteGroup/JAV-AV-Engine #ifndef JCOMPRESSFILEH #define JCOMPRESSFILEH #include "Jfile.h" #include "IUnCompersser.h" class JCompressFile : public JFile { public : JCompressFile(); void SetCompressor(IUnCompersser *inposIUnCompersser); JString GetDisplayName () ; void SetDisplayName (JString i_strDisplayName) ; void GetShortName(JString &o_strShortPath , UINT32 MaxLenght) ; BOOLEAN Close(); BOOLEAN CloseHandle(); void SetFileAsVirus(); void SetFileAsWorm(); ~JCompressFile(); #ifdef JFILEKERNEL BOOLEAN OpenTempFile(JString &Name); static BOOLEAN DeleteForTemp(JString &Name); #endif private : JString m_strDisPlayName ; IUnCompersser *posIUnCompersser; BOOLEAN bIsInfected, bIsWorm; }; #endif
0.949219
high
ModelViewer/CropVectorsPage.h
scharlton2/modelviewer-mf6
1
4988400
#if !defined(AFX_CROPVECTORSPAGE_H__2447BF73_04BC_40D3_B68F_5B93BC61F475__INCLUDED_) #define AFX_CROPVECTORSPAGE_H__2447BF73_04BC_40D3_B68F_5B93BC61F475__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // CropVectorsPage.h : header file // class CMvDoc; class CVectorDlg; ///////////////////////////////////////////////////////////////////////////// // CCropVectorsPage dialog class CCropVectorsPage : public CPropertyPage { DECLARE_DYNCREATE(CCropVectorsPage) // Construction public: double m_XDelta; double m_XMax; double m_XMin; double m_YDelta; double m_YMax; double m_YMin; double m_ZDelta; double m_ZMax; double m_ZMin; int m_CropAngle; void OnDefault(); void Activate(BOOL b); void Reinitialize(); void Apply(); BOOL CustomUpdateData(BOOL b); CCropVectorsPage(); ~CCropVectorsPage(); CMvDoc* m_pDoc; // Dialog Data //{{AFX_DATA(CCropVectorsPage) enum { IDD = IDD_CROP_VECTORS }; // NOTE - ClassWizard will add data members here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CCropVectorsPage) public: protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // CVectorDlg *m_Parent; BOOL m_ExchangeData; BOOL m_IsActive; // Implementation protected: // Generated message map functions //{{AFX_MSG(CCropVectorsPage) afx_msg void OnDeltaposXminSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposXmaxSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposYminSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposYmaxSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposZminSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposZmaxSpin(NMHDR* pNMHDR, LRESULT* pResult); virtual BOOL OnInitDialog(); afx_msg void OnDeltaposCropAngleSpin(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() void AssignDefaultValues(); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CROPVECTORSPAGE_H__2447BF73_04BC_40D3_B68F_5B93BC61F475__INCLUDED_)
0.929688
high
src/yars/configuration/data/DataRecording.h
kzahedi/YARS
4
6517136
<gh_stars>1-10 #ifndef __DATA_RECORDING_H__ #define __DATA_RECORDING_H__ # define YARS_STRING_RECORDING (char*)"recording" # define YARS_STRING_RECORDING_DEFINITION (char*)"recording_definition" #include <yars/configuration/data/DataNode.h> #include <yars/configuration/data/DataParameter.h> #include <yars/configuration/data/DataActuator.h> #include <yars/types/Matrix.h> #include <yars/types/Domain.h> #include <map> #include <vector> #include <string> typedef __Domain<unsigned long> RecordingInterval; using namespace std; class DataRecording : public DataNode, public std::vector<RecordingInterval> { public: DataRecording(DataNode *parent); virtual ~DataRecording() { }; static void createXsd(XsdSpecification *spec); void add(DataParseElement *element); void resetTo(const DataRecording*); DataRecording* copy(); // returns true if current time step is within a recoding interval bool record(); }; #endif // __DATA_RECORDING_H__
0.976563
high
text/library/gpuimageplus/src/main/jni/include/cgeGLFunctions.h
qwertyezi/test
0
312688
<filename>text/library/gpuimageplus/src/main/jni/include/cgeGLFunctions.h /* * cgeGLFunctions.h * * Created on: 2013-12-5 * Author: <NAME> * Mail: <EMAIL> */ #ifndef _CGEGLFUNCTIONS_H_ #define _CGEGLFUNCTIONS_H_ #include "cgeCommonDefine.h" #include <cassert> #if defined(_CGE_DISABLE_GLOBALCONTEXT_) && _CGE_DISABLE_GLOBALCONTEXT_ #define CGE_ENABLE_GLOBAL_GLCONTEXT(...) #define CGE_DISABLE_GLOBAL_GLCONTEXT(...) #else #define CGE_ENABLE_GLOBAL_GLCONTEXT(...) cgeEnableGlobalGLContext() #define CGE_DISABLE_GLOBAL_GLCONTEXT(...) cgeDisableGlobalGLContext() #endif namespace CGE { #if !(defined(_CGE_DISABLE_GLOBALCONTEXT_) && _CGE_DISABLE_GLOBALCONTEXT_) typedef bool (*CGEEnableGLContextFunction)(void*); typedef bool (*CGEDisableGLContextFunction)(void*); void cgeSetGLContextEnableFunction(CGEEnableGLContextFunction func, void* param); void cgeSetGLContextDisableFunction(CGEDisableGLContextFunction func, void* param); void* cgeGetGLEnableParam(); void* cgeGetGLDisableParam(); void cgeStopGlobalGLEnableFunction(); void cgeRestoreGlobalGLEnableFunction(); void cgeEnableGlobalGLContext(); void cgeDisableGlobalGLContext(); #endif // CGEBufferLoadFun 的返回值将作为 CGEBufferUnloadFun 的第一个参数 // CGEBufferLoadFun 的参数 arg 将作为 CGEBufferUnloadFun 的第二个参数 typedef void* (*CGEBufferLoadFun)(const char* sourceName, void** bufferData, GLint* w, GLint* h, CGEBufferFormat* fmt, void* arg); typedef bool (*CGEBufferUnloadFun)(void* arg1, void* arg2); //加载纹理回调, 注, 为了保持接口简洁性, 回调返回的纹理单元将由调用者负责释放 //返回的纹理不应该为 glDeleteTextures 无法处理的特殊纹理类型. typedef GLuint (*CGETextureLoadFun)(const char* sourceName, GLint* w, GLint* h, void* arg); //You can set a common function for loading textures void cgeSetCommonLoadFunction(CGEBufferLoadFun fun, void* arg); void cgeSetCommonUnloadFunction(CGEBufferUnloadFun fun, void* arg); void* cgeLoadResourceCommon(const char* sourceName, void** bufferData, GLint* w, GLint* h, GLenum* format, GLenum* type); CGEBufferLoadFun cgeGetCommonLoadFunc(); void* cgeGetCommonLoadArg(); bool cgeUnloadResourceCommon(void* bufferArg); CGEBufferUnloadFun cgeGetCommonUnloadFunc(); void* cgeGetCommonUnloadArg(); char* cgeGetScaledBufferInSize(const void* buffer, int& w, int& h, int channel, int maxSizeX, int maxSizeY); char* cgeGetScaledBufferOutofSize(const void* buffer, int& w, int& h, int channel, int minSizeX, int minSizeY); inline GLint cgeGetMaxTextureSize() { GLint n; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &n); return n-1; } class SharedTexture { public: SharedTexture() : m_textureID(0), m_refCount(nullptr), width(0), height(0) {} SharedTexture(GLuint textureID, int w, int h); SharedTexture(const SharedTexture& other) : m_textureID(0), m_refCount(nullptr) { *this = other; } ~SharedTexture(); inline SharedTexture& operator =(const SharedTexture& other) { assert(this != &other && other.m_textureID != 0); if(m_refCount != nullptr && --*m_refCount <= 0) { clear(); } m_textureID = other.m_textureID; m_refCount = other.m_refCount; if (m_refCount) { ++*m_refCount; CGE_LOG_INFO("CGESharedTexture assgin: textureID %d, refCount: %d\n", m_textureID, *m_refCount); } width = other.width; height = other.height; return *this; } inline GLuint texID() const { return m_textureID; } inline void bindToIndex(GLint index) const { glActiveTexture(GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_2D, m_textureID); } void forceRelease(bool bDelTexture); //特殊用法, 与 forceRelease 配对使用 inline void forceAssignTextureID(GLuint texID) { m_textureID = texID; } public: int width; //public, for easy accessing. int height; protected: void clear(); private: GLuint m_textureID; mutable int* m_refCount; }; class FrameBuffer { public: FrameBuffer() { glGenFramebuffers(1, &m_framebuffer); } ~FrameBuffer() { glDeleteFramebuffers(1, &m_framebuffer); } inline void bind() const { glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer); } inline void bindTexture2D(const SharedTexture& texture, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texture.texID(), texture.width, texture.height, attachment); } inline void bindTexture2D(const SharedTexture& texture, GLsizei x, GLsizei y, GLsizei w, GLsizei h, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texture.texID(), x, y, w, h, attachment); } inline void bindTexture2D(GLuint texID, GLsizei w, GLsizei h, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texID, 0, 0, w, h, attachment); } inline void bindTexture2D(GLuint texID, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bind(); glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, texID, 0); CGE_LOG_CODE( if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { CGE_LOG_ERROR("CGE::FrameBuffer::bindTexture2D - Frame buffer is not valid!"); } ) } inline void bindTexture2D(GLuint texID, GLsizei x, GLsizei y, GLsizei w, GLsizei h, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texID, attachment); glViewport(x, y, w, h); } inline GLuint getID() { return m_framebuffer; } private: GLuint m_framebuffer; }; struct CGESizei { CGESizei(): width(0), height(0) {} CGESizei(int w, int h) : width(w), height(h) {} void set(int w, int h) { width = w; height = h; } bool operator ==(const CGESizei &other) const { return width == other.width && height == other.height; } bool operator !=(const CGESizei &other) const { return width != other.width || height != other.height; } GLint width; GLint height; }; struct CGESizef { CGESizef() : width(0.0f), height(0.0f) {} CGESizef(float w, float h) : width(w), height(h) {} void set(float w, float h) { width = w; height = h; } GLfloat width; GLfloat height; }; #ifndef CGE_MIN template<typename Type> inline Type CGE_MIN(Type a, Type b) { return a < b ? a : b; } #endif #ifndef CGE_MAX template<typename Type> inline Type CGE_MAX(Type a, Type b) { return a > b ? a : b; } #endif #ifndef CGE_MID template<typename Type> inline Type CGE_MID(Type n, Type vMin, Type vMax) { if(n < vMin) n = vMin; else if(n > vMax) n = vMax; return n; } #endif #ifndef CGE_MIX template<typename OpType, typename MixType> inline auto CGE_MIX(OpType a, OpType b, MixType value) -> decltype(a - a * value + b * value) { return a - a * value + b * value; } #endif struct CGELuminance { enum { CalcPrecision = 16 }; enum { Weight = (1<<CalcPrecision) }; enum { RWeight = int(0.299*Weight), GWeight = int(0.587*Weight), BWeight = int(0.114*Weight) }; static inline int RGB888(int r, int g, int b) { return (r * RWeight + g * GWeight + b * BWeight) >> CalcPrecision; } //color 从低位到高位的顺序为r-g-b, 传参时需要注意大小端问题 static inline int RGB565(unsigned short color) { const int r = (color & 31) << 3; const int g = ((color >> 5) & 63) << 2; const int b = ((color >> 11) & 31) << 3; return RGB888(r, g, b); } }; } ////////////////////////////////////////////////////////////////////////// #include <vector> #include <ctime> #include <memory> #include "cgeShaderFunctions.h" #include "cgeImageHandler.h" #include "CGEImageFilter.h" #endif /* _CGEGLFUNCTIONS_H_ */
0.996094
high
executor/operator/ref/kernel/add_n/ref_addn_uint8.c
wangshankun/Tengine_Atlas
25
1841424
static int ref_addn_uint8(uint8_t** input, uint8_t* output, const ref_addn_param* param) { int input_size = param->input_size; int in_num = param->in_num; float* out_f32 = ( float* )malloc(input_size); memset(out_f32, 0, input_size); for(int i = 0; i < in_num; ++i) { uint8_t* input_data = input[i]; float input_scale = param->in_scale[i]; int zero_point = param->in_zero[i]; for(int j = 0; j < input_size; ++j) { out_f32[j] += (input_data[j] * input_scale + zero_point); } } for(int j = 0; j < input_size; ++j) { int s32_out = round(out_f32[j] / param->out_scale) + param->out_zero; if(s32_out > 255) s32_out = 255; if(s32_out < 0) s32_out = 0; output[j] = s32_out; } free(out_f32); out_f32 = NULL; return 0; }
0.992188
high
Cinegy.Srt.Wrapper/Cinegy.Srt.Wrapper.h
Cinegy/Cinegy.SRT
16
3503528
// Cinegy.Srt.Wrapper.h #pragma once using namespace System; using namespace msclr::interop; namespace Cinegy { namespace Srt { public delegate void OnDataEventHandler(const char* data, size_t dataSize); public ref class SrtReceiver { public: //Helper(void); void SrtReceiver::Run(); void SrtReceiver::Stop(); int GetPort() { return _port; }; void SetPort(int value) { _port = value; } void SetHostname(String^ value) { _strHostname = _strHostname->Copy(value); } String^ GetHostname() { return _strHostname; } event OnDataEventHandler ^ OnDataReceived; private: int _port; String^ _strHostname; void FireOnDataEvent(const char* data, size_t size) { OnDataReceived(data, size); } }; } }
0.992188
high
C/useafterfree/sbrk.c
mudongliang/Language_Programming
0
5032248
/************************************************************************* > File Name: sbrk.c > Author: mudongliang > Mail: <EMAIL> > Created Time: Mon 23 Nov 2015 03:51:48 PM CST ************************************************************************/ #include<stdio.h> #include<unistd.h> #include<sys/types.h> int main() { void *curr_brk, *tmp_brk = NULL; printf("Welcome to sbrk example : %d\n", getpid()); tmp_brk = curr_brk = sbrk(0); printf("Program Break Location1: %p\n", curr_brk); getchar(); brk(curr_brk+0x1000); curr_brk = sbrk(0); printf("Program break Location2: %p\n", curr_brk); getchar(); brk(tmp_brk); curr_brk = sbrk(0); printf("Program break Location3: %p\n", curr_brk); getchar(); return 0; }
0.5
low
headers/os/package/GlobalWritableFileInfo.h
Kirishikesan/haiku
1,338
2027984
<reponame>Kirishikesan/haiku<gh_stars>1000+ /* * Copyright 2013, Haiku, Inc. * Distributed under the terms of the MIT License. */ #ifndef _PACKAGE__GLOBAL_WRITABLE_FILE_INFO_H_ #define _PACKAGE__GLOBAL_WRITABLE_FILE_INFO_H_ #include <package/WritableFileUpdateType.h> #include <String.h> namespace BPackageKit { namespace BHPKG { struct BGlobalWritableFileInfoData; } class BGlobalWritableFileInfo { public: BGlobalWritableFileInfo(); BGlobalWritableFileInfo( const BHPKG::BGlobalWritableFileInfoData& infoData); BGlobalWritableFileInfo(const BString& path, BWritableFileUpdateType updateType, bool isDirectory); ~BGlobalWritableFileInfo(); status_t InitCheck() const; const BString& Path() const; bool IsIncluded() const; BWritableFileUpdateType UpdateType() const; bool IsDirectory() const; void SetTo(const BString& path, BWritableFileUpdateType updateType, bool isDirectory); private: BString fPath; BWritableFileUpdateType fUpdateType; bool fIsDirectory; }; } // namespace BPackageKit #endif // _PACKAGE__GLOBAL_WRITABLE_FILE_INFO_H_
0.996094
high
3dEngine/src/resources/Resource.h
petitg1987/urchinEngine
18
490000
#pragma once #include <string> namespace urchin { class Resource { public: virtual ~Resource() = default; const std::string& getId() const; void setId(const std::string&); const std::string& getName() const; void setName(const std::string&); private: std::string id; std::string name; }; }
0.980469
high
eglibc-2.15/sysdeps/unix/sysv/sigaction.c
huhong789/shortcut
47
2152136
<filename>eglibc-2.15/sysdeps/unix/sysv/sigaction.c<gh_stars>10-100 /* Copyright (C) 1992,1994,1995,1996,1997,2002 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <sysdep.h> #include <errno.h> #include <stddef.h> #include <signal.h> /* If ACT is not NULL, change the action for SIG to *ACT. If OACT is not NULL, put the old action for SIG in *OACT. */ int __sigaction (sig, act, oact) int sig; const struct sigaction *act; struct sigaction *oact; { sighandler_t handler; int save; if (sig <= 0 || sig >= NSIG) { __set_errno (EINVAL); return -1; } if (act == NULL) { if (oact == NULL) return 0; /* Race condition, but this is the only way to do it. */ handler = signal (sig, SIG_IGN); if (handler == SIG_ERR) return -1; save = errno; (void) signal (sig, handler); __set_errno (save); } else { int i; if (act->sa_flags != 0) { unimplemented: __set_errno (ENOSYS); return -1; } for (i = 1; i < NSIG; ++i) if (__sigismember (&act->sa_mask, i)) goto unimplemented; handler = signal (sig, act->sa_handler); if (handler == SIG_ERR) return -1; } if (oact != NULL) { oact->sa_handler = handler; __sigemptyset (&oact->sa_mask); oact->sa_flags = 0; } return 0; } libc_hidden_def (__sigaction) weak_alias (__sigaction, sigaction)
0.980469
high
ul_exec_libc.c
mgood7123/userlandexec
1
6012897
<gh_stars>1-10 // #include <libstatic/libstatic.h> #include <errno.h> // extern long errno; #define PGSZ 0x1000 #include <elf.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <sys/syscall.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <assert.h> #include <string.h> #include <errno.h> #include <libgen.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> extern char **environ; // "look deep into yourself, Clarice" -- <NAME> char findyourself_save_pwd[PATH_MAX]; char findyourself_save_argv0[PATH_MAX]; char findyourself_save_path[PATH_MAX]; char findyourself_path_separator='/'; char findyourself_path_separator_as_string[2]="/"; char findyourself_path_list_separator[8]=":"; // could be ":; " char findyourself_debug=0; int findyourself_initialized=0; void findyourself_init(char *argv0) { getcwd(findyourself_save_pwd, sizeof(findyourself_save_pwd)); strncpy(findyourself_save_argv0, argv0, sizeof(findyourself_save_argv0)); findyourself_save_argv0[sizeof(findyourself_save_argv0)-1]=0; strncpy(findyourself_save_path, getenv("PATH"), sizeof(findyourself_save_path)); findyourself_save_path[sizeof(findyourself_save_path)-1]=0; findyourself_initialized=1; } int find_yourself(char *result, size_t size_of_result) { char newpath[PATH_MAX+256]; char newpath2[PATH_MAX+256]; assert(findyourself_initialized); result[0]=0; if(findyourself_save_argv0[0]==findyourself_path_separator) { if(findyourself_debug) printf(" absolute path\n"); realpath(findyourself_save_argv0, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } else { perror("access failed 1"); } } else if( strchr(findyourself_save_argv0, findyourself_path_separator )) { if(findyourself_debug) printf(" relative path to pwd\n"); strncpy(newpath2, findyourself_save_pwd, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_save_argv0, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; realpath(newpath2, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } else { perror("access failed 2"); } } else { if(findyourself_debug) printf(" searching $PATH\n"); char *saveptr; char *pathitem; for(pathitem=strtok_r(findyourself_save_path, findyourself_path_list_separator, &saveptr); pathitem; pathitem=strtok_r(NULL, findyourself_path_list_separator, &saveptr) ) { if(findyourself_debug>=2) printf("pathitem=\"%s\"\n", pathitem); strncpy(newpath2, pathitem, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_save_argv0, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; realpath(newpath2, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } } // end for perror("access failed 3"); } // end else // if we get here, we have tried all three methods on argv[0] and still haven't succeeded. Include fallback methods here. return(1); } // #include <ulexec.h> unsigned long file_size(char *filename) { char sbuf[144]; unsigned long ret; if (0 > (long)(ret = stat(filename, (void *)&sbuf))) { printf("stat problem: %l\n", errno); } else { ret = *(unsigned long *)(sbuf+48); } return ret; } void brk_(unsigned long addr) { asm volatile ("syscall" : : "a" (__NR_brk), "D" (addr)); } struct saved_block { int size; int cnt; char *block; }; void release_args(struct saved_block *args); struct saved_block *save_elfauxv(char **envp); struct saved_block *save_argv(int argc, char **argv); void *stack_setup( struct saved_block *args, struct saved_block *envp, struct saved_block *auxvp, Elf64_Ehdr *ehdr, Elf64_Ehdr *ldso ); #define JMP_ADDR(x) asm("\tjmp *%0\n" :: "r" (x)) #define SET_STACK(x) asm("\tmovq %0, %%rsp\n" :: "r"(x)) #define ROUNDUP(x, y) ((((x)+((y)-1))/(y))*(y)) #define ALIGN(k, v) (((k)+((v)-1))&(~((v)-1))) #define ALIGNDOWN(k, v) ((unsigned long)(k)&(~((unsigned long)(v)-1))) #define ALLOCATE(size) \ mmap(0, (size), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) void print_maps(void) { char rbuf[1024]; int fd, cc; fd = open("/proc/self/maps", 0, 0); while (0 < (cc = read(fd, rbuf, sizeof(rbuf)))) write(1, rbuf, cc); close(fd); } void error_msg(char *msg) { char buf[32]; printf("%s, %d\n", msg, errno); } void print_address(char *phrase, void *address) { printf("%s, 0x%08x\n", phrase, address); } void * memcopy(void *dest, const void *src, unsigned long n) { unsigned long i; unsigned char *d = (unsigned char *)dest; unsigned char *s = (unsigned char *)src; for (i = 0; i < n; ++i) d[i] = s[i]; return dest; } void copy_in(char *filename, void *address) { int fd, cc; off_t offset = 0; char buf[1024]; if (0 > (fd = open(filename, 0, 0))) { error_msg("opening dynamically-loaded file failed"); exit(2); } while (0 < (cc = read(fd, buf, sizeof(buf)))) { memcpy((address + offset), buf, cc); offset += cc; } close(fd); } void * map_file(char *file_to_map) { struct stat sb; void *mapped; if (0 > stat(file_to_map, &sb)) { error_msg("map_file stat() failed "); exit(1); } mapped = mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (mapped == (void *)-1) { error_msg("map_file mmap() failed "); exit(1); } copy_in(file_to_map, mapped); return mapped; } void unmap(char *progname) { char buf[1024], *p; char rbuf[2048]; int cc, fd; fd = open("/proc/self/maps", 0, 0); p = &buf[0]; while (0 < (cc = read(fd, rbuf, sizeof(rbuf)))) { int i; for (i = 0; i < cc; ++i) { int c = rbuf[i]; if ('\n' != c) *p++ = c; else { *p = '\0'; /* When a line from /proc/self/maps shows up as having been * mapped in from this running program, ld.so or libc, unmap it. * This will keep the exec'd program's address space a lot * cleaner. But even a 32-bit address space can hold 2 copies * of glibc without ill effects, so you don't really have to * munmap() anything other than the program calling ul_exec() */ if (strstr(buf, progname) || /* strstr(buf, "libdl") || strstr(buf, "/usr/lib/ld-") || strstr(buf, "/lib64/ld-") || */strstr(buf, "libc")) { char *u; char *first, *second; unsigned long low, high; u = strchr(buf, ' '); *u = '\0'; first = buf; second = strchr(first, '-'); *second = '\0'; ++second; low = strtoul(first, NULL, 0x10); high = strtoul(second, NULL, 0x10); printf("before unap:\n"); // print_maps(); munmap((void *)low, high-low); printf("after unap:\n"); // print_maps(); } p = &buf[0]; } } } close(fd); } /* call with argc as positive value for main's argv, * call with argc == 0 for env. */ struct saved_block * save_argv(int argc, char **argv) { struct saved_block *r = NULL; int i, len; char *str; if (argc > 0) for (i = 0, len = 0; i < argc; ++i) len += strlen(argv[i]) + 1; else { argc = 0; char **p = argv; while (*p) { len += strlen(*p) + 1; ++p; /* move past ASCII Nul */ ++argc; } } r = ALLOCATE(sizeof(*r)); r->size = len; r->cnt = argc; r->block = ALLOCATE(len); /* Do it this way because the values of argv[] may not actually * exist as contiguous strings. We will make them contiguous. */ for (i = 0, str = r->block; i < argc; i++) { int j; for (j = 0; argv[i][j]; ++j) str[j] = argv[i][j]; str[j] = '\0'; str += (j + 1); } return r; } void release_args(struct saved_block *args) { munmap((void *)args->block, args->size); munmap((void *)args, sizeof(*args)); } struct saved_block * save_elfauxv(char **envp) { struct saved_block *r; unsigned long *p; int cnt; Elf64_auxv_t *q; p = (unsigned long *)envp; while (*p != 0) ++p; ++p; /* skip null word after env */ for (cnt = 0, q = (Elf64_auxv_t *)p; q->a_type != AT_NULL; ++q) ++cnt; ++cnt; /* The AT_NULL final entry */ r = ALLOCATE(sizeof(*r)); r->size = sizeof(*q) * cnt; r->cnt = cnt; r->block = ALLOCATE(r->size); memcpy((void *)r->block, (void *)p, r->size); return r; } /* Returns value for %rsp, the new "bottom of the stack */ void * stack_setup( struct saved_block *args, struct saved_block *envp, struct saved_block *auxvp, Elf64_Ehdr *ehdr, Elf64_Ehdr *ldso ) { Elf64_auxv_t *aux, *excfn = NULL; char **av, **ev; char *addr, *str, *rsp; unsigned long *ptr; int i, j; char newstack[16384]; /* Align new stack. */ rsp = (char *)ALIGN(((unsigned long)&newstack[150]), 16); /* * After returning from * stack_setup(), don't do anything that uses the call stack: that * will roach this newly-constructed stack. */ ptr = (unsigned long *)rsp; *ptr++ = args->cnt; /* set argc */ av = (char **)ptr; ptr += args->cnt; /* skip over argv[] */ *ptr++ = 0; ev = (char **)ptr; ptr += envp->cnt; /* skip over envp[] */ *ptr++ = 0; aux = (Elf64_auxv_t *)ptr; ptr = (unsigned long *)ROUNDUP((unsigned long)ptr + auxvp->size, sizeof(unsigned long)); /* copy ELF auxilliary vector table */ addr = (char *)aux; for (j = 0; j < auxvp->size; ++j) addr[j] = auxvp->block[j]; /* Fix up a few entries: kernel will have set up the AUXV * for the user-land exec program, mapped in at a low address. * need to fix up a few AUXV entries for the "real" program. */ for (i = 0; i < auxvp->cnt; ++i) { switch (aux[i].a_type) { case AT_PHDR: aux[i].a_un.a_val = (unsigned long)((char *)ehdr + ehdr->e_phoff); break; case AT_PHNUM: aux[i].a_un.a_val = ehdr->e_phnum; break; case AT_BASE: aux[i].a_un.a_val = (unsigned long)ldso; break; case AT_ENTRY: aux[i].a_un.a_val = (unsigned long)ehdr->e_entry; break; #ifdef AT_EXECFN case AT_EXECFN: excfn = &(aux[i]); break; #endif } } *ptr++ = 0; /* Copy argv strings onto stack */ addr = (char *)ptr; str = args->block; for (i = 0; i < args->cnt; ++i) { av[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Copy envp strings onto stack */ addr = (char *)ptr; str = envp->block; for (i = 0; i < envp->cnt; ++i) { ev[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Executable name at top of stack */ if (excfn) { addr = (char *)ptr; str = args->block; excfn->a_un.a_val = (unsigned long)addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); } release_args(args); release_args(envp); release_args(auxvp); return ((void *)rsp); } int read_(const char *src, char **dest, int len) { char *p = malloc(len + 1); memcpy(p, src, len); p[len] = 0; *dest = p; return len; } void lseek_string(char **src, int len, int offset) { char *p = malloc(len); memcpy(p, *src+offset, len); *src = p; } #define QUOTE_0_TERMINATED 0x01 #define QUOTE_OMIT_LEADING_TRAILING_QUOTES 0x02 #define QUOTE_OMIT_TRAILING_0 0x08 #define QUOTE_FORCE_HEX 0x10 #define QUOTE_FORCE_LEN 9999 int string_quote(const char *instr, char *outstr, const unsigned int size, const unsigned int style) { const unsigned char *ustr = (const unsigned char *) instr; char *s = outstr; unsigned int i; int usehex, uselen, c; int xflag = 0; usehex = 0; uselen = 0; if ((style == 9999)) { uselen = 1; } else if ((xflag > 1) || (style & QUOTE_FORCE_HEX)) { usehex = 1; } else if (xflag) { /* Check for presence of symbol which require to hex-quote the whole string. */ for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) break; /* Force hex unless c is printable or whitespace */ if (c > 0x7e) { usehex = 1; break; } /* In ASCII isspace is only these chars: "\t\n\v\f\r". * They happen to have ASCII codes 9,10,11,12,13. */ if (c < ' ' && (unsigned)(c - 9) >= 5) { usehex = 1; break; } } } if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES)) *s++ = '\"'; if (usehex == 1) { /* Hex-quote the whole string. */ for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) goto asciz_ended; // print hex in " 00 00" format instead of "\x00\x00" format // *s++ = '\\'; *s++ = ' '; *s++ = "0123456789abcdef"[c >> 4]; *s++ = "0123456789abcdef"[c & 0xf]; } } else if (uselen == 1) { /* Hex-quote the whole string. */ for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) goto asciz_ended; *s++ = '1'; } } else { for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) goto asciz_ended; if ((i == (size - 1)) && (style & QUOTE_OMIT_TRAILING_0) && (c == '\0')) goto asciz_ended; int pass_one = 0; int pass_two = 0; int pass_three = 0; int pass_four = 0; if (c == '\f') { *s++ = '\\'; *s++ = 'f'; pass_one = 1; pass_three = 1; pass_four= 1; } if (pass_one == 0) { if (c == '%'/*FOR PRINTF*/) { *s++ = '%'; *s++ = '%'; pass_two = 1; pass_three = 1; pass_four= 1; } else { pass_two = 1; } } if (pass_two == 0) { if (c == '\"') { /*FOR PRINTF/SHELL*/ *s++ = '\\'; *s++ = '\"'; pass_three = 1; pass_four= 1; } else if (c == '\\') { /*FOR PRINTF/SHELL*/ *s++ = '\\'; *s++ = '\\'; pass_three = 1; pass_four= 1; } else if (c == '`'/*FOR PRINTF*/|| c == '$'/*FOR BASH*/) { // *s++ = '\\'; *s++ = c; pass_three = 1; pass_four= 1; } else if (c == '\''/*FOR PRINTF*/) { // *s++ = '\\'; // *s++ = 'x'; // *s++ = '2'; *s++ = c; pass_three = 1; pass_four= 1; } else if (c == '!'/*FOR BASH*/ || c == '-'/*FOR PRINTF*/) { // *s++ = '"'; // *s++ = '\''; *s++ = c; // *s++ = '\''; // *s++ = '"'; pass_three = 1; pass_four= 1; } else if (c == '%'/*FOR PRINTF*/) { *s++ = '%'; *s++ = '%'; *s++ = '%'; *s++ = '%'; pass_three = 1; pass_four= 1; } } if (pass_three == 0) { if (c == '\n') { *s++ = '\\'; *s++ = 'n'; pass_four = 1; } else if (c == '\r') { *s++ = '\\'; *s++ = 'r'; pass_four = 1; } else if (c == '\t') { *s++ = '\\'; *s++ = 't'; pass_four = 1; } else if (c == '\v') { *s++ = '\\'; *s++ = 'v'; pass_four = 1; } } if (pass_four == 0) { if (c >= ' ' && c <= 0x7e) *s++ = c; else { /* Print \octal */ *s++ = '\\'; if (i + 1 < size && ustr[i + 1] >= '0' && ustr[i + 1] <= '9' ) { /* Print \ooo */ *s++ = '0' + (c >> 6); *s++ = '0' + ((c >> 3) & 0x7); } else { /* Print \[[o]o]o */ if ((c >> 3) != 0) { if ((c >> 6) != 0) *s++ = '0' + (c >> 6); *s++ = '0' + ((c >> 3) & 0x7); } } *s++ = '0' + (c & 0x7); } } } } if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES)) *s++ = '\"'; *s = '\0'; /* Return zero if we printed entire ASCIZ string (didn't truncate it) */ if (style & QUOTE_0_TERMINATED && ustr[i] == '\0') { /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended') * but next char is NUL. */ return 0; } return 1; asciz_ended: if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES)) *s++ = '\"'; *s = '\0'; /* Return zero: we printed entire ASCIZ string (didn't truncate it) */ return 0; } #ifndef ALLOCA_CUTOFF # define ALLOCA_CUTOFF 4032 #endif #define use_alloca(n) ((n) <= ALLOCA_CUTOFF) /* * Quote string `str' of length `size' and print the result. * * If QUOTE_0_TERMINATED `style' flag is set, * treat `str' as a NUL-terminated string and * quote at most (`size' - 1) bytes. * * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set, * do not add leading and trailing quoting symbols. * * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise. * Note that if QUOTE_0_TERMINATED is not set, always returns 1. */ char * print_quoted_string(const char *str, unsigned int size, const unsigned int style, const char * return_type) { char *buf; char *outstr; unsigned int alloc_size; int rc; if (size && style & QUOTE_0_TERMINATED) --size; alloc_size = 4 * size; if (alloc_size / 4 != size) { error_msg("Out of memory"); printf("???"); return "-1"; } alloc_size += 1 + (style & QUOTE_OMIT_LEADING_TRAILING_QUOTES ? 0 : 2); if (use_alloca(alloc_size)) { outstr = alloca(alloc_size); buf = NULL; } else { outstr = buf = malloc(alloc_size); if (!buf) { error_msg("Out of memory"); printf("???"); return "-1"; } } // rc = string_quote(str, outstr, size, style); string_quote(str, outstr, size, style); if ( return_type == "return") { return outstr; } else if ( return_type == "print") { printf(outstr); } free(buf); // return rc; } void * load_elf(char *mapped, int anywhere, Elf64_Ehdr **elf_ehdr, Elf64_Ehdr **ldso_ehdr, void * mapped_b) { Elf64_Ehdr *hdr; Elf64_Phdr *pdr, *interp = NULL; int i; void *text_segment = NULL; void *entry_point = NULL; unsigned long initial_vaddr = 0; unsigned long brk_addr = 0; char buf[128]; unsigned int mapflags = MAP_PRIVATE|MAP_ANONYMOUS; if (!anywhere) mapflags |= MAP_FIXED; /* Just addresses in mapped-in file. */ hdr = (Elf64_Ehdr *)mapped; pdr = (Elf64_Phdr *)(mapped + hdr->e_phoff); entry_point = (void *)hdr->e_entry; for (i = 0; i < hdr->e_phnum; ++i, ++pdr) { unsigned int protflags = 0; unsigned long map_addr = 0, rounded_len, k; unsigned long unaligned_map_addr = 0; void *segment; if (pdr->p_type == 0x03) /* PT_INTERP */ { interp = pdr; continue; } if (pdr->p_type != PT_LOAD) /* Segment not "loadable" */ continue; if (text_segment != 0 && anywhere) { unaligned_map_addr = (unsigned long)text_segment + ((unsigned long)pdr->p_vaddr - (unsigned long)initial_vaddr) ; map_addr = ALIGNDOWN((unsigned long)unaligned_map_addr, 0x1000); mapflags |= MAP_FIXED; } else if (!anywhere) { map_addr = ALIGNDOWN(pdr->p_vaddr, 0x1000); } else { map_addr = 0UL; } if (!anywhere && initial_vaddr == 0) initial_vaddr = pdr->p_vaddr; /* mmap() freaks out if you give it a non-multiple of pagesize */ rounded_len = (unsigned long)pdr->p_memsz + ((unsigned long)pdr->p_vaddr % 0x1000); rounded_len = ROUNDUP(rounded_len, 0x1000); segment = mmap( (void *)map_addr, rounded_len, PROT_WRITE, mapflags, -1, 0 ); if (segment == (void *) -1) { printf("Failed to mmap()"); exit(3); } printf("anywhere = %d\n", anywhere); memcopy( !anywhere? (void *)pdr->p_vaddr: (void *)((unsigned long)segment + ((unsigned long)pdr->p_vaddr % 0x1000)), mapped + pdr->p_offset, pdr->p_filesz ); if (!text_segment) { *elf_ehdr = segment; text_segment = segment; initial_vaddr = pdr->p_vaddr; if (anywhere) entry_point = (void *)((unsigned long)entry_point - (unsigned long)pdr->p_vaddr + (unsigned long)text_segment); } if (pdr->p_flags & PF_R) protflags |= PROT_READ; if (pdr->p_flags & PF_W) protflags |= PROT_WRITE; if (pdr->p_flags & PF_X) protflags |= PROT_EXEC; mprotect(segment, rounded_len, protflags); k = pdr->p_vaddr + pdr->p_memsz; if (k > brk_addr) brk_addr = k; } if (interp) { Elf64_Ehdr *junk_ehdr = NULL; printf("LOAD_ELF mapping %p\n", mapped_b); entry_point = load_elf(mapped_b, 1, ldso_ehdr, &junk_ehdr, NULL); } if (!anywhere) brk_(ROUNDUP(brk_addr, 0x1000)); return (void *)entry_point; } char *strjoinb(const char *_a, const char *_b) { size_t na = strlen(_a); size_t nb = strlen(_b); char *p = malloc(na + nb + 1); memcpy(p, _a, na); memcpy(p + na, _b, nb); p[na + nb] = 0; return p; } int shift_split(char * argv[], char * program[], char * args[], int * ac) { // shift function modified for this purpose char ** args_tmp = malloc(1 * sizeof(*args_tmp)); for(int i=0; i<99; i++) { if (argv[i] == NULL) { printf("end of argument list\n"); break; } if (i == 0) { } else if (i == 1) { printf("program[%d] = %s\n", *ac, argv[i]); program[0] = argv[i]; *ac = *ac+1; } else { printf("args[%d] = %s\n", *ac-1, argv[i]); args[i-2] = argv[i]; *ac = *ac+1; } } return 0; } int split (char *str, char c, char ***arr) { int count = 1; int token_len = 1; int i = 0; char *p; char *t; p = str; while (*p != '\0') { if (*p == c) count++; p++; } *arr = (char**) malloc(sizeof(char*) * count); if (*arr == NULL) exit(1); p = str; while (*p != '\0') { if (*p == c) { (*arr)[i] = (char*) malloc( sizeof(char) * token_len ); if ((*arr)[i] == NULL) exit(1); token_len = 0; i++; } p++; token_len++; } (*arr)[i] = (char*) malloc( sizeof(char) * token_len ); if ((*arr)[i] == NULL) exit(1); i = 0; p = str; t = ((*arr)[i]); while (*p != '\0') { if (*p != c && *p != '\0') { *t = *p; t++; } else { *t = '\0'; i++; t = ((*arr)[i]); } p++; } return count; } // not used but kept incase needed, a version of lseek_string that has an offset multiplier as so this does not need to be specified multiple times, eg if offset is 64 and multiplier is 2 the offset is then 128, this is intended for loops and related void lseek_stringb(char **src, int len, int offset, int offsetT) { char *p = malloc(len); int off; off=((len*offsetT)); memcpy(p, *src+offset+off, len); *src = p; } char *strjoin(const char *_a, const char *_b, int _a_len, int len) { size_t na = _a_len; size_t nb = len; char *p = malloc(na + nb + 1); memcpy(p, _a, na); memcpy(p + na, _b, nb); p[na + nb] = 0; return p; } int stream__(char *file, char **p, int *q, int LINES_TO_READ) { const char *filename = file; int fd = open(filename, O_RDONLY); if (fd < 0) { printf("cannot open \"%s\", returned %i\n", filename, fd); return -1; } char * array; char ch; size_t lines = 1; // Read the file byte by byte int bytes=1; int count=1; array = malloc(sizeof(char) * 2048); char *array_tmp; while (read(fd, &ch, 1) == 1) { printf("\rbytes read: %'i", bytes); if (count == 1024) { array_tmp = realloc(array, bytes+1024); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } count=1; } array[bytes-1] = ch; if (ch == '\n') { if (lines == LINES_TO_READ) { break; } lines++; } count++; bytes++; } bytes--; array_tmp = realloc(array, bytes); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } printf("\rbytes read: %'i\n", bytes); *p = array; *q = bytes; return bytes; } // not used but kept incase needed, a version of stream__ that only outputs the last line read int stream__o(char *file, char **p, int *q, int LINES_TO_READ) { const char *filename = file; int fd = open(filename, O_RDONLY); if (fd < 0) { printf("cannot open \"%s\", returned %i\n", filename, fd); return -1; } char * array; char * array_tmp; char * array_lines; char * array_lines_tmp; char ch; size_t lines = 1; // Read the file byte by byte int bytes=1; int count=1; array = malloc(sizeof(char) * 2048); while (read(fd, &ch, 1) == 1) { printf("\rbytes read: %'i", bytes); if (count == 1024) { array_tmp = realloc(array, bytes+1024); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } count=1; } array[bytes-1] = ch; if (ch == '\n') { printf("attempting to reset array\n"); if (lines == LINES_TO_READ) { break; } else { // reset array to as if we just executed this function int y; for (y=0; y<bytes; y++) { array[y] = 0; } free(array); array = malloc(sizeof(char) * 2048); bytes=1; count=1; } lines++; } // count++; bytes++; } bytes--; array_tmp = realloc(array, bytes); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } printf("\rbytes read: %'i\n", bytes); *p = array; *q = bytes; return bytes; } // reads a entire file int read__(char *file, char **p, size_t *q) { int fd; size_t len = 0; char *o; if (!(fd = open(file, O_RDONLY))) { fprintf(stderr, "open() failure\n"); return (1); } len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); if (!(o = malloc(len))) { fprintf(stderr, "failure to malloc()\n"); } if ((read(fd, o, len)) == -1) { fprintf(stderr, "failure to read()\n"); } int cl = close(fd); if (cl < 0) { printf("cannot close \"%s\", returned %i\n", file, cl); return -1; } *p = o; *q = len; return len; } void * stack_setupb( struct saved_block *args, struct saved_block *envp, struct saved_block *auxvp, Elf64_Ehdr *ehdr, Elf64_Ehdr *ldso ) { Elf64_auxv_t *aux, *excfn = NULL; char **av, **ev; char *addr, *str, *rsp; unsigned long *ptr; int i, j; char newstack[16384]; /* Align new stack. */ rsp = (char *)ALIGN(((unsigned long)&newstack[150]), 16); /* * After returning from * stack_setup(), don't do anything that uses the call stack: that * will roach this newly-constructed stack. */ ptr = (unsigned long *)rsp; *ptr++ = args->cnt; /* set argc */ av = (char **)ptr; ptr += args->cnt; /* skip over argv[] */ *ptr++ = 0; ev = (char **)ptr; ptr += envp->cnt; /* skip over envp[] */ *ptr++ = 0; aux = (Elf64_auxv_t *)ptr; ptr = (unsigned long *)ROUNDUP((unsigned long)ptr + auxvp->size, sizeof(unsigned long)); /* copy ELF auxilliary vector table */ addr = (char *)aux; for (j = 0; j < auxvp->size; ++j) addr[j] = auxvp->block[j]; /* Fix up a few entries: kernel will have set up the AUXV * for the user-land exec program, mapped in at a low address. * need to fix up a few AUXV entries for the "real" program. */ for (i = 0; i < auxvp->cnt; ++i) { switch (aux[i].a_type) { case AT_PHDR: aux[i].a_un.a_val = (unsigned long)((char *)ehdr + ehdr->e_phoff); break; case AT_PHNUM: aux[i].a_un.a_val = ehdr->e_phnum; break; case AT_BASE: aux[i].a_un.a_val = (unsigned long)ldso; break; case AT_ENTRY: aux[i].a_un.a_val = (unsigned long)ehdr->e_entry; break; #ifdef AT_EXECFN case AT_EXECFN: excfn = &(aux[i]); break; #endif } } *ptr++ = 0; /* Copy argv strings onto stack */ addr = (char *)ptr; str = args->block; for (i = 0; i < args->cnt; ++i) { av[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Copy envp strings onto stack */ addr = (char *)ptr; str = envp->block; for (i = 0; i < envp->cnt; ++i) { ev[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Executable name at top of stack */ if (excfn) { addr = (char *)ptr; str = args->block; excfn->a_un.a_val = (unsigned long)addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); } release_args(args); release_args(envp); release_args(auxvp); return ((void *)rsp); } #include <sys/auxv.h> void die(const char *s) { perror(s); exit(errno); } void set_auxv(char * value) { char buf[1024]; int fd = -1; ssize_t r = 0; Elf64_auxv_t *auxv = NULL; snprintf(buf, sizeof(buf), "/proc/self/auxv"); if ((fd = open(buf, O_RDONLY)) < 0) die("[-] open"); if ((r = read(fd, buf, sizeof(buf))) < 0) die("[-] read"); close(fd); for (auxv = (Elf64_auxv_t *)buf; auxv->a_type != AT_NULL && (char *)auxv < buf + r; ++auxv) { switch (auxv->a_type) { case AT_EXECFN: printf("old AT_EXECFN:\t%s\n", (void *)auxv->a_un.a_val); auxv->a_un.a_val = value; printf("new AT_EXECFN:\t%s\n", (void *)auxv->a_un.a_val); break; default: break; } } } char * get_full_path() { findyourself_init((char *)getauxval(AT_EXECFN)); char * auxAT = (char *)getauxval(AT_EXECFN); char newpath[PATH_MAX]; find_yourself(newpath, sizeof(newpath)); if(1 || strcmp((char *)getauxval(AT_EXECFN),newpath)) { } char *fullpath = strdup( newpath ); char *directorypath = dirname( strdup( newpath ) ); printf("current = %s\nfullpath = %s\ndirname = %s\n", auxAT, fullpath, directorypath); return fullpath; } #define _dl_printf printf #define strchrb strchr #define strcpyb strcpy #define strncpyb strncpy #define strncatb strncat #define strstrb strstr int * resolve(char * path) { _dl_printf("called resolve()\n"); if(!access(path, F_OK)) { } else { return -1; } char * pathb = (char *)malloc(strlen(path) + 1); char * strcpyb(char *dest, const char *src); strcpyb(pathb,path); char save_pwd[PATH_MAX]; getcwd(save_pwd, sizeof(save_pwd)); char path_separator='/'; char relpathdot_separator[4]="/./"; char relpathdotdor_separator[5]="/../"; char newpathb[PATH_MAX+256]; char newpathc[PATH_MAX+256]; char linkb[PATH_MAX+256]; char linkd[PATH_MAX+256]; char tmp_pwd[PATH_MAX]; char current_pwd[PATH_MAX]; getcwd(current_pwd, sizeof(current_pwd)); #include <sys/types.h> #include <sys/stat.h> char* resolvedir(const char * pathb) { _dl_printf("chdir(%s)\n", pathb); chdir(pathb); _dl_printf("getcwd(%s, sizeof(%s))\n", tmp_pwd, tmp_pwd); getcwd(tmp_pwd, sizeof(tmp_pwd)); _dl_printf("%s points to %s\n\n", pathb, tmp_pwd); _dl_printf("chdir(%s)\n", current_pwd); chdir(current_pwd); _dl_printf("return %s\n", tmp_pwd); return tmp_pwd; } char* resolvefile(char * pathb) { _dl_printf("strncpyb(%s, %s, sizeof(%s)\n", linkb, pathb, linkb); strncpyb(linkb, pathb, sizeof(linkb)); _dl_printf("linkb[sizeof(%s)-1]=0\n", linkb); linkb[sizeof(linkb)-1]=0; _dl_printf("strncpyb(%s, %s, sizeof(%s)\n", linkd, pathb, linkb); strncpyb(linkd, pathb, sizeof(linkb)); _dl_printf("linkb[sizeof(%s)-1]=0\n", linkb); linkb[sizeof(linkb)-1]=0; _dl_printf("dirname(%s)\n", linkd); dirname(linkd); _dl_printf("strncatb(%s, \"/\", sizeof(%s));\n", linkd, linkd); strncatb(linkd, "/", sizeof(linkd)); _dl_printf("linkd[sizeof(%s)-1]=0\n", linkd); linkd[sizeof(linkd)-1]=0; _dl_printf("chdir(%s)\n", linkd); chdir(linkd); _dl_printf("getcwd(%s, sizeof(%s))\n", tmp_pwd, tmp_pwd); getcwd(tmp_pwd, sizeof(tmp_pwd)); _dl_printf("strncatb(%s, \"/\", sizeof(%s));\n", tmp_pwd, tmp_pwd); strncatb(tmp_pwd, "/", sizeof(tmp_pwd)); _dl_printf("tmp_pwd[sizeof(%s)-1]=0\n", tmp_pwd); tmp_pwd[sizeof(tmp_pwd)-1]=0; _dl_printf("strncpyb(%s, %s, sizeof(%s));\n", linkb, basename(pathb), linkb); strncpyb(linkb, basename(pathb), sizeof(linkb)); _dl_printf("linkb[sizeof(%s)-1]=0\n", linkb); linkb[sizeof(linkb)-1]=0; _dl_printf("strncatb(%s, %s, sizeof(%s));\n", tmp_pwd, linkb, tmp_pwd); strncatb(tmp_pwd, linkb, sizeof(tmp_pwd)); _dl_printf("tmp_pwd[sizeof(%s)-1]=0\n", tmp_pwd); tmp_pwd[sizeof(tmp_pwd)-1]=0; _dl_printf("%s points to %s\n\n", pathb, tmp_pwd); _dl_printf("chdir(%s)\n", current_pwd); chdir(current_pwd); _dl_printf("return %s\n", tmp_pwd); return tmp_pwd; } #include <sys/types.h> #include <sys/stat.h> char * getlink(const char * link) { struct stat p_statbuf; if (lstat(link,&p_statbuf)==0) { _dl_printf("%s type is <int>\n",link, S_ISLNK(p_statbuf.st_mode)); if (S_ISLNK(p_statbuf.st_mode)==1) { _dl_printf("%s is symbolic link \n", link); } else { _dl_printf("%s is not symbolic link \n", link); return 0; } } struct stat sb; char *linkname; ssize_t r; if (lstat(link, &sb) == -1) { _exit(EXIT_FAILURE); } linkname = malloc(sb.st_size + 1); if (linkname == NULL) { _exit(EXIT_FAILURE); } r = readlink(link, linkname, sb.st_size + 1); if (r < 0) { _exit(EXIT_FAILURE); } if (r > sb.st_size) { _exit(EXIT_FAILURE); } linkname[sb.st_size] = '\0'; _dl_printf("\"%s\" points to '%s'\n", link, linkname); path = linkname; char * checkifsymlink(const char * tlink) { struct stat p_statbuf; if (lstat(tlink,&p_statbuf)==0) { _dl_printf("%s type is <int>\n",tlink, S_ISLNK(p_statbuf.st_mode)); if (S_ISLNK(p_statbuf.st_mode)==1) { _dl_printf("%s is symbolic link \n", tlink); _dl_printf("called getlink()\n"); getlink(tlink); } else { _dl_printf("%s is not symbolic link \n", tlink); return 0; } } return 0; } _dl_printf("called checkifsymlink()\n"); checkifsymlink(path); return 0; } _dl_printf("called getlink()\n"); getlink(path); char * testtype(const char * patha) { int is_regular_file(const char *patha) { struct stat path_stat; stat(patha, &path_stat); return S_ISREG(path_stat.st_mode); } int isDirectory(const char *patha) { struct stat statbuf; if (stat(patha, &statbuf) != 0) return 0; return S_ISDIR(statbuf.st_mode); } if (is_regular_file(patha)==1) { _dl_printf("%s is file \n", patha); if (path[0]==path_separator) { if ( strstrb(path, relpathdot_separator )) { _dl_printf("%s is an absolute path which contains a dot relative path\n", path); _dl_printf("called Rresolvefile()\n"); return resolvefile(path); } else if ( strstrb(path, relpathdotdor_separator )) { _dl_printf("%s is an absolute path which contains a dot dot relative path\n", path); _dl_printf("called resolvefile()\n"); return resolvefile(path); } else { _dl_printf("%s is an absolute path with no relative paths\n", path); return path; } } else if ( strchrb(path, path_separator )) { _dl_printf("%s is a relative path\n", path); strncpyb(newpathb, current_pwd, sizeof(newpathb)); newpathb[sizeof(newpathb)-1]=0; strncatb(newpathb, "/", sizeof(newpathb)); newpathb[sizeof(newpathb)-1]=0; strncatb(newpathb, path, sizeof(newpathb)); newpathb[sizeof(newpathb)-1]=0; _dl_printf("called resolvefile()\n"); printf("need to re execute\n"); char * new_aux = resolvefile(newpathb); printf("executing with %s\n\n\n\n", new_aux); int ret = execv(new_aux, NULL); printf("ret = %d\n\n", ret); return "ERROR"; } else { _dl_printf("could not determine path type of %s\n", path); return "NULL"; } } else if (isDirectory(patha)==1) { _dl_printf("%s is a directory \n", patha); if (path[0]==path_separator) { if ( strstrb(path, relpathdot_separator )) { _dl_printf("%s is an absolute path which contains a dot relative path\n", path); _dl_printf("called resolvedir()\n"); resolvedir(path); } else if ( strstrb(path, relpathdotdor_separator )) { _dl_printf("%s is an absolute path which contains a dot dot relative path\n", path); _dl_printf("called resolvedir()\n"); resolvedir(path); } else { _dl_printf("%s is an absolute path with no relative paths\n", path); return path; } } else if ( strchrb(path, path_separator )) { _dl_printf("%s is a relative path\n", path); _dl_printf("strncpyb(%s, %s, sizeof(%s));\n", newpathc, current_pwd, newpathc); strncpyb(newpathc, current_pwd, sizeof(newpathc)); _dl_printf("newpath2[sizeof(%s)-1]=0;\n", newpathc); newpathc[sizeof(newpathc)-1]=0; _dl_printf("strncatb(%s, %s, sizeof(%s));\n", newpathc, "/", newpathc); strncatb(newpathc, "/", sizeof(newpathc)); _dl_printf("newpathc[sizeof(%s)-1]=0;\n", newpathc); newpathc[sizeof(newpathc)-1]=0; _dl_printf("strncatb(%s, %s, sizeof(%s));\n", newpathc, path, newpathc); strncatb(newpathc, path, sizeof(newpathc)); _dl_printf("newpathc[sizeof(%s)-1]=0;\n", newpathc); newpathc[sizeof(newpathc)-1]=0; _dl_printf("called resolvedir()\n"); return resolvedir(newpathc); } else { _dl_printf("could not determine path type of %s\n", path); return "NULL"; } } return "FAILED"; } _dl_printf("called testtype()\n"); return testtype(path); } void * setaux(int *argc, char ** argv, void * value, unsigned long type) { // printf("type = %d\n", type); #define AUX_CNT 32 // AT_SYSINFO_EHDR: 0x7fffdb375000 // AT_HWCAP: 178bfbff // AT_PAGESZ: 4096 // AT_CLKTCK: 100 // AT_PHDR: 0x400040 // AT_PHENT: 56 // AT_PHNUM: 10 // AT_BASE: 0x7ff5e3c1c000 // AT_FLAGS: 0x0 // AT_ENTRY: 0x4032e0 // AT_UID: 1000 // AT_EUID: 1000 // AT_GID: 1001 // AT_EGID: 1001 // AT_SECURE: 0 // AT_RANDOM: 0x7fffdb34a379 // AT_HWCAP2: 0x0 // AT_EXECFN: /usr/bin/gcc // AT_PLATFORM: x86_64 size_t i; int num = -1; void * AUXV_TYPE; char * AUXV_NAME; for (i=argc+1; argv[i]; i++); for (int ii=0; ii<=(void *)(argv+i+1)[0]+(2*20); ii+=2) { // 20 extra incase auxv does not have the same vectors for every machine (could have more than +4) size_t tmp = (void *)(argv+i+1+ii)[0]; switch(tmp) { case 0: AUXV_NAME = "AT_NULL"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 0; break; case 1: AUXV_NAME = "AT_IGNORE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 1; break; case 2: AUXV_NAME = "AT_EXECFD"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 2; break; case 3: AUXV_NAME = "AT_PHDR"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 3; break; case 4: AUXV_NAME = "AT_PHENT"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 4; break; case 5: AUXV_NAME = "AT_PHNUM"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 5; break; case 6: AUXV_NAME = "AT_PAGESZ"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 6; break; case 7: AUXV_NAME = "AT_BASE"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 7; break; case 8: AUXV_NAME = "AT_FLAGS"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 8; break; case 9: AUXV_NAME = "AT_ENTRY"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 9; break; case 10: AUXV_NAME = "AT_NOTELF"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 10; break; case 11: AUXV_NAME = "AT_UID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 11; break; case 12: AUXV_NAME = "AT_EUID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 12; break; case 13: AUXV_NAME = "AT_GID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 13; break; case 14: AUXV_NAME = "AT_EGID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 14; break; case 15: AUXV_NAME = "AT_PLATFORM"; AUXV_TYPE = "CHAR*"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 15; break; case 16: AUXV_NAME = "AT_HWCAP"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 16; break; case 17: AUXV_NAME = "AT_CLKTCK"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 17; break; case 18: AUXV_NAME = "AT_FPUCW"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 18; break; case 19: AUXV_NAME = "AT_DCACHEBSIZE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 19; break; case 20: AUXV_NAME = "AT_ICACHEBSIZE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 20; break; case 21: AUXV_NAME = "AT_UCACHEBSIZE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 21; break; case 22: AUXV_NAME = "AT_IGNOREPPC"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 22; break; case 23: AUXV_NAME = "AT_SECURE"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 23; break; case 24: AUXV_NAME = "AT_BASE_PLATFORM"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 24; break; case 25: AUXV_NAME = "AT_RANDOM"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 25; break; case 26: AUXV_NAME = "AT_HWCAP2"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 26; break; case 31: AUXV_NAME = "AT_EXECFN"; AUXV_TYPE = "CHAR*"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 31; break; case 32: AUXV_NAME = "AT_SYSINFO"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 32; break; case 33: AUXV_NAME = "AT_SYSINFO_EHDR"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 33; break; case 34: AUXV_NAME = "AT_L1I_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 34; break; case 35: AUXV_NAME = "AT_L1D_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 35; break; case 36: AUXV_NAME = "AT_L2_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 36; break; case 37: AUXV_NAME = "AT_L3_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 37; break; default: AUXV_NAME = "UNDEFINED"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = -1; break; } if (num == type) { // printf("changing %s (type %s)\n", AUXV_NAME, AUXV_TYPE); // printf("address of (void *)(argv+%d+1+%d)[1] = %p\n", i, ii, (void *)&(argv+i+1+ii)[1]); #include <sys/auxv.h> if (AUXV_TYPE == "CHAR*") { printf("calling getauxval: "); printf("%s = %s\n", AUXV_NAME, (char *)getauxval(type)); char * string = value; char *j = (void *)(argv+i+1+ii)[1]; int len = strlen((void *)(argv+i+1+ii)[1]); int len_ = strlen(string); // printf("j = %s\n(void *)(argv+i+1+%d)[1] = %s\n", j, ii, (void *)(argv+i+1+ii)[1]); // printf("attempting to modify %s\n", AUXV_NAME); for (int g = 0; g<=len_; g++) { *j = string[g]; j+=1; } for (int g = 0; g<=len-len_; g++) { // NULL the rest of the string *j = '\0'; j+=1; } // printf("j = %s\n(void *)(argv+i+1+%d)[1] = %s\n", j, ii, (void *)(argv+i+1+ii)[1]); printf("calling getauxval: "); printf("%s = %s\n", AUXV_NAME, (char *)getauxval(type)); } else if (AUXV_TYPE == "INT") { printf("calling getauxval: "); printf("%s = %d\n", AUXV_NAME, (char *)getauxval(type)); // printf("(void *)(argv+i+1+%d)[1] (auxv) =\n", ii); // print_quoted_string_catraw((void *)(argv+i+1+ii)[1], 1, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES); // printf("\n"); // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); // printf("attempting to modify %s\n", AUXV_NAME); (argv+i+1+ii)[1] = value; // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); printf("calling getauxval: "); printf("%s = %d\n", AUXV_NAME, (char *)getauxval(type)); } else if (AUXV_TYPE == "ADDRESS") { printf("calling getauxval: "); printf("%s = %p\n", AUXV_NAME, (char *)getauxval(type)); // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); // printf("attempting to modify %s\n", AUXV_NAME); (argv+i+1+ii)[1] = value; // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); printf("calling getauxval: "); printf("%s = %p\n", AUXV_NAME, (char *)getauxval(type)); } } } type = -1; } // execve implimentation void ulexec(char * pro, char * args, char **env) { print_maps(); char * current_aux = (char *)getauxval(AT_EXECFN); // printf("returned %s\n", resolve(current_aux)); printf("AT_EXECFN = %s\n", current_aux); printf ("current_aux[0] = %c\n", current_aux[0]); printf("need to re execute\n"); char * new_aux = get_full_path(); printf("executing with %s\n\n", new_aux); // setaux(argc, argv, "", AT_EXECFN); // int ret = execv(new_aux, NULL); // printf("ret = %d\n\n", ret); printf("safe to continue\n\n"); int arg_c = 0; char ** program_to_execute = malloc(1 * sizeof(*program_to_execute)); printf("allocating %d\n", 1 * sizeof(*program_to_execute)); program_to_execute[0] = "placeholder"; char ** program_arguments = malloc(1 * sizeof(*program_arguments)); printf("allocating %d\n", 1 * sizeof(*program_arguments)); program_arguments[0] = "placeholder"; char ** program_program_arguments = malloc(1 * sizeof(*program_program_arguments)); program_program_arguments[0] = "placeholder"; // shift_split(av, program_to_execute, program_arguments, program_program_arguments, &arg_c); char * s = strjoinb(pro, " "); s = strjoinb(s, args); int c = 0; char **arr = NULL; c = split(s, ' ', &arr); printf("found %d tokens.\n", c-1); for (int i = 0; i < c; i++) { program_program_arguments[i] = arr[i]; printf("program_program_arguments[%d] = %s\n", i, program_program_arguments[i]); } program_to_execute[0] = program_program_arguments[0]; printf("program_to_execute[%d] = %s\n", 0, program_to_execute[0]); for (int i = 1; i < c; i++) { program_arguments[i-1] = arr[i]; printf("program_arguments[%d] = %s\n", i-1, program_arguments[i-1]); } printf("number of arguments: \n%d\nprogram: \n%s\n", c, program_to_execute[0]); for (int i = 0; i<=arg_c-2; i++) printf("program args: %d = \n%s\n", i, program_arguments[i]); // print_maps(); int how_to_map = 0; void *entry_point; struct stat sb; Elf64_Ehdr *ldso_ehdr; struct saved_block *argvb, *envb, *elfauxvb; int trim_args, i; void *stack_bottom; how_to_map = 0; trim_args = 1; // if (file_to_unmap) // unmap(file_to_unmap);#include <sys/mman.h> void * mapped_interp; const char * filename = program_to_execute[0]; int fd = open(filename, O_RDONLY); if (fd < 0) { printf("cannot open \"%s\", returned %i\n", filename, fd); } size_t len = 0; len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); void * mapped = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped == MAP_FAILED) { printf ("map failed\n"); exit; } else { printf ("map (%s) succeded with address: 0x%08x\n", filename, mapped); } // mapped = map_file(av[1]); // elf_ehdr = (Elf64_Ehdr *)mapped; printf("aquiring header\n"); Elf64_Ehdr * elf_ehdr = (Elf64_Ehdr *) mapped; // phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("aquiring program header\n"); Elf64_Phdr *phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("searching for PT_LOAD and PT_INTERP\n"); void * mapped_i; for (i = 0; i < elf_ehdr->e_phnum; ++i) { if (phdr[i].p_type == PT_LOAD && phdr[i].p_vaddr == 0) { how_to_map = 1; /* map it anywhere, like ld.so, or PIC code. */ printf("mapping anywhere\n"); break; } if (phdr[i].p_type == PT_INTERP) { printf("ATTEMPING TO READ\n"); char * tmp99; read_(mapped, &tmp99, (phdr[i].p_memsz + phdr[i].p_offset)); lseek_string(&tmp99, phdr[i].p_memsz, phdr[i].p_offset); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\nREAD\n"); const char * filename = print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "return"); int fd = open(filename, O_RDONLY); // usually /lib64/ld-linux-x86-64.so.2 if (fd < 0) { printf ("cannot open \""); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\", returned %i\n", fd); } size_t len = 0; len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); mapped_i = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped_i == MAP_FAILED) { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") failed\n"); exit; } else { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") succeded with address: 0x%08x\n", mapped_i); } } } printf("loading\n"); entry_point = load_elf(mapped, how_to_map, &elf_ehdr, &ldso_ehdr, mapped_i); printf("unmapping\n"); munmap(mapped, sb.st_size); printf("argvb = save_argv(%d, %s);\n", c, program_program_arguments[0]); argvb = save_argv(c, &program_program_arguments[0]); printf("saving envb\n"); envb = save_argv(0, env); printf("saving elfauxvb\n"); elfauxvb = save_elfauxv(env); printf("stack_setup()\n"); stack_bottom = stack_setup(argvb, envb, elfauxvb, elf_ehdr, ldso_ehdr); printf("SET_STACK()\n"); SET_STACK(stack_bottom); printf("printing maps before executing\n"); print_maps(); printf("jumping to %p\n", entry_point); JMP_ADDR(entry_point); } // executes an exeutable using the packaged interpreter void ulexec_array(void * mapped, void * mapped_interpreter, char * args, char **env) { print_maps(); int arg_c = 0; char ** program_arguments = malloc(1 * sizeof(*program_arguments)); printf("allocating %d\n", 1 * sizeof(*program_arguments)); program_arguments[0] = "placeholder"; int c = 0; char **arr = NULL; c = split(args, ' ', &arr); printf("found %d tokens.\n", c); for (int i = 0; i < c; i++) { program_arguments[i+1] = arr[i]; printf("program_arguments[%d] = %s\n", i+1, program_arguments[i+1]); } for (int i = 0; i<=arg_c-2; i++) printf("program args: %d = \n%s\n", i, program_arguments[i]); int how_to_map = 0; void *entry_point; struct stat sb; Elf64_Ehdr *ldso_ehdr; struct saved_block *argvb, *envb, *elfauxvb; int trim_args, i; void *stack_bottom; how_to_map = 0; trim_args = 1; // if (file_to_unmap) // unmap(file_to_unmap); void * mapped_interp; // mapped = map_file(av[1]); // elf_ehdr = (Elf64_Ehdr *)mapped; printf("aquiring header\n"); Elf64_Ehdr * elf_ehdr = (Elf64_Ehdr *) mapped; // phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("aquiring program header\n"); Elf64_Phdr *phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("searching for PT_LOAD and PT_INTERP\n"); void * mapped_i; if (mapped_interpreter == NULL) { printf("mapped = null\n"); for (i = 0; i < elf_ehdr->e_phnum; ++i) { if (phdr[i].p_type == PT_LOAD && phdr[i].p_vaddr == 0) { how_to_map = 1; /* map it anywhere, like ld.so, or PIC code. */ printf("mapping anywhere\n"); break; } if (phdr[i].p_type == PT_INTERP) { printf("ATTEMPING TO READ\n"); char * tmp99; read_(mapped, &tmp99, (phdr[i].p_memsz + phdr[i].p_offset)); lseek_string(&tmp99, phdr[i].p_memsz, phdr[i].p_offset); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\nREAD\n"); const char * filename = print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "return"); int fd = open(filename, O_RDONLY); // opens the system's ld.so and uses it if an interpreter is not provided in the 2nd argument of ulexec_array if (fd < 0) { printf ("cannot open \""); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\", returned %i\n", fd); } size_t len = 0; len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); mapped_i = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped_i == MAP_FAILED) { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") failed\n"); exit; } else { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") succeded with address: 0x%08x\n", mapped_i); } } } } else { mapped_i = mapped_interpreter; } printf("loading %p\n", mapped_i); entry_point = load_elf(mapped, how_to_map, &elf_ehdr, &ldso_ehdr, mapped_i); printf("unmapping\n"); munmap(mapped, sb.st_size); printf("argvb = save_argv(%d, %s);\n", c+1, program_arguments[0]); argvb = save_argv(c+1, &program_arguments[0]); envb = save_argv(0, env); elfauxvb = save_elfauxv(env); stack_bottom = stack_setup(argvb, envb, elfauxvb, elf_ehdr, ldso_ehdr); SET_STACK(stack_bottom); // printf("printing maps before executing\n"); // print_maps(); printf("jumping to %p\n", entry_point); JMP_ADDR(entry_point); } // executes using system's interpreter int ulexecb(void * array, char ** env) { print_maps(); int i = 0; print_quoted_string(array, 16, QUOTE_FORCE_HEX, "print"); printf("hai\n"); # include <elf.h> printf(" )\n"); Elf64_Ehdr * _elf_header = (Elf64_Ehdr *) array; printf("hai again\n"); printf("ELF Identifier\t %s (", _elf_header->e_ident); print_quoted_string(_elf_header->e_ident, sizeof(_elf_header->e_ident), QUOTE_FORCE_HEX|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(" )\n"); if(!strncmp((char*)_elf_header->e_ident, "\177ELF", 4)) { // ELF Header: // Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 // Class: ELF64 // Data: 2's complement, little endian // Version: 1 (current) // OS/ABI: UNIX - System V // ABI Version: 0 // Type: EXEC (Executable file) // Machine: Advanced Micro Devices X86-64 // Version: 0x1 // Entry point address: 0x400820 // Start of program headers: 64 (bytes into file) // Start of section headers: 11408 (bytes into file) // Flags: 0x0 // Size of this header: 64 (bytes) // Size of program headers: 56 (bytes) // Number of program headers: 9 // Size of section headers: 64 (bytes) // Number of section headers: 30 // Section header string table index: 29 // printf("ELF Identifier\t %s (", _elf_header->e_ident); print_quoted_string(_elf_header->e_ident, sizeof(_elf_header->e_ident), QUOTE_FORCE_HEX|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(" )\n"); printf("Architecture\t "); switch(_elf_header->e_ident[EI_CLASS]) { case ELFCLASSNONE: printf("None\n"); break; case ELFCLASS32: printf("32-bit\n"); break; case ELFCLASS64: printf("64-bit\n"); break; case ELFCLASSNUM: printf("NUM ( unspecified )\n"); break; default: printf("Unknown CLASS\n"); break; } printf("Data Type\t "); switch(_elf_header->e_ident[EI_DATA]) { case ELFDATANONE: printf("None\n"); break; case ELFDATA2LSB: printf("2's complement, little endian\n"); break; case ELFDATA2MSB: printf("2's complement, big endian\n"); break; case ELFDATANUM: printf("NUM ( unspecified )\n"); break; default: printf("Unknown \n"); break; } printf("Version\t\t "); switch(_elf_header->e_ident[EI_VERSION]) { case EV_NONE: printf("None\n"); break; case EV_CURRENT: printf("Current\n"); break; case EV_NUM: printf("NUM ( Unspecified )\n"); break; default: printf("Unknown \n"); break; } printf("OS ABI\t\t "); switch(_elf_header->e_ident[EI_OSABI]) { case ELFOSABI_NONE: printf("UNIX System V ABI\n"); break; // case ELFOSABI_SYSV: // printf("SYSV\n"); // break; // case ELFOSABI_HPUX: printf("HP-UX\n"); break; case ELFOSABI_NETBSD: printf("NetBSD\n"); break; case ELFOSABI_GNU: printf("GNU\n"); break; // case ELFOSABI_LINUX: // printf("Linux\n"); // break; // case ELFOSABI_SOLARIS: printf("Sun Solaris\n"); break; case ELFOSABI_AIX: printf("ABM AIX\n"); break; case ELFOSABI_FREEBSD: printf("FreeBSD\n"); break; case ELFOSABI_TRU64: printf("Compaq Tru64\n"); break; case ELFOSABI_MODESTO: printf("Novell Modesto\n"); break; case ELFOSABI_OPENBSD: printf("OpenBSD\n"); break; // case ELFOSABI_ARM_AEABI: // printf("ARM EABI\n"); // break; case ELFOSABI_ARM: printf("ARM\n"); break; case ELFOSABI_STANDALONE: printf("Standalone (embedded) application\n"); break; default: printf("Unknown \n"); break; } printf("File Type\t "); switch(_elf_header->e_type) { case ET_NONE: printf("None\n"); break; case ET_REL: printf("Relocatable file\n"); break; case ET_EXEC: printf("Executable file\n"); break; case ET_DYN: printf("Shared object file\n"); break; case ET_CORE: printf("Core file\n"); break; case ET_NUM: printf("Number of defined types\n"); break; case ET_LOOS: printf("OS-specific range start\n"); break; case ET_HIOS: printf("OS-specific range end\n"); break; case ET_LOPROC: printf("Processor-specific range start\n"); break; case ET_HIPROC: printf("Processor-specific range end\n"); break; default: printf("Unknown \n"); break; } printf("Machine\t\t "); switch(_elf_header->e_machine) { case EM_NONE: printf("None\n"); break; case EM_386: printf("INTEL x86\n"); break; case EM_X86_64: printf("AMD x86-64 architecture\n"); break; case EM_ARM: printf("ARM\n"); break; default: printf("Unknown\n"); break; } /* Entry point */ int entry=_elf_header->e_entry; printf("Entry point\t 0x%08x Step 3. and jump to e_entry\n", _elf_header->e_entry); /* ELF header size in bytes */ printf("ELF header size\t 0x%08x\n", _elf_header->e_ehsize); /* Program Header */ printf("Program Header\t 0x%08x (%d entries with a total of %d bytes)\n", _elf_header->e_phoff, _elf_header->e_phnum, _elf_header->e_phentsize ); // for static, obtain the following: everything in the structure Elf64_Phdr, then `, PT_LOAD, PT_DYNAMIC, then e_entry Elf64_Phdr *elf_program_header = (Elf64_Phdr *)((unsigned long)_elf_header + _elf_header->e_phoff); char * exe = ""; int lenexe = 0; int lentotal = 0; for (i = 0; i < _elf_header->e_phnum; ++i) { // printf("dl_iterate_phdr =\n"); // dl_iterate_phdr(callback, NULL); printf("p_type;\t\t\t/* Segment type */\t\t= "); switch(elf_program_header[i].p_type) { case PT_NULL: printf("PT_NULL\t\t/* Program header table entry unused */\n"); break; case PT_LOAD: printf("PT_LOAD\t\t/* Loadable program segment */ Step 2. then parse and process all PT_LOAD segments\n"); break; case PT_DYNAMIC: printf("PT_DYNAMIC\t\t/* Dynamic linking information */ Step 2.5 keep in mind that static-PIE binaries are dynamic ELF objects though, so to load those you need to parse the PT_DYNAMIC stuff\n"); break; case PT_INTERP: printf("PT_INTERP\t\t/* Program interpreter */\n"); break; case PT_NOTE: printf("PT_NOTE\t\t/* Auxiliary information */\n"); break; case PT_SHLIB: printf("PT_SHLIB\t\t/* Reserved */\n"); break; case PT_PHDR: printf("PT_PHDR\t\t/* Entry for header table itself */ Step 1. if the first entry is a PT_PHDR, use that as the program header table\n"); break; case PT_TLS: printf("PT_TLS\t\t/* Thread-local storage segment */\n"); break; case PT_NUM: printf("PT_NUM\t\t/* Number of defined types */\n"); break; case PT_LOOS: printf("PT_LOOS\t\t/* Start of OS-specific */\n"); break; case PT_GNU_EH_FRAME: printf("PT_GNU_EH_FRAME\t/* GCC .eh_frame_hdr segment */\n"); break; case PT_GNU_STACK: printf("PT_GNU_STACK\t\t/* Indicates stack executability */\n"); break; case PT_GNU_RELRO: printf("PT_GNU_RELRO\t\t/* Read-only after relocation */\n"); break; case PT_SUNWBSS: printf("PT_SUNWBSS\t\t/* Sun Specific segment */\n"); break; case PT_SUNWSTACK: printf("PT_SUNWSTACK\t\t/* Stack segment */\n"); break; case PT_HIOS: printf("PT_HIOS\t\t/* End of OS-specific */\n"); break; case PT_LOPROC: printf("PT_LOPROC\t\t/* Start of processor-specific */\n"); break; case PT_HIPROC: printf("PT_HIPROC\t\t/* End of processor-specific */\n"); break; default: printf("Unknown\n"); break; } // read_pload (dst address in memory, how many bytes to read, offset in the file) read_pload(ph->p_paddr, ph->p_memsz, ph->p_offset); char * tmp99; if (elf_program_header[i].p_type == PT_LOAD) { lentotal = lentotal + elf_program_header[i].p_memsz; exe = strjoin(exe, tmp99, lenexe, lentotal); // print_quoted_string(exe, lentotal, 0, "print"); printf("\n"); lenexe = lentotal; } else { printf("ATTEMPING TO READ\n"); read_(array, &tmp99, (elf_program_header[i].p_memsz + elf_program_header[i].p_offset)); lseek_string(&tmp99, elf_program_header[i].p_memsz, elf_program_header[i].p_offset); print_quoted_string(tmp99, elf_program_header[i].p_memsz, 0, "print"); printf("\nREAD\n"); } // could this [ // read_pload (dst address in memory, how many bytes to read, offset in the file) read_pload(ph->p_paddr, ph->p_memsz, ph->p_offset); ] be shortened to [ read_pload(mapped_file, ph->p_memsz, (ph->p_paddr + ph->p_offset); ] ? https://stackoverflow.com/a/29326748/8680581 printf("p_flags;\t\t/* Segment flags */\t\t= 0x%08x\np_offset;\t\t/* Segment file offset */\t= 0x%08x\np_vaddr;\t\t/* Segment virtual address */\t= 0x%08x\np_paddr;\t\t/* Segment physical address */\t= 0x%08x\np_filesz;\t\t/* Segment size in file */\t= 0x%08x\np_memsz;\t\t/* Segment size in memory */\t= 0x%08x\np_align;\t\t/* Segment alignment */\t\t= 0x%08x\n\n\n", elf_program_header[i].p_flags, elf_program_header[i].p_offset, elf_program_header[i].p_vaddr, elf_program_header[i].p_paddr, elf_program_header[i].p_filesz, elf_program_header[i].p_memsz, elf_program_header[i].p_align); printf("p_flags = 0x%08x, p_offset = 0x%08x, p_vaddr = 0x%08x, p_paddr = 0x%08x, p_filesz = 0x%08x, p_memsz = 0x%08x, p_align = 0x%08x\n\n\n", elf_program_header[i].p_flags, elf_program_header[i].p_offset, elf_program_header[i].p_vaddr, elf_program_header[i].p_paddr, elf_program_header[i].p_filesz, elf_program_header[i].p_memsz, elf_program_header[i].p_align); } // rest MAY be irrelivant for static executable execution // printf("Section Header\t \ _elf_header->e_shstrndx 0x%08x (\ _elf_header->e_shnum = %d entries with a total of \ _elf_header->e_shentsize = %d (should match %d) bytes, offset is \ _elf_header->e_shoff = 0x%08x)\n",\ _elf_header->e_shstrndx,\ _elf_header->e_shnum,\ _elf_header->e_shentsize,\ sizeof(Elf64_Shdr),\ _elf_header->e_shoff,\ (char *)array + _elf_header->e_shoff\ ); Elf64_Shdr *_symbol_table; // read section header table void read_section_header_table_(const char * arrayb, Elf64_Ehdr * eh, Elf64_Shdr * sh_table[]) { *sh_table = (Elf64_Shdr *)(arrayb + eh->e_shoff); if(!_symbol_table) { printf("Failed to read table\n"); } } char * read_section_(char * ar, Elf64_Shdr sh) { char * buff = (char *)(ar + sh.sh_offset); return buff ; } char * print_section_headers_(char * sourcePtr, Elf64_Ehdr * eh, Elf64_Shdr sh_table[]) { printf ("\n"); printf("eh->e_shstrndx = 0x%x\n", eh->e_shstrndx); char * sh_str; sh_str = read_section_(sourcePtr, sh_table[eh->e_shstrndx]); // will fail untill section header table can be read printf("\t========================================"); printf("========================================\n"); printf("\tidx offset load-addr size algn type flags section\n"); printf("\t========================================"); printf("========================================\n"); for(i=0; i<eh->e_shnum; i++) { // will fail untill section header table can be read printf("\t%03d ", i); printf("0x%08x ", _symbol_table[i].sh_offset); // p_offset printf("0x%08x ", _symbol_table[i].sh_addr); // p_paddr or p_vaddr printf("0x%08x ", _symbol_table[i].sh_size); // p_filesz or p_memsz printf("%4d ", _symbol_table[i].sh_addralign); // p_align // for some reason sh_flags ans sh_type are swiched around printf("0x%08x ", _symbol_table[i].sh_flags); // p_flags printf("0x%08x ", _symbol_table[i].sh_type); // Unknown printf("%s\t", (sh_str + sh_table[i].sh_name)); printf("\n"); } printf("\t========================================"); printf("========================================\n"); printf("\n"); } void print_symbol_table(char * arrayc, Elf64_Ehdr eh, Elf64_Shdr sh_table[], uint64_t symbol_table) { char *str_tbl; Elf64_Sym* sym_tbl; uint64_t i, symbol_count; sym_tbl = (Elf64_Sym*)read_section_(arrayc, sh_table[symbol_table]); /* Read linked string-table * Section containing the string table having names of * symbols of this section */ uint64_t str_tbl_ndx = sh_table[symbol_table].sh_link; printf("str_tbl_ndx = 0x%x\n", str_tbl_ndx); str_tbl = read_section_(arrayc, sh_table[str_tbl_ndx]); symbol_count = (sh_table[symbol_table].sh_size/sizeof(Elf64_Sym)); printf("%d symbols\n", symbol_count); for(i=0; i< symbol_count; i++) { printf("PART0 sym_tbl[i].st_value = 0x%08x\n", sym_tbl[i].st_value); printf("PART1 ELF64_ST_BIND(sym_tbl[%d].st_info) = 0x%02x\n", i, ELF64_ST_BIND(sym_tbl[i].st_info)); printf("PART2 ELF64_ST_TYPE(sym_tbl[%d].st_info) = 0x%02x\n", i, ELF64_ST_TYPE(sym_tbl[i].st_info)); printf("PART3 (str_tbl + sym_tbl[%d].st_name) = %s\n\n", i, (str_tbl + sym_tbl[i].st_name)); } } void print_symbols(char * arrayd, Elf64_Ehdr * eh, Elf64_Shdr sh_table[]) { for(i=0; i<eh->e_shnum; i++) { if ((sh_table[i].sh_type==SHT_SYMTAB) || (sh_table[i].sh_type==SHT_DYNSYM)) { printf("\n[Section %03d]", i); print_symbol_table(arrayd, *eh, sh_table, i); } } } // // ## dynamic // p_flags; /* Segment flags */ = 0x00000006 // p_offset; /* Segment file offset */ = 0x00003e20 // p_vaddr; /* Segment virtual address */ = 0x00603e20 // p_paddr; /* Segment physical address */ = 0x00603e20 // p_filesz; /* Segment size in file */ = 0x000001d0 // p_memsz; /* Segment size in memory */ = 0x000001d0 // p_align; /* Segment alignment */ = 0x00000008 // // 021 0x00003e20 0x00603e20 0x000001d0 8 0x00000006 0x00000003 .dynamic read_section_header_table_(array, _elf_header, &_symbol_table); print_section_headers_(array, _elf_header, _symbol_table); /* Symbol tables : * _symbol_table[i].sh_type * |`- SHT_SYMTAB * `- SHT_DYNSYM */ print_symbols(array, _elf_header, _symbol_table); // fd2 = open(pwd, O_RDWR|O_SYNC|O_CREAT); print_maps(); ulexec_array(array, NULL, "-l", env); return 1; } else { printf("ELFMAGIC mismatch!\n"); /* Not ELF file */ return 0; } printf("\n"); // OBJECT END exit(0); }
0.773438
low
src/script_context.h
wjkemp/agamemnon
0
1541809
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SCRIPT_CONTEXT_H #define SCRIPT_CONTEXT_H #include "memory_region.h" #include "variable.h" #include <map> class script_context { public: ~script_context(); void add_memory_region(memory_region* region); memory_region* get_memory_region(const std::string& name) const; void set_variable(const variable& variable); uint64_t resolve_value(const std::string& value) const; private: std::map<std::string, memory_region*> _memory_regions; std::map<std::string, variable> _variables; }; #endif
0.992188
high
base/include/material_manager.h
snowzurfer/vulkan-forward-plus
3
3070577
#ifndef VKS_MATERIALMANAGER #define VKS_MATERIALMANAGER #include <EASTL/string.h> #include <EASTL/hash_map.h> #include <EASTL/vector.h> #include <unordered_map> #include <material.h> #include <material_instance.h> namespace vks { class VulkanDevice; class VulkanBuffer; class MaterialManager { public: MaterialManager(); Material *CreateMaterial( const VulkanDevice &device, eastl::unique_ptr<MaterialBuilder> builder); void RegisterMaterialName(const eastl::string &name); MaterialInstance *CreateMaterialInstance( const VulkanDevice &device, const MaterialInstanceBuilder &builder); const MaterialInstance &GetMaterialInstance(const eastl::string &name) const; const MaterialInstance &GetMaterialInstance(uint32_t index) const; const Material *GetMaterial(const eastl::string &name) const; uint32_t GetMaterialInstancesCount() const; void GetMaterialConstantsBuffer(const VulkanDevice &device, VulkanBuffer &buffer) const; eastl::vector<MaterialConstants> GetMaterialConstants() const; void ReloadAllShaders(const VulkanDevice &device); /** * @brief Get all the descriptor infos of a given type of texture for all the * existing textures. * * @param texture_type Type of texture (eg. diffuse, specular, etc) * @param descs Vector where the descriptors are returned */ void GetDescriptorImageInfosByType( const MatTextureType texture_type, eastl::vector<VkDescriptorImageInfo> &descs); void Shutdown(const VulkanDevice &device); private: // List of all materials typedef eastl::hash_map<eastl::string, eastl::unique_ptr<Material>> NameMaterialMap; NameMaterialMap materials_map_; eastl::hash_map<eastl::string, bool> registered_names_; // List of all material instances typedef eastl::hash_map<eastl::string, MaterialInstance *> NameMaterialInstMap; NameMaterialInstMap material_instances_map_; eastl::vector<MaterialInstance> material_instances_; }; // class MaterialManager } // namespace vks #endif
0.996094
high
Source/Jailbreak/Components/PositionReport.h
prodbymozart/jailbreak-unreal
0
6266097
<reponame>prodbymozart/jailbreak-unreal // Copyright 2018 <NAME> #pragma once #include "Components/ActorComponent.h" #include "PositionReport.generated.h" UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent)) class JAILBREAK_API UPositionReport : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UPositionReport(); protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; };
0.59375
high
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card